Exemplo n.º 1
0
 def evaluate(self):
     #print(self.players[self.myId]['position'], self.myId, self.whoPlay)
     return self.players[self.myId]['hp'] - self.players[
         self.opponentId]['hp']
     if self.players[self.myId]['hp'] // self.players[
             self.myId]['maxHp'] < 0.5:
         return (self.players[self.myId]['hp'] - self.players[
             self.opponentId]['hp']) * 1000 + lib.getDistance(
                 self.players[self.myId]['position'],
                 self.players[self.opponentId]['position'])
     else:
         return (self.players[self.myId]['hp'] - self.players[
             self.opponentId]['hp']) * 1000 - lib.getDistance(
                 self.players[self.myId]['position'], [8, 8])
Exemplo n.º 2
0
def moveMap(center, mp):
    moveMap = [center]
    for y in range(lib.getMapHeight()):
        for x in range(lib.getMapWidth()):
            if lib.getDistance([x, y], center) < mp + 1 and lib.getCellContent(
                [x, y]) == lib.CELL_EMPTY:
                path = lib.getPath([x, y], center)
                if path != -1 and len(path) <= mp:
                    moveMap.append([x, y])
    return moveMap
Exemplo n.º 3
0
 def compute_distances(self):
     """ compute distances from the first point to the last point """
     current_lat, current_lon = 0.0, 0.0
     dist = 0
     x, t = 0, 0
     tp = Trace_point.objects.filter(trace=self).order_by('time')
     for p in tp:
         x = lib.getDistance(current_lat, current_lon, p.latitude, p.longitude)
         dist = dist + x
         p.distance = dist
         p.save()
         current_lat = p.latitude
         current_lon = p.longitude
     transaction.commit()
Exemplo n.º 4
0
 def compute_distances(self):
     """ compute distances from the first point to the last point """
     current_lat, current_lon = 0.0, 0.0
     dist = 0
     x, t = 0, 0
     tp = Trace_point.objects.filter(trace=self).order_by('time')
     for p in tp:
         x = lib.getDistance(current_lat, current_lon, p.latitude,
                             p.longitude)
         dist = dist + x
         p.distance = dist
         p.save()
         current_lat = p.latitude
         current_lon = p.longitude
     transaction.commit()
Exemplo n.º 5
0
 def get_closest_tracks(tr_id, lat, lon):
     """Renvoie les traces les plus proches du point passé en paramètre
         à l'exception de tr_id (trace courante)
        Calcul fait sur la base du point "moyen" des traces
     """
     #boundbox progressivement agrandie, on s'arrete quand on a plus de 10 traces, on les ordonne par distance puis on renvoie les 10 premiers
     boxsize, trs, trsdis = gps.settings.SEARCH_BOX_SIZE, [], []
     #TODO optimiser ?
     while len(trs) < 10 and boxsize < 2000:
         boxsize = boxsize * 2 + gps.settings.SEARCH_BOX_SIZE  #on augmente de plus en plus vite
         trs = Trace.get_tracks_in_bounds(lat - boxsize, lon - boxsize, lat + boxsize, lon + boxsize)
     #recherche des 10 plus proches
     #trsdis = [(t,lib.getDistanceAB(lat,lon,t.getFirstPoint().latitude,t.getFirstPoint().longitude)) for t in trs]
     for t in trs:
         if t.id != tr_id:
             avgPt = t.get_avg_lat_lon()
             trsdis.append((t, lib.getDistance(lat, lon, avgPt['lat'], avgPt['lon'])))
     trs = sorted(trsdis, key=lambda trk: trk[1])[0:10]
     return trs
