Пример #1
0
def main():
    # def main(arglist):
    file = './testcases/4g1_m1.txt'
    outfile = 'out/4g1_m1_output.txt'
    # file = arglist[0]
    # outfile = arglist[1]

    prm = EST(file)
    # config = prm.sampling(1000)
    # robot = prm.get_init_state();
    f = open("tmp_output.txt", "w")
    f.write("")
    f.close()
    prm.run_EST(outfile)
    # D = [1e-3,1e-3]
    # sampleRobot = prm.sampling_withinD(robot,D,100)
    # robot = prm.assign_config(config.tolist(),0)
    # print(sampleRobot)
    # print(config.tolist())
    # config = config[:,:-1]
    # prm.write_config('test.txt',config.tolist())

    aa = test_robot(prm)
    qq = aa.load_output('output.txt')
    vis = Visualiser(prm, qq)
Пример #2
0
 def setUp(self):
     self.parser = DataParser()
     self.cmd_view = CmdView()
     self.file_view = FileView()
     self.validator = Validator()
     self.db = DatabaseView("test.db")
     self.vis = Visualiser()
     # self.val = Validator()
     self.controller = Controller(self.cmd_view, self.file_view,
                                  self.parser, self.validator, self.db,
                                  self.vis)
Пример #3
0
 def setUp(self):
     self.parser = DataParser()
     self.cmd_view = CmdView()
     self.file_reader = FileReader()
     self.validator = Validator()
     self.db = Database("test.db")
     self.vis = Visualiser()
     self.val = Validator()
     self.serial = Serializer()
     self.controller = Controller(self.cmd_view, self.file_reader,
                                  self.parser, self.validator, self.db,
                                  self.vis, self.serial)
     self.init()
Пример #4
0
    def print_top(self, sentiments=[], n=10):
        '''

        :param sentiments:
        :param n:
        :return:
        '''

        if not self._scored : self.score_tweets()

        if len(set(sentiments).difference(self._data.columns)) != 0 or not isinstance(sentiments, list) or len(
                sentiments) == 0:
            raise Exception("Use a valid sentiment list {}".format([sentiment for sentiment in self.models_ar]))
        Visualiser(self._data).print_top(sentiments=sentiments, n=n)
Пример #5
0
    def create_widgets(self):

        self.code_text = CodeText(self)
        self.visualiser = Visualiser(self)
        self.code_runner = wx.Panel(self)

        # self.aui_manager = wx.aui.AuiManager(self, wx.aui.AUI_MGR_DEFAULT | wx.aui.AUI_MGR_LIVE_RESIZE)
        self.aui_manager = wx.aui.AuiManager(
            self,
            wx.aui.AUI_MGR_ALLOW_FLOATING | wx.aui.AUI_MGR_TRANSPARENT_HINT
            | wx.aui.AUI_MGR_LIVE_RESIZE)
        # self.aui_manager = wx.lib.agw.aui.AuiManager(self, wx.aui.AUI_MGR_ALLOW_FLOATING | wx.aui.AUI_MGR_TRANSPARENT_HINT
        #                                              | wx.aui.AUI_MGR_LIVE_RESIZE)
        self.aui_manager.AddPane(self.code_text, wx.CENTRE, 'Code Text')
        self.aui_manager.AddPane(self.visualiser, wx.TOP, 'Visualiser')
        self.aui_manager.AddPane(self.code_runner, wx.BOTTOM, 'Code Runner')
        self.aui_manager.Update()
Пример #6
0
def ql_vs_minmax(visualise):
	print("ql vs minmax ql")
	numActions = env.n_actions
	drawProbability = 0.1
	decay = 10**(-2. / N_EPISODES * 0.05)
	if(visualise):
		vis = Visualiser(env, 80)
	numActions = env.n_actions
	start_time = time.time()
	ql_wins = 0
	minmax_wins = 0
	playerA = QLearn(actions=list(range(numActions)), reward_decay=0.7)
	playerB = MinimaxQPlayer(numActions, numActions, decay=decay, expl=0.01, gamma=1-drawProbability)
	playerA.load_Qtable('saved_players/QR')
	playerB.load_Qtable("MR")
	# no explore
	iterations = 5000
	for episode in range(iterations):
		# initial observation
		observation = env.reset()
		# print(str(episode))
		if(episode % 100 == 0):
			print(str(float(episode) / iterations * 100) + "%")
		# if(episode > iterations - 100):
		# 	vis.update_canvas(env)
		while True:
			# RL choose action based on observation
			actionA = playerA.choose_action(str(observation))
			actionB = playerB.choose_action(str(observation))

			# RL take action and get next observation and reward
			observation_, reward, done = env.step(actionA, actionB)
			if reward == 1:
				ql_wins += 1
			elif reward == -1:
				minmax_wins += 1
			
			observation = observation_
			if(visualise):
				vis.update_canvas(env)
			if done:
				if(visualise):
					vis.reset()
				break
	return (ql_wins, minmax_wins)
