def main():
    parser = OptionParser(usage=usage, version="%prog 42")
    parser.add_option("-s", "--scale", type=int, metavar='scale',
                      action="store", dest="scale",
                      default=2, help=help['scale'])
    parser.add_option("-r", "--repeat", type='str', metavar='nx,ny[,nz]',
                      action="callback", dest="repeat",
                      callback=parse_repeat, default=None, help=help['repeat'])
    parser.add_option("-e", "--eps", type=float, metavar='eps',
                      action="store", dest="eps",
                      default=1e-8, help=help['eps'])
    (options, args) = parser.parse_args()

    if (len( args ) == 2):
        filename_in = args[0]
        filename_out = args[1]
    else:
        parser.print_help()
        return

    output = Output('tpm:')
    output('scale:', options.scale)
    output('repeat:', options.repeat)
    output('eps:', options.eps)

    mesh_in = Mesh.from_file(filename_in)
    mesh_out = gen_tiled_mesh(mesh_in, options.repeat, 1./options.scale,
                              options.eps)
    mesh_out.write(filename_out, io='auto')
    output('done.')
示例#2
0
    def test_verbose_output(self):
        try:
            from StringIO import StringIO  # Python 2
        except ImportError:
            from io import StringIO  # Python 3

        from sfepy.base.base import Output, goptions

        fd = StringIO()

        output = Output('test', filename=fd)

        output('test1')
        goptions['verbose'] = False
        output('test2')
        goptions['verbose'] = 1
        output('test3')

        _ok1 = bool(goptions['verbose'])
        _ok2 = fd.getvalue() == 'test test1\ntest test3\n'

        fd.close()

        ok = _ok1 and _ok2

        return ok
示例#3
0
    def test_log_rw(self):
        from sfepy.base.base import Output
        from sfepy.base.log import read_log, write_log

        log, info = read_log(self.log_filename)

        output = Output('',
                        filename=os.path.join(self.options.out_dir,
                                              'test_log2.txt'),
                        quiet=True)
        write_log(output, log, info)

        log2, info2 = read_log(self.log_filename)

        ok = True
        _ok = info == info2
        if not _ok:
            self.report('headers are not equal!')
            self.report(info)
            self.report(info2)
        ok = ok and _ok

        for key, val2 in log2.items():
            val = log[key]
            _ok = nm.allclose(val[0], val2[0], rtol=0.0, atol=1e-14)
            if not _ok:
                self.report('x values are not equal!')
                self.report(val[0])
                self.report(val2[0])
            ok = ok and _ok

            _ok = nm.allclose(val[1], val2[1], rtol=0.0, atol=1e-14)
            if not _ok:
                self.report('y values are not equal!')
                self.report(val[1])
                self.report(val2[1])
            ok = ok and _ok

            _ok = nm.allclose(val[2], val2[2], rtol=0.0, atol=1e-14)
            if not _ok:
                self.report('vlines are not equal!')
                self.report(val[2])
                self.report(val2[2])
            ok = ok and _ok

        return ok
示例#4
0
def main():
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("--version", action="version", version="%(prog)s 42")
    parser.add_argument("-s",
                        "--scale",
                        type=int,
                        metavar='scale',
                        action="store",
                        dest="scale",
                        default=2,
                        help=help['scale'])
    parser.add_argument("-r",
                        "--repeat",
                        type=str,
                        metavar='nx,ny[,nz]',
                        action=ParseRepeat,
                        dest="repeat",
                        default=None,
                        help=help['repeat'])
    parser.add_argument("-e",
                        "--eps",
                        type=float,
                        metavar='eps',
                        action="store",
                        dest="eps",
                        default=1e-8,
                        help=help['eps'])
    parser.add_argument('filename_in')
    parser.add_argument('filename_out')
    options = parser.parse_args()

    filename_in = options.filename_in
    filename_out = options.filename_out

    output = Output('tpm:')
    output('scale:', options.scale)
    output('repeat:', options.repeat)
    output('eps:', options.eps)

    mesh_in = Mesh.from_file(filename_in)
    mesh_out = gen_tiled_mesh(mesh_in, options.repeat, 1. / options.scale,
                              options.eps)
    mesh_out.write(filename_out, io='auto')
    output('done.')
