Configure the gibbs sampler

@param iterations
number of total iterations
@param burnIn
number of burn-in iterations
@param thinInterval
update statistics interval
@param sampleLag
sample interval (-1 for just one sample at the end)
961448
public void configure(int iterations, int burnIn, int thinInterval,
        int sampleLag) {
        ITERATIONS = iterations;
        BURN_IN = burnIn;
        THIN_INTERVAL = thinInterval;
        SAMPLE_LAG = sampleLag;
    }
363924
public static void main(String[] args) {

    // WARNING: Be careful before you set sampler value to always sample, especially in
    // production environment. Trace data is often very large in size and is expensive to
    // collect. This is why rather than collecting traces for every request(i.e. alwaysSample),
    // downsampling is prefered.
    //
    // By default, OpenCensus provides a probabilistic sampler that will trace once in every
    // 10,000 requests, that's why if default probabilistic sampler is used
    // you might not see trace data printed or exported and this is expected behavior.

    TraceConfig traceConfig = Tracing.getTraceConfig();
    traceConfig.updateActiveTraceParams(
        traceConfig.getActiveTraceParams().toBuilder().setSampler(Samplers.alwaysSample()).build());

    LoggingTraceExporter.register();
    try (Scope ss = tracer.spanBuilderWithExplicitParent("MyRootSpan", null).startScopedSpan()) {
      doWork();
    }

    // Wait for a duration longer than reporting duration (5s) to ensure spans are exported.
    // Spans are exported every 5 seconds
    sleep(5100);
  }
300869
@Override
    public void setMaxInactiveInterval(int maxInactiveInterval) {
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) {
            StringBuffer sb = new StringBuffer(newValueString).append(maxInactiveInterval).append(oldValueString).append(_maxInactiveInterval).append(appNameAndIdString);
            LoggingUtil.SESSION_LOGGER_CORE.logp(Level.FINE, methodClassName, "setMaxInactiveInterval", sb.toString());
        }
        if (maxInactiveInterval <= 0) {
            _maxInactiveInterval = -1;
        } else {
            _maxInactiveInterval = maxInactiveInterval;
        }
    }
424881
def run(self):
        """"""
        if self.target_eff_nsamples and self.checkpoint_interval is None:
            raise ValueError("A checkpoint interval must be set if "
                             "targetting an effective number of samples")
        # get the starting number of samples:
        # "nsamples" keeps track of the number of samples we've obtained (if
        # target_eff_nsamples is not None, this is the effective number of
        # samples; otherwise, this is the total number of samples).
        # _lastclear is the number of iterations that the file already
        # contains (either due to sampler burn-in, or a previous checkpoint)
        if self.new_checkpoint:
            self._lastclear = 0
        else:
            with self.io(self.checkpoint_file, "r") as fp:
                self._lastclear = fp.niterations
        if self.target_eff_nsamples is not None:
            target_nsamples = self.target_eff_nsamples
            with self.io(self.checkpoint_file, "r") as fp:
                nsamples = fp.effective_nsamples
        elif self.target_niterations is not None:
            # the number of samples is the number of iterations times the
            # number of walkers
            target_nsamples = self.nwalkers * self.target_niterations
            nsamples = self._lastclear * self.nwalkers
        else:
            raise ValueError("must set either target_eff_nsamples or "
                             "target_niterations; see set_target")
        self._itercounter = 0
        # figure out the interval to use
        iterinterval = self.checkpoint_interval
        if iterinterval is None:
            iterinterval = self.target_niterations
        # run sampler until we have the desired number of samples
        while nsamples < target_nsamples:
            # adjust the interval if we would go past the number of iterations
            if self.target_niterations is not None and (
                    self.niterations + iterinterval > self.target_niterations):
                iterinterval = self.target_niterations - self.niterations
            # run sampler and set initial values to None so that sampler
            # picks up from where it left off next call
            logging.info("Running sampler for {} to {} iterations".format(
                self.niterations, self.niterations + iterinterval))
            # run the underlying sampler for the desired interval
            self.run_mcmc(iterinterval)
            # update the itercounter
            self._itercounter = self._itercounter + iterinterval
            # dump the current results
            self.checkpoint()
            # update nsamples for next loop
            if self.target_eff_nsamples is not None:
                nsamples = self.effective_nsamples
                logging.info("Have {} effective samples post burn in".format(
                    nsamples))
            else:
                nsamples += iterinterval * self.nwalkers
