Python math.tanh() Examples

The following are code examples for showing how to use math.tanh(). 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: soccer-matlab   Author: utra-robosoccer   File: minitaur_ball_gym_env_example.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def FollowBallManualPolicy():
  """An example of a minitaur following a ball."""
  env = minitaur_ball_gym_env.MinitaurBallGymEnv(render=True,
                                                 pd_control_enabled=True,
                                                 on_rack=False)
  observation = env.reset()
  sum_reward = 0
  steps = 100000
  for _ in range(steps):
    action = [math.tanh(observation[0] * 4)]
    observation, reward, done, _ = env.step(action)
    sum_reward += reward
    if done:
      tf.logging.info("Return is {}".format(sum_reward))
      observation = env.reset()
      sum_reward = 0 
Example 2
Project: dac   Author: KBNLresearch   File: dac.py    GNU General Public License v3.0 6 votes vote down vote up
def set_candidate_inlinks(self):
        '''
        Determine inlinks feature values.
        '''
        if not [f for f in self.features if f.startswith('candidate_inlinks')]:
            return

        for link_type in ['inlinks', 'inlinks_newspapers']:
            link_count = self.document.get(link_type)
            if link_count:
                setattr(self, 'candidate_' + link_type,
                        math.tanh(link_count * 0.001))
                if not hasattr(self.cand_list, 'sum_' + link_type):
                    self.cand_list.set_sum_inlinks()
                link_sum = getattr(self.cand_list, 'sum_' + link_type)
                if link_sum:
                    link_count_rel = link_count / float(link_sum)
                    setattr(self, 'candidate_' + link_type + '_rel',
                            link_count_rel) 
Example 3
Project: dac   Author: KBNLresearch   File: dac.py    GNU General Public License v3.0 6 votes vote down vote up
def set_solr_properties(self):
        '''
        Determine Solr iteration, position and score.
        '''
        if not [f for f in self.features if f.startswith('match_str_solr')]:
            return

        # Solr query
        setattr(self, 'match_str_solr_query_{}'.format(self.query_id), 1)

        # Solr iteration
        setattr(self, 'match_str_solr_iteration_{}'.format(self.iteration), 1)

        # Solr position (relative to other remaining candidates)
        pos = self.cand_list.filtered_candidates.index(self)
        self.match_str_solr_position = 1.0 - math.tanh(pos * 0.25)

        # Solr score (relative to other remaining candidates)
        if not hasattr(self.cand_list, 'max_score'):
            self.cand_list.set_max_score()
        if self.cand_list.max_score:
            self.match_str_solr_score = (self.document.get('score') /
                                         float(self.cand_list.max_score)) 
Example 4
Project: dac   Author: KBNLresearch   File: dac.py    GNU General Public License v3.0 6 votes vote down vote up
def set_entity_match(self):
        '''
        Match other entities appearing in the article with DBpedia abstract.
        '''
        if 'match_txt_entities' not in self.features:
            return

        if not hasattr(self.cluster, 'entity_parts'):
            self.cluster.get_entity_parts()
        if not hasattr(self.cluster, 'context_entity_parts'):
            self.cluster.get_context_entity_parts()
        if not self.cluster.context_entity_parts:
            return

        abstract = self.document.get('abstract_norm')
        if not abstract:
            return

        bow = [t for t in abstract.split() if len(t) >= 5]

        entity_match = len(set(self.cluster.context_entity_parts) & set(bow))
        self.match_txt_entities = math.tanh(entity_match * 0.25) 
Example 5
Project: neat-python   Author: CodeReclaimers   File: activations.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self):
        self.functions = {}
        self.add('sigmoid', sigmoid_activation)
        self.add('tanh', tanh_activation)
        self.add('sin', sin_activation)
        self.add('gauss', gauss_activation)
        self.add('relu', relu_activation)
        self.add('elu', elu_activation)
        self.add('lelu', lelu_activation)
        self.add('selu', selu_activation)
        self.add('softplus', softplus_activation)
        self.add('identity', identity_activation)
        self.add('clamped', clamped_activation)
        self.add('inv', inv_activation)
        self.add('log', log_activation)
        self.add('exp', exp_activation)
        self.add('abs', abs_activation)
        self.add('hat', hat_activation)
        self.add('square', square_activation)
        self.add('cube', cube_activation) 
Example 6
Project: lightML   Author: jfzhang95   File: NeuralNetwork.py    MIT License 6 votes vote down vote up
def update(self, inputs):
        # input activations
        for i in range(self.input_size - 1):
            self.ai[i] = inputs[i]

        # hidden activations
        for j in range(self.hidden_size):
            sum = 0.0
            for i in range(self.input_size):
                sum = sum + self.ai[i] * self.Wi[i][j]
            self.ah[j] = math.tanh(sum)

        # output activations
        for k in range(self.output_size):
            sum = 0.0
            for j in range(self.hidden_size):
                sum = sum + self.ah[j] * self.Wo[j][k]
            self.ao[k] = sigmoid(sum)

        return self.ao[:] 
Example 7
Project: CAPTCHA-breaking   Author: lllcho   File: test_activations.py    MIT License 6 votes vote down vote up
def test_tanh():

    from keras.activations import tanh as t
    test_values = get_standard_values()

    x = T.vector()
    exp = t(x)
    f = theano.function([x], exp)

    result = f(test_values)
    expected = [math.tanh(v) for v in test_values]

    print(result)
    print(expected)

    list_assert_equal(result, expected) 
Example 8
Project: Huawei_CodeCraft_2018   Author: luojie1024   File: martix_utils.py    Apache License 2.0 6 votes vote down vote up
def tanh(x):
    x_is_mat = type_of(x) == 'matrix'
    x_is_vct = type_of(x) == 'vector'
    x_is_scl = type_of(x) == 'scalar'
    if x_is_mat:
        res = [[0] * len(x[0]) for i in range(len(x))]
        for i in range(len(x)):
            for j in range(len(x[0])):
                res[i][j] = math.tanh(x[i][j])
        return res
    if x_is_vct:
        res = [0] * len(x)
        for i in range(len(x)):
            res[i] = math.tanh(x[i])
        return res
    if x_is_scl:
        return math.tanh(x)


