Example #1
0
def random_moves(unit_id):
    if gc.unit(unit_id).location.is_in_garrison() or gc.unit(unit_id).location.is_in_space():
        return
    if config.attack_moving == False and config.rocket_boarding == False:
        destination = gc.unit(unit_id).location.map_location().add(Navigation.random_dir())
        Navigation.fuzzygoto(gc.unit(unit_id).id, destination)
        return
Example #2
0
def board_rocket(unit_id):
    if gc.planet() == bc.Planet.Mars:
        return
    nearby_rockets = gc.sense_nearby_units_by_type(gc.unit(unit_id).location.map_location(), 99999,
                                                   bc.UnitType.Rocket)

    if len(nearby_rockets) <= 0:
        return False, False
    board_rocket.distance = 9999
    board_rocket.target_unit = None
    for unit in nearby_rockets:
        if unit.structure_is_built() and unit.team == config.my_team and len(unit.structure_garrison()) < 8:
            if gc.can_load(unit.id, gc.unit(unit_id).id):
                gc.load(unit.id, gc.unit(unit_id).id)
                return True, False

            else:
                new_distance = unit.location.map_location().distance_squared_to(
                    gc.unit(unit_id).location.map_location())
                if new_distance < board_rocket.distance and unit.structure_is_built() and unit.team == config.my_team and len(
                        unit.structure_garrison()) < 8:
                    board_rocket.target_unit = unit.id

    if board_rocket.target_unit != None:
        destination = gc.unit(board_rocket.target_unit).location.map_location()
        Navigation.fuzzygoto(gc.unit(unit_id).id, destination)
        return False, True

    return False, False
Example #3
0
def turn(gc, unit):
    Units.shoot_at_best_target(gc, unit)
    if gc.is_move_ready(unit.id):
        planet = unit.location.map_location().planet
        path = get_closest_fact(unit) if planet == bc.Planet.Earth else Globals.updatePathMars
        Navigation.path_with_bfs(gc, unit, path)
    return
Example #4
0
def rocket_actions(unit_id):
    if gc.unit(unit_id).structure_is_built() and (gc.unit(unit_id).location.is_on_planet(bc.Planet.Earth) or
                                                  gc.unit(unit_id).location.is_on_planet(bc.Planet.Mars)):
        config.my_units = gc.my_units()
        this_rocket = gc.unit(unit_id)
        # print ("I AM ROCKET", unit_id)
    else:
        return

    garrison = this_rocket.structure_garrison()

    if gc.round() >= config.rocket_launch_round and this_rocket.location.is_on_planet(bc.Planet.Earth):

        if len(garrison) >= 7:  #
            destination = Navigation.pick_random_landing_location()
            if gc.can_launch_rocket(this_rocket.id, destination):
                gc.launch_rocket(this_rocket.id, destination)

        else:
            if gc.round() >= 700 and len(garrison) >= 1:
                if gc.can_launch_rocket(this_rocket.id, Navigation.pick_random_landing_location()):
                    gc.launch_rocket(this_rocket.id, Navigation.pick_random_landing_location())

    if this_rocket.location.is_on_planet(bc.Planet.Mars):
        if len(garrison) > 0:  # ungarrison
            d = random.choice(directions)
            if gc.can_unload(this_rocket.id, d):
                gc.unload(this_rocket.id, d)
                config.my_units = gc.my_units()
Example #5
0
def turn(gc, unit):
    # t = time.time()
    result = Units.shoot_at_best_target(gc, unit)
    # Globals.ranger_find_time += time.time() - t
    # print("find target time", Globals.ranger_find_time)
    if isinstance(result, bc.Unit):
        return
    elif isinstance(result, bc.VecUnit):
        nearby_enemies = result
    else:
        nearby_enemies = send_radar_info(unit, gc)
    # t = time.time()
    if gc.is_move_ready(unit.id):
        e, should_retreat = ranger_retreat(unit, nearby_enemies)
        if should_retreat:
            moved = Navigation.retreatFromKnownEnemy(gc, unit, Globals.radar.get_enemy_center(unit.location.map_location().planet))
            if moved:
                return
        if gc.is_attack_ready(unit.id):
            planet = unit.location.map_location().planet
            path = Globals.updatePath if planet == bc.Planet.Earth else Globals.updatePathMars
            Navigation.path_with_bfs(gc, unit, path)
    # Globals.ranger_else_time += time.time() - t
    # print("other ranger time", Globals.ranger_else_time)
    return
def healer_actions(unit_id):
    this_healer = gc.unit(unit_id)
    config.my_units = gc.my_units()
    #print("I AM HEALER", unit_id)
    healable_friendly = 0

    if not this_healer.location.is_in_garrison(
    ):  # can't move from inside a factory
        friendlies = gc.sense_nearby_units_by_team(
            this_healer.location.map_location(), this_healer.attack_range(),
            config.my_team)

        if len(friendlies) > 0:
            for friendly in friendlies:
                if friendly.health / friendly.max_health <= .9:
                    healable_friendly = friendly.id
                    break

        if healable_friendly > 0:
            if gc.is_heal_ready(
                    this_healer.id) and this_healer.attack_heat() < 10:
                gc.heal(this_healer.id, healable_friendly)

        elif gc.is_move_ready(this_healer.id):
            nearbyFriendlies = gc.sense_nearby_units_by_team(
                this_healer.location.map_location(), this_healer.vision_range,
                config.my_team)
            if len(nearbyFriendlies) > 0:
                destination = nearbyFriendlies[0].location.map_location()
                print("Friends nearby")
            else:
                print("no friends moving randomly")
                destination = this_healer.location.map_location().add(
                    Navigation.random_dir())
            Navigation.fuzzygoto(this_healer.id, destination)
Example #7
0
    def __init__(self, queue_dict):
        self.queues = queue_dict
        # filter properties
        self.toofar = 3
        self.toohigh = 1
        self.n = 500
        #n = 500
        #self.n = math.floor(math.sqrt(n))

        # create row and column structures
        message = self.queues["input"].retrieve(method="recent")
        self.height, self.width = message["images"]["depth"].shape
        self.rows = np.arange(start=0, stop=self.height)[:, np.newaxis]
        self.rows = np.repeat(self.rows, self.width, axis=1)
        self.cols = np.ones(self.height)[:, np.newaxis] * np.arange(
            start=0, stop=self.width)
        #self.rows = np.arange(start=0, stop=self.height)
        #self.rows = np.repeat(self.rows, self.width)
        #self.cols = np.arange(start=0, stop=self.width)
        #self.cols = np.tile(self.cols, self.height)
        #self.cols = self.cols.flatten()

        # init camera
        self.near_clip = 0.1
        self.far_clip = 10
        self.cx = math.floor(self.width / 2)
        self.cy = math.floor(self.height / 2)
        FOV = 90
        self.f = 320 / math.tan(math.pi * (FOV / 2) / 180)

        # grouping
        self.k = 10

        # create mapping class instances
        self.map = AngleMapper(self.toofar)
        self.nav = Navigation(point_range=self.toofar, size=3 * self.toofar)

        # create windows
        self.images_display = NamedWindow("images", size=(500, 500))
        self.angles_display = NamedWindow("angles",
                                          place=(500, 0),
                                          size=(500, 500),
                                          conversions="heat_map")
        self.coded_display = NamedWindow("coded",
                                         place=(1000, 500),
                                         size=(500, 500))
        self.detection_display = NamedWindow("Litter Detection",
                                             place=(1000, 0),
                                             size=(500, 500))
        # self.large_display = NamedWindow("cost", place=(500, 500), size=(500, 500))

        # find original position of camera
        self.original_orientation = np.array(
            [-1.56821251, 0, 3.14152694])  # np.array(message["orientation"])
        self.original_position = np.array(message["position"])

        self.C_svd = C_svd
