Real AnalyticBarrierEngine::B(Real phi) const {
     Real x2 =
         std::log(underlying()/barrier())/stdDeviation() + muSigma();
     Real N1 = f_(phi*x2);
     Real N2 = f_(phi*(x2-stdDeviation()));
     return phi*(underlying() * dividendDiscount() * N1
                 - strike() * riskFreeDiscount() * N2);
 }
 Real AnalyticBarrierEngine::D(Real eta, Real phi) const {
     Real HS = barrier()/underlying();
     Real powHS0 = std::pow(HS, 2 * mu());
     Real powHS1 = powHS0 * HS * HS;
     Real y2 = std::log(barrier()/underlying())/stdDeviation() + muSigma();
     Real N1 = f_(eta*y2);
     Real N2 = f_(eta*(y2-stdDeviation()));
     return phi*(underlying() * dividendDiscount() * powHS1 * N1
                 - strike() * riskFreeDiscount() * powHS0 * N2);
 }
 Real AnalyticBarrierEngine::E(Real eta) const {
     if (rebate() > 0) {
         Real powHS0 = std::pow(barrier()/underlying(), 2 * mu());
         Real x2 =
             std::log(underlying()/barrier())/stdDeviation() + muSigma();
         Real y2 =
             std::log(barrier()/underlying())/stdDeviation() + muSigma();
         Real N1 = f_(eta*(x2 - stdDeviation()));
         Real N2 = f_(eta*(y2 - stdDeviation()));
         return rebate() * riskFreeDiscount() * (N1 - powHS0 * N2);
     } else {
         return 0.0;
     }
 }
 Real AnalyticContinuousFloatingLookbackEngine::A(Real eta) const {
     Volatility vol = volatility();
     Real lambda = 2.0*(riskFreeRate() - dividendYield())/(vol*vol);
     Real s = underlying()/minmax();
     Real d1 = std::log(s)/stdDeviation() + 0.5*(lambda+1.0)*stdDeviation();
     Real n1 = f_(eta*d1);
     Real n2 = f_(eta*(d1-stdDeviation()));
     Real n3 = f_(eta*(-d1+lambda*stdDeviation()));
     Real n4 = f_(eta*-d1);
     Real pow_s = std::pow(s, -lambda);
     return eta*((underlying() * dividendDiscount() * n1 -
                 minmax() * riskFreeDiscount() * n2) +
                 (underlying() * riskFreeDiscount() *
                 (pow_s * n3 - dividendDiscount()* n4/riskFreeDiscount())/
         lambda));
 }
Esempio n. 5
0
int main(int argc, char** argv){
	initializeBoard();
	initializeUSB1208();
	int k=0,i=1,nSamples=16;
	float angle;
	float* measurement=calloc(sizeof(float),nSamples);
	float* involts=calloc(sizeof(float),NUMCHANNELS);

	printf("    VERT VERTsd   |    HORIZ HORIZsd  |     REF REFsd    | Approx Angle\n");
	for(k=1;k<NUMCHANNELS+1;k++){
		for (i=0;i<nSamples;i++){
			getUSB1208AnalogIn(k,&measurement[i]);
			involts[k-1]=involts[k-1]+measurement[i];
			delay(10);
		}
		involts[k-1]=fabs(involts[k-1])/(float)nSamples;
		printf("  %0.4f %0.4f  ",involts[k-1],stdDeviation(measurement,nSamples));
		if(k<NUMCHANNELS) printf(" | ");
	}
	printf("\t");
	angle=atan(sqrt(involts[0]/involts[1]));
	printf("%0.3f",angle);
	printf("\n");


	return 0;
}
Esempio n. 6
0
 inline Disposable<Matrix> StochasticProcess1D::stdDeviation(
                                 Time t0, const Array& x0, Time dt) const {
     #if defined(QL_EXTRA_SAFETY_CHECKS)
     QL_REQUIRE(x0.size() == 1, "1-D array required");
     #endif
     Matrix m(1, 1, stdDeviation(t0, x0[0], dt));
     return m;
 }
