Updates the hidden-state transition matrix and the initial distribution
174757
def _updateTransitionMatrix(self):
        
        # TRANSITION MATRIX
        C = self.model.count_matrix() + self.prior_C  # posterior count matrix

        # check if we work with these options
        if self.reversible and not _tmatrix_disconnected.is_connected(C, strong=True):
            raise NotImplementedError('Encountered disconnected count matrix with sampling option reversible:\n '
                                      + str(C) + '\nUse prior to ensure connectivity or use reversible=False.')
        # ensure consistent sparsity pattern (P0 might have additional zeros because of underflows)
        # TODO: these steps work around a bug in msmtools. Should be fixed there
        P0 = msmest.transition_matrix(C, reversible=self.reversible, maxiter=10000, warn_not_converged=False)
        zeros = np.where(P0 + P0.T == 0)
        C[zeros] = 0
        # run sampler
        Tij = msmest.sample_tmatrix(C, nsample=1, nsteps=self.transition_matrix_sampling_steps,
                                    reversible=self.reversible)

        # INITIAL DISTRIBUTION
        if self.stationary:  # p0 is consistent with P
            p0 = _tmatrix_disconnected.stationary_distribution(Tij, C=C)
        else:
            n0 = self.model.count_init().astype(float)
            first_timestep_counts_with_prior = n0 + self.prior_n0
            positive = first_timestep_counts_with_prior > 0
            p0 = np.zeros_like(n0)
            p0[positive] = np.random.dirichlet(first_timestep_counts_with_prior[positive])  # sample p0 from posterior

        # update HMM with new sample
        self.model.update(p0, Tij)
559615
def transition(prior_state, next_state):
    
    if next_state not in STATES[prior_state][TRANSITION]:
        acceptable = STATES[prior_state][TRANSITION]
        err = "cannot {}->{} may only {}->{}".format(prior_state,
                                                     next_state,
                                                     prior_state,
                                                     acceptable)
        raise InvalidStateTransition(err)
    return next_state
1183464
function generateTransitionHelpers(currentState, parsedStates) {
  const buildFnBody = state => (...args) => {
    return PossibleStatesContainer({current: state, data: zip(state.data, args), allStates: parsedStates})
  }

  return parsedStates.reduce(
    (transitions, state) => ({...transitions, [buildFnName('to', state.name)]: buildFnBody(state)}),
    {}
  )
}
146505
def add_state(self, new_data, method='inc'):
        """"""
        self.sfx.append(0)
        self.rsfx.append([])
        self.trn.append([])
        self.lrs.append(0)

        # Experiment with pointer-based
        self.f_array.add(new_data)

        self.n_states += 1
        i = self.n_states - 1

        # assign new transition from state i-1 to i
        self.trn[i - 1].append(i)
        k = self.sfx[i - 1]
        pi_1 = i - 1

        # iteratively backtrack suffixes from state i-1
        if method == 'inc':
            suffix_candidate = 0
        elif method == 'complete':
            suffix_candidate = []
        else:
            suffix_candidate = 0

        while k is not None:

            if self.params['dfunc'] == 'other':
                # dvec = self.dfunc_handle([new_data],
                #                          self.f_array[self.trn[k]])[0]
                dvec = dist.cdist([new_data],
                                  self.f_array[self.trn[k]],
                                  metric=self.params['dfunc_handle'])[0]
            else:
                dvec = dist.cdist([new_data],
                                  self.f_array[self.trn[k]],
                                  metric=self.params['dfunc'])[0]

            I = np.where(dvec < self.params['threshold'])[0]
            if len(I) == 0:  # if no transition from suffix
                self.trn[k].append(i)  # Add new forward link to unvisited state
                pi_1 = k
                if method != 'complete':
                    k = self.sfx[k]
            else:
                if method == 'inc':
                    if I.shape[0] == 1:
                        suffix_candidate = self.trn[k][I[0]]
                    else:
                        suffix_candidate = self.trn[k][I[np.argmin(dvec[I])]]
                    break
                elif method == 'complete':
                    suffix_candidate.append((self.trn[k][I[np.argmin(dvec[I])]],
                                             np.min(dvec)))
                else:
                    suffix_candidate = self.trn[k][I[np.argmin(dvec[I])]]
                    break

            if method == 'complete':
                k = self.sfx[k]

        if method == 'complete':
            if not suffix_candidate:
                self.sfx[i] = 0
                self.lrs[i] = 0
                self.latent.append([i])
                self.data.append(len(self.latent) - 1)
            else:
                sorted_suffix_candidates = sorted(suffix_candidate,
                                                  key=lambda suffix: suffix[1])
                self.sfx[i] = sorted_suffix_candidates[0][0]
                self.lrs[i] = self._len_common_suffix(pi_1, self.sfx[i] - 1) + 1
                self.latent[self.data[self.sfx[i]]].append(i)
                self.data.append(self.data[self.sfx[i]])
        else:
            if k is None:
                self.sfx[i] = 0
                self.lrs[i] = 0
                self.latent.append([i])
                self.data.append(len(self.latent) - 1)
            else:
                self.sfx[i] = suffix_candidate
                self.lrs[i] = self._len_common_suffix(pi_1, self.sfx[i] - 1) + 1
                self.latent[self.data[self.sfx[i]]].append(i)
                self.data.append(self.data[self.sfx[i]])

        # Temporary adjustment
        k = self._find_better(i, self.data[i - self.lrs[i]])
        if k is not None:
            self.lrs[i] += 1
            self.sfx[i] = k

        self.rsfx[self.sfx[i]].append(i)

        if self.lrs[i] > self.max_lrs[i - 1]:
            self.max_lrs.append(self.lrs[i])
        else:
            self.max_lrs.append(self.max_lrs[i - 1])

        self.avg_lrs.append(self.avg_lrs[i - 1] * ((i - 1.0) / (self.n_states - 1.0)) +
                            self.lrs[i] * (1.0 / (self.n_states - 1.0)))
