Example #1
0
def main():

	counter = 0
	success = 0
	matchCheck = ""

	while True:
		try:
			interactionsNum = int(input("Enter the number of interactions (1 or greater): "))
			if interactionsNum <= 0:
				print("Number must be 1 or greater") ##For 1 or greater
			else:
				break
		except ValueError:
			print("Do not enter non-numeric values") ##For non-numeric

	while True:
		try:
			xPercent = int(input("Enter the percentage # of 'X' interactions for target (whole numbers from 0 - 100):"))
			if xPercent < 0 or xPercent > 100:
				print("Enter a value between 0 - 100 only") ##Sub one and greater than 100
			else:
				break
		except ValueError:
			print("Do not enter non-numeric values") ##Non-numeric

	targetCall = Target() #Makes a Target
	pursuerCall = Pursuer() #Makes a Pursuer
	targetCall.setPercents(xPercent) #Set Target to user input

	##Start run interactions
	while counter < interactionsNum:
		targetVal = targetCall.runRandom()
		pursuerVal = pursuerCall.runRandom()
		if targetVal == pursuerVal:
			matchCheck = "Matched behavior"
			success += 1
		elif (targetVal == "x" and pursuerVal == "y"):
			pursuerCall.setPercents(5) #Set X percent up 
			matchCheck = "Mis-Matched behavior"
		else:
			pursuerCall.setPercents(-5)
			matchCheck = "Mis-Matched behavior"	

		print("Target: "+targetVal +" | Pursuer:" +pursuerVal +" | " +matchCheck) #Display interaction Target and Pursuer
		counter += 1
	print()
	print()

	##Begin post run display	
	print("ANALYSIS OF ALL THE INTERACTIONS (THE DATE)")
	print(" Target: No. of X's: "+str(targetCall.xCount) +"\tNo. of Y's: "+str(targetCall.yCount))
	print("Pursuer: No. of X's: "+str(pursuerCall.xCount) +"\tNo. of Y's: "+str(pursuerCall.yCount))
	print("Number of successful matches: "+str(success))
	print("Proportion of successful matches: " +"{0:0.1f}".format((success/interactionsNum)*100) +"%")
	print()
	if (success/interactionsNum)*100 >= 50:
		print("Date was successful <3")
	else:
		print("Date was unsuccessful </3")
def make_default_robot(robot_name, path_color):
    start_point = Target(
        (np.random.randint(50, 350), np.random.randint(350, 550)),
        radius=20,
        color=0x00FF00)
    initial_position = np.array(start_point.position)
    target = Target((np.random.randint(600, 760), np.random.randint(50, 250)),
                    radius=20)
    objective = NavigationObjective(target, env)

    env.non_interactive_objects += [start_point, target]

    robot = Robot(initial_position,
                  cmdargs,
                  env,
                  path_color=path_color,
                  name=robot_name,
                  objective=objective)
    robot.put_sensor('radar', RadarSensor(env, robot, [], radar))
    robot.put_sensor('gps', GpsSensor(robot))
    if robot_name in params['robots']:
        robot.put_sensor('params', params['robots'][robot_name])
    else:
        robot.put_sensor('params', {})

    robot_obstacle = DynamicObstacle(MovementPattern.RobotBodyMovement(robot))
    robot_obstacle.shape = 1
    robot_obstacle.radius = 10
    robot_obstacle.fillcolor = (0xcc, 0x88, 0x44)
    robot.set_obstacle(robot_obstacle)

    return robot, target
Example #3
0
    def print_targets(self):
        '''
            Prints targets to console
        '''
        if len(self.targets) == 0:
            Color.p('\r')
            return

        if self.previous_target_count > 0:
            # We need to "overwrite" the previous list of targets.
            if Configuration.verbose <= 1:
                # Don't clear screen buffer in verbose mode.
                if self.previous_target_count > len(self.targets) or \
                   Scanner.get_terminal_height() < self.previous_target_count + 3:
                    # Either:
                    # 1) We have less targets than before, so we can't overwrite the previous list
                    # 2) The terminal can't display the targets without scrolling.
                    # Clear the screen.
                    from Process import Process
                    Process.call('clear')
                else:
                    # We can fit the targets in the terminal without scrolling
                    # "Move" cursor up so we will print over the previous list
                    Color.pl(Scanner.UP_CHAR * (3 + self.previous_target_count))

        self.previous_target_count = len(self.targets)

        # Overwrite the current line
        Color.p('\r')

        Target.print_header()
        for (index, target) in enumerate(self.targets):
            index += 1
            Color.clear_entire_line()
            Color.pl('   {G}%s %s' % (str(index).rjust(3), target))