float collectDiscreteFourierData(FILE* fp, int* photoDetector, int numPhotoDetectors,int motor, int revolutions)
{
    float sumSin=0;
    float sumCos=0;
    int count=0;
    int steps,i,j,k;
	float angle;
    float laserAngle=-100;


    int nSamples=16;
	float* measurement = malloc(nSamples*sizeof(float));

    
    float* involts = calloc(numPhotoDetectors,sizeof(float));
    float* stdDev = calloc(numPhotoDetectors,sizeof(float));

    for (k=0;k<revolutions;k++){ //revolutions
        for (steps=0;steps < STEPSPERREV;steps+=(int)STEPSIZE){ // steps
            // (STEPSPERREV) in increments of STEPSIZE
            delay(300); // watching the o-scope, it looks like it takes ~100ms for the ammeter to settle after a change in LP. UPDATE: with the Lock-in at a time scale of 100 ms, it takes 500 ms to settle. 
            // With time scale of 30 ms, takes 300 ms to settle.

            //get samples and average
            for(j=0;j<numPhotoDetectors;j++){ // numPhotoDet1
                involts[j]=0.0;	
                for (i=0;i<nSamples;i++){ // nSamples
                        getUSB1208AnalogIn(photoDetector[j],&measurement[i]);
                        involts[j]=involts[j]+fabs(measurement[i]);
                        delay(WAITTIME);
                } // nSamples
                involts[j]=involts[j]/(float)nSamples; 
                stdDev[j]=stdDeviation(measurement,nSamples);
            } // numPhotoDet1

            fprintf(fp,"%d\t",steps+(int)STEPSPERREV*k);
            for(j=0;j<numPhotoDetectors;j++){
                if(j!=numPhotoDetectors-1)
                    fprintf(fp,"%f\t%f\t",involts[j],stdDev[j]);
                else
                    fprintf(fp,"%f\t%f\n",involts[j],stdDev[j]);
            }
            angle=2.0*PI*(steps)/STEPSPERREV;
            sumSin+=involts[1]*sin(2*angle);
            sumCos+=involts[1]*cos(2*angle);
			

            count++;
            stepMotor(motor,CLK,(int)STEPSIZE);
        } // steps
		laserAngle=180/PI*0.5*atan2(sumCos,sumSin);
    } // revolutions
    free(measurement);
    free(stdDev);
    free(involts);
	
	return laserAngle;
}
    Real AnalyticDoubleBarrierEngine::callKO() const {
       // N.B. for flat barriers mu3=mu1 and mu2=0
       Real mu1 = 2 * costOfCarry() / volatilitySquared() + 1;
       Real bsigma = (costOfCarry() + volatilitySquared() / 2.0) * residualTime() / stdDeviation();

       Real acc1 = 0;
       Real acc2 = 0;
       for (int n = -series_ ; n <= series_ ; ++n) {
          Real L2n = std::pow(barrierLo(), 2 * n);
          Real U2n = std::pow(barrierHi(), 2 * n);
          Real d1 = std::log( underlying()* U2n / (strike() * L2n) ) / stdDeviation() + bsigma;
          Real d2 = std::log( underlying()* U2n / (barrierHi() * L2n) ) / stdDeviation() + bsigma;
          Real d3 = std::log( std::pow(barrierLo(), 2 * n + 2) / (strike() * underlying() * U2n) ) / stdDeviation() + bsigma;
          Real d4 = std::log( std::pow(barrierLo(), 2 * n + 2) / (barrierHi() * underlying() * U2n) ) / stdDeviation() + bsigma;

          acc1 += std::pow( std::pow(barrierHi(), n) / std::pow(barrierLo(), n), mu1 ) * 
                  (f_(d1) - f_(d2)) -
                  std::pow( std::pow(barrierLo(), n+1) / (std::pow(barrierHi(), n) * underlying()), mu1 ) * 
                  (f_(d3) - f_(d4));

          acc2 += std::pow( std::pow(barrierHi(), n) / std::pow(barrierLo(), n), mu1-2) * 
                  (f_(d1 - stdDeviation()) - f_(d2 - stdDeviation())) -
                  std::pow( std::pow(barrierLo(), n+1) / (std::pow(barrierHi(), n) * underlying()), mu1-2 ) * 
                  (f_(d3-stdDeviation()) - f_(d4-stdDeviation()));
       }

       Real rend = std::exp(-dividendYield() * residualTime());
       Real kov = underlying() * rend * acc1 - strike() * riskFreeDiscount() * acc2;
       return std::max(0.0, kov);
    }
 Real AnalyticDoubleBarrierEngine::vanillaEquivalent() const {
     // Call KI equates to vanilla - callKO
     boost::shared_ptr<StrikedTypePayoff> payoff =
         boost::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);
     Real forwardPrice = underlying() * dividendDiscount() / riskFreeDiscount();
     BlackCalculator black(payoff, forwardPrice, stdDeviation(), riskFreeDiscount());
     Real vanilla = black.value();
     if (vanilla < 0.0)
        vanilla = 0.0;
     return vanilla;
 }
