Exemple #1
0
 def plot_device_log_curves(event=None):
     # 作光态对数曲线
     if device_list:
         Plot.plot_log_curves('Light Log Curves', 'all', pls.log_x_label,
                              pls.log_y_label, pls.log_x_min, pls.log_x_max,
                              pls.log_y_min, pls.log_y_max, device_list,
                              legend_list)
Exemple #2
0
    def plotAbsolute(self):
        self.logMessage("Plotting the absolute alignment profile...")
        self.app.processEvents()

        # checando se todos os arquivos foram devidamente carregados
        if (not self.isNominalsLoaded or not self.isMeasuredLoaded
                or not self.isLookuptableLoaded):
            self.logMessage("error: not all required files were loaded")
            return

        # calculando desvios de todos dof de cada berço com o best-fit de seus pontos
        diffAllDoFs = GirderGroup.evalDiff_bestFit(
            self.girderNominal.pointGroup.ptList,
            self.girderMeasured.pointGroup.ptList)

        # definindo as propriedades do plot
        plot_args = {
            'y_list': ['Tx', 'Ty', 'Tz', 'Rx', 'Ry', 'Rz'],
            'title_list': [
                'Transversal', 'Longitudinal', 'Vertical', 'Pitch', 'Roll',
                'Yaw'
            ],
            'fig_title':
            'Global Alignment Profile - Storage Ring'
        }

        # chamando o plot
        Plot.plotGirderDeviation(diffAllDoFs,
                                 'allDoFs',
                                 plot_args,
                                 freezePlot=True)
Exemple #3
0
    def __init__(self):
        super().__init__()
        pygame.init()
        pygame.display.set_caption("ControlGUI(UWU")
        self.screen_width = 400
        self.screen_height = 300
        self.screen = pygame.display.set_mode(
            (self.screen_width, self.screen_height))
        self.clock = pygame.time.Clock()
        self.plot = Plot(self.screen, 400, 300)
        self.movement = [0 for i in range(6)]
        self.power = [0 for i in range(6)]
        self.profile = -1

        self.widgets = []
        self.widgets.append((ProfilePopup(self.screen_width,
                                          self.screen_height), (0, 0)))
        self.widgets.append((EMPopup(self.screen_width, self.screen_height,
                                     1), (0, 0)))
        self.widgets.append((EMPopup(self.screen_width, self.screen_height,
                                     2), (0, 0)))
        self.widgets.append((InvertPopup(self.screen_width,
                                         self.screen_height), (0, 0)))

        self.charts = []
        self.charts.append(
            (Plot(['strafe', 'drive', 'yaw', 'ud', 'tilt', 'zero'],
                  self.screen_width, self.screen_height), (0, 0), 0))
        self.charts.append(
            (Plot(['FL', 'FR', 'BL', 'BR', 'TL', 'TR'], self.screen_width,
                  self.screen_height), (self.screen_width / 2, 0), 1))
    def test_constructor(self):
        #
        # Define mesh, element, and dofhandler
        #
        mesh = QuadMesh(box=[0, 20, 0, 20],
                        resolution=(20, 20),
                        periodic={0, 1})
        dim = mesh.dim()
        element = QuadFE(dim, 'Q2')
        dofhandler = DofHandler(mesh, element)
        dofhandler.distribute_dofs()
        basis = Basis(dofhandler, 'u')

        alph = 2
        kppa = 1

        # Symmetric tensor gma T + bta* vv^T
        gma = 0.1
        bta = 25

        p = lambda x: 10/np.pi*(0.75*np.sin(np.pi*x[:,0]/10)+\
                                0.25*np.sin(np.pi*x[:,1]/10))
        f = Nodal(f=p, basis=basis)
        fx = f.differentiate((1, 0))
        fy = f.differentiate((1, 1))

        #plot.contour(f)

        x = np.linspace(0, 20, 12)
        X, Y = np.meshgrid(x, x)
        xy = np.array([X.ravel(), Y.ravel()]).T
        U = fx.eval(xy).reshape(X.shape)
        V = fy.eval(xy).reshape(X.shape)

        v1 = lambda x: -0.25 * np.cos(np.pi * x[:, 1] / 10)
        v2 = lambda x: 0.75 * np.cos(np.pi * x[:, 0] / 10)

        U = v1(xy).reshape(X.shape)
        V = v2(xy).reshape(X.shape)

        #plt.quiver(X,Y, U, V)
        #plt.show()

        h11 = Explicit(lambda x: gma + bta * v1(x) * v1(x), dim=2)
        h12 = Explicit(lambda x: bta * v1(x) * v2(x), dim=2)
        h22 = Explicit(lambda x: gma + bta * v2(x) * v2(x), dim=2)

        tau = (h11, h12, h22)

        #tau = (Constant(2), Constant(1), Constant(1))
        #
        # Define default elliptic field
        #
        u = EllipticField(dofhandler, kappa=1, tau=tau, gamma=2)
        Q = u.precision()
        v = Nodal(data=u.sample(mode='precision', decomposition='chol'),
                  basis=basis)

        plot = Plot(20)
        plot.contour(v)
Exemple #5
0
 def plot_dark_log_curves(event=None):
     # 作暗态对数曲线
     if device_list:
         Plot.plot_log_curves('Dark Log Curves', 'dark', pls.log_x_label,
                              pls.log_y_label, pls.log_x_min, pls.log_x_max,
                              pls.log_y_min, pls.log_y_max, device_list,
                              legend_list)
Exemple #6
0
 def plot_dark_line_curves(event=None):
     # 作暗态线性曲线
     if device_list:
         Plot.plot_line_curves('Dark Line Curves', 'dark', pls.line_x_label,
                               pls.line_y_label, pls.line_x_min,
                               pls.line_x_max, pls.line_y_min,
                               pls.line_y_max, device_list, legend_list)
Exemple #7
0
    def plot_before (before, output_dir):
        from chemotext_util import LoggingUtil
        logger = LoggingUtil.init_logging (__file__)

        if before.count () <= 0:
            return
        '''
        before = before.reduceByKey (lambda x, y : x + y). \
                 mapValues (lambda x : filter (lambda v : v is not None, x))
        '''
        true_plots_dir = os.path.join (output_dir, "chart")
        print ("-------------> before 0")
        true_mentions = before. \
                        mapValues (lambda x : Plot.plot_true_mentions (x, true_plots_dir)). \
                        filter (lambda x : len(x[1]) > 0)
        logger.info ("Plotted {0} sets of true mentions.".format (true_mentions.count ()))
        print ("-------------> before 1")

        false_plots_dir = os.path.join (output_dir, "chart", "false")
        false_mentions = before.subtractByKey (true_mentions)
        false_frequency = false_mentions. \
                          mapValues   (lambda x : Plot.false_mention_histogram (x, false_plots_dir))

        false_mentions = false_mentions. \
                         mapValues   (lambda x : Plot.plot_false_mentions (x, false_plots_dir))

        logger.info ("false mentions: {0}".format (false_mentions.count ()))
        true_mentions = None
        false_mentions = None
        false_frequency = None
Exemple #8
0
 def set_source(self,source,nodes=None):
     """
     Handles opening a new file. Creates a plot with the given source
     file. Uses input plugins to convert file to SVG. This disregards
     all previous settings, thus ui_updates should be called.
     """
     height = self.material.length and self.material.length*UNITS[self.units] or None
     p = Plot(width=self.material.width*UNITS[self.units],height=height,color=self.material.color)
     m = self.material.margin
     p.set_padding(top=m[0],right=m[1],bottom=m[2],left=m[3])
     if type(source) == etree._ElementTree:
         try:
             # If certain nodes are selected, only plot them.
             if nodes:
                 xml = etree.tostring(get_selected_nodes(source,nodes))
             else:
                 xml = etree.tostring(source)
             # Set a job name if none exists
             if self.name is None:
                 self.name = "*inkscape.svg"
             # Try to make a plot
             p.set_graphic(xml)
             self.plot = p
         except (IOError,etree.XMLSyntaxError),trace:
             log.debug(trace)
             raise Exception("Failed to create plot. Reason: Failed to import the Inkscape file.")
