Пример #1
0
void ofApp::setup() {
    //ccv.setup("image-net-2012-vgg-d.sqlite3");
    ccv.setup("image-net-2012.sqlite3");

    cat.load("cat.jpg");
    dog.load("dog.jpg");
    car.load("car.jpg");
  
    // encode returns a vector containing the activations of a given
    // layer in the network. So if we run it on the last layer, i.e.
    // ccv.encode(myImage, ccv.numLayers()) we will receive a 1000-dim
    // vector containing the activations of the output neurons (the 1000
    // imageNet classes). better would be to use the second-to-last layer
    // instead, which for this network contains 4096 neurons. using this
    // layer makes a better compact image representation because these
    // neurons correspond to high-level features but are not as closely
    // tied to the specific classes of imageNet
    vector<float> catFeatures = ccv.encode(cat, ccv.numLayers()-1);
    vector<float> dogFeatures = ccv.encode(dog, ccv.numLayers()-1);
    vector<float> carFeatures = ccv.encode(car, ccv.numLayers()-1);

    // we take the correlation between every pair of feature
    // representations and see that the correlation between the
    // cat and dog pictures is higher than the other two.
    // this is probably because cats and dogs share a number of
    // common features
    r_cat_dog = correlation(catFeatures, dogFeatures);
    r_cat_car = correlation(catFeatures, carFeatures);
    r_dog_car = correlation(dogFeatures, carFeatures);
}
Пример #2
0
 T BivarStats<T>::sigmaYX(void) const
 {
    if (ns>2)
       return (stdDevY() * SQRT(T(ns-1) / T(ns-2))
               * SQRT(T(1) - correlation() * correlation()) );
    else return T();
 }
Пример #3
0
 // TODO: maybe factor out the vector similarity methods. They're not exactly
 // specific to tone profiling.
 float ToneProfile::similarity(similarity_measure_t measure, const std::vector<float>& input, int offset) const {
   if (input.size() != 12) throw Exception("Input vector for similarity must have 12 elements");
   if (measure == SIMILARITY_CORRELATION)
     return correlation(input, offset);
   else
     return cosine(input, offset);
 }
Пример #4
0
double Corr::avgCorrelation(int N1, int N2, deque<int> *spikeTimesCor, double sig, double dt) {
    double t = 0;
    for (int i = N1; i < N2 - 1; i++) {
        t += correlation(spikeTimesCor[i], spikeTimesCor[i + 1], dt, sig);

    }
    return t / pow((N2 - N1), 2);
}
Пример #5
0
Файл: corrsp.c Проект: ombt/ombt
/* main entry */
submain(int argc, char **argv)
{
	int c;

	/* get command line options */
	while ((c = getopt(argc, argv, "?")) != EOF)
	{
		/* get options */
		switch (c)
		{
		case '?':
			/* help message */
			usage(argv[0]);
			return(0);

		default:
			/* error */
			ERROR("invalid option.", EINVAL);
			usage(argv[0]);
			return(2);
		}
	}

	/* check if spectra and output file were given */
	if ((optind + 3) > argc)
	{
		ERROR("missing spectrum or output file.", EINVAL);
		usage(argv[0]);
		return(2);
	}

	/* create spectra */
	Spectrum sp1(argv[optind]);
	if ((errno = sp1.getStatus()) != OK)
	{
		ERRORS("spectrum constructor failed for spectrum.", 
			argv[optind], errno);
		exit(2);
	}
	Spectrum sp2(argv[optind+1]);
	if ((errno = sp2.getStatus()) != OK)
	{
		ERRORS("spectrum constructor failed for spectrum.", 
			argv[optind+1], errno);
		exit(2);
	}

	/* do correlation */
	Spectrum corrsp = correlation(sp1, sp2);
	
	/* write out spectrum */
	corrsp.writeSpectrum(argv[optind+2]);

	/* all done */
	return(0);
}
Пример #6
0
float correlation(List<Pixel> *ps) {
	List<float> xs,ys;
	for (int i=1;i<=ps->len;i++) {
		xs.add(ps->num(i).x);
		ys.add(ps->num(i).y);
	}
	float c=correlation(xs,ys);
	xs.freedom(); ys.freedom();
	return c;
}
Пример #7
0
double pWaveOccurenceRatio(const QVector<Cit> &pWaveStarts,
                           const Cit &endOfSignal) {
  if (biggestIteratorTooBig(pWaveStarts, endOfSignal))
    throw PWaveStartTooCloseToEndOfSignal();
  const int count =
      count_if(begin(pWaveStarts), end(pWaveStarts), [](const Cit &it) {
        return 0.2 < correlation(begin(averagePWave), end(averagePWave), it);
      });
  return double(count) / pWaveStarts.size();
}
Пример #8
0
int main(int argc, char* argv[]) 
//int main(void) 
{
	double t_start, t_end;
	
	DATA_TYPE* data;
	DATA_TYPE* mean;
	DATA_TYPE* stddev;
	DATA_TYPE* symmat;
	DATA_TYPE* symmat_outputFromGpu;
        if(argc==2){
          printf("arg 1 = %s\narg 2 = %s\n", argv[0], argv[1]);
          cpu_offset = atoi(argv[1]);
        }


	data = (DATA_TYPE*)malloc((M + 1)*(N + 1)*sizeof(DATA_TYPE));
	mean = (DATA_TYPE*)malloc((M + 1)*sizeof(DATA_TYPE));
	stddev = (DATA_TYPE*)malloc((M + 1)*sizeof(DATA_TYPE));
	symmat = (DATA_TYPE*)malloc((M + 1)*(N + 1)*sizeof(DATA_TYPE));
	symmat_outputFromGpu = (DATA_TYPE*)malloc((M + 1)*(N + 1)*sizeof(DATA_TYPE));
	
	init_arrays(data);
	read_cl_file();
	cl_initialization_fusion();
	//cl_initialization();
	cl_mem_init(data, mean, stddev, symmat);
	cl_load_prog();

	double start = rtclock();
	cl_launch_kernel();
	double end = rtclock(); 
	fprintf(stdout, "CAUTION:CPU offset %d %% GPU Runtime: %0.6lf s\n",cpu_offset, (end - start));
	//fprintf(stdout, "CAUTION:CPU offset %d %% GPU Runtime: %0.6lf s\n",cpu_offset, 1000*(end - start));

	errcode = clEnqueueReadBuffer(clCommandQue[0], symmat_mem_obj, CL_TRUE, 0, (M+1) * (N+1) * sizeof(DATA_TYPE), symmat_outputFromGpu, 0, NULL, NULL);
	if(errcode != CL_SUCCESS) printf("Error in reading GPU mem\n");

	t_start = rtclock();
	correlation(data, mean, stddev, symmat);
	t_end = rtclock(); 
	fprintf(stdout, "CPU Runtime: %0.6lfs\n", t_end - t_start);   


	compareResults(symmat, symmat_outputFromGpu);
	cl_clean_up();
	
	free(data);
	free(mean);
	free(stddev);
	free(symmat);
	free(symmat_outputFromGpu);
	
    return 0;
}
Пример #9
0
 boost::shared_ptr<StochasticProcess>
 TwoFactorModel::ShortRateDynamics::process() const {
     Matrix correlation(2,2);
     correlation[0][0] = correlation[1][1] = 1.0;
     correlation[0][1] = correlation[1][0] = correlation_;
     std::vector<boost::shared_ptr<StochasticProcess1D> > processes;
     processes[0] = xProcess_;
     processes[1] = yProcess_;
     return boost::shared_ptr<StochasticProcess>(
                        new StochasticProcessArray(processes,correlation));
 }