Пример #7
0
    def bubble_chart(self,
                     rounding=2,
                     positive_sentiments=['joy', 'love'],
                     negative_sentiments=['anger', 'sadness']):
        '''

        :param rounding:
        :param positive_sentiments:
        :param negative_sentiments:
        :return:
        '''

        if not self._scored : self.score_tweets()

        Visualiser(self._data).bubble_chart(
            rounding=rounding,
            positive_sentiments=positive_sentiments,
            negative_sentiments=negative_sentiments)
Пример #8
0
def sample(spec):
    samples = []
    samples += sample_double_grappled(spec)
    samples += uniform_sample(spec)
    double_samples = []
    for s in samples:
        angles = s.ee1_angles.copy()
        lengths = s.lengths.copy()
        lengths.reverse()
        double_samples.append(
            make_robot_config_from_ee2(s.points[0][0],
                                       s.points[0][1],
                                       angles,
                                       lengths,
                                       ee1_grappled=s.ee2_grappled,
                                       ee2_grappled=s.ee1_grappled))
    samples += double_samples
    Visualiser(spec, samples)
    return samples
Пример #9
0
    def __init__(self, current_season: int):
        self.current_season = current_season
        self.data = Data(current_season)
        self.visualiser = Visualiser()

        # Import environment variables
        __file__ = 'data.py'
        dotenv_path = join(dirname(__file__), '.env')
        load_dotenv(dotenv_path)
        self.url = os.getenv('URL')
        self.headers = {'X-Auth-Token': os.getenv('X_AUTH_TOKEN')}

        # Number of games played in a season for season data to be used
        self.games_threshold = 4
        self.home_games_threshold = 6
        self.star_team_threshold = 0.75  # Rating over 75% to be a star team

        # Store for new requested API data or old data from memory
        self.json_data = {'fixtures': {}, 'standings': {}}
        self.last_updated = None  # type: str
Пример #10
0
def run_optimal():
	vis = Visualiser(env, 80)
	numActions = env.n_actions
	playerA = QLearn(actions=list(range(numActions)))
	playerA.load_Qtable("saved_players/QR")
	playerB = QLearn(actions=list(range(numActions)))
	playerB.load_Qtable("saved_players/QR_base")
	for episode in range(500):
		observation = env.reset()
		vis.update_canvas(env)
		while(True):
			actionA = playerA.choose_action(str(observation))
			actionB = playerB.choose_action(str(observation))
			observation_, reward, done = env.step(actionA, actionB)
			observation = observation_
			vis.update_canvas(env)
			if done:
				vis.reset()
				break
	print("Games won: " + str(env.win_count))
	vis.destroy()
Пример #11
0
    def pie_chart(self,
                  treshold_pos=0.7,
                  treshold_neg=0.3,
                  positive_sentiments=['joy', 'love'],
                  negative_sentiments=['anger', 'sadness']):
        '''

        :param treshold_pos:
        :param treshold_neg:
        :param positive_sentiments:
        :param negative_sentiments:
        :return:
        '''

        if not self._scored : self.score_tweets()

        Visualiser(self._data).pie_chart(
            treshold_pos=treshold_pos,
            treshold_neg=treshold_neg,
            positive_sentiments=positive_sentiments,
            negative_sentiments=negative_sentiments)
Пример #12
0
def main():
    # input data
    inputDataFileName = '/home/dane/repos/oops/datasets/small.in'
    print("Input Dataset: ", inputDataFileName)
    smallData = InputData(inputDataFileName)

    # assume the slices piece is valid
    # magic code goes here
    slicedSmallPizza = [
        7,
        [[0, 0, 1, 1], [0, 3, 1, 4], [0, 5, 1, 6], [2, 0, 3, 1], [2, 2, 3, 3],
         [2, 4, 3, 5], [4, 5, 5, 6]]
    ]
    # visualise slices
    Visualiser(smallData, slicedSmallPizza[1])

    # calculate the score
    print('Score: ', ScoreCalc(slicedSmallPizza[1]).score)

    # output the the file
    outputDataFileName = '/home/dane/repos/oops/output/small.out'
    print("Output file: ", outputDataFileName)
    GenerateOutput(slicedSmallPizza, outputDataFileName)
