コード例 #1
0
def command_line_arguments(year, month, day, plot_day, plot_month):
    if day!='None':
        limit = monthrange(int(year), int(month))[1]
        if int(day) > limit:
            print("Invalid Date for given month and year. Exiting...\n")
            exit()
        val = get_day(year, month, day)

        if plot_day:
            try:
                plot_points = get_day(year, month, day, rtr=True); val=False
                pl = plotting.Plotting(year=year, month=month, day=day)
                pl.normal_plot(plot_points)
                return "plotted"
            except IndexError:
                pass

    elif day == 'None':
        if month and year:
            print("\n YEAR: {} | MONTH: {} | \n".format(year, month))
            get_data.main(year, month)

            if plot_month:
                try:
                    monthly_average = get_month(year, month)
                    plot = plotting.Plotting(year=year, month=month)
                    plot.normal_plot(monthly_average, day=False)
                except IndexError:
                    raise("Index Error. Can't Plot Monthy Average Values.")
コード例 #2
0
    def __init__(self, s_start, s_goal, step_len, goal_sample_rate,
                 waypoint_sample_rate, iter_max):
        self.s_start = Node(s_start)
        self.s_goal = Node(s_goal)
        self.step_len = step_len
        self.goal_sample_rate = goal_sample_rate
        self.waypoint_sample_rate = waypoint_sample_rate
        self.iter_max = iter_max
        self.vertex = [self.s_start]
        self.vertex_old = []
        self.vertex_new = []
        self.edges = []

        self.env = env.Env()
        self.plotting = plotting.Plotting(s_start, s_goal)
        self.utils = utils.Utils()
        self.fig, self.ax = plt.subplots()

        self.x_range = self.env.x_range
        self.y_range = self.env.y_range
        self.obs_circle = self.env.obs_circle
        self.obs_rectangle = self.env.obs_rectangle
        self.obs_boundary = self.env.obs_boundary
        self.obs_add = [0, 0, 0]  # [x,y,r]

        self.path = []
        self.waypoint = []
def run_sklearn_svm(kernel='linear', C='auto', gamma='auto', degree='auto'):
    #------------------------------------------------------------------------------------------------------------------
    # Initialise Classes:
    objData = datageneration.Data();                                                 # Data object.
    objPlot = plotting.Plotting();                                                   # Plotting object.

    # Generate Data:
    # Run Fit:
    if kernel == 'linear':
        if C>10:
            X1, y1, X2, y2 = objData.gen_lin_separable_overlap_data(seed=1)
        else:
            X1, y1, X2, y2 = objData.generate_linearly_separable_data(seed=1)

        skl = SVC(kernel=kernel,C=C)  # Fit the training data.
    elif kernel == 'poly':
        X1, y1, X2, y2 = objData.gen_non_lin_separable_data(seed=1)
        ### NOTE: polynomial kernel has some input 'coef0'. This is interpretted as C by other kernels.
        ### sklearn documentation:
        ### K(X, Y) = (gamma < X, Y > + coef0) ^ degree
        ### source: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.polynomial_kernel.html
        skl = SVC(kernel=kernel,coef0=C,  gamma=gamma, degree=degree, tol=0.000001)  # Fit the training data.
    elif kernel == 'rbf':
        X1, y1, X2, y2 = objData.gen_non_lin_separable_data(seed=1)
        skl = SVC(kernel=kernel, gamma=gamma)  # Fit the training data.

    percent = 0.80  # The amount of data assigned to training.
    X_train, y_train, X_test, y_test = datageneration.Data.split_data(X1, y1, X2, y2,percent)  # Break up examples into training and test data.

    objFit = skl.fit(X_train, y_train)
    objFit.fit_type = 'sklearn'

    # Output:
    objPlot.plot_margin(X_train[y_train == 1], X_train[y_train == -1], objFit);  # Plot the margin and training data.
コード例 #4
0
ファイル: Astar.py プロジェクト: sldai/RoboticsAdventure
def main():
    s_start = (2, 2)
    s_goal = (49, 24)

    astar = AStar(s_start, s_goal, "euclidean", res=1.0)
    plot = plotting.Plotting(s_start, s_goal)
    path, visited = astar.searching()
    plot.animation(visited, path, "A*")  # animation
コード例 #5
0
ファイル: Dijkstra.py プロジェクト: sldai/RoboticsAdventure
def main():
    s_start = (2, 2)
    s_goal = (49, 24)

    astar = Dijkstra(s_start, s_goal, res=1.0)
    plot = plotting.Plotting(s_start, s_goal)
    path, visited = astar.searching()
    plot.animation(visited, path, "Dijkstra*")  # animation
コード例 #6
0
def main():
    s_start = (7, 7)
    s_goal = (1, 1)

    astar = AStar(s_start, s_goal, "manhattan")
    plot = plotting.Plotting(s_start, s_goal)

    path, visited = astar.searching()
    plot.animation(path, visited, "A*")  # animation
コード例 #7
0
 def main(self):
     self.PARENT[self.s_start] = None
     self.g[self.s_start] = 0
     self.g[self.s_goal] = math.inf
     self.OPEN.put(self.s_start, self.f_value(self.s_start))
     path, node_list = self.compute_shortest_path()
     self.plot = plotting.Plotting(self.s_start, self.s_goal)
     self.plot.animation(node_list, path, "Anytime D*", show=False)
     self.fig = plt.gcf()
     self.fig.canvas.mpl_connect('button_press_event', self.on_press)
     plt.show()
