Exemple #1
0
    def preCalc(self, config):
        list_alpha, num_alpha = linspace(config["alpha"])
        list_lmbda0, num_lmbda0 = linspace(config["lambda_0"])
        list_flux, num_flux = linspace(config["flux"])

        a = config["a"]
        mu0 = config["mu0"]

        B_phi = np.empty((num_alpha, num_lmbda0))
        B_theta = np.empty((num_alpha, num_lmbda0))
        P_ohm = np.empty((num_alpha, num_lmbda0))
        U_mag = np.empty((num_alpha, num_lmbda0))
        Ip = np.empty((num_alpha, num_lmbda0, num_flux))
        F = np.empty((num_alpha, num_lmbda0, num_flux))

        for (i, alpha) in enumerate(list_alpha):
            for (j, lmbda0) in enumerate(list_lmbda0):
                r, B = self.calcB(lmbda0, alpha, config)
                flux = si.simps(r * B[:, 0], r)
                B_phi[i, j] = B[-1, 0] / flux
                B_theta[i, j] = B[-1, 1] / flux
                P_ohm[i, j] = Pohm(r, B, lmbda(r, alpha, lmbda0)) / flux**2
                U_mag[i, j] = Umag(r, B) / flux**2
                for (k, phi) in enumerate(list_flux):
                    Ip[i, j, k] = B[-1, 1] * phi / (a * mu0 * flux)
                    F[i, j, k] = B[-1, 0] / (2 * flux)

        return list_alpha, list_lmbda0, list_flux, B_phi, B_theta, P_ohm, U_mag, Ip, F
Exemple #2
0
    def render(self):
        self.clear()
        tiles = self.proxy.get_tiles()
        pyglet.gl.glLineWidth(2.0)
        for tile in tiles:
            keys = ['x', 'y', 'width', 'height', 'nutrition', "n_agents"]
            x, y, width, height, nutrition, n_agents = (tile.get(key)
                                                        for key in keys)
            pyglet.gl.glColor4f(1.0, 1.0, 1.0, 1.0)
            pyglet.graphics.draw(
                4, pyglet.gl.GL_LINE_LOOP,
                ("v2f",
                 (x, y, x, y + height, x + width, y + height, x + width, y)))
            pyglet.gl.glColor4f(0.0, 0.0, n_agents / 3.0, 1.0)
            pyglet.graphics.draw(
                4, pyglet.gl.GL_QUADS,
                ("v2f",
                 (x, y, x, y + height, x + width, y + height, x + width, y)))

        agents = self.proxy.get_agents()
        for agent in agents:
            x = agent['x']
            y = agent['y']
            direction = agent['direction']
            sight = agent['sight']
            vision = agent['vision']
            n_cell = agent['n_cell']
            aov = agent['aov']
            for idx, sight_dir in enumerate(
                    utils.linspace(-aov / 2, aov / 2, n_cell)):
                sight_dir = direction + sight_dir
                ratio = vision[idx]
                if ratio != 1.0:
                    color = (1, 0, 0, 1)
                else:
                    color = (0, 1, 0, 1)
                pyglet.gl.glColor4f(*color)
                pyglet.graphics.draw(
                    2, pyglet.gl.GL_LINES,
                    ("v2f", (x, y, x + sight * ratio * math.cos(sight_dir),
                             y + sight * ratio * math.sin(sight_dir))))

        for agent in agents:
            x = agent['x']
            y = agent['y']
            reward = agent['reward']
            size = agent['size']
            circle = pyglet.sprite.Sprite(
                img=self.circle_img,
                x=x,
                y=y,
            )
            if reward:
                circle.color = (255, 0, 0)
            else:
                circle.color = (255, 255, 255)
            circle.scale = size / self.circle_img.width * 1.3
            circle.draw()

        self.flip()
Exemple #3
0
    def robot_curve(self, curve_type: CurveType, side: RobotSide):
        """
        Calculates the given curve for the given side of the robot.
        :param curve_type: The type of the curve to calculate
        :param side: The side to use in the calculation
        :return: The points of the calculated curve
        """
        coeff = (self.robot.robot_info[3] /
                 2) * (1 if side == RobotSide.LEFT else -1)
        cp = self.control_points()

        t = linspace(0, 1, samples=Trajectory.SAMPLE_SIZE + 1)
        curves = [
            Curve(control_points=points,
                  spline_type=SplineType.QUINTIC_HERMITE) for points in cp
        ]

        dx, dy = npconcat([c.calculate(t, CurveType.VELOCITY)
                           for c in curves]).T
        theta = nprads(angle_from_slope(dx, dy))

        points = npconcat([c.calculate(t, curve_type) for c in curves])
        normals = coeff * nparray([-npsin(theta), npcos(theta)]).T

        return points + normals
