Statistiques
| Révision :

root / pobysoPythonSage / src / sageSLZ / sageSLZ.sage @ 165

Historique | Voir | Annoter | Télécharger (51,65 ko)

1
r"""
2
Sage core functions needed for the implementation of SLZ.
3

    
4
AUTHORS:
5
- S.T. (2013-08): initial version
6

    
7
Examples:
8

    
9
TODO::
10
"""
11
print "sageSLZ loading..."
12
#
13
def slz_check_htr_value(function, htrValue, lowerBound, upperBound, precision, \
14
                        degree, targetHardnessToRound, alpha):
15
    """
16
    Check an Hard-to-round value.
17
    TODO::
18
    Full rewriting: this is hardly a draft.
19
    """
20
    polyApproxPrec = targetHardnessToRound + 1
21
    polyTargetHardnessToRound = targetHardnessToRound + 1
22
    internalSollyaPrec = ceil((RR('1.5') * targetHardnessToRound) / 64) * 64
23
    RRR = htrValue.parent()
24
    #
25
    ## Compute the scaled function.
26
    fff = slz_compute_scaled_function(f, lowerBound, upperBound, precision)[0]
27
    print "Scaled function:", fff
28
    #
29
    ## Compute the scaling.
30
    boundsIntervalRifSa = RealIntervalField(precision)
31
    domainBoundsInterval = boundsIntervalRifSa(lowerBound, upperBound)
32
    scalingExpressions = \
33
        slz_interval_scaling_expression(domainBoundsInterval, i)
34
    #
35
    ## Get the polynomials, bounds, etc. for all the interval.
36
    resultListOfTuplesOfSo = \
37
        slz_get_intervals_and_polynomials(f, degree, lowerBound, upperBound, \
38
                                          precision, internalSollyaPrec,\
39
                                          2^-(polyApproxPrec))
40
    #
41
    ## We only want one interval.
42
    if len(resultListOfTuplesOfSo) > 1:
43
        print "Too many intervals! Aborting!"
44
        exit
45
    #
46
    ## Get the first tuple of Sollya objects as Sage objects. 
47
    firstTupleSa = \
48
        slz_interval_and_polynomial_to_sage(resultListOfTuplesOfSo[0])
49
    pobyso_set_canonical_on()
50
    #
51
    print "Floatting point polynomial:", firstTupleSa[0]
52
    print "with coefficients precision:", firstTupleSa[0].base_ring().prec()
53
    #
54
    ## From a polynomial over a real ring, create a polynomial over the 
55
    #  rationals ring.
56
    rationalPolynomial = \
57
        slz_float_poly_of_float_to_rat_poly_of_rat(firstTupleSa[0])
58
    print "Rational polynomial:", rationalPolynomial
59
    #
60
    ## Create a polynomial over the rationals that will take integer 
61
    # variables instead of rational. 
62
    rationalPolynomialOfIntegers = \
63
        slz_rat_poly_of_rat_to_rat_poly_of_int(rationalPolynomial, precision)
64
    print "Type:", type(rationalPolynomialOfIntegers)
65
    print "Rational polynomial of integers:", rationalPolynomialOfIntegers
66
    #
67
    ## Check the rational polynomial of integers variables.
68
    # (check against the scaled function).
69
    toIntegerFactor = 2^(precision-1)
70
    intervalCenterAsIntegerSa = int(firstTupleSa[3] * toIntegerFactor)
71
    print "Interval center as integer:", intervalCenterAsIntegerSa
72
    lowerBoundAsIntegerSa = int(firstTupleSa[2].endpoints()[0] * \
73
                                toIntegerFactor) - intervalCenterAsIntegerSa
74
    upperBoundAsIntegerSa = int(firstTupleSa[2].endpoints()[1] * \
75
                                toIntegerFactor) - intervalCenterAsIntegerSa
76
    print "Lower bound as integer:", lowerBoundAsIntegerSa
77
    print "Upper bound as integer:", upperBoundAsIntegerSa
78
    print "Image of the lower bound by the scaled function", \
79
            fff(firstTupleSa[2].endpoints()[0])
80
    print "Image of the lower bound by the approximation polynomial of ints:", \
81
            RRR(rationalPolynomialOfIntegers(lowerBoundAsIntegerSa))
82
    print "Image of the center by the scaled function", fff(firstTupleSa[3])
83
    print "Image of the center by the approximation polynomial of ints:", \
84
            RRR(rationalPolynomialOfIntegers(0))
85
    print "Image of the upper bound by the scaled function", \
86
            fff(firstTupleSa[2].endpoints()[1])
87
    print "Image of the upper bound by the approximation polynomial of ints:", \
88
            RRR(rationalPolynomialOfIntegers(upperBoundAsIntegerSa))
89

    
90
# End slz_check_htr_value.
91

    
92
def slz_compute_binade(number):
93
    """"
94
    For a given number, compute the "binade" that is integer m such that
95
    2^m <= number < 2^(m+1). If number == 0 return None.
96
    """
97
    # Checking the parameter.
98
    # The exception construction is used to detect if numbre is a RealNumber
99
    # since not all numbers have
100
    # the mro() method. sage.rings.real_mpfr.RealNumber do.
101
    try:
102
        classTree = [number.__class__] + number.mro()
103
        # If the number is not a RealNumber (of offspring thereof) try
104
        # to transform it.
105
        if not sage.rings.real_mpfr.RealNumber in classTree:
106
            numberAsRR = RR(number)
107
        else:
108
            numberAsRR = number
109
    except AttributeError:
110
        return None
111
    # Zero special case.
112
    if numberAsRR == 0:
113
        return RR(-infinity)
114
    else:
115
        return floor(numberAsRR.abs().log2())
116
# End slz_compute_binade
117

    
118
#
119
def slz_compute_binade_bounds(number, emin, emax=sys.maxint):
120
    """
121
    For given "real number", compute the bounds of the binade it belongs to.
122
    
123
    NOTE::
124
        When number >= 2^(emax+1), we return the "fake" binade 
125
        [2^(emax+1), +infinity]. Ditto for number <= -2^(emax+1)
126
        with interval [-infinity, -2^(emax+1)]. We want to distinguish
127
        this case from that of "really" invalid arguments.
128
        
129
    """
130
    # Check the parameters.
131
    # RealNumbers or RealNumber offspring only.
132
    # The exception construction is necessary since not all objects have
133
    # the mro() method. sage.rings.real_mpfr.RealNumber do.
134
    try:
135
        classTree = [number.__class__] + number.mro()
136
        if not sage.rings.real_mpfr.RealNumber in classTree:
137
            return None
138
    except AttributeError:
139
        return None
140
    # Non zero negative integers only for emin.
141
    if emin >= 0 or int(emin) != emin:
142
        return None
143
    # Non zero positive integers only for emax.
144
    if emax <= 0 or int(emax) != emax:
145
        return None
146
    precision = number.precision()
147
    RF  = RealField(precision)
148
    if number == 0:
149
        return (RF(0),RF(2^(emin)) - RF(2^(emin-precision)))
150
    # A more precise RealField is needed to avoid unwanted rounding effects
151
    # when computing number.log2().
