def OptionPrice(cls, spot, strike, NbExp, vol, rate, q, optionType):
    # v = float()
     d1 = float()
     d2 = float()
     Nd1 = float()
     Nd2 = float()
     T = float()
     
     if NbExp < 0:
         return 0
     T = NbExp / 365
     if NbExp == 0:
         if optionType == "c":
             print "TESTTESTTESTTEST", long((math.max(spot - strike, 0)))
             return float((math.max(spot - strike, 0)))
         else:
             print "TESTTESTTESTTEST", long((math.max(spot - strike, 0)))
             return float((math.max(strike - spot, 0)))
             
     d1 = ((math.log(spot / strike)) + (rate - q + (vol * vol) / 2) * T) / (vol * math.sqrt(T))
     d2 = d1 - vol * math.sqrt(T)
     Nd1 = cls.cdnf(d1)
     Nd2 = cls.cdnf(d2)
     if optionType == "c":
         # call option
         return float((spot * math.exp(-q * T) * Nd1 - strike * math.exp(-rate * T) * Nd2))
     else:
         # put option
         return float((-spot * math.exp(-q * T) * (1 - Nd1) + strike * math.exp(-rate * T) * (1 - Nd2)))
示例#2
0
def OptionPrice(spot, strike, NbExp, vol, rate, q, optionType):
    # v = float()
    d1 = float()
    d2 = float()
    Nd1 = float()
    Nd2 = float()
    T = float()
        
    if NbExp < 0:
        return 0
    T = NbExp / 365
    if NbExp == 0:
        if optionType == "c":
            print "TESTTESTTESTTEST", long((math.max(spot - strike, 0)))
            return float((math.max(spot - strike, 0)))
        else:
            print "TESTTESTTESTTEST", long((math.max(spot - strike, 0)))
            return float((math.max(strike - spot, 0)))
    
    d1 = ((math.log(spot / strike)) + (rate - q + (vol * vol) / 2) * T) / (vol * math.sqrt(T))
    d2 = d1 - vol * math.sqrt(T)
    Nd1 = cdnf(d1)
    Nd2 = cdnf(d2)
    if optionType == "c":
        # call option
        return float((spot * math.exp(-q * T) * Nd1 - strike * math.exp(-rate * T) * Nd2))
    else:
        # put option
        return float((-spot * math.exp(-q * T) * (1 - Nd1) + strike * math.exp(-rate * T) * (1 - Nd2)))
示例#3
0
 def maxSubArray(self, nums):
     a = []
     MAX = a[0] = nums[0]
     for i in range(len(nums)):
         a[i] = math.max(a[i - 1] + nums[i], nums[i])
         MAX = math.max(a[i], MAX)
     return MAX
示例#4
0
 def payoff(self, contract_size: int = 100, position: int = 1) -> float:
     # negative position means short
     if self.type == OptionType.CALL:
         return ((math.max(0, self.current_stock_price - self.strike)) -
                 self.bid) * contract_size * position
     else:
         return ((math.max(0, self.strike, self.current_stock_price)) -
                 self.bid) * contract_size * position
 def mul_interval(self, y):
    p1 = self.lower_bound * y.lower_bound
    p2 = self.lower_bound * y.upper_bound
    p3 = self.upper_bound * y.lower_bound
    p4 = self.upper_bound * y.upper_bound
    return Interval(
       math.min(math.min(p1, p2), math.min(p3, p4)),
       math.max(math.max(p1, p2), math.max(p3, p4)))
示例#6
0
 def max_intensity(self):
     try:
         from numpy import max
         return max(self.y)
     except ImportError:
         from math import max
         maximum = 0.
         for i in self.y:
             maximum = max(maximum, i)
         return maximum
 def onMove(self, context):
     super.onMove(context)
     for iterator in draggableList:
         draggable = iterator.next()
         draggable.desiredX = context.desiredDraggableX - dropTargetOffsetX + draggable.relativeX
         draggable.desiredY = context.desiredDraggableY - dropTargetOffsetY + draggable.relativeY
         draggable.desiredX = math.max(
             0, math.min(draggable.desiredX, dropTargetClientWidth - draggable.offsetWidth)
         )
         draggable.desiredY = math.max(
             0, math.min(draggable.desiredY, dropTargetClientHeight - draggable.offsetHeight)
         )
         draggable.desiredX = math.round(float(draggable.desiredX) / gridX) * gridX
         draggable.desiredY = math.round(float(draggable.desiredY) / gridY) * gridY
         dropTarget.add(draggable.positioner, draggable.desiredX, draggable.desiredY)
示例#8
0
    def activationFunction(self, input):
        output = [None] * len(input)

        for idx in range(0, len(output)):
            output[idx] = math.max(input[idx], 0.0)

        return output
示例#9
0
def crossover(g1, g2):
    # Make sure g1 is the highest fitness genome
    if g2.fitness > g1.fitness:
        tempg = g1
        g1 = g2
        g2 = tempg
    child = newGenome()

    innovations2 = {}
    # for gene in g2.genes:
    for i in range(len(g2.genes)):
        gene = g2.genes[i]
        innovations2[gene.innovation] = gene

    for i in range(len(g1.genes)):
        gene1 = g1.genes[i]
        gene2 = innovations2[gene1.innovation]

        if gene2 != None and math.random(2) == 1 and gene2.enabled:
            # table.insert(child.genes, copyGene(gene2))
            child.genes.append(copyGene(gene2))
        else:
            # table.insert(child.genes, copyGene(gene1))
            child.genes.append(copyGene(gene1))

    child.maxneuron = math.max(g1.maxneuron, g2.maxneuron)

    child.mutationRates = g1.mutationRates.copy()
    """
    for mutation, rate in pairs(g1.mutationRates) do
        child.mutationRates[mutation] = rate
    """
    return child
