/** @note Because of the virtual public inheritance, we create the Pdf
      baseclass ourselves
  */
  CondGausAddNoise::CondGausAddNoise(const Gaussian& additiveNoise,
				     int num_conditional_arguments)
    : AnalyticConditionalGaussian(additiveNoise.DimensionGet(),
			  num_conditional_arguments)
    , _additiveNoise_Mu   (additiveNoise.ExpectedValueGet())
    , _additiveNoise_Sigma(additiveNoise.CovarianceGet())
  {}
Пример #2
0
void SumFactor::_internal_update(
    Variable* var,
    std::vector<Gaussian*> y,
    std::vector<Gaussian*> fy,
    std::vector<double>* a) {

    double sum_pi = 0.0, sum_tau = 0.0, new_pi, new_tau, da;
    unsigned int i = 0, size = a->size();
    Gaussian gy, gfy;

    for (i = 0; i < size; ++i) {
        da = (*a)[i];
        gy = *y[i];
        gfy = *fy[i];

        sum_pi = sum_pi + ((da * da) / (gy.pi - gfy.pi));
        sum_tau = sum_tau + (da * (gy.tau - gfy.tau) / (gy.pi - gfy.pi));
    }

    new_pi = 1.0 / sum_pi;
    new_tau = new_pi * sum_tau;

    Gaussian* gaussian = new Gaussian();
    gaussian->init_pi_tau(new_pi, new_tau);
    var->update_message(this, gaussian);
}
Пример #3
0
//----------------------------------------------------------------------------------------------------------------------  
void SMCEnvironmentViz::drawGaussian(const Gaussian& g) const
{
  const int numPoints = 50;
  ci::Vec2f start, end;
  
  // Three sigmas cover approx. 99% of the gaussian
  float a = -3.0 * g.getW();
  float inc = 6.0 * g.getW() / numPoints;
  
  ci::Path2d path;
  path.moveTo(g.getPointAt(a));
  for(int i = 0; i < numPoints; ++i)
  {
    end = g.getPointAt((a+inc));
    path.lineTo(end);
    a += inc;
  }
  path.close();
  
  glColor4f(0.5,0.5,0.5,0.25);
  glDisable(GL_CULL_FACE);
  glDisable(GL_DEPTH_TEST);
  ci::gl::drawSolid(path);
  glEnable(GL_CULL_FACE);
  glEnable(GL_DEPTH_TEST);
}
Пример #4
0
    bool is_approx(const Gaussian<OtherVariate>& other)
    {


        return fl::are_similar(mean(), other.mean()) &&
               fl::are_similar(covariance(), other.covariance());
    }
