Ejemplo n.º 1
0
def signature_function_of_integral_matrix(V, prec=53):
    """
    Computes the signature function sigma of V via numerical methods.
    Returns two lists, the first representing a partition of [0, 1]:

         x_0 = 0 < x_1 < x_2 < ... < x_n = 1

    and the second list consisting of the values [v_0, ... , v_(n-1)]
    of sigma on the interval (x_i, x_(i+1)).  Currently, the value of
    sigma *at* x_i is not computed.
    """
    poly = alexander_poly_from_seifert(V)
    RR = RealField(prec)
    CC = ComplexField(prec)
    pi = RR.pi()
    I = CC.gen()
    partition = [RR(0)] + [a for a, e in roots_on_unit_circle(poly, prec)
                           ] + [RR(1)]
    n = len(partition) - 1
    values = []
    for i in range(n):
        omega = exp((2 * pi * I) * (partition[i] + partition[i + 1]) / 2)
        A = (1 - omega) * V + (1 - omega.conjugate()) * V.transpose()
        values.append(signature_via_numpy(A))

    assert list(reversed(values)) == values
    return partition, values
Ejemplo n.º 2
0
def compare_row(a, b, verbose=True):
    for i, c in enumerate(cols):
        if c in [
                'hecke_orbit_code', 'conrey_label', 'embedding_index',
                'embedding_m'
        ]:
            if a[i] != b[i]:
                print(c, a[i], b[i])
                return False
        elif c in ['embedding_root_real', 'embedding_root_imag']:
            if not compare_floats(a[i], b[i]):
                print(c, a[i], b[i], a[i] - b[i])
                return False
        elif c == 'an':
            for j, ((ax, ay), (bx, by)) in enumerate(zip(a[i], b[i])):
                if not compare_floats(ax, bx):
                    print(c, j, ax, bx, ax - bx)
                    if ax != 0:
                        print(RR(abs((ax - bx) / ax)).log(2))
                    return False
                if not compare_floats(ay, by):
                    print(c, j, ay, by, ay - by)
                    if ay != 0:
                        print(RR(abs((ay - by) / ay)).log(2))
                    return False
        elif c == 'angles':
            for j, (at, bt) in enumerate(zip(a[i], b[i])):
                if not compare_floats(at, bt):
                    print(c, j, at, bt)
                    if None not in [at, bt]:
                        print(at - bt)
                        if at != 0:
                            print(RR(abs((at - bt) / at)).log(2))
                    return False
    return True
Ejemplo n.º 3
0
def DecomposeSpaces(filename,
                    Nk2min,
                    Nk2max,
                    dmax=20,
                    nan=100,
                    njobs=1,
                    jobno=0,
                    Detail=0):
    out = open(filename, 'w') if filename else None
    screen = sys.stdout
    Nmax = int(Nk2max / 4.0)
    nspaces = 0
    n = -1  # will increment for each (N,k,chi) in range, so we skip unless n%njobs==jobno
    failed_spaces = []
    for N in range(1, Nmax + 1):
        kmin = max(2, (RR(Nk2min) / N).sqrt().ceil())
        kmax = (RR(Nk2max) / N).sqrt().floor()
        if kmin > kmax:
            continue
        level_info = "N = {}: ".format(N)
        level_info += "{} <=k<= {} ".format(kmin, kmax)
        #level_info += "({} <=Nk^2<= {})".format(N*kmin**2,N*kmax**2)
        #screen.write(level_info)
        info_written = False
        nchars = NChars(N)
        for k in range(kmin, kmax + 1):
            if not info_written:
                screen.write(level_info)
                info_written = True
            screen.write(" [k={}] ".format(k))
            screen.flush()
            nspaces += 1

            for i in range(nchars):
                n += 1
                if n % njobs != jobno:
                    continue

                screen.write(" (o={}) ".format(i + 1))
                screen.flush()
                t0 = time.time()
                try:
                    newforms = Newforms(N, k, i + 1, dmax, nan, Detail)
                    t0 = time.time() - t0
                    line = data_to_string(N, k, i + 1, t0, newforms) + "\n"
                    if out:
                        out.write(line)
                        out.flush()
                    else:
                        screen.write('\n')
                        screen.write(line)
                except PariError, e:
                    t1 = time.time()
                    print(
                        "\n*************************\nPariError {} on ({},{},{}) after {}s\n***********************"
                        .format(e, N, k, i + 1, t1 - t0))
                    failed_spaces.append((N, k, i + 1))
        if info_written:
            screen.write('\n')
            screen.flush()
