Example #1
0
def round(value, decimal=None, digits=None):
    value = float(value)
    if digits != None:
        m = pow(10, math.ceil(math.log10(abs(value))))
        return __builtin__.round(value / m, digits) * m

    return __builtin__.round(value, decimal)
Example #2
0
def round_to_error(x, error, latex=False, eng_exp=False, keep_whole=True):
    if not x:
        return '0'
    round_error = round(error, 1)
    error_exp = calc_sci_exp(round_error)
    round_x = __builtin__.round(x * math.pow(10, -1*error_exp)) * math.pow(10, error_exp)
    x_exp = calc_sci_exp(round_x)
    error_digit = '%i' % __builtin__.round(round_error * math.pow(10, -1*error_exp))
    digits = x_exp - error_exp + 1
    if not (x > 1 and keep_whole):
        x = round_x
    if digits == 0:
        digits = 1
        error_digit = error_digit + '0'
    assert digits >= 1
    s = round_to_str(x, digits, latex=False, eng_exp=eng_exp, keep_whole=keep_whole)
    reo = rex.match(s)
    assert reo
    if reo.group(4): # has exponent
        s = '%s(%s)e%s' % (reo.group(1), error_digit, reo.group(4))
        if latex:
            s = latex_sci(s)
    else:
        if error_exp >= 0:
            s = '%s(%i)' % (s, __builtin__.round(error))
        else:
            s = '%s(%s)' % (s, error_digit)
    return s
Example #3
0
def round_to_error(x, error, latex=False, eng_exp=False, keep_whole=True):
    if not x:
        return '0'
    round_error = round(error, 1)
    x_exp = calc_sci_exp(x)
    error_exp = calc_sci_exp(round_error)
    error_digit = '%i' % __builtin__.round(
        round_error * math.pow(10, -1 * error_exp))
    digits = x_exp - error_exp + 1
    if digits == 0:
        digits = 1
    assert digits >= 1
    s = round_to_str(x,
                     digits,
                     latex=False,
                     eng_exp=eng_exp,
                     keep_whole=keep_whole)
    reo = rex.match(s)
    assert reo
    if reo.group(4):  # has exponent
        s = '%s(%s)e%s' % (reo.group(1), error_digit, reo.group(4))
        if latex:
            s = latex_sci(s)
    else:
        if error_exp >= 0:
            s = '%s(%i)' % (s, __builtin__.round(error))
        else:
            s = '%s(%s)' % (s, error_digit)
    return s
Example #4
0
def round(value, decimal=None, digits=None):
    value=float(value)
    if digits != None:
        m = pow(10, math.ceil(math.log10(abs(value))))
        return __builtin__.round(value / m, digits) * m

    return __builtin__.round(value, decimal)
Example #5
0
    def round(value, decimal=7, digits=None):
        """
        ROUND TO GIVEN NUMBER OF DIGITS, OR GIVEN NUMBER OF DECIMAL PLACES
        decimal - NUMBER OF SIGNIFICANT DIGITS (LESS THAN 1 IS INVALID)
        digits - NUMBER OF DIGITS AFTER DECIMAL POINT (NEGATIVE IS VALID)
        """
        if value == None:
            return None
        else:
            value = float(value)

        if digits != None:
            if digits <= 0:
                if value == 0:
                    return int(__builtin__.round(value, digits))
                try:
                    m = pow(10, math.ceil(math.log10(abs(value))))
                    return int(__builtin__.round(value / m, digits) * m)
                except Exception, e:
                    from pyLibrary.debugs.logs import Log

                    Log.error("not expected", e)
            else:
                if value == 0:
                    return __builtin__.round(value, digits)
                try:
                    m = pow(10, math.ceil(math.log10(abs(value))))
                    return __builtin__.round(value / m, digits) * m
                except Exception, e:
                    from pyLibrary.debugs.logs import Log
                    Log.error("not expected", e)
