/
intervalo.py
680 lines (521 loc) · 20.8 KB
/
intervalo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
# -*- coding: utf-8 -*-
# Usamos mpmath para las funciones elementales (exp, log, sin, cos, tan, etc)
# para adem\'as poder usar precisi\'on extendida
from sympy.mpmath import mp, mpf
from matplotlib import pyplot as plt
import numpy as np
class Intervalo(object):
"""
Se define la clase 'Intervalo', y la aritm\'etica b\'asica de intervalos,
es decir, suma, resta, multiplicaci\'on y divisi\'on, y las funciones básicas.
Se carga antes (internamente) mp y mpf de mpmath para usar las funciones
elementales y poder usar precisi\'on extendida de manera sencilla.
"""
def __init__(self, a, b=None):
"""
Se define la clase 'Intervalo', y los m\'etodos para la aritm\'etica
b\'asica de intervalos, es decir, suma, resta, multiplicaci\'on y
divisi\'on.
Se incluyen otras funciones (sin, cos, exp, log) que ser\'an \'utiles.
"""
if b is None: # single argument, so make thin interval
b = a
elif (b < a): # limits wrong way round; not right approach for extended IA
a, b = b, a
a = make_mpf(a)
b = make_mpf(b)
self.lo, self.hi = a, b
# Lo siguiente sirve para dar informaci\'on bonita del objeto `Intervalo`
#
def __repr__(self):
return "Intervalo [{},{}]".format(repr(self.lo),repr(self.hi))
def __str__(self):
return "[{},{}]".format(self.lo,self.hi)
# Aqu\'i vienen las operaciones aritm\'eticas y varias funciones
#
def __add__(self, otro):
"""
Suma de intervalos
"""
otro = self.make_interval(otro)
return Intervalo(self.lo + otro.lo, self.hi + otro.hi)
def __radd__(self, otro):
return self + otro
def __sub__(self, otro):
"""
Resta de intervalos
"""
otro = self.make_interval(otro)
return Intervalo( self.lo - otro.hi, self.hi - otro.lo )
def __rsub__(self, otro):
return -(self - otro)
def __pos__(self):
return self
def __neg__(self):
"""
El negativo de un intervalo
"""
return Intervalo(-self.hi,-self.lo)
def __mul__(self, otro):
"""
Se implementa la multiplicaci\'on usando `multFast`
"""
otro = self.make_interval(otro)
return self.mult2(otro)
def __rmul__(self, otro):
return self * otro
def mult1(self,otro):
""" Algor\'itmo de la multiplicaci\'on ingenuo """
S = [ self.lo*otro.lo, self.lo*otro.hi,
self.hi*otro.lo, self.hi*otro.hi ]
return Intervalo( min(S), max(S) )
def mult2(self,otro):
"""
Algor\'itmo de la multiplicaci\'on que distingue los nueve casos posibles
"""
if (self.lo >= 0.0 and otro.lo >= 0.0):
return Intervalo( self.lo*otro.lo, self.hi*otro.hi )
elif (self.hi < 0.0 and otro.hi < 0.0):
return Intervalo( self.hi*otro.hi, self.lo*otro.lo )
elif (self.lo >= 0.0 and otro.hi < 0.0):
return Intervalo( self.lo*otro.hi, self.hi*otro.lo )
elif (self.hi < 0.0 and otro.lo >= 0.0):
return Intervalo( self.hi*otro.lo, self.lo*otro.hi )
elif (self.lo >= 0.0 and otro.lo*otro.hi < 0.0):
return Intervalo( self.hi*otro.lo, self.hi*otro.hi )
elif (self.hi < 0.0 and otro.lo*otro.hi < 0.0):
return Intervalo( self.lo*otro.hi, self.lo*otro.lo )
elif (otro.lo >= 0.0 and self.lo*self.hi < 0.0):
return Intervalo( self.lo*otro.hi, self.hi*otro.hi )
elif (otro.hi < 0.0 and self.lo*self.hi < 0.0):
return Intervalo( self.hi*otro.lo, self.lo*otro.lo )
else: #(self.lo*self.hi < 0.0 and otro.lo*otro.hi < 0.0):
S1 = [ self.lo*otro.lo, self.hi*otro.hi ]
S2 = [ self.hi*otro.lo, self.lo*otro.hi ]
return Intervalo( min(S2), max(S1) )
def __div__(self, otro):
"""
Divisi\'on de intervalos: producto del primero por el rec\'iproco del segundo
"""
otro = self.make_interval(otro)
try:
return self * otro.reciprocal()
except ZeroDivisionError:
print "To divide by an interval containining 0, we need to implement extended intervals!"
# put extended interval code here
def __rdiv__(self, otro):
# Esto se encarga de cosas tipo numero/intervalo; self es el intervalo
return (self / otro).reciprocal()
def __contains__(self, x):
"""
Esto verifica si el intervalo contiene (o no) un n\'umero real;
implementa al operador `is`
"""
return self.lo <= x <= self.hi
def strictly_contains(self, x):
return self.lo < x < self.hi
def reciprocal(self):
"""
Esto define el rec\'iproco de un intervalo
"""
try:
lower = 1. / self.hi
except:
lower = - mpf("inf")
try:
upper = 1. / self.lo
except:
upper = mpf("inf")
if self.strictly_contains(0):
txt_error = "Interval {} in denominator contains 0.".format(self)
#raise ZeroDivisionError( txt_error )
lower = - mpf("inf")
upper = mpf("inf")
#return Intervalo( 1.0/self.hi, 1.0/self.lo )
return Intervalo(lower, upper)
# pow, rpow, abs, sin, cos, ...
def exp(self):
"""
Exponencial de un intervalo: 'self.exp()'
"""
return Intervalo( mp.exp(self.lo), mp.exp(self.hi) )
def log(self):
"""
Logaritmo de un intervalo: 'self.log()'
NOTA: Si el intervalo contiene al 0, pero no es estrictamente negativo,
se calcula el logaritmo de la intersecci\'on del intervalo con el dominio
natural del logaritmo, i.e., [0,+inf].
"""
if 0 in self:
domainNatural = Intervalo( 0, mpf('inf') )
intervalRestricted = self.intersection( domainNatural )
txt_warning = "\nWARNING: Interval {} contains 0 or negative numbers.\n".format(self)
print txt_warning
txt_warning = "Restricting to the intersection "\
"with the natural domain of log(x), i.e. {}\n".format(intervalRestricted)
print txt_warning
return Intervalo( mp.log(intervalRestricted.lo), mp.log(intervalRestricted.hi) )
elif 0 > self.hi:
txt_error = 'Interval {} < 0\nlog(x) cannot be computed '\
'for negative numbers.'.format(self)
raise ValueError( txt_error )
else:
return Intervalo( mp.log(self.lo), mp.log(self.hi) )
def __pow__(self, exponent):
"""
Se calcula la potencia de un intervalo; operador '**'
UNDER TESTING
"""
if isinstance( exponent, Intervalo ): # exponent is an interval
if exponent.lo == exponent.hi: # exponent is a thin interval
return self**exponent.lo
else: # exponent is a generic interval
return ( exponent*self.log() ).exp()
else: # exponent is a number (int, float, mpf, ...)
if exponent == int(exponent): # exponent is an integer
if exponent >= 0:
if exponent%2 == 0: # even exponent
return Intervalo( (self.mig())**exponent, (self.mag())**exponent )
else: # odd exponent
return Intervalo( self.lo**exponent, self.hi**exponent )
else: # exponent < 0
return (self**(-exponent)).reciprocal()
else:
# exponent is a generic float
if exponent >= 0:
if 0 in self:
domainNatural = Intervalo( 0, mpf('inf') )
intervalRestricted = self.intersection( domainNatural )
txt_warning = "\nWARNING: Interval {} contains 0.\n".format(self)
print txt_warning
txt_warning = "Restricting to the intersection "\
"with the natural domain of **, i.e. {}\n".format(intervalRestricted)
print txt_warning
return Intervalo( 0, self.hi**exponent )
elif 0 > self:
raise ValueError("negative interval can not be raised to a fractional power")
else:
return Intervalo( self.lo**exponent, self.hi**exponent )
else:
return (self**(-exponent)).reciprocal()
def __rpow__(self,exponent):
return Intervalo(exponent)**self
def sin(self):
"""
Se calcula el seno de un intervalo
TEST CAREFULLY
"""
pi = mp.pi
pi_half = 0.5 * pi
dospi = 2.0 * pi
xlow, xhig = self.lo, self.hi
whole_range = Intervalo(-1,1)
# Check the specific case:
if xhig > xlow + dospi: # more than 1 full period away
return whole_range
else: # within 1 full period of sin(x); 20 cases
# some abreviations
lo_mod2pi = xlow % dospi
hi_mod2pi = xhig % dospi
sin_xlo = mp.sin( xlow )
sin_xhi = mp.sin( xhig )
lo_quarter = mp.floor( lo_mod2pi / pi_half )
hi_quarter = mp.floor( hi_mod2pi / pi_half )
if lo_quarter == hi_quarter: # mismo cuadrante --> 8 casos
if lo_mod2pi <= hi_mod2pi:
return Intervalo( sin_xlo, sin_xhi )
else:
return whole_range
else:
# other abreviations
min_sin, max_sin = sin_xlo, sin_xhi
if sin_xhi < sin_xlo:
min_sin, max_sin = sin_xhi, sin_xlo
if ( lo_quarter == 3 and hi_quarter==0 ) or \
( lo_quarter == 1 and hi_quarter==2 ) : # 2 cases
return Intervalo( sin_xlo, sin_xhi )
elif ( lo_quarter == 0 or lo_quarter==3 ) and \
( hi_quarter==1 or hi_quarter==2 ) : # 4 cases
return Intervalo( min_sin, 1 )
elif ( lo_quarter == 1 or lo_quarter==2 ) and \
( hi_quarter==3 or hi_quarter==0 ) : # 4 cases
return Intervalo( -1, max_sin )
elif ( lo_quarter == 0 and hi_quarter==3 ) or \
( lo_quarter == 2 and hi_quarter==1 ) : # 2 cases
return whole_range
else: # This should be never reached!
raise NotImplementedError( 'SOMETHING WENT WRONG. This should have never\
been reached' )
def cos(self):
"""
Se calcula el coseno de un intervalo
TEST CAREFULLY
"""
pi = mp.pi
pi_half = 0.5 * pi
dospi = 2.0 * pi
xlow, xhig = self.lo, self.hi
whole_range = Intervalo(-1,1)
# Check the specific case:
if xhig > xlow + dospi: # more than 1 full period away
return whole_range
else: # within 1 full period of sin(x); 20 cases
# some abreviations
lo_mod2pi = xlow % dospi
hi_mod2pi = xhig % dospi
lo_quarter = mp.floor( lo_mod2pi / pi_half )
hi_quarter = mp.floor( hi_mod2pi / pi_half )
cos_xlo = mp.cos( xlow )
cos_xhi = mp.cos( xhig )
if lo_quarter == hi_quarter: # mismo cuadrante --> 8 casos
if lo_mod2pi <= hi_mod2pi:
return Intervalo( cos_xlo, cos_xhi )
else:
return whole_range
else:
# other abreviations
min_cos, max_cos = cos_xlo, cos_xhi
if cos_xhi < cos_xlo:
min_cos, max_cos = cos_xhi, cos_xlo
if ( lo_quarter == 2 and hi_quarter==3 ) or \
( lo_quarter == 0 and hi_quarter==1 ) : # 2 cases
return Intervalo( cos_xlo, cos_xhi )
elif ( lo_quarter == 2 or lo_quarter==3 ) and \
( hi_quarter==0 or hi_quarter==1 ) : # 4 cases
return Intervalo( min_cos, 1 )
elif ( lo_quarter == 0 or lo_quarter==1 ) and \
( hi_quarter==2 or hi_quarter==3 ) : # 4 cases
return Intervalo( -1, max_cos )
elif ( lo_quarter == 3 and hi_quarter==2 ) or \
( lo_quarter == 1 and hi_quarter==0 ) : # 2 cases
return whole_range
else: # This should be never reached!
raise NotImplementedError( 'SOMETHING WENT WRONG. This should have never\
been reached' )
def tan(self):
"""
Se calcula la tangente de un intervalo
"""
return self.sin() / self.cos()
# Las relaciones que sirven para checar el orden parcial
def __eq__(self, otro):
"""
Aqu\'i se checa la igualdad de dos intervalos; operador '=='
"""
try:
return self.lo == otro.lo and self.hi == otro.hi
except:
return self == Intervalo(otro)
def __ne__(self, otro):
"""
Aqu\'i se checa la NO igualdad de dos intervalos; operador '!='
"""
return not self == otro
def __le__(self, otro):
"""
Se checa el ordenamiento de los intervalos (ver Tucker);
operador '<='
"""
try:
return self.lo <= otro.lo and self.hi <= otro.hi
except:
return self <= Intervalo(otro)
def __rle__(self, otro):
return self >= otro
def __ge__(self, otro):
"""
Se checa el ordenamiento de los intervalos (ver Tucker);
operador '>='
"""
try:
return self.lo >= otro.lo and self.hi >= otro.hi
except:
return self >= Intervalo(otro)
def __rge__(self, otro):
return self <= otro
def __lt__(self, otro):
"""
Se checa el ordenamiento de los intervalos (ver Tucker);
operador '<'
"""
try:
return self.lo < otro.lo and self.hi < otro.hi
except:
return self < Intervalo(otro)
def __rlt__(self, otro):
return self > otro
def __gt__(self, otro):
"""
Se checa el ordenamiento de los intervalos (ver Tucker);
operador '>'
"""
try:
return self.lo > otro.lo and self.hi > otro.hi
except:
return self > Intervalo(otro)
def __rgt__(self, otro):
return self < otro
# Las operaciones entre intervalos vistas como conjuntos
def _is_empty_intersection(self, otro):
"""Verifica si la intersecci\'on de los intervalos es vac\'ia"""
return self.hi < otro.lo or otro.hi < self.lo
def intersection(self, otro):
"""
Intersecci\'on de intervalos
"""
if not isinstance(otro, Intervalo):
otro = Intervalo(otro)
if self._is_empty_intersection(otro):
print "Intersection is empty: " \
"Intervals {} and {} are disjoint".format(self,otro)
else:
return Intervalo( max(self.lo,otro.lo), min(self.hi,otro.hi) )
def hull(self, otro):
"""Envoltura/casco de dos intervalos"""
return Intervalo( min(self.lo,otro.lo), max(self.hi,otro.hi) )
def union(self, otro):
"""Uni\'on de intervalos"""
if not isinstance(otro, Intervalo):
otro = Intervalo(otro)
if self._is_empty_intersection(otro):
print "Union yields no connected interval: " \
"Intervals {} and {} are disjoint".format(self,otro)
else:
return self.hull(otro)
# Algunas funciones escalares de intervalos (ver Tucker)
def diam(self):
return self.hi-self.lo
def rad(self):
return diam(self)*0.5
def mid(self):
return 0.5*(self.lo+self.hi)
def mag(self):
"""Distancia máxima (magnitude) al origen"""
return max( abs(self.lo), abs(self.hi) )
def mig(self):
"""Distancia mínima (mignitude) al origen"""
if 0 in self:
return 0
else:
return min( abs(self.lo), abs(self.hi) )
def __abs__(self): # use as abs(i)
"""
Esto define la función abs() de un intervalo, cuyo resultado
es un intervalo (ver Tucker).
NOTA: La función que regresa la máxima distancia al origen es `self.mag()`
(magnitud) y la que regresa la mínima distancia es `self.mig()` ('mignitud').
"""
return Intervalo( self.mig(), self.mag() )
def abs(self): # use as i.abs()
return abs(self)
def dist(self, otro):
"""
Esto define la distancia de Hausdorff entre dos intervalos; ver Tucker.
"""
return max( abs(self.lo-otro.lo), abs(self.hi-otro.hi) )
# Representaciones especiales para el IPython Notebook:
def _repr_html_(self):
reprn = "[{}, {}]".format(self.lo, self.hi)
reprn = reprn.replace("inf", r"∞")
return reprn
def _repr_latex_(self):
return "$[{}, {}]$".format(self.lo, self.hi)
def make_interval(self, a):
if isinstance(a, Intervalo):
return a
return Intervalo(a)
# Funciones extras
def make_mpf(a):
if isinstance(a, mpf):
return a
return mpf(str(a))
def exp(a):
try:
return a.exp()
except:
return mp.exp(a)
def log(a):
try:
return a.log()
except:
return mp.log(a)
def sin(a):
try:
return a.sin()
except:
return mp.sin(a)
def cos(a):
try:
return a.cos()
except:
return mp.cos(a)
def tan(a):
try:
return a.tan()
except:
return mp.tan(a)
def random_interval( infimum=-10.0, supremum=10.0 ):
num1a = np.random.uniform( infimum, supremum )
num2a = np.random.uniform( infimum, supremum )
return Intervalo( num1a, num2a )
def split_interval( x, num_divisions=1 ):
"""
Divide un intervalo en n=num_divisions intervalos iguales
"""
num_divisions = int(num_divisions)
if num_divisions < 1:
num_divisions = 1
edge_points = np.linspace(x.lo, x.hi, num_divisions+1)
splited_intervals = [Intervalo(a, b) for (a,b) in zip(edge_points[:-1], edge_points[1:])]
return splited_intervals
def range_interval_f( fun, subdivided_interval ):
"""
Evalua la función f(x) extendida sobre intervalos, en una lista de subintervalos
y regresa el hull de todos ellos, es decir, una cota del rango de la función
"""
if not isinstance( subdivided_interval, list ):
subdivided_interval = [ subdivided_interval ]
range_fun = [ fun(i) for i in subdivided_interval ]
range_tot = range_fun[0]
for i in range_fun[1:]:
range_tot = range_tot.hull(i)
return range_tot
def plot_interval_f( fun, x, pow2=0, num_points=101 ):
"""
This plots the interval extension of a function `fun` over the interval `x`,
which is diveded in num=1,2,4,...,2**pow2 uniform subintervals.
"""
num_intervals = [ 2**p for p in range(pow2+1) ]
plt.figure()
plt.subplot(1, 1, 1)
for num in num_intervals:
fact_alfa = num*1.0/num_intervals[-1] # for plotting
# Se divide los subintervaloe en 2**num subintervalos iguales
subdivided_intervals = split_interval( x, num )
# Se calculan las extensiones de la función sobre el intervalo, usando los subintervalos
rango_total = range_interval_f( fun, subdivided_intervals )
print "Rango_tot (N={}) = {}".format(num,rango_total)
# Hago el dibujo
for x1 in subdivided_intervals:
low = float(x1.lo)
high = float(x1.hi)
Ffun = fun(x1)
xa1 = np.array([low, low, high, high])
ya1 = np.array([float(Ffun.lo), float(Ffun.hi), float(Ffun.hi), float(Ffun.lo) ])
plt.fill( xa1, ya1, 'b', alpha=fact_alfa )
low = float(x.lo)
high = float(x.hi)
xx = np.linspace(low,high,num_points)
yy = fun(xx)
plt.plot( xx, yy, 'red')
return
# Correct (directed) rounding:
# in each calculation of the lower bound, "floor" rounding must be used;
# for the upper bound, "ceiling" rounding
# In mpmath, use keyword arguments rounding="f" or rounding="c", respectively
# E.g. to construct the thin interval 0.1, we use:
# mp.pretty = False
# a = mpf("0.1", rounding="f")
# b = mpf("0.1", rounding="c")
# i = Intervalo(a, b)
# i.lo, i.hi