Example #4
0
    def print_targets(self):
        '''
            Prints targets to console
        '''
        if len(self.targets) == 0:
            Color.p('\r')
            return

        if self.previous_target_count > 0:
            # We need to "overwrite" the previous list of targets.
            if self.previous_target_count > len(self.targets) or \
               Scanner.get_terminal_height() < self.previous_target_count + 3:
                # Either:
                # 1) We have less targets than before, so we can't overwrite the previous list
                # 2) The terminal can't display the targets without scrolling.
                # Clear the screen.
                from Process import Process
                Process.call('clear')
            else:
                # We can fit the targets in the terminal without scrolling
                # "Move" cursor up so we will print over the previous list
                Color.pl(Scanner.UP_CHAR * (3 + self.previous_target_count))

        self.previous_target_count = len(self.targets)

        # Overwrite the current line
        Color.p('\r')

        Target.print_header()
        for (index, target) in enumerate(self.targets):
            index += 1
            Color.pl('   {G}%s %s' % (str(index).rjust(3), target))
Example #5
0
	def loadTarget(self, approx):
		'''Does all the higher level calculations.

		Takes an input array of points and sends it to the Target object.
		Then takes the width and height from the target object and calculates Distance, Azimuth, and Altitude.
		'''

		self.dist = 0
		self.azimuth = 0
		self.altitude = 0
		self.targetType = -1

		self.target = Target(approx)
	
		imgWidth = self.target.getWidth()
		imgHeight = self.target.getHeight()
		imgCenter = self.target.getCenter()
		
		rectCentX = imgCenter[0]
		rectCentY = imgCenter[1]
		
		offsetX = float(rectCentX - self.horizCent)
		offsetY = float(rectCentY - self.vertiCent)
		
		self.targetType = self.target.getType()

		self.dist = self.rectWidth * self.focalLen / imgWidth
		self.azimuth = np.arctan(offsetX / self.focalLen) * 180 / math.pi
		self.altitude = np.arctan(offsetY / self.focalLen) * 180 / math.pi
Example #6
0
 def __init__(self, cadi, model):
     try:
         Target.__init__(self, cadi, model)
         self._add_alias("Memory", "N", True)
         self._add_alias("Physical Memory", "NP", True)
     except:
         self._disconnect_callbacks()
         raise
Example #7
0
 def __init__(self, cadi, model):
     try:
         Target.__init__(self, cadi, model)
         self._add_alias("Memory", "N", True)
         self._add_alias("Physical Memory", "NP", True)
     except:
         self._disconnect_callbacks()
         raise
 def getCState(self):
     try:
         camera_pos = self.Comms.get('cState').payload
         self.cTurret = CameraTurret([
             Target(np.array([0, 100, 100]).reshape(3, 1), "t0"),
             Target(np.array([0, 100, 150]).reshape(3, 1), "t1"),
             Target(np.array([0, 150, 150]).reshape(3, 1), "t2")
         ], camera_pos[0][0], camera_pos[1][0])
     except queue.Empty:
         pass
Example #9
0
 def __init__(self, cadi, model):
     try:
         Target.__init__(self, cadi, model)
         self._add_alias("Normal", "N", True)
         self._add_alias("Secure", "S")
         self._add_alias("NS Hyp", "H")
         self._add_alias("Physical Memory (Non Secure)", "NP")
         self._add_alias("Physical Memory (Secure)", "SP")
     except:
         self._disconnect_callbacks()
         raise
def test_get_percent_observed_targets():
    sen1 = Sensor(2, 2, Point(0, 0))
    sen2 = Sensor(2, 2, Point(1, 0))
    tar1 = Target(Point(1, 1))
    tar2 = Target(Point(4, 4))
    tar4 = Target(Point(5, 5))
    tar3 = Target(Point(3, 0))
    sensor_list = [sen1, sen2]
    targest_list = [tar1, tar2, tar3, tar4]
    a = Scheduler(sensor_list, targest_list, 2, 2)
    assert a.get_percent_observed_targets() == 50