Пример #5
0
// load the HMM from a file
void HMMState::load(FileInput &file, unsigned char iEstimationMethod) {

	// phonetic symbol
	char strPhone[MAX_PHONETIC_SYMBOL_LENGTH+1];	
	IOBase::readBytes(file.getStream(),reinterpret_cast<char*>(strPhone),MAX_PHONETIC_SYMBOL_LENGTH+1);
	m_iPhone = m_phoneSet->getPhoneIndex(strPhone);
	assert(m_iPhone != UCHAR_MAX);
	
	// state
	IOBase::read(file.getStream(),&m_iState);
	assert(m_iState < NUMBER_HMM_STATES);
	
	// within word position (DEPRECATED)
	IOBase::read(file.getStream(),&m_iPosition);
	
	// Gaussian components
	int iGaussianComponents = -1;
	IOBase::read(file.getStream(),&iGaussianComponents);
	for(int iGaussian = 0 ; iGaussian < iGaussianComponents ; ++iGaussian) {
	
		Gaussian *gaussian = new Gaussian(m_iDim,m_iCovarianceModeling);	
		
		IOBase::read(file.getStream(),&gaussian->weight());
		gaussian->mean().readData(file.getStream());		
		if (m_iCovarianceModeling == COVARIANCE_MODELLING_TYPE_DIAGONAL) {
			gaussian->covarianceDiag().readData(file.getStream());
		} else {
			gaussian->covarianceFull().readData(file.getStream());
		}	
		m_gaussianMixture->addGaussianComponent(gaussian);
	}
}
Пример #6
0
// store the HMM into a file
void HMMState::store(FileOutput &file) {
	
	// phonetic symbol
	char strPhone[MAX_PHONETIC_SYMBOL_LENGTH+1];
	memset(strPhone,0,MAX_PHONETIC_SYMBOL_LENGTH+1);
	strcpy(strPhone,m_phoneSet->getStrPhone(m_iPhone));	
	IOBase::writeBytes(file.getStream(),reinterpret_cast<char*>(strPhone),MAX_PHONETIC_SYMBOL_LENGTH+1);
	
	// state
	IOBase::write(file.getStream(),m_iState);
	
	// within word position (DEPRECATED)
	IOBase::write(file.getStream(),m_iPosition);

	// Gaussian components
	int iGaussianComponents = m_gaussianMixture->getNumberComponents();
	IOBase::write(file.getStream(),iGaussianComponents);
	for(int iGaussian = 0 ; iGaussian < iGaussianComponents ; ++iGaussian) {
		Gaussian *gaussian = (*m_gaussianMixture)(iGaussian); 
		IOBase::write(file.getStream(),gaussian->weight());
		gaussian->mean().writeData(file.getStream());
		if (m_iCovarianceModeling == COVARIANCE_MODELLING_TYPE_DIAGONAL) {
			gaussian->covarianceDiag().writeData(file.getStream());
		} else {
			gaussian->covarianceFull().writeData(file.getStream());
		}
	}
}
Пример #7
0
void OpenCLExecuter::ocl_filterGaussian_init(float sigma, float size)
{
	Gaussian gauss;
	gauss.sigma = sigma;
	gauss.size = size;
	filter_width = (size-1)/2.0;
	filter_kernel = gauss.gaussianmask1Df(gauss.sigma, gauss.size);
}
Пример #8
0
void testGaussianNumerics(){
  
  std::cout.precision(16);
  std::cout << std::scientific;
    
  Gaussian g = Gaussian(5, 1);
  for(unsigned i = 0; i < 100; i++){
    std::cout << i << ": L: " << g.likelihood((fracfloat_t)i) << " -LL: " << (-INV_LN_2 * log(g.likelihood(i))) << ", S: " << g.surprisal((fracfloat_t)i) << std::endl;
  }
}
Пример #9
0
void GMMfitData::defaultAonly(Gaussian &g)
{
    Vector2d mu;
    mu<< 1.0, 0.1;
    g.setMu(mu);

    Matrix2d sigma;
    sigma<< 0.020,   -0.001,
           -0.001,    0.005;
    g.setSigma(sigma);
}
Пример #10
0
void GMMfitData::defaultDonly(Gaussian &g)
{
    Vector2d mu;
    mu<< 0.0, 0.98;
    g.setMu(mu);

    Matrix2d sigma;
    sigma<< 0.0012,    0.0000,
            0.0000,    0.0015;
    g.setSigma(sigma);
}
Пример #11
0
void GMMfitData::defaultLowFRET(Gaussian &g)
{
    Vector2d mu;
    mu<< 0.15, 0.5;
    g.setMu(mu);

    Matrix2d sigma;
    sigma<< 0.050,    0.000,
            0.000,    0.020;
    g.setSigma(sigma);
}
Пример #12
0
void LikelihoodFactor::update_mean() {
    Gaussian x = *this->value->value;
    Gaussian fx = *this->value->get_message(this);
    double a = 1.0 / (1.0 + this->variance * (x.pi - fx.pi));

    Gaussian* gaussian = new Gaussian();
    gaussian->init_pi_tau(
        a * (x.pi - fx.pi),
        a * (x.tau - fx.tau)
    );
    this->mean->update_message(this, gaussian);
}
void vwcgauss
(const RealArray& energy, const RealArray& parameter, 
 /*@unused@*/ int spectrum, RealArray& flux, /*@unused@*/ RealArray& fluxError,
 /*@unused@*/ const string& init)
{
  fluxError.resize (0);
  Real LineEnergy, Sigma;
  vwcgaussProcessParameter (parameter, LineEnergy, Sigma);
  Gaussian G (energy, LineEnergy, Sigma);
  G.getFlux (flux);
  return;
}
Пример #14
0
void Test::RunCannyTest(const RGBImage* in) {
	Gaussian smoother;
	Sobel sobel;
	Canny canny;
	StudentPreProcessing converter;

	double sigma = 1.6;
	int kernelSize = 5;

	// Convert RGB to Intensity
	IntensityImage* grey = ImageFactory::newIntensityImage(in->getWidth(), in->getHeight());
	grey = converter.stepToIntensityImage(*in);

	BaseTimer timer;
	int total = 0;
	for (int i = 0; i < 10; ++i) {
		timer.start();

		/* Start of Canny */

		// 1. Smooth Intensity with Gaussian
		IntensityImage* gaussian = ImageFactory::newIntensityImage(in->getWidth() - kernelSize, in->getHeight() - kernelSize);
		smoother.smoothImage(grey, gaussian, sigma, kernelSize);

		// 2. Find edges with Sobel (convolve X and Y separately for Canny)
		int sobelKernelSize = 3;
		IntensityImage* sobelX = ImageFactory::newIntensityImage(gaussian->getWidth() - sobelKernelSize, gaussian->getHeight() - sobelKernelSize);
		IntensityImage* sobelY = ImageFactory::newIntensityImage(gaussian->getWidth() - sobelKernelSize, gaussian->getHeight() - sobelKernelSize);
		sobel.filterXY(gaussian, sobelX, sobelY);

		// 3. Apply non-maximum suppresion
		IntensityImage* nonMaxSuppression = ImageFactory::newIntensityImage(sobelX->getWidth(), sobelX->getHeight());
		canny.nonMaximumSurpression(sobelX, sobelY, nonMaxSuppression);

		// 4. Apply hysteresis threshold
		IntensityImage* hysteresisThreshold = ImageFactory::newIntensityImage(sobelX->getWidth(), sobelX->getHeight());
		canny.threshold(nonMaxSuppression, hysteresisThreshold, 60, 70);

		timer.stop();
		std::cout << timer.elapsedMilliSeconds() << " ms" << std::endl;
		total += timer.elapsedMilliSeconds();
		timer.reset();

		if (i == 9)
			ImageIO::saveIntensityImage(*hysteresisThreshold, ImageIO::getDebugFileName("Canny.png"));
	}
	std::cout << "Average time per Canny edge detection: " << (total / 10) << " ms" << std::endl;
	std::cout << "Press the X in the console window to exit program" << std::endl;
}
Пример #15
0
/**
 * Create a time series of input data.
 *
 * Description:\n
 * 	Creates a time series of complex floats representing a signal at
 * 	a given frequency.
 */
