예제 #1
0
void TimeWarp::createCombinedMatrix(DoubleMatrix myChromaMatrix, DoubleVector energyVector, DoubleMatrix* chromaEnergyMatrix){
	chromaEnergyMatrix->clear();
	int sizeRatio = energyVector.size() / myChromaMatrix.size();//
	printf("COMBINE: size of my chroma is %i\n", (int) myChromaMatrix.size());// energyVector.size() / myChromaMatrix.size();
	printf("COMBINED: size ratio of energy to chroma is %i \n", sizeRatio);
	int chromaSize = myChromaMatrix.size();	
//	printf("index is %i\n", index);
	
	for (int i = 0;i < energyVector.size();i++){
		DoubleVector d;
		int index = min(chromaSize-1, (int) floor(i/sizeRatio));

		for (int y = 0;y < 12;y++){
			d.push_back(myChromaMatrix[index][y]);//
		}

		
		d.push_back(energyVector[i]);
					(*chromaEnergyMatrix).push_back(d);
	}
	printf("COMBINED: size of chroma energy is %i\n", (int)(*chromaEnergyMatrix).size());

//	int x = (int)(*chromaEnergyMatrix).size()/3;
//	printf("energy[%i] %f \n", x, energyVector[x]);
/*
 for (int y = 0;y < 13;y++){
		printf("chroma[%i][%i] %f \n", x, y, myChromaMatrix[x/sizeRatio][y]);
		printf("c[%i][%i] %f \n", x, y, (*chromaEnergyMatrix)[x][y]);
	}
		printf("\n");
*/	

}
예제 #2
0
 std::vector<double> ContinuousVariable_Impl::incrementalValues() const {
   DoubleVector result;
   if (m_minimum && m_maximum && (m_increment || m_nSteps)) {
     // empty range
     if (*m_minimum > *m_maximum) { return result; }
     // degenerate range (single point)
     if (equal(*m_minimum,*m_maximum)) {
       result.push_back((*m_minimum + *m_maximum)/2.0);
       return result;
     }
     // otherwise get incremental values
     if (m_increment) {
       for (double value = *m_minimum; lessThanOrEqual(value,*m_maximum); value += *m_increment) {
         result.push_back(value);
       }
     }
     else {
       // m_nSteps
       double inc = (*m_maximum - *m_minimum)/static_cast<double>(*m_nSteps);
       for (double value = *m_minimum; lessThanOrEqual(value,*m_maximum); value += inc) {
         result.push_back(value);
       }
     }
   }
   return result;
 }