41106
func (samplerOptions) SamplingRefreshInterval(samplingRefreshInterval time.Duration) SamplerOption {
	return func(o *samplerOptions) {
		o.samplingRefreshInterval = samplingRefreshInterval
	}
}
703835
public void waitUntil(Sampler<Boolean> variable, Ticker ticker) {
        waitUntil(variable, ticker, isQuietlyTrue());
    }
349638
protected void purgeObsoleteSamples(MetricConfig config, long now) {
        long expireAge = config.samples() * config.timeWindowMs();
        for (int i = 0; i < samples.size(); i++) {
            Sample sample = this.samples.get(i);
            if (now - sample.lastWindowMs >= expireAge) {
                // The samples array is used as a circular list. The rank represents how many spots behind the current
                // window is window #i at. The current sample is rank 0, the next older sample is 1 and so on until
                // the oldest sample, which has a rank equal to samples.size() - 1.
                int rank = current - i;
                if (rank < 0) {
                    rank += samples.size();
                }
                // Here we reset the expired window to a time in the past that is offset proportionally to its rank.
                sample.reset(now - rank * config.timeWindowMs());
            }
        }
    }
1084368
def iterate(self, params, repetition, iteration):
    
    print("\nStarting iteration",iteration)
    print("Learning rate:", self.learningRate if self.lr_scheduler is None
                                              else self.lr_scheduler.get_lr())
    t1 = time.time()
    ret = {}

    # Update dataset epoch when using pre-processed speech dataset
    if self.use_preprocessed_dataset:
      t2 = time.time()
      self.train_loader.dataset.next_epoch()
      self.validation_loader.dataset.next_epoch()
      self.test_loader.dataset.next_epoch()
      self.bg_noise_loader.dataset.next_epoch()
      print("Dataset Load time = {0:.3f} secs, ".format(time.time() - t2))

    # Update learning rate using learning rate scheduler if configured
    if self.lr_scheduler is not None:
      # ReduceLROnPlateau lr_scheduler step should be called after validation,
      # all other lr_schedulers should be called before training
      if params["lr_scheduler"] != "ReduceLROnPlateau":
        self.lr_scheduler.step()

    self.train(params, epoch=iteration, repetition=repetition)

    # Run validation test
    if self.validation_loader is not None:
      validation = self.test(params, self.validation_loader)

      # ReduceLROnPlateau step should be called after validation
      if params["lr_scheduler"] == "ReduceLROnPlateau":
        self.lr_scheduler.step(validation["test_loss"])

      ret["validation"] = validation
      print("Validation: error=", validation["testerror"],
            "entropy=", validation["entropy"],
            "loss=", validation["test_loss"])
      ret.update({"validationerror": validation["testerror"]})

    # Run test set
    if self.test_loader is not None:
      testResults = self.test(params, self.test_loader)
      ret["testResults"] = testResults
      print("Test: error=", testResults["testerror"],
            "entropy=", testResults["entropy"],
            "loss=", testResults["test_loss"])
      ret.update({"testerror": testResults["testerror"]})

    # Run bg noise set
    if self.bg_noise_loader is not None:
      bgResults = self.test(params, self.bg_noise_loader)
      ret["bgResults"] = bgResults
      print("BG noise error=", bgResults["testerror"])
      ret.update({"bgerror": bgResults["testerror"]})

    ret.update({"elapsedTime": time.time() - self.startTime})
    ret.update({"learningRate": self.learningRate if self.lr_scheduler is None
                                                  else self.lr_scheduler.get_lr()})

    # Run noise set
    if params.get("run_noise_tests", False):
      ret.update(self.runNoiseTests(params))
      print("Noise test results: totalCorrect=", ret["totalCorrect"],
            "Test error=", ret["testerror"], ", entropy=", ret["entropy"])

    ret.update({"elapsedTime": time.time() - self.startTime})
    ret.update({"learningRate": self.learningRate if self.lr_scheduler is None
                                                  else self.lr_scheduler.get_lr()})

    print("Iteration time= {0:.3f} secs, "
          "total elapsed time= {1:.3f} mins".format(
            time.time() - t1,ret["elapsedTime"]/60.0))

    return ret
318817
public void addZoomIntervalConfiguration(String zoomIntervalConfiguaration) {
        if (zoomIntervalConfiguaration != null) {
            setZoomIntervalConfiguration(ZoomIntervalConfiguration.fromString(zoomIntervalConfiguaration));
        } else {
            setZoomIntervalConfiguration(ZoomIntervalConfiguration.getStandardConfiguration());
        }
    }
1023434
public boolean sendSample(SampleMessage sampleMessage) {
    if (!this.canSendSamples) {
      log.warn("Cannot send samples.");
      return false;
    }

    if (this.session.getScheduledWriteMessages() > this.maxOutstandingSamples) {
      log.warn("Buffer full, cannot send sample.");
      return false;
    }
    this.session.write(sampleMessage);
    return true;
  }