ComplexFloat32 *
createTdData(float64_t fMHz, float64_t driftHz, int32_t samples,
		float64_t noise)
{
	size_t size = samples * sizeof(ComplexFloat32);
	ComplexFloat32 *td = static_cast<ComplexFloat32 *> (fftwf_malloc(size));
	float64_t dfMHz = fMHz - centerFreqMHz;
	float64_t widthMHz = subchannels * subchannelWidthMHz;
	Gaussian gen;
	// no noise, just signal
	gen.setup(0, widthMHz, noise);
	gen.addCwSignal(dfMHz, driftHz, 1);
	gen.getSamples(td, samples);
	return (td);
}
Пример #16
0
    bool is_approx(const Gaussian<OtherVariate>& other,
                   Real eps = 1.e-9,
                   bool scale_with_size = false)
    {
        Real eps_mean = eps;
        Real eps_cov = eps;

        if (scale_with_size)
        {
            eps_mean *= mean().size();
            eps_cov *= covariance().size();
        }

        return fl::are_similar(mean(), other.mean(), eps_mean) &&
               fl::are_similar(covariance(), other.covariance(), eps_cov);
    }
  // constructor
  NonLinearAnalyticConditionalGaussian_Ginac::NonLinearAnalyticConditionalGaussian_Ginac
  (const GiNaC::matrix& func,
   const vector<GiNaC::symbol>& u,
   const vector<GiNaC::symbol>& x,
   const Gaussian& additiveNoise,
   const vector<GiNaC::symbol>& cond )
    :AnalyticConditionalGaussianAdditiveNoise(additiveNoise,3),
     func_sym        (func),
     cond_sym        (cond),
     u_sym           (u),
     x_sym           (x),
     cond_size       (cond_sym.size()),
     u_size          (u_sym.size()),
     x_size          (x_sym.size()),
     func_size       (func_sym.rows()),
     dfunc_dcond     (cond_size),
     dfunc_dx        (x_size)
  {
    // test for consistent input
    assert (func_sym.cols() == 1);
    assert (additiveNoise.DimensionGet() == cond_size);

    // derive func to cond
    for (unsigned int i=0; i < cond_size; i++)
      dfunc_dcond[i] = func_sym.diff(cond_sym[i]);

    // derive func to x
    for (unsigned int i=0; i < x_size; i++)
      dfunc_dx[i] = func_sym.diff(x_sym[i]);
  }
Пример #18
0
 /**
  * Generate next point
  * @param n space dimensionality
  * @param radius sphere radius
  * @param center sphere center (null for 0)
  * @param x resulting vector point
  */
 static void nextPoint(int n, double radius, double * center, double* x) {
   double norm;
   Gaussian gauss;
   gauss.setSeqLen(n);
   norm = 0.;
   for(int j = 0; j < n; j ++) {
     x[j] = gauss.getRand();
     norm += x[j] * x[j];;
   }
   double a;
   a = radius / sqrt(norm);
   for(int j = 0; j < n; j ++) {
     x[j] *= a;
   }
   if(center) {
     for(int j = 0; j < n; j ++) {
       x[j] += center[j];
     }
   }
 }