# element-wise product 
Example 9
Project: PyNeurGen   Author: jacksonpradolima   File: nodes.py    GNU General Public License v3.0 6 votes vote down vote up
def set_activation_type(self, activation_type):
        """
        This function sets the activation type for the node.  Currently
        available values are ACTIVATION_SIGMOID, ACTIVATION_TANH,
        ACTIVATION_LINEAR. When specifying the activation type, the
        corresponding derivative type for the error functions are assigned as
        well.

        """

        if activation_type == ACTIVATION_SIGMOID:
            self._activate = sigmoid
        elif activation_type == ACTIVATION_TANH:
            self._activate = tanh
        elif activation_type == ACTIVATION_LINEAR:
            self._activate = linear
        else:
            raise ValueError("invalid activation type: %s" % (activation_type))

        self._set_error_func(activation_type)
        self._activation_type = activation_type 
Example 10
Project: FitML   Author: FitMachineLearning   File: BipedalWalker_Selective_Memory.py    MIT License 6 votes vote down vote up
def addToMemory(reward,averageReward):

    prob = 0.1
    if( reward > averageReward):
        prob = prob + 0.9 * math.tanh(reward - averageReward)
    else:
        prob = prob + 0.1 * math.tanh(reward - averageReward)
    print("average reward", averageReward, " reward ", reward, " prob", prob)
    #prob = prob / (rangeH - rangeL)
    #prob = reward / (1 + math.fabs(reward))
    #prob = (prob+1)/2
    if np.random.rand(1)<=prob :
        print("Adding reward",reward," based on prob ", prob)
        return True
    else:
        return False 
Example 11
Project: scikit-learn-graph   Author: nickgentoo   File: ODDSTGraphKernel.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, r =3, l =1, normalization =True, ntype =0):
        """
        Constructor
        @type r: integer number
        @param r: ODDKernel Parameter
        
        @type l: number in (0,1]
        @param l: ODDKernel Parameter
        
        @type normalization: boolean
        @param normalization: True to normalize the feature vectors
        
        @type ntype: enum in [0,1]
        @param ntype: 0 for default normalization, 1 for tanh normalization

        @type show: boolean
        @param show: If true shows graphs and DAGs during computation
        """
        self.Lambda=l
        self.max_radius=r
        self.normalization=normalization
        self.normalization_type = ntype
        self.__startsymbol='!' #special symbols used in encoding
        self.__conjsymbol='#'
        self.__endsymbol='?' 
Example 12
Project: scikit-learn-graph   Author: nickgentoo   File: ODDSTGraphKernel.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, r =3, l =1, normalization =True, ntype =0):
        """
        Constructor
        @type r: integer number
        @param r: ODDKernel Parameter
        
        @type l: number in (0,1]
        @param l: ODDKernel Parameter
        
        @type normalization: boolean
        @param normalization: True to normalize the feature vectors
        
        @type ntype: enum in [0,1]
        @param ntype: 0 for default normalization, 1 for tanh normalization

        @type show: boolean
        @param show: If true shows graphs and DAGs during computation
        """
        self.Lambda=l
        self.max_radius=r
        self.normalization=normalization
        self.normalization_type = ntype
        self.__startsymbol='!' #special symbols used in encoding
        self.__conjsymbol='#'
        self.__endsymbol='?' 
Example 13
Project: scikit-learn-graph   Author: nickgentoo   File: ODDSTGraphKernel.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, r =3, l =1, normalization =True, ntype =0):
        """
        Constructor
        @type r: integer number
        @param r: ODDKernel Parameter
        
        @type l: number in (0,1]
        @param l: ODDKernel Parameter
        
        @type normalization: boolean
        @param normalization: True to normalize the feature vectors
        
        @type ntype: enum in [0,1]
        @param ntype: 0 for default normalization, 1 for tanh normalization

        @type show: boolean
        @param show: If true shows graphs and DAGs during computation
        """
        self.Lambda=l
        self.max_radius=r
        self.normalization=normalization
        self.normalization_type = ntype
        self.__startsymbol='!' #special symbols used in encoding
        self.__conjsymbol='#'
        self.__endsymbol='?' 
Example 14
Project: scikit-learn-graph   Author: nickgentoo   File: ODDSTGraphKernel.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, r =3, l =1, normalization =True, ntype =0):
        """
        Constructor
        @type r: integer number
        @param r: ODDKernel Parameter
        
        @type l: number in (0,1]
        @param l: ODDKernel Parameter
        
        @type normalization: boolean
        @param normalization: True to normalize the feature vectors
        
        @type ntype: enum in [0,1]
        @param ntype: 0 for default normalization, 1 for tanh normalization

        @type show: boolean
        @param show: If true shows graphs and DAGs during computation
        """
        self.Lambda=l
        self.max_radius=r
        self.normalization=normalization
        self.normalization_type = ntype
        self.__startsymbol='!' #special symbols used in encoding
        self.__conjsymbol='#'
        self.__endsymbol='?' 
Example 15
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testTanh(self):
        self.assertRaises(TypeError, math.tanh)
        self.ftest('tanh(0)', math.tanh(0), 0)
        self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
        self.ftest('tanh(inf)', math.tanh(INF), 1)
        self.ftest('tanh(-inf)', math.tanh(NINF), -1)
        self.assertTrue(math.isnan(math.tanh(NAN)))
        # check that tanh(-0.) == -0. on IEEE 754 systems
        if float.__getformat__("double").startswith("IEEE"):
            self.assertEqual(math.tanh(-0.), -0.)
            self.assertEqual(math.copysign(1., math.tanh(-0.)),
                             math.copysign(1., -0.)) 
Example 16
Project: dac   Author: KBNLresearch   File: dac.py    GNU General Public License v3.0 5 votes vote down vote up
def set_alt_label_match(self):
        '''
        Match alternative labels with the normalized entity.
        '''
        if self.iteration != 3:
            labels = self.document.get('alt_label')
        else:
            labels = self.document.get('alt_label_ocr')

        if not labels:
            return

        ne = self.cluster.entities[0].norm

        alt_label_exact_match = 0
        alt_label_end_match = 0
        alt_label_match = 0
        for l in labels:
            if not set(ne.split()) - set(l.split()):
                if l == ne:
                    alt_label_exact_match += 1
                elif l.endswith(ne):
                    alt_label_end_match += 1
                elif l.find(ne) > -1:
                    alt_label_match += 1
                else:
                    self.non_matching.append(l)
            else:
                self.non_matching.append(l)

        self.match_str_alt_label_exact = math.tanh(alt_label_exact_match * 0.25)
        self.match_str_alt_label_end = math.tanh(alt_label_end_match * 0.25)
        self.match_str_alt_label = math.tanh(alt_label_match * 0.25) 
Example 17
Project: dac   Author: KBNLresearch   File: dac.py    GNU General Public License v3.0 5 votes vote down vote up
def set_non_matching(self):
        '''
        Count total number of non matching labels.
        '''
        self.match_str_non_matching = math.tanh(len(self.non_matching) * 0.25) 