Esempio n. 10
0
    inline const Real GeneralizedJcirProcess<__URng_Poisson_Type, __URng_Exp_Type>::evolve(Time t0, Real x0, Time dt, Real dw) const {
        Real xContinuous, totalJump = 0.;
        xContinuous = apply(expectation(t0, x0, dt), stdDeviation(t0, x0, dt)*dw);

        InverseCumulativePoisson invP(jumpIntensity_*dt);
        int Pt = (int)invP(URng_Poisson_.next().value);

        for (int i = 0; i < Pt; ++i) {
            totalJump += -mean*std::log(1 - URng_Exp_.next().value);
        }

        return apply(xContinuous, totalJump);
    }
 Real GeneralizedBlackScholesProcess::evolve(Time t0, Real x0,
                                             Time dt, Real dw) const {
     localVolatility(); // trigger update
     if (isStrikeIndependent_ && !forceDiscretization_) {
         // exact value for curves
         Real var = variance(t0, x0, dt);
         Real drift = (riskFreeRate_->forwardRate(t0, t0 + dt, Continuous,
                                                  NoFrequency, true) -
                       dividendYield_->forwardRate(t0, t0 + dt, Continuous,
                                                   NoFrequency, true)) *
                          dt -
                      0.5 * var;
         return apply(x0, std::sqrt(var) * dw + drift);
     } else
         return apply(x0, discretization_->drift(*this, t0, x0, dt) +
                              stdDeviation(t0, x0, dt) * dw);
 }
