예제 #1
0
파일: hba.py 프로젝트: kgmstwo/THBCP
def get_robot_neighbors():
    nbr_list_out = []
    nbr_list = neighbors.get_neighbors()
    for nbr in nbr_list:
        if neighbors.get_nbr_id(nbr) not in nav_tower_ids:
            nbr_list_out.append(nbr)
    return nbr_list_out
예제 #2
0
파일: hba.py 프로젝트: va17/THBCP
def get_robot_neighbors():
    nbr_list_out = []
    nbr_list = neighbors.get_neighbors()
    for nbr in nbr_list:
        if neighbors.get_nbr_id(nbr) not in nav_tower_ids:
            nbr_list_out.append(nbr)
    return nbr_list_out
def calculateWithK(test_set_by_user=[], k=-1, trainingSet=[]):
    if (k == -1):
        k = raw_input("Please input K: ")
        k = int(k)

    global neighbors, accuracy

    # data preparation
    if (test_set_by_user == -1):
        testSet = get_test_set()
    else:
        testSet = test_set_by_user

    trainingSet = get_training_set()
    print 'training set -->  ' + repr(trainingSet)
    print 'testing set --> ' + repr(testSet)
    # predictions
    predictions = []
    for x in range(len(testSet)):
        neighbors = get_neighbors(trainingSet, testSet[x], k)
        responses_result = get_response(neighbors)
        predictions.append(responses_result)
        print('> predicted = ' + repr(responses_result) + ', actual = ' + repr(testSet[x][-1]))

    # accuracy:
    accuracy = get_accuracy(testSet, predictions)
    print('Accuracy: ' + repr(accuracy) + '%')
예제 #4
0
def get_Gaussian_gamma_correction(a, U, FWHM=None,
                                  cutoff=None, accuracy_goal=12):
    """
    Gaussian charge distribution.
    """
    if FWHM is None:
        FWHM = sqrt(8*log2/pi)/U

    max_FWHM = np.max(FWHM)
    if max_FWHM <= 0.0:
        raise ValueError("Maximum FWHM (%f) smaller than or equal to zero. " %
                         max_FWHM)

    if cutoff is None and not a.is_cluster():
        # Estimate a cutoff from the accuracy goal if the
        # system is periodic and no cutoff was given
        cutoff = sqrt(log(10.0)*accuracy_goal*max_FWHM/(sqrt(4*log2)))

    il, jl, dl, nl = get_neighbors(a, cutoff)

    nat = len(a)
    G   = np.zeros([nat, nat], dtype=float)
    dG  = np.zeros([nat, nat, 3], dtype=float)
    G[diag_indices_from(G)] = U

    if il is not None:
        for i, j, d, n in zip(il, jl, dl/Bohr, nl):
            const        = 2*sqrt( log2/(FWHM[i]**2+FWHM[j]**2) )
            ecr          = -erfc(const*d)
            decr         = 2/sqrt(pi)*exp(-(const*d)**2)*const
            G[i, j]     += ecr/d
            dG[i, j, :] += (ecr/d-decr)*n/d

    return G, dG
예제 #5
0
파일: Wall_Follow.py 프로젝트: va17/THBCP
def wall_follow_demo():
    velocity.init(0.22, 40, 0.5, 0.1)
    leds.init()
    pose.init()
    motion.init()
    neighbors.init(NBR_PERIOD)

    state = STATE_IDLE
    wall_time = 0
    
    while True:
        # Do updates
        leds.update()
        pose.update()
        velocity.update()
        new_nbrs = neighbors.update()
        
        nbrList = neighbors.get_neighbors()
        tv = 0
        rv = 0

        # this is the main finite-state machine
        if state == STATE_IDLE:
            leds.set_pattern('r', 'circle', LED_BRIGHTNESS)
            if new_nbrs:
                print "idle"
            if rone.button_get_value('r'):
                state = STATE_LOOK_FOR_WALL
            
        elif state == STATE_LOOK_FOR_WALL:
            leds.set_pattern('r', 'blink_fast', LED_BRIGHTNESS)
            if new_nbrs:
                print "look for wall"
            tv = MOTION_TV
            obs = neighbors.get_obstacles() 
            if (obs != None):
                state = STATE_WALL_FOLLOW                
            
        elif state == STATE_WALL_FOLLOW:
            leds.set_pattern('b', 'blink_fast', LED_BRIGHTNESS)
            if new_nbrs:
                print "wall follow"
            # follow the wall
            (tv, rv, active) = wall_follow(MOTION_TV / 2)
            if active == True:
                wall_time = sys.time()
            if sys.time() > (wall_time + WALL_TIMEOUT):
                state = STATE_LOOK_FOR_WALL
                
        # end of the FSM
                        
        # set the velocities
        velocity.set_tvrv(tv, rv)
        
        #set the message
        hba.set_msg(0, 0, 0)
예제 #6
0
def main():
    training_set, test_set = data.load_dataset('formatted_file.data')
    predictions = []
    k = 3
    for x in range(len(test_set)):
        neighbors = ns.get_neighbors(training_set, test_set[x], k)
        result = rs.get_response(neighbors)
        predictions.append(result[0][0])
        print('> predicted = ' + repr(result) + ', actual = ' +
              repr(test_set[x][-1]))
    accuracy = acc.accuracy(test_set, predictions)
    print('Accuracy: ' + repr(accuracy) + '%')
예제 #7
0
파일: hba.py 프로젝트: kgmstwo/THBCP
def find_nav_tower_nbr(id):
    nbr_list = neighbors.get_neighbors()
    # If low power ID availible, get bearing from it
    low_power_id = id
    high_power_id = id - 1
    nbr_out = None
    for nbr in nbr_list:
        if low_power_id == neighbors.get_nbr_id(nbr):
            nbr_out = nbr
    # Else take bearing from high power ID
        elif (high_power_id == neighbors.get_nbr_id(nbr)) and (nbr_out == None):
            nbr_out = nbr
    return nbr_out
예제 #8
0
파일: hba.py 프로젝트: va17/THBCP
def find_nav_tower_nbr(id):
    nbr_list = neighbors.get_neighbors()
    # If low power ID availible, get bearing from it
    low_power_id = id
    high_power_id = id - 1
    nbr_out = None
    for nbr in nbr_list:
        if low_power_id == neighbors.get_nbr_id(nbr):
            nbr_out = nbr
    # Else take bearing from high power ID
        elif (high_power_id == neighbors.get_nbr_id(nbr)) and (nbr_out
                                                               == None):
            nbr_out = nbr
    return nbr_out
def calculateWithKFofGraph(test_set_by_user=[], trainingSet=[], k = 1):
    global neighbors, accuracy

    testSet = test_set_by_user
    # predictions
    predictions = []
    for x in range(len(testSet)):
        neighbors = get_neighbors(trainingSet, testSet[x], k)
        responses_result = get_response(neighbors)
        predictions.append(responses_result)
        print('> predicted = ' + repr(responses_result) + ', actual = ' + repr(testSet[x][-1]))

    # accuracy:
    accuracy = get_accuracy(testSet, predictions)
    print('Accuracy: ' + repr(accuracy) + '%')
    return accuracy
예제 #10
0
파일: Flock_Demo.py 프로젝트: va17/THBCP
def flock_beh():
    # act on the information from the message.  Note that this might be 
    # information stored from the last message we received, because message 
    # information remains active for a while
    nbr_list = neighbors.get_neighbors()
    if len(nbr_list) > 0:
        # any neighbor wil do.  get the first neighbor
        x = 0.0
        y = 0.0
        for nbr in nbr_list:
            nbr_bearing = neighbors.get_nbr_bearing(nbr)
            nbr_orientation = neighbors.get_nbr_orientation(nbr)
            nbr_heading = math2.normalize_angle(math.pi + nbr_bearing - nbr_orientation)
            x += math.cos(nbr_heading)
            y += math.sin(nbr_heading)
        nbr_heading_avg = math.atan2(y, x)
        beh = (0, FLOCK_RV_GAIN * nbr_heading_avg, True)
    else:
        #no neighbors. do nothing
        beh = (0, 0, False)
    return beh