Exemple #9
0
def spm_geometry_and_inside_outside_test():
    # # Write your own path here
    # path = r'C:\Users\User\Documents\python\aero\airfoils_data'
    # # Airfoil name
    # name = 'ua79sff.txt'
    # test_fig = figure.Airfoil(name, path)

    test_fig = figure.Circle(10, num_points=20)
    # test_fig = figure.Ellipse(10, 5, num_points=50)
    # test_fig = figure.Square(10, num_points=50)
    # test_fig = figure.Rectangle(10, 5, num_points=50)
    # test_fig = figure.Triangle((0, 0), (6, 0), (3, 3))
    # test_fig = figure.Triangle((0, 0), (0, 6), (3, 3))
    # test_fig = figure.Triangle((0, 0), (6, 3), (3, 4))
    # test_fig = figure.Polygon('Polygon',
    #                           [(1, 1), (2, 2), (3, 3),
    #                            (2, 3), (2, 4), (1, 4), (0, 3)])
    # test_fig = figure.Ogive(2, 1, 5)
    geometry = Geometry(test_fig, 1)
    x0, y0, dx, dy = test_fig.rect
    grid = figure.Grid(x0, y0,
                       1.5 * dx, 1.5 * dy, 20)
    plt = Plot(grid)
    plt.plot_figure(test_fig)
    plt.plot_source_panel_method(geometry)

    for x in grid.x:
        for y in grid.y:
            res = test_fig.is_inside(x, y)
            if not res:
                plt.plot_point(x, y, '.y')

    plt.show()
Exemple #10
0
 def evaluate(self):
     score = self.model.evaluate(self.testset[0],
                                 self.testset[1],
                                 verbose=0)
     print('Test Accuracy: ', score[1])
     figure = Plot(self.loss_hist)
     figure.show_loss()
Exemple #11
0
def main(p: Plot):
    p.plot_size = 4
    p.setup()
    p.draw_bounding_box()
    num_bins = round(100/p.inches_to_units(0.02))
    audio = af.read('soundwave/caves.m4a')[0]
    # take abs to get magnitude
    audio = np.abs(audio)
    # sum to mono
    audio = np.sum(audio, axis=0)
    # pad end to nearest multiple of bin width
    pad_len = math.ceil(audio.shape[0]/num_bins)*num_bins - audio.shape[0]
    audio = np.pad(audio, (0, pad_len))
    # reshape into 2d array of bins
    audio = np.reshape(audio, (num_bins, -1))
    # sum bins to 1d array of values
    audio = np.sum(audio, axis=1)
    # normalize
    audio = audio/np.max(audio)

    max_width = 30
    for i, sample in enumerate(audio):
        x = 100*i/len(audio)
        p.goto(x, 50 + max_width*sample)
        p.lineto(x, 50 - max_width*sample)
 def plot(cls):
     Plot.draw_border()
     cls.draw_ui()
     if cls.view == "Info":
         cls.draw_info()
     else:
         cls.draw_terrain()
    def sample_counts_by_gene(self,
                              result,
                              tcga_cancer_code,
                              genie_cancer_code,
                              cancer_type_label,
                              rollup=False):
        outpath = self.find_outpath(rollup)
        indecies_to_drop = [
        ]  # captures the row index where mutation gene is not in panel
        result.sort_values('tcga_gene_sample_count',
                           inplace=True,
                           ascending=False)
        for i, row in result.iterrows():
            tcga_count = row['tcga_gene_sample_count']
            genie_count = row['genie_gene_sample_count']

            if tcga_count <= 5 and genie_count <= 5:
                indecies_to_drop.append(i)  # Add to drop list
                continue

            if i >= 40:
                indecies_to_drop.append(i)  # Add to drop list
                continue

        result.drop(indecies_to_drop, inplace=True)
        # Generate plot...
        print(
            f"Plotting sample counts by gene results for TCGA cancer code: {tcga_cancer_code}"
        )
        Plot.reset()
        Plot.sample_counts_by_gene(outpath,
                                   str(os.getenv('SYNAPSE_RELEASE_VERSION')),
                                   result, genie_cancer_code,
                                   cancer_type_label)
Exemple #14
0
    def set_up_plot(self, settings=None):
        self.plot = Plot()
        if settings is not None:
            for key in settings:
                self.plot.settings[key] = settings[key]
        self.settings['plot'] = self.plot.settings
        n_rows = self.plot.settings['n_rows']
        n_cols = self.plot.settings['n_cols']
        if n_rows is not None and n_cols is not None:
            print '\nSetting up {0:d}x{1:d} plot.'.format(n_rows, n_cols)
        else:
            e_str = 'Number of {0:s} must be an integer > 0.'
            n_rows, n_cols = (0, 0)
            while n_rows < 1 or n_cols < 1:
                n_rows = utils.get_input_integer( \
                    '\nNumber of subplot rows?\n> ',
                    error_text=e_str.format('rows'))[0]
                n_cols = utils.get_input_integer( \
                    'Number of subplot columns?\n> ',
                    error_text=e_str.format('columns'))[0]
                if n_rows < 1 or n_cols < 1:
                    print 'Must have > 0 rows and columns.'

        self.plot.set_up_plot_grid(n_rows, n_cols)
        #self.plot.plot_grid.tight_layout(self.plot.figure)
        self.plot.figure.set_tight_layout(True)
        plt.show(block=False)
        print '(If you cannot see the plot, try changing the '
        print 'matplotlib backend. Current backend is ' + \
            plt.get_backend() + '.)'
Exemple #15
0
def main():
    data = CollectData('192.168.1.69', 'AC:75:1D:57:8A:D8')
    regression = Regression()
    value = input('Would you like to collect data? [y/n] ')
    n = 0
    while (value == 'y' and n < 6):
        # collect data foreach distance
        val = data.collect()

        # call AddRSSI of regression
        regression.addRSSI(val)

        print(regression._RSSIAritmetica)
        print(regression._RSSIQuadratica)
        value = input('Would you like to collect data?[y/n] ').strip(
            '\r').strip('\n')
        n += 1

    # call regression
    result = regression.linearRegression()
    print(result)

    # plot line above point with data gave from regression
    p1 = Plot('DEVICE', '-log10(distance)', 'RSSI')
    p1.pointsAndLine(regression.getLog10Distance(),
                     regression.getRSSIAritmetica(), -1, 1, 100,
                     result['arithmeticK'], result['arithmeticA'])
Exemple #16
0
def test02():
    """
    Spatially varying anisotropy
    """
    print('Test 2:')
    grid = Grid(box=[0, 20, 0, 20], resolution=(100, 100))
    mesh = Mesh(grid=grid)
    element = QuadFE(2, 'Q1')
    system = System(mesh, element)

    alph = 2
    kppa = 1

    # Symmetric tensor gma T + bta* vv^T
    gma = 0.1
    bta = 25
    v2 = lambda x, y: -0.75 * np.cos(np.pi * x / 10)
    v1 = lambda x, y: 0.25 * np.sin(np.pi * y / 10)

    h11 = lambda x, y: gma + v1(x, y) * v1(x, y)
    h12 = lambda x, y: v1(x, y) * v2(x, y)
    h22 = lambda x, y: v2(x, y) * v2(x, y)

    X = Gmrf.from_matern_pde(alph, kppa, mesh, element, tau=(h11, h12, h22))
    x = X.sample(1).ravel()

    fig, ax = plt.subplots()
    plot = Plot()
    ax = plot.contour(ax, fig, x, mesh, element, resolution=(200, 200))
    plt.show()
    def __init__(self, main):
        super(Plugin, self).__init__("Stack Of Tasks plugin", main)
        self.setObjectName("Stack Of Tasks plugin")
        self.main = main
        self.graph = Graph(self)
        self.plot = Plot(self)

        self.tabWidget = QtGui.QTabWidget(self)
        self.setWidget(self.tabWidget)
        self.tabWidget.addTab(self.graph.view, "SoT graph")
        self.tabWidget.addTab(self.plot, "Plot")

        toolBar = QtGui.QToolBar("SoT buttons")
        toolBar.addAction(QtGui.QIcon.fromTheme("view-refresh"),
                          "Create entire graph", self.graph.createAllGraph)
        toolBar.addSeparator()
        toolBar.addAction(QtGui.QIcon.fromTheme("zoom-fit-best"),
                          "Zoom fit best", self.plot.zoomFitBest)
        toolBar.addAction(QtGui.QIcon.fromTheme("media-playback-stop"),
                          "Stop fetching data", self.stopAnimation)
        toolBar.addSeparator()
        toolBar.addAction(QtGui.QIcon.fromTheme("window-new"), "Create viewer",
                          self.createRobotView)
        toolBar.addSeparator()
        toolBar.addAction(QtGui.QIcon.fromTheme("view-filter"),
                          "Set entity filter by name", self.entityFilterByName)
        main.addToolBar(toolBar)

        self.displaySignals = []
        self.hookRegistered = False
        self.displaySignalValuesStarted = False