152
    RRF = RealField(max(2048, 2 * precision))
153
    # number = 0 special case, the binade bounds are 
154
    # [0, 2^emin - 2^(emin-precision)]
155
    # Begin general case
156
    l2 = RRF(number).abs().log2()
157
    # Another special one: beyond largest representable -> "Fake" binade.
158
    if l2 >= emax + 1:
159
        if number > 0:
160
            return (RF(2^(emax+1)), RF(+infinity) )
161
        else:
162
            return (RF(-infinity), -RF(2^(emax+1)))
163
    # Regular case cont'd.
164
    offset = int(l2)
165
    # number.abs() >= 1.
166
    if l2 >= 0:
167
        if number >= 0:
168
            lb = RF(2^offset)
169
            ub = RF(2^(offset + 1) - 2^(-precision+offset+1))
170
        else: #number < 0
171
            lb = -RF(2^(offset + 1) - 2^(-precision+offset+1))
172
            ub = -RF(2^offset)
173
    else: # log2 < 0, number.abs() < 1.
174
        if l2 < emin: # Denormal
175
           # print "Denormal:", l2
176
            if number >= 0:
177
                lb = RF(0)
178
                ub = RF(2^(emin)) - RF(2^(emin-precision))
179
            else: # number <= 0
180
                lb = - RF(2^(emin)) + RF(2^(emin-precision))
181
                ub = RF(0)
182
        elif l2 > emin: # Normal number other than +/-2^emin.
183
            if number >= 0:
184
                if int(l2) == l2:
185
                    lb = RF(2^(offset))
186
                    ub = RF(2^(offset+1)) - RF(2^(-precision+offset+1))
187
                else:
188
                    lb = RF(2^(offset-1))
189
                    ub = RF(2^(offset)) - RF(2^(-precision+offset))
190
            else: # number < 0
191
                if int(l2) == l2: # Binade limit.
192
                    lb = -RF(2^(offset+1) - 2^(-precision+offset+1))
193
                    ub = -RF(2^(offset))
194
                else:
195
                    lb = -RF(2^(offset) - 2^(-precision+offset))
196
                    ub = -RF(2^(offset-1))
197
        else: # l2== emin, number == +/-2^emin
198
            if number >= 0:
199
                lb = RF(2^(offset))
200
                ub = RF(2^(offset+1)) - RF(2^(-precision+offset+1))
201
            else: # number < 0
202
                lb = -RF(2^(offset+1) - 2^(-precision+offset+1))
203
                ub = -RF(2^(offset))
204
    return (lb, ub)
205
# End slz_compute_binade_bounds
206
#
207
def slz_compute_coppersmith_reduced_polynomials(inputPolynomial,
208
                                                 alpha,
209
                                                 N,
210
                                                 iBound,
211
                                                 tBound):
212
    """
213
    For a given set of arguments (see below), compute a list
214
    of "reduced polynomials" that could be used to compute roots
215
    of the inputPolynomial.
216
    INPUT:
217
    
218
    - "inputPolynomial" -- (no default) a bivariate integer polynomial;
219
    - "alpha" -- the alpha parameter of the Coppersmith algorithm;
220
    - "N" -- the modulus;
221
    - "iBound" -- the bound on the first variable;
222
    - "tBound" -- the bound on the second variable.
223
    
224
    OUTPUT:
225
    
226
    A list of bivariate integer polynomial obtained using the Coppersmith
227
    algorithm. The polynomials correspond to the rows of the LLL-reduce
228
    reduced base that comply with the Coppersmith condition.
229
    """
230
    # Arguments check.
231
    if iBound == 0 or tBound == 0:
232
        return ()
233
    # End arguments check.
234
    nAtAlpha = N^alpha
235
    ## Building polynomials for matrix.
236
    polyRing   = inputPolynomial.parent()
237
    # Whatever the 2 variables are actually called, we call them
238
    # 'i' and 't' in all the variable names.
239
    (iVariable, tVariable) = inputPolynomial.variables()[:2]
240
    #print polyVars[0], type(polyVars[0])
241
    initialPolynomial = inputPolynomial.subs({iVariable:iVariable * iBound,
242
                                              tVariable:tVariable * tBound})
243
    polynomialsList = \
244
        spo_polynomial_to_polynomials_list_5(initialPolynomial,
245
                                             alpha,
246
                                             N,
247
                                             iBound,
248
                                             tBound,
249
                                             0)
250
    #print "Polynomials list:", polynomialsList
251
    ## Building the proto matrix.
252
    knownMonomials = []
253
    protoMatrix    = []
254
    for poly in polynomialsList:
255
        spo_add_polynomial_coeffs_to_matrix_row(poly,
256
                                                knownMonomials,
257
                                                protoMatrix,
258
                                                0)
259
    matrixToReduce = spo_proto_to_row_matrix(protoMatrix)
260
    #print matrixToReduce
261
    ## Reduction and checking.
262
    ## S.T. changed 'fp' to None as of Sage 6.6 complying to
263
    #  error message issued when previous code was used.
264
    #reducedMatrix = matrixToReduce.LLL(fp='fp')
265
    reducedMatrix = matrixToReduce.LLL(fp=None)
266
    isLLLReduced  = reducedMatrix.is_LLL_reduced()
267
    if not isLLLReduced:
268
        return ()
269
    monomialsCount     = len(knownMonomials)
270
    monomialsCountSqrt = sqrt(monomialsCount)
271
    #print "Monomials count:", monomialsCount, monomialsCountSqrt.n()
272
    #print reducedMatrix
273
    ## Check the Coppersmith condition for each row and build the reduced 
274
    #  polynomials.
275
    ccReducedPolynomialsList = []
276
    for row in reducedMatrix.rows():
277
        l2Norm = row.norm(2)
278
        if (l2Norm * monomialsCountSqrt) < nAtAlpha:
279
            #print (l2Norm * monomialsCountSqrt).n()
280
            #print l2Norm.n()
281
            ccReducedPolynomial = \
282
                slz_compute_reduced_polynomial(row,
283
                                               knownMonomials,
284
                                               iVariable,
285
                                               iBound,
286
                                               tVariable,
287
                                               tBound)
288
            if not ccReducedPolynomial is None:
289
                ccReducedPolynomialsList.append(ccReducedPolynomial)
290
        else:
291
            #print l2Norm.n() , ">", nAtAlpha
292
            pass
293
    if len(ccReducedPolynomialsList) < 2:
294
        print "Less than 2 Coppersmith condition compliant vectors."
295
        return ()
296
    
297
    #print ccReducedPolynomialsList
298
    return ccReducedPolynomialsList
299
# End slz_compute_coppersmith_reduced_polynomials
300

    
301
def slz_compute_integer_polynomial_modular_roots(inputPolynomial,
302
                                                 alpha,
303
                                                 N,
304
                                                 iBound,
305
                                                 tBound):
306
    """
307
    For a given set of arguments (see below), compute the polynomial modular 
308
    roots, if any.
309
    
310
    """
311
    # Arguments check.
312
    if iBound == 0 or tBound == 0:
313
        return set()
314
    # End arguments check.
315
    nAtAlpha = N^alpha
316
    ## Building polynomials for matrix.
