def __init__(self, configurator, motors_object):

        print('Initializing ProximityManager..')

        #Check configurazione
        if configurator is None:
            raise Exception('No configuration received')
            return

        #Check istanza classe Motors
        if motors_object is None:
            raise Exception('Motors object cannot be null')
            return

        #Reference istanza oggetto classe Motors
        self.motors_object = motors_object

        #Inizializzazione oggetto classe Proximity
        self.proximity = Proximity(configurator)
        print('Initializing proximity sensors..')
Exemple #2
0
 def menu_item_selected(self):
     """Select the current menu item"""
     # If ANYTHING selected, we gracefully
     # kill any challenge threads open
     self.stop_threads()
     if self.menu[self.menu_state]=="Remote Control":
         # Start the remote control
         logging.info("Entering into Remote Control Mode")
         self.challenge = rc.rc(self.drive, self.wiimote)
         # Create and start a new thread running the remote control script
         self.challenge_thread = threading.Thread(target=self.challenge.run)
         self.challenge_thread.start()
         # Ensure we know what challenge is running
         if self.challenge:
             self.challenge_name = self.menu[self.menu_state]
         # Move menu index to quit challenge by default
         self.menu_state = self.menu_quit_challenge
     elif self.menu[self.menu_state]=="Three Point Turn":
         # Start the three point turn challenge
         logging.info("Starting Three Point Turn Challenge")
         self.challenge = ThreePointTurn(self.drive)
         # Create and start a new thread running the remote control script
         self.challenge_thread = threading.Thread(target=self.challenge.run)
         self.challenge_thread.start()
         # Ensure we know what challenge is running
         if self.challenge:
             self.challenge_name = self.menu[self.menu_state]
         # Move menu index to quit challenge by default
         self.menu_state = self.menu_quit_challenge
     elif self.menu[self.menu_state]=="Straight Line Speed":
         # Start the straight line speed challenge
         logging.info("Starting Straight Line Speed Challenge")
         self.challenge = StraightLineSpeed(self.drive)
         # Ensure we know what challenge is running
         if self.challenge:
             self.challenge_name = self.menu[self.menu_state]
         # Move menu index to quit challenge by default
         self.menu_state = self.menu_quit_challenge
     elif self.menu[self.menu_state]=="Line Following":
         # Start the Line Following challenge
         logging.info("Starting Line Following Challenge")
         self.challenge = LineFollowing(self.drive)
         # Ensure we know what challenge is running
         if self.challenge:
             self.challenge_name = self.menu[self.menu_state]
         # Move menu index to quit challenge by default
         self.menu_state = self.menu_quit_challenge
     elif self.menu[self.menu_state]=="Proximity":
         # Start the Proximity challenge
         logging.info("Starting Proximity Challenge")
         self.challenge = Proximity(self.drive)
         # Ensure we know what challenge is running
         if self.challenge:
             self.challenge_name = self.menu[self.menu_state]
         # Move menu index to quit challenge by default
         self.menu_state = self.menu_quit_challenge        
     elif self.menu[self.menu_state]=="Quit Challenge":
         # Reset menu item back to top of list
         self.menu_state = 0
         logging.info("No Challenge Challenge Thread")
     elif self.menu[self.menu_state]=="Power Off Pi":
         # Power off the raspberry pi safely
         # by sending shutdown command to terminal
         logging.info("Shutting Down Pi")
         os.system("sudo shutdown -h now")
         self.shutting_down = True