Example 18
Project: dac   Author: KBNLresearch   File: dac.py    GNU General Public License v3.0 5 votes vote down vote up
def set_entity_quotes(self):
        '''
        Count number of quotes surrounding entity mentions.
        '''
        if 'entity_quotes' not in self.features:
            return

        if not hasattr(self.cluster, 'sum_quotes'):
            self.cluster.sum_quotes = sum([e.quotes for e in
                                           self.cluster.entities])

        self.entity_quotes = math.tanh(self.cluster.sum_quotes * 0.25) 
Example 19
Project: metk   Author: PatWalters   File: metk_util.py    MIT License 5 votes vote down vote up
def pearson_confidence(r, num, interval=0.95):
    """
    Calculate upper and lower 95% CI for a Pearson r (not R**2)
    Inspired by https://stats.stackexchange.com/questions/18887
    :param r: Pearson's R
    :param num: number of data points
    :param interval: confidence interval (0-1.0)
    :return: lower bound, upper bound
    """
    stderr = 1.0 / math.sqrt(num - 3)
    z_score = norm.ppf(interval)
    delta = z_score * stderr
    lower = math.tanh(math.atanh(r) - delta)
    upper = math.tanh(math.atanh(r) + delta)
    return lower, upper 
Example 20
Project: neat-python   Author: CodeReclaimers   File: activations.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tanh_activation(z):
    z = max(-60.0, min(60.0, 2.5 * z))
    return math.tanh(z) 
Example 21
Project: Wall-Following-Robot   Author: seifullaah73   File: bpnn.py    GNU General Public License v3.0 5 votes vote down vote up
def dsig(y):
    return y*(1-y)


# our sigmoid function, tanh is a little nicer than the standard 1/(1+e^-x) 
Example 22
Project: Wall-Following-Robot   Author: seifullaah73   File: bpnn.py    GNU General Public License v3.0 5 votes vote down vote up
def sigtanh(x):
    return math.tanh(x)

# derivative of our sigmoid function, in terms of the output (i.e. y) 
Example 23
Project: Wall-Following-Robot   Author: seifullaah73   File: bpnn.py    GNU General Public License v3.0 5 votes vote down vote up
def demo():
    # Teach network XOR function
    xorPat = [
            [[-1, 0,0], [0]],
            [[-1, 0,1], [1]],
            [[-1, 1,0], [1]],
            [[-1, 1,1], [0]]
            ]

    # create a network with two input, two hidden, and one output nodes
    n = NN(3, 2, 1) #default uses tanh activation function  
    # train it with some patterns
    n.train(xorPat, 1000, .2, 0.1)
    # test it
    n.test(xorPat) 
Example 24
Project: Wall-Following-Robot   Author: seifullaah73   File: bpnn.py    GNU General Public License v3.0 5 votes vote down vote up
def demo2():
    # Teach network XOR function
    xnorPat = [
            [[-1, 0,0], [1]],
            [[-1, 0,1], [0]],
            [[-1, 1,0], [0]],
            [[-1, 1,1], [1]]
            ]

    # create a network with two input, two hidden, and one output nodes
    n = NN(3, 2, 1) #default uses tanh activation function  
    # train it with some patterns
    n.train(xnorPat, 1000, .2, 0.1)
    # test it
    n.test(xnorPat) 
Example 25
Project: Wall-Following-Robot   Author: seifullaah73   File: bpnn.py    GNU General Public License v3.0 5 votes vote down vote up
def demo3():
    # Teach network OR function
    orPat = [
            [[-1, 0,0], [0]],
            [[-1, 0,1], [1]],
            [[-1, 1,0], [1]],
            [[-1, 1,1], [1]]
            ]

    # create a network with two input, two hidden, and one output nodes
    n = NN(3, 2, 1) #default uses tanh activation function  
    # train it with some patterns
    n.train(orPat, 1000, .2, 0.1)
    # test it
    n.test(orPat) 
Example 26
Project: Wall-Following-Robot   Author: seifullaah73   File: bpnn.py    GNU General Public License v3.0 5 votes vote down vote up
def demo5():
    # Teach network XNOR function
    nandPat = [
            [[-1, 0,0], [1]],
            [[-1, 0,1], [1]],
            [[-1, 1,0], [1]],
            [[-1, 1,1], [0]]
            ]

    # create a network with two input, two hidden, and one output nodes
    n = NN(3, 2, 1) #default uses tanh activation function  
    # train it with some patterns
    n.train(nandPat, 1000, .2, 0.1)
    # test it
    n.test(nandPat) 
Example 27
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testTanh(self):
        self.assertRaises(TypeError, math.tanh)
        self.ftest('tanh(0)', math.tanh(0), 0)
        self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0,
                   abs_tol=ulp(1))
        self.ftest('tanh(inf)', math.tanh(INF), 1)
        self.ftest('tanh(-inf)', math.tanh(NINF), -1)
        self.assertTrue(math.isnan(math.tanh(NAN))) 
Example 28
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testTanhSign(self):
        # check that tanh(-0.) == -0. on IEEE 754 systems
        self.assertEqual(math.tanh(-0.), -0.)
        self.assertEqual(math.copysign(1., math.tanh(-0.)),
                         math.copysign(1., -0.)) 
Example 29
Project: controlled-text-generation   Author: wiseodd   File: train_discriminator.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def kl_weight(it):
    """
    Credit to: https://github.com/kefirski/pytorch_RVAE/
    0 -> 1
    """
    return (math.tanh((it - 3500)/1000) + 1)/2 
Example 30
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 5 votes vote down vote up
def sigmoide(d,valore1,valore2,distanza,n=1):
    #n intero tra 1 (scalino marcato) e 6 (scalino dolce circa coseno)
    y=-10.0+20.0*d/distanza#y=[-10:10]
    y=y*1.0/n
    sigm=1.0*valore1+0.5*(valore2-valore1)*(1+math.tanh(y))
    grad_sigm=0.5*(valore2-valore1)/(math.cosh(y))**2
    grad_sigm=-grad_sigm*20.0/(n*distanza)
    return (sigm,grad_sigm)
#MAIN------------------------------------------------------------ 
Example 31
Project: PySail-426   Author: j3b4   File: SimulazioneRegata316.py    GNU General Public License v3.0 5 votes vote down vote up
def sigmoide(d,valore1,valore2,distanza,n=1):
    #n intero tra 1 (scalino marcato) e 6 (scalino dolce circa coseno)
    y=-10.0+20.0*d/distanza#y=[-10:10]
    y=y*1.0/n
    sigm=1.0*valore1+0.5*(valore2-valore1)*(1+math.tanh(y))
    grad_sigm=0.5*(valore2-valore1)/(math.cosh(y))**2
    grad_sigm=-grad_sigm*20.0/(n*distanza)
    return (sigm,grad_sigm)