Ejemplo n.º 4
0
def find_packing(ccdata):
    """
    INPUT:

    - ``ccdata`` -- a list of pairs `(n, o)` of Integers, one for each conjugacy class, giving the size `n` and order `o`

    OUTPUT:

    - a list of tuples `(x, y, r, rgb)` giving centers `(x, y)`, radii `r` and color triple `rgb` for the image associated to this conjugacy class data
    - a real number `R` so that all circles will be contained within the box [-R, R] x [-R, R]
    """
    by_pcount = defaultdict(list)
    for (n, o) in ccdata:
        n, o = ZZ(n), ZZ(o)
        if o != 1:
            by_pcount[sum(e for (p, e) in o.factor())].append(
                (get_radius(n), o))
    r0 = R = get_radius(1)
    circles = [(RR(0), RR(0), r0, get_color(ZZ(1)))]
    for pcnt in sorted(by_pcount):
        # Add a gap between annuli
        annulus = by_pcount[pcnt]
        r1 = max(r for (r, o) in annulus)
        R += max(r0, r1)
        r0 = r1
        new_circles, R = arrange(annulus, R, r0)
        circles.extend(new_circles)
    return circles, R
Ejemplo n.º 5
0
    def sample_motion(self, N, numeric=True, start_margin=0, end_margin=0):
        r"""
        Return a sampling of the motion.

        TODO:

        Doc, examples
        """
        a, b = self._interval
        if numeric:
            if self._sampling_type == 'uniform':
                return [self.realization(RR(a + (i/Integer(N)) * (b-a)),  numeric=True) 
                        for i in range(start_margin, N+1-end_margin)]
            elif self._sampling_type == 'tan':
                return [self.realization(tan(RR(a + (i/Integer(N)) * (b-a))),  numeric=True) 
                        for i in range(start_margin, N+1-end_margin)]
            else:
                raise exceptions.NotImplementedError('Sampling ' + str(self._sampling_type) + ' is not supported.')
        else:
            if self._sampling_type == 'uniform':
                return [self.realization(a + (i/Integer(N)) * (b-a)) 
                        for i in range(start_margin, N+1-end_margin)]
            elif self._sampling_type == 'tan':
                return [self.realization(tan(a + (i/Integer(N)) * (b-a))) 
                        for i in range(start_margin, N+1-end_margin)]
            else:
                raise exceptions.NotImplementedError('Sampling ' + str(self._sampling_type) + ' is not supported.')
Ejemplo n.º 6
0
    def realization(self, value,  numeric=False):
        r"""
        Return the realization for given value of the parameter.

        TODO:

        Doc, examples
        """
        res = {}
        if self._par_type == 'symbolic':
            subs_dict = { self._parameter : value}
            for v in self._graph.vertices():
                if numeric:
                    res[v] = vector([RR(xi.subs(subs_dict)) for xi in self._parametrization[v]])
                else:
                    res[v] = vector([xi.subs(subs_dict) for xi in self._parametrization[v]])
            return res
        elif self._par_type == 'rational':
            h = self._field.hom(value)
            for v in self._graph.vertices():
                if numeric:
                    res[v] = vector([RR(h(xi)) for xi in self._parametrization[v]])
                else:
                    res[v] = vector([h(xi) for xi in self._parametrization[v]])
            return res
        else:
            raise exceptions.NotImplementedError('')
Ejemplo n.º 7
0
def Nspaces(Nk2min, Nk2max):
    Nmax = int(Nk2max / 4.0)
    nspaces = 0
    for N in range(1, Nmax + 1):
        kmin = max(2, (RR(Nk2min) / N).sqrt().ceil())
        kmax = (RR(Nk2max) / N).sqrt().floor()
        if kmin > kmax:
            continue
        nspaces += NChars(N) * (1 + kmax - kmin)
    return nspaces