Exemple #3
0
class launcher:
    def __init__(self):
        # Need a state set for this launcher.
        self.menu = ["Remote Control"]
        self.menu += ["Three Point Turn"]
        self.menu += ["Straight Line Speed"]
        self.menu += ["Line Following"]
        self.menu += ["Proximity"]
        self.menu += ["Quit Challenge"]
        self.menu += ["Power Off Pi"]

        self.menu_quit_challenge = 3

        # default menu item is remote control
        self.menu_state = 0
        self.menu_button_pressed = False
        self.drive = None
        self.wiimote = None
        # Current Challenge
        self.challenge = None
        self.challenge_name = ""

        GPIO.setwarnings(False)
        self.GPIO = GPIO

        # LCD Display
        self.lcd = Adafruit_CharLCD( pin_rs=25, pin_e=24, pins_db=[23, 17, 27, 22], GPIO=self.GPIO )
        self.lcd.begin(16, 1)
        self.lcd.clear()
        self.lcd.message('Initiating...')
        self.lcd_loop_skip = 5
        # Shutting down status
        self.shutting_down = False

    def menu_item_selected(self):
        """Select the current menu item"""
        # If ANYTHING selected, we gracefully
        # kill any challenge threads open
        self.stop_threads()
        if self.menu[self.menu_state]=="Remote Control":
            # Start the remote control
            logging.info("Entering into Remote Control Mode")
            self.challenge = rc.rc(self.drive, self.wiimote)
            # Create and start a new thread running the remote control script
            self.challenge_thread = threading.Thread(target=self.challenge.run)
            self.challenge_thread.start()
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state]=="Three Point Turn":
            # Start the three point turn challenge
            logging.info("Starting Three Point Turn Challenge")
            self.challenge = ThreePointTurn(self.drive)
            # Create and start a new thread running the remote control script
            self.challenge_thread = threading.Thread(target=self.challenge.run)
            self.challenge_thread.start()
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state]=="Straight Line Speed":
            # Start the straight line speed challenge
            logging.info("Starting Straight Line Speed Challenge")
            self.challenge = StraightLineSpeed(self.drive)
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state]=="Line Following":
            # Start the Line Following challenge
            logging.info("Starting Line Following Challenge")
            self.challenge = LineFollowing(self.drive)
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state]=="Proximity":
            # Start the Proximity challenge
            logging.info("Starting Proximity Challenge")
            self.challenge = Proximity(self.drive)
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge        
        elif self.menu[self.menu_state]=="Quit Challenge":
            # Reset menu item back to top of list
            self.menu_state = 0
            logging.info("No Challenge Challenge Thread")
        elif self.menu[self.menu_state]=="Power Off Pi":
            # Power off the raspberry pi safely
            # by sending shutdown command to terminal
            logging.info("Shutting Down Pi")
            os.system("sudo shutdown -h now")
            self.shutting_down = True

    def set_neutral(self, drive, wiimote):
        """Simple method to ensure motors are disabled"""
        if drive:
            drive.set_neutral()
            drive.disable_drive()
        if wiimote is not None:
            # turn on leds on wii remote
            wiimote.led = 2

    def set_drive(self, drive, wiimote):
        """Simple method to highlight that motors are enabled"""
        if wiimote is not None:
            # turn on leds on wii remote
            #turn on led to show connected
            drive.enable_drive()
            wiimote.led = 1

    def stop_threads(self):
        """Method neatly closes any open threads started by this class"""
        if self.challenge:
            self.challenge.stop()
            self.challenge = None
            self.challenge_thread = None
            logging.info("Stopping Challenge Thread")
        else:
            logging.info("No Challenge Challenge Thread")
        # Safety setting
        self.set_neutral(self.drive, self.wiimote)

    def run(self):
        """ Main Running loop controling bot mode and menu state """
        # Tell user how to connect wiimote
        self.lcd.clear()
        self.lcd.message( 'Press 1+2 \n' )
        self.lcd.message( 'On Wiimote' )

        # Initiate the drivetrain
        self.drive = drivetrain.DriveTrain(pwm_i2c=0x40)
        self.wiimote = None
        try:
            self.wiimote = Wiimote()

        except WiimoteException:
            logging.error("Could not connect to wiimote. please try again")

        if not self.wiimote:
            # Tell user how to connect wiimote
            self.lcd.clear()
            self.lcd.message( 'Wiimote \n' )
            self.lcd.message( 'Not Found' + '\n' )

        # Constantly check wiimote for button presses
        loop_count = 0
        while self.wiimote:
            buttons_state = self.wiimote.get_buttons()
            nunchuk_buttons_state = self.wiimote.get_nunchuk_buttons()
            joystick_state = self.wiimote.get_joystick_state()

#            logging.info("joystick_state: {0}".format(joystick_state))
#            logging.info("button state {0}".format(buttons_state))
            # Always show current menu item
            # logging.info("Menu: " + self.menu[self.menu_state])

            if loop_count >= self.lcd_loop_skip:
                # Reset loop count if over
                loop_count = 0

                self.lcd.clear()
                if self.shutting_down:
                    # How current menu item on LCD
                    self.lcd.message( 'Shutting Down Pi' + '\n' )
                else:
                    # How current menu item on LCD
                    self.lcd.message( self.menu[self.menu_state] + '\n' )

                    # If challenge is running, show it on line 2
                    if self.challenge:
                        self.lcd.message( '[' + self.challenge_name + ']' )

            # Increment Loop Count
            loop_count = loop_count + 1

            # Test if B button is pressed
            if joystick_state is None or (buttons_state & cwiid.BTN_B) or (nunchuk_buttons_state & cwiid.NUNCHUK_BTN_Z):
                # No nunchuk joystick detected or B or Z button
                # pressed, must go into neutral for safety
                logging.info("Neutral")
                self.set_neutral(self.drive, self.wiimote)
            else:
                # Enable motors
                self.set_drive(self.drive, self.wiimote)

            if ((buttons_state & cwiid.BTN_A)
                or (buttons_state & cwiid.BTN_UP)
                or (buttons_state & cwiid.BTN_DOWN)):
                # Looking for state change only
                if not self.menu_button_pressed and (buttons_state & cwiid.BTN_A):
                    # User wants to select a menu item
                    self.menu_item_selected()
                elif not self.menu_button_pressed and (buttons_state & cwiid.BTN_UP):
                    # Decrement menu index
                    self.menu_state = self.menu_state - 1
                    if self.menu_state < 0:
                        # Loop back to end of list
                        self.menu_state = len(self.menu)-1
                    logging.info("Menu item: {0}".format(self.menu[self.menu_state]))
                elif not self.menu_button_pressed and (buttons_state & cwiid.BTN_DOWN):
                    # Increment menu index
                    self.menu_state = self.menu_state + 1
                    if self.menu_state >= len(self.menu):
                        # Loop back to start of list
                        self.menu_state = 0
                    logging.info("Menu item: {0}".format(self.menu[self.menu_state]))

                # Only change button state AFTER we have used it
                self.menu_button_pressed = True
            else:
                # No menu buttons pressed
                self.menu_button_pressed = False

            time.sleep(0.05)