Exemple #4
0
 def compute_breaks(self, n=50):
     """Return output like that of numpy.histogram."""
     last = 0.0
     counts = []
     bounds = linspace(*self.bounds(), num=n)
     for e in bounds[1:]:
         new = self.sum(e)
         counts.append(new-last)
         last = new
     return counts, bounds
Exemple #5
0
 def compute_breaks(self, n=50):
     """Return output like that of numpy.histogram."""
     last = 0.0
     counts = []
     bounds = linspace(*self.bounds(), num=n)
     for e in bounds[1:]:
         new = self.sum(e)
         counts.append(new - last)
         last = new
     return counts, bounds
def input_versus_output(start_dBV, end_dBV, step_dBV,
                        frequency_hz=1000,
                        generator=pyQA400.GEN1,
                        input_channel=pyQA400.LEFTIN):

    # Create a list of levels to sweep across
    test_levels = utils.linspace(start_dBV, end_dBV, step=step_dBV)

    results = []
    for level in test_levels:
        power_dbv = get_peak_power(generator, input_channel, level, frequency_hz)
        print(level, power_dbv)
        results.append( (level, power_dbv) )
    return results
Exemple #7
0
    def curve(self, curve_type: CurveType, concat: bool = True):
        """
        Calculates the curve corresponding to the given type for the _middle_ of the robot.
        :param curve_type: The curve type wanted to calculate
        :param concat: Should concat the segments or not. Default - false
        :return: A list of numpy point vectors if concat is false. Else - one huge numpy vector
        """
        cp = self.control_points()

        t = linspace(0, 1, samples=Trajectory.SAMPLE_SIZE + 1)
        curves = [
            Curve(control_points=points,
                  spline_type=SplineType.QUINTIC_HERMITE).calculate(
                      t, curve_type) for points in cp
        ]

        return npconcat(curves) if concat else curves
Exemple #8
0
    def headings(self):
        """
        Calculates the robot's heading angles for each point in the curve (theta(t)) and calculates the angular velocity
        in each point on the curve (theta'(t)).
        :return: A tuple consisting of the values of theta(t) and theta'(t) through the curve.
        """
        cp = self.control_points()

        t = linspace(0, 1, samples=Trajectory.SAMPLE_SIZE + 1)
        curves = [
            Curve(control_points=points,
                  spline_type=SplineType.QUINTIC_HERMITE) for points in cp
        ]

        dx, dy = npconcat([c.calculate(t, CurveType.VELOCITY)
                           for c in curves]).T
        d2x, d2y = npconcat(
            [c.calculate(t, CurveType.ACCELERATION) for c in curves]).T

        return angle_from_slope(dx,
                                dy), ((d2y * dx - d2x * dy) / (dx**2 + dy**2))
Exemple #9
0
    def calcB(self, lmbda0, alpha, config):
        # Parameters
        r, num = linspace(config["rho"])
        beta_theta = config["beta_theta"]
        c1, c2 = config["pressure"]["c1"], config["pressure"]["c2"]
        P = (1 - r**c1)**c2
        P_avg = 2 * si.simps(r * P, r)

        # Magnetic field
        B = np.zeros((num, 2))

        # Iterate to derive poloidal beta and magnetic fields
        max_iter = 10
        for i in xrange(max_iter):
            beta0 = beta_theta * B[-1, 1]**2 / P_avg
            B[0, 0] = 1.0
            B[0, 1] = 0.0

            # Solve ODE
            solver = si.ode(gradB)
            solver.set_integrator("dopri5")
            solver.set_initial_value(B[0, :], r[0])
            solver.set_f_params(lmbda0, alpha, beta0, c1, c2)
            for i in xrange(1, num):
                if not solver.successful():
                    print(
                        "Warning: Integration failed at ρ={0} (iteration: {1})"
                        .format(r[i], i))
                    break
                solver.integrate(r[i])
                B[i, :] = solver.y

            # Stop at 0.01% accuracy for poloidal beta
            if abs(1 - beta0 * P_avg /
                   (beta_theta * max(B[-1, 1]**2, 1e-8))) <= 1e-4:
                break

        # Return final profile
        return r, B
