示例#1
0
static void SampleSobol(This *t, ccount iregion)
{
  SAMPLERDEFS;
  Vector(real, avg, NCOMP);
  real norm;
  number i;
  count dim, comp;

  for( i = 0; i < n; ++i ) {
    t->rng.getrandom(t, x);
    for( dim = 0; dim < t->ndim; ++x, ++dim )
      *x = b[dim].lower + *x*(b[dim].upper - b[dim].lower);
  }

  t->nrand += n;

  DoSample(t, n, samples->x, f);

  FCopy(avg, f);
  f += t->ncomp;
  for( i = 2; i < n; ++i )
    for( comp = 0; comp < t->ncomp; ++comp )
      avg[comp] += *f++;

  norm = region->vol/samples->neff;
  for( comp = 0; comp < t->ncomp; ++comp ) {
    res[comp].avg = norm*avg[comp];
    res[comp].err = 0;
  }
}
TEST (LayoutSamplingTest, GenerateSimpleLayout) {
	for (uint32_t iter = 0; iter < 100; iter++) {
		GameState gameState = GenLayout();
		vector<shared_ptr<IPlayer>> players = {
			CreatePlayer("random", nullptr),
			CreatePlayer("random", nullptr),
			CreatePlayer("random", nullptr)
		};
		GameManager manager(players);
		manager.SetNewLayout(gameState, /*openCards=*/true);
		manager.PlayForNMoves(15);
		auto sampler = LayoutSampler(manager.GetState(), gameState.GetFirstPlayer(), 0);
		auto newLayouts = sampler.DoSample(5, /*playMoveHistory=*/false);
		for (const auto& newLayout : newLayouts) {
			// 2. If suit is out for some player, cards of suit in sampled layout must be the same
			// 3. Moves in history must be in the player hands
			ASSERT_EQ(newLayout.Hand(0).Size(), 10);
			ASSERT_EQ(newLayout.Hand(1).Size(), 10);
			ASSERT_EQ(newLayout.Hand(2).Size(), 10);
			ASSERT_EQ(newLayout.Hand(0).Add(newLayout.Hand(1).Add(newLayout.Hand(2))).Size(), 30);

			for (uint32_t player = 0; player < 3; player++) {
				for (Suit suit = (Suit)0; (uint8_t)suit < 4; suit = (Suit)((uint8_t)suit + 1)) {
					if (manager.GetState().IsSuitOut(player, suit)) {
						ASSERT_EQ(newLayout.Hand(player).GetSubsetOfSuit(suit), gameState.Hand(player).GetSubsetOfSuit(suit));
					}
				}
			}

			for (const auto moveData : manager.GetState().GetMoveHistory()) {
				ASSERT_TRUE(newLayout.Hand(moveData.player_).IsInSet(moveData.card_));
			}
		}
	}
}
示例#3
0
static inline count SampleExtra(This *t, cBounds *b)
{
  number n = t->nextra;
  t->peakfinder(&t->ndim, b, &n, t->xextra);
  DoSample(t, n, t->ldxgiven, t->xextra, t->fextra);
  return n;
}
示例#4
0
static inline count SampleExtra(cBounds *b)
{
    count n = nextra_;
    peakfinder_(&ndim_, b, &n, xextra_);
    DoSample(n, ldxgiven_, xextra_, fextra_);
    return n;
}
示例#5
0
文件: Sample.c 项目: Omer80/wimps
static real Sample(creal *x0)
{
  real xtmp[2*NDIM], ftmp[2*NCOMP], *xlast = xtmp, f;
  real dist = 0;
  count dim, nextra = 1;

  for( dim = 0; dim < ndim_; ++dim ) {
    creal x1 = *xlast++ = Min(Max(*x0++, 0), 1);
    real dx;
    if( (dx = x1 - border_.lower) < 0 ||
        (dx = x1 - border_.upper) > 0 ) dist += Sq(dx);
  }

  if( dist > 0 ) {
    dist = sqrt(dist)/EXTRAPOLATE_EPS;
    for( dim = 0; dim < ndim_; ++dim ) {
      real x2 = xtmp[dim], dx, b;
      if( (dx = x2 - (b = border_.lower)) < 0 ||
          (dx = x2 - (b = border_.upper)) > 0 ) {
        xtmp[dim] = b;
        x2 = b - dx/dist;
      }
      *xlast++ = x2;
    }
    nextra = 2;
  }

  DoSample(nextra, ndim_, xtmp, ftmp);

  f = ftmp[selectedcomp_];
  if( nextra > 1 ) f += dist*(f - ftmp[selectedcomp_ + ncomp_]);

  return f;
}
示例#6
0
static void SampleKorobov(This *t, ccount iregion)
{
  SAMPLERDEFS;
  real *xlast = x + t->ndim, *flast = f + t->ncomp;
  Vector(real, avg, NCOMP);
  real norm;
  cnumber neff = samples->neff;
  number nextra = 0, i;
  real dist = 0;
  count dim, comp;

  for( i = 1; i < n; ++i ) {
    number c = i;
    for( dim = 0; dim < t->ndim; ++dim ) {
      creal dx = abs(2*c - neff)/(real)neff;
      *xlast++ = b[dim].lower + dx*(b[dim].upper - b[dim].lower);
      c = c*samples->coeff % neff;
    }
  }

  for( dim = 0; dim < t->ndim; ++dim ) {
    creal dx = (x[dim] = b[dim].upper) - t->border.upper;
    if( dx > 0 ) dist += Sq(dx);
  }

  if( dist > 0 ) {
    dist = sqrt(dist)/EXTRAPOLATE_EPS;
    for( dim = 0; dim < t->ndim; ++dim ) {
      real x2 = x[dim], dx = x2 - t->border.upper;
      if( dx > 0 ) {
        x[dim] = t->border.upper;
        x2 = t->border.upper - dx/dist;
      }
      xlast[dim] = x2;
    }
    nextra = 1;
  }

  DoSample(t, n + nextra, x, f);

  FCopy(avg, flast);
  flast += t->ncomp;
  for( i = 2; i < n; ++i )
    for( comp = 0; comp < t->ncomp; ++comp )
      avg[comp] += *flast++;

  if( nextra ) {
    for( comp = 0; comp < t->ncomp; ++comp )
      f[comp] += dist*(f[comp] - flast[comp]);
    for( dim = 0; dim < t->ndim; ++dim )
      x[dim] = b[dim].upper;
  }

  norm = region->vol/samples->neff;
  for( comp = 0; comp < t->ncomp; ++comp ) {
    res[comp].avg = norm*(avg[comp] + avg[comp] + f[comp]);
    res[comp].err = 0;
  }
}
示例#7
0
void COCCDemoDoc::OnBUTTONPrev() 
{
  if (!myPresentation->AtFirstSample())
  {
    myPresentation->PrevSample();
    DoSample();
  }
}
示例#8
0
void COCCDemoDoc::OnBUTTONNext() 
{
  if (!myPresentation->AtLastSample())
  {
    myPresentation->NextSample();
    DoSample();
  }
}
示例#9
0
Extern void EXPORT(Divonne)(ccount ndim, ccount ncomp,
  Integrand integrand,
  creal epsrel, creal epsabs,
  cint flags, cnumber mineval, cnumber maxeval,
  cint key1, cint key2, cint key3, ccount maxpass,
  creal border, creal maxchisq, creal mindeviation,
  cnumber ngiven, ccount ldxgiven, real *xgiven,
  cnumber nextra, PeakFinder peakfinder,
  int *pnregions, number *pneval, int *pfail,
  real *integral, real *error, real *prob)
{
  ndim_ = ndim;
  ncomp_ = ncomp;

  if( BadComponent(ncomp) ||
      BadDimension(ndim, flags, key1) ||
      BadDimension(ndim, flags, key2) ||
      ((key3 & -2) && BadDimension(ndim, flags, key3)) ) *pfail = -1;
  else {
    neval_ = neval_opt_ = neval_cut_ = 0;
    integrand_ = integrand;
    peakfinder_ = peakfinder;
    border_.lower = border;
    border_.upper = 1 - border_.lower;
    ngiven_ = ngiven;
    xgiven_ = NULL;
    ldxgiven_ = IMax(ldxgiven, ndim_);
    nextra_ = nextra;

    if( ngiven + nextra ) {
      cnumber nxgiven = ngiven*ldxgiven;
      cnumber nxextra = nextra*ldxgiven;
      cnumber nfgiven = ngiven*ncomp;
      cnumber nfextra = nextra*ncomp;

      Alloc(xgiven_, nxgiven + nxextra + nfgiven + nfextra);
      xextra_ = xgiven_ + nxgiven;
      fgiven_ = xextra_ + nxextra;
      fextra_ = fgiven_ + nfgiven;

      if( nxgiven ) {
        phase_ = 0;
        Copy(xgiven_, xgiven, nxgiven);
        DoSample(ngiven_, ldxgiven_, xgiven_, fgiven_);
      }
    }

    *pfail = Integrate(epsrel, Max(epsabs, NOTZERO),
      flags, mineval, maxeval, key1, key2, key3, maxpass,
      maxchisq, mindeviation,
      integral, error, prob);
    *pnregions = nregions_;
    *pneval = neval_;

    if( xgiven_ ) free(xgiven_);
  }
}
示例#10
0
文件: Sample.c 项目: Omer80/wimps
static void SampleKorobov(cSamples *samples, cBounds *b, creal vol)
{
  creal norm = vol*samples->weight;
  real *x = samples->x, *xlast = x + ndim_;
  real *f = samples->f, *flast = f + ncomp_;
  real *avg = samples->avg;
  ccount n = samples->n, neff = samples->neff;
  count nextra = n;
  real dist = 0;
  count i, dim, comp;

  for( i = 1; i < n; ++i ) {
    count c = i;
    for( dim = 0; dim < ndim_; ++dim ) {
      creal dx = abs(2*c - neff)*samples->weight;
      *xlast++ = b[dim].lower + dx*(b[dim].upper - b[dim].lower);
      c = c*samples->coeff % neff;
    }
  }

  for( dim = 0; dim < ndim_; ++dim ) {
    creal dx = (x[dim] = b[dim].upper) - border_.upper;
    if( dx > 0 ) dist += Sq(dx);
  }

  if( dist > 0 ) {
    dist = sqrt(dist)/EXTRAPOLATE_EPS;
    for( dim = 0; dim < ndim_; ++dim ) {
      real x2 = x[dim], dx = x2 - border_.upper;
      if( dx > 0 ) {
        x[dim] = border_.upper;
        x2 = border_.upper - dx/dist;
      }
      xlast[dim] = x2;
    }
    ++nextra;
  }

  DoSample(nextra, ndim_, x, f);

  ResCopy(avg, flast);
  flast += ncomp_;
  for( i = 2; i < n; ++i )
    for( comp = 0; comp < ncomp_; ++comp )
      avg[comp] += *flast++;

  if( nextra > n ) {
    for( comp = 0; comp < ncomp_; ++comp )
      f[comp] += dist*(f[comp] - flast[comp]);
    for( dim = 0; dim < ndim_; ++dim )
      x[dim] = b[dim].upper;
  }

  for( comp = 0; comp < ncomp_; ++comp )
    avg[comp] = (avg[comp] + avg[comp] + f[comp])*norm;
}
void
nsSMILTimeContainer::Sample()
{
  if (!NeedsSample())
    return;

  UpdateCurrentTime();
  DoSample();

  mNeedsPauseSample = PR_FALSE;
}
示例#12
0
void Divonne(ccount ndim, ccount ncomp, Integrand integrand,
             creal epsrel, creal epsabs,
             cint flags, ccount mineval, ccount maxeval,
             cint key1, cint key2, cint key3, ccount maxpass,
             creal border, creal maxchisq, creal mindeviation,
             ccount ngiven, ccount ldxgiven, real *xgiven,
             ccount nextra, PeakFinder peakfinder,
             int *pnregions, int *pneval, int *pfail,
             real *integral, real *error, real *prob)
{
    ndim_ = ndim;
    ncomp_ = ncomp;

    if( ndim < MINDIM || ndim > MAXDIM ) *pfail = -1;
    else {
        neval_ = neval_opt_ = neval_cut_ = 0;
        integrand_ = integrand;
        peakfinder_ = peakfinder;
        border_.lower = border;
        border_.upper = 1 - border_.lower;
        ngiven_ = ngiven;
        xgiven_ = NULL;
        ldxgiven_ = IMax(ldxgiven, ndim_);
        nextra_ = nextra;

        if( ngiven + nextra ) {
            ccount nxgiven = ngiven*ldxgiven;
            ccount nxextra = nextra*ldxgiven;
            ccount nfgiven = ngiven*ncomp;
            ccount nfextra = nextra*ncomp;

            Allocate(xgiven_, nxgiven + nxextra + nfgiven + nfextra);
            xextra_ = xgiven_ + nxgiven;
            fgiven_ = xextra_ + nxextra;
            fextra_ = fgiven_ + nfgiven;

            if( nxgiven ) {
                phase_ = 0;
                Copy(xgiven_, xgiven, nxgiven);
                DoSample(ngiven_, ldxgiven_, xgiven_, fgiven_);
            }
        }

        *pfail = Integrate(epsrel, Max(epsabs, NOTZERO),
                           flags, mineval, maxeval, key1, key2, key3, maxpass,
                           maxchisq, mindeviation,
                           integral, error, prob);
        *pnregions = nregions_;
        *pneval = neval_;

        if( xgiven_ ) free(xgiven_);
    }
}
示例#13
0
文件: Rule.c 项目: cran/cubature
static void SampleRule(This *t, ccount iregion)
{
  SAMPLERDEFS;
  Set *first = samples->rule->first;
  Set *last = samples->rule->last;
  Set *s;
  creal *errcoeff = samples->rule->errcoeff;
  count comp, rul, sn;
  csize_t setsize = SetSize;

  for( s = first; s <= last; NextSet(s) )
    if( s->n ) x = ExpandFS(t, b, s->gen, x);

  DoSample(t, n, samples->x, f);

  for( comp = 0; comp < t->ncomp; ++comp ) {
    real sum[nrules];
    creal *f1 = f++;

    Zap(sum);
    for( s = first; s <= last; NextSet(s) )
      for( sn = s->n; sn; --sn ) {
        creal fun = *f1;
        f1 += t->ncomp;
        for( rul = 0; rul < nrules; ++rul )
          sum[rul] += fun*s->weight[rul];
      }

    /* Search for the null rule, in the linear space spanned by two
       successive null rules in our sequence, which gives the greatest
       error estimate among all normalized (1-norm) null rules in this
       space. */

    for( rul = 1; rul < nrules - 1; ++rul ) {
      real maxerr = 0;
      for( s = first; s <= last; NextSet(s) )
        maxerr = Max(maxerr,
          fabsx(sum[rul + 1] + s->scale[rul]*sum[rul])*s->norm[rul]);
      sum[rul] = maxerr;
    }

    res[comp].avg = region->vol*sum[0];
    res[comp].err = region->vol*(
      (errcoeff[0]*sum[1] <= sum[2] && errcoeff[0]*sum[2] <= sum[3]) ?
        errcoeff[1]*sum[1] :
        errcoeff[2]*Max(Max(sum[1], sum[2]), sum[3]) );
  }
}
示例#14
0
static inline void AllocGiven(This *t, creal *xgiven)
{
  if( t->ngiven | t->nextra ) {
    cnumber nxgiven = t->ngiven*(t->ldxgiven = IMax(t->ldxgiven, t->ndim));
    cnumber nxextra = t->nextra*t->ldxgiven;
    cnumber nfgiven = t->ngiven*t->ncomp;
    cnumber nfextra = t->nextra*t->ncomp;

    Alloc(t->xgiven, nxgiven + nxextra + nfgiven + nfextra);
    t->xextra = t->xgiven + nxgiven;
    t->fgiven = t->xextra + nxextra;
    t->fextra = t->fgiven + nfgiven;

    if( nxgiven ) {
      t->phase = 0;
      Copy(t->xgiven, xgiven, nxgiven);
      DoSample(t, t->ngiven, t->ldxgiven, t->xgiven, t->fgiven);
    }
  }
}
示例#15
0
static real Sample(This *t, creal *x0)
{
  Vector(real, xtmp, 2*NDIM);
  Vector(real, ftmp, 2*NCOMP);
  real *xlast = xtmp, f;
  real dist = 0;
  count dim, comp;
  number n = 1;

  for( dim = 0; dim < t->ndim; ++dim ) {
    creal x1 = *xlast++ = Min(Max(*x0++, 0.), 1.);
    real dx;
    if( (dx = x1 - t->border.lower) < 0 ||
        (dx = x1 - t->border.upper) > 0 ) dist += Sq(dx);
  }

  if( dist > 0 ) {
    dist = sqrt(dist)/EXTRAPOLATE_EPS;
    for( dim = 0; dim < t->ndim; ++dim ) {
      real x2 = xtmp[dim], dx, b;
      if( (dx = x2 - (b = t->border.lower)) < 0 ||
          (dx = x2 - (b = t->border.upper)) > 0 ) {
        xtmp[dim] = b;
        x2 = b - dx/dist;
      }
      *xlast++ = x2;
    }
    n = 2;
  }

  DoSample(t, n, xtmp, ftmp);

#define fin(x) Min(Max(x, -.5*INFTY), .5*INFTY) 

  comp = Untag(t->selectedcomp);
  f = fin(ftmp[comp]);
  if( n > 1 ) f += dist*(f - fin(ftmp[comp + t->ncomp]));

  return Sign(t->selectedcomp)*f;
}
示例#16
0
文件: Sample.c 项目: Omer80/wimps
static void SampleSobol(cSamples *samples, cBounds *b, creal vol)
{
  creal norm = vol*samples->weight;
  real *x = samples->x, *f = samples->f, *avg = samples->avg;
  ccount n = samples->n;
  count i, dim, comp;

  for( i = 0; i < n; ++i ) {
    GetRandom(x);
    for( dim = 0; dim < ndim_; ++x, ++dim )
      *x = b[dim].lower + *x*(b[dim].upper - b[dim].lower);
  }

  DoSample(n, ndim_, samples->x, f);

  ResCopy(avg, f);
  f += ncomp_;
  for( i = 1; i < n; ++i )
    for( comp = 0; comp < ncomp_; ++comp )
      avg[comp] += *f++;

  for( comp = 0; comp < ncomp_; ++comp )
    avg[comp] *= norm;
}
示例#17
0
static void Sample(This *t, Region *region)
{
  csize_t setsize = SetSize;
  creal vol = ldexp(1., -region->div);

  real *x = t->frame, *f = x + t->rule.n*t->ndim;
  Set *first = t->rule.first, *last = t->rule.last, *s;
  Bounds *b, *B = region->bounds + t->ndim;
  Result *result = RegionResult(region), *res, *Res = result + t->ncomp;
  creal *errcoeff = t->rule.errcoeff;
  creal ratio = Sq(IndexSet(first,2)->gen[0]/
                   IndexSet(first,1)->gen[0]);

  ccount offset = 2*t->ndim*t->ncomp;
  count dim, rul, n, maxdim = 0;
  real maxrange = 0;

  for( b = region->bounds, dim = 0; b < B; ++b, ++dim ) {
    creal range = b->upper - b->lower;
    if( range > maxrange ) {
      maxrange = range;
      maxdim = dim;
    }
  }

  for( s = first; s <= last; NextSet(s) )
    if( s->n ) x = ExpandFS(t, region->bounds, s->gen, x);

  DoSample(t, t->rule.n, t->frame, f);

  for( res = result; res < Res; ++res ) {
    real sum[nrules];
    creal *f1 = f;
    creal base = *f1*2*(1 - ratio);
    real maxdiff = 0;
    count bisectdim = maxdim;

    for( dim = 0; dim < t->ndim; ++dim ) {
      creal *fp = f1 + t->ncomp;
      creal *fm = fp + t->ncomp;
      creal fourthdiff = fabs(base +
        ratio*(fp[0] + fm[0]) - (fp[offset] + fm[offset]));
      f1 = fm;
      if( fourthdiff > maxdiff ) {
        maxdiff = fourthdiff;
        bisectdim = dim;
      }
    }
    res->bisectdim = bisectdim;

    f1 = f++;
    Zap(sum);
    for( s = first; s <= last; NextSet(s) )
      for( n = s->n; n; --n ) {
        creal fun = *f1;
        f1 += t->ncomp;
        for( rul = 0; rul < nrules; ++rul )
          sum[rul] += fun*s->weight[rul];
      }

    /* Search for the null rule, in the linear space spanned by two
       successive null rules in our sequence, which gives the greatest
       error estimate among all normalized (1-norm) null rules in this
       space. */

    for( rul = 1; rul < nrules - 1; ++rul ) {
      real maxerr = 0;
      for( s = first; s <= last; NextSet(s) )
        maxerr = Max(maxerr,
          fabs(sum[rul + 1] + s->scale[rul]*sum[rul])*s->norm[rul]);
      sum[rul] = maxerr;
    }

    res->avg = vol*sum[0];
    res->err = vol*(
      (errcoeff[0]*sum[1] <= sum[2] && errcoeff[0]*sum[2] <= sum[3]) ?
        errcoeff[1]*sum[1] :
        errcoeff[2]*Max(Max(sum[1], sum[2]), sum[3]) );
  }

  if( VERBOSE > 2 ) {
    Vector(char, out, 64*NDIM + 128*NCOMP);
    char *oe = out;
    count comp;
    cchar *msg = "\nRegion (" REALF ") - (" REALF ")";

    for( b = region->bounds; b < B; ++b ) {
      oe += sprintf(oe, msg, b->lower, b->upper);
      msg = "\n       (" REALF ") - (" REALF ")";
    }

    for( res = result, comp = 0; res < Res; ++res )
      oe += sprintf(oe, "\n[" COUNT "] "
        REAL " +- " REAL, ++comp, res->avg, res->err);

    Print(out);
  }
示例#18
0
static void Sample(This *t, void *voidregion)
{
  TYPEDEFREGION;
  TYPEDEFSET;

  Region *const region = (Region *)voidregion;
  creal vol = ldexp(1., -region->div);

  real *x = t->rule.x, *f = t->rule.f;
  Set *first = (Set *)t->rule.first, *last = (Set *)t->rule.last, *s;
  creal *errcoeff = t->rule.errcoeff;
  creal ratio = Sq(first[2].gen[0]/first[1].gen[0]);

  ccount offset = 2*t->ndim*t->ncomp;
  count dim, comp, rul, n, maxdim = 0;
  real maxrange = 0;

  for( dim = 0; dim < t->ndim; ++dim ) {
    cBounds *b = &region->bounds[dim];
    creal range = b->upper - b->lower;
    if( range > maxrange ) {
      maxrange = range;
      maxdim = dim;
    }
  }

  for( s = first; s <= last; ++s )
    if( s->n ) x = ExpandFS(t, region->bounds, s->gen, x);

  DoSample(t, t->rule.n, t->rule.x, f);

  for( comp = 0; comp < t->ncomp; ++comp ) {
    Result *r = &region->result[comp];
    real sum[nrules];
    creal *f1 = f;
    creal base = *f1*2*(1 - ratio);
    real maxdiff = 0;
    count bisectdim = maxdim;

    for( dim = 0; dim < t->ndim; ++dim ) {
      creal *fp = f1 + t->ncomp;
      creal *fm = fp + t->ncomp;
      creal fourthdiff = fabs(base +
        ratio*(fp[0] + fm[0]) - (fp[offset] + fm[offset]));
      f1 = fm;
      if( fourthdiff > maxdiff ) {
        maxdiff = fourthdiff;
        bisectdim = dim;
      }
    }
    r->bisectdim = bisectdim;

    f1 = f++;
    Zap(sum);
    for( s = first; s <= last; ++s )
      for( n = s->n; n; --n ) {
        creal fun = *f1;
        f1 += t->ncomp;
        for( rul = 0; rul < nrules; ++rul )
          sum[rul] += fun*s->weight[rul];
      }

    /* Search for the null rule, in the linear space spanned by two
       successive null rules in our sequence, which gives the greatest
       error estimate among all normalized (1-norm) null rules in this
       space. */

    for( rul = 1; rul < nrules - 1; ++rul ) {
      real maxerr = 0;
      for( s = first; s <= last; ++s )
        maxerr = Max(maxerr,
          fabs(sum[rul + 1] + s->scale[rul]*sum[rul])*s->norm[rul]);
      sum[rul] = maxerr;
    }

    r->avg = vol*sum[0];
    r->err = vol*(
      (errcoeff[0]*sum[1] <= sum[2] && errcoeff[0]*sum[2] <= sum[3]) ?
        errcoeff[1]*sum[1] :
        errcoeff[2]*Max(Max(sum[1], sum[2]), sum[3]) );
  }

  if( VERBOSE > 2 ) {
    char s[64*NDIM + 128*NCOMP], *p = s;

    for( dim = 0; dim < t->ndim; ++dim ) {
      cBounds *b = &region->bounds[dim];
      p += sprintf(p,
        (dim == 0) ? "\nRegion (" REALF ") - (" REALF ")" :
                     "\n       (" REALF ") - (" REALF ")",
        b->lower, b->upper);
    }

    for( comp = 0; comp < t->ncomp; ++comp ) {
      cResult *r = &region->result[comp];
      p += sprintf(p, "\n[" COUNT "] "
        REAL " +- " REAL, comp + 1, r->avg, r->err);
    }

    Print(s);
  }
}
示例#19
0
void COCCDemoDoc::OnBUTTONEnd()
{
  myAISContext->EraseAll(Standard_False);
  myPresentation->LastSample();
  DoSample();
}
示例#20
0
void COCCDemoDoc::OnBUTTONRepeat() 
{
  DoSample();
}
示例#21
0
static int Integrate(This *t, real *integral, real *error, real *prob)
{
  bin_t *bins;
  count dim, comp;
  int fail;
  struct {
    count niter;
    number nsamples, neval;
    Cumulants cumul[NCOMP];
    Grid grid[NDIM];
  } state;
  int statemsg = VERBOSE;
  struct stat st;

  if( VERBOSE > 1 ) {
    char s[512];
    sprintf(s, "Vegas input parameters:\n"
      "  ndim " COUNT "\n  ncomp " COUNT "\n"
      "  epsrel " REAL "\n  epsabs " REAL "\n"
      "  flags %d\n  seed %d\n"
      "  mineval " NUMBER "\n  maxeval " NUMBER "\n"
      "  nstart " NUMBER "\n  nincrease " NUMBER "\n"
      "  nbatch " NUMBER "\n  gridno %d\n"
      "  statefile \"%s\"",
      t->ndim, t->ncomp,
      t->epsrel, t->epsabs,
      t->flags, t->seed,
      t->mineval, t->maxeval,
      t->nstart, t->nincrease, t->nbatch,
      t->gridno, t->statefile);
    Print(s);
  }

  if( BadComponent(t) ) return -2;
  if( BadDimension(t) ) return -1;

  FrameAlloc(t, ShmRm(t));
  ForkCores(t);
  Alloc(bins, t->nbatch*t->ndim);

  if( (fail = setjmp(t->abort)) ) goto abort;

  IniRandom(t);

  if( t->statefile && *t->statefile == 0 ) t->statefile = NULL;

  if( t->statefile &&
      stat(t->statefile, &st) == 0 &&
      st.st_size == sizeof state && (st.st_mode & 0400) ) {
    cint h = open(t->statefile, O_RDONLY);
    read(h, &state, sizeof state);
    close(h);
    t->rng.skiprandom(t, t->neval = state.neval);

    if( VERBOSE ) {
      char s[256];
      sprintf(s, "\nRestoring state from %s.", t->statefile);
      Print(s);
    }
  }
  else {
    state.niter = 0;
    state.nsamples = t->nstart;
    Zap(state.cumul);
    GetGrid(t, state.grid);
  }

  /* main iteration loop */

  for( ; ; ) {
    number nsamples = state.nsamples;
    creal jacobian = 1./nsamples;
    Grid margsum[NCOMP][NDIM];

    Zap(margsum);

    for( ; nsamples > 0; nsamples -= t->nbatch ) {
      cnumber n = IMin(t->nbatch, nsamples);
      real *w = t->frame;
      real *x = w + n;
      real *f = x + n*t->ndim;
      real *lastf = f + n*t->ncomp;
      bin_t *bin = bins;

      while( x < f ) {
        real weight = jacobian;

        t->rng.getrandom(t, x);

        for( dim = 0; dim < t->ndim; ++dim ) {
          creal pos = *x*NBINS;
          ccount ipos = (count)pos;
          creal prev = (ipos == 0) ? 0 : state.grid[dim][ipos - 1];
          creal diff = state.grid[dim][ipos] - prev; 
          *x++ = prev + (pos - ipos)*diff;
          *bin++ = ipos;
          weight *= diff*NBINS;
        }

        *w++ = weight;
      }

      DoSample(t, n, w, f, t->frame, state.niter + 1);

      bin = bins;
      w = t->frame;

      while( f < lastf ) {
        creal weight = *w++;

        for( comp = 0; comp < t->ncomp; ++comp ) {
          real wfun = weight*(*f++);
          if( wfun ) {
            Cumulants *c = &state.cumul[comp];
            Grid *m = margsum[comp];

            c->sum += wfun;
            c->sqsum += wfun *= wfun;
            for( dim = 0; dim < t->ndim; ++dim )
              m[dim][bin[dim]] += wfun;
          }
        }

        bin += t->ndim;
      }
    }

    fail = 0;

    /* compute the integral and error values */

    for( comp = 0; comp < t->ncomp; ++comp ) {
      Cumulants *c = &state.cumul[comp];
      real avg, sigsq;
      real w = Weight(c->sum, c->sqsum, state.nsamples);

      sigsq = 1/(c->weightsum += w);
      avg = sigsq*(c->avgsum += w*c->sum);

      c->avg = LAST ? (sigsq = 1/w, c->sum) : avg;
      c->err = sqrt(sigsq);
      fail |= (c->err > MaxErr(c->avg));

      if( state.niter == 0 ) c->guess = c->sum;
      else {
        c->chisum += w *= c->sum - c->guess;
        c->chisqsum += w*c->sum;
      }
      c->chisq = c->chisqsum - avg*c->chisum;

      c->sum = c->sqsum = 0;
    }

    if( VERBOSE ) {
      char s[128 + 128*NCOMP], *p = s;

      p += sprintf(p, "\n"
        "Iteration " COUNT ":  " NUMBER " integrand evaluations so far",
        state.niter + 1, t->neval);

      for( comp = 0; comp < t->ncomp; ++comp ) {
        cCumulants *c = &state.cumul[comp];
        p += sprintf(p, "\n[" COUNT "] "
          REAL " +- " REAL "  \tchisq " REAL " (" COUNT " df)",
          comp + 1, c->avg, c->err, c->chisq, state.niter);
      }

      Print(s);
    }

    if( fail == 0 && t->neval >= t->mineval ) {
      if( t->statefile && KEEPFILE == 0 ) unlink(t->statefile);
      break;
    }

    if( t->neval >= t->maxeval && t->statefile == NULL ) break;

    if( t->ncomp == 1 )
      for( dim = 0; dim < t->ndim; ++dim )
        RefineGrid(t, state.grid[dim], margsum[0][dim]);
    else {
      for( dim = 0; dim < t->ndim; ++dim ) {
        Grid wmargsum;
        Zap(wmargsum);
        for( comp = 0; comp < t->ncomp; ++comp ) {
          real w = state.cumul[comp].avg;
          if( w != 0 ) {
            creal *m = margsum[comp][dim];
            count bin;
            w = 1/Sq(w);
            for( bin = 0; bin < NBINS; ++bin )
              wmargsum[bin] += w*m[bin];
          }
        }
        RefineGrid(t, state.grid[dim], wmargsum);
      }
    }

    ++state.niter;
    state.nsamples += t->nincrease;

    if( t->statefile ) {
      cint h = creat(t->statefile, 0666);
      if( h != -1 ) {
        state.neval = t->neval;
        write(h, &state, sizeof state);
        close(h);

        if( statemsg ) {
          char s[256];
          sprintf(s, "\nSaving state to %s.", t->statefile);
          Print(s);
          statemsg = false;
        }
      }
      if( t->neval >= t->maxeval ) break;
    }
  }

  for( comp = 0; comp < t->ncomp; ++comp ) {
    cCumulants *c = &state.cumul[comp];
    integral[comp] = c->avg;
    error[comp] = c->err;
    prob[comp] = ChiSquare(c->chisq, state.niter);
  }

abort:
  PutGrid(t, state.grid);
  free(bins);
  WaitCores(t);
  FrameFree(t);

  return fail;
}
示例#22
0
static int Integrate(This *t, real *integral, real *error, real *prob)
{
  bin_t *bins;
  count dim, comp;
  int fail;

  StateDecl;
  csize_t statesize = sizeof(State) +
    NCOMP*sizeof(Cumulants) + NDIM*sizeof(Grid);
  Sized(State, state, statesize);
  Cumulants *c, *C = state->cumul + t->ncomp;
  Grid *state_grid = (Grid *)C;
  Array(Grid, margsum, NCOMP, NDIM);
  Vector(char, out, 128*NCOMP + 256);

  if( VERBOSE > 1 ) {
    sprintf(out, "Vegas input parameters:\n"
      "  ndim " COUNT "\n  ncomp " COUNT "\n"
      "  epsrel " REAL "\n  epsabs " REAL "\n"
      "  flags %d\n  seed %d\n"
      "  mineval " NUMBER "\n  maxeval " NUMBER "\n"
      "  nstart " NUMBER "\n  nincrease " NUMBER "\n"
      "  nbatch " NUMBER "\n  gridno %d\n"
      "  statefile \"%s\"",
      t->ndim, t->ncomp,
      t->epsrel, t->epsabs,
      t->flags, t->seed,
      t->mineval, t->maxeval,
      t->nstart, t->nincrease, t->nbatch,
      t->gridno, t->statefile);
    Print(out);
  }

  if( BadComponent(t) ) return -2;
  if( BadDimension(t) ) return -1;

  FrameAlloc(t, ShmRm(t));
  ForkCores(t);
  Alloc(bins, t->nbatch*t->ndim);

  if( (fail = setjmp(t->abort)) ) goto abort;

  IniRandom(t);

  StateSetup(t);

  if( StateReadTest(t) ) {
    StateReadOpen(t, fd) {
      if( read(fd, state, statesize) != statesize ||
          state->signature != StateSignature(t, 1) ) break;
    } StateReadClose(t, fd);
    t->neval = state->neval;
    t->rng.skiprandom(t, t->neval);
  }

  if( ini ) {
    state->niter = 0;
    state->nsamples = t->nstart;
    FClear(state->cumul);
    GetGrid(t, state_grid);
    t->neval = 0;
  }

  /* main iteration loop */
  for( ; ; ) {
    number nsamples = state->nsamples;
    creal jacobian = 1./nsamples;

    FClear(margsum);

    for( ; nsamples > 0; nsamples -= t->nbatch ) {
      cnumber n = IMin(t->nbatch, nsamples);
      real *w = t->frame;
      real *x = w + n;
      real *f = x + n*t->ndim;
      real *lastf = f + n*t->ncomp;
      bin_t *bin = bins;

      while( x < f ) {
        real weight = jacobian;

        t->rng.getrandom(t, x);

        for( dim = 0; dim < t->ndim; ++dim ) {
          creal pos = *x*NBINS;
          ccount ipos = (count)pos;
          creal prev = (ipos == 0) ? 0 : state_grid[dim][ipos - 1];
          creal diff = state_grid[dim][ipos] - prev; 
          *x++ = prev + (pos - ipos)*diff;
          *bin++ = ipos;
          weight *= diff*NBINS;
        }

        *w++ = weight;
      }

      DoSample(t, n, w, f, t->frame, state->niter + 1);

      bin = bins;
      w = t->frame;

      while( f < lastf ) {
        creal weight = *w++;
        Grid *m = &margsum[0][0];

        for( c = state->cumul; c < C; ++c ) {
          real wfun = weight*(*f++);
          if( wfun ) {
            c->sum += wfun;
            c->sqsum += wfun *= wfun;
            for( dim = 0; dim < t->ndim; ++dim )
              m[dim][bin[dim]] += wfun;
          }
          m += t->ndim;
        }

        bin += t->ndim;
      }
    }

    fail = 0;

    /* compute the integral and error values */

    for( c = state->cumul; c < C; ++c ) {
      real w = Weight(c->sum, c->sqsum, state->nsamples);
      real sigsq = 1/(c->weightsum += w);
      real avg = sigsq*(c->avgsum += w*c->sum);

      c->avg = LAST ? (sigsq = 1/w, c->sum) : avg;
      c->err = sqrt(sigsq);
      fail |= (c->err > MaxErr(c->avg));

      if( state->niter == 0 ) c->guess = c->sum;
      else {
        c->chisum += w *= c->sum - c->guess;
        c->chisqsum += w*c->sum;
      }
      c->chisq = c->chisqsum - avg*c->chisum;

      c->sum = c->sqsum = 0;
    }

    if( VERBOSE ) {
      char *oe = out + sprintf(out, "\n"
        "Iteration " COUNT ":  " NUMBER " integrand evaluations so far",
        state->niter + 1, t->neval);
      for( c = state->cumul, comp = 0; c < C; ++c )
        oe += sprintf(oe, "\n[" COUNT "] "
          REAL " +- " REAL "  \tchisq " REAL " (" COUNT " df)",
          ++comp, c->avg, c->err, c->chisq, state->niter);
      Print(out);
    }

    if( fail == 0 && t->neval >= t->mineval ) break;

    if( t->neval >= t->maxeval && !StateWriteTest(t) ) break;

    if( t->ncomp == 1 )
      for( dim = 0; dim < t->ndim; ++dim )
        RefineGrid(t, state_grid[dim], margsum[0][dim]);
    else {
      for( dim = 0; dim < t->ndim; ++dim ) {
        Grid wmargsum;
        Zap(wmargsum);
        for( comp = 0; comp < t->ncomp; ++comp ) {
          real w = state->cumul[comp].avg;
          if( w != 0 ) {
            creal *m = margsum[comp][dim];
            count bin;
            w = 1/Sq(w);
            for( bin = 0; bin < NBINS; ++bin )
              wmargsum[bin] += w*m[bin];
          }
        }
        RefineGrid(t, state_grid[dim], wmargsum);
      }
    }

    ++state->niter;
    state->nsamples += t->nincrease;

    if( StateWriteTest(t) ) {
      state->signature = StateSignature(t, 1);
      state->neval = t->neval;
      StateWriteOpen(t, fd) {
        StateWrite(fd, state, statesize);
      } StateWriteClose(t, fd);
      if( t->neval >= t->maxeval ) break;
    }
  }
示例#23
0
static void Sample(This *t, cnumber nnew, void *voidregion,
                   real *lastw, real *lastx, real *lastf)
{
    TYPEDEFREGION;

    Region *const region = (Region *)voidregion;
    count comp, dim, df;
    number n;
    Cumulants cumul[NCOMP];
    char **ss, *s;
    ccount chars = 128*(region->div + 1);

    creal jacobian = 1/ldexp((real)nnew, region->div);
    real *w = lastw, *f = lastx;
    bin_t *bin = (bin_t *)(lastf + nnew*t->ncomp);

    for( n = nnew; n; --n ) {
        real weight = jacobian;

        t->rng.getrandom(t, f);

        for( dim = 0; dim < t->ndim; ++dim ) {
            cBounds *b = &region->bounds[dim];
            creal pos = *f*NBINS;
            ccount ipos = (count)pos;
            creal prev = (ipos == 0) ? 0 : b->grid[ipos - 1];
            creal diff = b->grid[ipos] - prev;
            *f++ = b->lower + (prev + (pos - ipos)*diff)*(b->upper - b->lower);
            *bin++ = ipos;
            weight *= diff*NBINS;
        }

        *w++ = weight;
    }

    DoSample(t, nnew, lastw, lastx, lastf, region->div + 1);

    w[-1] = -w[-1];
    lastw = w;
    w = region->w;
    region->n = lastw - w;

    if( VERBOSE > 2 ) {
        char *p0;
        MemAlloc(ss, t->ndim*64 + t->ncomp*(sizeof(char *) + chars));
        s = (char *)(ss + t->ncomp);
        p0 = s + t->ndim*64;
        for( comp = 0; comp < t->ncomp; ++comp ) {
            ss[comp] = p0;
            p0 += chars;
        }
    }

    Zap(cumul);
    df = n = 0;

    while( w < lastw ) {
        cbool final = (*w < 0);
        creal weight = fabs(*w++);
        ++n;

        for( comp = 0; comp < t->ncomp; ++comp ) {
            Cumulants *c = &cumul[comp];

            creal wfun = weight*(*f++);
            c->sum += wfun;
            c->sqsum += Sq(wfun);

            if( final ) {
                if( n > 1 ) {
                    real w = Weight(c->sum, c->sqsum, n);
                    c->weightsum += c->weight = w;
                    c->avgsum += c->avg = w*c->sum;

                    if( VERBOSE > 2 ) {
                        creal sig = sqrt(1/w);
                        ss[comp] += (df == 0) ?
                                    sprintf(ss[comp], "\n[" COUNT "] "
                                            REAL " +- " REAL " (" NUMBER ")", comp + 1,
                                            c->sum, sig, n) :
                                    sprintf(ss[comp], "\n    "
                                            REAL " +- " REAL " (" NUMBER ")",
                                            c->sum, sig, n);
                    }

                    if( df == 0 ) c->guess = c->sum;
                    else {
                        c->chisum += w *= c->sum - c->guess;
                        c->chisqsum += w*c->sum;
                    }
                }

                c->sum = c->sqsum = 0;
            }
        }

        if( final ) ++df, n = 0;
    }

    region->df = --df;

    for( comp = 0; comp < t->ncomp; ++comp ) {
        Result *r = &region->result[comp];
        Cumulants *c = &cumul[comp];
        creal sigsq = 1/c->weightsum;
        creal avg = sigsq*c->avgsum;

        if( LAST ) {
            r->sigsq = 1/c->weight;
            r->avg = r->sigsq*c->avg;
        }
        else {
            r->sigsq = sigsq;
            r->avg = avg;
        }
        r->err = sqrt(r->sigsq);

        r->chisq = (sigsq < .9*NOTZERO) ? 0 : c->chisqsum - avg*c->chisum;
        /* This catches the special case where the integrand is constant
           over the entire region.  Unless that constant is zero, only the
           first set of samples will have zero variance, and hence weight
           (n - 1) 1e30 (see above).  All other sets have been sampled
           from a non-constant weight function and therefore inevitably
           show some variance.  This is an artificial effect, brought about
           by the fact that the constancy of the integrand in the region is
           seen only in this subdivision, and can degrade the chi-square
           score quite a bit.  If the constancy was determined from more
           than two samples (hence .9*NOTZERO), the chi-squares from the
           other sets are removed here. */
    }

    if( VERBOSE > 2 ) {
        char *p = s;
        char *p0 = p + t->ndim*64;

        for( dim = 0; dim < t->ndim; ++dim ) {
            cBounds *b = &region->bounds[dim];
            p += sprintf(p,
                         (dim == 0) ? "\nRegion (" REALF ") - (" REALF ")" :
                         "\n       (" REALF ") - (" REALF ")",
                         b->lower, b->upper);
        }

        for( comp = 0; comp < t->ncomp; ++comp ) {
            cResult *r = &region->result[comp];
            p += sprintf(p, "%s  \tchisq " REAL " (" COUNT " df)",
                         p0, r->chisq, df);
            p0 += chars;
        }

        Print(s);
        free(ss);
    }
}