示例#10
0
文件: code.py 项目: jcsombria/myjobs
class Program_BinaryOperation:
    OPERATIONS = {
        'plus': lambda a, b: a + b,
        'minus': lambda a, b: a - b,
        'times': lambda a, b: a * b,
        'divided by': lambda a, b: a / b,
        'minimum': lambda a, b: math.min(a, b),
        'maximum': lambda a, b: math.max(a, b),
        'power': lambda a, b: math.pow(a, b),
        'atan2': lambda a, b: math.atan2(a, b)
    }

    def __init__(self, name):
        self.op1 = None
        self.op2 = None
        self.operation = None
        self.result = None

    def setProperty(self, propertyName, propertyValue):
        if propertyName == 'Operand1':
            self.op1 = propertyValue
        elif propertyName == 'Operand2':
            self.op2 = propertyValue
        elif propertyName == 'Operation':
            if propertyValue in OPERATIONS:
                self.operation = propertyValue

    def getProperty(self, propertyName, propertyValue):
        if propertyName == 'Result':
            return self.result
        return None

    def run(self):
        self.result = OPERATIONS[self.operation](self.op1, self.op2)
示例#11
0
def disjoint(genes1, genes2):
    i1 = []
    for i in range(len(genes1)):
        gene = genes1[i]
        i1[gene.innovation] = True

    i2 = []
    for i in range(len(genes2)):
        gene = genes2[i]
        i2[gene.innovation] = True

    disjointGenes = 0
    for i in range(len(genes1)):
        gene = genes1[i]
        if not i2[gene.innovation]:
            disjointGenes = disjointGenes + 1

    for i in range(len(genes2)):
        gene = genes2[i]
        if not i1[gene.innovation]:
            disjointGenes = disjointGenes + 1

    n = math.max(len(genes1), len(genes2))

    return disjointGenes / n
示例#12
0
def calculateTime(model, altitude):
#(model:DescentModel) (altitude:float<Feet>) =
    aTime = math.pow(altitude, model.TimePower)
    time = model.TimeIntercept + model.TimeAltitude * aTime
    maxDescent = math.fabs(float(altitude / model.MaximumRateOfDescent))
    result =  math.max(maxDescent, time)
    return result
示例#13
0
    def getDirections(self):
        self.__initSeeds()
        d = self.getNum()
        MSEa = 0
        while (MSEa != self.__MSE):
            MSEa = self.__MSE
            MSEp = 0.
            new_centroids = [Point3() for i in range(d)]
            classes_sizes = []
            for i in range(d):
                new_centroids[i] = Point3()
                classes_sizes[i] = 0

            # We find the closest centroid for each vertex
            for i in vertices:
                l = i.distance2From(self.__centroids[0])
                i0 = 0
                for i in range(d):
                    ll = i.distance2From(centroids[i])
                    if (ll < l):
                        l = ll
                        i0 = i
                new_centroids[i0] = new_centroids[i0] + i
                classes_sizes[i0] = classes_sizes[i0] + 1
                MSEp = MSEp + l

            for i in range(d):
                classes_sizes[i] = math.max(classes_sizes[i], 1)
                self.__centroids[i] = new_centroids[i] * (1. /
                                                          classes_sizes[i])

            self.__MSE = MSEp

        return self.__centroids
示例#14
0
 def train(self, data, inputSize=None, outputSize=None, iterations=20000, errorThresh=0.005, logLevel=logging.DEBUG, log=False, logPeriod=10, learningRate=0.3, callback=None, callbackPeriod=10):
     if inputSize is None:
         inputSize = len(data[0][0])
     if outputSize is None:
         outputSize = len(data[0][1])
     hiddenSizes = self.hiddenSizes
     if not hiddenSizes:
         hiddenSizes = [math.max(3, math.floor(inputSize / 2))]
     self._initialize(list(flatten([inputSize, hiddenSizes, outputSize])))
     error = 1
     done = 0
     for i in range(iterations):
         done = i
         if error <= errorThresh:
             break
         sum = 0
         for d in data:
             err = self.trainPattern(d[0], d[1], learningRate)
             sum = sum + err
         error = sum / len(data)
         if log and i % logPeriod == 0:
             logging.log(
                 logLevel, "iterations:{0}, training error: {1}".format(i, error))
         if callback is not None and i % callbackPeriod == 0:
             callback(error=error, iterations=i)
     return (error, done)
示例#15
0
def getActionsInfoSet(h,p):
    potSize = reduce(lambda a,b : a+b, h.pMPIP)
    totalChips = len(PLAYERS) * STARTING_STACK
    potsizeBuckets = math.floor((potSize / totalChips) * 10)

    playersRemain = reduce(lambda a,b : a+b,map(lambda folded : 0 if folded else 1, h.pFolded))
    allBetsSize = reduce(lambda a,b : a+b, h.pBet)
    potSizeWithBets = potSize + allBetsSize
    myBet = h.pBet[p]
    biggestBet = math.max(**h.pBet)
    toCall = biggestBet - myBet
    potOdds = toCall / potSizeWithBets
    potOddsBuckets = math.floor(potOdds * 10)

    positions = map(lambda p,i : len(PLAYERS)-i, PLAYERS)
    myPosition = positions[p]
    p1 = p + 1
    while (p1 < len(PLAYERS)):
        if h.pFolded[p1]:
            myPosition -= 1
        p1 += 1
    
    bettingRound = h.bettingRound

    actionsString = bettingRound + myPosition + potOddsBuckets +
                    potSizeBuckets + "," + playersRemain