Example #8
0
def avoid_enemies(unit_id):
    nearbyEnemies = gc.sense_nearby_units_by_team(gc.unit(unit_id).location.map_location(),
                                                  gc.unit(unit_id).vision_range, config.enemy_team)

    if len(nearbyEnemies) > 0:
        for enemy in nearbyEnemies:
            if enemy.unit_type != bc.UnitType.Worker and enemy.unit_type != bc.UnitType.Factory and enemy.unit_type != bc.UnitType.Rocket and enemy.unit_type != bc.UnitType.Healer:
                dir_to_run = enemy.location.map_location().direction_to(
                    gc.unit(unit_id).location.map_location())
                destination = gc.unit(unit_id).location.map_location().add(dir_to_run)
                Navigation.fuzzygoto(gc.unit(unit_id).id, destination)
                return True
            else:
                return False
    return False
    def build_factory(unit_id):
        worker_actions.building_factory = False
        worker_actions.moving_to_build = False
        if config.factory_count < config.factory_target and gc.round(
        ) < config.rocket_target_round:
            for dir in directions:
                if gc.can_blueprint(unit_id, bc.UnitType.Factory, dir):
                    gc.blueprint(unit_id, bc.UnitType.Factory, dir)
                    config.factory_count = config.factory_count + 1
                    worker_actions.building_factory = True
                    worker_actions.moving_to_build = False
                    return

        very_nearby_factories = gc.sense_nearby_units_by_type(
            gc.unit(unit_id).location.map_location(), 1, bc.UnitType.Factory)

        if len(very_nearby_factories) > 0:
            for unit in very_nearby_factories:
                if not unit.structure_is_built(
                ) and unit.team == config.my_team:
                    # factories_qued = factories_qued + 1
                    blueprint_waiting = unit.id
                    if gc.can_build(unit_id, blueprint_waiting):
                        gc.build(unit_id, blueprint_waiting)
                        worker_actions.building_factory = True
                        worker_actions.moving_to_build = False
                        return

        nearby_factories = gc.sense_nearby_units_by_type(
            gc.unit(unit_id).location.map_location(), 16, bc.UnitType.Factory)
        if worker_actions.building_factory is False:
            if len(nearby_factories) > 0:
                for unit in nearby_factories:
                    if not unit.structure_is_built(
                    ) and unit.team == config.my_team:
                        # print("factory built",unit.structure_is_built())
                        worker_actions.destination = unit.location.map_location(
                        )
                        worker_actions.building_factory = False
                        worker_actions.moving_to_build = True
                        # print("inner move to build",worker_actions.moving_to_build)
                        Navigation.fuzzygoto(
                            gc.unit(unit_id).id, worker_actions.destination)
                        return
        worker_actions.building_factory = False
        worker_actions.moving_to_build = False

        return
Example #10
0
 def addNavigation(self, noclose=False):
     navigation = Navigation.Navigation(noclose)
     navigation.activeItemChanged.connect(self.plot)
     navigation.close.connect(self.closeNavigation)
     navigation.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Minimum)
     self.navigationLayout.addWidget(navigation)
     self.navigations.append(navigation)
Example #11
0
 def create_navigation(self,
                       INPUT_DEVICE_TYPE,
                       INPUT_DEVICE_NAME,
                       STARTING_MATRIX,
                       PLATFORM_SIZE,
                       ANIMATE_COUPLING,
                       MOVEMENT_TRACES,
                       DEVICE_TRACKING_NAME=None):
     _navigation = Navigation()
     _navigation.my_constructor(
         self.SCENEGRAPH, PLATFORM_SIZE, STARTING_MATRIX,
         self.navigation_list, INPUT_DEVICE_TYPE, INPUT_DEVICE_NAME,
         self.no_tracking_mat, self.ground_following_settings,
         ANIMATE_COUPLING, MOVEMENT_TRACES, DEVICE_TRACKING_NAME)
     self.navigation_list.append(_navigation)
     self.border_observer_list.append(None)
 def harvest_karbonite_at_location(loc):
     np_loc = Navigation.trans_coord_to_np(loc)
     # print(np_loc)
     y = np_loc[0]
     x = np_loc[1]
     # print(y,x)
     if gc.can_sense_location(loc):
         karb_at_loc = gc.karbonite_at(loc)
         # print("karb at location",karb_at_loc)
         if karb_at_loc == 0:
             config.karbonite_map[y, x] = 0
             # print("updated karb",config.karbonite_map[y,x])
             worker_actions.harvesting_karbonite = False
             worker_actions.harvesting_location = None
         if karb_at_loc > 0:
             config.karbonite_map[y, x] = karb_at_loc
             # print("updated karb",config.karbonite_map[y,x])
             bestDir = gc.unit(
                 unit_id).location.map_location().direction_to(loc)
             # print("karb direction", bestDir)
             if gc.can_harvest(gc.unit(unit_id).id, bestDir):
                 gc.harvest(gc.unit(unit_id).id, bestDir)
                 # print("harvested", bestDir)
                 worker_actions.harvesting_karbonite = True
                 worker_actions.harvesting_location = loc
Example #13
0
def try_go_to_rocket(gc, unit):
    if unit.location.is_in_garrison():
        return True
    for f in Globals.rockets_queue:
        if unit.id in Globals.rockets_queue[f]:
            if gc.is_move_ready(unit.id):
                x = Navigation.path_with_bfs(gc, unit, Globals.rockets_queue[f][unit.id])
                return True
Example #14
0
    def __init__(self):
        log.info('Loading Teledyski')
        self.settings = settings.TVSettings()
        self.parser = Parser.Parser()
        self.cm = pCommon.common()
	self.exception = Errors.Exception()
	self.navigation = Navigation.VideoNav()
	self.history = pCommon.history()
    def harvest_karbonite(unit_id):

        tick = time.clock()
        loc = find_karbonite(unit_id)

        tock = time.clock()
        # print("time to find karb", (tick - tock) * 1000, loc, gc.unit(unit_id).location.map_location())

        # print("distance to karb", loc.distance_squared_to(gc.unit(unit_id).location.map_location()))

        if gc.unit(unit_id).location.map_location().distance_squared_to(
                loc) <= 2:
            harvest_karbonite_at_location(loc)
            # print("harvesting, less than 2 dist, 141")

        if gc.unit(unit_id).location.map_location().distance_squared_to(
                loc) > 2:
            Navigation.a_star_move(unit_id, loc)
Example #16
0
    def __init__(self):
	log.info('Loading ' + SERVICE)
	self.parser = Parser.Parser()
	self.up = urlparser.urlparser()
	self.cm = pCommon.common()
	self.history = pCommon.history()
	self.navigation = Navigation.VideoNav()
	self.chars = pCommon.Chars()
	self.exception = Errors.Exception()
    def build_rocket(unit_id):
        worker_actions.building_rocket = False
        worker_actions.worker_moving_to_build = False
        if gc.round(
        ) >= config.rocket_target_round and config.rocket_count < config.rocket_target:
            for dir in directions:
                if gc.can_blueprint(unit_id, bc.UnitType.Rocket, dir):
                    gc.blueprint(unit_id, bc.UnitType.Rocket, dir)
                    config.rocket_count = config.rocket_count + 1
                    worker_actions.building_rocket = True
                    worker_actions.moving_to_build = False
                    return

        very_nearby_rockets = gc.sense_nearby_units_by_type(
            gc.unit(unit_id).location.map_location(), 1, bc.UnitType.Rocket)
        if len(very_nearby_rockets) > 0:
            for unit in very_nearby_rockets:
                if not unit.structure_is_built(
                ) and unit.team == config.my_team:
                    blueprint_waiting = unit.id
                    if gc.can_build(unit_id, blueprint_waiting):
                        gc.build(unit_id, blueprint_waiting)
                        worker_actions.moving_to_build = False
                        worker_actions.building_rocket = True
                        return

        nearby_rockets = gc.sense_nearby_units_by_type(
            gc.unit(unit_id).location.map_location(), 60, bc.UnitType.Rocket)
        if worker_actions.building_rocket is False:
            if len(nearby_rockets) > 0:
                for unit in nearby_rockets:
                    if not unit.structure_is_built(
                    ) and unit.team == config.my_team:
                        worker_actions.destination = unit.location.map_location(
                        )
                        worker_actions.moving_to_build = True
                        worker_actions.building_rocket = False
                        Navigation.fuzzygoto(
                            gc.unit(unit_id).id, worker_actions.destination)
                        return

        worker_actions.building_rocket = False
        worker_actions.worker_moving_to_build = False
        return