#MAIN------------------------------------------------------------ 
Example 32
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 5 votes vote down vote up
def c_tanh(x, y):
    # Formula:
    #
    #   tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) /
    #   (1+tan(y)^2 tanh(x)^2)
    #
    #   To avoid excessive roundoff error, 1-tanh(x)^2 is better computed
    #   as 1/cosh(x)^2.  When abs(x) is large, we approximate 1-tanh(x)^2
    #   by 4 exp(-2*x) instead, to avoid possible overflow in the
    #   computation of cosh(x).

    if not isfinite(x) or not isfinite(y):
        if isinf(x) and isfinite(y) and y != 0.:
            if x > 0:
                real = 1.0        # vv XXX why is the 2. there?
                imag = copysign(0., 2. * math.sin(y) * math.cos(y))
            else:
                real = -1.0
                imag = copysign(0., 2. * math.sin(y) * math.cos(y))
            r = (real, imag)
        else:
            r = tanh_special_values[special_type(x)][special_type(y)]

        # need to raise ValueError if y is +/-infinity and x is finite
        if isinf(y) and isfinite(x):
            raise ValueError("math domain error")
        return r

    if fabs(x) > CM_LOG_LARGE_DOUBLE:
        real = copysign(1., x)
        imag = 4. * math.sin(y) * math.cos(y) * math.exp(-2.*fabs(x))
    else:
        tx = math.tanh(x)
        ty = math.tan(y)
        cx = 1. / math.cosh(x)
        txty = tx * ty
        denom = 1. + txty * txty
        real = tx * (1. + ty*ty) / denom
        imag = ((ty / denom) * cx) * cx
    return real, imag 
Example 33
Project: rpython-lang-scheme   Author: tomoh1r   File: rcomplex.py    MIT License 5 votes vote down vote up
def c_tan(r, i):
    # tan(z) = -i tanh(iz)
    sr, si = c_tanh(-i, r)
    return si, -sr 
Example 34
Project: ironpython2   Author: IronLanguages   File: test_math.py    Apache License 2.0 5 votes vote down vote up
def testTanh(self):
        self.assertRaises(TypeError, math.tanh)
        self.ftest('tanh(0)', math.tanh(0), 0)
        self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
        self.ftest('tanh(inf)', math.tanh(INF), 1)
        self.ftest('tanh(-inf)', math.tanh(NINF), -1)
        self.assertTrue(math.isnan(math.tanh(NAN)))
        # check that tanh(-0.) == -0. on IEEE 754 systems
        if float.__getformat__("double").startswith("IEEE"):
            self.assertEqual(math.tanh(-0.), -0.)
            self.assertEqual(math.copysign(1., math.tanh(-0.)),
                             math.copysign(1., -0.)) 
Example 35
Project: nevergrad   Author: facebookresearch   File: corefuncs.py    MIT License 5 votes vote down vote up
def genzcornerpeak(y: np.ndarray) -> float:
    """One of the Genz functions, originally used in integration,

    tested in optim because why not."""
    value = float(1 + np.mean(np.tanh(y)))
    if value == 0:
        return float("inf")
    return value ** (-len(y) - 1) 
Example 36
Project: nevergrad   Author: facebookresearch   File: corefuncs.py    MIT License 5 votes vote down vote up
def linear(x: np.ndarray) -> float:
    return tanh(x[0]) 
Example 37
Project: visma   Author: aerospaceresearch   File: hyperbolic.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        super().__init__()
        self.value = 'tanh' 
Example 38
Project: visma   Author: aerospaceresearch   File: hyperbolic.py    GNU General Public License v3.0 5 votes vote down vote up
def calculate(self, val):
        return self.coefficient * ((math.tanh(val)) ** self.power)

################################
# Inverse Hyperbolic Functions #
################################ 
Example 39
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testTanh(self):
        self.assertRaises(TypeError, math.tanh)
        self.ftest('tanh(0)', math.tanh(0), 0)
        self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
        self.ftest('tanh(inf)', math.tanh(INF), 1)
        self.ftest('tanh(-inf)', math.tanh(NINF), -1)
        self.assertTrue(math.isnan(math.tanh(NAN))) 
Example 40
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testTanhSign(self):
        # check that tanh(-0.) == -0. on IEEE 754 systems
        self.assertEqual(math.tanh(-0.), -0.)
        self.assertEqual(math.copysign(1., math.tanh(-0.)),
                         math.copysign(1., -0.)) 
Example 41
Project: Huawei_CodeCraft_2018   Author: luojie1024   File: BPNN.py    Apache License 2.0 5 votes vote down vote up
def predict(self, inputs):  # 一次反馈,计算隐含层和输出层的输出,并返回输出层的输出
        # activate input layer
        # print "type(input_cells) = ", type(self.input_cells[0])
        # print "type(inputs) = ", type(inputs[0])
        # print "inputs = ", inputs
        # print "inputs[0] = ", inputs[0]

        for i in range(self.input_n - 1):
            self.input_cells[i] = inputs[i]
            # self.input_cells[i] = inputs  # 更改
        # activate hidden layer
        for j in range(self.hidden_n):
            total = 0.0
            for i in range(self.input_n):
                total += self.input_cells[i] * self.input_weights[i][j]
            # self.hidden_cells[j] = sigmoid(total)
            # self.hidden_cells[j] = math.tanh(total)
            self.hidden_cells[j] = 0.01 * total

        # activate output layer
        for k in range(self.output_n):
            total = 0.0
            for j in range(self.hidden_n):
                total += self.hidden_cells[j] * self.output_weights[j][k]
            # self.output_cells[k] = sigmoid(total)
            self.output_cells[k] = 0.01 * total
        return self.output_cells[:] 
Example 42
Project: ngraph-python   Author: NervanaSystems   File: test_activations.py    Apache License 2.0 5 votes vote down vote up
def reference_value(self, x):
        return np.vectorize(true_tanh)(x) 
Example 43
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_math.py    GNU General Public License v2.0 5 votes vote down vote up
def testTanh(self):
        self.assertRaises(TypeError, math.tanh)
        self.ftest('tanh(0)', math.tanh(0), 0)
        self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0,
                   abs_tol=ulp(1))
        self.ftest('tanh(inf)', math.tanh(INF), 1)
        self.ftest('tanh(-inf)', math.tanh(NINF), -1)
        self.assertTrue(math.isnan(math.tanh(NAN))) 