Exemple #18
0
def main(p: Plot, img_filename):
    p.plot_size = 6
    p.setup()

    img = Image.open(img_filename)
    max_res = 250
    max_size = max(img.width, img.height)
    img = img.resize((round(max_res * img.width / max_size),
                      round(max_res * img.height / max_size)))

    pixels = [luminance(*c) for c in img.getdata()]

    def getpix(r, c):
        return pixels[r * img.width + c]

    def setpix(r, c, col):
        pixels[r * img.width + c] = col

    def find_closest_palette_color(col):
        return 255 if col > 127 else 0

    for r in range(1, img.height - 1):
        print('row {}/{}'.format(r, img.height - 2))
        for c in range(1, img.width - 1):
            oldpixel = getpix(r, c)
            newpixel = find_closest_palette_color(oldpixel)
            if newpixel == 0:
                x = (c / max_res) * 100 + random.uniform(-0.1, 0.1)
                y = (r / max_res) * 100 + random.uniform(-0.1, 0.1)
                p.dot(x, y)
            quant_error = oldpixel - newpixel
            setpix(r, c + 1, getpix(r, c + 1) + quant_error * 7 / 16)
            setpix(r + 1, c - 1, getpix(r + 1, c - 1) + quant_error * 3 / 16)
            setpix(r + 1, c, getpix(r + 1, c) + quant_error * 5 / 16)
            setpix(r + 1, c + 1, getpix(r + 1, c + 1) + quant_error * 1 / 16)
Exemple #19
0
    def __init__(self, port, baudrate, tag, buffer_len):

        self.plot = Plot()

        self.reader = Reader(port, baudrate, len(tag)+buffer_len)
        self.reader.register_tag_listener(tag, buffer_len, self.process_flydata)
        self.reader.start()
Exemple #20
0
def test03():
    """
    Constant Anisotropy
    """
    print('Test 3:')
    # Mesh
    mesh = Mesh.newmesh([0, 20, 0, 20], grid_size=(40, 40))
    mesh.refine()
    element = QuadFE(2, 'Q1')
    system = System(mesh, element)

    gma = 1
    bta = 8
    tht = np.pi / 4
    v = np.array([np.cos(tht), np.sin(tht)])
    H = gma * np.eye(2, 2) + bta * np.outer(v, v)
    Z = 10 * np.random.normal(size=system.n_dofs())

    # Bilinear forms
    bf = [(1,'u','v'), \
          (H[0,0],'ux','vx'), (H[0,1],'uy','vx'),\
          (H[1,0],'ux','vy'), (H[1,1],'uy','vy')]

    A = system.assemble(bilinear_forms=bf, linear_forms=None)
    M = system.assemble(bilinear_forms=[(1, 'u', 'v')])
    m_lumped = np.array(M.sum(axis=1)).squeeze()
    X = spla.spsolve(A.tocsc(), np.sqrt(m_lumped) * Z)

    fig, ax = plt.subplots()
    plot = Plot()
    ax = plot.contour(ax, fig, X, mesh, element, resolution=(200, 200))
    plt.show()
    def train(self, epochs=500, batch=16):

        figure = Plot()
        fix_noise = np.random.normal(0, 5, (batch, 125, 1))
        for i in range(epochs):

            # train discriminator
            random_index = np.random.randint(0, len(self.Xtrain), size=batch)
            gt_data = self.Xtrain[random_index]

            gen_noise = np.random.normal(0, 5, (batch, 125, 1))
            fake_data = self.G.predict(gen_noise)

            x_combined_batch = np.concatenate((gt_data, fake_data))
            y_combined_batch = np.concatenate((np.ones(
                (batch, 1)), np.zeros((batch, 1))))

            d_loss = self.D.train_on_batch(x_combined_batch, y_combined_batch)

            # train generator
            noise = np.random.normal(0, 5, (batch, 125, 1))
            y_gen_label = np.ones((batch, 1))

            g_loss = self.G_and_D.train_on_batch(noise, y_gen_label)

            print(
                'epoch: %d, [Discriminator :: d_loss: %f], [ Generator :: loss: %f]'
                % (i, d_loss, g_loss))

            if i % 100 == 0:
                figure.show_dataset(self.G.predict(fix_noise))
    def plotSizes(self):
        """Generates a plot of the size of a data structure without actually performing the operations themselves.

        Since the operations in bm_length may alter the data structure size significantly, all operations that are
        benchmarked will be simulated, and the median data structure size will be used for each plot point."""

        # Convenience lambda.
        op = lambda x: self.operations[x][0]

        size = 0
        plot = Plot()

        # Do operations until bm_start.
        for i in range(self.bm_start):
            size += MixedSIDBenchmarkPlot._simOp(op(i))

        # Now plot points until we run out of road.
        current_benchmark = self.bm_start
        while current_benchmark < len(self.operations):
            # Very first thing: establish the next benchmark and the end of the current benchmark, since we'll need
            # both of these in various places.
            next_benchmark = min(len(self.operations),
                                 current_benchmark + self.bm_interval)
            end_of_benchmark = min(len(self.operations),
                                   current_benchmark + self.bm_length)

            # We're at a plot point, so gather all the data structure sizes and plot the median value.

            # We'll do the first by hand, then we can loop through easily.
            bm_sizes = [
                size + MixedSIDBenchmarkPlot._simOp(op(current_benchmark))
            ]

            # Now we'll loop through the rest.
            # Bounds explained:
            # start at current_benchmark + 1 because we just did current_benchmark.
            # End (exclusive of the end) at current_benchmark + bm_length (i.e. the last item being benchmarked),
            # unless that exceeds the operations list, in which case, terminate after the last operation.
            for index in range(current_benchmark + 1, end_of_benchmark):
                bm_sizes.append(bm_sizes[-1] +
                                MixedSIDBenchmarkPlot._simOp(op(index)))
                index += 1

            # Now we'll plot the median value
            plot.plotPoint(current_benchmark, statistics.median(bm_sizes))

            # Having finished the benchmark, we'll simulate operations up to the next benchmark, then loop.

            # First, a bit of clean-up.
            size = bm_sizes[-1]

            # Now, we'll simply loop, adjusting sizes.
            for index in range(end_of_benchmark, next_benchmark):
                size += MixedSIDBenchmarkPlot._simOp(op(index))

            # Finally, we're at the next benchmark, so update current_benchmark and loop.
            current_benchmark = next_benchmark

        return plot
    def draw_pointer(cls):
        """Draws cursor on screen."""

        #TODO: use different char for cursor when moving ship
        #TODO: rename to draw_cursor ?
        #TODO: read char from config file
        #TODO: have tile change background color when pointer on object
        Plot.draw(cls.posx,cls.posy,cls.panx,cls.pany, '░', 4)
Exemple #24
0
def main():
    '''The main Program runs the Data and Plot objects to read and plot the
    data from the radiosonde.'''

    dat = Data('dats')
    pl = Plot(dat)

    pl.plot()
Exemple #25
0
 def __init__(self):
     self.root = tk.Tk()
     self.model = Model()
     self.view = View(self.root, self.model, self)
     self.popup = Popup(self.model)
     self.plot = Plot(self.model)
     self.config = configparser.ConfigParser()
     self.config.read("config.ini")
Exemple #26
0
 def end(cls, exception=''):
     """Calls method to perform necessary steps for clean exit."""
     Plot.end()
     if exception:
         Log.add(str(exception))
     Log.add('Exiting program')
     Log.print()
     exit()
Exemple #27
0
 def plot(self, x, y):
     # assign two columns (x,y) for plot
     nofrow, noffeature = self.data.shape
     graph = Plot()
     if self.__type == 'supervise' and x < (noffeature - 1) and y < (noffeature - 1):
         graph.plotting(self.data[:, x], self.data[:, y], self.data[:, -1])
     else:
         print 'Invalid feature number'
Exemple #28
0
def main(p: Plot):
    p.setup()
    grid_size = 8
    for r in range(grid_size + 1):
        for c in range(grid_size + 1):
            x = c * 100 / grid_size
            y = r * 100 / grid_size
            draw_blob(p, vec2(x, y), 25 / grid_size)
Exemple #29
0
def fillPlot(draw_data, ax, mnist):
    feed = {data: mnist.test.images.reshape([-1, 28, 28])}
    test_elbo, test_codes, test_samples = sess.run(draw_data, feed)

    print('Epoch', epoch, 'elbo', test_elbo)
    ax[epoch, 0].set_ylabel('Epoch {}'.format(epoch))
    Plot.plot_codes(ax[epoch, 0], test_codes, mnist.test.labels)
    Plot.plot_samples(ax[epoch, 1:], test_samples)
Exemple #30
0
def main(p: Plot):
    p.setup()
    p.draw_bounding_box(True)
    num_waves = 7
    for i in range(num_waves + 1):
        yoffset = 100 * i / num_waves
        size = 50 / num_waves
        draw_wave(p, yoffset, 0, size)
