Exemplo n.º 1
0
    def test_query_limit(self, users=None, rate_limit_only=False, rate=2):
        """Initializes a test for speed constraints
        @users: a user list to be used for this experiment
        @rate_limit_only:   only check rate limiting (do not attempt continuous
                            queries but only a certain number of queries / min)
        @rate: start rate limiting check with this many queries per second and
                adjust accordintgly.
        """

        vb.vb_print(self.verbose, "Initiating query limit test")

        if users is None:
            users = self._db.get_ordered_users()

        if len(users) == 1:
            raise SystemExit("Not enough users! At least two users required")

        self.attackers = [AuditorUser(self.service_id, u) for u in users]
        self.attacker = self.attackers.pop()
        victim = self.attackers.pop(0)

        self._db.insert_test("query_limit")
        self.test_id = self._db.get_test_id("query_limit")

        # limit on update location queries
        self.qps_u_limit = self._query_rate_limit_update(rate_limit_only,
                                                         rate)

        # limit on get_distance queries
        self.qps_r_limit = self._query_rate_limit_request(rate_limit_only,
                                                          rate)

        # total query limit should be the minimum of update/request limits
        self.absq_limit = math.min(self.absq_u_limit, self.absq_r_limit)
        self.qps_limit = math.min(self.qps_u_limit, self.qps_r_limit)
Exemplo n.º 2
0
def bdsqr(alpha, beta):
# BDSQR: Compute the singular values and bottom element of
#        the left singular vectors of a (k+1) x k lower bidiagonal 
#        matrix with diagonal alpha(1:k) and lower bidiagonal beta(1:k),
#        where length(alpha) = length(beta) = k.
#
# [sigma,bnd] = bdsqr(alpha,beta)
#
# Input parameters:
#   alpha(1:k)   : Diagonal elements.
#   beta(1:k)    : Sub-diagonal elements.
# Output parameters:
#   sigma(1:k)  : Computed eigenvalues.
#   bnd(1:k)    : Bottom elements in left singular vectors.

# Below is a very slow replacement for the BDSQR MEX-file.

# warning('PROPACK:NotUsingMex','Using slow matlab code for bdsqr.')

	k = len(alpha)
	if math.min(np.shape(alpha).conj().transpose()) != 1 or math.min(np.shape(beta).conj().transpose()) != 1:
		print("[bdsqr] alpha and beta must be vectors")
		return
	elif len(beta) != k:
		print("[bdsqr] alpha and beta must have the same length")
		return

	B = np.spdiags([alpha[:], beta[:]], [0, -1], k+1, k)
	U, S, V = np.linalg.svd(full(B), 0)
	sigma = np.diag(S)
	bnd = U[end, 1:k].conj().transpose()
	return sigma, bnd
Exemplo n.º 3
0
	def update(self):
		self.viewX = self.follow.appearance.x - self.viewWidth/2
		self.viewY = self.follow.appearance.y - self.viewHeight/2

		# Prevent offscreen viewport
		self.viewX = math.min(self.viewX, 0)
		self.viewY = math.min(self.viewY, 0)
Exemplo n.º 4
0
 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)))
    def get_reward(self):
        '''returns the reward of the last action taken'''
        '''Calculate Ec and Dc values'''
        self.Ec = math.min(max_energy_charging_possible_per_timestep,
                           self.It_actual, BSOC_max - self.old_BSOC)
        self.Dc = math.min(max_energy_discharging_possible_per_timestep,
                           self.Ot_actual, self.old_BSOC - BSOC_min)
        '''To calculate the reward, we will use the true demand of the data center at each time step.'''
        self.true_total_DCI_demand_next_timestep = self.get_demand_for_new_timestep(
        )
        alpha_term_one = self.action_array[2] + self.Ec
        alpha_term_two = (self.true_total_DCI_demand_next_timestep -
                          (self.action_array[2] + self.Dc))
        self.consumption_from_utility_after_taking_agent_action_into_account = alpha_term_one + alpha_term_two
        '''Keep in buffer for later use'''
        self.utility_demand_buffer_for_timesteps_in_a_slot.append(
            self.
            consumption_from_utility_after_taking_agent_action_into_account)

        if self.current_timestep == 3:
            '''take new Ymax value into account while calculating the reward'''
            '''calculate new Ymax first'''
            assert len(self.utility_demand_buffer_for_timesteps_in_a_slot) == 3
            self.Ymax_new = statistics.mean(
                self.utility_demand_buffer_for_timesteps_in_a_slot)
            if self.Ymax_new > self.Ymax_old:
                self.is_new_Ymax_greater = True
            else:
                self.is_new_Ymax_greater = False

            self.reward_of_the_last_action_taken = -(
                self.
                consumption_from_utility_after_taking_agent_action_into_account
                + self.Dc * battery_degradation_cost_per_unit_energy +
                self.is_new_Ymax_greater * peak_demand_cost_per_unit *
                (self.Ymax_new - self.Ymax_old))
            self.cumulative_reward_in_a_day.append(
                self.reward_of_the_last_action_taken)
            self.utility_demand_buffer_for_timesteps_in_a_slot = []

        else:
            '''Do not take the new cost function into account while calculating the reward.'''
            self.reward_of_the_last_action_taken = -(
                self.
                consumption_from_utility_after_taking_agent_action_into_account
                + self.Dc * battery_degradation_cost_per_unit_energy +
                self.is_new_Ymax_greater)
            self.cumulative_reward_in_a_day.append(
                self.reward_of_the_last_action_taken)
        '''Update the old BSOC value here'''
        self.old_BSOC = self.current_BSOC

        return self.reward_of_the_last_action_taken