Example #11
0
 def __init__(self, cadi, model):
     try:
         Target.__init__(self, cadi, model)
         self._add_alias("Normal", "N", True)
         self._add_alias("Secure", "S")
         self._add_alias("NS Hyp", "H")
         self._add_alias("Physical Memory (Non Secure)", "NP")
         self._add_alias("Physical Memory (Secure)", "SP")
     except:
         self._disconnect_callbacks()
         raise
    def select_next_action(self):
        rcnt = 10
        if self._tmp_counter > 30:
            self._tmp_counter = 0
            self._global_algo = util.algo_from_config(
                self._params['global_algorithm'],
                self._sensors,
                self._target,
                self._cmdargs,
                use_as_global_planner=True)
            self._global_algo.select_next_action()
            if self._global_algo.has_given_up():
                self._has_given_up = True
            if len(self._global_algo._solution) == 0:
                self._next_waypoint = self._target
            else:
                self._next_waypoint = Target(np.array(
                    self._global_algo._solution[0].data),
                                             radius=self._waypoint_radius)
            self._local_algo = util.algo_from_config(
                self._params['local_algorithm'], self._sensors,
                self._next_waypoint, self._cmdargs)
            #self._local_algo.set_target(self._next_waypoint)
        elif self._gps.distance_to(
                self._next_waypoint.position
        ) < self._next_waypoint.radius or self._tmp_counter % rcnt == (rcnt -
                                                                       1):
            if self._gps.distance_to(
                    self._next_waypoint.position) < self._next_waypoint.radius:
                self._tmp_counter = 0

            old_waypoint = self._next_waypoint
            self._global_algo.select_next_action()
            if len(self._global_algo._solution) > 0:
                self._next_waypoint = Target(np.array(
                    self._global_algo._solution[0].data),
                                             radius=self._waypoint_radius)
            else:
                self._next_waypoint = self._target

            if self._next_waypoint != old_waypoint:
                self._local_algo = util.algo_from_config(
                    self._params['local_algorithm'], self._sensors,
                    self._next_waypoint, self._cmdargs)
                #self._local_algo.set_target(self._next_waypoint)

        self._tmp_counter += 1
        next_action = self._local_algo.select_next_action()
        self.debug_info = {
            **self._local_algo.debug_info,
            **self._global_algo.debug_info
        }
        return next_action
Example #13
0
 def __init__(self,
              name,
              sources=None,
              paths=None,
              defines=None,
              link=None):
     Target.__init__(self,
                     name,
                     sources=sources,
                     paths=paths,
                     defines=defines,
                     link=link,
                     linkTo=Target.Executable)
Example #14
0
 def __init__(self,
              name,
              sources=None,
              paths=None,
              defines=None,
              link=None):
     Target.__init__(self,
                     name,
                     sources=sources,
                     paths=paths,
                     defines=defines,
                     link=link,
                     linkTo=Target.StaticLibrary)
Example #15
0
    def __init__(self, name, platform, importer, generator):
        Target.__init__(self, name)

        #	self.message( 'Configuring build environment for ' + name + '...' )

        self._targets = []
        self._externals = None
        self.importer = importer
        self.platform = platform
        self.generator = generator
        self.toolsPath = None
        self.outputLibPath = None
        self.outputExePath = None
Example #16
0
    def restart(self, event):
        touche = event.keysym
        if touche == 'Return':
            # print("Enter")
            self.unbind('<Key>')
            self.field.destroy()
            self.h = 150
            self.score = 0
            self.field = Canvas(self, width=600, height=600, background='black')
            self.field.grid(row=1)
            self.p = Snack(self.field)
            self.q = Target(self.field)

            self.start()
def playbackRedrawAll(canvas, data):
    canvas.create_image(data.width/2,data.height/2,image=data.playBGImage)
    drawSnowflakes(canvas,data)
    Drop.draw(canvas,data)
    Brick.draw(canvas,data)
    Target.draw(canvas,data)
    Scroll.draw(canvas,data)
    drawScore(canvas,data)
    drawLevel(canvas,data)
    Spike.draw(canvas,data)
    Bomb.draw(canvas,data)
    WormholeA.draw(canvas,data)
    WormholeB.draw(canvas,data)
    Trap.draw(canvas,data)
    drawPlaybackTable(canvas,data)