Ejemplo n.º 8
0
def pack(rdata, R0, rmax):
    """
    INPUT:

    - ``rdata`` -- a list of pairs `(r, o)` to be packed into an annulus
    - ``R0`` -- the inner radius of the annulus
    - ``rmax`` -- the maximum radius of any circle to be packed

    OUTPUT:

    - a list of tuples `(x, y, r, rgb)` as in the output of find_packing
    - the incremental radius of the annulus used
    """
    # If there are few enough circles, we space them out around the annulus with uniform gaps
    # We approximate the intersections as happening at radius R0+rmax, then check that this doesn't cause problems
    rdata = sorted(rdata, key=lambda pair: (-pair[1].valuation(2), -pair[1].valuation(3), pair[1], -pair[0]))
    #print("Packing", R0, rmax, rdata)
    radii = [r for (r, o) in rdata]
    Rc = R0 + rmax
    thetasum = sum(2*r / Rc for r in radii)
    if thetasum < 2*pi:
        thetaspace = (2*pi - thetasum) / len(rdata)
        thetas = [RR(0)]
        for i in range(len(rdata) - 1):
            thetas.append(thetas[i] + (radii[i] + radii[i+1])/Rc + thetaspace)
        pos = [(Rc * theta.cos(), Rc * theta.sin()) for theta in thetas]
        if all(distxy(pos[i], pos[(i+1) % len(pos)]) >= radii[i] + radii[(i+1) % len(pos)] for i in range(len(pos))):
            return [(x, y, r, get_color(o)) for ((r, o), (x, y)) in zip(rdata, pos)], R0 + 2*rmax
    area = sum(r**2 for r in radii) # actually area/pi
    density = 0.86
    segments = []
    for i, (r, o) in enumerate(rdata):
        if i != 0 and o == rdata[i-1][1]:
            segments[-1][1][r] += 1
        else:
            segments.append((o, Counter({r: 1})))
    while True:
        R1 = (R0**2 + area / density).sqrt()
        squeezed = (R1 < R0 + 2*rmax)
        if squeezed:
            R1 = R0 + 2*rmax # 4*R0*rmax + 4*rmax^2 = area/density
        #print("Looping", density, R1, R0+2*rmax)
        placed = []
        thetamin = RR(0)
        for sctr, segment in enumerate(segments):
            ok, placements = place_segment(segment, R0, R1, thetamin, placed, sctr == len(segments) - 1)
            if not ok: break
            thetamin = max(C.theta for C in placements)
            placed.extend(placements)
        else:
            return [(C.x, C.y, C.r, get_color(C.o)) for C in placed], R1
        if squeezed:
            density = area / (4 * rmax * (R0 + rmax))
        density -= 0.01
Ejemplo n.º 9
0
def compare_formulas_2(D, k):
    d1 = old_div(RR(abs(D)), RR(6))
    if D < 0:
        D = -D
    s1 = RR(
        sqrt(abs(D)) * sum([
            log(d) for d in divisors(D) if is_fundamental_discriminant(-d)
            and kronecker(-d, old_div(D, d)) == 1
        ]))
    d2 = RR((old_div(2, (sqrt(3) * pi))) * s1)
    return d1 - d2, d2, RR(2 * sqrt(D) * log(D) / pi)