Example #6
0
    def round(value, decimal=7, digits=None):
        """
        ROUND TO GIVEN NUMBER OF DIGITS, OR GIVEN NUMBER OF DECIMAL PLACES
        decimal - NUMBER OF SIGNIFICANT DIGITS (LESS THAN 1 IS INVALID)
        digits - NUMBER OF DIGITS AFTER DECIMAL POINT (NEGATIVE IS VALID)
        """
        if value == None:
            return None
        else:
            value = float(value)

        if digits != None:
            if digits <= 0:
                if value == 0:
                    return int(__builtin__.round(value, digits))
                try:
                    m = pow(10, math.ceil(math.log10(abs(value))))
                    return int(__builtin__.round(value / m, digits) * m)
                except Exception, e:
                    from pyLibrary.debugs.logs import Log

                    Log.error("not expected", e)
            else:
                if value == 0:
                    return __builtin__.round(value, digits)
                try:
                    m = pow(10, math.ceil(math.log10(abs(value))))
                    return __builtin__.round(value / m, digits) * m
                except Exception, e:
                    from pyLibrary.debugs.logs import Log
                    Log.error("not expected", e)
Example #7
0
def round(x, ndigits=0):
    """
    round(number[, ndigits]) - double-precision real number

    Round a number to a given precision in decimal digits (default 0
    digits). If no precision is specified this just calls the element's
    .round() method.

    EXAMPLES::

        sage: round(sqrt(2),2)
        1.41
        sage: q = round(sqrt(2),5); q
        1.41421
        sage: type(q)
        <type 'sage.rings.real_double.RealDoubleElement'>
        sage: q = round(sqrt(2)); q
        1
        sage: type(q)
        <type 'sage.rings.integer.Integer'>
        sage: round(pi)
        3
        sage: b = 5.4999999999999999
        sage: round(b)
        5


    Since we use floating-point with a limited range, some roundings can't
    be performed::

        sage: round(sqrt(Integer('1'*1000)),2)
        +infinity

    IMPLEMENTATION: If ndigits is specified, it calls Python's builtin
    round function, and converts the result to a real double field
    element. Otherwise, it tries the argument's .round() method; if
    that fails, it reverts to the builtin round function, converted to
    a real double field element.

    .. note::

       This is currently slower than the builtin round function, since
       it does more work - i.e., allocating an RDF element and
       initializing it. To access the builtin version do
       ``import __builtin__; __builtin__.round``.
    """
    try:
        if ndigits:
            return RealDoubleElement(__builtin__.round(x, ndigits))
        else:
            try:
                return x.round()
            except AttributeError:
                return RealDoubleElement(__builtin__.round(x, 0))
    except ArithmeticError:
        if not isinstance(x, RealDoubleElement):
            return round(RDF(x), ndigits)
        else:
            raise
Example #8
0
def round(x, ndigits=0):
    """
    round(number[, ndigits]) - double-precision real number

    Round a number to a given precision in decimal digits (default 0
    digits). If no precision is specified this just calls the element's
    .round() method.

    EXAMPLES::

        sage: round(sqrt(2),2)
        1.41
        sage: q = round(sqrt(2),5); q
        1.41421
        sage: type(q)
        <type 'sage.rings.real_double.RealDoubleElement'>
        sage: q = round(sqrt(2)); q
        1
        sage: type(q)
        <type 'sage.rings.integer.Integer'>
        sage: round(pi)
        3
        sage: b = 5.4999999999999999
        sage: round(b)
        5


    Since we use floating-point with a limited range, some roundings can't
    be performed::

        sage: round(sqrt(Integer('1'*1000)),2)
        +infinity

    IMPLEMENTATION: If ndigits is specified, it calls Python's builtin
    round function, and converts the result to a real double field
    element. Otherwise, it tries the argument's .round() method; if
    that fails, it reverts to the builtin round function, converted to
    a real double field element.

    .. note::

       This is currently slower than the builtin round function, since
       it does more work - i.e., allocating an RDF element and
       initializing it. To access the builtin version do
       ``import __builtin__; __builtin__.round``.
    """
    try:
        if ndigits:
            return RealDoubleElement(__builtin__.round(x, ndigits))
        else:
            try:
                return x.round()
            except AttributeError:
                return RealDoubleElement(__builtin__.round(x, 0))
    except ArithmeticError:
        if not isinstance(x, RealDoubleElement):
            return round(RDF(x), ndigits)
        else:
            raise