DoubleVector QuantitationRatio::getIntensityRatios () const
{
	DoubleVector dv;
	for ( int i = 0 ; i < numRatios ; i++ ) {
		if ( quanPep )
			dv.push_back ( getQuanRatio ( lightHeavyIntRatio [i][0], lightHeavyIntRatioType [i][0] ) );
		else
			dv.push_back ( 0.0 );
	}
	return dv;
}
예제 #4
0
TEST(String,NumFractionalDigits) {
  DoubleVector values;
  values.push_back(128196.198);
  values.push_back(19671.281);
  values.push_back(218528.28);
  values.push_back(192.186);

  std::pair<unsigned,unsigned> result = numFractionalDigits(values,3u);
  EXPECT_EQ(0u,result.first); EXPECT_EQ(0u,result.second);

  result = numFractionalDigits(values,4u);
  EXPECT_EQ(0u,result.first); EXPECT_EQ(1u,result.second);

  result = numFractionalDigits(values,7u);
  EXPECT_EQ(1u,result.first); EXPECT_EQ(4u,result.second);

  values.clear();
  values.push_back(0.189678);
  values.push_back(0.001869168);
  values.push_back(0.7198);

  result = numFractionalDigits(values,2u);
  EXPECT_EQ(2u,result.first); EXPECT_EQ(4u,result.second);

  result = numFractionalDigits(values,8u);
  EXPECT_EQ(8u,result.first); EXPECT_EQ(10u,result.second);

  values.clear();
  values.push_back(0.07592);
  values.push_back(198.82);
  values.push_back(210.28);
  values.push_back(0.628);

  result = numFractionalDigits(values,2u);
  EXPECT_EQ(0u,result.first); EXPECT_EQ(3u,result.second);

  result = numFractionalDigits(values,3u);
  EXPECT_EQ(0u,result.first); EXPECT_EQ(4u,result.second);

  result = numFractionalDigits(values,5u);
  EXPECT_EQ(2u,result.first); EXPECT_EQ(6u,result.second);

  values.clear();
  values.push_back(0.0);

  result = numFractionalDigits(values,2u);
  EXPECT_EQ(1u,result.first); EXPECT_EQ(1u,result.second);

  result = numFractionalDigits(values,5u);
  EXPECT_EQ(4u,result.first); EXPECT_EQ(4u,result.second);
}
DoubleVector MSMSFragmentation::getLossMasses ()
{
	DoubleVector dv;
	dv.push_back ( 0.0 );
	for ( int i = 0 ; i < ionTypes.size () ; i++ ) {
		string it = ionTypes [i];
		if ( isPrefix ( it, "M+" ) || isPrefix ( it, "M-" ) ) {
			string loss = it.substr ( 1 );
			if ( loss.length () > 1 && isdigit ( loss [1] ) ) {
				dv.push_back ( atof ( loss.c_str () ) );
			}
		}
	}
	return dv;
}
예제 #6
0
bool TimeWarp::extendRestrictedAlignmentAlong(const int& endIndexX, DoubleMatrix* alignmentMatrix, DoubleMatrix* simMatrix){
	DoubleVector d;
	//firstMatrix.size()
	int widthSize = (*alignmentMatrix).size();
	if (widthSize < endIndexX){//firstMatrix.size()
	//	printf("restruicted along %i\n", widthSize);
		//then we can extend along
		double value = getDistanceFromMatrix(widthSize, 0, simMatrix);
		value += getMinimumFromMatrix(widthSize, 0, value, alignmentMatrix);
		
		d.push_back(value);
		(*alignmentMatrix).push_back(d);
		
		for (int j = 1;j < (*alignmentMatrix)[widthSize - 1].size();j++){
		//	printf("restruicted along %i %i\n", widthSize, j);
			value = getDistanceFromMatrix(widthSize, j, simMatrix);
			value += getMinimumFromMatrix(widthSize, j, value, alignmentMatrix);
			(*alignmentMatrix)[widthSize].push_back(value);
		}
		
	}
	
	if ((*alignmentMatrix).size() == endIndexX)
		return true;
	else
		return false;
	
}
예제 #7
0
void TimeWarp::calculatePartAlignmentMatrix(const int& endIndexX, const int& endIndexY, DoubleMatrix* alignmentMatrix, DoubleMatrix* simMatrix){
//	printf("starting PART Alignment calculation : sim matrix size %i %i endX %i Y %i\n", (int)(*simMatrix).size(), (int)(*simMatrix)[0].size(), endIndexX, endIndexY);
	//initialise alignment
	alignmentMatrix->clear();
	
	DoubleVector d;
	d.push_back(getDistanceFromMatrix(0, 0, simMatrix));
//	printf("first distance %f\n", d[0]);
	(*alignmentMatrix).push_back(d);
	
	bool chromaCalculated = false;
	bool secondCalculated = false;
	
	while (!chromaCalculated || !secondCalculated) {
		
		if (!chromaCalculated)
			chromaCalculated = extendRestrictedAlignmentAlong(endIndexX, alignmentMatrix, simMatrix);
		
		if (!secondCalculated)
			secondCalculated = extendRestrictedAlignmentUp(endIndexY, alignmentMatrix, simMatrix);
		
	}
	
//	printf("PART Alignment matrix calculated, size %i by %i\n", (int) (*alignmentMatrix).size() , (int) (*alignmentMatrix)[0].size());
//	printf("PART Alignment ends at x %i y %i\n", (int) (*alignmentMatrix)[0][(*alignmentMatrix)[0].size()-1], (int)(*alignmentMatrix)[0][(*alignmentMatrix)[1].size()-1]);

}
예제 #8
0
void TimeWarp::calculatePartSimilarityMatrix(DoubleMatrix* firstChromaMatrix, DoubleMatrix* secondChromaMatrix, DoubleMatrix* simMatrix, int startX, int startY, int endX){
//	printf("Calculate similarity : pointers : size %i x %i  ", (int) firstChromaMatrix.size(), (int) secondChromaMatrix.size());
	
	simMatrix->clear();
	
	double distance, firstSum, secondSum;
	endX = min (endX, (int)(*firstChromaMatrix).size()-1);//in case out of size
	
	for (int x = startX;x <= endX;x++){
		DoubleVector d;
		
		for (int y = startY;y < (*secondChromaMatrix).size();y++){

			if (useDotProduct)
				distance  = getChromaSimilarity(x, y, firstChromaMatrix, secondChromaMatrix);
			else
				distance = getEuclideanDistance(x, y, firstChromaMatrix, secondChromaMatrix);
			
			d.push_back( distance);	
		}	//end for y
		
		(*simMatrix).push_back(d);
		
	}//end for x
	
	printf("..part sim size: %i, height: %i \n", (int) (*simMatrix).size(), (int) (*simMatrix)[0].size());
	
}//end self sim
예제 #9
0
void TimeWarp::calculateSimilarityMatrixWithPointers(DoubleMatrix* firstChromaMatrix, DoubleMatrix* secondChromaMatrix, DoubleMatrix* simMatrix){
	printf("Calculate similarity : pointers : size %i x %i  ", (int) (*firstChromaMatrix).size(), (int) (*secondChromaMatrix).size());
	
	simMatrix->clear();

	double distance, firstSum, secondSum;
	
	for (int x = 0;x < (*firstChromaMatrix).size();x++){
		DoubleVector d;
		
		for (int y = 0;y < (*secondChromaMatrix).size();y++){
			
			if (useDotProduct)
				distance = getChromaSimilarity(x, y, firstChromaMatrix, secondChromaMatrix);
			else
				distance = getEuclideanDistance(x, y, firstChromaMatrix, secondChromaMatrix);
			
			d.push_back( distance);	
		}	//end for y
		
		(*simMatrix).push_back(d);
		
	}//end for x

		 printf("..sim size: %i, height: %i \n", (int) (*simMatrix).size(), (int) (*simMatrix)[0].size());
	
}//end self sim
예제 #10
0
int main(int argc, char **argv)
{
  std::string cornerString="   0.1     0.1      0.1   20 20 10";
  
  typedef boost::tokenizer<boost::char_separator<char> >            Tokenizer;
  typedef std::vector<double>                                       DoubleVector;
  typedef boost::tokenizer<boost::char_separator<char> >::iterator  TokIterator;

  boost::char_separator<char> sep(", ");
  Tokenizer tok(cornerString, sep);
  DoubleVector corners;
  corners.clear();

  for (TokIterator it=tok.begin(); it!=tok.end(); ++it ) {
    double q;
    printf("");
    sscanf(it->c_str(), "%lf", &q);
    //DPrintf(DebugReaction," %lf  ['%s'];  ", q, it->c_str());
    corners.push_back( q );
  }
  printf("the corners are:\n   ");
  printf("%e", corners[0]);
  for(int i=1; i<corners.size(); ++i ) {
    printf(", %e", corners[i]);
  }
  printf("\n");
}
예제 #11
0
void testApp::addToFFT(float sample) {
    //window
    fftSampleBuffer.push_back(sample);

    if (fftSampleBuffer.size() == fftSize) {
        setFFTinput();
        //do FFT using Accelerate
        audiofft->forward_FFT_d(fftInput, fftOutput);//Result);//&fftRealResult[0], &fftImagResult[0]);

        DoubleVector v;
        for (int i = 0; i < bufferSize; i++) {
            v.push_back(sqrt(fftOutput[i][0]*fftOutput[i][0] + fftOutput[i][1]*fftOutput[i][1]));
        }
        magnitudeSpectrum.push_back(v);
        /*
         //see what it's doing for low frequencies
         for (int j = 0; j < 4; j++){
         printf("%i %.3f, ", j, v[j]);
         }
         printf("\n");
         */

        //now remove many samples
        for (int removeIndex = 0; removeIndex < fftHopsize; removeIndex++) {
            fftSampleBuffer.erase(fftSampleBuffer.begin());//just need first to go each time
        }
    }
}
예제 #12
0
DoubleVector* ImageFeature::toJF(int channel) {
  DoubleVector* dv = new DoubleVector(0);
  for (uint i = 0; i < xsize_ * ysize_; i++) {
    dv->push_back(data_[channel][i]);
  }
  return dv;
}
예제 #13
0
std::vector<double> OSArgument::domainAsDouble() const {
  if (!hasDomain()) {
    LOG_AND_THROW("No domain set for OSArgument '" << name() << "'.");
  }
  DoubleVector result;
  BOOST_FOREACH(const QVariant& value,m_domain) {
    result.push_back(value.toDouble());
  }
예제 #14
0
파일: FastbReader.C 프로젝트: bmajoros/BOOM
FastbSequence *FastbReader::nextSequence()
{
  String defline, ID;

  // Read defline
  if(!nextDefline.isEmpty()) {
    defline=nextDefline;
    nextDefline="";
  }
  else {
    bool found=false;
    while(!file.eof()) {
      String line=file.getline();
      if(!line.isEmpty()) {defline=line; found=true; break;}
    }
    if(!found) return NULL;
  }
  FastbSeqType seqType;
  Regex *regex;
  if(discreteRegex.match(defline)) {
    ID=discreteRegex[1]; 
    seqType=FASTB_DISCRETE;}
  else if(continuousRegex.match(defline)) {
    ID=continuousRegex[1];
    seqType=FASTB_CONTINUOUS;}
  else throw String("Bad defline in FASTB file: ")+defline;

  // Read sequence data
  String discreteSeq;
  DoubleVector continuousSeq;
  while(!file.eof()) {
    String line=file.getline();
    line.trimWhitespace();
    if(file.eof() && line.isEmpty()) break;
    if(discreteRegex.match(line) || continuousRegex.match(line)) 
      {nextDefline=line; break;}
    else switch(seqType)
      {
      case FASTB_DISCRETE:
	discreteSeq+=line;
	break;
      case FASTB_CONTINUOUS: 
	{
	  const double d=line.asDouble();
	  //continuousSeq.push_back(isFinite(d) ? d : 0);

	  continuousSeq.push_back(d);//### 
	  if(!isFinite(d)) //### represents "missing data"
	    cerr<<"warning: non-finite value encountered: "<<d<<endl;//###
	}
	break;
      }
  }
  if(seqType==FASTB_DISCRETE) 
    return new FastbDiscreteSeq(discreteSeq,defline,ID);
  else 
    return new FastbContinuousSeq(continuousSeq,defline,ID);
}
예제 #15
0
DoubleVector
Line2D::intersectsAtLengths(const Position2DVector &v) {
    Position2DVector p = v.intersectsAtPoints(myP1, myP2);
    DoubleVector ret;
    for (size_t i=0; i<p.size(); i++) {
        ret.push_back(myP1.distanceTo(p[int(i)]));
    }
    return ret;
}
예제 #16
0
DoubleVector QuantitationMulti::getIntensityRatios () const
{
	DoubleVector dv;
	for ( int i = 0 ; i < numQuanPks ; i++ ) {
		if ( i != iTRAQRefPk && iTRAQPks [i] ) {
			dv.push_back ( getQuanRatio ( lightHeavyIntRatio [0][i], lightHeavyIntRatioType [0][i] ) );
		}
	}
	return dv;
}
예제 #17
0
void TimeWarp::calculateJointSimilarityMatrix(DoubleVector* energyVectorOne, DoubleVector* energyVectorTwo,  DoubleMatrix*  chromaSimilarityMatrix, DoubleMatrix* simMatrix){

	//requires a chromagram similarity first this already done
	//calculateSimilarityMatrixWithPointers(chromaMatrixOne, chromaMatrixTwo, &chromaSimilarityMatrix);
	
	conversionFactor = (int) round((*energyVectorOne).size() / (*chromaSimilarityMatrix).size() );
	
	printf("tw.ROUNDED CONVERSION FACTOR IS %i\n", conversionFactor);
	printf("tw.CHROMA SIM SIZE %i\n", (int) (*chromaSimilarityMatrix).size());
	
	simMatrix->clear();

	double energyProportion = 0.3;
	double chromaProportion = 1 - energyProportion;
	
	double distance, firstSum, secondSum;
	
	//lets try not actually doing calculation
	
	for (int x = 0;x < (*energyVectorOne).size();x++){
		DoubleVector d;
		
		for (int y = 0;y < (*energyVectorTwo).size();y++){
			
			//create chroma similarity first
			
			//			distance = (*energyVectorOne)[x] * (*energyVectorTwo)[y];//energy similarity
			
			//now need the chroma part
			int chromaIndexX = min(x / conversionFactor, (int)(*chromaSimilarityMatrix).size()-1);
			int chromaIndexY = min(y / conversionFactor, (int)(*chromaSimilarityMatrix)[chromaIndexX].size()-1);
			
			double chromaComponent = (*chromaSimilarityMatrix)[chromaIndexX][chromaIndexY];
//			getChromaSimilarity(chromaIndexX, chromaIndexY, firstChromaMatrix, secondChromaMatrix);
				

			distance *= energyProportion;
			distance += chromaProportion * chromaComponent;
						
			//distance = getJointChromaAndEnergyDistance(energyVectorOne, firstChromaMatrix, energyVectorTwo, secondChromaMatrix, x, y, conversionFactor, energyProportion, chromaProportion);
			

			
			d.push_back( distance);	
		}	//end for y
		
		(*simMatrix).push_back(d);
		
	}//end for x
	 
	 printf("..sim size: %i, height: %i \n", (int) (*simMatrix).size(), (int) (*simMatrix)[0].size());
	 

	
}
예제 #18
0
  void LowessSmoothing::smoothData(const DoubleVector& input_x, const DoubleVector& input_y, DoubleVector& smoothed_output)
  {
    if (input_x.size() != input_y.size())
    {
      throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
          "Sizes of x and y values not equal! Aborting... ", String(input_x.size()));
    }

    // unable to smooth over 2 or less data points (we need at least 3)
    if (input_x.size() <= 2)
    {
      smoothed_output = input_y;
      return;
    }

    Size input_size = input_y.size();

    // const Size q = floor( input_size * alpha );
    const Size q = (window_size_ < input_size) ? static_cast<Size>(window_size_) : input_size - 1;

    DoubleVector distances(input_size, 0.0);
    DoubleVector sortedDistances(input_size, 0.0);

    for (Size outer_idx = 0; outer_idx < input_size; ++outer_idx)
    {
      // Compute distances.
      // Size inner_idx = 0;
      for (Size inner_idx = 0; inner_idx < input_size; ++inner_idx)
      {
        distances[inner_idx] = std::fabs(input_x[outer_idx] - input_x[inner_idx]);
        sortedDistances[inner_idx] = distances[inner_idx];
      }

      // Sort distances in order from smallest to largest.
      std::sort(sortedDistances.begin(), sortedDistances.end());

      // Compute weigths.
      std::vector<double> weigths(input_size, 0);
      for (Size inner_idx = 0; inner_idx < input_size; ++inner_idx)
      {
        weigths.at(inner_idx) = tricube_(distances[inner_idx], sortedDistances[q]);
      }

      //calculate regression
      Math::QuadraticRegression qr;
      std::vector<double>::const_iterator w_begin = weigths.begin();
      qr.computeRegressionWeighted(input_x.begin(), input_x.end(), input_y.begin(), w_begin);

      //smooth y-values
      double rt = input_x[outer_idx];
      smoothed_output.push_back(qr.eval(rt));
    }

    return;
  }