Example 44
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_math.py    GNU General Public License v2.0 5 votes vote down vote up
def testTanhSign(self):
        # check that tanh(-0.) == -0. on IEEE 754 systems
        self.assertEqual(math.tanh(-0.), -0.)
        self.assertEqual(math.copysign(1., math.tanh(-0.)),
                         math.copysign(1., -0.)) 
Example 45
Project: agentsmith   Author: underwit   File: brain.py    MIT License 5 votes vote down vote up
def _multiply(self, values, weights):
        """Перемножаем входные значения на соответствующие веса."""
        # никогда так не пишите
        result = [sum(map(lambda a, b: a * b, values, w)) for w in weights]
        return list(map(math.tanh, result)) 
Example 46
Project: oss-ftp   Author: aliyun   File: test_math.py    MIT License 5 votes vote down vote up
def testTanh(self):
        self.assertRaises(TypeError, math.tanh)
        self.ftest('tanh(0)', math.tanh(0), 0)
        self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
        self.ftest('tanh(inf)', math.tanh(INF), 1)
        self.ftest('tanh(-inf)', math.tanh(NINF), -1)
        self.assertTrue(math.isnan(math.tanh(NAN)))
        # check that tanh(-0.) == -0. on IEEE 754 systems
        if float.__getformat__("double").startswith("IEEE"):
            self.assertEqual(math.tanh(-0.), -0.)
            self.assertEqual(math.copysign(1., math.tanh(-0.)),
                             math.copysign(1., -0.)) 
Example 47
Project: hybrid_rvae   Author: kefirski   File: functions.py    MIT License 5 votes vote down vote up
def kld_coef(i):
    import math
    return (math.tanh((i - 13000) / 5000) + 1) / 2 
Example 48
Project: absorbing-layer-for-free-surface-waves   Author: wave-absorbing-layers   File: CRest.py    GNU General Public License v3.0 5 votes vote down vote up
def period(T, h):
	w = 2.0 * math.pi / T	# angular wave frequency
	# iterate to obtain corresponding intermediate depth wavelength
	tmp = (w**2)/9.81	# initial guess: deep water wave number
	for i in range(50):	# 50 iterations is usually enough...
		tmp2 = w*w/(9.81*math.tanh(tmp*h))
		tmp = (tmp+tmp2)/2.0	#bisection
	return 2.0 * math.pi / tmp	# return wavelength



# batch mode 
Example 49
Project: m2cgen   Author: BayesWitnesses   File: test_python.py    MIT License 5 votes vote down vote up
def test_tanh_expr():
    expr = ast.TanhExpr(ast.NumVal(2.0))

    interpreter = interpreters.PythonInterpreter()

    expected_code = """
import math
def score(input):
    return math.tanh(2.0)
    """

    utils.assert_code_equal(interpreter.interpret(expr), expected_code) 
Example 50
Project: PyNeurGen   Author: jacksonpradolima   File: nodes.py    GNU General Public License v3.0 5 votes vote down vote up
def tanh(value):
    """
    This function calculates the hyperbolic tangent function.

    """

    return math.tanh(value) 
Example 51
Project: PyNeurGen   Author: jacksonpradolima   File: nodes.py    GNU General Public License v3.0 5 votes vote down vote up
def tanh_derivative(value):
    """
    This function calculates the tanh derivative of the value.

    """

    return 1.0 - pow(math.tanh(value), 2) 
Example 52
Project: TSP-Hopfield-Tank   Author: MacStan   File: hopfield.py    MIT License 5 votes vote down vote up
def activation(self, input):
        sigm = 0.5 * (1 + tanh(input / self.u0))
        activ = 0 if sigm < 0.2 else sigm
        activ = 1 if sigm > 0.8 else activ
        return sigm 
Example 53
Project: Multiple-kernal-scikit-svr   Author: YashSinha1996   File: multi_kernel.py    MIT License 5 votes vote down vote up
def sig(alpha=1.0,offset=0):
	"""
	Argments:	alpha (default 1.0) 
			offset (defaut 0)
	Returns:	a callable which returns math.tanh(alpha*1.0*x1.dot(x2.transpose())+offset) for some x1,x2
	"""
	def sig_fun(x1,x2):
		return math.tanh(alpha*1.0*x1.dot(x2.transpose())+offset)
	return sig_fun 
Example 54
Project: profitpy   Author: hpsilva   File: bpnn.py    GNU General Public License v2.0 5 votes vote down vote up
def makeMatrix(I, J, fill=0.0):
    m = []
    for i in range(I):
        m.append([fill]*J)
    return m

# our sigmoid function, tanh is a little nicer than the standard 1/(1+e^-x) 
Example 55
Project: profitpy   Author: hpsilva   File: bpnn.py    GNU General Public License v2.0 5 votes vote down vote up
def sigmoid(x):
    return math.tanh(x)

# derivative of our sigmoid function 
Example 56
Project: ufora   Author: ufora   File: pure_math.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, val):
        return __inline_fora(
            """fun(@unnamed_args:(val), *args) {
                   PyFloat(math.tanh([email protected]))
                   }"""
            )(val) 
Example 57
Project: ufora   Author: ufora   File: MathTestCases.py    Apache License 2.0 5 votes vote down vote up
def test_pure_python_math_module(self):
        vals = [1, -.5, 1.5, 0, 0.0, -2, -2.2, .2]

        # not being tested: math.asinh, math.atanh, math.lgamma, math.erfc, math.acos
        def f():
            functions = [
                math.sqrt, math.cos, math.sin, math.tan, math.asin, math.atan,
                math.acosh, math.cosh, math.sinh, math.tanh, math.ceil,
                math.erf, math.exp, math.expm1, math.factorial, math.floor,
                math.log, math.log10, math.log1p
            ]
            tr = []
            for idx1 in range(len(vals)):
                v1 = vals[idx1]
                for funIdx in range(len(functions)):
                    function = functions[funIdx]
                    try:
                        tr = tr + [function(v1)]
                    except ValueError as ex:
                        pass

            return tr

        r1 = self.evaluateWithExecutor(f)
        r2 = f()
        self.assertGreater(len(r1), 100)
        self.assertTrue(numpy.allclose(r1, r2, 1e-6)) 
Example 58
Project: pyml   Author: longtengz   File: AF.py    MIT License 5 votes vote down vote up
def tan(x):
    return math.tanh(x) 