Пример #10
0
double *linear_fit(dataset *dat, fit_conf *conf) {
	double *fit, *fit_act;
	double chng = 1;
	double chng_o = 0;
	int k, l;

	fit = malloc(9 * sizeof(double));
	if (!fit)
		return NULL;

	if (!(fit_act = init_fit(dat, conf)))
		return NULL;
	for (k = 0;
			(k < conf->max_iter) && (chng >= conf->min_chng)
					&& (fabs(chng_o - chng) > 1e-20); ++k) {
		for (l = 0; l < 5; ++l)
			fit[l] = fit_act[l];
		free(fit_act);
		fit_act = m_fit(dat, conf, fit[0], fit[2]);
		if (fit_act != NULL) {
			chng_o = chng;
			chng = fabs(fit[0] - fit_act[0]);
		} else {
			fit_act = fit;
			fit_act[5] = 4;
			/*printf("Speicher konnte nicht zugewiesen werden,\n");*/
			break;
		}
	}
	if (k == conf->max_iter) {
		/*printf("Maximale Anzahl Iterationen erreicht.\n");*/
		fit_act[5] = 1;
	} else if (chng < conf->min_chng) {
		/*printf("Aenderung wurde zu klein.\n");*/
		fit_act[5] = 2;

	} else if (fabs(chng_o - chng) < 1e-20) {
		/*printf("Daten eingependelt.\n");*/
		fit_act[5] = 3;
	}
	/* 4 = speicher konnte nicht zugewiesen werden, iteration musste abgebrochen werden*/

	/*Rueckgabe der Anzahl an Iterationen*/
	fit_act[6] = k;
	/*Rueckgabe der letzten Aenderung*/
	fit_act[7] = chng;
	/*Berechnung des Korellationskoeffizienten */
	fit_act[4] = correlation(dat, conf);

	if (fit != fit_act)
		free(fit);
	return fit_act;
}
Пример #11
0
double multipleCorrelation(double **X, double *y, int n, int m, double *b){

 int i,j; 
 double *yprime;
 yprime=allocateDoubleVector(m);

 for (i=0; i<m; i++){
  yprime[i]=0.0; 
  for (j=0; j<n; j++){
   yprime[i]+=b[j]*X[i][j];
  }
 }
  return correlation ((float*)y,(float*)yprime,m);
}
Пример #12
0
UpperTriangleVanillaSwaptionQuotes_ConstPTR create_UpperTriangleVanillaSwaptionQuotes(LMMTenorStructure_PTR pLMMTenorStructure, const Tenor& tenorfixedleg, const Tenor& tenorfloatleg)
{
	/// Creation of Rebonato Approx ==================================

	size_t nbFactor       = 3; // need to test nbFactor  = 3, and nbFactor = 
	size_t correlFullRank = pLMMTenorStructure->get_horizon()+1;
	size_t correlReducedRank = nbFactor;
	CorrelationReductionType::CorrelationReductionType correlReductionType = CorrelationReductionType::PCA;
	double correlAlpha = 0.0;
	double correlBeta  = 0.1;
	Correlation_PTR correlation(new XY_beta_Correlation(correlFullRank,correlReducedRank, correlReductionType,correlAlpha,correlBeta));
	correlation->calculate(); // for print.

	double a=0.22,b=0.4,c=0.6,d=0.15;
	double g_constParam = 1.;
	double shift_constParam = 0.0;

	Shifted_HGVolatilityParam::ABCDParameter abcdParam(a,b,c,d);
	ConstShifted_HGVolatilityParam_PTR pConstShifted_HGVolatilityParam( new ConstShifted_HGVolatilityParam(pLMMTenorStructure, abcdParam, g_constParam, shift_constParam));


	Shifted_HGVolatilityFunction_PTR pVolatilityFunction (new ConstShifted_HGVolatilityFunction(pLMMTenorStructure, correlation, pConstShifted_HGVolatilityParam)); 

	//! Dispersion
	Dispersion dispersion(pVolatilityFunction);

	Lmm_PTR lmm_ptr(new Lmm(dispersion) );

	LmmVanillaSwaptionApproxPricer_Rebonato_PTR pLmmApproxVanillaSwaptionPricer(new LmmVanillaSwaptionApproxPricer_Rebonato(lmm_ptr));	
	/// End of creation of Rebonato Approx ==================================


	LiborQuotes_ConstPTR libor_quote_ptr = LiborQuotes::create_LiborInit(pLMMTenorStructure, 0.02);

	UpperTriangleVanillaSwaptionQuotes_ConstPTR atm_swaption_implied_vol_ptr = UpperTriangleVanillaSwaptionQuotes::create_ATMSwaptionImpliedVol(
		libor_quote_ptr,
		tenorfixedleg,
		tenorfloatleg,
		pLmmApproxVanillaSwaptionPricer
		);

	//assert( atm_swaption_implied_vol_ptr->check_swaprate_consistency(libor_quote_ptr) );

	return atm_swaption_implied_vol_ptr;
}
Пример #13
0
void testBivariateStats(){

 
 float x[]={95.0,85.0,80.0,70.0,60.0};
 float y[]={85.0,95.0,70.0,65.0,70.0};
 regressionCoefficients coeffs;
 
 coeffs=regression(x,y,5);
 
 printf("\nBivariate Stats\n"); 
 printf("correlation =%f\n",correlation(x,y,5));
 printf("covariance =%f\n",covariance(x,y,5));
 printf("rmse =%f\n",rmse(x,y,5));
 printf("bias =%f\n",bias(x,y,5));
 printf("m =%f\n",coeffs.m);
 printf("c =%f\n",coeffs.c);
 
}
Пример #14
0
//*************************************************************************
double cost(double **image,double *vec, int *bounds, int vecbounds[2], int ncols, int n) {
    int i;

    int ba=vecbounds[0];
    int fa=vecbounds[1];    
    int bb,fb,deb,fin;    
    double s=0;
        
    for(i=0;i<ncols;i++) {
        if(i!=n) {
            bb=bounds[2*i];
            fb=bounds[2*i+1];
            deb=(ba>bb?ba:bb);
            fin=(fa<fb?fa:fb);
            s+=correlation(vec+deb-ba, image[i]+deb-bb, fin-deb);
        }
    }
    return s/ncols;
}
Пример #15
0
void B2Trk(B2ChnlPrms * chnlInst,char dataIn)
{	
	B2TrkPrms *trkInst = &(chnlInst->trkInst);

	// 相关运算
	correlation(chnlInst,dataIn);

	//如果是一个完整的码周期
	if (trkInst->oneCircle == 1)
	{
		// 鉴相
			discriminator(trkInst);	

		//一阶滤波
			trkInst->flt_codeLoop = codeLoopFilter(&(trkInst->lpf),trkInst->dis_dll);
				
		//二阶滤波
			trkInst->flt_carrierLoop = carrierLoopFilter(&(trkInst->lpf),trkInst->dis_pll,trkInst->dis_fll);
		
		// 更新跟踪参数
			updateTrk(chnlInst);
		

		//比特流处理
			//subFrameUpdate(chnl);

	}

	
	//↓↓↓↓↓↓ for test↓↓↓↓↓↓↓
	if (outflag == 1)
	{
		writeToFile(chnlInst->TCAR.phs,(chnlInst->chnlID-1)*11+CAR_PHS_SRC_OUT);
		writeToFile(chnlInst->TPRN.phs,(chnlInst->chnlID-1)*11+PRN_PHS_SRC_OUT);
		writeToFile(chnlInst->trkInst.car.phs,(chnlInst->chnlID-1)*11+CAR_PHS_LCL_OUT);
		writeToFile(chnlInst->trkInst.prn.phs.phsP,(chnlInst->chnlID-1)*11+PRN_PHS_LCL_OUT);
	}
	// ↑↑↑↑↑↑for test↑↑↑↑↑↑↑
	


}
Пример #16
0
double calcDistanceFromCluster(struct rnaBinder *rb, struct clusterMember *cmList,
			       struct dMatrix *sjIndex, struct dMatrix *psInten)
