Example #1
0
def _find_root(f, x1, x2, f1=None, f2=None, epsilon=None):
    """Find root of function f between x1,x2 by using the regula falsi method
       with the pegasus modification.
       See also U{http://de.wikipedia.org/wiki/Regula_Falsi}. (The english
       version lacks the description of pegasus modification.)
       The algorithm stops if the error estimation is smaller than epsilon
       or there is an ZeroDivisionError, which means both values f1 and f2 are
       identical (should be 0 then).
       
       @param f: function for which to find M{f(x)=0}
       @type f: M{f(x)}
       @param x1: left border of range
       @type x1: float
       @param x2: right border of range
       @type x2: float
       @param f1: value for x1, if available
       @type f1: float
       @param f2: value for x2, if available
       @type f2: float
       @param epsilon: break condition for algorithm (value < epsilon)
       @type epsilon: float/None
       @return: M{x} where M{f(x)=0}
       @rtype: float
    """
    if f1 is None:
        f1 = f(x1)
    if f2 is None:
        f2 = f(x2)
    if f1 * f2 > 0.:
        raise FuzzyException("need interval with root")
    if epsilon is None:
        epsilon = 1.e-10
    epsx = epsz = epsilon
    z = (x1 + x2) / 2.
    try:
        i = 0
        while i < 1000:
            i += 1
            z = x1 - f1 * (x2 - x1) / (f2 - f1)  # approximation for root
            fz = f(z)

            #print x1,z,x2,f1,fz,f2
            # smaller than epsilon: return z as approximation
            if abs(x2 - x1) <= epsx or abs(fz) <= epsz:
                return z

            # root in [f(xz), f(x2)]?:
            if fz * f2 < 0.:
                # check [z, x2], but exchange borders
                x1, x2, f1, f2 = x2, z, f2, fz
            else:
                # check [x1, z], and modify the value f1,
                # so next steps x1 will move
                x1, x2, f1, f2 = x1, z, f1 * f2 / (f2 + fz), fz
        raise FuzzyException("Too much iterations: %d" % i)
    except ZeroDivisionError:
        #print "ZeroDivisionError"
        return z
Example #2
0
def get_test_params(range_):
    """Get a list of usable values depending of the allowed range for them."""
    for p in __params:
        if p[0] == range_:
            return p[1]
    from fuzzy.Exception import FuzzyException
    raise FuzzyException("No params for range %s defined." % repr(range_))
Example #3
0
def checkRange(value, ranges):
    """Checks if the value is in the defined range.
    
    The range definition is a list/iterator from:
        - float values belonging to the defined range M{x \in {a}}
        - 2-tuples of two floats which define a range not including the tuple values itself M{x \in ]a,b[}
        - 2-list of two floats which define a range including the list values M{x \in [a,b]}
    The order of elements is not important. So could define the set of integer numbers by a
    generator returning the following sequence: M{0,1,-1,2,-2,3-,3,...} .
    
    It returns True if the value is in one of the defined ranges.
    Otherwise it returns false.
    """
    for part in ranges:
        if isinstance(part, float):
            if part == value:
                return True
        elif isinstance(part, list) and len(part) == 2:
            if part[0] <= value and value <= part[1]:
                return True
        elif isinstance(part, tuple) and len(part) == 2:
            if part[0] < value and value < part[1]:
                return True
        else:
            from fuzzy.Exception import FuzzyException
            raise FuzzyException("Range definition is wrong")
    return False
Example #4
0
 def _checkParam(self, value):
     """check parameter if allowed for parameter p
     @param value: the value to be checked 
     @type value: float"""
     from fuzzy.utils import checkRange
     if not checkRange(value, self._range):
         from fuzzy.Exception import FuzzyException
         raise FuzzyException("Parameter value %s is not allowed" %
                              str(value))