示例#5
0
    def test_verbose_output(self):
        import StringIO
        from sfepy.base.base import Output, goptions

        fd = StringIO.StringIO()

        output = Output('test', filename=fd)

        output('test1')
        goptions['verbose'] = False
        output('test2')
        goptions['verbose'] = 1
        output('test3')

        _ok1 = goptions['verbose'] == True
        _ok2 = fd.getvalue() == 'test test1\ntest test3\n'

        fd.close()

        ok = _ok1 and _ok2

        return ok
示例#6
0
def print_mem_usage(usage, order_by='usage', direction='up', print_key=False):
    """
    Print memory usage dictionary.

    Parameters
    ----------
    usage : dict
        The dict with memory usage records.
    order_by : 'usage', 'name', 'kind', 'nrefs', 'traversal_order', or 'level'
        The sorting field name.
    direction : 'up' or 'down'
        The sorting direction.
    print_key : bool
        If True, print also the record key (object's id).
    """
    keys = usage.keys()
    order_vals = nm.array(
        [record.get(order_by) for record in usage.itervalues()])

    order = nm.argsort(order_vals)
    if direction == 'down':
        order = order[::-1]

    output = Output('')
    fmt = '%9s, %s, %s, %d %d %d' + ', %d' * print_key

    for ii in order:
        key = keys[ii]
        record = usage[key]

        if print_key:
            output(fmt % (record.usage, record.name, record.kind, record.nrefs,
                          record.traversal_order, record.level, key))

        else:
            output(fmt % (record.usage, record.name, record.kind, record.nrefs,
                          record.traversal_order, record.level))
