コード例 #1
0
ファイル: binsearch.py プロジェクト: ruricolist/dig
    def filter_terms(terms, inps):
        assert isinstance(inps, set) and \
            all(isinstance(s, str) for s in inps), inps

        if not inps:
            mlog.warning("Have not tested case with no inps")

        excludes = set()
        for term in terms:
            if isinstance(term, data.poly.mp.MP):
                a_symbs = list(map(str, Miscs.get_vars(term.a)))
                b_symbs = list(map(str, Miscs.get_vars(term.b)))
                inp_in_a = any(s in inps for s in a_symbs)
                inp_in_b = any(s in inps for s in b_symbs)

                if ((inp_in_a and inp_in_b)
                        or (not inp_in_a and not inp_in_b)):
                    excludes.add(term)
                    continue

                t_symbs = set(a_symbs + b_symbs)

            else:
                t_symbs = set(map(str, term.symbols))

            if len(t_symbs) <= 1:  # ok for finding bound of single input val
                continue

            if (inps.issuperset(t_symbs)
                    or all(s not in inps for s in t_symbs)):
                excludes.add(term)

        new_terms = [term for term in terms if term not in excludes]
        return new_terms
コード例 #2
0
ファイル: kplt.py プロジェクト: joelypoley/kplt
def left_ideal(gens, O):
    """Returns the left O-ideal generated by gens.

    If gens = [gens_0, ..., gens_n] then the ideal returned is O*gens_0 + ... +
    O*gens_n.

    Args:
        gens: A list of elements of O.
        O: An order in a quaternion algebra.

    Returns:
        The left O-ideal generated by gens.
    """
    if not all(x in O for x in gens):
        raise ValueError("All the generators must be in O.")

    module_gens = [x * y for x in O.basis() for y in gens]
    B = O.quaternion_algebra()
    Z, d = (quaternion_algebra_cython.
            integral_matrix_and_denom_from_rational_quaternions(module_gens))
    H = Z.hermite_form(include_zero_rows=False)
    basis = (quaternion_algebra_cython.
             rational_quaternions_from_integral_matrix_and_denom(B, H, d))

    I = O.left_ideal(basis)

    assert all(x in O for x in I.basis())
    assert all(x * y in O for x in O.basis() for y in I.basis())
    assert I.left_order() == O
    return I
コード例 #3
0
ファイル: Exec_1.py プロジェクト: txowista/cripto_uoc
def UOC_jeff_gen_key(disks=None, order=None):
    jeff_key = []

    #### IMPLEMENTATION GOES HERE ####
    if disks and order:
        t1 = all([len(uniq(k)) == len(k)
                  for k in disks])  ##Disco contenido repetido
        if not t1:
            return ERR_INV_DISKS
        t2 = len(uniq(order)) == len(order)  ##orden repetido
        if not t2:
            return ERR_INV_ORDER
        t3 = all([len(disks) >= k
                  for k in order])  ##orden mayor que numero de discos
        if not t3:
            return ERR_INV_ORDER
        t4 = all([len(uniq(k)) == len(disks[0])
                  for k in disks])  ##orden mayor que numero de discos
        if not t4:
            return ERR_INV_DISKS
        t5 = len(uniq(disks)) == len(disks)  ##Disco repetido
        if not t5:
            return ERR_INV_DISKS
        if len(disks) != len(order):  #distintos numero de orden que de discos
            return ERR_INV_ORDER
        else:
            jeff_key = [disks[i] for i in order]
    else:  ##sin definir discos o orden
        for i in range(0, NUM_DISKS):
            jeff_key.append(''.join(random.sample(ALPH, len(ALPH))))

    ##################################

    return jeff_key
コード例 #4
0
ファイル: ILC_topology.py プロジェクト: mehdidc/boosting
    def __CountPaths(self, G, V, I, cp, l):
        assert  isinstance(G, GraphCell) and\
                V.issubset(G.E) and\
                I.issubset(G.E) and\
                cp in G.N.list()

        Cc = Set([]) # adjacent critical nodes w.r.t. Z2
        N_S = self.__GetManifoldNodes(G, V, I, cp, l) # nodes covered by 1-separatices of cp
        C_NS = Set([up for up in N_S.list() if all([a != up for (a,wk) in V.list()])]) # critical nodes in N_S
        P = Set([]) # control container for the breadth-first search
        L = Set([cp]) # initialize list of visited nodes with cp
        Q = multiprocessing.Queue()
        Q.put((cp, False)) # all links of cp are unmatched
        while not Q.empty(): # constrained breadth-first search
            (up, flag) = Q.get() # get the next node and the flag of its links
            P = P.union(Set([up])) # add the node to the control container
            W = self.__AlternatingEdges(G, V, up, flag) # get the correctly flagged links
            W = W.intersection(I) # consider only links that are also part of the intersection I
            for (up, wk) in W.list(): # for each link={start node, end node}
                if wk in N_S.list(): # the end node must be covered by the 1-separatrices of cp
                    if up in L.list(): # if the start node is flagged
                        L = L.symmetric_difference(Set([wk])) # flag the end node w.r.t. Z2
                    Z = self.__AlternatingEdges(G, V, wk, flag) # get the links of the end node
                    Z = Z.intersection(I) # restrict them to the intersection I
                    N_Z = Set([up for up in G.N.list() if not all([a != up for (a,wk) in Z.list()])]) # get their start nodes
                    if N_Z.issubset(P): # all start nodes must already be processed
                        Q.put((wk, not flag))
        Cc = L.intersection(C_NS).difference(Set([cp])) # restrict visited nodes to the critical nodes except cp

        assert Cc.issubset(G.N)
        return Cc
コード例 #5
0
ファイル: utils.py プロジェクト: roed314/lmfdb
def parse_torsion_structure(L, maxrank=2):
    r"""
    Parse a string entered into torsion structure search box
    '[]' --> []
    '[n]' --> [str(n)]
    'n' --> [str(n)]
    '[m,n]' or '[m n]' --> [str(m),str(n)]
    'm,n' or 'm n' --> [str(m),str(n)]
    ... and similarly for up to maxrank factors
    """
    # strip <whitespace> or <whitespace>[<whitespace> from the beginning:
    L1 = re.sub(r"^\s*\[?\s*", "", str(L))
    # strip <whitespace> or <whitespace>]<whitespace> from the beginning:
    L1 = re.sub(r"\s*]?\s*$", "", L1)
    # catch case where there is nothing left:
    if not L1:
        return []
    # This matches a string of 1 or more digits at the start,
    # optionally followed by up to 3 times (nontrivial <ws> or <ws>,<ws> followed by
    # 1 or more digits):
    TORS_RE = re.compile(r"^\d+((\s+|\s*,\s*)\d+){0,%s}$" % (maxrank - 1))
    if TORS_RE.match(L1):
        if "," in L1:
            # strip interior <ws> and use ',' as delimiter:
            res = [int(a) for a in L1.replace(" ", "").split(",")]
        else:
            # use whitespace as delimiter:
            res = [int(a) for a in L1.split()]
        n = len(res)
        if all(x > 0 for x in res) and all(res[i + 1] % res[i] == 0 for i in range(n - 1)):
            return res
    return (
        "Error parsing input %s.  It needs to be a list of up to %s integers, optionally in square brackets, separated by spaces or a comma, such as [6], 6, [2,2], or [2,4].  Moreover, each integer should be bigger than 1, and each divides the next."
        % (L, maxrank)
    )
コード例 #6
0
ファイル: miscs.py プロジェクト: ruricolist/dig
    def solve_eqts(cls, eqts, uks, template):
        assert isinstance(eqts, list) and eqts, eqts
        assert isinstance(uks, list) and uks, uks
        assert len(eqts) >= len(uks), (len(eqts), len(uks))

        mlog.debug("solve {} uks using {} eqts".format(len(uks), len(eqts)))

        # print(eqts)

        # I don't think this helps
        # @fork(timeout=settings.EQT_SOLVER_TIMEOUT, verbose=False)
        def mysolve(eqts, uks, solution_dict):
            return sage.all.solve(eqts, *uks, solution_dict=True)

        rs = mysolve(eqts, uks, solution_dict=True)
        assert isinstance(rs, list), rs
        assert all(isinstance(s, dict) for s in rs), rs

        # filter sols with all uks = 0, e.g., {uk_0: 0, uk_1: 0, uk_2: 0}
        rs = [d for d in rs if not all(x == 0 for x in d.values())]

        reqts = cls.instantiate_template(template, rs)
        reqts = cls.refine(reqts)
        # print '\n'.join(map(str, eqts))
        # print uks
        # print reqts
        # CM.pause()

        return reqts