def build_scheduler(sen, tar):
    sen1 = Sensor(2, 2, Point(0, 0))
    sen2 = Sensor(2, 2, Point(1, 0))
    tar1 = Target(Point(1, 1))
    tar4 = Target(Point(0, 1))
    tar2 = Target(Point(2.5, 0))
    tar3 = Target(Point(8, 8))
    target_list = [tar1, tar2, tar3, tar4]
    sensor_list = [sen1, sen2]
    for sensor in sen:
        sensor_list.append(sensor)
    for target in tar:
        sensor_list.append(target)
    a = Scheduler(sensor_list, target_list, 2, 2)
    return a
def test_build_fields_list():

    sen1 = Sensor(2, 2, Point(0, 0))
    sen2 = Sensor(2, 2, Point(1, 0))
    tar1 = Target(Point(1, 1))
    tar4 = Target(Point(0, 1))
    tar2 = Target(Point(2.5, 0))
    tar3 = Target(Point(8, 8))
    target_list = [tar1, tar2, tar3, tar4]
    sensor_list = [sen1, sen2]
    a = Scheduler(sensor_list, target_list, 2, 2)
    assert len(a.fields_list) == 2
    assert len(sen1.fields) == 1
    assert len(sen2.fields) == 2
    assert len(sen1.fields[0].targets) == 2
Example #20
0
    def populateTargets(self):
        '''
        create targets and populate targets list
        '''
        # create targets
        for indx in range(vars.target_num):
            # randomly place target outside of UAV FOV, so this radius is in addition to d_fov
            radius = random.random() * vars.uav_dfov / 2
            # get random angle direction to place target
            angle = random.random() * 2 * math.pi
            direction = random.random() * math.pi * 2
            position = np.array([
                (radius + vars.uav_dfov / 2) * math.cos(angle),
                (radius + vars.uav_dfov / 2) * math.sin(angle)
            ]) + self.uav.position

            # create target
            target = Target(position=position, direction=direction)

            # add measurement of initial location
            #             measured = np.array([target.position]).T
            #             target.measure(measured)

            # create targets
            self.targets.append(target)
Example #21
0
	def _initialize_mdps(self, maps, targetss, cmdargs, height, width):
		mdps = list()
		features = dict()
		for i in range(len(maps)):
			targets = targetss[i]
			env = Environment(width, height, maps[i], cmdargs)
			start_point = Target(targets[0], color=0x00FF00)
			target = Target(targets[1])

			# Init robots
			mdp = MDPAdapterSensor(env, start_point.position, target.position, cell_size = 20, unique_id=os.path.basename(maps[i]))
			feature = self._get_features(mdp)
			mdps.append(mdp)
			features[mdp] = feature

		return mdps, features
Example #22
0
    def __init__(self, CanvasWindow, numOfTargets, image):
        """ Initializes the Rover class.
               Parameters:
               ------------
                   CanvasWindow : CanvasWindow object
                       CanvasWindow object for the targets.
                   numOfTargets : int
                       The total number of targets.
                   image : Image file
                       The image file for the targets
               Attributes:
               ------------
                   canvasWindow:
                   numOfTargets:
                   targetList:
                   canvas_height:
                   canvas_width:
               """

        self.canvasWindow = CanvasWindow
        self.numOfTargets = numOfTargets
        self.targetCoords = self.generateTargetCoordinates()
        self.size = numOfTargets
        self.targetsList = []
        for i in xrange(numOfTargets):
            self.targetsList.append(
                Target(self.canvasWindow, i, image, self.targetCoords[i]))
            self.canvasWindow.map_array[self.targetCoords[i][0]][
                self.targetCoords[i][1]] = 1

        # Canvas variables
        self.canvas_height = self.canvasWindow.canvas.winfo_height()
        self.canvas_width = self.canvasWindow.canvas.winfo_width()
        self.canvasWindow.tbwCaptured.config(text=self.size)