Пример #13
0
def main(arglist):
    # input_file = arglist[0]
    # output_file = arglist[1]
    input_file = "testcases/3g1_m2.txt"
    output_file = "testcases/output.txt"
    spec = ProblemSpec(input_file)

    init_node = GraphNode(spec, spec.initial)
    goal_node = GraphNode(spec, spec.goal)

    g = GraphNode(spec, spec.goal)
    # path_plan = []
    #
    # for i in range(200):
    #     c = g.generate_sample()
    #     path_plan.append(c)

    steps = []

    path_plan = g.PRM(init_node, goal_node)
    # write_robot_config_list_to_file(output_file, path_plan)

    # Code for your main method can go here.
    #
    # Your code should find a sequence of RobotConfig objects such that all configurations are collision free, the
    # distance between 2 successive configurations is less than 1 primitive step, the first configuration is the initial
    # state and the last configuration is the goal state.
    #
    #

    # if len(arglist) > 1:

    #
    # You may uncomment this line to launch visualiser once a solution has been found. This may be useful for debugging.
    # *** Make sure this line is commented out when you submit to Gradescope ***
    #
    v = Visualiser(spec, path_plan)
Пример #14
0
def run_optimalB():
	numActions = env.n_actions
	drawProbability = 0.1
	decay = 10**(-2. / N_EPISODES * 0.05)
	vis = Visualiser(env, 80)
	numActions = env.n_actions
	playerB = MinimaxQPlayer(numActions, numActions, decay=decay, expl=0.00, gamma=1-drawProbability)
	playerB.load_Qtable("MR")
	playerA = QLearn(actions=list(range(numActions)))
	playerA.load_Qtable("saved_players/MR_base")
	for episode in range(20):
		observation = env.reset()
		vis.update_canvas(env)
		while(True):
			actionA = playerA.choose_action(str(observation))
			actionB = playerB.choose_action(str(observation))
			observation_, reward, done = env.step(actionA, actionB)
			observation = observation_
			vis.update_canvas(env)
			if done:
				vis.reset()
				break
	print("Games won: " + str(env.win_count))
	vis.destroy()
Пример #15
0
def main(arglist):
    input_file = arglist[0]
    output_file = arglist[1]

    spec = ProblemSpec(input_file)

    init_node = GraphNode(spec, spec.initial)
    goal_node = GraphNode(spec, spec.goal)

    num_grapple_points = spec.num_grapple_points
    if num_grapple_points == 1:
        graph_nodes = [[init_node, goal_node]]
    else:
        graph_nodes = [[] for i in range(num_grapple_points)]
        graph_nodes[0].append(init_node)
        graph_nodes[-1].append(goal_node)

    steps = []

    # Solution

    # Note on solution: if there are multiple grapple points, samples are collected separately for each grapple point
    # Then, the closest node to a grapple point in the sample for an ADJACENT grapple point is taken as the goal node.
    #

    steps = generate_steps(spec, 5000 * spec.num_grapple_points, graph_nodes,
                           init_node, goal_node, spec.num_grapple_points)

    if len(arglist) > 1:
        write_robot_config_list_to_file(output_file, steps)

    #
    # You may uncomment this line to launch visualiser once a solution has been found. This may be useful for debugging.
    # *** Make sure this line is commented out when you submit to Gradescope ***
    #
    v = Visualiser(spec, steps)