Example #18
0
 def __init__(self):
     log.info('Loading BestPlayer')
     self.settings = settings.TVSettings()
     self.parser = Parser.Parser()
     self.up = urlparser.urlparser()
     self.cm = pCommon.common()
     self.history = pCommon.history()
     self.navigation = Navigation.VideoNav()
     self.chars = pCommon.Chars()
     self.exception = Errors.Exception()
Example #19
0
 def __init__(self):
     log.info("Starting TVN Player")
     self.parser = Parser.Parser()
     self.navigation = Navigation.VideoNav()
     self.common = pCommon.common()
     self.exception = Errors.Exception()
     if quality_manual == 'true':
         ptv.setSetting('tvn_quality_temp', '')
     elif quality_manual == 'false':
         ptv.setSetting('tvn_quality_temp', quality)
Example #20
0
def manage_healers(gc, unit):
    """
    Runs all of the healers. Takes in a GameController object and a unit as
    inputs.
    """
    location = unit.location
    violent_enemies = [bc.UnitType.Ranger, bc.UnitType.Mage, bc.UnitType.Knight]
    if location.is_on_map() and not location.is_in_garrison():
        nearby_units = gc.sense_nearby_units(location.map_location(), unit.vision_range)
        gc.is_overcharge_ready(unit.id)
        to_heal = None
        retreat_from = None
        found = False
        for patient in nearby_units:
            if unit.team == Globals.them:
                Globals.radar.update_enemy_cache(patient)
                if patient.unit_type in violent_enemies and patient.location.is_within_range(patient.attack_range(), unit.location) and gc.is_move_ready(unit.id):
                    retreat_from = patient
                    break
            elif gc.can_heal(unit.id, patient.id) and patient.health < patient.max_health and gc.is_heal_ready(unit.id):
                if patient.unit_type != bc.UnitType.Worker:
                    to_heal = patient
                    found = True
                elif not found:
                    to_heal = patient
        if retreat_from is not None:
            moved = Navigation.retreatFromKnownEnemy(gc, unit, retreat_from.location.map_location())
            if moved:
                return
        if to_heal is not None:
            if gc.is_overcharge_ready(unit.id) and gc.can_overcharge(unit.id, to_heal.id):
                print("OVERCHARGING")
                gc.overcharge(unit.id, to_heal.id)
                run_turn(gc, to_heal)
                return
            gc.heal(unit.id, to_heal.id)
            return

    if gc.is_move_ready(unit.id):
        if gc.is_heal_ready(unit.id):
            planet = location.map_location().planet
            path = Globals.updatePath if planet == bc.Planet.Earth else Globals.updatePathMars
            Navigation.path_with_bfs(gc, unit, path)
Example #21
0
def attack_move(unit_id):
    attackableEnemies = gc.sense_nearby_units_by_team(gc.unit(unit_id).location.map_location(),
                                                      gc.unit(unit_id).attack_range(), config.enemy_team)

    if len(attackableEnemies) <= 0 and len(config.global_enemy_scan) <= 0:
        return False

    if len(attackableEnemies) > 0:

        Navigation.a_star_move(unit_id, attackableEnemies[0].location.map_location())
        if gc.is_attack_ready(gc.unit(unit_id).id) and gc.can_attack(gc.unit(unit_id).id,
                                                                     attackableEnemies[0].id) and gc.unit(
                unit_id).attack_heat() < 10:
            gc.attack(gc.unit(unit_id).id, attackableEnemies[0].id)

        return True

    else:
        if len(config.global_enemy_scan) > 0:
            destination = config.global_enemy_scan[0].location.map_location()
            distance_to_enemy = gc.unit(unit_id).location.map_location().distance_squared_to(destination)
            if distance_to_enemy > 100:
                Navigation.fuzzygoto(unit_id, config.global_enemy_scan[0].location.map_location())
            else:
                Navigation.a_star_move(unit_id, destination)

            return True

    return False
    def find_karbonite(unit_id):

        start = Navigation.trans_coord_to_np(
            gc.unit(unit_id).location.map_location())
        start = (start[0], start[1])

        if config.karbonite_map[
                start[0], start[1]] > 0 or config.karbonite_depleted == True:
            # print("found karbonite at",start[0],start[1])
            return Navigation.trans_coord_to_ml(start[0], start[1])

        levels = max(config.planet_map.planet_x, config.planet_map.planet_y)
        y_root = start[0]
        x_root = start[1]

        for level in range(1, levels + 1):
            y_allowed = [level, -level]
            x_allowed = [level, -level]
            for y in y_allowed:
                for x in range(-level, level + 1):
                    if 0 <= x + x_root < config.planet_map.planet_x and 0 <= y + y_root < config.planet_map.planet_y:
                        # print(y + y_root,config.planet_map.planet_y-1, x + x_root,config.planet_map.planet_x-1)
                        if config.karbonite_map[y + y_root, x + x_root] > 0:
                            # print("found karbonite", y + y_root, x + x_root,config.karbonite_map[y + y_root, x + x_root])
                            return Navigation.trans_coord_to_ml(
                                y + y_root, x + x_root)
            for x in x_allowed:
                for y in range(-(level + 1), level):
                    if 0 <= x + x_root < config.planet_map.planet_x and 0 <= y + y_root < config.planet_map.planet_y:
                        # print(y + y_root, config.planet_map.planet_y - 1, x + x_root, config.planet_map.planet_x - 1)
                        if config.karbonite_map[y + y_root, x + x_root] > 0:
                            # print("found karbonite", y + y_root, x + x_root,config.karbonite_map[y + y_root, x + x_root])
                            return Navigation.trans_coord_to_ml(
                                y + y_root, x + x_root)
        config.karbonite_depleted = True
        return gc.unit(unit_id).location.map_location()
Example #23
0
    def __init__(self):
        super().__init__()

        self.title = 'NixLacs GUI - Relacs > Nix > GUI'

        # set MainWindow instance in config / fileInteractions
        Config.setMainWindow(self)
        FileInteractions.setMainWindow(self)

        self.setupUi()

        self.navigation = Navigation(self)
        self.content = Content(self)

        self.sigConfirmDialog.connect(self.displayConfirmDialog)
Example #24
0
def Nav(Flora, gx, gy):
    goal = 0
    while (not goal):
        tmp = Flora.pose()
        A = ConvertMapToScatter(Flora)
        ox, oy
        for i in range(10):
            rx, ry = Navigation.NAV(tmp[0], tmp[1], gx, gy, ox, oy, flora.rad,
                                    1, i * 20)
            if len(rx) != 0:
                break
        for i in range(len(rx)):
            Flag = Flora.drivexy(rx, ry)
            if Flag == -1:  #OBSTACLE
                UpdateMapForObstacle(Flora)
                break
        goal = 1
    return rx, ry
Example #25
0
  def __init__(self, parent = None):
    super(View, self).__init__(parent)

    self.figure = plt.figure()
    self.canvas = FigureCanvas(self.figure)
    self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
    self.canvas.setMinimumHeight(200)    
    toolbar = NavigationToolbar(self.canvas, self)
    
    self.navigation = Navigation.Navigation(self)
    self.navigation.activeItemChanged.connect(self.updateVisualisation)
    self.navigation.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Minimum)
    
    self.info = Info.Info(self)

    hLayout = QHBoxLayout()
    hLayout.addWidget(self.navigation)
    hLayout.addWidget(self.info)  
    
    layout = QVBoxLayout(self)
    layout.addLayout(hLayout)
    layout.addWidget(toolbar)
    layout.addWidget(self.canvas)
