Performs the Hopcroft minimization algorithm
        Args:
            None
        Returns:
            DFA: The minimized input DFA
967901
def hopcroft(self):
        

        def _getset(testset, partition):
            """
            Checks if a set is in a partition
            Args:
                testset (set): The examined set
                partition (list): A list of sets
            Returns:
                bool: A value indicating if it is a member or not
            """
            for part in partition:
                if set(testset) == set(part):
                    return True
            return None

        def _create_transitions_representation(graph):
            """
            In order to speedup the transition iteration using
            the alphabet, the function creates an index
            Args:
                graph (DFA): The input dfa
                state (DFA state): The examined state
            Returns:
                dict: The generated transition map
            """
            return {x.stateid:{self.isyms.find(arc.ilabel): arc.nextstate \
                               for arc in x} for x in graph.states}

        def _create_reverse_transitions_representation(graph):
            """
            In order to speedup the transition iteration using
            the alphabet, the function creates an index
            Args:
                graph (DFA): The input dfa
                state (DFA state): The examined state
            Returns:
                dict: The generated transition map
            """
            return {x.stateid: {self.isyms.find(arc.ilabel): arc.nextstate \
                                for arc in x} for x in graph.states}

        def _reverse_to_source(target, group1):
            """
            Args:
                target (dict): A table containing the reverse transitions for each state
                group1 (list): A group of states
            Return:
                Set: A set of states for which there is a transition with the states of the group
            """
            new_group = []
            for dst in group1:
                new_group += target[dst]
            return set(new_group)

        def _get_group_from_state(groups, sid):
            """
            Args:
                sid (int): The state identifier
            Return:
                int: The group identifier that the state belongs
            """
            for index, selectgroup in enumerate(groups):
                if sid in selectgroup:
                    return index

        def _delta(graph, cur_state, char):
            """
            Function describing the transitions
            Args:
                graph (DFA): The DFA states
                cur_state (DFA state): The DFA current state
                char (str):: The char that will be used for the transition
            Return:
                DFA Node: The next state
            """
            for arc in cur_state.arcs:
                if graph.isyms.find(arc.ilabel) == char:
                    return graph[arc.nextstate]

        def _partition_group(bookeeping, group):
            """
            Args:
                group (list):  A group of states
            Return:
                tuple: A set of two groups
            """
            for (group1, group2) in bookeeping:
                if group & group1 != set() and not group.issubset(group1):
                    new_g1 = group & group1
                    new_g2 = group - group1
                    return (new_g1, new_g2)
                if group & group2 != set() and not group.issubset(group2):
                    new_g1 = group & group2
                    new_g2 = group - group2
                    return (new_g1, new_g2)
            assert False, "Unmatched group partition"

        def _object_set_to_state_list(objectset):
            """
            Args:
                objectset (list): A list of all the DFA states (as objects)
            Return:
                list: A list of all the DFA states (as identifiers)
            """
            return [state.stateid for state in objectset]

        def _get_accepted(graph):
            """
            Find the accepted states
            Args:
                graph (DFA): The DFA states
            Return:
                list: Returns the list of the accepted states
            """
            return [state for state in graph \
                    if  state.final != TropicalWeight(float('inf'))]

        graph = self

        # Find Q
        set_q = set(_object_set_to_state_list(graph.states))
        # We will work with states addresses here instead of states stateid for
        # more convenience
        set_f = set(_object_set_to_state_list(_get_accepted(graph)))
        # Perform P := {F, Q-F}
        set_nf = set_q.copy() - set_f.copy()
        groups = [set_f.copy(), set_nf.copy()]
        bookeeping = [(set_f, set_nf)]

        done = False
        while not done:
            done = True
            new_groups = []
            for selectgroup in groups:
                # _check for each letter if it splits the current group
                for character in self.alphabet:
                    # print 'Testing symbol: ', c
                    target = defaultdict(list)
                    target_states = defaultdict(int)
                    new_g = [set(selectgroup)]
                    for sid in selectgroup:
                        # _check if all transitions using c are going in a state
                        # in the same group. If they are going on a different
                        # group then split
                        deststate = _delta(graph, graph[sid], character)
                        destgroup = _get_group_from_state(groups,
                            deststate.stateid)
                        target[destgroup].append(sid)
                        target_states[destgroup] = deststate.stateid
                    if len(target) > 1:

                        inv_target_states = {
                            v: k for k, v in target_states.iteritems()}
                        new_g = [set(selectedstate) for selectedstate in target.values()]
                        done = False
                        # Get all the partitions of destgroups
                        queue = [set([x for x in target_states.values()])]
                        while queue:
                            top = queue.pop(0)
                            (group1, group2) = _partition_group(bookeeping, top)
                            ng1 = _reverse_to_source(
                                target, [inv_target_states[x] for x in group1])
                            ng2 = _reverse_to_source(
                                target, [inv_target_states[x] for x in group2])

                            bookeeping.append((ng1, ng2))

                            if len(group1) > 1:
                                queue.append(group1)
                            if len(group2) > 1:
                                queue.append(group2)
                        break
                new_groups += new_g

            # End of iteration for the k-equivalence
            # Assign new groups and check if any change occured
            groups = new_groups

        # Make a copy of the old states, and prepare the
        # automaton to host the minimum states

        oldstates = copy.deepcopy(self.states)
        self.states = []
        self.define()

        def findpart(stateid, partitions):
            """Searches for the groupt that the state identifier
            belongs to.
            Args:
                stateid (int): The state identifier
                partitions (list): The list of the groups
            Returns:
                set: The group that the stateid belongs to.
            """
            for group in partitions:
                if stateid in group:
                    return frozenset(group)
            return frozenset(set(            ))

        def add_state_if_not_exists(group, statesmap, final):
            """
            Adds a new state in the final dfa. It initialy checks if
            the group of states is already registered to the automaton.
            If it is registered, the state identifier is returned, or
            else, a new state is added.
            Args:
                group (frozenset):  The group that the state identifier belongs
                statesmap (dict):   A dictionary that maintains the state
                                    identifiers for each forzenset
                final (bool):       A value indicating if the current state is
                                    final
            Returns:
                int: The new state identifier
            """
            if group not in statesmap:
                sid = self.add_state()
                self[sid].final = final
                statesmap[group] = sid
            return statesmap[group]

        statesmap = {}
        self.states = []
        group = findpart(0, groups)
        sid = add_state_if_not_exists(frozenset(list(group)), statesmap,
                                      oldstates[0].final)
        self[sid].initial = True
        for group in groups:
            if len(group) == 0:
                continue
            sid = add_state_if_not_exists(frozenset(group), statesmap,
                                          oldstates[list(group)[0]].final)
            state = next(iter(group))
            for arc in oldstates[state]:
                dst_group = findpart(arc.nextstate, groups)
                dst_sid = add_state_if_not_exists(
                    dst_group, statesmap, oldstates[arc.nextstate].final)
                self.add_arc(sid, dst_sid, graph.isyms.find(arc.ilabel))