Exemplo n.º 6
0
 def get_closest_tracks(tr_id, lat, lon):
     """Renvoie les traces les plus proches du point passé en paramètre
         à l'exception de tr_id (trace courante)
        Calcul fait sur la base du point "moyen" des traces
     """
     #boundbox progressivement agrandie, on s'arrete quand on a plus de 10 traces, on les ordonne par distance puis on renvoie les 10 premiers
     boxsize, trs, trsdis = gps.settings.SEARCH_BOX_SIZE, [], []
     #TODO optimiser ?
     while len(trs) < 10 and boxsize < 2000:
         boxsize = boxsize * 2 + gps.settings.SEARCH_BOX_SIZE  #on augmente de plus en plus vite
         trs = Trace.get_tracks_in_bounds(lat - boxsize, lon - boxsize,
                                          lat + boxsize, lon + boxsize)
     #recherche des 10 plus proches
     #trsdis = [(t,lib.getDistanceAB(lat,lon,t.getFirstPoint().latitude,t.getFirstPoint().longitude)) for t in trs]
     for t in trs:
         if t.id != tr_id:
             avgPt = t.get_avg_lat_lon()
             trsdis.append(
                 (t, lib.getDistance(lat, lon, avgPt['lat'], avgPt['lon'])))
     trs = sorted(trsdis, key=lambda trk: trk[1])[0:10]
     return trs
Exemplo n.º 7
0
def main():
    print('---USER 1---')
    lib.setWeapon(lib.WEAPON_SIMPLE_GUN)
    selfId = lib.getMyId()
    selfPos = lib.getCell(selfId)
    selfMp = lib.getMp(selfId)

    enemyId = lib.getEnemyId()
    enemyPos = lib.getCell(enemyId)
    enemyMp = lib.getMp(enemyId)

    tab = []
    OBSTACLES = lib.getObstacles()

    # Movemap
    selfMoveMap = moveMap(selfPos, selfMp)
    #for cell in selfMoveMap:
    #    lib.mark(cell, 'green')

    enemyMoveMap = moveMap(enemyPos, enemyMp)
    print(enemyPos, enemyMp, enemyMoveMap, file=sys.stderr)
    #for cell in enemyMoveMap:
    #    lib.mark(cell, 'red')

    # Find safe cell / attack cell

    canHit = False
    bestMove = [[], -1]
    for simulated in selfMoveMap:
        # Find far cell where we can attack
        if lib.getDistance(simulated, enemyPos) <= 5 and lib.getLineOfSight(
                simulated, enemyPos):
            if lib.getDistance(simulated, enemyPos) >= bestMove[1]:
                bestMove = [
                    simulated.copy(),
                    lib.getDistance(simulated, enemyPos)
                ]
                canHit = True

    if canHit:
        lib.mark(bestMove[0], 'blue')
        path = lib.getPath(selfPos, bestMove[0])
        if path != -1:
            for move in path:
                lib.moveOn(move)
                selfMp -= 1
            lib.attackOn(enemyPos)
            lib.mark(bestMove[0], 'yellow')
            selfPos = bestMove[0]

    # Flee on safe cell
    canFlee = False
    bestFlee = [[], 99999]
    if (selfMp > 0):
        selfMoveMap = moveMap(selfPos, selfMp)
        for selfSimu in selfMoveMap:
            safeCell = True
            for enemySimu in enemyMoveMap:
                print('Simualted (E/S):',
                      enemySimu,
                      '/',
                      selfSimu,
                      file=sys.stderr)
                if lib.getDistance(selfSimu,
                                   enemySimu) <= 5 and lib.getLineOfSight(
                                       selfSimu, enemySimu):
                    # If user can hit us, then cell isn't safe
                    safeCell = False
                    break
            if safeCell:
                lib.mark(selfSimu, 'green')
                canFlee = True
                if (bestFlee[1] >= lib.getDistance(selfSimu, enemyPos)):
                    bestFlee = [[selfSimu.copy()],
                                lib.getDistance(selfSimu, enemyPos)]
                elif (bestFlee[1] == lib.getDistance(selfSimu, enemyPos)):
                    bestFlee[0].append(selfSimu.copy())
            else:
                lib.mark(selfSimu, 'red')

        if canFlee:
            bestFlee[0] = random.choice(bestFlee[0])
            lib.mark(bestFlee[0], 'blue')
            path = lib.getPath(selfPos, bestFlee[0])
            if path != -1:
                for move in path:
                    lib.moveOn(move)
                    selfMp -= 1
                selfPos = bestFlee[0]