コード例 #8
0
def main():
    s_start = (7, 7)
    s_goal = (1, 1)

    arastar = AraStar(s_start, s_goal, 2.5, "euclidean")
    plot = plotting.Plotting(s_start, s_goal)

    path, visited = arastar.searching()
    for p in path:
        print(len(p))
    print(len(path))
    plot.animation_ara_star(path, visited, "Anytime Repairing A* (ARA*)")
コード例 #9
0
def cla():
    val = True
    try:
        year = sys.argv[1]
        month = sys.argv[2]
    except IndexError:
        display_error()
        exit()
    try:
        if int(year) > 2013 or int(year) < 1950:
            print("Year beyond the range. Exiting...\n")
            display_error()
            exit()
        if int(month) < 1 or int(month) > 12:
            print("Invlaid Month. Exiting...\n")
            display_error()
            exit()
    except ValueError:
        print("Invalid Numerical Value")
        exit()
    try:
        day = sys.argv[3]
        if int(day) > 31 or int(day) < 1:
            print("Invalid Dates. Exiting...\n")
            display_error()
            exit()
        limit = monthrange(int(year), int(month))[1]
        if int(day) > limit:
            print("Invalid Date for given month and year. Exiting...\n")
            display_error()
            exit()
        try:
            if not sys.argv[4]:
                val = get_day(year, month, day)
        except:
            pass
    except IndexError:
        pass
    try:
        if sys.argv[4]:
            plot_points = get_day(year, month, day, rtr=True)
            val = False
            pl = plotting.Plotting(year=year, month=month, day=day)
            pl.normal_plot(plot_points)
            return "plotted"
    except IndexError:
        pass
    if val:
        get_data.main(year, month)
コード例 #10
0
    def __init__(self, start, goal, obs, bot_size, ratio):
        self.decider = Decider()
        self.decider.reinit(start, goal)
        self.astar = Astar(start, goal, obs, bot_size, ratio)
        self.plot = plotting.Plotting(start, goal, obs)
        # self.astar_sol = self.astar.searching()[0]

        # self.REWARD_STEP = 0.01
        self.REWARD_REACH = 100
        self.REWARD_BOUND = -10
        self.REWARD_CRASH = -10
        self.REWARD_OVERRUN = -10
        self.MAX_STEPS = 100
        self.BOUNDS = [1000,800]  # tune according to the environment
        self.TOTAL_DISTANCE = self.count_distance()  # the Original distance between goal and start 
コード例 #11
0
    def __init__(self, s_start, s_goal, step_len, goal_sample_rate, iter_max):
        self.s_start = Node(s_start)
        self.s_goal = Node(s_goal)
        self.step_len = step_len
        self.goal_sample_rate = goal_sample_rate
        self.iter_max = iter_max
        self.vertex = [self.s_start]

        self.env = env.Env()
        self.plotting = plotting.Plotting(s_start, s_goal)
        self.utils = utils.Utils()

        self.x_range = self.env.x_range
        self.y_range = self.env.y_range
        self.obs_circle = self.env.obs_circle
        self.obs_rectangle = self.env.obs_rectangle
        self.obs_boundary = self.env.obs_boundary
コード例 #12
0
def realtime_search(objects):
    """ Path finding with realtime Astar algorithm
    return command at each step and the original Astar path solution"""

    decider = Decider(False)
    # plot the original path
    jetbot_pos, jetbot_size = objects['Jetbot'][0], objects['Jetbot'][-4:]
    grab_pos = objects['Grabber'][0]
    decider.reinit(jetbot_pos, grab_pos)

    obstacle_ls = objects['Obstacle']
    s_start = objects['Jetbot'][0]
    s_goal = objects['Target'][0]
    if type(obstacle_ls[0]) == type(()):  # if there is only one obstacle:
        obstacle_ls = [obstacle_ls]

    global Ratio
    Path_Found = False
    while not Path_Found:  # Error might take place when scale changes
        try:
            astar = Astar(s_start, s_goal, obstacle_ls, jetbot_size, Ratio)
            Original_path, visited = astar.searching()
            Path_Found = True
        except UnboundLocalError:
            Ratio -= 0.1
            print('Error, try change the size, ratio = ', Ratio)

    plot = plotting.Plotting(s_start, s_goal, obstacle_ls)
    plot.animation(Original_path, visited, 'AStar')

    # define path and obstacle set
    path = Original_path
    obs_set = get_obs_set(obstacle_ls, jetbot_size)

    # start iteration
    while len(path) > decider.Horizon:
        decider.jetbot_step(path, obs_set)
        path = Astar_search(objects, decider)

    # get the result
    trajectory = decider.get_trajectory()
    print('Terminate, Total number of movements is: %d' % len(trajectory))
    plot.plot_traj(Original_path, trajectory)
    return decider.cmd_record, Original_path