Пример #16
0
def main(video, json_logger=None, visualise_callback=False, mode=None, inferencer=None, model_name=None, image_size=None, model_alpha=None, shot_name=None, preset_name=None, prob_threshold=None, iou_threshold=None, union_threshold=None, model_precision=None, inference_device=None, num_shots_hint=None, video_descriptor=None, gender_estimation=False, emotions_recognision=False, run_faceid=False, create_feauture_list=None, faceid_search=False):
    if faceid_search:
        run_faceid = True
    if not(create_feauture_list is None):
        feauture_list = []
        run_faceid = True
        if preset_name is None:
            preset_name = 'accuracy'

    if not(mode is None):
        try:
            mode = str(mode)
        except (TypeError, ValueError):
            raise ErrorSignal(invalid_argument_value)
    else:
        mode = default_mode

    if not(json_logger is None):
        try:
            json_logger = str(json_logger)
        except (TypeError, ValueError):
            raise ErrorSignal(invalid_argument_value)

    exit_code = 1

    reader = VideoReader(video, width_hint, height_hint)
    detector = FaceDetection(reader.get_width(), reader.get_height(), inferencer=inferencer, model_name=model_name, image_size=image_size, model_alpha=model_alpha, shot_name=shot_name, preset_name=preset_name, prob_threshold=prob_threshold, iou_threshold=iou_threshold, union_threshold=union_threshold, model_precision=model_precision, inference_device=inference_device, num_shots_hint=num_shots_hint)
    if gender_estimation:
        gender_estimatior = GenderEstimation(reader.get_width(), reader.get_height(), inferencer=inferencer)
    if run_faceid:
        faceid = FaceID(reader.get_width(), reader.get_height(), inferencer=inferencer)
    if emotions_recognision:
        emotions_recogniser = EmotionsRecognision(reader.get_width(), reader.get_height(), inferencer=inferencer)
    if faceid_search:
        try:
            faceid_dict_f = open(faceid_dict, "r")
        except IOError:
            raise ErrorSignal(faceid_dict_missing)
        faceid_json = json.load(faceid_dict_f)
        faceid_dict_f.close()
        faceids = []
        for name in faceid_json:
            faceids.append((name, faceid_json[name]['threshold'], np.array(faceid_json[name]['feautures'])))

    callbacks = []

    if visualise_callback:
        callbacks.append(Visualiser(reader.get_width(), reader.get_height()))

    if not(json_logger is None):
        callbacks.append(JSONLogger(reader.get_width(), reader.get_height(), json_logger))

    if len(callbacks) == 0:
        reader.release()
        raise ErrorSignal(nothing_to_do)

    if mode == 'byframe':
        frame_number = 0
        try:
            while True:
                frame = reader.read()
                boxes = detector.detect(frame)
                genders = None
                faceid_feautures = None
                emotions = None
                names = None
                if gender_estimation:
                    genders = gender_estimatior.estimate(frame, boxes)
                if emotions_recognision:
                    emotions = emotions_recogniser.recognise(frame, boxes)
                if run_faceid:
                    faceid_feautures = faceid.feautures(frame, boxes)
                if faceid_search:
                    names = []
                    for i in range(faceid_feautures.shape[0]):
                        face_names = []
                        for fid in faceids:
                            d = np.min(cosine_dist_norm(faceid_feautures[i].reshape(1, 128), fid[2]))
                            if d < fid[1]:
                                face_names.append(fid[0])
                        names.append(face_names)
                if not(create_feauture_list is None):
                    if faceid_feautures.shape[0] > 1:
                        raise ErrorSignal(only_one_face_required_in_create_feauture_list_mode)
                    elif faceid_feautures.shape[0] == 1:
                        feauture_list.append(faceid_feautures[0])
                frame_number += 1
                for callback in callbacks:
                    try:
                        callback.call(video=video, frame=frame, boxes=boxes, frame_number=frame_number, genders=genders, emotions=emotions, faceid_feautures=faceid_feautures, names=names)
                    except QuitSignal as ret:
                        exit_code = int(ret)
                        break
                else:
                    continue
                break
        except KeyboardInterrupt:
            exit_code = 0
            pass
        reader.release()
        for callback in callbacks:
            callback.destroy()
    elif mode == 'realtime':
        raise NotImplementedError()
    else:
        raise ErrorSignal(unknown_mode)

    if not(create_feauture_list is None):
        try:
            create_feauture_list = str(create_feauture_list)
        except (KeyError, ValueError):
            raise ErrorSignal(invalid_argument_value)
        feautures, threshold = feauture_select(feauture_list)
        try:
            faceid_dict_f = open(faceid_dict, "r")
        except IOError:
            raise ErrorSignal(faceid_dict_missing)
        faceid_json = json.load(faceid_dict_f)
        faceid_dict_f.close()
        faceid_json[create_feauture_list] = {
            'threshold': float(threshold),
            'feautures': feautures.tolist()
        }
        try:
            faceid_dict_f = open(faceid_dict, "w")
        except IOError:
            raise ErrorSignal(faceid_dict_missing)
        json.dump(faceid_json, faceid_dict_f)
        faceid_dict_f.close()
        print(faceid_success_prefix + create_feauture_list + faceid_success_suffix)

    return exit_code
Пример #17
0
from controller import Controller
from cmdview import CmdView
from file_reader import FileReader
from data_parser import DataParser
from validator import Validator
from database import Database
from visualiser import Visualiser
from serializer import Serializer

if __name__ == "__main__":
    parser = DataParser()
    cmd_view = CmdView()
    file_reader = FileReader()
    validator = Validator()
    db = Database("test.db")
    vis = Visualiser()
    serial = Serializer()

    con = Controller(cmd_view, file_reader, parser, validator, db, vis, serial)
    cmd_view.set_controller(con)

    # run program
    cmd_view.cmdloop()
Пример #18
0
import pygame
import sys
import random

from map import Map
from visualiser import Visualiser
from pathfinder import Pathfinder

map = Map()
map.loadData()

visualiser = Visualiser("Inlupp 2 - Visualiser", map.getWidth(),
                        map.getHeight())
visualiser.setMap(map)

pathfinder = Pathfinder(visualiser, map)
pathfinder.findCheapestPath()