예제 #19
0
void Fresnel::spiral (DoubleVector &spiralX, DoubleVector &spiralY) const
{
    spiralX.clear ();
    spiralY.clear ();
    spiralX.push_back (0.0);
    spiralY.push_back (0.0);

    Complex sp;

    int    fn     = currentFresnelNumber;
    double R      = holeRadius;
    double b      = observerDistance;
    double b2     = b * b;
    double innerR = 0.0;
    double outerR = 0.0;
    double innerD = b;
    double outerD = 0.0;
    double dd     = 0.0;

    for (int n = 0; n < fn + 1; ++n) {
        outerR = zoneOuterRadius (n);
        outerD = sqrt (outerR*outerR + b2);
        dd     = (outerD - innerD) / accuracySpiral;
        bool stop = false;

        for (int i = 0; i < accuracySpiral && !stop; ++i) {
            innerR = sqrt (innerD*innerD - b2);

            innerD += dd;
            outerR  = sqrt (innerD*innerD - b2);

            if (outerR >= R) {
                outerR = R;
                stop = true;
            }

            sp += amplitude (innerR, outerR);
            spiralX.push_back (sp.im);
            spiralY.push_back (sp.re);
        }
    }
}
예제 #20
0
ResultVector cluster(vector<LocalFeatures*> &locfeat, bool clusterWithPositions, string splitMode, uint maxSplit, uint stopWithNClusters, string disturbMode, string poolMode, uint dontSplitBelow, uint iterationsBetweenSplits, uint minObservationsPerCluster, double epsilon, string distanceMaker, string saveModelTo, bool saveBeforeSplits, string loadModelFrom)
{

  BaseClusterer *clusterer = new EM();

  if(loadModelFrom!="")
  {
    clusterer->loadModel(loadModelFrom);
  }
  setupClusterer(dynamic_cast<EM*>(clusterer), splitMode, maxSplit, stopWithNClusters, disturbMode, poolMode, dontSplitBelow,
                 iterationsBetweenSplits, minObservationsPerCluster, epsilon, distanceMaker, saveBeforeSplits);


  ResultVector clusterinformation;

  if (clusterWithPositions)
  {
    DBG(10) << "clustering with position information included" << endl;
  }

  DoubleVectorVector localFeaturesData;
  for (uint j = 0; j < locfeat.size(); j++)
  {
    LocalFeatures* localFeatures = locfeat[j];
    int xSize = localFeatures->imageSizeX();
    int ySize = localFeatures->imageSizeY();
    for (uint i = 0; i < localFeatures->numberOfFeatures(); i++)
    {
      DoubleVector* lfvector = &((*localFeatures)[i]);
      if (clusterWithPositions)
      {
        pair<double, double> pos = localFeatures->relativePosition(i);
        lfvector->push_back((double) localFeatures->position(i).x / (double) xSize);
        lfvector->push_back((double) localFeatures->position(i).y / (double) ySize);
      }
      localFeaturesData.push_back( lfvector );
    }
  }


  if(saveModelTo!="")
  {
    dynamic_cast<EM*>(clusterer)->run(localFeaturesData, clusterinformation, saveModelTo);
    clusterer->saveModel(saveModelTo);
  }
  else
  {
    clusterer->run(localFeaturesData, clusterinformation);
  }

  delete clusterer;
  return clusterinformation;
}
예제 #21
0
DoubleVectorVector QuanMSMSXMLData::getFormulaPurityCoefficients ( const string& name ) const
{
	DoubleVectorVector dvv;
	StringVector f = getQuanMSMSInfo ( name ).formulae;
	DoubleVector m = getQuanMSMSInfo ( name ).masses;
	for ( int i = 0 ; i < f.size () ; i++ ) {
		DoubleVector dv;
		if ( f [i] != "" ) {
			IsotopePeakStats ips ( f [i], 1 );
			int index = ips.getProbabilityIndexForMass ( m [i] );
			if ( index >= 2 ) dv.push_back ( ips.getProbability ( index - 2 ) );
			else dv.push_back ( 0.0 );
			if ( index >= 1 ) dv.push_back ( ips.getProbability ( index - 1 ) );
			else dv.push_back ( 0.0 );
			dv.push_back ( ips.getProbability ( index + 1 ) );
			dv.push_back ( ips.getProbability ( index + 2 ) );
		}
		else {									// No formulae so assume no correction
			for ( int j = 0 ; j < 4 ; j++ ) {
				dv.push_back ( 0.0 );
			}
		}
		dvv.push_back ( dv );
	}
	return dvv;
}
예제 #22
0
파일: ngs.cpp 프로젝트: Cibiv/IQ-TREE
void testSingleRateModel(Params &params, NGSAlignment &aln, NGSTree &tree, string model,
                         double *freq, DoubleVector &rate_info, StrVector &rate_name,
                         bool write_info, const char *report_file)
{
    char model_name[20];
    NGSAlignment sum_aln(aln.num_states, 1, freq);
    ModelsBlock *models_block = new ModelsBlock;

    NGSTree sum_tree(params, &sum_aln);
    sum_aln.tree = &sum_tree;

    if (model == "")
        sprintf(model_name, "GTR+F1");
    else
        sprintf(model_name, "%s+F1", model.c_str());
    try {
        params.model_name = model_name;
        sum_tree.setModelFactory(new ModelFactory(params, &sum_tree, models_block));
        sum_tree.setModel(sum_tree.getModelFactory()->model);
        sum_tree.setRate(sum_tree.getModelFactory()->site_rate);
        double bestTreeScore = sum_tree.getModelFactory()->optimizeParameters(false, write_info);
        cout << "LogL: " << bestTreeScore;
        cout << " / Rate: " << sum_tree.getRate()->getRate(0) << endl;
    } catch (...) {
        cout << "Skipped due to sparse matrix" << endl;
        //rate_info.push_back(MIN_SITE_RATE);
        rate_info.insert(rate_info.end(), rate_name.size(), MIN_SITE_RATE);
        return;
    }
    //return sum_tree.getRate()->getRate(0);
    rate_info.push_back(sum_tree.getRate()->getRate(0));

    double *rate_mat = new double[aln.num_states*aln.num_states];
    memset(rate_mat, 0, aln.num_states*aln.num_states*sizeof(double));
    sum_tree.getModel()->getRateMatrix(rate_mat);
    rate_info.insert(rate_info.end(), rate_mat, rate_mat+sum_tree.getModel()->getNumRateEntries());

    if (tree.getModel()->isReversible()) {
        sum_tree.getModel()->getStateFrequency(rate_mat);
        rate_info.insert(rate_info.end(), rate_mat, rate_mat+aln.num_states);
    }
	delete [] rate_mat;
	delete models_block;

    if (report_file) {
        DoubleMatrix tmp(1);
        tmp[0] = rate_info;
        reportNGSAnalysis(report_file, params, sum_aln, sum_tree, tmp, rate_name);
    }
}
예제 #23
0
void MainWindow::gradient()
{
    DoubleVector x;
    x.push_back(-1.0);
    x.push_back(+1.2);

    SampleGradient gm;
    connect(&gm, SIGNAL(showCoordinares(const DoubleVector &)), this, SLOT(showCoordinares(const DoubleVector &)));
    gm.setEpsilon1(0.00001);
    gm.setEpsilon2(0.00001);
    gm.setEpsilon3(0.00001);
    gm.setR1MinimizeEpsilon(0.01, 0.00001);
    gm.calculate(x);
}
예제 #24
0
void TimeWarp::calculateCausalChromaSimilarityMatrix(DoubleMatrix& firstChromaMatrix, DoubleMatrix& secondChromaMatrix, DoubleMatrix& simMatrix){
	//calculates the chroma only similarity matrix 
	//but we have already done some, so is extending it...
	
	int size = 0;
	if (simMatrix.size() > 0){
		size = simMatrix[0].size();
	}
	
	if (secondChromaMatrix.size() > size ){
	
	for (int x = 0;x < firstChromaMatrix.size();x++){
		
		if (x < simMatrix.size()){
			//i.e. entries already exist
				for (int y = (int)simMatrix[x].size();y < secondChromaMatrix.size();y++){
					double distance;
					if (useDotProduct)
					distance = getChromaSimilarity(x, y, &firstChromaMatrix, &secondChromaMatrix);
					else
					distance = getEuclideanDistance(x, y, &firstChromaMatrix, &secondChromaMatrix);
				
					printf("putting one back X %i Y %i dist %f \n", x, y, distance);
					simMatrix[x].push_back(distance);
				}
			}
		else {
			DoubleVector d;
			for (int y = 0;y < secondChromaMatrix.size();y++){
					double distance;
					if (useDotProduct)
					distance = getChromaSimilarity(x, y, &firstChromaMatrix, &secondChromaMatrix);
					else
					distance = getEuclideanDistance(x, y, &firstChromaMatrix, &secondChromaMatrix);
			
				printf("new row X %i Y %i dist %f\n", x, y, distance);
					d.push_back( distance);	
				}
				simMatrix.push_back(d);
			}
		}
	}
			if (size > 0)
				printf("Causial CHROMA ONLY SIM SIZE %i x %i; ", (int)simMatrix.size(), (int) simMatrix[0].size());
		printf("First matrix SIZE %i , SECOND size %i\n", (int)firstChromaMatrix.size(), (int) secondChromaMatrix.size());	

	
}
 bool ThermochromicGlazing_Impl::setThickness(double value) {
   GlazingVector glazings = mf_glazings();
   DoubleVector rollbackValues;
   for (unsigned i = 0,n = glazings.size(); i < n; ++ i) {
     rollbackValues.push_back(glazings[i].thickness());
     bool ok = glazings[i].setThickness(value);
     if (!ok) {
       // rollback previous values
       for (int j = i-1; j >= 0; --j) {
         glazings[j].setThickness(rollbackValues[j]);
       }
       return false;
     }
   }
   return true;
 }