/* Calculate the distance from the rnaBinder intensity measurement to
   the sjIndexes of the cluster members. If no intensity present use
   0 as it will fall in the middle of [-1,1]. */
{
double sum = 0;
int count = 0;
int sjIx = 0, gsIx = 0;
struct clusterMember *cm = NULL;
double corr = 0;
if(sjIndex->colCount != psInten->colCount)
    errAbort("Splice Junction and Intensity files must have same number of columns.");

/* Get the index of the gene set in the intensity file. */
gsIx = hashIntValDefault(psInten->nameIndex, rb->psName, -1);
if(gsIx == -1)
    {
/*     warn("Probe Set %s not found in intensitiy file."); */
    return 0;
    }
for(cm = cmList; cm != NULL; cm = cm->next)
    {
    /* For each member get the index in the splice junction file. */
    sjIx = hashIntValDefault(sjIndex->nameIndex, cm->psName, -1);
    if(sjIx == -1)
	errAbort("Probe Set %s not found in SJ index file.");
    corr = correlation(psInten->matrix[gsIx], sjIndex->matrix[sjIx], sjIndex->colCount);
    sum += corr;
    count++;
    }
if(count == 0)
    errAbort("No junctions in cluster.");
sum = sum / (double) count;
return sum;
}
Пример #17
0
Файл: knnc.c Проект: cran/EMV
void knnc(double *array_vec,int *nb_col,int *nb_row, int*k, int *corre_flag, double *dist, double *dist_bound)
{
  int missing,i,j,ii;
  int count;
  double value;
  double *temp;
  double *row_nb;
  double ** array;
  int *miss_pos;
  int index;
  int *n_position;
  int* nb_neighboors;

  int min=0;
  int max=*k-1;
  
  array=dmatrix(*nb_row,*nb_col);

  /** contain the row numbers of the missing values **/
  miss_pos=ivector(*nb_col, code_miss);

  /** contains the distances of the neighboors **/
  temp=dvector(*k,code_miss); 
  /** contains the row numbers of the neighboors **/
  row_nb=dvector(*k,code_miss);
  /** initilize all the distances with the missing codes **/
  init_dvector(dist, nb_row, code_miss);

  n_position=ivector(*nb_row, code_miss); /** positions of potential neighboors **/
  nb_neighboors=ivector(1, code_miss); /** number of neighboors **/

  /** coerce the vector into a two dimmensional array **/
  vec_mat(array_vec,nb_row,nb_col,array); 
 
  neighboors(array, nb_row, nb_col, n_position, nb_neighboors);

  if(*nb_neighboors==0) /** Stop if no neighboors **/ 
    {
      error("No rows without missing values"); 
    }
  else 
    {
      if(*nb_neighboors<*k) /** If less than k neighboors give a warning **/
	warning("Only %d neighboors could be used", *nb_neighboors); 
      
      for(i=0;i<*nb_row;i++)
	{
	  /** Check for missing values **/
	  missing=is_na(array[i],nb_col,miss_pos);
	  
	  if (missing==1 && miss_pos[*nb_col-1]==code_miss) /**at least one missing value at most nb_col**/
	    {
	      if(*corre_flag==1 && miss_pos[*nb_col-2]!=code_miss) /** Give a warning if based on correlation and only one observation **/
		warning("Could not estimate the missing values for the row %d\n One observation is not enough to compute the sample correlation", i+1); 
	      else
		{
		  count=0;  
		  
		  for(j=0;j<*nb_neighboors;j++)  /** loop on the neighboors only **/
		    { 
		      index=n_position[j];
		      
		      if(*corre_flag==0)
			value=distance(array[i],array[index],nb_col);  /** compute the distance **/
		      else
			value=-correlation(array[i],array[index],nb_col);  /** compute the correlation **/
		      
		      if(value!=code_miss)
			{
			  if (count<*k) /** store the first k **/
			    {
			      temp[count]=value;
			      row_nb[count]=index;
			      count++;
			    }
			  else
			    {
			      quicksort2(temp,row_nb,&min,&max); /** sort the neighboors to keep the kth nearest **/
			      if (temp[*k-1]>value)  /** keep it if the distance is shorter **/
				{
				  temp[*k-1]=value;
				  row_nb[*k-1]=index;
				}       
			    } 
			}
		      
		    } 
		  
		  if(*corre_flag==0)
		    {
		      fill_up(array,row_nb,nb_col,k,i,miss_pos,temp, dist_bound); /** fill up the missing values by the averaging the distance**/
		      dist[i]=mean_vec(temp, k); /** Compute the average distances **/
		    }
		  else
		    {
		      fill_up_corr(array,row_nb, nb_col, k,i, miss_pos, temp, dist_bound); /** fill up the missing values based on correlations**/
		      dist[i]=-mean_vec(temp, k); /** Compute the average distances **/
		    }
		  
		  
		  init_dvector(row_nb, k, code_miss);    /** initialize row_nb with missing codes **/
		  init_dvector(temp, k, code_miss);        /** initialize temp with missing codes **/
		}
	    }
	  else if(missing==1 && miss_pos[*nb_col-1]!=code_miss)
	    warning("Could not estimate the missing values for the row %d\n The row only contains missing values", i+1); 
	}
    }
  
  mat_vec(array_vec, nb_row, nb_col,array); /** recoerce the matrix into a vector **/

  /** free the memory **/
  free_dmatrix(array,*nb_row); 
  Free(miss_pos);
  Free(temp);
  Free(row_nb);
  Free(n_position);
  Free(nb_neighboors);
}
Пример #18
0
void Test_McGeneticSwapLMMPricer()
{

	//! Parameters
	double	strike			=	0.02;
	LMM::Index	indexStart	=	0;
	LMM::Index	indexEnd	=	20;
	Tenor	floatingTenor	=	Tenor::_6M;
	Tenor	fixedTenor		=	Tenor::_12M;
	Tenor	tenorStruture	=	Tenor::_6M;
	size_t	horizonYear		=	10;
	LMMTenorStructure_PTR lmmTenorStructure( new LMMTenorStructure(tenorStruture, horizonYear));

	cout	<<	"strike:                        "	<<	strike												<<	endl;
	cout	<<	"indexStart:                    "	<<	indexStart											<<	endl;
	cout	<<	"indexEnd:                      "	<<	indexEnd											<<	endl;
	cout	<<	"tenorStrutureYearFraction:     "	<<	lmmTenorStructure->get_tenorType().YearFraction()	<<	endl;
	cout	<<	"floatingVStenorStrutureRatio:  "	<<	floatingTenor.ratioTo(tenorStruture)				<<	endl;
	cout	<<	"fixedVStenorStrutureRatio:     "	<<	fixedTenor.ratioTo(tenorStruture)					<<	endl;

	double	fwdRate		=	0.02;
	std::vector<double> liborsInitValue(lmmTenorStructure->get_horizon()+1, fwdRate);
	cout	<<	"myInitialLibor:  ";
	for (size_t i = 0; i <liborsInitValue.size(); i++)
	{
		cout	<<	liborsInitValue[i]	<<	" ";
	}
	cout	<<	 endl;
	cout	<<	 endl;


	//VanillaSwap_Chi_Trang
	VanillaSwap firstVersionVanillaSwap(strike, indexStart , indexEnd, floatingTenor, fixedTenor, lmmTenorStructure);
	LmmVanillaSwapPricer myVSP(lmmTenorStructure);
	double FirstVersionSwapPrice	=	myVSP.swapNPV_Analytical_1(firstVersionVanillaSwap, liborsInitValue);

	//---------------------------Build Lmm and McLmm's structure--------------------------------------
	//! Parameter of h
	double a = -0.06;
	double b = 0.17;
	double c = 0.54;
	double d = 0.17;
	Shifted_HGVolatilityParam::ABCDParameter abcdParam (a,b,c,d);
	//Parameter of hg
	double g_constParam = 1.0;
	double shift_constParam = -0.01;
	ConstShifted_HGVolatilityParam_PTR hgParam( new ConstShifted_HGVolatilityParam(lmmTenorStructure,abcdParam,g_constParam,shift_constParam));
	
	//! Correlation 1
	size_t nbFactor       = 3; // need to test nbFactor  = 3, and nbFactor = 
	size_t correlFullRank = lmmTenorStructure->get_horizon()+1;
	size_t correlReducedRank = nbFactor;
	//!"Check Parameters(): Condition not implemented yet."
	std::cout << "checkParams(): ";
	CorrelationReductionType::CorrelationReductionType correlReductionType = CorrelationReductionType::PCA;
	double correlAlpha = 0.0;
	double correlBeta  = 0.1;
	Correlation_PTR correlation(new XY_beta_Correlation(correlFullRank,correlReducedRank, correlReductionType,correlAlpha,correlBeta));
	correlation->calculate(); // for print.
	correlation->print("test_McTerminalLmm_Correlation.csv");
	//hgVolatilityFunction
	ConstShifted_HGVolatilityFunction_PTR hgVolatilityFunction (new ConstShifted_HGVolatilityFunction(lmmTenorStructure, correlation, hgParam)); 
	hgVolatilityFunction->print("test_McTerminalLmm_Volatility.csv");
	//! Dispersion
	Dispersion dispersion(hgVolatilityFunction);

	unsigned long seed = 5033;
	RNGenerator_PTR  rnGenerator(new McGenerator(seed));

	//build lmm and mcLmm model
	Lmm_PTR shiftedLmm (new Lmm(dispersion));
	McLmm_PTR mcLmm(new McTerminalLmm(shiftedLmm, liborsInitValue, rnGenerator, MCSchemeType::EULER));

	//build a McGeneticSwapLMMPricer
	McGeneticSwapLMMPricer_PTR mcGeneticSwapLMMPricer(new McGeneticSwapLMMPricer(mcLmm));

	//build the geneticVanillaSwap
	GeneticSwap_CONSTPTR vanillaSwap_Genetic=InstrumentFactory::createVanillaSwap(
			strike,indexStart,indexEnd,floatingTenor,fixedTenor,lmmTenorStructure,1.0);

	//use Monte Carlo Method
	size_t nbSimulation=10000;
	double	MonteCarloPrice		=	mcGeneticSwapLMMPricer->swapNPV(vanillaSwap_Genetic, nbSimulation);

	//ordinaryGeneticVanillaSwapPricer
	GeneticVanillaSwapPricer_PTR geneticVanillaSwapPricer(new GeneticVanillaSwapPricer());
	double	OrdinaryGeneticVanillaSwapPrice		=	geneticVanillaSwapPricer->geneticVanillaSwap_Analytical(vanillaSwap_Genetic,liborsInitValue);

	//subVanillaSwap
	LMM::Index	subIndexStart	=	10;
	LMM::Index	subIndexEnd		=	16;
	GeneticSwap_CONSTPTR subVanillaSwap_Genetic=InstrumentFactory::createVanillaSwap(
			strike,subIndexStart,subIndexEnd,floatingTenor,fixedTenor,lmmTenorStructure,1.0);
	double	subMonteCarloPrice	=	mcGeneticSwapLMMPricer->swapNPV(subVanillaSwap_Genetic, nbSimulation);
	//subOrdinaryGeneticVanillaSwapPrice
	double	subOrdinaryGeneticVanillaSwapPrice		=	geneticVanillaSwapPricer->geneticVanillaSwap_Analytical(subVanillaSwap_Genetic,liborsInitValue);
	//subFirstVersionVanillaSwapPrice
	VanillaSwap subFirstVersionVanillaSwap(strike, subIndexStart , subIndexEnd, floatingTenor, fixedTenor, lmmTenorStructure);
	double subFirstVersionSwapPrice		=	myVSP.swapNPV_Analytical_1(subFirstVersionVanillaSwap, liborsInitValue);


	cout	<<	"MonteCarloPrice: "																		<<	MonteCarloPrice													<<	endl;
	cout	<<	"OrdinaryGeneticVanillaSwapPrice: "														<<	OrdinaryGeneticVanillaSwapPrice									<<	endl;
	cout	<< "FirstVersionSwapPrice: "																<< FirstVersionSwapPrice											<< endl;
	cout	<<	"Difference between MonteCarloPrice and OrdinaryGeneticVanillaSwapPrice: "				<<	MonteCarloPrice-OrdinaryGeneticVanillaSwapPrice					<<	endl;	
	cout	<<	"Difference between OrdinaryGeneticVanillaSwapPrice and FirstVersionSwapPrice: "		<<	OrdinaryGeneticVanillaSwapPrice-FirstVersionSwapPrice			<<	endl;	
	cout	<<	"subMonteCarloPrice: "																	<<	subMonteCarloPrice												<<	endl;
	cout	<<	"subOrdinaryGeneticVanillaSwapPrice: "													<<	subOrdinaryGeneticVanillaSwapPrice								<<	endl;
	cout	<< "subFirstVersionSwapPrice: "																<< subFirstVersionSwapPrice											<< endl;
	cout	<<	"Difference between subMonteCarloPrice and subOrdinaryGeneticVanillaSwapPrice: "		<<	subMonteCarloPrice-subOrdinaryGeneticVanillaSwapPrice			<<	endl;	
	cout	<<	"Difference between subOrdinaryGeneticVanillaSwapPrice and subFirstVersionSwapPrice: "	<<	subOrdinaryGeneticVanillaSwapPrice-subFirstVersionSwapPrice		<<	endl;

	ofstream o;
	o.open("TestResult_GeneticVanillaSwap_05_06.csv",  ios::out | ios::app );
	o	<<	endl;
	o	<<	endl;
	o	<<	endl;
	o	<<	"strike: "									<<	strike														<<	endl;
	o	<<	"indexStart: "								<<	indexStart													<<	endl;
	o	<<	"indexEnd: "								<<	indexEnd													<<	endl;
	o	<<	"floatingTenorVSLmmStructureTenorRatio: "	<<	floatingTenor.ratioTo(lmmTenorStructure->get_tenorType())	<<	endl;
	o	<<	"fixedTenorVSLmmStructureTenorRatio: "		<<	fixedTenor.ratioTo(lmmTenorStructure->get_tenorType())		<<	endl;
	o	<<	"floatingTenorYearFraction: "				<<	floatingTenor.YearFraction()								<<	endl;
	o	<<	"fixedTenorYearFraction: "					<<	fixedTenor.YearFraction()									<<	endl;
	o	<<	"horizonYear: "								<<	horizonYear													<<	endl;
	o	<<	"liborsInitValue: ";
	for(size_t i=0; i<liborsInitValue.size(); i++)
	{
		o	<<	liborsInitValue[i]	<<	" ";
	}
	o	<<	endl;
	o	<<	"nbSimulation: "																		<<	nbSimulation													<<	endl;
	o	<<	"PRICES: "	<<	endl;
	o	<<	"MonteCarloPrice: "																		<<	MonteCarloPrice													<<	endl;
	o	<<	"OrdinaryGeneticVanillaSwapPrice: "														<<	OrdinaryGeneticVanillaSwapPrice									<<	endl;
	o	<<	"FirstVersionSwapPrice: "																<< FirstVersionSwapPrice											<<	endl;
	o	<<	"Difference between MonteCarloPrice and OrdinaryGeneticVanillaSwapPrice: "				<<	MonteCarloPrice-OrdinaryGeneticVanillaSwapPrice					<<	endl;	
	o	<<	"Difference between OrdinaryGeneticVanillaSwapPrice and FirstVersionSwapPrice: "		<<	OrdinaryGeneticVanillaSwapPrice-FirstVersionSwapPrice			<<	endl;
	o	<<	"SUBPRICES: "<<	endl;
	o	<<	"subIndexStart: "																		<<	subIndexStart													<<	endl;
	o	<<	"subIndexEnd: "																			<<	subIndexEnd														<<	endl;
	o	<<	"subMonteCarloPrice: "																	<<	subMonteCarloPrice												<<	endl;
	o	<<	"subOrdinaryGeneticVanillaSwapPrice: "													<<	subOrdinaryGeneticVanillaSwapPrice								<<	endl;
	o	<<	"subFirstVersionSwapPrice: "															<< subFirstVersionSwapPrice											<<	endl;
	o	<<	"Difference between subMonteCarloPrice and subOrdinaryGeneticVanillaSwapPrice: "		<<	subMonteCarloPrice-subOrdinaryGeneticVanillaSwapPrice			<<	endl;	
	o	<<	"Difference between subOrdinaryGeneticVanillaSwapPrice and subFirstVersionSwapPrice: "	<<	subOrdinaryGeneticVanillaSwapPrice-subFirstVersionSwapPrice		<<	endl;	

	o.close();
}
Пример #19
0
static int
guessSize(int fd, TIFFDataType dtype, off_t hdr_size, uint32 nbands,
	  int swab, uint32 *width, uint32 *length)
{
	const float longt = 40.0;    /* maximum possible height/width ratio */
	char	    *buf1, *buf2;
	struct stat filestat;
	uint32	    w, h, scanlinesize, imagesize;
	uint32	    depth = TIFFDataWidth(dtype);
	float	    cor_coef = 0, tmp;

	fstat(fd, &filestat);

	if (filestat.st_size < hdr_size) {
		fprintf(stderr, "Too large header size specified.\n");
		return -1;
	}

	imagesize = (filestat.st_size - hdr_size) / nbands / depth;

	if (*width != 0 && *length == 0) {
		fprintf(stderr,	"Image height is not specified.\n");

		*length = imagesize / *width;
		
		fprintf(stderr, "Height is guessed as %lu.\n",
			(unsigned long)*length);

		return 1;
	} else if (*width == 0 && *length != 0) {
		fprintf(stderr, "Image width is not specified.\n");

		*width = imagesize / *length;
		
		fprintf(stderr,	"Width is guessed as %lu.\n",
			(unsigned long)*width);

		return 1;
	} else if (*width == 0 && *length == 0) {
		fprintf(stderr,	"Image width and height are not specified.\n");

#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
		for (w = (uint32) sqrt(imagesize / longt);
		     w < sqrt(imagesize * longt);
		     w++) {
			if (imagesize % w == 0) {
				scanlinesize = w * depth;
				buf1 = _TIFFmalloc(scanlinesize);
				buf2 = _TIFFmalloc(scanlinesize);
				h = imagesize / w;
				lseek(fd, hdr_size + (int)(h/2)*scanlinesize,
				      SEEK_SET);
				read(fd, buf1, scanlinesize);
				read(fd, buf2, scanlinesize);
				if (swab) {
					swapBytesInScanline(buf1, w, dtype);
					swapBytesInScanline(buf2, w, dtype);
				}
				tmp = (float) fabs(correlation(buf1, buf2,
							       w, dtype));
				if (tmp > cor_coef) {
					cor_coef = tmp;
					*width = w, *length = h;
				}

				_TIFFfree(buf1);
				_TIFFfree(buf2);
			}
		}

		fprintf(stderr,
			"Width is guessed as %lu, height is guessed as %lu.\n",
			(unsigned long)*width, (unsigned long)*length);

		return 1;
	} else {
		if (filestat.st_size<(off_t)(hdr_size+(*width)*(*length)*nbands*depth)) {
			fprintf(stderr, "Input file too small.\n");
		return -1;
		}
	}

	return 1;
}
Пример #20
0
void preoptim(int nv)
{
int answ,k,i,s,gdrive=VGA,gmode=2;
long n[3];
double c[16],pv[16];
extern int npexp;
extern double pexpx[],pexpy[],pexpz[];
extern char namesch[],statpexp[];
int grafcond(void);
void grafica(int, double *pv);
void inspect(double *pv);
int search(long nsteps,long npoints,int nv,double *pv,double *c);
int search1(long nsteps,long npoints,double *a,double *c);
void searchpar(long *n);
void eliminate(void);
void initial(int nv,double *pv,double *c);
void initial1(int nv,double *pv,double *c);
int npgr;
double correlation(double *pv);
	for(i=0;i<npexp;i++)
		statpexp[i]=1;
	npgr=grafcond();
	initgraph(&gdrive,&gmode,"");
	answ=5993;
	do
	{
		switch(answ)
		{
			case 5993:
				initial(nv,pv,c);
			case 6512:
				n[2]=long(nv);
				searchpar(n);
			case 11875:
				if(nv==1)
					s=search1(n[1],n[0],pv,c);
				else
					s=search(n[1],n[0],nv,pv,c);
				switch(s)
				{
					case 1:
						puts("This is what you are searching for!");
					break;
					case 2:
						puts("Continue ! Modify parameters with <p> if you want.");
					break;
					case 0:
						if(nv==1)
						{
							puts("Raise npoints from <p> !");
							break;
						}
					default:
						puts("Something is bad !");
						return;
				}
				break;
			case 12654:
				inspect(pv);
				break;
			case 561:
				initial1(nv,pv,c);
				break;
			case 4978:
				printf("correlation coefficient = %f\n",correlation(pv));
				break;
			case 7777:
				npgr=grafcond();
			case 8807:
				puts("YOU MUST WAIT A LITTLE !");
				grafica(npgr,pv);
				break;
			case 4709:
				eliminate();
				break;
			default:
				puts("	Initialization        search Parameters      Continue");
				puts("	Eliminate/insert      iNspect                coRrelation");
				puts("	Graphics              graph quAlity          Stop");
				printf("	(i/p/c\n	 e/n/r\n	 g/a/s)\n ");
		}
		flushall();
		answ=bioskey(0);
	}
	while(answ!=8051);
	closegraph();
	puts("FINAL VALUES :");
	for(k=0;k<nv;k++)
	{
		printf("%2d  ",k);
		for(i=0;i<10;i++)
			printf("%c",namesch[10*k+i]);
		printf("		%12.7e\n",pv[k]);
	}
	return;
}
Пример #21
0
/**
 * Train a fern cascade.
 * @param images training images in gray scale
 * @param normalize_matrix similarity matrix
 * @param target_shapes target shapes of each face image
 * @param mean_shape mean shape
 * @param second_level_num level number for second level regression 
 * @param current_shapes current shapes of training images
 * @param pixel_pair_num number of pair of pixels to be selected
 * @param normalized_targets (target - current) * normalize_matrix
 */