Esempio n. 12
0
void collectDiscreteFourierData(FILE* fp, int* photoDetector, int numPhotoDetectors,int motor, int revolutions)
{
    int count=0;
    int steps,i,j,k;

    int nSamples=16;
	float* measurement = malloc(nSamples*sizeof(float));

    
    float* involts = calloc(numPhotoDetectors,sizeof(float));
    float* stdDev = calloc(numPhotoDetectors,sizeof(float));

    for (k=0;k<revolutions;k++){ //revolutions
        for (steps=0;steps < NUMSTEPS;steps+=STEPSIZE){ // steps
            // (NUMSTEPS) in increments of STEPSIZE
            delay(150); // watching the o-scope, it looks like it takes ~100ms for the ammeter to settle after a change in LP
            //get samples and average
            for(j=0;j<numPhotoDetectors;j++){ // numPhotoDet1
                involts[j]=0.0;	
                for (i=0;i<nSamples;i++){ // nSamples
                        getMCPAnalogIn(photoDetector[j],&measurement[i]);
                        involts[j]=involts[j]+measurement[i];
                        delay(WAITTIME);
                } // nSamples
                involts[j]=involts[j]/(float)nSamples; 
                stdDev[j]=stdDeviation(measurement,nSamples);
            } // numPhotoDet1

            fprintf(fp,"%d\t",steps+NUMSTEPS*k);
            for(j=0;j<numPhotoDetectors;j++){
                if(j!=numPhotoDetectors-1)
                    fprintf(fp,"%f\t%f\t",involts[j],stdDev[j]);
                else
                    fprintf(fp,"%f\t%f\n",involts[j],stdDev[j]);
            }

            count++;
            stepMotor(motor,CLK,STEPSIZE);
        } // steps
    } // revolutions
    free(measurement);
    free(stdDev);
    free(involts);
}
    Real AnalyticBarrierEngine::F(Real eta) const {
        if (rebate() > 0) {
            Rate m = mu();
            Volatility vol = volatility();
            Real lambda = std::sqrt(m*m + 2.0*riskFreeRate()/(vol * vol));
            Real HS = barrier()/underlying();
            Real powHSplus = std::pow(HS, m + lambda);
            Real powHSminus = std::pow(HS, m - lambda);

            Real sigmaSqrtT = stdDeviation();
            Real z = std::log(barrier()/underlying())/sigmaSqrtT
                + lambda * sigmaSqrtT;

            Real N1 = f_(eta * z);
            Real N2 = f_(eta * (z - 2.0 * lambda * sigmaSqrtT));
            return rebate() * (powHSplus * N1 + powHSminus * N2);
        } else {
            return 0.0;
        }
    }
Esempio n. 14
0
   /*
   * Output statistical properties to file
   */
   void Average::output(std::ostream& out)
   {
      // Find first stage (descending) with nSample >= 16
      AverageStage* ptr = 0;
      int n = descendants_.size();
      int i = n;
      int nSample = 1;
      while (nSample < 16 && i > 0) {
         --i;
         ptr = descendants_[i];
         nSample = ptr->nSample();
      }

      double error  = ptr->error();
      double sigma  = error/sqrt(2.0*double(nSample-1));
      double weight = 1.0/(sigma*sigma);
      double sum    = error*weight;
      double norm   = weight;
      double aveErr = error;
      double oldSig;

      // Find weighted average within plateau
      bool next = true;
      while (next && i > 0) {
         oldSig = sigma;
         --i;
         ptr = descendants_[i];
         error = ptr->error();
         if (fabs(error - aveErr) < 2.0*oldSig) {
            nSample = ptr->nSample();
            sigma  = error/sqrt(2.0*double(nSample-1));
            weight = 1.0/(sigma*sigma);
            sum   += error*weight;
            norm  += weight;
            aveErr = sum/norm;
         } else {
            next = false;
         }
      }

      out <<  "Average   " << Dbl(average())         
          <<  "  +- " << Dbl(aveErr, 9, 2) << std::endl;
      out <<  "Variance  " << Dbl(variance())        << std::endl;
      out <<  "Std Dev   " << Dbl(stdDeviation())    << std::endl;
      out <<  std::endl;

      out << "Hierarchichal Error Analysis:" << std::endl;
      int interval;
      for (int i = 0; i < n; ++i) {
         ptr = descendants_[i];
         error    = ptr->error();
         nSample  = ptr->nSample();
         interval = ptr->stageInterval();
         if (nSample >= 16) {
            out << Int(i) 
                << Int(interval) 
                << Dbl(error) 
                << Dbl(error/sqrt(double(nSample)))
                << Int(nSample) << std::endl;
         }
      }
      out << std::endl;
   }
