Hello,
I send you the module I've made for working with unions and 
intersections of intervals. For the moment this module only works with 
integer and not with sympy "numbers" (I haven't tested it yet).
I know that my code is uggly and with a lot of mispealings. I also know 
that I need to do some doctest. Can you give me an example of a module 
of sympy with a good doctest ?

Any suggestion is welcome.
Christophe

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sympy" group.
To post to this group, send email to sympy@googlegroups.com
To unsubscribe from this group, send email to sympy+unsubscr...@googlegroups.com
For more options, visit this group at http://groups.google.com/group/sympy?hl=en
-~----------~----~----~----~------~----~------~--~---

#!/usr/bin/env python
#coding=utf-8

import simpleSets

listEx = []

listEx.append("""I = simpleSets.Interval(14, 14, '()')
J = simpleSets.Interval(-5, -5, '[)')
K = simpleSets.Interval(3, 3, '()')
L = simpleSets.Interval(-5, -5, '(]')""")

listEx.append("""I = simpleSets.Interval(-5, 14, '[]')
J = simpleSets.Interval(-5, 7, '()')
K = simpleSets.Interval(3, 3, '()')
L = simpleSets.Interval(-5, -5, '(]')""")

listEx.append("""I = simpleSets.Interval(-5, 14, '(]')
J = simpleSets.Interval(-5, 7, '[)')
K = simpleSets.Interval(-5, 7, '[)')
L = simpleSets.Interval(-5, -5, '(]')""")


listEx.append("""I = simpleSets.Interval(-5, 7, '[)')
J = simpleSets.Interval(-5, 7, '()')
K = simpleSets.Interval(3, 3, '()')
L = simpleSets.Interval(-5, -5, '(]')""")

listEx.append("""I = simpleSets.Interval(9, 14, '[]')
J = simpleSets.Interval(-5, 7, '[]')
K = simpleSets.Interval(3, 3, '()')
L = simpleSets.Interval(-5, -5, '(]')""")

listEx.append("""I = simpleSets.Interval(9, 14, '[]')
J = simpleSets.Interval(-5, 7, '[]')
K = simpleSets.Interval(-5, 3, '[]')
L = simpleSets.Interval(-5, -5, '(]')""")

listEx.append("""I = simpleSets.Interval(9, 14, '[]')
J = simpleSets.Interval(-5, 3, '[]')
K = simpleSets.Interval(14, 17, '(]')
L = simpleSets.Interval(-5, 7, '[]')""")

listEx.append("""I = simpleSets.Interval(9, 14, '[]')
J = simpleSets.Interval(-5, 3, '[)')
K = simpleSets.Interval(14, 17, '(]')
L = simpleSets.Interval(-5, 3, '(]')""")

listEx.append("""I = simpleSets.Interval(-4, 3, '[]')
J = simpleSets.Interval(-2, 7, '(]')
K = simpleSets.Interval(3, 3, '()')
L = simpleSets.Interval(3, 3, '()')""")

listEx.append("""I = simpleSets.Interval(-5, 3, '()')
J = simpleSets.Interval(-4, 3, '[]')
K = simpleSets.Interval(-2, 7, '(]')
L = simpleSets.Interval(-3, 13, '[]')""")

listEx.append("""I = simpleSets.Interval(-5, 3, '()')
J = simpleSets.Interval(-3, 13, '[]')
K = simpleSets.Interval(24, 24, '[]')
L = simpleSets.Interval(3, 3, '()')""")





###########################
# WRITING OF THE EXAMPLES #
###########################

#for i in range(len(examples)):
for i in range(len(listEx)):
    exec(listEx[i])
    for line in listEx[i].splitlines():
        print line

    I_u_J_u_K_u_L = simpleSets.UnionIntervals([I, J, K, L])
    I_u_J_u_K_u_L___SIMPLIFIED = I_u_J_u_K_u_L.simplify()
    
    print '\tI : ' + str(I)
    print '\tJ : ' + str(J)
    print '\tK : ' + str(K)
    print '\tL : ' + str(L)
    print '\tI_u_J_u_K_u_L : ' + str(I_u_J_u_K_u_L)
    print '\tAfter simplification : ' + str(I_u_J_u_K_u_L___SIMPLIFIED)

    print '-'*30

print simpleSets.UnionIntervals([])
#!/usr/bin/env python
#coding=utf-8

# Code writing by BAL Christophe
# Mail : projet...@club.fr

# Lines automatically built by tool_simpleSets.py. ===== START
epEuropean_2_User = {}

# AM-erican notations.
epEuropean_2_User['am'] = {']]': '(]', '[[': '[)', '[]': '[]', '][': '()'}
# CZ-ech notations.
epEuropean_2_User['cz'] = {']]': '(>', '[[': '<)', '[]': '<>', '][': '()'}
# EU-ropean notations.
epEuropean_2_User['eu'] = {'[[': '[[', ']]': ']]', '][': '][', '[]': '[]'}
# Lines automatically built by tool_simpleSets.py. ===== END



def endPointsToUser(europeanEndpoints, notation):
#    global epEuropean_2_User
    return epEuropean_2_User[notation][europeanEndpoints]


class Interval():
    """
    
    """
    def __init__(self, minPoint, maxPoint, endpoints, notation = 'am'):
# Lines automatically built by tool_simpleSets.py. ===== START
        epNotationIsValid = {}
        epUser_2_European = {}

# AM-erican notations.
        epNotationIsValid['am'] = ['[]', '(]', '[)', '()']
        epUser_2_European['am'] = [{'(': ']', '[': '['}, {')': '[', ']': ']'}]
# CZ-ech notations.
        epNotationIsValid['cz'] = ['<>', '(>', '<)', '()']
        epUser_2_European['cz'] = [{'(': ']', '<': '['}, {')': '[', '>': ']'}]
# EU-ropean notations.
        epNotationIsValid['eu'] = ['[]', ']]', '[[', '][']
        epUser_2_European['eu'] = [{'[': '[', ']': ']'}, {'[': '[', ']': ']'}]
# Lines automatically built by tool_simpleSets.py. ===== END


        self.notation = notation
        
# An empty set ?
        if endpoints == '':
            minPoint = 0
            minPoint = 0
            endpoints = endPointsToUser('][', self.notation)

        if minPoint > maxPoint:
            raise TypeError, 'The first value ' + str(minPoint) + ' is not 
lower or equal to the second one ' + str(maxPoint) + '.'

        self.minPoint = minPoint
        self.maxPoint = maxPoint
        self.endpoints = endpoints

        if self.endpoints not in epNotationIsValid[self.notation]:
            raise TypeError, 'Unknown endpoints of interval : "' + 
str(endpoints) + '"'

# We are gonning to work with the european notations.
        if self.notation == 'eu':
            self.europeanEndpoints = self.endpoints
        else:
            self.europeanEndpoints = 
epUser_2_European[self.notation][0][self.endpoints[0]] + 
epUser_2_European[self.notation][1][self.endpoints[1]]        

#        print 'self.notation = ' + self.notation
#        print 'self.endpoints = ' + self.endpoints
#        print 'self.europeanEndpoints = ' + self.europeanEndpoints

    def __str__(self):
        if self.minPoint == self.maxPoint:
            if self.europeanEndpoints == '[]':
                return '{' + str(self.minPoint) + '}'
            else:
                return 'Empty Set'

        return self.endpoints[0] + str(self.minPoint) + ';' + 
str(self.maxPoint) + self.endpoints[1]

    def isEmpty(self):
        return str(self) == 'Empty Set'

    def __xor__(self, otherInterval):
# The intersection is empty.
        if self.minPoint == self.maxPoint or otherInterval.minPoint == 
otherInterval.maxPoint:
            return Interval(0, 0, endPointsToUser('][', self.notation), 
self.notation)
        
        maxOfminPoints = max(self.minPoint, otherInterval.minPoint)
        minOfmaxPoints = min(self.maxPoint, otherInterval.maxPoint)

        if maxOfminPoints > minOfmaxPoints:
            return Interval(0, 0, endPointsToUser('][', self.notation), 
self.notation)

        if self.minPoint == self.maxPoint or otherInterval.minPoint == 
otherInterval.maxPoint:
            return Interval(0, 0, endPointsToUser('][', self.notation), 
self.notation)

# The intersection could be a set with a single element.
        if minOfmaxPoints == maxOfminPoints:
            if self.maxPoint == minOfmaxPoints:
                if self.europeanEndpoints[1] == '[' or 
otherInterval.europeanEndpoints[0] ==']':
                    return Interval(0, 0, endPointsToUser('][', self.notation), 
self.notation)
                else:
                    return Interval(minOfmaxPoints, minOfmaxPoints, 
endPointsToUser['[]', self.notation], self.notation)

            else:
                if self.europeanEndpoints[0] == ']' or 
otherInterval.europeanEndpoints[1] =='[':
                    return Interval(0, 0, endPointsToUser('][', self.notation), 
self.notation)
                else:
                    return Interval(minOfmaxPoints, minOfmaxPoints, 
endPointsToUser('[]', self.notation), self.notation)

# Wath is the endpoints of the intersection ?
        interEndPtMin = '['
        
        if self.minPoint == maxOfminPoints :
            interEndPtMin = self.europeanEndpoints[0]
            
        if otherInterval.minPoint == maxOfminPoints and interEndPtMin == '[':
            interEndPtMin = otherInterval.europeanEndpoints[0]
        
        interEndPtMax = ']'
        
        if self.maxPoint == minOfmaxPoints :
            interEndPtMax = self.europeanEndpoints[1]
            
        if otherInterval.maxPoint == minOfmaxPoints and interEndPtMax == ']':
            interEndPtMax = otherInterval.europeanEndpoints[1]
        
#        print 'interEndPtMin + interEndPtMax'
#        print interEndPtMin + interEndPtMax
#        print endPointsToUser(interEndPtMin + interEndPtMax, self.notation)
        return Interval(maxOfminPoints, minOfmaxPoints, 
endPointsToUser(interEndPtMin + interEndPtMax, self.notation), self.notation)


    def __contains__(self, x):
        if self.isEmpty():
            return False

        if x == self.minPoint:
            return self.europeanEndpoints[0] =='['
        
        if x == self.maxPoint:
            return self.europeanEndpoints[1] ==']'
        
        if str(self.minPoint) == '-oo':
            return x < self.maxPoint
        elif str(self.maxPoint) == 'oo':
            return x > self.minPoint
        else:
            return self.minPoint < x < self.maxPoint


class UnionIntervals():
    def __init__(self, listIntervals):
        if listIntervals == []:
            self.listIntervals = [Interval(0, 0, '')]
        else:
            self.listIntervals = listIntervals

        self.shortListIntervals = None
# The first notation will be used for the simplified union.
        self.notation = self.listIntervals[0].notation

    def __str__(self):
        if len(self.listIntervals)==1:
            return str(self.listIntervals[0])

        t = str(self.listIntervals[0])
        for i in range(1, len(self.listIntervals)):
            t += ' _u_ ' + str(self.listIntervals[i])

        return t

    def __unionOfTwo(self, interval_1, interval_2):
        """
        intervalle ranbgés
        """
        
        if (interval_1^interval_2).isEmpty() == False :
            minPoint = min(interval_1.minPoint, interval_2.minPoint)
            maxPoint = max(interval_1.maxPoint, interval_2.maxPoint)
        
            if minPoint == interval_1.minPoint:
                if minPoint == interval_2.minPoint:
                    if interval_1.europeanEndpoints[0]==']' and 
interval_2.europeanEndpoints[0]==']':
                        europeanEndpoints = ']'
                    else:
                        europeanEndpoints = '['
                else:
                    europeanEndpoints = interval_1.europeanEndpoints[0]
            else:
                europeanEndpoints = interval_2.europeanEndpoints[0]
        
            if maxPoint == interval_1.maxPoint:
                if maxPoint == interval_2.maxPoint:
                    if interval_1.europeanEndpoints[1]=='[' and 
interval_2.europeanEndpoints[1]=='[':
                        europeanEndpoints += '['
                    else:
                        europeanEndpoints += ']'
                else:
                    europeanEndpoints += interval_1.europeanEndpoints[1]
            else:
                europeanEndpoints += interval_2.europeanEndpoints[1]
        
            return Interval(minPoint, maxPoint, 
endPointsToUser(europeanEndpoints, self.notation), self.notation)
        
        if interval_1.maxPoint == interval_2.minPoint and 
(interval_1.europeanEndpoints[1]==']' or interval_2.europeanEndpoints[0]=='['):
            return Interval(interval_1.minPoint, interval_2.maxPoint, 
endPointsToUser(interval_1.europeanEndpoints[0] + 
interval_2.europeanEndpoints[1], self.notation), self.notation)

        return None

    def simplify(self):
        if self.shortListIntervals <> None :
            return self.shortListIntervals

# We only keep non-empty intervals.
        self.shortListIntervals = []
        for i in range(len(self.listIntervals)):
            if self.listIntervals[i].isEmpty() == False:
                self.shortListIntervals.append(self.listIntervals[i])
        
        if len(self.shortListIntervals) == 1:
            return self.shortListIntervals

# We start by sorting the intervals regarding to their minPoint value.
        self.shortListIntervals.sort(key=lambda x: x.minPoint)

# We can start the simplification.
        i = 0
        while (i < len(self.shortListIntervals)-1):
            newUnion = self.__unionOfTwo(self.shortListIntervals[i], 
self.shortListIntervals[i+1])
            if newUnion==None:
                i+=1
            else:                
                self.shortListIntervals.pop(i)
                self.shortListIntervals[i] = newUnion
                
        return UnionIntervals(self.shortListIntervals)


class IntersectionIntervals():
    def __init__(self, listIntervals):
        if listIntervals == []:
            self.listIntervals = [Interval(0, 0, '')]
        else:
            self.listIntervals = listIntervals

        self.finalIntersection = None
# The first notation will be used for the simplified union.
        self.notation = self.listIntervals[0].notation

    def __str__(self):
        if len(self.listIntervals)==1:
            return str(self.listIntervals[0])

        t = str(self.listIntervals[0])
        for i in range(1, len(self.listIntervals)):
            t += ' _n_ ' + str(self.listIntervals[i])

        return t

    def simplify(self):
        if self.finalIntersection<>None:
            return self.finalIntersection

        if len(self.listIntervals) == 1:    
            self.finalIntersection = self.listIntervals[0]
            return self.finalIntersection
        
        self.finalIntersection = self.listIntervals[0]

        for i in range(1, len(self.listIntervals)):     
            if self.finalIntersection.isEmpty():
                break
            self.finalIntersection = 
self.finalIntersection^self.listIntervals[i]

        return self.finalIntersection

class MixingIntervals():
    def __init__(self, strIntervalsMixed, notation = 'am'):
        self.strIntervalsMixed = strIntervalsMixed
        self.notation = notation
        self.minimalUnion = None
        
    def __str__(self):    
        return self.strIntervalsMixed
    
    def simplify(self):
        if self.minimalUnion <> None:
            return self.minimalUnion

        piecesOfUnions = self.strIntervalsMixed.split('_u_')
        listIntervalsUnion = []
        
        for i in range(len(piecesOfUnions)):
#            print 
#            print 'piecesOfIntersections'
            piecesOfIntersections = piecesOfUnions[i].split('_n_')
            listIntervalsIntersection = []
 
            for j in range(len(piecesOfIntersections)):
                oneInterval = piecesOfIntersections[j].strip()
                endpoints = oneInterval[0] + oneInterval[-1]
                if endpoints=='{}':
                    endpoints='[]'
                    minMax = [oneInterval[1:-1], oneInterval[1:-1]]
                else:
                    minMax = oneInterval[1:-1].split(';')
#                print 'Interval(minMax[0], minMax[1], endpoints, 
self.notation)'
#                print Interval(minMax[0], minMax[1], endpoints, self.notation)
                listIntervalsIntersection.append(Interval(int(minMax[0]), 
int(minMax[1]), endpoints, self.notation))
#            print 'IntersectionIntervals(listIntervalsIntersection).simplify()'
#            print IntersectionIntervals(listIntervalsIntersection).simplify()
            