visualiser.runLoop()
Пример #19
0
def main(arglist):
    input_file = arglist[0]
    output_file = arglist[1]

    spec = ProblemSpec(input_file)

    init_node = GraphNode(spec, spec.initial)
    goal_node = GraphNode(spec, spec.goal)

    steps = []

    #
    #
    # Code for your main method can go here.
    #
    # Your code should find a sequence of RobotConfig objects such that all configurations are collision free, the
    # distance between 2 successive configurations is less than 1 primitive step, the first configuration is the initial
    # state and the last configuration is the goal state.
    #
    #
    def get_config_distance(c1, c2, spec):
        max_ee1_delta = 0
        max_ee2_delta = 0
        for i in range(spec.num_segments):
            if abs((c2.ee1_angles[i] - c1.ee1_angles[i]).in_radians()) > max_ee1_delta:
                max_ee1_delta = abs((c2.ee1_angles[i] - c1.ee1_angles[i]).in_radians())

            if abs((c2.ee2_angles[i] - c1.ee2_angles[i]).in_radians()) > max_ee2_delta:
                max_ee2_delta = abs((c2.ee2_angles[i] - c1.ee2_angles[i]).in_radians())

        # measure leniently - allow compliance from EE1 or EE2
        max_delta = min(max_ee1_delta, max_ee2_delta)

        for i in range(spec.num_segments):
            if abs(c2.lengths[i] - c1.lengths[i]) > max_delta:
                max_delta = abs(c2.lengths[i] - c1.lengths[i])

        return max_delta

    def rand_angle():
        minKAngle = -2879
        maxKAngle = 2879
        anglesRand = Angle(radians=0.001) * random.randint(minKAngle, maxKAngle)
        return anglesRand

    def rand_length(spec, initLength):
        minKLength = 0
        maxKLength = (spec.max_lengths[0] - spec.min_lengths[0]) / 0.001
        maxKLength = float(f'{maxKLength:.3f}')
        if not maxKLength == 0:
            return float(f'{initLength + random.randint(minKLength, maxKLength) * 1e-3:.3f}')
        else:
            return initLength

    def generate_sample():
        initialConfig = spec.initial

        # if spec.initial.ee1_grappled:
        #     initialAngles = initialConfig.ee1_angles
        # else:
        #     initialAngles = initialConfig.ee2_angles
        anglesRand = []
        for i in range(spec.num_segments):
            anglesRand.append(rand_angle())
        # print([angle.in_degrees() for angle in anglesRand])

        lengthsRand = [rand_length(spec, length) for length in spec.min_lengths]

        randomIndexGrapplePoint = random.randint(0, len(spec.grapple_points) - 1)
        grappleXRand, grappleYRand = spec.grapple_points[randomIndexGrapplePoint]

        # check number of grapple
        numGrapplePoints = spec.num_grapple_points
        if numGrapplePoints == 1:
            ee1_grappled = True if spec.initial.ee1_grappled else False
            ee2_grappled = not ee1_grappled
        else:
            # Careful
            ee1_grappled = bool(random.getrandbits(1))
            ee2_grappled = bool(random.getrandbits(1))

        if ee1_grappled:
            robotConfig = make_robot_config_from_ee1(grappleXRand, grappleYRand, anglesRand, lengthsRand,
                                                     ee1_grappled=ee1_grappled, ee2_grappled=ee2_grappled)
        else:
            robotConfig = make_robot_config_from_ee2(grappleXRand, grappleYRand, anglesRand, lengthsRand,
                                                     ee1_grappled=ee1_grappled, ee2_grappled=ee2_grappled)

        if test_obstacle_collision(robotConfig, spec, spec.obstacles) and test_self_collision(robotConfig, spec):
            return robotConfig

        return generate_sample()

    def get_current_grapple_point(config):
        if config.ee1_grappled:
            return config.get_ee1()
        return config.get_ee2()

    def get_nearest_grapple_point(newConfig, lastX, lastY):
        nearestGrappleDistance = float('inf')
        nearestGrapplePoint = None
        for grapplePoint in spec.grapple_points:
            if grapplePoint == get_current_grapple_point(newConfig):
                continue
            grappleX, grappleY = grapplePoint
            deltaX = abs(lastX - grappleX)
            deltaY = abs(lastY - grappleY)
            if deltaX + deltaY < nearestGrappleDistance:
                nearestGrappleDistance = deltaX + deltaY
                nearestGrapplePoint = grapplePoint
                delta = (deltaX, deltaY)
        return nearestGrapplePoint

    def get_perpendicular_intersect(A, B, C):
        x1, y1 = A
        x2, y2 = B
        x3, y3 = C
        px = x2 - x1
        py = y2 - y1
        dAB = px * px + py * py
        u = ((x3 - x1) * px + (y3 - y1) * py) / dAB
        x = x1 + u * px
        y = y1 + u * py;
        return x, y

    def get_bridge_config(ee1_grappled, ee2_grappled, grappledX, grappledY):
        # randomly sample n-1 links
        while True:
            anglesRand = []
            lengthsRand = []
            for i in range(spec.num_segments - 1):
                anglesRand.append(rand_angle())
                lengthsRand.append(rand_length(spec, spec.min_lengths[i]))
            # Connect last link to the endpoint
            # Get coords of the second last joint
            if ee1_grappled:
                newConfig = make_robot_config_from_ee1(grappledX, grappledY, anglesRand, lengthsRand,
                                                       ee1_grappled, ee2_grappled)
            else:
                newConfig = make_robot_config_from_ee2(grappledX, grappledY, anglesRand, lengthsRand,
                                                       ee1_grappled, ee2_grappled)

            # if not test_obstacle_collision(newConfig, spec, spec.obstacles) or not test_self_collision(newConfig, spec):
            #     continue

            lastX, lastY = newConfig.points[-1]

            grapplePoint = get_nearest_grapple_point(newConfig, lastX, lastY)

            # xD, yD = get_perpendicular_intersect(newConfig.points[-1], newConfig.points[-2], grapplePoint)
            # deltaY = math.sqrt((grapplePoint[0] - xD)**2 + (grapplePoint[1] - yD)**2)
            # deltaX = math.sqrt((grapplePoint[0] - lastX) ** 2 + (grapplePoint[1] - lastY) ** 2)

            # angleLastLink = - Angle.atan(deltaY / deltaX)
            # lengthLastLink = math.sqrt(deltaX**2 + deltaY**2)

            gX, gY = grapplePoint
            deltaY = gY - lastY
            deltaX = gX - lastX
            angleLastLink = Angle.atan2(deltaY, deltaX)
            lengthLastLink = math.sqrt(deltaY**2 + deltaX**2)

            if not ((-11 * math.pi / 12) - spec.TOLERANCE < angleLastLink < (11 * math.pi / 12) + spec.TOLERANCE) \
                    or lengthLastLink < spec.min_lengths[-1] - spec.TOLERANCE \
                    or lengthLastLink > spec.max_lengths[-1] + spec.TOLERANCE:
                continue

            anglesRand.append(angleLastLink)
            lengthsRand.append(lengthLastLink)

            if ee1_grappled:
                finalConfig = make_robot_config_from_ee1(grappledX, grappledY, anglesRand, lengthsRand,
                                                         ee1_grappled=ee1_grappled, ee2_grappled=True)
            else:
                finalConfig = make_robot_config_from_ee2(grappledX, grappledY, anglesRand, lengthsRand,
                                                         ee1_grappled=True, ee2_grappled=ee2_grappled)

            gX, gY = finalConfig.points[-1]
            grappledX, grappledY = grapplePoint
            if not point_is_close(gX, gY, grappledX, grappledY, spec.TOLERANCE):
                continue
            if test_obstacle_collision(finalConfig, spec, spec.obstacles) and test_self_collision(finalConfig, spec):
                return finalConfig

    def interpolate_path(RobotConfig1, RobotConfig2):
        paths = [RobotConfig1]

        lengths1 = RobotConfig1.lengths
        lengths2 = RobotConfig2.lengths

        kLengths = []
        for i in range(len(lengths1)):
            differences = lengths2[i] - lengths1[i]
            if differences >= 0:
                kLengths.append(math.floor(differences / 0.001))
            else:
                kLengths.append(math.ceil(differences / 0.001))

        angles1 = RobotConfig1.ee1_angles
        angles2 = RobotConfig2.ee1_angles

        kAngles = []
        for i in range(len(angles1)):
            differences = angles2[i].radians - angles1[i].radians
            if differences >= 0:
                kAngles.append(math.floor(differences / 0.001))
            else:
                kAngles.append(math.ceil(differences / 0.001))

        if RobotConfig1.ee1_grappled:
            ee2Grappled = True if RobotConfig1.ee2_grappled else False
            ee1Grappled = True
            grappledX, grappledY = RobotConfig1.get_ee1()
        else:
            ee2Grappled = True
            ee1Grappled = False
            grappledX, grappledY = RobotConfig1.get_ee2()

        #  for each config,
        newLengths = []
        newAngles = []
        counter = 0
        # getConfig2 = False
        while True:
            if counter < 2:
                counter += 1
            for i in range(len(lengths1)):
                if kLengths[i] > 0:
                    if counter == 1:
                        newLengths.append(lengths1[i] + 0.001)
                    else:
                        newLengths[i] += 0.001
                    kLengths[i] -= 1
                elif kLengths[i] < 0:
                    if counter == 1:
                        newLengths.append(lengths1[i] - 0.001)
                    else:
                        newLengths[i] -= 0.001
                    kLengths[i] += 1
                else:
                    if counter != 1:
                        if lengths2[i] - newLengths[i] > 0:
                            newLengths[i] += (lengths2[i] - newLengths[i])
                        elif lengths2[i] - newLengths[i] < 0:
                            newLengths[i] -= (lengths1[i] - lengths2[i])
                    else:
                        newLengths.append(lengths1[i])

                if kAngles[i] > 0:
                    if counter == 1:
                        newAngles.append(angles1[i] + 0.001)
                    else:
                        newAngles[i] += 0.001
                    kAngles[i] -= 1

                    print(newAngles[i])
                    print(angles2[i])
                elif kAngles[i] < 0:
                    if counter == 1:
                        newAngles.append(angles1[i] - 0.001)
                    else:
                        newAngles[i] -= 0.001
                    kAngles[i] += 1
                else:
                    if counter != 1:
                        # if i == 0:
                        #     print("This")
                        if angles2[i] > newAngles[i]:
                            newAngles[i] += (angles2[i] - newAngles[i])
                        elif angles2[i] < newAngles[i]:
                            newAngles[i] -= (newAngles[i] - angles2[i])
                    else:
                        newAngles.append(angles1[i])
                if i == len(lengths1) - 1:
                    newConfig = make_robot_config_from_ee1(x=grappledX, y=grappledY,
                                                           angles=newAngles.copy(), lengths=newLengths.copy(),
                                                           ee1_grappled=ee1Grappled, ee2_grappled=ee2Grappled)
                    paths.append(newConfig)

            if paths[-1]:
                if test_config_equality(paths[-1], RobotConfig2, spec):
                    break

        return paths

    def check_path_collision(RobotConfig1, RobotConfig2):
        """
        return: true if pass, false otherwise
        """
        configList = interpolate_path(RobotConfig1, RobotConfig2)
        for config in configList:
            if not test_obstacle_collision(config, spec, spec.obstacles):
                return False
        return True

    def connect_node(Node1, Node2):
        if check_path_collision(Node1.config, Node2.config):
            GraphNode.add_connection(Node1, Node2)

    def build_graph():
        graph = []
        paths = []
        # graph.add(init_node)
        # graph.add(goal_node)

        minInitDistance = float('inf')
        minGoalDistance = float('inf')
        while True:
            numberOfSamples = 10
            for i in range(numberOfSamples):
                randomConfig = generate_sample()

                # initDistance = get_config_distance(init_node.config, randomConfig, spec)
                # if initDistance < minInitDistance:
                #     minInitDistance = initDistance
                #     configNearInit = randomConfig
                #
                # goalDistance = get_config_distance(goal_node.config, randomConfig, spec)
                # if goalDistance < minGoalDistance:
                #     minGoalDistance = goalDistance
                #     configNearGoal = randomConfig

                newNode = GraphNode(spec, randomConfig)

                if graph:
                    for node in graph:
                        # Should bias the node with low distance
                        connect_node(newNode, node)
                        # careful
                    connect_node(newNode, goal_node)
                    connect_node(newNode, init_node)
                    graph.append(newNode)
                else:
                    graph.append(newNode)

            # connect init and goal to the graph
            # nodeNearInit = GraphNode(spec, configNearInit)
            # nodeNearGoal = GraphNode(spec, configNearGoal)
            # connect_node(init_node, nodeNearInit)
            # connect_node(goal_node, nodeNearGoal)

            initPaths = find_graph_path(spec, init_node)
            # if initPaths:
            #      return initPaths
            # else:
            #     continue

            foundGoal = True
            if initPaths:
                for i in range(len(initPaths) - 1):
                    if check_path_collision(initPaths[i], initPaths[i + 1]):
                        paths += (interpolate_path(initPaths[i], initPaths[i + 1]))
                    else:
                        foundGoal = False
                        paths = []
                        break
                if foundGoal:
                    return paths

    if len(arglist) > 1:
        counter = 0
        while counter < 10:
            counter += 1
            print(counter)
            grappleX, grappleY = spec.initial.get_ee1()
            config = get_bridge_config(spec.initial.ee1_grappled, spec.initial.ee2_grappled, grappleX, grappleY)
            steps.append(config)

        # steps = build_graph()
        # grappleX, grappleY = spec.initial.get_ee1()
        # steps = get_bridge_config(spec.initial.ee1_grappled, spec.initial.ee2_grappled, grappleX, grappleY)
        # print("Bridge", bridge)
        # steps = interpolate_path(spec.initial, )
        write_robot_config_list_to_file(output_file, steps)

    #
    # You may uncomment this line to launch visualiser once a solution has been found. This may be useful for debugging.
    # *** Make sure this line is commented out when you submit to Gradescope ***
    #
    v = Visualiser(spec, steps)