예제 #11
0
def get_Gaussian_gamma_correction(a,
                                  U,
                                  FWHM=None,
                                  cutoff=None,
                                  accuracy_goal=12):
    """
    Gaussian charge distribution.
    """
    if FWHM is None:
        FWHM = sqrt(8 * log2 / pi) / U

    max_FWHM = np.max(FWHM)
    if max_FWHM <= 0.0:
        raise ValueError("Maximum FWHM (%f) smaller than or equal to zero. " %
                         max_FWHM)

    if cutoff is None and not a.is_cluster():
        # Estimate a cutoff from the accuracy goal if the
        # system is periodic and no cutoff was given
        cutoff = sqrt(log(10.0) * accuracy_goal * max_FWHM / (sqrt(4 * log2)))

    il, jl, dl, nl = get_neighbors(a, cutoff)

    nat = len(a)
    G = np.zeros([nat, nat], dtype=float)
    dG = np.zeros([nat, nat, 3], dtype=float)
    G[diag_indices_from(G)] = U

    if il is not None:
        for i, j, d, n in zip(il, jl, dl / Bohr, nl):
            const = 2 * sqrt(log2 / (FWHM[i]**2 + FWHM[j]**2))
            ecr = -erfc(const * d)
            decr = 2 / sqrt(pi) * exp(-(const * d)**2) * const
            G[i, j] += ecr / d
            dG[i, j, :] += (ecr / d - decr) * n / d

    return G, dG
예제 #12
0
def spring():
    at_tree_odo = None
    tree_pose = None
    followers = 0
    have_seen_leader = False
    beh.init(0.22, 40, 0.5, 0.1)
    motion.init_rv(1000, MOTION_RV, MOTION_CAPTURE_DISTANCE,
                   MOTION_RELEASE_DISTANCE, MOTION_CAPTURE_ANGLE,
                   MOTION_RELEASE_ANGLE)
    state = STATE_IDLE

    while True:
        # run the system updates
        new_nbrs = beh.update()
        nbr_list = neighbors.get_neighbors()
        if new_nbrs:
            print state

        beh_out = beh.BEH_INACTIVE

        # set colors, because why not do it at the top
        color_counts = [0, 0, 0]
        for i in range(3):
            color_counts[i] = min([5, (state - 5 * i)])
        if state == STATE_IDLE:
            leds.set_pattern('rb', 'group', LED_BRIGHTNESS)
        elif state == STATE_SUCCESS:
            leds.set_pattern('g', 'circle', LED_BRIGHTNESS)
        else:
            leds.set_pattern(color_counts, 'count', LED_BRIGHTNESS)

        if rone.button_get_value('g'):
            tree_pose = None
            followers = 0
            have_seen_leader = False
            state = STATE_IDLE

        # this is the main finite-state machine
        if not state in [
                STATE_IDLE, STATE_LEADER, STATE_SUCCESS, STATE_FOLLOW
        ]:
            for nbr in nbr_list:
                nbr_state = hba.get_msg_from_nbr(nbr, new_nbrs)[MSG_IDX_STATE]
                if nbr_state in [STATE_LEADER, STATE_SUCCESS]:
                    start_time = sys.time()
                    state = STATE_FOLLOW

        if state == STATE_IDLE:

            if rone.button_get_value('r'):
                pose.set_pose(0, 0, 0)
                state = STATE_WANDER
            elif rone.button_get_value('b'):
                state = STATE_QUEEN

        elif state == STATE_QUEEN:
            pass

        elif state == STATE_WANDER:
            ##            leds.set_pattern('r', 'circle', LED_BRIGHTNESS)
            nav = hba.find_nav_tower_nbr(NAV_ID)
            beh_out = beh.avoid_nbr(nav, MOTION_TV)
            queen = None
            for nbr in nbr_list:
                nbr_state = hba.get_msg_from_nbr(nbr, new_nbrs)[MSG_IDX_STATE]
                if nbr_state == STATE_QUEEN:
                    queen = nbr

            if bump_front():
                if queen != None:
                    state = STATE_SUCCESS
                else:
                    tree_pose = pose.get_pose()
                    motion.set_goal((0.0, 0.0), MOTION_TV)
                    at_tree_odo = pose.get_odometer()
                    state = STATE_RETURN
            elif nav == None:
                motion.set_goal((0.0, 0.0), MOTION_TV)
                state = STATE_RETURN

        elif state == STATE_RETURN:
            ##            nav_tower = hba.find_nav_tower_nbr(NAV_ID)
            queen = None
            recruiter = None
            for nbr in nbr_list:
                nbr_state = hba.get_msg_from_nbr(nbr, new_nbrs)[MSG_IDX_STATE]
                if nbr_state == STATE_QUEEN:
                    queen = nbr
                elif nbr_state == STATE_RECRUIT:
                    recruiter = nbr
            if queen != None:
                if (recruiter == None) and (tree_pose != None) and \
                close_to_nbr(queen):
                    start_time = sys.time()
                    dist_traveled = pose.get_odometer() - at_tree_odo
                    at_queen_odo = pose.get_odometer()
                    state = STATE_RECRUIT
                elif not closer_to_nbr(queen):
                    beh_out = beh.follow_nbr(queen, MOTION_TV)
                else:
                    start_time = sys.time()
                    state = STATE_FOLLOW
            else:
                (tv, rv) = motion.update()
                beh_out = beh.tvrv(tv, rv)

        elif state == STATE_RECRUIT:
            new_followers = 0
            for nbr in nbr_list:
                nbr_state = hba.get_msg_from_nbr(nbr, new_nbrs)[MSG_IDX_STATE]
                if nbr_state == STATE_RECRUIT:
                    if neighbors.get_nbr_id(nbr) > rone.get_id():
                        state = STATE_FOLLOW
                elif nbr_state in [STATE_FOLLOW, STATE_QUEEN]:
                    new_followers += 1
            if new_followers > followers:
                print 'reset timer'
                start_time = sys.time()
            followers = max([followers, new_followers])
            if followers == 4 or sys.time() > start_time + WAIT_TIME:
                tree_pos = (tree_pose[0], tree_pose[1])
                motion.set_goal(tree_pos, MOTION_TV)
                state = STATE_LEADER

        elif state == STATE_FOLLOW:
            recruiter = None
            leader = None
            success = False
            new_followers = 1
            for nbr in nbr_list:
                nbr_state = hba.get_msg_from_nbr(nbr, new_nbrs)[MSG_IDX_STATE]
                if nbr_state == STATE_RECRUIT:
                    recruiter = nbr
                elif nbr_state == STATE_LEADER:
                    leader = nbr
                elif nbr_state == STATE_SUCCESS:
                    leader = nbr
                    success = True
                elif nbr_state in [STATE_FOLLOW, STATE_WANDER]:
                    new_followers += 1
            if success:
                have_seen_leader = True
            if new_followers > followers:
                start_time = sys.time()
            followers = max([followers, new_followers])

            if recruiter == None:
                if leader == None:
                    if have_seen_leader:
                        beh_out = beh.tvrv(MOTION_TV, 0)
                    elif followers == 5 or sys.time() > start_time + WAIT_TIME:
                        followers = 0
                        state = STATE_WANDER
                else:
                    if success and bump() and close_to_nbr(leader):
                        state = STATE_SUCCESS
                    beh_out = beh.follow_nbr(leader, MOTION_TV)

        elif state == STATE_LEADER:
            ##            (tv, rv) = motion.update()
            ##            beh_out = beh.tvrv(tv, rv)
            ##            if motion.is_done():
            ##                state = STATE_SUCCESS
            beh_out = beh.tvrv(-MOTION_TV, 0)

            if bump() or (pose.get_odometer() - at_queen_odo) > dist_traveled:
                state = STATE_SUCCESS

        elif state == STATE_SUCCESS:
            pass

        # end of the FSM

        if state not in [
                STATE_IDLE, STATE_RECRUIT, STATE_LEADER, STATE_SUCCESS,
                STATE_QUEEN
        ]:
            bump_beh_out = beh.bump_beh(MOTION_TV)
            beh_out = beh.subsume([beh_out, bump_beh_out])

        # set the beh velocities
        beh.motion_set(beh_out)

        #set the HBA message
        msg = [0, 0, 0]
        msg[MSG_IDX_STATE] = state
        hba.set_msg(msg[0], msg[1], msg[2])