317
    polyRing   = inputPolynomial.parent()
318
    # Whatever the 2 variables are actually called, we call them
319
    # 'i' and 't' in all the variable names.
320
    (iVariable, tVariable) = inputPolynomial.variables()[:2]
321
    ccReducedPolynomialsList = \
322
        slz_compute_coppersmith_reduced_polynomials (inputPolynomial,
323
                                                     alpha,
324
                                                     N,
325
                                                     iBound,
326
                                                     tBound)
327
    if len(ccReducedPolynomialsList) == 0:
328
        return set()   
329
    ## Create the valid (poly1 and poly2 are algebraically independent) 
330
    # resultant tuples (poly1, poly2, resultant(poly1, poly2)).
331
    # Try to mix and match all the polynomial pairs built from the 
332
    # ccReducedPolynomialsList to obtain non zero resultants.
333
    resultantsInITuplesList = []
334
    for polyOuterIndex in xrange(0, len(ccReducedPolynomialsList)-1):
335
        for polyInnerIndex in xrange(polyOuterIndex+1, 
336
                                     len(ccReducedPolynomialsList)):
337
            # Compute the resultant in resultants in the
338
            # first variable (is it the optimal choice?).
339
            resultantInI = \
340
               ccReducedPolynomialsList[polyOuterIndex].resultant(ccReducedPolynomialsList[polyInnerIndex],
341
                                                                  ccReducedPolynomialsList[0].parent(str(iVariable)))
342
            #print "Resultant", resultantInI
343
            # Test algebraic independence.
344
            if not resultantInI.is_zero():
345
                resultantsInITuplesList.append((ccReducedPolynomialsList[polyOuterIndex],
346
                                                 ccReducedPolynomialsList[polyInnerIndex],
347
                                                 resultantInI))
348
    # If no non zero resultant was found: we can't get no algebraically 
349
    # independent polynomials pair. Give up!
350
    if len(resultantsInITuplesList) == 0:
351
        return set()
352
    #print resultantsInITuplesList
353
    # Compute the roots.
354
    Zi = ZZ[str(iVariable)]
355
    Zt = ZZ[str(tVariable)]
356
    polynomialRootsSet = set()
357
    # First, solve in the second variable since resultants are in the first
358
    # variable.
359
    for resultantInITuple in resultantsInITuplesList:
360
        tRootsList = Zt(resultantInITuple[2]).roots()
361
        # For each tRoot, compute the corresponding iRoots and check 
362
        # them in the input polynomial.
363
        for tRoot in tRootsList:
364
            #print "tRoot:", tRoot
365
            # Roots returned by root() are (value, multiplicity) tuples.
366
            iRootsList = \
367
                Zi(resultantInITuple[0].subs({resultantInITuple[0].variables()[1]:tRoot[0]})).roots()
368
            print iRootsList
369
            # The iRootsList can be empty, hence the test.
370
            if len(iRootsList) != 0:
371
                for iRoot in iRootsList:
372
                    polyEvalModN = inputPolynomial(iRoot[0], tRoot[0]) / N
373
                    # polyEvalModN must be an integer.
374
                    if polyEvalModN == int(polyEvalModN):
375
                        polynomialRootsSet.add((iRoot[0],tRoot[0]))
376
    return polynomialRootsSet
377
# End slz_compute_integer_polynomial_modular_roots.
378
#
379
def slz_compute_integer_polynomial_modular_roots_2(inputPolynomial,
380
                                                 alpha,
381
                                                 N,
382
                                                 iBound,
383
                                                 tBound):
384
    """
385
    For a given set of arguments (see below), compute the polynomial modular 
386
    roots, if any.
387
    This version differs in the way resultants are computed.   
388
    """
389
    # Arguments check.
390
    if iBound == 0 or tBound == 0:
391
        return set()
392
    # End arguments check.
393
    nAtAlpha = N^alpha
394
    ## Building polynomials for matrix.
395
    polyRing   = inputPolynomial.parent()
396
    # Whatever the 2 variables are actually called, we call them
397
    # 'i' and 't' in all the variable names.
398
    (iVariable, tVariable) = inputPolynomial.variables()[:2]
399
    #print polyVars[0], type(polyVars[0])
400
    ccReducedPolynomialsList = \
401
        slz_compute_coppersmith_reduced_polynomials (inputPolynomial,
402
                                                     alpha,
403
                                                     N,
404
                                                     iBound,
405
                                                     tBound)
406
    if len(ccReducedPolynomialsList) == 0:
407
        return set()   
408
    ## Create the valid (poly1 and poly2 are algebraically independent) 
409
    # resultant tuples (poly1, poly2, resultant(poly1, poly2)).
410
    # Try to mix and match all the polynomial pairs built from the 
411
    # ccReducedPolynomialsList to obtain non zero resultants.
412
    resultantsInTTuplesList = []
413
    for polyOuterIndex in xrange(0, len(ccReducedPolynomialsList)-1):
414
        for polyInnerIndex in xrange(polyOuterIndex+1, 
415
                                     len(ccReducedPolynomialsList)):
416
            # Compute the resultant in resultants in the
417
            # first variable (is it the optimal choice?).
418
            resultantInT = \
419
               ccReducedPolynomialsList[polyOuterIndex].resultant(ccReducedPolynomialsList[polyInnerIndex],
420
                                                                  ccReducedPolynomialsList[0].parent(str(tVariable)))
421
            #print "Resultant", resultantInT
422
            # Test algebraic independence.
423
            if not resultantInT.is_zero():
424
                resultantsInTTuplesList.append((ccReducedPolynomialsList[polyOuterIndex],
425
                                                 ccReducedPolynomialsList[polyInnerIndex],
426
                                                 resultantInT))
427
    # If no non zero resultant was found: we can't get no algebraically 
428
    # independent polynomials pair. Give up!
429
    if len(resultantsInTTuplesList) == 0:
430
        return set()
431
    #print resultantsInITuplesList
432
    # Compute the roots.
433
    Zi = ZZ[str(iVariable)]
434
    Zt = ZZ[str(tVariable)]
435
    polynomialRootsSet = set()
436
    # First, solve in the second variable since resultants are in the first
437
    # variable.
438
    for resultantInTTuple in resultantsInTTuplesList:
439
        iRootsList = Zi(resultantInTTuple[2]).roots()
440
        # For each iRoot, compute the corresponding tRoots and check 
441
        # them in the input polynomial.
442
        for iRoot in iRootsList:
443
            #print "iRoot:", iRoot
444
            # Roots returned by root() are (value, multiplicity) tuples.
445
            tRootsList = \
446
                Zt(resultantInTTuple[0].subs({resultantInTTuple[0].variables()[0]:iRoot[0]})).roots()
447
            print tRootsList
448
            # The tRootsList can be empty, hence the test.
449
            if len(tRootsList) != 0:
450
                for tRoot in tRootsList:
451
                    polyEvalModN = inputPolynomial(iRoot[0],tRoot[0]) / N
452
                    # polyEvalModN must be an integer.
453
                    if polyEvalModN == int(polyEvalModN):
454
                        polynomialRootsSet.add((iRoot[0],tRoot[0]))
455
    return polynomialRootsSet