1065244
def forward_state(self, sequence, state=None):
        
        if state is None:
            state = self.zero_state(sequence.size(0))

        data = self.input_block(sequence)

        state_outputs = []

        # for layer_length, layer in zip(self.hidden_layers, self.recurrent_layers):
        for idx in range(len(self.recurrent_layers)):
            layer_length = self.recurrent_layers[idx].state_dim

            # Partition hidden state, for each layer we have layer_length of h state and layer_length of c state
            current_state = state[:, :, :layer_length]
            state = state[:, :, layer_length:]

            # Propagate through the GRU state
            data, new_h = self.recurrent_layers[idx](data, current_state)

            if self.dropout_layers:
                data = self.dropout_layers[idx](data)

            state_outputs.append(new_h)

        output_data = self.output_activation(self.output_layer(data))

        concatenated_hidden_output = torch.cat(state_outputs, dim=2)

        return output_data, concatenated_hidden_output
362156
protected void upgradeSolution( DMatrixRMaj X ) {
        DMatrixRMaj z = Y; // recycle Y

        // compute the z which will minimize the 2-norm of X
        // because of the identity matrix tacked onto the end 'A' should never be singular
        if( !internalSolver.setA(W) )
            throw new RuntimeException("This should never happen.  Is input NaN?");
        z.reshape(numCols-rank,1);
        internalSolver.solve(X, z);

        // compute X by tweaking the original
        CommonOps_DDRM.multAdd(-1, W, z, X);
    }
959208
public function updateStateTransitionMatrix(array $matrix)
    {
        // Do some cleanup, we don't need to store too many things
        foreach ($matrix as $from => $toList) {
            foreach ($toList as $to => $roleList) {
                $current = array_filter($roleList);
                if ($from == $to || empty($current)) {
                    unset($matrix[$from][$to]);
                } else {
                    // Store the role list as key-value for easier usage
                    $matrix[$from][$to] = array_combine($current, $current);
                }
            }
        }
        variable_set('ucms_site_state_transition_matrix', $matrix);
    }
576618
def _init_state(self, initial_state: Union[int, np.ndarray]):
        """"""
        state = np.reshape(
            sim.to_valid_state_vector(initial_state, self._num_qubits),
            (self._num_shards, self._shard_size))
        state_handle = mem_manager.SharedMemManager.create_array(
            state.view(dtype=np.float32))
        self._shared_mem_dict['state_handle'] = state_handle
141355
def transitionStates(self,state):
        
        newstates,rates         = self.transition(state)              
        newindices              = self.getStateIndex(newstates)
        return newindices,rates
1031801
def parameters_changed(self):
        
        # Get the model matrices from the kernel
        (F,L,Qc,H,Pinf,dF,dQc,dPinf) = self.kern.sde()

        # Use the Kalman filter to evaluate the likelihood
        self._log_marginal_likelihood = self.kf_likelihood(F,L,Qc,H,self.sigma2,Pinf,self.X.T,self.Y.T)
        gradients  = self.compute_gradients()
        self.sigma2.gradient_full[:] = gradients[-1]
        self.kern.gradient_full[:] = gradients[:-1]
436528
def update(self, es, function_values, **kwargs):
        
        # TODO: on the linear function, the two mirrored samples lead
        # to a sharp increase of condition of the covariance matrix.
        # They should not be used to update the covariance matrix,
        # if the step-size inreases quickly. This should be fine with
        # negative updates though.
        if not self.initialized:
            self.initialize(es.N, es.opts)
        if 1 < 3:
            # use the ranking difference of the mirrors for adaptation
            # damp = 5 should be fine
            z = np.where(es.fit.idx == 1)[0][0] - np.where(es.fit.idx == 0)[0][0]
            z /= es.popsize - 1  # z in [-1, 1]
        self.s = (1 - self.sp.c) * self.s + self.sp.c * np.sign(z) * np.abs(z)**self.sp.z_exponent
        if self.s > 0:
            es.sigma *= exp(self.s / self.sp.dampup)
        else:
            es.sigma *= exp(self.s / self.sp.dampdown)