コード例 #13
0
    def __init__(self, x_start, x_goal):
        self.xI, self.xG = x_start, x_goal
        self.e = 0.001  # threshold for convergence
        self.gamma = 0.9  # discount factor

        self.env = env.Env(self.xI, self.xG)
        self.motion = motion_model.Motion_model(self.xI, self.xG)
        self.plotting = plotting.Plotting(self.xI, self.xG)

        self.u_set = self.env.motions  # feasible input set
        self.stateSpace = self.env.stateSpace  # state space
        self.obs = self.env.obs_map()  # position of obstacles
        self.lose = self.env.lose_map()  # position of lose states

        self.name1 = "policy_iteration, gamma=" + str(self.gamma)

        [self.value, self.policy] = self.iteration()
        self.path = self.extract_path(self.xI, self.xG, self.policy)
        self.plotting.animation(self.path, self.name1)
コード例 #14
0
    def __init__(self, step_len, goal_sample_rate, iter_max):

        self.step_len = step_len
        self.goal_sample_rate = goal_sample_rate
        self.iter_max = iter_max

        self.env = env.Env()
        self.plotting = plotting.Plotting("RRT_CONNECT")
        self.utils = utils.Utils()

        self.x_range = self.env.x_range
        self.y_range = self.env.y_range
        self.obs_circle = self.env.obs_circle
        self.obs_rectangle = self.env.obs_rectangle
        self.obs_boundary = self.env.obs_boundary
        self.s_start = Node((0, 0))
        self.s_goal = Node((0, 0))
        self.path = []
        self.key_points = []
def run_custom_svm(kernel='linear', C=0, gamma=0.1, degree=3):
    #--------------------------------------------------------------
    # Purpose: SVM hard margin estimation and plot.
    # Inputs:
    #       run_type    : What margin calculation to perform.
    #                     Accepted Inputs: 'hard','soft','kernel'.
    #--------------------------------------------------------------

    print("Estimating kernel: " + kernel)

    # Initialise Classes:
    objData = datageneration.Data();                                                 # Data object.
    objPlot = plotting.Plotting();                                                   # Plotting object.

    # Generate Data:
    if kernel == 'linear':
        if C==None or C==0:
            # Soft margin
            X1, y1, X2, y2 = objData.generate_linearly_separable_data(seed=1)
        else:
            # Hard margin
            X1, y1, X2, y2 = objData.gen_lin_separable_overlap_data(seed=1)  # Generate the examples.
    elif kernel=='polynomial' or kernel=='gaussian':
        X1, y1, X2, y2 = objData.gen_non_lin_separable_data(seed=1)
    else:
        return

    objFit = SVM(kernel=kernel, C=C, gamma=gamma, degree=degree)  # Create model object.

    # Run Fit:
    percent=0.80                                                              # The amount of data assigned to training.
    X_train, y_train, X_test, y_test = datageneration.Data.split_data(X1, y1, X2, y2,percent)   # Break up examples into training and test data.
    objFit.fit(X_train, y_train)                                            # Fit the training data.
    y_predict = objFit.predict(X_test)                                       # Fit the out-of-sample (predicted data).
    correct_predictions = np.sum(y_predict == y_test)                                    # Check how many examples were predicted correctly.
    objFit.correct_predictions=correct_predictions
    objFit.number_of_test_examples = len(X_test)
    objFit.number_of_train_examples = len(X_train)
    objFit.fit_type = 'custom'

    # Output:
    formattedOutput(objFit)
    objPlot.plot_margin(X_train[y_train == 1], X_train[y_train == -1], objFit);  # Plot the margin and training data.
コード例 #16
0
    def __init__(self, env, x_start, x_goal, step_len,
                 goal_sample_rate, search_radius, iter_max):
        self.s_start = Node(x_start)
        self.s_goal = Node(x_goal)
        self.step_len = step_len
        self.goal_sample_rate = goal_sample_rate
        self.search_radius = search_radius
        self.iter_max = iter_max
        self.vertex = [self.s_start]
        self.path = []

        self.env = env
        self.plotting = plotting.Plotting(self.env, x_start, x_goal)
        self.utils = utils.Utils(self.env)

        self.x_range = self.env.x_range
        self.y_range = self.env.y_range
        self.obs_circle = self.env.obs_circle
        self.obs_rectangle = self.env.obs_rectangle
        self.obs_boundary = self.env.obs_boundary
コード例 #17
0
    def __init__(self, x_start, x_goal):
        self.xI, self.xG = x_start, x_goal
        self.M = 500  # iteration numbers
        self.gamma = 0.9  # discount factor
        self.alpha = 0.5
        self.epsilon = 0.1

        self.env = env.Env(self.xI, self.xG)
        self.motion = motion_model.Motion_model(self.xI, self.xG)
        self.plotting = plotting.Plotting(self.xI, self.xG)

        self.u_set = self.env.motions  # feasible input set
        self.stateSpace = self.env.stateSpace  # state space
        self.obs = self.env.obs_map()  # position of obstacles
        self.lose = self.env.lose_map()  # position of lose states

        self.name1 = "SARSA, M=" + str(self.M)

        [self.value, self.policy] = self.Monte_Carlo(self.xI, self.xG)
        self.path = self.extract_path(self.xI, self.xG, self.policy)
        self.plotting.animation(self.path, self.name1)