예제 #13
0
def get_Slater_gamma_correction(a,
                                U,
                                FWHM=None,
                                cutoff=None,
                                accuracy_goal=12):
    """
    Slater-type charge distribution.
    See: M. Elstner et al., Phys. Rev. B 58, 7260 (1998)
    """
    min_U = np.min(U)
    if min_U <= 0.0:
        raise ValueError("Minimum U (%f) smaller than or equal to zero. " %
                         min_U)

    if cutoff is None and not a.is_cluster():
        # Estimate a cutoff from the accuracy goal if the
        # system is periodic and no cutoff was given
        cutoff = sqrt(log(10.0) * accuracy_goal / (sqrt(pi / 2) * min_U))

    tau = 16 * np.asarray(U) / 5

    il, jl, dl, nl = get_neighbors(a, cutoff)

    nat = len(a)
    G = np.zeros([nat, nat], dtype=float)
    dG = np.zeros([nat, nat, 3], dtype=float)
    G[diag_indices_from(G)] = U

    if il is not None:
        for i, j, d, n in zip(il, jl, dl / Bohr, nl):
            if abs(tau[i] - tau[j]) < 1e-6:
                src = 1.0 / (tau[i] + tau[j])
                fac = tau[i] * tau[j] * src
                avg = 1.6 * (fac + fac * fac * src)
                fac = avg * d
                fac2 = fac * fac
                efac = exp(-fac) / (48 * d)
                h = -(48 + 33 * fac + fac2 * (9 + fac)) * efac
                G[i, j] += \
                    h
                dG[i, j, :] += \
                    (   h/d \
                      + avg*h \
                      + (33*avg + 18*fac*avg + 3*fac2*avg)*efac )*n
            else:
                fi1 = 1.0 / (2 * (tau[i]**2 - tau[j]**2)**2)
                fj1 = -tau[i]**4 * tau[j] * fi1
                fi1 *= -tau[j]**4 * tau[i]

                fi2 = 1.0 / ((tau[i]**2 - tau[j]**2)**3)
                fj2 = -(tau[i]**6 - 3 * tau[i]**4 * tau[j]**2) * fi2
                fi2 *= (tau[j]**6 - 3 * tau[j]**4 * tau[i]**2)

                expi = exp(-tau[i] * d)
                expj = exp(-tau[j] * d)

                G[i, j] += \
                      expi*(fi1+fi2/d) \
                    + expj*(fj1+fj2/d)
                dG[i, j, :] += \
                    (   expi*(tau[i]*(fi1+fi2/d) + fi2/(d**2)) \
                      + expj*(tau[j]*(fj1+fj2/d) + fj2/(d**2)) )*n

    return G, dG
예제 #14
0
파일: fall.py 프로젝트: kgmstwo/THBCP
def fall(): 
    found_flower = False
    start_time = 0
    target_theta = 0
    my_color = -1
    beh.init(0.22, 40, 0.5, 0.1)
    state = STATE_IDLE
    color = 'r' #for flowers only

    def wander():
        state = STATE_WANDER
    def collect_pollen():
        state = STATE_COLLECT_POLLEN
        start_time = sys.time()
    def align_with(target):
        target_theta = target
        pose.set_pose(0,0,0)
        state = STATE_ALIGN
        start_time = sys.time()

    #motion_start_odo = pose.get_odometer()

    while True:
        beh.init(0.22, 40, 0.5, 0.1)

        new_nbrs = beh.update()
        nbrList = neighbors.get_neighbors()       
        if new_nbrs:
            print nbrList
        beh_out = beh.BEH_INACTIVE

        #FINITE STATE MACHINE
        if state == STATE_IDLE:
            leds.set_pattern('rb', 'group', LED_BRIGHTNESS)
            if rone.button_get_value('r'):
                state = STATE_MOVE_TO_FLOWER
            if rone.button_get_value('b'):
                state = STATE_QUEEN
            if new_nbrs:
                print "idle"

        elif state == STATE_WANDER: #run forward, avoid direction of neighbors
            nav_tower = hba.find_nav_tower_nbr(NAV_ID)
            if nav_tower == None:
                state = STATE_RETURN_TO_BASE
            else:
                beh_out = beh.avoid_nbr(nav_tower, MOTION_TV)

                (flower, color) = detflower(nbrList)
                if flower != None:
                    state = STATE_MOVE_TO_FLOWER

        elif state == STATE_MOVE_TO_FLOWER:
            leds.set_pattern('b', 'ramp_slow', LED_BRIGHTNESS)
            (flower, color) = detflower(nbrList)
            if flower != None:
                if (neighbors.get_nbr_range_bits(flower) > 6) or (beh.bump_angle_get() != None):
                    collect_pollen() #collect pollen if we bump or get close
                else:
                #otherwise keep following that flower
                    beh_out = beh.follow_nbr(flower, MOTION_TV)

        elif state == STATE_COLLECT_POLLEN:
            motion_start_odo = pose.get_odometer()
            if sys.time() > (collect_pollen_start_time + COLLECT_POLLEN_TIME):
                state = STATE_RETURN_TO_BASE
                found_flower = True
            elif sys.time() < (collect_pollen_start_time + BACK_UP_TIME):    
                tv = -MOTION_TV
                rv = 0
                beh_out = beh.tvrv(tv,rv) 
                turn_start_time = (collect_pollen_start_time + BACK_UP_TIME)

            elif sys.time() < (turn_start_time + TURN_TIME): 
                tv = 40
                rv = -MOTION_RV
                beh_out = beh.tvrv(tv,rv)

            else: 
                tv = MOTION_TV
                rv = (MOTION_RV - 300)
                beh_out = beh.tvrv(tv,rv)

        elif state == STATE_RETURN_TO_BASE:
            nav_tower = hba.find_nav_tower_nbr(NAV_ID)
            queen = find_queen(nbrList)
            if (nav_tower == None) and (queen == None):
                beh_out = (-MOTION_TV, 0, True)
            elif (nav_tower != None) and (queen == None):
                beh_out = beh.follow_nbr(nav_tower)
            elif neighbors.get_nbr_range_bits(queen) > 2:
                beh_out = beh.follow_nbr(queen, MOTION_TV)
            elif found_flower:
                state = STATE_RECRUIT
                start_time = sys.time()
            else:
                state = STATE_FOLLOW
                start_time = sys.time()

        elif state == STATE_FOLLOW:
            recruiter = find_recruiter()
            if recruiter == None:
                beh_out = beh.BEH_INACTIVE
                if sys.time() > (follow_start_time + FOLLOW_TIME):
                    wander()
            else:
                bearing = neighbors.get_nbr_bearing(recruiter)
                orientation = neighbors.get_nbr_orientation(recruiter)
                align_with(math.pi + bearing - orientation)

        elif state == STATE_GO:
            flower = detflower()
            if not flower == None:
                state = STATE_MOVE_TO_FLOWER
            beh_out = beh.tvrv(MOTION_TV, 0)

        elif state == STATE_RECRUIT:
            if sys.time() > (recruit_start_time + RECRUIT_TIME):
                align_with(pose.get_theta() - math.pi)

        elif state == STATE_ALIGN:
            tv = 0
            heading_error = math.normalize_angle(pose.get_theta() - target_theta)
            rv = ROTATE_RV_GAIN * heading_error
            beh_out = beh.tvrv(tv, rv)
            # you could actually do a running average in the list here
            small_error = hba.average_error_check(heading_error, [], HEADING_ERROR_LIMIT, new_nbrs)
            if new_nbrs:
                print "error", error_list
            if small_error:
                state = STATE_GO
        #END OF FINITE STATE MACHINE 

        bump_beh_out = beh.bump_beh(MOTION_TV)
        if state not in [STATE_RETURN_TO_BASE, STATE_COLLECT_POLLEN, STATE_RECRUIT]:
            beh_out = beh.subsume([beh_out, bump_beh_out])
        beh.motion_set(beh_out)
        hba.set_msg(state, my_color, 0)