Example 59
Project: MojiTalk   Author: claude-zhou   File: helpers.py    MIT License 5 votes vote down vote up
def get_kl_weight(global_step, total_step, ratio):
    # python3!
    progress = global_step / total_step
    if progress >= ratio:
        return 1.
    else:
        return tanh(6 * progress / ratio - 3) + 1 
Example 60
Project: hask   Author: billpmurphy   File: Num.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def make_instance(typeclass, cls, pi, exp, sqrt, log, pow, logBase, sin,
            tan, cos, asin, atan, acos, sinh, tanh, cosh, asinh, atanh, acosh):
        attrs = {"pi":pi, "exp":exp, "sqrt":sqrt, "log":log, "pow":pow,
                "logBase":logBase, "sin":sin, "tan":tan, "cos":cos,
                "asin":asin, "atan":atan, "acos":acos, "sinh":sinh,
                "tanh":tanh, "cosh":cosh, "asinh":asinh, "atanh":atanh,
                "acosh":acosh}
        build_instance(Floating, cls, attrs)
        return 
Example 61
Project: hask   Author: billpmurphy   File: Num.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def tanh(x):
    """
    tanh :: Floating a => a -> a
    """
    return Floating[x].tanh(x) 
Example 62
Project: hotxlfp   Author: aidhound   File: mathtrig.py    MIT License 5 votes vote down vote up
def TANH(number):
    number = utils.parse_number(number)
    if isinstance(number, error.XLError):
        return number
    return math.tanh(number) 
Example 63
Project: Python3   Author: IntelBUAP   File: ExamenGrupo.py    GNU General Public License v2.0 5 votes vote down vote up
def atangente(a):
    r = math.tanh(a)
    return r 
Example 64
Project: ocr-pytorch   Author: rosinality   File: clr.py    MIT License 5 votes vote down vote up
def anneal_tanh(start, end, proportion, lower=-6, upper=3):
    return end + (start - end) / 2 * (1 - tanh(lower + (upper - lower) * proportion)) 
Example 65
Project: ocr-pytorch   Author: rosinality   File: clr.py    MIT License 5 votes vote down vote up
def __init__(
        self,
        optimizer,
        lr_max,
        n_iter,
        divider=25,
        warmup_proportion=0.3,
        phase=('linear', 'cos'),
    ):
        self.optimizer = optimizer

        phase1 = int(n_iter * warmup_proportion)
        phase2 = n_iter - phase1
        lr_min = lr_max / divider

        phase_map = {
            'linear': anneal_linear,
            'cos': anneal_cos,
            'cospow': anneal_cospow,
            'poly': anneal_poly,
            'tanh': anneal_tanh,
        }

        self.lr_phase = [
            Phase(lr_min, lr_max, phase1, phase_map[phase[0]]),
            Phase(lr_max, lr_min / 1e4, phase2, phase_map[phase[1]]),
        ]

        self.phase = 0 
Example 66
Project: ocr-pytorch   Author: rosinality   File: scheduler.py    MIT License 5 votes vote down vote up
def anneal_tanh(start, end, proportion, lower=-6, upper=3):
    return end + (start - end) / 2 * (1 - tanh(lower + (upper - lower) * proportion)) 
Example 67
Project: ocr-pytorch   Author: rosinality   File: scheduler.py    MIT License 5 votes vote down vote up
def __init__(
        self,
        optimizer,
        lr_max,
        n_iter,
        divider=25,
        warmup_proportion=0.3,
        phase=('linear', 'cos'),
    ):
        self.optimizer = optimizer

        phase1 = int(n_iter * warmup_proportion)
        phase2 = n_iter - phase1
        lr_min = lr_max / divider

        phase_map = {
            'linear': anneal_linear,
            'cos': anneal_cos,
            'cospow': anneal_cospow,
            'poly': anneal_poly,
            'tanh': anneal_tanh,
        }

        self.lr_phase = [
            Phase(lr_min, lr_max, phase1, phase_map[phase[0]]),
            Phase(lr_max, lr_min / 1e4, phase2, phase_map[phase[1]]),
        ]

        self.phase = 0 
Example 68
Project: Python-iBeacon-Scan   Author: NikNitro   File: test_functions.py    GNU General Public License v3.0 5 votes vote down vote up
def test_trig_hyperb_basic():
    for x in (list(range(100)) + list(range(-100,0))):
        t = x / 4.1
        assert cos(mpf(t)).ae(math.cos(t))
        assert sin(mpf(t)).ae(math.sin(t))
        assert tan(mpf(t)).ae(math.tan(t))
        assert cosh(mpf(t)).ae(math.cosh(t))
        assert sinh(mpf(t)).ae(math.sinh(t))
        assert tanh(mpf(t)).ae(math.tanh(t))
    assert sin(1+1j).ae(cmath.sin(1+1j))
    assert sin(-4-3.6j).ae(cmath.sin(-4-3.6j))
    assert cos(1+1j).ae(cmath.cos(1+1j))
    assert cos(-4-3.6j).ae(cmath.cos(-4-3.6j)) 
Example 69
Project: Python-iBeacon-Scan   Author: NikNitro   File: test_functions.py    GNU General Public License v3.0 5 votes vote down vote up
def test_invhyperb_inaccuracy():
    mp.dps = 15
    assert (asinh(1e-5)*10**5).ae(0.99999999998333333)
    assert (asinh(1e-10)*10**10).ae(1)
    assert (asinh(1e-50)*10**50).ae(1)
    assert (asinh(-1e-5)*10**5).ae(-0.99999999998333333)
    assert (asinh(-1e-10)*10**10).ae(-1)
    assert (asinh(-1e-50)*10**50).ae(-1)
    assert asinh(10**20).ae(46.744849040440862)
    assert asinh(-10**20).ae(-46.744849040440862)
    assert (tanh(1e-10)*10**10).ae(1)
    assert (tanh(-1e-10)*10**10).ae(-1)
    assert (atanh(1e-10)*10**10).ae(1)
    assert (atanh(-1e-10)*10**10).ae(-1) 
Example 70
Project: Python-iBeacon-Scan   Author: NikNitro   File: test_functions.py    GNU General Public License v3.0 5 votes vote down vote up
def test_complex_functions():
    for x in (list(range(10)) + list(range(-10,0))):
        for y in (list(range(10)) + list(range(-10,0))):
            z = complex(x, y)/4.3 + 0.01j
            assert exp(mpc(z)).ae(cmath.exp(z))
            assert log(mpc(z)).ae(cmath.log(z))
            assert cos(mpc(z)).ae(cmath.cos(z))
            assert sin(mpc(z)).ae(cmath.sin(z))
            assert tan(mpc(z)).ae(cmath.tan(z))
            assert sinh(mpc(z)).ae(cmath.sinh(z))
            assert cosh(mpc(z)).ae(cmath.cosh(z))
            assert tanh(mpc(z)).ae(cmath.tanh(z)) 