示例#7
0
class LogPlotter(Struct):
    """
    LogPlotter to be used by :class:`sfepy.base.log.Log`.
    """
    output = Output('plotter:')
    output = staticmethod(output)

    def __init__(self, aggregate=100, sleep=1.0):
        Struct.__init__(self, aggregate=aggregate, sleep=sleep)

    def process_command(self, command):
        from matplotlib.ticker import LogLocator, AutoLocator

        self.output(command[0])

        if command[0] == 'ig':
            self.ig = command[1]

        elif command[0] == 'plot':
            xdata, ydata, plot_kwargs = command[1:]

            ig = self.ig
            ax = self.ax[ig]
            ax.set_yscale(self.yscales[ig])
            ax.yaxis.grid(True)
            ax.plot(xdata, ydata, **plot_kwargs)

            if self.yscales[ig] == 'log':
                ymajor_formatter = ax.yaxis.get_major_formatter()
                ymajor_formatter.label_minor(True)
                yminor_locator = LogLocator()
            else:
                yminor_locator = AutoLocator()
                self.ax[ig].yaxis.set_minor_locator(yminor_locator)

        elif command[0] == 'vline':
            x, kwargs = command[1:]

            self.vlines[self.ig].append((x, kwargs))

        elif command[0] == 'clear':
            self.ax[self.ig].cla()

        elif command[0] == 'legends':
            for ig, ax in enumerate(self.ax):
                try:
                    ax.legend(self.data_names[ig])
                except:
                    pass

                if self.xlabels[ig]:
                    ax.set_xlabel(self.xlabels[ig])
                if self.ylabels[ig]:
                    ax.set_ylabel(self.ylabels[ig])

                for x, kwargs in self.vlines[ig]:
                    ax.axvline(x, **kwargs)

            try:
                self.plt.tight_layout(pad=0.5)

            except:
                pass

        elif command[0] == 'add_axis':
            ig, names, yscale, xlabel, ylabel = command[1:]
            self.data_names[ig] = names
            self.yscales[ig] = yscale
            self.xlabels[ig] = xlabel
            self.ylabels[ig] = ylabel
            self.n_gr = len(self.data_names)
            self.make_axes()

        elif command[0] == 'save':
            self.fig.savefig(command[1])
            self.pipe.send(True)  # Acknowledge save.

    def terminate(self):
        if self.ii:
            self.output('processed %d commands' % self.ii)
        self.output('ended.')
        self.plt.close('all')

    def poll_draw(self):

        while 1:
            self.ii = 0

            while 1:
                if not self.pipe.poll():
                    break

                command = self.pipe.recv()
                can_break = False

                if command is None:
                    self.terminate()
                    return False
                elif command[0] == 'continue':
                    can_break = True
                else:
                    self.process_command(command)

                if (self.ii >= self.aggregate) and can_break:
                    break

                self.ii += 1

            if self.ii:
                self.fig.canvas.draw()
                self.output('processed %d commands' % self.ii)
            time.sleep(self.sleep)

        return True

    def make_axes(self):
        from sfepy.linalg import cycle

        self.fig.clf()
        self.ax = []

        n_col = min(5.0, nm.fix(nm.sqrt(self.n_gr)))
        if int(n_col) == 0:
            n_row = 0
        else:
            n_row = int(nm.ceil(self.n_gr / n_col))
            n_col = int(n_col)

        for ii, (ir, ic) in enumerate(cycle((n_col, n_row))):
            if ii == self.n_gr: break
            self.ax.append(self.fig.add_subplot(n_row, n_col, ii + 1))
            self.vlines.setdefault(ii, [])

    def __call__(self, pipe, log_file, data_names, yscales, xlabels, ylabels):
        """
        Sets-up the plotting window, starts a thread calling self.poll_draw()
        that does the actual plotting, taking commands out of `pipe`.

        Note that pyplot _must_ be imported here and not in this module so that
        the import occurs _after_ the plotting process is started in that
        process.
        """
        import matplotlib.pyplot as plt

        self.plt = plt

        self.output.set_output(filename=log_file)
        self.output('starting plotter...')

        self.pipe = pipe
        self.data_names = data_names
        self.yscales = yscales
        self.xlabels = xlabels
        self.ylabels = ylabels
        self.n_gr = len(data_names)
        self.vlines = {}

        self.fig = self.plt.figure()
        self.make_axes()

        import threading
        draw_thread = threading.Thread(target=self.poll_draw)
        draw_thread.start()

        self.output('...done')
        self.plt.show()

        draw_thread.join()
