Exemplo n.º 1
0
def main():
  TRAIN_DBS, VAL_DBS, TEST_DBS, TRAIN_N_DBS, VAL_N_DBS, TEST_N_DBS = \
      load_dbs(sys.argv[1], False)
  ret = Retriever(TRAIN_DBS)
  sess = tf.Session()
  cv2.namedWindow("image", cv2.WINDOW_NORMAL)
  cv2.resizeWindow("image", 600, 1200)
  l = 1000
  div = ret.get_length() / l
  pairs = []
  for i in range(l):
    img1, img2 = ret.get_image_pair(i*div + 1, sess)
    #img1, img2 = ret.get_random_pair(sess)
    img2 = np.squeeze(img2.astype(np.uint8))
    img1 = np.squeeze(img1.astype(np.uint8))
    img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2RGB)
    #cv2.cvtColor(img1, cv2.COLOR_RGB2BGR)
    img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
    #cv2.cvtColor(img2, cv2.COLOR_RGB2BGR)

    #cv2.imwrite("image1.png", img1)
    #cv2.imwrite("image2.png", img2)

    ss = np.concatenate((img1, img2), axis=1)
    cv2.imshow("image", ss)
    val = cv2.waitKey(0)
    if val == 27:
      break
  cv2.destroyWindow("image")
  sess.close()
Exemplo n.º 2
0
 def execute(self, html):
     soup = get_soup(html)
     dirs = Retriever.get_accept_dirs(soup, self.link)
     books = Retriever.get_accept_books(soup, self.link)
     self.tasks = [ DirPage( link )  for link,_ in dirs ]
     self.tasks += [ BookPage( link+'_Ascii.txt' ) for link,_ in books ]
     return True