void FernCascade::train(const vector<Mat_<uchar> >& images,
        const vector<Mat_<double> >& target_shapes,
        int second_level_num,
        vector<Mat_<double> >& current_shapes,
        int pixel_pair_num,
        vector<Mat_<double> >& normalized_targets,
        int pixel_pair_in_fern,
        const Mat_<double>& mean_shape,
        const vector<Bbox>& target_bounding_box){

    second_level_num_ = second_level_num;
	// coordinates of selected pixels
    Mat_<double> pixel_coordinates(pixel_pair_num,2);
	Mat_<int> nearest_keypoint_index(pixel_pair_num,1);
    RNG random_generator(getTickCount());
    int landmark_num = current_shapes[0].rows;
    int training_num = images.size();
    int image_width = images[0].cols;
    int image_height = images[0].rows;

    /* vector<Mat_<double> > normalized_curr_shape;  */
    // get bounding box of target shapes
   
    vector<Mat_<double> > normalized_shapes;
    /* vector<Mat_<double> > normalized_ground_truth; */


    normalized_shapes = project_shape(current_shapes,target_bounding_box);
    /* normalized_ground_truth = project_shape(target_shapes,target_bounding_box); */
    
    /*
    vector<SimilarityTransform> curr_to_mean_shape;
    vector<SimilarityTransform> ground_to_mean_shape;
    
    curr_to_mean_shape = get_similarity_transform(mean_shape,normalized_shapes);
    ground_to_mean_shape = get_similarity_transform(mean_shape,normalized_ground_truth);
     
    vector<Mat_<double> > curr_project_to_mean;
    vector<Mat_<double> > ground_project_to_mean;
    
    for(int i = 0;i < current_shapes.size();i++){
    ipd// get normalized_targets 
        Mat_<double> temp = curr_to_mean_shape[i].apply_similarity_transform(normalized_shapes[i]);
        curr_project_to_mean.push_back(temp.clone());

        temp = ground_to_mean_shape[i].apply_similarity_transform(normalized_ground_truth[i]);
        ground_to_mean_shape.push_back(temp.clone()); 
    }i
    */


    // calculate normalized targets
    normalized_targets = inverse_shape(current_shapes,target_bounding_box);
    normalized_targets = compose_shape(normalized_targets,target_shapes,target_bounding_box); 
    
    for(int i = 0;i < normalized_targets.size();i++){
        Mat_<double> rotation;
        Mat_<double> translation;
        double scale;
        translate_scale_rotate(mean_shape,normalized_shapes[i],translation,scale,rotation);
        transpose(rotation,rotation);
        normalized_targets[i] = scale * normalized_targets[i] * rotation;
    } 

    
    // normalized_targets.clear();
    // for(int i = 0;i < curr_project_to_mean.size();i++){
        // normalized_targets.push_back(ground_project_to_mean[i] - curr_project_to_mean[i]);
    // }

    // generate feature pixel location 
    for(int i = 0;i < pixel_pair_num;i++){
        double x = random_generator.uniform(-1.0,1.0);
        double y = random_generator.uniform(-1.0,1.0);

        if(x*x + y*y > 1){
            i--;
            continue;
        }
        
        // get its nearest landmark
        double min_dist = 1e10;
        int min_index = 0;
        for(int j = 0;j < landmark_num;j++){
            double temp = pow(mean_shape(j,0) - x,2.0) + pow(mean_shape(j,1) - y,2.0);
            if(temp < min_dist){
                min_dist = temp;
                min_index = j;
            } 
        } 
        nearest_keypoint_index(i) = min_index;
        pixel_coordinates(i,0) = x - mean_shape(min_index,0);
        pixel_coordinates(i,1) = y - mean_shape(min_index,1);
    }

    // get feature pixel location for each image
    // for pixel_density, each vector in it stores the pixel value for each image on the corresponding pixel locations
    vector<vector<double> > pixel_density;
    pixel_density.resize(pixel_pair_num);
    for(int i = 0;i < normalized_shapes.size();i++){
        // similarity transform from normalized_shapes to mean shape     
        Mat_<double> rotation(2,2);
        Mat_<double> translation(landmark_num,2);
        double scale = 0;

        translate_scale_rotate(normalized_shapes[i],mean_shape,translation,scale,rotation); 
       
        for(int j = 0;j < pixel_pair_num;j++){
            double x = pixel_coordinates(j,0);
            double y = pixel_coordinates(j,1);
            double project_x = rotation(0,0) * x + rotation(0,1) * y;
            double project_y = rotation(1,0) * x + rotation(1,1) * y;
            project_x = project_x * scale;
            project_y = project_y * scale;
            
            // resize according to bounding_box
            project_x = project_x * target_bounding_box[i].width/2.0;
            project_y = project_y * target_bounding_box[i].height/2.0; 
            
            int index = nearest_keypoint_index(j); 
            int real_x = project_x + current_shapes[i](index,0);
            int real_y = project_y + current_shapes[i](index,1);
            
             
            if(real_x < 0){
                real_x = 0;
            } 
            if(real_y < 0){
                real_y = 0;
            }
            if(real_x > images[i].cols-1){
                real_x = images[i].cols-1;
            }
            if(real_y > images[i].rows - 1){
                real_y = images[i].rows - 1;
            }
            pixel_density[j].push_back(int(images[i](real_y,real_x)));    
        }
    }

   	// calculate the correlation between pixels 
    Mat_<double> correlation(pixel_pair_num,pixel_pair_num);
    for(int i = 0;i < pixel_pair_num;i++){
        for(int j = i;j< pixel_pair_num;j++){
            double correlation_result = calculate_covariance(pixel_density[i],pixel_density[j]);
            correlation(i,j) = correlation_result;
            correlation(j,i) = correlation_result;
        }
    }
	// train ferns
    primary_fern_.resize(second_level_num);

    // predications for each shape 
    vector<Mat_<double> > prediction;
    prediction.resize(current_shapes.size());
    for(int i = 0;i < current_shapes.size();i++){
        prediction[i] = Mat::zeros(landmark_num,2,CV_64FC1);
    }
    
    for(int i = 0;i < second_level_num;i++){
		cout<<"Training fern "<<i<<endl;
        primary_fern_[i].train(pixel_density,correlation,pixel_coordinates,nearest_keypoint_index, current_shapes,pixel_pair_in_fern,normalized_targets,
                prediction); 
    }
    for(int i = 0;i < prediction.size();i++){
        Mat_<double> rotation;
        Mat_<double> translation;
        double scale;
        translate_scale_rotate(normalized_shapes[i],mean_shape,translation,scale,rotation);
        transpose(rotation,rotation);
        prediction[i] = scale * prediction[i] * rotation; 
    }
    current_shapes = compose_shape(prediction, current_shapes, target_bounding_box); 
    current_shapes = reproject_shape(current_shapes, target_bounding_box);
   
    /* Mat_<uchar> test_image_1 = images[10].clone(); */
    // for(int i = 0;i < landmark_num;i++){
        // circle(test_image_1,Point2d(current_shapes[10](i,0),current_shapes[10](i,1)),3,Scalar(255,0,0),-1,8,0);
    // }
    // imshow("result",test_image_1);
    /* waitKey(0);  */

}
Пример #22
0
void Key::compute() {

  const vector<Real>& pcp = _pcp.get();

  int pcpsize = (int)pcp.size();
  int n = pcpsize/12;

  if (pcpsize < 12 || pcpsize % 12 != 0)
    throw EssentiaException("Key: input PCP size is not a positive multiple of 12");

  if (pcpsize != (int)_profile_dom.size()) {
    resize(pcpsize);
  }

  ///////////////////////////////////////////////////////////////////
  // compute correlation

  // Compute means
  Real mean_pcp = mean(pcp);
  Real std_pcp = 0;

  // Compute Standard Deviations
  for (int i=0; i<pcpsize; i++)
    std_pcp += (pcp[i] - mean_pcp) * (pcp[i] - mean_pcp);
  std_pcp = sqrt(std_pcp);

  // Compute correlation matrix
  int keyIndex = -1; // index of the first maximum
  Real max     = -1;     // first maximum
  Real max2    = -1;    // second maximum
  int scale    = MAJOR;  // scale

  // Compute maximum for major, minor and other.
  Real maxMajor     = -1;
  Real max2Major    = -1;
  int keyIndexMajor = -1;

  Real maxMinor     = -1;
  Real max2Minor    = -1;
  int keyIndexMinor = -1;

  Real maxOther     = -1;
  Real max2Other    = -1;
  int keyIndexOther = -1;

  // calculate the correlation between the profiles and the PCP...
  // we shift the profile around to find the best match
  for (int shift=0; shift<pcpsize; shift++) {
    /*
    // Penalization if the Tonic has not a minimum amplitude
    // max_pcp needs to be calculated...
    Real factor = pcp[i]/max_pcp;
    if (factor < 0.6) {
      corrMajor *= factor / 0.6;
      corrMinor *= factor / 0.6;
    }
    */
    Real corrMajor = correlation(pcp, mean_pcp, std_pcp, _profile_doM, _mean_profile_M, _std_profile_M, shift);
    // Compute maximum value for major keys
    if (corrMajor > maxMajor) {
      max2Major = maxMajor;
      maxMajor = corrMajor;
      keyIndexMajor = shift;
    }

    Real corrMinor = correlation(pcp, mean_pcp, std_pcp, _profile_dom, _mean_profile_m, _std_profile_m, shift);
    // Compute maximum value for minor keys
    if (corrMinor > maxMinor) {
      max2Minor = maxMinor;
      maxMinor = corrMinor;
      keyIndexMinor = shift;
    }

    Real corrOther = 0;
    if (_useMajMin) {
      corrOther = correlation(pcp, mean_pcp, std_pcp, _profile_doO, _mean_profile_O, _std_profile_O, shift);
      // Compute maximum value for other keys
      if (corrOther > maxOther) {
        max2Other = maxOther;
        maxOther = corrOther;
        keyIndexOther = shift;
      }
    }
  }


  if (maxMajor > maxMinor && maxMajor > maxOther) {
    keyIndex = (int) (keyIndexMajor *  12 / pcpsize + 0.5);
    scale = MAJOR;
    max = maxMajor;
    max2 = max2Major;
  }

  else if (maxMinor >= maxMajor && maxMinor >= maxOther) {
    keyIndex = (int) (keyIndexMinor * 12 / pcpsize + 0.5);
    scale = MINOR;
    max = maxMinor;
    max2 = max2Minor;
    }

	else if (maxOther > maxMajor && maxOther > maxMinor) {
    keyIndex = (int) (keyIndexOther * 12 / pcpsize + 0.5);
    scale = MAJMIN;
    max = maxOther;
    max2 = max2Other;
    }

  // In the case of Wei Chai algorithm, the scale is detected in a second step
  // In this point, always the major relative is detected, as it is the first
  // maximum
  if (_profileType == "weichai") {
    if (scale == MINOR)
      throw EssentiaException("Key: error in Wei Chai algorithm. Wei Chai algorithm does not support minor scales.");

    int fifth = keyIndex + 7*n;
    if (fifth > pcpsize)
      fifth -= pcpsize;
    int sixth = keyIndex + 9*n;
    if (sixth > pcpsize)
      sixth -= pcpsize;

    if (pcp[sixth] >  pcp[fifth]) {
      keyIndex = sixth;
      keyIndex = (int) (keyIndex * 12 / pcpsize + .5);
      scale = MINOR;
    }
  }

  // keyIndex = (int)(keyIndex * 12.0 / pcpsize + 0.5) % 12;

  if (keyIndex < 0) {
    throw EssentiaException("Key: keyIndex smaller than zero. Could not find key.");
  }

  //////////////////////////////////////////////////////////////////////////////
  // Here we calculate the outputs...

  // first three outputs are key, scale and strength
  _key.get() = _keys[keyIndex];

  if (scale == MAJOR) {
    _scale.get() = "major";
  }

  else if (scale == MINOR) {
    _scale.get() = "minor";
  }

  else if (scale == MAJMIN) {
    _scale.get() = "majmin";
  }

  _strength.get() = max;

  // this one outputs the relative difference between the maximum and the
  // second highest maximum (i.e. Compute second highest correlation peak)
  _firstToSecondRelativeStrength.get() = (max - max2) / max;

}
Пример #23
0
double correlation(const QVector<double> &v1, const QVector<double> &v2) {
  return correlation(begin(v1), end(v1), begin(v2));
}
Пример #24
0
int main(void) 
{
  /* Prepare ctuning vars */
  long ct_repeat=0;
  long ct_repeat_max=1;

  DATA_TYPE* data;
  DATA_TYPE* mean;
  DATA_TYPE* stddev;
  DATA_TYPE* symmat;
  DATA_TYPE* symmat_outputFromGpu;

#ifdef OPENME
  openme_init(NULL,NULL,NULL,0);
  openme_callback("PROGRAM_START", NULL);
#endif

  /* Run kernel. */
  if (getenv("CT_REPEAT_MAIN")!=NULL) ct_repeat_max=atol(getenv("CT_REPEAT_MAIN"));

  data = (DATA_TYPE*)malloc((M + 1)*(N + 1)*sizeof(DATA_TYPE));
  mean = (DATA_TYPE*)malloc((M + 1)*sizeof(DATA_TYPE));
  stddev = (DATA_TYPE*)malloc((M + 1)*sizeof(DATA_TYPE));
  symmat = (DATA_TYPE*)malloc((M + 1)*(N + 1)*sizeof(DATA_TYPE));
  symmat_outputFromGpu = (DATA_TYPE*)malloc((M + 1)*(N + 1)*sizeof(DATA_TYPE));

  srand(1);
  init_arrays(data);
  read_cl_file();
  cl_initialization();
  cl_mem_init(data, mean, stddev, symmat);
  cl_load_prog();

#ifdef OPENME
  openme_callback("ACC_KERNEL_START", NULL);
#endif
  for (ct_repeat=0; ct_repeat<ct_repeat_max; ct_repeat++)
  {
    cl_launch_kernel();

    err_code = clEnqueueReadBuffer(clCommandQue, symmat_mem_obj, CL_TRUE, 0, (M+1) * (N+1) * sizeof(DATA_TYPE), symmat_outputFromGpu, 0, NULL, NULL);
    if(err_code != CL_SUCCESS)
    {
      printf("Error in reading GPU mem\n");
      exit(1);
    }
  }
#ifdef OPENME
  openme_callback("ACC_KERNEL_END", NULL);
#endif

  srand(1);
  init_arrays(data);

#ifdef OPENME
  openme_callback("KERNEL_START", NULL);
#endif
  for (ct_repeat=0; ct_repeat<ct_repeat_max; ct_repeat++)
  {
    correlation(data, mean, stddev, symmat);
  }
#ifdef OPENME
  openme_callback("KERNEL_END", NULL);
#endif

  compareResults(symmat, symmat_outputFromGpu);
  cl_clean_up();

  free(data);
  free(mean);
  free(stddev);
  free(symmat);
  free(symmat_outputFromGpu);

#ifdef OPENME
  openme_callback("PROGRAM_END", NULL);
#endif

  return 0;
}
Пример #25
0
int main(){
    int i, N;
    char c, file[100];
    
    // check that gnuplot is present on the system
    int gnupl = control();
    if(gnupl == 1){
        printf("\nYou need gnuplot to graph the results.");
        printf("\nInstall it with: sudo apt-get install gnuplot\n\n");
        exit(2);
    }
    
    printf("Enter the name or path of file: ");
    fgets(file,sizeof(file),stdin);
    file[strlen(file)-1] = '\0';
    
    // the file's lines number is the number of points to be saved
    N = linesFile(file);
    if(N <= 2){
        printf("\nError: insufficient data number.\n");
        exit(2);
    }
    
    // creating data's arrays
    double *x = calloc(N,sizeof(double));
    double *y = calloc(N,sizeof(double));
    double *errors = calloc(N,sizeof(double));
    if(x == NULL || y == NULL || errors == NULL){
            perror("\nerror");
            printf("\n");
            exit(1);
    }
    
    // reading from file
    FILE *inputFile = fopen(file,"r");
    if(inputFile == NULL){
        perror("\nError");
        exit(1);
    }
    
    for(i=0; i<N; i++){
        fscanf(inputFile,"%lf %lf %lf\n",&x[i],&y[i],&errors[i]);
    }
    
    fclose(inputFile);
    
    // determine linear coefficients
    double M = Mbest(N,x,y,errors);
    double Q = Qbest(N,x,y,errors,M);
    double sigmaM = fabs(uM(N,x,y,errors,M,Q));
    double sigmaQ = fabs(uQ(N,x,errors,sigmaM));
    
    // defining best sigma(Y) and correlation coefficient
    double sigmaY = fabs(bestSigma(N,x,y,M,Q)); // <-- residuals analysis
    double cov = covariance(N,x,y);
    double cor = correlation(N,x,y);
    double lCov = linearParamCovariance(N,mean(x,N),sigma(x,N,mean(x,N)),sigmaY,M,Q);
    double lCor = linearParamCorrelation(N,x);
    
    // Chi-square test
    int freedomDegrees = N - 2; // infer 2 parameters (): M and Q
    double chi2 = 0, rChi2;
    
    for(i=0; i<N; i++){
        chi2 += pow(y[i] - ((M * x[i]) + Q),2) / pow(errors[i],2);
    }
    
    rChi2 = chi2 / freedomDegrees;
    
    printf("\nThe best linear fit Y = mX + q is:");
    printf("\nm = %.3lf\tsigma(m) = %.3lf\nq = %.3lf\tsigma(q) = %.3lf",M,sigmaM,Q,sigmaQ);
    printf("\n\nBest sigma(Y) = %.3lf",sigmaY);
    printf("\nCov(X,Y) = %.3lf",cov);
    printf("\nCor(X,Y) = %.3lf",cor);
    printf("\nCov(m,c) = %.3lf",lCov);
    printf("\nCor(m,c) = %.3lf",lCor);
    //printf("\nChi square = %.3lf",chi2);
    printf("\nReduced Chi square = %.3lf",rChi2);
    
    // interpolation and extrapolation
    int choice;
    double pointX, pointY, sigmaPointY, alpha;
    printf("\n\nDo you want to extrapolate a point with the calculated linear regression? (1 = YES | 0 = NO): ");
    scanf("%d",&choice);
    if(choice == 1){
        extrapolation(N,x,errors,sigmaY,M,Q);
    }
    
    // creating fit
    printf("\nPlotting fit...\n");
    FILE *data = fopen("data.dat","w");
    if(data == NULL){
        perror("\nError");
        exit(1);
    }
    
    // writing experimental datas
    for(i=0; i<N; i++){
        fprintf(data,"%lf %lf %lf\n",x[i],y[i],errors[i]);
    }
    
    fclose(data);
    
    // creating fit points
    //fit(M,Q,x,N); // gnuplot feature
    
    free(x);
    free(y);
       
    return 0;
}
Пример #26
0
static int
guessSize(int fd, TIFFDataType dtype, _TIFF_off_t hdr_size, uint32 nbands,
	  int swab, uint32 *width, uint32 *length)
{
	const float longt = 40.0;    /* maximum possible height/width ratio */
	char	    *buf1, *buf2;
	_TIFF_stat_s filestat;
	uint32	    w, h, scanlinesize, imagesize;
	uint32	    depth = TIFFDataWidth(dtype);
	float	    cor_coef = 0, tmp;

	if (_TIFF_fstat_f(fd, &filestat) == -1) {
                fprintf(stderr, "Failed to obtain file size.\n");
		return -1;
        }

	if (filestat.st_size < hdr_size) {
		fprintf(stderr, "Too large header size specified.\n");
		return -1;
	}

	imagesize = (filestat.st_size - hdr_size) / nbands / depth;

	if (*width != 0 && *length == 0) {
		fprintf(stderr,	"Image height is not specified.\n");

		*length = imagesize / *width;
		
		fprintf(stderr, "Height is guessed as %lu.\n",
			(unsigned long)*length);

		return 1;
	} else if (*width == 0 && *length != 0) {
		fprintf(stderr, "Image width is not specified.\n");

		*width = imagesize / *length;
		
		fprintf(stderr,	"Width is guessed as %lu.\n",
			(unsigned long)*width);

		return 1;
	} else if (*width == 0 && *length == 0) {
                unsigned int fail = 0;
		fprintf(stderr,	"Image width and height are not specified.\n");
                w = (uint32) sqrt(imagesize / longt);
                if( w == 0 )
                {
                    fprintf(stderr, "Too small image size.\n");
                    return -1;
                }

		for (;
		     w < sqrt(imagesize * longt);
		     w++) {
			if (imagesize % w == 0) {
				scanlinesize = w * depth;
				buf1 = _TIFFmalloc(scanlinesize);
				buf2 = _TIFFmalloc(scanlinesize);
				h = imagesize / w;
                                do {
                                        if (_TIFF_lseek_f(fd, hdr_size + (int)(h/2)*scanlinesize,
                                                  SEEK_SET) == (_TIFF_off_t)-1) {
                                                fprintf(stderr, "seek error.\n");
                                                fail=1;
                                                break;
                                        }
                                        if (read(fd, buf1, scanlinesize) !=
                                            (long) scanlinesize) {
                                                fprintf(stderr, "read error.\n");
                                                fail=1;
                                                break;
                                        }
                                        if (read(fd, buf2, scanlinesize) !=
                                            (long) scanlinesize) {
                                                fprintf(stderr, "read error.\n");
                                                fail=1;
                                                break;
                                        }
                                        if (swab) {
                                                swapBytesInScanline(buf1, w, dtype);
                                                swapBytesInScanline(buf2, w, dtype);
                                        }
                                        tmp = (float) fabs(correlation(buf1, buf2,
                                                                       w, dtype));
                                        if (tmp > cor_coef) {
                                                cor_coef = tmp;
                                                *width = w, *length = h;
                                        }
                                } while (0);

                                _TIFFfree(buf1);
				_TIFFfree(buf2);
			}
		}

                if (fail) {
                        return -1;
                }

		fprintf(stderr,
			"Width is guessed as %lu, height is guessed as %lu.\n",
			(unsigned long)*width, (unsigned long)*length);

		return 1;
	} else {
		if (filestat.st_size<(_TIFF_off_t)(hdr_size+(*width)*(*length)*nbands*depth)) {
			fprintf(stderr, "Input file too small.\n");
		return -1;
		}
	}

	return 1;
}
    void
    LognormalCmsSpreadPricer::initialize(const FloatingRateCoupon &coupon) {

        coupon_ = dynamic_cast<const CmsSpreadCoupon *>(&coupon);
        QL_REQUIRE(coupon_, "CMS spread coupon needed");
        index_ = coupon_->swapSpreadIndex();
        gearing_ = coupon_->gearing();
        spread_ = coupon_->spread();

        fixingDate_ = coupon_->fixingDate();
        paymentDate_ = coupon_->date();

        // if no coupon discount curve is given just use the discounting curve
        // from the _first_ swap index.
        // for rate calculation this curve cancels out in the computation, so
        // e.g. the discounting
        // swap engine will produce correct results, even if the
        // couponDiscountCurve is not set here.
        // only the price member function in this class will be dependent on the
        // coupon discount curve.

        today_ = QuantLib::Settings::instance().evaluationDate();

        if (couponDiscountCurve_.empty())
            couponDiscountCurve_ =
                index_->swapIndex1()->exogenousDiscount()
                    ? index_->swapIndex1()->discountingTermStructure()
                    : index_->swapIndex1()->forwardingTermStructure();

        discount_ = paymentDate_ > couponDiscountCurve_->referenceDate()
                        ? couponDiscountCurve_->discount(paymentDate_)
                        : 1.0;

        spreadLegValue_ = spread_ * coupon_->accrualPeriod() * discount_;

        gearing1_ = index_->gearing1();
        gearing2_ = index_->gearing2();

        QL_REQUIRE(gearing1_ > 0.0 && gearing2_ < 0.0,
                   "gearing1 (" << gearing1_
                                << ") should be positive while gearing2 ("
                                << gearing2_ << ") should be negative");

        c1_ = ext::shared_ptr<CmsCoupon>(new CmsCoupon(
            coupon_->date(), coupon_->nominal(), coupon_->accrualStartDate(),
            coupon_->accrualEndDate(), coupon_->fixingDays(),
            index_->swapIndex1(), 1.0, 0.0, coupon_->referencePeriodStart(),
            coupon_->referencePeriodEnd(), coupon_->dayCounter(),
            coupon_->isInArrears()));

        c2_ = ext::shared_ptr<CmsCoupon>(new CmsCoupon(
            coupon_->date(), coupon_->nominal(), coupon_->accrualStartDate(),
            coupon_->accrualEndDate(), coupon_->fixingDays(),
            index_->swapIndex2(), 1.0, 0.0, coupon_->referencePeriodStart(),
            coupon_->referencePeriodEnd(), coupon_->dayCounter(),
            coupon_->isInArrears()));

        c1_->setPricer(cmsPricer_);
        c2_->setPricer(cmsPricer_);

        if (fixingDate_ > today_) {

            fixingTime_ = cmsPricer_->swaptionVolatility()->timeFromReference(
                fixingDate_);

            swapRate1_ = c1_->indexFixing();
            swapRate2_ = c2_->indexFixing();

            adjustedRate1_ = c1_->adjustedFixing();
            adjustedRate2_ = c2_->adjustedFixing();

            ext::shared_ptr<SwaptionVolatilityStructure> swvol =
                *cmsPricer_->swaptionVolatility();
            ext::shared_ptr<SwaptionVolatilityCube> swcub =
                ext::dynamic_pointer_cast<SwaptionVolatilityCube>(swvol);

            if(inheritedVolatilityType_ && volType_ == ShiftedLognormal) {
                shift1_ =
                    swvol->shift(fixingDate_, index_->swapIndex1()->tenor());
                shift2_ =
                    swvol->shift(fixingDate_, index_->swapIndex2()->tenor());
            }

            if (swcub == NULL) {
                // not a cube, just an atm surface given, so we can
                // not easily convert volatilities and just forbid it
                QL_REQUIRE(inheritedVolatilityType_,
                           "if only an atm surface is given, the volatility "
                           "type must be inherited");
                vol1_ = swvol->volatility(
                    fixingDate_, index_->swapIndex1()->tenor(), swapRate1_);
                vol2_ = swvol->volatility(
                    fixingDate_, index_->swapIndex2()->tenor(), swapRate2_);
            } else {
                vol1_ = swcub->smileSection(fixingDate_,
                                            index_->swapIndex1()->tenor())
                            ->volatility(swapRate1_, volType_, shift1_);
                vol2_ = swcub->smileSection(fixingDate_,
                                            index_->swapIndex2()->tenor())
                            ->volatility(swapRate2_, volType_, shift2_);
            }

            if(volType_ == ShiftedLognormal) {
                mu1_ = 1.0 / fixingTime_ * std::log((adjustedRate1_ + shift1_) /
                                                    (swapRate1_ + shift1_));
                mu2_ = 1.0 / fixingTime_ * std::log((adjustedRate2_ + shift2_) /
                                                    (swapRate2_ + shift2_));
            }
            // for the normal volatility case we do not need the drifts
            // but rather use adjusted rates directly in the integrand

            rho_ = std::max(std::min(correlation()->value(), 0.9999),
                            -0.9999); // avoid division by zero in integrand
        } else {
            // fixing is in the past or today
            adjustedRate1_ = c1_->indexFixing();
            adjustedRate2_ = c2_->indexFixing();
        }
    }