def main():
    torch.manual_seed(args.seed)
    os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
    use_gpu = torch.cuda.is_available()
    if args.use_cpu: use_gpu = False

    sys.stdout = Logger(
        osp.join(args.save_dir, 'log_' + 'CIFAR-10_PC_Loss' + '.txt'))

    if use_gpu:
        print("Currently using GPU: {}".format(args.gpu))
        cudnn.benchmark = True
        torch.cuda.manual_seed_all(args.seed)
    else:
        print("Currently using CPU")

    # Data Load
    num_classes = 10
    print('==> Preparing dataset')
    transform_train = transforms.Compose([
        transforms.RandomCrop(32, padding=4),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize((0.4914, 0.4822, 0.4465),
                             (0.2023, 0.1994, 0.2010)),
    ])

    transform_test = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize((0.4914, 0.4822, 0.4465),
                             (0.2023, 0.1994, 0.2010)),
    ])

    trainset = torchvision.datasets.CIFAR10(root='./data/cifar10',
                                            train=True,
                                            download=True,
                                            transform=transform_train)
    trainloader = torch.utils.data.DataLoader(trainset,
                                              batch_size=args.train_batch,
                                              pin_memory=True,
                                              shuffle=True,
                                              num_workers=args.workers)

    testset = torchvision.datasets.CIFAR10(root='./data/cifar10',
                                           train=False,
                                           download=True,
                                           transform=transform_test)
    testloader = torch.utils.data.DataLoader(testset,
                                             batch_size=args.test_batch,
                                             pin_memory=True,
                                             shuffle=False,
                                             num_workers=args.workers)

    # Loading the Model
    model = resnet(num_classes=num_classes, depth=110)

    if True:
        model = nn.DataParallel(model).cuda()

    criterion_xent = nn.CrossEntropyLoss()
    criterion_prox_1024 = Proximity(num_classes=num_classes,
                                    feat_dim=1024,
                                    use_gpu=use_gpu)
    criterion_prox_256 = Proximity(num_classes=num_classes,
                                   feat_dim=256,
                                   use_gpu=use_gpu)

    criterion_conprox_1024 = Con_Proximity(num_classes=num_classes,
                                           feat_dim=1024,
                                           use_gpu=use_gpu)
    criterion_conprox_256 = Con_Proximity(num_classes=num_classes,
                                          feat_dim=256,
                                          use_gpu=use_gpu)

    optimizer_model = torch.optim.SGD(model.parameters(),
                                      lr=args.lr_model,
                                      weight_decay=1e-04,
                                      momentum=0.9)

    optimizer_prox_1024 = torch.optim.SGD(criterion_prox_1024.parameters(),
                                          lr=args.lr_prox)
    optimizer_prox_256 = torch.optim.SGD(criterion_prox_256.parameters(),
                                         lr=args.lr_prox)

    optimizer_conprox_1024 = torch.optim.SGD(
        criterion_conprox_1024.parameters(), lr=args.lr_conprox)
    optimizer_conprox_256 = torch.optim.SGD(criterion_conprox_256.parameters(),
                                            lr=args.lr_conprox)

    filename = 'Models_Softmax/CIFAR10_Softmax.pth.tar'
    checkpoint = torch.load(filename)

    model.load_state_dict(checkpoint['state_dict'])
    optimizer_model.load_state_dict = checkpoint['optimizer_model']

    start_time = time.time()

    for epoch in range(args.max_epoch):

        adjust_learning_rate(optimizer_model, epoch)
        adjust_learning_rate_prox(optimizer_prox_1024, epoch)
        adjust_learning_rate_prox(optimizer_prox_256, epoch)

        adjust_learning_rate_conprox(optimizer_conprox_1024, epoch)
        adjust_learning_rate_conprox(optimizer_conprox_256, epoch)

        print("==> Epoch {}/{}".format(epoch + 1, args.max_epoch))
        train(model, criterion_xent, criterion_prox_1024, criterion_prox_256,
              criterion_conprox_1024, criterion_conprox_256, optimizer_model,
              optimizer_prox_1024, optimizer_prox_256, optimizer_conprox_1024,
              optimizer_conprox_256, trainloader, use_gpu, num_classes, epoch)

        if args.eval_freq > 0 and (epoch + 1) % args.eval_freq == 0 or (
                epoch + 1) == args.max_epoch:
            print("==> Test")  #Tests after every 10 epochs
            acc, err = test(model, testloader, use_gpu, num_classes, epoch)
            print("Accuracy (%): {}\t Error rate (%): {}".format(acc, err))

            state_ = {
                'epoch': epoch + 1,
                'state_dict': model.state_dict(),
                'optimizer_model': optimizer_model.state_dict(),
                'optimizer_prox_1024': optimizer_prox_1024.state_dict(),
                'optimizer_prox_256': optimizer_prox_256.state_dict(),
                'optimizer_conprox_1024': optimizer_conprox_1024.state_dict(),
                'optimizer_conprox_256': optimizer_conprox_256.state_dict(),
            }

            torch.save(state_, 'Models_PCL/CIFAR10_PCL.pth.tar')

    elapsed = round(time.time() - start_time)
    elapsed = str(datetime.timedelta(seconds=elapsed))
    print("Finished. Total elapsed time (h:m:s): {}".format(elapsed))