Exemplo n.º 8
0
    def availableMoves(self):
        mp = self.players[self.whoPlay]['mp']
        x, y = self.players[self.whoPlay]['position']
        #print('X/Y', x, y)
        path = lib.getPath(list(self.players[self.whoPlay]['position']),
                           list(self.players[1 - self.whoPlay]['position']))
        if path != -1:
            moves = [path[0]]
            moves[0].append('[FLEE]')
            """if len(path) <= 4:
                print('path', path[2])
                moves.append[path[max(0, len(path) - 2)]]
                moves[1].append('[ATTACK]', self.weapons[lib.WEAPON_SWORD])"""
        else:
            moves = [list(self.players[self.whoPlay]['position'])]
            moves[0].append('[FLEE]')
        if self.whoPlay == self.myId:
            for weapon in self.weapons:
                accessibleCells = [[x, y]]
                enemyPos = lib.getCell(1 - self.whoPlay)
                weaponRange = weapon['maxRange']

                last = [[x, y]]
                while mp >= 0:
                    tmp = []
                    for cell in last:
                        if lib.getLineOfSight(
                                cell, enemyPos) and lib.getDistance(
                                    cell, enemyPos) <= weaponRange:
                            moves.append(
                                tuple(cell) + tuple(['[ATTACK]', weapon]))
                            mp = 0
                        else:
                            for dx, dy in [(0, 1), (0, -1), (-1, 0), (1, 0)]:
                                if lib.getCellContent(
                                    (cell[0] + dx,
                                     cell[1] + dy)) == lib.CELL_EMPTY and not [
                                         cell[0] + dx, cell[1] + dy
                                     ] in accessibleCells:
                                    tmp.append([cell[0] + dx, cell[1] + dy])
                                    accessibleCells.append(
                                        [cell[0] + dx, cell[1] + dy])
                    mp -= 1
                    last = tmp.copy()
        else:
            accessibleCells = [[x, y]]
            enemyPos = lib.getCell(1 - self.whoPlay)
            weaponRange = self.weapons[self.players[self.whoPlay]
                                       ['currentWeapon']]['maxRange']

            last = [[x, y]]
            while mp >= 0:
                tmp = []
                for cell in last:
                    if lib.getLineOfSight(cell, enemyPos) and lib.getDistance(
                            cell, enemyPos) <= weaponRange:
                        moves.append(
                            tuple(cell) + tuple([
                                '[ATTACK]', self.weapons[self.players[
                                    self.whoPlay]['currentWeapon']]
                            ]))
                        mp = 0
                    else:
                        for dx, dy in [(0, 1), (0, -1), (-1, 0), (1, 0)]:
                            if lib.getCellContent(
                                (cell[0] + dx,
                                 cell[1] + dy)) == lib.CELL_EMPTY and not [
                                     cell[0] + dx, cell[1] + dy
                                 ] in accessibleCells:
                                tmp.append([cell[0] + dx, cell[1] + dy])
                                accessibleCells.append(
                                    [cell[0] + dx, cell[1] + dy])
                mp -= 1
                last = tmp.copy()

        # Defensive moves
        mp = self.players[self.whoPlay]['mp']
        last = [[x, y]]
        accessibleCells = [[x, y]]
        defMoves = []
        while mp > 0:
            tmp = []
            h = False
            if defMoves:
                h = True
            for cell in last:
                for dx, dy in [(0, 1), (0, -1), (-1, 0), (1, 0)]:
                    if (lib.getCellContent((cell[0] + dx, cell[1] + dy))
                            == lib.CELL_EMPTY) and not [
                                cell[0] + dx, cell[1] + dy
                            ] in accessibleCells:
                        tmp.append([cell[0] + dx, cell[1] + dy])
                        accessibleCells.append([cell[0] + dx, cell[1] + dy])
                        if not lib.getLineOfSight([cell[0] + dx, cell[1] + dy],
                                                  enemyPos):
                            if h:
                                defMoves = []
                                h = False
                            defMoves.append(
                                (cell[0] + dx, cell[1] + dy, '[FLEE]'))

            mp -= 1
            last = tmp.copy()

        for move in defMoves:
            moves.append(move)

        return moves