Example #26
0
import sys
sys.path.append('/home/pi/Navigation')
import Navigation
from RPi.GPIO import cleanup
from time import sleep

#main
"""
Navigation.turnleft(60)
sleep(3)
Navigation.turnright(60)
"""
"""
Remember turn functions have built in sleep
around (2) seconds to complete a turn
"""
#Route 100
Navigation.turnright(47) #turn toward objective A1
sleep(0.5)
Navigation.stop()
sleep(1)
Navigation.forward(50)  #move towards objective A1
sleep(1.4)
Navigation.stop() #simulate button hit time
sleep(4)          #simulate completion of first objective
Navigation.backward(50) #return to center
sleep(1.4)
Navigation.stop()
sleep(1)
Navigation.turnleft(47)    #turn towards plank
sleep(0.5)
Example #27
0
class PointCloud(object):
    def __init__(self, queue_dict):
        self.queues = queue_dict
        # filter properties
        self.toofar = 3
        self.toohigh = 1
        self.n = 500
        #n = 500
        #self.n = math.floor(math.sqrt(n))

        # create row and column structures
        message = self.queues["input"].retrieve(method="recent")
        self.height, self.width = message["images"]["depth"].shape
        self.rows = np.arange(start=0, stop=self.height)[:, np.newaxis]
        self.rows = np.repeat(self.rows, self.width, axis=1)
        self.cols = np.ones(self.height)[:, np.newaxis] * np.arange(
            start=0, stop=self.width)
        #self.rows = np.arange(start=0, stop=self.height)
        #self.rows = np.repeat(self.rows, self.width)
        #self.cols = np.arange(start=0, stop=self.width)
        #self.cols = np.tile(self.cols, self.height)
        #self.cols = self.cols.flatten()

        # init camera
        self.near_clip = 0.1
        self.far_clip = 10
        self.cx = math.floor(self.width / 2)
        self.cy = math.floor(self.height / 2)
        FOV = 90
        self.f = 320 / math.tan(math.pi * (FOV / 2) / 180)

        # grouping
        self.k = 10

        # create mapping class instances
        self.map = AngleMapper(self.toofar)
        self.nav = Navigation(point_range=self.toofar, size=3 * self.toofar)

        # create windows
        self.images_display = NamedWindow("images", size=(500, 500))
        self.angles_display = NamedWindow("angles",
                                          place=(500, 0),
                                          size=(500, 500),
                                          conversions="heat_map")
        self.coded_display = NamedWindow("coded",
                                         place=(1000, 500),
                                         size=(500, 500))
        self.detection_display = NamedWindow("Litter Detection",
                                             place=(1000, 0),
                                             size=(500, 500))
        # self.large_display = NamedWindow("cost", place=(500, 500), size=(500, 500))

        # find original position of camera
        self.original_orientation = np.array(
            [-1.56821251, 0, 3.14152694])  # np.array(message["orientation"])
        self.original_position = np.array(message["position"])

        self.C_svd = C_svd

    def litter_localiser(self, corner, z, scale=0.2):
        # bottom right is index 0 and corners are in cartesian coords
        # not row / col
        # first find center
        br = corner[0]
        tr = corner[1]
        half_box_size = [abs(br[0] - tr[0]) / 2, abs(br[1] - tr[1]) / 2]
        half_box_size[0], half_box_size[1] = math.floor(
            half_box_size[0] * scale), math.floor(half_box_size[1] * scale)
        center = [
            math.floor((br[0] + tr[0]) / 2),
            math.floor((br[1] + tr[1]) / 2)
        ]
        br = center[0] - half_box_size[0], center[1] - half_box_size[1]
        tr = center[0] + half_box_size[0], center[1] + half_box_size[1]
        z_selected = z[br[1]:tr[1], br[0]:tr[0]]
        rows, cols = self.rows[br[1]:tr[1],
                               br[0]:tr[0]], self.cols[br[1]:tr[1],
                                                       br[0]:tr[0]]
        # find x and y coords
        x = (cols - self.cx) * z_selected / self.f
        y = (self.cy - rows) * z_selected / self.f
        x, y, z_selected = [np.mean(arr) for arr in [x, y, z_selected]]
        return [x, y, z_selected]

    def main_loop(self):
        # get data from other process
        message = self.queues["input"].retrieve(method="recent")

        start = time.time()
        # convert current depth images to meters
        depth = message["images"]["depth"] * (self.far_clip -
                                              self.near_clip) + self.near_clip

        # litter_location = self.litter_localiser(z, message["detections"])

        # reduce size to save computation time
        # create random row and col indices to select random values from 2d arrays
        random_indices = np.array([
            np.random.randint(low=0, high=self.height, size=self.n),
            np.random.randint(low=0, high=self.width, size=self.n)
        ])
        z, rows, cols = self.select([depth, self.rows, self.cols],
                                    random_indices,
                                    two_dim=True)

        # zero orientation and position from original frame
        euler = np.array(message["orientation"]) - self.original_orientation
        position = np.array(message["position"]) - self.original_position
        R = self.euler2rotation(euler)

        # find position of any detections
        if message["detections"] is not None:
            litter_locations = list(
                map(lambda corner: self.litter_localiser(corner, depth),
                    message["detections"]))
            litter_locations = [
                np.matmul(R,
                          np.array(loc)[:, np.newaxis])
                for loc in litter_locations
            ]
        else:
            litter_locations = None

        # filter objects too far away
        toofar = np.where(z < self.toofar)
        z, rows, cols = self.select([z, rows, cols], toofar)
        z = z[np.where(z < self.toofar)]

        # find x and y coords
        x = (cols - self.cx) * z / self.f
        y = (self.cy - rows) * z / self.f

        x, y, z = np.matmul(R, np.array([x, y, z]))

        toohigh = np.where(np.abs(y) < self.toohigh)
        x, y, z, rows, cols = self.select([x, y, z, rows, cols], toohigh)

        if z.size > 20:
            time1 = time.time()
            xb = x[:, np.newaxis] - x
            yb = y[:, np.newaxis] - y
            zb = z[:, np.newaxis] - z
            d = (xb**2) + (yb**2) + (zb**2)
            #PrintFunctionTime("\nbroad", time1)

            #time2 = time.time()
            closest = np.argpartition(d, self.k, axis=0)[:self.k]
            #PrintFunctionTime("sorting", time2)

            #p_time = time.time()
            #angles = np.apply_along_axis(self.SVD, 0, closest, x, y, z)
            #PrintFunctionTime("p_time", p_time)

            #c_time = time.time()
            groups = np.array([x[closest], y[closest], z[closest]])
            groups_mean = np.mean(groups, axis=1)
            groups = groups - groups_mean[:, np.newaxis, :]
            #print(groups[:, :, 0])
            #print(groups.shape)
            angles = self.C_svd(groups)
            # dum = np.abs(angles)
            #print(dum)

            angles = np.abs(angles - 1)
            #PrintFunctionTime("c_time", time1)

            #print(f"Cloud takes: {round((time.time() - start) * 1000, 3)}ms, FPS: {round(1 / (time.time() - start), 3)}")
            # timing the updates
            start_mn = time.time()
            self.map.update(x, z, angles, euler, position)
            self.nav.update(self.map.large_coded, self.map.position, euler,
                            litter_locations)

            # print(f"Map&Nav takes: {round((time.time() - start_mn) * 1000, 3)}ms, FPS: {round(1 / (time.time() - start_mn), 3)}")

        self.angles_display.show(self.map.small_map, max_value=1)
        self.coded_display.show(self.nav.map_vis)
        self.images_display.show(message["images"]["display"])
        self.detection_display.show(message["images"]["RGB"])
        if cv2.waitKey(1) & 0xFF == ord('q'):
            return "break"
        # self.large_display.show(self.nav.distances)

        self.queues["output"].send(self.nav.speed, method="no_wait")

    def euler2rotation(self, euler):
        """
        taken from https://en.wikipedia.org/wiki/Rotation_matrix
        """
        a, b, g = euler[0], euler[1], euler[2]
        return np.array([[
            cos(a) * cos(b),
            cos(a) * sin(b) * sin(g) - sin(a) * cos(g),
            cos(a) * sin(b) * cos(g) + sin(a) * sin(g)
        ],
                         [
                             sin(a) * cos(b),
                             sin(a) * sin(b) * sin(g) + cos(a) * cos(g),
                             sin(a) * sin(b) * cos(g) - cos(a) * sin(g)
                         ], [-sin(b),
                             cos(b) * sin(g),
                             cos(b) * cos(g)]])

    def SVD(self, closest, x, y, z):
        group = np.array([x[closest], y[closest], z[closest]])
        centroid = np.mean(group, axis=1)[:, np.newaxis]
        relative = group - centroid
        svd = np.transpose(np.linalg.svd(relative))
        normal = np.transpose(svd[0])[2]
        return np.abs(np.dot(normal, [0, 1, 0]))

    def select(self, arrays, indices, two_dim=False):
        if two_dim:
            return [array[indices[0], indices[1]] for array in arrays]
        else:
            return [array[indices] for array in arrays]

    def cleanup(self):
        # close all queues
        for _, q in self.queues.items():
            q.close()