670662
def factoring_qaoa(n_step, num, minimizer=None, sampler=None, verbose=True):
    
    def get_nbit(n):
        m = 1
        while 2**m < n:
            m += 1
        return m

    n1_bits = get_nbit(int(num**0.5)) - 1
    n2_bits = get_nbit(int(num**0.5))

    def mk_expr(offset, n):
        expr = pauli.Expr.from_number(1)
        for i in range(n):
            expr = expr + 2**(i + 1) * q(i + offset)
        return expr

    def bitseparator(bits):
        assert len(bits) == n1_bits + n2_bits
        p = 1
        m = 1
        for b in bits[:n1_bits]:
            if b:
                p += 2**m
            m += 1
        q = 1
        m = 1
        for b in bits[n1_bits:]:
            if b:
                q += 2**m
            m += 1
        return p, q

    hamiltonian = (num - mk_expr(0, n1_bits) * mk_expr(n1_bits, n2_bits))**2
    return vqe.Vqe(vqe.QaoaAnsatz(hamiltonian, n_step), minimizer, sampler), bitseparator
1106037
def main():
    
    if len(argv) < 3:
        print 'Usage for getting CFG: %s CFG_fileA CFG ' % argv[0]
        print 'Usage for getting STR: %s CFG_fileA STR ' \
              'Optimize[0 or 1] splitstring[0 or 1] ' % argv[0]
        print ''
        print 'For example: python pdacnf.py grammar.y STR 1 0'
        print '             python pdacnf.py grammar.y STR 1 1'
        print '             python pdacnf.py grammar.y CFG'
        return

    alphabet = createalphabet()

    mode = argv[2]

    optimized = 0
    splitstring = 0
    if mode == 'STR':
        optimized = int(argv[3])
        splitstring = int(argv[4])

    cfgtopda = CfgPDA(alphabet)
    print '* Parsing Grammar:',
    mma = cfgtopda.yyparse(argv[1])
    print 'OK'
    print ' - Total PDA states are ' + repr(len(mma.s))

    print '* Simplify State IDs:',
    simple_a = SimplifyStateIDs()
    mma.s, biggestid, newaccepted = simple_a.get(mma.s)
    if newaccepted:
        print 'OK'
    else:
        print 'OK'

    print '* Eliminate READ states:',
    replace = ReadReplace(mma.s, biggestid)
    mma.s = replace.replace_read()
    print 'OK'
    print ' - Total PDA states now are ' + repr(len(mma.s))
    maxstate = replace.nextstate() - 1

    print '* Reduce PDA:',
    simple_b = ReducePDA()
    mma.s = simple_b.get(mma.s)
    print 'OK'
    print ' - Total PDA states now are ' + repr(len(mma.s))

    print '* PDA to CFG transformation:',
    cnfgenerator = PdaCnf(mma.s)
    grammar = cnfgenerator.get_rules(optimized)
    print 'OK'
    print ' - Total CFG rules generated: ' + repr(len(grammar))

    if mode == 'STR':
        gen = CFGGenerator(CNFGenerator(grammar),
                           optimized=optimized,
                           splitstring=splitstring,
                           maxstate=maxstate)
        print gen.generate()
    else:
        print grammar