Exemplo n.º 6
0
 def secondary_effects(self):
     # +1 CP
     if self.state_values['current_second_power'] < self.state_values[
             'max_second_power']:
         self.state_values['current_second_power'] = math.min(
             self.state_values['current_second_power'] + 1,
             self.state_values['max_second_power'])
     if self.engine.talents.anticipation and self.state_values[
             'current_second_power'] == self.state_values[
                 'max_second_power']:
         self.state_values['anticipation'] += math.min(
             self.state_values['anticipation'] + 1,
             self.state_values['anticipation_max'])
Exemplo n.º 7
0
def helper2(start, end, arr):
    if (start > end):
        return False

    i = (start + end) // 2
    if (i == arr[i]):
        return True

    leftIndex = math.min(i-1, arr[i])
    ok = helper(start, leftIndex, arr)
    if (ok) return ok

    rightIndex = math.min(arr[i], i + 1)
    return helper(rightIndex, end, arr)
 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)
Exemplo n.º 9
0
def chapman_orderedname_compound_sim(func1, func2, src, dest, qgrams=2):
    #soundex and smith waterman are used in java implementation
    # we have extended our suppor to change the functions.
    ESTIMATEDTIMINGCONST = float(0.026571428571428571428571428571429)
    if isinstance(src, Counter) and isinstance(dest, Counter):
        q_src = src
        q_dest = dest
    elif qgraml and qgraml > 0:
        print(" In qgrams")
        q_src = QGrams(src, qgram1)
        q_dest = QGrams(dest, qgraml)
    else:
        q_src = Counter(src.strip().split())
        q_dest = Counter(dest.strip().split())
    q_src_mag = sum(q_src.values())
    q_dest_mag = sum(q_dest.values())
    minTokens = math.min(q_src_mag, q_dest_mag)
    SKEW_AMOUNT = float(1)
    sumMatches = float(0)
    for i in xrange(1, minTokens + 1, 1):
        strWeightingAdjustment = ((float(1) / minTokens) + (
            ((((minTokens - i) + float(0.5)) -
              (minTokens / float(2))) / minTokens) * SKEW_AMMOUNT *
            (float(1) / minTokens)))
        sToken = q_src[q_src_mag - i]
        tToken = q_dest[q_dest_mag - i]
        found1 = func1(src, dest, qgram)
        found2 = func2(src, dest, qgram)
        sumMatches += ((float(0.5) * (found1 + found2)) *
                       strWeightingAdjustment)
    return sumMatches
Exemplo n.º 10
0
 def set_bandits_guile_level(self):
     c = self.state_values['bg_counter']
     level = math.min(c // 4, 3) #BG30/50 is highest level
     if level == 3:
         self.state_values['damage_multiplier'] *= 1.5 / 1.2 #would be 1.3/1.2 if under level 100
     else:
         self.state_values['damage_multiplier'] *= (1 + .1 * level) / (1 + .1 * (level-1))
Exemplo n.º 11
0
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)
Exemplo n.º 12
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)
Exemplo n.º 13
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))
		}
Exemplo n.º 14
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)
Exemplo n.º 15
0
def get_highest_day(year: int) -> int:
    now = datetime.datetime.today()
    if now.year != year:
        return 25
    if now.month != 12:
        return 25
    return math.min([25, now.day()])
Exemplo n.º 16
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)
def minhinge(length, mean=12.315):
    """
    :param length: length for which function needs to be evaluated
    :param mean: mean of the training sentence lengths
    :return: value of the minhinge function
    """
    return math.min(mean, length)  # Not used in experiments
Exemplo n.º 18
0
    def chunk(self, blob):
        """Break up a blob into a list of smaller chunks for the wire."""
        # return type hint:
        #   { __peerData: number, n: number, total: number, data: Blob }[]
        chunks = []
        size = blob.size
        total = math.ceil(size / util.chunkedMTU)

        index = 0
        start = 0

        while (start < size):
            end = math.min(size, start + util.chunkedMTU)
            b = blob.slice(start, end)
            chunk = {
                '__peerData': self._dataCount,
                'n': index,
                'data': b,
                'total': total
            }
            chunks.push(chunk)
            start = end
            index += 1
        self._dataCount += 1
        return chunks
Exemplo n.º 19
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)
Exemplo n.º 20
0
def targetRotation(matrix, r):
    m= len(matrix)
    n=len(matrix[0])
    r_circle=math.min(m,n)/2
    for idx in range(r):
        for idx_circle in range(r_circle):
            row_end=m-idx_circle
            col_end=n-idx_circle
Exemplo n.º 21
0
def jd_to_islamic(jd):
    jd = math.floor(jd) + 0.5
    year = math.floor(((30 * (jd - ISLAMIC_EPOCH)) + 10646) / 10631)
    month = math.min(
        12,
        math.ceil((jd - (29 + islamic_to_jd(year, 1, 1))) / 29.5) + 1)
    day = (jd - islamic_to_jd(year, month, 1)) + 1
    return [year, month, day]
    def time_of_closest_approach(self, other):
        # Going to be finding time
        time = 0

        # Setting up velocity and position vectors for given time
        radiiAB = self.size + other.size
        positionAB = euclid.Vector2(self.x, self.y) - euclid.Vector2(other.x, other.y)
        velocityAB = self.vector - other.vector

        # d(t) = |A(t) - B(t)| - (Ra + Rb)
        # 0 = math.sqrt(A(t) - B(t))**2 - (Ra + Rb)
        # (Ra + Rb)**2 = (A(t) - B(t))**2
        # (Ra + Rb)**2 = ( ( Pa + Va(t) ) - ( Pb + Vb(t) ) )**2
        #   Pab = Pa - Pb   Vab = Va - Vb
        # (Ra + Rb)**2 = ( Pab + Vab(t) )**2
        # 0 = ( Pab + Vab(t) )**2 - (Ra + Rb)**2
        # 0 = ( Pab + Vab(t) )*( Pab + Vab(t) ) - (Ra + Rb)**2
        # 0 = t**2(Vab * Vab) + 2t(Pab * Vab) + (Pab * Pab) - (Ra + Rb)**2
        # Quadratic formula
        # t = ( -b +- math.sqrt(b**2 - 4ac) ) / 2a
        # Making quadratic variables a, b, c
        # a = Vab * Vab
        # b = 2(Pab * Vab)
        # c = (Pab * Pab) - (Ra + Rb)**2
        # http://twobitcoder.blogspot.com/2010/04/circle-collision-detection.html
        a = velocityAB.dot(velocityAB)
        b = 2 * positionAB.dot(velocityAB)
        c = positionAB.dot(positionAB) - (radiiAB**2)

        # The quadratic discriminant.
        discriminant = b * b - 4 * a * c

        # Case 1:
        # If the discriminant is negative, then there are no real roots, so there is no collision.
        # The time of closest approach is given by the average of the imaginary roots, which is:  t = -b / 2a
        if (discriminant < 0):
            time = -b / (2 * a)
            collision = false
        else:
            # Case 2 and 3:
            # If the discriminant is zero, then there is exactly one real root, meaning that the circles just grazed each other.
            # If the discriminant is positive, then there are two real roots, meaning that the circles penetrate each other.
            # In that case, the smallest of the two roots is the initial time of impact.  We handle these two cases identically.
            time0 = (-b + math.sqrt(float(discriminant))) / (2 * a)
            time1 = (-b - math.sqrt(float(discriminant))) / (2 * a)
            time = math.min(time0, time1)

            # We also have to check if the time to impact is negative.  If it is negative, then that means that the collision
            # occured in the past.
            if (time < 0):
                collision = false
            else:
                collision = true

        # Finally, if the time is negative, then set it to zero, because, again, we want this function to respond only to future events.
        if (time < 0):
            time = 0
        return time, collision
Exemplo n.º 23
0
def edit_dist(sa, sb, ai, bi):
  if ai == len(sa):
    return len(sb) - bi
  if bi == len(sb):
    return len(sa) - ai
  
  a = sa[ai:]
  b = sb[bi:]

  minv = 1 << 20

  if a[0] == b[0]:
    minv = min(minv, edit_dist(sa, sb, ai + 1, bi + 1))

  e1 = 1 + edit_dist(sa, sb, ai + 1, bi)
  e2 = 1 + edit_dist(sa, sb, ai, bi + 1)

  return min(minv, min(e1, e2))
Exemplo n.º 24
0
def intersection(predict_test_y, test_y):
    res = 0
    for i in range(len(test_y)):
        temp = 0
        for j in range(len(test_y[i])):
            temp += math.min(test_y[i][j], predict_test_y[i][j])
        res += temp
    res = res * 1.0 / len(test_y)
    return res
Exemplo n.º 25
0
def jd_to_islamic(jd):


    jd = math.floor(jd) + 0.5
    year = math.floor(((30 * (jd - ISLAMIC_EPOCH)) + 10646) / 10631)
    month = math.min(12,
                math.ceil((jd - (29 + islamic_to_jd(year, 1, 1))) / 29.5) + 1)
    day = (jd - islamic_to_jd(year, month, 1)) + 1
    return [year, month, day]
Exemplo n.º 26
0
def intersection(predict_test_y,test_y):
	res=0
	for i in range(len(test_y)):
		temp=0
		for j in range(len(test_y[i])):
			temp += math.min( test_y[i][j] , predict_test_y[i][j] )
		res += temp
	res = res*1.0/len(test_y)
	return res
Exemplo n.º 27
0
 def set_bandits_guile_level(self):
     c = self.state_values['bg_counter']
     level = math.min(c // 4, 3)  #BG30/50 is highest level
     if level == 3:
         self.state_values[
             'damage_multiplier'] *= 1.5 / 1.2  #would be 1.3/1.2 if under level 100
     else:
         self.state_values['damage_multiplier'] *= (1 + .1 * level) / (
             1 + .1 * (level - 1))
Exemplo n.º 28
0
 def collide_time(self, ball):
     vel = self.n.dot(ball.vel)
     pos = self.n.dot(ball.pos)
     if vel == 0:
         return None
     t1 = (pos + ball.r) / vel
     t2 = (pos - ball.r) / vel
     t = math.min(t1, t2)
     return None if t < 0 else t
Exemplo n.º 29
0
 def step(self, action):
     # Execute one time step within the environment
     self.old_states = self.states
     self._take_action(action)
     self.currentStep += 1 #we just advanced by one dwellTime
     
     #check if we have reached our timeout or otherwise ended
     done = False #todo: check if we come within distance of origin
     if self.currentStep >= self.maxSteps:
         done = True
 
     ### Calculate the Reward ###
     '''Reward is the minimum distance between the origin and
     the particle as it moves between the initial and final states'''
     x0 = self.old_states[0]
     xf = self.states[0]
     y0 = self.old_states[1]
     yf = self.states[1]
     
     #calculate slope from dx and dy
     dx = xf - x0
     dy = yf - y0
     
     #first, we can assume cost = distance from final position to origin
     dist = np.linalg.norm(self.states[0:2])
     #check if we are passing by the origin (so we could be closer)
     if xf*x0 < 0 or yf*y0 < 0:
         if dx == 0: #moving only vertically
             dist = abs(x0)
         if dy == 0: #moving only horizontally
             dist= abs(y0)
         if dx != 0 and dy != 0: #moving at an angle
             m = dy / dx
             x = (m*m*x0 + m*y0) / (m*m + 1)
             y = m*(x - x0) + y0
             dist = math.min(dist, math.sqrt(x*x + y*y))
     
     #reward the agent by -1 * dist from origin
     reward = -dist
     
     
     #penalize the agent by 1,000 if it exits the state bounds
     if xf < self.stateBounds[0] or xf > self.stateBounds[1] or yf < self.stateBounds[0] or yf > self.stateBounds[1]:
             reward -= 1000;
     
     #finally, convert to float32 to play nice with pytorch
     reward = reward.astype('float32')
     
     #finish if we are within 0.01 microns of the goal
     done = done or (dist < 0.01)
             
     newState = self.states
 
 
     #return state, reward, done, next state
     return self.states, reward, done, newState 
Exemplo n.º 30
0
def update_RD(periods, old_RD):
	PERIODS_TILL_MAX_UNCERTAINTY = 100
	TYPICAL_RATING_DEVIATION = 50
	# c is a constant, based on the above 2 factors, based on uncertainty in 
	#		player's skill
	c_sq = (BASE_RD**2 - TYPICAL_RATING_DEVIATION**2)/PERIODS_TILL_MAX_UNCERTAINTY
	c = math.sqrt(c_sq)
	
	new_RD = math.sqrt(old_RD**2 + c**2 * periods)
	return math.min(new_RD, 350)
Exemplo n.º 31
0
def compute():
    # read out
    p1 = np.array([float(e_x1.get()), float(e_y1.get()), float(e_z1.get())])
    p2 = np.array([float(e_x2.get()), float(e_y2.get()), float(e_z2.get())])
    p3 = np.array([float(e_x3.get()), float(e_y3.get()), float(e_z3.get())])
    pts = [p1, p2, p3]

    # get corner and edges
    dists = [
        np.linalg.norm(p[:-1] - p1[:-1]) + np.linalg.norm(p[:-1] - p2[:-1]) +
        np.linalg.norm(p[:-1] - p3[:-1]) for p in pts
    ]
    corner = pts[np.argmin(dists)]
    other1 = pts[(np.argmin(dists) + 1) % 3]
    other2 = pts[(np.argmin(dists) + 2) % 3]

    # find rotations
    theta1 = math.degrees(
        math.atan2(other1[1] - corner[1], other1[0] - corner[0]))
    theta1 = (theta1 + 180) % 90
    theta2 = math.degrees(
        math.atan2(other2[1] - corner[1], other2[0] - corner[0]))
    theta2 = (theta2 + 180) % 90

    # check average rot
    if math.fabs(theta2 - theta1) <= 45:
        theta = (theta1 + theta2) / 2
        theta_diff = math.fabs(theta2 - theta1)
    else:
        theta = ((theta1 + theta2 + 90) / 2) % 90
        theta_diff = math.min(math.fabs(theta2 - theta1 + 90),
                              math.fabs(theta2 - theta1 - 90))

    # Rotate
    s = math.sin(theta / 180 * math.pi)
    c = math.cos(theta / 180 * math.pi)

    # bounds
    x = [p[0] * c + p[1] * s for p in pts]
    y = [-p[0] * s + p[1] * c for p in pts]
    z = [p[2] for p in pts]

    t_res.delete('1.0', END)
    t_res.insert(
        END,
        "x_min: {:.3f}\nx_max: {:.3f}\ny_min: {:.3f}\ny_max: {:.3f}\nz_min: {:.3f}\nz_max: "
        "{:.3f}\nrotation: {:.3f}".format(np.min(x), np.max(x), np.min(y),
                                          np.max(y), np.min(z), np.max(z),
                                          theta))
    if theta_diff <= 5:
        rospy.loginfo("Success: Bounding Box computed (delta theta %.1fdeg)!" %
                      theta_diff)
    else:
        rospy.logwarn("Large delta theta (%.1fdeg) detected!" % theta_diff)
        rospy.loginfo("Success: Bounding Box computed!")
Exemplo n.º 32
0
 def minimumTotal(self, triangle):
     m = len(triangle)
     a = []
     a[m - 1] = triangle[m - 1]
     for i in range(m - 2, -1, -1):
         currentLine = triangle[i]
         a[i] = []
         for j in range(0, len(currentLine)):
             a[i][j] = math.min(a[i + 1][j],
                                a[i + 1][j + 1]) + currentLine[j]
     return a[0][0]
Exemplo n.º 33
0
 def coinChange(self, coins, amount):
     a = []
     a[0] = 0
     for i in range(1, amount + 1):
         for j in range(0, len(coins)):
             if i - coins[j] > -1:
                 if a[i]:
                     a[i] = math.min(a[i], a[i - coins[j]] + 1)
                 else:
                     a[i] = a[i - coins[j]] + 1
     return a[amount] > amount and -1 or a[amount]
Exemplo n.º 34
0
def create_simulation_actuals(options: Options, data_provider: DataProvider,
                              this_date: datetime.date, this_hour: int,
                              step_size_minutes: int) -> EgretModel:
    ''' Get an Egret model consisting of data to be treated as actuals, starting at a given time.

    Parameters
    ----------
    options:Options
        Global option values
    data_provider: DataProvider
        An object that can provide actual and/or forecast data for the requested days
    this_date: date
        The date of the first time step for which data should be retrieved
    this_hour: int
        0-based index of the first hour of the day for which data should be retrieved
    step_size_minutes: int
        The number of minutes between each time step
    '''
    # Convert time string to time
    start_time = datetime.datetime.combine(this_date,
                                           datetime.time(hour=this_hour))

    # Pick whether we're getting actuals or forecasts
    if options.simulate_out_of_sample:
        get_data_func = data_provider.populate_with_actuals
    else:
        print("")
        print(
            "***WARNING: Simulating the forecast scenario when running deterministic RUC - "
            "time consistency across midnight boundaries is not guaranteed, and may lead to threshold events."
        )
        get_data_func = data_provider.populate_with_forecast_data

    # Get a new model
    total_step_count = options.ruc_horizon * 60 // step_size_minutes
    md = data_provider.get_initial_actuals_model(options, total_step_count,
                                                 step_size_minutes)

    # Fill it in with data
    if this_hour == 0:
        get_data_func(options, start_time, total_step_count, step_size_minutes,
                      md)
    else:
        # only get up to 24 hours of data, then copy it
        timesteps_per_day = 24 * 60 / step_size_minutes
        steps_to_request = math.min(timesteps_per_day, total_step_count)
        get_data_func(options, start_time, steps_to_request, step_size_minutes,
                      md)
        for _, vals in get_forecastables(md):
            for t in range(timesteps_per_day, total_step_count):
                vals[t] = vals[t - timesteps_per_day]

    return md
Exemplo n.º 35
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
Exemplo n.º 36
0
def parseCigar(cigar):
	cigar2={}
	present=[]
	detectEndOfCigar=0
	i=0
	while 1:
		present=[]
		posM=cigar.find('M')
		posD=cigar.find('D')
		posS=cigar.find('S')
		posI=cigar.find('I')
		if cigar.find('M')!=-1:
			present.append(posM)
		if cigar.find('D')!=-1:
			present.append(posD)
		if cigar.find('S')!=-1:
			present.append(posS)
		if cigar.find('I')!=-1:
			present.append(posI)
		#print(present)
		closest=min(present)
		#print("Closest="+str(closest))
		if closest==posM:
			cigar2[i]=['M',cigar.split('M')[0]]
			if len(present)==1:
				detectEndOfCigar=1
			else:
				cigar=cigar.split('M')[1]
		elif closest==posD:
			cigar2[i]=['D',cigar.split('D')[0]]
			if len(present)==1:
				detectEndOfCigar=1
			else:
				cigar=cigar.split('D')[1]
		elif closest==posI:
			cigar2[i]=['I',cigar.split('I')[0]]
			if len(present)==1:
				detectEndOfCigar=1
			else:
				cigar=cigar.split('I')[1]
		elif closest==posS:
			cigar2[i]=['S',cigar.split('S')[0]]
			if len(present)==1:
				detectEndOfCigar=1
			else:
				cigar=cigar.split('S')[1]
		#print("detectEndCigar="+str(detectEndOfCigar))
		if detectEndOfCigar==1:
			break
		del(present[present.index(closest)])
		i+=1
	return cigar2
Exemplo n.º 37
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
Exemplo n.º 38
0
 def get_random_key_frame_duration_gene(max_frame, max_duration):
     """
     Creates a random (in input, frame and duration) key frame duration gene
     :param max_frame: <int> the maximum frame that the gene created can have
     :param max_duration: <int> the maximum frame duration that the gene created can have
     :return: <KeyFrameDurationGene> a random (in input, frame and duration) key frame duration gene
     """
     random_key_input = random.choice(word_list)
     random_frame = random.randint(1, max_frame)
     random_duration = math.min(random.randint(1, max_duration),
                                max_frame - random_frame + 1)
     return KeyFrameDurationGene(random_key_input, random_frame,
                                 random_duration)
Exemplo n.º 39
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
Exemplo n.º 40
0
def jumpSearch(arr, key):
    """
    Keep jumping with step size of sqrt(n) till the interval 
    has the key in range
    Then do linear search.
    Its complexity is O(sqrt(n)). its between linear and binary search. 
    In systems where jumping back is difficult, jump search is better than binary search.
    """
    print '~~~ jump search ~~~'
    n = len(arr)
    step = int(math.sqrt(len(arr)))
    prev = 0
    while (arr[math.min(step,n)] < key):
        prev = step
        step = step + step
        if prev >= n:
            return -1
Exemplo n.º 41
0
def generateWeightMap(LS, shape, lens, roi):

    H=LS[2]
    w,h = LensSensorFOVCalc(lens.focalLen, lens.sensorSize, H)
    
    px_x = w / shape[1];
    px_y = h / shape[0] 
    
    LS[0]=LS[0] /px_x
    LS[1]=LS[1] /px_y

    LS_rw=[int(shape[0]/2) + LS[0], int(shape[1]/2)+LS[1]]

    LS_rw[0]=LS_rw[0]*px_x
    LS_rw[1]=LS_rw[1]*px_y
    
    X,Y = np.meshgrid(range(0,shape[1]), range(0,shape[0]));
    
    X=X*px_x
    Y=Y*px_y
   
    coords=np.vstack((X.flatten(), Y.flatten()))

    r=LS_rw[0] - coords[0]
    s=LS_rw[1] - coords[1]
    
    m=np.sqrt(r**2 + s**2)

    m=np.sqrt(m**2 + H**2)
    m=m**2
   
    m=m/m.min()

    m=np.reshape(m,shape)
    

    if np.size(roi) > 0:
        x1=roi[0]
        x2=roi[1]
        y1=roi[2]
        y2=roi[3]
        
        m=m[y1:y2, x1:x2]
        
    return m
    def DP(self, ans, start, end):
        if start > end:
            return 0
        if ans[start][end]:
            return ans[start][end]
        ans[start][end] = sys.minint

        # 现在要从[from, to] 中猜数字
        # 假设先猜i,i可以是[from, to] 中的任何数字,遍历之
        for i in range(start, end + 1):
            # left为从[from, i - 1] 猜对数字至少需要花费的money
            left = self.DP(start, i - 1)
            # right为从[i + 1, end] 猜对数字至少需要花费的money
            right = self.DP(i + 1, end)

            temp = math.max(left, right)
            ans[start][end] = math.min(temp, ans[start][end])
        return ans[start][end]
Exemplo n.º 43
0
    def smoothOneSubSeries(self, weights, rawData, smoothedData): 
        cycleLength = len(rawData)
 
        #Smooth the cyclic sub-series with LOESS and then extrapolate one place beyond each end.
        smoother = self._fLoessSmootherFactory.setData(rawData).setExternalWeights(weights).build()

        """
         public static void arraycopy(Object source_arr, int sourcePos,
                        Object dest_arr, int destPos, int len)
         Parameters : 
          source_arr : array to be copied from
          sourcePos : starting position in source array from where to copy
          dest_arr : array to be copied in
          destPos : starting position in destination array, where to copy in
          len : total no. of components to be copied.
        """
        #Copy, shifting by 1 to leave room for the extrapolated point at the beginning.
        #System.arraycopy(smoother.smooth(), 0, smoothedData, self._fNumPeriodsToExtrapolateBackward, cycleLength)

        smoothedData[destPos:destPos + cycleLength] = smoother.smooth()[self._fNumPeriodsToExtrapolateBackward:self._fNumPeriodsToExtrapolateBackward + cycleLength]
          
        interpolator = smoother.getInterpolator()

        #Extrapolate from the leftmost "width" points to the "-1" position
        left = 0;
        right = left + self._fWidth - 1;
        right = math.min(right, cycleLength - 1)
        leftValue = self._fNumPeriodsToExtrapolateBackward

        #es menor e igual
        for i in range(1,fNumPeriodsToExtrapolateBackward + 1):
            ys = interpolator.smoothOnePoint(-i, left, right)
            smoothedData[leftValue - i] = smoothedData[leftValue] if ys == None else ys

            #Extrapolate from the rightmost "width" points to the "length" position (one past the array end).
            right = cycleLength - 1
            left = right - sel._fWidth + 1
            left = math.max(0, left)
            rightValue = sel._fNumPeriodsToExtrapolateBackward + right

            #es menor e igual
            for i in range(1,fNumPeriodsToExtrapolateForward + 1):
                ys = interpolator.smoothOnePoint(right + i, left, right)
                smoothedData[rightValue + i] = smoothedData[rightValue] if ys == None else ys
 def maxArea(self, height):
     """
     :type height: List[int]
     :rtype: int
     """
     if len(height) < 2:
         return 0
     left = 0
     right = len(height) - 1
     maxArea = 0
     while left < right:
         area = (right - left) * math.min(height[left], height[right])
         if maxArea < area:
             maxArea = area
         if height[left] < height[right]:
             left += 1
         else:
             right -= 1
     return maxArea
Exemplo n.º 45
0
def simulatedAnnealing(M, N, D, W, start, end):
    # Takes Tmax and dT in to allow for experimentation.
    # When everything's done it'll only take the size of a the board, and eggs (M, N, k)
    State = Switchboard(M, N, D, W) # The State to be returned when optimal
    Temp = 0.07
    dT = 0.00001
    targetBoardEvaluation = 0.7
    while (State.evaluateBoard() < targetBoardEvaluation):
        neighbours = State.generateNeighbours()
        newState = None # The best neighbour
        for neighbour in neighbours: # Loop through neighbours to find the best one
            if (neighbour.evaluateBoard() > newState):
                newState = neighbour
        q = ((newState.evaluateBoard()-State.evaluateBoard())/State.evaluateBoard())
        p = math.min(1, math.e((-q)/Temp))
        x = random.random() # Random number between 0 and 1
        if (x > p ):
            State = newState
        else:
            State = neighbours[random.randint(0, len(neighbours))] # None of them were very good, choose a random one
        Temp -= dT
    return State
Exemplo n.º 46
0
def indian_civil_to_jd(year, month, day):


    gyear = year + 78
    leap = leap_gregorian(gyear)     ## Is this a leap year ?
    start = gregorian_to_jd(gyear, 3, 21 if leap else 22)
    Caitra = 31 if leap else 30

    if (month == 1):
        jd = start + (day - 1)
    else :
        jd = start + Caitra
        m = month - 2
        m = math.min(m, 5)
        jd += m * 31
        if (month >= 8):
            m = month - 7
            jd += m * 30
        
        jd += day - 1
    

    return jd
Exemplo n.º 47
0
Arquivo: leo.py Projeto: Kraji/lambo
cursor.execute("SELECT Price,Volume,Time FROM ETHEUR")
eth = np.array(cursor.fetchall())

cursor.execute("SELECT Price,Volume,Time FROM XBTEUR")
btc = np.array(cursor.fetchall())

(size, p) = btc.shape
# plt.plot(btc[:,2],btc[:,0])
# plt.show()
minWindowSize = 3

ethPrice= av_group(eth[:,0],minWindowSize)
btcPrice= av_group(btc[:,0],minWindowSize)
size = ethPrice.size

ethPrice = ethPrice[-20000:]

ethLog = np.log(ethPrice[1:]) - np.log(ethPrice[:(size-1)]) 
btcLog = np.log(btcPrice[1:]) - np.log(btcPrice[:(size-1)]) 
# ethLog = 1000* ethLog
 # print np.mean(np.square(trueValue-predi))

money = 1000
eth = 10

step=3
for i in range(ethLog.size - step):
    if (money > 0) and (ethLog[i] > 0) and (ethLog[i+1] > 0) and (ethLog[i+2] > 0):
        useMoney = math.min(money, 20.)
        eth += useMoney/ ethPrice[]
Exemplo n.º 48
0
 def send_messages(self, messages):
     entries = [{'Id': 'message_'+str(i), 'MessageBody': messages[i]} for i in range(len(messages))]
     for i in range(len(int(entries/10))):
         self._client._client.send_message_batch(
             QueueUrl=self.topic,
             Entries=entries[(i*10):math.min((i*10+1), len(entries))])
Exemplo n.º 49
0
def findMin(node):
	if node==None:
		return 0
	return 1+math.min(findMin(node.right),findMin(node.left))
 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)
Exemplo n.º 51
0
        
        if step <= minStep:
        
            print "starting city-based search"  
    
            for city in areas.keys():
                print "starting city: " + areas[city]
                
                try:
                    url = baseURL.format(city, startNum+1, upperRange, 1)
                    print url
                    page = fetch(url)
                    soup = BeautifulSoup(page)
                    items = soup.findAll('span','org bold')[0].string.strip()
                    pagesCity = math.ceil(float(items) / resultsPerPage)
                    pagesCity = math.min(pagesCity, 100)
                    print "number of pages in range: " + str(pagesCity)
                except:
                    print "no results in range"
                    continue
                    
                fetch_items(soup)
                    
                for j in range(2,int(pagesCity)+1):
                    
                    url = baseURL.format(city, startNum+1, upperRange, j)
                    print url
                    page = fetch(url)
                    soup = BeautifulSoup(page)

                    fetch_items(soup)
Exemplo n.º 52
0
 def secondary_effects(self):
     # +1 CP
     if self.state_values['current_second_power'] < self.state_values['max_second_power']:
         self.state_values['current_second_power'] = math.min(self.state_values['current_second_power']+1, self.state_values['max_second_power'])
     if self.engine.talents.anticipation and self.state_values['current_second_power'] == self.state_values['max_second_power']:
         self.state_values['anticipation'] += math.min(self.state_values['anticipation']+1, self.state_values['anticipation_max'])
Exemplo n.º 53
0
 def min(self, a, b):
     self[0] = math.min(a[0], b[0])
     self[1] = math.min(a[1], b[1])
     self[2] = math.min(a[2], b[2])
     self[3] = math.min(a[3], b[3])
     return self
Exemplo n.º 54
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