Пример #28
0
void KeyEDM3::compute() {

  const vector<Real>& pcp = _pcp.get();

  int pcpsize = (int)pcp.size();
  int n = pcpsize/12;

  if (pcpsize < 12 || pcpsize % 12 != 0)
    throw EssentiaException("KeyEDM3: input PCP size is not a positive multiple of 12");

  if (pcpsize != (int)_profile_dom.size()) {
    resize(pcpsize);
  }

  // Compute Correlation
  // Means
  Real mean_pcp = mean(pcp);
  Real std_pcp = 0;

  // Standard Deviations
  for (int i=0; i<pcpsize; i++)
    std_pcp += (pcp[i] - mean_pcp) * (pcp[i] - mean_pcp);
  std_pcp = sqrt(std_pcp);

  // Correlation Matrix
  int keyIndex = -1; // index of the first maximum
  Real max     = -1;     // first maximum
  Real max2    = -1;    // second maximum
  int scale    = MAJOR;  // scale

  // Compute maximum for major, minor and other.
  Real maxMajor     = -1;
  Real max2Major    = -1;
  int keyIndexMajor = -1;

  Real maxMinor     = -1;
  Real max2Minor    = -1;
  int keyIndexMinor = -1;

  Real maxOther     = -1;
  Real max2Other    = -1;
  int keyIndexOther = -1;


  // calculate the correlation between the profiles and the PCP...
  // we shift the profile around to find the best match
  for (int shift=0; shift<pcpsize; shift++) {
    Real corrMajor = correlation(pcp, mean_pcp, std_pcp, _profile_doM, _mean_profile_M, _std_profile_M, shift);
    // Compute maximum value for major keys
    if (corrMajor > maxMajor) {
      max2Major = maxMajor;
      maxMajor = corrMajor;
      keyIndexMajor = shift;
    }

    Real corrMinor = correlation(pcp, mean_pcp, std_pcp, _profile_dom, _mean_profile_m, _std_profile_m, shift);
    // Compute maximum value for minor keys
    if (corrMinor > maxMinor) {
      max2Minor = maxMinor;
      maxMinor = corrMinor;
      keyIndexMinor = shift;
    }

    Real corrOther = correlation(pcp, mean_pcp, std_pcp, _profile_doO, _mean_profile_O, _std_profile_O, shift);
    // Compute maximum value for other keys
    if (corrOther > maxOther) {
      max2Other = maxOther;
      maxOther = corrOther;
      keyIndexOther = shift;
    }
  }


  if (maxMajor > maxMinor && maxMajor > maxOther) {
    keyIndex = (int) (keyIndexMajor *  12 / pcpsize + 0.5);
    scale = MAJOR;
    max = maxMajor;
    max2 = max2Major;
  }

  else if (maxMinor >= maxMajor && maxMinor >= maxOther) {
    keyIndex = (int) (keyIndexMinor * 12 / pcpsize + 0.5);
    scale = MINOR;
    max = maxMinor;
    max2 = max2Minor;
    }

	else if (maxOther > maxMajor && maxOther > maxMinor) {
    keyIndex = (int) (keyIndexOther * 12 / pcpsize + 0.5);
    scale = OTHER;
    max = maxOther;
    max2 = max2Other;
    }
  
  if (keyIndex < 0) {
    throw EssentiaException("KeyEDM3: keyIndex smaller than zero. Could not find key.");
  }

  //////////////////////////////////////////////////////////////////////////////
  // Here we calculate the outputs...

  // first three outputs are key, scale and strength
  _key.get() = _keys[keyIndex];

  if (scale == MAJOR) {
    _scale.get() = "major";
  }

  else if (scale == MINOR) {
    _scale.get() = "minor";
  }

  else if (scale == OTHER) {
    _scale.get() = "minor";
  }

  _strength.get() = max;

  // this one outputs the relative difference between the maximum and the
  // second highest maximum (i.e. Compute second highest correlation peak)
  _firstToSecondRelativeStrength.get() = (max - max2) / max;
}