Esempio n. 15
0
	inline void Evaluation::generateOutput()
	{
		cv::FileStorage storage;
		cv::Mat_<float> output;
		int nLabels = this->labelsName.size();
		output.release();
		output.create(cv::Size(9, nLabels)); //4 = TP, FP, FN, TN, precision, recall, specificity, accuracy per class, balanced accuracy per class 
		output = 0;
		float precision, recall, specificity;
		std::map<int, std::vector<float>> TPScores, FPScores, FNScores, TNScores; //first = class, second = scores

		//Create output file
		storage.open("output.yml", cv::FileStorage::WRITE);
		if (storage.isOpened() == false)
			std::cerr << "Invalid file storage!" << std::endl;

		storage << "ClassificationOutput" << "{";

		// TP - True Positive
		for (int tp = 0; tp < nLabels; tp++)
		{
			output[tp][0] = this->confusionMat[tp][tp];
			for (int score = 0; score < this->confusionMatScores[tp][tp].size(); score++)
				TPScores[tp].push_back(this->confusionMatScores[tp][tp].at(score));
		}

		// FP - False Positive
		for (int col = 0; col < nLabels; col++)
		{
			for (int row = 0; row < nLabels; row++)
			{
				output[col][1] += this->confusionMat[row][col];

				if (col != row)
					for (int score = 0; score < this->confusionMatScores[row][col].size(); score++)
						FPScores[col].push_back(this->confusionMatScores[row][col].at(score));
			}
			output[col][1] -= output[col][0];
		}

		// FN - False Negative
		for (int row = 0; row < nLabels; row++)
		{
			for (int col = 0; col < nLabels; col++)
			{
				output[row][2] += this->confusionMat[row][col];

				if (col != row)
					for (int score = 0; score < this->confusionMatScores[row][col].size(); score++)
						FNScores[row].push_back(this->confusionMatScores[row][col].at(score));
			}
			output[row][2] -= output[row][0];
		}

		// TN - True Negative
		cv::Scalar sum = cv::sum(this->confusionMat);
		for (int tn = 0; tn < nLabels; tn++)
			output[tn][3] = sum[0] - output[tn][0] - output[tn][1] - output[tn][2];

		for (int l = 0; l < nLabels; l++)
		{
			precision = output[l][0] / (output[l][0] + output[l][1]);
			output[l][4] = precision;
			recall = output[l][0] / (output[l][0] + output[l][2]);
			output[l][5] = recall;
			specificity = output[l][3] / (output[l][3] + output[l][1]);
			output[l][6] = specificity;
			output[l][7] = (output[l][0] + output[l][3]) / (output[l][0] + output[l][1] + output[l][2] + output[l][3]); //accuracy per class
			output[l][8] = balancedAccuracy(output[l][0], output[l][1], output[l][2], output[l][3]); //balanced accuracy per class
		}

		float *ap = new float[nLabels];
		for (int label = 0; label < nLabels; label++)
			ap[label] = averagePrecision(label, output[label][0], output[label][2], TPScores, FPScores);

		double meanAP = std::accumulate(ap, ap + nLabels, 0.0f);
		double meanACC = meanAccuracy(output.col(7));
		double stdDev = stdDeviation(output.col(7), meanACC);
		double meanBalACC = meanAccuracy(output.col(8));
		double stdDevBal = stdDeviation(output.col(8), meanBalACC);

		storage << "MeanBalancedAccuracy" << meanBalACC;
		storage << "StandardDeviationBalACC" << stdDevBal;
		//storage << "MeanAccuracy" << meanACC; // Removed because we are using balanced accuracy
		//storage << "StandardDeviationACC" << stdDev; // Removed because we are using balanced accuracy
		storage << "MeanAveragePrecision" << meanAP;

		for (int label = 0; label < nLabels; label++)
		{
			std::stringstream classLabel;
			classLabel << "Class" << label;
			storage << classLabel.str() << "{";
			storage << "Label" << this->labelsName[label];
			storage << "TP" << output[label][0];
			storage << "FP" << output[label][1];
			storage << "FN" << output[label][2];
			storage << "TN" << output[label][3];
			storage << "precision" << output[label][4];
			storage << "recall" << output[label][5];
			storage << "specificity" << output[label][6];
			//storage << "accPerClass" << output[label][7]; // Removed because we are using balanced accuracy
			storage << "accBalPerClass" << output[label][8];
			storage << "apPerClass" << ap[label];
			storage << "}";
		}
		storage.release();

		delete ap;
	}