listIntervalsUnion.append(IntersectionIntervals(listIntervalsIntersection).simplify())

#        print 'listIntervalsUnion'
        for i in range(len(listIntervalsUnion)):
            print listIntervalsUnion[i]

        return UnionIntervals(listIntervalsUnion).simplify()
#!/usr/bin/env python
#coding=utf-8

import simpleSets

listEx = []

listEx.append("""I = simpleSets.Interval(-4, -4, '[[', 'eu')
x = -4""")

listEx.append("""I = simpleSets.Interval(-4, -2, '][', 'eu')
x = -4""")
listEx.append("""I = simpleSets.Interval(-4, -2, '[[', 'eu')
x = -4""")

listEx.append("""I = simpleSets.Interval(-4, 2, ']]', 'eu')
x = 2""")
listEx.append("""I = simpleSets.Interval(-4, 2, '[[', 'eu')
x = 2""")

listEx.append("""I = simpleSets.Interval(-4, 2, '[[', 'eu')
x = 0""")

listEx.append("""I = simpleSets.Interval(-4, 'oo', '[[', 'eu')
x = 155450""")


###########################
# WRITING OF THE EXAMPLES #
###########################

#for i in range(len(examples)):
for i in range(len(listEx)):
    exec(listEx[i])
    for line in listEx[i].splitlines():
        print line

    print '\tI : ' + str(I)
    print '\tx : ' + str(x)
    print '\tx in I : ' + str(x in I)

    print '-'*30