コード例 #18
0
    def initiate(self, param):
        if param['modelname'] == 'LES':
            self.model = model_les.LES(param, self.grid)
        elif param['modelname'] == 'linear':
            self.model = model_les.LES(param, self.grid, linear=True)
        elif param['modelname'] == 'advection':
            self.model = model_adv.Advection(param, self.grid)

        self.tend = param['tend']
        self.auto_dt = param['auto_dt']
        self.dt0 = param['dt']
        self.cfl = param['cfl']
        self.dt_max = param['dt_max']

        # Load the plotting module
        if param["show"]:
            self.plotting = plotting.Plotting(param, self.model.state,
                                              self.grid)
        else:
            self.plotting = None
        # number of grid cell per subdomain
        self.gridcellpersubdom = param["nx"] * param["ny"] * param["nz"]
コード例 #19
0
    def __init__(self, x_start, x_goal, eta, iter_max):
        self.x_start = Node(x_start[0], x_start[1])
        self.x_goal = Node(x_goal[0], x_goal[1])
        self.eta = eta
        self.iter_max = iter_max

        self.env = env.Env()
        self.plotting = plotting.Plotting(x_start, x_goal)
        self.utils = utils.Utils()

        self.fig, self.ax = plt.subplots()

        self.delta = self.utils.delta
        self.x_range = self.env.x_range
        self.y_range = self.env.y_range

        self.obs_circle = self.env.obs_circle
        self.obs_rectangle = self.env.obs_rectangle
        self.obs_boundary = self.env.obs_boundary

        self.Tree = Tree(self.x_start, self.x_goal)
        self.X_sample = set()
        self.g_T = dict()
コード例 #20
0
import simulation
import plotting as plot
import solar_system

if __name__ == "__main__":
    solar = solar_system.Solar_System()
    sun_earth = solar.get_sun_and_earth()
    solar_system = solar.get_solar_system()
    inner_solar_system = solar.get_inner_solar_system()
    outer_solar_system = solar.get_outer_solar_system()

    number_timesteps = 365 * 1
    delta_t = 1 * 24 * 60 * 60.

    sim = simulation.EulerLeapfrog(sun_earth, number_timesteps, delta_t)
    sim.run_simulation()

    print("Start Plotting")
    plot = plot.Plotting()
    plot.print_energy(sim.df)
    plot.print_position(sim.df, len(sim.bodies))
    plot.print_energy_deviation(sim.df)
    # plot.print_EvE(sim.df[["timestep", "planet0_x", "planet0_y", "planet0_z", "planet1_x", "planet1_y", "planet1_z"]])
    # plot.print_EvE(sim.df)
コード例 #21
0
def umba(x,y,z,Vtot,Theta, Psi, SpinRate, TiltH, Tiltm, SpinE, Yang, Zang, LorR, i, seamsOn, FullRot):
    """

    The inputs are:
        x,
        y,
        z,
        Initial Ball Speed,
        vertical release angle,
        horizontal release angle,
        Spin Rate,
        Tilt in Hours,
        Tilt in minutes,
        Spin Efficiency,
        Y seam orientation angle,
        Z seam orientation angle,




    Primay inputs are: initial position, x0, y0, and z0 with origin at the
    point of home plate, x to the rright of the catcher, y from the catcher
    towards the pitcher, and z straight up. Initial velocities
    u0, v0, and w0 which are the speeds of the ball in x, y, and z
    respectivley. And spin rates


   UMBA1.0: This code uses a constant Cd and rod cross's model for CL
   Predictions. Seam Orientation is not accounted for. Air Density is
   considered only at sea level at 60% relative humidity. but can be easily
   altered

   UMBA2.0 Adding seam positions and attempting to model CL from seams.
   """

    Yang = (Yang) * np.pi/180
    Zang = -Zang * np.pi/180

#    seamsOn = True
    frameRate = 0.002



    Tilt = TimeToTilt(TiltH, Tiltm)
    if LorR == 'l':
        Gyro = np.arcsin(SpinE/100)
    elif LorR =='r':
        Gyro = np.pi - np.arcsin(SpinE/100)
    else:
        while LorR != 'l' or LorR != 'r':
            if LorR == 'l':
                Gyro = np.arcsin(SpinE/100)
            elif LorR =='r':
                Gyro = np.pi - np.arcsin(SpinE/100)
            else:
                LorR = input('please type in an "l" or an "r" for which pole goes forward')

    positions,NGfinal = (PitchedBallTraj(x, y, z, Vtot, Theta, Psi, SpinRate, Tilt, Gyro, Yang, Zang, i, frameRate, seamsOn, FullRot))
    plotting.Plotting(positions)

    pX = (positions[0])
    pY = (positions[1])
    pZ = (positions[2])
    IX = (positions[3])
    IY = (positions[4])
    IZ = (positions[5])
    DX = (positions[6])
    DY = (positions[7])
    DZ = (positions[8])
    FX = (positions[9])
    FY = (positions[10])
    FZ = (positions[11])
    TF = (positions[12])
    aX = (positions[13])
    aY = (positions[14])
    aZ = (positions[15])

    TiltDeg = np.arctan2((NGfinal[0] - x + ((60-y)*np.arctan(Psi*np.pi/180))), (NGfinal[2] - z - (60-z)*np.arctan(Theta*np.pi/180)))*180/np.pi
    TiltTime = TiltToTime(-TiltDeg)
    print('Apparent Tilt = ',TiltTime[0],':',TiltTime[1])

    return(pX,pY,pZ,IX,IY,IZ,DX,DY,DZ,FX,FY,FZ,TF,aX,aY,aZ,TiltTime)