Example 71
Project: Python-iBeacon-Scan   Author: NikNitro   File: test_functions.py    GNU General Public License v3.0 5 votes vote down vote up
def test_tanh():
    mp.dps = 15
    assert tanh(0) == 0
    assert tanh(inf) == 1
    assert tanh(-inf) == -1
    assert isnan(tanh(nan))
    assert tanh(mpc('inf', '0')) == 1 
Example 72
Project: DeepLearningWithPython   Author: MoriKen254   File: ActivationFunction.py    MIT License 5 votes vote down vote up
def compute(self, x):
        return math.tanh(x) 
Example 73
Project: pytorch_RVAE   Author: kefirski   File: functional.py    MIT License 5 votes vote down vote up
def kld_coef(i):
    import math
    return (math.tanh((i - 3500)/1000) + 1)/2 
Example 74
Project: NLP.py   Author: PythonOptimizers   File: sparse_vector_class.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tanh(a):
    """Elementwise hyperbolic tangent."""
    if not isSparseVector(a):
        raise TypeError("Argument must be a SparseVector")
    rv = SparseVector(a.n, {})
    for k in a.values.keys():
        rv.values[k] = math.tanh(a.values[k])
    return rv 
Example 75
Project: pytorch-image-models   Author: rwightman   File: tanh_lr.py    Apache License 2.0 5 votes vote down vote up
def _get_lr(self, t):
        if t < self.warmup_t:
            lrs = [self.warmup_lr_init + t * s for s in self.warmup_steps]
        else:
            if self.warmup_prefix:
                t = t - self.warmup_t

            if self.t_mul != 1:
                i = math.floor(math.log(1 - t / self.t_initial * (1 - self.t_mul), self.t_mul))
                t_i = self.t_mul ** i * self.t_initial
                t_curr = t - (1 - self.t_mul ** i) / (1 - self.t_mul) * self.t_initial
            else:
                i = t // self.t_initial
                t_i = self.t_initial
                t_curr = t - (self.t_initial * i)

            if self.cycle_limit == 0 or (self.cycle_limit > 0 and i < self.cycle_limit):
                gamma = self.decay_rate ** i
                lr_min = self.lr_min * gamma
                lr_max_values = [v * gamma for v in self.base_values]

                tr = t_curr / t_i
                lrs = [
                    lr_min + 0.5 * (lr_max - lr_min) * (1 - math.tanh(self.lb * (1. - tr) + self.ub * tr))
                    for lr_max in lr_max_values
                ]
            else:
                lrs = [self.lr_min * (self.decay_rate ** self.cycle_limit) for _ in self.base_values]
        return lrs 
Example 76
Project: numpynet   Author: uptake   File: test_activation.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_tanh(self):
        activation = nnc.Activation("tanh")

        # Compare scalars
        self.assertEqual(activation.function(1), math.tanh(1))
        self.assertEqual(activation.function(0), math.tanh(0))

        # Compare vectors
        vect = np.array([1, 2, 3])
        true_values = np.array(
            [0.7615941559557649, 0.9640275800758169, 0.9950547536867305]
        )
        self.assertTrue(np.array_equal(activation.function(vect), true_values))

        # Compare matrices
        matrix = np.array([[0.2, 0.0000001, 3], [-0.5, 1000, -10]])
        true_values = np.array(
            [[0.19737532, 0.0000001, 0.99505475], [-0.46211716, 1.0, -1.0]]
        )
        self.assertTrue(
            np.array_equal(np.round(activation.function(matrix), 8), true_values)
        )

        # Test derivative and scalars
        self.assertEqual(activation._tanh(1, deriv=True), 1 - math.tanh(1) ** 2)
        self.assertEqual(activation._tanh(0, deriv=True), 1 - math.tanh(0) ** 2)

        # Test derivative and vectors
        true_values = np.array(
            [0.41997434161402614, 0.07065082485316443, 0.009866037165440211]
        )
        self.assertTrue(np.array_equal(activation._tanh(vect, deriv=True), true_values))

        # Test derivative and matrices
        true_values = np.array(
            [[0.96104298, 1.0, 0.00986604], [0.78644773, 0.0, 0.00000001]]
        )
        self.assertTrue(
            np.array_equal(
                np.round(activation._tanh(matrix, deriv=True), 8), true_values
            )
        ) 
Example 77
Project: data_algebra   Author: WinVector   File: SQLite.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def prepare_connection(self, conn):
        # https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
        conn.create_function("is_bad", 1, _check_scalar_bad)
        # math fns
        conn.create_function("acos", 1, math.acos)
        conn.create_function("acosh", 1, math.acosh)
        conn.create_function("asin", 1, math.asin)
        conn.create_function("asinh", 1, math.asinh)
        conn.create_function("atan", 1, math.atan)
        conn.create_function("atanh", 1, math.atanh)
        conn.create_function("ceil", 1, math.ceil)
        conn.create_function("cos", 1, math.cos)
        conn.create_function("cosh", 1, math.cosh)
        conn.create_function("degrees", 1, math.degrees)
        conn.create_function("erf", 1, math.erf)
        conn.create_function("erfc", 1, math.erfc)
        conn.create_function("exp", 1, math.exp)
        conn.create_function("expm1", 1, math.expm1)
        conn.create_function("fabs", 1, math.fabs)
        conn.create_function("factorial", 1, math.factorial)
        conn.create_function("floor", 1, math.floor)
        conn.create_function("frexp", 1, math.frexp)
        conn.create_function("gamma", 1, math.gamma)
        conn.create_function("isfinite", 1, math.isfinite)
        conn.create_function("isinf", 1, math.isinf)
        conn.create_function("isnan", 1, math.isnan)
        conn.create_function("lgamma", 1, math.lgamma)
        conn.create_function("log", 1, math.log)
        conn.create_function("log10", 1, math.log10)
        conn.create_function("log1p", 1, math.log1p)
        conn.create_function("log2", 1, math.log2)
        conn.create_function("modf", 1, math.modf)
        conn.create_function("radians", 1, math.radians)
        conn.create_function("sin", 1, math.sin)
        conn.create_function("sinh", 1, math.sinh)
        conn.create_function("sqrt", 1, math.sqrt)
        conn.create_function("tan", 1, math.tan)
        conn.create_function("tanh", 1, math.tanh)
        conn.create_function("trunc", 1, math.trunc)
        conn.create_function("atan2", 2, math.atan2)
        conn.create_function("copysign", 2, math.copysign)
        conn.create_function("fmod", 2, math.fmod)
        conn.create_function("gcd", 2, math.gcd)
        conn.create_function("hypot", 2, math.hypot)
        conn.create_function("isclose", 2, math.isclose)
        conn.create_function("ldexp", 2, math.ldexp)
        conn.create_function("pow", 2, math.pow) 