Exemplo n.º 9
0
    def get_matching_segments(self, tr2_id):
        """ repérage et TODO: stockage des segments communs entre self et tr2
        on passe une tolerance en longueur pour le match (plus c'est élevé plus on tolère de mismatchs
        TODO: stockage en base des repérages de segments matchés
        TODO: search_small_step est le levier d'amélioration dans le paramétrage
        """
        search_big_step = 30  # nombre de points entre 2 tests en recherche grosse maille
        search_small_step = 2  # nombre de points entre 2 tests après avoir trouvé le premier match
        dist_tolerance = 0.030
        min_seg_dist = 0.300  # 300m
        mismatch_tolerance = 2  #tolerance de perte de chemin commun  en nombre de points
        lonlat_delta = 10
        seg2_search_length = 100  #range of points to be search further after first match found

        def get_matching_points(tp1, tr2_id, excluded_ranges=''):
            """ renvoie pour tp1 les points de t2 susceptible de matcher les points de t1
                avec un order_num >= à order_min
            """
            match = {}
            tps = Trace_point.objects.filter(
                trace=tr2_id).order_by('order_num')
            # if num_min != 0:
            #     tps = tps.filter(order_num__lt = num_min + seg2_search_length)
            #tps = tps.filter(order_num__gt = num_min)
            if excluded_ranges != '':
                excluded_ranges = 'not (' + excluded_ranges[0:-4] + ')'
                tps = tps.extra(where=[excluded_ranges])
            tps = tps.extra(where=[
                '10000*(abs(' + str(tp1.latitude) + '-latitude)+abs(' +
                str(tp1.longitude) + '-longitude)) <' + str(lonlat_delta)
            ])
            tps = tps.order_by('order_num')
            # print tps.query
            if tps.count() > 0:
                min_dist = 1  #on commence avec 1 km
                tp2 = tps[0]
                for t in tps:
                    #dist = lib.getDistance(tp1.latitude, tp1.longitude,t.latitude, t.longitude)
                    dist = lib.getQuickDistance(tp1.latitude, tp1.longitude,
                                                t.latitude, t.longitude)
                    if dist < min_dist:
                        min_dist = dist
                        tp2 = t
                if min_dist < dist_tolerance:
                    match[tp1] = tp2
                else:
                    return {}
            return match

        tps = Trace_point.objects.filter(trace=self).order_by(
            'order_num'
        )[::search_big_step]  #query with a step equals to tolerance
        matches = []  #liste de points matchants
        t1_order_num = 0
        range_extra = ''
        matching_segments = [
        ]  #liste de matches dont la longueur est suffisante
        for tp1 in tps:
            if tp1.order_num > t1_order_num:
                t1_order_num = tp1.order_num
                match = get_matching_points(tp1, tr2_id, range_extra)
                if match != {}:
                    # matches.append((match.keys()[0].order_num, match.values()[0][0].order_num))
                    t1_order_num = t1_order_num - search_big_step
                    segtps = Trace_point.objects.filter(trace=self).filter(
                        order_num__gt=t1_order_num)
                    n_unmatch, first_match_found = 0, 0
                    #boucle en small step
                    for tp in segtps[::search_small_step]:
                        match = get_matching_points(tp, tr2_id, range_extra)
                        if match == {}:
                            n_unmatch += 1
                            if n_unmatch > mismatch_tolerance and first_match_found == 1:
                                break
                        else:
                            matches.append((match.keys()[0].order_num,
                                            match.values()[0].order_num))
                            n_unmatch, first_match_found = 0, 1

                    if len(matches) > 0:
                        start = Trace_point.objects.filter(trace=self).filter(
                            order_num=matches[0][0])[0]
                        end = Trace_point.objects.filter(trace=self).filter(
                            order_num=matches[-1][0])[0]
                        dist_seg = lib.getDistance(start.latitude,
                                                   start.longitude,
                                                   end.latitude, end.longitude)
                        if dist_seg > min_seg_dist:
                            matching_segments.append(matches)
                            t1_order_num = matches[-1][
                                0] + 1  # on reprendra au dernier point matché sur t1
                            if len(matches) > 0:
                                range_extra += '(order_num >' + str(
                                    matches[0][1]) + ' and order_num <' + str(
                                        matches[-1][1]) + ') or '
                        matches = []
        return matching_segments