430529
def set_sampling_info(self, sample):
        
        if sample.getScheduledSamplingSampler() and sample.getSamplingDate():
            return True
        sampler = self.get_form_value("getScheduledSamplingSampler", sample,
                                      sample.getScheduledSamplingSampler())
        sampled = self.get_form_value("getSamplingDate",
                                      sample.getSamplingDate())
        if not all([sampler, sampled]):
            return False
        sample.setScheduledSamplingSampler(sampler)
        sample.setSamplingDate(DateTime(sampled))
        return True
1012338
public void setRefreshFrequency(IntervalFrequency frequency) {
        if (NONE_REFRESH_INTERVAL == mRefreshInterval && IntervalFrequency.NONE != frequency) {
            // Install draw-frame listener if frequency is no longer NONE
            getGVRContext().unregisterDrawFrameListener(mFrameListener);
            getGVRContext().registerDrawFrameListener(mFrameListener);
        }
        switch (frequency) {
            case REALTIME:
                mRefreshInterval = REALTIME_REFRESH_INTERVAL;
                break;
            case HIGH:
                mRefreshInterval = HIGH_REFRESH_INTERVAL;
                break;
            case MEDIUM:
                mRefreshInterval = MEDIUM_REFRESH_INTERVAL;
                break;
            case LOW:
                mRefreshInterval = LOW_REFRESH_INTERVAL;
                break;
            case NONE:
                mRefreshInterval = NONE_REFRESH_INTERVAL;
                break;
            default:
                break;
        }
    }
1227324
private void runIntervalTagger(JCas jcas) {
		logger.log(Level.FINEST, "Running Interval Tagger...");
		Integer beforeAnnotations = jcas.getAnnotationIndex().size();
		
		// Prepare the options for IntervalTagger's execution
		Properties settings = new Properties();
		settings.put(IntervalTagger.PARAM_LANGUAGE, language.getResourceFolder());
		settings.put(IntervalTagger.PARAM_INTERVALS, true);
		settings.put(IntervalTagger.PARAM_INTERVAL_CANDIDATES, false);
		
		// Instantiate and process with IntervalTagger
		IntervalTaggerWrapper iTagger = new IntervalTaggerWrapper();
		iTagger.initialize(settings);
		iTagger.process(jcas);
		
		// debug output
		Integer afterAnnotations = jcas.getAnnotationIndex().size();
		logger.log(Level.FINEST, "Annotation delta: " + (afterAnnotations - beforeAnnotations));
	}
549824
protected void initTopLevelState(APMSpan topSpan, TraceRecorder recorder, ContextSampler sampler) {
        nodeBuilder = new NodeBuilder();
        traceContext = new TraceContext(topSpan, nodeBuilder, recorder, sampler);
    }
751470
public static void main(String[] args) {

    // WARNING: Be careful before you set sampler value to always sample, especially in
    // production environment. Trace data is often very large in size and is expensive to
    // collect. This is why rather than collecting traces for every request(i.e. alwaysSample),
    // downsampling is prefered.
    //
    // By default, OpenCensus provides a probabilistic sampler that will trace once in every
    // 10,000 requests, that's why if default probabilistic sampler is used
    // you might not see trace data printed or exported and this is expected behavior.

    TraceConfig traceConfig = Tracing.getTraceConfig();
    traceConfig.updateActiveTraceParams(
        traceConfig.getActiveTraceParams().toBuilder().setSampler(Samplers.alwaysSample()).build());

    LoggingTraceExporter.register();
    doWork();

    // Wait for a duration longer than reporting duration (5s) to ensure spans are exported.
    // Spans are exported every 5 seconds
    sleep(5100);
  }
1022415
public void record(double sample, TimeUnit timeUnit) {
        rotate();
        final long sampleNanos = (long) TimeUtils.convert(sample, timeUnit, TimeUnit.NANOSECONDS);
        for (AtomicLong max : ringBuffer) {
            updateMax(max, sampleNanos);
        }
    }
1107342
public final void sample()
  {
    synchronized (_lock) {
      long count = _totalCount.get();
      long lastCount = _lastAvgTotalCount;
      _lastAvgTotalCount = count;

      long sum = _sum.get();
      double lastSum = _lastAvgSum;
      _lastAvgSum = sum;

      if (count == lastCount) {
        _avg =  0;
      }
      else {
        _avg = _scale * (sum - lastSum) / (double) (count - lastCount);
      }
    }
  }