Example #28
0
def processAzSlice(model_residuals,svs,args,params,numDays,minVal_dt,az) :
    
    tSat = np.size(svs) * (int(14./args.nadir_grid) + 2)
    tSite = int(90./args.zen) + 1 
    numParams = tSat + tSite
    Neq = np.zeros((numParams,numParams))
    AtWb = np.zeros(numParams)
    SiteFreq = np.zeros(tSite)
    # set up a lookup dictionary
    lookup_svs = {}
    lctr = 0
    for sv in svs:
        lookup_svs[str(sv)] = lctr
        lctr+=1
        
    site_geocentric_distance = np.linalg.norm(params['sitepos'])

    for d in range(0,numDays):
        minDTO = minVal_dt + dt.timedelta(days = d)
        maxDTO = minVal_dt + dt.timedelta(days = d+1)
                        
        #print(d,"Stacking residuals on:",minDTO,maxDTO)
        criterion = ( ( model_residuals[:,0] >= calendar.timegm(minDTO.utctimetuple()) ) &
                      ( model_residuals[:,0] < calendar.timegm(maxDTO.utctimetuple()) ) )
        tind = np.array(np.where(criterion))[0]
        
        # if there are less than 300 obs, then skip to the next day
        if np.size(tind) < 300:
            continue
        
        #print("rejecting any residuals greater than 100mm",np.shape(site_residuals))
        tdata = res.reject_absVal(model_residuals[tind,:],100.)
        
        #print("rejecting any residuals greater than 5 sigma",np.shape(tdata))
        data = res.reject_outliers_elevation(tdata,5,0.5)
        #print("finished outlier detection",np.shape(data))
        del tdata
        
        # determine the elevation dependent weighting
        a,b = res.gamitWeight(data)
        
        if(az - args.az/2. < 0) :
            criterion = (data[:,1] < (az + args.az/2.)) | (data[:,1] > (360. - args.az/2.) )
        else:
            criterion = (data[:,1] < (az + args.az/2.)) & (data[:,1] > (az - args.az/2.) )
            
        azind = np.array(np.where(criterion))[0]
        #print("Size of data before azimuth search",np.size(data))
        data = data[azind,:]    
        #print("Size of data after azimuth search",np.size(data))
        # parse the broadcast navigation file for this day to get an accurate
        # nadir angle
        yy = minDTO.strftime("%y") 
        doy = minDTO.strftime("%j") 
        navfile = args.brdc_dir + 'brdc'+ doy +'0.'+ yy +'n'
        #print("Will read in the broadcast navigation file:",navfile)
        nav = rnxN.parseFile(navfile)
        
        # Get the total number of observations for this site
        numd = np.shape(data)[0]
        #print("Have:",numd,"observations")
        for i in range(0,numd):
            # work out the svn number
            svndto =  gt.unix2dt(data[i,0])
            svn = svnav.findSV_DTO(svdat,data[i,4],svndto)
            svn_search = 'G{:03d}'.format(svn) 
            #print("Looking for:",svn_search,lookup_svs)
            ctr = lookup_svs[str(svn_search)]
            #print("Position is CTR:",ctr,data[i,4])
            try:
                # get the satellite position
                svnpos = rnxN.satpos(data[i,4],svndto,nav)
                #print("SVNPOS:",svnpos[0])
                satnorm = np.linalg.norm(svnpos[0])
                #print("NORM:",np.linalg.norm(svnpos[0]))
            except:
                print("Error calculation satelite position for",svndto,data[i,:])
                continue
        
            # work out the nadir angle
            nadir = NADIR.calcNadirAngle(data[i,2],site_geocentric_distance,satnorm)
            #print("Ele {:.2f} Old: {:.2f} New:{:.2f}".format(data[i,2],oldnadir,nadir))
            #print("Ele {:.2f} New:{:.2f}".format(data[i,2],nadir))
            w = a**2 + b**2/np.sin(np.radians(90.-data[i,2]))**2
            w = 1./w
        
            # Work out the indices for the satellite parameters
            niz = int(np.floor(nadir/args.nadir_grid))
            iz = int((numParamsPerSat * ctr) + niz)
            pco_iz = numParamsPerSat * (ctr+1) - 1 
        
            # work out the location of site parameters
            nsiz = int(np.floor(data[i,2]/args.zen))
            #aiz = int(np.floor(data[i,1]/args.az))
            
            #siz = int( tSat +  (m*numParamsPerSite) + (aiz * nZen) + nsiz)
            siz = int( tSat + nsiz)
        
            # check that the indices are not overlapping
            if iz+1 >= pco_iz or iz >= pco_iz:
                #print("WARNING in indices iz+1 = pco_iz skipping obs",nadir,iz,pco_iz)
                continue
        
            #NadirFreq[ctr,niz] = NadirFreq[ctr,niz] +1
            SiteFreq[nsiz] = SiteFreq[nsiz] +1
            #
            # R = SITE_PCV_ERR + SAT_PCV_ERR + SAT_PCO_ERR * cos(nadir)
            #
            # dR/dSITE_PCV_ERR = 1
            # dR/dSAT_PCV_ERR  = 1 
            # dR/dSAT_PCO_ERR  = cos(nadir)
            #
            # nice partial derivative tool:
            #  http://www.symbolab.com/solver/partial-derivative-calculator
            #
            # Nadir partials..
            Apart_1 = (1.-(nadir-niz*args.nadir_grid)/args.nadir_grid)
            Apart_2 = (nadir-niz*args.nadir_grid)/args.nadir_grid
            #
            # PCO partial ...
            Apart_3 = np.cos(np.radians(nadir)) 
        
            # Site partials
            Apart_4 = (1.-(data[i,2]-nsiz*args.zen)/args.zen)
            Apart_5 = (data[i,2]-nsiz*args.zen)/args.zen
            #print("Finished forming Design matrix")
         
            #print("Starting AtWb",np.shape(AtWb),iz,pco_iz,siz)
            AtWb[iz]     = AtWb[iz]     + Apart_1 * data[i,3] * w
            AtWb[iz+1]   = AtWb[iz+1]   + Apart_2 * data[i,3] * w
            AtWb[pco_iz] = AtWb[pco_iz] + Apart_3 * data[i,3] * w
            AtWb[siz]    = AtWb[siz]    + Apart_4 * data[i,3] * w
            AtWb[siz+1]  = AtWb[siz+1]  + Apart_5 * data[i,3] * w
            #print("Finished forming b vector")
        
            Neq[iz,iz]     = Neq[iz,iz]     + (Apart_1 * Apart_1 * w)
            Neq[iz,iz+1]   = Neq[iz,iz+1]   + (Apart_1 * Apart_2 * w)
            Neq[iz,pco_iz] = Neq[iz,pco_iz] + (Apart_1 * Apart_3 * w)
            Neq[iz,siz]    = Neq[iz,siz]    + (Apart_1 * Apart_4 * w)
            Neq[iz,siz+1]  = Neq[iz,siz+1]  + (Apart_1 * Apart_5 * w)
        
            Neq[iz+1,iz]     = Neq[iz+1,iz]     + (Apart_2 * Apart_1 * w)
            Neq[iz+1,iz+1]   = Neq[iz+1,iz+1]   + (Apart_2 * Apart_2 * w)
            Neq[iz+1,pco_iz] = Neq[iz+1,pco_iz] + (Apart_2 * Apart_3 * w)
            Neq[iz+1,siz]    = Neq[iz+1,siz]    + (Apart_2 * Apart_4 * w)
            Neq[iz+1,siz+1]  = Neq[iz+1,siz+1]  + (Apart_2 * Apart_5 * w)
            #print("Finished NEQ Nadir estimates")
        
            Neq[pco_iz,iz]     = Neq[pco_iz,iz]     + (Apart_3 * Apart_1 * w)
            Neq[pco_iz,iz+1]   = Neq[pco_iz,iz+1]   + (Apart_3 * Apart_2 * w)
            Neq[pco_iz,pco_iz] = Neq[pco_iz,pco_iz] + (Apart_3 * Apart_3 * w)
            Neq[pco_iz,siz]    = Neq[pco_iz,siz]    + (Apart_3 * Apart_4 * w)
            Neq[pco_iz,siz+1]  = Neq[pco_iz,siz+1]  + (Apart_3 * Apart_5 * w)
            #print("Finished NEQ PCO estimates")
        
            Neq[siz,iz]     = Neq[siz,iz]     + (Apart_4 * Apart_1 * w)
            Neq[siz,iz+1]   = Neq[siz,iz+1]   + (Apart_4 * Apart_2 * w)
            Neq[siz,pco_iz] = Neq[siz,pco_iz] + (Apart_4 * Apart_3 * w)
            Neq[siz,siz]    = Neq[siz,siz]    + (Apart_4 * Apart_4 * w)
            Neq[siz,siz+1]  = Neq[siz,siz+1]  + (Apart_4 * Apart_5 * w)
        
            Neq[siz+1,iz]     = Neq[siz+1,iz]     + (Apart_5 * Apart_1 * w)
            Neq[siz+1,iz+1]   = Neq[siz+1,iz+1]   + (Apart_5 * Apart_2 * w)
            Neq[siz+1,pco_iz] = Neq[siz+1,pco_iz] + (Apart_5 * Apart_3 * w)
            Neq[siz+1,siz]    = Neq[siz+1,siz]    + (Apart_5 * Apart_4 * w)
            Neq[siz+1,siz+1]  = Neq[siz+1,siz+1]  + (Apart_5 * Apart_5 * w)
            #print("Finished NEQ Site estimates")
            
            if siz == pco_iz:
                print("ERROR in indices siz = pco_iz")
                
                
    # Add the parameter constraints to the Neq
    #Neq = np.add(Neq,C_inv) 
    C_inv = formConstraints(args,tSat,tSite,1,numParams)
    Neq = np.add(Neq,C_inv)
    #print("Inverting")
    Cov = np.linalg.pinv(Neq)
    Sol = np.dot(Cov,AtWb)

    stdev = np.sqrt(np.diag(Cov))
    
    return Sol, stdev, SiteFreq, az