Example #9
0
def round_std(x, std, sig=1):
    '''
    Round float x and uncertainty sigma to the significant digits sig of sigma.
    '''
    n = num_digits(std)
    if n == 0:
        n = num_digits(x)
    return __builtin__.round(x,
                             sig - n - 1), __builtin__.round(std, sig - n - 1)
Example #10
0
def generate_hex(edge_length, offset):
    '''Generator for coordinates in a hexagon.'''
    coords = []
    x, y = offset
    coords.append([x, y])
    for angle in range(0, 360, 60):
        x += round(math.cos(math.radians(angle)) * edge_length, 1)
        y += round(math.sin(math.radians(angle)) * edge_length, 1)
        coords.append([x, y])

    coords.append([offset])
    return coords
Example #11
0
def round(x, ndigits=0):
    """
    round(number[, ndigits]) - double-precision real number
    
    Round a number to a given precision in decimal digits (default 0
    digits). This always returns a real double field element.
    
    EXAMPLES::
    
        sage: round(sqrt(2),2)
        1.41
        sage: round(sqrt(2),5)
        1.41421
        sage: round(pi)
        3.0
        sage: b = 5.4999999999999999
        sage: round(b)
        5.0
    
    Since we use floating-point with a limited range, some roundings can't
    be performed::
    
        sage: round(sqrt(Integer('1'*500)))
        Traceback (most recent call last):
        ...
        OverflowError: cannot convert float infinity to long
    
    IMPLEMENTATION: If ndigits is specified, it calls Python's builtin
    round function, and converts the result to a real double field
    element. Otherwise, it tries the argument's .round() method, and if
    that fails, it falls back to the builtin round function.
    
    .. note::

       This is currently slower than the builtin round function, since
       it does more work - i.e., allocating an RDF element and
       initializing it. To access the builtin version do
       ``import __builtin__; __builtin__.round``.
    """
    try:
        if ndigits:
            return RealDoubleElement(__builtin__.round(x, ndigits))
        else:
            try:
                return RealDoubleElement(x.round())
            except AttributeError:
                return RealDoubleElement(__builtin__.round(x, 0))
    except ArithmeticError:
        if not isinstance(x, RealDoubleElement):
            return round(RDF(x), ndigits)
        else:
            raise
Example #12
0
    def round(value, decimal=0, digits=None):
        """
        ROUND TO GIVEN NUMBER OF DIGITS, OR GIVEN NUMBER OF DECIMAL PLACES
        decimal - NUMBER OF SIGNIFICANT DIGITS (LESS THAN 1 IS INVALID)
        digits - NUMBER OF DIGITS AFTER DECIMAL POINT (NEGATIVE IS VALID)
        """
        if value == None:
            return None

        if digits != None:
            m = pow(10, math.ceil(math.log10(value)))
            return __builtin__.round(value / m, digits) * m

        return __builtin__.round(value, decimal)
Example #13
0
    def paint_text(self):
        facesize = round(self.plot.axis_title_font_size *
                         self.plot.magnification)
        margin = self.plot.axis_title_font_size * 0.3514598 / 6.
        self._margin = margin

        if self.position == 'bottom':
            tics = self.tics(self.plot.xmin, self.plot.xmax)[0]
            h = []
            for x in tics:
                st = self.totex(x)
                xm, _ = self.plot.data_to_phys(x, 0.)
                _, height = self.plot.textpainter.render_text(
                    st, facesize, 0, 0, measure_only=True)
                h.append(height)

            for x in tics:
                st = self.totex(x)
                xm, _ = self.plot.data_to_phys(x, 0.)
                self.plot.textpainter.render_text(st, facesize, xm,
                                                  -margin - max(h), 'center',
                                                  'bottom')
                self._bottommargin = -margin - max(h)

        elif self.position == 'left':
            for y in self.tics(self.plot.ymin, self.plot.ymax)[0]:
                st = self.totex(y)
                _, ym = self.plot.data_to_phys(0., y)
                self.plot.textpainter.render_text(st, facesize, -margin, ym,
                                                  'right', 'center')
