Exemplo n.º 1
0
def remove_missions_with_redundancies(strategies):
    final_possible_strategies = []

    #chaque stratégie est un tuple de missions, c'est à dire une assignation spécifique d'une mission par groupe
    while len(
            strategies
    ) > 1:  #on parcourt la liste des stratégies, et on elève celles qui ont des doublons
        mission_tuple = strategies[-1]
        strategies.pop()
        #on reconverti cette assignation de missions sous forme d'une liste d'actions
        actionList = convertStratToActions(mission_tuple)
        # Et on vérifie qu'il n'y a pas de doublons dans les groupes visés par ces actions
        target_list = []
        duplicate_count = 0
        for action in actionList:
            if action.target_group not in target_list:
                target_list.append(action.target_group)
            else:  #todo plutot que de l'effacer brutalement, implementer merge
                duplicate_count += 1
        if duplicate_count == 0:
            newMission = Mission(actionList)
            final_possible_strategies.append(newMission)
    final_possible_strategies.append(
        Mission(convertStratToActions(strategies[0]))
    )  #mais, quoi qu'il arrive, on rajoute toujours au moins une stratégie

    return final_possible_strategies
Exemplo n.º 2
0
def create_runner():
    r = Robot(SensorMap(sensor_map_master),
              bluetooth=BluetoothMaster(MAC_ADDRESS, PORT))

    mission_Mission = Mission([
        BorderAction(priority=5),
        ColorDetAction(colors=[ColorSensor.COLOR_RED], priority=4),
        DontDrownAction(lakes=[
            ColorSensor.COLOR_RED, ColorSensor.COLOR_YELLOW,
            ColorSensor.COLOR_BLUE
        ],
                        priority=3),
        UltrasoundAction(rotate_degrees=0.5, dodge_rocks=False, priority=2),
        DriveAction(priority=1)
    ])
    mission_Mission2 = Mission([
        BorderAction(priority=5),
        ColorDetAction(colors=[ColorSensor.COLOR_RED], priority=4),
        DontDrownAction(
            lakes=[ColorSensor.COLOR_RED, ColorSensor.COLOR_YELLOW],
            priority=3),
        UltrasoundAction(rotate_degrees=0.5, dodge_rocks=False, priority=2),
        DriveAction(priority=1)
    ])

    Runner(r, [mission_Mission, mission_Mission2]).run()
Exemplo n.º 3
0
def create_runner():
    r = Robot(SensorMap(sensor_map_master),
              bluetooth=BluetoothMaster(MAC_ADDRESS, PORT))

    mission_Name24 = Mission([
        BorderAction(rotate_degrees=0.3, priority=4),
        ColorDetAction(colors=[ColorSensor.COLOR_RED], priority=3),
        DontDrownAction(lakes=[
            ColorSensor.COLOR_RED, ColorSensor.COLOR_YELLOW,
            ColorSensor.COLOR_BLUE
        ],
                        priority=2),
        DriveAction(speed=3, priority=1)
    ], SpeakCelebration('weeeeeeeeeeeeeeeeeee'))
    mission_Name52 = Mission([
        BorderAction(priority=4),
        DontDrownAction(lakes=[
            ColorSensor.COLOR_RED, ColorSensor.COLOR_YELLOW,
            ColorSensor.COLOR_BLUE
        ],
                        priority=3),
        PushRockAction(number_of_rocks=1, priority=2),
        DriveAction(speed=3, priority=1)
    ], DanceCelebration())

    Runner(r, [mission_Name24, mission_Name52]).run()