示例#16
0
def next_pallindrome(num):
    fringe = [num]
    pallindromes = []

    # iterate through fringe

    for i in range(num_digits(num)/2):
        left_place = 10**i
        left = digit_at_place(num, left_place)

        right_place = 10**(num_digits(num)-i-1)
        right = digit_at_place(num, right_place) 

        smaller, larger = math.min(left, right), math.max(left, right)

        for j in range(smaller, larger+1):
            left_diff = (j - left) * left_place
            right_diff = (j - right) * right_place
            new_num = num
            new_num += left_diff
            new_num += right_diff
            if is_pallindrome(new_num):
                pallindromes.appned(new_num)
            else:
                fringe.append(new_num)
示例#17
0
	def point_on_line(self, line, p):
		min_dist = 1000000000
		minX, minY, minI, minT = 0,0,0,0

		for i in range(len(line)-1):

			x, y = line[i][0], line[i][1]
			dx, dy = (line[i+1][0] - x) * self.kx, (line[i+1][1] - y) * self.ky

			if dx and dy:
				t = ((p[0] - x) * this.kx * dx + (p[1] - y) * this.ky * dy) / (dx * dx + dy * dy)

				if t > 1:
					x = line[i+1][0]
					y = line[i+1][1]

				elif t > 0:
					x += (dx / self.kx) * t
					y += (dy / self.ky) * t

			dx = (p[0] - x) * self.kx
			dy = (p[1] - y) * self.ky

			sq_dist = dx**2 + dy**2
			if sq_dist < min_dist:
				min_dist = sq_dist
				minX, minY, minI, minT = x, y, i, t

		return { 
			'point': [minX, minY],
			'index': minI,
			't' : math.max(0, math.min(1,minT))
		}
示例#18
0
def FrozenSoil(Fdepth,ROOTD,WAS,WCFC,WCL,Tsurf,LAMBDAsoil,RHOwater,LatentHeat,DELT):
     # Determining the amount of solid water that contributes in transportation of heat to surface 'WCeff'
     if Fdepth > ROOTD:
       WCeff = WCFC
     elif Fdepth > 0:
       WCeff = (0.001*WAS) / Fdepth
     else:
       WCeff = WCL

     # Calculating potential frost rate 'PFrate'
     #  if ((Fdepth == 0.).and.(Tsurf>0.)) : # No soil frost present AND no frost starting
     if Fdepth == 0 and Tsurf>0 or WCeff == 0: # No soil frost present AND no frost starting
       PFrate = 0
     else :
       alpha  = LAMBDAsoil / ( RHOwater * WCeff * LatentHeat)
       PFrate = math.sqrt( math.max(0, math.pow(Fdepth,2) - 2*alpha*Tsurf) ) - Fdepth

     if PFrate >= 0 and Fdepth > 0 and Fdepth < ROOTD:
       Frate = PFrate * (0.001*WAS/Fdepth) / WCFC # Soil frost increasing
     elif (PFrate+Fdepth/DELT) < 0 :
       Frate = -Fdepth / DELT                     # Remaining soil frost thaws away
     else :
       Frate = PFrate
       
     return (WCeff,PFrate,Frate)  
示例#19
0
def qualityalgo(arg7, arg8, arg9):
    v0 = 0
    v3 = 0x1388
    v2 = 0xFF
    if (arg9 == 0):
        if (arg7 == 0x63 and arg8 == 0x24):
            v0 = 0x8A
            if (v0 < 1):
                v0 = 1
            elif (v0 > v2):
                v0 = v2
            return v0

        a = (arg7 * b[arg8] / 0x1000000 + 1)
        v0 = int(a / 2)
    elif (arg9 == 1):
        if arg8 < 0x32:
            v0 = math.min(int(v3) / arg8, v3)
        else:
            v0 = math.max(int(0xC8) - arg8 * 2, 0)
        v0 = (v0 * arg7 + 0x32) / 0x64
    else:
        print("qualityAlgorithm")
        return 0

    if (v0 < 1):
        v0 = 1
    elif (v0 > v2):
        v0 = v2
    return (v0 & 0xFF)
示例#20
0
def run(mass):
    try:
        mass = int(mass)
    except ValueError:
        return False

    return math.max(0, math.floor(mass / 3) - 2)