Пример #19
0
// estimate the parameters of the given HMM-state
void MAPEstimator::estimateParameters(HMMState *hmmState, Accumulator **accumulators, float fPriorKnowledgeWeight) {

	// (1) update the mean of each Gaussian component
	for(unsigned int g = 0 ; g < hmmState->getMixture().getNumberComponents() ; ++g) {
	
		Gaussian *gaussian = hmmState->getMixture()(g);
		Accumulator *accumulator = accumulators[g];
		// if there occupation for this component?
		if (accumulator == NULL) {
			continue;
		}
		
		// mean (needs to be computed first in the case of full covariance)
		gaussian->mean().mul(fPriorKnowledgeWeight);
		gaussian->mean().add(accumulator->getObservation());
		gaussian->mean().mul((float)(1.0f/(fPriorKnowledgeWeight+accumulator->getOccupation())));
	}	

	assert(hmmState->getMixture().getNumberComponents() > 0);
}
Пример #20
0
void TruncateFactorDraw::update() {
    Gaussian* x = this->variable->value;
    Gaussian* fx = this->variable->get_message(this);

    double c, d, sqrt_c, V, W, t, e, mW;
    c = x->pi - fx->pi;
    d = x->tau = fx->tau;
    sqrt_c = sqrt(c);

    t = d / sqrt_c;
    e = epsilon * sqrt_c;

    V = Vdraw(t, e);
    W = Wdraw(t, e);
    mW = 1.0 - W;

    Gaussian* gaussian = new Gaussian();
    gaussian->init_pi_tau(c / mW, (d + sqrt_c * V) / mW);
    this->variable->update_value(this, gaussian);
}
Пример #21
0
void testDifferentialEntropy(){
  std::cout << "Testing Differential Entropy." << std::endl;
  
  fracfloat_t samples[DE_TEST_SIZE];
  
  std::default_random_engine generator;
  std::normal_distribution<fracfloat_t> distributions[DISTSIZE];
  
  distributions[0] = std::normal_distribution<fracfloat_t>(0.0,1.0);
  distributions[1] = std::normal_distribution<fracfloat_t>(0.1,4.0);
  distributions[2] = std::normal_distribution<fracfloat_t>(2.0,1.0);
  distributions[3] = std::normal_distribution<fracfloat_t>(5.0,8.0);
  
  
  for(unsigned i = 0; i < DE_TEST_SIZE; i++){
    samples[i] = distributions[i % DISTSIZE](generator);
  }
  
  Gaussian g = Gaussian(samples, DE_TEST_SIZE);
  MultiGaussian mg = MultiGaussian::fitGaussianKernel(samples, DE_TEST_SIZE, (unsigned)sqrt(DE_TEST_SIZE));
  
  fracfloat_t supportStart = min<fracfloat_t>(samples, DE_TEST_SIZE) * 2;
  fracfloat_t supportEnd = max<fracfloat_t>(samples, DE_TEST_SIZE) * 2;
  
  std::cout << "Gaussian: " << g << std::endl;
  std::cout << "Multi Gaussian: " << mg << std::endl;
  
  std::cout << "Integral gaussian approximation: " << g.integrate(supportStart, supportEnd, 1000) << std::endl;
  std::cout << "Integral multigaussian approximation: " << mg.integrate(supportStart, supportEnd, 1000) << std::endl;
  std::cout << "Integral 10: " << mg.approximateDifferentialEntropyFromIntegral(supportStart, supportEnd, 10) << std::endl;
  std::cout << "Integral 100: " << mg.approximateDifferentialEntropyFromIntegral(supportStart, supportEnd, 100) << std::endl;
  std::cout << "Integral 1000: " << mg.approximateDifferentialEntropyFromIntegral(supportStart, supportEnd, 1000) << std::endl;
  std::cout << "Distribution Trick:      " << mg.approximateDifferentialEntropyFromSamples(Array<fracfloat_t>(samples, DE_TEST_SIZE / 1)) << std::endl;
  std::cout << "Distribution Trick 1/2:  " << mg.approximateDifferentialEntropyFromSamples(Array<fracfloat_t>(samples, DE_TEST_SIZE / 2)) << std::endl;
  std::cout << "Distribution Trick 1/4:  " << mg.approximateDifferentialEntropyFromSamples(Array<fracfloat_t>(samples, DE_TEST_SIZE / 4)) << std::endl;
  std::cout << "Distribution Trick 1/8:  " << mg.approximateDifferentialEntropyFromSamples(Array<fracfloat_t>(samples, DE_TEST_SIZE / 8)) << std::endl;
  std::cout << "Distribution Trick 1/16: " << mg.approximateDifferentialEntropyFromSamples(Array<fracfloat_t>(samples, DE_TEST_SIZE / 16)) << std::endl;
  
}
Пример #22
0
Scalar minDistanceSquared(
  const Gaussian<Scalar, NDims>& model,
  const Matrix<Scalar, NDims, Dynamic>& bag,
  int* index
) {
  Scalar minDistance = numeric_limits<Scalar>::infinity();
  int minIndex = -1;
  for (int p = 0; p < bag.cols(); p++) {
    Matrix<Scalar, NDims, 1> point(bag.col(p));
    Scalar distance = model.distanceSquared(point);
    if (distance < minDistance) {
      minDistance = distance;
      minIndex = p;
    }
  }
  if (index) {
    *index = minIndex;
  }
  return minDistance;
}
Пример #23
0
void TrueSkill::adjust_players(std::vector<Player*> players) {
    Constants constants;

    std::sort(players.begin(), players.end(), player_sorter());

    std::vector<Variable*> ss, ps, ts, ds;
    unsigned int i = 0, size = players.size();
    double gammasqr = constants.GAMMA * constants.GAMMA,
           betasqr = constants.BETA * constants.BETA;

    for (i = 0; i < size; ++i) {
        ss.push_back(new Variable());
        ps.push_back(new Variable());
        ts.push_back(new Variable());
    }

    for (i = 0; i < size - 1; ++i) {
        ds.push_back(new Variable());
    }

    std::vector<PriorFactor*> skill;
    for (i = 0; i < size; ++i) {
        Player* pl = players[i];
        Variable* s = ss[i];
        Gaussian* gaussian = new Gaussian();
        gaussian->init_mu_sigma(pl->mu, sqrt((pl->sigma * pl->sigma) + gammasqr));
        skill.push_back(new PriorFactor(s, gaussian));
    }

    std::vector<LikelihoodFactor*> skill_to_perf;
    for (i = 0; i < size; ++i) {
        Variable* s = ss[i];
        Variable* p = ps[i];
        skill_to_perf.push_back(new LikelihoodFactor(s, p, betasqr));
    }

    std::vector<SumFactor*> perf_to_team;
    for (i = 0; i < size; ++i) {
        std::vector<Variable*>* p = new std::vector<Variable*>();
        std::vector<double>* c = new std::vector<double>;
        p->push_back(ps[i]);
        c->push_back(1.0);
        perf_to_team.push_back(new SumFactor(ts[i], p, c));
    }

    std::vector<SumFactor*> team_diff;
    for (i = 0; i < size - 1; ++i) {
        std::vector<Variable*>* p = new std::vector<Variable*>();
        p->push_back(ts[i]);
        p->push_back(ts[i + 1]);
        std::vector<double>* c = new std::vector<double>;
        c->push_back(1.0);
        c->push_back(-1.0);
        team_diff.push_back(new SumFactor(ds[i], p, c));
    }

    std::vector<TruncateFactor*> trunc;
    for (i = 0; i < size - 1; ++i) {
        TruncateFactor* tf;
        if (players[i]->rank == players[i + 1]->rank) {
            tf = new TruncateFactorDraw(ds[i], constants.EPSILON);
        } else {
            tf = new TruncateFactorWin(ds[i], constants.EPSILON);
        }
        trunc.push_back(tf);
    }

    for(std::vector<PriorFactor*>::iterator it = skill.begin(); it != skill.end(); ++it) {
        (*it)->start();
    }

    for(std::vector<LikelihoodFactor*>::iterator it = skill_to_perf.begin(); it != skill_to_perf.end(); ++it) {
        (*it)->update_value();
    }

    for(std::vector<SumFactor*>::iterator it = perf_to_team.begin(); it != perf_to_team.end(); ++it) {
        (*it)->update_sum();
    }

    for (i = 0; i < 5; ++i) {
        for(std::vector<SumFactor*>::iterator it = team_diff.begin(); it != team_diff.end(); ++it) {
            (*it)->update_sum();
        }

        for(std::vector<TruncateFactor*>::iterator it = trunc.begin(); it != trunc.end(); ++it) {
            (*it)->update();
        }

        for(std::vector<SumFactor*>::iterator it = team_diff.begin(); it != team_diff.end(); ++it) {
            (*it)->update_term(0);
            (*it)->update_term(1);
        }
    }

    for(std::vector<SumFactor*>::iterator it = perf_to_team.begin(); it != perf_to_team.end(); ++it) {
        (*it)->update_term(0);
    }

    for(std::vector<LikelihoodFactor*>::iterator it = skill_to_perf.begin(); it != skill_to_perf.end(); ++it) {
        (*it)->update_mean();
    }

    for (i = 0; i < size; ++i) {
        players[i]->mu = ss[i]->value->get_mu();
        players[i]->sigma = ss[i]->value->get_sigma();
    }

    while(!skill.empty()) {
        delete skill.back();
        skill.pop_back();
    }

    while(!skill_to_perf.empty()) {
        delete skill_to_perf.back();
        skill_to_perf.pop_back();
    }

    while(!perf_to_team.empty()) {
        delete perf_to_team.back();
        perf_to_team.pop_back();
    }

    while(!team_diff.empty()) {
        delete team_diff.back();
        team_diff.pop_back();
    }

    while(!trunc.empty()) {
        delete trunc.back();
        trunc.pop_back();
    }

    while(!ss.empty()) {
        delete ss.back();
        ss.pop_back();
    }

    while(!ts.empty()) {
        delete ts.back();
        ts.pop_back();
    }

    while(!ds.empty()) {
        delete ds.back();
        ds.pop_back();
    }

    while(!ps.empty()) {
        delete ps.back();
        ps.pop_back();
    }
}
Пример #24
0
bool Gaussian :: operator<(const Gaussian& gaussian) const
{
    return (get_sort_parameter() > gaussian.get_sort_parameter());
}
Пример #25
0
void ClauseAllocator::updateAllOffsetsAndPointers(
    Solver* solver
    , const vector<ClOffset>& offsets
) {
    //Must be at toplevel, otherwise propBy reset will not work
    //and also, detachReattacher will fail
    assert(solver->decisionLevel() == 0);

    //We are at decision level 0, so we can reset all PropBy-s
    for (VarData& vdata: solver->varData) {
        vdata.reason = PropBy();
        //vdata.level = 0;
    }

    //Detach long clauses
    CompleteDetachReatacher detachReattach(solver);
    detachReattach.detach_nonbins_nontris();

    #ifdef USE_GAUSS
    for(size_t i = 0; i < solver->gauss_matrixes.size(); i++) {
        Gaussian* g = solver->gauss_matrixes[i];
        g->assert_clauses_toclear_is_empty();
    }
    #endif

    //Make sure all non-freed clauses were accessible from solver
    const size_t origNumClauses =
        solver->longIrredCls.size() + solver->longRedCls.size();
    if (origNumClauses != offsets.size()) {
        std::cerr
        << "ERROR: Not all non-freed clauses are accessible from Solver"
        << endl
        << " This usually means that a clause was not freed, i.e. a mem leak"
        << endl
        << " no. clauses accessible from solver: " << origNumClauses
        << endl
        << " no. clauses non-freed: " << offsets.size()
        << endl;

        assert(origNumClauses == offsets.size());
        std::exit(-1);
    }

    //Clear clauses
    solver->longIrredCls.clear();
    solver->longRedCls.clear();

    //Add back to the solver the correct red & irred clauses
    for(auto offset: offsets) {
        Clause* cl = ptr(offset);
        assert(!cl->freed());

        //Put it in the right bucket
        if (cl->red()) {
            solver->longRedCls.push_back(offset);
        } else {
            solver->longIrredCls.push_back(offset);
        }
    }

    //Finally, reattach long clauses
    detachReattach.reattachLongsNoClean();
}
Пример #26
0
int
main(int argc, char **argv)
{
	parseArgs(argc, argv);

   if (beam)
      channel = 0;
	sndX = new MCSend(channel, mcPortX+channel, mcAddr);
	sndY = new MCSend(channel, mcPortY+channel, mcAddr);

	/**
	* initialize the sample generators
	*/
	genX.setup(seedX, bandwidth, power);
	genY.setup(seedY, bandwidth, power);
	/**
	* if we're writing to output, open the file
	*/
	if (packetFile.length())
		openFile(packetFile);

	if (beam) {
		pkt = new BeamPacket(source, channel);
		xPkt = new BeamPacket(source, channel);
		yPkt = new BeamPacket(source, channel);
		ATADataPacketHeader hdr = pkt->getHeader();
		complex<float> val(1, 1);
		for (uint32_t i = 0; i < hdr.len; ++i) {
			pkt->putSample(i, val);
			xPkt->putSample(i, val);
			yPkt->putSample(i, val);
		}
		/**
		* send packets with no valid bit to reset Channelizer
		*/
		createPackets(genX, genY, *xPkt, *yPkt);
		sendPackets(*xPkt, *yPkt);
	}
	else {
		pkt = new ChannelPacket(source, channel);
		xPkt = new ChannelPacket(source, channel);
		yPkt = new ChannelPacket(source, channel);
		ATADataPacketHeader hdr = pkt->getHeader();
		complex<float> val(1, 1);
		for (uint32_t i = 0; i < hdr.len; ++i) {
			pkt->putSample(i, val);
			xPkt->putSample(i, val);
			yPkt->putSample(i, val);
		}
	}

	//
	// set the valid flag for all remaining packets
	//
	data_valid = ATADataPacketHeader::DATA_VALID;

	//
	// add signals
	//
	for (PacketSigList::iterator p = signals.begin(); p != signals.end(); ++p) {
		PacketSig sig = *p;
		if (sig.tOff == 0.0)
		{
			if (sig.pol == ATADataPacketHeader::XLINEAR ||
					sig.pol ==  ATADataPacketHeader::BOTH )
						genX.addCwSignal(sig.freq, sig.drift, sig.snr);
			if (sig.pol == ATADataPacketHeader::YLINEAR ||
					sig.pol ==  ATADataPacketHeader::BOTH )
						genY.addCwSignal(sig.freq, sig.drift, sig.snr);
		}
		else
		{
			if (sig.pol == ATADataPacketHeader::XLINEAR ||
					sig.pol ==  ATADataPacketHeader::BOTH )
						genX.addPulseSignal(sig.freq, sig.drift, sig.snr,
							sig.tStart, sig.tOn, sig.tOff);
			if (sig.pol == ATADataPacketHeader::YLINEAR ||
					sig.pol ==  ATADataPacketHeader::BOTH )
						genY.addPulseSignal(sig.freq, sig.drift, sig.snr,
							sig.tStart, sig.tOn, sig.tOff);
		}
	}

	gettimeofday(&start, NULL);
	//
	// now create and send packets at an interval or
	// 	continuously
	//
	if (alarmInterval)
		frameAlarm.set(&alarmHandler, alarmInterval, alarmInterval);
	else
		fullThrottle();

	while (1)
		;
}
Пример #27
0
				Perturbation(const Gaussian & p) :
					Gaussian(p), x_ct(p.size()), P_ct(p.size()) {
					x_ct.clear();
					P_ct.clear();
				}