Example #14
0
    def render_text_chunk_normal(self, text, size, orientation='h'):
        fonte = ImageFont.FreeTypeFont(FONTFILE, int(round(size)))
        w, h = fonte.getsize(text)
        ascent, descent = fonte.getmetrics()
        origin = h - ascent
        if self.plot.ps:
            origin = 0
        if orientation == 'v': 
            ww, hh, angle = h, w, 90.0
        else: 
            ww, hh, angle = w, h, 0.0

        def renderer(x, y):
            if self.plot.ps:
                glColor4f(0, 0, 0, 1)
                glRasterPos2d(x, y)
                font = FT2Font(str(FONTFILE))
                fontname = font.postscript_name
                gl2ps_TextOpt(text, fontname, size, GL2PS__TEXT_BL, angle)
            else:
                image = Image.new('L', (w, h), 255)
                ImageDraw.Draw(image).text((0, 0), text, font=fonte)
                image = image.transpose(Image.FLIP_TOP_BOTTOM)
                if orientation == 'v':
                    image = image.transpose(Image.ROTATE_270)
                glRasterPos2d(x, y)
#                ww, wh = image.size
                glDrawPixels(ww, hh, GL_LUMINANCE, GL_UNSIGNED_BYTE, image.tostring())

        return ww, hh, origin, renderer
Example #15
0
 def parse_polygon(self, polygon):
     zu = []
     print polygon
     for ring in polygon:
         list_ponts = []
         for node in ring:
             # Тут происходит переход к геодезической СК
             point = node
             x = round(point.y(), 2)
             y = round(point.x(), 2)
             name = u""
             for pointfeature in self.pointLayer.getFeatures():
                 if pointfeature.geometry().equals(
                         QgsGeometry.fromPoint(QgsPoint(node.x(),
                                                        node.y()))):
                     name += unicode(pointfeature.attribute(u'name'))
             list_ponts.append([x, y, name])
             print str(x) + ";" + str(y)
         zu.append(list_ponts)
     self.zu_multi.append(zu)
def num_to_byte(number):
    if not isinstance(number, int):
        number = round(number, 4)
    byt = []
    for letter in str(number):
        if letter == '.':
            byt.append(46)
        elif letter == '-':
            byt.append(45)
        else:
            byt.append(int(letter) + 48)
    return bytearray(byt)
Example #17
0
def round_to_str(x, digits, latex=False, eng_exp=False, keep_whole=False):
    e = calc_sci_exp(x)
    s = ''
    if e + 1 >= digits and keep_whole:  # all sig digs are whole numbers
        s = str(int(__builtin__.round(x)))
    else:
        s = '%.*e' % (digits - 1, x)  # does rounding
        if eng_exp and abs(e) >= 3:
            # shift digits for exponent to be multiple of 3
            rmd_e = e % 3
            if rmd_e:
                div_e = e // 3
                new_e = '%0+3i' % (3 * div_e)
                reo = rex.match(s)
                assert reo
                left = reo.group(2)
                right = reo.group(3)
                len_right = len(right)
                if len_right > rmd_e:
                    left += right[:rmd_e]
                    right = right[rmd_e:]
                else:
                    left += right + '0' * (rmd_e - len_right)
                    right = ''
                if right:
                    s = '%s.%se%s' % (left, right, new_e)
                else:
                    s = '%se%s' % (left, new_e)
        else:
            s = '%g' % float(s)
        # append significant zeros
        dig_count = 0
        has_started = False
        for c in s:
            if not has_started and c.isdigit() and c != '0':
                has_started = True
            if has_started:
                if c == 'e': break
                if c.isdigit(): dig_count += 1
        if dig_count < digits:
            s_list = s.split('e')
            assert 1 <= len(s_list) <= 2
            if s_list[0].count('.'):
                s_list[0] += '0' * (digits - dig_count)
            else:
                s_list[0] += '.' + '0' * (digits - dig_count)
            if len(s_list) == 2:
                s_list[1] = 'e' + s_list[1]
            s = ''.join(s_list)
    if latex:
        s = latex_sci(s)
    return s