示例#21
0
def downscale_evaporation(self, k):
    """
    REQUIRED INPUT:
        daily evaporation (EpDay)
        - hour of the day (x; derived from self.thestep)
        - start of the day (derived from global radiation)
        - end of the day (derived from global radiation)
    PARAMETERS:
    - 
    """

    # teller = numpy.nanmax(pcr.pcr2numpy(self.thestep,np.nan))
    teller = pcr.pcr2numpy(self.thestep, np.nan)[0, 0]
    x = teller - math.floor(teller / 24) * 24 * pcr.scalar(self.catchArea)
    DL = self.DE - self.DS + 1
    P = 2 * math.pi / (2 * DL)  # period
    SH = DL - 12  # horizontal shift of new signal
    aN = -1 * self.EpDay * P  # nominator of the amplitude
    aDN = math.sin((P * (self.DE + SH)) * 180 / math.pi) - math.sin(
        (P * (self.DS + SH)) * 180 / math.pi
    )  # denominator of the amplitude
    ampl = aN / aDN  # amplitude of new signal

    self.EpHour = math.max(
        pcr.ifthenelse(
            pcr.pcrand(x >= self.DS, x <= self.DE),
            -1 * ampl * math.cos((P * (x + SH)) * 180 / math.pi),
            0,
        ),
        0,
    )
    def ComputeBreakpointAt(self, y):

        # we use the equation of the parabola to get the intersection of the two arcs
        d = 2 * (self.site1.y - y)
        a1 = 1 / d
        b1 = -2 * self.site1.x / d
        c1 = y + d / 4 + self.site1.x * self.site1.x / d

        d = 2 * (self.site2.y - y)
        a2 = 1 / d
        b2 = -2 * self.site2.x / d
        c2 = y + d / 4 + self.site2.x * self.site2.x / d  # minor adjustment

        a = a1 - a2
        b = b1 - b2
        c = c1 - c2

        # since this is a quadratic equation, so it will have 2 solutions
        discremenant = b * b - 4 * a * c
        x1 = (-b + math.sqrt(discremenant)) / (2 * a)
        x2 = (-b - math.sqrt(discremenant)) / (2 * a)

        # the two solutions are basically the left and the right breakpoint values (just x)
        if self.site1.x <= self.site2.x:
            return math.min(x1, x2)
        else:
            return math.max(x1, x2)
示例#23
0
def getActions(h):
    betsAreEqual = allEqual(filter(
        lambda p,i : !h.pFolded[i],
        h.pBet
    ))

    highestBet = math.max(**h.pBet)
    currentBet = h.pBet[h.currentPlayer]
    diff = highestBet - currentBet

    hasChips = h.pChips[h.currentPlayer] > diff
    hasFolded = h.pFolded[h.currentPlayer]

    let actions = []

    if (hasFolded):
        actions = ["none"]
    else:
        if betsAreEqual:
            actions = ["check"]
            if hasChips:
                actiosn = actions + ["bet"]
        else:
            actions = ["fold", "call"]
            if hasChips:
                actions = actions + ["bet"]
    
    return actions
    def search_thread():
        global iters_per_search
        global parallel_threads
        global candidate

        def search():
            global lists
            lists = lists[:]
            global min_number
            global batch_size
            global iters_per_batch

            loop = True
            return_list = []
            while loop:
                batch = []
                # create batch
                for i in range(batch_size):
                    try:
                        batch.append(lists[0])
                        del lists[0]
                    except IndexError:  # list is empty now, break loop
                        loop = False
                # perform on batch
                new = random_from_lists_bestof(batch, saved_profiles + return_list,
                                               min_number, iters_per_batch)
                return_list += new[:]
            return return_list

        for i in range(math.ceil(iters_per_search/math.max(parallel_threads, 1))):
            new_candidate = search()
            if len(new_candidate) < len(candidate):
                candidate = new_candidate[:]
示例#25
0
class Program_Function1D:
    FUNCTIONS = {
        'min': lambda a, b: math.min(a, b),
        'max': lambda a, b: math.max(a, b),
        'pow': lambda a, b: math.pow(a, b),
        'atan': lambda a, b: math.atan(a, b)
    }

    def __init__(self, name):
        self.argument = None
        self.function = None
        self.result = None

    def setProperty(self, propertyName, propertyValue):
        if propertyName == 'Argument':
            self.argument = propertyValue
        elif propertyName == 'Function':
            if propertyValue in FUNCTIONS:
                self.function = propertyValue

    def getProperty(self, propertyName, propertyValue):
        if propertyName == 'Result':
            return self.result
        return None

    def run(self):
        self.result = FUNCTIONS[self.function](self.argument)
示例#26
0
	def sweepCollisionTest(self, bb1, bb2, p1, p2, v1, v2):
		""" 
			Where p1 and p2 are position vectors 
			and v1 and v2 are velocity vectors

			NOTE: sweep tests are only supported for 
			AABB-AABB.  SAT sweeps are a little outside my 
			expertise.
		"""
		type1 = 0
		type2 = 0

		for type in range(len(self.boundingArray)):
			if bb1.getBoundType == self.boundingArray[type]:
				type1 = type
			if bb1.getBoundType == self.boundingArray[type]:
				type2 = type

		if type1 == 1 and type2 == 1:
			"""Simple AABB collision"""

			#bb1 controls the collision: translate movement to bb2's frame of reference

			rvel = v1 - v2

			#sweep for a collision

			#check x path
			if rvel.x != 0:
				t_min_x = ((p2.x - bb2.half_width) - p1.x) / rvel.x
				t_max_x = ((p2.x + bb2.half_width) - p1.x) / rvel.x
			else:
				if (p2.x - bb2.half_width) <= (p1.x + bb1.half_width) or (p2.x + bb2.half_width) >= (p1.x - bb1.half_width):
					#if they have the same x velocity but still intersect on the x axis...
					t_min_x = t_max_x = 0
				else:
					t_min_x = 2
					t_max_x = -2

			#check y path
			if rvel.y != 0:
				t_min_y = ((p2.y - bb2.half_height) - p1.y) / rvel.y
				t_max_y = ((p2.y + bb2.half_height) - p1.y) / rvel.y
			else:
				if (p2.y - bb2.half_height) <= (p1.y + bb1.half_height) or (p2.y + bb2.half_height) >= (p1.y - bb1.half_height):
					#if they have the same x velocity but still intersect on the x axis...
					t_min_y = t_max_y = 0
				else:
					t_min_y = 2
					t_max_y = -2

			if t_min_x <= t_max_x and t_min_y <= t_max_y:
				intersect_time = math.max(t_min_x, t_min_y)
			else:
				intersect_time = -1
			return intersect_time				

		else:
			raise TypeError('Sweep tests are not supported for non-AABB collisions')