Пример #28
0
				/**
				 * Discrete perturbation from continuous specifications.
				 * - The variance integrates linearly with dt:
				 *		- P = Pct.P * _dt
				 * - Therefore, the mean values integrate with time linearly with the square root of dt:
				 * 		- x = Pct.x * sqrt(_dt)
				 *
				 * \param Pct a continuous-time Gaussian process noise.
				 * \param _dt the time interval to integrate.
				 */
				void set_from_continuous(Gaussian & Pct, double _dt) {
					JFR_ASSERT(Pct.size() == size(), "Sizes mismatch");
					set_x_continuous(Pct.x());
					set_P_continuous(Pct.P());
					set_from_continuous(_dt);
				}
Пример #29
0
/**
* Create LCP and RCP packets with different noise and signals
*
*/
void
createPackets(Gaussian &xGen, Gaussian &yGen, 
			ATAPacket &xPkt, ATAPacket &yPkt)
{
	//
	// we're reusing the packets, so make sure they're in the right order
	//
	xPkt.putPacket(pkt->getPacket());
	yPkt.putPacket(pkt->getPacket());

	ATADataPacketHeader& hdr = xPkt.getHeader();

	//
	// the following converts the timeval unix time into a 64-bit sec.frac
	// format; this requires converting tv_usec to a 32-bit fraction
	// of the form usec / 1e6, then conve[Brting it back to a 32-bit unsigned
	// integer by multiplying by 2^32.
	//
	timeval tp;
	gettimeofday(&tp, NULL);
	hdr.absTime = ATADataPacketHeader::timevalToAbsTime(tp);

	hdr.chan = channel;
	hdr.freq = cfreq;
//	hdr.sampleRate = bandwidth;
//	hdr.usableFraction = usable;
	hdr.seq = sequence++;
	hdr.flags |= data_valid;
	static ComplexFloat64 *samples = 0;
//   		Copy the whole packet to get the header
	memcpy(&yPkt, &xPkt, xPkt.getSize());  
//		Now fill in the samples
	if (!samples)
		samples = new ComplexFloat64[hdr.len];
	if (!local) {
//
// 	Only create samples for the pols to be sent
//
		if ( !singlePol || (singlePol && xPol))
		{
			xGen.getSamples(samples, hdr.len);
		//
		// store the samples in the  X packet
		//
			for (uint32_t i = 0; i < hdr.len; ++i) {
				ComplexFloat32 s(samples[i]);
				if (swapri)
					s = ComplexFloat32(s.imag(), s.real());
				xPkt.putSample(i, s);
			}
		}
		if ( !singlePol || (singlePol && !xPol))
		{
			yGen.getSamples(samples, hdr.len);
		//
		// store the samples in the Y packet 
		//
			for (uint32_t i = 0; i < hdr.len; ++i) {
				ComplexFloat32 s(samples[i]);
				if (swapri)
					s = ComplexFloat32(s.imag(), s.real());
				yPkt.putSample(i, s);
			}
		}
	}
	switch (polarization) {
	case ATADataPacketHeader::XLINEAR:
		xPkt.getHeader().polCode = ATADataPacketHeader::XLINEAR;
		yPkt.getHeader().polCode = ATADataPacketHeader::YLINEAR;
		break;
	case ATADataPacketHeader::RCIRC:
	default:
		xPkt.getHeader().polCode = ATADataPacketHeader::RCIRC;
		yPkt.getHeader().polCode = ATADataPacketHeader::LCIRC;
	}
}
Пример #30
0
/**
 * Print Statistics for the generated Packets
 *
 * Description:\n
 * Prints Total number of packets sent, the elapsed time,
 * the mean power, mean real and imaginary values for the samples
 * for both LCP and RCP
 *
 */