188749
def minimum(attrs, inputs, proto_obj):
    """"""
    # MXNet minimum compares only two symbols at a time.
    # ONNX can send more than two to compare.
    # Breaking into multiple mxnet ops to compare two symbols at a time
    if len(inputs) > 1:
        mxnet_op = symbol.minimum(inputs[0], inputs[1])
        for op_input in inputs[2:]:
            mxnet_op = symbol.minimum(mxnet_op, op_input)
    else:
        mxnet_op = symbol.minimum(inputs[0], inputs[0])
    return mxnet_op, attrs, inputs
232905
def opt(self, x_init, f_fp=None, f=None, fp=None):
        
        tnc_rcstrings = ['Local minimum', 'Converged', 'XConverged', 'Maximum number of f evaluations reached',
             'Line search failed', 'Function is constant']

        assert f_fp != None, "TNC requires f_fp"

        opt_dict = {}
        if self.xtol is not None:
            opt_dict['xtol'] = self.xtol
        if self.ftol is not None:
            opt_dict['ftol'] = self.ftol
        if self.gtol is not None:
            opt_dict['pgtol'] = self.gtol

        opt_result = optimize.fmin_tnc(f_fp, x_init, messages=self.messages,
                       maxfun=self.max_f_eval, **opt_dict)
        self.x_opt = opt_result[0]
        self.f_opt = f_fp(self.x_opt)[0]
        self.funct_eval = opt_result[1]
        self.status = tnc_rcstrings[opt_result[2]]
537272
def main(dimension, iterations):
    
    optimizer = PSOOptimizer()
    solution = optimizer.minimize(sphere, -5.12, 5.12, dimension,
                                  max_iterations(iterations))
    return solution, optimizer
1195695
def _optimize_A(self, A):
        
        right_eigenvectors = self.right_eigenvectors_[:, :self.n_macrostates]
        flat_map, square_map = get_maps(A)
        alpha = to_flat(1.0 * A, flat_map)

        def obj(x):
            return -1 * self._objective_function(
                    x, self.transmat_, right_eigenvectors, square_map,
                    self.populations_
            )

        alpha = scipy.optimize.basinhopping(
                obj, alpha, niter_success=1000,
        )['x']

        alpha = scipy.optimize.fmin(
                obj, alpha, full_output=True, xtol=1E-4, ftol=1E-4,
                maxfun=5000, maxiter=100000
        )[0]

        if np.isneginf(obj(alpha)):
            raise ValueError(
                    "Error: minimization has not located a feasible point.")

        A = to_square(alpha, square_map)
        return A
262803
private int minimumFnRemove(int[] h) {
    int minIndex = Integer.MAX_VALUE;
    double minValue = Double.MAX_VALUE;

    for (int i = 0; i < nbHash; i++) {
      double keyWeight = getWeight(keyVector[h[i]]);

      if (keyWeight < minValue) {
        minIndex = h[i];
        minValue = keyWeight;
      }

    }

    return minIndex;
  }