Exemple #31
0
 def __standard_train(self, generator, discriminator, gan, config):
     epochs = config["train"]["epochs"]
     save_result_interval = config["train"]["save_result_interval"]
     for epoch in range(epochs):
         print("Epoch %d" % epoch)
         self.__train_epoch(generator, discriminator, gan)
         if epoch % save_result_interval == 0:
             Plot.plot_generated_images(epoch, generator, config)
Exemple #32
0
 def plot_device_line_curves(event=None):
     # 作器件线性曲线
     if device_list:
         Plot.plot_line_curves('Device Line Curves', 'all',
                               pls.line_x_label, pls.line_y_label,
                               pls.line_x_min, pls.line_x_max,
                               pls.line_y_min, pls.line_y_max, device_list,
                               legend_list)
Exemple #33
0
 def plot_light_line_curves(event=None):
     # 作光态线性曲线
     if device_list:
         Plot.plot_line_curves('Light Line Curves', 'light',
                               pls.line_x_label, pls.line_y_label,
                               pls.line_x_min, pls.line_x_max,
                               pls.line_y_min, pls.line_y_max, device_list,
                               legend_list)
Exemple #34
0
class TestPlotBasic(TestCase):
    def setUp(self):
        self.plot = Plot("star wars")

    def test_init(self):
        self.assertTrue(self.plot.name == "star wars")

        self.assertTrue(len(self.plot.entities_at_time(0)) == 0)
        self.assertTrue(len(self.plot.relations_at_time(0)) == 0)
    def __init__( self, serial = None, *args ) :
        """TemperaturePlot constructor it add axis titles."""

        Plot.__init__( self, *args )

        self.curve.setTitle( self._tr('LHe level data') )
        self.setAxisTitle( Qwt.QwtPlot.xBottom, self._tr('Time (min)') )
        self.setAxisTitle( Qwt.QwtPlot.yLeft, self._tr('LHe level (mm)') )

        self.serial = serial
def main():
  imgSrc=os.listdir(c.test)
  imagenes=[]
  tmp=[]
  for e in imgSrc:
    img=Imagen(e).imagen
    rects=f.detectCara(img)
    im,key=opc.dibujarPuntos(img)
    tmp.append((im,e))
  plt=Plot()
  plt.show(tmp,5)
Exemple #37
0
    def plot_distances (distances):
        if distances.count () <= 0:
            return

        d = distances. \
            map (lambda x : ( x[0], x[1], x[2], x[3] ) ). \
            sample (False, 0.15). \
            toDF().toPandas ()
        d = d.rename (columns = { "_1" : "truth",
                                  "_2" : "doc_dist",
                                  "_3" : "par_dist",
                                  "_4" : "sen_dist" })
        Plot.plot_distances (d)
Exemple #38
0
    def setAxisAutoScale(self, axis, auto=True):
        if axis != Qwt.QwtPlot.yRight:
            Plot.setAxisAutoScale(self, axis, auto)
        else:
            if not hasattr(self, '_cmap'):
                self._cmap = CmapJack()
            if auto:
                self.set_cbar(self._cmap, None)
            else:
                self.set_cbar(self._cmap, (self._axis_limits[axis][0],
                                           self._axis_limits[axis][1]))

            Plot.setAxisAutoScale(self, axis, auto)
Exemple #39
0
    def Run(self):
        try:
            field = Field(self._length, self._springconst, self._deltaslope)
            field.addTubes(self._count)
            plot = Plot(self._length)
            tubes = field.getTubes()
            
            # Debugging code
            start = []
            stop =[]
            for key in field.getTubes().keys():
                if field.getTubes()[key].getParams()['P'][0] <= 0:
                    start.append(key),","
                if field.getTubes()[key].getParams()['Q'][0] >= self._length:
                    stop.append(key)
            print "Starting Tubes:",start
            print "Stopping Tubes:",stop
            print "------------------------------------------"
            #time.sleep(10)
            plot.plotField(tubes)
            end = 0
            while end < 1:
                field.calculateIntercepts()
                point_forces = field.getPointForces()
                
                for key in field.getTubes().keys():
                    print key,":",field.getTubes()[key].getParams()['neighbors'].keys()
                print "=================================="
                traverses = 0
                neighbor_dict = {}
                roots = []
                leaves = []
                for index in tubes.keys():
                    neighbor_dict[index] = list()
                    neighbor_dict[index] = tubes[index].getParams()['neighbors'].keys()
                    if tubes[index].getParams()['P'][0] <= 0:
                        roots.append(index)
                    if tubes[index].getParams()['Q'][0] >= self._length:
                        leaves.append(index)
                        #print index
                for index in roots:
                    traverses += field.traverseNeighbors(index,neighbor_dict,leaves,())
                print traverses

                #if end % 1 == 0:
                #plot.plotField(tubes)
                #field.rotateTubes(point_forces)
                end += 1
                
        except EquitubeException, e:
            raise EquitubeException(e.get_message())
Exemple #40
0
 def __init__(self, parent):
     Frame.__init__(self, parent)
     self.parent = parent
     # create plots for drawing on
     self.accel_plot = Plot(self, ylabel="Acceleration (g)", numy=3, xrng=10, name="ACCEL")
     self.gyro_plot = Plot(self, ylabel="Angular Velocity (degrees/s)", numy=3, xrng=10, name="GYRO")
     self.mag_plot = Plot(self, ylabel="Field Strength", numy=3, xrng=10, name="MAG")
     self.plots = (self.accel_plot, self.gyro_plot, self.mag_plot)
     self.attitude_plot = Tiltmeter(self)
     self.x = 0
     self.y = 0
     self.width = 0
     self.height = 0
     self.plotnext = 0
Exemple #41
0
    def __init__(self, parent):
        Plot.__init__(self, parent)

        # the plot and its data
        self._raster_data = RasterData(self)
        self._plot_item = Qwt.QwtPlotSpectrogram()
        self._plot_item.setData(self._raster_data)
        self._plot_item.attach(self)
        
        # enable colormap and -bar
        self._cbar = self.axisWidget(Qwt.QwtPlot.yRight)
        self._cbar.setColorBarEnabled(True)
        self.enableAxis(Qwt.QwtPlot.yRight)
        self.set_cbar()
Exemple #42
0
def processPage(img):

    print "Finding all possible rectangles in the page"
    rects = findAllRects(img)

    plotOuts = []
    for rect in rects:
        plot = Plot(img)
        plot.corners = rect
        try:
            pout = processPlot(plot)
        except:
            pass

        if pout != False:
            plotOuts.append(pout)

    return plotOuts
Exemple #43
0
def main():
  imgSrc=os.listdir(c.test)
  imagenes=[]
  total=0
  detectadas=0
  for e in imgSrc:
    total+=1
    im,todo=f.detectFace(Imagen(e).imagen,e)
    if todo:
      detectadas+=1
    tmp=Imagen(im,name=e)
    imagenes.append(tmp)
  plt=Plot()
  tmp=[]
  print "total caras = "+str(total)+" todo detectado = "+str(detectadas)
  for e in imagenes:
    tmp.append((e.imagen,e.name))
  plt.show(tmp,5)
Exemple #44
0
    def init_ui(self):
        self.init_radio()
        self.acceleration_input.setText("9.8")
        self.l1_input.setText("1.0")
        self.l2_input.setText("1.0")
        self.m1_input.setText("1.0")
        self.m2_input.setText("1.0")
        self.alpha_input.setText("120.0")
        self.beta_input.setText("-10.0")
        self.acceleration_input.textChanged[str].connect(self.change_argument)
        self.l1_input.textChanged[str].connect(self.change_argument)
        self.l2_input.textChanged[str].connect(self.change_argument)
        self.m1_input.textChanged[str].connect(self.change_argument)
        self.m2_input.textChanged[str].connect(self.change_argument)
        self.alpha_input.textChanged[str].connect(self.change_argument)
        self.beta_input.textChanged[str].connect(self.change_argument)
        self.update_button.clicked.connect(self.update_animation)

        layout = QtGui.QVBoxLayout(self)

        splitter1 = QtGui.QSplitter(Qt.Vertical)
        splitter1.addWidget(self.lbl1)
        splitter1.addWidget(self.acceleration_input)
        splitter1.addWidget(self.lbl2)
        splitter1.addWidget(self.l1_input)
        splitter1.addWidget(self.lbl3)
        splitter1.addWidget(self.l2_input)
        splitter1.addWidget(self.lbl4)
        splitter1.addWidget(self.m1_input)
        splitter1.addWidget(self.lbl5)
        splitter1.addWidget(self.m2_input)
        splitter1.addWidget(self.lbl7)
        splitter1.addWidget(self.alpha_input)
        splitter1.addWidget(self.lbl8)
        splitter1.addWidget(self.beta_input)
        splitter1.addWidget(self.lbl6)
        splitter1.addWidget(self.r0)
        splitter1.addWidget(self.r1)
        splitter1.addWidget(self.r2)
        splitter1.addWidget(self.r3)
        splitter1.addWidget(self.update_button)
        # splitter1.addWidget(left)

        splitter0 = QtGui.QSplitter(Qt.Horizontal)
        splitter0.addWidget(splitter1)

        splitter2 = QtGui.QSplitter(Qt.Vertical)
        splitter2.addWidget(self.toolbar)
        splitter2.addWidget(self.canvas)

        splitter0.addWidget(splitter2)

        layout.addWidget(splitter0)

        self.setLayout(layout)
        self.p = Plot(self.figure, self.data)
