def rho_harm(x, xp, beta):
    # here upsilon_1 and upsilon_2 are just exponents
    Upsilon_1 = sum((x[d] + xp[d]) ** 2 / 4.0 * \
                    math.tanh(beta / 2.0) for d in range(3))
    Upsilon_2 = sum((x[d] - xp[d]) ** 2 / 4.0 / \
                    math.tanh(beta / 2.0) for d in range(3))
    return math.exp(- Upsilon_1 - Upsilon_2)
Example #2
0
def levy_harmonic_path(k):
    x = [random.gauss(0.0, 1.0 / math.sqrt(2.0 * math.tanh(k * beta / 2.0)))]
    if k == 2:
        Ups1 = 2.0 / math.tanh(beta)
        Ups2 = 2.0 * x[0] / math.sinh(beta)
        x.append(random.gauss(Ups2 / Ups1, 1.0 / math.sqrt(Ups1)))
    return x[:]
Example #3
0
    def feedForward(self):
        nIn = len(self.wordIds)
        nHidden = len(self.hiddenIds)
        nOut = len(self.urlIds)

        # the only inputs are the query words
        for i in range(nIn):
            self.wordOut[i] = 1.0

        # hidden activations
        for i in range(nHidden):
            sum = 0.0

            for j in range(nIn):
                sum += self.wordOut[j] * self.wordHidden[j][i]

            self.hiddenOut[i] = tanh(sum)

        # output activations
        for i in range(nOut):
            sum = 0.0

            for j in range(nHidden):
                sum += self.hiddenOut[j] * self.hiddenUrl[j][i]

            self.urlOut[i] = tanh(sum)

        return self.urlOut[:]
Example #4
0
 def testHyperbolic(self):
     self.assertEqual(math.sinh(5), hyperbolic.sineh_op(5))
     self.assertEqual(math.cosh(5), hyperbolic.cosineh_op(5))
     self.assertEqual(math.tanh(5), hyperbolic.tangenth_op(5))
     self.assertEqual(1. / math.sinh(5), hyperbolic.cosecanth_op(5))
     self.assertEqual(1. / math.cosh(5), hyperbolic.secanth_op(5))
     self.assertEqual(1. / math.tanh(5), hyperbolic.cotangenth_op(5))
    def feed_forward(self):
        '''
        This returns the output of all the output nodes, with the inputs
        coming from the setup_network function.
        '''
        # first it sets the input word weights to 1.0
        for i in xrange(len(self.word_ids)):
            self.ai[i] = 1.0

        # then it iterates through all of the hidden nodes associated with
        # the words and urls (query and results) and uses a sigmoid to
        # accumulate the weights coming from the inputs (ai) and the
        # input weight matrix (wi) for each word-hidden_node relation.
        for j in xrange(len(self.hidden_ids)):
            sum = 0.0
            for i in xrange(len(self.word_ids)):
                sum = sum + self.ai[i] * self.wi[i][j]
            self.ah[j] = tanh(sum)

        # finally it iterates through all of the output nodes (urls)
        # and uses a sigmoid function to accumulate the weights
        # coming from the hidden nodes (ah) updated in the
        # previous step and the output weights (wo) for each
        # hidden_node-url relation.
        for k in xrange(len(self.url_ids)):
            sum = 0.0
            for j in xrange(len(self.hidden_ids)):
                sum = sum + self.ah[j] * self.wo[j][k]
            self.ao[k] = tanh(sum)

        return self.ao[:]
Example #6
0
 def _zoom_animation(self):
     import time
     from math import tanh
     scale = 5
     for i1 in range(-scale, scale+1):
         self.replot(zlfrac=0.5 + 0.5*tanh(i1*2.0/scale)/tanh(2.0))
         self.c.update()
def rho_harm(x, xp, beta):
    ''' Gives a diagonal harmonic density matrix, exchanging 2 particles '''
    Upsilon_1 = sum((x[d] + xp[d]) ** 2 / 4.0 *
                    math.tanh(beta / 2.0) for d in range(3))
    Upsilon_2 = sum((x[d] - xp[d]) ** 2 / 4.0 /
                    math.tanh(beta / 2.0) for d in range(3))
    return math.exp(- Upsilon_1 - Upsilon_2)
Example #8
0
    def set_eta1eta2(self, eta1, eta2):
        eta=sqrt(eta1**2 + eta2**2)

        if eta==0.:
            self.e1,self.e2,self.g1,self.g2=(0.,0.,0.,0.)
            return

        etot=tanh(eta)
        gtot=tanh(eta/2.)

        if etot >= 1.0:
            mess="e values must be < 1, found %.16g" % etot
            raise ShapeRangeError(mess)
        if gtot >= 1.0:
            mess="g values must be < 1, found %.16g" % gtot
            raise ShapeRangeError(mess)

        cos2theta = eta1/eta
        sin2theta = eta2/eta

        e1=etot*cos2theta
        e2=etot*sin2theta

        g1=gtot*cos2theta
        g2=gtot*sin2theta

        self.eta1,self.eta2=eta1,eta2
        self.e1,self.e2=e1,e2
        self.g1,self.g2=g1,g2
def we_context_mod(w, v, words,phrases,rep):
    w = deepcopy(w)
    v = deepcopy(v)
    for repet in range(rep):
        for o in range(len(words)):
            print o, ' of ', len(words)
            # h = np.zeros(prof)
            # for pal in phrases[c].split():
            #     h += v[words.index(pal)]
            # div = 0.0
            # for aux in w:
            #     div += math.exp(-1 * math.tanh(np.dot(aux, h)))
            for c in range(len(phrases)):
                ##
                h = np.zeros(prof)
                for pal in phrases[c].split():
                    h += v[words.index(pal)]
                div = 0.0
                for aux in w:
                    div += math.exp(-1 * math.tanh(np.dot(aux, h)))
                ##

                poc = math.exp(-1 * math.tanh(np.dot(w[o],h))) / div
                err = 0.0
                if words[o] in phrases[c]:
                    err = 1 - poc
                else:
                    err = 0 - poc

                v[o] = v[o] - (eta * err * h)

            for word in phrases[c].split():
                w[words.index(word)] -=  (eta * sum(v) / len(phrases[c].split()))

    return {'w': w, 'v':v}
Example #10
0
    def feedforward(self):
        # the only inputs are the query words
        for i in range(len(self.wordids)):
            self.ai[i] = 1.0
            # hidden activations

        for j in range(len(self.hiddenids)):
            sum = 0.0

            for i in range(len(self.wordids)):

                sum = sum + self.ai[i] * self.wi[i][j]

            self.ah[j] = tanh(sum) * 10

            # output activations
        for k in range(len(self.urlids)):
            sum = 0.0

            for j in range(len(self.hiddenids)):

                sum = sum + self.ah[j] * self.wo[j][k]

            self.ao[k] = tanh(sum)

        return self.ao[:]
Example #11
0
    def feed_forward(self):
        """
        フィードフォワードアルゴリズム
        """
        # 入力はクエリの単語たち?(aiの初期化)
        for i in range(len(self.wordids)):
            self.ai[i] = 1.0

        # 隠れ層の発火
        for j in range(len(self.hiddenids)):
            sum = 0.0
            for i in range(len(self.wordids)):
                # リンクの強度を掛け合わせる
                # TODO : なぜaiを使うのか。1.0直値ではいけない理由が不明
                # sum = sum + self.ai[j] * self.wi[i][j]
                sum = sum + 1.0 * self.wi[i][j]
            # tanhを適用して最終的な出力を作り出す
            self.ah[j] = tanh(sum)

        # 出力層の発火
        for k in range(len(self.urlids)):
            sum = 0.0
            for j in range(len(self.hiddenids)):
                sum = sum + self.ah[j] * self.wo[j][k]
            self.ao[k] = tanh(sum)

        return self.ao[:]