class ProximityManager:

    #Oggetto classe Proximity
    proximity = None

    #Variabili direzionali
    front_availability = None
    left_availability = None
    right_availability = None

    #Reference all'istanza della classe Motors
    motors_object = None

    #Dizionario misurazioni
    measurements = {}

    #Distanze ostacoli
    out_of_range_distance = float(150)  #1,5m
    critical_distance = float(20)  #20 cm

    def getMeasurements(self):
        return self.measurements

    def getFrontAvailability(self):
        return self.front_availability

    def getLeftAvailability(self):
        return self.left_availability

    def getRightAvailability(self):
        return self.right_availability

    def getFrontStopDistance(self):
        return self.front_stop_distance

    def getLeftStopDistance(self):
        return self.left_stop_distance

    def getRightStopDistance(self):
        return self.right_stop_distance

    def setFrontAvailability(self, value):
        self.front_availability = value

    def setLeftAvailability(self, value):
        self.left_availability = value

    def setRightAvailability(self, value):
        self.right_availability = value

    def setFrontStopDistance(self, value):
        self.front_stop_distance = value

    def setLeftStopDistance(self, value):
        self.left_stop_distance = value

    def setRightStopDistance(self, value):
        self.right_stop_distance = value

    def getAvailability(self):
        directions_availability = {
            'LEFT': self.left_availability,
            'FRONT': self.front_availability,
            'RIGHT': self.right_availability
        }
        return directions_availability

    def getStringifyMeasurements(self):

        if self.measurements is None:
            return

        return str(self.measurements.get('LEFT')) + ', ' + str(
            self.measurements.get('FRONT')) + ', ' + str(
                self.measurements.get('RIGHT'))

    def __init__(self, configurator, motors_object):

        print('Initializing ProximityManager..')

        #Check configurazione
        if configurator is None:
            raise Exception('No configuration received')
            return

        #Check istanza classe Motors
        if motors_object is None:
            raise Exception('Motors object cannot be null')
            return

        #Reference istanza oggetto classe Motors
        self.motors_object = motors_object

        #Inizializzazione oggetto classe Proximity
        self.proximity = Proximity(configurator)
        print('Initializing proximity sensors..')

    def retrieveProximityData(self):

        print('Getting measurements for all directions..')
        self.measurements = self.proximity.getDistance()

        print('Measurements: ' + str(self.measurements))

        #Check caso di errore
        if self.measurements is None:

            print('Error while getting measurements')
            raise proximityMeasurementErrorException(
                'Error while getting proximity measurements')
            self.front_availability = False
            self.left_availability = False
            self.right_availability = False

        else:

            if self.measurements.get('FRONT') is None:

                self.front_availability = False

                #Check caso in cui la direzione motori sia FORWARD e direzione FRONT bloccata
                if self.motors_object.getMotorsStatus(
                ) == self.motors_object.FORWARD:

                    print('Stopping front measurement None')
                    self.motors_object.stop()

                raise proximityMeasurementErrorException('FRONT measure None')

            elif self.measurements.get('FRONT') > self.critical_distance:
                self.front_availability = True
            elif self.measurements.get('FRONT') <= self.critical_distance:

                self.front_availability = False

                #Check caso in cui la direzione motori sia FORWARD e direzione FRONT bloccata
                if self.motors_object.getMotorsStatus(
                ) == self.motors_object.FORWARD:

                    print('ProximityManager stopping motors..')
                    self.motors_object.stop()

                    #print('ninetyDegreesRotation..')
                    #self.motors_object.rotation('CLOCKWISE', False, True)

            if self.measurements.get('LEFT') is None:
                self.left_availability = False
                raise proximityMeasurementErrorException('LEFT measure None')
            elif self.measurements.get('LEFT') > self.critical_distance:
                self.left_availability = True
            elif self.measurements.get('LEFT') <= self.critical_distance:

                self.left_availability = False

                #Check caso in cui il robot sia in movimento e abbia raggiunto la distanza critica
                if self.motors_object.getMotorsStatus(
                ) != self.motors_object.STOPPED:

                    print('ProximityManager stopping motors..')
                    self.motors_object.stop()

            if self.measurements.get('RIGHT') is None:
                self.right_availability = False
                raise proximityMeasurementErrorException('RIGHT measure None')
            elif self.measurements.get('RIGHT') > self.critical_distance:
                self.right_availability = True
            elif self.measurements.get('RIGHT') <= self.critical_distance:

                self.right_availability = False

                #Check caso in cui il robot sia in movimento e abbia raggiunto la distanza critica
                if self.motors_object.getMotorsStatus(
                ) != self.motors_object.STOPPED:

                    print('ProximityManager stopping motors..')
                    self.motors_object.stop()

    def proximityRotation(self, from_dir, to_dir):

        print('proximityRotation start..')

        if from_dir is None:
            raise Exception('Parameter "from_dir" cannot be None')

        if to_dir is None:
            raise Exception('Parameter "to_dir" cannot be None')

        #TODO checl from_dir == FRONT, LEFT, RIGHT
        #TODO checl to_dir == FRONT, LEFT, RIGHT
        #TODO check che from_dir e to_dir non siano uguali

        #Check caso in cui robot non sia fermo
        if self.motors_object.getMotorsStatus() != self.motors_object.STOPPED:
            print('Stopping motors 2..')
            self.motors_object.stop()

        #Check parametro distanza "from_dir"
        if self.measurements.get(from_dir) is None:
            print('Distance from obastacle not found')
            return
            #raise Exception('None value distance for ' + str(from_dir) + ' direction, cannot use it as reference')

        #Check presenza effettiva ostacolo
        if self.measurements.get(from_dir) > self.critical_distance:
            raise Exception('No obastacle found in ' + str(from_dir) +
                            ' direction to use as reference')

        if from_dir == 'FRONT':

            if to_dir == 'LEFT':
                #Rotazione senso orario
                self.motors_object.rotation('CLOCKWISE')
            elif to_dir == 'RIGHT':
                #Rotazione senso antiorario
                self.motors_object.rotation('COUNTERCLOCKWISE')

        elif from_dir == 'LEFT':

            if to_dir == 'FRONT':
                #Rotazione senso antiorario
                self.motors_object.rotation('COUNTERCLOCKWISE')
            elif to_dir == 'RIGHT':
                #Rotazione senso antiorario
                self.motors_object.rotation('COUNTERCLOCKWISE')

        elif from_dir == 'RIGHT':

            if to_dir == 'FRONT':
                #Rotazione senso orario
                self.motors_object.rotation('CLOCKWISE')
            elif to_dir == 'LEFT':
                #Rotazione senso orario
                self.motors_object.rotation('CLOCKWISE')

        time.sleep(0.4)
        print('Motors stop..')
        self.motors_object.stop()

    def stop(self):

        print('Stopping ProximityManager..')

        self.motors_object.stop()

        if self.proximity is not None:
            self.proximity.cancel()