Exemplo n.º 10
0
    def get_matching_segments_old(self, tr2_id):
        """ repérage et TODO: stockage des segments communs entre self et tr2
        on passe une tolerance en longueur pour le match (plus c'est élevé plus on tolère de mismatchs
        TODO: stockage en base des repérages de segments matchés
        TODO: search_small_step est le levier d'amélioration dans le paramétrage
        """
        search_big_step = 30  # nombre de points entre 2 tests en recherche grosse maille
        search_small_step = 1  # nombre de points entre 2 tests après avoir trouvé le premier match
        dist_tolerance = 0.040
        min_seg_dist = 0.300  # 300m
        mismatch_tolerance = 5  #tolerance de perte de chemin commun  en nombre de points
        lonlat_delta = 10
        seg2_search_length = 100  #range of points to be search further after first match found

        #DONE: use excluded ranges instead of excluded lists
        def get_matching_points(tp1, tr2_id, num_min=0, exclude_list=[]):
            """ renvoie pour tp1 les points de t2 susceptible de matcher les points de t1
                avec un order_num >= à order_min
            """
            match = {}
            tps = Trace_point.objects.filter(trace=tr2_id)
            if num_min != 0:
                tps = tps.filter(order_num__lt=num_min + seg2_search_length)
            if len(exclude_list) > 950:
                #handling sqlite limitations (but exclude list should not be so long) i should use excluded_ranges cf previous to do.
                # this is artificially introducing a maxlength to the matching segment
                return {}
            tps = tps.filter(order_num__gt=num_min).exclude(
                order_num__in=exclude_list)
            tps = tps.extra(where=[
                '10000*(abs(' + str(tp1.latitude) + '-latitude)+abs(' +
                str(tp1.longitude) + '-longitude)) <' + str(lonlat_delta)
            ])
            tps = tps.order_by('order_num')
            # print tps.query
            if tps.count() > 0:
                min_dist = 1  #on commence avec 1 km
                tp2 = tps[0]
                for t in tps:
                    #dist = lib.getDistance(tp1.latitude, tp1.longitude,t.latitude, t.longitude)
                    dist = lib.getQuickDistance(tp1.latitude, tp1.longitude,
                                                t.latitude, t.longitude)
                    if dist < min_dist:
                        min_dist = dist
                        tp2 = t
                if min_dist < dist_tolerance:
                    match[tp1] = tp2
                else:
                    return {}
            return match

        tps = Trace_point.objects.filter(
            trace=self
        )[::search_big_step]  #query with a step equals to tolerance
        matches = []  #liste de points matchants
        t1_order_num = 0
        exclude_list = []  #liste des points déjà matchés dans t2=> à exclure
        matching_segments = [
        ]  #liste de matches dont la longueur est suffisante
        for tp1 in tps:
            if tp1.order_num > t1_order_num:
                t1_order_num = tp1.order_num
                match = get_matching_points(tp1, tr2_id, 0, exclude_list)
                if match != {}:
                    # matches.append((match.keys()[0].order_num, match.values()[0][0].order_num))
                    t2_min_num = match.values()[0].order_num - search_big_step
                    t1_order_num = t1_order_num - search_big_step
                    # try to build a segment ( with first match, i go back search_step points) and find the first matching point
                    segtps = Trace_point.objects.filter(trace=self).filter(
                        order_num__gt=t1_order_num)
                    n_unmatch, first_match_found = 0, 0
                    #boucle en small step
                    for tp in segtps[::search_small_step]:
                        match = get_matching_points(
                            tp, tr2_id, t2_min_num - search_small_step,
                            exclude_list)
                        if match == {}:
                            n_unmatch += 1
                            if n_unmatch > mismatch_tolerance and first_match_found == 1:
                                break
                        else:
                            matches.append((match.keys()[0].order_num,
                                            match.values()[0].order_num))
                            t2_min_num = match.values()[0].order_num
                            n_unmatch, first_match_found = 0, 1

                    if len(matches) > 0:
                        start = Trace_point.objects.filter(trace=self).filter(
                            order_num=matches[0][0])[0]
                        end = Trace_point.objects.filter(trace=self).filter(
                            order_num=matches[-1][0])[0]
                        dist_seg = lib.getDistance(start.latitude,
                                                   start.longitude,
                                                   end.latitude, end.longitude)
                        if dist_seg > min_seg_dist:
                            matching_segments.append(matches)
                            if len(matches) > 0:
                                exclude_list += range(matches[0][1],
                                                      matches[-1][1])
                        matches = []

        return matching_segments