Example 78
Project: data_algebra   Author: WinVector   File: SQLite.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def prepare_connection(self, conn):
        # https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function
        conn.create_function("is_bad", 1, _check_scalar_bad)
        # math fns
        conn.create_function("acos", 1, math.acos)
        conn.create_function("acosh", 1, math.acosh)
        conn.create_function("asin", 1, math.asin)
        conn.create_function("asinh", 1, math.asinh)
        conn.create_function("atan", 1, math.atan)
        conn.create_function("atanh", 1, math.atanh)
        conn.create_function("ceil", 1, math.ceil)
        conn.create_function("cos", 1, math.cos)
        conn.create_function("cosh", 1, math.cosh)
        conn.create_function("degrees", 1, math.degrees)
        conn.create_function("erf", 1, math.erf)
        conn.create_function("erfc", 1, math.erfc)
        conn.create_function("exp", 1, math.exp)
        conn.create_function("expm1", 1, math.expm1)
        conn.create_function("fabs", 1, math.fabs)
        conn.create_function("factorial", 1, math.factorial)
        conn.create_function("floor", 1, math.floor)
        conn.create_function("frexp", 1, math.frexp)
        conn.create_function("gamma", 1, math.gamma)
        conn.create_function("isfinite", 1, math.isfinite)
        conn.create_function("isinf", 1, math.isinf)
        conn.create_function("isnan", 1, math.isnan)
        conn.create_function("lgamma", 1, math.lgamma)
        conn.create_function("log", 1, math.log)
        conn.create_function("log10", 1, math.log10)
        conn.create_function("log1p", 1, math.log1p)
        conn.create_function("log2", 1, math.log2)
        conn.create_function("modf", 1, math.modf)
        conn.create_function("radians", 1, math.radians)
        conn.create_function("sin", 1, math.sin)
        conn.create_function("sinh", 1, math.sinh)
        conn.create_function("sqrt", 1, math.sqrt)
        conn.create_function("tan", 1, math.tan)
        conn.create_function("tanh", 1, math.tanh)
        conn.create_function("trunc", 1, math.trunc)
        conn.create_function("atan2", 2, math.atan2)
        conn.create_function("copysign", 2, math.copysign)
        conn.create_function("fmod", 2, math.fmod)
        conn.create_function("gcd", 2, math.gcd)
        conn.create_function("hypot", 2, math.hypot)
        conn.create_function("isclose", 2, math.isclose)
        conn.create_function("ldexp", 2, math.ldexp)
        conn.create_function("pow", 2, math.pow) 
Example 79
Project: Python-iBeacon-Scan   Author: NikNitro   File: test_functions.py    GNU General Public License v3.0 4 votes vote down vote up
def test_perturbation_rounding():
    mp.dps = 100
    a = pi/10**50
    b = -pi/10**50
    c = 1 + a
    d = 1 + b
    mp.dps = 15
    assert exp(a) == 1
    assert exp(a, rounding='c') > 1
    assert exp(b, rounding='c') == 1
    assert exp(a, rounding='f') == 1
    assert exp(b, rounding='f') < 1
    assert cos(a) == 1
    assert cos(a, rounding='c') == 1
    assert cos(b, rounding='c') == 1
    assert cos(a, rounding='f') < 1
    assert cos(b, rounding='f') < 1
    for f in [sin, atan, asinh, tanh]:
        assert f(a) == +a
        assert f(a, rounding='c') > a
        assert f(a, rounding='f') < a
        assert f(b) == +b
        assert f(b, rounding='c') > b
        assert f(b, rounding='f') < b
    for f in [asin, tan, sinh, atanh]:
        assert f(a) == +a
        assert f(b) == +b
        assert f(a, rounding='c') > a
        assert f(b, rounding='c') > b
        assert f(a, rounding='f') < a
        assert f(b, rounding='f') < b
    assert ln(c) == +a
    assert ln(d) == +b
    assert ln(c, rounding='c') > a
    assert ln(c, rounding='f') < a
    assert ln(d, rounding='c') > b
    assert ln(d, rounding='f') < b
    assert cosh(a) == 1
    assert cosh(b) == 1
    assert cosh(a, rounding='c') > 1
    assert cosh(b, rounding='c') > 1
    assert cosh(a, rounding='f') == 1
    assert cosh(b, rounding='f') == 1 
Example 80
Project: linear_neuron   Author: uglyboxer   File: isotonic.py    MIT License 4 votes vote down vote up
def check_increasing(x, y):
    """Determine whether y is monotonically correlated with x.

    y is found increasing or decreasing with respect to x based on a Spearman
    correlation test.

    Parameters
    ----------
    x : array-like, shape=(n_samples,)
            Training data.

    y : array-like, shape=(n_samples,)
        Training target.

    Returns
    -------
    `increasing_bool` : boolean
        Whether the relationship is increasing or decreasing.

    Notes
    -----
    The Spearman correlation coefficient is estimated from the data, and the
    sign of the resulting estimate is used as the result.

    In the event that the 95% confidence interval based on Fisher transform
    spans zero, a warning is raised.

    References
    ----------
    Fisher transformation. Wikipedia.
    http://en.wikipedia.org/w/index.php?title=Fisher_transformation
    """

    # Calculate Spearman rho estimate and set return accordingly.
    rho, _ = spearmanr(x, y)
    increasing_bool = rho >= 0

    # Run Fisher transform to get the rho CI, but handle rho=+/-1
    if rho not in [-1.0, 1.0]:
        F = 0.5 * math.log((1. + rho) / (1. - rho))
        F_se = 1 / math.sqrt(len(x) - 3)

        # Use a 95% CI, i.e., +/-1.96 S.E.
        # http://en.wikipedia.org/wiki/Fisher_transformation
        rho_0 = math.tanh(F - 1.96 * F_se)
        rho_1 = math.tanh(F + 1.96 * F_se)

        # Warn if the CI spans zero.
        if np.sign(rho_0) != np.sign(rho_1):
            warnings.warn("Confidence interval of the Spearman "
                          "correlation coefficient spans zero. "
                          "Determination of ``increasing`` may be "
                          "suspect.")

    return increasing_bool