Python math.abs() Examples

The following are code examples for showing how to use math.abs(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: exomerge   Author: timkostka   File: exomerge.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _transform_eval_expression(expression, variable_names):
        """Transform a string expression into one usable by eval."""
        eval_expression = ' %s ' % expression
        for name in variable_names:
            eval_expression = re.sub('([^a-zA-Z0-9_])%s([^a-zA-Z0-9_])' % name,
                                     r"\1var['%s']\2" % name,
                                     eval_expression)
        # add "math." to supported mathematical functions
        # Note: abs is a built-in function, it is not math.abs
        for name in ['atan', 'sinh', 'cosh', 'tanh', 'exp',
                     'sqrt', 'sin', 'cos', 'tan']:
            eval_expression = re.sub('([^a-zA-Z0-9_])%s([^a-zA-Z0-9_])' % name,
                                     r'\1math.%s\2' % name,
                                     eval_expression)
        # convert powers to from "^" to "**" format
        eval_expression = re.sub(r'\^', '**', eval_expression)
        return eval_expression.strip() 
Example 2
Project: exomerge   Author: timkostka   File: exomerge.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_length_scale(self):
        """
        Return the length scale of the model.

        The length scale is defined as the largest of the following:
        * absolute nodal coordinate component
        * total range in nodal coordinate component

        Example:
        >>> model.get_length_scale()

        """
        if not self.nodes:
            return 0.0
        bounds = [[self.nodes[0][d], self.nodes[0][d]]
                  for d in range(3)]
        for node in self.nodes:
            for d in xrange(3):
                if node[d] < bounds[d][0]:
                    bounds[d][0] = node[d]
                if node[d] > bounds[d][1]:
                    bounds[d][1] = node[d]
        relative = max([bound[1] - bound[0] for bound in bounds])
        absolute = max([abs(x) for x in bound for bound in bounds])
        return max(relative, absolute) 
Example 3
Project: PythonBlocks   Author: go2net   File: BlockShape.py    MIT License 6 votes vote down vote up
def appendConnectorOffset(self,gp, topPoint, botPoint,
        blockConnector, aboveConnector):

        # if top and bottom are equal, then no offset necessary
        if(topPoint.x() == botPoint.x()): return;

        # if top further right than bottom, then Xdiff is positive
        Xdiff = topPoint.x() - botPoint.x();
        # absolute distance
        Ydiff = math.abs(topPoint.y() - botPoint.y());


        # check to only offset correctly above or below the connector:
        # offset only above connectors on right slanting sides
        if(Xdiff > 0 and not aboveConnector) : return;
        # offset only below connectors on left slanting sides
        if(Xdiff < 0 and    aboveConnector): return;

        # get fraction by dividing connector height by total height of the side
        fraction = BlockConnectorShape.getConnectorDimensions(blockConnector).getHeight()/Ydiff;
        insetDist = Xdiff * fraction;

        # if top further out, then inset left - else move right
        BlockShapeUtil.lineToRelative(gp, -insetDist, 0); 
Example 4
Project: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 5 votes vote down vote up
def keydown(key):
    # move paddles
    for each in (player1, player2):
        each.add_force(each.controls.get(chr(key), [0, 0]))
    # throw the ball
    if chr(key) == " ":
        angle = random.random() * 3.142 * 0.333  # [0-60] gradians
        force = [math.abs(math.cos(angle)) * side, -math.abs(math.sin(angle))]
        ball.add_force(force) 
Example 5
Project: jingtum-lib-python   Author: swtcpro   File: tum_amount.py    MIT License 5 votes vote down vote up
def parse_tum_value(self, j):
        self._is_native = False
        if isinstance(j, (int, float)):
            self._is_negative = j < 0
            self._value = math.abs(j)
            self._offset = 0
            self.canonicalize()

        elif isinstance(j, str):
            i = re.match('^ (-?)(\d +)$' ,j)
            d = not i and re.match('^(-?)(\d*)\.(\d*)$',j)
            e = not d and re.match('^(-?)(\d*)e(-?\d+)$',j) #? !e

            if e:
                # e notation
                self._value = e[2]  # BigInteger(e[2])
                self._offset = int(e[3])
                self._is_negative = e[1]
            elif d:
                # float notation
                precision = len(d[3])
                #self._value = # integer.multiply(Amount.bi_10.clone().pow(precision)).add(fraction)
                self._offset = -precision
                self._is_negative = d[1]
            elif i:
                # integer notation
                self._value = i[2] #  BigInteger(i[2])
                self._offset = 0
                self._is_negative = i[1]
            else:
                self._value = None

        else:
            self._value = None

        return self

    # Convert the internal obj to JSON 
Example 6
Project: microbit_python   Author: whaleygeek   File: paintroller.py    MIT License 5 votes vote down vote up
def play_game():
    count_dots = 0
    x = 2
    y = 2
    xdir = True
    display.clear()
    start_time = running_time
    prev_compass = compass.heading()
    
    while count_dots < 25 and running_time - start_time < MAX_GAME_TIME:
        #TODO: was_shake: get from gestures
        if was_shake:
            display.show(ROLLER_MOVE)
            r = random.randrange(5)
            if xdir:
                if display.get_pixel(r, y) == 0:
                    display.set_pixel(r, y, 9)
                    count_dots += 1
            else: # must be ydir
                if display.get_pixel(x, r) == 0:
                    display.set_pixel(x, r, 9)
                    count_dots += 1
                    
        h = compass.get_heading()
        if math.abs(h - prev-compass) > 60:
            xdir = not xdir
            prev_compass = h
            if xdir:
                x = random.randrange(5)
            else:
                y = random.randrange(5) 
Example 7
Project: VerifAI   Author: BerkeleyLearnVerify   File: features.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def distance(self, pointA, pointB):
        return math.abs(pointA - pointB) 
Example 8
Project: VerifAI   Author: BerkeleyLearnVerify   File: features.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def distance(self, pointA, pointB):
        return math.abs(pointA - pointB) 
Example 9
Project: PostTelemac   Author: Artelia   File: geometry.py    GNU General Public License v3.0 5 votes vote down vote up
def isClose( p1,p2,size=5 ):

   if ( p2 == [] or p1 == [] ): return False
   s = 1.e-5 + abs(max(p1)+max(p2))
   accuracy = np.power(10.0, -size+np.floor(np.log10(s)))

   return getNorm2( p1[0:2],p2[0:2] ) < accuracy

# _____             ________________________________________________
# ____/ MAIN CALL  /_______________________________________________/
# 
Example 10
Project: PostTelemac   Author: Artelia   File: geometry.py    GNU General Public License v3.0 5 votes vote down vote up
def isClose( p1,p2,size=5 ):

   if ( p2 == [] or p1 == [] ): return False
   s = 1.e-5 + abs(max(p1)+max(p2))
   accuracy = np.power(10.0, -size+np.floor(np.log10(s)))

   return getNorm2( p1[0:2],p2[0:2] ) < accuracy

# _____             ________________________________________________
# ____/ MAIN CALL  /_______________________________________________/
# 
Example 11
Project: DeepPavlov   Author: deepmipt   File: network.py    Apache License 2.0 5 votes vote down vote up
def load_params(self):
        path = str(self.load_path.with_suffix('.json').resolve())
        log.info('[loading parameters from {}]'.format(path))
        with open(path, 'r', encoding='utf8') as fp:
            params = json.load(fp)
        for p in self.GRAPH_PARAMS:
            if self.opt.get(p) != params.get(p):
                if p in ('kb_embedding_control_sum') and \
                        (math.abs(self.opt.get(p, 0.) - params.get(p, 0.)) < 1e-3):
                    continue
                raise ConfigError("`{}` parameter must be equal to saved model"
                                  " parameter value `{}`, but is equal to `{}`"
                                  .format(p, params.get(p), self.opt.get(p))) 
Example 12
Project: insightface   Author: deepinsight   File: data.py    MIT License 4 votes vote down vote up
def next_sample(self):
        """Helper function for reading in next sample."""
        #set total batch size, for example, 1800, and maximum size for each people, for example 45
        if self.seq is not None:
          while True:
            if self.cur >= len(self.seq):
                raise StopIteration
            idx = self.seq[self.cur]
            self.cur += 1
            if self.imgrec is not None:
              s = self.imgrec.read_idx(idx)
              header, img = recordio.unpack(s)
              label = header.label
              if self.output_c2c:
                count = self.idx2flag[idx]
                if self.output_c2c==1:
                  v = np.random.uniform(0.4, 0.5)
                elif self.output_c2c==2:
                  v = np.random.uniform(0.4, 0.5)
                  if count>=self.output_c2c:
                    v = np.random.uniform(0.3, 0.4)
                elif self.output_c2c==3:
                  v = (9.5 - math.log(2.0+count))/10.0
                  v = min(max(v, 0.3), 0.5)
                elif self.output_c2c==4:
                  mu = 0.0
                  sigma = 0.1
                  mrange = [0.4,0.5]
                  v = numpy.random.normal(mu, sigma)
                  v = math.abs(v)*-1.0+mrange[1]
                  v = max(v, mrange[0])
                elif self.output_c2c==5:
                  v = np.random.uniform(0.41, 0.51)
                  if count>=175:
                    v = np.random.uniform(0.37, 0.47)
                elif self.output_c2c==6:
                  v = np.random.uniform(0.41, 0.51)
                  if count>=175:
                    v = np.random.uniform(0.38, 0.48)
                else:
                  assert False

                label = [label, v]
              else:
                if not isinstance(label, numbers.Number):
                  label = label[0]
              return label, img, None, None
            else:
              label, fname, bbox, landmark = self.imglist[idx]
              return label, self.read_image(fname), bbox, landmark
        else:
            s = self.imgrec.read()
            if s is None:
                raise StopIteration
            header, img = recordio.unpack(s)
            return header.label, img, None, None 
Example 13
Project: face-recognition--summary   Author: 994374821   File: data.py    MIT License 4 votes vote down vote up
def next_sample(self):
        """Helper function for reading in next sample."""
        #set total batch size, for example, 1800, and maximum size for each people, for example 45
        if self.seq is not None:
          while True:
            if self.cur >= len(self.seq):
                raise StopIteration
            idx = self.seq[self.cur]
            self.cur += 1
            if self.imgrec is not None:
              s = self.imgrec.read_idx(idx)
              header, img = recordio.unpack(s)
              label = header.label
              if self.output_c2c:
                count = self.idx2flag[idx]
                if self.output_c2c==1:
                  v = np.random.uniform(0.4, 0.5)
                elif self.output_c2c==2:
                  v = np.random.uniform(0.4, 0.5)
                  if count>=self.output_c2c:
                    v = np.random.uniform(0.3, 0.4)
                elif self.output_c2c==3:
                  v = (9.5 - math.log(2.0+count))/10.0
                  v = min(max(v, 0.3), 0.5)
                elif self.output_c2c==4:
                  mu = 0.0
                  sigma = 0.1
                  mrange = [0.4,0.5]
                  v = numpy.random.normal(mu, sigma)
                  v = math.abs(v)*-1.0+mrange[1]
                  v = max(v, mrange[0])
                elif self.output_c2c==5:
                  v = np.random.uniform(0.41, 0.51)
                  if count>=175:
                    v = np.random.uniform(0.37, 0.47)
                elif self.output_c2c==6:
                  v = np.random.uniform(0.41, 0.51)
                  if count>=175:
                    v = np.random.uniform(0.38, 0.48)
                else:
                  assert False

                label = [label, v]
              else:
                if not isinstance(label, numbers.Number):
                  label = label[0]
              return label, img, None, None
            else:
              label, fname, bbox, landmark = self.imglist[idx]
              return label, self.read_image(fname), bbox, landmark
        else:
            s = self.imgrec.read()
            if s is None:
                raise StopIteration
            header, img = recordio.unpack(s)
            return header.label, img, None, None 
Example 14
Project: arcface   Author: chenggongliang   File: data.py    MIT License 4 votes vote down vote up
def next_sample(self):
        """Helper function for reading in next sample."""
        #set total batch size, for example, 1800, and maximum size for each people, for example 45
        if self.seq is not None:
          while True:
            if self.cur >= len(self.seq):
                raise StopIteration
            idx = self.seq[self.cur]
            self.cur += 1
            if self.imgrec is not None:
              s = self.imgrec.read_idx(idx)
              header, img = recordio.unpack(s)
              label = header.label
              if self.output_c2c:
                count = self.idx2flag[idx]
                if self.output_c2c==1:
                  v = np.random.uniform(0.4, 0.5)
                elif self.output_c2c==2:
                  v = np.random.uniform(0.4, 0.5)
                  if count>=self.output_c2c:
                    v = np.random.uniform(0.3, 0.4)
                elif self.output_c2c==3:
                  v = (9.5 - math.log(2.0+count))/10.0
                  v = min(max(v, 0.3), 0.5)
                elif self.output_c2c==4:
                  mu = 0.0
                  sigma = 0.1
                  mrange = [0.4,0.5]
                  v = numpy.random.normal(mu, sigma)
                  v = math.abs(v)*-1.0+mrange[1]
                  v = max(v, mrange[0])
                elif self.output_c2c==5:
                  v = np.random.uniform(0.41, 0.51)
                  if count>=175:
                    v = np.random.uniform(0.37, 0.47)
                elif self.output_c2c==6:
                  v = np.random.uniform(0.41, 0.51)
                  if count>=175:
                    v = np.random.uniform(0.38, 0.48)
                else:
                  assert False

                label = [label, v]
              else:
                if not isinstance(label, numbers.Number):
                  label = label[0]
              return label, img, None, None
            else:
              label, fname, bbox, landmark = self.imglist[idx]
              return label, self.read_image(fname), bbox, landmark
        else:
            s = self.imgrec.read()
            if s is None:
                raise StopIteration
            header, img = recordio.unpack(s)
            return header.label, img, None, None 
Example 15
Project: mapr-streams-mxnet-face   Author: mengdong   File: data.py    Apache License 2.0 4 votes vote down vote up
def next_sample(self):
        """Helper function for reading in next sample."""
        #set total batch size, for example, 1800, and maximum size for each people, for example 45
        if self.seq is not None:
          while True:
            if self.cur >= len(self.seq):
                raise StopIteration
            idx = self.seq[self.cur]
            self.cur += 1
            if self.imgrec is not None:
              s = self.imgrec.read_idx(idx)
              header, img = recordio.unpack(s)
              label = header.label
              if self.output_c2c:
                count = self.idx2flag[idx]
                if self.output_c2c==1:
                  v = np.random.uniform(0.4, 0.5)
                elif self.output_c2c==2:
                  v = np.random.uniform(0.4, 0.5)
                  if count>=self.output_c2c:
                    v = np.random.uniform(0.3, 0.4)
                elif self.output_c2c==3:
                  v = (9.5 - math.log(2.0+count))/10.0
                  v = min(max(v, 0.3), 0.5)
                elif self.output_c2c==4:
                  mu = 0.0
                  sigma = 0.1
                  mrange = [0.4,0.5]
                  v = numpy.random.normal(mu, sigma)
                  v = math.abs(v)*-1.0+mrange[1]
                  v = max(v, mrange[0])
                elif self.output_c2c==5:
                  v = np.random.uniform(0.41, 0.51)
                  if count>=175:
                    v = np.random.uniform(0.37, 0.47)
                elif self.output_c2c==6:
                  v = np.random.uniform(0.41, 0.51)
                  if count>=175:
                    v = np.random.uniform(0.38, 0.48)
                else:
                  assert False

                label = [label, v]
              else:
                if not isinstance(label, numbers.Number):
                  label = label[0]
              return label, img, None, None
            else:
              label, fname, bbox, landmark = self.imglist[idx]
              return label, self.read_image(fname), bbox, landmark
        else:
            s = self.imgrec.read()
            if s is None:
                raise StopIteration
            header, img = recordio.unpack(s)
            return header.label, img, None, None 
Example 16
Project: ChromaStarPy   Author: sevenian3   File: MulGrayTCorr.py    MIT License 4 votes vote down vote up
def expOne(x): 
    
    """// Approximate first exponential integral function E_1(x) = -Ei(-x)"""

    #// From http://en.wikipedia.org/wiki/Exponential_integral 
    #// Series expansion for first exponential integral function, E_1(x) = -Ei(-x)
    #// Ee_one(x) = -gamma - ln(abs(x)) - Sigma_k=1^infnty{(-x)^k)/(k*k!)}
    #// where: gamma =  Euler–Mascheroni constant = 0.577215665...
    #double E1;

    x = math.abs(x) #// x must be positive
    #// E1(x) undefined at x=0 - singular:
    #//double tiny = 1.25;  //tuned to give J ~ 0.5B @ tau=0
    tiny = 1.0e-6
    if (x < tiny): 
        x = tiny
        

    #// Caution: even at 11th order acuracy (k=11), approximation starts to diverge for x . 3.0:
    if (x > 3.0):

        E1 = math.exp(-1.0 * x) / x #// large x approx

    else:
        gamma = 0.577215665 #//Euler–Mascheroni constant
        kTerm = 0.0
        order = 11 #//order of approximation
        #double kFloat;
        accum = 0.0  #//accumulator
        kFac = 1.0 #// initialize k! (k factorial)

        for k in range(1, order+1):
            kFloat = float(k)
            kFac = kFac * kFloat
            accum = accum + Math.pow((-1.0 * x), kFloat) / (k * kFac);
            #//System.out.println("k: " + k + " kFac: " + kFac);
            #//System.out.println("k: " + k + " Math.pow(x, kFloat): " + Math.pow(x, kFloat));
            
        kTerm = accum

        E1 = -1.0 * gamma - Math.log(Math.abs(x)) - kTerm
    #}

    #//System.out.println("x: " + x + " exp1(x): " + E1);
    return E1

#}