Exemple #6
0
import datetime
import pwm
import os
import signal
import sys
import select
from proximity import Proximity

pwm.enable()

__prox = Proximity()

__prox.attach("P9_16", "48")

__prox.start()

#fd = os.open("/sys/class/gpio/gpio48/value", os.O_RDONLY | os.O_NONBLOCK)

#READ_ONLY = select.POLLPRI
#poller = select.poll()
#poller.register(fd, READ_ONLY)

#def signal_handler(signal, frame):
#	print 'cleaning up'
#	__prox.detach()
#	open("/sys/class/gpio/unexport", 'w').write("48")
#	fd.close()
#	sys.exit(0)

#toggle = 0
#pre = 0
Exemple #7
0
import datetime
import pwm
import os
import signal
import sys
import select
from proximity import Proximity

pwm.enable()

__prox = Proximity()

__prox.attach("P9_16", "48")

__prox.start()

#fd = os.open("/sys/class/gpio/gpio48/value", os.O_RDONLY | os.O_NONBLOCK)

#READ_ONLY = select.POLLPRI
#poller = select.poll()
#poller.register(fd, READ_ONLY)


#def signal_handler(signal, frame):
#	print 'cleaning up'
#	__prox.detach()
#	open("/sys/class/gpio/unexport", 'w').write("48")
#	fd.close()
#	sys.exit(0)