Example #12
0
def n_b_prof(coef,set,sol):
    tip = 7
    tipp = 1
    for y in range(1,set['Ny'],2):
        for x in range(1,set['Nx'],2):
            step = int(set['Ny']/(tip))
            range_1 = step
            range_2 = step*2+1
            range_3 = step*3
            range_4 = step*4+1
            range_5 = step*5
            range_6 = step*6+1
            if tipp == 1:
                if y > range_3 and y < range_4:
                    sol['n'][x,y] = 0.4*m.exp(-(x*set['Hh']-set['rad'])**2/0.0005)*(m.sin(tip*m.pi*y*set['Hh']))**2 
                    sol['b'][x,y] = (0.5 + 0.5*m.tanh(((set['rad']-0.05)-x*set['Hh'])/0.01))*(m.sin(tip*m.pi*y*set['Hh']))**2 
            else:   
                if y > range_1 and y < range_2: 
                    sol['n'][x,y] = 0.4*m.exp(-(x*set['Hh']-set['rad'])**2/0.0005)*(m.sin(tip*m.pi*y*set['Hh']))**2 
                    sol['b'][x,y] = (0.5 + 0.5*m.tanh(((set['rad']-0.05)-x*set['Hh'])/0.01))*(m.sin(tip*m.pi*y*set['Hh']))**2 
                if y > range_3 and y < range_4:
                    sol['n'][x,y] = 0.4*m.exp(-(x*set['Hh']-set['rad'])**2/0.0005)*(m.sin(tip*m.pi*y*set['Hh']))**2 
                    sol['b'][x,y] = (0.5 + 0.5*m.tanh(((set['rad']-0.05)-x*set['Hh'])/0.01))*(m.sin(tip*m.pi*y*set['Hh']))**2
                if y > range_5 and y < range_6:
                    sol['n'][x,y] = 0.4*m.exp(-(x*set['Hh']-set['rad'])**2/0.0005)*(m.sin(tip*m.pi*y*set['Hh']))**2 
                    sol['b'][x,y] = (0.5 + 0.5*m.tanh(((set['rad']-0.05)-x*set['Hh'])/0.01))*(m.sin(tip*m.pi*y*set['Hh']))**2
            
#             sol['n'][x,y] = 0.4*m.exp(-(x*set['Hh']-set['rad'])**2/0.01)*(m.sin(tip*m.pi*y*set['Hh']))**2 
#             sol['b'][x,y] = (m.sin(tip*m.pi*y*set['Hh']))**2*(0.5 + 0.5*m.tanh(((set['rad']-0.05)-x*set['Hh'])/0.01))  
#             if x*set['Hh'] <= set['rad']: 
    return sol
Example #13
0
 def skill_variation(self, K, V):
     """calcola la variazione di skill dei players K e V in seguito alla kill"""
     if self.PT[V].team == 3:
         return  # A volte viene killato qualcuno che risulta spect
     D = self.PT[K].skill - self.PT[V].skill  # Delta skill tra i due player
     Dk = self.PT[K].skill - self.TeamSkill[(self.PT[V].team - 1)]  # Delta skill Killer rispetto al team avversario
     Dv = self.TeamSkill[(self.PT[K].team - 1)] - self.PT[V].skill  # Delta skill Vittima rispetto al team avversario
     K_opponent_variation = (
         1 - math.tanh(D / self.Sk_range)
     ) / self.Sk_Kpp  # Variazione skill del Killer in base a skill vittima
     V_opponent_variation = (
         2 / self.Sk_Kpp - K_opponent_variation
     )  # Variazione skill della Vittima in base a skill killer
     KT_variation = (
         1 - math.tanh(Dk / self.Sk_range)
     ) / self.Sk_Kpp  # Variazione skill del Killer in base a skill team vittima
     VT_variation = (
         -(1 - math.tanh(Dv / self.Sk_range)) / self.Sk_Kpp
     )  # Variazione skill della Vittima in base a skill team killer
     Dsk_K = self.Sbil * (
         self.Sk_team_impact * KT_variation + (1 - self.Sk_team_impact) * K_opponent_variation
     )  # delta skill del Killer
     Dsk_V = self.Sbil * (
         self.Sk_team_impact * VT_variation + (1 - self.Sk_team_impact) * V_opponent_variation
     )  # delta skill della vittima
     self.PT[K].skill += Dsk_K * self.PT[K].skill_coeff  # (nuova skill)
     self.PT[V].skill += Dsk_V * self.PT[V].skill_coeff  # (nuova skill)
     self.PT[K].skill_var += Dsk_K  # variazione skill per mappa
     self.PT[V].skill_var += Dsk_V  # variazione skill per mappa
     return
Example #14
0
	def Evap(self, p0, p1, t1, tau, beta, duration):
		"""Evaporation ramp"""
		if duration <=0:
			return
		else:
			N=int(round(duration/self.ss))
			print '...Evap nsteps = ' + str(N)
			ramp=[]
			ramphash = 'L:/software/apparatus3/seq/ramps/' + 'Evap_' \
					   + hashlib.md5(str(self.ss)+str(duration)+str(p0)+str(p1)+str(t1)+str(tau)+str(beta)).hexdigest()
			if not os.path.exists(ramphash):
				print '...Making new Evap ramp'
				for xi in range(N):
					t = (xi+1)*self.ss
					if t < t1:
						phys =  (p0-p1)*math.tanh( beta/tau * (t-t1)* p1/(p0-p1))/math.tanh( beta/tau * (-t1) * p1/(p0-p1)) + p1
					else:
						phys =   p1 * math.pow(1,beta) / math.pow( 1 + (t-t1)/tau ,beta)
					volt = cnv(self.name,phys)
					ramp = numpy.append( ramp, [ volt])
				ramp.tofile(ramphash,sep=',',format="%.4f")
			else:
				print '...Recycling previously calculated Evap ramp'
				ramp = numpy.fromfile(ramphash,sep=',')

			self.y=numpy.append(self.y,ramp)
			
		return
Example #15
0
def tanh(self, other=None):
# Return hyperbolic tangent of interval
	
 	if other != None:
  		intv = IReal(self, other)
 	else:
  		if type(self) == float or type(self) == str:
   			intv = IReal(self)
  		else:
   			intv = self
 
 	if math.tanh(intv.inf) > math.tanh(intv.sup):
		inf = max(intv.inf, intv.sup)
		sup = min(intv.inf, intv.sup)
	else:
		inf = intv.inf
		sup = intv.sup


 	ireal.rounding.set_mode(1)

 	ireal.rounding.set_mode(-1)
 	ireal.rounding.set_mode(-1)

 	new_inf = math.tanh(inf)
 	ireal.rounding.set_mode(1)
	new_sup = max(float(IReal('%.16f' % math.tanh(sup)).sup), float(IReal('%.19f' % math.tanh(sup)).sup))

 	return IReal(new_inf, new_sup)
