Returns a function which get the expectations by sampling the measured circuit
355207
def get_measurement_sampler(n_sample, run_options=None):
    """"""
    if run_options is None:
        run_options = {}

    def sampling_by_measurement(circuit, meas):
        def reduce_bits(bits, meas):
            bits = [int(x) for x in bits[::-1]]
            return tuple(bits[m] for m in meas)

        meas = tuple(meas)
        circuit.measure[meas]
        counter = circuit.run(shots=n_sample, returns="shots", **run_options)
        counts = Counter({reduce_bits(bits, meas): val for bits, val in counter.items()})
        return {k: v / n_sample for k, v in counts.items()}

    return sampling_by_measurement
1020302
def sample_observed_state(self, s: pd.Series) -> Dict:
        

        return {
            n[0]: {
                i.name: np.random.normal(s[n[0]] * i.mean, i.stdev)
                for i in n[1]["indicators"].values()
            }
            for n in self.nodes(data=True)
        }
509046
def _function(self):
        
        plant = self.instruments['plant']['instance']
        controler = self.instruments['controler']['instance']
        plant.update(self.instruments['plant']['settings'])
        controler.update(self.instruments['controler']['settings'])

        time_step = 1./self.settings['sample rate']

        controler.update({'time_step': time_step})
        self.last_plot = datetime.datetime.now()

        controler.reset()
        # if length changed we have to redefine the queue and carry over the data
        if self.data['plant_output'].maxlen != self.settings['buffer_length']:
            plant_output = deepcopy(self.data['plant_output'])
            control_output = deepcopy(self.data['control_output'])
            self.data = {'plant_output': deque(maxlen=self.settings['buffer_length']),
                         'control_output': deque(maxlen=self.settings['buffer_length'])}

            x = list(range(min(len(plant_output), self.settings['buffer_length'])))
            x.reverse()
            for i in x:
                self.data['plant_output'].append(plant_output[-i-1])
                self.data['control_output'].append(control_output[-i - 1])

        while not self._abort:

            measurement = plant.output

            self.data['plant_output'].append(measurement)
            control_value = controler.controler_output(measurement)
            self.data['control_output'].append(control_value)

            if self.settings['on/off']:
                print(('set plant control', control_value))
                plant.control = float(control_value)

            self.progress = 50
            self.updateProgress.emit(self.progress)

            time.sleep(time_step)
1096549
@Override
	public Iterator<T> sample(final Iterator<T> input) {
		if (fraction == 0) {
			return emptyIterable;
		}

		return new SampledIterator<T>() {
			T current = null;

			@Override
			public boolean hasNext() {
				if (current == null) {
					current = getNextSampledElement();
				}

				return current != null;
			}

			@Override
			public T next() {
				if (current == null) {
					return getNextSampledElement();
				} else {
					T result = current;
					current = null;

					return result;
				}
			}

			private T getNextSampledElement() {
				if (fraction <= THRESHOLD) {
					double rand = random.nextDouble();
					double u = Math.max(rand, EPSILON);
					int gap = (int) (Math.log(u) / Math.log(1 - fraction));
					int elementCount = 0;
					if (input.hasNext()) {
						T element = input.next();
						while (input.hasNext() && elementCount < gap) {
							element = input.next();
							elementCount++;
						}
						if (elementCount < gap) {
							return null;
						} else {
							return element;
						}
					} else {
						return null;
					}
				} else {
					while (input.hasNext()) {
						T element = input.next();

						if (random.nextDouble() <= fraction) {
							return element;
						}
					}
					return null;
				}
			}
		};
	}
295096
def expectation(self, operator: Union[PauliTerm, PauliSum]):
        
        if not isinstance(operator, PauliSum):
            operator = PauliSum([operator])

        return sum(_term_expectation(self.wf, term, n_qubits=self.n_qubits) for term in operator)
1251758
function sample_variance(x) {
        // The variance of no numbers is null
        if (x.length <= 1) return null;

        var sum_squared_deviations_value = sum_nth_power_deviations(x, 2);

        // Find the mean value of that list
        return sum_squared_deviations_value / (x.length - 1);
    }