#!/usr/bin/env python
#coding=utf-8

import simpleSets

listEx = []

listEx.append("""M = simpleSets.MixingIntervals('(-5;3)  _n_  [-4;3]  _u_  
(-2;7]  _n_  [-3;13] _u_ {24}')""")

listEx.append("""M = simpleSets.MixingIntervals('(-5;3)  _u_  [-4;3]  _u_  
(4;7]  _u_  [10;13) _u_ {13}')""")


###########################
# WRITING OF THE EXAMPLES #
###########################

#for i in range(len(examples)):
for i in range(len(listEx)):
    exec(listEx[i])
    for line in listEx[i].splitlines():
        print line

    M___SIMPLIFIED = M.simplify()

    print '\tM : ' + str(M)
    print '\tAfter simplification : ' + str(M___SIMPLIFIED)

    
    print '-'*30
#!/usr/bin/env python
#coding=utf-8

import simpleSets

listEx = []

listEx.append("""I = simpleSets.Interval(-5, 3, '(]')
J = simpleSets.Interval(-4,3, '(]')""")
listEx.append("""I = simpleSets.Interval(-5, 3, ']]', 'eu')
J = simpleSets.Interval(-4,3, ']]', 'eu')""")
listEx.append("""I = simpleSets.Interval(-5, 3, '(>', 'cz')
J = simpleSets.Interval(-4,3, '(>', 'cz')""")