Exemple #45
0
    def __init__(self, **kwargs):

        # Initialize self.Fixed (subset of self.Prognostic which will NOT be time-marched)
        if 'Fixed' in kwargs: self.Fixed = kwargs.pop('Fixed')
        else: self.Fixed = []

        # Initialize I/O
        self.Io = IO(self, **kwargs)

        # Get values from restart file, if available
        if 'RestartFile' in kwargs:
            ParamNames = Parameters().value.keys()
            FieldNames = self.Required
            kwargs = self.Io.readRestart(FieldNames, ParamNames, kwargs)

        # Initialize scalar parameters
        self.Params  = Parameters(**kwargs)

        # Frequency with which compute() will be executed
        if 'UpdateFreq' in kwargs:
            self.UpdateFreq = kwargs.pop('UpdateFreq')
        else:
            self.UpdateFreq = self.Params['dt']

        # Initialize State
        self.State = State(self, **kwargs)
        self.Grid = self.State.Grid

        # Dictionary to hold increments on prognos fields
        self.Inc = {}

        # Initialize diagnostics
        self.compute(ForcedCompute=True)

        # Create output file
        self.Io.createOutputFile(self.State, self.Params.value)

        # Write out initial state
        if not self.Io.Appending: self.write()

        # Initialize plotting facilities
        self.Plot = Plot()

        # Initialize runtime monitor
        self.Monitor = Monitor(self,**kwargs)

        # Notify user of unused input quantities
        self._checkUnused(kwargs)

        # Set some redundant attributes (mainly for backward compatibility)
        self.nlon = self.Grid['nlon']
        self.nlat = self.Grid['nlat']
        self.nlev = self.Grid['nlev']
        try: self.o3 = self.State['o3']
        except: pass
 def plotGains(coordinator_id ,tx_node_id, rx_node_id, year = None, month = None, day = None):
     #call the method when you want to plot the results from the file
     #open file with measurements and plot results from it
     #specify year, month, day if you only want to take into account gain measurements made until that date. If those are not specified, then all measurements will be taken into account.
     
     #first get data from the file
     gains = GainCalculations.getFileResults(coordinator_id, tx_node_id, rx_node_id, year=year, month=month, day=day)
     #gains will have the following form : [ [gain - linear , received_power[w] , noise_power[w], transmitted_power[w], date ], [gain - linear , received_power[w] , noise_power[w], transmitted_power[w], date ], .. ]
     
     if gains is None:
         aux = tx_node_id
         tx_node_id = rx_node_id
         rx_node_id = aux
         print "There are no values available for this combination. Trying with gain_between_tx_%d_and_rx_%d.dat? (yes or no)" %(tx_node_id, rx_node_id)
         choice = raw_input("")
         
         if choice.lower() == "no":
             print "You have chosen no"
             return None
         elif choice.lower() == "yes":
             gains = GainCalculations.getFileResults(coordinator_id, tx_node_id, rx_node_id, year=year, month=month, day=day)
             if gains is None:
                 print "Sorry, there are no measurements for this combination at all"
                 return None
         else:
             print "Invalid input, you were supposed to enter yes or no"
             return None
         
     print "Plot gains"    
         
     #define a gain_list : [[gain_dB], [date]]
     gain_list = [[],[]]
     
     for i in gains:
         date = DateTime.strptime((i[4])[0:16], "%Y-%m-%d %H:%M")
         gain_list[0].append(10.00 * math.log10(i[0]) )
         gain_list[1].append(date)
         
     #plot results
     Plot.plotGains(gain_list[1], gain_list[0], "Number of measurements", "Gain [dB]", "Gain between tx%d and rx%d" %(tx_node_id, rx_node_id), False)
Exemple #47
0
def onclickmethod(*args):
	canvasExists = True
	try:
		canvas = doc['brythoncanvas']
	except KeyError:
		canvasExists = False

	v = PlotParamValidator()
	if v.isValid():
		pr = FunctionParser()	
		if pr.canParse():
			if (canvasExists == True):
				ctx = canvas.getContext('2d')
				mgr = CanvasManager(v, pr)
				mgr.drawFunction(ctx)
			else:
				p = Plot(v, pr)
				p.run()
		else:
			pr.block()
	else:
		v.block()
Exemple #48
0
  def __init__(self, firn, config):
    """
    """
    self.firn   = firn
    self.config = config
    
    # form the physics :
    self.fe = Enthalpy(firn, config)
    self.fv = Velocity(firn, config)
    self.fd = FullDensity(firn, config)
    if config['age']['on']:
      self.fa = Age(firn, config)

    if config['plot']['on']:
      #plt.ion()
      self.plot = Plot(firn, config)
Exemple #49
0
def plot_implicit(expr, *args, **kwargs):
    """A plot function to plot implicit equations / inequalities.

    Arguments
    =========

    - ``expr`` : The equation / inequality that is to be plotted.
    - ``(x, xmin, xmax)`` optional, 3-tuple denoting the range of symbol
      ``x``
    - ``(y, ymin, ymax)`` optional, 3-tuple denoting the range of symbol
      ``y``

    The following arguments can be passed as named parameters.

    - ``adaptive``. Boolean. The default value is set to True. It has to be
        set to False if you want to use a mesh grid.

    - ``depth`` integer. The depth of recursion for adaptive mesh grid.
        Default value is 0. Takes value in the range (0, 4).

    - ``points`` integer. The number of points if adaptive mesh grid is not
        used. Default value is 200.

    - ``title`` string .The title for the plot.

    - ``xlabel`` string. The label for the x - axis

    - ``ylabel`` string. The label for the y - axis

    plot_implicit, by default, uses interval arithmetic to plot functions. If
    the expression cannot be plotted using interval arithmetic, it defaults to
    a generating a contour using a mesh grid of fixed number of points. By
    setting adaptive to False, you can force plot_implicit to use the mesh
    grid. The mesh grid method can be effective when adaptive plotting using
    interval arithmetic, fails to plot with small line width.

    Examples:
    =========

    Plot expressions:

    >>> from sympy import plot_implicit, cos, sin, symbols, Eq, And
    >>> x, y = symbols('x y')

    Without any ranges for the symbols in the expression

    >>> p1 = plot_implicit(Eq(x**2 + y**2, 5))

    With the range for the symbols

    >>> p2 = plot_implicit(Eq(x**2 + y**2, 3),
    ...         (x, -3, 3), (y, -3, 3))

    With depth of recursion as argument.

    >>> p3 = plot_implicit(Eq(x**2 + y**2, 5),
    ...         (x, -4, 4), (y, -4, 4), depth = 2)

    Using mesh grid and not using adaptive meshing.

    >>> p4 = plot_implicit(Eq(x**2 + y**2, 5),
    ...         (x, -5, 5), (y, -2, 2), adaptive=False)

    Using mesh grid with number of points as input.

    >>> p5 = plot_implicit(Eq(x**2 + y**2, 5),
    ...         (x, -5, 5), (y, -2, 2),
    ...         adaptive=False, points=400)

    Plotting regions.

    >>> p6 = plot_implicit(y > x**2)

    Plotting Using boolean conjunctions.

    >>> p7 = plot_implicit(And(y > x, y > -x))
    """
    has_equality = False  # Represents whether the expression contains an Equality,
                     #GreaterThan or LessThan

    def arg_expand(bool_expr):
        """
        Recursively expands the arguments of an Boolean Function
        """
        for arg in bool_expr.args:
            if isinstance(arg, BooleanFunction):
                arg_expand(arg)
            elif isinstance(arg, Relational):
                arg_list.append(arg)

    arg_list = []
    if isinstance(expr, BooleanFunction):
        arg_expand(expr)

    #Check whether there is an equality in the expression provided.
        if any(isinstance(e, (Equality, GreaterThan, LessThan))
               for e in arg_list):
            has_equality = True

    elif not isinstance(expr, Relational):
        expr = Eq(expr, 0)
        has_equality = True
    elif isinstance(expr, (Equality, GreaterThan, LessThan)):
        has_equality = True

    free_symbols = set(expr.free_symbols)
    range_symbols = set([t[0] for t in args])
    symbols = set.union(free_symbols, range_symbols)
    if len(symbols) > 2:
        raise NotImplementedError("Implicit plotting is not implemented for "
                                  "more than 2 variables")

    #Create default ranges if the range is not provided.
    default_range = Tuple(-5, 5)
    if len(args) == 2:
        var_start_end_x = args[0]
        var_start_end_y = args[1]
    elif len(args) == 1:
        if len(free_symbols) == 2:
            var_start_end_x = args[0]
            var_start_end_y, = (Tuple(e) + default_range
                                for e in (free_symbols - range_symbols))
        else:
            var_start_end_x, = (Tuple(e) + default_range for e in free_symbols)
            #Create a random symbol
            var_start_end_y = Tuple(Dummy()) + default_range

    elif len(args) == 0:
        if len(free_symbols) == 1:
            var_start_end_x, = (Tuple(e) + default_range for e in free_symbols)
            #create a random symbol
            var_start_end_y = Tuple(Dummy()) + default_range
        else:
            var_start_end_x, var_start_end_y = (Tuple(e) + default_range
                                                for e in free_symbols)

    use_interval = kwargs.pop('adaptive', True)
    nb_of_points = kwargs.pop('points', 300)
    depth = kwargs.pop('depth', 0)
    #Check whether the depth is greater than 4 or less than 0.
    if depth > 4:
        depth = 4
    elif depth < 0:
        depth = 0

    series_argument = ImplicitSeries(expr, var_start_end_x, var_start_end_y,
                                    has_equality, use_interval, depth,
                                    nb_of_points)
    show = kwargs.pop('show', True)

    #set the x and y limits
    kwargs['xlim'] = tuple(float(x) for x in var_start_end_x[1:])
    kwargs['ylim'] = tuple(float(y) for y in var_start_end_y[1:])
    p = Plot(series_argument, **kwargs)
    if show:
        p.show()
    return p