示例#8
0
    def __init__(self, data_names=None, plot_kwargs=None,
                 xlabels=None, ylabels=None, yscales=None,
                 show_legends=True, is_plot=True, aggregate=100, sleep=1.0,
                 log_filename=None, formats=None):
        """
        Parameters
        ----------
        data_names : list of lists of str
            The data names grouped by subplots: [[name1, name2, ...], [name3,
            name4, ...], ...], where name<n> are strings to display in
            (sub)plot legends.
        plot_kwargs : list of (lists of dicts) or dicts
            The keyword arguments dicts passed to plot(). For each group the
            item can be either a dict that is applied to all lines in the
            group, or a list of dicts for each line in the group.
        xlabels : list of str
            The x axis labels of subplots.
        ylabels : list of str
            The y axis labels of subplots.
        yscales : list of 'linear' or 'log'
            The y axis scales of subplots.
        show_legends : bool
            If True, show legends in plots.
        is_plot : bool
            If True, try to use LogPlotter for plotting.
        aggregate : int
            The number of plotting commands to process before a redraw.
        sleep : float
            The number of seconds to sleep between polling draw commands.
        log_filename : str, optional
            If given, save log data into a log file.
        formats : list of lists of number format strings
            The print formats of data to be used in a log file, group in the
            same way as subplots.
        """
        try:
            import matplotlib as mpl
        except:
            mpl = None

        Struct.__init__(self,
                        show_legends=show_legends, is_plot=is_plot,
                        aggregate=aggregate, sleep=sleep,
                        data_names={}, n_arg=0, n_gr=0,
                        data={}, x_values={}, n_calls=0, plot_kwargs={},
                        yscales={}, xlabels={}, ylabels={},
                        plot_pipe=None, formats={}, _format_styles={},
                        output=None)

        if data_names is not None:
            n_gr = len(data_names)
        else:
            n_gr = 0
            data_names = []

        plot_kwargs = get_default(plot_kwargs, [{}] * n_gr)
        yscales = get_default(yscales, ['linear'] * n_gr)
        xlabels = get_default(xlabels, ['iteration'] * n_gr)
        ylabels = get_default(ylabels, [''] * n_gr)

        if formats is None:
            formats = [None] * n_gr

        for ig, names in enumerate(data_names):
            self.add_group(names, plot_kwargs[ig],
                           yscales[ig], xlabels[ig], ylabels[ig],
                           formats[ig])

        self.can_plot = (mpl is not None) and (Process is not None)

        if log_filename is not None:
            self.output = Output('', filename=log_filename)
            self.output('# started: %s' % time.asctime())
            self.output('# groups: %d' % n_gr)
            for ig, names in enumerate(data_names):
                self.output('#   %d' % ig)
                self.output('#     xlabel: "%s", ylabel: "%s", yscales: "%s"'
                            % (xlabels[ig], ylabels[ig], yscales[ig]))
                self.output('#     names: "%s"' % ', '.join(names))
                self.output('#     plot_kwargs: "%s"'
                            % ', '.join('%s' % ii
                                        for ii in self.plot_kwargs[ig]))

        if self.is_plot and (not self.can_plot):
            output(_msg_no_live)
示例#9
0
文件: log.py 项目: uberstig/sfepy
    def __init__(self, data_names=None, xlabels=None, ylabels=None,
                 yscales=None, is_plot=True, aggregate=200,
                 log_filename=None, formats=None):
        """
        Parameters
        ----------
        data_names : list of lists of str
            The data names grouped by subplots: [[name1, name2, ...], [name3,
            name4, ...], ...], where name<n> are strings to display in
            (sub)plot legends.
        xlabels : list of str
            The x axis labels of subplots.
        ylabels : list of str
            The y axis labels of subplots.
        yscales : list of 'linear' or 'log'
            The y axis scales of subplots.
        is_plot : bool
            If True, try to use LogPlotter for plotting.
        aggregate : int
            The number of plotting commands to process before a redraw.
        log_filename : str, optional
            If given, save log data into a log file.
        formats : list of lists of number format strings
            The print formats of data to be used in a log file, group in the
            same way as subplots.
        """
        try:
            import matplotlib as mpl
        except:
            mpl = None

        if (mpl is not None) and mpl.rcParams['backend'] == 'GTKAgg':
            can_live_plot = True
        else:
            can_live_plot = False

        Struct.__init__(self, data_names = {},
                        n_arg = 0, n_gr = 0,
                        data = {}, x_values = {}, n_calls = 0,
                        yscales = {}, xlabels = {}, ylabels = {},
                        plot_pipe = None, formats = {}, output = None)

        if data_names is not None:
            n_gr = len(data_names)
        else:
            n_gr = 0
            data_names = []

        yscales = get_default(yscales, ['linear'] * n_gr)
        xlabels = get_default(xlabels, ['iteration'] * n_gr)
        ylabels = get_default(ylabels, [''] * n_gr)

        if formats is None:
            formats = [None] * n_gr

        for ig, names in enumerate(data_names):
            self.add_group(names, yscales[ig], xlabels[ig], ylabels[ig],
                           formats[ig])

        self.is_plot = get_default(is_plot, True)
        self.aggregate = get_default(aggregate, 100)

        self.can_plot = (can_live_plot and (mpl is not None)
                         and (Process is not None))

        if log_filename is not None:
            self.output = Output('', filename=log_filename)
            self.output('# started: %s' % time.asctime())
            self.output('# groups: %d' % n_gr)
            for ig, names in enumerate(data_names):
                self.output('#   %d' % ig)
                self.output('#     xlabel: "%s", ylabel: "%s", yscales: "%s"'
                            % (xlabels[ig], ylabels[ig], yscales[ig]))
                self.output('#     names: "%s"' % ', '.join(names))

        if self.is_plot and (not self.can_plot):
            output(_msg_no_live)