138149
def rmse(y, p):
    

    # check and get number of samples
    assert y.shape == p.shape

    return np.sqrt(mse(y, p))
204873
function buildSample (sampleNumber, rawData, sendCounts) {
  let sample;
  if (sendCounts) {
    sample = newSampleNoScale(sampleNumber);
    sample.channelDataCounts = rawData;
  } else {
    sample = newSample(sampleNumber);
    for (let j = 0; j < k.OBCINumberOfChannelsGanglion; j++) {
      sample.channelData.push(rawData[j] * k.OBCIGanglionScaleFactorPerCountVolts);
    }
  }
  sample.timestamp = Date.now();
  return sample;
}
232639
def _sample_points(X, centers, oversampling_factor, random_state):
    

    """
    # re-implement evaluate_cost here, to avoid redundant computation
    distances = pairwise_distances(X, centers).min(1) ** 2
    denom = distances.sum()
    p = oversampling_factor * distances / denom

    draws = random_state.uniform(size=len(p), chunks=p.chunks)
    picked = p > draws

    new_idxs, = da.where(picked)
    return new_idxs
119159
function(ts, val) {
      var sample = new PowerSample(this, ts, val);
      this.samples_.push(sample);
      return sample;
    }
1321472
function getSamplerSetFunction( type, location, gl, context ){
  var unit = context.texIndex++;
  return function(){
    if( arguments.length === 1 ) {
      if( arguments[0].bind !== undefined ){ // is texture
        arguments[0].bind( unit );
        gl.uniform1i( location, unit );
      } else {
        gl.uniform1i( location, arguments[0] );
      }
    }
    return location;
  };
}
569886
def _simulate_measurement(self, op: ops.Operation, data: _StateAndBuffer,
            indices: List[int], measurements: Dict[str, List[bool]],
            num_qubits: int) -> None:
        """"""
        meas = ops.op_gate_of_type(op, ops.MeasurementGate)
        # TODO: support measurement outside computational basis.
        if meas:
            invert_mask = meas.invert_mask or num_qubits * (False,)
            # Measure updates inline.
            bits, _ = wave_function.measure_state_vector(data.state,
                                                         indices,
                                                         data.state)
            corrected = [bit ^ mask for bit, mask in
                         zip(bits, invert_mask)]
            key = protocols.measurement_key(meas)
            measurements[key].extend(corrected)
499694
def _expectation(p, mean, none1, none2, none3, nghp=None):
    
    return mean(p.mu)
164289
function sample(alpha, beta) {
    var u = jStat.randg(alpha);
    return u / (u + jStat.randg(beta));
  }
977586
def _expectation(p, kern1, feat1, kern2, feat2, nghp=None):
    
    """
    crossexps = []

    if kern1 == kern2 and feat1 == feat2:  # avoid duplicate computation by using transposes
        for i, k1 in enumerate(kern1.kernels):
            crossexps.append(expectation(p, (k1, feat1), (k1, feat1), nghp=nghp))

            for k2 in kern1.kernels[:i]:
                eKK = expectation(p, (k1, feat1), (k2, feat2), nghp=nghp)
                eKK += tf.matrix_transpose(eKK)
                crossexps.append(eKK)
    else:
        for k1, k2 in it.product(kern1.kernels, kern2.kernels):
            crossexps.append(expectation(p, (k1, feat1), (k2, feat2), nghp=nghp))

    return functools.reduce(tf.add, crossexps)
60686
def expects(self, prop):
        
        expectation = SinonExpectation(self.obj, prop)
        self.exp_list.append(expectation)
        return expectation
370801
def _expectation(self, X):
        """"""

        # Calculate probabilities of X belonging to the different clusters
        weighted_likelihoods = self._get_likelihoods(X) * self.priors
        sum_likelihoods = np.expand_dims(np.sum(weighted_likelihoods, axis=1), axis=1)
        # Determine responsibility as P(X|y)*P(y)/P(X)
        self.responsibility = weighted_likelihoods / sum_likelihoods
        # Assign samples to cluster that has largest probability
        self.sample_assignments = self.responsibility.argmax(axis=1)
        # Save value for convergence check
        self.responsibilities.append(np.max(self.responsibility, axis=1))