Example #18
0
def comma(value):
    """
    FORMAT WITH THOUSANDS COMMA (,) SEPARATOR
    """
    try:
        if float(value) == __builtin__.round(float(value), 0):
            output = "{:,}".format(int(value))
        else:
            output = "{:,}".format(float(value))
    except Exception:
        output = _unicode(value)

    return output
Example #19
0
def percent(value, decimal=None, digits=None, places=None):
    value = float(value)
    if value == 0.0:
        return "0%"

    digits = coalesce(digits, places)
    if digits != None:
        left_of_decimal = int(math.ceil(math.log10(abs(value)))) + 2
        decimal = digits - left_of_decimal

    decimal = coalesce(decimal, 0)
    right_of_decimal = max(decimal, 0)
    format = "{:." + _unicode(right_of_decimal) + "%}"
    return format.format(__builtin__.round(value, decimal + 2))
Example #20
0
 def prepare_data(self):
     # Создаётся на один объект
     nameidx = self.pointLayer.fieldNameIndex('name')
     if len(self.features) > 1:
         self.multi = True
         for feat in self.features:
             geom = feat.geometry()
             gt = QgsGeometry(geom)
             gt.transform(self.transform)
             self.names.append(feat.attributes()[nameidx])
             self.area.append(round(gt.area(), 0))
             self.perimeter.append(round(gt.length(), 2))
             #self.zu = []
             self.parse_polygon(geom.asMultiPolygon()[0])
     else:
         # #print(len(self.features))
         # geom = self.features[0].geometry()
         # self.names.append(self.features[0].attributes()[nameidx])
         # if self.isMultiPart(self.features[0]):
         #     self.multi = True
         #     multiGeom = geom.asMultiPolygon()
         #     for i in multiGeom:
         #         poly = QgsGeometry().fromPolygon(i)
         #         gt = QgsGeometry(poly)
         #         gt.transform(self.transform)
         #         #print str(poly.area())
         #         self.area.append(round(gt.area(), 0))
         #         self.perimeter.append(round(gt.length(), 2))
         #         self.zu = []
         #         #print poly
         #         self.parse_polygon(poly.asPolygon())
         # else:
         geom = self.features[0].geometry()
         gt = QgsGeometry(geom)
         self.area.append(round(gt.area(), 0))
         self.perimeter.append(round(gt.length(), 2))
         self.parse_polygon(geom.asMultiPolygon()[0])
Example #21
0
    def paint_text(self):
        facesize = round(self.plot.axis_title_font_size *
                         self.plot.magnification)

        if self.position == 'bottom':
            tics = self.tics(self.plot.xmin, self.plot.xmax)[0]
            for x in tics:
                st = self.totex(x)
                xm, _ = self.plot.data_to_phys(x, 0.)
                self.plot.textpainter.render_text(st, facesize, xm, -5,
                                                  'center', 'bottom')
        elif self.position == 'left':
            for y in self.tics(self.plot.ymin, self.plot.ymax)[0]:
                st = self.totex(y)
                _, ym = self.plot.data_to_phys(0., y)
                self.plot.textpainter.render_text(st, facesize, -2, ym,
                                                  'right', 'center')
Example #22
0
 def paint_title(self):
     facesize = round(self.plot.axis_title_font_size *
                      self.plot.magnification)
     if self.position == 'bottom':
         self.plot.textpainter.render_text(self.plot.xtitle,
                                           facesize,
                                           self.plot.plot_width / 2,
                                           -facesize / 2.,
                                           align_x='center',
                                           align_y='top')
     elif self.position == 'left':
         self.plot.textpainter.render_text(self.plot.ytitle,
                                           facesize,
                                           -facesize / 2. - self.plot.ticw,
                                           self.plot.plot_height / 2,
                                           align_x='right',
                                           align_y='center',
                                           orientation='v')