Exemplo n.º 4
0
def save_missions(soup):
    dprint('Extracting missions...            ', end='')
    sys.stdout.flush()
    locations = []
    rewardsTableNames = [
        'missionRewards', 'keyRewards', 'transientRewards', 'sortieRewards'
    ]
    for name in rewardsTableNames:
        locations += next(
            soup.find_all(id=name)[0].next_sibling.children).contents
    missions = []
    for element in locations:
        if 'class' in element and element['class'] == 'blank-row':
            continue
        if element.contents[0].name == 'th' and len(element.contents) == 1:
            if element.contents[0].string.split()[0] == 'Rotation':
                rotation = element.string.split()[1]
            else:
                rotation = ''
                current_element = element.string
        elif len(element.contents
                 ) == 2 and not element.contents[0].name == 'th':
            event = False
            mission = current_element.replace('Infested Salvage', 'Salvage')
            if mission.split()[0] == "Event:":
                event = True
                mission = ' '.join(mission.split()[1:])
            if re.match(r'^([\w -]+)/([\w -]+) \(([\w -]+)\)$', mission):
                match = re.search(r'^([\w -]+)/([\w -]+) \(([\w -]+)\)$',
                                  mission)
                mission = Mission(match.group(1), match.group(2),
                                  match.group(3), event)
            elif mission.startswith('Orokin Derelict'):
                mission_type = mission.split()[-1]
                mission = Mission('Derelict', mission_type, mission_type,
                                  False)
            else:

                mission = GenericDropLocation(mission)
            missions.append(
                MissionDrop(
                    mission, element.contents[0].string, rotation,
                    float(element.contents[1].string.split()[-1][1:-2])))
    dprint('done.')
    dprint('Writing to file...                ', end='')
    sys.stdout.flush()

    if not os.path.exists('data/missions.db'):
        open('data/missions.db', 'x').close()
    open('data/missions.db', 'w').write(repr(missions))
    dprint('done.')
Exemplo n.º 5
0
    def refresh_missions(self):
        results = self.web.get_started()
        for mission in results['missions']:
            if (mission['user_id'] != 2091):
                logging.info('mission of id {} is not owned by 2091 - {}'.format(mission['id'], mission['user_id']))
                continue
            if str(mission['id']) not in self.missions:
                self.missions[str(mission['id'])] = Mission(mission)
            else:
                self.missions[str(mission['id'])].update(mission)

            if (str(mission['id']) not in self.mission_ids):
                self.mission_ids.append(str(mission['id']))
        for drive in results['drive']:
            self.queue.put({
                'type': 'unit_update',
                'data': {
                    'id': drive['id'],
                    'fms_real': drive['fms_real'],
                    'mission_id': drive['mid']
                }
            })
        for patient in results['combined_patients']:
            self.queue.put({'type':'patientcombined_add','data':patient})
        for patient in results['patients']:
            self.queue.put({'type':'patient_add','data':patient})
Exemplo n.º 6
0
    def __update_db_missions(self, mission_tree):
        """
        Postorder traversal of a list of MissionJson objects that converts them into
        missions that are stored in the DB.  Recursive.
        """
        parent_dbm_list = []

        for mission in mission_tree:
            # recurse down to leaf nodes
            child_dbm_list = self.__update_db_missions(mission.branches)

            db_mission = None

            try:
                # update existing missions
                db_mission = database.session.query(Mission).filter(
                    Mission._name == mission.name).one()
                db_mission.update_data(mission)
            except orm.exc.NoResultFound:
                # add new mission
                db_mission = Mission(mission)
                database.session.add(db_mission)

            db_mission._branches = child_dbm_list
            parent_dbm_list.append(db_mission)

        return parent_dbm_list
Exemplo n.º 7
0
Arquivo: game.py Projeto: ajmitc/b-17
    def init_mission(self):
        self.game.mission = Mission( len(self.game.missions) + 1 )
        self.init_bomber()

        # Get Target City and Target Type
        targettable = MissionTargetTable()
        target, targettype, targetzone = targettable.get_mission( self.game.mission.mission_number )
        self.game.mission.target = target
        self.game.mission.target_type = targettype
        self.game.mission.target_zone = targetzone

        print "Mission %d: %s [%s] Zone %d" % (self.game.mission.mission_number, target, targettype, targetzone)
        self.pause()

        # Get formation position
        formationtable = FormationPositionTable()
        self.game.mission.position_in_formation = formationtable.get_position()
        self.game.mission.position_in_squadron  = formationtable.get_squadron_position()

        print "Formation Position: %s" % self.game.mission.position_in_formation
        if self.game.mission.mission_number >= 6:
            print "Squadron Position: %s" % self.game.mission.position_in_squadron
        self.pause()

        # Get fighter coverage
        fightercoveragetable = FighterCoverageTable()
        for zone in xrange( 2, targetzone + 1 ):
            self.game.mission.fighter_coverage[ OUT  ][ zone ] = fightercoveragetable.get_fighter_coverage( self.game.mission.mission_number )
            self.game.mission.fighter_coverage[ BACK ][ zone ] = fightercoveragetable.get_fighter_coverage( self.game.mission.mission_number )

        # Get fighter waves modifiers
        flightlogtable = FlightLogGazeteer()
        for zone in xrange( 2, targetzone + 1 ):
            self.game.mission.fighter_waves_modifiers[ zone ] = flightlogtable.get_modifier( target, zone )