456
# End slz_compute_integer_polynomial_modular_roots_2.
457
#
458
def slz_compute_polynomial_and_interval(functionSo, degreeSo, lowerBoundSa, 
459
                                        upperBoundSa, approxPrecSa, 
460
                                        sollyaPrecSa=None):
461
    """
462
    Under the assumptions listed for slz_get_intervals_and_polynomials, compute
463
    a polynomial that approximates the function on a an interval starting
464
    at lowerBoundSa and finishing at a value that guarantees that the polynomial
465
    approximates with the expected precision.
466
    The interval upper bound is lowered until the expected approximation 
467
    precision is reached.
468
    The polynomial, the bounds, the center of the interval and the error
469
    are returned.
470
    OUTPUT:
471
    A tuple made of 4 Sollya objects:
472
    - a polynomial;
473
    - an range (an interval, not in the sense of number given as an interval);
474
    - the center of the interval;
475
    - the maximum error in the approximation of the input functionSo by the
476
      output polynomial ; this error <= approxPrecSaS.
477
    
478
    """
479
    RRR = lowerBoundSa.parent()
480
    intervalShrinkConstFactorSa = RRR('0.5')
481
    absoluteErrorTypeSo = pobyso_absolute_so_so()
482
    currentRangeSo = pobyso_bounds_to_range_sa_so(lowerBoundSa, upperBoundSa)
483
    currentUpperBoundSa = upperBoundSa
484
    currentLowerBoundSa = lowerBoundSa
485
    # What we want here is the polynomial without the variable change, 
486
    # since our actual variable will be x-intervalCenter defined over the 
487
    # domain [lowerBound-intervalCenter , upperBound-intervalCenter]. 
488
    (polySo, intervalCenterSo, maxErrorSo) = \
489
        pobyso_taylor_expansion_no_change_var_so_so(functionSo, degreeSo, 
490
                                                    currentRangeSo, 
491
                                                    absoluteErrorTypeSo)
492
    maxErrorSa = pobyso_get_constant_as_rn_with_rf_so_sa(maxErrorSo)
493
    while maxErrorSa > approxPrecSa:
494
        #print "++Approximation error:", maxErrorSa
495
        sollya_lib_clear_obj(polySo)
496
        sollya_lib_clear_obj(intervalCenterSo)
497
        sollya_lib_clear_obj(maxErrorSo)
498
        shrinkFactorSa = RRR('5')/(maxErrorSa/approxPrecSa).log2().abs()
499
        #shrinkFactorSa = 1.5/(maxErrorSa/approxPrecSa)
500
        #errorRatioSa = approxPrecSa/maxErrorSa
501
        #print "Error ratio: ", errorRatioSa
502
        if shrinkFactorSa > intervalShrinkConstFactorSa:
503
            actualShrinkFactorSa = intervalShrinkConstFactorSa
504
            #print "Fixed"
505
        else:
506
            actualShrinkFactorSa = shrinkFactorSa
507
            #print "Computed",shrinkFactorSa,maxErrorSa
508
            #print shrinkFactorSa, maxErrorSa
509
        #print "Shrink factor", actualShrinkFactorSa
510
        currentUpperBoundSa = currentLowerBoundSa + \
511
                                  (currentUpperBoundSa - currentLowerBoundSa) * \
512
                                   actualShrinkFactorSa
513
        #print "Current upper bound:", currentUpperBoundSa
514
        sollya_lib_clear_obj(currentRangeSo)
515
        if currentUpperBoundSa <= currentLowerBoundSa or \
516
              currentUpperBoundSa == currentLowerBoundSa.nextabove():
517
            sollya_lib_clear_obj(absoluteErrorTypeSo)
518
            print "Can't find an interval."
519
            print "Use either or both a higher polynomial degree or a higher",
520
            print "internal precision."
521
            print "Aborting!"
522
            return (None, None, None, None)
523
        currentRangeSo = pobyso_bounds_to_range_sa_so(currentLowerBoundSa, 
524
                                                      currentUpperBoundSa)
525
        # print "New interval:",
526
        # pobyso_autoprint(currentRangeSo)
527
        #print "Second Taylor expansion call."
528
        (polySo, intervalCenterSo, maxErrorSo) = \
529
            pobyso_taylor_expansion_no_change_var_so_so(functionSo, degreeSo, 
530
                                                        currentRangeSo, 
531
                                                        absoluteErrorTypeSo)
532
        #maxErrorSa = pobyso_get_constant_as_rn_with_rf_so_sa(maxErrorSo, RRR)
533
        #print "Max errorSo:",
534
        #pobyso_autoprint(maxErrorSo)
535
        maxErrorSa = pobyso_get_constant_as_rn_with_rf_so_sa(maxErrorSo)
536
        #print "Max errorSa:", maxErrorSa
537
        #print "Sollya prec:",
538
        #pobyso_autoprint(sollya_lib_get_prec(None))
539
    sollya_lib_clear_obj(absoluteErrorTypeSo)
540
    return((polySo, currentRangeSo, intervalCenterSo, maxErrorSo))
541
# End slz_compute_polynomial_and_interval
542

    
543
def slz_compute_reduced_polynomial(matrixRow,
544
                                    knownMonomials,
545
                                    var1,
546
                                    var1Bound,
547
                                    var2,
548
                                    var2Bound):
549
    """
550
    Compute a polynomial from a single reduced matrix row.
551
    This function was introduced in order to avoid the computation of the
552
    all the polynomials  from the full matrix (even those built from rows 
553
    that do no verify the Coppersmith condition) as this may involves 
554
    expensive operations over (large) integers.
555
    """
556
    ## Check arguments.
557
    if len(knownMonomials) == 0:
558
        return None
559
    # varNounds can be zero since 0^0 returns 1.
560
    if (var1Bound < 0) or (var2Bound < 0):
561
        return None
562
    ## Initialisations. 
563
    polynomialRing = knownMonomials[0].parent() 
564
    currentPolynomial = polynomialRing(0)
565
    # TODO: use zip instead of indices.
566
    for colIndex in xrange(0, len(knownMonomials)):
567
        currentCoefficient = matrixRow[colIndex]
568
        if currentCoefficient != 0:
569
            #print "Current coefficient:", currentCoefficient
570
            currentMonomial = knownMonomials[colIndex]
571
            #print "Monomial as multivariate polynomial:", \
572
            #currentMonomial, type(currentMonomial)
573
            degreeInVar1 = currentMonomial.degree(var1)
574
            #print "Degree in var1", var1, ":", degreeInVar1
575
            degreeInVar2 = currentMonomial.degree(var2)
576
            #print "Degree in var2", var2, ":", degreeInVar2
577
            if degreeInVar1 > 0:
578
                currentCoefficient = \
579
                    currentCoefficient / (var1Bound^degreeInVar1)
580
                #print "varBound1 in degree:", var1Bound^degreeInVar1
581
                #print "Current coefficient(1)", currentCoefficient
582
            if degreeInVar2 > 0:
583
                currentCoefficient = \
584
                    currentCoefficient / (var2Bound^degreeInVar2)
585
                #print "Current coefficient(2)", currentCoefficient