Example #29
0
def init_nav():
    print("init nav")
    import Navigation
    import NavigationInstance
    NavigationInstance.instance = Navigation.Navigation()
# Then let's import the logging module so we can print out information
import logging
import Navigation

# GAME START
# Here we define the bot's name as Settler and initialize the game, including communication with the Halite engine.
game = hlt.Game("Settler")
# Then we print our start message to the logs
logging.info("Starting my Settler bot!")

while True:
    # TURN START
    # Update the map for the new turn and get the latest version
    game_map = game.update_map()

    Planner = Navigation.PathPlanner(game_map)

    # Here we define the set of commands to be sent to the Halite engine at the end of the turn
    command_queue = []
    # For every ship that I control
    for ship in game_map.get_me().all_ships():
        # If the ship is docked
        if ship.docking_status != ship.DockingStatus.UNDOCKED:
            # Skip this ship
            continue

        # For each planet in the game (only non-destroyed planets are included)
        for planet in game_map.all_planets():
            # If the planet is owned
            if planet.is_owned():
                # Skip this planet
Example #31
0
import sys

import Parsers
import Consolidation
import Reports
import Charts
import Navigation

from Config import *

if __name__ == "__main__":
    #fout = open('EVENT.log', 'w')
    #temp = sys.stdout
    #sys.stdout = fout
    ReadConfigFile()
    #Run parsers
    
    Parsers.main()
    #Run consolidation
    Consolidation.main()
    #run reports
    Reports.main()
    #run charts
    Charts.main()
    #run navigation
    Navigation.GenerateNavigation()
    raw_input('All done! Please hit Enter key to continue...')
    #sys.stdout.close()
    #sys.stdout = temp
    
Example #32
0
def print_all_classes(browser):
    # go to classes list
    Nav.perform_std(browser, "Pcl")
    find_all_departments(browser)

    # why like this? because i suck at character encoding o ina
    shin = "ش"
    ye = "ي"
    dal = "د"
    sin = "س"
    for dep_id in all_departments.keys():
        select = Select(browser.find_element_by_id('edDepartment'))
        # select department by department id
        select.select_by_value(dep_id)
        browser.execute_script("Save()")
        dep_page_source = browser.page_source
        idents_list = find_all_ident(dep_page_source)
        # for every class in a department:
        for ident in idents_list:
            # navigate to the class detail page
            Nav.perform(browser, 'Edit;Ident={}'.format(ident))
            # get every section of a class
            sections = get_class_info(browser.page_source)
            # extract other info of the class
            class_info = find_class_info(browser.page_source)

            # for every section of the class put class info in it's relevant day
            for section in sections:
                if str(section)[0] != "<":
                    class_location = re.search(
                        '\(([^\)]+)\)', section.encode("utf-8")).group()
                    section = fix_letters(section).encode("utf-8").replace(
                        class_location, '')
                    class_time = section.split('-')[1]
                    class_day = section.split('-')[0]
                    data = {
                        "day": class_day,
                        "title": class_info[0].encode("utf-8"),
                        "class_loc": class_location,
                        "class_time": class_time,
                        "teacher": class_info[1],
                        "exam_date": class_info[2].encode("utf-8"),
                        "exam_time": class_info[3].encode("utf-8"),
                        "id": class_info[4].encode("utf-8"),
                        "units": class_info[5].encode("utf-8"),
                        "group": class_info[6].encode("utf-8"),
                        "capacity": class_info[7].encode("utf-8"),
                        "department": {
                            "id": dep_id,
                            "title": all_departments[dep_id],
                        }
                    }

                    # SAT
                    if class_day[0] == shin:
                        all_classes[0].append(data)
                        # SUN
                    elif class_day[0] == ye:
                        all_classes[1].append(data)
                        # MON
                    elif class_day[0] == dal:
                        all_classes[2].append(data)
                        # TUE
                    elif class_day[0] == sin:
                        all_classes[3].append(data)
                        # WED
                    else:
                        all_classes[4].append(data)

            Nav.back(browser)

    # save extracted data as a json file
    with open('data.json', 'w+') as outfile:
        json.dump(
            {
                "classes": all_classes,
                "teachers": all_teachers,
                "departments": all_departments,
            },
            outfile,
            ensure_ascii=False)
Example #33
0
def init_nav():
    print "init nav"
    import Navigation, NavigationInstance
    NavigationInstance.instance = Navigation.Navigation()