Exemple #50
0
# This is a hacky way of re-plotting graphs...

from plot import Plot
from bandit_algorithms import IncrementalUniformAlgorithm
from bandit_algorithms import UCBAlgorithm
from bandit_algorithms import EpsilonGreedyAlgorithm
from bandit import SBRDBandit

# load old plot
arm_params = [(1,1)] # dummy params
b = SBRDBandit(arm_params, 'custom_bandit')

num_pulls = 10001
num_trials = 1000
plot_sample_rate = 1
algorithms = [IncrementalUniformAlgorithm(b), UCBAlgorithm(b), EpsilonGreedyAlgorithm(b)]
plot = Plot(num_pulls, num_trials, [a.get_name() for a in algorithms], plot_sample_rate)

print "loading data..."
plot.load('custom_bandit_data.npz')

# new plot
print "creating plots..."
sample_rate = 1
end_index = 501
plot.plot_cumulative_regret('new_'+b.get_name(), sample_rate, end_index)
plot.plot_simple_regret('new_'+b.get_name(), sample_rate, end_index)
Exemple #51
0
    def process(self):
        """
        Converts the source svg to data svg using job requirements.
        """
        req = self.requirements
        plot = Plot(material)
        plot.set_graphic(self.source)
        plot.set_selected_nodes(req.plot_selected_nodes)
        plot.set_margin(req.plot_margin_top,req.plot_margin_right,req.plot_margin_bottom,req.plot_margin_left)
        plot.set_scale(req.scale_x*(invert_axis_x and 1 or -1),req.scale_y*(invert_axis_y and 1 or -1))
        plot.set_copy_spacing(req.copy_spacing_x,req.copy_spacing_y)
        plot.set_copies(req.copies)
        plot.create()


        self.data = self.source
Exemple #52
0
 def setUp(self):
     self.plot = Plot("star wars")
     self.plot.add_entity("vader")
     self.plot.add_entity("luke")
     self.plot.add_entity("emperor")
    def create_record(self, root):
        self.frame_record = Frame(root)
        self.frame_record.pack(side=TOP, fill=BOTH, pady=(0,5))
        self.frame_record1 = Frame(self.frame_record)
        self.frame_record1.pack(side=TOP, fill=BOTH, pady=(0,10))
        self.frame_record2 = Frame(self.frame_record)                    #12 between 1 and 2
        self.frame_record2.pack(side=TOP, fill=BOTH, pady=(0,10))
        self.frame_record3 = Frame(self.frame_record)
        self.frame_record3.pack(side=BOTTOM, fill=NONE)

        l_caption = Label(self.frame_record1, text="Record sound:")
        l_caption.pack(side=LEFT)
        b_help = Button(self.frame_record1, text="info", width=3, height=1)
        b_help.pack(side=RIGHT)

        self.l_selected_file_name_var = StringVar()
        self.l_selected_file_name_var.set("[Selected file name:] none")

        l_selected_file_name = Label(self.frame_record2, textvariable = self.l_selected_file_name_var, width = 30, height = 1, anchor = 'w')
        l_selected_file_name.pack(side = LEFT)

        self.b_waveform = Button(self.frame_record2, text = "WaveForm", width = 8, height = 1, command = lambda : Plot.plot_audio(self.full_file_path, "raw", self.radioIntVar))
        self.b_waveform.pack(side = RIGHT)
        self.b_waveform['state'] = 'disabled'

        self.b_fft = Button(self.frame_record2, text = "FFT", width = 8, height = 1, command = lambda : Plot.plot_audio(self.full_file_path, "fft", self.radioIntVar))
        self.b_fft.pack(side = RIGHT, padx = 3)
        self.b_fft['state'] = 'disabled'

        self.b_spectrogram = Button(self.frame_record2, text = "Spectrogram", width = 10, height = 1, command = lambda : Plot.plot_audio(self.full_file_path, "spectrogram", self.radioIntVar))
        self.b_spectrogram.pack(side = RIGHT, padx = 3)
        self.b_spectrogram['state'] = 'disabled'

        self.radioIntVar = IntVar()
        R1 = Radiobutton(self.frame_record2, text="2D", variable=self.radioIntVar, value=1, command= lambda: self.handleRadioSel())
        R1.pack( side = RIGHT)
        self.radioIntVar.set(1)     # init 2D as default

        R2 = Radiobutton(self.frame_record2, text="3D", variable=self.radioIntVar, value=2, command= lambda: self.handleRadioSel())
        R2.pack( side = RIGHT)


        global b_start
        global l_time
        b_start = Button(self.frame_record3, text='Record', width=12, height=2, command=lambda: self.main_button_click())
        b_start.pack(pady=10, padx=15, side=LEFT)

        self.l_timer_var.set('00:00')
        l_time = Label(self.frame_record3, height=1, width=5, state='disabled', bg='white', textvariable=self.l_timer_var, foreground='black')
        l_time.pack(pady=10, padx=(10,0), side=LEFT)
        l_status = Label(self.frame_record3, text="...recording", foreground='red')
        l_status.pack(pady=10, padx=(5,10), side=LEFT)
        b_reset = Button(self.frame_record3, text='Reset', padx=2, command=self.reset_button_click())
        b_reset.pack(pady=10, padx=20, side=LEFT)
Exemple #54
0
			def getX(t):
				return f(t)*math.cos(t*t_size)/x_size
			def getY(t):
				return f(t)*math.sin(t*t_size)/y_size
			x_values = [ getX(t) for t in range(int(t_min/t_size),int(t_max/t_size)) ]
			y_values = [ getY(t) for t in range(int(t_min/t_size),int(t_max/t_size)) ]
			x_max = max(x_max, max(x_values))
			x_min = min(x_min, min(x_values))
			y_max = max(y_max, max(y_values))
			y_min = min(y_min, min(y_values))
		x_max = int(x_max + 1) + 1
		x_min = int(x_min - 1) - 1
		y_max = int(y_max + 1) + 1
		y_min = int(y_min - 1) - 1
		
	plot = Plot(x_min, x_max, x_size, y_min, y_max, y_size, t_min, t_max, t_size)
		
	#Plot axes
	if plot_axes: plot.plot_axes

	#Fix descrepancies betwen functions and colors	
	if len(functions) < len(colors):
		colors = colors[:len(functions)]
	
	if len(functions) > len(colors):
		colors += [default] * (len(functions)-len(colors))
	
	#Plot functions
	for (function, color) in zip(functions,colors):
		if polar:
			plot.plot_polar(function, color)