586
            #print "Current reduced monomial:", (currentCoefficient * \
587
            #                                    currentMonomial)
588
            currentPolynomial += (currentCoefficient * currentMonomial)
589
            #print "Current polynomial:", currentPolynomial
590
        # End if
591
    # End for colIndex.
592
    #print "Type of the current polynomial:", type(currentPolynomial)
593
    return(currentPolynomial)
594
# End slz_compute_reduced_polynomial
595
#
596
def slz_compute_reduced_polynomials(reducedMatrix,
597
                                        knownMonomials,
598
                                        var1,
599
                                        var1Bound,
600
                                        var2,
601
                                        var2Bound):
602
    """
603
    Legacy function, use slz_compute_reduced_polynomials_list
604
    """
605
    return(slz_compute_reduced_polynomials_list(reducedMatrix,
606
                                                knownMonomials,
607
                                                var1,
608
                                                var1Bound,
609
                                                var2,
610
                                                var2Bound)
611
    )
612
def slz_compute_reduced_polynomials_list(reducedMatrix,
613
                                         knownMonomials,
614
                                         var1,
615
                                         var1Bound,
616
                                         var2,
617
                                         var2Bound):
618
    """
619
    From a reduced matrix, holding the coefficients, from a monomials list,
620
    from the bounds of each variable, compute the corresponding polynomials
621
    scaled back by dividing by the "right" powers of the variables bounds.
622
    
623
    The elements in knownMonomials must be of the "right" polynomial type.
624
    They set the polynomial type of the output polynomials list.
625
    @param reducedMatrix:  the reduced matrix as output from LLL;
626
    @param kwnonMonomials: the ordered list of the monomials used to
627
                           build the polynomials;
628
    @param var1:           the first variable (of the "right" type);
629
    @param var1Bound:      the first variable bound;
630
    @param var2:           the second variable (of the "right" type);
631
    @param var2Bound:      the second variable bound.
632
    @return: a list of polynomials obtained with the reduced coefficients
633
             and scaled down with the bounds
634
    """
635
    
636
    # TODO: check input arguments.
637
    reducedPolynomials = []
638
    #print "type var1:", type(var1), " - type var2:", type(var2)
639
    for matrixRow in reducedMatrix.rows():
640
        currentPolynomial = 0
641
        for colIndex in xrange(0, len(knownMonomials)):
642
            currentCoefficient = matrixRow[colIndex]
643
            if currentCoefficient != 0:
644
                #print "Current coefficient:", currentCoefficient
645
                currentMonomial = knownMonomials[colIndex]
646
                parentRing = currentMonomial.parent()
647
                #print "Monomial as multivariate polynomial:", \
648
                #currentMonomial, type(currentMonomial)
649
                degreeInVar1 = currentMonomial.degree(parentRing(var1))
650
                #print "Degree in var", var1, ":", degreeInVar1
651
                degreeInVar2 = currentMonomial.degree(parentRing(var2))
652
                #print "Degree in var", var2, ":", degreeInVar2
653
                if degreeInVar1 > 0:
654
                    currentCoefficient = \
655
                        currentCoefficient / var1Bound^degreeInVar1
656
                    #print "varBound1 in degree:", var1Bound^degreeInVar1
657
                    #print "Current coefficient(1)", currentCoefficient
658
                if degreeInVar2 > 0:
659
                    currentCoefficient = \
660
                        currentCoefficient / var2Bound^degreeInVar2
661
                    #print "Current coefficient(2)", currentCoefficient
662
                #print "Current reduced monomial:", (currentCoefficient * \
663
                #                                    currentMonomial)
664
                currentPolynomial += (currentCoefficient * currentMonomial)
665
                #print "Current polynomial:", currentPolynomial
666
            # End if
667
        # End for colIndex.
668
        #print "Type of the current polynomial:", type(currentPolynomial)
669
        reducedPolynomials.append(currentPolynomial)
670
    return reducedPolynomials 
671
# End slz_compute_reduced_polynomials.
672

    
673
def slz_compute_scaled_function(functionSa,
674
                                lowerBoundSa,
675
                                upperBoundSa,
676
                                floatingPointPrecSa,
677
                                debug=False):
678
    """
679
    From a function, compute the scaled function whose domain
680
    is included in [1, 2) and whose image is also included in [1,2).
681
    Return a tuple: 
682
    [0]: the scaled function
683
    [1]: the scaled domain lower bound
684
    [2]: the scaled domain upper bound
685
    [3]: the scaled image lower bound
686
    [4]: the scaled image upper bound
687
    """
688
    x = functionSa.variables()[0]
689
    # Reassert f as a function (an not a mere expression).
690
    
691
    # Scalling the domain -> [1,2[.
692
    boundsIntervalRifSa = RealIntervalField(floatingPointPrecSa)
693
    domainBoundsIntervalSa = boundsIntervalRifSa(lowerBoundSa, upperBoundSa)
694
    (domainScalingExpressionSa, invDomainScalingExpressionSa) = \
695
        slz_interval_scaling_expression(domainBoundsIntervalSa, x)
696
    if debug:
697
        print "domainScalingExpression for argument :", \
698
        invDomainScalingExpressionSa
699
        print "f: ", f
700
    ff = f.subs({x : domainScalingExpressionSa})
701
    #ff = f.subs_expr(x==domainScalingExpressionSa)
702
    domainScalingFunction(x) = invDomainScalingExpressionSa
703
    scaledLowerBoundSa = \
704
        domainScalingFunction(lowerBoundSa).n(prec=floatingPointPrecSa)
705
    scaledUpperBoundSa = \
706
        domainScalingFunction(upperBoundSa).n(prec=floatingPointPrecSa)
707
    if debug:
708
        print 'ff:', ff, "- Domain:", scaledLowerBoundSa, \
709
              scaledUpperBoundSa
710
    #
711
    # Scalling the image -> [1,2[.
712
    flbSa = ff(scaledLowerBoundSa).n(prec=floatingPointPrecSa)
713
    fubSa = ff(scaledUpperBoundSa).n(prec=floatingPointPrecSa)
714
    if flbSa <= fubSa: # Increasing
715
        imageBinadeBottomSa = floor(flbSa.log2())
716
    else: # Decreasing
717
        imageBinadeBottomSa = floor(fubSa.log2())
718
    if debug:
719
        print 'ff:', ff, '- Image:', flbSa, fubSa, imageBinadeBottomSa
720
    imageBoundsIntervalSa = boundsIntervalRifSa(flbSa, fubSa)
721
    (imageScalingExpressionSa, invImageScalingExpressionSa) = \
722
        slz_interval_scaling_expression(imageBoundsIntervalSa, x)
723
    if debug:
724
        print "imageScalingExpression for argument :", \
725
              invImageScalingExpressionSa
726
    iis = invImageScalingExpressionSa.function(x)
727
    fff = iis.subs({x:ff})
728
    if debug:
729
        print "fff:", fff,
730
        print " - Image:", fff(scaledLowerBoundSa), fff(scaledUpperBoundSa)
731
    return([fff, scaledLowerBoundSa, scaledUpperBoundSa, \
732
            fff(scaledLowerBoundSa), fff(scaledUpperBoundSa)])