Example #16
0
    def compute(self, plug, data):

        #   Check if output value is connected
        if plug == self.aOutputVaue:

            #    Get input datas
            operationTypeHandle = data.inputValue(self.aOperationType)
            operationType = operationTypeHandle.asInt()

            inputValueXHandle = data.inputValue(self.aInputValueX)
            inputValueX = inputValueXHandle.asFloat()

            inputValueYHandle = data.inputValue(self.aInputValueY)
            inputValueY = inputValueYHandle.asFloat()
            
            #   Math tanus
            outputValue = 0
            if operationType == 0:
                outputValue = math.atan(inputValueX)
            if operationType == 1:
                outputValue = math.tan(inputValueX)
            if operationType == 2:
                outputValue = math.atanh(inputValueX)
            if operationType == 3:
                outputValue = math.tanh(inputValueX)
            if operationType == 4:
                outputValue = math.tanh(inputValueY, inputValueX)

            #   Output Value
            output_data = data.outputValue(self.aOutputVaue)
            output_data.setFloat(outputValue)

        #   Clean plug
        data.setClean(plug)
	def feedforward(self):
		""" the feedforward algorithm. This takes a list of inputs,
		pushes them through the network, and returns the output of all the nodes in the out
		put layer. In this case, since youve only constructed a network with words in the
		query, the output from all the input nodes will always be 1:
		"""
		# The only inputs are the query words
		for i in range(len(self.wordids)):
			self.ai[i] = 1.0

		# Hidden activations
		for j in range(len(self.hiddenids)):
			sum = 0.0
			for i in range(len(self.wordids)):
				sum =sum + self.ai[i] * self.wi[i][j]
			self.ah[j] = tanh(sum)

		# output activations
		for k in range(len(self.urlids)):
			sum = 0.0
			for j in range(len(self.hiddenids)):
				sum = sum + self.ah[j] * self.wo[j][k]
			self.ao[k] = tanh(sum)

		return self.ao[:]  # Return a copy of self.ao 
Example #18
0
 def get_gm(self, xxx_todo_changeme2, dev, debug=False):
     """Returns the source to output transconductance or d(I)/d(Vsn1-Vsn2)."""
     (vout, vin) = xxx_todo_changeme2
     self._update_status(vin, dev)
     gm = self.A * self.SLOPE * (math.tanh(self.SLOPE * (self.V - vin)) ** 2 - 1) / (
         self.A * math.tanh(self.SLOPE * (self.V - vin)) - self.B) ** 2
     return gm + options.gmin
Example #19
0
def score(filename):
    """
    Score individual image files for the genetic algorithm.
    The idea is to derive predictive factors for the langmuir performance
    (i.e., max power) based on the connectivity, phase fractions, domain sizes,
    etc. The scoring function should be based on multivariate fits from a database
    of existing simulations. To ensure good results, use robust regression techniques
    and cross-validate the best-fit.

    :param filename: image file name
    :type filename: str

    :return score (ideally as an estimated maximum power in W/(m^2))
    :rtype float
    """
    # this works around a weird bug in scipy.misc.imread with 1-bit images
    # open them with PIL as 8-bit greyscale "L" and then convert to ndimage
    pil_img = Image.open(filename)
    image = misc.fromimage(pil_img.convert("L"))

    width, height = image.shape
    if width != 256 or height != 256:
        print "Size Error: ", filename

    #    isize = analyze.interface_size(image)
    ads1, std1 = analyze.average_domain_size(image)

    # we now need to invert the image to get the second domain size
    inverted = (image < image.mean())
    ads2, std2 = analyze.average_domain_size(inverted)

    #overall average domain size
    ads = (ads1 + ads2) / 2.0

    # transfer distances
    # connectivity
    td1, connect1, td2, connect2 = analyze.transfer_distance(image)

    spots = np.logical_xor(image,
        ndimage.binary_erosion(image, structure=np.ones((2,2))))
    erosion = np.count_nonzero(spots)

    spots = np.logical_xor(image,
        ndimage.binary_dilation(image, structure=np.ones((2,2))))
    dilation = np.count_nonzero(spots)

    # fraction of phase one
    nonzero = np.count_nonzero(image)
    fraction = float(nonzero) / float(image.size)
    # scores zero at 0, 1 and maximum at 0.5
    ps = fraction*(1.0-fraction)

    # from simulations with multivariate nonlinear regression
    return (-1.98566e8) + (-1650.14)/ads + (-680.92)*math.pow(ads,0.25) + \
           1.56236e7*math.tanh(14.5*(connect1 + 0.4)) + 1.82945e8*math.tanh(14.5*(connect2 + 0.4)) \
           + 2231.32*connect1*connect2 \
           + (-4.72813)*td1 + (-4.86025)*td2 \
           + 3.79109e7*ps**8 \
           + 0.0540293*dilation + 0.0700451*erosion
Example #20
0
	def getallhiddenids(self,wordids,urlids):
		l1={}
		for wordid in wordids:
			cur=self.con.execute('select toid from wordhidden where from id=%d'% wordid)
			for  row in cur: l1[row[0]=1
		for urlid in urlids:
			cur=self.con.select('select fromid from hiddenurl where toid=%d'% urlid)
			for row in cur:l1[row[0]]=1
		return l1.keys()
	def setupnetwork(self,wordids,urlids):
		self.wordids=wordids
		self.hiddenids=self.getallhiddenids(wordids,urlids)
		self.urlids=self.urlids
		
		self.ai=[1.0]*len(self.wordids)
		self.ah=[1.0]*len(self.hiddenids)
		self.ao=[1.0]*len(self.urlids)
		
		self.wi=[[self.getstrength(wordid,hiddenid,0) for hiddenid in self.hiddenids] for wordid in self.wordids]
		self.wo=[[self.getstrenth(hiddenid,urlid,1) for urlid in self.urlids]for hiddenid in self.hiddenids]
	def feedforward(self):
		for i in range(len(self.wordids)):
			self.ai[i]=1
		
		for j in range(len(self.hiddenids)):
			sum=0.0
			for i in range(len(self.wordids)):
				sum=sum+self.ai[i]*self.wi[i][j]
			self.ah[j]=tanh(sum)
		for k in range(len(self.urlids)):
			sum=0.0
			for j in range(len(self.hiddenids)):
				sum=sum+self.ah[j]*self.wo[j][k]
			self.ao[k]=tanh(sum)
		return self.ao[:]
	def getresult(self,wordids,urlids):
		self.setupnetwork(wordids,urlids)
		return self.feedforward()
	def dtanh(y):
		return 1.0-y*y
	def backPropagete(self,targets,N=0.5):
		output_deltas=[0.0]*len(self.urlids)
		for k in range(len(self.urlids)):
			error=targets[k]-self.ao[k]
			output_deltas=dtanh(self.ao[k]])*error
		hidden_deltas=[0.0]*len(self.hiddenids)
		for j in range(len(self.hidddenids)):
			error=0.0
			for k in range(len(self.len(urlids))):
				error=error+output[k]*self.wo[j][k]
			hidden_deltas[j]=dtanh(self.ah[j])*error
		for j in range(len(self.hiddenids)):
			for k in range(len(self.urlids)):
				change = output_delta[k]*self.ah[j]
				self.wo[j][k]=self.wo[j][k]+N*change
		for i in range(len(self.wordids)):
			for j in range(len(self.hiddenids)):
				change=hidden_delta[j]*self.ai[i]
				self.wi[i][j]=self.wi[i][j]+N*change
def distance_Sigmoid(X,Y,a,r):
    d = np.dot(X,X)
    d = math.tanh(a * d + r)
    b = np.dot(Y,Y)
    b = math.tanh(a * b + r)
    c = np.dot(X,Y)
    c = math.tanh(a * c + r)
    return a + b - 2 * c