예제 #15
0
def summer():
    beh.init(0.22, 40, 0.5, 0.1)

    state = STATE_IDLE

    while True:
        # run the system updates
        new_nbrs = beh.update()

        nbrList = neighbors.get_neighbors()
        if new_nbrs:
            print nbrList
        beh_out = beh.BEH_INACTIVE

        # this is the main finite-state machine
        if state == STATE_IDLE:
            leds.set_pattern('r', 'circle', LED_BRIGHTNESS)
            leds.set_pattern('b', 'circle', LED_BRIGHTNESS)
            if rone.button_get_value('r'):
                state = STATE_FIND_QUEEN
            if rone.button_get_value('b'):
                state = STATE_QUEEN
            if new_nbrs:
                print "idle"
        elif state == STATE_FIND_QUEEN:
            leds.set_pattern('r', 'ramp_slow', LED_BRIGHTNESS)
            beh_out = beh.tvrv(MOTION_TV, 0)
            queen = get_queen()
            if not queen == None:
                state = STATE_BUMP_QUEEN
            else:
                #go straight and hope for the best
                beh_out = beh.tvrv(MOTION_TV, 0)
        elif state == STATE_BUMP_QUEEN:
            leds.set_pattern('r', 'ramp_slow', LED_BRIGHTNESS)
            queen = get_queen()
            if queen == None:
                state = STATE_RETURN
            else:
                if (neighbors.get_nbr_range_bits(queen) >
                        6) or (beh.bump_angle_get() != None):
                    state = STATE_BACK_UP
                    start_time = sys.time()
                else:
                    beh_out = beh.follow_nbr(queen, MOTION_TV)
        elif state == STATE_BACK_UP:
            if sys.time() > start_time + BACK_UP_TIME:
                state = STATE_RETURN
            else:
                beh_out = beh.tvrv(-MOTION_TV, 0)
        elif state == STATE_RETURN:
            leds.set_pattern('r', 'circle', LED_BRIGHTNESS)
            if rone.button_get_value('r'):
                state = STATE_FIND_QUEEN
            queen = get_queen()
            if queen == None:
                state = STATE_IDLE
            else:
                beh_out = beh.avoid_nbr(queen, MOTION_TV)
        elif state == STATE_QUEEN:
            if new_nbrs:
                print 'Ich bin die Koenigin der welt!'

        # end of the FSM
        bump_beh_out = beh.bump_beh(MOTION_TV)
        if not state == STATE_QUEEN:
            beh_out = beh.subsume([beh_out, bump_beh_out])

        # set the beh velocities
        beh.motion_set(beh_out)

        #set the HBA message
        hba.set_msg(state, 0, 0)
예제 #16
0
파일: Message_Demo.py 프로젝트: va17/THBCP
def message_demo():
    beh.init(0.22, 40, 0.5, 0.1)

    state = STATE_LEADER

    num_r = 1
    num_g = 1
    num_b = 1
    button_red_old = 0
    button_green_old = 0
    button_blue_old = 0

    while True:
        # run the system updates
        new_nbrs = beh.update()
        nbr_list = neighbors.get_neighbors()

        # init the velocities
        beh_out = beh.BEH_INACTIVE

        # read the buttons and update the local counts
        (num_r, button_red_old) = check_button('r', num_r, button_red_old)
        (num_g, button_green_old) = check_button('g', num_g, button_green_old)
        (num_b, button_blue_old) = check_button('b', num_b, button_blue_old)

        # build this robot's neighbor message
        distance_local = num_r
        mode_local = num_g
        quality_local = num_b
        hba.set_msg(distance_local, mode_local, quality_local)

        # find the neighbor with the lowest ID
        nbr_leader = nbrList_getRobotWithLowID(nbr_list)

        # are you the leader?
        if nbr_leader == None:
            # no neighbors.  you are the leader
            state = STATE_LEADER
        else:
            low_ID = neighbors.get_nbr_id(nbr_leader)
            #            if new_nbrs:
            #                print 'nbr lowID=',nbr_leader
            if low_ID < rone.get_id():
                state = STATE_MINION
            else:
                state = STATE_LEADER

        # this is the main finite-state machine
        if state == STATE_LEADER:
            msg = (distance_local, mode_local, quality_local)
            if new_nbrs:
                print "leader:", msg
            brightness = LED_BRIGHTNESSER

        elif state == STATE_MINION:
            if nbr_leader != None:
                msg = hba.get_msg_from_nbr(nbr_leader, new_nbrs)
                if new_nbrs:
                    print "minion. leader = ", str(low_ID), " msg=", msg
            brightness = LED_BRIGHTNESS

        # end of the FSM
        # unpack the message and display it on the LEDs
        (distance, mode, quality) = msg
        leds.set_pattern((distance, mode, quality), 'count', brightness)

        # set the velocities
        beh.motion_set(beh_out)
예제 #17
0
from accuracy import get_accuracy
from neighbors import get_neighbors

# trainingSet = get_training_set()
# testSet = get_test_set()

# neighbors:
from response import get_response

trainingSetDemo = [[2, 2, 2, 'a'], [4, 4, 4, 'b']]
testSetDemo = [5, 5, 5]
k = 1
neighbors = get_neighbors(trainingSetDemo, testSetDemo, k)
print neighbors

# response:
neighborsDemo = [[1, 1, 1, 'a'], [2, 2, 2, 'a'], [3, 3, 3, 'b']]
response = get_response(neighbors)
print(response)

# accuracy:
testSetAccuracy = [[1, 1, 1, 'a'], [2, 2, 2, 'a'], [3, 3, 3, 'b']]
predictions = ['a', 'a,', 'a']