733
# End slz_compute_scaled_function
734

    
735
def slz_float_poly_of_float_to_rat_poly_of_rat(polyOfFloat):
736
    # Create a polynomial over the rationals.
737
    polynomialRing = QQ[str(polyOfFloat.variables()[0])]
738
    return(polynomialRing(polyOfFloat))
739
# End slz_float_poly_of_float_to_rat_poly_of_rat.
740

    
741
def slz_get_intervals_and_polynomials(functionSa, degreeSa, 
742
                                      lowerBoundSa, 
743
                                      upperBoundSa, floatingPointPrecSa, 
744
                                      internalSollyaPrecSa, approxPrecSa):
745
    """
746
    Under the assumption that:
747
    - functionSa is monotonic on the [lowerBoundSa, upperBoundSa] interval;
748
    - lowerBound and upperBound belong to the same binade.
749
    from a:
750
    - function;
751
    - a degree
752
    - a pair of bounds;
753
    - the floating-point precision we work on;
754
    - the internal Sollya precision;
755
    - the requested approximation error
756
    The initial interval is, possibly, splitted into smaller intervals.
757
    It return a list of tuples, each made of:
758
    - a first polynomial (without the changed variable f(x) = p(x-x0));
759
    - a second polynomial (with a changed variable f(x) = q(x))
760
    - the approximation interval;
761
    - the center, x0, of the interval;
762
    - the corresponding approximation error.
763
    TODO: fix endless looping for some parameters sets.
764
    """
765
    resultArray = []
766
    # Set Sollya to the necessary internal precision.
767
    precChangedSa = False
768
    currentSollyaPrecSo = pobyso_get_prec_so()
769
    currentSollyaPrecSa = pobyso_constant_from_int_so_sa(currentSollyaPrecSo)
770
    if internalSollyaPrecSa > currentSollyaPrecSa:
771
        pobyso_set_prec_sa_so(internalSollyaPrecSa)
772
        precChangedSa = True
773
    #
774
    x = functionSa.variables()[0] # Actual variable name can be anything.
775
    # Scaled function: [1=,2] -> [1,2].
776
    (fff, scaledLowerBoundSa, scaledUpperBoundSa,                             \
777
            scaledLowerBoundImageSa, scaledUpperBoundImageSa) =               \
778
                slz_compute_scaled_function(functionSa,                       \
779
                                            lowerBoundSa,                     \
780
                                            upperBoundSa,                     \
781
                                            floatingPointPrecSa)
782
    #
783
    print "Approximation precision: ", RR(approxPrecSa)
784
    # Prepare the arguments for the Taylor expansion computation with Sollya.
785
    functionSo = \
786
      pobyso_parse_string_sa_so(fff._assume_str().replace('_SAGE_VAR_', ''))
787
    degreeSo = pobyso_constant_from_int_sa_so(degreeSa)
788
    scaledBoundsSo = pobyso_bounds_to_range_sa_so(scaledLowerBoundSa, 
789
                                                  scaledUpperBoundSa)
790
    # Compute the first Taylor expansion.
791
    (polySo, boundsSo, intervalCenterSo, maxErrorSo) = \
792
        slz_compute_polynomial_and_interval(functionSo, degreeSo,
793
                                        scaledLowerBoundSa, scaledUpperBoundSa,
794
                                        approxPrecSa, internalSollyaPrecSa)
795
    if polySo is None:
796
        print "slz_get_intervals_and_polynomials: Aborting and returning None!"
797
        if precChangedSa:
798
            pobyso_set_prec_so_so(currentSollyaPrecSo)
799
            sollya_lib_clear_obj(currentSollyaPrecSo)
800
        sollya_lib_clear_obj(functionSo)
801
        sollya_lib_clear_obj(degreeSo)
802
        sollya_lib_clear_obj(scaledBoundsSo)
803
        return None
804
    realIntervalField = RealIntervalField(max(lowerBoundSa.parent().precision(),
805
                                              upperBoundSa.parent().precision()))
806
    boundsSa = pobyso_range_to_interval_so_sa(boundsSo, realIntervalField)
807
    errorSa = pobyso_get_constant_as_rn_with_rf_so_sa(maxErrorSo)
808
    print "First approximation error:", errorSa.n(digits=50)
809
    # If the error and interval are OK a the first try, just return.
810
    if boundsSa.endpoints()[1] >= scaledUpperBoundSa:
811
        # Change variable stuff in Sollya x -> x0-x.
812
        changeVarExpressionSo = sollya_lib_build_function_sub( \
813
                              sollya_lib_build_function_free_variable(), \
814
                              sollya_lib_copy_obj(intervalCenterSo))
815
        polyVarChangedSo = sollya_lib_evaluate(polySo, changeVarExpressionSo) 
816
        sollya_lib_clear_obj(changeVarExpressionSo)
817
        resultArray.append((polySo, polyVarChangedSo, boundsSo, \
818
                            intervalCenterSo, maxErrorSo))
819
        if internalSollyaPrecSa != currentSollyaPrecSa:
820
            pobyso_set_prec_sa_so(currentSollyaPrecSa)
821
        sollya_lib_clear_obj(currentSollyaPrecSo)
822
        sollya_lib_clear_obj(functionSo)
823
        sollya_lib_clear_obj(degreeSo)
824
        sollya_lib_clear_obj(scaledBoundsSo)
825
        #print "Approximation error:", errorSa
826
        return resultArray
827
    # The returned interval upper bound does not reach the requested upper
828
    # upper bound: compute the next upper bound.
829
    # The following ratio is always >= 1
830
    currentErrorRatio = approxPrecSa / errorSa
831
    # Starting point for the next upper bound.
832
    currentScaledUpperBoundSa = boundsSa.endpoints()[1]
833
    boundsWidthSa = boundsSa.endpoints()[1] - boundsSa.endpoints()[0]
834
    # Compute the increment. 
835
    if currentErrorRatio > RR('1000'): # ]1.5, infinity[
836
        currentScaledUpperBoundSa += \
837
                        currentErrorRatio * boundsWidthSa * 2
838
    else:  # [1, 1.5]
839
        currentScaledUpperBoundSa += \
840
                        (RR('1.0') + currentErrorRatio.log() / 500) * boundsWidthSa
841
    # Take into account the original interval upper bound.                     
842
    if currentScaledUpperBoundSa > scaledUpperBoundSa:
843
        currentScaledUpperBoundSa = scaledUpperBoundSa
844
    # Compute the other expansions.
845
    while boundsSa.endpoints()[1] < scaledUpperBoundSa:
846
        currentScaledLowerBoundSa = boundsSa.endpoints()[1]
847
        (polySo, boundsSo, intervalCenterSo, maxErrorSo) = \
848
            slz_compute_polynomial_and_interval(functionSo, degreeSo,
849
                                            currentScaledLowerBoundSa, 
850
                                            currentScaledUpperBoundSa, 
851
                                            approxPrecSa, 
852
                                            internalSollyaPrecSa)
853
        errorSa = pobyso_get_constant_as_rn_with_rf_so_sa(maxErrorSo)
854
        if  errorSa < approxPrecSa:
855
            # Change variable stuff