1263571
private void update() {
        if (!predefinedPriori) {
            for (int c = 0; c < k; c++) {
                priori[c] = (nc[c] + EPSILON) / (n + k * EPSILON);
            }
        }

        if (model == Model.MULTINOMIAL || model == Model.POLYAURN) {
            for (int c = 0; c < k; c++) {
                for (int t = 0; t < p; t++) {
                    condprob[c][t] = (ntc[c][t] + sigma) / (nt[c] + sigma * p);
                }
            }
        } else {
            for (int c = 0; c < k; c++) {
                for (int t = 0; t < p; t++) {
                    condprob[c][t] = (ntc[c][t] + sigma) / (nc[c] + sigma * 2);
                }
            }
        }
    }
655649
function initializeStates()
    {
        // Set all states to NOT_READY
        var numVertices = graph.vertexCount();
        var vertexIds = graph.getVertexIds();

        for(var i = 0; i < numVertices; i++)
        {
            graph.getVertex(vertexIds[i]).setState("NOT_READY");
        }
    }
1240988
def determinize(m):
    """"""
    if not m.is_finite():
        raise TypeError("machine must be a finite automaton")

    transitions = collections.defaultdict(lambda: collections.defaultdict(set))
    alphabet = set()
    for transition in m.get_transitions():
        [[lstate], read] = transition.lhs
        [[rstate]] = transition.rhs
        if len(read) > 1:
            raise NotSupportedException("multiple input symbols on transition not supported")
        if len(read) == 1:
            alphabet.add(read[0])
        transitions[lstate][tuple(read)].add(rstate)

    class Set(frozenset):
        def __str__(self):
            return "{{{}}}".format(",".join(map(str, sorted(self))))
        def _repr_html_(self):
            return "{{{}}}".format(",".join(x._repr_html_() for x in sorted(self)))

    def eclosure(states):
        """Find epsilon-closure of set of states"""
        states = set(states)
        frontier = set(states)
        while len(frontier) > 0:
            lstate = frontier.pop()
            for rstate in transitions[lstate][()]:
                if rstate not in states:
                    states.add(rstate)
                    frontier.add(rstate)
        return states

    dm = FiniteAutomaton()

    start_state = Set(eclosure([m.get_start_state()]))
    dm.set_start_state(start_state)

    frontier = {start_state}
    visited = set()
    while len(frontier) > 0:
        lstates = frontier.pop()
        if lstates in visited:
            continue
        visited.add(lstates)
        dtransitions = collections.defaultdict(set)
        for lstate in lstates:
            for read in alphabet:
                dtransitions[read] |= transitions[lstate][(read,)]
        for read in alphabet:
            rstates = Set(eclosure(dtransitions[read]))
            dm.add_transition([[lstates], read], [[rstates]])
            frontier.add(rstates)

    accept_states = set(m.get_accept_states())
    for states in visited:
        if len(states & accept_states) > 0:
            dm.add_accept_state(states)

    return dm
130646
def _generate_standard_transitions(cls):
        """"""
        allowed_transitions = cls.context.get_config('transitions', {})
        for key, transitions in allowed_transitions.items():
            key = cls.context.new_meta['translator'].translate(key)

            new_transitions = set()
            for trans in transitions:
                if not isinstance(trans, Enum):
                    trans = cls.context.new_meta['translator'].translate(trans)
                new_transitions.add(trans)

            cls.context.new_transitions[key] = new_transitions

        for state in cls.context.states_enum:
            if state not in cls.context.new_transitions:
                cls.context.new_transitions[state] = set()
1156744
def parameters_changed(self):
        
        # using the warped X to update
        self.X = self.transform_data(self.X_untransformed)
        super(InputWarpedGP, self).parameters_changed()
        # the gradient of log likelihood w.r.t. input AFTER warping is a product of dL_dK and dK_dX
        dL_dX = self.kern.gradients_X(self.grad_dict['dL_dK'], self.X)
        self.warping_function.update_grads(self.X_untransformed, dL_dX)
703872
private RealMatrix firstLayer(RealMatrix input)
	{
		RealMatrix hidden = (this.weightsOne.multiply(input)).scalarAdd(this.biasOne);
		double[] tempValues = new double[this.hiddenLayerSize];
		
		// Logistic function used for hidden layer activation
		for(int i = 0 ; i < this.hiddenLayerSize ; i++)
		{
			tempValues[i] = 1.0 / (1.0 + Math.pow(Math.E, -1.0*hidden.getEntry(i, 0)));
		}
		
		return new Array2DRowRealMatrix(tempValues);
	}