Example #22
0
def levy_harmonic_path(xstart, xend, dtau, N):
    x = [xstart]
    for k in range(1, N):
        dtau_prime = (N - k) * dtau
        Ups1 = 1.0 / math.tanh(dtau) + 1.0 / math.tanh(dtau_prime)
        Ups2 = x[k-1] / math.sinh(dtau) + xend / math.sinh(dtau_prime)
        x.append(random.gauss(Ups2 / Ups1, 1.0 / math.sqrt(Ups1)))
    return x
def st_tanh(x):
    if isinstance(x, StataVarVals):
        return StataVarVals([
            mv if _is_missing(v) else math.tanh(v) for v in x.values
        ])
    if _is_missing(x):
        return mv
    return math.tanh(x)
 def __init__(self):
     ActivationFunction.__init__(
         self,
         lambda x: math.tanh(x),
         # This could be optimized as the derivative
         # will always be called after the fn.
         # And will be called with the same x value.
         lambda x: 1 - math.pow(math.tanh(x), 2))
Example #25
0
 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 #26
0
def run_gr4j(x, p, e, q, s, uh1_tab, uh2_tab, l, m):
    for t in range(p.size):
        if p[t] > e[t]:
            pn = p[t] - e[t]
            en = 0.0
            tmp = s[0] / x[0]
            ps = x[0] * (1.0 - tmp * tmp) * math.tanh(pn / x[0]) / (1.0 + tmp * math.tanh(pn / x[0]))
            s[0] += ps
        elif p[t] < e[t]:
            ps = 0.0
            pn = 0.0
            en = e[t] - p[t]
            tmp = s[0] / x[0]
            es = s[0] * (2.0 - tmp) * np.tanh(en / x[0]) / (1.0 + (1.0 - tmp) * np.tanh(en / x[0]))
            tmp = s[0] - es
            if tmp > 0.0:
                s[0] = tmp
            else:
                s[0] = 0.0
        else:
            pn = 0.0
            en = 0.0
            ps = 0.0
        tmp = 4.0 * s[0] / (9.0 * x[0])
        perc = s[0] * (1.0 - (1.0 + tmp * tmp * tmp * tmp) ** (-1.0 / 4.0))
        s[0] -= perc
        pr_0 = perc + pn - ps
        q9 = 0.0
        q1 = 0.0
        for i in range(m):
            if i == 0:
                pr_i = pr_0
            else:
                pr_i = s[2 + i - 1]
            if i < l:
                q9 += uh1_tab[i] * pr_i
            q1 += uh2_tab[i] * pr_i
        q9 *= 0.9
        q1 *= 0.1
        f = x[1] * ((s[1] / x[2]) ** (7.0 / 2.0))
        tmp = s[1] + q9 + f
        if tmp > 0.0:
            s[1] = tmp
        else:
            s[1] = 0.0
        tmp = s[1] / x[2]
        qr = s[1] * (1.0 - ((1.0 + tmp * tmp * tmp * tmp) ** (-1.0 / 4.0)))
        s[1] -= qr
        tmp = q1 + f
        if tmp > 0.0:
            qd = tmp
        else:
            qd = 0.0
        q[t] = qr + qd
        for i in range(s.size - 2 - 2, -1, -1):
            s[2 + i + 1] = s[2 + i]
        if s.size > 2:
            s[2] = pr_0
