Esempio n. 1
0
EXPORT union ipsr_t CORE_ipsr_read(void) {
	union ipsr_t i;
	i.storage = SR(&ipsr.storage);
	return i;
}
Esempio n. 2
0
EXPORT union epsr_t CORE_epsr_read(void) {
	union epsr_t e;
	e.storage = SR(&epsr.storage);
	return e;
}
Esempio n. 3
0
double_vector L0Smoothing_1D(double_vector data, int jump)
{
	double lambda = 0.01, kappa = 2.0;
	double_vector out(data.size());
	Matrix SR(data.size(), 1);
	for(int j = 0; j < 1; ++j)
	{
		for(int i = 0; i < data.size(); ++i)
		{
			SR(i, j) = data[i];
		}
	}
	double betamax = 1;
	Matrix fx(1, 2);
	fx(0, 0) = 1;
	fx(0, 1) = -1;
	Matrix fy(2, 1);
	fy(0, 0) = 1;
	fy(1, 0) = -1;
	Matrix sizeI2D(1, 2);
	sizeI2D(0, 0) = data.size();
	sizeI2D(0, 1) = 1;
	Matrix2 otfFx = psf2otf(fx, sizeI2D);
	Matrix2 otfFy = psf2otf(fy, sizeI2D);
	Matrix otfFx2 = MatAbsPow2(otfFx);
	Matrix otfFy2 = MatAbsPow2(otfFy);
	Matrix2 Normin1R = fft2_1D(SR);
	Matrix Denormin2 = otfFx2;
	float beta = 2 * lambda;
	while(beta < betamax)
	{
		float lb = lambda / beta;
		Matrix Denormin = ZMatrix(data.size(), 1);
		Denormin = beta * Denormin2;
		MatAdd(Denormin, 1);
		Matrix vR = Matdiff(SR, 1);
		Matrix Pos2Sum = MatPow2(vR);
		for(int j = 0; j < 1; ++j)
		{
			for(int i = 0; i < data.size(); ++i)
			{
				if(Pos2Sum(i, j) < lb)
				{
					vR(i, j) = 0;
				}
			}
		}
		Matrix Normin2R = Matdiffinv(vR, 1);
		Matrix2 FSR = (Normin1R + fft2_1D(vR) * beta) / Denormin;
		SR = ifft2_1D(FSR);
		beta = beta * kappa;
		printf(".");
		for(uint i = 0; i < data.size(); ++i)
		{
			for(uint j = 0; j < 1; ++j)
			{
				out[i] = SR(i, j);
			}
		}
	}
	return out;
}
Esempio n. 4
0
EXPORT union apsr_t CORE_apsr_read(void) {
	union apsr_t a;
	a.storage = SR(&apsr.storage);
	return a;
}
Esempio n. 5
0
double
stgran(float p[], int n_args)
{
   int inchans, outchans, inchan;
   float indur, outdur, insk, outsk;
   long bgrainsamps, bgraindist, bgrainslide, inbgraindist;
   long i, nsamps, gstt_var, in_gstt_var, count, outcount, branch, skip;
   long s;                      /* sample number */
   long egrainsamps, egraindist, egrainslide, inegraindist;
   long grainsamps, grainslide, graindistdiff;
   long ingrainsamps, ingrainslide, ingraindistdiff;
   long  maxinsamps, maxoutsamps;
   float val, amp, aamp;
   float gdist_inc, in_gdist_inc;
   float tab1[2], tab2[2], tab3[2], tab4[2], tab5[2], tab6[2], tab7[2], tab8[2];
   double *in_rate_shape, *rate_shape, *dur_shape, *transp_shape, *amp_shape;
   double *loc_shape, *envel, *slarray;
   float *inarr, *outarr;
   double gstt_per, in_gstt_per, lo, mid, hi, ti, sig, table_val;
   double slodiff, smiddiff, shidiff, stidiff;
   double ilodiff, imiddiff, ihidiff, itidiff;
   double dlodiff, dmiddiff, dhidiff, dtidiff;
   double alodiff, amiddiff, ahidiff, atidiff, grainamp;
   double tlodiff, tmiddiff, thidiff, ttidiff;
   double llodiff, lmiddiff, lhidiff, ltidiff, pctleft = 0.0;
   double tlobeg, tmidbeg, thibeg, tloend, tmidend, thiend;
   double voldsig = 0.0, oldsig, newsig, interval, increment;
   double counter = 0., frac;
   register int incount = 1, getflag = 1;

   outsk = p[0];
   insk = p[1];
   outdur = p[2];
   indur = p[3];
   amp = p[4];

   setnote(insk, indur, INPUT);
   nsamps = setnote(outsk, outdur, OUTPUT);

   tlobeg = (double) octpch(p[33]);
   tmidbeg = (double) octpch(p[34]);
   thibeg = (double) octpch(p[35]);
   tloend = (double) octpch(p[37]);
   tmidend = (double) octpch(p[38]);
   thiend = (double) octpch(p[39]);

   inchan = (int) p[58];
   inchans = sfchans(&sfdesc[INPUT]);
   if (inchan >= inchans)
      die("stgran", "You asked for channel %d of a %d-channel file.",
                                                          inchan, inchans);
   outchans = sfchans(&sfdesc[OUTPUT]);
   if (outchans > 2)
      die("stgran", "Output file must be either mono or stereo.");

   /* allocate input and output buffers */
   interval = MAX(thibeg, thiend);      /* maximum transp. value (lin oct) */
   increment = cpsoct(10.0 + interval) / cpsoct(10.0);
   hi = MAX(p[31], p[27]) * SR();         /* maximum grain duration */
   maxinsamps = (long) (hi * increment + 1.0);
   inarr = malloc(maxinsamps * inchans * sizeof(float));
   if (inarr == NULL)
      die("stgran", "Can't allocate input buffer.");
   maxoutsamps = (long) (hi + 1.0);
   outarr = malloc(maxoutsamps * outchans * sizeof(float));
   if (outarr == NULL)
      die("stgran", "Can't allocate output buffer.");

   bgrainsamps = grainsamps = p[26] * SR();
   bgraindist = p[7] * SR();
   bgrainslide = grainslide = bgraindist - bgrainsamps;
   egrainsamps = p[30] * SR();
   egraindist = p[8] * SR();
   egrainslide = egraindist - egrainsamps;
   graindistdiff = egraindist - bgraindist;

   inbgraindist = p[5] * SR();
   inegraindist = p[6] * SR();
   ingraindistdiff = inegraindist - inbgraindist;

   in_rate_shape = floc(2);
	if (in_rate_shape == NULL)
		die("stgran",
				"You haven't made the grain input rate function (table 2).");
   tableset(SR(), indur - p[6], fsize(2), tab2);

   rate_shape = floc(3);
	if (rate_shape == NULL)
		die("stgran",
				"You haven't made the grain output rate function (table 3).");
   tableset(SR(), outdur - p[8], fsize(3), tab3);

   dur_shape = floc(4);
	if (dur_shape == NULL)
		die("stgran", "You haven't made the grain duration function (table 4).");
   tableset(SR(), outdur - p[8], fsize(4), tab4);

   transp_shape = floc(5);
	if (transp_shape == NULL)
		die("stgran",
				"You haven't made the grain transposition function (table 5).");
   tableset(SR(), outdur - p[8], fsize(5), tab5);

   amp_shape = floc(6);
	if (amp_shape == NULL)
		die("stgran", "You haven't made the grain amplitude function (table 6).");
   tableset(SR(), outdur - p[8], fsize(6), tab6);

   loc_shape = floc(7);
	if (loc_shape == NULL)
		die("stgran",
				"You haven't made the grain stereo location function (table 7).");
   tableset(SR(), outdur - p[8], fsize(7), tab7);

   envel = floc(8);           /* tableset in sample loop */
	if (envel == NULL)
		die("stgran", "You haven't made the grain envelope (table 8).");

   /* get infile stt var zero/one differences */
   ilodiff = (double) (p[13] - p[9]) / nsamps;
   imiddiff = (double) (p[14] - p[10]) / nsamps;
   ihidiff = (double) (p[15] - p[11]) / nsamps;
   itidiff = (double) (p[16] - p[12]) / nsamps;

   /* get outfile stt var zero/one differences */
   slodiff = (double) (p[21] - p[17]) / nsamps;
   smiddiff = (double) (p[22] - p[18]) / nsamps;
   shidiff = (double) (p[23] - p[19]) / nsamps;
   stidiff = (double) (p[24] - p[20]) / nsamps;

   /* get dur zero/one differences */
   dlodiff = (double) (p[29] - p[25]);
   dmiddiff = (double) (p[30] - p[26]);
   dhidiff = (double) (p[31] - p[27]);
   dtidiff = (double) (p[32] - p[28]);

   /* transp zero/one differences */
   tlodiff = tloend - tlobeg;
   tmiddiff = tmidend - tmidbeg;
   thidiff = thiend - thibeg;
   ttidiff = (double) (p[40] - p[36]);

   /* amp zero/one differences */
   alodiff = (double) (p[45] - p[41]);
   amiddiff = (double) (p[46] - p[42]);
   ahidiff = (double) (p[47] - p[43]);
   atidiff = (double) (p[48] - p[44]);

   /* loc zero/one differences */
   llodiff = (double) (p[53] - p[49]);
   lmiddiff = (double) (p[54] - p[50]);
   lhidiff = (double) (p[55] - p[51]);
   ltidiff = (double) (p[56] - p[52]);

   if (p[57] > 0)
      srrand(p[57]);
   else
      srrand(.3);    /* JGG: srrand takes unsigned int! */

   skip = SR() / (float) resetval;               /* control rate for amp curve */

   gstt_var = in_gstt_var = 0;
   count = 0;

   aamp = amp;                       /* in case there is no setline function */
   slarray = floc(1);
   if (slarray) {
      int len = fsize(1);
      tableset(SR(), outdur, len, tab1);
   }
   else
      rtcmix_advise("stgran", "Setting phrase curve to all 1's.");

   for (i = 0; i < nsamps; i++) {
      count++;
      table_val = (double) tablei(i, transp_shape, tab5);
      lo = tlobeg + (tlodiff * table_val);
      mid = tmidbeg + (tmiddiff * table_val);
      hi = thibeg + (thidiff * table_val);
      ti = p[36] + (ttidiff * table_val);
      lo = (lo > mid) ? mid : lo;
      hi = (hi < mid) ? mid : hi;
      interval = prob(lo, mid, hi, ti);                      /* in lin oct */
      increment = cpsoct(10.0 + interval) / cpsoct(10.0);    /* samp incr. */

      /* calculate next grain duration */
      table_val = (double) tablei(i, dur_shape, tab4);
      lo = p[25] + (dlodiff * table_val);
      mid = p[26] + (dmiddiff * table_val);
      hi = p[27] + (dhidiff * table_val);
      ti = p[28] + (dtidiff * table_val);
      lo = (lo > mid) ? mid : lo;
      hi = (hi < mid) ? mid : hi;
      grainsamps = (long) (prob(lo, mid, hi, ti) * SR());
      tableset(SR(), grainsamps / SR(), fsize(8), tab8);

      /* calculate grain amplitude */
      table_val = (double) tablei(i, amp_shape, tab6);
      lo = p[41] + (alodiff * table_val);
      mid = p[42] + (amiddiff * table_val);
      hi = p[43] + (ahidiff * table_val);
      ti = p[44] + (atidiff * table_val);
      lo = (lo > mid) ? mid : lo;
      hi = (hi < mid) ? mid : hi;
      grainamp = prob(lo, mid, hi, ti);

      /* calculate grain stereo location */
      if (outchans > 1) {
         table_val = (double) tablei(i, amp_shape, tab7);
         lo = p[49] + (llodiff * table_val);
         mid = p[50] + (lmiddiff * table_val);
         hi = p[51] + (lhidiff * table_val);
         ti = p[52] + (ltidiff * table_val);
         lo = (lo > mid) ? mid : lo;
         hi = (hi < mid) ? mid : hi;
         pctleft = prob(lo, mid, hi, ti);
      }

      /* get percentage to vary next stt of grain */
      lo = p[17] + slodiff * i;
      mid = p[18] + smiddiff * i;
      hi = p[19] + shidiff * i;
      ti = p[20] + stidiff * i;
      lo = (lo > mid) ? mid : lo;
      hi = (hi < mid) ? mid : hi;
      gstt_per = prob(lo, mid, hi, ti);
      gstt_var = (long) (gstt_per * (grainsamps + grainslide));

      /* calculate grainslide */
      gdist_inc = tablei(i, rate_shape, tab3);
      grainslide = (float) bgraindist
                     + (float) graindistdiff * gdist_inc - grainsamps;

      ingrainsamps = grainsamps * increment;

#ifdef DEBUG
      printf("ingrainsamps: %ld, maxinsamps: %ld\n", ingrainsamps, maxinsamps);
      assert(ingrainsamps <= maxinsamps);
      assert(grainsamps <= maxoutsamps);
#endif

      bgetin(inarr, INPUT, ingrainsamps * inchans);  /* read in grain */

      ingrainslide = ((float) inbgraindist) * increment
                      + (float) ingraindistdiff * increment - ingrainsamps;

      /* transpose the grain and write it to output file */
      oldsig = inarr[inchan];
      newsig = inarr[inchans + inchan];
      incount = 1;
      outcount = 0;
      counter = 0;
      branch = 0;
      for (s = 0; s < grainsamps; s++) {
         while (getflag) {
            voldsig = oldsig;
            oldsig = newsig;
            newsig = inarr[(incount * inchans) + inchan];
            incount++;
            if ((counter - (float) incount) < 0.5) {
               getflag = 0;
            }
         }
         /* update overall amp envelope at control rate */
         while (!branch--) {
            if (slarray)
               aamp = tablei(i, slarray, tab1) * amp;
            branch = skip;
         }
         /* update grain envelope on every sample */
         val = tablei(s, envel, tab8) * grainamp * aamp;

         frac = counter - incount + 2.0;               /* the interp value */

         sig = interp(voldsig, oldsig, newsig, frac) * val;

         if (outchans == 2) {
            outarr[outcount] = sqrt(pctleft) * sig;
            outarr[outcount + 1] = sqrt(1.0 - pctleft) * sig;
         }
         else
            outarr[outcount] = sig;

         counter += increment;            /* keeps track of interp pointer */
         if ((counter - (float) incount) >= -0.5) {
            getflag = 1;
         }
         outcount += outchans;
      }
      baddout(outarr, OUTPUT, grainsamps * outchans);
      inrepos(ingrainslide, INPUT);

      if ((i + grainslide + gstt_var + grainsamps) < 0) {
         outrepos(grainslide, OUTPUT);
         i += grainsamps;
         i += grainslide;
      }
      else {
         outrepos((grainslide + gstt_var), OUTPUT);
         i += grainsamps;
         i += grainslide;
         i += gstt_var;
      }
   }
   printf("\n%ld grains\n", count);
   endnote(OUTPUT);

   free(inarr);
   free(outarr);

   return 0.0;
}
Esempio n. 6
0
cv::Mat L0Smoothing(cv::Mat Im, double lambda = 0.02, double kappa = 2.0)
{
	cv::Mat out(Im.rows, Im.cols, CV_32FC3);
	Matrix SR(Im.rows, Im.cols);
	Matrix SG(Im.rows, Im.cols);
	Matrix SB(Im.rows, Im.cols);
	for(int j = 0; j < Im.cols; ++j)
	{
		for(int i = 0; i < Im.rows; ++i)
		{
			cv::Vec3f& v1 = Im.at<cv::Vec3f>(i, j);
			SR(i, j) = v1[0];
			SG(i, j) = v1[1];
			SB(i, j) = v1[2];
		}
	}
	double betamax = 1e5;
	Matrix fx(1, 2);
	fx(0, 0) = 1;
	fx(0, 1) = -1;
	Matrix fy(2, 1);
	fy(0, 0) = 1;
	fy(1, 0) = -1;
	Matrix sizeI2D(1, 2);
	sizeI2D(0, 0) = Im.rows;
	sizeI2D(0, 1) = Im.cols;
	Matrix2 otfFx = psf2otf(fx, sizeI2D);
	Matrix2 otfFy = psf2otf(fy, sizeI2D);
	Matrix otfFx2 = MatAbsPow2(otfFx);
	Matrix otfFy2 = MatAbsPow2(otfFy);
	Matrix2 Normin1R = fft2(SR);
	Matrix2 Normin1G = fft2(SG);
	Matrix2 Normin1B = fft2(SB);
	Matrix Denormin2 = otfFx2 + otfFy2;
	float beta = 2 * lambda;
	int count = 1;
	while(beta < betamax)
	{
		float lb = lambda / beta;
		Matrix Denormin = beta * Denormin2;
		MatAdd(Denormin, 1);
		Matrix hR = Matdiff(SR, 2);
		Matrix vR = Matdiff(SR, 1);
		Matrix hG = Matdiff(SG, 2);
		Matrix vG = Matdiff(SG, 1);
		Matrix hB = Matdiff(SB, 2);
		Matrix vB = Matdiff(SB, 1);
		Matrix Pos2Sum = MatPow2(hR) + MatPow2(vR) +
						 MatPow2(hG) + MatPow2(vG) +
						 MatPow2(hB) + MatPow2(vB);
		for(int j = 0; j < Im.cols; ++j)
		{
			for(int i = 0; i < Im.rows; ++i)
			{
				if(Pos2Sum(i, j) < lb)
				{
					hR(i, j) = 0;
					vR(i, j) = 0;
					hG(i, j) = 0;
					vG(i, j) = 0;
					hB(i, j) = 0;
					vB(i, j) = 0;
				}
			}
		}
		Matrix Normin2R = Matdiffinv(hR, 2) + Matdiffinv(vR, 1);
		Matrix Normin2G = Matdiffinv(hG, 2) + Matdiffinv(vG, 1);
		Matrix Normin2B = Matdiffinv(hB, 2) + Matdiffinv(vB, 1);
		Matrix2 FSR = (Normin1R + fft2(Normin2R) * beta) / Denormin;
		Matrix2 FSG = (Normin1G + fft2(Normin2G) * beta) / Denormin;
		Matrix2 FSB = (Normin1B + fft2(Normin2B) * beta) / Denormin;
		SR = ifft2(FSR);
		SG = ifft2(FSG);
		SB = ifft2(FSB);
		beta = beta * kappa;
		printf(".");
		for(uint i = 0; i < out.rows; ++i)
		{
			for(uint j = 0; j < out.cols; ++j)
			{
				cv::Vec3f& v1 = out.at<cv::Vec3f>(i, j);
				v1[0] = SR(i, j);
				v1[1] = SG(i, j);
				v1[2] = SB(i, j);
			}
		}
		cv::imshow("out", out);
		char filename[100];
		sprintf(filename, "o%02d.png", count++);
		cv::Mat theout;
		out.convertTo(theout, CV_8UC3, 255);
		cv::imwrite(filename, theout);
		cv::waitKey(1);
	}
	for(uint j = 0; j < out.cols; ++j)
	{
		for(uint i = 0; i < out.rows; ++i)
		{
			cv::Vec3f& v1 = out.at<cv::Vec3f>(i, j);
			v1[0] = SR(i, j);
			v1[1] = SG(i, j);
			v1[2] = SB(i, j);
		}
	}
	return out;
}
Esempio n. 7
0
	clang::StmtResult InsiemeSema::ActOnCompoundStmt(clang::SourceLocation L, clang::SourceLocation R, llvm::ArrayRef<clang::Stmt*> Elts, bool isStmtExpr) {
		// we parse the original code segment, within the original locations
		StmtResult&& ret = Sema::ActOnCompoundStmt(L, R, std::move(Elts), isStmtExpr);
		clang::CompoundStmt* CS = cast<clang::CompoundStmt>(ret.get());
		
		// This is still buggy as of Clang 3.6.2:
		// when pragmas are just after the beginning of a compound stmt, example:
		// {
		// 		#pragma xxx
		// 		...
		// }
		// the location of the opening bracket is wrong because of a bug in the clang parser.
		//
		// We solve the problem by searching for the bracket in the input stream and overwrite
		// the value of L (which contains the wrong location) with the correct value.

		enum { MacroIDBit = 1U << 31 }; // from clang/Basic/SourceLocation.h for use with cpp classes
		{
			SourceLocation&& leftBracketLoc = SourceMgr.getImmediateSpellingLoc(L);
			std::pair<FileID, unsigned>&& locInfo = SourceMgr.getDecomposedLoc(leftBracketLoc);
			llvm::StringRef&& buffer = SourceMgr.getBufferData(locInfo.first);
			const char* strData = buffer.begin() + locInfo.second;
			char const* lBracePos = strbchr(strData, buffer.begin(), '{');

			// We know the location of the left bracket, we overwrite the value of L with the correct location
			// but only if the location is valid as in getFileLocWithOffset() in SourceLocation
			if((((leftBracketLoc.getRawEncoding() & ~MacroIDBit) + (lBracePos - strData)) & MacroIDBit) == 0) {
				L = leftBracketLoc.getLocWithOffset(lBracePos - strData);
			}
		}

		// For the right bracket, we start at the final statement in the compound 
		//   (or its start if it is empty) and search forward until we find the first "}"
		// Otherwise, cases such as this:
		//
		// {
		//    bla();
		// }
		// #pragma test expect_ir(R"( {} )")
		//
		// will be broken

		{
			SourceLocation rightBracketLoc;
			if(CS->size() == 0) {
				rightBracketLoc = SourceMgr.getImmediateSpellingLoc(L);
			} else {
				rightBracketLoc = SourceMgr.getImmediateSpellingLoc(CS->body_back()->getLocEnd());
			}
			std::pair<FileID, unsigned>&& locInfo = SourceMgr.getDecomposedLoc(rightBracketLoc);
			llvm::StringRef buffer = SourceMgr.getBufferData(locInfo.first);
			const char* strData = buffer.begin() + locInfo.second;
			char const* rBracePos = strchr(strData, '}');

			// We know the location of the right bracket, we overwrite the value of R with the correct location
			if((((rightBracketLoc.getRawEncoding() & ~MacroIDBit) + (rBracePos - strData)) & MacroIDBit) == 0) {
				R = rightBracketLoc.getLocWithOffset(rBracePos - strData);
			}
		}
		
		// the source range we inspect is defined by the new source locations,
		// this fix the problem with boundaries jumping to the beginning of the file in
		// the macro expansions:
		//
		//	#define F(x) { }
		//
		//		...
		//
		//		F(r)    // <-this statement will jum to the macro location
		//
		PragmaList matched;
		SourceRange SR(L, R);

		// for each of the pragmas in the range between brackets
		for(PragmaFilter&& filter = PragmaFilter(SR, SourceMgr, pimpl->pending_pragma); *filter; ++filter) {
			PragmaPtr P = *filter;

			unsigned int pragmaStart = utils::Line(P->getStartLocation(), SourceMgr);
			unsigned int pragmaEnd = utils::Line(P->getEndLocation(), SourceMgr);

			bool found = false;
			// problem with first pragma, compound start is delayed until fist usable line (first stmt)
			if(CS->size() > 0) {
				for(clang::CompoundStmt::body_iterator it = CS->body_begin(); it != CS->body_end(); ++it) {
					unsigned int stmtStart = (Line((*it)->getLocStart(), SourceMgr));

					if((pragmaEnd <= stmtStart)) {
						// ACHTUNG: if the node is a nullStmt, and is not at the end of the compound (in
						// which case is most probably ours) we can not trust it. semantics wont change,
						// we move one more. (BUG: nullStmt followed by pragmas, the source begin is
						// postponed until next stmt) this makes pragmas to be attached to a previous
						// stmt
						if(!llvm::isa<clang::NullStmt>(*it)) {
							// this pragma is attached to the current stmt
							P->setStatement(*it);
							matched.push_back(P);
							found = true;
							break;
						}
					}
				}
			}
			if(!found && pragmaStart <= utils::Line(R, SourceMgr)) {
				// this is a de-attached pragma (barrier i.e.) at the end of the compound
				// we need to create a fake NullStmt ( ; ) to attach this
				Stmt** stmts = new Stmt*[CS->size() + 1];

				ArrayRef<clang::Stmt*> stmtList(stmts, CS->size() + 1);

				clang::CompoundStmt* newCS =
				    new(Context) clang::CompoundStmt(Context, stmtList, CS->getSourceRange().getBegin(), CS->getSourceRange().getEnd());

				std::copy(CS->body_begin(), CS->body_end(), newCS->body_begin());
				std::for_each(CS->body_begin(), CS->body_end(), [&](Stmt*& curr) { this->Context.Deallocate(curr); });
				newCS->setLastStmt(new(Context) NullStmt(SourceLocation()));

				P->setStatement(*newCS->body_rbegin());
				matched.push_back(P);

				// transfer the ownership of the statement
				clang::CompoundStmt* oldStmt = ret.getAs<clang::CompoundStmt>();
				oldStmt->setStmts(Context, NULL, 0);
				ret = newCS;
				CS = newCS;

				// destroy the old compound stmt
				Context.Deallocate(oldStmt);
				delete[] stmts;
			}
		}
		// remove matched pragmas
		EraseMatchedPragmas(pimpl->pending_pragma, matched);

		return std::move(ret);
	}