#toggle = 0
Exemple #8
0
 def menu_item_selected(self):
     """Select the current menu item"""
     # If ANYTHING selected, we gracefully
     # kill any challenge threads open
     self.stop_threads()
     if self.menu[self.menu_state] == "Remote Control":
         # Start the remote control
         logging.info("Entering into Remote Control Mode")
         self.challenge = rc.rc(self.drive, self.wiimote)
         # Create and start a new thread running the remote control script
         self.challenge_thread = threading.Thread(target=self.challenge.run)
         self.challenge_thread.start()
         # Ensure we know what challenge is running
         if self.challenge:
             self.challenge_name = self.menu[self.menu_state]
         # Move menu index to quit challenge by default
         self.menu_state = self.menu_quit_challenge
     elif self.menu[self.menu_state] == "Three Point Turn":
         # Start the three point turn challenge
         logging.info("Starting Three Point Turn Challenge")
         self.challenge = ThreePointTurn(self.drive)
         # Create and start a new thread running the remote control script
         self.challenge_thread = threading.Thread(target=self.challenge.run)
         self.challenge_thread.start()
         # Ensure we know what challenge is running
         if self.challenge:
             self.challenge_name = self.menu[self.menu_state]
         # Move menu index to quit challenge by default
         self.menu_state = self.menu_quit_challenge
     elif self.menu[self.menu_state] == "Straight Line Speed":
         # Start the straight line speed challenge
         logging.info("Starting Straight Line Speed Challenge")
         self.challenge = StraightLineSpeed(self.drive)
         # Ensure we know what challenge is running
         if self.challenge:
             self.challenge_name = self.menu[self.menu_state]
         # Move menu index to quit challenge by default
         self.menu_state = self.menu_quit_challenge
     elif self.menu[self.menu_state] == "Line Following":
         # Start the Line Following challenge
         logging.info("Starting Line Following Challenge")
         self.challenge = LineFollowing(self.drive)
         # Ensure we know what challenge is running
         if self.challenge:
             self.challenge_name = self.menu[self.menu_state]
         # Move menu index to quit challenge by default
         self.menu_state = self.menu_quit_challenge
     elif self.menu[self.menu_state] == "Proximity":
         # Start the Proximity challenge
         logging.info("Starting Proximity Challenge")
         self.challenge = Proximity(self.drive)
         # Ensure we know what challenge is running
         if self.challenge:
             self.challenge_name = self.menu[self.menu_state]
         # Move menu index to quit challenge by default
         self.menu_state = self.menu_quit_challenge
     elif self.menu[self.menu_state] == "Quit Challenge":
         # Reset menu item back to top of list
         self.menu_state = 0
         logging.info("No Challenge Challenge Thread")
     elif self.menu[self.menu_state] == "Power Off Pi":
         # Power off the raspberry pi safely
         # by sending shutdown command to terminal
         logging.info("Shutting Down Pi")
         os.system("sudo shutdown -h now")
         self.shutting_down = True
