def getInitialPoints(allPoints): pointLen = len(allPoints) resAllPoints = [] i = 0 prePoint = allPoints[i] while i < pointLen: curList = allPoints[i].strip('\n').split(',') # 去掉后面换行 curTuple = (curList[0], curList[1], curList[2], curList[3]) if i == 0: curTuple = curTuple + (0, 0, 0, 'none', 0) resAllPoints.append(curTuple) pre = curTuple i = i + 1 continue if i == 1: # 计算 速度、距离 distance = func.getDistance(float(pre[0]), float(pre[1]), float(curList[0]), float(curList[1])) timeInterval = func.getTimeInterval(pre[2], curList[2]) v = distance / timeInterval curTuple = curTuple + (v, 0, distance, 'none', 0) resAllPoints.append(curTuple) pre = curTuple # print(curTuple) i = i + 1 continue # 第3个点之后,计算速度、加速度、距离、point label distance = func.getDistance(float(pre[0]), float(pre[1]), float(curList[0]), float(curList[1])) timeInterval = func.getTimeInterval(pre[2], curList[2]) v = distance / timeInterval a = abs(v - pre[4]) / timeInterval pointLabel = 'non-walk-point' if v < vThreshold and a < aThreshold: pointLabel = 'walk-point' if i == pointLen - 1: curTuple = curTuple + (v, a, distance, pointLabel, 0) else: curTuple = curTuple + (v, a, distance, pointLabel, 0) resAllPoints.append(curTuple) pre = curTuple # print(curTuple) i = i + 1 return resAllPoints
def crossOver(self): self.listFitness = getDistance(self.population, self.finishPos) totalFit = [(x / max(self.listFitness)) for x in self.listFitness] listFinishCount = [x.finish_at_count for x in self.population] #die => giam ti le chon #finish it nuoc di nhat tang ti le theChosen = [] for i in range(self.number_population): if self.population[i].dead: totalFit[i] *= 1.15 elif min(listFinishCount) != -1 and i == listFinishCount.index( min(listFinishCount)): totalFit[i] = 0 theChosen.append(self.population[i]) elif listFinishCount[i] != -1: totalFit[i] *= 0.9 #all dead => ti le chhon 10% each totalFit = relu(np.array(totalFit)) if min(totalFit) >= 0.99: totalFit = [0] * self.number_population # os.system('cls') # t = [round(x,3) for x in totalFit] # print(*t, sep='\t') for i in range(int(self.number_population / 2 - len(theChosen))): while True: pos = np.random.randint(self.number_population) if totalFit[pos] <= np.random.uniform(0, 1): theChosen.append(self.population[pos]) break childs = [] for i in range(int(self.number_population)): parentA = theChosen[np.random.randint(len(theChosen))] parentB = theChosen[np.random.randint(len(theChosen))] child = self.mating(parentA, parentB) childs.append(child) #replace all current DNA #keep the last most fitness for i in range(self.number_population): #if i != self.listFitness.index(min(self.listFitness)): self.population[i].DNA = childs[i] for i in self.population: i.resetPos([self.startPos[0], self.startPos[1]]) self.gen += 1
def crossOver(self): self.listFitness = getDistance(self.population, self.finishPos) totalFit = [(x / max(self.listFitness)) for x in self.listFitness] listFinishCount = [x.finish_at_count for x in self.population] #die => giam ti le chon #finish it nuoc di nhat tang ti le for i in range(self.number_population): if self.population[i].dead: totalFit[i] *= 1.1 elif min(listFinishCount) != -1 and i == listFinishCount.index( min(listFinishCount)): totalFit[i] *= 0.5 elif listFinishCount[i] != -1: totalFit[i] *= 0.7 #all dead => ti le chhon 10% each if min(totalFit) == max(totalFit): totalFit = [0.5] * self.number_population theChosen = [] for i in range(int(self.number_population / 2)): while True: pos = np.random.randint(self.number_population) if totalFit[pos] <= np.random.uniform(0, 1): theChosen.append(self.population[pos].DNA) break childs = [] for i in range(int(self.number_population)): parentA = theChosen[np.random.randint(len(theChosen))] parentB = theChosen[np.random.randint(len(theChosen))] #child = [] #if self.mutation_chance >= np.random.uniform(0,1): #child = DNA() #else: child = self.mating(parentA, parentB) childs.append(child) #replace all current DNA #keep the last most fitness for i in range(self.number_population): #if i != self.listFitness.index(min(self.listFitness)): self.population[i].DNA = childs[i] for i in self.population: i.resetPos([self.startPos[0], self.startPos[1]]) self.gen += 1
def addDistVelocity(DBPath, i): """ if time interval between cur and pre record is greater than 20min, then we consider the begin of another trajectory, the first record's distance and velocity of trajectory is -1 default. we can say value "-1" can understand as the begin of single trajectory """ conn = DBUtil.get_conn(DBPath) # find all points fetchAllPointSql = 'select * from GPS_points_' + str(i) allPointRecords = DBUtil.fetchAll(conn, fetchAllPointSql) if allPointRecords is None: print('fetch point set Fail!') return """ records: type list-> [(1, 3, 39.9752333333333, 116.330066666667, '2008/04/29 17:15:24', -1, -1, -1, 'non', 0, 0, 0, 0, 'none')......] the index of time is 4 lat: 2 lon: 3 distance: 7 velocity: 5 """ pre = allPointRecords[0] # print(preRecord) parameters = [] for index in range(len(allPointRecords)): cur = allPointRecords[index] if index == 0: parameters.append((-1, -1, cur[0])) continue timeInterval = func.getTimeInterval(pre[4], cur[4]) # if pre time equals cur time, we set timeInterval 1 second if timeInterval == 0: timeInterval = 1 if timeInterval >= TimeThreshold: parameters.append((-1, -1, cur[0])) pre = cur continue # print("points id: " + str(cur[0])) dist = func.getDistance(pre[2], pre[3], cur[2], cur[3]) lineTuple = (dist, dist / timeInterval, cur[0]) parameters.append(lineTuple) pre = cur updateSql = 'update GPS_points_' + \ str(i) + ' set distance = ?, velocity = ? where id = ?' DBUtil.update(conn, updateSql, parameters) DBUtil.closeDB(conn) print("update distance and velocity successfully!")
def getBSR(segment, busInfoPath): """ Args: segment: such as, [(id,latitude,longitude,day_time,velocity,accelerometer,distance,true_label, tp)] 0, 1, 2, 3, 4, 5, 6, 7, 8 busInfoPath: bus information file Returns: BSR value of segment """ # open bus information file busInfoFile = open(busInfoPath) try: allLines = busInfoFile.readlines() finally: busInfoFile.close() # get BSR value segLen = len(segment) num = 0 lowNum = 0 index = 0 while index < segLen: cur = segment[index] min = 999999 # if cur[5] < lowVth and cur[6] < lowAth: if cur[4] < lowVth: # get near 0 point lowNum += 1 for line in allLines: line = line.strip('\n') lineList = line.split(',') busLat = lineList[0] busLon = lineList[1] tempDist = func.getDistance(cur[1], cur[2], float(busLat), float(busLon)) if tempDist < min: min = tempDist if min < busDistTh: num += 1 index += 1 if lowNum == 0: return 0 else: return num / lowNum
def addTrueCP(DBPath, i): """ if the distance between an normal GPS points and actual transition points is within 150 m, we regard the GPS point is transition point. """ conn = DBUtil.get_conn(DBPath) # find all points fetchAllPointSql = 'select id,lat,lon,accelerometer,mode,time_stamp ' + \ 'from GPS_points_' + str(i) allPointRecords = DBUtil.fetchAll(conn, fetchAllPointSql) if allPointRecords is None: print('fetch point set Fail!') return """ records: type list-> [(1, 39.9752333333333, 116.330066666667, 'none').....] id: 0 lat: 1 lon: 2 accelerometer: 3 mode: 4 time_stamp: 5 """ parameters = [] recordLen = len(allPointRecords) pre = allPointRecords[0] index = 1 while index < recordLen: cur = allPointRecords[index] if cur[3] == -1: pre = cur index += 1 continue tempTime = func.getTimeInterval(pre[5], cur[5]) if cur[4] != pre[4] and tempTime < TimeThreshold: parameters.append((cur[0], )) # forward forStart = index - 1 while forStart >= 0: forward = allPointRecords[forStart] tempDist = func.getDistance(cur[1], cur[2], forward[1], forward[2]) if tempDist > transiPointDist: break parameters.append((forward[0], )) forStart -= 1 # afterward aftStart = index + 1 while aftStart < recordLen: aftward = allPointRecords[aftStart] tempDist = func.getDistance(cur[1], cur[2], aftward[1], aftward[2]) if tempDist > transiPointDist: break parameters.append((aftward[0], )) aftStart += 1 # update into database if len(parameters) != 0: print(parameters) updateSql = "update GPS_points_" + str(i) + \ " set is_true_tp = 1 where id = ?" DBUtil.update(conn, updateSql, parameters) parameters.clear() pre = cur index += 1 DBUtil.closeDB(conn)
def addStayPoint(DBPath, i): """ caculate stay point value in table GPS_points_i, value: 1 denotes the point is stay point value: 0 denotes the normal stap point step 1: find stay point according to rule: Distance(p1, p2)<D and TimeDiff(p1, p2)>T step 2: use direction change to drop extra stay points step 3: noise filtering """ conn = DBUtil.get_conn(DBPath) # find all points fetchAllPointSql = 'select * from GPS_points_' + str(i) allPointRecords = DBUtil.fetchAll(conn, fetchAllPointSql) if allPointRecords is None: print('fetch point set Fail!') return """ records: type list-> [(1, 3, 39.9752333333333, 116.330066666667, '2008/04/29 17:15:24', -1, -1, -1, 'non', 0, 0, 0, 0, 'none')......] id: 0 time: 4 lat: 2 lon: 3 distance: 7 velocity: 5 """ parameters = [] stayPointSet = [] recordLen = len(allPointRecords) index = 0 while index < recordLen: cur = allPointRecords[index] j = index + 1 token = 0 while j < recordLen: aft = allPointRecords[j] # if another trajectory bagins if aft[7] == -1: index = j token = 1 break dist = func.getDistance(cur[2], cur[3], aft[2], aft[3]) if dist > StayPoinDistThd: curTimeDiff = func.getTimeInterval(cur[4], aft[4]) if curTimeDiff > StayPoinTiThd: # index ~ j points are added to stayPointSet sIndex = index while sIndex < j: temp = allPointRecords[sIndex] stayPointSet.append((temp[0], temp[2], temp[3])) sIndex += 1 # output the stay points set # print(stayPointSet) """ check stay points set 1, abandon the case of traffic congestion """ # isTraCong = func.isTrafficCongestion(stayPointSet, # changeAngle, # changeRate) # if isTraCong == 1: # stayPointSet.clear() # break """ check stay points set 2 (noise filtering), get content: [(39, 39.8146666666667, 119.476816666667, 0),......], """ resPointList = func.noiseFilter(stayPointSet, 3) """ insert stay points into table GPS_points_i field: is_stay_point """ for item in resPointList: parameters.append((item[3], item[0])) # print("resPointList's size:" + str(len(resPointList))) # print(resPointList) func.writeFile( 'stay_point_set_result.txt', "resPointList's size: " + str(len(resPointList))) func.writeFile('stay_point_set_result.txt', str(resPointList)) func.writeFile('stay_point_set_result.txt', "\n\n") updateSql = "update GPS_points_" + str(i) + \ " set is_stay_point = 1, is_deleted = ? where id = ?" # DBUtil.update(conn, updateSql, parameters) # clear the stay points set resPointList.clear() stayPointSet.clear() parameters.clear() index = j token = 1 break else: break j += 1 # end while if token != 1: index += 1 DBUtil.closeDB(conn)
# Check detected object for i, box in enumerate(boxes[0]): if (scores[0][i] > 0.5): # Get x, y, z coord of ball yMin = int((box[0] * height)) xMin = int((box[1] * width)) yMax = int((box[2] * height)) xMax = int((box[3] * width)) xCoor = int(np.mean([xMin, xMax])) yCoor = int(np.mean([yMin, yMax])) # Find distance from camera in inches distance = func.getDistance(focalLength, 29.5, (xMax - xMin) * resize) # draw object detection if (classes[0][i] == 1): # basketball cv2.rectangle(frame, (xMin, yMin), (xMax, yMax), (36, 255, 12), 2) cv2.putText(frame, 'basketball', (xMin, yMin - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36, 255, 12), 2) # if ball has finished shooting if(shooting == True): if(last <= hoopYMax and yCoor > hoopYMax): # Record makes and misses if(make == True): made += 1 total += 1
def draw(self): colorLast = (232, 150, 217) distance = getDistance(self.pop.population, self.pop.finishPos) count_Dead = 0 count_Finish = 0 pos_min_fit = [10000, 10000] for i in range(self.pop.number_population): if self.pop.population[i].finish: count_Finish += 1 if self.pop.population[i].dead: count_Dead += 1 if not self.pop.population[i].dead and not self.pop.population[ i].finish and distance[i] < pos_min_fit[1]: pos_min_fit[0] = i pos_min_fit[1] = distance[i] #setting text self.screen.fill(pg.Color('black')) genTxt = self.font.render('Gen: %s' % self.pop.gen, 1, (255, 255, 255)) second = self.font.render('%s/%s' % (self.pop.count, DNA_length), 1, (255, 255, 255)) mutationTxt = self.font.render( 'Mutation: %s%%' % (self.pop.mutation_chance * 100), 1, (255, 255, 255)) popTxt = self.font.render( 'Number population: %s' % (self.pop.number_population), 1, (255, 255, 255)) currentFitness = self.font.render( 'Current specie fitness: %s - %s' % (pos_min_fit[0], round(pos_min_fit[1], 2)), 1, pg.Color('green')) countFinish = self.font.render('Finish: %s' % count_Finish, 1, (197, 232, 52)) countDead = self.font.render('Dead: %s' % count_Dead, 1, (43, 50, 52)) #draw start pos pg.draw.rect( self.screen, pg.Color('blue'), (self.pop.startPos[0] - 5, self.pop.startPos[1] - 5, 10, 10)) #draw species for pos in range(self.pop.number_population): if pos_min_fit[0] == pos: self.pop.population[pos].draw(self.screen, 'green') else: self.pop.population[pos].draw(self.screen) #draw wall self.listWall.draw(self.screen) self.listWallGood.draw(self.screen) #text self.screen.blit(genTxt, (10, 10)) self.screen.blit(second, (100, 10)) self.screen.blit(currentFitness, (10, 30)) self.screen.blit(countFinish, (10, 50)) self.screen.blit(countDead, (10, 70)) self.screen.blit(mutationTxt, (10, screen_width - 40)) self.screen.blit(popTxt, (10, screen_width - 20))