Exemplo n.º 11
0
    def get_matching_segments(self, tr2_id):
        """ repérage et TODO: stockage des segments communs entre self et tr2
        on passe une tolerance en longueur pour le match (plus c'est élevé plus on tolère de mismatchs
        TODO: stockage en base des repérages de segments matchés
        TODO: search_small_step est le levier d'amélioration dans le paramétrage
        """
        search_big_step = 30# nombre de points entre 2 tests en recherche grosse maille
        search_small_step = 2 # nombre de points entre 2 tests après avoir trouvé le premier match
        dist_tolerance = 0.030
        min_seg_dist = 0.300 # 300m
        mismatch_tolerance = 2 #tolerance de perte de chemin commun  en nombre de points
        lonlat_delta = 10
        seg2_search_length = 100 #range of points to be search further after first match found

        def get_matching_points(tp1 ,tr2_id,  excluded_ranges=''):
            """ renvoie pour tp1 les points de t2 susceptible de matcher les points de t1
                avec un order_num >= à order_min
            """
            match = {}
            tps = Trace_point.objects.filter(trace=tr2_id).order_by('order_num')
            # if num_min != 0:
            #     tps = tps.filter(order_num__lt = num_min + seg2_search_length)
            #tps = tps.filter(order_num__gt = num_min)
            if excluded_ranges != '':
                excluded_ranges = 'not (' +excluded_ranges[0:-4] +')'
                tps = tps.extra(where=[excluded_ranges])
            tps = tps.extra(where=['10000*(abs('+str(tp1.latitude)+'-latitude)+abs('+str(tp1.longitude)+'-longitude)) <'+str(lonlat_delta)])
            tps = tps.order_by('order_num')
            # print tps.query
            if tps.count()>0:
                min_dist = 1 #on commence avec 1 km
                tp2 = tps[0]
                for t in tps:
                    #dist = lib.getDistance(tp1.latitude, tp1.longitude,t.latitude, t.longitude)
                    dist = lib.getQuickDistance(tp1.latitude, tp1.longitude,t.latitude, t.longitude)
                    if dist < min_dist:
                        min_dist = dist
                        tp2 = t
                if min_dist < dist_tolerance:
                    match[tp1] = tp2
                else:
                    return {}
            return match

        tps = Trace_point.objects.filter(trace=self).order_by('order_num')[::search_big_step] #query with a step equals to tolerance
        matches = [] #liste de points matchants
        t1_order_num = 0
        range_extra=''
        matching_segments = [] #liste de matches dont la longueur est suffisante
        for tp1 in tps:
            if tp1.order_num > t1_order_num:
                t1_order_num = tp1.order_num
                match = get_matching_points(tp1, tr2_id, range_extra)
                if match != {}:
                    # matches.append((match.keys()[0].order_num, match.values()[0][0].order_num))
                    t1_order_num = t1_order_num-search_big_step
                    segtps = Trace_point.objects.filter(trace=self).filter(order_num__gt=t1_order_num)
                    n_unmatch , first_match_found = 0,0
                    #boucle en small step
                    for tp in segtps[::search_small_step]:
                        match = get_matching_points(tp,tr2_id,range_extra)
                        if match == {}:
                            n_unmatch += 1
                            if n_unmatch > mismatch_tolerance and first_match_found==1:
                                break
                        else:
                            matches.append((match.keys()[0].order_num, match.values()[0].order_num))
                            n_unmatch, first_match_found=0,1

                    if len(matches) > 0:
                        start = Trace_point.objects.filter(trace= self).filter(order_num = matches[0][0])[0]
                        end = Trace_point.objects.filter(trace= self).filter(order_num = matches[-1][0])[0]
                        dist_seg = lib.getDistance(start.latitude,start.longitude, end.latitude, end.longitude)
                        if dist_seg > min_seg_dist:
                            matching_segments.append(matches)
                            t1_order_num = matches[-1][0] +1  # on reprendra au dernier point matché sur t1
                            if len(matches) >0:
                                range_extra += '(order_num >' + str(matches[0][1]) +' and order_num <'+str(matches[-1][1])+') or '
                        matches = []
        return matching_segments