Пример #20
0
#new_data = new_data[:, :]
#new_means = new_means[:, :]

reducer5 = umap.UMAP(n_components=3, verbose=True)
reducer = umap.UMAP(n_components=2,
                    metric=metrics.fast_bhattacharyya_mvn,
                    metric_kwds={'dim': dim},
                    verbose=True)
reducer2 = skman.Isomap(n_components=3)
reducer3 = skman.LocallyLinearEmbedding(n_components=2)
reducer4 = skman.SpectralEmbedding(n_components=2)
#reducer = umap.UMAP(n_components = 3, metric = metrics.bhattacharyya_mvn_vec, metric_kwds = {'dim': dim, 'full_cov': False}, verbose = True)
#reducer = umap.UMAP(n_components = 2)

labels = {'Leg': labels[::20], 'Slice': slices[::20]}
visualiser = Visualiser(data[::20], labels, reducer)
#visualiser = Visualiser(means[::50], [labels[::50], labels2[::50]], reducer4)
visualiser.fit_transform()
visualiser.plot_result()

##embedding = reducer.fit_transform(new_means)
##embedding = reducer.fit_transform(new_data)
#t = time.time()
#embedding = reducer.fit_transform(data[::50])
#elapsed = time.time() - t
#print("Fitting and transforming took {} seconds".format(elapsed))