accuracy = get_accuracy(testSetAccuracy, predictions)
print(accuracy)
예제 #18
0
파일: fall.py 프로젝트: va17/THBCP
def fall():
    found_flower = False
    start_time = 0
    target_theta = 0
    my_color = -1
    beh.init(0.22, 40, 0.5, 0.1)
    state = STATE_IDLE
    color = 'r'  #for flowers only

    def wander():
        state = STATE_WANDER

    def collect_pollen():
        state = STATE_COLLECT_POLLEN
        start_time = sys.time()

    def align_with(target):
        target_theta = target
        pose.set_pose(0, 0, 0)
        state = STATE_ALIGN
        start_time = sys.time()

    #motion_start_odo = pose.get_odometer()

    while True:
        beh.init(0.22, 40, 0.5, 0.1)

        new_nbrs = beh.update()
        nbrList = neighbors.get_neighbors()
        if new_nbrs:
            print nbrList
        beh_out = beh.BEH_INACTIVE

        #FINITE STATE MACHINE
        if state == STATE_IDLE:
            leds.set_pattern('rb', 'group', LED_BRIGHTNESS)
            if rone.button_get_value('r'):
                state = STATE_MOVE_TO_FLOWER
            if rone.button_get_value('b'):
                state = STATE_QUEEN
            if new_nbrs:
                print "idle"

        elif state == STATE_WANDER:  #run forward, avoid direction of neighbors
            nav_tower = hba.find_nav_tower_nbr(NAV_ID)
            if nav_tower == None:
                state = STATE_RETURN_TO_BASE
            else:
                beh_out = beh.avoid_nbr(nav_tower, MOTION_TV)

                (flower, color) = detflower(nbrList)
                if flower != None:
                    state = STATE_MOVE_TO_FLOWER

        elif state == STATE_MOVE_TO_FLOWER:
            leds.set_pattern('b', 'ramp_slow', LED_BRIGHTNESS)
            (flower, color) = detflower(nbrList)
            if flower != None:
                if (neighbors.get_nbr_range_bits(flower) >
                        6) or (beh.bump_angle_get() != None):
                    collect_pollen()  #collect pollen if we bump or get close
                else:
                    #otherwise keep following that flower
                    beh_out = beh.follow_nbr(flower, MOTION_TV)

        elif state == STATE_COLLECT_POLLEN:
            motion_start_odo = pose.get_odometer()
            if sys.time() > (collect_pollen_start_time + COLLECT_POLLEN_TIME):
                state = STATE_RETURN_TO_BASE
                found_flower = True
            elif sys.time() < (collect_pollen_start_time + BACK_UP_TIME):
                tv = -MOTION_TV
                rv = 0
                beh_out = beh.tvrv(tv, rv)
                turn_start_time = (collect_pollen_start_time + BACK_UP_TIME)

            elif sys.time() < (turn_start_time + TURN_TIME):
                tv = 40
                rv = -MOTION_RV
                beh_out = beh.tvrv(tv, rv)

            else:
                tv = MOTION_TV
                rv = (MOTION_RV - 300)
                beh_out = beh.tvrv(tv, rv)

        elif state == STATE_RETURN_TO_BASE:
            nav_tower = hba.find_nav_tower_nbr(NAV_ID)
            queen = find_queen(nbrList)
            if (nav_tower == None) and (queen == None):
                beh_out = (-MOTION_TV, 0, True)
            elif (nav_tower != None) and (queen == None):
                beh_out = beh.follow_nbr(nav_tower)
            elif neighbors.get_nbr_range_bits(queen) > 2:
                beh_out = beh.follow_nbr(queen, MOTION_TV)
            elif found_flower:
                state = STATE_RECRUIT
                start_time = sys.time()
            else:
                state = STATE_FOLLOW
                start_time = sys.time()

        elif state == STATE_FOLLOW:
            recruiter = find_recruiter()
            if recruiter == None:
                beh_out = beh.BEH_INACTIVE
                if sys.time() > (follow_start_time + FOLLOW_TIME):
                    wander()
            else:
                bearing = neighbors.get_nbr_bearing(recruiter)
                orientation = neighbors.get_nbr_orientation(recruiter)
                align_with(math.pi + bearing - orientation)

        elif state == STATE_GO:
            flower = detflower()
            if not flower == None:
                state = STATE_MOVE_TO_FLOWER
            beh_out = beh.tvrv(MOTION_TV, 0)

        elif state == STATE_RECRUIT:
            if sys.time() > (recruit_start_time + RECRUIT_TIME):
                align_with(pose.get_theta() - math.pi)

        elif state == STATE_ALIGN:
            tv = 0
            heading_error = math.normalize_angle(pose.get_theta() -
                                                 target_theta)
            rv = ROTATE_RV_GAIN * heading_error
            beh_out = beh.tvrv(tv, rv)
            # you could actually do a running average in the list here
            small_error = hba.average_error_check(heading_error, [],
                                                  HEADING_ERROR_LIMIT,
                                                  new_nbrs)
            if new_nbrs:
                print "error", error_list
            if small_error:
                state = STATE_GO
        #END OF FINITE STATE MACHINE

        bump_beh_out = beh.bump_beh(MOTION_TV)
        if state not in [
                STATE_RETURN_TO_BASE, STATE_COLLECT_POLLEN, STATE_RECRUIT
        ]:
            beh_out = beh.subsume([beh_out, bump_beh_out])
        beh.motion_set(beh_out)
        hba.set_msg(state, my_color, 0)
예제 #19
0
def message_demo():
    beh.init(0.22, 40, 0.5, 0.1)

    state = STATE_LEADER

    num_r = 1
    num_g = 1
    num_b = 1
    button_red_old = 0
    button_green_old = 0
    button_blue_old = 0

    while True:
        # run the system updates
        new_nbrs = beh.update()
        nbr_list = neighbors.get_neighbors()

        # init the velocities
        beh_out = beh.BEH_INACTIVE

        # read the buttons and update the local counts
        (num_r, button_red_old) = check_button("r", num_r, button_red_old)
        (num_g, button_green_old) = check_button("g", num_g, button_green_old)
        (num_b, button_blue_old) = check_button("b", num_b, button_blue_old)

        # build this robot's neighbor message
        distance_local = num_r
        mode_local = num_g
        quality_local = num_b
        hba.set_msg(distance_local, mode_local, quality_local)

        # find the neighbor with the lowest ID
        nbr_leader = nbrList_getRobotWithLowID(nbr_list)

        # are you the leader?
        if nbr_leader == None:
            # no neighbors.  you are the leader
            state = STATE_LEADER
        else:
            low_ID = neighbors.get_nbr_id(nbr_leader)
            #            if new_nbrs:
            #                print 'nbr lowID=',nbr_leader
            if low_ID < rone.get_id():
                state = STATE_MINION
            else:
                state = STATE_LEADER

        # this is the main finite-state machine
        if state == STATE_LEADER:
            msg = (distance_local, mode_local, quality_local)
            if new_nbrs:
                print "leader:", msg
            brightness = LED_BRIGHTNESSER

        elif state == STATE_MINION:
            if nbr_leader != None:
                msg = hba.get_msg_from_nbr(nbr_leader, new_nbrs)
                if new_nbrs:
                    print "minion. leader = ", str(low_ID), " msg=", msg
            brightness = LED_BRIGHTNESS

        # end of the FSM
        # unpack the message and display it on the LEDs
        (distance, mode, quality) = msg
        leds.set_pattern((distance, mode, quality), "count", brightness)

        # set the velocities
        beh.motion_set(beh_out)
예제 #20
0
파일: Flower_Motion.py 프로젝트: va17/THBCP
def flower_motion():
    beh.init(0.22, 40, 0.5, 0.1)

    state = STATE_IDLE

    while True:
        # run the system updates
        new_nbrs = beh.update()
        
        nbrList = neighbors.get_neighbors()
        if new_nbrs:
            print nbrList
        beh_out = beh.BEH_INACTIVE
            
        # this is the main finite-state machine
        if state == STATE_IDLE:
            leds.set_pattern('r', 'circle', LED_BRIGHTNESS)
            if rone.button_get_value('r'):
                state = STATE_MOVE_TO_FLOWER
            if new_nbrs:
                print "idle"
            
        elif state == STATE_MOVE_TO_FLOWER:
            leds.set_pattern('b', 'ramp_slow', LED_BRIGHTNESS)
            if new_nbrs:
                print "move to flower"
           
            # Move towards the flower until you bump into it
            # for this demo, assume the first robot on the list is a flower