Example #5
0
    def getCOG(self):
        """Return center of gravity."""
        if len(self.__points) <= 1:
            #return 0.0
            raise FuzzyException(
                "no COG calculable: single point = constant value")
        if self.__points[0][Polygon.Y] > 0 or self.__points[-1][Polygon.Y] > 0:
            raise FuzzyException(
                "no COG calculable: end points of polygon not y=0.0")
        area = 0.
        COG = 0.

        iterator = iter(self.__points)
        for x0, y0 in iterator:
            # only to initialize x0,y0
            # up to 2.6 one could do this with x0, y0 in iterator.next()
            # but 3.x doesn't support no longer the next() method
            # TODO: But it supports a built-in function next()!
            x0_2 = x0 * x0  # =x²
            x0_3 = x0_2 * x0  # =x³

            # and now use the rest of the iterator
            for x1, y1 in iterator:
                if x1 != x0:  # vertical slopes don't have an area to x.axis
                    x1_2 = x1 * x1
                    x1_3 = x1_2 * x1
                    area += (y0 + y1) / 2.0 * (x1 - x0)  # area of trapezoid
                    # Integral( x*f(x) )
                    COG += y0 / 2.0 * (x1_2 - x0_2) + (y1 - y0) / (x1 - x0) * (
                        x1_3 / 3.0 - x0_3 / 3.0 - x1_2 * x0 / 2.0 + x0_3 / 2.0)
                    x0, x0_2, x0_3 = x1, x1_2, x1_3
                y0 = y1

            # not really necessary as the above for loop should have exhausted the iterator
            break

        if area == 0.0:
            raise FuzzyException("no COG calculable: polygon area is zero!")
        COG /= area
        return COG  # XXX
Example #6
0
def check(x, y1, y2):
    if isinstance(y1, list) and len(y1) == 1:
        y1 = y1[0]
    if isinstance(y1, float) and isinstance(y2, float):
        return [(x, y1, y2)]
    elif isinstance(y1, float) and isinstance(y2, list):
        return [(x, y1, y2_) for y2_ in y2]
    elif isinstance(y1, list) and isinstance(y2, float):
        return [(x, y2_, y1_) for x, y1_, y2_ in check(x, y2, y1)]
    else:
        if len(y1) == len(y2):
            # intersection
            # for all x,y1,y2
            return [(x, y1_, y2_) for y1_, y2_ in zip(y1, y2)]
        elif len(y1) < len(y2):
            if len(y2) > 3:
                raise FuzzyException()
            # only case 2-3 is left
            return [(x, y1[0], y2[0]), (x, y1[1], y2[1]), (x, y1[1], y2[2])]
        else:
            return [(x, y2, y1) for x, y1, y2 in check(x, y2_, y1_)]
Example #7
0
    def compute(self):
        """Compute and set value for given fuzzy adjective."""

        import fuzzy.Adjective
        if isinstance(self.adjective, fuzzy.Adjective.Adjective):
            self.adjective.setMembership(
                                    (self.CER or self._CER)(
                                        self.certainty,       # how sure are we about this rule
                                        self.operator() # value from input
                                    )
                                )
        elif isinstance(self.adjective, list):
            for adj in self.adjective:
                adj.setMembership(
                                    (self.CER or self._CER)(
                                        self.certainty,       # how sure are we about this rule
                                        self.operator() # value from input
                                    )
                                )
        else:
            from fuzzy.Exception import FuzzyException
            raise FuzzyException("rule target not set.")
Example #8
0
 def clear(self):
     """Don't let anyone destroy our triangle."""
     raise FuzzyException()
Example #9
0
 def remove(self, x, where=Polygon.END):
     """Don't let anyone destroy our triangle."""
     raise FuzzyException()
Example #10
0
 def getCOG(self):
     """Return center of gravity."""
     from fuzzy.Exception import FuzzyException
     raise FuzzyException("COG of SFunction uncalculable")
Example #11
0
 def clear(self):
     """Don't let anyone destroy our trapezoid."""
     raise FuzzyException()
Example #12
0
 def add(self, x, y, where=Polygon.END):
     """Don't let anyone destroy our trapezoid."""
     raise FuzzyException()