Sample a collection of observed state sequences from the likelihood
        model given a collection of transition matrices.

        Args:
            n_timesteps: The number of timesteps for the sequences.
167945
def sample_from_likelihood(self, n_timesteps=10):
        

        self.latent_state_sequences = lmap(
            lambda A: ltake(
                n_timesteps,
                iterate(
                    lambda s: pd.Series(A @ s.values, index=s.index), self.s0
                ),
            ),
            self.transition_matrix_collection,
        )

        self.observed_state_sequences = [
            [self.sample_observed_state(s) for s in latent_state_sequence]
            for latent_state_sequence in self.latent_state_sequences
        ]
867655
private List<SequenceState<State, Observation, Path>> computeViterbiSequence(
            List<TimeStep<State, Observation, Path>> timeSteps, int originalGpxEntriesCount,
            QueryGraph queryGraph) {
        final HmmProbabilities probabilities
                = new HmmProbabilities(measurementErrorSigma, transitionProbabilityBeta);
        final ViterbiAlgorithm<State, Observation, Path> viterbi = new ViterbiAlgorithm<>();

        logger.debug("\n=============== Paths ===============");
        int timeStepCounter = 0;
        TimeStep<State, Observation, Path> prevTimeStep = null;
        int i = 1;
        for (TimeStep<State, Observation, Path> timeStep : timeSteps) {
            logger.debug("\nPaths to time step {}", i++);
            computeEmissionProbabilities(timeStep, probabilities);

            if (prevTimeStep == null) {
                viterbi.startWithInitialObservation(timeStep.observation, timeStep.candidates,
                        timeStep.emissionLogProbabilities);
            } else {
                computeTransitionProbabilities(prevTimeStep, timeStep, probabilities, queryGraph);
                viterbi.nextStep(timeStep.observation, timeStep.candidates,
                        timeStep.emissionLogProbabilities, timeStep.transitionLogProbabilities,
                        timeStep.roadPaths);
            }
            if (viterbi.isBroken()) {
                String likelyReasonStr = "";
                if (prevTimeStep != null) {
                    Observation prevGPXE = prevTimeStep.observation;
                    Observation gpxe = timeStep.observation;
                    double dist = distanceCalc.calcDist(prevGPXE.getPoint().lat, prevGPXE.getPoint().lon,
                            gpxe.getPoint().lat, gpxe.getPoint().lon);
                    if (dist > 2000) {
                        likelyReasonStr = "Too long distance to previous measurement? "
                                + Math.round(dist) + "m, ";
                    }
                }

                throw new IllegalArgumentException("Sequence is broken for submitted track at time step "
                        + timeStepCounter + " (" + originalGpxEntriesCount + " points). "
                        + likelyReasonStr + "observation:" + timeStep.observation + ", "
                        + timeStep.candidates.size() + " candidates: "
                        + getSnappedCandidates(timeStep.candidates)
                        + ". If a match is expected consider increasing max_visited_nodes.");
            }

            timeStepCounter++;
            prevTimeStep = timeStep;
        }

        return viterbi.computeMostLikelySequence();
    }
221406
def sample(self, sampling_period, start=None, end=None,
               interpolate='previous'):
        
        start, end, mask = self._check_boundaries(start, end)

        sampling_period = \
            self._check_regularization(start, end, sampling_period)

        result = []
        current_time = start
        while current_time <= end:
            value = self.get(current_time, interpolate=interpolate)
            result.append((current_time, value))
            current_time += sampling_period
        return result
593626
def _make_sampling_sequence(n):
    # type: (int) -> List[int]
    
    seq = list(range(5))
    i = 50
    while len(seq) < n:
        seq.append(i)
        i += 50
    return seq
1039503
def numSteps(self, row):
        
        param = self._parameters[row]
        return self.nStepsForParam(param)
480883
def get_trajectories(self, indexes, rollout_length):
        
        # assert indexes.shape[0] > 1, "There must be multiple indexes supplied"
        assert rollout_length > 1, "Rollout length must be greater than 1"

        batch_indexes = (
                indexes.reshape(1, indexes.shape[0]) - np.arange(rollout_length - 1, -1, -1).reshape(rollout_length, 1)
        )

        return self.get_transitions(batch_indexes)
632785
def _learnOnNewSegments(connections, rng, newSegmentCells, growthCandidates,
                          initialPermanence, sampleSize, maxSynapsesPerSegment):
    

    numNewSynapses = len(growthCandidates)

    if sampleSize != -1:
      numNewSynapses = min(numNewSynapses, sampleSize)

    if maxSynapsesPerSegment != -1:
      numNewSynapses = min(numNewSynapses, maxSynapsesPerSegment)

    newSegments = connections.createSegments(newSegmentCells)
    connections.growSynapsesToSample(newSegments, growthCandidates,
                                     numNewSynapses, initialPermanence,
                                     rng)
1229846
def likelihood(self, samples):
        
        ret = np.ones(NUM_OF_INSTANCE)
        for i in range(NUM_OF_INSTANCE):
            for j in range(1, self.point_num + 1):
                ret[i] *= self.normal_distribution(j, samples[i])
        return ret