listEx.append("""I = simpleSets.Interval(-5, 3, '[]')
J = simpleSets.Interval(-4,3, ']]', 'eu')""")
listEx.append("""I = simpleSets.Interval(-5, 3, '[]', 'eu')
J = simpleSets.Interval(-4,3, ']]', 'eu')""")


###########################
# WRITING OF THE EXAMPLES #
###########################

#for i in range(len(examples)):
for i in range(len(listEx)):
    exec(listEx[i])
    for line in listEx[i].splitlines():
        print line

    I_inter_J = I.intersection(J)
    print '\tI : ' + str(I)
    print '\tJ : ' + str(J)
    print '\tI_inter_J : ' + str(I_inter_J)

    print '-'*30
#!/usr/bin/env python
#coding=utf-8

import simpleSets

listEx = []

listEx.append("""I = simpleSets.Interval(-4, -2, '][', 'eu')
J = simpleSets.Interval(3, 5, ']]', 'eu')""")
listEx.append("""I = simpleSets.Interval(-4, -2, '][', 'eu')
J = simpleSets.Interval(-12, -7, ']]', 'eu')""")

listEx.append("""I = simpleSets.Interval(-4, 3, '][', 'eu')
J = simpleSets.Interval(3, 3, ']]', 'eu')""")
listEx.append("""I = simpleSets.Interval(-4, 3, '][', 'eu')
J = simpleSets.Interval(3, 5, ']]', 'eu')""")