##            flower = nbrList_getFirstRobot(nbrList)
            (color,nbr) = detflower(nbrList)
            flower = nbr
            if flower != None:
                # Stop if we get close or bump into the flower
                #if neighbors.get_nbr_close_range(flower):
                if (neighbors.get_nbr_range_bits(flower) > 6) or (beh.bump_angle_get() != None):
                    state = STATE_COLLECT_POLLEN
                    collect_pollen_start_time = sys.time()
                else:
                    # Move to the flower
                    beh_out = beh.follow_nbr(flower, MOTION_TV)
                    #print beh_out

        elif state == STATE_COLLECT_POLLEN:
            # this is where you will put your clever pollen collection code
            # we will just wait for a second, then leave. (this will not collect very much pollen)
            leds.set_pattern('g', 'blink_fast', LED_BRIGHTNESS)
            if new_nbrs:
                print "collect"
            
            # Timeout after 5 seconds
            if sys.time() > (collect_pollen_start_time + COLLECT_POLLEN_TIME):
                state = STATE_MOVE_AWAY_FLOWER
            
            elif sys.time() < (collect_pollen_start_time + BACK_UP_TIME):    
                tv = -MOTION_TV
                rv = 0
                beh_out = beh.tvrv(tv,rv) 
                turn_start_time = (collect_pollen_start_time + BACK_UP_TIME)
                
            elif sys.time() < (turn_start_time + TURN_TIME): 
                tv = 0
                rv = -MOTION_RV
            
            else: 
                tv = MOTION_TV
                rv = MOTION_RV
                beh_out = beh.tvrv(tv,rv)
            
        elif state == STATE_MOVE_AWAY_FLOWER:
            if new_nbrs:
                print "avoid flower"
            leds.set_pattern('r', 'blink_slow', LED_BRIGHTNESS)
            if rone.button_get_value('r'):
                state = STATE_MOVE_TO_FLOWER

            # Move away from the flower until it is out of range
            flower = nbrList_getFirstRobot(nbrList)
            if flower != None:
                # Point away the flower
                beh_out = beh.avoid_nbr(flower, MOTION_TV)
            else:
                state = STATE_IDLE
                
        # end of the FSM
        bump_beh_out = beh.bump_beh(MOTION_TV)

        if state != STATE_COLLECT_POLLEN:
            beh_out = beh.subsume([beh_out, bump_beh_out])

        # set the beh velocities
        beh.motion_set(beh_out)

        #set the HBA message
        hba.set_msg(0, 0, 0)
예제 #21
0
파일: winter.py 프로젝트: va17/THBCP
def winter():
    beh.init(0.22, 40, 0.5, 0.1)

    state = STATE_IDLE

    manual_control = False

    while True:
        # run the system updates
        new_nbrs = beh.update()

        nbr_list = neighbors.get_neighbors()

        beh_out = beh.BEH_INACTIVE

        # this is the main finite-state machine
        if state == STATE_IDLE:
            leds.set_pattern('r', 'circle', LED_BRIGHTNESS)
            if new_nbrs:
                print "idle"

            if rone.button_get_value('r'):
                ##### This is one way to find a cutoff for being in light.
                ##### Make sure you press the 'r' button when the robot is
                ##### in the light!
                global BRIGHTNESS_THRESHOLDS
                for sensor_dir in BRIGHTNESS_THRESHOLDS.keys():
                    BRIGHTNESS_THRESHOLDS[
                        sensor_dir] = 0.85 * rone.light_sensor_get_value(
                            sensor_dir)
                #####
                initial_time = sys.time()
                state = STATE_LIGHT

        elif state == STATE_LIGHT:
            leds.set_pattern('g', 'circle', LED_BRIGHTNESS)
            if manual_control:
                leds.set_pattern('gr', 'group', LED_BRIGHTNESS)
            nbr_in_dark = get_nearest_nbr_in_dark(nbr_list)
            if nbr_in_dark != None:
                bearing = neighbors.get_nbr_bearing(nbr_in_dark)
                bearing = bearing - math.pi
                bearing = math2.normalize_angle(bearing)
                beh_out = move_in_dir(bearing)

            if not manual_control:
                if not self_in_light():
                    dark_start_time = sys.time()
                    state = STATE_DARK

            if rone.button_get_value('b'):
                manual_control = True
                dark_start_time = sys.time()
                state = STATE_DARK
            elif rone.button_get_value('r'):
                manual_control = False
                state = STATE_IDLE

        elif state == STATE_DARK:
            leds.set_pattern('b', 'circle', LED_BRIGHTNESS)
            if manual_control:
                leds.set_pattern('br', 'group', LED_BRIGHTNESS)
            nbrs_in_light = get_nbrs_in_light()
            nbrs_in_dark = get_nbrs_in_dark()
            if len(nbrs_in_light) > 0:
                bearing = get_avg_bearing_to_nbrs(nbrs_in_light)
                beh_out = move_in_dir(bearing)
            elif len(nbrs_in_dark) > 0:
                bearing = get_avg_bearing_to_nbrs(nbrs_in_dark)
                beh_out = move_in_dir(bearing)

            if not manual_control:
                if self_in_light():
                    state = STATE_LIGHT
                elif sys.time() - dark_start_time > LIFESPAN:
                    score_time = hba.winter_time_keeper(initial_time)
                    hba.winter_score_calc(score_time, LED_BRIGHTNESS)
                    state = STATE_DEAD
            if rone.button_get_value('g'):
                manual_control = True
                state = STATE_LIGHT
            elif rone.button_get_value('r'):
                manual_control = False
                state = STATE_IDLE

        elif state == STATE_DEAD:
            pass

        # end of the FSM

##        bump_beh_out = beh.bump_beh(MOTION_TV)
##        beh_out = beh.subsume([beh_out, bump_beh_out])

# set the beh velocities
        beh.motion_set(beh_out)

        #set the HBA message
        msg = [0, 0, 0]
        msg[MSG_IDX_STATE] = state
        hba.set_msg(msg[0], msg[1], msg[2])
예제 #22
0
def recruit_demo():
    beh.init(0.22, 40, 0.5, 0.1)

    state = STATE_IDLE
    
    while True:
        # run the system updates
        new_nbrs = beh.update()
        
        nbr_list = neighbors.get_neighbors()
        beh_out = beh.BEH_INACTIVE

        # this is the main finite-state machine
        if state == STATE_IDLE:
            leds.set_pattern('r', 'circle', LED_BRIGHTNESS)
            if rone.button_get_value('r'):
                state = STATE_MATCH_HEADING
                error_list = []
            if new_nbrs:
                print "idle"
                #print nbr_list
            
        elif state == STATE_MATCH_HEADING:
            leds.set_pattern('b', 'ramp_slow', LED_BRIGHTNESS)
            if new_nbrs:
                print "match heading"
           
            # match the heading with the first robot on your nbr list
            # use the average_error_check() function to wait until you get a accurate match
            # for this demo, assume the first robot on the list is a dancing_nbr that is recruiting you to a flower
            dancing_nbr = nbrList_getFirstRobot(nbr_list)
            if dancing_nbr != None:
                # rotate to face the "dancing" robot
                tv = 0
                (rv, heading_error) = match_nbr_heading(dancing_nbr)
                beh_out = beh.tvrv(tv, rv)
                small_error = hba.average_error_check(heading_error, error_list, HEADING_ERROR_LIMIT, new_nbrs)
                if new_nbrs:
                    print "error", error_list
                if small_error:
                    # We have a good heading match.  Go get pollen!
                    state = STATE_MOVE_TO_FLOWER
                    collect_pollen_start_odo = pose.get_odometer()

        elif state == STATE_MOVE_TO_FLOWER:
            # move forward
            beh_out = beh.tvrv(MOTION_TV, 0)
            
            # stop after a fixed distance_to_go
            distance_to_go = (collect_pollen_start_odo + MOVE_TO_FLOWER_DISTANCE) - pose.get_odometer() 
            if distance_to_go < 0:
                state = STATE_IDLE

            if new_nbrs:
                print "move to flower dist:", distance_to_go
            leds.set_pattern('g', 'blink_fast', LED_BRIGHTNESS)

        # end of the FSM
                        
        # set the beh velocities
        beh.motion_set(beh_out)
        
        #set the HBA message
        hba.set_msg(0, 0, 0)