Exemplo n.º 8
0
def simpleTest2():
    mission = Mission()

    mission.takeOff()
    mission.up(15)
    mission.forward(10)
    mission.backward(10)
    mission.land()

    mission.execute()
Exemplo n.º 9
0
def simpleTest():
    mission = Mission()

    mission.takeOff()

    mission.forward(5)
    mission.backward(5)
    mission.land()

    mission.execute()
Exemplo n.º 10
0
def generate_group_missions(groupes, state, species, max_split_rate):
    nb_human_groups = len(state.getMembers(Species.human))
    nb_enemy_groups = len(state.getMembers(species.inverse()))
    nb_my_groups = len(groupes)
    sub_missions_array = []
    #on genere une liste de missions possibles par groupe (split et non split)
    for groupMe in groupes:
        possible_actions = enumerate_possible_actions(state, groupMe, species,
                                                      nb_my_groups,
                                                      max_split_rate)

        possible_simple_actions = possible_actions[0]
        possible_simple_rates = []
        possible_split_actions = possible_actions[1]
        possible_split_rates = []
        group_missions = []

        for action in possible_simple_actions:
            #on calcule les notes des actions "simples": un groupe attaque un groupe d'humains
            action.calc_mark(state)
            possible_simple_rates.append(action.mark)
        for actions in possible_split_actions:
            #on calcule les notes des missions splittées
            actions[0].calc_mark(state)
            actions[1].calc_mark(state)
            possible_split_rates.append(actions[0].mark + actions[1].mark)

        #ensuite, on cree notre liste de missions possibles pour ce groupe
        for action in possible_simple_actions:
            group_missions.append(Mission([action]))
        for split_couple in possible_split_actions:
            group_missions.append(Mission([split_couple[0], split_couple[1]]))

        merged_rates = possible_simple_rates + possible_split_rates

        group_missions.sort(key=dict(zip(group_missions, merged_rates)).get,
                            reverse=True)

        #on rajoute les missions possibles de ce groupe (déjà pré-tronquée) à la liste de sous-missions globales
        sub_missions_array.append(group_missions[:(nb_human_groups +
                                                   nb_enemy_groups)])

    return sub_missions_array
Exemplo n.º 11
0
    def save_model(self, request, obj, form, change):
        ip = obj.host.ip
        username = obj.host.username
        password = obj.host.password
        rule = obj.firewall_template.config_message
        value = json.loads(obj.template_value)
        command = rule.format(**value)
        print command
        # TODO:下发添加命令
        Mission().create_firewall_rule(ip, username, password, command)

        obj.save()