def worker_actions(unit_id):
    if not gc.can_sense_unit(unit_id):
        return
    this_worker = gc.unit(unit_id)
    config.my_units = gc.my_units()
    worker_actions.building_rocket = False
    worker_actions.building_factory = False
    worker_actions.moving_to_build = False
    worker_actions.harvesting_karbonite = False
    worker_actions.harvesting_location = False

    worker_actions.destination = None
    worker_actions.moving_to_harvest = False
    worker_actions.boarded_rocket = False
    worker_actions.avoiding_enemies = False
    worker_actions.moving_to_board_rocket = False

    def build_rocket(unit_id):
        worker_actions.building_rocket = False
        worker_actions.worker_moving_to_build = False
        if gc.round(
        ) >= config.rocket_target_round and config.rocket_count < config.rocket_target:
            for dir in directions:
                if gc.can_blueprint(unit_id, bc.UnitType.Rocket, dir):
                    gc.blueprint(unit_id, bc.UnitType.Rocket, dir)
                    config.rocket_count = config.rocket_count + 1
                    worker_actions.building_rocket = True
                    worker_actions.moving_to_build = False
                    return

        very_nearby_rockets = gc.sense_nearby_units_by_type(
            gc.unit(unit_id).location.map_location(), 1, bc.UnitType.Rocket)
        if len(very_nearby_rockets) > 0:
            for unit in very_nearby_rockets:
                if not unit.structure_is_built(
                ) and unit.team == config.my_team:
                    blueprint_waiting = unit.id
                    if gc.can_build(unit_id, blueprint_waiting):
                        gc.build(unit_id, blueprint_waiting)
                        worker_actions.moving_to_build = False
                        worker_actions.building_rocket = True
                        return

        nearby_rockets = gc.sense_nearby_units_by_type(
            gc.unit(unit_id).location.map_location(), 60, bc.UnitType.Rocket)
        if worker_actions.building_rocket is False:
            if len(nearby_rockets) > 0:
                for unit in nearby_rockets:
                    if not unit.structure_is_built(
                    ) and unit.team == config.my_team:
                        worker_actions.destination = unit.location.map_location(
                        )
                        worker_actions.moving_to_build = True
                        worker_actions.building_rocket = False
                        Navigation.fuzzygoto(
                            gc.unit(unit_id).id, worker_actions.destination)
                        return

        worker_actions.building_rocket = False
        worker_actions.worker_moving_to_build = False
        return

    def build_factory(unit_id):
        worker_actions.building_factory = False
        worker_actions.moving_to_build = False
        if config.factory_count < config.factory_target and gc.round(
        ) < config.rocket_target_round:
            for dir in directions:
                if gc.can_blueprint(unit_id, bc.UnitType.Factory, dir):
                    gc.blueprint(unit_id, bc.UnitType.Factory, dir)
                    config.factory_count = config.factory_count + 1
                    worker_actions.building_factory = True
                    worker_actions.moving_to_build = False
                    return

        very_nearby_factories = gc.sense_nearby_units_by_type(
            gc.unit(unit_id).location.map_location(), 1, bc.UnitType.Factory)

        if len(very_nearby_factories) > 0:
            for unit in very_nearby_factories:
                if not unit.structure_is_built(
                ) and unit.team == config.my_team:
                    # factories_qued = factories_qued + 1
                    blueprint_waiting = unit.id
                    if gc.can_build(unit_id, blueprint_waiting):
                        gc.build(unit_id, blueprint_waiting)
                        worker_actions.building_factory = True
                        worker_actions.moving_to_build = False
                        return

        nearby_factories = gc.sense_nearby_units_by_type(
            gc.unit(unit_id).location.map_location(), 16, bc.UnitType.Factory)
        if worker_actions.building_factory is False:
            if len(nearby_factories) > 0:
                for unit in nearby_factories:
                    if not unit.structure_is_built(
                    ) and unit.team == config.my_team:
                        # print("factory built",unit.structure_is_built())
                        worker_actions.destination = unit.location.map_location(
                        )
                        worker_actions.building_factory = False
                        worker_actions.moving_to_build = True
                        # print("inner move to build",worker_actions.moving_to_build)
                        Navigation.fuzzygoto(
                            gc.unit(unit_id).id, worker_actions.destination)
                        return
        worker_actions.building_factory = False
        worker_actions.moving_to_build = False

        return

    def replicate(unit_id):

        if gc.unit(unit_id).location.is_on_planet(bc.Planet.Earth):
            if config.worker_count < 3 or (config.factory_count >= 1 and config.worker_count < config.worker_target) or \
                    (worker_actions.harvesting_karbonite == True and config.worker_count < min(
                        int(config.planet_map.planet_total_starting_karbonite / 300), 20)):
                for dir in directions:
                    if gc.can_replicate(unit_id, dir):
                        gc.replicate(unit_id, dir)
                        config.worker_count = config.worker_count + 1

        if gc.unit(unit_id).location.is_on_planet(bc.Planet.Mars):
            for dir in directions:
                if gc.can_replicate(unit_id,
                                    dir) and config.worker_count < 100:
                    gc.replicate(unit_id, dir)
                    config.worker_count = config.worker_count + 1

    def harvest_karbonite(unit_id):

        tick = time.clock()
        loc = find_karbonite(unit_id)

        tock = time.clock()
        # print("time to find karb", (tick - tock) * 1000, loc, gc.unit(unit_id).location.map_location())

        # print("distance to karb", loc.distance_squared_to(gc.unit(unit_id).location.map_location()))

        if gc.unit(unit_id).location.map_location().distance_squared_to(
                loc) <= 2:
            harvest_karbonite_at_location(loc)
            # print("harvesting, less than 2 dist, 141")

        if gc.unit(unit_id).location.map_location().distance_squared_to(
                loc) > 2:
            Navigation.a_star_move(unit_id, loc)

    def harvest_karbonite_at_location(loc):
        np_loc = Navigation.trans_coord_to_np(loc)
        # print(np_loc)
        y = np_loc[0]
        x = np_loc[1]
        # print(y,x)
        if gc.can_sense_location(loc):
            karb_at_loc = gc.karbonite_at(loc)
            # print("karb at location",karb_at_loc)
            if karb_at_loc == 0:
                config.karbonite_map[y, x] = 0
                # print("updated karb",config.karbonite_map[y,x])
                worker_actions.harvesting_karbonite = False
                worker_actions.harvesting_location = None
            if karb_at_loc > 0:
                config.karbonite_map[y, x] = karb_at_loc
                # print("updated karb",config.karbonite_map[y,x])
                bestDir = gc.unit(
                    unit_id).location.map_location().direction_to(loc)
                # print("karb direction", bestDir)
                if gc.can_harvest(gc.unit(unit_id).id, bestDir):
                    gc.harvest(gc.unit(unit_id).id, bestDir)
                    # print("harvested", bestDir)
                    worker_actions.harvesting_karbonite = True
                    worker_actions.harvesting_location = loc

    def find_karbonite(unit_id):

        start = Navigation.trans_coord_to_np(
            gc.unit(unit_id).location.map_location())
        start = (start[0], start[1])

        if config.karbonite_map[
                start[0], start[1]] > 0 or config.karbonite_depleted == True:
            # print("found karbonite at",start[0],start[1])
            return Navigation.trans_coord_to_ml(start[0], start[1])

        levels = max(config.planet_map.planet_x, config.planet_map.planet_y)
        y_root = start[0]
        x_root = start[1]

        for level in range(1, levels + 1):
            y_allowed = [level, -level]
            x_allowed = [level, -level]
            for y in y_allowed:
                for x in range(-level, level + 1):
                    if 0 <= x + x_root < config.planet_map.planet_x and 0 <= y + y_root < config.planet_map.planet_y:
                        # print(y + y_root,config.planet_map.planet_y-1, x + x_root,config.planet_map.planet_x-1)
                        if config.karbonite_map[y + y_root, x + x_root] > 0:
                            # print("found karbonite", y + y_root, x + x_root,config.karbonite_map[y + y_root, x + x_root])
                            return Navigation.trans_coord_to_ml(
                                y + y_root, x + x_root)
            for x in x_allowed:
                for y in range(-(level + 1), level):
                    if 0 <= x + x_root < config.planet_map.planet_x and 0 <= y + y_root < config.planet_map.planet_y:
                        # print(y + y_root, config.planet_map.planet_y - 1, x + x_root, config.planet_map.planet_x - 1)
                        if config.karbonite_map[y + y_root, x + x_root] > 0:
                            # print("found karbonite", y + y_root, x + x_root,config.karbonite_map[y + y_root, x + x_root])
                            return Navigation.trans_coord_to_ml(
                                y + y_root, x + x_root)
        config.karbonite_depleted = True
        return gc.unit(unit_id).location.map_location()

    if this_worker.location.is_on_planet(
            bc.Planet.Earth) and not (this_worker.location.is_in_garrison()
                                      or this_worker.location.is_in_space()):
        # tick=time.clock()
        worker_actions.avoid_enemies = Utilities.avoid_enemies(unit_id)
        # tock=time.clock()
        # print((tick-tock)*1000)
        if worker_actions.avoid_enemies == False:

            build_rocket(unit_id)

            build_factory(unit_id)

            if worker_actions.building_factory == False and worker_actions.moving_to_build == False and worker_actions.building_rocket == False \
                    and config.karbonite_depleted == False:
                harvest_karbonite(unit_id)

            replicate(unit_id)

            if gc.round() > config.rocket_launch_round and gc.planet(
            ) == bc.Planet.Earth:
                worker_actions.boarded_rocket, worker_actions.moving_to_board_rocket = Utilities.board_rocket(
                    unit_id)

            if config.karbonite_depleted == True and worker_actions.building_factory == False and worker_actions.moving_to_build == False and worker_actions.building_rocket == False and worker_actions.boarded_rocket == False and worker_actions.avoid_enemies == False and worker_actions.moving_to_board_rocket == False:
                destination = gc.unit(unit_id).location.map_location().add(
                    Navigation.random_dir())
                Navigation.fuzzygoto(gc.unit(unit_id).id, destination)
        i += 1
        shipPath = Object.Object(Area.trajectory, i)
        startLonLat = ship[0]
        stopLonLat = ship[1]
        sx = transform.distance(ref_lonmin, ref_latmin, startLonLat[0], ref_latmin)
        sy = transform.distance(ref_lonmin, ref_latmin, ref_lonmin, startLonLat[1])
        gx = transform.distance(ref_lonmin, ref_latmin, stopLonLat[0], ref_latmin)
        gy = transform.distance(ref_lonmin, ref_latmin, ref_lonmin, stopLonLat[1])

        attrmap, xw, yw = PF.calc_potential_field(min(allX), max(allX), min(allY), max(allY), pfConfig.grid_size,
                                                  pfConfig.robot_radius, [], gx, gy, mapType, FieldType.attractive)

        shipPF = np.array(repmapG) + np.array(attrmap)

        shipPath.x, shipPath.y = nav.potential_field_planning(sx, sy, gx, gy, shipPF, xmin, ymin, xmax, ymax, objects)
        shipPaths.append(shipPath)

        repmapL, xw, yw = PF.calc_potential_field(min(allX), max(allX), min(allY), max(allY), pfConfig.grid_size,
                                                  pfConfig.robot_radius, [shipPath], 0, 0, Maptype.trajectories, FieldType.repulsive)

        ship = [xw, yw, attrmap.tolist(), repmapL.tolist(), [shipPath.x, shipPath.y]]
        ships.append(ship)
        dbConnection.insertShip(client, ship, pfConfig.shipID)

    print("-----------------------------------------------------------------------------------------------------------")
    print(" Start potential field drawing")
    print("-----------------------------------------------------------------------------------------------------------")

    if PF.show_animation:
        print
 def create_navigation(self, INPUT_DEVICE_TYPE, INPUT_DEVICE_NAME, STARTING_MATRIX, PLATFORM_SIZE, ANIMATE_COUPLING, MOVEMENT_TRACES, DEVICE_TRACKING_NAME = None):
   _navigation = Navigation()
   _navigation.my_constructor(self.SCENEGRAPH, PLATFORM_SIZE, STARTING_MATRIX, self.navigation_list, INPUT_DEVICE_TYPE, INPUT_DEVICE_NAME, self.no_tracking_mat, self.ground_following_settings, ANIMATE_COUPLING, MOVEMENT_TRACES, DEVICE_TRACKING_NAME)
   self.navigation_list.append(_navigation)
   self.border_observer_list.append(None)