Exemple #9
0
class launcher:
    def __init__(self):
        # Need a state set for this launcher.
        self.menu = ["Remote Control"]
        self.menu += ["Three Point Turn"]
        self.menu += ["Straight Line Speed"]
        self.menu += ["Line Following"]
        self.menu += ["Proximity"]
        self.menu += ["Quit Challenge"]
        self.menu += ["Power Off Pi"]

        self.menu_quit_challenge = 3

        # default menu item is remote control
        self.menu_state = 0
        self.menu_button_pressed = False
        self.drive = None
        self.wiimote = None
        # Current Challenge
        self.challenge = None
        self.challenge_name = ""

        GPIO.setwarnings(False)
        self.GPIO = GPIO

        # LCD Display
        self.lcd = Adafruit_CharLCD(pin_rs=25,
                                    pin_e=24,
                                    pins_db=[23, 17, 27, 22],
                                    GPIO=self.GPIO)
        self.lcd.begin(16, 1)
        self.lcd.clear()
        self.lcd.message('Initiating...')
        self.lcd_loop_skip = 5
        # Shutting down status
        self.shutting_down = False

    def menu_item_selected(self):
        """Select the current menu item"""
        # If ANYTHING selected, we gracefully
        # kill any challenge threads open
        self.stop_threads()
        if self.menu[self.menu_state] == "Remote Control":
            # Start the remote control
            logging.info("Entering into Remote Control Mode")
            self.challenge = rc.rc(self.drive, self.wiimote)
            # Create and start a new thread running the remote control script
            self.challenge_thread = threading.Thread(target=self.challenge.run)
            self.challenge_thread.start()
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state] == "Three Point Turn":
            # Start the three point turn challenge
            logging.info("Starting Three Point Turn Challenge")
            self.challenge = ThreePointTurn(self.drive)
            # Create and start a new thread running the remote control script
            self.challenge_thread = threading.Thread(target=self.challenge.run)
            self.challenge_thread.start()
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state] == "Straight Line Speed":
            # Start the straight line speed challenge
            logging.info("Starting Straight Line Speed Challenge")
            self.challenge = StraightLineSpeed(self.drive)
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state] == "Line Following":
            # Start the Line Following challenge
            logging.info("Starting Line Following Challenge")
            self.challenge = LineFollowing(self.drive)
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state] == "Proximity":
            # Start the Proximity challenge
            logging.info("Starting Proximity Challenge")
            self.challenge = Proximity(self.drive)
            # Ensure we know what challenge is running
            if self.challenge:
                self.challenge_name = self.menu[self.menu_state]
            # Move menu index to quit challenge by default
            self.menu_state = self.menu_quit_challenge
        elif self.menu[self.menu_state] == "Quit Challenge":
            # Reset menu item back to top of list
            self.menu_state = 0
            logging.info("No Challenge Challenge Thread")
        elif self.menu[self.menu_state] == "Power Off Pi":
            # Power off the raspberry pi safely
            # by sending shutdown command to terminal
            logging.info("Shutting Down Pi")
            os.system("sudo shutdown -h now")
            self.shutting_down = True

    def set_neutral(self, drive, wiimote):
        """Simple method to ensure motors are disabled"""
        if drive:
            drive.set_neutral()
            drive.disable_drive()
        if wiimote is not None:
            # turn on leds on wii remote
            wiimote.led = 2

    def set_drive(self, drive, wiimote):
        """Simple method to highlight that motors are enabled"""
        if wiimote is not None:
            # turn on leds on wii remote
            #turn on led to show connected
            drive.enable_drive()
            wiimote.led = 1

    def stop_threads(self):
        """Method neatly closes any open threads started by this class"""
        if self.challenge:
            self.challenge.stop()
            self.challenge = None
            self.challenge_thread = None
            logging.info("Stopping Challenge Thread")
        else:
            logging.info("No Challenge Challenge Thread")
        # Safety setting
        self.set_neutral(self.drive, self.wiimote)

    def run(self):
        """ Main Running loop controling bot mode and menu state """
        # Tell user how to connect wiimote
        self.lcd.clear()
        self.lcd.message('Press 1+2 \n')
        self.lcd.message('On Wiimote')

        # Initiate the drivetrain
        self.drive = drivetrain.DriveTrain(pwm_i2c=0x40)
        self.wiimote = None
        try:
            self.wiimote = Wiimote()

        except WiimoteException:
            logging.error("Could not connect to wiimote. please try again")

        if not self.wiimote:
            # Tell user how to connect wiimote
            self.lcd.clear()
            self.lcd.message('Wiimote \n')
            self.lcd.message('Not Found' + '\n')

        # Constantly check wiimote for button presses
        loop_count = 0
        while self.wiimote:
            buttons_state = self.wiimote.get_buttons()
            nunchuk_buttons_state = self.wiimote.get_nunchuk_buttons()
            joystick_state = self.wiimote.get_joystick_state()

            #            logging.info("joystick_state: {0}".format(joystick_state))
            #            logging.info("button state {0}".format(buttons_state))
            # Always show current menu item
            # logging.info("Menu: " + self.menu[self.menu_state])

            if loop_count >= self.lcd_loop_skip:
                # Reset loop count if over
                loop_count = 0

                self.lcd.clear()
                if self.shutting_down:
                    # How current menu item on LCD
                    self.lcd.message('Shutting Down Pi' + '\n')
                else:
                    # How current menu item on LCD
                    self.lcd.message(self.menu[self.menu_state] + '\n')

                    # If challenge is running, show it on line 2
                    if self.challenge:
                        self.lcd.message('[' + self.challenge_name + ']')

            # Increment Loop Count
            loop_count = loop_count + 1

            # Test if B button is pressed
            if joystick_state is None or (buttons_state & cwiid.BTN_B) or (
                    nunchuk_buttons_state & cwiid.NUNCHUK_BTN_Z):
                # No nunchuk joystick detected or B or Z button
                # pressed, must go into neutral for safety
                logging.info("Neutral")
                self.set_neutral(self.drive, self.wiimote)
            else:
                # Enable motors
                self.set_drive(self.drive, self.wiimote)

            if ((buttons_state & cwiid.BTN_A) or (buttons_state & cwiid.BTN_UP)
                    or (buttons_state & cwiid.BTN_DOWN)):
                # Looking for state change only
                if not self.menu_button_pressed and (buttons_state
                                                     & cwiid.BTN_A):
                    # User wants to select a menu item
                    self.menu_item_selected()
                elif not self.menu_button_pressed and (buttons_state
                                                       & cwiid.BTN_UP):
                    # Decrement menu index
                    self.menu_state = self.menu_state - 1
                    if self.menu_state < 0:
                        # Loop back to end of list
                        self.menu_state = len(self.menu) - 1
                    logging.info("Menu item: {0}".format(
                        self.menu[self.menu_state]))
                elif not self.menu_button_pressed and (buttons_state
                                                       & cwiid.BTN_DOWN):
                    # Increment menu index
                    self.menu_state = self.menu_state + 1
                    if self.menu_state >= len(self.menu):
                        # Loop back to start of list
                        self.menu_state = 0
                    logging.info("Menu item: {0}".format(
                        self.menu[self.menu_state]))

                # Only change button state AFTER we have used it
                self.menu_button_pressed = True
            else:
                # No menu buttons pressed
                self.menu_button_pressed = False

            time.sleep(0.05)