Exemple #10
0
    def update_vision(self):
        agents = set()
        for tile in self.tile.neighbors(self.sight):
            agents.update(tile.agents)
        agents.remove(self)

        vision = []
        for sight_dir in utils.linspace(-self.aov / 2, self.aov / 2,
                                        self.n_cell):
            sight_dir = self.direction + sight_dir
            min_sight = 1.0
            for agent in agents:
                sight = utils.intersect(self.x, self.y, self.sight, sight_dir,
                                        agent.x, agent.y, agent.size / 2)
                min_sight = min(sight, min_sight)
            vision.append(min_sight)
        self.vision = vision

        self.reward = 0
        for agent in agents:
            if self.is_collide_with(agent):
                self.reward -= 1
Exemple #11
0
    def plot_act(self,
                 data=None,
                 ax=None,
                 data_type='u',
                 save=True,
                 save_path='./',
                 save_name='act_map.png',
                 cmap='jet',
                 plot_N_num=200,
                 select_strategy='first',
                 verbose=False):
        if isinstance(data, torch.Tensor):
            data = data.detach().cpu().numpy()  # [step_num, N_num]

        step_num = data.shape[0]
        N_num = data.shape[1]
        #data = np.transpose(data, (1, 0)) # [N_num, step_num]

        if N_num > plot_N_num:
            is_select = True
            if select_strategy in ['first']:
                plot_index = range(plot_N_num)
            elif select_strategy in ['random']:
                plot_index = random.sample(range(N_num), plot_N_num)
            else:
                raise Exception('Invalid select strategy: %s' %
                                select_strategy)
            data = data[:, plot_index]
        else:
            is_select = False
            plot_N_num = N_num

        if ax is None:
            #fig, ax = plt.subplots(figsize = (step_num / 20 * 5, plot_N_num / 20 * 5)) # figsize: (width, height), in inches
            fig, ax = plt.subplots(nrows=1,
                                   ncols=1,
                                   figsize=(plot_N_num / 20 * 2,
                                            step_num / 20 * 2))
        data_min, data_max, data_mean, data_std = get_items_from_dict(
            get_np_stat(data, verbose=verbose), ['min', 'max', 'mean', 'std'])
        #print(np.argmax(data))
        #print(unravel_index(data.argmax(), data.shape))

        if data_min < data_mean - 3 * data_std:
            data_down = data_mean - 3 * data_std
        else:
            data_down = data_min
        if data_max > data_mean + 3 * data_std:
            data_up = data_mean + 3 * data_std
        else:
            data_up = data_max

        if verbose:
            print('data_down:%.3e data_up:%.3e' % (data_down, data_up))

        norm = mpl.colors.Normalize(vmin=data_down, vmax=data_up)

        data_norm = (data - data_min) / (data_max - data_min)

        cmap_func = plt.cm.get_cmap(cmap)
        data_mapped = cmap_func(data_norm)

        im = ax.imshow(data_mapped)
        ax.set_yticks(utils.linspace(0, step_num - 1, 10))
        ax.set_xticks(utils.linspace(0, plot_N_num - 1, 200))
        ax.set_ylabel('Time Step')
        if is_select:
            if select_strategy in ['first']:
                x_label = 'Neuron index'
            elif select_strategy in ['random']:
                x_label = '%d randomly selected neurons'
            else:
                raise Exception('Invalid select strategy: %s' %
                                select_strategy)
        else:
            x_label = 'Neuron index'

        ax.set_xlabel(x_label)

        # plot colorbar
        cbar_ticks = utils.linspace(data_down, data_up, step='auto')
        cbar_ticks_str = list(map(lambda x: '%.2e' % x, cbar_ticks.tolist()))
        cbar = ax.figure.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap),
                                  ticks=cbar_ticks,
                                  ax=ax)
        cbar.ax.set_yticklabels(
            cbar_ticks_str
        )  # vertical colorbar. use set_xticklabels for horizontal colorbar

        if data_type in ['u']:
            ax.set_title('Firing rate across time')
            cbar.set_label('Firing rate')
        else:
            ax.set_title('Membrane potential rate across time')
            cbar.set_label('Membrane potential')

        if save:
            ensure_path(save_path)
            plt.savefig(save_path + save_name)
        return ax