void Wf_return::setVals(Array2 <dcomplex> & vals ,
                        Array1 <doublevar> &  p) {
  
  // here we extract amplitude and phase, and their gradients and laplacians,
  // from the complex value and its gradient and derivative
  
  is_complex=1;
  cvals=vals;
  int ntype=vals.GetDim(1);
  int nwf=vals.GetDim(0);
  for (int w=0; w< nwf; w++) {
    amp(w,0)=vals(w,0).real();
    phase(w,0)=p(w);
    
    doublevar sum_ii=0;
    doublevar sum_ri=0;
    if (ntype>=4) {
      for (int i=1; i<4; i++) {
        amp(w,i)=vals(w,i).real();
        phase(w,i)=vals(w,i).imag();
        sum_ii+=phase(w,i)*phase(w,i);
        sum_ri+=amp(w,i)*phase(w,i);
      }
    }
    
    if (ntype>=5) {
      amp(w,4)=vals(w,4).real()+sum_ii;
      phase(w,4)=vals(w,4).imag()-2*sum_ri;
    }
  }
  
}
void Wf_return::setVals(Array2 <log_value<doublevar> > & v ) {
  is_complex=0;
  int nfunc=v.GetDim(0);
  int nst=v.GetDim(1);
  Resize(nfunc,nst);
  for(int f=0; f< nfunc; f++) {
    amp(f,0)=v(f,0).logval;
    phase(f,0)=v(f,0).sign<0?pi:0.0;
    for(int s=1; s< nst; s++) {
      amp(f,s)=v(f,s).val();
      phase(f,s)=0.0;
    }
  }
}
示例#3
0
  void playWithHomeTheater() {

    // Create all the parts of the home theatre system
    Amplifier amp("Top-O-Line Amplifier");
    CdPlayer cd("Top-O-Line CD Player", &amp);
    DvdPlayer dvd("Top-O-Line DVD Player", &amp);
    Screen screen("My Theater Screen");
    PopcornPopper popper("My Popcorn Popper");
    Tuner tuner("Top-O-Line AM/FM Tuner", &amp);
    TheaterLights lights("Theater Ceiling Lights");
    Projector projector("Top-O-Line Projector");

    popper.on();  // Turn on the popcorn popper...
    popper.pop(); // and start popping...

    lights.dim(10); // Dim the lights to 10%... 
    
    screen.down();  // Put the screen down...

    projector.on();             // Turn on the projector...
    projector.setInput(&dvd);    // set it to DVD...
    projector.wideScreenMode(); // and put it on wide screen mode for the movie...

    amp.on();                // Turn on the amp...
    amp.setInput(&dvd);       // set it to DVD and...
    amp.setSurroundSound();  // put it into surround sound mode...
    amp.setVolume(11);       // and set the volume to 11...

    dvd.on();                            // Turn on the DVD player...
    dvd.play("Raiders of the lost ark"); // and FINALLY, play the movie!

    // What about shutting everything down again?!
    // How would you play a CD? etc...
  }