Exemple #10
0
def main():
    # init model, ResNet18() can be also used here for training
    # model = WideResNet().to(device)
    if args.network == 'smallCNN':
        model = SmallCNN().to(device)
    elif args.network == 'wideResNet':
        model = WideResNet().to(device)
    elif args.network == 'resnet':
        model = ResNet().to(device)
    else:
        model = VGG(args.network, num_classes=10).to(device)
    sys.stdout = Logger(os.path.join(args.log_dir, args.log_file))
    print(model)
    criterion_prox = Proximity(10, args.feat_size, True)
    criterion_conprox = Con_Proximity(10, args.feat_size, True)
    optimizer_prox = optim.SGD(criterion_prox.parameters(), lr=args.lr_prox)
    optimizer_conprox = optim.SGD(criterion_conprox.parameters(), lr=args.lr_conprox)
    optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)
    if args.fine_tune:
        base_dir = args.base_dir
        state_dict = torch.load("{}/{}_ep{}.pt".format(base_dir, args.base_model, args.checkpoint))
        opt = torch.load("{}/opt-{}_ep{}.tar".format(base_dir, args.base_model, args.checkpoint))
        model.load_state_dict(state_dict)
        optimizer.load_state_dict(opt)


    natural_acc = []
    robust_acc = []

    for epoch in range(1, args.epochs + 1):
        # adjust learning rate for SGD
        adjust_learning_rate(optimizer, epoch)
        adjust_learning_rate(optimizer_prox, epoch)
        adjust_learning_rate(optimizer_conprox, epoch)

        start_time = time.time()

        # adversarial training
        train(model, device, train_loader, optimizer,
              criterion_prox, optimizer_prox,
              criterion_conprox, optimizer_conprox, epoch)

        # evaluation on natural examples
        print('================================================================')
        print("Current time: {}".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
        # eval_train(model, device, train_loader)
        # eval_test(model, device, test_loader)
        natural_err_total, robust_err_total = eval_adv_test_whitebox(model, device, test_loader)
        with open(os.path.join(stats_dir, '{}.txt'.format(args.save_model)), "a") as f:
            f.write("{} {} {}\n".format(epoch, natural_err_total, robust_err_total))

        print('using time:', datetime.timedelta(seconds=round(time.time() - start_time)))

        natural_acc.append(natural_err_total)
        robust_acc.append(robust_err_total)


        file_name = os.path.join(stats_dir, '{}_stat{}.npy'.format(args.save_model, epoch))
        # np.save(file_name, np.stack((np.array(self.train_loss), np.array(self.test_loss),
        #                              np.array(self.train_acc), np.array(self.test_acc),
        #                              np.array(self.elasticity), np.array(self.x_grads),
        #                              np.array(self.fgsms), np.array(self.pgds),
        #                              np.array(self.cws))))
        np.save(file_name, np.stack((np.array(natural_acc), np.array(robust_acc))))

        # save checkpoint
        if epoch % args.save_freq == 0:
            torch.save(model.state_dict(),
                       os.path.join(model_dir, '{}_ep{}.pt'.format(args.save_model, epoch)))
            torch.save(optimizer.state_dict(),
                       os.path.join(model_dir, 'opt-{}_ep{}.tar'.format(args.save_model, epoch)))
            print("Ep{}: Model saved as {}.".format(epoch, args.save_model))
        print('================================================================')