Exemplo n.º 12
0
    def __init__(self, config):
        self.default_webserver_ip = config.ip
        self.default_port = config.port
        self.default_webserver_port = config.webport
        self.id = config.id
        self.ip = config.ip
        self.home_location = LocationGlobalRelative(config.lat, config.lon,
                                                    config.alt)
        self.sitl = config.sitl
        # Follow instructions @ https://github.com/abearman/sparrow-dev/wiki/How-to-use-the-DroneKit-SITL-simulator
        self.instance = self.id - 1
        self.sitlInstance = SITL(instance=self.instance)
        self.sitlInstance.download('copter', '3.3', verbose=True)
        # system (e.g. "copter", "solo"), version (e.g. "3.3"), verbose

        if self.sitl:
            sitl_args = [
                '--simin=127.0.0.1:4000', '--simout=127.0.0.1:4001', '--model',
                'quad', '--home=' + str(self.home_location.lat) + "," +
                str(self.home_location.lon) + "," +
                str(self.home_location.alt) + ",360"
            ]
            print(str(sitl_args))
            self.sitlInstance.launch(sitl_args,
                                     verbose=False,
                                     await_ready=False,
                                     restart=True)
            self.connection_string = self.sitlInstance.connection_string()
        else:
            self.connection_string = '/dev/tty/ACM0'

        self.formation = None
        self.webserver = str(self.ip) + ":" + str(self.default_webserver_port)
        print('\nConnecting to vehicle on: %s\n' % self.connection_string)
        #print(site.USER_SITE)
        self.vehicle = connect(self.connection_string)
        print("Drone: " + str(self.id) + " connected!")
        self.drone_data = self.get_drone_data()
        # print(self.drone_data.__dict__.get(str(self.id)))
        # self.print_drone_data()
        self.mission = Mission(self.vehicle)
        # logger config
        self.logger = logging.getLogger("/logs/drone" + str(self.id) + "_log")
        self.logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler("drone" + str(self.id) + "_log")
        fh.setLevel(logging.DEBUG)
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)
Exemplo n.º 13
0
def get_missions():
	connection = psycopg2.connect("dbname=mydb user=searcher password=allDatSQL")
	myCursor = connection.cursor()
	myCursor.execute("SELECT * FROM missions ORDER BY level;")
	missions = []
	results = myCursor.fetchall()
	for miss in results:
		pk = int(miss[0])
		name = miss[1]
		description = miss[2]
		level = int(miss[3])
		new_mission = Mission(pk, name, level, description)
		missions.append(new_mission)
	return missions
Exemplo n.º 14
0
def square():
    mission = Mission()

    mission.takeOff()
    mission.counterClockwise(90)
    mission.forward(5)
    mission.clockwise(90)
    mission.forward(5)
    mission.clockwise(90)
    mission.forward(5)
    mission.clockwise(90)
    mission.forward(5)
    mission.land()

    mission.execute()
Exemplo n.º 15
0
    def dp_wd():
        dp_wd = Toplevel()
        dp_wd.title('待办事项')
        to_do_list = Frame(dp_wd)
        to_do_list.pack(fill='x')
        add_mission = Frame(dp_wd)
        add_mission.pack(fill='x')

        with open('data.json', 'r') as f:
            data = load(f)

        for i in range(len(data)):
            locals()[data[i]['MID']] = Mission(data[i]['content'], 'Top')
            locals()[data[i]['MID']].display(to_do_list)

        new_mission_entry = Entry(add_mission, width=20)
        new_mission_entry.pack(side=LEFT)

        def add_mission_button():
            locals()['MS' + strftime('%Y%m%d%H%M%S', localtime())] = Mission(
                new_mission_entry.get(), 'Top')
            locals()['MS' +
                     strftime('%Y%m%d%H%M%S', localtime())].display(to_do_list)

            def is_MS(s):
                if list(s)[0] == 'M' and list(s)[1] == 'S':
                    return s

            new_list = list(filter(is_MS, list(locals())))

            def ms2dict(ms):
                return {'MID': 'MS' + ms.MID, 'content': ms.content}

            for i in range(len(new_list)):
                new_list[i] = ms2dict(locals()[new_list[i]])
            with open('data.json', 'w') as f:
                f.write(dumps(new_list))

        Button(add_mission, text='添加',
               command=add_mission_button).pack(side=RIGHT)

        test_list = [{
            'MID': 'MS002',
            'content': 'Test suceed!'
        }, {
            'MID': 'MS003',
            'content': 'Succed again!'
        }]
Exemplo n.º 16
0
        def add_mission_button():
            locals()['MS' + strftime('%Y%m%d%H%M%S', localtime())] = Mission(
                new_mission_entry.get(), 'Top')
            locals()['MS' +
                     strftime('%Y%m%d%H%M%S', localtime())].display(to_do_list)

            def is_MS(s):
                if list(s)[0] == 'M' and list(s)[1] == 'S':
                    return s

            new_list = list(filter(is_MS, list(locals())))

            def ms2dict(ms):
                return {'MID': 'MS' + ms.MID, 'content': ms.content}

            for i in range(len(new_list)):
                new_list[i] = ms2dict(locals()[new_list[i]])
            with open('data.json', 'w') as f:
                f.write(dumps(new_list))