Ejemplo n.º 10
0
def estimate(nlen=256, m=85, klen=254, skip=None):
    """
    Estimate the cost of solving HNP for an ECDSA with biased nonces instance.

    :param nlen:
    :param m:
    :param klen:
    :param compute:
    :returns:
    :rtype:

    EXAMPLES::

        sage: estimate(256, m=85, klen=254)
        sage: estimate(160, m=85, klen=158)

    """
    from usvp import solvers

    if skip is None:
        skip = []

    ecdsa = ECDSA(nbits=nlen)
    klen_list = make_klen_list(klen, m)
    gh = ECDSASolver.ghf(m, ecdsa.n, klen_list, prec=nlen // 2)
    vol = ECDSASolver.volf(m, ecdsa.n, klen_list, prec=nlen // 2)
    target_norm = ECDSASolver.evf(m, max(klen_list), prec=nlen // 2)

    print(
        ("% {t:s} {h:s}, nlen: {nlen:3d}, m: {m:2d}, klen: {klen:.3f}").format(
            t=str(datetime.datetime.now()), h=socket.gethostname(), nlen=nlen, m=m, klen=float(mean(klen_list))
        )
    )

    print("     E[|b[0]|]: 2^{v:.2f}".format(v=float(RR(log(gh, 2)))))
    print("        E[|v|]: 2^{v:.2f}".format(v=float(RR(log(target_norm, 2)))))
    print("  E[v]/E[b[0]]: %.4f" % float(target_norm / gh))
    print("")

    for solver in solvers:
        if solver in skip:
            continue
        cost, params = solvers[solver].estimate((2 * log(vol), m + 1), target_norm ** 2)
        if cost is None:
            print(" {solver:20s} not applicable".format(solver=solver))
            continue
        else:
            print(
                " {solver:20s} cost: 2^{c:.1f} cycles ≈ {t:12.4f}h, aux data: {params}".format(
                    solver=solver, c=float(log(cost, 2)), t=cost / (2.0 * 10.0 ** 9 * 3600.0), params=params
                )
            )
Ejemplo n.º 11
0
    def evf(cls, m, max_klen, prec=53):
        """
        Estimate norm of target vector.

        :param m: number of samples
        :param klen: length of key to recover
        :param prec: precision to use

        """
        w = 2 ** (max_klen - 1)
        RR = RealField(prec)
        w = RR(w)
        return RR(sqrt(m * (w ** 2 / 3 + 1 / RR(6)) + w ** 2))
def run_instance(L, block_size, tours, evec):
    from fpylll import BKZ, LLL, GSO, IntegerMatrix
    from fpylll.algorithms.bkz2 import BKZReduction as BKZ2
    from sage.all import e

    A = IntegerMatrix.from_matrix(L)

    block_size = ZZ(block_size)
    par = BKZ.Param(block_size=block_size,
                    strategies=BKZ.DEFAULT_STRATEGY,
                    flags=BKZ.VERBOSE)

    block_size = ZZ(block_size)
    delta_0 = (block_size / (2 * pi * e) *
               (pi * block_size)**(1 / block_size))**(1 / (2 * block_size - 1))
    n = ZZ(L.nrows())
    alpha = delta_0**(-2 * n / (n - 1))

    if len(evec) == n - 1:
        evec = vector(list(evec) + [1])

    LLL.reduction(A)
    M = GSO.Mat(A)
    M.update_gso()

    vol = sqrt(prod([RR(M.get_r(i, i)) for i in range(n)]))

    norms = [
        map(lambda x: RR(log(x, 2)),
            [(alpha**i * delta_0**n * vol**(1 / n))**2 for i in range(n)])
    ]

    def proj(v, i):
        return v - vector(RR, M.to_canonical(list(M.from_canonical(v, 0, i))))

    # norms += [map(lambda x: RR(log(x,2)),
    #               [(stddev*sqrt(n-i))**2 for i in range(n)])]
    norms += [
        map(lambda x: RR(log(x, 2)),
            [proj(evec, i).norm()**2 for i in range(1, n - 1)])
    ]

    norms += [[log(RR(M.get_r(i, i)), 2) for i in range(n)]]

    bkz = BKZ2(M)

    for i in range(tours):
        bkz.tour(par)
        norms += [[log(M.get_r(i, i), 2) for i in range(n)]]

    return A.to_matrix(matrix(ZZ, n, n)), norms
Ejemplo n.º 13
0
def find_simple_anisotropic_parallel(num,
                                     s,
                                     weights=range(2,
                                                   Integer(27) / 2),
                                     dynamic=True,
                                     lower=1,
                                     only_2_n=False,
                                     reduction=False):
    r"""
      Test for anisotropic $k$-simple fqm's for $k$ in weights.

      INPUT::
        - num: upper bound
        - s: number of iterations
        - lower: lower bound
    """
    simple = dict()
    for kk in weights:
        simple[kk] = list()
    m = round(RR(num) / s)
    args = [(m * a + lower, min(m * (a + lower),
                                lower + num - 1), lower + num - 1, None, None,
             weights, True, dynamic, only_2_n, reduction) for a in range(s)]
    tests = find_simple_anisotropic_wrapper(args)
    done = 0

    #starttime = walltime()
    for test in tests:
        done += 1
        simple_part = test[1][0]
        if isinstance(simple_part, str):
            print "Result: ", test
            continue
        tt = test[1][1]
        for kk in simple_part.keys():
            print "Result from process: ", simple_part[kk]
            simple[kk] = uniq(simple[kk] + simple_part[kk])
        #tt = walltime(starttime)
        sl = [len(sp) for sp in simple.values()]
        num_simple = sum(sl)
        timeest = (s - done) * RR(tt) / RR(60)
        if timeest > 1:
            if timeest > 60:
                print("%g%% done, ETA: %d hour" +
                      ("s" if timeest / 60 >= 2 else "") +
                      ", %d minutes, simple lattices: %d") % (
                          RR(done) / RR(s) * 100, timeest / 60,
                          (timeest / 60).frac() * 60, num_simple)
            else:
                print("%g%% done, ETA: %d minute" +
                      ("s" if timeest >= 2 else "") + ", simple lattices: %d"
                      ) % (RR(done) / RR(s) * 100, timeest, num_simple)
        else:
            print "%g%% done, ETA: %d seconds, simple lattices: %d" % (
                RR(done) / RR(s) * 100, timeest * 60, num_simple)
    return simple
Ejemplo n.º 14
0
    def mvf(cls, m, max_klen, prec=53):
        """
        Maximal norm of target vector.

        :param m: number of samples
        :param max_klen: length of key to recover
        :param prec: precision to use


        """
        w = 2 ** (max_klen - 1)
        RR = RealField(prec)
        w = RR(w)
        d = m + 1
        return RR(sqrt(d) * w)
Ejemplo n.º 15
0
def AJ1_digits(f, P, desired_digits, mesh=4):
    for k in range(1, f.degree() + 1):
        assert mesh >= 2
        # the guess should take less than 2s
        working_digits = 300
        SetPariPrec(working_digits)
        CF = ComplexField(ceil(RR(log(10) / log(2)) * working_digits))
        aj = {}
        correct_digits = {}
        sum = 0
        total = 0
        guess = 10000
        CF = ComplexField(log(10) / log(2) * working_digits)
        for i in range(mesh, max(0, mesh - 3), -1):
            PariIntNumInit(i)
            aj[i] = AJ1(CF, f, P, k)
            if i < mesh:
                correct_digits[i] = RR((-log(
                    max([
                        abs(CF((aj[mesh][j] - x) / aj[mesh][j]))
                        for j, x in enumerate(aj[i])
                    ])) / log(10.)) / working_digits)
            if i + 1 < mesh:
                sum += correct_digits[i + 1] / correct_digits[i]
                total += 1
        for i in sorted(correct_digits.keys()):
            if correct_digits[i] > 1:
                guess = i
                break
        avg = sum / total
        if guess == 0 and avg > 1.1:
            guess = mesh - 1 + ceil(
                log((1.1 / correct_digits[mesh - 1])) / log(avg))

        if guess != 0 and 2**guess * desired_digits**2 * log(
                RR(desired_digits))**3 < (300**2 * 2**11 * log(RR(300))**3):
            SetPariPrec(ceil(desired_digits) + 10 * guess)
            PariIntNumInit(guess)
            CF = ComplexField(log(10) / log(2) * desired_digits)
            result = vector(CF, AJ1(CF, f, P, k))
            # avoiding memory leaks
            gp._reset_expect()
            load_gp()
            return result
    else:
        gp._reset_expect()
        load_gp()
        raise OverflowError
Ejemplo n.º 16
0
def real_parabolic_reps_from_ptolemy(M, pari_prec=15):
    R = PolynomialRing(QQ, 'x')
    RR = RealField(1000)
    ans = []
    obs_classes = M.ptolemy_obstruction_classes()
    for obs in obs_classes:
        V = M.ptolemy_variety(N=2, obstruction_class=obs)
        #for sol in V.retrieve_solutions():
        for sol in V.compute_solutions(engine='magma'):
            if sol.dimension > 0:
                print("Positive dimensional component!")
                continue
            prec = snappy.pari.set_real_precision(pari_prec)
            is_geometric = sol.is_geometric()
            snappy.pari.set_real_precision(prec)
            cross_ratios = sol.cross_ratios()
            shapes = [
                R(cross_ratios['z_0000_%d' % i].lift())
                for i in range(M.num_tetrahedra())
            ]
            s = shapes[0]
            p = R(sol.number_field())
            if p == 0:  # Field is Q
                assert False
            # print p, '\n'
            for r in p.roots(RR, False):
                rho = pe.real_reps.PSL2RRepOf3ManifoldGroup(
                    M,
                    target_meridian_holonomy=RR(1),
                    rough_shapes=[cr(r) for cr in shapes])
                rho.is_galois_conj_of_geom = is_geometric
                ans.append(rho)
    return ans
Ejemplo n.º 17
0
    def type_2_bounds(self):
        """generate the type 2 bounds table"""

        output_str = (
            r"${d}$ & ${Delta_K}$ & ${label}$ & ${rem} \times 10^{{{exp_at_10}}}$\\"
        )
        latex_output = []
        for d in range(2, self.range + 1):
            Delta_K, f_K, K, label = get_smallest_good_number_field(d)
            type_2_bound = RR(get_type_2_bound(K))
            log_type_2_bound = type_2_bound.log10()
            exp_at_10 = int(log_type_2_bound)
            rem = log_type_2_bound - exp_at_10
            rem = 10 ** rem
            rem = rem.numerical_approx(digits=3)
            lmfdb_link = LMFDB_NF_URL_TRUNK.format(label)
            lmfdb_link_latex = r"\href{{{the_link}}}{{{my_text}}}".format(
                the_link=lmfdb_link, my_text=label
            )
            output_here = output_str.format(
                d=d,
                Delta_K=Delta_K,
                label=lmfdb_link_latex,
                rem=rem,
                exp_at_10=exp_at_10,
            )
            latex_output.append(output_here)

        for one_line in latex_output:
            print(one_line)
Ejemplo n.º 18
0
    def representativeParameters(self):
        if self._representativeParameters :
            return self._representativeParameters

        initial = numerical_approx(self.pI) 
        final = numerical_approx(self.pF)
    
        curvature_Llam=[]
        linear_Llam=[]
        if self.curvature_plotpoints :
            print("Taking "+str(self.curvature_plotpoints)+" curvature points (can take a long time) ...")
            curvature_Llam=self.getRegularCurvatureParameter(initial,final,self.total_curvature()/self.curvature_plotpoints,initial_point=True,final_point=True)
            print("... done")
        if self.linear_plotpoints:
            import numpy
            # If not RR, the elements of Llam are type numpy.float64. In this case, computing the sqrt of negative return NaN instead of complex. Then we cannot remove the probably fake imaginary part. It happens for the function sqrt(cos(x)) with x=3*pi/2. 
            linear_Llam=[ RR(s) for s in  numpy.linspace(initial,final,self.linear_plotpoints)]
        Llam=[]
        Llam.extend(self.added_plotpoints)
        Llam.extend(linear_Llam)
        Llam.extend(curvature_Llam)
        Llam.sort()

        # seem to me that these two lines do not serve : (June 2017)
        #for llam in Llam:
        #    P=self.get_point(llam,advised=False)

        self._representativeParameters = Llam
        return Llam
Ejemplo n.º 19
0
def global_height(x, prec=53):
    r"""
    Return the (correct) global height of a homogeneous coordinate.

    EXAMPLES::
    
        sage: from rational_points import global_height
        sage: global_height([1/1,2/3,5/8])
        24
        sage: F.<u> = NumberField(x^3-5)
        sage: P = ProjectiveSpace(F, 2)
        sage: global_height(P(u,u^2/5,1))
        2.92401773821287
    """
    k = x[0].parent()
    # first get rid of the denominators
    denom = lcm([xi.denominator() for xi in x])
    x = [xi * denom for xi in x]
    if is_RationalField(k):
        return max(abs(xi) for xi in x) / gcd(x)
    else:
        finite = 1 / sum(k.ideal(xi) for xi in x).norm()
        d = k.degree()
        infinite = product(
            max(abs(xi.complex_embedding(prec, i)) for xi in x)
            for i in range(d))
        return (finite * infinite)**(RR(1) / d)
Ejemplo n.º 20
0
def make_y_coord(ainvs, x):
    a1, a2, a3, a4, a6 = ainvs
    f = ((x + a2) * x + a4) * x + a6
    b = (a1 * x + a3)
    d = (RR(b * b + 4 * f)).sqrt()
    y = ZZ((-b + d) / 2)
    return y, ZZ(d)
Ejemplo n.º 21
0
    def T(self, n):
        """
        Return matrix mod 2 of the n-th Hecke operator on the +1
        quotient of cuspidal modular symbols.

        INPUT:

            - `n` -- integer

        OUTPUT:

            matrix modulo 2

        EXAMPLES::

            sage: from mdsage import *
            sage: C = KamiennyCriterion(29)
            sage: C.T(2)
            22 x 22 dense matrix over Finite Field of size 2 (use the '.str()' method to see the entries)
            sage: C.T(2)[0]
            (1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1)
        """
        if self.verbose: tm = cputime(); mem = get_memory_usage(); print("T(%s) start" % (n))
        
        T = self.M.hecke_matrix(n).restrict(self.S_integral, check=False)
    
        if self.verbose: print("time and mem", cputime(tm), get_memory_usage(mem), "T created")
        if self.verbose: print("sparsity", len(T.nonzero_positions()) / RR(T.nrows()**2), T.nrows())
        T = matrix_modp(T)
        if self.verbose: print("time and mem", cputime(tm), get_memory_usage(mem), "T reduced")
        #self.M._hecke_matrices={}
        #self.S._hecke_matrices={}
        #if self.verbose: print "time and mem", cputime(tm), get_memory_usage(mem), "T freed"
        return matrix_modp(T)
Ejemplo n.º 22
0
def make_y_coords(ainvs, x):
    a1, a2, a3, a4, a6 = ainvs
    f = ((x + a2) * x + a4) * x + a6
    b = (a1 * x + a3)
    d = (RR(b * b + 4 * f)).sqrt()
    y = ZZ((-b + d) / 2)
    return [y, -b - y] if d else [y]
Ejemplo n.º 23
0
 def cutout_digits(elt):
     digits = 1 if elt == 0 else floor(RR(abs(elt)).log(10)) + 1
     if digits > bigint_cutoff:
         # a large number would be replaced by ab...cd
         return digits - 7
     else:
         return 0
Ejemplo n.º 24
0
 def cnf(self):
     if self.degree()==1:
         return r'=\frac{2^1\cdot (2\pi)^0 \cdot 1\cdot 1}{2\sqrt 1}=1$'
     if not self.haskey('class_group'):
         return r'$<td>  '+na_text()
     # Otherwise we should have what we need
     [r1,r2] = self.signature()
     reg = self.regulator()
     h = self.class_number()
     w = self.root_of_1_order()
     r1term= r'2^{%s}\cdot'% r1
     r2term= r'(2\pi)^{%s}\cdot'% r2
     disc = ZZ(self._data['disc_abs'])
     approx1 = r'\approx' if self.unit_rank()>0 else r'='
     ltx = r'%s\frac{%s%s %s \cdot %s}{%s\sqrt{%s}}'%(approx1,r1term,r2term,str(reg),h,w,disc)
     ltx += r'\approx %s$'%(2**r1*(2*RR(pi))**r2*reg*h/(w*sqrt(RR(disc))))
     return ltx
Ejemplo n.º 25
0
def _circ_arc(t0, t1, c, r, num_pts=5000):
    r""" Circular arc
    INPUTS:
    - ''t0'' -- starting parameter
    - ''t1'' -- ending parameter
    - ''c''  -- center point of the circle
    - ''r''  -- radius of circle
    - ''num_pts''  -- (default 100) number of points on polygon
    OUTPUT:
    - ''ca'' -- a polygonal approximation of a circular arc centered
    at c and radius r, starting at t0 and ending at t1

    
    EXAMPLES::

        sage: ca=_circ_arc(0.1,0.2,0.0,1.0,100)
    
    """
    from sage.plot.plot import line, parametric_plot
    from sage.functions.trig import (cos, sin)
    from sage.all import var
    t00 = t0
    t11 = t1
    ## To make sure the line is correct we reduce all arguments to the same branch,
    ## e.g. [0,2pi]
    pi = RR.pi()
    while (t00 < 0.0):
        t00 = t00 + RR(2.0 * pi)
    while (t11 < 0):
        t11 = t11 + RR(2.0 * pi)
    while (t00 > 2 * pi):
        t00 = t00 - RR(2.0 * pi)
    while (t11 > 2 * pi):
        t11 = t11 - RR(2.0 * pi)

    xc = CC(c).real()
    yc = CC(c).imag()
    num_pts = 3
    t = var('t')
    if t11 > t00:
        ca = parametric_plot((r * cos(t) + xc, r * sin(t) + yc), (t, t00, t11))
    else:
        ca = parametric_plot((r * cos(t) + xc, r * sin(t) + yc), (t, t11, t00))
    #L0 = [[RR(r*cos(t00+i*(t11-t00)/num_pts))+xc,RR(r*sin(t00+i*(t11-t00)/num_pts))+yc] for i in range(0 ,num_pts)]
    #ca=line(L0)
    return ca
Ejemplo n.º 26
0
def cli_handler(args):  # pylint: disable=redefined-outer-name

    f = R(args.f)

    K = NumberField(f, name="a")

    loglevel = logging.DEBUG if args.verbose else logging.INFO
    logging.basicConfig(
        format="%(asctime)s %(levelname)s: %(message)s",
        datefmt="%H:%M:%S",
        level=loglevel,
    )
    logging.debug("Debugging level for log messages set.")

    if args.dlmv:
        dlmv_bound = DLMV(K)
        logging.info(
            "DLMV bound for {} is:\n\n{}\n\nwhich is approximately {}".format(
                K, dlmv_bound, RR(dlmv_bound)))
    else:
        logging.warning(
            "Only checking Type 2 primes up to %s. "
            "To check all, use the PARI/GP script.",
            args.bound,
        )

        if args.norm_bound:
            norm_bound = args.norm_bound
            auto_stop_strategy = False
        else:
            norm_bound = 50  # still needed for Type 1
            auto_stop_strategy = True

        superset, type_3_fields = get_isogeny_primes(
            K,
            args.bound,
            args.ice,
            args.appendix_bound,
            norm_bound=norm_bound,
            auto_stop_strategy=auto_stop_strategy,
        )

        superset_list = list(superset)
        superset_list.sort()
        logging.info(f"superset = {superset_list}")

        possible_new_isog_primes = superset - EC_Q_ISOGENY_PRIMES
        possible_new_isog_primes_list = list(possible_new_isog_primes)
        possible_new_isog_primes_list.sort()
        logging.info(
            f"Possible new isogeny primes = {possible_new_isog_primes_list}")
        if type_3_fields:
            how_many_fields = len(type_3_fields)
            logging.info(
                f"Outside of the above set, any isogeny primes must be "
                f"of Momose Type 3 with imaginary quadratic field L, for L one "
                f"of the following {how_many_fields} field(s):\n {type_3_fields}"
            )
Ejemplo n.º 27
0
 def Cn_symmetric_k_points(n,k, alpha=Integer(1) ):   
     n = Integer(n)
     k = Integer(k) 
     if not mod(k,n) in [Integer(0) ,Integer(1) ]:
         raise ValueError('Only possible if k mod n in {{0,1}}, here {} mod {} = {}.'.format(k,n,mod(k,n)))
     res = {
             i : vector([RR(cos(RR(Integer(2) *pi*i)/n)),RR(sin(RR(Integer(2) *pi*i)/n))]) for i in range(Integer(0) ,n)
         }
     N = k
     if mod(k,n)==Integer(1) :
         res[N-Integer(1) ] = vector([Integer(0) ,Integer(0) ])
         N = N-Integer(1) 
     for i in range(n,N):
         r = (i-i%n)/n +Integer(1) 
         res[i] = r*res[i%n]
     for i in res:
         res[i] = alpha*vector([res[i][Integer(0) ], res[i][Integer(1) ]])
     return [res[i] for i in sorted(res.keys())]
Ejemplo n.º 28
0
def compare_formulas_2a(D, k):
    d1 = dimension_new_cusp_forms(kronecker_character(D), k)
    if D < 0:
        D = -D
    d2 = RR(1 / pi * sqrt(D) * sum([
        log(d) * sigma(old_div(D, d), 0) for d in divisors(D) if Zmod(d)
        (old_div(D, d)).is_square() and is_fundamental_discriminant(-d)
    ]))
    return d1 - d2
Ejemplo n.º 29
0
def findrotationmulticiphertexts(lwe_n, q, sd, B, m, name):
    n = 2 * RR(lwe_n)
    q = RR(q)
    B = RR(B)
    vars = RR(sd**2)
    varc = vars

    #####################
    #  precalculations  #
    #####################

    # qt
    qt = q / 2**(B + 1)

    # |s| and |c*|
    norms = ZZ(ceil(sqrt(n *
                         vars)))  # This is an approximation of the mean value
    normc = norms

    ##################
    #  calculations  #
    ##################
    numsucces = 0
    for CIPHERTEXTS in [3, 4, 5]:
        results = []

        import pathos
        pool = pathos.pools._ProcessPool(4, maxtasksperchild=1)
        results = pool.map(
            lambda x: findonemulticiphertextrotation(n, varc, CIPHERTEXTS, qt,
                                                     norms), range(0, TESTS))
        pool.terminate()
        pool.join()

        numsucces = np.sum(results)

        print(
            'experimental probability of combining %d ciphertexts in %d rounds, succesprob %f'
            % (CIPHERTEXTS, REP, numsucces / TESTS))
        with open(name + '/findingfailurelocation.txt', 'a') as f:
            print(
                'experimental probability of combining %d ciphertexts in %d rounds, succesprob %f'
                % (CIPHERTEXTS, REP, numsucces / TESTS),
                file=f)
Ejemplo n.º 30
0
    def ghf(cls, m, p, klen_list, prec=53):
        """
        Estimate norm of shortest vector according to Gaussian Heuristic.

        :param m: number of samples
        :param p: ECDSA modulus
        :param klen_list: list of lengths of key to recover
        :param prec: precision to use

        """
        # NOTE: The Gaussian Heuristic does not hold in small dimensions
        w = 2 ** (max(klen_list) - 1)
        RR = RealField(prec)
        w = RR(w)
        f_list = [Integer(w / (2 ** (klen - 1))) for klen in klen_list]
        d = m + 1
        log_vol = log(p) * (m - 1) + sum(map(log, f_list)) + log(w)
        lgh = log_gamma(1 + d / 2.0) * (1.0 / d) - log(sqrt(pi)) + log_vol * (1.0 / d)
        return RR(exp(lgh))