예제 #23
0
파일: spring.py 프로젝트: kgmstwo/THBCP
def spring():
    at_tree_odo = None
    tree_pose = None
    followers = 0
    have_seen_leader = False
    beh.init(0.22, 40, 0.5, 0.1)
    motion.init_rv(1000, MOTION_RV, MOTION_CAPTURE_DISTANCE, MOTION_RELEASE_DISTANCE
            , MOTION_CAPTURE_ANGLE, MOTION_RELEASE_ANGLE)
    state = STATE_IDLE

    while True:
        # run the system updates
        new_nbrs = beh.update()
        nbr_list = neighbors.get_neighbors()
        if new_nbrs:
            print state
            
        beh_out = beh.BEH_INACTIVE

        # set colors, because why not do it at the top
        color_counts = [0, 0, 0]
        for i in range(3):
            color_counts[i] = min([5, (state - 5 * i)])
        if state == STATE_IDLE:
            leds.set_pattern('rb', 'group', LED_BRIGHTNESS)
        elif state == STATE_SUCCESS:
            leds.set_pattern('g', 'circle', LED_BRIGHTNESS)
        else:
            leds.set_pattern(color_counts, 'count', LED_BRIGHTNESS)

        if rone.button_get_value('g'):
            tree_pose = None
            followers = 0
            have_seen_leader = False
            state = STATE_IDLE
            
        # this is the main finite-state machine
        if not state in [STATE_IDLE, STATE_LEADER, STATE_SUCCESS, STATE_FOLLOW]:
            for nbr in nbr_list:
                nbr_state = hba.get_msg_from_nbr(nbr, new_nbrs)[MSG_IDX_STATE]
                if nbr_state in [STATE_LEADER, STATE_SUCCESS]:
                    start_time = sys.time()
                    state = STATE_FOLLOW
                    
        if state == STATE_IDLE:

            if rone.button_get_value('r'):
                pose.set_pose(0, 0, 0)
                state = STATE_WANDER
            elif rone.button_get_value('b'):
                state = STATE_QUEEN

        elif state == STATE_QUEEN:
            pass

        elif state == STATE_WANDER:
            ##            leds.set_pattern('r', 'circle', LED_BRIGHTNESS)
            nav = hba.find_nav_tower_nbr(NAV_ID)
            beh_out = beh.avoid_nbr(nav, MOTION_TV)
            queen = None
            for nbr in nbr_list:
                nbr_state = hba.get_msg_from_nbr(nbr, new_nbrs)[MSG_IDX_STATE]
                if nbr_state == STATE_QUEEN:
                    queen = nbr

            if bump_front():
                if queen != None:
                    state = STATE_SUCCESS
                else:
                    tree_pose = pose.get_pose()
                    motion.set_goal((0.0, 0.0), MOTION_TV)
                    at_tree_odo = pose.get_odometer()
                    state = STATE_RETURN
            elif nav == None:
                motion.set_goal((0.0, 0.0), MOTION_TV)
                state = STATE_RETURN

        elif state == STATE_RETURN:
            ##            nav_tower = hba.find_nav_tower_nbr(NAV_ID)
            queen = None
            recruiter = None
            for nbr in nbr_list:
                nbr_state = hba.get_msg_from_nbr(nbr, new_nbrs)[MSG_IDX_STATE]
                if nbr_state == STATE_QUEEN:
                    queen = nbr
                elif nbr_state == STATE_RECRUIT:
                    recruiter = nbr
            if queen != None:
                if (recruiter == None) and (tree_pose != None) and \
                close_to_nbr(queen):
                    start_time = sys.time()
                    dist_traveled = pose.get_odometer() - at_tree_odo
                    at_queen_odo = pose.get_odometer()
                    state = STATE_RECRUIT
                elif not closer_to_nbr(queen):
                    beh_out = beh.follow_nbr(queen, MOTION_TV)
                else:
                    start_time = sys.time()
                    state = STATE_FOLLOW
            else:
                (tv, rv) = motion.update()
                beh_out = beh.tvrv(tv, rv)

        elif state == STATE_RECRUIT:
            new_followers = 0
            for nbr in nbr_list:
                nbr_state = hba.get_msg_from_nbr(nbr,new_nbrs)[MSG_IDX_STATE]
                if nbr_state == STATE_RECRUIT:
                    if neighbors.get_nbr_id(nbr) > rone.get_id():
                        state = STATE_FOLLOW
                elif nbr_state in [STATE_FOLLOW, STATE_QUEEN]:
                    new_followers += 1
            if new_followers > followers:
                print 'reset timer'
                start_time = sys.time()
            followers = max([followers, new_followers])
            if followers == 4 or sys.time() > start_time + WAIT_TIME:
                tree_pos = (tree_pose[0], tree_pose[1])
                motion.set_goal(tree_pos, MOTION_TV)
                state = STATE_LEADER

        elif state == STATE_FOLLOW: 
            recruiter = None
            leader = None
            success = False
            new_followers = 1
            for nbr in nbr_list:
                nbr_state = hba.get_msg_from_nbr(nbr,new_nbrs)[MSG_IDX_STATE]
                if nbr_state == STATE_RECRUIT:
                    recruiter = nbr
                elif nbr_state == STATE_LEADER:
                    leader = nbr
                elif nbr_state == STATE_SUCCESS:
                    leader = nbr
                    success = True
                elif nbr_state in [STATE_FOLLOW, STATE_WANDER]:
                    new_followers += 1
            if success:
                have_seen_leader = True
            if new_followers > followers:
                start_time = sys.time()
            followers = max([followers, new_followers])

            if recruiter == None:
                if leader == None:
                    if have_seen_leader:
                        beh_out = beh.tvrv(MOTION_TV, 0)
                    elif followers == 5 or sys.time() > start_time + WAIT_TIME:
                        followers = 0
                        state = STATE_WANDER
                else:
                    if success and bump() and close_to_nbr(leader):
                        state = STATE_SUCCESS
                    beh_out = beh.follow_nbr(leader, MOTION_TV)
            
        elif state == STATE_LEADER:
##            (tv, rv) = motion.update()
##            beh_out = beh.tvrv(tv, rv)
##            if motion.is_done():
##                state = STATE_SUCCESS
            beh_out = beh.tvrv(-MOTION_TV, 0)

            if bump() or (pose.get_odometer() - at_queen_odo) > dist_traveled:
                state = STATE_SUCCESS

        elif state == STATE_SUCCESS:
            pass
        
        # end of the FSM
        
        if state not in [STATE_IDLE, STATE_RECRUIT, STATE_LEADER, STATE_SUCCESS, STATE_QUEEN]:
            bump_beh_out = beh.bump_beh(MOTION_TV)
            beh_out = beh.subsume([beh_out, bump_beh_out])

        # set the beh velocities
        beh.motion_set(beh_out)

        #set the HBA message
        msg = [0, 0, 0]
        msg[MSG_IDX_STATE] = state
        hba.set_msg(msg[0], msg[1], msg[2])