示例#27
0
def hex_linedraw(a, b):
    N = hex_distance(a, b)
    a_nudge(a['q'] + 1e-6, a['r'] + 1e-6, a['s'] - 2e-6)
    b_nudge(b['q'] + 1e-6, b['r'] + 1e-6, b['s'] - 2e-6)
    results = []
    step = 1.0 / math.max(N, 1)
    for i in range(N):
        results.append(hex_round(hex_lerp(a_nudge, b_nudge, step * i)))
    return results
示例#28
0
def update_state(time):
    global wheelbase
    global steering_command
    global state, last_update

    if steering_command is not None:
        v0 = steering_command.speed
        a0 = steering_command.acceleration
        j0 = steering_command.jerk

        time_diff = time - last_update

        dt = time_diff.secs + time_diff.nsecs * 1e-9
        ds = v0 * dt + a0 * dt**2 / 2 + j0 * dt**3 / 6

        v = v0 + a0 * dt + j0 * dt**2 / 2

        delta = steering_command.steering_angle

        if max_steering_angle > 0:
            delta = max(-max_steering_angle, min(delta, max_steering_angle))

        if max_steering_angle_velocity > 0:
            delta = math.max(
                state.delta - max_steering_angle_velocity * dt,
                min(delta, state.delta + max_steering_angle_velocity * dt))

        state.delta = delta
        if isclose(delta, 0.0):
            # Approximate movement as linear motion
            state.x += ds * math.cos(state.th)
            state.y += ds * math.sin(state.th)

        else:
            # Treat movement as circular motion

            # Calculate radius of curvature (positive sign = left turn)
            r = wheelbase / math.tan(delta)

            # Calculate coordinates of the center of curvature
            cx = state.x - r * math.sin(state.th)
            cy = state.y + r * math.cos(state.th)

            # Calculate current yaw and angular velocity
            state.th += ds / r
            state.vth = v / r

            # Calculate new position
            state.x = cx + r * math.sin(state.th)
            state.y = cy - r * math.cos(state.th)

        # Calculate instantaneous velocity
        state.vx = v * math.cos(state.th)
        state.vy = v * math.sin(state.th)

    last_update = time
    return state
示例#29
0
    def prox_f(q, x, t):
        if len(locals()) < 3:
            print("[RPCA_c : prox_f] Not enough arguments")

        V = math.sqrt(np.sum(np.power(x, 2), 1))
        s = 1 - np.divide(1, math.max(np.divide(v, np.multiply(t, q)), 1))
        m = len(s)
        x = scipy.sparse.spdiags(x, 0, m, m) * x

        return x
示例#30
0
文件: JMLanfis.py 项目: jhasanov/JML
 def calcOut(self, inputs):
     if self.operation == 'AND':
         self.output = 1.0
         for i in self.inputIndex:
             self.output *= inputs[i]
     elif self.operation == 'OR':
         for i in self.inputIndex:
             self.output = math.max(self.output, inputs[i])
     else:
         self.output = 0.0
示例#31
0
    def _compute_tree_structures(self, current_layer, current_depth):

        layer_actions_count = 0
        layer_terminal_actions_count = 0
        next_layer = []

        for n in range(1, len(current_layer)):
            node = current_layer[n]
            layer_actions_count = math.max(layer_actions_count, len(node.children))

            node_terminal_actions_count = 0
            for c in range(1, len(current_layer[n].children)):
                if node.children[c].terminal or node.children[c].current_player == constants.players.chance:
                    node_terminal_actions_count = node_terminal_actions_count + 1

            layer_terminal_actions_count = math.max(layer_terminal_actions_count, node_terminal_actions_count)

            ###--add children of the node to the next layer for later pass of BFS
            if not node.terminal:
                for c in range(1, len(node.children)):
                    next_layer.append(node.children[c])

        assert ((layer_actions_count == 0) == (len(next_layer) == 0))
        assert ((layer_actions_count == 0) == (current_depth == self.lookahead.depth))

        ##--set action and bet counts
        self.lookahead.bets_count[current_depth] = layer_actions_count - layer_terminal_actions_count

        self.lookahead.nonallinbets_count[
            current_depth] = layer_actions_count - layer_terminal_actions_count - 1  # - -remove allin
        ###--if no alllin...
        if layer_actions_count == 2:
            assert (layer_actions_count == layer_terminal_actions_count)
        self.lookahead.nonallinbets_count[current_depth] = 0

        self.lookahead.terminal_actions_count[current_depth] = layer_terminal_actions_count
        self.lookahead.actions_count[current_depth] = layer_actions_count

        if len(next_layer) > 0:
            assert (layer_actions_count >= 2)
            ##--go deeper
            self._compute_tree_structures(next_layer, current_depth + 1)