Example #23
0
 def __init__(self, num_util, nb_repet, taille, densite, pathGenPoints,
              pathRandPoints):
     super(QWidget, self).__init__()
     self.setMouseTracking(True)
     self.num_util = num_util
     self.nb_repet = nb_repet
     self.cpt = nb_repet
     self.taille = taille
     self.densite = densite
     self.targets = list()
     file1 = open(pathGenPoints, 'r')
     line1 = reader(file1)
     for row in line1:
         self.targets.append(Target(int(row[0]), int(row[1]), int(row[2])))
     #file2 = open(pathRandPoints,'r')
     #line2 = reader(file2)
     self.randoms = list()
     #for row in line2:
     #    self.randoms.append(Target(int(row[0]),int(row[1]),int(row[2])))
     self.curosr = RopeCursor(self.targets)
     self.error = 0
     self.timer = None
     self.random = None
     self.randomTarget()
     self.fileL = "log@" + str(self.num_util) + ".csv"
     self.fileLog = open(self.fileL, 'a', newline='')
     self.writerLog = writer(self.fileLog)
     self.log = list()
Example #24
0
    def load_from_txt_file(cls,
                           fname,
                           query_interval=None,
                           min_merge_dist=DEFAULT_MERGE_DISTANCE):
        """
        Loads a plain text bed file into a list of Interval objects,
        only including those in the query interval if specified.

        :param fname: text file with bed format of chrom, start, end, id
        :param query_interval: Query Interval, will return all if none
        :param min_merge_dist: Minimum distance to merge intervals by
        :return: A TargetCollection from the bed file that overlap the query interval
        """
        if not os.path.exists(fname):
            raise IOError("Text file " + fname + " does not exist")
        result = cls(min_merge_dist=min_merge_dist)
        with open(fname) as fh:
            for line in fh:
                if line[0] != "#":
                    interval = Target.create_from_BED_string(line)
                    if query_interval and query_interval.overlaps(interval):
                        result.append(interval)
                    elif not query_interval:
                        result.append(interval)
        result.merge_nearby_intervals()
        return result
Example #25
0
    def get_target(self, target):
        """
        Obtain an interface to a target
        
        :param target: The instance name corresponding to the desired target
        """

        interface_name = "eslapi.CADI2"
        target_id = next((t.id for t in self.__simulation.GetTargetInfos()
                         if t.instanceName == target), None)
        if target_id == None:
            raise ValueError("Model has no target named \"%s\"" % target)
        if target_id not in self.__targets:
            target = self.__simulation.GetTarget(target_id)
            result = target.ObtainInterface(interface_name)
            if type(result) == int:
                raise Model.ObtainInterfaceFailed(interface_name)
            (interface, rev) = result
            cadi = CADI.CAInterface_CADI(interface)
            target_name = cadi.CADIGetTargetInfo().targetName
            try:
                # if this fails, this target object hangs around, breaking the
                # modechange callbacks
                target_object = _target_classes[target_name](cadi, self)
            except Exception as ex:
                target_object = Target(cadi, self)
                if self.__verbose:
                    warn("Failed to load specialised target, falling back to general implementation.\n(Error: %s)" % ex)
            self.__targets[target_id] = target_object
        return self.__targets[target_id]
Example #26
0
 def getTargets(self):
     targets = []
     for t in self.data["targets"]:
         pose = Pose3d()
         pose.x = t["x"]; pose.y = t["y"]
         targets.append(Target(t["name"],pose,False,False))
     return targets
Example #27
0
 def __init__(self):
     # ----- Initialisation de la fenĂȘtre ---------
     Tk.__init__(self)
     self.geometry('600x635+400+20')
     self.title('Snack Game')
     self.h = 150
     self.score = 0
     self.info = Canvas(self, width=600, height=31, bg='black')
     self.info.grid(row=2)
     self.info_score = self.info.create_text(548, 18, text='Score : ' + str(self.score), font='Arial 15 bold', fill='white')
     # ----- Initialisation du canvas ------------
     self.field = Canvas(self, width=600, height=600, background='black')
     self.field.grid(row=1)
     self.p = Snack(self.field)
     self.q = Target(self.field)
     self.start()