Example #37
0
import argparse

#================================================================================
parser = argparse.ArgumentParser(prog='plotRinex',description='plot RINEX file')

parser.add_argument('-f', '--file', dest='rnxObsFile', default='./t/yar20010.12o')
parser.add_argument('-n', '--nav', dest='rnxNavFile', default='./t/brdc0010.12n')
parser.add_argument('-g', '--gnav', dest='rnxGlonassNavFile', default='./t/alic0010.13n')

#parser.add_argument('-g', '--grid', dest='grid', default=5., type=float)
#parser.add_argument('--polar',dest='polar', default=False, action='store_true')

args = parser.parse_args()
#================================================================================

nav = rnxN.parseFile(args.rnxNavFile)
obs = rnxO.parseRinexObsFile(args.rnxObsFile)

# TODO: Need to calculate my own position
name   = 'YAR2'
lat    = -29. #0465520472
lon    = 115. #3469787567
h      = 0.
eleAng = 0.

sit1 = { 'name'           : name ,
         'latitude'       : lat,
         'longitude'      : lon,
         'height'         : h,
         'ElCutOff'       : eleAng
         }
  def create_navigation(
      self
    , INPUT_DEVICE_TYPE
    , INPUT_DEVICE_NAME
    , STARTING_MATRIX
    , PLATFORM_SIZE
    , SCALE
    , ANIMATE_COUPLING
    , MOVEMENT_TRACES
    , INVERT
    , NO_TRACKING_MAT
    , GROUND_FOLLOWING_SETTINGS
    , TRANSMITTER_OFFSET
    , DISPLAYS
    , AVATAR_TYPE
    , CONFIG_FILE
    , DEVICE_TRACKING_NAME = None
    ):
    
    # convert list of parsed display strings to the corresponding instances
    _display_instances = []
    _displays_found = list(DISPLAYS)

    # create bool list if displays were found
    for _i in range(len(_displays_found)):
      _displays_found[_i] = False

    # search for display instances
    for _i in range(len(DISPLAYS)):
      for _display_instance in displays:
        if _display_instance.name == DISPLAYS[_i]:
          _display_instances.append(_display_instance)
          _displays_found[_i] = True
    
    # check if all display instances were found
    for _i in range(len(_displays_found)):
      if _displays_found[_i] == False:
        print_error("No matching display instance found for " + DISPLAYS[_i], True)

    # create the navigation instance
    _navigation = Navigation()
    _navigation.my_constructor(
        NET_TRANS_NODE = self.NET_TRANS_NODE
      , SCENEGRAPH = self.SCENEGRAPH
      , PLATFORM_SIZE = PLATFORM_SIZE
      , SCALE = SCALE
      , STARTING_MATRIX = STARTING_MATRIX
      , NAVIGATION_LIST = self.navigation_list
      , INPUT_SENSOR_TYPE = INPUT_DEVICE_TYPE
      , INPUT_SENSOR_NAME = INPUT_DEVICE_NAME
      , NO_TRACKING_MAT = NO_TRACKING_MAT
      , GF_SETTINGS = GROUND_FOLLOWING_SETTINGS
      , ANIMATE_COUPLING = ANIMATE_COUPLING
      , MOVEMENT_TRACES = MOVEMENT_TRACES
      , INVERT = INVERT
      , SLOT_MANAGER = self.slot_manager
      , TRANSMITTER_OFFSET = TRANSMITTER_OFFSET
      , DISPLAYS = _display_instances
      , AVATAR_TYPE = AVATAR_TYPE
      , CONFIG_FILE = CONFIG_FILE
      , TRACKING_TARGET_NAME = DEVICE_TRACKING_NAME
    )
    self.navigation_list.append(_navigation)
    self.border_observer_list.append(None)