示例#32
0
    def getExpectationOfProperties(self, iin, out, cnt):
        inHs, outHs = [], []
        res = [12]
        for i in range(len(iin)):
            res[0] += cnt[i]
            res[1] += iin[i] * cnt[i]
            res[7] = math.max(res[7], iin[i])
            res[8] = math.max(res[8], out[i])
            inHs.add(iin[i])
            outHs.add(out[i])
        res[2] = res[1] / res[0]

        for i in range(len(iin)):
            res[3] += math.min(1, iin[i] * iin[i]/res[0]) * cnt[i]
            res[4] += math.min(1, out[i] * out[i]/res[0]) * cnt[i]
            res[11] += math.min(1, out[i] * iin[i]/res[0]) * cnt[i]
        res[11] /= res[2]
        tmp = res[0] * (res[0] - 1)
        for i in range(len(iin)):
            for j in range(len(out)):
                if iin[i] != 0 and out[j] != 0:
                    res[5] += iin[i] * out[j] / res[1] * cnt[i] * cnt[j] / tmp
        res[6] = len(iin)
        res[9] = np.size(inHs)
        res[10] = np.size(outHs)

        print("\n Expectations:"
                    "\n\t num Node: "
                    "\n\t num Edge: "
                    "\n\t expected In/Out Degree: "
                    "\n\t Second Moment In Degree: "
                    "\n\t Second Moment out Degree: "
                    "\n\t expected connection probability: "
                    "\n\t num unique joint in/out degree: "
                    "\n\t max In Degree: "
                    "\n\t max out degree: "
                    "\n\t num of unique in degree: "
                    "\n\t num of unique out degree: "
                    "\n\t expected num of self loop  \n", res[0], res[1], res[2], res[3], res[4], res[5], res[6], res[7], res[8], res[9], res[10, res[11]])
        return res
示例#33
0
    def _lorentz_smooth(self, vi=4.0):
        import numpy as np
        from math import min, max, sqrt

        intbuf = np.copy(self.y)
        prefac = [
            e_step * vi / ((e_step * i)**2 + vi**2) for i in range(len(self.y))
        ]

        # First check if vi is nonzero
        if vi < 0.001:
            raise ValueError('vi is too small')

        # Sort IV curve if not yet done
        if not self.sorted:
            self.sort()

        # smooth IV curve
        if self.equidistant:

            e_step = self.x[1] - self.x[0]

            if e_step == 0.:
                raise ValueError("energy step is too small")

            # Find energy range for integral
            n_range = vi * sqrt((1. / 0.001) - 1.) / e_step

            # scan over all energies
            for i in range(len(self.y)):
                # store original intensities and calculate
                # first element of integral sum
                self._data[1][i] *= prefac[0]
                norm_sum = prefac[0]

                # upper branch:
                i_hi = min(i + n_range, len(self.x))
                for i_sum in range(i + 1, i_hi):
                    self._data[1][i] += self.y[i_sum] * prefac[i_sum - i]
                    norm_sum += prefac[i_sum - i]

                # lower branch:
                i_lo = max(i - n_range + 1, 0)
                for i_sum in range(i_lo, i):
                    self._data[1][i] += intbuf[i_sum] * prefac[i - i_sum]
                    norm_sum += prefac[i - i_sum]

                # normalize intensity
                self._data[1][i] /= norm_sum

            # set smooth flag
            self.smoothed = True
示例#34
0
def _max(a, b):
    if isNum(a) and isNum(b):
        try:
            result = math.max(a, b)
        except:
            return 0
        return result
    if not isNum(a) and isNum(b):
        return _max(parse(a), b)
    if isNum(a) and not isNum(b):
        return _max(a, parse(b))
    if not isNum(a) and not isNum(b):
        return _max(parse(a), parse(b))
def main():
	#store size of L1 CPU cache in bytes
	L1D_CACHE_SIZE = 32768 #32*1024 = 32Kbytes	
	
	print('What is the largest number you want primes to go upto in the prime list?')	
	N_initial = raw_input()
	if N_initial.isdigit() is False:
		print('You have not entered an integer. Please reenter.')
		sys.exit()

	#now convert type for N into a long:
	N = long(N_initial)
	
	#Simple Checks for N:
	if N==0:
		print('Number entered is 0. Please choose another number.')
		sys.exit()
	if N==1:
		print('1 is not a prime. Please choose another number.')
		sys.exit()
	if N<0:
		print('Number entered is negative. Please enter another number')
		sys.exit()

	#Store square root of N
	sqrt_N = math.sqrt(N)

	#Set segment_size to be max of CPU's L1 data cache size and sqrt_N
	segment_size = math.max(L1D_CACHE_SIZE,sqrt_N)

	if limit < 2:
		count=0
	else:
		count=1

	s = 3
	n = 3

	#Now need to generate sieving primes less than sqrt_N - which are needed to cross off multiples
	#is_prime="" #This needs to be a vector containing characters ???
	is_prime = []
	#is_prime = [sqrt_N + 1,1]
	i = 2
	for i * i <= sqrt_N: #N=10000. Hence sqrt_N=100. 1st loop i=2 hence i*i=4. 4 <= 100
		#if is_prime[i]:	#is_prime[4] This doesn't exist!!!
		if i not in is_prime:
			j = i * i			
			for j <= sqrt_N:
				is_prime.append(0)
				j = j + i