Example #28
0
    def __init__(self, agents_to_create, targets_per_agent_to_create, mode):
        """ TODO still have to finish up this as well
        """
        # Creates the agent and target lists
        self.agents = list()
        self.targets = list()

        # Loops to create the necessary number of agents
        for a_id in range(0, agents_to_create):
            location = self.generate_unique_location()
            new_agent = Agent(self, a_id, location)
            self.agents.append(new_agent)

            # Adds all the targets for the newly generated agent
            for t_id in range(0, targets_per_agent_to_create):
                location = self.generate_location()
                new_target = Target(self, t_id, location, new_agent)
                self.targets.append(new_target)

        # Sets the game mode of the game field
        self.object_list = self.agents + self.targets
        self.mode = mode

        # Sets up the public and private information channels
        self.public_info = list()
        self.private_info = list()

        print("GameMode: {}".format(self.mode))
Example #29
0
    def __init__(self,
                 sensors,
                 target,
                 cmdargs,
                 global_algo_init=DynamicRrtNavigationAlgorithm,
                 local_algo_init=SamplingNavigationAlgorithm):
        self._sensors = sensors
        self._target = target
        self._cmdargs = cmdargs
        self._global_algo_init = global_algo_init
        self._local_algo_init = local_algo_init

        self._radar = sensors['radar']
        self._gps = sensors['gps']
        sensors['mapper'] = StaticMapper(sensors)

        self.debug_info = {}

        self._waypoint_radius = 26

        self._global_algo = global_algo_init(sensors, target, cmdargs)
        self._next_waypoint = Target(self._gps.location(),
                                     radius=self._waypoint_radius)
        self._local_algo = local_algo_init(sensors, self._next_waypoint,
                                           cmdargs)
        self._tmp_counter = 0
        self._has_given_up = False
Example #30
0
 def add_new_item(self, item_name, found, picture):
     '''adds new item to end of list'''
     # make new item object using given info
     new_item = Target(item_name, found, picture)
     cur_list = self.get_item_list()  # gets list as it stands now
     cur_list.append(new_item)  # appends item at end of list
     self.set_item_list(cur_list)  # set class field to modified list
 def getTargets(self):
     targets = []
     for t in self.data["targets"]:
         targets.append(
             Target(t["name"],
                    jderobot.Pose3DData(t["x"], t["y"], 0, 0, 0, 0, 0, 0),
                    False, False))
     return targets
Example #32
0
 def effects(controller, source):
     target = yield Target(isArtifactCreature,
                           msg="Target Artifact Creature for %s" % source)
     if controller.you_may("move all +1/+1 counters from %s to target" %
                           source.name):
         target.add_counters(PowerToughnessCounter(1, 1),
                             number=source.num_counters("+1+1"))
     yield
Example #33
0
def make_target(ip):
    ans, unans = arping(ip)
    conf.verb = 0
    for snd,rcv in ans:
        ipv4 = ip
        mac = rcv[Ether].src
        manu = find_vendor(mac)
        return Target(ipv4, mac, manu)
Example #34
0
class Main(object):
    """description of class"""
    def __init__(self, img):
        self.img = cv2.resize(img, (0, 0), fx = 0.2, fy = 0.2)
        self.detect = TargetDetector(self.img)
        self.detect.threshold([0, 0, 200], [255, 100, 255])
        self.target = Target(self.img, self.detect.findRect())
        self.processor = TargetProcessor(self.img, self.detect.findRect())
    def display(self):
        cv2.imshow("dd", self.img)
        cv2.waitKey(0)
    def distance(self):
        return self.processor.distance(self.target.xmin, self.target.xmax)
    def azimuth(self):
        return self.processor.azimuth(self.target.center(), self.target.img_center())
    def altitude(self):
        return self.processor.altitude(self.target.center(), self.target.img_center())
Example #35
0
        essid = Configuration.target_essid
        i = 0
        while i < len(result):
            if bssid and result[i].bssid.lower() != bssid.lower():
                result.pop(i)
                continue
            if essid and result[i].essid.lower() != essid.lower():
                result.pop(i)
                continue
            i += 1
        return result


if __name__ == '__main__':
    ''' Example usage. wlan0mon should be in Monitor Mode '''
    with Airodump() as airodump:

        from time import sleep
        sleep(7)

        from Color import Color

        targets = airodump.get_targets()
        Target.print_header()
        for (index, target) in enumerate(targets):
            index += 1
            Color.pl('   {G}%s %s' % (str(index).rjust(3), target))

    Configuration.delete_temp()

Example #36
0
 def __init__(self, name, sources): 
     Target.__init__(self, name)
     self.sources = sources