コード例 #22
0
ファイル: wrapper_OLD.py プロジェクト: RainW7/SamPy
    #If set to False, output will be save to a file rather than presented on screen
    verbose = True
    debug = False

    #sets constants
    FEFU = 10.**-15.
    FUVresel = 6.
    NUVresel = 3.

    # smoothing factor (wave - sm < x < wave + sm) for sensitivity plots
    smoothing = 5.
    g230lsm = 25.  #25

    #creates plotting and reading instances
    plot = P.Plotting('.pdf')
    log = L.Logger('Plotting.output', verbose)
    if referenceFiles or Chapter13: read = IO.COSHBIO(COSrefFiles, 'temp.tmp')
    if computedPhot: readcom = IO.COSHBIO(COScomFiles, 'tempcom.tmp')
    if local: readlocal = IO.COSHBIO(localFolder, 'templocal.tmp')
    if PSFs: readPSF = IO.COSHBIO(localFolder, 'tempPSF.tmp')

    #Begins plotting...
    if referenceFiles:
        log.write('Starting to create plots based on reference files...\n')
        ########################################################################################
        #Dispersion solutions for FUV.
        #These are needed for effective areas
        FUVd = read.FITSTable(FUVdispersionReferenceFile, 1)
        G130Mdisp = [
            x[5][1] for x in FUVd if x[0] == 'FUVA' and x[1] == 'G130M'
コード例 #23
0
"""It is possible to compute the ship wake pattern directly, thanks
to a beautiful mathematical trick found in a Pierre Gilles de Gennes
paper (French 1991 Nobel Prize). See the fourier.py module. """

# to activate it, copy-paste this script in your Ipython window, after
# you've run the main wave2d script

import plotting as pt

fig = pt.Plotting(param)
p = model.fspace.compute_balanced_wake(model.hphi0, param.U)
fig.init_figure(p)
コード例 #24
0
def main():
    x_range = 15  # size of background
    y_range = 15
    s_start = (7, 7)
    highvalueGoal = (1, 13)
    lowvalueGoal = [(1, 1), (13, 1), (13, 13)]
    motions = [(-1, 0), (0, 1), (1, 0), (0, -1)]
    x_range = 15  # size of background
    y_range = 15
    randomObsNum = 18
    randomSampleMaze = RandomSampleMaze(x_range, y_range, randomObsNum,
                                        [s_start], [highvalueGoal],
                                        lowvalueGoal)

    maze = namedtuple(
        'maze', 'initAgent highValueGoalPos highValueSteps fixedObstacles ')

    highValueSteps = 20
    lowValueSteps = 13
    numberOfMaze = 5

    # Samples = 1000000
    # for i in range(Samples):
    i = 0
    selectedMazeList = []

    visualize = True
    while i < numberOfMaze:
        proposalMaze = randomSampleMaze()
        proposalMazeWithWall = addWall(x_range, y_range, proposalMaze)
        astar = Astar.AStar(s_start, highvalueGoal, proposalMazeWithWall,
                            motions, "manhattan")
        try:
            path = []
            path, visited = astar.searching()
        except:
            pass
        else:
            pass
        if len(path) == highValueSteps:
            # print(len(path))
            popOut = False
            for goal in lowvalueGoal:
                astar2 = Astar.AStar(s_start, goal, proposalMazeWithWall,
                                     motions, "manhattan")
                try:
                    path2, visited2 = astar2.searching()
                except:
                    popOut = True
                    break
                else:
                    # print(goal, len(path2))
                    if len(path2) != lowValueSteps:
                        popOut = True
                        break
            if popOut:
                continue

            minDistractDistance = []
            for goal in lowvalueGoal:

                minDistance = np.min(
                    [calculateGridDis(goal, node) for node in path])
                # print(minDistance)
                minDistractDistance.append({goal: minDistance})

            # currentMaze = maze(initAgent = s_start, highValueGoalPos = highvalueGoal, highValueSteps = len(path), fixedObstacles = proposalMaze)
            currentMaze = {
                'initAgent': s_start,
                'highValueGoalPos': highvalueGoal,
                'highValueSteps': len(path),
                'distractDistance': minDistractDistance,
                'fixedObstacles': proposalMaze
            }
            # print(currentMaze,i)
            i = i + 1
            print(currentMaze, i)
            selectedMazeList.append(currentMaze)
            if visualize:
                plot = plotting.Plotting(s_start, highvalueGoal,
                                         proposalMazeWithWall)
                plot.animation(path, visited, "A*")  # animation


#
    savePath = os.path.join(
        'map',
        str(highValueSteps) + 'highValueSteps' + str(numberOfMaze) + 'maps' +
        '.pickle')
    saveToPickle(selectedMazeList, savePath)
コード例 #25
0
def main():
    plot = plotting.Plotting()
    plot.plot_grid("Map")

    adj_matrix = get_matrix(plot.ret_map())
コード例 #26
0
    def run(self, param, anim=True):

        if param.generation in ['wake', 'oscillator']:
            hphi = self.hphi0.copy() * 0

        else:
            hphi = self.hphi0.copy()

        if anim:
            self.plot = plotting.Plotting(param)
            var = self.fspace.compute_all_variables(hphi)
            if param.plotvector == 'velocity':
                self.plot.init_figure(self.phi0, u=var['u'], v=var['v'])

            elif param.plotvector == 'energyflux':
                self.plot.init_figure(self.phi0, u=var['up'], v=var['vp'])

            else:
                self.plot.init_figure(self.phi0)

        tend = param.tend
        dt = param.dt
        nt = int(tend / dt)
        kxx, kyy = self.fspace.kxx, self.fspace.kyy
        omega = self.fspace.omega
        propagator = np.exp(-1j * omega * dt)

        sigma = param.sigma
        aspect_ratio = param.aspect_ratio
        x0, y0 = param.x0, param.y0
        xx, yy = self.fspace.xx, self.fspace.yy

        time = 0.
        kplot = np.ceil(param.tplot / dt)
        xb, yb = param.x0 + param.Lx / 2, param.y0 + param.Ly / 2
        xb, yb = 0, 0  # param.x0, param.y0
        energy = np.zeros((nt, ))
        if param.netcdf:
            attrs = {"model": "wave2d", "wave": param.typewave}

            sizes = {"y": param.ny, "x": param.nx}

            variables = [{
                "short": "time",
                "long": "time",
                "units": "s",
                "dims": ("time")
            }, {
                "short": "p",
                "long": "pressure anomaly",
                "units": "m^2 s^-2",
                "dims": ("time", "y", "x")
            }, {
                "short": "u",
                "long": "velocity x-component",
                "units": "m s^-1",
                "dims": ("time", "y", "x")
            }, {
                "short": "v",
                "long": "velocity y-component (or z-)",
                "units": "m s^-1",
                "dims": ("time", "y", "x")
            }, {
                "short": "up",
                "long": "up flux x-component",
                "units": "m^3 s^-3",
                "dims": ("time", "y", "x")
            }, {
                "short": "vp",
                "long": "vp flux y-component",
                "units": "m^3 s^-3",
                "dims": ("time", "y", "x")
            }]

            fid = nct.NcTools(variables,
                              sizes,
                              attrs,
                              ncfilename=param.filename)
            fid.createhisfile()
            ktio = 0

        for kt in range(nt):
            energy[kt] = 0.5 * np.mean(np.abs(hphi.ravel())**2)
            hphi = hphi * propagator

            if param.generation == 'wake':

                if hasattr(self, "traj"):

                    xb, yb = self.traj.get_position(time)
                    vx, vy = self.traj.get_velocity(time)

                    kalpha = vx * kxx + vy * kyy
                    # recompute self.boat (complex Fourier amplitude)
                    # to account for the new heading
                    heading = np.angle(vx + 1j * vy)
                    self.set_wave_packet(param, heading)
                    # shift the source at the boat location (xb,yb)
                    shift = np.exp(-1j * (kxx * xb + kyy * yb))
                    # add the source term to hphi
                    hphi -= 1j * dt * self.boat * kalpha * shift
                else:
                    if kt == 0:
                        kalpha = np.cos(param.alphaU)*kxx + \
                            np.sin(param.alphaU)*ky
                    hphi += (1j*1e2*dt*self.boat*param.U*kalpha) * \
                        np.exp(-1j*(kxx*xb+kyy*yb))
                    xb += dt * param.U * np.cos(param.alphaU)
                    yb += dt * param.U * np.sin(param.alphaU)

            elif param.generation == 'oscillator':
                hphi += (1e2 * dt * self.boat) * np.exp(
                    -1j * time * param.omega0)

            kt += 1
            time += dt

            if anim:
                if (kt % kplot == 0):
                    var = self.fspace.compute_all_variables(hphi)
                    z2d = var[param.varplot]
                    self.var = var
                    if param.plotvector == 'velocity':
                        self.plot.update(kt, time, z2d, u=var['u'], v=var['v'])
                    elif param.plotvector == 'energyflux':
                        self.plot.update(kt,
                                         time,
                                         z2d,
                                         u=var['up'],
                                         v=var['vp'])
                    else:
                        self.plot.update(kt, time, z2d)

                    if param.netcdf:
                        with Dataset(param.filename, "r+") as nc:
                            nc.variables["time"][ktio] = time
                            nc.variables["p"][ktio, :, :] = z2d
                            for v in ["u", "v", "up", "vp"]:
                                nc.variables[v][ktio, :, :] = var[v]

                            ktio += 1
            else:
                print('\rkt=%i / %i' % (kt, nt), end='')

        var = self.fspace.compute_all_variables(hphi)
        self.energy = energy
        self.var = var
コード例 #27
0
def main():
    """
        Primay inputs are: initial position, x0, y0, and z0 with origin at the
        point of home plate, x to the rright of the catcher, y from the catcher
        towards the pitcher, and z straight up. Initial velocities
        u0, v0, and w0 which are the speeds of the ball in x, y, and z
        respectivley. And spin rates


       UMBA1.0: This code uses a constant Cd and rod cross's model for CL
       Predictions. Seam Orientation is not accounted for. Air Density is
       considered only at sea level at 60% relative humidity. but can be easily
       altered

       UMBA2.0 Adding seam positions and attempting to model CL from seams.
    """

    print("This baseball trajectory calculator models \
still air at sea level with about 60% humidity.\nThe ambient\
 conditions are fixed can be adjusted in the code \
if needed or made into variable at a later time.\n\
\nAll initial ball state variables have default values that approximate\
 a 90 mph ball with no spin.\nThe release point is only asked once\
and remains the same for subsequent pitches.\nAll other variables\
can be changed for comparison. To retain the current value, just press return")

    pX = []
    pY = []
    pZ = []
    IX = []
    IY = []
    IZ = []
    DX = []
    DY = []
    DZ = []
    FX = []
    FY = []
    FZ = []

    #x y and z here are typical of an approximately 6' tall rhp
    # these are the defualt initial values and can be changed here or as the code runs
    # as the code
    seamsOn = True
    frameRate = 0.002  #frame rate can change how quickly or slowly the code
    x = 0
    y = 5.5
    z = 6
    Vtot = 90
    Theta = 0
    Psi = 0
    SpinRate = 1200
    TiltH = 12
    Tiltm = 0
    SpinE = 100
    Yangle = 0 * np.pi / 180
    Zangle = 0 * np.pi / 180
    #will run if you are plotting the

    print('\n\n\ncurent release distance left to right is', x)
    Qx = (input(
        'distance left from center of rubber (right haded pitchers should have negative numbers) (ft): '
    ))
    if Qx == "":
        x = x
    else:
        x = float(x)

    print('\n\n\ncurent release distance from rubber', y)
    Qy = (input(
        'release distance from rubber (should be approximatly the stride lenght)(ft): '
    ))
    if Qy == "":
        y = y
    else:
        y = float(Qy)

    print('\n\n\ncurent release height is', z)
    Qz = (input('height of ball from field at release (ft): '))
    if Qz == "":
        z = z
    else:
        z = float(Qz)

    i = 0
    repeat = True
    while repeat == True:

        if i == 0:
            print(
                '\n\nIf you want to keep the current value simply hit return. Otherwise enter a new value.\n\n'
            )
        print("\n\nCurrent initial speed set to ", Vtot)
        QVtot = (input('what is the ball\'s release speed (mph): '))
        if QVtot == "":
            Vtot = Vtot
        else:
            Vtot = float(QVtot)

        print("\n\nCurrent vertical release angle set to ", Theta)
        QTheta = (input('what is the ball\'s vertical release angle (deg): '))
        if QTheta == "":
            Theta = Theta
        else:
            Theta = float(QTheta)

        print("\n\nCurrent horizontal release angle set to ", Psi)
        QPsi = (input('what is the ball\'s horizontal release angle(deg): '))
        if QPsi == "":
            Psi = Psi
        else:
            Psi = float(QPsi)

        print("\n\nCurrent initial Spin Rate set to ", SpinRate)
        QSpinRate = (input('what is the ball\'s initial spin rate (rpm): '))
        if QSpinRate == "":
            SpinRate = SpinRate
        else:
            SpinRate = float(QSpinRate)

        print("\n\nCurrent initial tilt hours set to ", TiltH)
        QTiltH = (input('what is the ball\'s initial hours tilt (hrs): '))
        if QTiltH == "":
            TiltH = TiltH
        else:
            TiltH = float(QTiltH)

        print("\n\nCurrent initial tilt minutes set to ", Tiltm)
        QTiltm = (input('what is the ball\'s initial minutes tilt (mins): '))
        if QTiltm == "":
            Tiltm = Tiltm
        else:
            Tiltm = float(QTiltm)
        Tiltr = processing.TimeToTilt(TiltH, Tiltm)

        print("\n\nCurrent initial spin efficiency set to ", SpinE)
        QSpinE = (input('what is the ball\'s initial spin efficiency (%): '))
        if QSpinE == "":
            SpinE = SpinE
        else:
            SpinE = float(QSpinE)
        if SpinE == 100:
            Gyro = np.arcsin(SpinE / 100)
#            Gyro = np.arccos(1 - (SpinE/100))
        else:
            TiltHnewUp = TiltH + 3
            if TiltHnewUp > 12:
                TiltHnewUp = int(TiltHnewUp - 12)
            else:
                TiltHnewUp = int(TiltHnewUp)
            TiltHnewDn = TiltH - 3
            if TiltHnewDn < 1:
                TiltHnewDn = int(TiltHnewDn + 12)
            else:
                TiltHnewDn = int(TiltHnewDn)

            print('if', TiltHnewUp, ':', int(Tiltm), 'is forward enter " r "')
            print('if', TiltHnewDn, ':', int(Tiltm), 'is forward enter " l "')

            leftRightGyro = ''
            while leftRightGyro != 'l' and leftRightGyro != 'r':
                leftRightGyro = input("l/r")
                if leftRightGyro == 'l':
                    Gyro = np.arcsin(SpinE / 100)


#                    Gyro = np.arccos(1 - (SpinE/100))
                elif leftRightGyro == 'r':
                    #                    Gyro = np.pi - np.arccos(1- (SpinE/100))
                    Gyro = np.pi - np.arcsin(SpinE / 100)

        if seamsOn == True:
            QSeamsOn = input('keep seams on?')
            if QSeamsOn == 'y' or QSeamsOn == 'yes' or QSeamsOn == 'Y' or QSeamsOn == 'YES' or QSeamsOn == 'Yes' or QSeamsOn == '':
                seamsOn == True

                print("\n\nCurrent Y orientation angle set to ",
                      Yangle * 180 / np.pi)
                QYangle = (input(
                    'what is the ball\'s initial Y orientation angle (degs): ')
                           )
                if QYangle == "":
                    Yangle = Yangle  #Zangle is still in radians
                else:
                    Yangle = float(QYangle)
                    Yangle = (np.pi / 180) * Yangle

                print("\n\nCurrent Z orientation angle set to ",
                      Zangle * 180 / np.pi)
                QZangle = (input(
                    'what is the ball\'s initial Z orientation angle (degs): ')
                           )
                if QZangle == "":
                    Zangle = Zangle  #Zangle is still in radians
                else:
                    Zangle = float(QZangle)
                    Zangle = (np.pi / 180) * Zangle  #converts to radians
                    # consult https://scout.texasleaguers.com/spin for further understanding

            elif QSeamsOn == 'n' or QSeamsOn == 'no' or QSeamsOn == 'N' or QSeamsOn == 'NO' or QSeamsOn == 'No':
                seamsOn = False
                Zangle = 0
                Yangle = 0
        else:
            QSeamsOn = input('keep seams off?')
            if QSeamsOn == 'y' or QSeamsOn == 'yes' or QSeamsOn == 'Y' or QSeamsOn == 'YES' or QSeamsOn == 'Yes' or QSeamsOn == '':
                seamsOn = False
                Zangle = 0
                Yangle = 0

            elif QSeamsOn == 'n' or QSeamsOn == 'no' or QSeamsOn == 'N' or QSeamsOn == 'NO' or QSeamsOn == 'No':

                seamsOn = True

                print("\n\nCurrent Y orientation angle set to ",
                      Yangle * 180 / np.pi)
                QYangle = (input(
                    'what is the ball\'s initial Y orientation angle (degs): ')
                           )
                if QYangle == "":
                    Yangle = Yangle  #Zangle is still in radians
                else:
                    Yangle = float(QYangle)
                    Yangle = (np.pi / 180) * Yangle

                print("\n\nCurrent Z orientation angle set to ",
                      Zangle * 180 / np.pi)
                QZangle = (input(
                    'what is the ball\'s initial Z orientation angle (degs): ')
                           )
                if QZangle == "":
                    Zangle = Zangle  #Zangle is still in radians
                else:
                    Zangle = float(QZangle)
                    Zangle = (np.pi / 180) * Zangle  #converts to radians
                    # consult https://scout.texasleaguers.com/spin for further understanding

        positions = (processing.PitchedBallTraj(x, y, z, Vtot, Theta, Psi,
                                                SpinRate, Tiltr, Gyro, Yangle,
                                                Zangle, i, frameRate, seamsOn))
        plotting.Plotting(positions)

        pX.append(positions[0])
        pY.append(positions[1])
        pZ.append(positions[2])
        IX.append(positions[3])
        IY.append(positions[4])
        IZ.append(positions[5])
        DX.append(positions[6])
        DY.append(positions[7])
        DZ.append(positions[8])
        FX.append(positions[9])
        FY.append(positions[10])
        FZ.append(positions[11])
        leave = False
        k = 0

        while leave == False:
            k = k + 1
            if k == 1:
                Again = input("Would you like to look at another pitch?\n")
            elif k > 6:
                Again = 'n'
            elif k > 5:
                Again = input(
                    "Last Chance.Would you like to look at another pitch (y/n)?\n"
                )
            else:
                Again = input(
                    "Would you like to look at another pitch (y/n)?\n")

            if Again == 'y' or Again == 'yes' or Again == 'Y' or Again == 'YES' or Again == 'Yes':
                repeat = True
                leave = True
            elif Again == 'n' or Again == 'no' or Again == 'N' or Again == 'NO' or Again == 'No':
                repeat = False
                leave = True
            else:
                leave = False

        i = i + 1

    plotting.plotSFinal(pX, pY, pZ, IX, IY, IZ, DX, DY, DZ, FX, FY, FZ, i)
コード例 #28
0
        :return: heuristic function value """

        heuristic_type = self.heuristic_type
        goal = self.s_goal

        if heuristic_type == 'manhattan':
            return abs(goal[0] - s[0]) + abs(goal[1] - s[1])
        else:
            return math.hypot(goal[0] - s[0], goal[1] - s[1])


if __name__ == '__main__':

    objects = {
        'Jetbot': [(953, 461), 834, 1073, 636, 287],
        'Obstacle': [(1100, 300), 1000, 1200, 800, 0],
        'Target': [(1342, 170), 1308, 1377, 249, 92],
        'Grabber': [(1054, 626), 1003, 1106, 728, 525]
    }
    obstacle_ls = objects['Obstacle']
    s_start = objects['Jetbot'][0]
    s_goal = objects['Target'][0]
    if type(obstacle_ls[0]) == type(()):  # if there is only one obstacle:
        obstacle_ls = [obstacle_ls]

    astar = Astar(s_start, s_goal, obstacle_ls)
    path, visited = astar.searching()

    plot = plotting.Plotting(s_start, s_goal, obstacle_ls)
    plot.animation(path, visited, 'AStar')