예제 #24
0
파일: summer.py 프로젝트: kgmstwo/THBCP
def summer():
    beh.init(0.22, 40, 0.5, 0.1)

    state = STATE_IDLE

    while True:
        # run the system updates
        new_nbrs = beh.update()

        nbrList = neighbors.get_neighbors()
        if new_nbrs:
            print nbrList
        beh_out = beh.BEH_INACTIVE

        # this is the main finite-state machine
        if state == STATE_IDLE:
            leds.set_pattern('r', 'circle', LED_BRIGHTNESS)
            leds.set_pattern('b', 'circle', LED_BRIGHTNESS)
            if rone.button_get_value('r'):
                state = STATE_FIND_QUEEN
            if rone.button_get_value('b'):
                state = STATE_QUEEN
            if new_nbrs:
                print "idle"
        elif state == STATE_FIND_QUEEN:
            leds.set_pattern('r', 'ramp_slow', LED_BRIGHTNESS)
            beh_out = beh.tvrv(MOTION_TV, 0)
            queen = get_queen()
            if not queen == None:
                state = STATE_BUMP_QUEEN
            else:
                #go straight and hope for the best
                beh_out = beh.tvrv(MOTION_TV, 0)  
        elif state == STATE_BUMP_QUEEN:
            leds.set_pattern('r', 'ramp_slow', LED_BRIGHTNESS)
            queen = get_queen()
            if queen == None:
                state = STATE_RETURN
            else:
                if (neighbors.get_nbr_range_bits(queen) > 6) or (beh.bump_angle_get() != None):
                    state = STATE_BACK_UP
                    start_time = sys.time()
                else:
                    beh_out = beh.follow_nbr(queen, MOTION_TV)
        elif state == STATE_BACK_UP:
            if sys.time() > start_time + BACK_UP_TIME:
                state = STATE_RETURN
            else:
                beh_out = beh.tvrv(-MOTION_TV, 0)
        elif state == STATE_RETURN:
            leds.set_pattern('r', 'circle', LED_BRIGHTNESS)
            if rone.button_get_value('r'):
                state = STATE_FIND_QUEEN
            queen = get_queen()
            if queen == None:
                state = STATE_IDLE
            else:
                beh_out = beh.avoid_nbr(queen, MOTION_TV)
        elif state == STATE_QUEEN:
            if new_nbrs:
                print 'Ich bin die Koenigin der welt!'

        # end of the FSM
        bump_beh_out = beh.bump_beh(MOTION_TV)
        if not state == STATE_QUEEN:
            beh_out = beh.subsume([beh_out, bump_beh_out])

        # set the beh velocities
        beh.motion_set(beh_out)

        #set the HBA message
        hba.set_msg(state, 0, 0)
예제 #25
0
def get_Slater_gamma_correction(a, U, FWHM=None,
                                cutoff=None, accuracy_goal=12):
    """
    Slater-type charge distribution.
    See: M. Elstner et al., Phys. Rev. B 58, 7260 (1998)
    """
    min_U = np.min(U)
    if min_U <= 0.0:
        raise ValueError("Minimum U (%f) smaller than or equal to zero. " %
                         min_U)

    if cutoff is None and not a.is_cluster():
        # Estimate a cutoff from the accuracy goal if the
        # system is periodic and no cutoff was given
        cutoff = sqrt(log(10.0)*accuracy_goal/(sqrt(pi/2)*min_U))

    tau = 16*np.asarray(U)/5

    il, jl, dl, nl = get_neighbors(a, cutoff)

    nat = len(a)
    G   = np.zeros([nat, nat], dtype=float)
    dG  = np.zeros([nat, nat, 3], dtype=float)
    G[diag_indices_from(G)] = U

    if il is not None:
        for i, j, d, n in zip(il, jl, dl/Bohr, nl):
            if abs(tau[i] - tau[j]) < 1e-6:
                src = 1.0/(tau[i]+tau[j])
                fac = tau[i]*tau[j]*src
                avg = 1.6*(fac+fac*fac*src)
                fac = avg*d
                fac2 = fac*fac
                efac = exp(-fac)/(48*d)
                h = -(48 + 33*fac + fac2*(9+fac))*efac
                G[i, j] += \
                    h
                dG[i, j, :] += \
                    (   h/d \
                      + avg*h \
                      + (33*avg + 18*fac*avg + 3*fac2*avg)*efac )*n
            else:
                fi1  = 1.0/(2*(tau[i]**2-tau[j]**2)**2)
                fj1  = -tau[i]**4*tau[j]*fi1
                fi1 *= -tau[j]**4*tau[i]

                fi2  = 1.0/((tau[i]**2-tau[j]**2)**3)
                fj2  = -(tau[i]**6-3*tau[i]**4*tau[j]**2)*fi2
                fi2 *=  (tau[j]**6-3*tau[j]**4*tau[i]**2)

                expi = exp(-tau[i]*d)
                expj = exp(-tau[j]*d)

                G[i, j] += \
                      expi*(fi1+fi2/d) \
                    + expj*(fj1+fj2/d)
                dG[i, j, :] += \
                    (   expi*(tau[i]*(fi1+fi2/d) + fi2/(d**2)) \
                      + expj*(tau[j]*(fj1+fj2/d) + fj2/(d**2)) )*n

    return G, dG
예제 #26
0
def recruit_demo():
    beh.init(0.22, 40, 0.5, 0.1)

    state = STATE_IDLE

    while True:
        # run the system updates
        new_nbrs = beh.update()

        nbr_list = neighbors.get_neighbors()
        beh_out = beh.BEH_INACTIVE

        # this is the main finite-state machine
        if state == STATE_IDLE:
            leds.set_pattern('r', 'circle', LED_BRIGHTNESS)
            if rone.button_get_value('r'):
                state = STATE_MATCH_HEADING
                error_list = []
            if new_nbrs:
                print "idle"
                #print nbr_list

        elif state == STATE_MATCH_HEADING:
            leds.set_pattern('b', 'ramp_slow', LED_BRIGHTNESS)
            if new_nbrs:
                print "match heading"

            # match the heading with the first robot on your nbr list
            # use the average_error_check() function to wait until you get a accurate match
            # for this demo, assume the first robot on the list is a dancing_nbr that is recruiting you to a flower
            dancing_nbr = nbrList_getFirstRobot(nbr_list)
            if dancing_nbr != None:
                # rotate to face the "dancing" robot
                tv = 0
                (rv, heading_error) = match_nbr_heading(dancing_nbr)
                beh_out = beh.tvrv(tv, rv)
                small_error = hba.average_error_check(heading_error,
                                                      error_list,
                                                      HEADING_ERROR_LIMIT,
                                                      new_nbrs)
                if new_nbrs:
                    print "error", error_list
                if small_error:
                    # We have a good heading match.  Go get pollen!
                    state = STATE_MOVE_TO_FLOWER
                    collect_pollen_start_odo = pose.get_odometer()

        elif state == STATE_MOVE_TO_FLOWER:
            # move forward
            beh_out = beh.tvrv(MOTION_TV, 0)

            # stop after a fixed distance_to_go
            distance_to_go = (collect_pollen_start_odo +
                              MOVE_TO_FLOWER_DISTANCE) - pose.get_odometer()
            if distance_to_go < 0:
                state = STATE_IDLE

            if new_nbrs:
                print "move to flower dist:", distance_to_go
            leds.set_pattern('g', 'blink_fast', LED_BRIGHTNESS)

        # end of the FSM

        # set the beh velocities
        beh.motion_set(beh_out)

        #set the HBA message
        hba.set_msg(0, 0, 0)