856
            #print "Approximation error:", errorSa
857
            changeVarExpressionSo = sollya_lib_build_function_sub(
858
                                    sollya_lib_build_function_free_variable(), 
859
                                    sollya_lib_copy_obj(intervalCenterSo))
860
            polyVarChangedSo = sollya_lib_evaluate(polySo, changeVarExpressionSo) 
861
            sollya_lib_clear_obj(changeVarExpressionSo)
862
            resultArray.append((polySo, polyVarChangedSo, boundsSo, \
863
                                intervalCenterSo, maxErrorSo))
864
        boundsSa = pobyso_range_to_interval_so_sa(boundsSo, realIntervalField)
865
        # Compute the next upper bound.
866
        # The following ratio is always >= 1
867
        currentErrorRatio = approxPrecSa / errorSa
868
        # Starting point for the next upper bound.
869
        currentScaledUpperBoundSa = boundsSa.endpoints()[1]
870
        boundsWidthSa = boundsSa.endpoints()[1] - boundsSa.endpoints()[0]
871
        # Compute the increment. 
872
        if currentErrorRatio > RR('1000'): # ]1.5, infinity[
873
            currentScaledUpperBoundSa += \
874
                            currentErrorRatio * boundsWidthSa * 2
875
        else:  # [1, 1.5]
876
            currentScaledUpperBoundSa += \
877
                            (RR('1.0') + currentErrorRatio.log()/500) * boundsWidthSa
878
        #print "currentErrorRatio:", currentErrorRatio
879
        #print "currentScaledUpperBoundSa", currentScaledUpperBoundSa
880
        # Test for insufficient precision.
881
        if currentScaledUpperBoundSa == scaledLowerBoundSa:
882
            print "Can't shrink the interval anymore!"
883
            print "You should consider increasing the Sollya internal precision"
884
            print "or the polynomial degree."
885
            print "Giving up!"
886
            if internalSollyaPrecSa != currentSollyaPrecSa:
887
                pobyso_set_prec_sa_so(currentSollyaPrecSa)
888
            sollya_lib_clear_obj(currentSollyaPrecSo)
889
            sollya_lib_clear_obj(functionSo)
890
            sollya_lib_clear_obj(degreeSo)
891
            sollya_lib_clear_obj(scaledBoundsSo)
892
            return None
893
        if currentScaledUpperBoundSa > scaledUpperBoundSa:
894
            currentScaledUpperBoundSa = scaledUpperBoundSa
895
    if internalSollyaPrecSa > currentSollyaPrecSa:
896
        pobyso_set_prec_so_so(currentSollyaPrecSo)
897
    sollya_lib_clear_obj(currentSollyaPrecSo)
898
    sollya_lib_clear_obj(functionSo)
899
    sollya_lib_clear_obj(degreeSo)
900
    sollya_lib_clear_obj(scaledBoundsSo)
901
    return(resultArray)
902
# End slz_get_intervals_and_polynomials
903

    
904

    
905
def slz_interval_scaling_expression(boundsInterval, expVar):
906
    """
907
    Compute the scaling expression to map an interval that spans at most
908
    a single binade to [1, 2) and the inverse expression as well.
909
    If the interval spans more than one binade, result is wrong since
910
    scaling is only based on the lower bound.
911
    Not very sure that the transformation makes sense for negative numbers.
912
    """
913
    # The "one of the bounds is 0" special case. Here we consider
914
    # the interval as the subnormals binade.
915
    if boundsInterval.endpoints()[0] == 0 or boundsInterval.endpoints()[1] == 0:
916
        # The upper bound is (or should be) positive.
917
        if boundsInterval.endpoints()[0] == 0:
918
            if boundsInterval.endpoints()[1] == 0:
919
                return None
920
            binade = slz_compute_binade(boundsInterval.endpoints()[1])
921
            l2     = boundsInterval.endpoints()[1].abs().log2()
922
            # The upper bound is a power of two
923
            if binade == l2:
924
                scalingCoeff    = 2^(-binade)
925
                invScalingCoeff = 2^(binade)
926
                scalingOffset   = 1
927
                return((scalingCoeff * expVar + scalingOffset),\
928
                       ((expVar - scalingOffset) * invScalingCoeff))
929
            else:
930
                scalingCoeff    = 2^(-binade-1)
931
                invScalingCoeff = 2^(binade+1)
932
                scalingOffset   = 1
933
                return((scalingCoeff * expVar + scalingOffset),\
934
                    ((expVar - scalingOffset) * invScalingCoeff))
935
        # The lower bound is (or should be) negative.
936
        if boundsInterval.endpoints()[1] == 0:
937
            if boundsInterval.endpoints()[0] == 0:
938
                return None
939
            binade = slz_compute_binade(boundsInterval.endpoints()[0])
940
            l2     = boundsInterval.endpoints()[0].abs().log2()
941
            # The upper bound is a power of two
942
            if binade == l2:
943
                scalingCoeff    = -2^(-binade)
944
                invScalingCoeff = -2^(binade)
945
                scalingOffset   = 1
946
                return((scalingCoeff * expVar + scalingOffset),\
947
                    ((expVar - scalingOffset) * invScalingCoeff))
948
            else:
949
                scalingCoeff    = -2^(-binade-1)
950
                invScalingCoeff = -2^(binade+1)
951
                scalingOffset   = 1
952
                return((scalingCoeff * expVar + scalingOffset),\
953
                   ((expVar - scalingOffset) * invScalingCoeff))
954
    # General case
955
    lbBinade = slz_compute_binade(boundsInterval.endpoints()[0])
956
    ubBinade = slz_compute_binade(boundsInterval.endpoints()[1])
957
    # We allow for a single exception in binade spanning is when the
958
    # "outward bound" is a power of 2 and its binade is that of the
959
    # "inner bound" + 1.
960
    if boundsInterval.endpoints()[0] > 0:
961
        ubL2 = boundsInterval.endpoints()[1].abs().log2()
962
        if lbBinade != ubBinade:
963
            print "Different binades."
964
            if ubL2 != ubBinade:
965
                print "Not a power of 2."
966
                return None
967
            elif abs(ubBinade - lbBinade) > 1:
968
                print "Too large span:", abs(ubBinade - lbBinade)
969
                return None
970
    else:
971
        lbL2 = boundsInterval.endpoints()[0].abs().log2()
972
        if lbBinade != ubBinade:
973
            print "Different binades."
974
            if lbL2 != lbBinade:
975
                print "Not a power of 2."
976
                return None
977
            elif abs(ubBinade - lbBinade) > 1:
978
                print "Too large span:", abs(ubBinade - lbBinade)
979
                return None
980
    #print "Lower bound binade:", binade
981
    if boundsInterval.endpoints()[0] > 0:
982
        return((2^(-lbBinade) * expVar),(2^(lbBinade) * expVar))
983
    else:
984
        return((-(2^(-lbBinade+1)) * expVar),(-(2^(lbBinade-1)) * expVar))