コード例 #7
0
def parse_torsion_structure(L, maxrank=2):
    r"""
    Parse a string entered into torsion structure search box
    '[]' --> []
    '[n]' --> [str(n)]
    'n' --> [str(n)]
    '[m,n]' or '[m n]' --> [str(m),str(n)]
    'm,n' or 'm n' --> [str(m),str(n)]
    ... and similarly for up to maxrank factors
    """
    # strip <whitespace> or <whitespace>[<whitespace> from the beginning:
    L1 = re.sub(r'^\s*\[?\s*', '', str(L))
    # strip <whitespace> or <whitespace>]<whitespace> from the beginning:
    L1 = re.sub(r'\s*]?\s*$', '', L1)
    # catch case where there is nothing left:
    if not L1:
        return []
    # This matches a string of 1 or more digits at the start,
    # optionally followed by up to 3 times (nontrivial <ws> or <ws>,<ws> followed by
    # 1 or more digits):
    TORS_RE = re.compile(r'^\d+((\s+|\s*,\s*)\d+){0,%s}$' % (maxrank - 1))
    if TORS_RE.match(L1):
        if ',' in L1:
            # strip interior <ws> and use ',' as delimiter:
            res = [int(a) for a in L1.replace(' ', '').split(',')]
        else:
            # use whitespace as delimiter:
            res = [int(a) for a in L1.split()]
        n = len(res)
        if all(x > 0 for x in res) and all(res[i + 1] % res[i] == 0
                                           for i in range(n - 1)):
            return res
    return 'Error parsing input %s.  It needs to be a list of up to %s integers, optionally in square brackets, separated by spaces or a comma, such as [6], 6, [2,2], or [2,4].  Moreover, each integer should be bigger than 1, and each divides the next.' % (
        L, maxrank)
コード例 #8
0
ファイル: web_HMF.py プロジェクト: akoutsianas/lmfdb
def construct_full_label(field_label, weight, level_label, label_suffix):
    if all([w == 2 for w in weight]):  # Parellel weight 2
        weight_label = ''
    elif all([w == weight[0] for w in weight]):  # Parellel weight
        weight_label = str(weight[0]) + '-'
    else:  # non-parallel weight
        weight_label = str(weight) + '-'
    return ''.join(
        [field_label, '-', weight_label, level_label, '-', label_suffix])
コード例 #9
0
ファイル: Exec_1.py プロジェクト: txowista/cripto_uoc
def test_case_1_1(name, num_its):
    res = []
    for _ in range(num_its):
        keys = UOC_jeff_gen_key(disks=None, order=None)
        t1 = len(keys) == NUM_DISKS
        t2 = all([len(uniq(k)) == len(k) for k in keys])
        t3 = all([all([l in ALPH for l in k]) for k in keys])
        res.append(t1 and t2 and t3)

    print "Test", name + ":", all(res)
コード例 #10
0
ファイル: symstates.py プロジェクト: ruricolist/dig
    def merge(cls, depthss, pc_cls, use_reals):
        """
        Merge PC's info into symbolic states sd[loc][depth]
        """
        assert isinstance(depthss, list) and depthss, depthss
        assert all(depth >= 1 and isinstance(ss, list)
                   for depth, ss in depthss), depthss

        symstates = defaultdict(lambda: defaultdict(lambda: PCs(loc, depth)))
        for depth, ss in depthss:
            for (loc, pcs, slocals) in ss:
                pc = pc_cls(loc, depth, pcs, slocals, use_reals)
                symstates[loc][depth].add(pc)

        # only store incremental states at each depth
        for loc in symstates:
            depths = sorted(symstates[loc])
            assert len(depths) >= 2, depths
            for i in range(len(depths)):
                iss = symstates[loc][depths[i]]
                # only keep diffs
                for j in range(i):
                    jss = symstates[loc][depths[j]]
                    for s in jss:
                        if s in iss:
                            iss.remove(s)

        # clean up
        empties = [(loc, depth) for loc in symstates
                   for depth in symstates[loc] if not symstates[loc][depth]]
        for loc, depth in empties:
            mlog.warning("{}: no new symbolic states at depth {}".format(
                loc, depth))
            symstates[loc].pop(depth)

        empties = [loc for loc in symstates if not symstates[loc]]
        for loc in empties:
            mlog.warning("{}: no symbolic states found".format(loc))
            symstates.pop(loc)

        if all(not symstates[loc] for loc in symstates):
            mlog.error("No symbolic states found for any locs. Exit!")
            exit(1)

        # compute the z3 exprs once
        for loc in symstates:
            for depth in sorted(symstates[loc]):
                pcs = symstates[loc][depth]
                pcs.myexpr
                pcs.mypc
                mlog.debug("{} uniq symstates at loc {} depth {}".format(
                    len(pcs), loc, depth))
                # print(pcs.myexpr)

        return symstates
コード例 #11
0
ファイル: ILC_topology.py プロジェクト: mehdidc/boosting
    def __ComputeCell(self, n, n_minus_2_cells, n_minus_1_cells):
        assert n >= 2
        n_minus_2_cells = [toTuple(x) for x in n_minus_2_cells]
        n_minus_1_cells = [toTuple(x) for x in n_minus_1_cells]
        n_minus_1_cellsUsed = []
        n_cells = []
        for n_minus_2_cell in n_minus_2_cells:
            V_n_minus_2_cells = [s for s in n_minus_1_cells if isSubTuple(n_minus_2_cell, s) and s not in n_minus_1_cellsUsed]
            if len(V_n_minus_2_cells) % 2**(n-1) != 0:
                V_n_minus_2_cells += V_n_minus_2_cells[:n-1]
#            print '%d-cell'%(n-2), n_minus_2_cell
            tmp1 = dict()
            for couples in NTuples(V_n_minus_2_cells, 2**(n-1)):
                assert all([len(couple) == 2**(n-1) for couple in couples])
#                print '  %d-cell existentes'%(n-1), couples
                diff = []
                for couple in couples:
                    diff += [x for x in couple if x not in diff]
                diff = NTuples([x for x in diff if not all([x in couple for couple in couples])], 2**(n-2))
#                print '    difference', diff
                for n_minus_1_cell in [s for s in n_minus_1_cells if s not in n_minus_1_cellsUsed and s not in couples]:
                    for d in [d for d in diff if isSubTuple(toTuple(d), n_minus_1_cell)]:
                        assert len(toTuple(d)) == 2**(n-2)
                        if not tmp1.has_key(toTuple(d)):
                            tmp1[toTuple(d)] = []
                        tmp1[toTuple(d)] += [toTuple(x) for x in toTuple(n_minus_1_cell) if x not in toTuple(d)]
                for key,val in tmp1.items():
                    tmp1[key] = list(set(val))
#                print '      %d-cell incidentes'%(n-2), tmp1
            tmp2 = []
            for permutation in list(itertools.permutations(tmp1.keys(), 2)):
                tmp2 += list(Set(tmp1[permutation[0]]).intersection(Set(tmp1[permutation[1]])))
            tmp2 = list(set(tmp2))
#            print '  %d-cell candidates'%(n-2), tmp2
            tmp3 = []
            for t in tmp2:
                tmp3 += [tuple(sorted([n_minus_2_cell] + [key for key, val in tmp1.items() if t in val] + [t]))]
            tmp4 = []
            for t in tmp3:
                s = ()
                for a in t:
                    s += toTuple(a)
                tmp4 += [toTuple(s)]
            n_minus_1_cellsUsed = list(set(n_minus_1_cellsUsed + V_n_minus_2_cells))
#            print '  %d-cell obtenues'%n, tmp4
            n_cells += tmp4
        res = []
        for r in NTuples(sorted(n_cells), 2**(n-2)):
            u = []
            for elt in r:
                u += list(Set(toTuple(elt)).union(Set(list(u))))
            res += [toTuple(list(set(u)))]
        assert all([len(x) == 2**n for x in sorted(res)])
        return sorted(res)
コード例 #12
0
def complete(S, context):
    result = list(S)
    if len(result) == 1:
        return result
    vars = list(range(len(context._independent)))

    def map_old_to_new(l):
        return context._independent[vars.index(l)]

    while 1:
        monomials = [(_, derivative_to_vec(_.Lder(), context)) for _ in result]
        ms = tuple([_[1] for _ in monomials])
        m0 = []

        # multiplier-collection is our M
        multiplier_collection = []
        for dp, monom in monomials:
            # S1
            _multipliers, _nonmultipliers = vec_multipliers(monom, ms, vars)
            multiplier_collection.append(
                (monom, dp, _multipliers, _nonmultipliers))
        for monom, dp, _multipliers, _nonmultipliers in multiplier_collection:
            if not _nonmultipliers:
                m0.append((monom, None, dp))
            else:
                # todo: do we need subsets or is a multiplication by only one
                # nonmultiplier one after the other enough ?
                for n in _nonmultipliers:
                    _m0 = list(monom)
                    _m0[n] += 1
                    m0.append((_m0, n, dp))
        to_remove = []
        for _m0 in m0:
            # S3: check whether in class of any of the monomials
            for monomial, _, _multipliers, _nonmultipliers in multiplier_collection:
                if all(_m0[0][x] >= monomial[x] for x in _multipliers) and \
                   all(_m0[0][x] == monomial[x] for x in _nonmultipliers):
                    # this is in _m0's class
                    to_remove.append(_m0)
        for _to in to_remove:
            try:
                m0.remove(_to)
            except:
                pass
        if not m0:
            return result
        else:
            for _m0 in m0:
                dp = _Differential_Polynomial(
                    _m0[2].diff(map_old_to_new(_m0[1])).expression(), context)
                if dp not in result:
                    result.append(dp)
        result = Reorder(result, context, ascending=False)
コード例 #13
0
 def induced_subgraph(self, S):
     if not all(0 <= x <= self.n for x in S):
         raise ValueError
     good_edges = [e for e in self.edges if all(x in S for x in e)]
     p = [0 for _ in range(self.n + 1)]
     for i, x in enumerate(S):
         p[x] = i + 1
     h = Flag()
     h.n = len(S)
     h.t = 0
     if self.oriented:
         h.edges = tuple(sorted([tuple([p[x] for x in e]) for e in good_edges]))
     else:
         h.edges = tuple(sorted([tuple(sorted([p[x] for x in e])) for e in good_edges]))
     return h