Esempio n. 8
0
double
m_clean(float p[], int n_args) /* a fast clean of file, after header */
{
/* if p1-> = 0, clean whole file, else skip=p1, dur=p2, ch-on? p3--> */
	int i;
	off_t n, nwrite, todo;
	char *point;
	int fno,segment,chlist[4];
	int skipbytes;

	fno = (int) p[0];
	skipbytes = 0;
	if(!status[fno]) {
		rtcmix_warn(NULL,"fno %d is write-protected!\n",fno);
		closesf();
	}
	todo = originalsize[fno] - headersize[fno];

	segment = (n_args > 1) ? 1 : 0;

	if(segment) {
		skipbytes = (p[1] > 0) ? p[1] * sfclass(&sfdesc[fno]) *
			    SR() * sfchans(&sfdesc[fno]) 
			    : -p[1] * sfclass(&sfdesc[fno]) * 
							 sfchans(&sfdesc[fno]);
		todo =  (p[2] > 0) ? p[2] * sfclass(&sfdesc[fno]) * 
			SR() * sfchans(&sfdesc[fno])
			: -p[2] * sfclass(&sfdesc[fno]) * 
						sfchans(&sfdesc[fno]);
		for(i=0; i<sfchans(&sfdesc[fno]); i++) chlist[i] = p[i+3];
	}
	point = (char *)sndbuf[fno];
	if(!segment) for(i=0; i<nbytes; i++) *(point+i) = 0;

	if((filepointer[fno] = 
	   lseek(sfd[fno],skipbytes+headersize[fno],0)) == -1) {
		rtcmix_warn("CMIX", "bad sflseek in clean\n");
		closesf();
	}
#ifdef MINGW
	// no %11 in Win libc, have to use %I64 instead:
	// http://stackoverflow.com/questions/13590735/printf-long-long-int-in-c-with-gcc?
	printf("Clean %I64d bytes\n",(long long)todo);
#else
	printf("Clean %lld bytes\n",(long long)todo);
#endif
	while(todo) {
		nwrite = (todo > nbytes) ? nbytes : todo;
		if(segment) {
			if((n = read(sfd[fno],sndbuf[fno],nwrite)) 
					== 0) { /* allow for fractional reads*/
				fprintf(stderr, "CMIX: Apparent eof in clean\n");
				return -1.0;
			}
			if(lseek(sfd[fno],-n,1) < 0) {
				fprintf(stderr,"Bad UNIX lseek in clean\n");
				closesf();
			}
			m_zapout(fno,sndbuf[fno],n,chlist);
			nwrite = n;
		}
		if((n = write(sfd[fno],sndbuf[fno],nwrite)) == 0) {
			fprintf(stderr, "CMIX: Apparent eof in clean\n");
	        	closesf();
		}
		todo -= n;
	}
	if(!segment) {
		if((lseek(sfd[fno],0,0)) == -1) {
			fprintf(stderr,"CMIX: bad lseek in clean\n");
			closesf();
		}

		for(i = 0; i<sfchans(&sfdesc[fno]); i++) { 
			sfmaxamp(&sfm[fno],i) = 0;
			sfmaxamploc(&sfm[fno],i) = 0;
		}

		putsfcode(&sfdesc[fno],(char *)&sfm[fno],&ampcode);

		if(wheader(sfd[fno],(char *)&sfdesc[fno])) {
			fprintf(stderr,"Bad header write\n");
			perror("write");
			closesf();
		}
	}
	else 
		if((lseek(sfd[fno],headersize[fno],0)) == -1) {
			fprintf(stderr,"CMIX: bad lseek in clean\n");
			closesf();
		}
	filepointer[fno] = headersize[fno];
	printf("Clean successfully finished.\n");

   return 0.0;
}
int a1_getScalingFactors(int pdgId, double metCut, double jetptCut, bool doEcaloCut, double ptCut, double ecaloCut, TString region){

  TFile *out = new TFile(Form("templates/leptonScalingFactors_pdgId_%i_metCut_%.f_jetptCut_%.0f_ptCut_%.0f",pdgId,metCut,jetptCut,ptCut) + region + ".root","RECREATE");

  sample pred("wjets");
  sample SR("wjets");


  TString selection = "chiTrackspreselectionTriggerNoQCDCuts";
  SR.getTree(fileSR, selection);
  if(pdgId==211)        pred.getTree(filePionCS, selection);
  else if(pdgId==11)    pred.getTree(fileElectronCS, selection);
  else if(pdgId==13)    pred.getTree(fileMuonCS, selection);

  /*
 
  pred.file -> GetObject(selectionType,pred.tree);
  SR.file   -> GetObject(selectionType,SR.tree);
  */

  SR.getTreeVariables();
  pred.getTreeVariables();

  int nbins=5;
  double xmin=0;
  double xmax=10;
  SR.histo   = new TH1D("SR","SR",nbins,xmin,xmax);
  pred.histo = new TH1D("pred","pred",nbins,xmin,xmax);

  SR.histo->Sumw2();
  pred.histo->Sumw2();


  double scalingFactor;
  double scalingFactorErrorUp;
  double scalingFactorErrorLow;
  
  if(pdgId==211 || pdgId==13){
    SR.Selection(   1, pdgId, metCut, jetptCut, 20., 0, 1,          ecaloCut, 1, region);
    pred.Selection( 0, pdgId, metCut, jetptCut, 20., 0, doEcaloCut, ecaloCut, 1, region);
  }
  else{
    SR.Selection(   1, pdgId, metCut, jetptCut, ptCut, 0, 1,          ecaloCut, 1, region);
    pred.Selection( 0, pdgId, metCut, jetptCut, ptCut, 0, doEcaloCut, ecaloCut, 1, region);
  }

  //  SR.Selection(   1, pdgId, metCut, jetptCut, ptCut, 0, 1,          ecaloCut, 1, region);
  //pred.Selection( 1, pdgId, metCut, jetptCut, ptCut, 0, doEcaloCut, ecaloCut, 1, region);


  //SR.Selection(   1, pdgId, 0, 70, ptCut, 0, 1,          ecaloCut, 1, region);
  //pred.Selection( 1, pdgId, 0, 70, ptCut, 0, doEcaloCut, ecaloCut, 1, region);
  
  double predIntError   =  0;
  double predInt        =  pred.histo->IntegralAndError(1,pred.histo->GetNbinsX(),predIntError);
  double SRInt          =  SR.histo->Integral(1,SR.histo->GetNbinsX()+1);
  double SRIntErrorUp   =  getOneSidedUpperLimit(SRInt,0.6827) -SRInt;
  double SRIntErrorLow  =  SRInt - getOneSidedLowerLimit(SRInt,0.6827);
      

  if(SRInt==0){
    /*
    SRInt        = getOneSidedUpperLimit(SRInt,0.6827) -SRInt;
    SRIntErrorUp   = 0.;
    SRIntErrorLow  = 0.;
    predIntError   = 0.;
    */

    SRIntErrorUp   = getOneSidedUpperLimit(SRInt,0.6827) -SRInt;
    SRIntErrorLow  = getOneSidedLowerLimit(SRInt,0.6827) -SRInt;

  }
  scalingFactor         = SRInt/predInt;
  scalingFactorErrorUp  = SRIntErrorUp/predInt;
  scalingFactorErrorLow = SRIntErrorLow/predInt;
  if(predInt==0){
    scalingFactor         = -1;
    scalingFactorErrorUp  = 0;
    scalingFactorErrorLow = 0;
  }

  cout<<"###########################################################################"<<endl;
  cout.precision(2);
  cout<<"Statisitcs for "<<pdgId<<" : "<<"pt="<<ptCut<<" ECalo="<<ecaloCut<<endl;
  cout<<"Signal region          = "<<SR.statistics<<endl;
  cout<<"Control region         = "<<pred.statistics<<endl;
  cout<<"Purity in CR           = "<<fixed<<pred.purity*100<<"%"<<endl;
  cout<<"scaling factor         = "<<scientific<<scalingFactor<<" + "<<scalingFactorErrorUp<<" - "<<scalingFactorErrorLow<<endl;
  cout<<"###########################################################################"<<endl;

  TString name = Form("%.0f_%.0f",ptCut,ecaloCut);

  double x[1]    = {0.5};
  double xLow[1] = {0};
  double xUp[1]  = {0};

  double y[1]    = {scalingFactor};
  double yLow[1] = {scalingFactorErrorLow};
  double yUp[1]  = {scalingFactorErrorUp};

  TGraphAsymmErrors* GScalingFactors = new TGraphAsymmErrors(1,x,y,xLow,xUp,yLow,yUp);
  GScalingFactors -> SetMarkerStyle(20);

  out->cd();
  GScalingFactors->Write(name);
  out->Close();

  gDirectory->Delete(); 
 
  return 0;
 
}
Esempio n. 10
0
int
endnote(int xno)
{
	struct timeval tp;	
	struct timezone tzp;	
	int i,j,final_bytes,fno;
	float notepeak,*pk;
	double total;
	long *pkloc;
	struct tms timbuf;
	float peakval;
	struct stat st;
	short tisamp,*tibuf;
	float tfsamp,*tfbuf;

	fno = ABS(xno);  /* if fno is negative it means don't write
					final buffer,just pretend to */
	if(wipe_is_off[fno]) 
		_backup(fno); 
	/* else _flushbuf(fno); */
	if(!peakoff[fno]) _chkpeak(fno);
	final_bytes =  pointer[fno]  * sfclass(&sfdesc[fno]);
	
	/* This was DS's and PL's version of real time */
	/* Not used in this version */
#ifdef OLDRT

	/*  SHOULD NOT PLAY HERE -- LAST BUFFERS ALREADY PLAYED */
	if ((sfclass(&sfdesc[fno]) == SF_SHORT) && play_is_on)
		playbuf(sndbuf[fno],final_bytes/SF_SHORT);
	else if ((sfclass(&sfdesc[fno]) == SF_FLOAT) && play_is_on) {
		peakval = getpeakval(peakflag,fno);
		playfbuf(sndbuf[fno],peakval,swap[fno],nbytes/SF_FLOAT);
	}
#endif

	/* write out only fractional part of last record, god bless unix!*/
	if(pointer[fno] && (play_is_on < 2)) {
		if(xno >= 0) {
			/* Swap bytes if necessary */
			if(final_bytes && swap_bytes[fno]) {
				/* SHORT file */
				if(sfclass(&sfdesc[fno]) == SF_SHORT) {
					tibuf = (short *)sndbuf[fno]; 
					for (i=0;i<final_bytes/SF_SHORT;i++) {
						tisamp = *(tibuf+i);
						*(tibuf+i) = reverse_int2(&tisamp);
					}
				}
				/* FLOAT file */
				if(sfclass(&sfdesc[fno]) == SF_FLOAT) {
					tfbuf = (float *)sndbuf[fno]; 
					for (i=0;i<final_bytes/SF_FLOAT;i++) {
						/* 	byte_reverse4(tfbuf+i); */
						/* 	tfsamp = *(tfbuf+i); */
						/* 	*(tfbuf+i) = (float)reverse_int4(&tfsamp); */
					  	tfsamp = *(tfbuf+i);
						byte_reverse4(&tfsamp);
					  	*(tfbuf+i) = tfsamp;
					}
				}
   			}
   			if((i = write(sfd[fno],sndbuf[fno],final_bytes)) 
											!= final_bytes) {
				fprintf(stderr,
					"CMIX: Bad UNIX write, file %d, nbytes = %d\n",
					fno,i);
				perror("write");
				closesf();
   			}
   		}
   		if((filepointer[fno] += final_bytes) > originalsize[fno]) 
   		if(xno >0)  originalsize[fno] = filepointer[fno];
	}
	/* DT: 	if(play_is_on) flush_buffers(); */
	
	pk = (float *)peak[fno];
	pkloc = (long *)peakloc[fno];
	total = ((double)filepointer[fno]-headersize[fno])
					/((double)sfclass(&sfdesc[fno]))
					/(double)sfchans(&sfdesc[fno])/SR();
	
	/* _writeit(fno);  write out final record */

	for(i = 0,notepeak=0; i<sfchans(&sfdesc[fno]); i++) { 
		if(*(pk+i) > sfmaxamp(&sfm[fno],i)) {
			sfmaxamp(&sfm[fno],i) = *(pk+i);
			sfmaxamploc(&sfm[fno],i) = *(pkloc+i);
		}
		if(*(pk+i) > notepeak) notepeak = *(pk+i);
	}
	
	gettimeofday(&tp,&tzp);
	sfmaxamptime(&sfm[fno]) = tp.tv_sec;
		
	if((filepointer[fno] = lseek(sfd[fno],0L,0)) < 0) {
		fprintf(stderr,"Bad lseek to beginning of file\n");
		perror("lseek");
		closesf();
	}


	times(&timbuf);

	printf("\n(%6.2f)",(float)(
					(timbuf.tms_stime-clockin[fno].tms_stime)+
					(timbuf.tms_utime-clockin[fno].tms_utime))/60.);
	printf(" %9.4f .. %9.4f MM ",starttime[fno],total);
	
	if(!peakoff[fno]) {
		for(j=0;j<sfchans(&sfdesc[fno]);j++)
			printf(" c%d=%e",j,*(pk+j));
		printf("\n");
		if(punch[fno]) {
			printf("alter(%e,%e,%e/%e",
						(double)starttime[fno],(double)(total-starttime[fno]),
						punch[fno],notepeak);
			for(i=0; i<sfchans(&sfdesc[fno]); i++)
				printf(",1 ");
			printf(")\n");
			printf("mix(%g,%g,%g,%g/%g",
							(double)starttime[fno],(double)starttime[fno],-(double)(total-starttime[fno]),punch[fno],notepeak);
			for(i=0; i<sfchans(&sfdesc[fno]); i++)
				printf(",%d ",i);
			printf(")\n");
		}
	}

	/* Copy the updated peak stats into the SFHEADER struct for this
	   output file. (No swapping necessary.)
	*/
	memcpy(&(sfmaxampstruct(&sfdesc[fno])), &sfm[fno], sizeof(SFMAXAMP));

	/* Write header to file. */
	if (wheader(sfd[fno], &sfdesc[fno])) {
		fprintf(stderr, "endnote: bad header write\n");
		perror("write");
		closesf();
	}
	return 0;
}
Esempio n. 11
0
static bool cpu_conf_regs_rd(uint32_t addr, uint32_t *val,
		bool debugger __attribute__ ((unused)) ) {
	assert((addr & 0xfffff000) == 0xA0001000);
	switch (addr) {
		case CHIP_ID_REG_RD:
			*val = SR(&m3_prc_reg_chip_id) & MASK(CHIP_ID_REG_NBITS);
			return true;
		case GOC_CTRL_REG_RD:
			*val = SR(&m3_prc_reg_goc_ctrl) & MASK(GOC_CTRL_REG_NBITS);
			return true;
		case PMU_CTRL_REG_RD:
			*val = SR(&m3_prc_reg_pmu_ctrl) & MASK(PMU_CTRL_REG_NBITS);
			return true;
		case WUP_CTRL_REG_RD:
			*val = SR(&m3_prc_reg_wup_ctrl) & MASK(WUP_CTRL_REG_NBITS);
			return true;
		case TSTAMP_REG_RD:
			*val = SR(&m3_prc_reg_tstamp) & MASK(TSTAMP_REG_NBITS);
			return true;
		case MSG_REG0_RD:
			*val = SR(&m3_prc_reg_msg0);
			return true;
		case MSG_REG1_RD:
			*val = SR(&m3_prc_reg_msg1);
			return true;
		case MSG_REG2_RD:
			*val = SR(&m3_prc_reg_msg2);
			return true;
		case MSG_REG3_RD:
			*val = SR(&m3_prc_reg_msg3);
			return true;
		case INT_MSG_REG0_RD:
			*val = SR(&m3_prc_reg_imsg0);
			return true;
		case INT_MSG_REG1_RD:
			*val = SR(&m3_prc_reg_imsg1);
			return true;
		case INT_MSG_REG2_RD:
			*val = SR(&m3_prc_reg_imsg2);
			return true;
		case INT_MSG_REG3_RD:
			*val = SR(&m3_prc_reg_imsg3);
			return true;
		default:
			CORE_ERR_unpredictable("Bad CPU Config Reg Read");
	}
}
Esempio n. 12
0
void test_memcpy_bounds (char *d, const char *s, size_t n)
{
#define FUNC memcpy

  /* Verify that invalid offsets into an array of known size are
     detected.  */

  T (char, 1, a + SR (DIFF_MIN, -1), s, n);     /* { dg-warning "offset \\\[-\[0-9\]+, -1] is out of the bounds \\\[0, 1] of object \[^\n\r]* with type .char ?\\\[1]" } */
  T (char, 1, a + SR (-2, -1), s, n);     /* { dg-warning "offset \\\[-2, -1] is out of the bounds \\\[0, 1] of object" } */
  T (char, 1, a + SR (-2, 0), s, n);

  T (char, 1, a + UR (0, 1), s, n);
  T (char, 1, a + UR (0, 2), s, n);
  T (char, 1, a + UR (1, 2), s, n);
  T (char, 1, a + UR (2, 3), s, n);       /* { dg-warning "offset \\\[2, 3] is out of the bounds \\\[0, 1] of object " } */
  T (char, 1, a + UR (2, DIFF_MAX), s, n);  /* { dg-warning "offset \\\[2, \[0-9\]+] is out of the bounds \\\[0, 1] of object " "memcpy" } */

  /* Offsets in excess of DIFF_MAX are treated as negative even if
     they appear as large positive in the source.  It would be nice
     if they retained their type but unfortunately that's not how
     it works so be prepared for both in case it even gets fixed.  */
  T (char, 1, a + UR (3, SIZE_MAX - 1), s, n);   /* { dg-warning "offset \\\[3, -?\[0-9\]+] is out of the bounds \\\[0, 1] of object" "memcpy" } */

  /* Verify that invalid offsets into an array of unknown size are
     detected.  */
  extern char arr[];
  T (char, 1, arr + SR (DIFF_MIN,             0), s, n);
  T (char, 1, arr + SR (DIFF_MIN + 1,        -1), s, n);   /* { dg-warning "offset \\\[-\[0-9\]+, -1] is out of the bounds of object " "memcpy" } */
  T (char, 1, arr + SR (DIFF_MIN,             1), s, n);
  T (char, 1, arr + SR (DIFF_MIN,      DIFF_MAX), s, n);
  T (char, 1, arr + SR (       -2,           -1), s, n);   /* { dg-warning "offset \\\[-2, -1] is out of the bounds of object " "memcpy" } */
  T (char, 1, arr + SR (       -1,            0), s, n);
  T (char, 1, arr + SR (       -1,            1), s, n);
  T (char, 1, arr + SR (       -1, DIFF_MAX - 1), s, n);
  T (char, 1, arr + SR (        0,            1), s, n);
  T (char, 1, arr + SR (        0, DIFF_MAX - 1), s, n);
  T (char, 1, arr + SR (        1,            2), s, n);
  T (char, 1, arr + SR (        1, DIFF_MAX - 1), s, n);

  /* Verify that all offsets via a pointer to an uknown object are
     accepted.  */

  /* Negative indices between [DIFF_MIN, DIFF_MAX] are valid since
     the pointer to which the offset is applied can be at a positive
     offset from the beginning of an object.  */
  T (char, 1, d + SR (DIFF_MIN,             0), s, n);
  T (char, 1, d + SR (DIFF_MIN,            -1), s, n);
  T (char, 1, d + SR (DIFF_MIN,             1), s, n);
  T (char, 1, d + SR (DIFF_MIN,  DIFF_MAX - 1), s, n);
  T (char, 1, d + SR (       -2,           -1), s, n);
  T (char, 1, d + SR (       -1,            0), s, n);
  T (char, 1, d + SR (       -1,            1), s, n);
  T (char, 1, d + SR (       -1, DIFF_MAX - 1), s, n);
  T (char, 1, d + SR (        0,            1), s, n);
  T (char, 1, d + SR (        0, DIFF_MAX - 1), s, n);
  T (char, 1, d + SR (        1,            2), s, n);
  T (char, 1, d + SR (        1, DIFF_MAX - 1), s, n);
}
Esempio n. 13
0
void test_strcpy_bounds (char *d, const char *s)
{
#undef FUNC
#define FUNC strcpy

  ptrdiff_t i;

  TI (char, 1, "",   a, a + SR (DIFF_MIN, 0));
  TI (char, 1, "",   a, a + SR (-1, 0));
  TI (char, 1, "",   a, a + SR (-1, 1));
  TI (char, 1, "",   a, a + SR (0, 1));
  TI (char, 1, "",   a, a + SR (0, DIFF_MAX - 1));
  TI (char, 2, "0",  a, a + SR (0, DIFF_MAX - 1));
  TI (char, 2, "0",  a, a + SR (1, DIFF_MAX - 1));
  /* The following needs a warning for reading past the end.  */
  TI (char, 2, "0",  a, a + SR (2, DIFF_MAX - 1));
  TI (char, 2, "0",  a, a + SR (3, DIFF_MAX - 1));   /* { dg-warning "offset \\\[3, \[0-9\]+] is out of the bounds \\\[0, 2] of object \[^\n\r\]+ with type .char ?\\\[2\\\]."  "strcpy" } */

  TI (char, 3, "01", a, a + SR (0, DIFF_MAX - 1));
  TI (char, 3, "01", a, a + SR (1, DIFF_MAX - 1));
  TI (char, 3, "01", a, a + SR (2, DIFF_MAX - 1));
  /* The following needs a warning for reading past the end.  */
  TI (char, 3, "01", a, a + SR (3, DIFF_MAX - 1));
  TI (char, 3, "01", a, a + SR (4, DIFF_MAX - 1));   /* { dg-warning "offset \\\[4, \[0-9\]+] is out of the bounds \\\[0, 3] of object \[^\n\r\]+ with type .char ?\\\[3\\\]."  "strcpy" } */

  TI (char, 4, "012", a, a + SR (DIFF_MAX - 2, DIFF_MAX - 1));   /* { dg-warning "offset \\\[\[0-9\]+, \[0-9\]+] is out of the bounds \\\[0, 4] of object \[^\n\r\]+ with type .char ?\\\[4\\\]."  "strcpy" } */


  TI (char, 1, "", a + SR (DIFF_MIN, 0), s);
  TI (char, 1, "", a + SR (-1, 0), s);
  TI (char, 1, "", a + SR (-1, 1), s);
  TI (char, 1, "", a + SR (0, 1), s);
  TI (char, 1, "", a + SR (0, DIFF_MAX - 1), s);
  TI (char, 2, "", a + SR (0, DIFF_MAX - 1), s);
  TI (char, 2, "", a + SR (1, DIFF_MAX - 1), s);
  /* The following is diagnosed not because the initial source offset
     it out of bounds (it isn't) but because the final source offset
     after the access has completed, is.  It would be clearer if
     the warning mentioned the final offset.  */
  TI (char, 2, "", a + SR (2, DIFF_MAX - 1), s);   /* { dg-warning "forming offset 3 is out of the bounds \\\[0, 2] of object \[^\n\r\]+ with type .char ?\\\[2\\\]."  "strcpy" } */
  TI (char, 2, "", a + SR (3, DIFF_MAX - 1), s);   /* { dg-warning "offset \\\[3, \[0-9\]+] is out of the bounds \\\[0, 2] of object \[^\n\r\]+ with type .char ?\\\[2\\\]."  "strcpy" } */

  TI (char, 3, "", a + SR (0, DIFF_MAX - 1), s);
  TI (char, 3, "", a + SR (1, DIFF_MAX - 1), s);
  TI (char, 3, "", a + SR (2, DIFF_MAX - 1), s);
  TI (char, 3, "", a + SR (3, DIFF_MAX - 1), s);   /* { dg-warning "forming offset 4 is out of the bounds \\\[0, 3] of object \[^\n\r\]+ with type .char ?\\\[3\\\]."  "strcpy" } */
  TI (char, 3, "", a + SR (4, DIFF_MAX - 1), s);   /* { dg-warning "offset \\\[4, \[0-9\]+] is out of the bounds \\\[0, 3] of object \[^\n\r\]+ with type .char ?\\\[3\\\]."  "strcpy" } */

  TI (char, 4, "", a + SR (DIFF_MAX - 2, DIFF_MAX - 1), s);   /* { dg-warning "offset \\\[\[0-9\]+, \[0-9\]+] is out of the bounds \\\[0, 4] of object \[^\n\r\]+ with type .char ?\\\[4\\\]."  "strcpy" } */
}
Esempio n. 14
0
int
_gnutls_cipher_init(cipher_hd_st *handle, const cipher_entry_st *e,
		    const gnutls_datum_t *key, const gnutls_datum_t *iv,
		    int enc)
{
	int ret = GNUTLS_E_INTERNAL_ERROR;
	const gnutls_crypto_cipher_st *cc = NULL;

	if (unlikely(e == NULL || e->id == GNUTLS_CIPHER_NULL))
		return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);

        FAIL_IF_LIB_ERROR;

	handle->e = e;
	handle->handle = NULL;

	/* check if a cipher has been registered
	 */
	cc = _gnutls_get_crypto_cipher(e->id);
	if (cc != NULL) {
		handle->encrypt = cc->encrypt;
		handle->decrypt = cc->decrypt;
		handle->aead_encrypt = cc->aead_encrypt;
		handle->aead_decrypt = cc->aead_decrypt;
		handle->deinit = cc->deinit;
		handle->auth = cc->auth;
		handle->tag = cc->tag;
		handle->setiv = cc->setiv;

		/* if cc->init() returns GNUTLS_E_NEED_FALLBACK we
		 * use the default ciphers */
		SR_FB(cc->init(e->id, &handle->handle, enc), cc_cleanup);
		SR_FB(cc->setkey(handle->handle, key->data, key->size),
		   cc_cleanup);
		if (iv) {
			if (unlikely(cc->setiv == NULL)) /* the API doesn't accept IV */
				return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
			SR(cc->setiv(handle->handle, iv->data, iv->size),
			   cc_cleanup);
		}

		return 0;
	}

 fallback:
	handle->encrypt = _gnutls_cipher_ops.encrypt;
	handle->decrypt = _gnutls_cipher_ops.decrypt;
	handle->aead_encrypt = _gnutls_cipher_ops.aead_encrypt;
	handle->aead_decrypt = _gnutls_cipher_ops.aead_decrypt;
	handle->deinit = _gnutls_cipher_ops.deinit;
	handle->auth = _gnutls_cipher_ops.auth;
	handle->tag = _gnutls_cipher_ops.tag;
	handle->setiv = _gnutls_cipher_ops.setiv;

	/* otherwise use generic cipher interface
	 */
	ret = _gnutls_cipher_ops.init(e->id, &handle->handle, enc);
	if (ret < 0) {
		gnutls_assert();
		return ret;
	}

	ret =
	    _gnutls_cipher_ops.setkey(handle->handle, key->data,
				      key->size);
	if (ret < 0) {
		gnutls_assert();
		goto cc_cleanup;
	}

	if (iv) {
		ret =
		    _gnutls_cipher_ops.setiv(handle->handle, iv->data,
					     iv->size);
		if (ret < 0) {
			gnutls_assert();
			goto cc_cleanup;
		}
	}

	return 0;

      cc_cleanup:

	if (handle->handle)
		handle->deinit(handle->handle);

	return ret;
}
Esempio n. 15
0
Exec::RetType Exec_SequenceAlign::Execute(CpptrajState& State, ArgList& argIn) {
  mprintf("Warning: THIS COMMAND IS NOT FULLY IMPLEMENTED.\n");
  std::string blastfile = argIn.GetStringKey("blastfile");
  if (blastfile.empty()) {
    mprinterr("Error: 'blastfile' must be specified.\n");
    return CpptrajState::ERR;
  }
  ReferenceFrame qref = State.DSL().GetReferenceFrame(argIn);
  if (qref.error() || qref.empty()) {
    mprinterr("Error: Must specify reference structure for query.\n");
    return CpptrajState::ERR;
  }
  std::string outfilename = argIn.GetStringKey("out");
  if (outfilename.empty()) {
    mprinterr("Error: Must specify output file.\n");
    return CpptrajState::ERR;
  }
  TrajectoryFile::TrajFormatType fmt = TrajectoryFile::GetFormatFromArg(argIn);
  if (fmt != TrajectoryFile::PDBFILE && fmt != TrajectoryFile::MOL2FILE)
    fmt = TrajectoryFile::PDBFILE; // Default to PDB
  int smaskoffset = argIn.getKeyInt("smaskoffset", 0) + 1;
  int qmaskoffset = argIn.getKeyInt("qmaskoffset", 0) + 1;

  // Load blast file
  mprintf("\tReading BLAST alignment from '%s'\n", blastfile.c_str());
  BufferedLine infile;
  if (infile.OpenFileRead( blastfile )) return CpptrajState::ERR;
  // Seek down to first Query line.
  const char* ptr = infile.Line();
  bool atFirstQuery = false;
  while (ptr != 0) {
    if (*ptr == 'Q') {
      if ( strncmp(ptr, "Query", 5) == 0 ) {
        atFirstQuery = true;
        break;
      }
    }
    ptr = infile.Line();
  }
  if (!atFirstQuery) {
    mprinterr("Error: 'Query' not found.\n");
    return CpptrajState::ERR;
  }

  // Read alignment. Replacing query with subject.
  typedef std::vector<char> Carray;
  typedef std::vector<int> Iarray;
  Carray Query; // Query residues
  Carray Sbjct; // Sbjct residues
  Iarray Smap;  // Smap[Sbjct index] = Query index
  while (ptr != 0) {
    const char* qline = ptr;           // query line
    const char* aline = infile.Line(); // alignment line
    const char* sline = infile.Line(); // subject line
    if (aline == 0 || sline == 0) {
      mprinterr("Error: Missing alignment line or subject line after Query:\n");
      mprinterr("Error:  %s", qline);
      return CpptrajState::ERR;
    }
    for (int idx = 12; qline[idx] != ' '; idx++) {
      if (qline[idx] == '-') {
        // Sbjct does not have corresponding res in Query
        Smap.push_back(-1);
        Sbjct.push_back( sline[idx] );
      } else if (sline[idx] == '-') {
        // Query does not have a corresponding res in Sbjct
        Query.push_back( qline[idx] );
      } else {
        // Direct Query to Sbjct map
        Smap.push_back( Query.size() );
        Sbjct.push_back( sline[idx] );
        Query.push_back( qline[idx] );
      }
    }
    // Scan to next Query 
    ptr = infile.Line();
    while (ptr != 0) {
      if (*ptr == 'Q') {
        if ( strncmp(ptr, "Query", 5) == 0 ) break;
      }
      ptr = infile.Line();
    }
  }
  // DEBUG
  std::string SmaskExp, QmaskExp;
  if (State.Debug() > 0) mprintf("  Map of Sbjct to Query:\n");
  for (int sres = 0; sres != (int)Sbjct.size(); sres++) {
    if (State.Debug() > 0)
      mprintf("%-i %3s %i", sres+smaskoffset, Residue::ConvertResName(Sbjct[sres]),
              Smap[sres]+qmaskoffset);
    const char* qres = "";
    if (Smap[sres] != -1) {
      qres = Residue::ConvertResName(Query[Smap[sres]]);
      if (SmaskExp.empty())
        SmaskExp.assign( integerToString(sres+smaskoffset) );
      else
        SmaskExp.append( "," + integerToString(sres+smaskoffset) );
      if (QmaskExp.empty())
        QmaskExp.assign( integerToString(Smap[sres]+qmaskoffset) );
      else
        QmaskExp.append( "," + integerToString(Smap[sres]+qmaskoffset) );

    }
    if (State.Debug() > 0) mprintf(" %3s\n", qres);
  }
  mprintf("Smask: %s\n", SmaskExp.c_str());
  mprintf("Qmask: %s\n", QmaskExp.c_str());
  // Check that query residues match reference.
  for (unsigned int sres = 0; sres != Sbjct.size(); sres++) {
    int qres = Smap[sres];
    if (qres != -1) {
      if (Query[qres] != qref.Parm().Res(qres).SingleCharName()) {
        mprintf("Warning: Potential residue mismatch: Query %s reference %s\n",
                Residue::ConvertResName(Query[qres]), qref.Parm().Res(qres).c_str());
      }
    }
  }
  // Build subject using coordinate from reference.
  //AtomMask sMask; // Contain atoms that should be in sTop
  Topology sTop;
  Frame sFrame;
  Iarray placeHolder; // Atom indices of placeholder residues.
  for (unsigned int sres = 0; sres != Sbjct.size(); sres++) {
    int qres = Smap[sres];
    NameType SresName( Residue::ConvertResName(Sbjct[sres]) );
    if (qres != -1) {
      Residue const& QR = qref.Parm().Res(qres);
      Residue SR(SresName, sres+1, ' ', QR.ChainID());
      if (Query[qres] == Sbjct[sres]) { // Exact match. All non-H atoms.
        for (int qat = QR.FirstAtom(); qat != QR.LastAtom(); qat++)
        {
          if (qref.Parm()[qat].Element() != Atom::HYDROGEN)
            sTop.AddTopAtom( qref.Parm()[qat], SR );
            sFrame.AddXYZ( qref.Coord().XYZ(qat) );
            //sMask.AddAtom(qat);
        }
      } else { // Partial match. Copy only backbone and CB.
        for (int qat = QR.FirstAtom(); qat != QR.LastAtom(); qat++)
        {
          if ( qref.Parm()[qat].Name().Match("N" ) ||
               qref.Parm()[qat].Name().Match("CA") ||
               qref.Parm()[qat].Name().Match("CB") ||
               qref.Parm()[qat].Name().Match("C" ) ||
               qref.Parm()[qat].Name().Match("O" ) )
          {
            sTop.AddTopAtom( qref.Parm()[qat], SR );
            sFrame.AddXYZ( qref.Coord().XYZ(qat) );
          }
        }
      }
    } else {
      // Residue in query does not exist for subject. Just put placeholder CA for now.
      Vec3 Zero(0.0);
      placeHolder.push_back( sTop.Natom() );
      sTop.AddTopAtom( Atom("CA", "C "), Residue(SresName, sres+1, ' ', ' ') );
      sFrame.AddXYZ( Zero.Dptr() );
    }
  }
  //sTop.PrintAtomInfo("*");
  mprintf("\tPlaceholder residue indices:");
  for (Iarray::const_iterator p = placeHolder.begin(); p != placeHolder.end(); ++p)
    mprintf(" %i", *p + 1);
  mprintf("\n");
  // Try to give placeholders more reasonable coordinates.
  if (!placeHolder.empty()) {
    Iarray current_indices;
    unsigned int pidx = 0;
    while (pidx < placeHolder.size()) {
      if (current_indices.empty()) {
        current_indices.push_back( placeHolder[pidx++] );
        // Search for the end of this segment
        for (; pidx != placeHolder.size(); pidx++) {
          if (placeHolder[pidx] - current_indices.back() > 1) break;
          current_indices.push_back( placeHolder[pidx] );
        }
        // DEBUG
        mprintf("\tSegment:");
        for (Iarray::const_iterator it = current_indices.begin();
                                    it != current_indices.end(); ++it)
          mprintf(" %i", *it + 1);
        // Get coordinates of residues bordering segment.
        int prev_res = sTop[current_indices.front()].ResNum() - 1;
        int next_res = sTop[current_indices.back() ].ResNum() + 1;
        mprintf(" (prev_res=%i, next_res=%i)\n", prev_res+1, next_res+1);
        Vec3 prev_crd(sFrame.XYZ(current_indices.front() - 1));
        Vec3 next_crd(sFrame.XYZ(current_indices.back()  + 1));
        prev_crd.Print("prev_crd");
        next_crd.Print("next_crd");
        Vec3 crd_step = (next_crd - prev_crd) / (double)(current_indices.size()+1);
        crd_step.Print("crd_step");
        double* xyz = sFrame.xAddress() + (current_indices.front() * 3);
        for (unsigned int i = 0; i != current_indices.size(); i++, xyz += 3) {
          prev_crd += crd_step;
          xyz[0] = prev_crd[0];
          xyz[1] = prev_crd[1];
          xyz[2] = prev_crd[2];
        }
        current_indices.clear();
      }
    }
  }
  //Topology* sTop = qref.Parm().partialModifyStateByMask( sMask );
  //if (sTop == 0) return CpptrajState::ERR;
  //Frame sFrame(qref.Coord(), sMask);
  // Write output traj
  Trajout_Single trajout;
  if (trajout.PrepareTrajWrite(outfilename, argIn, &sTop, CoordinateInfo(), 1, fmt))
    return CpptrajState::ERR;
  if (trajout.WriteSingle(0, sFrame)) return CpptrajState::ERR;
  trajout.EndTraj();
  return CpptrajState::OK;
}
Esempio n. 16
0
File: gen1.c Progetto: RTcmix/RTcmix
/* Let user load a function table with samples from a sound file.  The file
   can be 16-bit integer or 32-bit floating point in either byte order, and
   in any of the header formats recognized by sndlib.  The makegen syntax
   used in Minc is:

      frames_read = makegen(slot, 1, size, filename, inskip [, inchan, dump])

   <size> is the duration (in seconds) of the sound file segment, or if it's
   negative, the number of sample frames to read.  If <size> is zero, the
   whole file is slurpped in.  (Beware with large files -- there is no
   check on memory consumption here!)

   <filename> is a double-quoted pathname (as in rtinput).

   <inskip> is the time (in seconds) to skip before reading, or if it's 
   negative, the number of sample frames to skip before reading.

   If <inchan> is missing, reads all channels from the file; otherwise,
   reads just the channel specified by <inchan> (with zero as first chan).

   If <dump> is 1, then dumps the gen table to a header-less sound file,
   called "dumpaudio.raw," in the current directory.  The file is 32-bit
   float, using the host byte order, <inchan> chans, and the sampling
   rate in the source file's header.

   As usual, if the slot number is positive, the table will be rescaled
   to fit in the range [-1,1]; if it's negative, it will not be rescaled.

   Returns to Minc the number of sample frames read.

   JGG, 07 Feb 2001
*/
double
gen1(struct gen *gen, char *sfname)
{
   int      i, fd, header_type, data_format, data_location, inchan;
   int      gen_chans, gen_frames, gen_samps, file_chans, file_frames;
   int      start_frame, bytes_per_samp, byteswap, is_float, dump;
   int      buf_start_frame, end_frame, frames_read, buf_frames;
   long     file_samps;
   off_t    seek_to;
   float    request_dur, filedur, inskip;
   double   srate, *block, *blockp;
   char     *buf;

   request_dur = gen->pvals[0];
   inskip = gen->pvals[2];
   if (gen->nargs > 3)
      inchan = (int) gen->pvals[3];
   else
      inchan = -1;   /* read all chans */
   dump = gen->nargs > 4? (int) gen->pvals[4] : 0;

   fd = open_sound_file("gen1", sfname, &header_type, &data_format,
                        &data_location, &srate, &file_chans, &file_samps);
   if (fd == -1)
      return die("gen1", "Can't open input file: \"%s\"!", sfname);

   if (srate != SR()) {
      rtcmix_warn("gen1", "The input file sampling rate is %g, but "
                      "the output rate is currently %g.", srate, SR());
   }

   file_frames = file_samps / file_chans;

   if (inchan == -1)
      gen_chans = file_chans;
   else
      gen_chans = 1;

   if (file_chans == 1)
      inchan = -1;                       /* more efficient copy below */

   if (inchan >= file_chans)
      return die("gen1", "You asked for channel %d of a %d-channel file. (\"%s\")",
                                                   inchan, file_chans, sfname);

   if (request_dur < 0.0)
      gen_frames = (int) -request_dur;
   else if (request_dur > 0.0)
      gen_frames = (int) (request_dur * srate);
   else
      gen_frames = file_frames;

   if (inskip < 0.0)
      start_frame = (int) -inskip;
   else
      start_frame = (int) (inskip * srate); 

   if (start_frame + gen_frames > file_frames)
      gen_frames = file_frames - start_frame;

   gen_samps = gen_frames * gen_chans;
 
   block = (double *) malloc((size_t) (gen_samps * sizeof(double)));
   if (block == NULL)
      return die("gen1", "Not enough memory for function table %d.", gen->slot);

   buf = (char *) malloc((size_t) BUFSIZE);
	if (buf == NULL) {
		free(block);
      return die("gen1", "Not enough memory for temporary buffer.");
	}

   bytes_per_samp = mus_data_format_to_bytes_per_sample(data_format);

   seek_to = data_location + (start_frame * file_chans * bytes_per_samp);
   if (lseek(fd, seek_to, SEEK_SET) == -1) {
	   free(block);
	   free(buf);
		return die("gen1", "lseek() failed");
   }

#if MUS_LITTLE_ENDIAN
   byteswap = IS_BIG_ENDIAN_FORMAT(data_format);
#else
   byteswap = IS_LITTLE_ENDIAN_FORMAT(data_format);
#endif
   is_float = IS_FLOAT_FORMAT(data_format);

   buf_frames = (BUFSIZE / bytes_per_samp) / file_chans;

   end_frame = start_frame + gen_frames;

   blockp = block;
   frames_read = 0;
   buf_start_frame = start_frame;
   for ( ; buf_start_frame < end_frame; buf_start_frame += frames_read) {
      int  samps_read;
      long bytes_read;

      if (buf_start_frame + buf_frames > end_frame) {      /* last buffer */
         int samps = (end_frame - buf_start_frame) * file_chans;
         bytes_read = read(fd, buf, samps * bytes_per_samp);
      }
      else
         bytes_read = read(fd, buf, BUFSIZE);
      if (bytes_read == -1) {
		  free(block);
		  free(buf);
		  return die("gen1", "read() failed");
      }
      if (bytes_read == 0)          /* EOF, somehow */
         break;

      samps_read = bytes_read / bytes_per_samp;
      frames_read = samps_read / file_chans;

      if (is_float) {
         float *bufp = (float *) buf;

         if (inchan == -1) {                 /* store all chans */
            if (byteswap) {
               for (i = 0; i < samps_read; i++) {
                  byte_reverse4(bufp);       /* modify *bufp in place */
                  *blockp++ = (double) *bufp++;
               }
            }
            else {
               for (i = 0; i < samps_read; i++)
                  *blockp++ = (double) *bufp++;
            }
         }
         else {                              /* store only inchan */
            bufp += inchan;
            if (byteswap) {
               for (i = 0; i < samps_read; i += file_chans) {
                  byte_reverse4(bufp);       /* modify *bufp in place */
                  *blockp++ = (double) *bufp;
                  bufp += file_chans;
               }
            }
            else {
               for (i = 0; i < samps_read; i += file_chans) {
                  *blockp++ = (double) *bufp;
                  bufp += file_chans;
               }
            }
         }
      }
      else {                                 /* is shortint file */
         short *bufp = (short *) buf;

         if (inchan == -1) {                 /* store all chans */
            if (byteswap) {
               for (i = 0; i < samps_read; i++, bufp++) {
                  short samp = reverse_int2(bufp);
                  *blockp++ = (double) samp;
               }
            }
            else {
               for (i = 0; i < samps_read; i++)
                  *blockp++ = (double) *bufp++;
            }
         }
         else {                              /* store only inchan */
            bufp += inchan;
            if (byteswap) {
               for (i = 0; i < samps_read; i += file_chans) {
                  short samp = reverse_int2(bufp);
                  *blockp++ = (double) samp;
                  bufp += file_chans;
               }
            }
            else {
               for (i = 0; i < samps_read; i += file_chans) {
                  *blockp++ = (double) *bufp;
                  bufp += file_chans;
               }
            }
         }
      }
   }

   free(buf);
   sndlib_close(fd, 0, 0, 0, 0);

   gen->array = block;
   gen->size = gen_samps;

   fnscl(gen);

   if (dump)
      dump_gen_to_raw_file(block, gen_samps);

   return (double) gen_frames;
}
Esempio n. 17
0
double
sgran(float p[], int n_args)
{
	long n,bgrainsamps,bgraindist,bgrainslide;
	long i,nsamps,gstt_var,count;
	long egrainsamps,egraindist,egrainslide;
	long grainsamps,grainslide,graindistdiff;
	float si=0.0,phase,val=0.0,amp,out[2],chb,freq;
	float tabs[2],tab[2],tab2[2],tab3[2],tab4[2],tab5[2];
	double *array,*wave,*envel,*rate_shape,*dur_shape,*loc_shape,*freq_shape;
	float gdist_inc;
	double gstt_per,lo,mid,hi,ti,slodiff,smiddiff,shidiff,stidiff;
	double dlodiff,dmiddiff,dhidiff,dtidiff;
	double llodiff,lmiddiff,lhidiff,ltidiff;
	double flodiff,fmiddiff,fhidiff,ftidiff;
	int len,j,z,chans,randflag=0;

#ifdef EMBEDDED
	int outrepos();
#endif
	float rrand();
	void srrand();
	double prob();

	if (p[37] > 0)
		srrand(p[37]);
   else
		srrand(3);

	nsamps = setnote(p[0],p[1],1); /* set file position */

	array = floc(1);             /* used to be setline  -JGG */
	if (array) {
		int amplen = fsize(1);
		tableset(SR(), p[1], amplen, tabs);
	}
	else
		rtcmix_advise("sgran", "Setting phrase curve to all 1's.");

	wave = floc(6); /* finds starting loc. of waveform */
	if (wave == NULL)
		die("sgran", "You haven't made the oscillator waveform (table 6).");
	len = fsize(6); /* length of playing waveform function */

	envel = floc(8);  /* NOTE: used to be floc(1), now stolen by setline  -JGG */
	if (envel == NULL)
		die("sgran", "You haven't made the grain envelope (table 8).");
	/* NOTE: fsize(8) called in loop below */

	bgrainsamps = grainsamps = p[14] * SR();
	bgraindist = p[3] * SR();
	bgrainslide = grainslide = bgraindist - bgrainsamps;

	egrainsamps = p[18] * SR();
	egraindist = p[4] * SR();
	egrainslide = egraindist - egrainsamps;

	graindistdiff = egraindist - bgraindist;

	rate_shape = floc(2);
	if (rate_shape == NULL)
		die("sgran", "You haven't made the grain density function (table 2).");
	tableset(SR(), p[1]-p[4],fsize(2),tab2);

	dur_shape = floc(3);
	if (dur_shape == NULL)
		die("sgran", "You haven't made the grain duration function (table 3).");
	tableset(SR(), p[1]-p[4],fsize(3),tab3);

	loc_shape = floc(4);
	if (loc_shape == NULL)
		die("sgran", "You haven't made the grain location function (table 4).");
	tableset(SR(), p[1]-p[4],fsize(4),tab4);

	freq_shape = floc(5);
	if (freq_shape == NULL)
		die("sgran", "You haven't made the grain frequency function (table 5).");
	tableset(SR(), p[1]-p[4],fsize(5),tab5);

	slodiff = (double)(p[9]-p[5])/nsamps; /* get stt zero/one differences */
	smiddiff = (double)(p[10]-p[6])/nsamps;
	shidiff = (double)(p[11]-p[7])/nsamps;
	stidiff = (double)(p[12]-p[8])/nsamps;

	dlodiff = (double)(p[17]-p[13]); /*get dur zero/one differences */
	dmiddiff = (double)(p[18]-p[14]);
	dhidiff = (double)(p[19]-p[15]);
	dtidiff = (double)(p[20]-p[16]);

	llodiff = (double)(p[25]-p[21]); /*get loc zero/one differences */
	lmiddiff = (double)(p[26]-p[22]);
	lhidiff = (double)(p[27]-p[23]);
	ltidiff = (double)(p[28]-p[24]);
	chb = p[21];

	if (p[29] < 0) 		/* if negative, noise is the input */
		randflag = 1;

	flodiff = (double)(p[33]-p[29]); /*freq zero/one differences */
	fmiddiff = (double)(p[34]-p[30]);
	fhidiff = (double)(p[35]-p[31]);
	ftidiff = (double)(p[36]-p[32]);

	z = 2;

	chans = sfchans(&sfdesc[1]); /* get file number of channels */
	amp = p[2];
	gstt_var = 0;
	count = 0;

	j = 0; /* "branch once a cycle" loop for amp envelope */

	for(i = 0; i < nsamps; i++) {
		count++;
		phase = 0;
		tableset(SR(), grainsamps/SR(),fsize(8),tab);
		if(!randflag) {
			lo = p[29] + flodiff*tablei(i,freq_shape,tab5);
			mid = p[30] + fmiddiff*tablei(i,freq_shape,tab5);
			hi = p[31] + fhidiff*tablei(i,freq_shape,tab5);
			ti = p[32] + ftidiff*tablei(i,freq_shape,tab5);
			lo = (lo > mid) ? mid : lo;
			hi = (hi < mid) ? mid : hi;
			ti = (ti < 0) ? 0 : ti; 
			freq = prob(lo, mid, hi, ti);
			si = freq * (float)len/SR(); 
		}

/*
	fprintf(stderr,"i: %ld, grainsamps: %ld, grainslide: %ld\n",i,grainsamps,grainslide);
*/

		for (n = 0; n < grainsamps; n++) {
			while (!j--) {   /* branch in here when j reaches 0 */
				float tmp = 1.0;
				if (array)
					tmp = tablei(i,array,tabs);
				val = amp * tablei(n,envel,tab) * tmp;
				j = ((grainsamps-n) > z) ? z : (grainsamps-n);
			}
			if(randflag)
				out[0] = rrand()*val;
			else
				out[0] =  oscili(val,si,wave,len,&phase);

			if (chans > 1) { /* stereo */
				out[1] = (1.0 - chb) * out[0];
				out[0] *= chb;
			}
			ADDOUT(out,1);
		}

		if((i+grainslide+gstt_var+grainsamps) < 0) {
			outrepos((grainslide),1);
			i += grainsamps;
			i += grainslide;
		}	
		else {
			outrepos((grainslide+gstt_var),1);
			i += grainsamps;
			i += grainslide;
			i += gstt_var;
		}

		lo = p[13] + dlodiff*tablei(i,dur_shape,tab3);
		mid = p[14] + dmiddiff*tablei(i,dur_shape,tab3);
		hi = p[15] + dhidiff*tablei(i,dur_shape,tab3);
		ti = p[16] + dtidiff*tablei(i,dur_shape,tab3);
		lo = (lo > mid) ? mid : lo;
		hi = (hi < mid) ? mid : hi;
		ti = (ti < 0) ? 0 : ti; 
		grainsamps = (long)(prob(lo, mid, hi, ti)*SR());


		/*	get percentage to vary next stt of grain */
		lo = p[5] + slodiff*i;
		mid = p[6] + smiddiff*i;
		hi = p[7] + shidiff*i;
		ti = p[8] + stidiff*i;
		lo = (lo > mid) ? mid : lo;
		hi = (hi < mid) ? mid : hi;
		ti = (ti < 0) ? 0 : ti; 
		gstt_per = prob(lo, mid, hi, ti);
		gstt_var = (long)(gstt_per*(grainsamps+grainslide)); 

/* calculate grainslide */
		gdist_inc = tablei(i,rate_shape,tab2);
		grainslide = (float)bgraindist + (float)graindistdiff*gdist_inc - grainsamps;

		lo = p[21] + llodiff*tablei(i,loc_shape,tab4);
		mid = p[22] + lmiddiff*tablei(i,loc_shape,tab4);
		hi = p[23] + lhidiff*tablei(i,loc_shape,tab4);
		ti = p[24] + ltidiff*tablei(i,loc_shape,tab4);
		lo = (lo > mid) ? mid : lo;
		hi = (hi < mid) ? mid : hi;
		ti = (ti < 0) ? 0 : ti; 
		chb = prob(lo, mid, hi, ti);
	}
	printf("\n%ld grains\n",count);
	endnote(1);

	return(0.0);
}
Esempio n. 18
0
double m_open(float *p, short n_args, double *pp) 
{
	char  *name,*cp,*getsfcode();
	int   fno,i,inew;
	float *opk;

	name = DOUBLE_TO_STRING(pp[0]);
	fno = p[1];
// JGG: will name ptr be valid for entire program run? Is its memory held by
// parser? If not, we should malloc sfname[fno] below (with other mallocs)
	sfname[fno] = name;
	status[fno] = (n_args == 3) ? (int)p[2] : 2;

	if((fno >=  NFILES) || (fno < 0)) {
		rtcmix_warn("m_open", "Only %d files allowed\n", NFILES);
		closesf();
		}
	inew = 0;
	if(isopen[fno]) {
		close(sfd[fno]);
	}
	else inew = 1;

	istape[fno] = (n_args == 4) ? 1 : 0;
			/* in the case of a tape, there will be a 
			   4th argument listing the file number */

	rwopensf(name,sfd[fno],sfdesc[fno],sfst[fno],"CMIX",i,status[fno]);
	if (i < 0)
		closesf();

	if (status[fno] == O_RDWR
			&& !WRITEABLE_HEADER_TYPE(sfheadertype(&sfdesc[fno]))) {
		rtcmix_warn("m_open", "can't write this type of header.\n");
		closesf();
	}

	isopen[fno] = 1;

	swap_bytes[fno] = swap;  /* swap and isNext set in rwopensf */
	is_Next[fno] = isNext;
	headersize[fno] = getheadersize(&sfdesc[fno]);

	rtcmix_advise(NULL, "name: %s   sr: %.3f  nchans: %d  class: %d\n",name,
		sfsrate(&sfdesc[fno]),sfchans(&sfdesc[fno]), sfclass(&sfdesc[fno]));
	rtcmix_advise(NULL, "Soundfile type: %s\n",
			mus_header_type_name(sfheadertype(&sfdesc[fno])));
	rtcmix_advise(NULL, "   data format: %s\n",
			mus_data_format_name(sfdataformat(&sfdesc[fno])));
	rtcmix_advise(NULL, "Duration of file is %f seconds.\n",
		(float)(sfst[fno].st_size - headersize[fno])/(float)sfclass(&sfdesc[fno])/(float)sfchans(&sfdesc[fno])/sfsrate(&sfdesc[fno]));

	originalsize[fno] = istape[fno] ? 999999999 : sfst[fno].st_size;
	/*
	sfstats(sfd[fno]);
	*/
	if(inew) {
		if((sndbuf[fno] = (char *)malloc((unsigned)nbytes)) == NULL) {
			rtcmix_warn("CMIX", "malloc sound buffer error\n");
			closesf();
		}
		if((peakloc[fno] = (char *)malloc((unsigned)(sfchans(&sfdesc[fno]) * 
			LONG))) == NULL) {
			rtcmix_warn("CMIX", "malloc ovpeak buffer error\n");
			closesf();
		}
		if((peak[fno] = 
			(char *)malloc((unsigned)(sfchans(&sfdesc[fno])* FLOAT))) 
			== NULL) {
			rtcmix_warn("CMIX", "malloc peak buffer error!\n");
			closesf();
		}
		peakoff[fno] = 0; /* default to peakcheckon when opening file*/
		punch[fno] = 0; /* default to no punch when opening file*/
	}
	if(sfclass(&sfdesc[fno]) == SHORT) {
		addoutpointer[fno] = _iaddout;
		layoutpointer[fno] = _ilayout;
		wipeoutpointer[fno] = _iwipeout;
		getinpointer[fno] = _igetin;
	}
	else 			        {   
		addoutpointer[fno] = _faddout;
		layoutpointer[fno] = _flayout;
		wipeoutpointer[fno] = _fwipeout;
		getinpointer[fno] = _fgetin;
	}

	if(!SR()) set_SR(sfsrate(&sfdesc[fno]));	

	if(sfsrate(&sfdesc[fno])!= SR())
		rtcmix_advise("CMIX", "Note--> SR reset to %f\n",SR());

	/* read in former peak amplitudes, make sure zero'ed out to start.*/

	/* In the sndlib version, we store peak stats differently. See
	   comments in sndlibsupport.c for an explanation. The sndlib
	   version of rwopensf reads peak stats, so here we just have to
	   copy these into the sfm[fno] array. (No swapping necessary.)
	*/
	memcpy(&sfm[fno], &(sfmaxampstruct(&sfdesc[fno])), sizeof(SFMAXAMP));

	for(opk = (float *)peak[fno], i = 0; i<sfchans(&sfdesc[fno]); i++) 
		*(opk+i) = sfmaxamp(&sfm[fno],i);
	bufsize[fno] = nbytes / sfclass(&sfdesc[fno]);/* set size in words */

	return 0.0;
}
Esempio n. 19
0
bool SparseMatrixTest(const size_t & size,
                      const C_FLOAT64 & sparseness,
                      const unsigned C_INT32 & seed,
                      const bool & RMP,
                      const bool & dgemmFlag,
                      const bool & SMP,
                      const bool & CCMP)
{
  size_t i, j, l, loop = 1;
  CRandom * pRandom =
    CRandom::createGenerator(CRandom::mt19937, seed);

  // If the sparseness is not specified we expect 4 metabolites per reaction
  C_FLOAT64 Sparseness = sparseness;

  if (Sparseness == 0.0) Sparseness = 4.0 / size;

  CMatrix< C_FLOAT64 > M(size - 3, size);
  CSparseMatrix S(size - 3, size);
  CMatrix< C_FLOAT64 > MM(size, size + 3);
  CSparseMatrix Ss(size, size + 3);
  C_FLOAT64 tmp;

  for (i = 0; i < size - 3; i++)
    for (j = 0; j < size; j++)
      {
        if (pRandom->getRandomCC() < Sparseness)
          S(i, j) = (pRandom->getRandomCC() - 0.5) * 100.0;
      }

  for (i = 0; i < size; i++)
    for (j = 0; j < size + 3; j++)
      {
        if (pRandom->getRandomCC() < Sparseness)
          Ss(i, j) = (pRandom->getRandomCC() - 0.5) * 100.0;
      }

  M = S;
  MM = Ss;

  CCompressedColumnFormat C(S);
  CCompressedColumnFormat CC(Ss);

  std::cout << "Memory requirements for sparseness:\t" << Sparseness << std::endl;

  tmp = (C_FLOAT64) sizeof(CMatrix< C_FLOAT64 >) + size * size * sizeof(C_FLOAT64);
  std::cout << "Matrix(" << size << "x" << size << "):\t" << tmp << std::endl;

  C_FLOAT64 tmp2 = (C_FLOAT64) sizeof(CSparseMatrix)
                   + 2 * size * sizeof(std::vector<CSparseMatrixElement *>)
                   + 2 * size * sizeof(C_FLOAT64)
                   + S.numNonZeros() * sizeof(CSparseMatrixElement);
  std::cout << "Sparse(" << size << "x" << size << "):\t" << tmp2 << std::endl;
  std::cout << "Sparse/Matrix:\t" << tmp2 / tmp << std::endl;

  tmp2 = (C_FLOAT64) sizeof(CCompressedColumnFormat)
         + 2 * C.numNonZeros() * sizeof(C_FLOAT64)
         + (size + 1) * sizeof(C_FLOAT64);
  std::cout << "CompressedColumnFormat(" << size << "x" << size << "):\t" << tmp2 << std::endl;
  std::cout << "CompressedColumnFormat/Matrix:\t" << tmp2 / tmp << std::endl << std::endl;

  CCopasiTimer CPU(CCopasiTimer::PROCESS);
  CCopasiTimer WALL(CCopasiTimer::WALL);

  if (RMP)
    {
      // Regular Matrix Product
      CPU.start();
      WALL.start();

      for (l = 0; l < loop; l++)
        {
          CMatrix< C_FLOAT64 > MR(M.numRows(), MM.numCols());
          const C_FLOAT64 *pTmp1, *pTmp2, *pTmp4, *pTmp5;
          const C_FLOAT64 *pEnd1, *pEnd2, *pEnd4;
          C_FLOAT64 *pTmp3;

          size_t LDA = M.numCols();
          size_t LDB = MM.numCols();

          pTmp1 = M.array();
          pEnd1 = pTmp1 + M.numRows() * LDA;

          pEnd2 = MM.array() + LDB;
          pTmp3 = MR.array();

          for (; pTmp1 < pEnd1; pTmp1 += LDA)
            for (pTmp2 = MM.array(); pTmp2 < pEnd2; pTmp2++, pTmp3++)
              {
                *pTmp3 = 0.0;

                for (pTmp4 = pTmp1, pTmp5 = pTmp2, pEnd4 = pTmp4 + LDA;
                     pTmp4 < pEnd4; pTmp4++, pTmp5 += LDB)
                  * pTmp3 += *pTmp4 * *pTmp5;
              }
        }

      CPU.refresh();
      WALL.refresh();
      std::cout << "Matrix * Matrix:\t";
      CPU.print(&std::cout);
      std::cout << "\t";
      WALL.print(&std::cout);
      std::cout << std::endl;
    }

  if (dgemmFlag)
    {
      CPU.start();
      WALL.start();

      for (l = 0; l < loop; l++)
        {
          CMatrix< C_FLOAT64 > dgemmR(M.numRows(), MM.numCols());
          char T = 'N';

          C_INT m = (C_INT) MM.numCols(); /* LDA, LDC */
          C_INT n = (C_INT) M.numRows();
          C_INT k = (C_INT) M.numCols();  /* LDB */

          C_FLOAT64 Alpha = 1.0;
          C_FLOAT64 Beta = 0.0;

          dgemm_(&T, &T, &m, &n, &k, &Alpha, MM.array(), &m,
                 M.array(), &k, &Beta, dgemmR.array(), &m);
        }

      /*
        for (i = 0; i < MR.numRows(); i++)
          for (j = 0; j < MR.numCols(); j++)
            assert(fabs(MR(i, j) - dgemmR(i, j)) <= 100.0 * std::numeric_limits< C_FLOAT64 >::epsilon() * fabs(MR(i, j)));
      */

      CPU.refresh();
      WALL.refresh();
      std::cout << "dgemm(Matrix, Matrix):\t";
      CPU.print(&std::cout);
      std::cout << "\t";
      WALL.print(&std::cout);
      std::cout << std::endl;
    }

  // Sparse Matrix Product
  if (SMP)
    {
      CPU.start();
      WALL.start();

      for (l = 0; l < loop; l++)
        {
          CSparseMatrix SR(S.numRows(), Ss.numCols());
          C_FLOAT64 Tmp;
          std::vector< std::vector< CSparseMatrixElement * > >::const_iterator itRow;
          std::vector< std::vector< CSparseMatrixElement * > >::const_iterator endRow;
          std::vector< CSparseMatrixElement * >::const_iterator itRowElement;
          std::vector< CSparseMatrixElement * >::const_iterator endRowElement;
          std::vector< std::vector< CSparseMatrixElement * > >::const_iterator itCol;
          std::vector< std::vector< CSparseMatrixElement * > >::const_iterator endCol;
          std::vector< CSparseMatrixElement * >::const_iterator itColElement;
          std::vector< CSparseMatrixElement * >::const_iterator endColElement;

          for (itRow = S.getRows().begin(), endRow = S.getRows().end(); itRow != endRow; ++itRow)
            {
              endRowElement = itRow->end();

              for (itCol = Ss.getColumns().begin(), endCol = Ss.getColumns().end(); itCol != endCol; ++itCol)
                {
                  Tmp = 0;
                  itRowElement = itRow->begin();
                  itColElement = itCol->begin();
                  endColElement = itCol->end();

                  while (itRowElement != endRowElement &&
                         itColElement != endColElement)
                    {
                      while (itRowElement != endRowElement &&
                             (*itRowElement)->col() < (*itColElement)->row()) ++itRowElement;

                      if (itRowElement == endRowElement) break;

                      while (itColElement != endColElement &&
                             (*itColElement)->row() < (*itRowElement)->col()) ++itColElement;

                      if (itColElement == endColElement) break;

                      if ((*itRowElement)->col() != (*itColElement)->row()) continue;

                      Tmp += **itRowElement * **itColElement;
                      ++itRowElement;
                      ++itColElement;
                    }

                  if (fabs(Tmp) < SR.getTreshold()) continue;

                  SR.insert((*itRow->begin())->row(), (*itCol->begin())->col(), Tmp);
                }
            }
        }

      CPU.refresh();
      WALL.refresh();
      std::cout << "Sparse * Sparse:\t";
      CPU.print(&std::cout);
      std::cout << "\t";
      WALL.print(&std::cout);
      std::cout << std::endl;

      /*
        for (i = 0; i < MR.numRows(); i++)
          for (j = 0; j < MR.numCols(); j++)
            assert(fabs(MR(i, j) - SR(i, j)) < SR.getTreshold());
      */
    }

  // Compressed Column Format Product
  if (CCMP)
    {
      CPU.start();
      WALL.start();

      for (l = 0; l < loop; l++)
        {
          CSparseMatrix TmpR(C.numRows(), CC.numCols());
          CCompressedColumnFormat CR(C.numRows(), CC.numCols(), 0);
          C_FLOAT64 Tmp;
          size_t imax = CR.numRows();
          size_t jmax = CR.numCols();
          C_FLOAT64 * pColElement, * pEndColElement;
          size_t * pColElementRow, * pEndColElementRow;
          size_t * pColStart;
          CCompressedColumnFormat::const_row_iterator itRowElement;
          CCompressedColumnFormat::const_row_iterator endRowElement = C.endRow(0);

          for (j = 0, pColStart = CC.getColumnStart(); j < jmax; j++, pColStart++)
            {
              for (i = 0; i < imax; i++)
                {
                  Tmp = 0;

                  itRowElement = C.beginRow(i);
                  pColElement = CC.getValues() + *pColStart;
                  pEndColElement = CC.getValues() + *(pColStart + 1);
                  pColElementRow = CC.getRowIndex() + *pColStart;
                  pEndColElementRow = CC.getRowIndex() + *(pColStart + 1);

                  while (itRowElement != endRowElement &&
                         pColElement != pEndColElement)
                    {
                      while (itRowElement != endRowElement &&
                             itRowElement.getColumnIndex() < *pColElementRow) ++itRowElement;

                      if (!(itRowElement != endRowElement)) break;

                      while (pColElement != pEndColElement &&
                             *pColElementRow < itRowElement.getColumnIndex())
                        {
                          ++pColElement;
                          ++pColElementRow;
                        }

                      if (pColElement == pEndColElement) break;

                      if (itRowElement.getColumnIndex() != *pColElementRow) continue;

                      Tmp += *itRowElement * *pColElement;
                      ++itRowElement;
                      ++pColElement;
                      ++pColElementRow;
                    }

                  if (fabs(Tmp) < TmpR.getTreshold()) continue;

                  TmpR.insert(i, j, Tmp);
                }
            }

          CR = TmpR;
        }

      CPU.refresh();
      WALL.refresh();
      std::cout << "Compressed * Compressed:\t";
      CPU.print(&std::cout);
      std::cout << "\t";
      WALL.print(&std::cout);
      std::cout << std::endl;

      /*
        for (i = 0; i < MR.numRows(); i++)
          for (j = 0; j < MR.numCols(); j++)
            assert(fabs(MR(i, j) - TmpR(i, j)) < SR.getTreshold());
      */
    }

  std::cout << std::endl;
  std::cout << std::endl;

  return true;
}