Exemplo n.º 17
0
    def __init__(self, config):
        self.default_webserver_ip = config.ip
        self.default_port = config.port
        self.default_webserver_port = config.webport
        self.id = config.id
        self.ip = config.ip
        self.sitl = config.sitl
        self.sitlInstance = SITL('/home/dino/.dronekit/sitl/copter-3.3/apm')
        if self.sitl:
            sitl_args = [
                '--instance ' + str(self.id - 1), '-I0', '--model', 'quad',
                '--home=-35.363261,149.165230,584,353'
            ]
            self.sitlInstance.launch(sitl_args,
                                     verbose=False,
                                     await_ready=False,
                                     restart=True)
            self.connection_string = self.sitlInstance.connection_string()
        else:
            self.connection_string = '/dev/tty/ACM0'

        self.formation = None
        self.webserver = str(self.ip) + ":" + str(self.default_webserver_port)
        print('\nConnecting to vehicle on: %s\n' % self.connection_string)
        self.vehicle = connect(self.connection_string)
        print("Drone: " + str(self.id) + " connected!")
        self.drone_data = self.get_drone_data()
        self.print_drone_data()
        self.mission = Mission(self.vehicle)
        # logger config
        self.logger = logging.getLogger("drone" + (str)(self.id) + "_log")
        self.logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler("drone" + (str)(self.id) + "_log")
        fh.setLevel(logging.DEBUG)
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)
Exemplo n.º 18
0
def build_mission(
        map_file: str,
        world_file: str,
        start_x: float,
        start_y: float,
        end_x: float,
        end_y: float,
        base_launch_file: str = os.path.join(
            os.path.dirname(__file__), 'robotest.launch'),  # noqa: pycodestyle
        distance_threshold: float = 0.3) -> Mission:
    pos_start = (start_x, start_y)
    pos_target = (end_x, end_y)
    mission = Mission(map_position_initial=pos_start,
                      map_position_end=pos_target,
                      base_launch_file=base_launch_file,
                      map_to_world=map_to_world,
                      map_file=map_file,
                      world_file=world_file,
                      time_limit=90,
                      distance_threshold=distance_threshold)
    return mission
Exemplo n.º 19
0
    def __init__(self, building_height):
        rospy.init_node('offb')
        self.height = building_height
        self.GPS_ready = False

        # Wait for Offboard and drone to be ready
        ready = rospy.wait_for_message('/gps_ready_from_offboard', Bool, timeout=rospy.Duration(60*5)) # Wait for offboard to get GPS fix for 5 minutes, because sometimes GPS locks take long to get when a board is booted up the first time

        if ready:
            nav = NavSatFix()
            # And now put the node into a waiting loop to wait for GPS Lock from Offboard
            nav = rospy.wait_for_message('mavros/global_position/global', NavSatFix)
            self.coordinates = np.array([nav.latitude, nav.longitude])
        else:
            rospy.loginfo("Never got position confirmation from Offboard")

        self.house_result_pub = rospy.Publisher('/house_results_from_overpass_local', BuildingPolygonResult, queue_size=5) # Information about the house
        self.camera_stuff_pub = rospy.Publisher('/camera_and_distances', CameraStuff, queue_size=1)
        self.impression_keyframes_pub = rospy.Publisher('/impression_poses_from_planner', PoseArray, queue_size=5) # Poses to take one image of each facade of the house
        self.inspection_keyframes_pub = rospy.Publisher('/keyframes_poses_from_planner', PoseArray, queue_size=5)

        #self.segmented_image_sub = rospy.Subscriber('segmented_image_from_cnn', cnnResult, self.segmented_image_callback, queue_size=5)

        self.image_and_rois_sub = rospy.Subscriber('/segmented_image_from_cnn', ImageAndRois, callback=self.image_and_rois_callback)

        self.get_tiles_ready = False

        self.images_list = []
        self.rois_list = []

        self.s = Sun(self.coordinates[0], self.coordinates[1])
        self.m = Mission(80, 80)
        self.model_walls = []
        self.model_windows = []

        self.fig_thread = Thread(target=self.draw_thread, args=())
        self.fig_thread.daemon = True

        self.fig = []
        self.ax = []