Example #23
0
def round(value, decimal=None, digits=None, places=None):
    """
    :param value:  THE VALUE TO ROUND
    :param decimal: NUMBER OF DECIMAL PLACES TO ROUND (NEGATIVE IS LEFT-OF-DECIMAL)
    :param digits: ROUND TO SIGNIFICANT NUMBER OF digits
    :param places: SAME AS digits
    :return:
    """
    value = float(value)
    if value == 0.0:
        return "0"

    digits = coalesce(digits, places)
    if digits != None:
        left_of_decimal = int(math.ceil(math.log10(abs(value))))
        decimal = digits - left_of_decimal

    right_of_decimal = max(decimal, 0)
    format = "{:." + _unicode(right_of_decimal) + "f}"
    return format.format(__builtin__.round(value, decimal))
Example #24
0
def round(x, d=0):
    """
    Compatible round which act the same behaviour in Python3.

    Args:
        x(float) : The number to round halfway.

    Returns:
        round result of x
    """
    if six.PY3:
        # The official walkaround of round in Python3 is incorrect
        # we implement according this answer: https://www.techforgeek.info/round_python.html
        if x > 0.0:
            p = 10**d
            return float(math.floor((x * p) + math.copysign(0.5, x))) / p
        elif x < 0.0:
            p = 10**d
            return float(math.ceil((x * p) + math.copysign(0.5, x))) / p
        else:
            return math.copysign(0.0, x)
    else:
        import __builtin__
        return __builtin__.round(x, d)
Example #25
0
def round(x):
    """Rounds the given number to a globally constant precision."""
    return __builtin__.round(x, this._precision_digits)
Example #26
0
    def round(value, decimal=None, digits=None):
        if digits != None:
            m = pow(10, math.floor(math.log10(digits)))
            return __builtin__.round(value / m, digits) * m

        return __builtin__.round(value, decimal)
Example #27
0
def round(x, digits):
    assert isinstance(digits, int)
    assert digits > 0
    e = calc_sci_exp(x)
    return __builtin__.round(x / float(pow(10, e + 1)), digits) * pow(
        10, e + 1)
Example #28
0
    def render_text_chunk_tex(self, text, size, orientation='h', cache={}):
        """Render a text chunk using mathtext"""
        size = int(round(size))
#        if (text, size, orientation) in cache and not self.plot.ps:
#            ww, hh, origin, listno =  cache[text, size, orientation]
#            def renderer(x, y):
#                glRasterPos2d(x, y)
#                glCallList(listno)
#            return ww, hh, origin, renderer
        
        if self.plot.ps:
            w, h, _, pswriter = mathtext.math_parse_s_ps(text, 75, size)
            origin = 0
        else:
            w, h, origin, fonts = mathtext.math_parse_s_ft2font(text, 75, size)

        if orientation == 'v': 
            ww, hh, angle = h, w, 90
        else: 
            ww, hh, angle = w, h, 0

        def renderer(x, y):
            if self.plot.ps:
                txt = pswriter.getvalue()
                ps = "gsave\n%f %f translate\n%f rotate\n%s\ngrestore\n" \
                        % ((self.plot.marginl+x)*self.plot.res,
                           (self.plot.marginb+y)*self.plot.res, 
                           angle, txt)
                self.plot.pstext.append(ps)
            else:
                w, h, imgstr = fonts[0].image_as_str()
                N = w*h
                Xall = zeros((N,len(fonts)), dtype=UnsignedInt8)

                for i, f in enumerate(fonts):
                    if orientation == 'v':
                        f.horiz_image_to_vert_image()
                    w, h, imgstr = f.image_as_str()
                    Xall[:,i] = fromstring(imgstr, UnsignedInt8)

                Xs = mlab.max(Xall, 1)
                Xs.shape = (h, w)

                pa = zeros(shape=(h,w,4), dtype=UnsignedInt8)
                rgb = (0., 0., 0.)
                pa[:,:,0] = int(rgb[0]*255)
                pa[:,:,1] = int(rgb[1]*255)
                pa[:,:,2] = int(rgb[2]*255)
                pa[:,:,3] = Xs[::-1]

                data = pa.tostring()

                # clear cache
                if len(cache) >= 20:
                    for key, value in cache.iteritems():
                        _, _, _, listno = value
                        glDeleteLists(listno, 1)
                    cache.clear()

#                listno = glGenLists(1)
                glRasterPos2d(x, y)