Example #27
0
def check_increasing(x, y):
    """Determine whether the relationship between x and y appears to be
    increasing or decreasing based on Spearman correlation.

    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
    -----
    Determine whether the relationship between x and y appears to be
    increasing or decreasing.  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)
    if rho >= 0:
        increasing_bool = True
    else:
        increasing_bool = False

    # 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
Example #28
0
def pi_two_bosons(x, beta):
    pi_x_1 = math.sqrt(math.tanh(beta / 2.0)) / math.sqrt(math.pi) *\
             np.exp(-x ** 2 * math.tanh(beta / 2.0))
    pi_x_2 = math.sqrt(math.tanh(beta)) / math.sqrt(math.pi) *\
             np.exp(-x ** 2 * math.tanh(beta))
    weight_1 = z(beta) ** 2 / (z(beta) ** 2 + z(2.0 * beta))
    weight_2 = z(2.0 * beta) / (z(beta) ** 2 + z(2.0 * beta))
    pi_x = pi_x_1 * weight_1 + pi_x_2 * weight_2
    return pi_x
Example #29
0
def tanhfilter(nx, fl, aa):
	#  generate discretized tanh filter
	from math import pi, tanh
	n = nx//2 + nx%2
	f = [0.0]*n
	for i in xrange(n):
		x = float(i)/nx
		f[i] = 0.5*( tanh(pi*(x+fl)/2.0/aa/fl) - tanh(pi*(x-fl)/2.0/aa/fl) )
	return  [[float(i)/nx for i in xrange(n)],f]
def uTOpwm(u):
    
    pwm = np.array([0.0,0.0])
    
    pwm[0] = 1800 + 200 * math.tanh(u[0]-1)
    
    pwm[1] = 1500 + 500 * math.tanh(u[1])
    
    return pwm
def run(_numAgents, _squareFactor, _generations, _cuttOff, _badImagesStart):
    numAgents = _numAgents  #100
    squareFactor = _squareFactor  #0.5
    numShapes = 4
    imageSize = 6 * 6
    #middleNeurons = 3
    #lastNeurons = 1
    generations = _generations  #200 #Number of Generations
    generation = 1  #Starting Generation
    cutOff = _cuttOff  #20 #Number of Agents Moving to Next generation
    badImagesStart = _badImagesStart  #4-1

    random.seed(time.time() * 1000)

    Agents = []
    BestAgent = []
    BestAgent2 = []
    BestAgent3 = []

    for i in range(0, numAgents):

        #print(i)    #debugging
        NeuronLinks = []
        #for i in range(0,imageSize*imageSize):
        #    agent.append(random.random())
        for i in range(0, 6):
            NeuronLinks.append(random.random())
            #random.seed(time.time()*1000+10)
        for i in range(0, middleNeurons):
            NeuronLinks.append(random.random())
            #random.seed(time.time()*1000)
        Agents.append(NeuronLinks)
        #print(len(NeuronLinks))
    #print(Agents)   #debugging

    #print(Agents[0])
    #print(Agents[1])

    # Import Image Data
    print('This many samples:')
    images = imageImport.getImages()
    print(len(images))

    # Main Loop
    while generation != generations + 1:

        random.seed(time.time() * 1000)
        #image = round(random.random()*(len(images)-1))
        #objectDataSL = images[image]

        print('-----------')
        print('Generation:')
        print(generation)
        print('-----------')

        perImageAgentScores = []

        for image in images:
            AgentScores = []
            objectDataSL = image
            for agentNum in range(0, numAgents):
                NeuronLinks = Agents[agentNum]
                # First row connects to First Neuron, 2nd row to 2nd etc.
                Layer1Nodes = []
                for k in range(0, 6):
                    #Simply each row adds to become the first neuron (goes through a function) (was averaging, now its tanh).
                    valueAt_k = (objectDataSL[k * 6] +
                                 objectDataSL[(k * 6) + 1] +
                                 objectDataSL[(k * 6) + 2] +
                                 objectDataSL[(k * 6) + 3] +
                                 objectDataSL[(k * 6) + 4] +
                                 objectDataSL[(k * 6) + 5])
                    valueAt_k = float((1 / 2) * (math.tanh(
                        (1 / 2) * (valueAt_k - 3)) + 1))
                    Layer1Nodes.append(valueAt_k)

                #print(Layer1Nodes)

                #There are 3 middle neurons
                Layer2Nodes = []
                for k in range(0, middleNeurons):
                    valueAt_k = ((Layer1Nodes[k * 2] * NeuronLinks[k * 2]) +
                                 (Layer1Nodes[(k * 2) + 1] * NeuronLinks[
                                     (k * 2) + 1])) * 2
                    valueAt_k = float((1 / 2) * (math.tanh(
                        (2) * (valueAt_k - 1)) + 1))
                    Layer2Nodes.append(valueAt_k)

                #print(Layer2Nodes)

                #There is 1 single output.
                Layer3Nodes = []
                for k in range(0, lastNeurons):
                    valueAt_k = (
                        (Layer2Nodes[k] * NeuronLinks[k + 6]) +
                        (Layer2Nodes[k + 1] * NeuronLinks[k + 6 + 1]) +
                        (Layer2Nodes[k + 2] * NeuronLinks[k + 6 + 2])) * 2
                    valueAt_k = float((1 / 2) * (math.tanh(
                        (1) * (valueAt_k - (3 / 2))) + 1))
                    Layer3Nodes.append(valueAt_k)

                #print(Layer3Nodes)

                AgentScores.append(Layer3Nodes[0])
            perImageAgentScores.append(AgentScores)
            #if Layer3Nodes[0] > squareFactor:
            #print('A Square!')
            #squareScore+=1
            #else:
            #print('Not a Square!')

        #print(perImageAgentScores)

        #Score Agents:
        AgentScores = []
        for agent in range(0, len(Agents)):
            agentScore = 0
            GenerationScore = []
            for image in range(0, badImagesStart):
                if perImageAgentScores[image][agent] > squareFactor:
                    agentScore += 1
                    GenerationScore.append('Square')
                else:
                    GenerationScore.append('Not Square')
            for image in range(badImagesStart, len(images)):
                if perImageAgentScores[image][agent] < squareFactor:
                    agentScore += 1
                    GenerationScore.append('Not Square')
                else:
                    GenerationScore.append('Square')
            AgentScores.append(agentScore)

        # Sort Agents Based on Score
        #print(bubbleSort.sort(AgentScores, Agents))
        sortedAgents = bubbleSort.sort(AgentScores, Agents)
        #print(AgentScores)
        #print(sortedAgents)
        BestAgent = sortedAgents[-1:]
        BestAgent2 = sortedAgents[-2:-1]
        BestAgent3 = sortedAgents[-3:-2]

        # Kill low scoring agents
        AliveAgents = sortedAgents[-cutOff:]

        # Breed and Mutate Agents
        NewAgents = []
        for i in range(0, int((numAgents - (numAgents - cutOff)) / 2)):
            newAgent = AliveAgents[i * 2][0:5] + AliveAgents[
                (i * 2) + 1][5:len(AliveAgents[0])]
            NewAgents.append(newAgent)

        #Mutation
        NewAgents[int(random.random() * (len(NewAgents) - 2))][int(
            random.random() * (len(NewAgents[0]) - 2))] = random.random()
        NewAgents[int(random.random() * (len(NewAgents) - 2))][int(
            random.random() * (len(NewAgents[0]) - 2))] = random.random()
        #NewAgents[int(random.random()*len(NewAgents))-1][int(random.random()*len(NewAgents[0]))] = random.random()

        #Missing Agents
        newAgent = []
        for k in range(0, numAgents - (len(NewAgents) + len(AliveAgents))):
            for i in range(0, 43 - 34):
                newAgent.append(random.random())
                #random.seed(time.time()*1000)
            NewAgents.append(newAgent)

        Agents = NewAgents + AliveAgents
        print(len(Agents[0]))
        #print(len(Agents))

        # THIS IS END OF LOOP
        os.system('cls')
        generation += 1

        if (generation == generations + 1):
            print(AgentScores)
            print(GenerationScore)
            print(BestAgent)

    return BestAgent[0]

    #After the Loop
    print(AgentScores)
    print(GenerationScore)
    print(BestAgent)
Example #32
0
def tangentehiper(value):
    return math.tanh(value)
Example #33
0
from collections import namedtuple
NodeParams = namedtuple("Node", "name additional frm")


def f_rlu(a, x):
    if x >= 0:
        return x
    else:
        return x * (1.0 / a)


func = {
    'var':
    lambda params, x: x,
    'tnh':
    lambda params, x: np.array(list(map(lambda z: math.tanh(z), x[0].flatten())
                                    ),
                               dtype="float64").reshape(x[0].shape),
    'rlu':
    lambda params, x: np.array(list(
        map(lambda z: f_rlu(params[0], z), x[0].flatten())),
                               dtype="float64").reshape(x[0].shape),
    'mul':
    lambda params, x: x[0].dot(x[1]),
    'sum':
    lambda params, x: reduce(lambda p1, p2: p1 + p2, x),
    'had':
    lambda params, x: reduce(lambda p1, p2: p1 * p2, x),
}

Example #34
0
    'exp': [math.exp],
    'expm1': [math.exp],
    'fabs': [_deriv_fabs],
    'hypot': [lambda x, y: x/math.hypot(x, y),
              lambda x, y: y/math.hypot(x, y)],
    'log': [log_der0,
            lambda x, y: -math.log(x, y)/y/math.log(y)],
    'log10': [lambda x: 1/x/math.log(10)],
    'log1p': [lambda x: 1/(1+x)],
    'pow': [_deriv_pow_0, _deriv_pow_1],
    'radians': [lambda x: math.radians(1)],
    'sin': [math.cos],
    'sinh': [math.cosh],
    'sqrt': [lambda x: 0.5/math.sqrt(x)],
    'tan': [lambda x: 1+math.tan(x)**2],
    'tanh': [lambda x: 1-math.tanh(x)**2]
    }

# Many built-in functions in the math module are wrapped with a
# version which is uncertainty aware:

this_module = sys.modules[__name__]

def wrap_locally_cst_func(func):
    '''
    Return a function that returns the same arguments as func, but
    after converting any AffineScalarFunc object to its nominal value.

    This function is useful for wrapping functions that are locally
    constant: the uncertainties should have no role in the result
    (since they are supposed to keep the function linear and hence,
Example #35
0
 def tanh_activation(self):
     return math.tanh(self.membrane_potential)
Example #36
0
 def getSigmoid(self):
     s = lambda d: 1.7159 * math.tanh(.6666 * d)
     return numpy.vectorize(s)
Example #37
0
def drop_chance(length, maximum):
    return tanh(float(length - maximum) / maximum * 2.0)
def opera(y):
    # En caso de ENTER sin número...
    print("__________________")
    # Árbol condicional de opciones.
    if (y == 0):
        username = getpass.getuser()
        print("Saliendo del programa... Adiós {:2}! ".format(username))
        time.sleep(3)
        os.system('clear')
        os.system('cls')
        sys.exit()
    elif (y == 1):
        print("Opción: Suma")
        a = int(input("Introduzca el primer número: "))
        b = int(input("Introduzca el segundo número: "))
        print("\n")
        resultado = (a + b)
        print("El resultado es: ", resultado)
    elif (y == 2):
        print("Opción: Resta")
        a = int(input("Introduzca el primer número: "))
        b = int(input("Introduzca el segundo número: "))
        resultado = a - b
        print("El resultado es: ", resultado)
    elif (y == 3):
        print("Opción: Multiplicación")
        a = int(input("Introduzca el primer número: "))
        b = int(input("Introduzca el segundo número: "))
        resultado = (a * b)
        print("El resultado es: ", resultado)
    elif (y == 4):
        print("Opción: División")
        a = int(input("Introduzca el primer número: "))
        b = int(input("Introduzca el segundo número: "))
        resultado = (a / b)
        resto = (a % b)
        print("El resultado es: ", resultado, " y de resto: ", resto)
    elif (y == 5):
        print("Opción: Porcentaje")
        b = int(input("¿Porcentaje? (Número) "))
        a = int(input("¿A qué le calculamos el {:2}% ?: ".format(b)))
        resultado = ((a * b) / 100)
        print("El ", b, "% de ", a, " es: ", resultado)
    elif (y == 6):
        print("Opción: Exponencial al cuadrado")
        a = int(input("Introduzca el número: "))
        resultado = (a**2)
        print("El resultado de {:2} a la '2' es: ".format(a), resultado)
    elif (y == 7):
        print("Opción: Exponente a la 'x'")
        a = int(input("Introduzca el número natural: "))
        b = int(input("¿A cuánto lo exponemos? "))
        resultado = (a**b)
        print("El resultado de {:2} a la  {:2} es: ".format(a, b), resultado)
    elif (y == 8):
        print("Opción:Polinomio de primer grado")
        a = int(input("Introduzca valor de las 'X's' : "))
        b = int(input("Introduzca valor de los enteros : "))
        resultado = (b / a)
        print("El resultado de {:2}x+({:2}) = 0, X = ".format(a, b), resultado)
    elif (y == 9):
        print("Opción: Polinomio de segundo grado")
        a = int(input("Introduzca valor de las 'X^2' : "))
        b = int(input("Introduzca valor de las 'X' : "))
        c = int(input("Introduzca valor de los enteros : "))
        calc = ((b**2) - (4 * a * c))
        if calc < 0:
            print(50 * "*")
            print("No puedo calular una raiz negativa... Sorry")
            print(50 * "*")
        else:
            resultado1 = (((-b) + math.sqrt(calc)) / (2 * a))
            resultado2 = (((-b) - math.sqrt(calc)) / (2 * a))
            print(
                "El resultado para +X de {:2}x^2+({:2}x)+({:2}) = 0 es: ".
                format(a, b, c), resultado1)
            print(
                "El resultado para -X de {:2}x^2+({:2}x)+({:2}) = 0 es: ".
                format(a, b, c), resultado2)
    elif (y == 10):
        print("Opción: Raíz cuadrada")
        a = int(input("Introduzca el número: "))
        resultado = (math.sqrt(a))
        print("El resultado es:", resultado)
    elif (y == 11):
        print("Opción: DEC a BIN")

        def binario(decimal):
            binario = ''
            while decimal // 2 != 0:
                binario = str(decimal % 2) + binario
                decimal = decimal // 2
            return str(decimal) + binario

        numero = int(input('Introduce el número a convertir a binario: '))
        print(numero, "> ", binario(numero))
        # OPCION FÁCIL: bin(numero)
        print("Opción 2: bin()")
        print(bin(numero)[2:])
    elif (y == 12):
        print("Opción: BIN a DEC")

        def decimal(binario):
            decimal = int(str(binario), 2)
            return decimal

        numero = int(input('Introduce el número a convertir a decimal: '))
        print(numero, "> ", decimal(numero))
    elif (y == 13):
        print("Opción: DEC a HEX")
        # def hexadec(decimal, base):
        #     conversion = ''
        #     while decimal // base != 0:
        #         conversion = str(decimal % base) + conversion
        #         decimal = decimal // base
        #         primero = str(decimal)
        #         segundo = conversion
        #         print(primero, "\n")
        #         print(segundo, "\n")
        #         #print(type(primero))
        #         #print(type(segundo))
        #         if primero == '10':
        #             primero = 'A'
        #         elif primero == '11':
        #             primero = 'B'
        #         elif primero == '12':
        #             primero = 'C'
        #         elif primero == '13':
        #             primero = 'D'
        #         elif primero == '14':
        #             primero = 'E'
        #         elif primero == '15':
        #             primero = 'F'
        #         if segundo == '10':
        #             segundo = 'A'
        #         elif segundo == '11':
        #             segundo = 'B'
        #         elif segundo == '12':
        #             segundo = 'C'
        #         elif segundo == '13':
        #             segundo = 'D'
        #         elif segundo == '14':
        #             segundo = 'E'
        #         elif segundo == '15':
        #             segundo = 'F'
        #         return (primero+segundo)
        numero = int(input('Introduce el número a cambiar de base: '))
        base = 16
        print(hex(numero)[2:])
        # print("Opción 2: \n", hexadec(numero, base))
    elif (y == 14):
        print("Opción: DEC a base 'X'")

        def cambio_base(decimal, base):
            conversion = ''
            while decimal // base != 0:
                conversion = str(decimal % base) + conversion
                decimal = decimal // base
            return str(decimal) + conversion

        numero = int(input('Introduce el número a cambiar de base: '))
        base = int(input('Introduce la base: '))
        print(cambio_base(numero, base))
    elif (y == 15):
        print("Opción: LOGARITMO EN CUALQUIER BASE.")
        a = float(input("Introduzca el número: "))
        b = int(input("¿Qué base? "))
        if a < 0.1:
            print(
                "TE RECUERDO QUE: \n Los logaritmos no deben ser mayores que cero."
            )
        else:
            resultado = math.log(a, b)
            print(
                "El resultado del logaritmo {:2} en base {:2} es:".format(
                    a, b), resultado)
    elif (y == 16):
        print("Opción: LOGARITMO NEPERIANO DE UN NÚMERO.")
        a = float(input("Introduzca el número: "))
        if a < 0.1:
            print(
                "TE RECUERDO QUE: \n Los logaritmos no deben ser mayores que cero."
            )
        else:
            resultado = (a)
            print("El resultado del logaritmo neperiano de {:2} es:".format(a),
                  resultado)
            print("ESTE DE MOMENTO NO LO HE SACADO...")
    elif (y == 17):
        print("Opción: Lado desconocido de un triángulo.")
        tipo = input("""
        ¿Qué tipo de triángulo es? (A-D)
            a. - Equilatero
            b. - Isóceles
            c. - Escaleno
            d. - Rectángulo
        """)
        print("Genial, ha seleccionado: ", tipo)
        print()
        if tipo == 'a' or tipo == 'A':
            lado = int(input("Introduzca valor del lado: "))
            print(
                "Como es un triángulo equilatero, todos sus lados son iguales, asi que"
            )
            print("El lado desconocido es: ", lado)
        elif tipo == 'b' or tipo == 'B':
            lado2 = input("¿Es el lado desigual? (Y/N) ")
            if lado2 == 'y' or lado2 == 'Y':
                a = int(input("Introduzca valor del lado que conoce: "))
                interior = (2 * (a**2) - (2 * (a**2) * math.cos(60)))
                b = (math.sqrt(interior))
                print("El lado que desconoce mide: ", b)
            else:
                print("Como es isóceles, dos de sus lados son iguales.")
                print("Lado desconocido: ", a)
        elif tipo == 'c' or tipo == 'C':
            print("""
                       
                A
                *
                | + +
                |  +    +
                |   +     +    
            h   |     +     +   c
                |      +       +        
                |     b +        +          
                |        +          +    
                |         +           +      
                |          +              +    
            -+-        C *---------------* B
                               a
            """)
            h = input("¿Sabes la altura (h)? (Y/N) ")
            if h == 'N' or h == 'n':
                print("Genial!")
                lado = input("¿Qué lado desconocemos? (a/b/c)")
                lado = lado.upper
                if lado == 'A':
                    ang = float(input("¿Ángulo de 'A'? "))
                    b = float(input("Lado 'b': "))
                    c = float(input("Lado 'c': "))
                    a = ((b**2) + (c**2) - (2 * b * c * math.cos(ang)))
                    print()
                    print("""Tenemos:
                    - a: {:2}
                    - b: {:2}
                    - c: {:2}
                    """.format(a, b, c))
                elif lado == 'B':
                    ang = float(input("¿Ángulo de 'B'? "))
                    a = float(input("Lado 'a': "))
                    c = float(input("Lado 'c': "))
                    b = ((a**2) + (c**2) - (2 * a * c * math.cos(ang)))
                    print()
                    print("""Tenemos:
                    - a: {:2}
                    - b: {:2}
                    - c: {:2}
                    """.format(a, b, c))
                elif lado == 'C':
                    ang = float(input("¿Ángulo de 'C'? "))
                    a = float(input("Lado 'a': "))
                    b = float(input("Lado 'b': "))
                    c = ((b**2) + (a**2) - (2 * b * a * math.cos(ang)))
                    print()
                    print("""Tenemos:
                    - a: {:2}
                    - b: {:2}
                    - c: {:2}
                    """.format(a, b, c))
                else:
                    print("Error en los datos de entrada")
            else:
                h = input("Dime la altura")
                lado = input("¿Qué lado calculamos? (A-C) ")
                lado = lado.upper
                if lado == 'A':
                    ang = float(input(" ¿Ángulo de 'B'? "))
                    a = h / (math.sin(ang))
                    print("El lado 'a' mide: ", a)
                elif lado == 'B':
                    ang = float(input(" ¿Ángulo de 'A'? "))
                    b = h / (math.sin(ang))
                    print("El lado 'a' mide: ", b)
                elif lado == 'C':
                    a = float(input("Valor de 'a': "))
                    b = float(input("Valor de 'b': "))
                    if h < b:
                        hipo = h**2
                        cat2 = b**2
                    else:
                        hipo = b**2
                        cat2 = h**2
                    x = (math.sqrt(hipo - cat2))
                    base = x + a
                    c = math.sqrt((base**2) + (h**2))
                    print("El lado 'c' mide: ", c)
                else:
                    print("Error en los datos de entrada")
        elif tipo == 'd' or tipo == 'D':
            lado = input("¿Qué lado desconoce? (c1 , c2 o h) ")
            if lado == 'c1' or lado == 'C1':
                h = input("Hipotenusa: ")
                c2 = input("Cateto :")
                c1 = math.sqrt((h**2) - (c2**2))
                print(" La medida del cateto es: ", c1)
            elif lado == 'c2' or lado == 'C2':
                h = input("Hipotenusa: ")
                c1 = input("Cateto :")
                c2 = math.sqrt((h**2) - (c1**2))
                print(" La medida del cateto es: ", c2)
            elif lado == 'h' or lado == 'H':
                c1 = input("Cateto 1: ")
                c2 = input("Cateto 2:")
                h = math.sqrt((c1**2) + (c2**2))
                print(" La medida de la hipotenusa es: ", h)
    elif (y == 18):
        print("Opción:Trigonometría")
        ang = float(input("¿Ángulo? "))
        print("")
        print("""
        OPCIONES (Sin usar pitágoras):
        Calcula
            1- La tangente de un ángulo. 
            2- El seno de un ángulo.
            3- El coseno de un ángulo.
            4- La cotangente de un ángulo
        """)
        opcion = int(input("Seleccione una opcion: "))

        c1 = math.tan(ang)
        c2 = math.sin(ang)
        c3 = math.cos(ang)
        c4 = math.tanh(ang)

        # Diccionario de minioperaciones
        opciones = {1: c1, 2: c2, 3: c3, 4: c4}

        print(15 * "_____")
        print(opciones)
        print(15 * "_____")

        valor = opciones.get(opcion)
        clave = list(opciones.keys())[list(opciones.values()).index(valor)]

        print("Resultado en RADIANES de la opción ", clave, " es: ", valor)
Example #39
0
 def transfer_function(self, x):
     #use hyperbolic tan
     return math.tanh(x)
def sigmoid(x):
    return math.tanh(x)
Example #41
0
# 가상으로 구현한 loocv(leave one out cross validation) 시뮬레이터

from collections import deque
import numpy as np
import random
import time
import math


def cross_validation(dataset, address, acc):
    print("%d th test_set : %s" % (int(address + 1), dataset[address]))
    print("cross_validation %d times... " % int(address + 1))
    print("accuracy : %.5f %%" % float(acc * 100))
    time.sleep(0.3)


#make fake 10000 datasets that have 7 features and 1 label
dataset = np.zeros((10000, 8))
acc = 0
for i in range(10000):
    for j in range(0, 7):
        dataset[i, j] = random.randrange(1, 10)
    dataset[i, 7] = random.choice([True, False])
dataset_address = deque(range(10000), maxlen=10000)
for i in range(dataset_address.__len__()):
    cross_validation(dataset, i, acc)
    acc = math.tanh((i / 100000000) * i * i)
    dataset_address.rotate(-1)

#
Example #42
0
import random, math

h = 1.0
beta = 2.0
p = math.exp(-2.0 * beta * h)
sigma = 1
tmax = 10000000
M_tot = 0
for t in range(tmax):
    if sigma == -1:
        sigma = 1
    elif random.uniform(0.0, 1.0) < p:
        sigma = -1
    M_tot += sigma
print('magnetization:', M_tot / float(tmax))
print('exact result: ', math.tanh(beta * h))
Example #43
0
             argCount=2,
             alg=lambda args: args[0] - args[1]),
    '=':
    Operator(leftAssoc=True,
             priority=1,
             argCount=2,
             alg=lambda args: args[0] == args[1]),
}
_functions = {
    'abs': Function(argCount=1, alg=lambda args: math.fabs(args[0])),
    'acosh': Function(argCount=1, alg=lambda args: math.acosh(args[0])),
    'acos': Function(argCount=1, alg=lambda args: math.acos(args[0])),
    'asinh': Function(argCount=1, alg=lambda args: math.asinh(args[0])),
    'asin': Function(argCount=1, alg=lambda args: math.asin(args[0])),
    'atan2': Function(argCount=1, alg=lambda args: math.atan2(args[0])),
    'atanh': Function(argCount=1, alg=lambda args: math.atanh(args[0])),
    'atan': Function(argCount=1, alg=lambda args: math.atan(args[0])),
    'cos': Function(argCount=1, alg=lambda args: math.cos(args[0])),
    'exp': Function(argCount=1, alg=lambda args: math.exp(args[0])),
    'log10': Function(argCount=1, alg=lambda args: math.log10(args[0])),
    'log': Function(argCount=1, alg=lambda args: math.log(args[0])),
    'sin': Function(argCount=1, alg=lambda args: math.sin(args[0])),
    'sqrt': Function(argCount=1, alg=lambda args: math.sqrt(args[0])),
    'tanh': Function(argCount=1, alg=lambda args: math.tanh(args[0])),
    'tan': Function(argCount=1, alg=lambda args: math.tan(args[0])),
}
_constants = {
    'e': Constant(value=2.71828182846),
    'pi': Constant(value=3.14159265359),
}
Example #44
0
File: nl.py Project: zmxu/misc
import math
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-6, 6, 0.05)
y1 = np.array([max(a, 0) for a in x])
y2 = np.array([1./(1+math.exp(-a)) for a in x])
y3 = np.array([math.tanh(a) for a in x])
plt.grid(color='gray', linestyle='--', linewidth=0.5)
plt.plot(x, y1, label='ReLU', linewidth=2)
plt.plot(x, y2, label='Logistic', linewidth=2)
plt.plot(x, y3, label='tanh', linewidth=2)
plt.legend()
plt.show()

Example #45
0
def transfer(activation):
	return tanh(activation)
def activationF(val):
    return math.tanh(val)
Example #47
0
def activationFunction(x):
    return math.tanh(x)
Example #48
0
def rho_harm(x, xp, beta):
    Upsilon_1 = sum(
        (x[d] + xp[d])**2 / 4.0 * math.tanh(beta / 2.0) for d in range(3))
    Upsilon_2 = sum(
        (x[d] - xp[d])**2 / 4.0 / math.tanh(beta / 2.0) for d in range(3))
    return math.exp(-Upsilon_1 - Upsilon_2)
Example #49
0
 def getFitness(self):
     print "evaluations taken ", self.evaluations_taken, " energy: ", self.energy
     energy_norm = math.tanh(self.energy)
     return max(self.evaluations_taken + energy_norm, 1)
Example #50
0
def math_tanh(A, B):
    i = cuda.grid(1)
    B[i] = math.tanh(A[i])
Example #51
0
def funcao_ativacao_tang_hip(x):
    return math.tanh(x)
Example #52
0
    def control(self, u_d=0, psi_d=0):

        #Nr hydrodynamic variable
        self.N_r = (-0.52) * (math.pow(
            math.pow((self.u), 2) + math.pow((self.v), 2), 0.5))
        #rospy.logwarn("Nr %f", self.N_r)
        #Xu and Xuu
        u_abs = math.fabs(self.u)
        #rospy.logwarn("abs u %f", u_abs)
        self.X_u = -25
        self.X_uu = 0
        if u_abs > 1.2:
            self.X_u = 64.55
            self.X_uu = -70.92

        self.error_u = self.u - u_d  #Speed error
        if (math.fabs(self.error_u) < 0.05):
            self.error_u = 0
        #rospy.logwarn("u error %f", self.error_u)
        self.error_psi = self.psi - psi_d  #Yaw error
        if (math.fabs(self.error_psi) > (math.pi)):
            self.error_psi = (self.error_psi / math.fabs(self.error_psi)) * (
                math.fabs(self.error_psi) - 2 * math.pi)
        if (math.fabs(self.error_psi)) < 0.015:
            self.error_psi = 0
        self.degree_error = math.degrees(self.error_psi)
        #rospy.logwarn("psi error %f", degree_error)

        psiexp = (-5.73) * math.fabs(self.error_psi)
        self.min_u = self.udyaw + (u_d - self.udyaw) * math.exp(psiexp)
        self.u_d_ref = min(self.min_u, u_d)
        tanhval = self.ka * (self.u_d_ref - self.u) / self.uamax
        self.u_dot_d = self.uamax * math.tanh(tanhval)
        self.epsilon_u = self.u_dot_d - (self.ku * self.error_u)

        self.epsilon_psi = (self.k1) * (self.error_psi) - (self.k2) * (self.r)

        self.X_drag = (self.X_uu) * (self.u) * u_abs + (self.X_u) * (self.u)
        self.T_x = (self.mass - self.X_u_dot) * (self.epsilon_u) - (
            self.mass - self.Y_v_dot) * (self.v) * (self.r) - (self.X_drag)

        self.T_z = (self.I_z - self.N_r_dot) * (self.epsilon_psi) - (
            self.Y_v_dot -
            self.X_u_dot) * (self.u) * (self.v) - (self.N_r) * (self.r)
        if math.fabs(self.error_psi) > 0.03:
            self.T_z = self.T_z * .5
        if math.fabs(self.error_psi) > 0.1:
            self.T_z = self.T_z * .7
        if math.fabs(self.error_psi) > 0.2:
            self.T_z = self.T_z * .7
        if math.fabs(self.error_psi) > 0.3:
            self.T_z = self.T_z * .8

        self.T_port = (self.T_x / (2 * self.c)) + (self.T_z /
                                                   (self.B * self.c))
        self.T_stbd = (self.T_x / 2) - (self.T_z / self.B)
        if self.T_port > 36.5:
            self.T_port = 20
        elif self.T_port < -30:
            self.T_port = -20
        if self.T_stbd > 36.5:
            self.T_stbd = 20
        elif self.T_stbd < -30:
            self.T_stbd = -20


#Controller outputs
        self.right_thruster_pub.publish(self.T_stbd)
        self.left_thruster_pub.publish(self.T_port)

        self.u_error_pub.publish(self.error_u)
        self.psi_error_pub.publish(self.degree_error)
Example #53
0
def delta(phi: float) -> float:
    return 1 - (1 + math.tanh(2 * (phi - max_dis))) / 2
Example #54
0
def mish(x):
    return x * math.tanh(math.log(1 + math.exp(x)))
Example #55
0
 def tanh(x1, x2, k, c):
     return math.tanh(k * np.dot(x1, x2) + c)
Example #56
0
def sho_energy(T):
    '''Return the energy of a simple harmonic osscilator at temperature T.'''
    # \hbar \omega / k_B = 1
    return 0.5 / math.tanh(0.5 / T)
Example #57
0
 def tanh(self,x):
     return math.tanh(x)
 def forward(self, distance):
     TForward = Transform.shiftOrigin(Point(math.tanh(-distance/2), 0))
     TToOrigin = self.transformToOrigin()
     TFromOrigin = TToOrigin.inverted()
     T = Transform.merge(TToOrigin, TForward, TFromOrigin)
     return Turtle(*T(self.point, self.head))
Example #59
0
ainvfinal = math.log10(1 + settings["zc_final"])
ainvarr = []
zcarr = []
for i in range(settings["bins"] + 1):
    ainvarr.append(float(i) / settings["bins"] * (ainvfinal - ainvinit))
    zcarr.append(10**ainvarr[i] - 1.0)

fp = open("TREECOOL.mod", "w")

for ii, zc in enumerate(zcarr):
    if zc > settings["XRadRedShiftOn"] or zc < settings["XRadRedShiftOff"]:
        settings["RampX"] = 0.0
    else:
        if zc > settings["XRadRedShiftFullOn"]:
            settings["RampX"] = 0.5 - 0.5*math.tanh(15.0*(zc-0.5*\
                (settings["XRadRedShiftOn"] \
                + settings["XRadRedShiftFullOn"])))

        if zc < settings["XRadRedShiftDropOff"]:
            settings["RampX"] = ( zc - settings["XRadRedShiftDropOff"] + \
                settings["XRadRedShiftf0to3"] * \
                (settings["XRadRedShiftDropOff"]-zc)) / \
                (settings["XRadRedShiftDropOff"] - \
                settings["XRadRedShiftOff"])

    if zc > settings["RadRedShiftOn"] or zc < settings["RadRedShiftOff"]:
        settings["Ramp"] = 0.0
    else:

        if zc > settings["RadRedShiftFullOn"]:
            settings["Ramp"] = 0.5 - 0.5*math.tanh(15.0*(zc-0.5*\
Example #60
0
def sigmoidkernel(x1, x2, k, delta):
    # print(pow(np.dot(x1, x2)+1, power))
    #   print(k*np.dot(x1, x2) - delta)
    return m.tanh((k * np.dot(x1, x2) - delta) * m.pi / 180.0) + 1