コード例 #14
0
 def induced_subgraph(self, S):
     if not all(0 <= x <= self.n for x in S):
         raise ValueError
     good_edges = [e for e in self.edges if all(x in S for x in e)]
     p = [0 for _ in range(self.n + 1)]
     for i, x in enumerate(S):
         p[x] = i + 1
     h = Flag()
     h.n = len(S)
     h.t = 0
     if self.oriented:
         h.edges = tuple(sorted([tuple([p[x] for x in e]) for e in good_edges]))
     else:
         h.edges = tuple(sorted([tuple(sorted([p[x] for x in e])) for e in good_edges]))
     return h
コード例 #15
0
    def solve(self):
        if self.density >= 0.9408 and not self.try_on_high_density:
            raise HighDensityException()

        # 1. Initialize Lattice
        L = Matrix(ZZ, self.n + 1, self.n + 1)
        N = inthroot(Integer(self.n), 2) // 2
        for i in range(self.n + 1):
            for j in range(self.n + 1):
                if j == self.n and i < self.n:
                    L[i, j] = 2 * N * self.array[i]
                elif j == self.n:
                    L[i, j] = 2 * N * self.target_sum
                elif i == j:
                    L[i, j] = 2
                elif i == self.n:
                    L[i, j] = 1
                else:
                    L[i, j] = 0

        # 2. LLL!
        B = L.LLL()

        # 3. Find answer
        for i in range(self.n + 1):
            if B[i, self.n] != 0:
                continue

            if all(v == -1 or v == 1 for v in B[i][:self.n]):
                ans = [(-B[i, j] + 1) // 2 for j in range(self.n)]
                if self._check_ans(ans):
                    return ans

        # Failed to find answer
        return None
コード例 #16
0
ファイル: analysis.py プロジェクト: ruricolist/dig
    def analyze_dicts(cls, ds, f, label):
        ks = set(k for d in ds for k in d)
        dd = defaultdict(list)
        for d in ds:
            for k in ks:
                try:
                    dd[k].append(d[k])
                except KeyError:
                    dd[k].append(0)

        assert all(len(dd[k]) == len(ds) for k in dd), dd

        s = []
        sizs = []

        for k in sorted(dd):
            t = f(dd[k])
            if isinstance(k, tuple):
                assert len(k) == 2
                from_, to_ = k
                k_str = "{}->{}".format(from_, to_)
            else:
                k_str = str(k)
            s.append((k, k_str, t))
            sizs.append(t)

        s = ', '.join('{}: {}'.format(k_str, f(dd[k])) for k, k_str, t in s)

        return '{} {} ({})'.format(label, sum(sizs), s)
コード例 #17
0
ファイル: rot_Sn_action.py プロジェクト: aldenwalker/sagescl
def compatible_on_quadpods(T_dict_in, rank, Q_in=None, T_in=None):
  gens = alphabet[:rank] + inverse(alphabet[:rank])
  if Q_in == None:
    Q = sage.combinat.subset.Subsets_sk(gens, 4)
  else:
    Q = Q_in
  if T_in == None:
    T = tripods(rank)
  else:
    T = T_in
  T_dict = {}
  for t in T_dict_in:
    T_dict[t] = T_dict_in[t]
    T_dict[(t[0], t[2], t[1])] = -T_dict_in[t]
    T_dict[(t[1], t[2], t[0])] = T_dict_in[t]
    T_dict[(t[1], t[0], t[2])] = -T_dict_in[t]
    T_dict[(t[2], t[0], t[1])] = T_dict_in[t]
    T_dict[(t[2], t[1], t[0])] = -T_dict_in[t]
  for q in Q:
    #for each quadruple, check that it is compatible
    #I'm just going to do this brute force
    all_quadpods = [ [q[0]] + x for x in permutations(q[1:])]
    its_compatible = False
    for qp in all_quadpods:
      tfq = tripods_from_quadpod(qp)
      if all([v==0 or v==1 for v in [T_dict.get(tuple(t), 0) for t in tfq]]):
        its_compatible = True
        break
    if not its_compatible:
      break
  return its_compatible
コード例 #18
0
ファイル: rot_Sn_action.py プロジェクト: aldenwalker/sagescl
 def compatible_on_quadpods(self, Q_in=None, T_in=None):
   if self.ell > 2:
     print "Not implemented for ell > 2"
     return
   gens = alphabet[:self.rank] + inverse(alphabet[:self.rank])
   if Q_in == None:
     Q = sage.combinat.subset.Subsets_sk(gens, 4)
   else:
     Q = Q_in
   if T_in == None:
     T = tripods(self.rank)
   else:
     T = T_in
   D = self.defect(T)
   for q in Q:
     #for each quadruple, check that it is compatible
     #I'm just going to do this brute force
     all_quadpods = [ [q[0]] + x for x in permutations(q[1:])]
     its_compatible = False
     for qp in all_quadpods:
       tfq = tripods_from_quadpod(qp)
       if all([v==0 or 2*v==D for v in [self.tripod_ap(t) for t in tfq]]):
         its_compatible = True
         break
     if not its_compatible:
       break
   return its_compatible
コード例 #19
0
ファイル: chern_classes.py プロジェクト: robertgoss/sage
 def exterior_power(self, p, name=None):
     #Returns the pth exterior power of this bundle
     #Also takes an optional name parameter for this bundle
     if not name:
         name = "Ext"+str(p)+self.name
     #By the splitting principle this is the same as computing a decomposition into elementary
     # symmetric polynomials of the polynomial which is the product of
     # (1+x_{i_1}+...x_{i_p}) for each combination of 1<=i_1<..<i_p<=n.
     # We call such a polynomial a one combination polynomial in p and n.
     if self.truncated:
         decomp = _decompose_one_combination_polynomial(self.dim, p, 'recursive', self.truncation+1)
         max_degree = self.truncation+1
     else:
         decomp = _decompose_one_combination_polynomial(self.dim, p, 'recursive')
         max_degree = binomial(self.dim, p)+1
     new_chern_classes = [self.chern_ring.zero() for _ in xrange(max_degree)]
     monomial_coefficients = decomp.monomial_coefficients()
     #Directly convert elementary symmetric monomials to monomials in chern generators
     # Would like to do this with a hom
     for monomial in monomial_coefficients:
         coefficient = monomial_coefficients[monomial]
         #As all chern classes of E are zero in degree greater than n
         # only include those monomials containing elementary symmetric polynomials
         # with degree less than or equal to n.
         if all(degree <= self.dim for degree in monomial):
             dim = sum(monomial)
             c_monomial = prod([self.chern_classes[i] for i in monomial], self.chern_ring.one())
             new_chern_classes[dim] += coefficient*c_monomial
     if self.truncated:
         return VectorBundle(name, binomial(self.dim, p), new_chern_classes, self.truncation)
     else:
         return VectorBundle(name, binomial(self.dim, p), new_chern_classes)
コード例 #20
0
ファイル: chern_classes.py プロジェクト: robertgoss/sage
def exterior_power(n, p, algorithm="recursive",degree=None):
    #Returns the chern class of the pth exterior power of an n dimensional bundle E
    # in terms of the chern class of E
    #Optional algorithm property gives the algorithm used to decompose polynomial of line bundles
    # Naive corresponds to computing the full polynomial mostly used for testing
    #If positive degree is given just return the chern class less than that degree.

    #Polynomial ring of polynomials in the chern classes.
    # N+1 gens as c_0 is 1 to get the dimensions to agree.
    # deglex is used to quickly see the equal degree parts.
    chern_ring = PolynomialRing(RationalField(), 'c', n+1, order='deglex')
    #By the splitting principle this is the same as computing a decomposition into elementary
    # symmetric polynomials of the polynomial which is the product of
    # (1+x_{i_1}+...x_{i_p}) for each combination of 1<=i_1<..<i_p<=n.
    # We call such a polynomial a one combination polynomial in p and n.
    decomp = _decompose_one_combination_polynomial(n, p, algorithm,degree)
    #Convert the decomposition into a polynomial in the chern classes.
    chern = chern_ring.zero()
    chern_gens = chern_ring.gens()
    monomial_coefficients = decomp.monomial_coefficients()
    #Directly convert elementary symmetric monomials to monomials in chern generators
    # Would like to do this with a hom
    for monomial in monomial_coefficients:
        coefficient = monomial_coefficients[monomial]
        #As all chern classes of E are zero in degree greater than n
        # only include those monomials containing elementary symmetric polynomials
        # with degree less than or equal to n.
        if all(degree <= n for degree in monomial):
            chern += coefficient*prod([chern_gens[i] for i in monomial], chern_ring.one())
    return chern
コード例 #21
0
ファイル: opt.py プロジェクト: ruricolist/dig
    def my_get_terms_user(self, symbols, uterms):
        assert isinstance(uterms, set) and uterms, uterms
        assert all(isinstance(t, str) for t in uterms), uterms

        mylocals = {str(s): s for s in symbols}

        import sage.all
        try:
            uterms = set(
                sage.all.sage_eval(term, locals=mylocals) for term in uterms)
        except NameError as ex:
            raise NameError("{} (defined vars: {})".format(
                ex, ','.join(map(str, symbols))))

        terms = set()
        for t in uterms:
            terms.add(t)
            terms.add(-t)
            for v in symbols:
                # v+t, v-t, -v+t, -v-t
                terms.add(v + t)
                terms.add(v - t)
                terms.add(-v + t)
                terms.add(-v - t)

        return terms
コード例 #22
0
    def __chooseG(self):
        """Choose a 'small' polynomial g subject to several conditions
		
		Conditions:
		- each coefficient should be smaller than 2^O(m^delta)
		- |R/(g)| is a large prime p (p > 2^lambda)
		- g^-1 when viewed in Q[X]/(X^m+1) is sufficiently small
		"""

        qr = QuotientRing(QQ[self.x], self.x**self.m + 1)
        cond = False
        bound = 2**(int(self.m**self.delta))

        while not (cond):
            #all coefficients smaller than 2^O(m^delta)
            coeffs = [ZZ.random_element(0, bound) for i in range(self.m)]
            g = sum(
                [a * self.t**i for a, i in zip(coeffs, range(len(coeffs)))])

            #conditions:
            #|R/(g)| is large prime p (p > 2^lambda/securityParameter)
            self.p = g.norm()
            p = self.p
            cond = p > 2**self.secParam and p in Primes()

            #g^-1 when viewed in Q[X]/(X^m+1) sufficiently small
            if cond:
                g_1 = qr(g)**(-1)
                cond = all([abs(c) < bound for c in g_1.list()])

        return g
コード例 #23
0
ファイル: alg.py プロジェクト: ruricolist/dig
    def instantiateTraces(self, traces, nTraces):
        """
        Instantiate a (potentially nonlinear) template with traces to obtain
        a set of linear expressions.

        sage: var('a,b,x,y,uk_0,uk_1,uk_2,uk_3,uk_4')
        (a, b, x, y, uk_0, uk_1, uk_2, uk_3, uk_4)

        sage: traces = [{y: 4, b: 2, a: 13, x: 1}, {y: 6, b: 1, a: 10, x: 2}, {y: 8, b: 0, a: 7, x: 3}, {y: 10, b: 4, a: 19, x: 4}, {y: 22, b: 30, a: 97, x: 10}, {y: 28, b: 41, a: 130, x: 13}]
        sage: exprs = Template(uk_1*a + uk_2*b + uk_3*x + uk_4*y + uk_0 == 0).instantiateTraces(traces, nTraces=None)
        sage: assert exprs == {uk_0 + 13*uk_1 + 2*uk_2 + uk_3 + 4*uk_4 == 0,\
        uk_0 + 10*uk_1 + uk_2 + 2*uk_3 + 6*uk_4 == 0,\
        uk_0 + 7*uk_1 + 3*uk_3 + 8*uk_4 == 0,\
        uk_0 + 19*uk_1 + 4*uk_2 + 4*uk_3 + 10*uk_4 == 0,\
        uk_0 + 97*uk_1 + 30*uk_2 + 10*uk_3 + 22*uk_4 == 0,\
        uk_0 + 130*uk_1 + 41*uk_2 + 13*uk_3 + 28*uk_4 == 0}
        """

        assert (traces
                and (isIterator(traces)
                     or all(isinstance(t, dict) for t in traces))), traces
        assert nTraces is None or nTraces >= 1, nTraces

        if nTraces is None:
            exprs = set(self.template.subs(t) for t in traces)
        else:
            exprs = set()
            for i, t in enumerate(traces):
                expr = self.template.subs(t)
                if expr not in exprs:
                    exprs.add(expr)
                    if len(exprs) > nTraces:
                        break

        return exprs
コード例 #24
0
 def _make_torus_images(self, *vertices):
     images = [self._make_simplex(*vertices)]
     for i, r in enumerate(self.side_length):
         if all(v[i] == 0 for v in vertices):
             t = TranslatePoint(i, r)
             images.extend([self._make_simplex(*map(t, s)) for s in images])
     return images
コード例 #25
0
        def f(_cache, e, seen):
            def f_cache(e):
                return _cache(f, e, seen)

            r = z3.is_mul(e) and \
                all(cls._is_literal_expr(c) or f_cache(c) for c in e.children())
            return r
コード例 #26
0
ファイル: kplt.py プロジェクト: joelypoley/kplt
def special_ell_power_equiv(I, O, ell, print_progress=False):
    """Solve ell isogeny problem where O is a special order.

    Args:
        I: A left O-ideal.
        O: A special order in a quaternion algebra.
        ell: A prime.
        print_progress: True if you want to print progress.

    Returns:
        A pair (J, delta) where J = I*delta, delta is in the quaternion algebra
        and J is a nonfractional ideal in the same class as I that has ell
        power norm.
    """
    assert all(x in O for x in I.basis())
    ell = Integer(ell)
    D = 4
    I_prime, beta_I_prime = prime_norm_representative(I, O, D, ell)
    N = Integer(I_prime.norm())
    gamma = element_of_norm(N * ell**20, O)
    # TODO: Handle failure to find gamma better.
    if gamma is None:
        raise ValueError("Couldn't find element of correct norm")

    mu_0 = solve_ideal_equation(gamma, I_prime, D, N, O)
    mu = strong_approximation(mu_0, N, O, ell)
    assert gamma * mu in I_prime
    beta = (gamma * mu).conjugate() / N
    J = I_prime.scale(beta)
    delta = beta_I_prime * beta
    assert J.left_order() == O
    assert Integer(J.norm()).prime_factors() == [ell]
    assert [x in O for x in J.basis()]
    return J, delta
コード例 #27
0
ファイル: analysis.py プロジェクト: ruricolist/dig
    def __init__(self, prog, results):
        assert isinstance(prog, str), prog
        assert isinstance(results, list) and results, results
        assert all(isinstance(r, AResult) for r in results), results

        self.prog = prog
        self.results = results
コード例 #28
0
ファイル: dig2.py プロジェクト: ruricolist/dig
    def mk_eqt(cls, ss, termIdxss, uks, uk_sols):
        """
        ss = [x, y, s, t]
        termIdxss = [(0,), (1,), (2,), (3,)]
        uks = [uk_0, uk_1, uk_2, uk_3, uk_4]
        uks = [(uk_1, -2), (uk_2, 0), (uk_3, 0), (uk_4, 1), (uk_0, -7)]
        uk_sols= [(uk_1, -2), (uk_2, 0), (uk_3, 0), (uk_4, 1), (uk_0, -7)]

        return a string
        """
        assert len(termIdxss) == len(uks) - 1
        assert len(uk_sols) == len(uks)

        terms = cls.mymul(ss, termIdxss)  #(1*x, 1*y, 1*s, 1*t)
        uk_sols_d = dict(uk_sols)  #uk_1: -2, uk_2: 0
        denoms = [v.denominator() for v in uk_sols_d.itervalues()]
        lcm = sage.all.lcm(denoms)
        uk_vs = [int(lcm * uk_sols_d[uk]) for uk in uks]
        if not all(Traces.rangeMaxV >= v >= -Traces.rangeMaxV for v in uk_vs):
            return None

        terms = [
            t if uk_v == 1 else uk_v * t for uk_v, t in zip(uk_vs[1:], terms)
            if uk_v != 0
        ]
        if uk_vs[0] != 0: terms = [uk_vs[0]] + terms

        if terms:
            rs = sum(terms) == 0
            return rs
        else:
            return None
コード例 #29
0
        def f(_cache, e, seen):
            def f_cache(e):
                return _cache(f, e, seen)

            r = (z3.is_const(e) and e.decl().kind() == z3.Z3_OP_ANUM) or \
                (e.num_args() > 0 and all(f_cache(c) for c in e.children()))
            return r
コード例 #30
0
 def mk_inps_from_models(self, models, inp_decls, exe, n_inps=0):
     if not models:
         if n_inps > 0:
             return exe.gen_rand_inps(n_inps)
         else:
             return Inps()
     else:
         assert isinstance(models, list), models
         if all(isinstance(m, z3.ModelRef) for m in models):
             ms, _ = Z3.extract(models)
         else:
             ms = [{x: sage.all.sage_eval(str(v))
                    for (x, v) in model} for model in models]
         s = set()
         rand_inps = []
         for m in ms:
             inp = []
             for v in inp_decls.names:
                 if v in m:
                     inp.append(m[v])
                 else:
                     if not rand_inps:
                         rand_inps = exe.gen_rand_inps(len(ms))
                         mlog.debug("rand_inps: {} - {}\n{}".format(
                             len(ms), len(rand_inps), rand_inps))
                     rand_inp = rand_inps.pop()
                     d = dict(zip(rand_inp.ss, rand_inp.vs))
                     inp.append(sage.all.sage_eval(str(d[v])))
             s.add(tuple(inp))
         inps = Inps()
         inps.merge(s, inp_decls.names)
         return inps
コード例 #31
0
 def check_homomorphism(is_homomorphic_method, graphs_generator):
     nonlocal i
     nonlocal T
     nonlocal upper_bound
     while i <= upper_bound:
         found_not_homomorphic = False
         T_next = []
         for H in graphs_generator(i):
             # Sprawdzamy, czy H zawiera którykolwiek z grafów w T
             if any(
                     map(
                         lambda x: all(
                             H.has_edge(e) for e in x.edge_iterator()), T)):
                 continue
             if is_homomorphic_method(H):
                 if i < upper_bound:
                     T_next.append(H)
             else:
                 found_not_homomorphic = True
                 if i > 5:
                     break
         if found_not_homomorphic:
             i += 1
             T = T + T_next
         else:
             break
コード例 #32
0
ファイル: kplt.py プロジェクト: joelypoley/kplt
def connecting_ideal(O_1, O_2):
    """Returns an O_1, O_2-connecting ideal.

    Args:
        O_1: A maximal order in a rational quaternion algebra.
        O_2: A maximal order in the same quaternion algebra.

    Returns:
        An ideal I that is a left O_1 ideal and a right O_2 ideal. Moreover I
        is a subset of O_1.
    """
    # There exists some integer d such that d*O_2 is a subset of O_1. We
    # first compute d.
    mat_1 = matrix([x.coefficient_tuple() for x in O_1.basis()])
    mat_2 = matrix([x.coefficient_tuple() for x in O_2.basis()])
    matcoeff = mat_2 * ~mat_1
    d = lcm(x.denominator() for x in matcoeff.coefficients())

    # J is a subset of O_1 and is a O_1, O_2-ideal by construction.
    J = left_ideal([d * x * y for x in O_1.basis() for y in O_2.basis()], O_1)

    assert J.left_order() == O_1
    assert J.right_order() == O_2
    assert all(x in O_1 for x in J.basis())

    return J
コード例 #33
0
def stuffle(A):
    A.set_immutable()
    ans = {A: 1}
    todo = {}
    for i in range(A.nrows()):
        for j in range(i):
            if all(A[i, k] + A[i, j] <= 1 for k in range(A.ncols())):
                do_stuffle(A, i, j)

    mm = m.__copy__()
    mm[i] += mm[j]
    D1 = clean_term(
        n, tuple((c, p) for c, (v, p) in zip(mm.columns(), den_tuple)))

    # big subsimplex 2
    mm = m.__copy__()
    mm[j] += mm[i]
    D2 = clean_term(
        n, tuple((c, p) for c, (v, p) in zip(mm.columns(), den_tuple)))

    # small subsimplex
    mm = m.__copy__()
    mm[i] += mm[j]
    mm = mm.delete_rows([j])
    D3 = clean_term(
        n - 1, tuple((c, p) for c, (v, p) in zip(mm.columns(), den_tuple)))

    return [(n, D1), (n, D2), (n - 1, D3)]
コード例 #34
0
def _get_projective_endpoints_of_line(vertices, vertex_reflections):
    e = PrimitivesDistanceEngine([0,0], vertex_reflections)
    
    endpoints, h = e.fixed_projective_points_or_bounding_halfsphere()
    
    if not endpoints:
        raise Exception("Blah")

    CIF = vertices[0].z.parent()
    
    for i in range(1, 4):
        m = _adjoint2(
            ProjectivePoint.matrix_taking_0_1_inf_to_given_points(
                endpoints[0], ProjectivePoint(CIF(i)), endpoints[1]))
        if m.det().abs() > 0:
            try:
                vs = [ v.translate_PGL(m) for v in vertices ]
            except:
                continue
            
            if not all([not v.z != 0 for v in vs]):
                raise Exception("Images of vertices supposed to be "
                                "on vertical line.")

            if vs[0].t > vs[1].t:
                return endpoints[::-1]
            if vs[0].t < vs[1].t:
                return endpoints
    
    raise Exception("Could not find endpoints")
コード例 #35
0
	def __chooseG(self):
		"""Choose a 'small' polynomial g subject to several conditions
		
		Conditions:
		- each coefficient should be smaller than 2^O(m^delta)
		- |R/(g)| is a large prime p (p > 2^lambda)
		- g^-1 when viewed in Q[X]/(X^m+1) is sufficiently small
		"""
		
		qr = QuotientRing(QQ[self.x], self.x**self.m+1)
		cond = False
		bound = 2**(int(self.m**self.delta))
		
		while not(cond):
			#all coefficients smaller than 2^O(m^delta)
			coeffs = [ZZ.random_element(0, bound) for i in range(self.m)]
			g = sum([a*self.t**i for a, i in zip(coeffs, range(len(coeffs)))])

			#conditions:
			#|R/(g)| is large prime p (p > 2^lambda/securityParameter)
			self.p = g.norm()
			p = self.p
			cond = p > 2**self.secParam and p in Primes()

			#g^-1 when viewed in Q[X]/(X^m+1) sufficiently small
			if cond:
				g_1 = qr(g)**(-1)
				cond = all([abs(c) < bound for c in g_1.list()])
		
		return g
コード例 #36
0
ファイル: kplt.py プロジェクト: joelypoley/isogenies
def is_minkowski_basis(basis):
    """Checks if the basis is Minkowski."""
    # TODO: Ask Steven about Minkowskiness.
    return all(
        one_norm(alpha_i) <= one_norm(
            sum(alpha_j for alpha_j in basis if alpha_j != alpha_i))
        for alpha_i in basis)
コード例 #37
0
ファイル: miscs.py プロジェクト: ruricolist/dig
    def getTerms(ss, deg):
        """
        get a list of terms from the given list of vars and deg
        the number of terms is len(rs) == binomial(len(ss)+d, d)

        Note: itertools is faster than Sage's MultichooseNK(len(ss)+1,deg)

        sage: ts = getTerms(list(var('a b')), 3)
        sage: assert ts == [1, a, b, a^2, a*b, b^2, a^3, a^2*b, a*b^2, b^3]

        sage: ts = getTerms(list(var('a b c d e f')), 3)
        sage: ts
        [1, a, b, c, d, e, f,
        a^2, a*b, a*c, a*d, a*e, a*f,
        b^2, b*c, b*d, b*e, b*f, c^2, c*d, c*e, c*f,
        d^2, d*e, d*f, e^2, e*f, f^2, a^3, a^2*b, a^2*c, a^2*d, a^2*e,
        a^2*f, a*b^2, a*b*c, a*b*d, a*b*e, a*b*f, a*c^2, a*c*d, a*c*e,
        a*c*f, a*d^2, a*d*e, a*d*f, a*e^2, a*e*f, a*f^2,
        b^3, b^2*c, b^2*d, b^2*e, b^2*f, b*c^2, b*c*d, b*c*e, b*c*f, b*d^2,
        b*d*e, b*d*f, b*e^2, b*e*f, b*f^2, c^3, c^2*d, c^2*e, c^2*f, c*d^2,
        c*d*e, c*d*f, c*e^2, c*e*f, c*f^2, d^3, d^2*e, d^2*f, d*e^2, d*e*f,
        d*f^2, e^3, e^2*f, e*f^2, f^3]

        """
        assert deg >= 0, deg
        assert ss and all(s.is_symbol() for s in ss), ss
        ss_ = ([sage.all.SR(1)] if ss else (sage.all.SR(1), )) + ss
        combs = itertools.combinations_with_replacement(ss_, deg)
        terms = [sage.all.prod(c) for c in combs]
        return terms
コード例 #38
0
ファイル: sage_mat.py プロジェクト: yawara/my-gc
def get(R):
    G = nx.Graph()
    V = product(R, repeat=3)

    zero_vec = (R.zero(), R.zero(), R.zero())

    G.add_node(zero_vec)

    Rp = list(R)
    Rp.remove(R.zero())

    for v in V:
        if all(not (r * v[0], r * v[1], r * v[2]) in G for r in Rp):
            v[0].set_immutable()
            v[1].set_immutable()
            v[2].set_immutable()
            G.add_node((v[0], v[1], v[2]))

    G.remove_node(zero_vec)

    for line1, line2 in product(G, repeat=2):
        if line1 != line2 and dot_product(line1, line2, R) == R.zero():
            G.add_edge(line1, line2)

    return G
コード例 #39
0
def bv_solve(points, m):
    num_pts = len(points)
    Zn = FreeModule(ZZ, num_pts)
    M = Zn / (m * Zn)
    pointsT = transpose(points)
    num_vars = len(pointsT)

    # add zero columns if required to make square matrix
    zero_list = [0] * num_pts
    diff = num_pts - num_vars
    for i in range(diff):
        pointsT.append(zero_list)

    A = matrix(pointsT)
    phi = M.hom([M(a) for a in A])
    # print "Nullspace(kernel):"
    # print [M(b) for b in phi.kernel()]
    # print "Basis:"
    basis = [M(b) for b in phi.kernel().gens()]

    # ignore the solution if it has non-zero coeff for only added variables
    basis = filter(lambda s: not all(elem == 0 for elem in s[:num_vars]),
                   basis)

    ret = []
    for s in basis:
        # drop the last (num_pts -num_vars) zeros added
        s_crop = clip_last_zeros(s, num_vars, diff)
        # move constant term to the last
        soln = rearrange(s_crop, m)
        ret.append(soln)
    return ret
コード例 #40
0
ファイル: solve.py プロジェクト: Akshaymb07/write-ups-2015
def v16_to_v512(v):
  assert len(v) == 16
  assert all(0 <= x < 2**32 for x in v)

  u = [0] * 512
  for i in xrange(512):
    u[i] = (v[i / 32] >> (i % 32)) & 1
  return u
コード例 #41
0
ファイル: solve.py プロジェクト: Akshaymb07/write-ups-2015
def v512_to_v16(v):
  assert len(v) == 512
  assert all(x in [0,1] for x in v)

  u = [0] * 16
  for i in xrange(512):
    u[i / 32] |= v[i] << (i % 32)
  return u
コード例 #42
0
def terminates_on_zero(B_s,B_w):
    zv = zero_vector(B_s.dimensions()[1])
    s_conds=map(lambda x:x>0,(B_s * zv).list())
    w_conds=map(lambda x:x>=0,(B_w * zv).list())
    if all(s_conds+w_conds):
        return False
    else:
        return True
コード例 #43
0
ファイル: ILC_topology.py プロジェクト: mehdidc/boosting
 def _isNext(self, current, next, axis):
     assert isinstance(axis, tuple) and len(axis) == len(self.domain) and \
            all([isinstance(val, int) and val >= 0 for val in axis]) and numpy.sum(axis) == 1
     if isinstance(current, tuple):
         assert len(current) == 3
         i,j,k = current
     elif isinstance(current, int):
         assert 0 <= current < numpy.prod(self.domain)
     Width, Height, Depth = self.domain
     return next == (j + axis[0]) + Width * ((i + axis[1]) + Height * (k + axis[2]))
コード例 #44
0
 def stochastic_states( self, N ):
     from itertools import product
     if not all( sum(r) == 0 for r,_ in self._transitions ):
         # discretize the state space
         ss = [ vector(l) for l in product( *((i/N for i in range(N+1)) for s in self._vars) ) ] #if sum(l) <= 1 ]
     else:
         print 'Reducing dimension to', tuple(self._vars[:-1])
         ss = [ vector(l + (1 - sum(l),)) for l in product( *((i/N for i in range(N+1)) for s in self._vars[:-1]) ) if sum(l) <= 1 ]
     for s in ss: s.set_immutable()
     return ss
コード例 #45
0
ファイル: transfer.py プロジェクト: aldenwalker/sagescl
def cyclic_transfer_families(n, rank, ntrials, family_bound=8, cover_degree_bound=9, time_limit=None, verbose=1):
  gens = word.alphabet[:rank]
  found_transfers = []
  for i in xrange(ntrials):
    F = word.random_family(n, rank)
    #F = word.FreeGroupFamily(['bb','a','aBAAB'], 1, 0, 2, 2)
    family_transfers = []
    if verbose>1:
      print "Trying family", F
    N=1
    while True:
      try:
        s = frac_to_sage_Rational(scl.scl(F(N)))
        num_fatgraph_verts = len(scl.scl_surface(F(N)).V)
      except:
        if verbose > 1:
          print "Scl computation failed"
          break
      min_cover_deg = (s.denominator()/2 if s.denominator()%2 == 0 else s.denominator())
      if verbose>1:
        print "N = ", N, "scl =", s, "cover degree =", min_cover_deg      
      if N>2 and min_cover_deg==1:
        if verbose>1:
          print "Family isn't getting complicated"
        break
      if N > family_bound or min_cover_deg > cover_degree_bound:
        if verbose>1:
          print "Cover is too complicated"
        break
      #perms = [range(1,min_cover_deg) + [0]] + [range(min_cover_deg) for g in xrange(rank-1)]
      #G = covering.FISubgroup(gens, perms)
      G = covering.cyclic_cover(gens, min_cover_deg)
      ET = single_transfer(F(N), G, all_orders=True, time_limit=time_limit)
      if verbose>2:
        print "Found all orders: ",ET
      cyclic_ET = [et for et in ET if is_cyclic_cover_order(G, et)]
      if len(cyclic_ET) > 0:
        if verbose>1:
          print "Found transfer orders: ", cyclic_ET
        family_transfers.append( (N, 'fgverts: ' + str(num_fatgraph_verts), G, cyclic_ET) )
        if len(cyclic_ET) > 20:
          if verbose>1:
            print "Too many orders!"
          break
        N += 1
      else:
        break
    if family_transfers != []:
      first_degree = family_transfers[0][2].degree
      if all([ft[2].degree == first_degree for ft in family_transfers]):
        if verbose>1:
          print "All are the same degree:", str([ft[2].degree for ft in family_transfers]), "; not interesting"
      else:
        found_transfers.append( (F, family_transfers) )
  return found_transfers
コード例 #46
0
ファイル: rot_Sn_action.py プロジェクト: aldenwalker/sagescl
def quadpod_boundary_function(T_dict_in, rank, Q_in=None, T_in=None):
  gens = alphabet[:rank] + inverse(alphabet[:rank])
  if Q_in == None:
    Q = sage.combinat.subset.Subsets_sk(gens, 4)
  else:
    Q = Q_in
  if T_in == None:
    T = tripods(rank)
  else:
    T = T_in
  T_dict = {}
  for t in T_dict_in:
    T_dict[t] = T_dict_in[t]
    T_dict[(t[0], t[2], t[1])] = -T_dict_in[t]
    T_dict[(t[1], t[2], t[0])] = T_dict_in[t]
    T_dict[(t[1], t[0], t[2])] = -T_dict_in[t]
    T_dict[(t[2], t[0], t[1])] = T_dict_in[t]
    T_dict[(t[2], t[1], t[0])] = -T_dict_in[t]
  all_words = {}
  for q in Q:
    #for each quadruple, check that it is compatible
    #I'm just going to do this brute force
    all_quadpods = [ [q[0]] + x for x in permutations(q[1:])]
    its_compatible = False
    compatible_quadpods = []
    for qp in all_quadpods:
      tfq = tripods_from_quadpod(qp)
      if all([v==0 or v==1 for v in [T_dict.get(tuple(t), 0) for t in tfq]]):
        its_compatible = True
        compatible_quadpods.append(qp)
    if not its_compatible:
      break
    #print "For ", q, " found the compatible quadpods:"
    #print compatible_quadpods
    #add a boundary word wherever it is needed (part of a positive tripod)
    num_cqp = len(compatible_quadpods)
    for cqp in compatible_quadpods:
      #print "For ", cqp, " adding ",
      for i in xrange(4):
        a,b,c,d = cqp[i:] + cqp[:i]
        if True: #T_dict.get((a,b,c), 0) == 1 or T_dict.get((a,b,d),0)==1:
          w = a.swapcase() + b
          all_words[w] = all_words.get(w,0)+(1/Integer(num_cqp))
          #print w, (1/Integer(num_cqp)), 
        else:
          pass
          #print "Not ", a.swapcase() + b, (1/Integer(num_cqp)),

  if not its_compatible:
    return None
  return CQ(ell=2, rank=rank, rules=all_words)
コード例 #47
0
 def index_z(idx_cond_tuples,var_vector,num_vector):
         # partial index_z function needs to be associated to a k
         def handle_expression(d,exp):
             if isinstance(exp,bool):
                 return exp
             else:
                 return exp.substitute(d)
         d=subsdict(var_vector,num_vector)
         for (i,cs) in idx_cond_tuples:
             num_cs=map(lambda c: handle_expression(d,c),cs)
             # print num_cs, all(num_cs)
             if all(num_cs):
                 return i
         return None
コード例 #48
0
def QuadraticForm_from_quadric(Q):
    """
    On input a homogeneous polynomial of degree 2 return the Quadratic Form corresponding to it.
    """
    R = Q.parent()
    assert all([sum(e)==2 for e in Q.exponents()])
    M = copy(zero_matrix(R.ngens(),R.ngens()))
    for i in range(R.ngens()):
        for j in range(R.ngens()):
            if i==j:
                M[i,j]=2*Q.coefficient(R.gen(i)*R.gen(j))
            else:
                M[i,j]=Q.coefficient(R.gen(i)*R.gen(j))
   
    return QuadraticForm(M)
コード例 #49
0
ファイル: conjecture.py プロジェクト: nvcleemp/inp
    def __init__(self, name=None, comparator=operator.le, graphs=[],
                 target=INPGraph.independence_number,
                 graph_invariants=_default_graph_invariants,
                 unary_operators=_default_unary_operators,
                 binary_commutative_operators=_default_binary_commutative_operators,
                 binary_noncommutative_operators=_default_binary_noncommutative_operators):
        self.name = name
        self.comparator = comparator
        self.target = target

        if not all(isinstance(g, INPGraph) for g in graphs):
            raise TypeError("Graphs must be INPGraph objects.")
        else:
            self.graphs = graphs

        self.graph_invariants = graph_invariants
        self.unary_operators = unary_operators
        self.binary_commutative_operators = binary_commutative_operators
        self.binary_noncommutative_operators = binary_noncommutative_operators
コード例 #50
0
	def encode(self, a, levelSet):
		"""Encode the element a at the level described by levelSet"""
		
		assert(all(i<self.k for i in levelSet))
		
		#reduce a modulo (g) to get small polynomial a^ in R
		aHat = self.R(a).mod(self.g)

		#choose error so that it is small and a^+e*g is discrete centered at the origin
		#all coefficients smaller than 2^O(m^delta)
		bound = 2**(int(self.m**self.delta)/2)
		coeffs = [ZZ.random_element(0, bound) for i in range(self.m)]
		error = sum([a*self.t**i for a, i in zip(coeffs, range(len(coeffs)))])
		
		#return: (a^ + e*g) / product of all z_i (i elem S)
		numerator = self.R_q(aHat + error*self.g)
		denominator = self.R_q(reduce(mul, [self.zList[i] for i in levelSet]))
		
		return numerator/denominator
コード例 #51
0
ファイル: device_process.py プロジェクト: kramer314/sagecell
def upload_files(upload_recv, file_child, session, fs_secret):
    """
    The user can pass in a list of filenames as a json message.  These will get uploaded.
    When the upload_queue gets an "end_exec" message, it then sends the hmac down the 
    file_child pipe and exits
    """
    # for some reason, doing fs.new_context hangs on the statement when fs._xreq is assigned
    from filestore import FileStoreZMQ
    global fs
    fs=FileStoreZMQ(fs.address)

    fs_hmac=hmac.new(fs_secret, digestmod=sha1)
    log("starting fs secret for upload_files: %r"%fs_hmac.digest())
    del fs_secret

    file_list={}
    while True:
        # The problem with using a Pipe is that if the user is writing file messages from several
        # threads, there can be a problem.  Maybe we should use normal sockets or a special file?
        try:
            msg=json.loads(upload_recv.recv_bytes())
        except Exception as e:
            log("An exception occurred in receiving file message: %s\n"%(e,))
            upload_recv.send_bytes("error")
            continue
        # note: check for basestring since json stuff comes back as unicode strings
        if isinstance(msg, list) and all(isinstance(i,basestring) for i in msg):
            # TODO: sanitize pathnames to only upload files below the current directory
            for filename in msg:
                try:
                    file_list[filename]=os.stat(filename).st_mtime
                    with open(filename) as f:
                        fs.create_file(f, session=session, session_auth_channel='upload', filename=filename, hmac=fs_hmac)
                except Exception as e:
                    log("An exception occurred in uploading files: %s\n"%(e,))
            upload_recv.send_bytes("success")
        elif isinstance(msg, dict) and 'msg_type' in msg and msg['msg_type']=='end_exec':
            file_child.send(file_list)
            # we recv just to make sure that we are synchronized with the execing process
            file_child.recv()
        elif isinstance(msg, dict) and 'msg_type' in msg and msg['msg_type']=='end_session':
            break
コード例 #52
0
def generators_of_subgroups_of_unit_group(R):
    """
    INPUT:
    
    - R - a commutative ring whose unit group is finite
    
    OUTPUT:
    
    - An iterator which yields a set of generators for each subgroup of R^*
    
    EXAMPLES::
        
        sage: list(generators_of_subgroups_of_unit_group(Integers(28)))
        [[15, 17], [11], [3], [13, 15], [15], [27], [17], [9], [13], []]
    
    """
    gens = R.unit_gens()
    invariants = [g.multiplicative_order() for g in gens]
    assert all(i!=0 for i in invariants)
    A=AbelianGroup(invariants)
    for G in A.subgroups():
        yield [prod(f**e for f,e in zip(gens,g.exponents())) for g in G.gens()]
コード例 #53
0
 def hamiltonian_system( self, p_vars=[], reduce=False, return_h=False ):
     if len(p_vars) == 0:
         p_vars = [ mk_var('p', v) for v in self._vars ]
     ## todo: this reduction repeats code with stochastic_states()?
     if reduce and all( sum(r) == 0 for r,_ in self._transitions ):
         print 'Reducing dimensions to', tuple(self._vars[:-1])
         reduce_bindings = dynamicalsystems.Bindings( { self._vars[-1]: 1 - sum(self._vars[:-1]) } )
         if len(p_vars) == len(self._vars):
             reduce_bindings.merge_in_place( { p_vars[-1] : 0 } )
             p_vars = p_vars[:-1]
     else:
         reduce=False
         reduce_bindings = dynamicalsystems.Bindings()
     vp = vector(p_vars)
     H = sum(
         reduce_bindings(m) * ( exp(
             vector(r[:len(vp)]).dot_product( vp )
         ) - 1 )
         for r,m in self._transitions
     )
     if return_h: return H
     x_vars = self._vars[:len(p_vars)]
     return hamiltonian.HamiltonianODE( H, x_vars, p_vars, bindings=reduce_bindings )
コード例 #54
0
ファイル: morph.py プロジェクト: aldenwalker/sagescl
 def is_identity(self):
   return all([self.rules[g]==g for g in self.rules])
コード例 #55
0
ファイル: fiberWalks.py プロジェクト: windisch/FiberMixing
def isPositive(u):
   return all(j>=0 for j in u)
コード例 #56
0
ファイル: candidates_mpi.py プロジェクト: videlec/max_plus
 def done(self):
     return not self.job_list and all(x is None for x in self.submitted)
コード例 #57
0
ファイル: elliptic_curve.py プロジェクト: sibilant/lmfdb
def elliptic_curve_search(**args):
    info = to_dict(args)
    query = {}
    bread = [('Elliptic Curves', url_for("ecnf.index")),
             ('$\Q$', url_for(".rational_elliptic_curves")),
             ('Search Results', '.')]
    if 'SearchAgain' in args:
        return rational_elliptic_curves()

    if 'jump' in args:
        label = info.get('label', '').replace(" ", "")
        m = match_lmfdb_label(label)
        if m:
            try:
                return by_ec_label(label)
            except ValueError:
                return elliptic_curve_jump_error(label, info, wellformed_label=True)
        elif label.startswith("Cremona:"):
            label = label[8:]
            m = match_cremona_label(label)
            if m:
                try:
                    return by_ec_label(label)
                except ValueError:
                    return elliptic_curve_jump_error(label, info, wellformed_label=True)
        elif match_cremona_label(label):
            return elliptic_curve_jump_error(label, info, cremona_label=True)
        elif label:
            # Try to parse a string like [1,0,3,2,4] as valid
            # Weistrass coefficients:
            lab = re.sub(r'\s','',label)
            lab = re.sub(r'^\[','',lab)
            lab = re.sub(r']$','',lab)
            try:
                labvec = lab.split(',')
                labvec = [QQ(str(z)) for z in labvec] # Rationals allowed
                E = EllipticCurve(labvec)
                # Now we do have a valid curve over Q, but it might
                # not be in the database.
                ainvs = [str(c) for c in E.minimal_model().ainvs()]
                data = db_ec().find_one({'ainvs': ainvs})
                if data is None:
                    info['conductor'] = E.conductor()
                    return elliptic_curve_jump_error(label, info, missing_curve=True)
                return by_ec_label(data['lmfdb_label'])
            except (TypeError, ValueError, ArithmeticError):
                return elliptic_curve_jump_error(label, info)
        else:
            query['label'] = ''

    if info.get('jinv'):
        j = clean_input(info['jinv'])
        j = j.replace('+', '')
        if not QQ_RE.match(j):
            info['err'] = 'Error parsing input for the j-invariant.  It needs to be a rational number.'
            return search_input_error(info, bread)
        query['jinv'] = str(QQ(j)) # to simplify e.g. 1728/1

    for field in ['conductor', 'torsion', 'rank', 'sha']:
        if info.get(field):
            info[field] = clean_input(info[field])
            ran = info[field]
            ran = ran.replace('..', '-').replace(' ', '')
            if not LIST_RE.match(ran):
                names = {'conductor': 'conductor', 'torsion': 'torsion order', 'rank':
                         'rank', 'sha': 'analytic order of &#1064;'}
                info['err'] = 'Error parsing input for the %s.  It needs to be an integer (such as 25), a range of integers (such as 2-10 or 2..10), or a comma-separated list of these (such as 4,9,16 or 4-25, 81-121).' % names[field]
                return search_input_error(info, bread)
            # Past input check
            tmp = parse_range2(ran, field)
            # work around syntax for $or
            # we have to foil out multiple or conditions
            if tmp[0] == '$or' and '$or' in query:
                newors = []
                for y in tmp[1]:
                    oldors = [dict.copy(x) for x in query['$or']]
                    for x in oldors:
                        x.update(y)
                    newors.extend(oldors)
                tmp[1] = newors
            query[tmp[0]] = tmp[1]

    if 'optimal' in info and info['optimal'] == 'on':
        # fails on 990h3
        query['number'] = 1

    if 'torsion_structure' in info and info['torsion_structure']:
        res = parse_torsion_structure(info['torsion_structure'])
        if 'Error' in res:
            info['err'] = res
            return search_input_error(info, bread)
        #update info for repeat searches
        info['torsion_structure'] = str(res).replace(' ','')
        query['torsion_structure'] = [str(r) for r in res]

    if info.get('surj_primes'):
        info['surj_primes'] = clean_input(info['surj_primes'])
        format_ok = LIST_POSINT_RE.match(info['surj_primes'])
        if format_ok:
            surj_primes = [int(p) for p in info['surj_primes'].split(',')]
            format_ok = all([ZZ(p).is_prime(proof=False) for p in surj_primes])
        if format_ok:
            query['non-surjective_primes'] = {"$nin": surj_primes}
        else:
            info['err'] = 'Error parsing input for surjective primes.  It needs to be a prime (such as 5), or a comma-separated list of primes (such as 2,3,11).'
            return search_input_error(info, bread)

    if info.get('nonsurj_primes'):
        info['nonsurj_primes'] = clean_input(info['nonsurj_primes'])
        format_ok = LIST_POSINT_RE.match(info['nonsurj_primes'])
        if format_ok:
            nonsurj_primes = [int(p) for p in info['nonsurj_primes'].split(',')]
            format_ok = all([ZZ(p).is_prime(proof=False) for p in nonsurj_primes])
        if format_ok:
            if info['surj_quantifier'] == 'exactly':
                nonsurj_primes.sort()
                query['non-surjective_primes'] = nonsurj_primes
            else:
                if 'non-surjective_primes' in query:
                    query['non-surjective_primes'] = { "$nin": surj_primes, "$all": nonsurj_primes }
                else:
                    query['non-surjective_primes'] = { "$all": nonsurj_primes }
        else:
            info['err'] = 'Error parsing input for nonsurjective primes.  It needs to be a prime (such as 5), or a comma-separated list of primes (such as 2,3,11).'
            return search_input_error(info, bread)

    if 'download' in info and info['download'] != '0':
        res = db_ec().find(query).sort([ ('conductor', ASCENDING), ('lmfdb_iso', ASCENDING), ('lmfdb_number', ASCENDING) ])
        return download_search(info, res)
    
    count_default = 100
    if info.get('count'):
        try:
            count = int(info['count'])
        except:
            count = count_default
    else:
        count = count_default
    info['count'] = count

    start_default = 0
    if info.get('start'):
        try:
            start = int(info['start'])
            if(start < 0):
                start += (1 - (start + 1) / count) * count
        except:
            start = start_default
    else:
        start = start_default

    cursor = db_ec().find(query)
    nres = cursor.count()
    if(start >= nres):
        start -= (1 + (start - nres) / count) * count
    if(start < 0):
        start = 0
    res = cursor.sort([('conductor', ASCENDING), ('lmfdb_iso', ASCENDING), ('lmfdb_number', ASCENDING)
                       ]).skip(start).limit(count)
    info['curves'] = res
    info['format_ainvs'] = format_ainvs
    info['curve_url'] = lambda dbc: url_for(".by_triple_label", conductor=dbc['conductor'], iso_label=split_lmfdb_label(dbc['lmfdb_iso'])[1], number=dbc['lmfdb_number'])
    info['iso_url'] = lambda dbc: url_for(".by_double_iso_label", conductor=dbc['conductor'], iso_label=split_lmfdb_label(dbc['lmfdb_iso'])[1])
    info['number'] = nres
    info['start'] = start
    if nres == 1:
        info['report'] = 'unique match'
    elif nres == 2:
        info['report'] = 'displaying both matches'
    else:
        if nres > count or start != 0:
            info['report'] = 'displaying matches %s-%s of %s' % (start + 1, min(nres, start + count), nres)
        else:
            info['report'] = 'displaying all %s matches' % nres
    credit = 'John Cremona'
    if 'non-surjective_primes' in query:
        credit += 'and Andrew Sutherland'
    t = 'Elliptic Curves search results'
    return render_template("search_results.html", info=info, credit=credit, bread=bread, title=t)
コード例 #58
0
ファイル: transfer.py プロジェクト: aldenwalker/sagescl
def find_transfer_families(n, ntrials, rank=2, \
                           cover_deg_bound=4,  \
                           fatgraph_size_bound=50, \
                           covers_to_try=None,
                           verbose=1):
  found_transfer_families = []
  for i in xrange(ntrials):
    F = word.random_family(n, rank, gens=['x','y'])
    if verbose>1:
      print "\nTrying family: ", F
    transfers = []
    N = 1
    while True:
      try:
        s = frac_to_sage_Rational(scl.scl(F(N)))
      except:
        if verbose > 1:
          print "Scl computation failed"
        break
      min_cover_deg = (s.denominator()/2 if s.denominator()%2 == 0 else s.denominator())
      if verbose > 1:
        print "Trying F(" +  str(N) +  ") = " + str(F(N))
        print "scl = ", s
        print "Min cover degree: ", min_cover_deg
      
      if N>2 and min_cover_deg == 1:
        if verbose > 1:
          print "Family scl isn't getting complicated"
        break
      if N>10:
        if verbose>1:
          print "Family is getting too complicated"
        break
      if cover_deg_bound > 4:
        if verbose > 1:
          print "Min cover degree ", min_cover_deg, " is too big"
        break
      
      if verbose>1:
        print "Finding extremal transfers at degree: ", [min_cover_deg]
      T = find_extremal_transfer(F(N), degree_list=[min_cover_deg], covers_to_try=covers_to_try, fatgraph_size_bound=fatgraph_size_bound, just_one=True)
      
      if len(T) > 0:
        if verbose>1:
          print "Found ", len(T), " good transfers"
        transfers.append(T)
        N += 1
      else:
        break
    
    if all([t[0][1].degree==1 for t in transfers]):
      #don't record this
      if verbose > 1:
        print "We only found extremal basic rots"
      continue
    elif len(transfers) == 0:
      if verbose>1:
        print "We found no transfers"
      continue
    
    if verbose>1:
      print "We found some good transfers"
    found_transfer_families.append( ( F, transfers ) )
      
  return found_transfer_families
コード例 #59
0
    def t1_prime(self, n=5, p=65521):
        """
        Return a multiple of element t1 of the Hecke algebra mod 2,
        computed using the Hecke operator $T_n$, where n is self.n.
        To make computation faster we only check if ...==0 mod p.
        Hence J will contain more elements, hence we get a multiple.
        
        INPUT:
        
            - `n` -- integer (optional default=5)
            - `p` -- prime (optional default=65521)

        OUTPUT:

            - a mod 2 matrix

        EXAMPLES::

            sage: C = KamiennyCriterion(29)
            sage: C.t1_prime()
            22 x 22 dense matrix over Finite Field of size 2
            sage: C.t1_prime() == 1
            True
            sage: C = KamiennyCriterion(37)
            sage: C.t1_prime()[0]
            (0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1)
        """
        if self.verbose: tm = cputime(); mem = get_memory_usage(); print "t1 start"
        T = self.S.hecke_matrix(n)
        if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "hecke 1"
        f = self.hecke_polynomial(n) # this is the same as T.charpoly()
        if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "char 1"
        Fint = f.factor()
        if all(i[1]!=1 for i in Fint):
            return matrix_modp(zero_matrix(T.nrows()))
        #    raise ValueError("T_%s needs to be a generator of the hecke algebra"%n)
        if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "factor 1, Fint = %s"%(Fint)
        R = f.parent().change_ring(GF(p))
        F = Fint.base_change(R)
        # Compute the iterators of T acting on the winding element.
        e = self.M([0, oo]).element().dense_vector().change_ring(GF(p))
        if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "wind"
        t = matrix_modp(self.M.hecke_matrix(n).dense_matrix(), p)
        if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "hecke 2"
        g = t.charpoly()
        if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "char 2"
        Z = t.iterates(e, t.nrows(), rows=True)
        if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "iter"
        # We find all factors F[i][0] for f such that
        # (g/F[i][0])(t) * e = 0.
        # We do this by computing the polynomial
        #       h = g/F[i][0],
        # turning it into a vector v, and computing
        # the matrix product v * Z.  If the product
        # is 0, then e is killed by h(t).
        J = []
        for i in range(len(F)):
            if F[i][1]!=1:
                J.append(i)
                continue
            h, r = g.quo_rem(F[i][0] ** F[i][1])
            assert r == 0
            v = vector(GF(p), h.padded_list(t.nrows()))
            if v * Z == 0:
                J.append(i)
        if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "zero check"

        if self.verbose: print "J =", J
        if len(J) == 0:
            # The annihilator of e is the 0 ideal.
            return matrix_modp(identity_matrix(T.nrows()))

        # Finally compute t1.  I'm concerned about how
        # long this will take, so we reduce T mod 2 first.

        # It is important to call "self.T(2)" to get the mod-2
        # reduction of T2 with respect to the right basis (e.g., the
        # integral basis in case use_integral_structure is true.
        Tmod2 = self.T(n)
        if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "hecke mod" 
        g = prod(Fint[i][0].change_ring(GF(2)) ** Fint[i][1] for i in J)
        if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "g has degree %s"%(g.degree())
        t1 = g(Tmod2)
        if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "t1 finnished"
        return t1        
コード例 #60
0
                results.append({"torsion_order":torsion_order,"congruence_type":congruence_type,
                            "algorithm":algorithm,"degree":degree,"n":t1n,"p":t1mod,
                            "q":t2q,"satisfied":satisfied,"message":message,"use_rand_vec":use_rand_vec,
                            "result_type":"single"})
                if stop_if_satisfied and satisfied:
                    break
            if stop_if_satisfied and satisfied:
                break

        print [len(i) for i in dependancy_spaces]
        intersected_dependancy_spaces=[]
        if dependancy_spaces:
            for i in range(len(dependancy_spaces[0])):
                intersection=reduce(lambda x,y:x.intersection(y), [s[i] for s in dependancy_spaces])
                intersected_dependancy_spaces.append(intersection)
            satisfied=all([d.dimension()<13 and (d.dimension()==0 or LinearCodeFromVectorSpace(d).minimum_distance()>degree) 
                                        for d in intersected_dependancy_spaces])
            results.append({"torsion_order":torsion_order,"congruence_type":congruence_type,
                            "algorithm":algorithm,"degree":degree,"n":(n_min,n_max),"p":t1mod,
                            "q":(q_min,q_max),"satisfied":satisfied,"message":"","use_rand_vec":use_rand_vec,
                            "result_type":"range"})
        return results,dependancy_spaces


        

    def verify_criterion(self, d, t=None, n=5, p=65521, q=3, v=None, use_rand_vec=True, verbose=False):
        """
        Attempt to verify the criterion at p using the input t. If t is not
        given compute it using n, p and q

        INPUT: