def run(self):
        # First create the reporting times list
        reporting_times = numpy.arange(self.reportingInterval,
                                       self.timeHorizon,
                                       self.reportingInterval)

        prev_time = 0.0
        # Iterate over the queue. The (delayed) events will be added to the queue as they are trigerred.
        for next_time in reporting_times:
            self.log.Message(
                "Simulating from {0:.5f}s to {1:.5f}s...".format(
                    prev_time, next_time), 0)

            try:
                while True:
                    # Get the first item from the heap
                    (t_event, inlet_event_port,
                     target_neurone) = heappop(self.events_heap)

                    # If out of the interval put it back
                    if t_event > next_time:
                        heappush(self.events_heap,
                                 (t_event, inlet_event_port, target_neurone))
                        break

                    #print('{0} --> {1}s (trigger event on {2})'.format(target_neurone.Name, t_event, inlet_event_port.CanonicalName))

                    # Integrate until next event time and report the data if there is a discontinuity
                    target_neurone.simulation.IntegrateUntilTime(
                        t_event, pyActivity.eDoNotStopAtDiscontinuity, True)

                    # Trigger the event and reinitialize the system
                    inlet_event_port.ReceiveEvent(t_event)
                    target_neurone.simulation.Reinitialize()

                    self.spike_count += 1

            except IndexError:
                pass

            # Integrate each neurone until the *next_time* is reached and report the data
            for simulation in self.simulations:
                #print('{0}........ {1} {2} {3}'.format(simulation.m.Name,
                #                                       simulation.CurrentTime,
                #                                       '<' if simulation.CurrentTime < next_time else '=' ,
                #                                       next_time))
                if simulation.CurrentTime < next_time:
                    simulation.IntegrateUntilTime(
                        next_time, pyActivity.eDoNotStopAtDiscontinuity, True)
                simulation.ReportData(next_time)

            # Set the progress
            self.log.SetProgress(100.0 * next_time / self.timeHorizon)
            prev_time = next_time

        print('Simulation has ended successfuly.')
        print('Processing the results...')

        # Finally, process the results (generate 2D plots, raster plots, and other voodoo-mojo stuff)
        self.processResults()
Пример #2
0
    def topKFrequent(self, words, K):
        """
        :type words: List[str]
        :type k: int
        :rtype: List[str]
        """
        mDict = collections.defaultdict(int)
        for w in words:
            mDict[w] += 1

        mDict2 = collections.OrderedDict()

        # knowledge sort dict by value in descending order
        sortedTuples = sorted(mDict.items(), key=lambda x: x[1], reverse=True)

        for k, v in sortedTuples:
            if v not in mDict2:
                mDict2[v] = []
                mDict2[v].append(k)
            else:
                mDict2[v].append(k)

        heap, res = [], []
        for key, val in mDict2.iteritems():
            for e in val:
                heappush(heap, e)

            while heap:
                res.append(heappop(heap))
                K -= 1
                if not K:
                    return res

        return res
Пример #3
0
    def find(self, origin, destination):
        frontier = []
        heappush(frontier, (0, origin))
        came_from = {origin: None}
        accumulated_cost = defaultdict(lambda: float('inf'))
        accumulated_cost[origin] = 0

        while frontier:
            current = heappop(frontier)[1]

            if current == destination:
                break

            for next, base_cost in self.grid.neighbors(*current):
                calculated = self.cost(current, next) * base_cost
                if not calculated:
                    continue
                new_cost = accumulated_cost[current] + calculated
                if new_cost < accumulated_cost[next]:
                    accumulated_cost[next] = new_cost
                    priority = new_cost + self.heuristic(next, destination)
                    heappush(frontier, (priority, next))
                    came_from[next] = current

        current = destination
        yield current
        while current != origin:
            current = came_from[current]
            yield current
Пример #4
0
	def __init__(self,g,vo,vd,heuristica = None):
		super(AEstrella, self).__init__(g,vo,vd,heuristica = None)
		abiertos = []
		unCamino = [vo]
		par = [0,unCamino] #dejo f(x) como 0
		heappush(abiertos,par)
		final = False
		padre = None
		verticeActual = None

		while abiertos and not final:
			par = heapq.heappop(abiertos)
			idVerticeActual = par[1][-1]
			if idVerticeActual != vd:
				vecinos = g.adj(idVerticeActual)
				for v in vecinos:
					id = v.get_id()
					if (id != idVerticeActual):
						parAGuardar = [None,None]
						unCamino = par[1] + [id]
						parAGuardar = [__f__(unCamino,vd,g,heuristica),unCamino]
						g.get_V(id).set_padre(idVerticeActual)
						heappush(abiertos,parAGuardar)	
														
			else:
				final = True				

		###ARMO EL RECORRIDO
		if final:
			self.resultado = par[1]
 def setTimeOut(self, callBackFunc, delayDuration):
     current_time = int(round(time.time() * 1000))
     call_time = current_time + delayDuration
     if call_time not in self.requests:
         self.requests[call_time] = []
     self.requests[call_time].append(callBackFunc)
     heappush(self.call_times, call_time)
Пример #6
0
 def add_task(self, callback, period=0.0, delay=0.0, duration=None, callback_args=()):
     task = PeriodicTask(callback, period, delay, callback_args)
     self._poller.register(task)
     if duration:
         expire = gettime() + duration + delay
         heappush(self._expireq, (expire, task))
         self._duration_timer.settime(self._expireq[0][0], 0.0, absolute=True)
 def setTimeOut(self, callBackFunc, delayDuration):
     current_time = int(round(time.time() * 1000))
     call_time = current_time + delayDuration
     if call_time not in self.requests:
         self.requests[call_time] = []
     self.requests[call_time].append(callBackFunc)
     heappush(self.call_times, call_time)
Пример #8
0
    def leastInterval(self, tasks, n):
        """
        :type tasks: List[str]
        :type n: int
        :rtype: int
        """
        heap, m = [], collections.defaultdict(int)
        for t in tasks:
            m[t] += 1

        res = 0
        for k, v in m.iteritems():
            heappush(heap, [-v, k])

        while heap:
            temp = []
            l = min(n + 1, len(heap))
            for i in xrange(l):
                item = heappop(heap)
                item[0] = item[0] + 1
                if item[0] <= 0:
                    temp.append(item)

            if not temp:
                break
            res += len(temp)
            if temp[0][0] != 0:
                res += max(0, n + 1 - len(temp))
            for t in temp:
                heappush(heap, t)

        return res
Пример #9
0
def add_task(task, priority=0):
    if task in entry_finder:
        remove_task(task)
    count = next(counter)
    entry = [priority, count, task]
    entry_finder[task] = entry
    heappush(pq, entry)
Пример #10
0
def djikstra(nodes,links,source,dest):
    """An implementation of Djikstra's Algorithm for our Node and Link classes"""
    route = []
    vertexes = []
    for v in nodes:
        v.set_dist(float("inf"))
        v.set_prev(None)
        heappush(vertexes, v)
    source.set_dist(0)
    heapify(vertexes)
    while vertexes:
        unsorted = False
        u = heappop(vertexes)
        if u == dest:
            break #because we found the destination no need to look further
        for v in u.get_links():
            if v.get_enabled():
                alt = u.get_dist() + 1
                target = v.get_target()
                if alt < target.get_dist():
                    target.set_dist(alt)
                    target.set_prev(u)
                    unsorted = True #just a variable that help check if changes were made to the objects inside the heap
            if unsorted: #because i updated the variables but the heap wasn't maintained, i just heapify it again
                heapify(vertexes) 
    #this is the part that saves the distance and route  
    if dest.get_dist() == float("inf"): #if there is no route then we just return None
        return None
    u = dest
    while u.get_prev() != None:
        v = u.get_prev()
        route.insert(0, v.get_specific_link(u)) 
        u = v
    return route
def uniform_cost_search(startState, goalState, image):
    frontier = []  # lowest cost comes out first
    startState.cost = 0.0
    startState.parent = None
    heappush(frontier, startState)
    beenthere = {startState : 0}  
       
    width, height = image.size
    pixels = image.load()
      
    it = 0  
    while len(frontier) > 0:
        s = heappop(frontier)    #Mystate
        if s == goalState:    #return state which reached goal
            return s
        actions = options(s, width, height)
        if ((it % 5000) < 1000):
            pixels[s.x, s.y] = (0, 255, 0)
        it+=1 
        for a in actions:
            child = transition(s, a, pixels)       # compute the next state
            acost = action_cost(s, a, pixels)      # compute the cost of the action
            
            c_cost = beenthere.get(child)
            if c_cost != None:               #if child is inside of beenthere
                if s.cost + acost < c_cost:
                    child.cost = s.cost + acost
                    child.parent = s;
                    beenthere[child] = child.cost
            else:
                child.cost = s.cost + acost;
                child.parent = s;
                heappush(frontier, child)  
                beenthere[child] = child.cost  
    raise Exception("No path to traverse")
Пример #12
0
    def scheduleCourse3(self, courses):
        """
        :type courses: List[List[int]]
        :rtype: int
        """

        if len(courses) == 0:
            return 0

        courses.sort(key=lambda x: x[1])

        selectedT = []
        sumT = 0

        for course in courses:
            t, d = course
            if sumT + t <= d:
                sumT += t
                heappush(selectedT, -t)
            else:
                if len(selectedT) > 0 and -selectedT[0] > t:
                    sumT = sumT - (-selectedT[0]) + t
                    heappushpop(selectedT, -t)

        return len(selectedT)
Пример #13
0
    def add(self, val: int) -> int:
        if len(self.stream) < self.k:
            heappush(self.stream, val)
        elif val > self.stream[0]:      # if the new value is greater than the smallest element in the min heap,
            # then it's one of the largest elements greater than kth. else it's even smaller, ignore it
            heappop(self.stream)
            heappush(self.stream, val)

        return self.stream[0]
Пример #14
0
    def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
        q = []
        heapify(q)
        for p in points:
            d = p[0] * p[0] + p[1] * p[1]
            heappush(q, (d, p))

        q = list(item for _, item in nsmallest(K, q))
        return q
Пример #15
0
def construct(tree):
    while (len(tree) > 1):
        left = _heapq.heappop(tree)
        right = _heapq.heappop(tree)
        root = (left[0] + right[0], left[1] + right[1],
                Tree(left[0] + right[0], left[1] + right[1]))
        root[2].left = left[2]
        root[2].right = right[2]
        _heapq.heappush(tree, root)
    return tree
 def Idle(self):
     time_ms = time.monotonic() * 1000
     while self._tasks_pq:
         entry = _heapq.heappop(self._tasks_pq)
         if entry[0] > time_ms:
             # Entry delay condition not met. Put back on queue and wait until next refresh cycle.
             _heapq.heappush(self._tasks_pq, entry)
             return
         task = entry[1]
         task()
Пример #17
0
def heapsort(iterable):
    h = []
    result = []
    # 모든 원소를 차례대로 힙에 삽입
    for value in iterable:
        _heapq.heappush(h, value)
    # 힙에 삽입된 모든 원소를 차례대로 꺼내어 담기
    for i in range(len(h)):
        result.append(_heapq.heappop(h))
    return result
Пример #18
0
def solution(v, k, l):
    # 방문 배열 만들어주고
    # visted = [0] * (v + 1)
    # 출발 노드 방문 처리

    # 최솟값 배열
    minArray = [int(1e9)] * (v + 1)
    minArray[k] = 0

    # 경로값 만들어 주고
    # route = [[int(1e9) for _ in range(v + 1)] for _ in range(v + 1)]
    graph = [[] for _ in range(v + 1)]

    # 경로 바꿔 주기 -> 양쪽 모든 간선을 연결 해줘야 한다
    for element in l:
        # route[element[0]][element[1]] = element[2]
        # route[element[1]][element[0]] = element[2]
        graph[element[0]].append((element[1], element[2]))
        # graph[element[1]].append((element[0], element[2])) // 단방향 그래프 ?

        q = []
        # 최소힙 사용 시간복잡도 줄이기
        # 힙푸시를 이용하기 0 = k로 가는 최소값
        _heapq.heappush(q, (0, k))

        # 큐가 있을때
    while q:
        # dist = 비용 , now = 현재 노드
        # 최단거리의 노드 끄내기, heapop 은 가장 작은 값이 출력된다. 비용이
        dist, now = _heapq.heappop(q)
        # 방문된 노드라 라면 무시하기-> 이미 처리가 끝났슴
        # if visted[now] == 1:
        #     continue
        # 방문처리
        # visted[now] = 1

        # 지금 볼려는 곳이, 들어온 경로 보다 작으면 굳이 비교 할 필요가 없음,
        if minArray[now] < dist:
            continue

        # 현재 노드의 비용들을 돌아보면서
        for cost in graph[now]:
            # 새로운 비용은 현재 거리랑, 최소 경로를 더해 주는데
            newCost = dist + cost[1]
            # newCost = route[now][cost] + dist
            # 현재 노드를 거쳐서, 다른 노드로 이동하는 거리가 더 짧은 경우
            if newCost < minArray[cost[0]]:
                minArray[cost[0]] = newCost
                _heapq.heappush(q, (newCost, cost[0]))

    # print(l)
    # print(route)
    # print(minArray)

    return minArray
 def Execute(self):
     #print('{0} FIRED AT {1}'.format(self.neurone.CanonicalName, time))
     
     # The floating point value of the data sent with the event is a current time 
     _time         = float(self.eventPort.EventData)
     delayed_time = 0.0
     for (synapse, event_port_index, delay, target_neurone) in self.neurone.target_synapses:
         inlet_event_port = synapse.getInletEventPort(event_port_index)
         delayed_time = _time + delay
         #print('    {0} should be triggered at {1}'.format(target_neurone.Name, delayed_time))
         heappush(self.neurone.events_heap, (delayed_time, inlet_event_port, target_neurone))
Пример #20
0
def sample(data_path, k=10000):
    level1_senses = ["Comparison", "Contingency", "Expansion", "Temporal"]

    for level1_sense in level1_senses:

        print("for %s ..." % level1_sense)

        with open("%s/%s/train/arg1.tok.full" % (data_path, level1_sense)) as fin_arg1, \
             open("%s/%s/train/arg2.tok.full" % (data_path, level1_sense)) as fin_arg2, \
             open("%s/%s/train/label.full" % (data_path, level1_sense)) as fin_label, \
             open("%s/%s/train/sense.full" % (data_path, level1_sense)) as fin_sense, \
             open("%s/%s/train/arg1.tok.%d" % (data_path, level1_sense, k), "w") as fout_arg1, \
             open("%s/%s/train/arg2.tok.%d" % (data_path, level1_sense, k), "w") as fout_arg2, \
             open("%s/%s/train/label.%d" % (data_path, level1_sense, k), "w") as fout_label, \
             open("%s/%s/train/sense.%d" % (data_path, level1_sense, k), "w") as fout_sense:

            H = []
            for arg1, arg2, label, sense in zip(fin_arg1, fin_arg2, fin_label,
                                                fin_sense):
                x = (arg1.strip(), arg2.strip(), label.strip(), sense.strip())
                r = random.random()
                if len(H) < k:
                    heappush(H, (r, x))
                elif r > H[0][0]:
                    heapreplace(H, (r, x))

            for (r, x) in H:
                # by negating the id, the reducer receives the elements from highest to lowest
                arg1, arg2, label, sense = x
                fout_arg1.write("%s\n" % arg1)
                fout_arg2.write("%s\n" % arg2)
                fout_label.write("%s\n" % label)
                fout_sense.write("%s\n" % sense)

            # arg1
            cmd = "cd %s ; rm arg1.tok; ln -s arg1.tok.%d arg1.tok; cd -" % (
                "%s/%s/train" % (data_path, level1_sense), k)
            os.system(cmd)

            # arg2
            cmd = "cd %s ; rm arg2.tok; ln -s arg2.tok.%d arg2.tok; cd -" % (
                "%s/%s/train" % (data_path, level1_sense), k)
            os.system(cmd)

            # label
            cmd = "cd %s ; rm label; ln -s label.%d label; cd -" % (
                "%s/%s/train" % (data_path, level1_sense), k)
            os.system(cmd)

            # sense
            cmd = "cd %s ; rm sense; ln -s sense.%d sense; cd -" % (
                "%s/%s/train" % (data_path, level1_sense), k)
            os.system(cmd)
 def run(self):
     # First create the reporting times list
     reporting_times = numpy.arange(self.reportingInterval, self.timeHorizon, self.reportingInterval)
     
     prev_time = 0.0
     # Iterate over the queue. The (delayed) events will be added to the queue as they are trigerred.
     for next_time in reporting_times:
         self.log.Message("Simulating from {0:.5f}s to {1:.5f}s...".format(prev_time, next_time), 0)
         
         try:
             while True:
                 # Get the first item from the heap
                 (t_event, inlet_event_port, target_neurone) = heappop(self.events_heap)
                 
                 # If out of the interval put it back
                 if t_event > next_time:
                     heappush(self.events_heap, (t_event, inlet_event_port, target_neurone))
                     break
                 
                 #print('{0} --> {1}s (trigger event on {2})'.format(target_neurone.Name, t_event, inlet_event_port.CanonicalName))
                 
                 # Integrate until next event time and report the data if there is a discontinuity
                 target_neurone.simulation.IntegrateUntilTime(t_event, pyActivity.eDoNotStopAtDiscontinuity, True)
                 
                 # Trigger the event and reinitialize the system
                 inlet_event_port.ReceiveEvent(t_event)
                 target_neurone.simulation.Reinitialize()
                 
                 self.spike_count += 1
         
         except IndexError:
             pass
             
         # Integrate each neurone until the *next_time* is reached and report the data
         for simulation in self.simulations:
             #print('{0}........ {1} {2} {3}'.format(simulation.m.Name, 
             #                                       simulation.CurrentTime, 
             #                                       '<' if simulation.CurrentTime < next_time else '=' , 
             #                                       next_time))
             if simulation.CurrentTime < next_time:
                 simulation.IntegrateUntilTime(next_time, pyActivity.eDoNotStopAtDiscontinuity, True)
             simulation.ReportData(next_time)
         
         # Set the progress
         self.log.SetProgress(100.0 * next_time / self.timeHorizon)
         prev_time = next_time
                 
     print('Simulation has ended successfuly.')
     print('Processing the results...')
     
     # Finally, process the results (generate 2D plots, raster plots, and other voodoo-mojo stuff)
     self.processResults()
Пример #22
0
    def _dictionary(self, dictfile, docfreq, k):
        """
            This function reads the file which contains the token list and
            their frequency in the entire training corpus. Then it selects the
            top k tokens and generates the dictionary.
            
            Parameters
            -----------
            dictfile: string
                path of file containing the tokens in training corpus and their 
                frequencies.
            docfreq: string
                path of the file containing the term-document frequencies. This is
                needed to the tf-idf calculations.
            k: int
                dictionary size
            
            Note
            -----
            this method creates an private variable self._vocab which 
            contains the frequent tokens and an unique id associated with them
            and self._idf which stores the term frequency of each token in self._vocab
        """
        
        temp_vocab = []
        

        data = pickle.load(open(dictfile, "r"))
        df = pickle.load(open(docfreq,"r"))
        for line in data.keys():
            # if the size of heap is smaller than k then add element
            if len(temp_vocab) <= k:
                heappush(temp_vocab, (int(data[line]), line))
            else:
            #if the size of heap is greater than k then replace smallest element
                heapreplace(temp_vocab, (int(data[line]), line))
                
        heappop(temp_vocab)  # remove the extra element
        
        self._vocab = dict()
        itr = 0
        self._idf = list()
        
        for term in list(temp_vocab):
            #convert heap into dictionary keyed on the token and value is token id
            self._vocab[term[1]] = itr
            #store the term-document frequency in case of tfidf calculations
            self._idf.append(df[term[1]])
            itr += 1
        self._idf = np.array(self._idf,dtype="float")
        self._idf = self._idf/1255353 #total number of documents is 1255353
        self._idf = np.log(self._idf)
    def Execute(self):
        #print('{0} FIRED AT {1}'.format(self.neurone.CanonicalName, time))

        # The floating point value of the data sent with the event is a current time
        _time = float(self.eventPort.EventData)
        delayed_time = 0.0
        for (synapse, event_port_index, delay,
             target_neurone) in self.neurone.target_synapses:
            inlet_event_port = synapse.getInletEventPort(event_port_index)
            delayed_time = _time + delay
            #print('    {0} should be triggered at {1}'.format(target_neurone.Name, delayed_time))
            heappush(self.neurone.events_heap,
                     (delayed_time, inlet_event_port, target_neurone))
 def scheduleCourse2(self, courses):
     """
     :type courses: List[List[int]]
     :rtype: int
     """
     heap, curTime, res = [], 0, 0
     courses.sort(key=lambda c: c[1])
     for k, v in enumerate(courses):
         curTime += v[0]
         heappush(heap, -v[0])
         if curTime > v[1] and heap:  # bugfixed need to check if heap is empty or not
             item = heappop(heap)
             curTime += item
     return len(heap)
Пример #25
0
 def add_task(self,
              callback,
              period=0.0,
              delay=0.0,
              duration=None,
              callback_args=()):
     task = PeriodicTask(callback, period, delay, callback_args)
     self._poller.register(task)
     if duration:
         expire = gettime() + duration + delay
         heappush(self._expireq, (expire, task))
         self._duration_timer.settime(self._expireq[0][0],
                                      0.0,
                                      absolute=True)
Пример #26
0
    def leastInterval(self, tasks, n):
        """
        :type tasks: List[str]
        :type n: int
        :rtype: int
        """
        heap, m = [], collections.defaultdict(int)
        for t in tasks:
            # got the frequency of the element, we could use `Counter` instead, more concise
            m[t] += 1

        res = 0
        for k, v in m.iteritems():
            heappush(heap, [-v, k])

        while heap:
            temp = []
            # Example 1:
            # Input: tasks = ["A","A","A","B","B","B"], n = 2
            # Output: 8
            # Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
            # for this test case, n+1 = 3, len(heap) = 2, interval might > or < the task #
            l = min(n + 1, len(heap))
            for i in xrange(l):
                # greedy, we firstly pick the most frequent element
                item = heappop(heap)
                # after choose one task, reduce the freq by 1, remember the freq is < 0
                item[0] = item[0] + 1
                if item[0] <= 0:
                    temp.append(item)

            # if all tasks are already finshed( heap is empty)
            if not temp:
                break
            # how many tasks been put in temp, let's say [[A,0], [B,0]]
            res += len(temp)
            # for [[A,0], [B,0]], means we have already finised all tasks
            # also, it is possible have [[A,2], [B,0]..] if A task more than B
            # but no matter what, the front one would always be the most frequent task, if it becomes 0
            # means no more task any more
            # but if we have [[A,1], [B,1]], n = 2, means we need an idle there, A, B, idle, so we need
            # n+1 - len(temp)
            if temp[0][0] != 0:
                res += max(0, n + 1 - len(temp))
            # we need to push it back ,even for [A,0], [B,0] , then at next for loop, it would become +1
            # and it would go to `if not temp: break`.
            for t in temp:
                heappush(heap, t)

        return res
Пример #27
0
def watershed(image, markers, connectivity=8, mask=None):
    """Return a matrix labeled using the watershed algorithm
    
    image - a two-dimensional matrix where the lowest value points are
            labeled first.
    markers - a two-dimensional matrix marking the basins with the values
              to be assigned in the label matrix. Zero means not a marker.
    connectivity - either 4 for four-connected or 8 (default) for eight-
                   connected
    mask    - don't label points in the mask
    """
    if connectivity not in (4, 8):
        raise ValueError(
            "Connectivity was %d: it should be either four or eight" %
            (connectivity))

    image = numpy.array(image)
    markers = numpy.array(markers)
    labels = markers.copy()
    max_x = markers.shape[0]
    max_y = markers.shape[1]
    if connectivity == 4:
        connect_increments = ((1, 0), (0, 1), (-1, 0), (0, -1))
    else:
        connect_increments = ((1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0),
                              (-1, -1), (0, -1), (1, -1))
    pq, age = __heapify_markers(markers, image)
    #
    # The second step pops a value off of the queue, then labels and pushes
    # the neighbors
    #
    while len(pq):
        pix_value, pix_age, ignore, pix_x, pix_y = heappop(pq)
        pix_label = labels[pix_x, pix_y]
        for xi, yi in connect_increments:
            x = pix_x + xi
            y = pix_y + yi
            if x < 0 or y < 0 or x >= max_x or y >= max_y:
                continue
            if labels[x, y]:
                continue
            if mask != None and not mask[x, y]:
                continue
            # label the pixel
            labels[x, y] = pix_label
            # put the pixel onto the queue
            heappush(pq, (image[x, y], age, 0, x, y))
            age += 1
    return labels
 def ScheduleTask(self, task, delay=0):
     time_ms = time.monotonic() * 1000
     # Assumption is that there are no ties. Otherwise, comparing last element of the tuple will lead to crashes.
     entry = (
         time_ms + delay,
         len(self._tasks_pq),
         # Add some random numbers so that one of these will break the tie
         int(self._random.random() * 16777215),
         int(self._random.random() * 16777215),
         int(self._random.random() * 16777215),
         int(self._random.random() * 16777215),
         int(self._random.random() * 16777215),
         task)
     _heapq.heappush(self._tasks_pq, entry)
     return entry
Пример #29
0
def solution(scoville, k):
    answer = 0

    h = []

    for i in scoville:
        _heapq.heappush(h, i)
    print(3**2)
    while h[0] < k:
        try:
            _heapq.heappush(h, _heapq.heappop(h) + (_heapq.heappop(h) * 2))

        except Exception:
            return -1
        answer += 1
    return answer
Пример #30
0
def watershed(image, markers, connectivity=8, mask=None):
    """Return a matrix labeled using the watershed algorithm
    
    image - a two-dimensional matrix where the lowest value points are
            labeled first.
    markers - a two-dimensional matrix marking the basins with the values
              to be assigned in the label matrix. Zero means not a marker.
    connectivity - either 4 for four-connected or 8 (default) for eight-
                   connected
    mask    - don't label points in the mask
    """
    if connectivity not in (4,8):
        raise ValueError("Connectivity was %d: it should be either four or eight"%(connectivity))
    
    image = numpy.array(image)
    markers = numpy.array(markers)
    labels = markers.copy()
    max_x  = markers.shape[0]
    max_y  = markers.shape[1]
    if connectivity == 4:
        connect_increments = ((1,0),(0,1),(-1,0),(0,-1))
    else:
        connect_increments = ((1,0),(1,1),(0,1),(-1,1),
                              (-1,0),(-1,-1),(0,-1),(1,-1))
    pq,age = __heapify_markers(markers,image)
    #
    # The second step pops a value off of the queue, then labels and pushes
    # the neighbors
    #
    while len(pq):
        pix_value, pix_age, ignore,pix_x,pix_y = heappop(pq)
        pix_label = labels[pix_x,pix_y]
        for xi,yi in connect_increments:
            x = pix_x+xi
            y = pix_y+yi
            if x < 0 or y < 0 or x >= max_x or y >= max_y:
                continue
            if labels[x,y]:
                continue
            if mask != None and not mask[x,y]:
                continue
            # label the pixel
            labels[x,y] = pix_label
            # put the pixel onto the queue
            heappush(pq, (image[x,y],age,0,x,y))
            age += 1
    return labels
Пример #31
0
	def __init__(self, g,vo,vd,heuristica = None): 
		super(Dijkstra, self).__init__(g,vo,vd,heuristica = None)
		heap = []
		heappush(heap,(0,vo))

		while heap and not g.get_V(vd).fue_visitado():
			verticeVisitado = heapq.heappop(heap)
			g.get_V(verticeVisitado[1]).visitar()
			verticesAdyacentes = g.adj(verticeVisitado[1])
			
			for vertice in verticesAdyacentes:
				pesoDelVisitadoAlVertice = g.get_A(verticeVisitado[1], vertice.get_id()).get_weight()
				if ( not vertice.fue_visitado() ) and ( vertice.get_distancia() > pesoDelVisitadoAlVertice):
					vertice.set_distancia(pesoDelVisitadoAlVertice)
					vertice.set_padre(verticeVisitado[1])
					heappush(heap,(pesoDelVisitadoAlVertice,vertice.get_id()))
		self.armarResultado(vd)
Пример #32
0
def prim(G, start_node):

    print("Running Prim's Algorithm")
    print("Starting Node: " + str(start_node))
    T = set()
    U = set()
    P = []

    vertices1 = []
    vertices2 = []
    vertices_list = []

    U.add(start_node)
    start = G[start_node]

    with open(filename, 'r') as textfile:
        firstLine = int(textfile.readline())
        for line in textfile:
            vertices1.append(line.split(None, 1)[0])
            vertices2.append(line.split(None, 2)[1])

    for elem in range(firstLine):
        if elem not in vertices1:
            vertices_list.append(elem)

    _heapq.heappush(P, vertices_list)

    while len(U) != len(G):
        weight_of_every = []
        for elem in range(len(G)):
            for node in U:
                if elem not in U and (G[node][elem]):
                    weight_of_every.append((node, elem))

        sortedWeights = sorted(
            weight_of_every,
            key=lambda common_weight: G[common_weight[1]][common_weight[0]])
        print("Added " + str(sortedWeights[0][1]))
        weight = (G[sortedWeights[0][0]][sortedWeights[0][1]])
        T.add(weight)
        T.add(sortedWeights[0])
        U.add(sortedWeights[0][1])
        edges = list((sortedWeights[0]))
        edges.sort()
        edges.append(weight)
        print("Using Edge " + str(edges))
Пример #33
0
def dijkstra(start):
    q = []
    # 시작 노드로 가기 위한 최단 거리는 0으로 설정하여, 큐에 삽입
    _heapq.heappush(q, (0, start))
    distance[start] = 0
    while q:  # 큐가 비어있지 않다면
        # 가장 최단 거리가 짧은 노드에 대한 정보를 꺼내기
        dist, now = _heapq.heappop(q)
        if distance[now] < dist:
            continue
        # 현재 노드와 연결된 다른 인접한 노드들을 확인
        for i in graph[now]:
            cost = dist + i[1]
            # 현재 노드를 거쳐서, 다른 노드로 이동하는 거리가 더 짧은 경우
            if cost < distance[i[0]]:
                distance[i[0]] = cost
                _heapq.heappush(q, (cost, i[0]))
Пример #34
0
def fa_cardio_scatter_plot(path):
    data_set = 'cardio'
    x_train, y_train = load_data(path + 'data/' + data_set + '/train/')

    pca = TruncatedSVD(n_components=5)
    pca_x_train = pca.fit_transform(x_train)

    kmeans = KMeans(n_clusters=10, random_state=0).fit(pca_x_train)
    print(kmeans.labels_)
    p = kmeans.predict(pca_x_train)

    for i in range(15):
        print(str(i) + " " + str(len(p[p == i])))

    h = []
    for i in range(15):
        heappush(h, (-1 * len(p[p == i]), i))
        print(str(i) + " " + str(len(p[p == i])))

    index = heappop(h)[1]
    plt.scatter(pca_x_train[:, 0][p == index].ravel(),
                pca_x_train[:, 1][p == index].ravel(),
                alpha=.1,
                color='red')
    index = heappop(h)[1]
    plt.scatter(pca_x_train[:, 0][p == index].ravel(),
                pca_x_train[:, 1][p == index].ravel(),
                alpha=.1,
                color='orange')
    index = heappop(h)[1]
    plt.scatter(pca_x_train[:, 0][p == index].ravel(),
                pca_x_train[:, 1][p == index].ravel(),
                alpha=.1,
                color='blue')
    index = heappop(h)[1]
    plt.scatter(pca_x_train[:, 0][p == index].ravel(),
                pca_x_train[:, 1][p == index].ravel(),
                alpha=.1,
                color='red')

    plt.xlabel('SVD Component 1')
    plt.ylabel('SVD Component 2')
    plt.title('Cardiovascular Data Representation after SVD')
    # plt.show()
    plt.savefig("plots/svd_cardio.png")
Пример #35
0
    def findMinArrowShots(self, points: List[List[int]]) -> int:
        if not points: return 0

        points.sort()

        # minimum r at top
        minr = [points[0][1]]
        arrows = 1
        heapify(minr)

        for l, r in points[1:]:
            if minr and l <= minr[0]:
                heappush(minr, r)
            else:
                minr.clear()
                arrows += 1
                heappush(minr, r)
        return arrows
def grp_cardio_scatter_plot(path):
    data_set = 'cardio'
    x_train, y_train = load_data(path + 'data/' + data_set + '/train/')

    grp = GaussianRandomProjection(n_components=3)
    grp_x_train = grp.fit_transform(x_train)

    kmeans = KMeans(n_clusters=10, random_state=0).fit(grp_x_train)
    print(kmeans.labels_)
    p = kmeans.predict(grp_x_train)

    p = kmeans.predict(grp_x_train)

    h = []
    for i in range(15):
        heappush(h, (-1 * len(p[p == i]), i))
        print(str(i) + " " + str(len(p[p == i])))

    index = heappop(h)[1]
    plt.scatter(grp_x_train[:, 0][p == index].ravel(),
                grp_x_train[:, 1][p == index].ravel(),
                alpha=.1,
                color='yellow')
    index = heappop(h)[1]
    plt.scatter(grp_x_train[:, 0][p == index].ravel(),
                grp_x_train[:, 1][p == index].ravel(),
                alpha=.1,
                color='orange')
    index = heappop(h)[1]
    plt.scatter(grp_x_train[:, 0][p == index].ravel(),
                grp_x_train[:, 1][p == index].ravel(),
                alpha=.1,
                color='blue')
    index = heappop(h)[1]
    plt.scatter(grp_x_train[:, 0][p == index].ravel(),
                grp_x_train[:, 1][p == index].ravel(),
                alpha=.1,
                color='red')
    plt.xlabel('GRP Component 1')
    plt.ylabel('GRP Component 2')
    plt.title('Cardiovascular Data Representation after GRP')
    plt.savefig("plots/grp_cardio.png")

    print()
def greedyPath(points, start):
    gPath = []  # greedy path
    dist = []   # distance heap
    curr = start
    gPath.append(curr)  # start path with start point
    
    while points:   # while there are points left
        for i, point in enumerate(points):  # get distances from current point to all other points
            heappush(dist, (distance(curr, point), i, point))   # 3-tuple [distance, point index, point coordinates]
            
        nearest = heappop(dist)    # get nearest point
        dist = []   # clear heap
        del points[nearest[1]]    # remove point from points
        curr = nearest[2]  # update current point
        gPath.append(curr)   # append point to greedyPath
    
    gPath.append(start) # return to start
    
    return gPath
Пример #38
0
 def insert_num(self, num):
     """这里面记住最小值在0位"""
     if not self.left or num <= -self.left[0]:
         _heapq.heappush(self.left, -num)
     else:
         _heapq.heappush(self.right, num)
     if len(self.left) > len(self.right) + 1:
         tmp = -_heapq.heappop(self.left)
         _heapq.heappush(self.right, tmp)
     elif len(self.right) > len(self.left) + 1:
         tmp = -_heapq.heappop(self.right)
         _heapq.heappush(self.left, tmp)
Пример #39
0
    def check_candidates(self):
        cand_queue = []
        for core in self._cores:
            cand = core.get_soonest_event()
            if cand is not None:
                heappush(cand_queue, cand)
        
#         print 'candidates: ', [event.time for event in cand_queue]
        
        soonest_candidate = None
        if len(cand_queue) > 0:
            soonest_candidate = cand_queue[0] 
        
        soonest_event = None
        if len(self._queue) > 0:
            soonest_event = self._queue[0]
            
        if soonest_candidate is not None and soonest_event is not None and soonest_candidate < soonest_event:
            self.put(soonest_candidate)
Пример #40
0
    def start(self, script):
        self.inicio = Nodo(script)
        self.final = Nodo()
        lista_abierta = []
        lista_cerrada = {}
        
        heappush(lista_abierta, self.inicio)

        while(lista_abierta):

            nodo_actual = heappop(lista_abierta)
            while(nodo_actual.g > len(script)):
                nodo_actual = heappop(lista_abierta)

            if(nodo_actual == self.final):
                print "Solucion Encontrada"
                self.lista_cerrada = lista_cerrada
                print 'Estados recorridos: '+str(len(lista_cerrada))
                print 'Estados a visitar: '+str(len(lista_abierta))
                print 'g: '+str(nodo_actual.g)
                print 'h: '+str(nodo_actual.h)
                return self.devolverRuta(nodo_actual)
            
            lista_cerrada[nodo_actual] = 'eliminado'
            
            for y in nodo_actual.gethijos():
                if(not y in lista_cerrada):
                    
                    if(y.g <= len(script)):
                        a = self.seek(lista_abierta,y)
                        if (a == None):
                            heappush(lista_abierta,y)
                        elif(nodo_actual.g + 1 < y.g):
                            a.g = y.g
                            a.h = y.h
                            a.f = y.f
                            a.padre = y.padre
                            a.script = y.script
                            heapify(lista_abierta)
        return "Ha ocurrido un Error"
Пример #41
0
 def getPotentialFriends(self,userid,count):
     '''
     used a min heap to get the top 'count' potential friends of a user.
     space complexity of min heap is O(count)
     insert into heap q and delete takes log(count) time
     printing the list in reverse order to get users with maximum count: complexity O(n)
     Overall runtime complexity is O(n)
     '''
     if userid not in self.friendmap:
         print "User does not exist"
         return  None
     minh = []
     potentialfriends = [] 
     for key,value in self.friendmap.iteritems():
         if  userid != key:
             if not self.areFriend(userid, key):
                 c = self.getMutualFriendCount(userid,key)
                 if len(minh) >= count:
                     heappop(minh)
                 heappush(minh,(c,key))
     
     for friend in minh[::-1]:
         potentialfriends.append(friend[1])   
     return potentialfriends         
def find_shortest_path(G, v):
    dist_so_far = {v: [0,[v]]}
    final_dist = {}
    heap=[]
    heappush(heap,(0,v))
    while len(final_dist) < len(G) and len(heap) :
        value,w = heappop(heap)
        if w not in final_dist:
            final_dist[w] = dist_so_far[w]
            del dist_so_far[w]
            for x in G[w]:
                if x not in final_dist:
                    path_len = G[w][x]
                    if x not in dist_so_far:
                        dist_so_far[x] = []
                        dist_so_far[x].append(final_dist[w][0] + path_len)
                        dist_so_far[x].append(final_dist[w][1] + [x])
                        heappush(heap,(final_dist[w][0] + path_len, x))
                    elif final_dist[w][0] + path_len < dist_so_far[x][0]:
                        dist_so_far[x][0] = final_dist[w][0] + path_len
                        dist_so_far[x][1] = final_dist[w][1] + [x]
                        heappush(heap,(final_dist[w][0] + path_len, x))
    return final_dist
Пример #43
0
 def append(self, item):
     if self.order == max:
         # If order is max, negate the score
         heappush(self.A, (-self.f(item), item))
     else:    
         heappush(self.A, (self.f(item), item))
Пример #44
0
# -*- coding: Latin-1 -*-

"""Heap queue algorithm (a.k.a. priority queue).

Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
all k, counting elements from 0.  For the sake of comparison,
non-existing elements are considered to be infinite.  The interesting
property of a heap is that a[0] is always its smallest element.

Usage:

heap = []            # creates an empty heap
heappush(heap, item) # pushes a new item on the heap
item = heappop(heap) # pops the smallest item from the heap
item = heap[0]       # smallest item on the heap without popping it
heapify(x)           # transforms list into a heap, in-place, in linear time
item = heapreplace(heap, item) # pops and returns smallest item, and adds
                               # new item; the heap size is unchanged

Our API differs from textbook heap algorithms as follows:

- We use 0-based indexing.  This makes the relationship between the
  index for a node and the indexes for its children slightly less
  obvious, but is more suitable since Python uses 0-based indexing.

- Our heappop() method returns the smallest item, not the largest.

These two make it possible to view the heap as a regular Python list
without surprises: heap[0] is the smallest item, and heap.sort()
maintains the heap invariant!
"""
Пример #45
0
def push_node(data_structure, node, heap=False):
    if heap:
        heappush(data_structure, node)
    else:
        data_structure.append(node)
Пример #46
0
# -*- coding: Latin-1 -*-

"""Heap queue algorithm (a.k.a. priority queue).

Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
all k, counting elements from 0.  For the sake of comparison,
non-existing elements are considered to be infinite.  The interesting
property of a heap is that a[0] is always its smallest element.

Usage:

heap = []            # creates an empty heap
heappush(heap, item) # pushes a new item on the heap
item = heappop(heap) # pops the smallest item from the heap
item = heap[0]       # smallest item on the heap without popping it
heapify(x)           # transforms list into a heap, in-place, in linear time
item = heapreplace(heap, item) # pops and returns smallest item, and adds
                               # new item; the heap size is unchanged

Our API differs from textbook heap algorithms as follows:

- We use 0-based indexing.  This makes the relationship between the
  index for a node and the indexes for its children slightly less
  obvious, but is more suitable since Python uses 0-based indexing.

- Our heappop() method returns the smallest item, not the largest.

These two make it possible to view the heap as a regular Python list
without surprises: heap[0] is the smallest item, and heap.sort()
maintains the heap invariant!
"""
Пример #47
0
@author: Rahul
'''
import heapq
from _heapq import heappush, heappop
if __name__ == '__main__':
    x = [1,0,3,5,2,0,1]
    
    minh = []
    maxh = []
    maxe = 0
    equal = 0
    for e in x:
        
        if equal == 0:
            heappush(minh,e)
            mine = heappop(minh)
            heappush(minh,mine)
            print mine 
            equal = 1
        else:
            heappush(minh,e)
            temp = heappop(minh)
            heappush(maxh,-temp)
            mine = heappop(minh)
            heappush(minh,mine)
            maxe = -1 * heappop(maxh)
            heappush(maxh,-maxe)
            median = float(maxe + mine) / 2
            equal = 0
            print median
Пример #48
0
def _slow_watershed(image, markers, connectivity=8, mask=None):
    """Return a matrix labeled using the watershed algorithm

    Use the `watershed` function for a faster execution.
    This pure Python function is solely for pedagogical purposes.

    Parameters
    ----------
    image: 2-d ndarray of integers
        a two-dimensional matrix where the lowest value points are
        labeled first.
    markers: 2-d ndarray of integers
        a two-dimensional matrix marking the basins with the values
        to be assigned in the label matrix. Zero means not a marker.
    connectivity: {4, 8}, optional
        either 4 for four-connected or 8 (default) for eight-connected
    mask: 2-d ndarray of bools, optional
        don't label points in the mask

    Returns
    -------
    out: ndarray
        A labeled matrix of the same type and shape as markers


    Notes
    -----
    This function implements a watershed algorithm [1]_that apportions pixels
    into marked basins. The algorithm uses a priority queue to hold the pixels
    with the metric for the priority queue being pixel value, then the time of
    entry into the queue - this settles ties in favor of the closest marker.

    Some ideas taken from
    Soille, "Automated Basin Delineation from Digital Elevation Models Using
    Mathematical Morphology", Signal Processing 20 (1990) 171-182

    The most important insight in the paper is that entry time onto the queue
    solves two problems: a pixel should be assigned to the neighbor with the
    largest gradient or, if there is no gradient, pixels on a plateau should
    be split between markers on opposite sides.

    This implementation converts all arguments to specific, lowest common
    denominator types, then passes these to a C algorithm.

    Markers can be determined manually, or automatically using for example
    the local minima of the gradient of the image, or the local maxima of the
    distance function to the background for separating overlapping objects.
    """
    if connectivity not in (4, 8):
        raise ValueError("Connectivity was %d: it should be either \
        four or eight" % (connectivity))

    image = np.array(image)
    markers = np.array(markers)
    labels = markers.copy()
    max_x = markers.shape[0]
    max_y = markers.shape[1]
    if connectivity == 4:
        connect_increments = ((1, 0), (0, 1), (-1, 0), (0, -1))
    else:
        connect_increments = ((1, 0), (1, 1), (0, 1), (-1, 1),
                              (-1, 0), (-1, -1), (0, -1), (1, -1))
    pq, age = __heapify_markers(markers, image)
    pq = pq.tolist()
    #
    # The second step pops a value off of the queue, then labels and pushes
    # the neighbors
    #
    while len(pq):
        pix_value, pix_age, ignore, pix_x, pix_y = heappop(pq)
        pix_label = labels[pix_x, pix_y]
        for xi, yi in connect_increments:
            x = pix_x + xi
            y = pix_y + yi
            if x < 0 or y < 0 or x >= max_x or y >= max_y:
                continue
            if labels[x, y]:
                continue
            if mask is not None and not mask[x, y]:
                continue
            # label the pixel
            labels[x, y] = pix_label
            # put the pixel onto the queue
            heappush(pq, [image[x, y], age, 0, x, y])
            age += 1
    return labels
Пример #49
0
 def _add_timeout(self, item):
     heapq.heappush(self._timeouts, (item.expiration, item))
Пример #50
0
#双端队列
s = "yeah but no but yeah but no but yeah"
words = s.split()
wordlocations = defaultdict(list)
for n, w in enumerate(words) : 
    wordlocations[w].append(n)
print  wordlocations  

#堆
heap = range(1, 100)
shuffle(heap)
heapq.heapify(heap) 
print heap
print heappop(heap)
heappush(heap, 101)
heapreplace(heap, 102)
print heap

#itertools
for i in chain(range(1, 10), range(10, 20)) : 
    print i
    
#3个一组排列组合
for list in combinations(range(1,20), 3) : 
    print list

#从某个数开始,连续生产整数    
for i in count(100) : 
    if i == 200 :
        break
Пример #51
0
 def push(self, key):
     heappush(self.heap, (key, key))
     self.size += 1;
Пример #52
0
 def put(self, event):
     heappush(self._queue, event)