53289
def min_func(fun, bounds_min, bounds_max, d=None, rmax=10,
             n0=64, nswp=10, verb=True, smooth_fun=None):
    """"""
    if d is None:
        d = len(bounds_min)
        a = np.asanyarray(bounds_min).copy()
        b = np.asanyarray(bounds_max).copy()
    else:
        a = np.ones(d) * bounds_min
        b = np.ones(d) * bounds_max

    if smooth_fun is None:
        smooth_fun = lambda p, lam: (math.pi / 2 - np.arctan(p - lam))
    #smooth_fun = lambda p, lam: np.exp(-10*(p - lam))

    # We do not need to store the cores, only the interfaces!
    Rx = [[]] * (d + 1)  # Python list for the interfaces
    Rx[0] = np.ones((1, 1))
    Rx[d] = np.ones((1, 1))
    Jy = [np.empty(0, dtype=np.int)] * (d + 1)
    ry = rmax * np.ones(d + 1, dtype=np.int)
    ry[0] = 1
    ry[d] = 1
    n = n0 * np.ones(d, dtype=np.int)
    fun_evals = 0

    grid = [np.reshape(np.linspace(a[i], b[i], n[i]), (n[i], 1))
            for i in xrange(d)]
    for i in xrange(d - 1):
        #cr1 = y[i]
        ry[i + 1] = min(ry[i + 1], n[i] * ry[i])
        cr1 = np.random.randn(ry[i], n[i], ry[i + 1])
        cr1 = reshape(cr1, (ry[i] * n[i], ry[i + 1]))
        q, r = np.linalg.qr(cr1)
        ind = maxvol(q)
        w1 = mkron(np.ones((n[i], 1), dtype=np.int), Jy[i])
        w2 = mkron(grid[i], np.ones((ry[i], 1), dtype=np.int))
        Jy[i + 1] = np.hstack((w1, w2))
        Jy[i + 1] = reshape(Jy[i + 1], (ry[i] * n[i], -1))
        Jy[i + 1] = Jy[i + 1][ind, :]

        # Jy{i+1} = [kron(ones(n(i),1), Jy{i}), kron((1:n(i))', ones(ry(i),1))];
        # Jy{i+1} = Jy{i+1}(ind,:);
    swp = 0
    dirn = -1
    i = d - 1
    lm = float('Inf')
    while swp < nswp:
        # Right-to-left sweep
        # The idea: compute the current core; compute the function of it;
        # Shift locally or globally? Local shift would be the first try
        # Compute the current core

        if np.size(Jy[i]) == 0:
            w1 = np.zeros((ry[i] * n[i] * ry[i + 1], 0), dtype=np.int)
        else:
            w1 = mkron(np.ones((n[i] * ry[i + 1], 1), dtype=np.int), Jy[i])
        w2 = mkron(mkron(np.ones((ry[i + 1], 1), dtype=np.int),
                         grid[i]), np.ones((ry[i], 1), dtype=np.int))
        if np.size(Jy[i + 1]) == 0:
            w3 = np.zeros((ry[i] * n[i] * ry[i + 1], 0), dtype=np.int)
        else:
            w3 = mkron(Jy[i + 1], np.ones((ry[i] * n[i], 1), dtype=np.int))

        J = np.hstack((w1, w2, w3))
        # Just add some random indices to J, which is rnr x d, need to make rn (r + r0) x add,
        # i.e., just generate random r, random n and random multiindex

        cry = fun(J)
        fun_evals += cry.size
        cry = reshape(cry, (ry[i], n[i], ry[i + 1]))
        min_cur = np.min(cry.flatten("F"))
        ind_cur = np.argmin(cry.flatten("F"))
        if lm > min_cur:
            lm = min_cur
            x_full = J[ind_cur, :]
            val = fun(x_full)
            if verb:
                print('New record:', val, 'Point:', x_full, 'fevals:', fun_evals)
        cry = smooth_fun(cry, lm)
        if (dirn < 0 and i > 0):
            cry = reshape(cry, (ry[i], n[i] * ry[i + 1]))
            cry = cry.T
            #q, r = np.linalg.qr(cry)
            u, s, v = mysvd(cry, full_matrices=False)
            ry[i] = min(ry[i], rmax)
            q = u[:, :ry[i]]
            ind = rect_maxvol(q)[0]  # maxvol(q)
            ry[i] = ind.size
            w1 = mkron(np.ones((ry[i + 1], 1), dtype=np.int), grid[i])
            if np.size(Jy[i + 1]) == 0:
                w2 = np.zeros((n[i] * ry[i + 1], 0), dtype=np.int)
            else:
                w2 = mkron(Jy[i + 1], np.ones((n[i], 1), dtype=np.int))
            Jy[i] = np.hstack((w1, w2))
            Jy[i] = reshape(Jy[i], (n[i] * ry[i + 1], -1))
            Jy[i] = Jy[i][ind, :]

        if (dirn > 0 and i < d - 1):
            cry = reshape(cry, (ry[i] * n[i], ry[i + 1]))
            q, r = np.linalg.qr(cry)
            #ind = maxvol(q)
            ind = rect_maxvol(q)[0]
            ry[i + 1] = ind.size
            w1 = mkron(np.ones((n[i], 1), dtype=np.int), Jy[i])
            w2 = mkron(grid[i], np.ones((ry[i], 1), dtype=np.int))
            Jy[i + 1] = np.hstack((w1, w2))
            Jy[i + 1] = reshape(Jy[i + 1], (ry[i] * n[i], -1))
            Jy[i + 1] = Jy[i + 1][ind, :]

        i += dirn
        if i == d or i == -1:
            dirn = -dirn
            i += dirn
            swp = swp + 1
    return val, x_full