Exemplo n.º 20
0
def build_mission(start_x: float, start_y: float, end_x: float,
                  end_y: float) -> Mission:
    pos_start = (start_x, start_y)
    pos_target = (end_x, end_y)

    # TODO: parameterise
    dir_catkin = '/home/mars/catkin_ws'
    dir_turtlebot_gazebo = os.path.join(
        dir_catkin, 'src/turtlebot_simulator/turtlebot_gazebo')
    map_file = os.path.join(dir_turtlebot_gazebo, 'maps/playground.yaml')
    world_file = os.path.join(dir_turtlebot_gazebo, 'worlds/playground.world')
    base_launch_file = os.path.join(os.path.dirname(__file__),
                                    'robotest.launch')

    mission = Mission(map_position_initial=pos_start,
                      map_position_end=pos_target,
                      base_launch_file=base_launch_file,
                      map_to_world=map_to_world,
                      map_file=map_file,
                      world_file=world_file,
                      time_limit=90)
    return mission
Exemplo n.º 21
0
 def handle_mission(self, data):
     if self.Title:
         self.Title_Text = data
         self.Title = False
         position = self.Title_Text.find('(')
         self.Missions.append(
             Mission(self.Title_Text[:position - 1],
                     self.Title_Text[position:]))
     elif self.Rotation:
         self.Rotation = False
         self.Rotation_Number = data
     else:
         if self.Loot == "":
             self.Loot = data
         else:
             self.Loot_Rarity = self.parse_luck(data)
             if self.Rotation_Number is not None:
                 self.Missions[-1].add_loot(self.Loot, self.Loot_Rarity,
                                            self.Rotation_Number)
             else:
                 self.Missions[-1].add_loot(self.Loot, self.Loot_Rarity)
             self.Loot = ""
             self.Loot_Rarity = ""
Exemplo n.º 22
0
# Start Telemetry module to load data into.
telemetry = {}

# initialize the constants instance so that we can update the WebAPI
util.log("Accessing HTTPConst singleton instance")
HTTPConst = HTTPConstants()

util.succLog(
    "Setting up mavlink recieving protocol - Instantiating modules...")

# Instantiate a Mavlink module.
mavl = Mavlink(constants['mavl-incoming']['host'],
               constants['mavl-incoming']['port'])

# Instantiate Mission module.
miss = Mission(constants['auvsi']['host'], constants['auvsi']['port'],
               constants['auvsi']['username'], constants['auvsi']['password'])

# Grab mission/server data from the competition server.
missPacket = miss.getMissionComponents()

HTTPConst.setMission(missPacket)

packets_sent = 0
startTime = time.time()

# Starting front end components.
util.log("Initiating telemetry status console front end")

util.log("Ready to recieve Mavlink Packets...")

packets_sent = 0
Exemplo n.º 23
0
#!/usr/bin/env python3
from character import Character
from mission import Mission

bStats = {"hp": 100, "defense": 20, "dmg": 10, "catch_rate": 70}
gStats = {"hp": 130, "defense": 20, "dmg": 10, "catch_rate": 30}
jStats = {"hp": 100, "defense": 40, "dmg": 10, "catch_rate": 80}
uStats = {"hp": 120, "defense": 30, "dmg": 10, "catch_rate": 40}
batman = Character("batman", bStats)
greenLantern = Character("green lantern", bStats)
joker = Character("joker", jStats)
universe = Character("univers", uStats)

mission = Mission("Death squad", [joker, universe])
mission.heroes.append(batman)
mission.heroes.append(greenLantern)
mission.start_mission()
print("j hp: " + str(joker.hp))
print("u hp: " + str(universe.hp))
print("b hp: " + str(batman.hp))
print("g hp: " + str(greenLantern.hp))

Exemplo n.º 24
0
 async def next(self, ctx, *, arg1=None):
     sub_command = ctx.subcommand_passed
     await ctx.send(embed=Mission(self, sub_command).embed_daily)
 def setUp(self):
     waypoint_dict = open('waypoints_test.json', 'rb')
     waypoint_list = json.loads(waypoint_dict.read())
     self.mission = Mission(waypoint_list["waypoints"], mission_type='regular_flight', takeoff_required=True)
Exemplo n.º 26
0
 async def daily(self, ctx):
     if ctx.invoked_subcommand is None:
         sub_command = ctx.subcommand_passed
         await ctx.send(embed=Mission(self, sub_command).embed_daily)