def main():
    figure = Plot.new_figure(figsize=(5,10))
    fit_ids = ['a', 'b', 'c', 'd']

    def data_path(fit_id):
        if fit_id == 'c':
            fit_type = 'parallel'
        else:
            fit_type = 'difference'
        return os.path.join('json', 'fig_4' + fit_id + '_' + fit_type + '.json')

    fits = [ Fit(data_path(fig)) for fig in fit_ids ]

    for fit in fits[0:3]:
        fit.maps['value_transforms']['Ω_C'] = lambda x: '%.2E' % round(x, 2)

    for i in (0, 1): fits[i].meta['contact_type'] = 'tunneling'
    fits[2].meta['contact_type'] = 'pinhole'
    fits[3].meta['contact_type'] = 'transparent'

    plots = []
    for idx, fit in enumerate(fits):
        n, m = 4, 1

        options = {}
        if idx != 0: options['sharex'] = plots[idx - 1].plt

        plot = Plot(fit, figure.add_subplot(n, m, (m * idx + 1), **options))
        plot.id = fit_ids[idx]
        plots.append(plot)

    for idx, plot in enumerate(plots):
        plot.plot_data()
        plot.plot_fit()

        if idx == 2:
            plot.add_ylabel(False)
        else:
            plot.add_ylabel(True)

        plot.add_parameter_overlay()

    plots[-1].add_xlabel()
    matplotlib.pyplot.setp([ p.plt.get_xticklabels() for p in plots[0:3] ], visible=False)

    figure.savefig(os.path.join('build', 'plot_fits.eps'), transparent=True)
    plots[0].fit.save_info('build/plot_fits_info.tex', 'plotFitsInfo')
    Plot.close_figure(figure)
Exemple #56
0
class TransientSolver(object):
  """
  """
  def __init__(self, firn, config):
    """
    """
    self.firn   = firn
    self.config = config
    
    # form the physics :
    self.fe = Enthalpy(firn, config)
    self.fv = Velocity(firn, config)
    self.fd = FullDensity(firn, config)
    if config['age']['on']:
      self.fa = Age(firn, config)

    if config['plot']['on']:
      #plt.ion()
      self.plot = Plot(firn, config)
      #plt.show()

  def solve(self):
    """
    """
    s    = '::: solving TransientSolver :::'
    text = colored(s, 'blue')
    print text
    
    firn   = self.firn
    config = self.config

    fe     = self.fe
    fv     = self.fv
    fd     = self.fd
    if config['age']['on']:
      fa     = self.fa
    
    t0      = config['t_start']
    tm      = config['t_mid']
    tf      = config['t_end']
    dt      = config['time_step']
    dt_list = config['dt_list']
    if dt_list != None:
      numt1   = (tm-t0)/dt_list[0] + 1       # number of time steps
      numt2   = (tf-tm)/dt_list[1] + 1       # number of time steps
      times1  = linspace(t0,tm,numt1)   # array of times to evaluate in seconds
      times2  = linspace(tm,tf,numt2)   # array of times to evaluate in seconds
      dt1     = dt_list[0] * ones(len(times1))
      dt2     = dt_list[1] * ones(len(times2))
      times   = hstack((times1,times2))
      dts     = hstack((dt1, dt2))
    
    else: 
      numt   = (tf-t0)/dt + 1         # number of time steps
      times  = linspace(t0,tf,numt)   # array of times to evaluate in seconds
      dts    = dt * ones(len(times))
      firn.t = t0
   
    self.times = times
    self.dts   = dts

    for t,dt in zip(times[1:], dts[1:]):
      
      # update timestep :
      firn.dt = dt
      firn.dt_v.assign(dt)

      # update boundary conditions :
      firn.update_Hbc()
      firn.update_rhoBc()
      firn.update_wBc()
      #firn.update_omegaBc()
    
      # newton's iterative method :
      fe.solve()
      fd.solve()
      fv.solve()
      if config['age']['on']:
        fa.solve()
      
      # update firn object :
      firn.update_vars(t)
      firn.update_height_history()
      if config['free_surface']['on']:
        if dt_list != None:
          if t > tm+dt:
            firn.update_height()
        else:
          firn.update_height()
      
      # update model parameters :
      if t != times[-1]:
         firn.H_1.assign(firn.H)
         firn.U_1.assign(firn.U)
         firn.omega_1.assign(firn.omega)
         firn.w_1.assign(firn.w)
         firn.a_1.assign(firn.a)
         firn.m_1.assign(firn.m)
    
      # update the plotting parameters :
      if config['plot']['on']:
        self.plot.update_plot()
        #plt.draw()
        
      s = '>>> Time: %i yr <<<'
      text = colored(s, 'red', attrs=['bold'])
      print text % (t / firn.spy)
    
    if config['plot']['on']:
      pass
def main():
    figure = Plot.new_figure(figsize=(5,10))

    data_path = lambda x: os.path.join('json', 'fig_4d_difference_' + x + '_lifetime.json')
    fits = [ Fit(data_path(fig)) for fig in ['large', 'larger'] ]

    for fit in fits:
        fit.maps['value_transforms']['τ'] = lambda x: '%.2E' % round(x, 2)
        fit.meta['contact_type'] = 'transparent'

    plots = []
    for idx, fit in enumerate(fits):
        n, m = 2, 1

        options = {}
        if idx != 0: options['sharex'] = plots[idx - 1].plt

        plot = Plot(fit, figure.add_subplot(n, m, (m * idx + 1), **options))
        plot.id = 'd.' + str(idx + 1)
        plots.append(plot)

    for plot in plots:
        plot.plot_data()
        plot.plot_fit()
        plot.add_ylabel()
        plot.add_parameter_overlay()

    plots[-1].add_xlabel()
    matplotlib.pyplot.setp(plots[0].plt.get_xticklabels(), visible=False)

    figure.savefig(os.path.join('build', 'plot_fits_large_lifetime.eps'), transparent=True)
    plots[0].fit.save_info('build/plot_fits_large_lifetime_info.tex', 'plotFitsLargeLifetimeInfo')
    Plot.close_figure(figure)
Exemple #58
0
    epoch_list.append(range(num_learning_epochs))
    avg_reward_list.append([])
    for epoch in epoch_list[e]:
        for trial in range(num_learning_trials):
            qlearner.run_learning_trial()

        avg_reward = 0
        for trial in range(num_simulation_trials):
            (total_reward, state_seq, action_seq) = qlearner.run_simulation_trial()
            avg_reward += total_reward
        avg_reward = 1.*avg_reward/num_simulation_trials
        avg_reward_list[e].append(avg_reward)
        print "MDP1 epoch {0}: {1}".format(epoch, avg_reward)

Plot.plot_multiple(epoch_list, avg_reward_list, [str(e) for e in epsilon_list], 'epsilon', 'MDP1 Learning: Epsilon', 'mdp1_epsilon_plot.png')
print


### PART III: MDP 1 alpha experiments
epsilon = 0.25
learning_rate_list = [0.001, 0.01, 0.1, 1.0]
epoch_list = []
avg_reward_list = []

for a, learning_rate in enumerate(learning_rate_list):
    print "Alpha: {0}".format(learning_rate)

    qlearner = QLearner(mdp1, initial_state1, epsilon=epsilon, alpha=learning_rate)

    epoch_list.append(range(num_learning_epochs))