示例#4
0
文件: ct.c 项目: EdKeith/core
static A jttayamp(J jt,A w,B nf,A x,A h){A y;B ng=!nf;I j,n;V*v=VAV(h);
 ASSERT(AR(x)<=(nf?v->lr:v->rr),EVRANK);
 switch(v->id){
  case CPLUS:  R tpoly(over(x,one));
  case CMINUS: R tpoly(nf?over(x,num[-1]):over(negate(x),one));
  case CSTAR:  R tpoly(over(zero,x));
  case CDIV:   ASSERT(ng,EVDOMAIN); R tpoly(over(zero,recip(x)));
  case CJDOT:  R tpoly(nf?over(x,a0j1):over(jdot1(x),one));
  case CPOLY:  ASSERT(nf,EVDOMAIN); R tpoly(BOX&AT(x)?poly1(x):x);
  case CHGEOM: ASSERT(nf,EVDOMAIN); RE(j=i0(x)); ASSERT(0<=j,EVDOMAIN);
               y=IX(j);
               R tpoly(divide(hgcoeff(y,h),fact(y)));
  case CBANG:  ASSERT(nf,EVDOMAIN); RE(j=i0(x)); ASSERT(0<=j,EVDOMAIN); 
               R tpoly(divide(poly1(box(iota(x))),fact(x)));
  case CEXP:   if(nf)R eva(x,"(^.x)&^ % !");
               RE(n=i0(x));   
               R 0<=n?tpoly(over(reshape(x,zero),one)):atop(ds(CDIV),amp(h,sc(-n))); 
  case CFIT:   ASSERT(nf&&CPOLY==ID(v->f),EVDOMAIN);
               y=over(x,IX(IC(x)));
               R tpoly(mdiv(df2(x,y,h),atab(CEXP,y,IX(IC(x)))));
  case CCIRCLE:
   switch(i0(x)){
    case 1:    R eval("{&0 1 0 _1@(4&|) % !");
    case -3:   R eval("{&0 1 0 _1@(4&|) % ]");
    case 2:    R eval("{&1 0 _1 0@(4&|) % !");
    case 5:    R eval("2&|    % !");
    case -7:   R eval("2&|    % ]");
    case 6:    R eval("2&|@>: % !");
    case -1:   R eval("(2&|              % ]) * ([: */ (1&+ % 2&+)@(i.@<.&.-:))\"0");
    case -5:   R eval("({&0 1 0 _1@(4&|) % ]) * ([: */ (1&+ % 2&+)@(i.@<.&.-:))\"0");
 }}
 ASSERT(0,EVDOMAIN);
}
示例#5
0
EvtComplex EvtD0gammaDalitz::dalitzKsKK( const EvtDalitzPoint& point ) const
{
  static const EvtDalitzPlot plot( _mKs, _mK, _mK, _mD0 );

  // Defining resonances.
  static EvtDalitzReso a00_980 ( plot, _AC, _BC, _SCALAR, 0.999  , _RBW, .550173, .324, _EtaPic   );
  static EvtDalitzReso phi     ( plot, _AC, _BC, _VECTOR, 1.01943,       .00459319    , _RBW      );
  static EvtDalitzReso a0p_980 ( plot, _AC, _AB, _SCALAR, 0.999  , _RBW, .550173, .324, _EtaPic   );
  static EvtDalitzReso f0_1370 ( plot, _AC, _BC, _SCALAR, 1.350  ,       .265         , _RBW      );
  static EvtDalitzReso a0m_980 ( plot, _AB, _AC, _SCALAR, 0.999  , _RBW, .550173, .324, _EtaPic   );
  static EvtDalitzReso f0_980  ( plot, _AC, _BC, _SCALAR, 0.965  , _RBW, .695   , .165, _PicPicKK );
  static EvtDalitzReso f2_1270 ( plot, _AC, _BC, _TENSOR, 1.2754 ,       .1851        , _RBW      );
  static EvtDalitzReso a00_1450( plot, _AC, _BC, _SCALAR, 1.474  ,       .265         , _RBW      );
  static EvtDalitzReso a0p_1450( plot, _AC, _AB, _SCALAR, 1.474  ,       .265         , _RBW      );
  static EvtDalitzReso a0m_1450( plot, _AB, _AC, _SCALAR, 1.474  ,       .265         , _RBW      );

  // Adding terms to the amplitude with their corresponding amplitude and phase terms.
  EvtComplex amp( 0., 0. ); // Phase space amplitude.
  amp += EvtComplex( 1.0          , 0.0        ) * a00_980 .evaluate( point );
  amp += EvtComplex( -.126314     ,  .188701   ) * phi     .evaluate( point );
  amp += EvtComplex( -.561428     ,  .0135338  ) * a0p_980 .evaluate( point );
  amp += EvtComplex(  .035        , -.00110488 ) * f0_1370 .evaluate( point );
  amp += EvtComplex( -.0872735    ,  .0791190  ) * a0m_980 .evaluate( point );
  amp += EvtComplex( 0.           , 0.         ) * f0_980  .evaluate( point );
  amp += EvtComplex(  .257341     , -.0408343  ) * f2_1270 .evaluate( point );
  amp += EvtComplex( -.0614342    , -.649930   ) * a00_1450.evaluate( point );
  amp += EvtComplex( -.104629     ,  .830120   ) * a0p_1450.evaluate( point );
  amp += EvtComplex( 0.           , 0.         ) * a0m_1450.evaluate( point );

  return 2.8 * amp; // Multiply by 2.8 in order to reuse the same probmax as Ks pi pi.
}
Cepstrum Spectrum_to_Cepstrum_hillenbrand (Spectrum me) {
	try {
		autoNUMfft_Table fftTable;
		// originalNumberOfSamplesProbablyOdd irrelevant
		if (my x1 != 0.0) {
			Melder_throw ("A Fourier-transformable Spectrum must have a first frequency of 0 Hz, not ", my x1, L" Hz.");
		}
		long numberOfSamples = my nx - 1;
		autoCepstrum thee = Cepstrum_create (0.5 / my dx, my nx);
		NUMfft_Table_init (&fftTable, my nx);
		autoNUMvector<double> amp (1, my nx);
		
		for (long i = 1; i <= my nx; i++) {
			amp [i] = my v_getValueAtSample (i, 0, 2);
		}
		NUMfft_forward (&fftTable, amp.peek());
		
		for (long i = 1; i <= my nx; i++) {
			double val = amp[i] / numberOfSamples;// scaling 1/n because ifft(fft(1))= n;
			thy z[1][i] = val * val; // power cepstrum
		}
		return thee.transfer();
	} catch (MelderError) {
		Melder_throw (me, ": not converted to Sound.");
	}
}
示例#7
0
//---------------------------------------------------------------------------
//	@function:
//		CParseHandlerTest::EresUnittest_RunAllNegativeTests
//
//	@doc:
//		Run all negative tests for parsing DXL documents into DXL trees.
//
//---------------------------------------------------------------------------
GPOS_RESULT
CParseHandlerTest::EresUnittest_RunAllNegativeTests()
{
	CAutoMemoryPool amp(CAutoMemoryPool::ElcNone);
	IMemoryPool *pmp = amp.Pmp();

	// loop over all test files
	for (ULONG ulFileNum = 0;
			ulFileNum < GPOS_ARRAY_SIZE(m_rgszNegativeTestsFileNames);
			ulFileNum++)
	{
		GPOS_TRY
		{
			// try running the test for the current file
			EresParseAndSerializePlan(
							pmp,
							m_rgszNegativeTestsFileNames[ulFileNum],
							true /* fValidate */
			);
			// if it does not throw an exception, then it failed
			return GPOS_FAILED;
		}
		GPOS_CATCH_EX(ex)
		{
			// these tests are supposed to throw exceptions, so if
			// the test throws an exception, then it is good
			GPOS_RESET_EX;
		}
		GPOS_CATCH_END;
	}

	return GPOS_OK;
}
示例#8
0
//---------------------------------------------------------------------------
//	@function:
//		CMiniDumperDXLTest::EresUnittest_Load
//
//	@doc:
//		Load a minidump file
//
//---------------------------------------------------------------------------
GPOS_RESULT
CMiniDumperDXLTest::EresUnittest_Load()
{
	CAutoMemoryPool amp(CAutoMemoryPool::ElcExc);
	IMemoryPool *mp = amp.Pmp();
	
	const CHAR *rgszMinidumps[] =
	{
		 "../data/dxl/minidump/Minidump.xml",
	};
	ULONG ulTestCounter = 0;

	GPOS_RESULT eres =
			CTestUtils::EresRunMinidumps
						(
						mp,
						rgszMinidumps,
						1, // ulTests
						&ulTestCounter,
						1, // ulSessionId
						1,  // ulCmdId
						false, // fMatchPlans
						false // fTestSpacePruning
						);
	return eres;

}
示例#9
0
void distortx_node_t::do_process( const render::context_t& context)
{
	if( !expr_.get() || !expr_->isValid())
	{
		image::make_color_bars( image_view());
		return;
	}

	bool thread_safe = true; // while testing
	//bool thread_safe = expr_->isThreadSafe();

	std::string warp_expr = get_value<std::string>( param( expr_param_name()));
	Imath::V2f amp( get_value<Imath::V2f>( param( "amplitude")));
	amp /= context.subsample;

	se_expr_warp_fun f( this, warp_expr, amp, context);

    image_node_t *in  = input_as<image_node_t>( 0);
    image_node_t *msk = input_as<image_node_t>( 1);

    if( msk)
    {
        mask_fun m( msk->const_image_view(), msk->defined());
        masked_warp_fun<se_expr_warp_fun, mask_fun> mf( f, m);

        switch( get_value<int>( param( "borders")))
        {
			case border_black:
				image::warp_bilinear( in->defined(), in->const_image_view(), defined(), image_view(), mf, false, thread_safe);
			break;
	
			case border_tile:
				image::warp_bilinear_tile( in->defined(), in->const_image_view(), defined(), image_view(), mf, false, thread_safe);
			break;
	
			case border_mirror:
				image::warp_bilinear_mirror( in->defined(), in->const_image_view(), defined(), image_view(), mf, false, thread_safe);
			break;
        }
    }
    else
    {
        switch( get_value<int>( param( "borders")))
        {
			case border_black:
				image::warp_bilinear( in->defined(), in->const_image_view(), defined(), image_view(), f, false, thread_safe);
			break;
	
			case border_tile:
				image::warp_bilinear_tile( in->defined(), in->const_image_view(), defined(), image_view(), f, false, thread_safe);
			break;
	
			case border_mirror:
				image::warp_bilinear_mirror( in->defined(), in->const_image_view(), defined(), image_view(), f, false, thread_safe);
			break;
        }
    }
}
示例#10
0
文件: ct.c 项目: EdKeith/core
static A jttcoamp(J jt,A w,B nf,A x,A h){I j;V*v=VAV(h);
 ASSERT(AR(x)<=v->mr,EVRANK);
 switch(v->id){
  case CEXP:   
   if(nf)R amp(logar1(x),ds(CEXP)); break;
  case CHGEOM: 
   ASSERT(nf,EVDOMAIN); RE(j=i0(x)); ASSERT(0<=j,EVDOMAIN);
   R tpoly(hgcoeff(IX(j),h));
 }
 R facit(tayamp(w,nf,x,h));
}
//----------------------------------------------------------------------
void Wf_return::setVals(Array2 <log_value<dcomplex> > & v ) {
  is_complex=1;
  int nfunc=v.GetDim(0);
  int nst=v.GetDim(1);
  Resize(nfunc,nst);
  for(int f=0; f< nfunc; f++) {
    amp(f,0)=v(f,0).logval.real();
    phase(f,0)=v(f,0).logval.imag();
    for(int s=1; s< nst; s++) {
      amp(f,s)=v(f,s).val().real();
      phase(f,s)=v(f,s).val().imag();
    }
    if(nst > 4) {
      doublevar sum_ii=0,sum_ri=0;
      for(int s=1; s< 4; s++) {
        sum_ii+=phase(f,s)*phase(f,s);
        sum_ri+=amp(f,s)*phase(f,s);
      }
      phase(f,4)-=2*sum_ri;
      amp(f,4)+=sum_ii;
    }
    
  }
}
示例#12
0
  void playWithHomeTheaterFacade() {
    // Create all the parts of the home theatre system
    // Not encapsulated or owned by the facade.
    Amplifier amp("Top-O-Line Amplifier");
    CdPlayer cd("Top-O-Line CD Player", &amp);
    DvdPlayer dvd("Top-O-Line DVD Player", &amp);
    Screen screen("My Theater Screen");
    PopcornPopper popper("My Popcorn Popper");
    Tuner tuner("Top-O-Line AM/FM Tuner", &amp);
    TheaterLights lights("Theater Ceiling Lights");
    Projector projector("Top-O-Line Projector");

    HomeTheaterFacade theater(&amp, &tuner, &dvd, &cd, &projector, &lights, &screen, &popper);
    theater.watchMovie("Raiders of the Lost Ark");
    theater.endMovie();
  }