listEx.append("""I = simpleSets.Interval(-4, 3, '[[', 'eu')
J = simpleSets.Interval(3, 5, '[[', 'eu')""")
listEx.append("""I = simpleSets.Interval(3, 5, '[[', 'eu')
J = simpleSets.Interval(-4, 3, '[]', 'eu')""")

listEx.append("""I = simpleSets.Interval(-4, 3, '][', 'eu')
J = simpleSets.Interval(-4, 3, ']]', 'eu')""")
listEx.append("""I = simpleSets.Interval(-4, 3, '[]', 'eu')
J = simpleSets.Interval(-4, 3, '[[', 'eu')""")

listEx.append("""I = simpleSets.Interval(-4, 3, '[]', 'eu')
J = simpleSets.Interval(-4, 5, '[[', 'eu')""")
listEx.append("""I = simpleSets.Interval(-4, 3, ']]', 'eu')
J = simpleSets.Interval(-4, 5, '[[', 'eu')""")
listEx.append("""I = simpleSets.Interval(-5, 3, '[]', 'eu')
J = simpleSets.Interval(-4, 3, '[[', 'eu')""")
listEx.append("""I = simpleSets.Interval(-5, 3, '[]', 'eu')
J = simpleSets.Interval(-4, 3, '[]', 'eu')""")
listEx.append("""I = simpleSets.Interval(-5, 3, '[[', 'eu')
J = simpleSets.Interval(-4, 3, '[]', 'eu')""")