## 2D Plot
##plt.scatter(embedding[:, 0], embedding[:, 1], c= labels[:], cmap='Spectral', s=5)
##plt.show()
Пример #21
0
            vis.update_canvas(env.actor, env.enemy)
            if done:
                break
    print("Games won: " + str(env.win_count))
    vis.destroy()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='QMaze options')
    parser.add_argument('--test',
                        dest='test',
                        action='store_true',
                        help='if you wish to re-train')
    parser.add_argument('--vis',
                        dest='vis',
                        action='store_true',
                        help='if you wish to see the GUI')
    args = parser.parse_args()
    print(args)
    if (args.test):
        env = Maze()
        RL = QLearn(actions=list(range(env.n_actions)))
        if (args.vis):
            vis = Visualiser(4, 4, 80, env.hell_blocks, env.goal, env.enemy)
        test(args.vis)
    else:
        env = Maze()
        vis = Visualiser(4, 4, 80, env.hell_blocks, env.goal, env.enemy)
        RL = QLearn(actions=list(range(env.n_actions)), e_greedy=1.0)
        run_optimal()
Пример #22
0
            sky_type += "-rgb"
        step = .1  # 10 cm
        tau_phi = np.pi  # 60 deg
        condition = Hybrid(tau_x=step, tau_phi=tau_phi)
        agent_name = create_agent_name(date, sky_type, step, fov[0], fov[1])
        print agent_name

        world = load_world()
        world.enable_pol_filters(enable_pol)
        world.uniform_sky = uniform_sky
        routes = load_routes()
        world.add_route(routes[0])

        agent = MBAgent(condition=condition,
                        live_sky=update_sky,
                        visualiser=Visualiser(),
                        rgb=rgb,
                        fov=fov,
                        name=agent_name)
        agent.set_world(world)
        print agent.homing_routes[0]

        agent.visualiser.set_mode("panorama")
        for route in agent.start_learning_walk():
            print "Learned route:", route

        agent.visualiser.set_mode("top")
        route = agent.start_homing()
        print route
        if route is not None:
            save_route(route, agent_name)
                                       body_luminosity=7,
                                       body_object_area=5000,
                                       body_hole_area=5000,
                                       edge_luminosity=7,
                                       edge_object_area=6,
                                       edge_hole_area=5000)
segmentor_nuc = ConfocalNucleusSegmentor(img_retriever=skimage_img_retriever)

masker_cell = ConfocalCellAreaMasker(img_retriever=skimage_img_retriever,
                                     body_luminosity=7,
                                     body_object_area=100,
                                     body_hole_area=100)
segmentor_cell = ConfocalCellSegmentor(img_retriever=skimage_img_retriever)

shaper_cell = ImageShapeMaker(img_retriever=skimage_img_retriever)
viz = Visualiser(cmap='gray', cmap_set_under='green')

df_labels = parse_labels('./data_tmp/train.csv')

for cell_id, data_path_collection in local_imgs.items():

    if not '0020ad' in cell_id:
        continue

    img_nuc = data_path_collection['nuclei']
    img_er = data_path_collection['ER']
    img_tube = data_path_collection['microtubule']
    img_prot = data_path_collection['green']

    masker_nuc.make_mask_(img_nuc)
    segmentor_nuc.make_segments_(img_nuc, masker_nuc.mask)
Пример #24
0
 def overview_chart(self):
     if not self._scored : self.score_tweets()
     sentiments = [sentiment for sentiment in self.models_ar]
     Visualiser(self._data).overview(sentiments=sentiments)