Exemplo n.º 3
0
def calc_image_stats(pos_db, neg_db, samples=None):
    ret = MixedRetriever(Retriever(pos_db), Retriever(neg_db))
    if samples is None:
        count = ret.get_length()
    else:
        count = samples

    ratio = 1. / 2
    sess = tf.Session()
    mean = np.zeros((192, 192, 3))
    std = np.zeros((192, 192, 3))
    k = 1
    n = 200
    # Calc mean
    print("Calculating mean")
    for i in xrange(0, ret.get_length(), ret.get_length() // count):
        r, l, g = ret.get_random_pairs(sess, n / 2, ratio)
        mean = mean * k / (k + n) + (np.sum(r, axis=0) +
                                     np.sum(l, axis=0)) / (k + n)
        k += 1
    #cv2.imshow("mean", mean)
    #cv2.waitKey(0)
    k = 1
    # Calc std
    mean_repeat = np.expand_dims(mean, 0).repeat(n, 0)
    print("Calculating standard deviation")
    for i in xrange(0, ret.get_length(), ret.get_length() // count):
        r, l, g = ret.get_random_pairs(sess, n / 2, ratio)
        arr = np.concatenate((r, l), axis=0)
        a = (np.sum(np.square(arr - mean_repeat), axis=0)) / (k + n)
        std = std * k / (k + n) + a / (k + n)
    #cv2.imshow("std", std)
    #cv2.waitKey(0)

    return mean, std
Exemplo n.º 4
0
 def retrieve(self,text):
     bi = BookInfo()
     bi.authors, bi.title = Retriever.get_authors_and_title(text)
     bi.pagelink = self.link
     bi.links['txt'] = self.link
     tag = Retriever.get_tag_by_link(self.link)
     bi.tags = [tag] if tag else []
     return bi
Exemplo n.º 5
0
 def execute(self, html):
     soup = get_soup(html)
     magazine_info = Retriever.get_magazine_info(soup)
     magazine_info.cover = make_correct_link(self.link, magazine_info.cover)
     magazine_info.link = self.link
     issue_links = [ make_correct_link(self.link, link) for link in Retriever.get_links_magazine_issue(soup) ]
     self.tasks = [ MagazineIssueTask( magazine_info.name, issue_link) for issue_link in issue_links ]
     self.tasks += [ MagazineSavingTask( magazine_info ) ]
     return True
Exemplo n.º 6
0
 def execute(self, html):
     data, page = html
     soup = BeautifulSoup(data,convertEntities=BeautifulSoup.XML_ENTITIES, fromEncoding='utf-8')
     if Retriever.is_acquisition_feed(soup):
         self.tasks = [ Entry(unicode(entry), self.link) for entry in Retriever.get_entries(soup) ]
     else: #navigation feed
         entries = Retriever.get_entries(soup)
         links = filter( lambda l: l!=None, [Retriever.get_catalog_link(entry) for entry in entries] )
         links = filter( Retriever.is_permitted_link, links)
         links = map( lambda link: make_correct_link(self.link, link), links)
         self.tasks = [ Page(link) for link in links]
     return True
Exemplo n.º 7
0
 def execute(self, html):
     soup = get_soup(html)
     year, number = Retriever.get_issue_year_number_by_link(self.link)
     articles = Retriever.get_issue_articles(soup)
     for article in articles:
         article.magazine = self.magazine
         article.year = year
         article.number = number
         article.link = make_correct_link(self.link, article.link)
         article.link = Retriever.print_version(article.link)
     self.tasks = [ArticleSavingTask(article) for article in articles]
     return True
Exemplo n.º 8
0
 def execute(self,html):
     soup = get_soup(html)
     book_info = BookInfo()
     book_info.title  = self.description['title']
     book_info.authors = [ "%s %s %s" % (self.description['firstname'],self.description['middlename'], self.description['lastname']) ]
     book_info.pagelink = self.link
     book_info.language = self.description['language']
     book_info.summary = Retriever.get_summary(soup)
     book_info.links = Retriever.get_links(soup, self.link)
     book_info.tags = Retriever.get_tags(soup)
     book_info.image = Retriever.get_picture(soup, self.link, self.description['ID'])
     self.tasks = [ BookSavingTask(book_info) ]
     return True
Exemplo n.º 9
0
 def execute(self, html):
     soup = get_soup(html)
     genres = Retriever.get_genres(soup)
     for genre in genres:
         genre['link'] = make_correct_link(self.link, genre['link'])
     self.tasks = [ GetAllPagesGenre(g['link'],g['name']) for g in genres ]
     return True
Exemplo n.º 10
0
def generate_snippet(file_name):
    relevant_list = open('cacm.rel', 'r')
    query_relevant = {}
    for line in relevant_list.readlines():
        words = line.split()
        if query_relevant.has_key(words[0]):
            doc_no = words[2][5:]
            doc_no = str(doc_no)
            doc = 'CACM-' + (4 - len(doc_no)) * '0' + doc_no
            query_relevant[words[0]].append(doc)
        else:
            query_relevant[words[0]] = []
            doc_no = words[2][5:]
            doc = 'CACM-' + (4 - len(doc_no)) * '0' + doc_no
            query_relevant[words[0]].append(doc)

    #Get query_dict from the file cacm.query.txt
    f = open('cacm.query.txt', 'r')
    soup = BeautifulSoup(f.read(), 'html.parser')
    f.close()
    rawquery_dict = {}
    for i in range(64):
        query_no = (soup.find('docno')).text.encode('utf-8')
        (soup.find('docno')).decompose()
        query = (soup.find('doc')).text.encode('utf-8')
        (soup.find('doc')).decompose()

        query_no = query_no.strip(" ")
        rawquery_dict[query_no] = query

    r = Retriever("", "")
    query_dict = {}
    for query_no, raw_query in rawquery_dict.viewitems():
        query_dict[query_no] = r.process_query(raw_query, True)

    print "Enter the query no"
    no = raw_input()
    no = str(no)
    query = query_dict[no]
    print query
    s = SnippetGen(file_name)
    query_results = s.get_queryresults(name='bms25')
    results = query_results[no]
    # pdb.set_trace()
    s.get_snippet(query, results)
Exemplo n.º 11
0
    def __init__(self, car):
        self.car = car
        self.rules = [
            ['1', ['signal:RED'], ['acceleration:N']
             ],  # rule base for signal, stop sign and speed limit
            ['2', ['signal:AMBER'], ['acceleration:N']],
            ['3', ['signal:GREEN'], ['acceleration:Y']],
            ['4', ['sign:STOP'], ['acceleration:N']],
            ['5', ['speed:Y'], ['aceleration:Y']],
            ['6', ['speed:N'], ['acceleration:N']]
        ]

        self.evtgen = EventGenerator.EventGenerator(
        )  # creating random event generator object
        self.rt = Retriever(
            'casebasedplan.txt')  # Retriever object for case retrieval
        self.exception_event = ExceptionalEvent()
        self.laneChanged = False
Exemplo n.º 12
0
 def execute(self):
     entry = BeautifulSoup(self.entry,convertEntities=BeautifulSoup.XML_ENTITIES)
     bookinfo = Retriever.get_bookinfo(entry)
     if not bookinfo:
         logger.write_fail("empty links at entry",entry=entry, link=self.link)
         return True
     bookinfo.pagelink = self.link
     for format, link in bookinfo.links.items():
         bookinfo.links[format] = make_correct_link(self.link, bookinfo.links[format] )
     self.tasks = [ BookSavingTask(bookinfo) ]
     return True
Exemplo n.º 13
0
 def __init__(self, car):
     self.car = car
     self.rules = [['1',['signal:RED'],['acceleration:N']],     # rule base for signal, stop sign and speed limit
                   ['2',['signal:AMBER'],['acceleration:N']],
                   ['3',['signal:GREEN'],['acceleration:Y']],
                   ['4',['sign:STOP'],['acceleration:N']],
                   ['5',['speed:Y'],['aceleration:Y']],
                   ['6',['speed:N'],['acceleration:N']]]
     
     self.evtgen = EventGenerator.EventGenerator()    # creating random event generator object
     self.rt = Retriever('casebasedplan.txt')         # Retriever object for case retrieval
     self.exception_event = ExceptionalEvent()
     self.laneChanged = False
Exemplo n.º 14
0
 def execute(self):
     self.tasks = []
     filename = os.path.join(settings.path_to_project, settings.analyser, settings.data, 'catalog.zip')
     zip_file = ZipFile(filename)
     catalog_file = zip_file.open('catalog.txt')
     for i in xrange(self.start_line):
         catalog_file.readline()
     N_IDS = 20 #number of reading ID's
     for n in range(N_IDS):
         description_line = catalog_file.readline()
         if description_line == '':
             break #end of file
         description = Retriever.read_description(description_line)
         self.tasks.append( GetBookInfoTask('http://flibusta.net/b/%s' % description['ID'], description)  )
     if catalog_file.readline() != '':
         self.tasks.append( GetNewId(self.start_line+N_IDS))
     return True
Exemplo n.º 15
0
def load_retrievers(dbtype, viewing=False):
    # INIT DATABASE RETRIEVERS
    TRAIN_DBS, VAL_DBS, TEST_DBS, TRAIN_N_DBS, VAL_N_DBS, TEST_N_DBS = \
              load_dbs(dbtype, viewing)
    train_pos = Retriever(TRAIN_DBS)
    train_neg = Retriever(TRAIN_N_DBS)
    train_ret = MixedRetriever(train_pos, train_neg)

    val_pos = Retriever(VAL_DBS)
    val_neg = Retriever(VAL_N_DBS)
    val_ret = MixedRetriever(val_pos, val_neg)

    test_pos = Retriever(TEST_DBS)
    test_neg = Retriever(TEST_N_DBS)
    test_ret = MixedRetriever(test_pos, test_neg)
    return train_ret, val_ret, test_ret
Exemplo n.º 16
0
 def execute(self,html):
     soup = get_soup(html)
     number = Retriever.get_pages_number(soup)
     pagelinks = Retriever.generate_all_pagelinks_for_genre(self.link, number)
     self.tasks = [ GenrePage(link, self.genre) for link in pagelinks]
     return True
Exemplo n.º 17
0
        dsOut.SetProjection(self.projection)
        '''
        ReprojectImage(Dataset src_ds, Dataset dst_ds, char src_wkt = None, 
        char dst_wkt = None, GDALResampleAlg eResampleAlg = GRA_NearestNeighbour, 
        double WarpMemoryLimit = 0.0, 
        double maxerror = 0.0, GDALProgressFunc callback = None, 
        void callback_data = None) -> CPLErr
        '''
        #gdal.ReprojectImage(self.dataset,self.dataset,self.DEFAULT_PROJ,self.LATLONG_PROJ)
        #subprocess.call(["gdalwarp","-t_srs","+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs","out.tiff","out1.tiff"])
        #subprocess.call("gdalwarp","-t_srs \"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\" out.tiff out1.tiff")
	#err = gdal.ReprojectImage(dsOut,dsOut,self.projection,self.LATLONG_PROJ_WKT)
	err = gdal.ReprojectImage(dsOut,projdsOut,self.projection,self.LATLONG_PROJ_WKT)

        
if __name__ == '__main__':
    from Retriever import Retriever
    retriever = Retriever()
    image_dict = retriever.downloadImages(['ss'])
    for i in image_dict.iterkeys():
        radar = Regional(image_dict[i],i) #(imagepath, region)
        #print "Creado radar regional: " + radar.imagepath + ' Region: ' + radar.region
        radar.printReport()
        #valid_gifindexes = radar.__getValidColors()
        radar.data = radar.swapValues(radar.data)
        radar.dumpToGeoTiff('out.tiff')
        
        
        
        
Exemplo n.º 18
0
 def execute(self, html):
     soup = get_soup(html)
     links_magazines = Retriever.get_links_on_magazines(soup)
     links_magazines = [make_correct_link(self.link, link) for link in links_magazines]
     self.tasks = [ MagazineInfoTask( link ) for link in links_magazines]
     return True
Exemplo n.º 19
0
#Get query_dict from the file cacm.query.txt
f = open('cacm.query.txt','r')
soup = BeautifulSoup(f.read(), 'html.parser')
f.close()
rawquery_dict = {}
for i in range(64):
  query_no = (soup.find('docno')).text.encode('utf-8')
  (soup.find('docno')).decompose()
  query = (soup.find('doc')).text.encode('utf-8')
  (soup.find('doc')).decompose

  query_no = query_no.strip(" ")
  rawquery_dict[query_no] = query

r = Retriever("", "")
query_dict = {}
for query_no, raw_query in rawquery_dict.viewitems():
  query_dict[query_no] = r.process_query(raw_query, True)
 
print "Enter the query no"
no = raw_input()
no = str(no)
query = query_dict[no]
print query
s = SnippetGen()
query_results = s.get_queryresults(name = 'bms25')
results = query_results[no]
# pdb.set_trace()
s.get_snippet(query,results)
Exemplo n.º 20
0
 def execute(self,html):
     soup = get_soup(html)
     book_info = Retriever.correct_book_info( Retriever.get_book_info(soup), self.link)
     self.tasks = [ BookSavingTask(book_info) ]
     return True
Exemplo n.º 21
0
 def execute(self,html):
     soup = get_soup(html)
     links = [make_correct_link(self.link, book_link) for book_link in Retriever.get_book_links(soup) ]
     self.tasks = [ GetBookInfoTask( link) for link in links]
     return True
Exemplo n.º 22
0
 def execute(self,html):
     soup = get_soup(html)
     links = [ self.link ]
     links += Retriever.get_link_pages(soup, self.link)
     self.tasks = [ BookListingTask(link) for link in links ]
     return True
Exemplo n.º 23
0
 def execute(self,html):
     soup = get_soup(html)
     tasks = [ GenreTask( make_correct_link(self.link, glink)) for glink in Retriever.get_genres_links(soup) ]
     self.tasks = tasks
     return True
Exemplo n.º 24
0
 def execute(self,html):
     soup = get_soup(html)
     bookinfos = [ Retriever.postprocess_bookinfo(raw_bookinfo,self.link, self.genre)  \
                   for raw_bookinfo in  Retriever.get_bookinfos(soup)  ]
     self.tasks = [ BookSavingTask(book_info) for book_info in bookinfos ]
     return True
Exemplo n.º 25
0
class EventHandler(object):
    
    g = 127008
    displayCount = -1
    sig_cnt = -1
    speed_limit_flag = False
    
    def __init__(self, car):
        self.car = car
        self.rules = [['1',['signal:RED'],['acceleration:N']],     # rule base for signal, stop sign and speed limit
                      ['2',['signal:AMBER'],['acceleration:N']],
                      ['3',['signal:GREEN'],['acceleration:Y']],
                      ['4',['sign:STOP'],['acceleration:N']],
                      ['5',['speed:Y'],['aceleration:Y']],
                      ['6',['speed:N'],['acceleration:N']]]
        
        self.evtgen = EventGenerator.EventGenerator()    # creating random event generator object
        self.rt = Retriever('casebasedplan.txt')         # Retriever object for case retrieval
        self.exception_event = ExceptionalEvent()
        self.laneChanged = False
        
    # Below method handles the basic driving events 
    def handleEvent(self, event): #all the event handling goes here
        action = ''
        self.speed_limit = self.car.maxSpeed
        
        if event['turn'] != '' and self.car.currentLane == 'M':
            if self.car.distanceCovered >= .65*self.car.laneDist and self.laneChanged == False:  # changes lane after distance covered 
                print("\nAttempting to change lanes...")                                       # crosses the threshold (65% of lane dist)
                self.laneChanged = self.handleLaneChange(event)
        
        if 'signal' in event:        # checking if signal is present at the end of the lane
            signal = event['signal']
            
        if 'sign' in event:           # checking for lane signs (speed limit)
            sign = event['sign']
            if 'speed' in sign:
                self.speed_limit = int(sign[sign.find('~')+1:])
                if self.speed_limit_flag == False:
                    print("\nSpeed Limit Sign in view...Speed Limit: "+str(self.speed_limit))
                self.handleSpeedSign()
        
        excp_event = self.exception_event.giveExceptionalEvent()  # event generator generates exception event
        
        if excp_event != False:
            print("\nExceptional Event in Progress...")
            self.handleExpCase(excp_event)               # method for handling exceptional events
            time.sleep(1)
                   
        
        if signal == True:    # if signal is present at the end of the lane. Either signal or STOP sign at the end of the lane.
            if self.car.remainingDist <= self.getBrakingDist():
                print("\nBraking Distance Reached...Signal in view...")
                self.evtgen.resetSignal()
                time.sleep(2)
                action = self.handleSignalStopSign(1, 'SIGNAL', event)
                return action
        else:                # indicates stop sign is present at the end of the lane. 
            if self.car.remainingDist <= self.getBrakingDist():
                print("\nBraking Distance Reached...STOP sign in view...")
                time.sleep(2)
                action = self.handleSignalStopSign(1, 'STOP', event)
                return action
        
        self.speed_limit = self.car.maxSpeed
        
        if(self.car.speed < self.speed_limit):       # if speed is less than speed limit then accelerate
            self.car.accelerate(1, self.speed_limit)  
        self.car.move()   
                    
        return False
    
    # Below method handles the exceptional events
    def handleExpCase(self, event):
        
        event.speed['me'] = self.car.speed   
        retrievedCase = self.rt.findClosestMatch(event)   # case retrieved from case base
        self.printExcpCase(event,retrievedCase)           # prints the details of the event
        
        result = retrievedCase[1][0]
        action = result[0]
        priority = result[2]
        speed_limit = result[3]
        
        if action == 'decelerate':
            print("Reducing Speed to speed limit of "+str(speed_limit)+"\n")
        else:
            print("Increasing Speed to speed limit of "+str(speed_limit)+"\n") 
        time.sleep(1)        
        
        while True:
            self.displayFullDtls('Y') 
            time.sleep(0.1)
            if action == 'decelerate':
                if self.car.speed > speed_limit:
                    self.car.decelerate(priority, speed_limit)       # decelerate the car
                    self.car.move()
                    if speed_limit == 0 and self.car.speed <= 0.35:  # if the car's speed goes below 0.35 kmph, reduce speed to 0.
                        self.car.speed = 0                    # This is done because the car's speed never reaches 0, only close to 0.
                    
                else:
                    break
            elif action == 'accelerate':
                if self.car.speed < speed_limit:
                    self.car.accelerate(priority, speed_limit)  # accelerate the car
                    self.car.move()
                else:
                    break
               
        print("\nExceptional event concluded...")  
        if self.car.speed <= self.speed_limit:
            temp_str = "increased"
        else:
            temp_str = "decreased"  
                
        if action == 'decelerate':
            print("\nSpeed reduced to "+str(self.car.speed)+". Speed will be "+temp_str+" to speed limit: "+\
                  str(self.speed_limit)+"\n")
        else:
            print("\nSpeed increased to "+str(self.car.speed)+". Speed will be "+temp_str+" to speed limit: "+\
                  str(self.speed_limit)+"\n")     
            
        time.sleep(1)
        
    
    # Below method handles the speed sign       
    def handleSpeedSign(self):
        if self.car.speed <= self.speed_limit:
            if self.speed_limit_flag == False:
                print("Increasing speed to "+str(self.speed_limit)+"\n")
                self.speed_limit_flag = True
            action = self.getAction('speed:' + 'Y')
        else:
            if self.speed_limit_flag == False:
                print("Reducing speed to "+str(self.speed_limit)+"\n")
                self.speed_limit_flag = True
            action = self.getAction('speed:' + 'N')
        self.changeSpeed(1, action, self.speed_limit)

    
    # Below method returns the action based on the rule     
    def getAction(self, event):
        event_value = event[event.find(':')+1:]
        event_type  = event[:event.find(':')]
         
        for rule in self.rules:
            ante = rule[1][0]
            evalue = ante[ante.find(':')+1:]
            etype  = ante[:ante.find(':')]
                
            if etype == event_type and evalue == event_value:  # if event type and event value matches, then return the action 
                result = rule[2][0]
                result_value = result[result.find(':')+1:]
                return result_value              
             
    
    #Below method handles the Signal as well as the Stop sign depending on the event type
    def handleSignalStopSign(self, priority, event_type, event):
        flag = True
        is_last = False
        turn = event['turn']
        
        if turn == 'D':     # checking if this is the last lane i.e. is the destination on this lane
            is_last = True
            
        while 1:
            time.sleep(Car.Car().sleepTime)
            
            if event_type == 'SIGNAL':                      # if event type is Signal
                currentSignal = self.evtgen.probeSignal()   # probe the event value generator for signal value
            
            if self.laneChanged == False:
                self.laneChanged = self.handleLaneChange(event)  # handle lane change if lane not already changed
            
            if event_type == 'SIGNAL':
                self.displayFullDtls('N',currentSignal)
                action = self.getAction('signal:' + currentSignal)
            elif event_type == 'STOP':
                action = self.getAction('sign:' + event_type)    
            
            if action == 'Y':
                speed_limit = self.car.maxSpeed
            else:
                speed_limit = 0
                    
            flag  = self.changeSpeed(priority, action, speed_limit)  #adjust speed based on the action (acceleration/deceleration) 
            
            if flag == False:
                self.car.speed = 0   # car has stopped
                break
            else:
                self.displayFullDtls('N')
                if self.car.distanceCovered >= self.car.laneDist:   # checking if the lane distance has been reached
                    print("\nLane Distance Reached")
                    if is_last == False:
                        return False
                    return True
        
        print("Lane Distance covered: " + str(self.car.distanceCovered*1000)), 
        print(" Speed: " + str(self.car.speed)),
        print(" Remaining Lane Distance: "+str(self.car.remainingDist*1000))
        print("\nCar STOPPED...")
        if is_last == False:
            if event_type == 'SIGNAL':
                print("Waiting for signal to turn GREEN...\n")
            elif event_type == 'STOP':
                print("Waiting to move...\n")
        time.sleep(2)         
        
        if is_last == False:   # not the last lane
            while 1:
                if event_type == 'SIGNAL':
                    signal = self.evtgen.probeSignal()    #probe for signal till "GREEN" is received
                elif event_type == 'STOP':
                    signal = self.evtgen.probeAllClear()  #probe for all clear signal from the value generator
                    
                if signal == 'GREEN':    # if signal is GREEN, accelerate the car and start moving
                    while 1:
                        self.car.accelerate(1, self.speed_limit)
                        self.car.move() 
                        
                        self.displayFullDtls('N')
                        if self.car.distanceCovered >= self.car.laneDist:
                            print("Lane Distance covered: " + str(self.car.distanceCovered*1000)), 
                            print(" Speed: " + str(self.car.speed)),
                            print(" Remaining Lane Distance: "+str(self.car.remainingDist*1000))
                            print("\nLane Distance Reached")
                            time.sleep(2)
                            return False   # Once lane distance is reached, return back to caller
            
        return True            

    # Below method adjusts the speed of the car based on the priority
    def changeSpeed(self, priority, acc_yn, speed_limit):  # acc_yn: 'Y' - Acceleration, 'N' - Deceleration
        if acc_yn == 'N':
            self.car.decelerate(priority, speed_limit)
            self.car.move()
            
            if self.car.speed < 0.35 or self.car.remainingDist <= 0.001: 
                return False          
        else:
            if(self.car.speed < speed_limit):
                self.car.accelerate(1, speed_limit)  
            else:
                self.car.decelerate(1, speed_limit)       
            self.car.move()              
        
        return True     
    
    # braking distance - distance at which the brakes should be applied to stop the car
    def getBrakingDist(self):
        brakingDistance =  self.car.speed*self.car.speed/2/0.7/self.g
        return brakingDistance

    # Below method handles the lane change
    def handleLaneChange(self, event):
        changeLane = ''
        laneChangeRules =  [[{'lane':1,'turn':'L', 'car':'Y'},'notrequired'],   # rules for lane change
                            [{'lane':1, 'turn':'R', 'car':'Y'},'notrequired'],
                            [{'lane':1, 'turn':'L', 'car':'N'},'notrequired'],
                            [{'lane':1, 'turn':'R', 'car':'N'},'notrequired'],
                            [{'lane':2, 'turn':'L', 'car':'Y'},'no'],
                            [{'lane':2,'turn':'R','car':'Y'},'notrequired'],
                            [{'lane':2,'turn':'R','car':'N'},'notrequired'],
                            [{'lane':2,'turn':'L','car':'N'},'yes'],
                            [{'lane':3,'turn':'R','car':'Y'}, 'no'],
                            [{'lane':3,'turn':'L','car':'Y'}, 'no'],
                            [{'lane':3,'turn':'R','car':'N'}, 'yes'],
                            [{'lane':3,'turn':'L','car':'N'}, 'yes']]
        
        turn = event.get('turn')
        lane = event.get('lane')
        car = self.evtgen.checkMirror()  # probe value generator to check if its safe to change the lane
        for rules in laneChangeRules:
            ante = rules[0]
            if turn == ante.get('turn') and lane == ante.get('lane') and car == ante.get('car'):
                changeLane = rules[1]
                break
        
        if changeLane == 'yes':
            print "Lane change successful...\n"
            time.sleep(2)
            return True
        elif changeLane == 'notrequired':
            print "No need to change lanes but turn ahead...\n"
            time.sleep(2)
            return True
        elif changeLane == 'no':
            print "Cannot change lane right now...\n"
            time.sleep(2)
            return False
        
    # Below method displays the full or partial output based on the argument 'full_yn'. Required as output is displayed very often.
    # full_yn = 'Y' is used when the change in speed needs to be displayed when the priority for deceleration is high.  
    def displayFullDtls(self, full_yn, signal_color = ''):
        displayLimit = 20  # counter used to limit the number of display
        signalLimit = 500  # counter used to limit the number of display while probing signal
        
        if signal_color != '':
            self.sig_cnt = self.sig_cnt + 1
            if self.sig_cnt%signalLimit == 0:
                print("Current Signal: "+signal_color+". Reducing the speed of the car...\n")
                
                if self.sig_cnt != 0:
                        self.sig_cnt = -1
                    
        else:
            if full_yn == 'N':
                self.displayCount = self.displayCount + 1
                if self.displayCount%displayLimit == 0:    
                    print("Lane Distance covered: " + str(self.car.distanceCovered*1000)), 
                    print(" Speed: " + str(self.car.speed)),
                    print(" Remaining Lane Distance: "+str(self.car.remainingDist*1000))
                   
                    if self.displayCount != 0:
                        self.displayCount = -1
            else:
                print("Lane Distance covered: " + str(self.car.distanceCovered*1000)), 
                print(" Speed: " + str(self.car.speed)),
                print(" Remaining Lane Distance: "+str(self.car.remainingDist*1000))
    
    # Below method prints the details of the exceptional case - the occurred event and the retrieved case            
    def printExcpCase(self, event, retrievedCase):
        print("Object: "+str(event.target))
        print("Object Distance from Car: "+str(abs(event.distance[event.target])))
        print("Object Speed: "+str(event.speed[event.target]))
        print("Object Direction wrt Car: "+str(event.direction[event.target]))
        print("")
         
        print("Retrieved Case:")
        
        if len(retrievedCase[0]) == 0:
            print("No Similar Case found. Applying Default Case...\n")
        else:
            object = retrievedCase[0][2]
            object = object[object.find('=')+1:]
            
            dist = retrievedCase[0][0]
            dist = dist[dist.find(':')+1:dist.find('}')]
            dist = dist.strip(' ')
            
            dir = retrievedCase[0][1]
            dir = dir[dir.find(':')+1:dir.find('}')]
            dir = dir.strip(' ')
            
            speed = retrievedCase[0][4]
            speed = speed[speed.find('{')+1:speed.find('}')]
            
            print("Object: "+object)
            print("Distance from Car: "+str(abs(float(dist))))
            print("Direction wrt Car: "+dir)
            print("Speed of Car and Object: "+speed)
            print("")
        
        time.sleep(1)    
                    
                        
        
        
Exemplo n.º 26
0
class EventHandler(object):

    g = 127008
    displayCount = -1
    sig_cnt = -1
    speed_limit_flag = False

    def __init__(self, car):
        self.car = car
        self.rules = [
            ['1', ['signal:RED'], ['acceleration:N']
             ],  # rule base for signal, stop sign and speed limit
            ['2', ['signal:AMBER'], ['acceleration:N']],
            ['3', ['signal:GREEN'], ['acceleration:Y']],
            ['4', ['sign:STOP'], ['acceleration:N']],
            ['5', ['speed:Y'], ['aceleration:Y']],
            ['6', ['speed:N'], ['acceleration:N']]
        ]

        self.evtgen = EventGenerator.EventGenerator(
        )  # creating random event generator object
        self.rt = Retriever(
            'casebasedplan.txt')  # Retriever object for case retrieval
        self.exception_event = ExceptionalEvent()
        self.laneChanged = False

    # Below method handles the basic driving events
    def handleEvent(self, event):  #all the event handling goes here
        action = ''
        self.speed_limit = self.car.maxSpeed

        if event['turn'] != '' and self.car.currentLane == 'M':
            if self.car.distanceCovered >= .65 * self.car.laneDist and self.laneChanged == False:  # changes lane after distance covered
                print("\nAttempting to change lanes..."
                      )  # crosses the threshold (65% of lane dist)
                self.laneChanged = self.handleLaneChange(event)

        if 'signal' in event:  # checking if signal is present at the end of the lane
            signal = event['signal']

        if 'sign' in event:  # checking for lane signs (speed limit)
            sign = event['sign']
            if 'speed' in sign:
                self.speed_limit = int(sign[sign.find('~') + 1:])
                if self.speed_limit_flag == False:
                    print("\nSpeed Limit Sign in view...Speed Limit: " +
                          str(self.speed_limit))
                self.handleSpeedSign()

        excp_event = self.exception_event.giveExceptionalEvent(
        )  # event generator generates exception event

        if excp_event != False:
            print("\nExceptional Event in Progress...")
            self.handleExpCase(
                excp_event)  # method for handling exceptional events
            time.sleep(1)

        if signal == True:  # if signal is present at the end of the lane. Either signal or STOP sign at the end of the lane.
            if self.car.remainingDist <= self.getBrakingDist():
                print("\nBraking Distance Reached...Signal in view...")
                self.evtgen.resetSignal()
                time.sleep(2)
                action = self.handleSignalStopSign(1, 'SIGNAL', event)
                return action
        else:  # indicates stop sign is present at the end of the lane.
            if self.car.remainingDist <= self.getBrakingDist():
                print("\nBraking Distance Reached...STOP sign in view...")
                time.sleep(2)
                action = self.handleSignalStopSign(1, 'STOP', event)
                return action

        self.speed_limit = self.car.maxSpeed

        if (self.car.speed < self.speed_limit
            ):  # if speed is less than speed limit then accelerate
            self.car.accelerate(1, self.speed_limit)
        self.car.move()

        return False

    # Below method handles the exceptional events
    def handleExpCase(self, event):

        event.speed['me'] = self.car.speed
        retrievedCase = self.rt.findClosestMatch(
            event)  # case retrieved from case base
        self.printExcpCase(event,
                           retrievedCase)  # prints the details of the event

        result = retrievedCase[1][0]
        action = result[0]
        priority = result[2]
        speed_limit = result[3]

        if action == 'decelerate':
            print("Reducing Speed to speed limit of " + str(speed_limit) +
                  "\n")
        else:
            print("Increasing Speed to speed limit of " + str(speed_limit) +
                  "\n")
        time.sleep(1)

        while True:
            self.displayFullDtls('Y')
            time.sleep(0.1)
            if action == 'decelerate':
                if self.car.speed > speed_limit:
                    self.car.decelerate(priority,
                                        speed_limit)  # decelerate the car
                    self.car.move()
                    if speed_limit == 0 and self.car.speed <= 0.35:  # if the car's speed goes below 0.35 kmph, reduce speed to 0.
                        self.car.speed = 0  # This is done because the car's speed never reaches 0, only close to 0.

                else:
                    break
            elif action == 'accelerate':
                if self.car.speed < speed_limit:
                    self.car.accelerate(priority,
                                        speed_limit)  # accelerate the car
                    self.car.move()
                else:
                    break

        print("\nExceptional event concluded...")
        if self.car.speed <= self.speed_limit:
            temp_str = "increased"
        else:
            temp_str = "decreased"

        if action == 'decelerate':
            print("\nSpeed reduced to "+str(self.car.speed)+". Speed will be "+temp_str+" to speed limit: "+\
                  str(self.speed_limit)+"\n")
        else:
            print("\nSpeed increased to "+str(self.car.speed)+". Speed will be "+temp_str+" to speed limit: "+\
                  str(self.speed_limit)+"\n")

        time.sleep(1)

    # Below method handles the speed sign
    def handleSpeedSign(self):
        if self.car.speed <= self.speed_limit:
            if self.speed_limit_flag == False:
                print("Increasing speed to " + str(self.speed_limit) + "\n")
                self.speed_limit_flag = True
            action = self.getAction('speed:' + 'Y')
        else:
            if self.speed_limit_flag == False:
                print("Reducing speed to " + str(self.speed_limit) + "\n")
                self.speed_limit_flag = True
            action = self.getAction('speed:' + 'N')
        self.changeSpeed(1, action, self.speed_limit)

    # Below method returns the action based on the rule
    def getAction(self, event):
        event_value = event[event.find(':') + 1:]
        event_type = event[:event.find(':')]

        for rule in self.rules:
            ante = rule[1][0]
            evalue = ante[ante.find(':') + 1:]
            etype = ante[:ante.find(':')]

            if etype == event_type and evalue == event_value:  # if event type and event value matches, then return the action
                result = rule[2][0]
                result_value = result[result.find(':') + 1:]
                return result_value

    #Below method handles the Signal as well as the Stop sign depending on the event type
    def handleSignalStopSign(self, priority, event_type, event):
        flag = True
        is_last = False
        turn = event['turn']

        if turn == 'D':  # checking if this is the last lane i.e. is the destination on this lane
            is_last = True

        while 1:
            time.sleep(Car.Car().sleepTime)

            if event_type == 'SIGNAL':  # if event type is Signal
                currentSignal = self.evtgen.probeSignal(
                )  # probe the event value generator for signal value

            if self.laneChanged == False:
                self.laneChanged = self.handleLaneChange(
                    event)  # handle lane change if lane not already changed

            if event_type == 'SIGNAL':
                self.displayFullDtls('N', currentSignal)
                action = self.getAction('signal:' + currentSignal)
            elif event_type == 'STOP':
                action = self.getAction('sign:' + event_type)

            if action == 'Y':
                speed_limit = self.car.maxSpeed
            else:
                speed_limit = 0

            flag = self.changeSpeed(
                priority, action, speed_limit
            )  #adjust speed based on the action (acceleration/deceleration)

            if flag == False:
                self.car.speed = 0  # car has stopped
                break
            else:
                self.displayFullDtls('N')
                if self.car.distanceCovered >= self.car.laneDist:  # checking if the lane distance has been reached
                    print("\nLane Distance Reached")
                    if is_last == False:
                        return False
                    return True

        print("Lane Distance covered: " +
              str(self.car.distanceCovered * 1000)),
        print(" Speed: " + str(self.car.speed)),
        print(" Remaining Lane Distance: " +
              str(self.car.remainingDist * 1000))
        print("\nCar STOPPED...")
        if is_last == False:
            if event_type == 'SIGNAL':
                print("Waiting for signal to turn GREEN...\n")
            elif event_type == 'STOP':
                print("Waiting to move...\n")
        time.sleep(2)

        if is_last == False:  # not the last lane
            while 1:
                if event_type == 'SIGNAL':
                    signal = self.evtgen.probeSignal(
                    )  #probe for signal till "GREEN" is received
                elif event_type == 'STOP':
                    signal = self.evtgen.probeAllClear(
                    )  #probe for all clear signal from the value generator

                if signal == 'GREEN':  # if signal is GREEN, accelerate the car and start moving
                    while 1:
                        self.car.accelerate(1, self.speed_limit)
                        self.car.move()

                        self.displayFullDtls('N')
                        if self.car.distanceCovered >= self.car.laneDist:
                            print("Lane Distance covered: " +
                                  str(self.car.distanceCovered * 1000)),
                            print(" Speed: " + str(self.car.speed)),
                            print(" Remaining Lane Distance: " +
                                  str(self.car.remainingDist * 1000))
                            print("\nLane Distance Reached")
                            time.sleep(2)
                            return False  # Once lane distance is reached, return back to caller

        return True

    # Below method adjusts the speed of the car based on the priority
    def changeSpeed(
            self, priority, acc_yn,
            speed_limit):  # acc_yn: 'Y' - Acceleration, 'N' - Deceleration
        if acc_yn == 'N':
            self.car.decelerate(priority, speed_limit)
            self.car.move()

            if self.car.speed < 0.35 or self.car.remainingDist <= 0.001:
                return False
        else:
            if (self.car.speed < speed_limit):
                self.car.accelerate(1, speed_limit)
            else:
                self.car.decelerate(1, speed_limit)
            self.car.move()

        return True

    # braking distance - distance at which the brakes should be applied to stop the car
    def getBrakingDist(self):
        brakingDistance = self.car.speed * self.car.speed / 2 / 0.7 / self.g
        return brakingDistance

    # Below method handles the lane change
    def handleLaneChange(self, event):
        changeLane = ''
        laneChangeRules = [
            [{
                'lane': 1,
                'turn': 'L',
                'car': 'Y'
            }, 'notrequired'],  # rules for lane change
            [{
                'lane': 1,
                'turn': 'R',
                'car': 'Y'
            }, 'notrequired'],
            [{
                'lane': 1,
                'turn': 'L',
                'car': 'N'
            }, 'notrequired'],
            [{
                'lane': 1,
                'turn': 'R',
                'car': 'N'
            }, 'notrequired'],
            [{
                'lane': 2,
                'turn': 'L',
                'car': 'Y'
            }, 'no'],
            [{
                'lane': 2,
                'turn': 'R',
                'car': 'Y'
            }, 'notrequired'],
            [{
                'lane': 2,
                'turn': 'R',
                'car': 'N'
            }, 'notrequired'],
            [{
                'lane': 2,
                'turn': 'L',
                'car': 'N'
            }, 'yes'],
            [{
                'lane': 3,
                'turn': 'R',
                'car': 'Y'
            }, 'no'],
            [{
                'lane': 3,
                'turn': 'L',
                'car': 'Y'
            }, 'no'],
            [{
                'lane': 3,
                'turn': 'R',
                'car': 'N'
            }, 'yes'],
            [{
                'lane': 3,
                'turn': 'L',
                'car': 'N'
            }, 'yes']
        ]

        turn = event.get('turn')
        lane = event.get('lane')
        car = self.evtgen.checkMirror(
        )  # probe value generator to check if its safe to change the lane
        for rules in laneChangeRules:
            ante = rules[0]
            if turn == ante.get('turn') and lane == ante.get(
                    'lane') and car == ante.get('car'):
                changeLane = rules[1]
                break

        if changeLane == 'yes':
            print "Lane change successful...\n"
            time.sleep(2)
            return True
        elif changeLane == 'notrequired':
            print "No need to change lanes but turn ahead...\n"
            time.sleep(2)
            return True
        elif changeLane == 'no':
            print "Cannot change lane right now...\n"
            time.sleep(2)
            return False

    # Below method displays the full or partial output based on the argument 'full_yn'. Required as output is displayed very often.
    # full_yn = 'Y' is used when the change in speed needs to be displayed when the priority for deceleration is high.
    def displayFullDtls(self, full_yn, signal_color=''):
        displayLimit = 20  # counter used to limit the number of display
        signalLimit = 500  # counter used to limit the number of display while probing signal

        if signal_color != '':
            self.sig_cnt = self.sig_cnt + 1
            if self.sig_cnt % signalLimit == 0:
                print("Current Signal: " + signal_color +
                      ". Reducing the speed of the car...\n")

                if self.sig_cnt != 0:
                    self.sig_cnt = -1

        else:
            if full_yn == 'N':
                self.displayCount = self.displayCount + 1
                if self.displayCount % displayLimit == 0:
                    print("Lane Distance covered: " +
                          str(self.car.distanceCovered * 1000)),
                    print(" Speed: " + str(self.car.speed)),
                    print(" Remaining Lane Distance: " +
                          str(self.car.remainingDist * 1000))

                    if self.displayCount != 0:
                        self.displayCount = -1
            else:
                print("Lane Distance covered: " +
                      str(self.car.distanceCovered * 1000)),
                print(" Speed: " + str(self.car.speed)),
                print(" Remaining Lane Distance: " +
                      str(self.car.remainingDist * 1000))

    # Below method prints the details of the exceptional case - the occurred event and the retrieved case
    def printExcpCase(self, event, retrievedCase):
        print("Object: " + str(event.target))
        print("Object Distance from Car: " +
              str(abs(event.distance[event.target])))
        print("Object Speed: " + str(event.speed[event.target]))
        print("Object Direction wrt Car: " +
              str(event.direction[event.target]))
        print("")

        print("Retrieved Case:")

        if len(retrievedCase[0]) == 0:
            print("No Similar Case found. Applying Default Case...\n")
        else:
            object = retrievedCase[0][2]
            object = object[object.find('=') + 1:]

            dist = retrievedCase[0][0]
            dist = dist[dist.find(':') + 1:dist.find('}')]
            dist = dist.strip(' ')

            dir = retrievedCase[0][1]
            dir = dir[dir.find(':') + 1:dir.find('}')]
            dir = dir.strip(' ')

            speed = retrievedCase[0][4]
            speed = speed[speed.find('{') + 1:speed.find('}')]

            print("Object: " + object)
            print("Distance from Car: " + str(abs(float(dist))))
            print("Direction wrt Car: " + dir)
            print("Speed of Car and Object: " + speed)
            print("")

        time.sleep(1)
Exemplo n.º 27
0
from Retriever import Retriever
R = Retriever()

# pagerank updates for random names
res = R.fetch_objects(size=1000)
print(res.keys())

n_iterations = 10000
d = 0.7
n = float(len(res.keys()))

for i in range(n_iterations):
    # for each name...
    for k, v in res.items():

        # calculate pagerank...
        updated_prob = (1 - d) * 1 / n

        # ...by inspecting its parents
        for parent_node in v.parents:
            # parents with high pageranks but few outbound are best
            updated_prob += d * (parent_node.pagerank) / parent_node.n_children

        # update node's pagerank
        v.update_pagerank(updated_prob)

    if i % (n_iterations / 5) == 0:
        print("iteration", i)

R.put_objects(res)