listEx.append("""I = simpleSets.Interval(-5, 3, '(]')
J = simpleSets.Interval(-4, 3, '[]')""")
listEx.append("""I = simpleSets.Interval(-5, 3, '()')
J = simpleSets.Interval(-4, 3, '[]')""")

listEx.append("""I = simpleSets.Interval(9, 14, '[]')
J = simpleSets.Interval(14, 17, '(]')""")
listEx.append("""I = simpleSets.Interval(-4, 3, '[]')
J = simpleSets.Interval(-2, 7, '(]')""")



###########################
# WRITING OF THE EXAMPLES #
###########################

#for i in range(len(examples)):
for i in range(len(listEx)):
    exec(listEx[i])
    for line in listEx[i].splitlines():
        print line

    I_inter_J = I^J
    print '\tI : ' + str(I)
    print '\tJ : ' + str(J)
    print '\tI_inter_J : ' + str(I_inter_J)

    print '-'*30
#!/usr/bin/env python
#coding=utf-8

import simpleSets

listEx = []

listEx.append("""I = simpleSets.Interval(-5, 3, '()')
J = simpleSets.Interval(-4, 3, '[]')
K = simpleSets.Interval(-2, 7, '(]')
L = simpleSets.Interval(-3, 13, '[]')""")


###########################
# WRITING OF THE EXAMPLES #
###########################

#for i in range(len(examples)):
for i in range(len(listEx)):
    exec(listEx[i])
    for line in listEx[i].splitlines():
        print line

    I_inter_J_inter_K_inter_L = simpleSets.IntersectionIntervals([I, J, K, L])
    I_inter_J_inter_K_inter_L___SIMPLIFIED = 
I_inter_J_inter_K_inter_L.simplify()

    print '\tI : ' + str(I)
    print '\tJ : ' + str(J)
    print '\tK : ' + str(K)
    print '\tL : ' + str(L)
    print '\tI_inter_J_inter_K_inter_L : ' + str(I_inter_J_inter_K_inter_L)
    print '\tAfter simplification : ' + 
str(I_inter_J_inter_K_inter_L___SIMPLIFIED)

    
    print '-'*30

Reply via email to