Esempio n. 16
0
 Real VarianceGammaProcess::evolve(Time t0, Real x0, Time dt, Real dg, Real dw) const {
     Real drift = discretization_->drift(*this,t0,x0,dt);
     X0_ += theta() * dg + stdDeviation(t0,x0,dt) * sqrt(dg) * dw;
     
     return apply(x0, drift + X0_);
 }
 Real GeneralizedBlackScholesProcess::evolve(Time t0, Real x0,
                                             Time dt, Real dw) const {
     return apply(x0, discretization_->drift(*this,t0,x0,dt) +
                      stdDeviation(t0,x0,dt)*dw);
 }
Esempio n. 18
0
int main(int argc, char *argv[])
{
	int i, npart;
	idxtype *part;
	float ncut=0;
	GraphType graph;
	char filename[256],outputFile[256];
	int wgtflag = 0, addSelfLoop=1, outputFileGiven=0, txtFormat=0 ;
	int randomInit = 0;
	idxtype minEdgeWeight = 0;
	Options opt;
	timer TOTALTmr, METISTmr, IOTmr;

	initOptions(&opt);

	if (argc < 2) {
		print_help(argv[0]);
		exit(0);
	}
	
	for (argv++; *argv != NULL; argv++){
	    if ((*argv)[0] == '-')
		{
			int temp;
	      	switch ((*argv)[1])
			{
			case 'b':
			case 'B':
			  opt.penalty_power=atof(*(++argv));
			  break;
			case 'i':
			case 'I':
			  opt.gamma=atof(*(++argv));
			  break;
			case 'o':
			case 'O':
			  strcpy(outputFile,*(++argv));
			  outputFileGiven=1;
			  break;
			case 'D'://quality threshold. This is a post-processing step proposed in SR-MCL. If you dont want post-processing (this is what original MLR-MCL, R-MCL, MCL do, please set "-d 0"  
			case 'd':
			  opt.quality_threshold = atof(*(++argv));
			  break;
			case 'w':
			case 'W':
		          opt.weighted_density = true; 
			  break;

			case 'c':
			case 'C':
			  opt.coarsenTo= atoi(*(++argv));
			  break;
			default:
			  printf("Invalid option %s\n", *argv);
			  print_help(argv[0]);
			  exit(0);
			}
		}
	    else
		{
	      strcpy(filename, *argv);
	    }
	}  

	if ( randomInit > 0 )
		InitRandom(time(NULL));
	else
		InitRandom(-1);

	cleartimer(TOTALTmr);
	cleartimer(METISTmr);
	cleartimer(IOTmr);

	starttimer(TOTALTmr);
	starttimer(IOTmr);

	ReadGraph(&graph, filename, &wgtflag, addSelfLoop, txtFormat);

	if ( opt.matchType == MATCH_UNSPECIFIED )
	{
//		opt.matchType = (graph.nvtxs>50000) ? MATCH_POWERLAW_FC :
//							MATCH_SHEMN;
		opt.matchType = MATCH_SHEMN;
	}
	
	stoptimer(IOTmr);

	if (graph.nvtxs <= 0) {
	  printf("Empty graph. Nothing to do.\n");
	  exit(0);
	}

	int noOfSingletons = 0; 
	GraphType *noSingletonGraph ;
	idxtype* nodeMap = lookForSingletons(&graph, &noOfSingletons);
	if ( noOfSingletons > 0 )
	{
		getSubgraph(&graph, nodeMap, graph.nvtxs-noOfSingletons, 
						wgtflag, &noSingletonGraph);
		GKfree((void**)&(graph.xadj), (void**)&(graph.adjncy), LTERM);
		if ( wgtflag&1 > 0 )
			GKfree( (void**)&(graph.adjwgt), LTERM);
//		free(graph.gdata);
		printf("Found %d singleton nodes in the", noOfSingletons);
		printf(" input graph. Removing them.\n");
	}

	if ( !outputFileGiven )
	{
		strcpy(outputFile, filename);

		sprintf(outputFile,"%s.c%d.i%1.1f.b%1.1f",outputFile,opt.coarsenTo,opt.gamma,opt.penalty_power);
	}
	
	printf("Input graph information ---------------------------------------------------\n");
	printf("  Name: %s, #Vertices: %d, #Edges: %d\n", filename, graph.nvtxs, graph.nedges/2);
	printf("Output shall be placed in the file %s\n",
	outputFile);
	fflush(stdout);

	part = idxmalloc(graph.nvtxs, "main: part");

	printf("------------------------------------------------\n");
	printf("Clustering....\n");
	fflush(stdout);
	starttimer(METISTmr);         //YK: main algorithm starts here!

	if ( noOfSingletons > 0 )
	{
		
		mlmcl(&(noSingletonGraph->nvtxs), noSingletonGraph->xadj, noSingletonGraph->adjncy,
			noSingletonGraph->vwgt,noSingletonGraph->adjwgt, &wgtflag, part, opt ); 
	}
	else	
	{
		mlmcl(&graph.nvtxs, graph.xadj, graph.adjncy,graph.vwgt,
			graph.adjwgt, &wgtflag, part, opt ); 
	}

	stoptimer(METISTmr); 

	printf("------------------------------------------------\n");
	if ( noOfSingletons > 0 )
	{
		npart=mapPartition(part,noSingletonGraph->nvtxs);
		ncut=ComputeNCut(noSingletonGraph, part,npart);
//		printf("In graph that does not include singletons,");
//		printf("No. of Clusters: %d, N-Cut value: %.2f\n",npart,ncut);


		idxtype *clusterSizes = histogram(part,
					graph.nvtxs-noOfSingletons, npart);

		int maxSize = clusterSizes[idxamax(npart, clusterSizes)];
		float avgClusterSize =
						(graph.nvtxs-noOfSingletons)*1.0/(npart);
		float balance =	(maxSize*1.0) /
				((graph.nvtxs-noOfSingletons)*1.0/npart);
		float stdDevn = stdDeviation(clusterSizes, npart);
		float avgNcut = ncut * 1.0/npart;
		float normStdDevn = stdDevn/avgClusterSize;

	// Warning: This computation only works if the singletons
	// have been placed in their own clusters. This works for
	// MLR-MCL, in other words, because it is guaranteed to
	// place singletons in their own clusters.
		printf("Output statistics for graph without singletons\n");
		printf("Clusters: %d N-Cut: %.3f", 
					npart, ncut);
		printf(" AvgN-Cut: %.3f Balance in cluster sizes: %.2f ",avgNcut,
					balance); 
		printf("Std_Deviation in cluster sizes: %.2f ", stdDevn);
		printf("Coefficient_of_Variation: %.2f\n", normStdDevn);

		free( clusterSizes );

		npart += noOfSingletons;
	//	ncut += noOfSingletons;
		printf("Output statistics for original graph\n");

		mapIndices(part, nodeMap, graph.nvtxs, npart-noOfSingletons);
	}
	else
	{
		npart=mapPartition(part,graph.nvtxs);
		ncut=ComputeNCut(&graph, part,npart);
	}

	idxtype* clusterSizes = histogram(part, graph.nvtxs, npart);
	int maxSize = clusterSizes[idxamax(npart, clusterSizes)];
	float avgClusterSize = (graph.nvtxs)*1.0/(npart);
	float balance = (maxSize*1.0)/(graph.nvtxs*1.0/npart);
	float stdDevn = stdDeviation(clusterSizes, npart);
	float avgNcut = ncut * 1.0/npart;
	float normStdDevn = stdDevn/avgClusterSize;
	
	printf("Clusters: %d N-Cut: %.3f AvgN-Cut: %.3f", npart,
						ncut, avgNcut );
	printf(" Balance in cluster sizes: %.2f Std.Deviation in cluster sizes: %.2f ",
				 balance, stdDevn);
	printf("Coefficient_of_Variation: %.2f\n", normStdDevn);

	starttimer(IOTmr);
	my_WritePartition(outputFile, part, graph.nvtxs, opt.gamma); 
	if ( noOfSingletons > 0 )
	{
		free(nodeMap);
		nodeMap = NULL;
	}

	printf("\nOutput is written to file: %s\n", outputFile);
	stoptimer(IOTmr);
	stoptimer(TOTALTmr);
	
	printf("\nTiming Information --------------------------------------------------\n");
	printf("  I/O:          \t\t %7.3f\n", gettimer(IOTmr));
	printf("  Partitioning: \t\t %7.3f   (MLR-MCL time)\n", gettimer(METISTmr));
	printf("  Total:        \t\t %7.3f\n", gettimer(TOTALTmr));
	printf("**********************************************************************\n");


	GKfree((void**)&graph.xadj, (void**)&graph.adjncy, (void**)&graph.vwgt, 
				(void**)&graph.adjwgt, (void**)&part, LTERM);
}  
 Real AnalyticBarrierEngine::muSigma() const {
     return (1 + mu()) * stdDeviation();
 }