def SA(P, Tmax, Ftarget, dT):                   # 1.    start point P: start random or defined value
    T = Tmax                                    # 2.    set temperature to Tmax
    while (true):                               # 3.    objective function F evaluate samples
        if P.F(P) >= Ftarget or T<=0: return P  # 4.    return P as solution
        neighbors = P.Gn(P)                     # 5.    generate n neighbors of P
        for i in range(len(neighbors)):
            eneighbors[i] = P.F(neighbors[i])   # 6.    Evaluate each neighbor
        Pmax = math.max(eneighbors)             # 7.    Let Pmax be the neighbor with the highest evaluation
        q = (P.F(Pmax) - P.F(P)) / P.F(p)       # 8.    q = (F(Pmax) - F(P)) / F(p)
        p = math.min[1, math.e ** (-q / T)]     # 9.
        x = random.uniform(0.0, 1.0)            # 10.   generate x = random [0,1]
        if x > p:   P = Pmax                    # 11.
        else: P = random.choice(eneighbors)     # 12.   a random choice among n neighbors
        T = T - dT                              # 13.
示例#37
0
    def __init__(self, rawLat, rawLng, noWrap):
        lat = float(rawLat)
        lng = float(rawLng)

        if not noWrap:
            lat = math.max(math.min(lat, 90), -90)
            lng = (lng + 180) % 360
            if  (lng < -180 or lng == 180):
                lng_fix = 180 
            else:
                lng_fix = -180
            lng += lng_fix

        self.lat = lat
        self.lng = lng
示例#38
0
def fuelBurn(ascentModel, descentModel, cruiseModel, weight, altitude, airSpeed, vertical):
# (ascentModel, descentModel, cruiseModel, _) (weight:float<Pounds>) (altitude:float<Feet>) 
# (airSpeed:float<Knots>) (vertical:VerticalMovement) =
    cruiseFuelBurn = Cruise.fuelBurn(cruiseModel, weight, altitude, airSpeed)
    #assertNumber "cruiseFuelBurn" cruiseFuelBurn
    #assertNonNegative "cruiseFuelBurn" cruiseFuelBurn
    (modelBurn, verticalVelocity) =
    if vertical == 'Descent':
        (descentRate, descentFuelBurn)= Descent.calculateRates(descentModel, altitude, weight)
        (modelBurn, verticalVelocity) = (descentFuelBurn, descentRate)
    elif vertical == 'Cruise':
        # | Cruise -> (0.0<FuelPounds/Hours>, 0.0<Feet/Hours>)
        (modelBurn, verticalVelocity) = (0, 0)
    elif vertical == 'Ascent':
        (ascentRate, rawAscentFuelBurn) = Ascent.calculateRates(ascentModel, altitude, weight)
        ascentFuelBurn = math.max(rawAscentFuelBurn, cruiseFuelBurn)
        (modelBurn, verticalVelocity) = (ascentFuelBurn, ascentRate)
    verticalCruiseFuelDiff = modelBurn - cruiseFuelBurn
    return (cruiseFuelBurn, verticalCruiseFuelDiff, verticalVelocity)
示例#39
0
def poll(**kwargs): 

    global joy
    portName = "COM4" 
    analogChannel = 4  
    serPort = serial.Serial(portName, 19200, timeout=.05)  #or 15200?

    while True:
        
        etime = time.time()
        try:
            serPort.write("adc read "+ str(analogChannel) + "\r")
            ret = serPort.read(read_duration)
            print ret[12:-3]
        except:
            print 'no ret'
        joy = inter
        poll_delay = math.max(time.time() - etime - (1.0 / float(pollHz)),0)
        if poll_delay > 0:
            time.sleep(poll_delay)
        
        return 
示例#40
0
 def addItem(self, name, amount):
     self.items[name][1] = math.max(_itemMax, self.items[name][1]+amount)
 def drop(self, widget, left, top):
     left = math.max(0, math.min(left, dropTarget.getOffsetWidth() - widget.getOffsetWidth()))
     top = math.max(0, math.min(top, dropTarget.getOffsetHeight() - widget.getOffsetHeight()))
     left = math.round(float(left) / gridX) * gridX
     top = math.round(float(top) / gridY) * gridY
     dropTarget.add(widget, left, top)
示例#42
0
 def removeItem(self, name, amount):
     self.items[name][1] = math.max(_itemMax, self.items[name][1]-amount)