739306
def sample_from_prior(self):
        

        # simple_path_dict caches the results of the graph traversal that finds
        # simple paths between pairs of nodes, so that it doesn't have to be
        # executed for every sampled transition matrix.

        node_pairs = list(permutations(self.nodes(), 2))
        simple_path_dict = {
            node_pair: [
                list(pairwise(path))
                for path in nx.all_simple_paths(self, *node_pair)
            ]
            for node_pair in node_pairs
        }

        self.transition_matrix_collection = []

        elements = self.get_latent_state_components()

        for i in range(self.res):
            A = pd.DataFrame(
                np.identity(2 * len(self)), index=elements, columns=elements
            )

            for node in self.nodes:
                A[f"∂({node})/∂t"][node] = self.Δt

            for node_pair in node_pairs:
                A[f"∂({node_pair[0]})/∂t"][node_pair[1]] = sum(
                    np.prod(
                        [
                            self.edges[edge[0], edge[1]]["βs"][i]
                            for edge in simple_path_edge_list
                        ]
                    )
                    * self.Δt
                    for simple_path_edge_list in simple_path_dict[node_pair]
                )
            self.transition_matrix_collection.append(A)
894364
def _split_sequences_singletraj(dtraj, nstates, lag):
    
    sall = [[] for _ in range(nstates)]
    res_states = []
    res_seqs = []

    for t in range(len(dtraj)-lag):
        sall[dtraj[t]].append(dtraj[t+lag])

    for i in range(nstates):
        if len(sall[i]) > 0:
            res_states.append(i)
            res_seqs.append(np.array(sall[i]))
    return res_states, res_seqs
1211566
def get_state(self):
        

        self.step_methods = set()
        for s in self.stochastics:
            self.step_methods |= set(self.step_method_dict[s])

        state = Sampler.get_state(self)
        state['step_methods'] = {}

        # The state of each StepMethod.
        for sm in self.step_methods:
            state['step_methods'][sm._id] = sm.current_state().copy()

        return state
1005389
def temporal_segmentation(segments, min_time):
    
    final_segments = []
    for segment in segments:
        final_segments.append([])
        for point in segment:
            if point.dt > min_time:
                final_segments.append([])
            final_segments[-1].append(point)

    return final_segments
1118278
@Override
	public TimelineSample<StopwatchTimeRange> sample() {
		StopwatchTimeRange[] timeRangesCopy;
		synchronized (this) {
			timeRangesCopy = timeRanges.toArray(new StopwatchTimeRange[timeRanges.size()]);
		}
		// TODO sample each time-range by making a copy of it
		return new TimelineSample<>(timeRanges.getCapacity(), timeRangeWidth * SimonClock.NANOS_IN_MILLIS, timeRangesCopy);
	}
367382
def sample_bitstrings(self, n_samples):
        
        if self.rs is None:
            raise ValueError("You have tried to perform a stochastic operation without setting the "
                             "random state of the simulator. Might I suggest using a PyQVM object?")
        probabilities = np.real_if_close(np.diagonal(self.density))
        possible_bitstrings = all_bitstrings(self.n_qubits)
        inds = self.rs.choice(2 ** self.n_qubits, n_samples, p=probabilities)
        bitstrings = possible_bitstrings[inds, :]
        bitstrings = np.flip(bitstrings, axis=1)  # qubit ordering: 0 on the left.
        return bitstrings
1061927
def get_time_objects_from_model_timesteps(cls, times, start):
        
        modelTimestep = []
        newtimes = []

        for i in xrange(0, len(times)):
            try:
                modelTimestep.append(times[i+1] - times[i])
            except StandardError:
                modelTimestep.append(times[i] - times[i-1])
            newtimes.append(start + timedelta(seconds=times[i]))
      
        return (modelTimestep, newtimes)
1096992
def sub_hmm(self, states):
        

        """
        # restrict initial distribution
        pi_sub = self._Pi[states]
        pi_sub /= pi_sub.sum()

        # restrict transition matrix
        P_sub = self._Tij[states, :][:, states]
        # checks if this selection is possible
        assert np.all(P_sub.sum(axis=1) > 0), \
            'Illegal sub_hmm request: transition matrix cannot be normalized on ' + str(states)
        P_sub /= P_sub.sum(axis=1)[:, None]

        # restrict output model
        out_sub = self.output_model.sub_output_model(states)

        return HMM(pi_sub, P_sub, out_sub, lag=self.lag)
1256683
def _num_samples(x):
    """"""
    if hasattr(x, 'fit'):
        # Don't get num_samples from an ensembles length!
        raise TypeError('Expected sequence or array-like, got '
                        'estimator %s' % x)
    if not hasattr(x, '__len__') and not hasattr(x, 'shape'):
        if hasattr(x, '__array__'):
            x = np.asarray(x)
        else:
            raise TypeError("Expected sequence or array-like, got %s" %
                            type(x))
    if hasattr(x, 'shape'):
        if len(x.shape) == 0:
            raise TypeError("Singleton array %r cannot be considered"
                            " a valid collection." % x)
        return x.shape[0]
    else:
        return len(x)