Exemplo n.º 12
0
    def get_matching_segments_old(self, tr2_id):
        """ repérage et TODO: stockage des segments communs entre self et tr2
        on passe une tolerance en longueur pour le match (plus c'est élevé plus on tolère de mismatchs
        TODO: stockage en base des repérages de segments matchés
        TODO: search_small_step est le levier d'amélioration dans le paramétrage
        """
        search_big_step = 30  # nombre de points entre 2 tests en recherche grosse maille
        search_small_step = 1  # nombre de points entre 2 tests après avoir trouvé le premier match
        dist_tolerance = 0.040
        min_seg_dist = 0.300 # 300m
        mismatch_tolerance = 5 #tolerance de perte de chemin commun  en nombre de points
        lonlat_delta = 10
        seg2_search_length = 100 #range of points to be search further after first match found

        #DONE: use excluded ranges instead of excluded lists
        def get_matching_points(tp1 ,tr2_id, num_min = 0, exclude_list = []):
            """ renvoie pour tp1 les points de t2 susceptible de matcher les points de t1
                avec un order_num >= à order_min
            """
            match = {}
            tps = Trace_point.objects.filter(trace=tr2_id)
            if num_min != 0:
                tps = tps.filter(order_num__lt = num_min + seg2_search_length)
            if len(exclude_list)>950:
            #handling sqlite limitations (but exclude list should not be so long) i should use excluded_ranges cf previous to do.
            # this is artificially introducing a maxlength to the matching segment
                return {}
            tps = tps.filter(order_num__gt = num_min).exclude(order_num__in=exclude_list)
            tps = tps.extra(where=['10000*(abs('+str(tp1.latitude)+'-latitude)+abs('+str(tp1.longitude)+'-longitude)) <'+str(lonlat_delta)])
            tps = tps.order_by('order_num')
            # print tps.query
            if tps.count()>0:
                min_dist = 1 #on commence avec 1 km
                tp2 = tps[0]
                for t in tps:
                    #dist = lib.getDistance(tp1.latitude, tp1.longitude,t.latitude, t.longitude)
                    dist = lib.getQuickDistance(tp1.latitude, tp1.longitude,t.latitude, t.longitude)
                    if dist < min_dist:
                        min_dist = dist
                        tp2 = t
                if min_dist < dist_tolerance:
                    match[tp1] = tp2
                else:
                    return {}
            return match

        tps = Trace_point.objects.filter(trace=self)[::search_big_step] #query with a step equals to tolerance
        matches = [] #liste de points matchants
        t1_order_num = 0
        exclude_list = [] #liste des points déjà matchés dans t2=> à exclure
        matching_segments = [] #liste de matches dont la longueur est suffisante
        for tp1 in tps:
            if tp1.order_num > t1_order_num:
                t1_order_num = tp1.order_num
                match = get_matching_points(tp1, tr2_id, 0, exclude_list)
                if match != {}:
                    # matches.append((match.keys()[0].order_num, match.values()[0][0].order_num))
                    t2_min_num = match.values()[0].order_num-search_big_step
                    t1_order_num = t1_order_num-search_big_step
                    # try to build a segment ( with first match, i go back search_step points) and find the first matching point
                    segtps = Trace_point.objects.filter(trace=self).filter(order_num__gt=t1_order_num)
                    n_unmatch , first_match_found = 0,0
                    #boucle en small step
                    for tp in segtps[::search_small_step]:
                        match = get_matching_points(tp,tr2_id,t2_min_num-search_small_step,exclude_list)
                        if match == {}:
                            n_unmatch += 1
                            if n_unmatch > mismatch_tolerance and first_match_found==1:
                                break
                        else:
                            matches.append((match.keys()[0].order_num, match.values()[0].order_num))
                            t2_min_num = match.values()[0].order_num
                            n_unmatch, first_match_found=0,1

                    if len(matches) > 0:
                        start = Trace_point.objects.filter(trace= self).filter(order_num = matches[0][0])[0]
                        end = Trace_point.objects.filter(trace= self).filter(order_num = matches[-1][0])[0]
                        dist_seg = lib.getDistance(start.latitude,start.longitude, end.latitude, end.longitude)
                        if dist_seg > min_seg_dist:
                            matching_segments.append(matches)
                            if len(matches) >0: exclude_list += range(matches[0][1],matches[-1][1])
                        matches = []

        return matching_segments