示例#43
0
 def run(self):
     self.active = True
     packetIdToRetransmit = -1
     yield hold, self, self.startTime
     while True:       
         packetIdToRetransmit = self.getPacketIdToRetransmit()
         
         # First time we get 3DA
         if self.enabledCCA and not self.fastRecovery and packetIdToRetransmit!= -1:
             # Enter Fast Recovery if necessary
             self.fastRecovery = True
             self.ssthresh = math.max(math.ceil(self.windowSize/2), 2)
             self.windowSize = self.ssthresh + 3               
         
         # Further times we get 3DA
         if self.fastRecovery and packetIdToRetransmit != -1:
             # For every 3 dup acks received, get the packetID for retransmit
             self.acks[packetIdToRetransmit-1] = 0
             assert(packetIdToRetransmit != -1)
             
             # Create a new packet based on the packetID, and resent the packet
             message = "Packet " + str(packetIdToRetransmit) + "'s data goes here!"
             # packetId, timesent, sourceID, destid, isroutermsg, isack, msg
             newPacket = Packet(packetIdToRetransmit, now(), self.ID,
                     self.destinationID, False, False, message)
             activate(newPacket, newPacket.run())
             self.sendPacketAgain(newPacket)
             yield hold, self, newPacket.size/float(self.link.linkRate)
         # resend anything, if need to
         elif len(self.toRetransmit) > 0:
             (didtransmit, p) = self.retransmitPacket()
             if (didtransmit): # if transmitted, wait
                 yield hold, self, p.size/float(self.link.linkRate)
                 # collect stats
                 if not now() == 0:
                     self.link.buffMonitor.observe(len(self.link.queue))
                     self.link.dropMonitor.observe(self.link.droppedPackets)
                     self.sendRateMonitor.observe(PACKET_SIZE*self.numPacketsSent / float(now()))
             
         # If everything has been sent, go to sleep
         elif (PACKET_SIZE * self.numPacketsSent >= self.bitsToSend):
             self.active = False
             yield passivate, self
             self.active = True
         # otherwise, send new packets!
         elif len(self.outstandingPackets) < self.windowSize:
             # send a new packet
             packet = self.createPacket()
             self.sendPacket(packet)
             # wait
             yield hold, self, packet.size/float(self.link.linkRate)
             # collect stats
             if not now() == 0:
                 self.link.buffMonitor.observe(len(self.link.queue))
                 self.link.dropMonitor.observe(self.link.droppedPackets)
                 self.sendRateMonitor.observe(PACKET_SIZE*self.numPacketsSent / float(now()))
         # nothing to retransmit and cannot send new packets
         else:
             self.active = False
             yield passivate, self
             self.active = True
示例#44
0
def findMax(node):
	if node==None:
		return 0
	return 1+math.max(findMax(node.right),findMax(node.left))
示例#45
0
 def conductClientExperiment(serverExperiment):
   clientExperiment = FunExperimentClient()
   clientExperiment.index = serverExperiment.index
   clientExperiment.newProperty.value = math.max(0, math.min(0xFFFFFFFF, math.round(random.gauss(serverExperiment.default.value, serverExperiment.deviation))))
   return clientExperiment
示例#46
0
文件: seismeSIA.py 项目: lcpt/xc
def eta(viscousDamping):
  '''
  correction coefficient "eta" to obtain the elastic response spectrum.
  according SIA 261 2003 (16.2.3.1).
  '''
  return math.max(mat.sqrt(1/(0.5+10*viscousDamping),0.55))
示例#47
0
# start of the dict completion (type and total) #
#################################################
i=0
#print("start of the dict completion")	#for debogue
while i < len(tabDict):
	tabDict[i].total=tabDict[i].numA+tabDict[i].numG+tabDict[i].numC+tabDict[i].numT
	#fill the total attribut
	if tabDict[i].total!=0:
		tabDict[i].numA=float(tabDict[i].numA/tabDict[i].total)
		tabDict[i].numT=float(tabDict[i].numT/tabDict[i].total)
		tabDict[i].numG=float(tabDict[i].numG/tabDict[i].total)
		tabDict[i].numC=float(tabDict[i].numC/tabDict[i].total)
	#fill the now attribut
	if tabDict[i].total==0:
		tabDict[i].now=tabDict[i].ref
	if (max(tabDict[i].numA, tabDict[i].numT, tabDict[i].numG, tabDict[i].numC)==
		tabDict[i].numA):
		tabDict[i].now='A'
	if (max(tabDict[i].numA, tabDict[i].numT, tabDict[i].numG, tabDict[i].numC)==
		tabDict[i].numT):
		tabDict[i].now='T'
	if (max(tabDict[i].numA, tabDict[i].numT, tabDict[i].numG, tabDict[i].numC)==
		tabDict[i].numC):
		tabDict[i].now='C'
	if (max(tabDict[i].numA, tabDict[i].numT, tabDict[i].numG, tabDict[i].numC)==
		tabDict[i].numG):
		tabDict[i].now='G'
	#fill the type attribut
	if tabDict[i].total==0:
		tabDict[i].type="Reference"
	elif tabDict[i].total < cut_Off_Uncertainty and tabDict[i].ref==tabDict[i].now:
示例#48
0
import FlightTypes
import Aircraft
import Units

import math

def grossWeight(flightParameters, flightState):
# (flightParameters:FlightParameters) (flightState:FlightState) =
#    // Passengers average 190 lb
#    // Luggage is an average of 10-20 lb per passenger
    aircraft = flightParameters.AircraftType
    payload = flightParameters.Payload
    payloadWeight = (payload.PremiumPassengerCount + 
                     payload.StandardPassengerCount)*190.0 + payload.PremiumPassengerCount * 20.0 +
                    payload.StandardPassengerCount * 10.0
    initialFuel = flightParameters.InitialFuel
    fuelWeight = math.max(0.0, (initialFuel - flightState.FuelConsumed))
    return aircraft.OperatingEmptyWeight + payloadWeight + fuelWeight
示例#49
0
 def max(self, a, b):
     self[0] = math.max(a[0], b[0])
     self[1] = math.max(a[1], b[1])
     self[2] = math.max(a[2], b[2])
     return self
示例#50
0
 def equals(self, obj):
   margin = math.max(
       math.abs(self.lat - obj.lat), math.abs(self.lon - obj.lon))
   return margin <= self.MAX_MARGIN