void
printStatistics()
{
	timeval end;
	gettimeofday(&end, NULL);

	int32_t sec = end.tv_sec - start.tv_sec;
	int32_t usec = end.tv_usec - start.tv_usec;
	if (usec < 0) {
		usec += 1000000;
		--sec;
	}
	cout << packet << " packets sent in "
		<< sec << "." << usec << " seconds" << endl;
	int32_t maxQueue = sndX->getSendHWM();
	cout << "maximum output queue X " << maxQueue << endl;
	maxQueue = sndY->getSendHWM();
	cout << "maximum output queue Y " << maxQueue << endl;

	int64_t samples;
	float64_t total;
	ComplexFloat64 power;
	ComplexFloat64 fSum;
	ComplexInt64 iSum;
/**
*	 X pol Statistics
*/
	samples = genX.getSampleCnt();
	power = genX.getPower();
	total = power.real() + power.imag();
	cout << "X pol" << endl;
	cout << samples << " samples, average (float) sample power = ";
	cout << total / samples << endl;
	cout << "power (float): re = " << power.real() << ", im = " << power.imag();
	cout << ", total = " << total << endl;
#ifdef notdef
	power = genX.getIntegerPower();
	total = power.real() + power.imag();
	cout << samples << " samples, average (short) sample power = ";
	cout << total / samples << endl;
	cout << "power (integer): re = " << power.real() << ", im = ";
	cout << power.imag() << ", total = " << total << endl;
#endif
	fSum = genX.getSum();
	cout << "sum of amplitudes (float64) = (" << fSum.real();
	cout << ", " << fSum.imag() << ")" << endl;
	cout << "avg of amplitudes (float64) = (" << fSum.real() / samples;
	cout << ", " << fSum.imag() / samples << ")" << endl;
#ifdef notdef
	iSum = genX.getIntegerSum();
	cout << "sum of amplitudes (short) = (" << iSum.real();
	cout << ", " << iSum.imag() << ")" << endl;
	cout << "avg of amplitudes (short) = (";
	cout << (float64_t) iSum.real() / samples;
	cout << ", " << (float64_t) iSum.imag() / samples << ")" << endl;
#endif

/**
*	 Y pol Statistics
*/
	samples = genY.getSampleCnt();
	power = genY.getPower();
	total = power.real() + power.imag();
	cout << "Y pol" << endl;
	cout << samples << " samples, average (float) sample power = ";
	cout << total / samples << endl;
	cout << "power (float): re = " << power.real() << ", im = " << power.imag();
	cout << ", total = " << total << endl;
#ifdef notdef
	power = genY.getIntegerPower();
	total = power.real() + power.imag();
	cout << samples << " samples, average (short) sample power = ";
	cout << total / samples << endl;
	cout << "power (integer): re = " << power.real() << ", im = ";
	cout << power.imag() << ", total = " << total << endl;
#endif
	fSum = genY.getSum();
	cout << "sum of amplitudes (float64) = (" << fSum.real();
	cout << ", " << fSum.imag() << ")" << endl;
	cout << "avg of amplitudes (float64) = (" << fSum.real() / samples;
	cout << ", " << fSum.imag() / samples << ")" << endl;
#ifdef notdef
	iSum = genY.getIntegerSum();
	cout << "sum of amplitudes (short) = (" << iSum.real();
	cout << ", " << iSum.imag() << ")" << endl;
	cout << "avg of amplitudes (short) = (";
	cout << (float64_t) iSum.real() / samples;
	cout << ", " << (float64_t) iSum.imag() / samples << ")" << endl;
#endif
}