1084398
def optimize(self, x0, f=None, df=None, f_df=None):
        

        if len(self.bounds) == 1:
            raise IndexError("CMA does not work in problems of dimension 1.")

        try:
            import cma
            def CMA_f_wrapper(f):
                def g(x):
                    return f(np.array([x]))
                return g
            lB = np.asarray(self.bounds)[:,0]
            uB = np.asarray(self.bounds)[:,1]
            x = cma.fmin(CMA_f_wrapper(f), x0, 0.6, options={"bounds":[lB, uB], "verbose":-1})[0]
            return np.atleast_2d(x), f(np.atleast_2d(x))
        except ImportError:
            print("Cannot find cma library, please install it to use this option.")
            raise
1017173
public static <I> CompactDFA<I> or(DFA<?, I> dfa1, DFA<?, I> dfa2, Alphabet<I> inputAlphabet) {
        return or(dfa1, dfa2, inputAlphabet, new CompactDFA<>(inputAlphabet));
    }
118164
def determinize(self) -> DFA:
        

        nfa = self

        new_states = {macro_state for macro_state in powerset(nfa._states)}
        initial_state = frozenset([nfa._initial_state])
        final_states = {q for q in new_states if len(q.intersection(nfa._accepting_states)) != 0}
        transition_function = {}

        for state_set in new_states:
            for action in nfa._alphabet:

                next_macrostate = set()
                for s in state_set:
                    for next_state in nfa._transition_function.get(s, {}).get(action, set()):
                        next_macrostate.add(next_state)

                next_macrostate = frozenset(next_macrostate)
                transition_function.setdefault(state_set, {})[action] = next_macrostate

        return DFA(new_states, set(nfa._alphabet), initial_state, set(final_states), transition_function)
327560
private void minimizeWithGeometricConstraints() {
		extractEpipoles.setTensor(solutionN);
		extractEpipoles.extractEpipoles(e2,e3);

		// encode the parameters being optimized
		param[0] = e2.x; param[1] = e2.y; param[2] = e2.z;
		param[3] = e3.x; param[4] = e3.y; param[5] = e3.z;

		// adjust the error function for the current inputs
		errorFunction.init();

		// set up the optimization algorithm
		optimizer.setFunction(errorFunction,null);
		optimizer.initialize(param,gtol,ftol);

		// optimize until convergence or the maximum number of iterations
		UtilOptimize.process(optimizer, maxIterations);

		// get the results and compute the trifocal tensor
		double found[] = optimizer.getParameters();
		paramToEpipoles(found,e2,e3);

		enforce.process(e2,e3,A);
		enforce.extractSolution(solutionN);
	}
223557
def optimize(self, x0, f=None, df=None, f_df=None):
        
        # Based on the documentation of DIRECT, it does not seem we can pass through an initial point x0
        try:
            from DIRECT import solve
            def DIRECT_f_wrapper(f):
                def g(x, user_data):
                    return f(np.array([x])), 0
                return g
            lB = np.asarray(self.bounds)[:,0]
            uB = np.asarray(self.bounds)[:,1]
            x,_,_ = solve(DIRECT_f_wrapper(f),lB,uB, maxT=self.maxiter)
            return np.atleast_2d(x), f(np.atleast_2d(x))
        except ImportError:
            print("Cannot find DIRECT library, please install it to use this option.")
            raise
1105027
def ustep(self):
        

        super(ConvCnstrMODMaskDcpl_Consensus, self).ustep()
        self.U1 += self.AX1 - self.Y1 - self.S
754626
def _bot(self, k):
        
        if k < 2:
            raise ValueError("k smaller than 2")
        G = np.ones((self.m, self.m))
        np.fill_diagonal(G, 0)
        for i in range(self.m):
            for j in range(self.m):
                if i == j:
                    continue
                if i <= k and j <= k:
                    G[i][j] = 0
        return G
1247122
def min(self):
        
        results = [x.ufuncs.min() for x in self.elem]
        return np.min(results)