985
"""
986
    # Code sent to attic. Should be the base for a 
987
    # "slz_interval_translate_expression" rather than scale.
988
    # Extra control and special cases code  added in  
989
    # slz_interval_scaling_expression could (should ?) be added to
990
    # this new function.
991
    # The scaling offset is only used for negative numbers.
992
    # When the absolute value of the lower bound is < 0.
993
    if abs(boundsInterval.endpoints()[0]) < 1:
994
        if boundsInterval.endpoints()[0] >= 0:
995
            scalingCoeff = 2^floor(boundsInterval.endpoints()[0].log2())
996
            invScalingCoeff = 1/scalingCoeff
997
            return((scalingCoeff * expVar, 
998
                    invScalingCoeff * expVar))
999
        else:
1000
            scalingCoeff = \
1001
                2^(floor((-boundsInterval.endpoints()[0]).log2()) - 1)
1002
            scalingOffset = -3 * scalingCoeff
1003
            return((scalingCoeff * expVar + scalingOffset,
1004
                    1/scalingCoeff * expVar + 3))
1005
    else: 
1006
        if boundsInterval.endpoints()[0] >= 0:
1007
            scalingCoeff = 2^floor(boundsInterval.endpoints()[0].log2())
1008
            scalingOffset = 0
1009
            return((scalingCoeff * expVar, 
1010
                    1/scalingCoeff * expVar))
1011
        else:
1012
            scalingCoeff = \
1013
                2^(floor((-boundsInterval.endpoints()[1]).log2()))
1014
            scalingOffset =  -3 * scalingCoeff
1015
            #scalingOffset = 0
1016
            return((scalingCoeff * expVar + scalingOffset,
1017
                    1/scalingCoeff * expVar + 3))
1018
"""
1019
# End slz_interval_scaling_expression
1020
   
1021
def slz_interval_and_polynomial_to_sage(polyRangeCenterErrorSo):
1022
    """
1023
    Compute the Sage version of the Taylor polynomial and it's
1024
    companion data (interval, center...)
1025
    The input parameter is a five elements tuple:
1026
    - [0]: the polyomial (without variable change), as polynomial over a
1027
           real ring;
1028
    - [1]: the polyomial (with variable change done in Sollya), as polynomial
1029
           over a real ring;
1030
    - [2]: the interval (as Sollya range);
1031
    - [3]: the interval center;
1032
    - [4]: the approximation error. 
1033
    
1034
    The function return a 5 elements tuple: formed with all the 
1035
    input elements converted into their Sollya counterpart.
1036
    """
1037
    polynomialSa = pobyso_get_poly_so_sa(polyRangeCenterErrorSo[0])
1038
    polynomialChangedVarSa = pobyso_get_poly_so_sa(polyRangeCenterErrorSo[1])
1039
    intervalSa = \
1040
            pobyso_get_interval_from_range_so_sa(polyRangeCenterErrorSo[2])
1041
    centerSa = \
1042
            pobyso_get_constant_as_rn_with_rf_so_sa(polyRangeCenterErrorSo[3])
1043
    errorSa = \
1044
            pobyso_get_constant_as_rn_with_rf_so_sa(polyRangeCenterErrorSo[4])
1045
    return((polynomialSa, polynomialChangedVarSa, intervalSa, centerSa, errorSa))
1046
    # End slz_interval_and_polynomial_to_sage
1047

    
1048
def slz_rat_poly_of_int_to_poly_for_coppersmith(ratPolyOfInt, 
1049
                                                precision,
1050
                                                targetHardnessToRound,
1051
                                                variable1,
1052
                                                variable2):
1053
    """
1054
    Creates a new multivariate polynomial with integer coefficients for use
1055
     with the Coppersmith method.
1056
    A the same time it computes :
1057
    - 2^K (N);
1058
    - 2^k (bound on the second variable)
1059
    - lcm
1060

    
1061
    :param ratPolyOfInt: a polynomial with rational coefficients and integer
1062
                         variables.
1063
    :param precision: the precision of the floating-point coefficients.
1064
    :param targetHardnessToRound: the hardness to round we want to check.
1065
    :param variable1: the first variable of the polynomial (an expression).
1066
    :param variable2: the second variable of the polynomial (an expression).
1067
    
1068
    :returns: a 4 elements tuple:
1069
                - the polynomial;
1070
                - the modulus (N);
1071
                - the t bound;
1072
                - the lcm used to compute the integral coefficients and the 
1073
                  module.
1074
    """
1075
    # Create a new integer polynomial ring.
1076
    IP = PolynomialRing(ZZ, name=str(variable1) + "," + str(variable2))
1077
    # Coefficients are issued in the increasing power order.
1078
    ratPolyCoefficients = ratPolyOfInt.coefficients()
1079
    # Print the reversed list for debugging.
1080
    print "Rational polynomial coefficients:", ratPolyCoefficients[::-1]
1081
    # Build the list of number we compute the lcm of.
1082
    coefficientDenominators = sro_denominators(ratPolyCoefficients)
1083
    coefficientDenominators.append(2^precision)
1084
    coefficientDenominators.append(2^(targetHardnessToRound + 1))
1085
    leastCommonMultiple = lcm(coefficientDenominators)
1086
    # Compute the expression corresponding to the new polynomial
1087
    coefficientNumerators =  sro_numerators(ratPolyCoefficients)
1088
    #print coefficientNumerators
1089
    polynomialExpression = 0
1090
    power = 0
1091
    # Iterate over two lists at the same time, stop when the shorter is
1092
    # exhausted.
1093
    for numerator, denominator in \
1094
                        zip(coefficientNumerators, coefficientDenominators):
1095
        multiplicator = leastCommonMultiple / denominator 
1096
        newCoefficient = numerator * multiplicator
1097
        polynomialExpression += newCoefficient * variable1^power
1098
        power +=1
1099
    polynomialExpression += - variable2
1100
    return (IP(polynomialExpression),
1101
            leastCommonMultiple / 2^precision, # 2^K or N.
1102
            leastCommonMultiple / 2^(targetHardnessToRound + 1), # tBound
1103
            leastCommonMultiple) # If we want to make test computations.
1104
        
1105
# End slz_ratPoly_of_int_to_poly_for_coppersmith
1106

    
1107
def slz_rat_poly_of_rat_to_rat_poly_of_int(ratPolyOfRat, 
1108
                                          precision):
1109
    """
1110
    Makes a variable substitution into the input polynomial so that the output
1111
    polynomial can take integer arguments.
1112
    All variables of the input polynomial "have precision p". That is to say
1113
    that they are rationals with denominator == 2^(precision - 1): 
1114
    x = y/2^(precision - 1).
1115
    We "incorporate" these denominators into the coefficients with, 
1116
    respectively, the "right" power.
1117
    """
1118
    polynomialField = ratPolyOfRat.parent()
1119
    polynomialVariable = ratPolyOfRat.variables()[0]
1120
    #print "The polynomial field is:", polynomialField
1121
    return \
1122
        polynomialField(ratPolyOfRat.subs({polynomialVariable : \
1123
                                   polynomialVariable/2^(precision-1)}))
1124
    
1125
    # Return a tuple:
1126
    # - the bivariate integer polynomial in (i,j);
1127
    # - 2^K
1128
# End slz_rat_poly_of_rat_to_rat_poly_of_int
1129

    
1130

    
1131
print "\t...sageSLZ loaded"