Exemplo n.º 13
0
def start():
	ret, frame = vc.read()

	# Timer for saving strum timings and saving music
	start = time.time()
	gap = 0
	prevStrum = ""
	song = []
	prevTime = 0.00
	elapsed = 0.00

	# Motion detection flags
	prevPos = 0
	direction = 0
	up = 0
	down = 0
	firstframe = 1

	while ret:
		# Change color space for better detection
		hsvframe = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
		fingerImages = lib.filterFingers(hsvframe)
		cv2.imshow('red', fingerImages[0])	
		cv2.imshow('green', fingerImages[1])
		cv2.imshow('blue', fingerImages[2])

		fingerPositions = lib.getPositions(fingerImages)

		# Detect the mode of playback
		mode = lib.getMode(fingerPositions)
		distance = lib.getDistance(fingerPositions)

		# Show the mode on screen
		cv2.putText(frame, mode , (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 4, 255)
		cv2.imshow('preview', frame)	
		
		# Find the postion of lower strumming hand
		lowerPos = lib.getLowerBlob(hsvframe)

		# Motion detection for lower hand
		if prevPos != 0:
			disp = lowerPos[0][1] - prevPos
			direction = direction + disp
			if direction < -200:
				up = 1
				direction = 0
			if direction > 200:
				down = 1
				direction = 0
		if firstframe == 1:
			firstframe = 0
		prevPos = lowerPos[0][1]
			
		# Perform the playback and append the strum in song
		if down == 1:
			if gap == 1:
				elapsed = time.time() - start
				song.append([prevStrum, elapsed])
				gap == 0
				if prevTime != 0.00:
					song.append([prevStrum, (elapsed-prevTime)])
				else:
					song.append([prevStrum, 0.00])
				prevTime = elapsed
			play.play(lib.getPattern(mode,distance,'down'))
			if gap == 0:
				start = time.time()
				prevStrum = lib.getPattern(mode,distance, 'down')
				gap = 1
			down = 0

		else:
			if up == 1:
				if gap == 1:
					elapsed = time.time() - start
					song.append([prevStrum, elapsed])
					gap == 0
					if prevTime != 0.00:
						song.append([prevStrum, (elapsed-prevTime)])
					else:
						song.append([prevStrum, 0.00])
					prevTime = elapsed
				play.play(lib.getPattern(mode,distance,'up'))
				if gap == 0:
					start = time.time()
					prevStrum = lib.getPattern(mode,distance,'up')
					gap = 1
				up = 0

		ret, frame = vc.read()
		key = cv2.waitKey(20)
		if key == 27:	#Ends the session and save the song. Press ESCAPE key
			play.save('muse', song, 0.05, [0, prevTime, 0.1])
			break