Exemplo n.º 27
0
def yaml_parse(yaml_text, navigator, total_time):
    my_missions = {}
    mission_to_mission_dep = {}
    count = 0
    base_mission = None
    missions_left = []
    tree = []

    for name in yaml_text.keys():
        mission = yaml_text[name]
        marker_dep = mission["marker_dep"]
        mis_dep = mission["mission_dep"]
        is_base = mission["is_base"]
        min_time = mission["min_time"]
        points = mission["points"]
        looking_for = mission["looking_for"]
        weight = mission["weight"]
        if marker_dep != "None":
            marker = yield navigator.database_query(marker_dep,
                                                    raise_exception=False)
            if not marker.found:
                fprint("NOT COMPLETING {}, NO MARKER FOUND".format(name),
                       msg_color="green")
                continue
            marker = marker.objects[0]
        else:
            marker = None

        num_mission_deps = len(mis_dep)
        if mis_dep == "None":
            num_mission_deps = 0
        if type(mis_dep) is not list:
            num_mission_deps = 1

        if "mission_script" in mission.keys():
            mission_script = mission["mission_script"]
            m = Mission(name,
                        marker,
                        min_time,
                        weight,
                        points,
                        looking_for,
                        num_mission_deps,
                        mission_script=mission_script)
        else:
            m = Mission(name, marker, min_time, weight, points, looking_for,
                        num_mission_deps)
        my_missions[name] = m

        if is_base:
            base_mission = m
        elif mis_dep == "None":
            count += 1
            missions_left.append(m)
            tree.append(m)
        else:
            count += 1
            missions_left.append(m)
            mission_to_mission_dep[name] = mis_dep

    # Go through the missions and give them all children dependencies
    for mission_name in mission_to_mission_dep.keys():
        parent_name = mission_to_mission_dep[mission_name]
        if type(parent_name) is not list:
            parent_names = []
            parent_names.append(parent_name)
        else:
            parent_names = parent_name
        for p in parent_names:
            child_name = mission_name
            parent_mission = my_missions[p]
            child_mission = my_missions[child_name]
            parent_mission.add_child(child_mission)

    total_time -= count * 60
    defer.returnValue((missions_left, base_mission, tree, total_time))
Exemplo n.º 28
0
from logger import get_logger

parser = argparse.ArgumentParser()
parser.add_argument('filenames',
                    metavar='<str>',
                    type=str,
                    nargs=True,
                    help='Files to process.')

logger = get_logger(__name__)

if __name__ == '__main__':
    logger.info('Starting...')

    args = parser.parse_args()

    for filename in args.filenames:
        logger.info("Processing file, filename = {}".format(filename))
        mission = Mission(filename)

        return_code = mission.read()
        if return_code != 0:
            logger.info('Skipping...')
            continue

        mission.compute()

        mission.write()

    logger.info('Terminating...')