Exemple #59
0
class Component:
    """
    Abstract class defining methods inherited by all CliMT components.
    """
    def __init__(self, **kwargs):

        # Initialize self.Fixed (subset of self.Prognostic which will NOT be time-marched)
        if 'Fixed' in kwargs: self.Fixed = kwargs.pop('Fixed')
        else: self.Fixed = []

        # Initialize I/O
        self.Io = IO(self, **kwargs)

        # Get values from restart file, if available
        if 'RestartFile' in kwargs:
            ParamNames = Parameters().value.keys()
            FieldNames = self.Required
            kwargs = self.Io.readRestart(FieldNames, ParamNames, kwargs)

        # Initialize scalar parameters
        self.Params  = Parameters(**kwargs)

        # Frequency with which compute() will be executed
        if 'UpdateFreq' in kwargs:
            self.UpdateFreq = kwargs.pop('UpdateFreq')
        else:
            self.UpdateFreq = self.Params['dt']

        # Initialize State
        self.State = State(self, **kwargs)
        self.Grid = self.State.Grid

        # Dictionary to hold increments on prognos fields
        self.Inc = {}

        # Initialize diagnostics
        self.compute(ForcedCompute=True)

        # Create output file
        self.Io.createOutputFile(self.State, self.Params.value)

        # Write out initial state
        if not self.Io.Appending: self.write()

        # Initialize plotting facilities
        self.Plot = Plot()

        # Initialize runtime monitor
        self.Monitor = Monitor(self,**kwargs)

        # Notify user of unused input quantities
        self._checkUnused(kwargs)

        # Set some redundant attributes (mainly for backward compatibility)
        self.nlon = self.Grid['nlon']
        self.nlat = self.Grid['nlat']
        self.nlev = self.Grid['nlev']
        try: self.o3 = self.State['o3']
        except: pass

    def compute(self, ForcedCompute=False):
        """
        Updates component's diagnostics and increments
        """
        # See if it's time for an update; if not, skip rest
        if not ForcedCompute:
            freq = self.UpdateFreq
            time = self.State.ElapsedTime
            if int(time/freq) == int((time-self['dt'])/freq): return

        # Set up union of State, Grid and Params
        Input = {}
        for dic in [self.State.Now, self.Grid.value, self.Params.value]: Input.update(dic)
        Input['UpdateFreq'] = self.UpdateFreq

        # For implicit time stepping, replace current time level with previous (old) time level
        if self.SteppingScheme == 'implicit': Input.update(self.State.Old)

        # For semimplicit time stepping, append previous (old) time level to Input dict
        if self.SteppingScheme == 'semi-implicit':
            for key in self.Prognostic: Input[key+'old'] = self.State.Old[key]

        # List of arguments to be passed to extension
        args = [ Input[key] for key in self.ToExtension ]

        # Call extension and build dictionary of ouputs
        OutputValues = self.driver(*args)
        if len(self.FromExtension) == 1: Output = {self.FromExtension[0]: OutputValues}
        else:                            Output = dict( zip(self.FromExtension, OutputValues ) )

        # Extract increments from Output
        for key in self.Prognostic:
            self.Inc[key] = Output.pop(key+'inc')

        # Remove increments of Fixed variables
        for key in self.Fixed:
            if key in self.Inc: self.Inc.pop(key)
            if key in Output: Output.pop(key)

        # Update State
        self.State.update(Output)
        for key in Output: exec('self.'+key+'=Output[key]')

        # No further need for input dictionary
        del(Input)

    def step(self, RunLength=1, Inc={}):
        """
        Advances component one timestep and writes to output file if necessary.
        Inc is an externally-specified set of increments added to the internally-computed
        increments at each time step.
        """

        # If RunLength is integer, interpret as number of time steps
        if type(RunLength) is type(1):
            NSteps = RunLength

        # If RunLength is float, interpret as length of run in seconds
        if type(RunLength) is type(1.):
            NSteps = int(RunLength/self['dt'])

        for i in range(NSteps):
            # Add external increments
            for key in Inc.keys():
                if key in self.Inc.keys():
                    self.Inc[key] += Inc[key]
                else:
                    self.Inc[key] = Inc[key]

            # Avance prognostics 1 time step
            self.State.advance(self)

            # Bring diagnostics and increments up to date
            self.compute()

            # Bring calendar up to date
            self['calday'] += self['dt']/self['lod']
            if self['calday'] > self['daysperyear']:
                self['calday'] -= self['daysperyear']

            # Write to file, if it's time to
            dt   = self.Params['dt']
            time = self.State.ElapsedTime
            freq = self.Io.OutputFreq
            if int(time/freq) != int((time-dt)/freq): self.write()

            # Refresh monitor, if it's time to
            if self.Monitor.Monitoring:
                freq = self.Monitor.MonitorFreq
                if int(time/freq) != int((time-dt)/freq): self.Monitor.refresh(self)

    def __call__(self,**kwargs):
        """
        # Provides a simple interface to extension, useful e.g. for diagnostics.
        """
        # Re-initialize parameters, grid and state
        self.Params  = Parameters(**kwargs)
        self.State = State(self, **kwargs)
        self.Grid = self.State.Grid
        # Bring diagnostics up to date
        self.compute()

    def write(self):
        """
        Invokes write method of IO instance to write out current State
        """
        self.Io.writeOutput(self.Params, self.State)

    def open(self, OutputFileName='CliMT.nc'):
        """
        """
        if self.Io.OutputFileName == OutputFileName:
            print '\n +++ ClimT.Io: File %s is currently open for output'% OutputFileName
            return
        else:
            print 'Opening %s for output'% OutputFileName
            self.Io.OutputFileName = OutputFileName
            self.Io.DoingOutput = True
            self.Io.Appending = False
            self.Io.OutputTimeIndex = 0
            self.Io.createOutputFile(self.State, self.Params)

    def plot(self, *FieldKeys):
        self.Plot(self, *FieldKeys)

    def setFigure(self, FigureNumber=None):
        self.Plot.setFigure(FigureNumber)

    def closeFigure(self, FigureNumber=None):
        self.Plot.closeFigure(FigureNumber)

    def usage(self):
        print self.__doc__

    def report(self):
        print 'CliMT component:\n    %s' % self.Name
        keys = self.State.keys()
        keys1 = []
        for i in range(len(keys)):
            if   keys[i] in self.Prognostic: keys1.append('%12s   %s' % (keys[i],'(prognostic)'))
        for i in range(len(keys)):
            if keys[i] in self.Diagnostic: keys1.append('%12s   %s' % (keys[i],'(diagnostic)'))
        for i in range(len(keys)):
            if keys[i] not in self.Prognostic and keys[i] not in self.Diagnostic:
                                           keys1.append('%12s   %s' % (keys[i],'(Fixed)'))
        print 'State variables:\n %s' % '\n '.join( keys1 )

    def _checkUnused(self,kwargs):
        '''
        Notify of unused input quantities.
        '''
        unused = []
        io_keys = ['RestartFile','OutputFile','OutputFreq','OutputFields','ElapsedTime']
        monitor_keys = ['MonitorFields','MonitorFreq']
        for key in kwargs:
            if key not in self.Params  \
            and key not in self.Grid   \
            and key not in KnownFields \
            and key not in io_keys \
            and key not in monitor_keys:
                unused.append(key)

        if len(unused) > 0:
           if len(unused) == 1: suffix = 'y'
           else              : suffix = 'ies'
           print '\n ++++ CliMT.'+self.Name+'.initialize: WARNING: Input quantit%s %s not used.\n' \
                  % (suffix,str(list(unused)))

    def _getShape3D(self, **kwargs):
        '''
        Returns shape of 3D arrays to be passed to extension.
        '''
        return (self._getAxisLength('lev', **kwargs),
                self._getAxisLength('lat', **kwargs),
                self._getAxisLength('lon', **kwargs))


    def _getAxisLength(self, AxisName, **kwargs):
        '''
        Returns length of axis.
        '''
        # Check input
        assert AxisName in ['lev','lat','lon'], \
               '\n\n ++++ CliMT.%s: Axis name must be one of "lon", "lat", "lev"' % self.Name

        # See if axis was supplied in input
        n = None
        if AxisName in kwargs:
            if ndim(array(kwargs[AxisName])) == 0:
                n = 1
            else:
                assert ndim(array(kwargs[AxisName])) == 1, \
                    '\n\n ++++ CliMT.%s.init: input %s must be rank 1' % (self.Name,AxisName)
                n = len(array(kwargs[AxisName]))

        # If not, see if some field was supplied
        else:
            for key in kwargs:
                if key in KnownFields:
                    if KnownFields[key][2] == '2D' and AxisName != 'lev':
                        i = ['lat','lon'].index(AxisName)
                        try:    n = array(kwargs[key]).shape[i]
                        except: n = 1
                    elif KnownFields[key][2] == '3D':
                        i = ['lev','lat','lon'].index(AxisName)
                        try:    n = array(kwargs[key]).shape[i]
                        except: n = 1

        # Last resort: get dimensions set in Makefile
        if n is None: exec('n = get_n%s()' % AxisName)

        # Check if extension enforces axis dimension, ensure consistency
        try:
            exec('n_ext = self.Extension.get_n%s()' % AxisName)
        except:
            n_ext = n
        assert n_ext == n, \
            '\n\n ++++ CliMT.%s.init: input %s has dimension %i but extension requires %i'% \
            (self.Name, AxisName, n, n_ext)

        return n

    # Returns requested quantity from Params, Grid or State
    def __getitem__(self, key):
        for obj in [self.Params, self.Grid, self.State]:
            if key in obj:
                if type(obj[key]) is type('string'): return obj[key]
                else: return squeeze(obj[key])
        raise IndexError,'\n\n CliMT.State: %s not in Params, Grid or State' % str(key)

    # Sets requested quantity in Params, Grid or State
    def __setitem__(self, key, value):
        if key in self.Params:
            self.Params[key] = value
            return
        if key in self.Grid:
            self.Grid[key] = value
            return
        elif key in self.State and KnownFields[key][2] == '2D':
            self.State[key]=reshape(value,self.Grid.Shape3D[1:3])
            return
        elif key in self.State and KnownFields[key][2] == '3D':
            self.State[key]=reshape(value,self.Grid.Shape3D)
            return
        else: raise IndexError,'\n\n CliMT.State: %s not in Params, Grid or State' % str(key)