#                glNewList(listno, GL_COMPILE)
                glDrawPixels(w, h, GL_RGBA, GL_UNSIGNED_BYTE, data)
#                glEndList()
#                glCallList(listno)
#                cache[text, size, orientation] = ww, hh, origin, listno

        return ww, hh, origin, renderer
Example #29
0
 def calclenght(self):
     a = math.pow(self.ddx, 2)
     b = math.pow(self.ddy, 2)
     self.len = math.sqrt(a + b)
     self.lenght = u'{0:.2f}'.format(round(self.len, 2))
Example #30
0
 def round(x):
     import __builtin__
     return int(__builtin__.round(float(x)))
Example #31
0
        if value == None:
            return None
        else:
            value = float(value)

        if digits != None:
            if value == 0:
                return __builtin__.round(value, digits)
            try:
                m = pow(10, math.ceil(math.log10(abs(value))))
                return __builtin__.round(value / m, digits) * m
            except Exception, e:
                from pyLibrary.debugs.logs import Log
                Log.error("not expected", e)

        return __builtin__.round(value, decimal)

    @staticmethod
    def floor(value, mod=1):
        """
        x == floor(x, a) + mod(x, a)  FOR ALL a
        """
        if value == None:
            return None
        v = int(math.floor(value))
        return v - (v % mod)

    # RETURN A VALUE CLOSE TO value, BUT WITH SHORTER len(unicode(value))<len(unicode(value)):
    @staticmethod
    def approx_str(value):
        v = unicode(value)
Example #32
0
def round(x, sig=1):
    '''
    Round float x to the significant digits sig.
    '''
    return __builtin__.round(x, sig - num_digits(x) - 1)
Example #33
0
def round(a, ndigits=1):
    return (__builtin__.round(a[0], ndigits), __builtin__.round(a[1], ndigits))