示例#10
0
文件: balloon.py 项目: uberstig/sfepy
The agreement should be very good, even though the mesh is coarse.

View the results using::

  python postproc.py unit_ball.h5 --wireframe -b -d'u,plot_displacements,rel_scaling=1' --step=-1
"""
import os
import numpy as nm

from sfepy.base.base import Output
from sfepy.discrete.fem import MeshIO
from sfepy.linalg import get_coors_in_ball
from sfepy import data_dir

output = Output('balloon:')


def get_nodes(coors, radius, eps, mode):
    if mode == 'ax1':
        centre = nm.array([0.0, 0.0, -radius], dtype=nm.float64)

    elif mode == 'ax2':
        centre = nm.array([0.0, 0.0, radius], dtype=nm.float64)

    elif mode == 'equator':
        centre = nm.array([radius, 0.0, 0.0], dtype=nm.float64)

    else:
        raise ValueError('unknown mode %s!' % mode)
示例#11
0
文件: log.py 项目: sdurve/sfepy
    def __init__(self,
                 data_names=None,
                 yscales=None,
                 xlabels=None,
                 ylabels=None,
                 is_plot=True,
                 aggregate=200,
                 formats=None,
                 log_filename=None):
        """`data_names` ... tuple of names grouped by subplots:
                            ([name1, name2, ...], [name3, name4, ...], ...)
        where name<n> are strings to display in (sub)plot legends."""
        try:
            import matplotlib as mpl
        except:
            mpl = None

        if (mpl is not None) and mpl.rcParams['backend'] == 'GTKAgg':
            can_live_plot = True
        else:
            can_live_plot = False

        Struct.__init__(self,
                        data_names={},
                        n_arg=0,
                        n_gr=0,
                        data={},
                        x_values={},
                        n_calls=0,
                        yscales={},
                        xlabels={},
                        ylabels={},
                        plot_pipe=None,
                        formats={},
                        output=None)

        if data_names is not None:
            n_gr = len(data_names)
        else:
            n_gr = 0
            data_names = []

        yscales = get_default(yscales, ['linear'] * n_gr)
        xlabels = get_default(xlabels, ['iteration'] * n_gr)
        ylabels = get_default(ylabels, [''] * n_gr)

        if formats is None:
            formats = [None] * n_gr

        for ig, names in enumerate(data_names):
            self.add_group(names, yscales[ig], xlabels[ig], ylabels[ig],
                           formats[ig])

        self.is_plot = get_default(is_plot, True)
        self.aggregate = get_default(aggregate, 100)

        self.can_plot = (can_live_plot and (mpl is not None)
                         and (Process is not None))

        if log_filename is not None:
            self.output = Output('', filename=log_filename)
            self.output('# started: %s' % time.asctime())
            self.output('# groups: %d' % n_gr)
            for ig, names in enumerate(data_names):
                self.output('#   %d' % ig)
                self.output('#     xlabel: "%s", ylabel: "%s", yscales: "%s"' %
                            (xlabels[ig], ylabels[ig], yscales[ig]))
                self.output('#     names: "%s"' % ', '.join(names))

        if self.is_plot and (not self.can_plot):
            output(_msg_no_live)