Exemplo n.º 29
0
    def configure(self):

        #Add Components
        compress = self.add('compress', CompressionSystem())
        mission = self.add('mission', Mission())
        pod = self.add('pod', Pod())
        flow_limit = self.add('flow_limit', TubeLimitFlow())
        tube_wall_temp = self.add('tube_wall_temp', TubeWallTemp())

        #Boundary Input Connections
        #Hyperloop -> Compress
        self.connect('Mach_pod_max', 'compress.Mach_pod_max')
        self.connect('Ps_tube', 'compress.Ps_tube')
        self.connect('Mach_c1_in', 'compress.Mach_c1_in')  #Design Variable
        self.connect('c1_PR_des', 'compress.c1_PR_des')  #Design Variable
        #Hyperloop -> Mission
        self.connect('tube_length', 'mission.tube_length')
        self.connect('pwr_marg', 'mission.pwr_marg')
        #Hyperloop -> Flow Limit
        self.connect('Mach_pod_max', 'flow_limit.Mach_pod')
        self.connect('Ps_tube', 'flow_limit.Ps_tube')
        self.connect('pod.radius_inlet_back_outer', 'flow_limit.radius_inlet')
        self.connect('Mach_bypass', 'flow_limit.Mach_bypass')
        #Hyperloop -> Pod
        self.connect('Ps_tube', 'pod.Ps_tube')
        self.connect('hub_to_tip', 'pod.hub_to_tip')
        self.connect('coef_drag', 'pod.coef_drag')
        self.connect('n_rows', 'pod.n_rows')
        self.connect('length_row', 'pod.length_row')
        #Hyperloop -> TubeWallTemp
        self.connect('solar_heating_factor',
                     'tube_wall_temp.nn_incidence_factor')
        self.connect('tube_length', 'tube_wall_temp.length_tube')

        #Inter-component Connections
        #Compress -> Mission
        self.connect('compress.speed_max', 'mission.speed_max')
        self.connect('compress.pwr_req', 'mission.pwr_req')
        #Compress -> Pod
        self.connect('compress.area_c1_in', 'pod.area_inlet_out')
        self.connect('compress.area_inlet_in', 'pod.area_inlet_in')
        self.connect('compress.rho_air', 'pod.rho_air')
        self.connect('compress.F_net', 'pod.F_net')
        self.connect('compress.speed_max', 'pod.speed_max')
        #Compress -> TubeWallTemp
        self.connect('compress.nozzle_Fl_O', 'tube_wall_temp.nozzle_air')
        self.connect('compress.bearing_Fl_O', 'tube_wall_temp.bearing_air')
        #Mission -> Pod
        self.connect('mission.time', 'pod.time_mission')
        self.connect('mission.energy', 'pod.energy')

        #Add Solver
        solver = self.add('solver', BroydenSolver())
        solver.itmax = 50  #max iterations
        solver.tol = .001
        #Add Parameters and Constraints
        solver.add_parameter('compress.W_in', low=-1e15, high=1e15)
        solver.add_parameter('compress.c2_PR_des', low=-1e15, high=1e15)
        solver.add_parameter([
            'compress.Ts_tube', 'flow_limit.Ts_tube',
            'tube_wall_temp.temp_boundary'
        ],
                             low=-1e-15,
                             high=1e15)
        solver.add_parameter(
            ['flow_limit.radius_tube', 'pod.radius_tube_inner'],
            low=-1e15,
            high=1e15)

        solver.add_constraint('.01*(compress.W_in-flow_limit.W_excess) = 0')
        solver.add_constraint('compress.Ps_bearing_residual=0')
        solver.add_constraint('tube_wall_temp.ss_temp_residual=0')
        solver.add_constraint(
            '.01*(pod.area_compressor_bypass-compress.area_c1_out)=0')

        driver = self.driver
        driver.workflow.add('solver')
        #driver.recorders = [CSVCaseRecorder(filename="hyperloop_data.csv")] #record only converged
        #driver.printvars = ['Mach_bypass', 'Mach_pod_max', 'Mach_c1_in', 'c1_PR_des', 'pod.radius_inlet_back_outer',
        #                    'pod.inlet.radius_back_inner', 'flow_limit.radius_tube', 'compress.W_in', 'compress.c2_PR_des',
        #                    'pod.net_force', 'compress.F_net', 'compress.pwr_req', 'pod.energy', 'mission.time',
        #                    'compress.speed_max', 'tube_wall_temp.temp_boundary']

        #Declare Solver Workflow
        solver.workflow.add(
            ['compress', 'mission', 'pod', 'flow_limit', 'tube_wall_temp'])
Exemplo n.º 30
0
        status = mission.get_status()
        if (status != MissionStatus.UNSURE) and (
                status != MissionStatus.UNDONE) and (status !=
                                                     MissionStatus.DONE):
            print("Wrong mission status", status)
            return False
        self.__missions[status].remove(mission)
        return True

    def get_missions(self, status):
        return self.__missions[status]

    def get_mission(self, status, index):
        return self.__missions[status][index]


# Test
if __name__ == "__main__":
    p = Project("Adserver", "")
    p.set_deadline("2017-12-31")
    m1 = Mission("a mission", "details", MissionStatus.UNDONE)
    m2 = Mission("b mission", "details", MissionStatus.UNDONE)
    p.add_mission(m1)
    p.add_mission(m2)

    print("Project: %s" % p.get_name())
    print("Dealine: %s" % p.get_deadline())
    missions = p.get_missions(MissionStatus.UNDONE)
    for m in missions:
        print("-->%d: %s" % (m.id(), m.get_description()))