Esempio n. 20
0
void collectAndRecordData(char* fileName, float startvalue, float endvalue, float stepsize){
	float value;
	FILE* fp;
	int k=0,i;
	int nSamples;
    int count=0;
	float involts[NUMCHANNELS];
	float kensWaveLength;

	fp=fopen(fileName,"a");
	if (!fp) {
		printf("unable to open file: %s\n",fileName);
		exit(1);
	}
	// Allocate some memory to store measurements for calculating
	// error bars.
	nSamples = 16;
	float* measurement = malloc(nSamples*sizeof(float));

	value=startvalue;
	setVortexPiezo(value);
	delay(10000);


	for (value=startvalue;value < endvalue && value >= startvalue;value+=stepsize){
        if(count%15==0) printf("          \t       \t\t\tVERTICAL      |        HORIZONTAL      |        REFERENCE\n");
		setVortexPiezo(value);
		printf("VOLT %3.1f \t",value);
		fprintf(fp,"%f\t",value);

		// delay to allow transients to settle
		delay(200);
		getProbeDetuning(&kensWaveLength);// Getting the wavelength invokes a significant delay
                                        // So we no longer need the previous delay statement. 
		//kensWaveLength = -1;
		fprintf(fp,"%03.4f\t",kensWaveLength);
		printf("%03.4f\t",kensWaveLength);
		for(k=0;k<NUMCHANNELS;k++){
			involts[k]=0.0;	
		}


		// grab several readings and average
		for(k=1;k<NUMCHANNELS;k++){
			for (i=0;i<nSamples;i++){
				getMCPAnalogIn(k,&measurement[i]);
				involts[k-1]=involts[k-1]+measurement[i];
				delay(10);
			}
//			for (i=0;i<nSamples;i++){
//				getUSB1208AnalogIn(k,&measurement[i]);
//				involts[k-1]=involts[k-1]+measurement[i];
//				delay(10);
//			}
			involts[k-1]=fabs(involts[k-1])/(float)nSamples;
			fprintf(fp,"%0.4f\t%0.4f\t",involts[k-1],stdDeviation(measurement,nSamples));
			printf("  %0.4f %0.4f  ",involts[k-1],stdDeviation(measurement,nSamples));
            if(k<NUMCHANNELS) printf(" | ");
		}
		for (i=0;i<nSamples;i++){
			getUSB1208AnalogIn(k,&measurement[i]);
			involts[k-1]=involts[k-1]+measurement[i];
			delay(10);
		}
        involts[k-1]=fabs(involts[k-1])/(float)nSamples;
        fprintf(fp,"%0.4f\t%0.4f\t",involts[k-1],stdDeviation(measurement,nSamples));
        printf("  %0.4f %0.4f  ",involts[k-1],stdDeviation(measurement,nSamples));

		fprintf(fp,"\n");
		printf("\n");
        count++;
	}

	fprintf(fp,"\n");
	fclose(fp);
	free(measurement);
}