示例#13
0
//---------------------------------------------------------------------------
//	@function:
//		CParseHandlerTest::EresUnittest_ErrSAXParseException
//
//	@doc:
//		Unittest for exception handling during parsing an ill-formed DXL document.
//
//---------------------------------------------------------------------------
GPOS_RESULT
CParseHandlerTest::EresUnittest_ErrSAXParseException()
{
	// create own memory pool
	CAutoMemoryPool amp(CAutoMemoryPool::ElcNone);
	IMemoryPool *mp = amp.Pmp();

	// read DXL file
	CHAR *dxl_string = CDXLUtils::Read(mp, m_rgszXerceTestFileNames[0]);
	
	// function call should throw an exception
	ULLONG plan_id = gpos::ullong_max;
	ULLONG plan_space_size = gpos::ullong_max;
	(void) CDXLUtils::GetPlanDXLNode(mp, dxl_string, CTestUtils::m_szXSDPath, &plan_id, &plan_space_size);

	return GPOS_FAILED;
}
示例#14
0
//---------------------------------------------------------------------------
//	@function:
//		CParseHandlerTest::EresUnittest_ErrSAXParseException
//
//	@doc:
//		Unittest for exception handling during parsing an ill-formed DXL document.
//
//---------------------------------------------------------------------------
GPOS_RESULT
CParseHandlerTest::EresUnittest_ErrSAXParseException()
{
	// create own memory pool
	CAutoMemoryPool amp(CAutoMemoryPool::ElcNone);
	IMemoryPool *pmp = amp.Pmp();

	// read DXL file
	CHAR *szDXL = CDXLUtils::SzRead(pmp, m_rgszXerceTestFileNames[0]);
	
	// function call should throw an exception
	ULLONG ullPlanId = ULLONG_MAX;
	ULLONG ullPlanSpaceSize = ULLONG_MAX;
	(void) CDXLUtils::PdxlnParsePlan(pmp, szDXL, CTestUtils::m_szXSDPath, &ullPlanId, &ullPlanSpaceSize);

	return GPOS_FAILED;
}
示例#15
0
//---------------------------------------------------------------------------
//	@function:
//		CMDAccessorTest::EresUnittest_Negative
//
//	@doc:
//		Test fetching non-existing metadata objects from the MD cache
//
//---------------------------------------------------------------------------
GPOS_RESULT
CMDAccessorTest::EresUnittest_Negative()
{
	CAutoMemoryPool amp(CAutoMemoryPool::ElcNone);
	IMemoryPool *mp = amp.Pmp();
	
	// Setup an MD cache with a file-based provider
	CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
	pmdp->AddRef();
	CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp);
	
	// lookup a non-existing objects
	CMDIdGPDB *pmdidNonExistingObject = GPOS_NEW(mp) CMDIdGPDB(GPOPT_MDCACHE_TEST_OID /* OID */, 15 /* version */, 1 /* minor version */);

	// call should result in an exception
	(void) mda.RetrieveRel(pmdidNonExistingObject);

	pmdidNonExistingObject->Release();
	
	return GPOS_OK;
}
示例#16
0
文件: amp.c 项目: danilopantani/synth
int main(int argc, char *argv[])
{
	float vol = 1.0f;
	int i;

	for (i = 1; i < argc; i++)
	{
		if (!strcmp(argv[i], "-vol") && i+1 < argc)
			vol = atof(argv[++i]);
		else if (!strcmp(argv[i], "-dB") && i+1 < argc)
			vol = pow(10.0f, atof(argv[++i]) / 20.0f);
		else if (!strcmp(argv[i], "-help"))
		{
			fprintf(stderr, "options: -vol multiplicand, -dB dB\n");
			exit(0);
		}
	}

	SET_BINARY_MODE
	amp(vol);
	return 0;
}
示例#17
0
void EvtEtaDalitz::decay( EvtParticle *p){

  p->initializePhaseSpace(getNDaug(),getDaugs());

  EvtVector4R mompi0 = p->getDaug(2)->getP4();
  double masspip = p->getDaug(0)->mass();
  double masspim = p->getDaug(1)->mass();
  double masspi0 = p->getDaug(2)->mass();
  double m_eta = p->mass();

  double y;

  //The decay amplitude coems from Layter et al PRD 7 2565 (1973).

  y=(mompi0.get(0)-masspi0)*(3.0/(m_eta-masspip-masspim-masspi0))-1.0;

  EvtComplex amp(sqrt(1.0-1.07*y),0.0);

  vertex(amp);

  return ;
   
}
示例#18
0
QVector<double> CrustalModel::calculate(const QVector<double> &freq) const
{
    QVector<double> amp(freq.size());
    // Slowness (inverse of the crustal velocity
    QVector<double> slowness(m_velocity.size());

    for (int i = 0; i < slowness.size(); ++i) {
        slowness[i] = 1./m_velocity.at(i);
    }

    // average slowness over a depth range (1/velocity)
    QVector<double> avgSlow(freq.size(), slowness.first());
    // Frequency dependent depth
    QVector<double> depth_f(freq.size(), 0.);

    for (int i = 0; i < freq.size(); ++i) {
        double error = 0;
        int count = 0;

        do {
            ++count;
            depth_f[i] = 1. / (4 * freq.at(i) * avgSlow.at(i));
            const double oldValue = avgSlow.at(i);
            avgSlow[i] = averageValue(m_thickness, slowness, depth_f.at(i));
            error = fabs((oldValue - avgSlow.at(i)) / avgSlow.at(i));
        } while (error > 0.005 && count < 10);
    }

    for (int i = 0; i < freq.size(); ++i) {
        // Average density for the depth range
        const double avgDensity = averageValue(m_thickness, m_density, depth_f.at(i));
        amp[i] = sqrt((m_velocity.at(i) * m_density.at(i)) / (avgDensity / avgSlow.at(i)));
    }

    return amp;
}
示例#19
0
文件: Test_all.cpp 项目: eriser/CSL
void test_Granulator() {
	StaticVariable wave(1);		//not implemented yet
	StaticVariable env(1);		//not implemented yet
	StaticVariable amp(0.2);
	StaticVariable dur(0.07);
	StaticVariable pan(0);
	
	Envelope rate(11,0,30,11,70);
	rate.trigger();
	RandomVariable freq_in1(kNormal, 500, 200, 0, 0);
	Clipper freq(freq_in1, kBoth, 100, 12000);

	Granulator gran(wave, env, rate, amp, freq, dur, pan);

	logMsg("playing granulator...");
	gIO->set_root(gran);
	gIO->open();
	//csl::sleep_usec(2000000);	
	std::cout << "Starting" << endl;
#ifdef RT_IO
	gIO->start();
	csl::sleep_usec(10000000);
#else
	//NOTE: REGULAR START FUNCTION DOESN"T SEEM TO WORK FOR FILEIO
	gIO->start(10);
#endif
	std::cout << "Stopping" << endl;
	gIO->stop();
	std::cout << "Closing" << endl;
	gIO->close();
	std::cout << "Total grains produced 1: " << gran.num_grains << endl;

	logMsg("granulator done.");

	csl::sleep_usec(5000000);
}
示例#20
0
文件: FFT.cpp 项目: dezed/mantid
QString FFT::fftCurve()
{
  int i, i2;
	int n2 = d_n/2;
	std::vector<double> amp(d_n);
	std::vector<double> result(2*d_n);

	if(amp.empty() || result.empty()){
    QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
                        tr("Could not allocate memory, operation aborted!"));
        d_init_err = true;
        return "";
	}

	double df = 1.0/(double)(d_n*d_sampling);//frequency sampling
	double aMax = 0.0;//max amplitude
	QString text;
	if(!d_inverse){
        d_explanation = tr("Forward") + " " + tr("FFT") + " " + tr("of") + " " + d_curve->title().text();
		text = tr("Frequency");

		gsl_fft_real_workspace *work=gsl_fft_real_workspace_alloc(d_n);
		gsl_fft_real_wavetable *real=gsl_fft_real_wavetable_alloc(d_n);

		if(!work || !real){
			QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
                        tr("Could not allocate memory, operation aborted!"));
            d_init_err = true;
			return "";
		}

		gsl_fft_real_transform(d_y, 1, d_n, real,work);
    gsl_fft_halfcomplex_unpack (d_y, result.data(), 1, d_n);

		gsl_fft_real_wavetable_free(real);
		gsl_fft_real_workspace_free(work);
	} else {
        d_explanation = tr("Inverse") + " " + tr("FFT") + " " + tr("of") + " " + d_curve->title().text();
		text = tr("Time");

    gsl_fft_real_unpack (d_y, result.data(), 1, d_n);
		gsl_fft_complex_wavetable *wavetable = gsl_fft_complex_wavetable_alloc (d_n);
		gsl_fft_complex_workspace *workspace = gsl_fft_complex_workspace_alloc (d_n);

		if(!workspace || !wavetable){
			QMessageBox::critical(dynamic_cast<ApplicationWindow *>(parent()), tr("MantidPlot") + " - " + tr("Error"),
                        tr("Could not allocate memory, operation aborted!"));
            d_init_err = true;
			return "";
		}

		gsl_fft_complex_inverse (result.data(), 1, d_n, wavetable, workspace);
		gsl_fft_complex_wavetable_free (wavetable);
		gsl_fft_complex_workspace_free (workspace);
	}

	if (d_shift_order){
		for(i=0; i<d_n; i++){
			d_x[i] = (i-n2)*df;
			int j = i + d_n;
			double aux = result[i];
			result[i] = result[j];
			result[j] = aux;
		}
	} else {
		for(i=0; i<d_n; i++)
			d_x[i] = i*df;
	}

	for(i=0;i<d_n;i++) {
		i2 = 2*i;
		double real_part = result[i2];
		double im_part = result[i2+1];
		double a = sqrt(real_part*real_part + im_part*im_part);
		amp[i]= a;
		if (a > aMax)
			aMax = a;
	}

  ApplicationWindow *app = dynamic_cast<ApplicationWindow *>(parent());
  if (!app) {
    throw std::logic_error("Parent of FFTDialog is not ApplicationWindow as expected.");
  }

	QLocale locale = app->locale();
	int prec = app->d_decimal_digits;

	text += "\t"+tr("Real")+"\t"+tr("Imaginary")+"\t"+ tr("Amplitude")+"\t"+tr("Angle")+"\n";
	for (i=0; i<d_n; i++){
		i2 = 2*i;
		text += locale.toString(d_x[i], 'g', prec)+"\t";
		text += locale.toString(result[i2], 'g', prec)+"\t";
		text += locale.toString(result[i2+1], 'g', prec)+"\t";
		if (d_normalize)
			text += locale.toString(amp[i]/aMax, 'g', prec)+"\t";
		else
			text += locale.toString(amp[i], 'g', prec)+"\t";
		text += locale.toString(atan(result[i2+1]/result[i2]), 'g', prec)+"\n";
	}
  return text;
}
示例#21
0
void EvtD0gammaDalitz::decay( EvtParticle* part )
{
  // Check if the D is from a B+- -> D0 K+- decay with the appropriate model.
  EvtParticle* parent = part->getParent(); // If there are no mistakes, should be B+ or B-.
  if (parent != 0 && EvtDecayTable::getInstance()->getDecayFunc( parent )->getName() == "BTODDALITZCPK" )
  {
    EvtId parId = parent->getId();
    if ( ( parId == _BP ) || ( parId == _BM ) ||
         ( parId == _B0 ) || ( parId == _B0B) )
    {
      _bFlavor = parId;
    }
    else
    {
      reportInvalidAndExit();
    }
  }
  else
  {
    reportInvalidAndExit();
  }

  // Read the D decay parameters from the B decay model.
  // Gamma angle in rad.
  double gamma = EvtDecayTable::getInstance()->getDecayFunc( parent )->getArg( 0 );
  // Strong phase in rad.
  double delta = EvtDecayTable::getInstance()->getDecayFunc( parent )->getArg( 1 );
  // Ratio between B->D0K and B->D0barK
  double rB    = EvtDecayTable::getInstance()->getDecayFunc( parent )->getArg( 2 );

  // Same structure for all of these decays.
  part->initializePhaseSpace( getNDaug(), getDaugs() );
  EvtVector4R pA = part->getDaug( _d1 )->getP4();
  EvtVector4R pB = part->getDaug( _d2 )->getP4();
  EvtVector4R pC = part->getDaug( _d3 )->getP4();

  // Squared invariant masses.
  double mSqAB = ( pA + pB ).mass2();
  double mSqAC = ( pA + pC ).mass2();
  double mSqBC = ( pB + pC ).mass2();

  EvtComplex amp( 1.0, 0.0 );

  // Direct and conjugated amplitudes.
  EvtComplex ampDir;
  EvtComplex ampCnj;

  if ( _isKsPiPi )
  {
    // Direct and conjugated Dalitz points.
    EvtDalitzPoint pointDir( _mKs, _mPi, _mPi, mSqAB, mSqBC, mSqAC );
    EvtDalitzPoint pointCnj( _mKs, _mPi, _mPi, mSqAC, mSqBC, mSqAB );

    // Direct and conjugated amplitudes.
    ampDir = dalitzKsPiPi( pointDir );
    ampCnj = dalitzKsPiPi( pointCnj );
  }
  else
  {
    // Direct and conjugated Dalitz points.
    EvtDalitzPoint pointDir( _mKs, _mK, _mK, mSqAB, mSqBC, mSqAC );
    EvtDalitzPoint pointCnj( _mKs, _mK, _mK, mSqAC, mSqBC, mSqAB );

    // Direct and conjugated amplitudes.
    ampDir = dalitzKsKK( pointDir );
    ampCnj = dalitzKsKK( pointCnj );
  }

  if ( _bFlavor == _BP || _bFlavor == _B0 )
  {
    amp = ampCnj + rB * exp( EvtComplex( 0., delta + gamma ) ) * ampDir;
  }
  else
  {
    amp = ampDir + rB * exp( EvtComplex( 0., delta - gamma ) ) * ampCnj;
  }

  vertex( amp );

  return;

}
示例#22
0
文件: ct.c 项目: EdKeith/core
static F1(jttpoly){A z;
 RZ(w);
 RZ(z=atop(amp(ds(CLBRACE),over(AT(w)&CMPX?w:xco1(w),zero)),amp(tally(w),ds(CMIN))));
 VAV(z)->flag=VTAYFINITE;
 R z;
}
示例#23
0
//---------------------------------------------------------------------------
//	@function:
//		CSubqueryHandlerTest::EresUnittest_SubqueryWithDisjunction
//
//	@doc:
//		Test case of subqueries in a disjunctive tree
//
//---------------------------------------------------------------------------
GPOS_RESULT
CSubqueryHandlerTest::EresUnittest_SubqueryWithDisjunction()
{
	// use own memory pool
	CAutoMemoryPool amp(CAutoMemoryPool::ElcNone);
	IMemoryPool *mp = amp.Pmp();

	// setup a file-based provider
	CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
	pmdp->AddRef();
	CMDAccessor mda(mp, CMDCache::Pcache());
	mda.RegisterProvider(CTestUtils::m_sysidDefault, pmdp);
	
	// install opt context in TLS
	CAutoOptCtxt aoc
					(
					mp,
					&mda,
					NULL,  /* pceeval */
					CTestUtils::GetCostModel(mp)
					);
		
	// create a subquery with const table get expression

	CExpression *pexprOuter = NULL;
	CExpression *pexprInner = NULL;
	CSubqueryTestUtils::GenerateGetExpressions(mp, &pexprOuter, &pexprInner);

	CExpression *pexpr = CSubqueryTestUtils::PexprSelectWithSubqueryBoolOp(mp, pexprOuter, pexprInner, true /*fCorrelated*/, CScalarBoolOp::EboolopOr);
	
	CXform *pxform = CXformFactory::Pxff()->Pxf(CXform::ExfSelect2Apply);

	CWStringDynamic str(mp);
	COstreamString oss(&str);

	oss	<< std::endl << "EXPRESSION:" << std::endl << *pexpr << std::endl;

	CExpression *pexprLogical = (*pexpr)[0];
	CExpression *pexprScalar = (*pexpr)[1];
	oss	<< std::endl << "LOGICAL:" << std::endl << *pexprLogical << std::endl;
	oss	<< std::endl << "SCALAR:" << std::endl << *pexprScalar << std::endl;

	GPOS_TRACE(str.GetBuffer());
	str.Reset();

	CXformContext *pxfctxt = GPOS_NEW(mp) CXformContext(mp);
	CXformResult *pxfres = GPOS_NEW(mp) CXformResult(mp);

	// calling the xform to perform subquery to Apply transformation
	pxform->Transform(pxfctxt, pxfres, pexpr);
	CExpression *pexprResult = pxfres->PexprNext();
	
	oss	<< std::endl << "NEW LOGICAL:" << std::endl << *((*pexprResult)[0]) << std::endl;
	oss	<< std::endl << "RESIDUAL SCALAR:" << std::endl << *((*pexprResult)[1]) << std::endl;

	GPOS_TRACE(str.GetBuffer());
	str.Reset();

	pxfres->Release();
	pxfctxt->Release();
	pexpr->Release();

	return GPOS_OK;
}
示例#24
0
//---------------------------------------------------------------------------
//	@function:
//		CMiniDumperDXLTest::EresUnittest_Basic
//
//	@doc:
//		Test minidumps in case of an exception
//
//---------------------------------------------------------------------------
GPOS_RESULT
CMiniDumperDXLTest::EresUnittest_Basic()
{
	CAutoMemoryPool amp(CAutoMemoryPool::ElcNone);
	IMemoryPool *mp = amp.Pmp();

	CWStringDynamic minidumpstr(mp);
	COstreamString oss(&minidumpstr);
	CMiniDumperDXL mdrs(mp);
	mdrs.Init(&oss);
	
	CHAR file_name[GPOS_FILE_NAME_BUF_SIZE];

	GPOS_TRY
	{
		CSerializableStackTrace serStackTrace;
		
		// read the dxl document
		CHAR *szQueryDXL = CDXLUtils::Read(mp, szQueryFile);

		// parse the DXL query tree from the given DXL document
		CQueryToDXLResult *ptroutput = 
				CDXLUtils::ParseQueryToQueryDXLTree(mp, szQueryDXL, NULL);
		GPOS_CHECK_ABORT;

		CSerializableQuery serQuery(mp, ptroutput->CreateDXLNode(), ptroutput->GetOutputColumnsDXLArray(), ptroutput->GetCTEProducerDXLArray());
		
		// setup a file-based provider
		CMDProviderMemory *pmdp = CTestUtils::m_pmdpf;
		pmdp->AddRef();

		// we need to use an auto pointer for the cache here to ensure
		// deleting memory of cached objects when we throw
		CAutoP<CMDAccessor::MDCache> apcache;
		apcache = CCacheFactory::CreateCache<gpopt::IMDCacheObject*, gpopt::CMDKey*>
					(
					true, // fUnique
					0 /* unlimited cache quota */,
					CMDKey::UlHashMDKey,
					CMDKey::FEqualMDKey
					);

		CMDAccessor::MDCache *pcache = apcache.Value();

		CMDAccessor mda(mp, pcache, CTestUtils::m_sysidDefault, pmdp);

		CSerializableMDAccessor serMDA(&mda);
		
		CAutoTraceFlag atfPrintQuery(EopttracePrintQuery, true);
		CAutoTraceFlag atfPrintPlan(EopttracePrintPlan, true);
		CAutoTraceFlag atfTest(EtraceTest, true);

		COptimizerConfig *optimizer_config = GPOS_NEW(mp) COptimizerConfig
												(
												CEnumeratorConfig::GetEnumeratorCfg(mp, 0 /*plan_id*/),
												CStatisticsConfig::PstatsconfDefault(mp),
												CCTEConfig::PcteconfDefault(mp),
												ICostModel::PcmDefault(mp),
												CHint::PhintDefault(mp),
												CWindowOids::GetWindowOids(mp)
												);

		// setup opt ctx
		CAutoOptCtxt aoc
						(
						mp,
						&mda,
						NULL,  /* pceeval */
						CTestUtils::GetCostModel(mp)
						);

		// translate DXL Tree -> Expr Tree
		CTranslatorDXLToExpr *pdxltr = GPOS_NEW(mp) CTranslatorDXLToExpr(mp, &mda);
		CExpression *pexprTranslated =	pdxltr->PexprTranslateQuery
													(
													ptroutput->CreateDXLNode(),
													ptroutput->GetOutputColumnsDXLArray(),
													ptroutput->GetCTEProducerDXLArray()
													);
		
		gpdxl::ULongPtrArray *pdrgul = pdxltr->PdrgpulOutputColRefs();
		gpmd::CMDNameArray *pdrgpmdname = pdxltr->Pdrgpmdname();

		ULONG ulSegments = GPOPT_TEST_SEGMENTS;
		CQueryContext *pqc = CQueryContext::PqcGenerate(mp, pexprTranslated, pdrgul, pdrgpmdname, true /*fDeriveStats*/);

		// optimize logical expression tree into physical expression tree.

		CEngine eng(mp);

		CSerializableOptimizerConfig serOptConfig(mp, optimizer_config);
		
		eng.Init(pqc, NULL /*search_stage_array*/);
		eng.Optimize();
		
		CExpression *pexprPlan = eng.PexprExtractPlan();
		(void) pexprPlan->PrppCompute(mp, pqc->Prpp());

		// translate plan into DXL
		IntPtrArray *pdrgpiSegments = GPOS_NEW(mp) IntPtrArray(mp);


		GPOS_ASSERT(0 < ulSegments);

		for (ULONG ul = 0; ul < ulSegments; ul++)
		{
			pdrgpiSegments->Append(GPOS_NEW(mp) INT(ul));
		}

		CTranslatorExprToDXL ptrexprtodxl(mp, &mda, pdrgpiSegments);
		CDXLNode *pdxlnPlan = ptrexprtodxl.PdxlnTranslate(pexprPlan, pqc->PdrgPcr(), pqc->Pdrgpmdname());
		GPOS_ASSERT(NULL != pdxlnPlan);
		
		CSerializablePlan serPlan(mp, pdxlnPlan, optimizer_config->GetEnumeratorCfg()->GetPlanId(), optimizer_config->GetEnumeratorCfg()->GetPlanSpaceSize());
		GPOS_CHECK_ABORT;

		// simulate an exception 
		GPOS_OOM_CHECK(NULL);
	}	
	GPOS_CATCH_EX(ex)
	{
		// unless we're simulating faults, the exception must be OOM
		GPOS_ASSERT_IMP
			(
			!GPOS_FTRACE(EtraceSimulateAbort) && !GPOS_FTRACE(EtraceSimulateIOError) && !IWorker::m_enforce_time_slices,
			CException::ExmaSystem == ex.Major() && CException::ExmiOOM == ex.Minor()
			);
		
		mdrs.Finalize();

		GPOS_RESET_EX;

		CWStringDynamic str(mp);
		COstreamString oss(&str);
		oss << std::endl << "Minidump" << std::endl;
		oss << minidumpstr.GetBuffer();
		oss << std::endl;
		
		// dump the same to a temp file
		ULONG ulSessionId = 1;
		ULONG ulCommandId = 1;

		CMinidumperUtils::GenerateMinidumpFileName(file_name, GPOS_FILE_NAME_BUF_SIZE, ulSessionId, ulCommandId, NULL /*szMinidumpFileName*/);

		std::wofstream osMinidump(file_name);
		osMinidump << minidumpstr.GetBuffer();

		oss << "Minidump file: " << file_name << std::endl;

		GPOS_TRACE(str.GetBuffer());
	}
	GPOS_CATCH_END;
	
	// TODO:  - Feb 11, 2013; enable after fixing problems with serializing
	// XML special characters (OPT-2996)
//	// try to load minidump file
//	CDXLMinidump *pdxlmd = CMinidumperUtils::PdxlmdLoad(mp, file_name);
//	GPOS_ASSERT(NULL != pdxlmd);
//	delete pdxlmd;

		
	// delete temp file
	ioutils::Unlink(file_name);
	
	return GPOS_OK;
}
示例#25
0
void sleep_apnea::median_filter (QVector<QVector<double> > &h_freq, QVector<QVector<double> > &h_amp)
{

    QVector<double> amp(window_median);
    QVector<double> freq(window_median);
    int i,j,k,l; double median_amp,median_freq;

    for (i=0;i<h_freq[0].size();i++)
    {
        if (i%window_median==0 && i>0)
        {
            k=(i/window_median)-1;
            //filling arrays
            l=0;
            for (j=0+window_median*k;j<window_median+window_median*k;j++)
            {
                freq[l]=h_freq[1][j];
                amp[l]=h_amp[1][j];
                l++;
            }
            //sorting arrays
            std::sort(freq.begin(),freq.end());
            std::sort(amp.begin(),amp.end());
            //finding median_elements
            if (freq.size()%2!=0)
            {
                median_freq=freq[int((freq.size()-1)/2)];
                median_amp=amp[int((amp.size()-1)/2)];
            }
            else
            {
                median_freq=(freq[int(floor((freq.size()-1)/2))]+ freq[int(floor((freq.size()-1)/2))+1] )*0.5;
                median_amp=(amp[int(floor((amp.size()-1)/2))]+ amp[int(floor((amp.size()-1)/2))+1] )*0.5;
            }
            //writing output arrays
            for (j=0+window_median*k;j<window_median+window_median*k;j++)
            {
                h_freq[1][j]=median_freq;
                h_amp[1][j]=median_amp;
            }
        }
    }

    //loop for last elements
    if (h_freq[0].size()%window_median!=0)
    {
        int start_id=int(floor(h_freq[0].size()/window_median)*window_median);
        int stop_id=h_freq[0].size()-1;
        QVector<double> amp1(stop_id-start_id+1);
        QVector<double> freq1(stop_id-start_id+1);
        //filling arrays
        j=start_id;
        for(i=0;i<freq1.size();i++)
        {
            freq1[i]=h_freq[1][j];
            amp1[i]=h_amp[1][j];
            j++;
        }
        //sorting arrays
        std::sort(freq1.begin(),freq1.end());
        std::sort(amp1.begin(),amp1.end());
        //finding median_elements
        if (freq1.size()%2!=0)
        {
            median_freq=freq1[int((freq1.size()-1)/2)];
            median_amp=amp1[int((amp1.size()-1)/2)];
        }
        else
        {
            median_freq=(freq1[int(floor((freq1.size()-1)/2))]+ freq1[int(floor((freq1.size()-1)/2))+1] )*0.5;
            median_amp=(amp1[int(floor((amp1.size()-1)/2))]+ amp1[int(floor((amp1.size()-1)/2))+1] )*0.5;
        }
        //writing output arrays
        for(i=start_id;i<=stop_id;i++)
        {
            h_freq[1][i]=median_freq;
            h_amp[1][i]=median_amp;
        }
    }

}
示例#26
0
double EvtPropSLPole::calBreitWigner(EvtParticle *pmeson, EvtPoint1D point){

  EvtId mesnum = pmeson->getId(); 
  double _mass = EvtPDL::getMeanMass(mesnum);
  double _width = EvtPDL::getWidth(mesnum);
  double _maxRange = EvtPDL::getMaxRange(mesnum);
  EvtSpinType::spintype mesontype=EvtPDL::getSpinType(mesnum);
  _includeDecayFact=true;
  _includeBirthFact=true;
  _spin = mesontype;
  _blatt = 3.0;

  double maxdelta = 15.0*_width;

  if ( _maxRange > 0.00001 ) {
    _massMax=_mass+maxdelta;
    _massMin=_mass-_maxRange;
  }
  else{
    _massMax=_mass+maxdelta;
    _massMin=_mass-15.0*_width;
  }

  _massMax=_mass+maxdelta;
  if ( _massMin< 0. ) _massMin=0.;


  EvtParticle* par=pmeson->getParent();
  double maxMass=-1.;
  if ( par != 0 ) {
    if ( par->hasValidP4() ) maxMass=par->mass();
    for ( size_t i=0;i<par->getNDaug();i++) {
      EvtParticle *tDaug=par->getDaug(i);
      if ( pmeson != tDaug )
        maxMass-=EvtPDL::getMinMass(tDaug->getId());
    }
  }

  EvtId *dauId=0;
  double *dauMasses=0;
  size_t nDaug = pmeson->getNDaug();
  if ( nDaug > 0) {
     dauId=new EvtId[nDaug];
     dauMasses=new double[nDaug];
     for (size_t j=0;j<nDaug;j++) {
       dauId[j]=pmeson->getDaug(j)->getId();
       dauMasses[j]=pmeson->getDaug(j)->mass();
     }
   }
   EvtId *parId=0;
   EvtId *othDaugId=0;
   EvtParticle *tempPar=pmeson->getParent();
   if (tempPar) {
     parId=new EvtId(tempPar->getId());
     if ( tempPar->getNDaug()==2 ) {
       if ( tempPar->getDaug(0) == pmeson ) othDaugId=new EvtId(tempPar->getDaug(1)->getId());
       else othDaugId=new EvtId(tempPar->getDaug(0)->getId());
     }
   }

  if ( nDaug!=2) return calBreitWignerBasic(maxMass);

  if ( _width< 0.00001) return 1.0;

  //first figure out L - take the lowest allowed.

  EvtSpinType::spintype spinD1=EvtPDL::getSpinType(dauId[0]);
  EvtSpinType::spintype spinD2=EvtPDL::getSpinType(dauId[1]);

  int t1=EvtSpinType::getSpin2(spinD1);
  int t2=EvtSpinType::getSpin2(spinD2);
  int t3=EvtSpinType::getSpin2(_spin);

  int Lmin=-10;

  // allow for special cases.
  if (Lmin<-1 ) {

    //There are some things I don't know how to deal with
    if ( t3>4) return calBreitWignerBasic(maxMass);
    if ( t1>4) return calBreitWignerBasic(maxMass);
    if ( t2>4) return calBreitWignerBasic(maxMass);

    //figure the min and max allowwed "spins" for the daughters state
    Lmin=std::max(t3-t2-t1,std::max(t2-t3-t1,t1-t3-t2));
    if (Lmin<0) Lmin=0;
    assert(Lmin==0||Lmin==2||Lmin==4);
  }

  //double massD1=EvtPDL::getMeanMass(dauId[0]);
  //double massD2=EvtPDL::getMeanMass(dauId[1]);
  double massD1=dauMasses[0];
  double massD2=dauMasses[1];

  // I'm not sure how to define the vertex factor here - so retreat to nonRel code.
  if ( (massD1+massD2)> _mass ) return  calBreitWignerBasic(maxMass);

  //parent vertex factor not yet implemented
  double massOthD=-10.;
  double massParent=-10.;
  int birthl=-10;
  if ( othDaugId) {
    EvtSpinType::spintype spinOth=EvtPDL::getSpinType(*othDaugId);
    EvtSpinType::spintype spinPar=EvtPDL::getSpinType(*parId);

    int tt1=EvtSpinType::getSpin2(spinOth);
    int tt2=EvtSpinType::getSpin2(spinPar);
    int tt3=EvtSpinType::getSpin2(_spin);

    //figure the min and max allowwed "spins" for the daughters state
    if ( (tt1<=4) && ( tt2<=4) ) {
      birthl=std::max(tt3-tt2-tt1,std::max(tt2-tt3-tt1,tt1-tt3-tt2));
      if (birthl<0) birthl=0;

      massOthD=EvtPDL::getMeanMass(*othDaugId);
      massParent=EvtPDL::getMeanMass(*parId);

    }

  }
  double massM=_massMax;
  if ( (maxMass > -0.5) && (maxMass < massM) ) massM=maxMass;

  //special case... if the parent mass is _fixed_ we can do a little better
  //and only for a two body decay as that seems to be where we have problems

  // Define relativistic propagator amplitude

  EvtTwoBodyVertex vd(massD1,massD2,_mass,Lmin/2);
  vd.set_f(_blatt);
  EvtPropBreitWignerRel bw(_mass,_width);
  EvtMassAmp amp(bw,vd);
//  if ( _fixMassForMax) amp.fixUpMassForMax();
//  else std::cout << "problem problem\n";
  if ( _includeDecayFact) {
    amp.addDeathFact();
    amp.addDeathFactFF();
  }
  if ( massParent>-1.) {
    if ( _includeBirthFact ) {

      EvtTwoBodyVertex vb(_mass,massOthD,massParent,birthl/2);
      amp.setBirthVtx(vb);
      amp.addBirthFact();
      amp.addBirthFactFF();
    }
  }

  EvtAmpPdf<EvtPoint1D> pdf(amp);

  double ampVal = sqrt(pdf.evaluate(point));

  if ( parId) delete parId;
  if ( othDaugId) delete othDaugId;
  if ( dauId) delete [] dauId;
  if ( dauMasses) delete [] dauMasses;

  return ampVal;
 
}