예제 #26
0
DoubleVector RRSchedule::reconfigureWeek(DoubleVector _week, Vector _permute)
// Creates a new week based on the current week and a permutation
{
    DoubleVector newWeek;
    
    for (Vector::const_iterator tSlotNum = _permute.begin(); tSlotNum != _permute.end(); ++tSlotNum)
    {
        // For week0, there are not enough timeslots
        if ((week0 and *tSlotNum < max_times - skip_first) or (not week0))
        {
            newWeek.push_back(_week[*tSlotNum]);
        }
    }
    
    return newWeek;
}
예제 #27
0
CosSimilarity::CosSimilarity ( const string& formulaString, int charge, const DoubleVector& intensity, const DoubleVector& area ) :
	cosSimilarityIntensity ( -100.0 ),
	cosSimilarityArea ( -100.0 )
{
	IsotopePeakStats id ( formulaString, charge );
	int np = id.getNumPeaks ();
	int ind1 = id.getProbabilityIndexForIdealMonoisotopicMZ ();
	int distSize = genMax ( intensity.size (), area.size () );
	DoubleVector dv;
	for ( int i = ind1 ; i < np ; i++ ) {
		dv.push_back ( id.getProbability ( i ) );
		if ( dv.size () == distSize ) break;
	}
	if ( dv.size () > 1 ) {
		if ( intensity.size () > 1 )	cosSimilarityIntensity = cosSimilarity ( intensity, dv );
		if ( area.size () > 1 )			cosSimilarityArea = cosSimilarity ( area, dv );
	}
}
예제 #28
0
void RddtClust::getDimData(DoubleVector& dimData, int idx){
    using namespace Rcpp;
    XmdvToolMainWnd* m_mwd = this->m_rddtOp->m_pm->getMainWnd();
    RInside r = m_mwd->getRinstance();
    //qDebug()<<"idx qt "<<idx;
    r["currentDim"] = idx;

    std::string cmd = "currentDim <- as.integer(currentDim)+1;\n"
            //"print(currentDim);\n"
            "dimData <- M[,currentDim];\n"
            "dimData";
    SEXP evals = r.parseEval(cmd);
    NumericVector rDimData(evals);

    dimData.clear();
    for(int i = 0; i< rDimData.length(); i++){
        dimData.push_back(rDimData[i]);
    }
}
예제 #29
0
void TimeWarp::calculateAlignmentMatrix(DoubleMatrix firstMatrix, DoubleMatrix secondMatrix, DoubleMatrix* alignmentMatrix){//, DoubleMatrix simMatrix
	printf("starting Alignment calculation\n");
	//initialise alignment
	alignmentMatrix->clear();

	DoubleVector d;
	d.push_back(getDistance(0,0));
	(*alignmentMatrix).push_back(d);
	
	bool chromaCalculated = false;
	bool secondCalculated = false;
	
	while (!chromaCalculated || !secondCalculated) {
		
		if (!chromaCalculated)
			chromaCalculated = extendAlignmentAlong((int) firstMatrix.size(), alignmentMatrix);
		
		if (!secondCalculated)
			secondCalculated = extendAlignmentUp((int) secondMatrix.size(), alignmentMatrix);
		
	}
	printf("Alignment matrix calculated, size %i\n", (int) (*alignmentMatrix).size());
}
예제 #30
0
void Application::reestimate(EmissionSequence &seq,MultiGauss &dist)
{
  int dim=seq.getSchema().getNumContinuous();
  GSL::Vector means(dim);
  GSL::Matrix covM(dim,dim);
  int L=seq.length();
  for(int d=0 ; d<dim ; ++d) {
    DoubleVector V;
    for(int pos=0 ; pos<L ; ++pos) {
      const Emission &s=seq[pos];
      const GSL::Vector &v=s.getContinuous();
      V.push_back(v[d]);
    }
    SummaryStats stats(V);
    means[d]=stats.getMean();
    covM(d,d)=stats.getVar();
  }
  for(int d1=0 ; d1<dim ; ++d1) {
    double sd1=sqrt(covM(d1,d1));
    for(int d2=0 ; d2<dim ; ++d2) {
      if(d2==d1) continue;
      double sd2=sqrt(covM(d2,d2));
      DoubleVector V1, V2;
      for(int pos=0 ; pos<L ; ++pos) {
	const Emission &s=seq[pos];
	const GSL::Vector &v=s.getContinuous();
	V1.push_back(v[d1]);
	V2.push_back(v[d2]);
      }
      Correlation cor(V1,V2);
      covM(d1,d2)=cor.getR()*sd1*sd2;
    }
  }
  cout<<"REESTIMATING FROM: "<<means<<"\n"<<covM<<endl;
  dist=MultiGauss(means,covM);
}