Example #34
0
    def MATSCORE(self, group = '', BandWidth=300, short = 0, pair = '', var = 0, replicate = 0):
        '''MATSCORE(group = '', BandWidth=300, short = 0, pair = '', var = 0, replicate = 0):
        return self.matscore and/or self.matscore_m (The first nTreat columns are Treat data)
        BandWidth[optional]: BandWidth, default 300 bp, the total window will be 2*BandWidth
        short[optional]: minimum number of probes to get the trimmed mean, default is \
        half probes within the window. The matscore will be set to 0 if #probes < short.
        pair[optional]: subtract control from the treat at the t-value level
        var[optional]: control the input variance, divide sd(input) in MATScore, default no.
        replicate[optional]: set the replicate to 1 for matscore of each replicate self.matscore_m, default is 0 (no)
        '''

        # reading Position and Chr if necessary
        if len(self.Position) == 0:
            self.Read(1, 'Chr', 'Position')
            self.bpmap.Close()

        # reading .mat files to get the final self.ndat
        if self.cels.iscel.any():    # read the raw cel files
            ndat = zeros((self.cels.nintensity, self.Position.shape[0]),dtype=float)
            ndat[self.cels.iscel] = transpose(self.ndat)
            ndat[self.cels.iscel == False] = self.cels.ReadTvalue()
            self.ndat = ndat
        else:
            self.ndat = self.cels.ReadTvalue()

        # init
        print >> sys.stderr, "Making MAT score", time.asctime()
        print >> sys.stderr, "Control Input Variance : ", var
        self.trim = 0.1
        self.var = var
        start = time.clock()
        self.short = short
        if not short:
            self.short = int(round(BandWidth / 35.))
        self.BandWidth = BandWidth
        self.pair = pair
        # if not group, treat every cel as treatment
        if len(group) == 0:
            group = ones(self.ndat.shape[0],dtype=bool)
        self.group = group
        # subtract control from the treat at the t-value level
        if pair:
            self.ndat[group == True] = self.ndat[group == True] - self.ndat[group == False]

        nTreat = sum(group == True)
        nContr =  sum(group == False)
        Treat = ravel(transpose(self.ndat[group == True])).tolist()
        Control = ravel(transpose(self.ndat[group == False])).tolist()
        self.ndat.transpose()
        self.matscore = zeros(self.Position.shape,dtype=float)
        self.foldchange = zeros(self.Position.shape,dtype=float)
        matscoreTreat = zeros(self.Position.shape,dtype=float)
        if nContr > 0 and not self.pair:
            matscoreControl = zeros(self.Position.shape,dtype=float)
            ControlVar = ones(self.Position.shape,dtype=float)
        if replicate:
            self.matscore_m = zeros((self.Position.shape[0], nTreat + nContr),dtype=float)

        nhits = 0           # number of total hits
        for ichr, chr in enumerate(self.ChrInd):
            st, end = 0, 0                 # start, end of the sliding window [st, end) < win
            Position = self.Position[self.Chr == ichr]
            for i, pos in enumerate(Position):
                while((pos - Position[st]) > BandWidth):
                    st += 1
                while((Position[end] - pos) < BandWidth and end < Position.shape[0] - 1):
                    end += 1
                # minimum probe numbers
                if (end - st) < self.short:
                    continue

                # treats
                window = sorted(Treat[nTreat*(st+nhits): nTreat*(end+nhits)])
                bound = int(round(len(window) * self.trim))       # boundary for trimmed mean
                if  bound:
                    window = window[bound: -bound]
                mean_win = suml(window)/len(window)
                TreatSqrtlen = math.sqrt(len(window))
                matscoreTreat[i + nhits] = mean_win * TreatSqrtlen
                self.foldchange[i + nhits] = mean_win

                if replicate:
                    for irep in range(nTreat):
                        window = sorted(Treat[nTreat*(st+nhits) + irep : nTreat*(end+nhits) : nTreat])
                        bound = int(round(len(window) * self.trim))       # boundary for trimmed mean
                        if  bound:
                            window = window[bound: -bound]
                        mean_win = suml(window) / len(window)
                        self.matscore_m[i + nhits][irep] = mean_win * TreatSqrtlen  # use the pool treat sqrtlen

                # if controls and not pair
                if nContr > 0 and not self.pair:
                    window = sorted(Control[nContr*(st+nhits) : nContr*(end+nhits)])
                    bound = int(round(len(window) * self.trim))       # boundary for trimmed mean
                    if  bound:
                        window = window[bound: -bound]
                    mean_win = suml(window)/len(window)
                    sqrtlen = math.sqrt(len(window))
                    matscoreControl[i + nhits] = mean_win * sqrtlen
                    self.foldchange[i + nhits] -=  mean_win
                    # control the input variance,
                    if var:
                        ControlVar[i + nhits] = sd(window)

                    if replicate:
                        for irep in range(nContr):
                            window = sorted(Control[nContr*(st+nhits) + irep : nContr*(end+nhits) : nContr])
                            bound = int(round(len(window) * self.trim))
                            if  bound:
                                window = window[bound: -bound]
                            mean_win = suml(window)/len(window)
                            self.matscore_m[i + nhits][irep+ nTreat] = mean_win * TreatSqrtlen   # use the treat pool sqrtlen

                if i % 100000 == 0:
                    print >> sys.stderr, i, chr, time.clock() - start
            nhits += Position.shape[0]

        # re-scale matscore to get the same variance
        if nContr > 0 and not self.pair:
            ControSigmahat =  self.NULLDIST(matscoreControl)[1]
            ScaleFactor = self.NULLDIST(matscoreTreat)[1] /ControSigmahat
            ControlVar += 0.15 * ControSigmahat
            self.matscore = (matscoreTreat - matscoreControl * ScaleFactor)
            if var:
                self.matscore /= ControlVar
            self.mhat, self.sigmahat = self.NULLDIST(self.matscore)
            if replicate:
                matscoreControl.resize(matscoreControl.shape[0], 1)   # numpy returns None, not array copy
                self.matscore_m -= matscoreControl * ScaleFactor
                if var:
                    ControlVar.resize(ControlVar.shape[0], 1)         # numpy returns None, not array copy
                    self.matscore_m /= ControlVar
        else:
            self.matscore = matscoreTreat
            self.mhat, self.sigmahat = self.NULLDIST(self.matscore)