Exemple #1
0
    def __init__(self, *args):
        """Initialize as a list of :class:`LinRes` instances, loading files as
        necessary.

        See the top-level class documentation.
        """
        if not args:
            super(LinResList, self).__init__([])

        elif isinstance(args[0], string_types):  # Filenames or directories
            try:
                fnames = multiglob(args)
            except TypeError:
                raise TypeError(
                    "The linearization list can only be initialized by "
                    "providing a list of LinRes instances or a series of "
                    "arguments, each of which is a filename or directory.")
            list.__init__(self, _get_lins(fnames))

        elif len(args) == 1:  # List or iterable of LinRes instances
            lins = list(args[0])
            for lin in lins:
                assert isinstance(lin, LinRes), ("All entries in the list must "
                                                 "be LinRes instances.")
            list.__init__(self, lins)

        else:
            raise TypeError(
                "The linearization list can only be initialized by "
                "providing a list of LinRes instances or a series of "
                "arguments, each of which is a filename or directory.")
def load(*args):
    """Load multiple Modelica_ simulation and/or linearization results.

    This function can be called with any number of arguments, each of which is
    a filename or directory with results to load.  The filenames or directory
    names may contain wildcards.  Each path must be absolute or resolved to the
    current directory.

    As many of the matching filenames will be loaded as possible.  No errors
    will be given for files that cannot be loaded.

    **Returns:**

    1. :class:`~simres.SimResList` of simulations

    2. :class:`~linres.LinResList` of linearizations

    Either may be an empty list.

    **Example:**

    .. code-block:: python

       # Get the mean values of the first capacitor's voltage from two runs of
       # the Chua circuit.
       >>> sims, __ = load('examples/ChuaCircuit/*/')
       >>> sims.sort()

       >>> sims['C1.v'].mean()
       [-1.6083468, 0.84736514]

       # The voltage is different because the inductance is different:
       >>> sims['L.L'].value()
       [15.0, 21.0]
    """
    from natu.util import multiglob

    # Get the set of matching filenames.
    fnames = multiglob(args)

    # Load the files and append each result onto the appropriate list.
    sims = SimResList()
    lins = LinResList()
    for fname in fnames:
        try:
            sims.append(SimRes(fname))
        except IOError:
            continue
        except (AssertionError, IndexError, KeyError, TypeError,
                ValueError):
            try:
                lins.append(LinRes(fname))
            except (AssertionError, IndexError, IOError, KeyError, TypeError,
                    ValueError):
                continue

    return sims, lins
Exemple #3
0
def load(*args):
    """Load multiple Modelica_ simulation and/or linearization results.

    This function can be called with any number of arguments, each of which is
    a filename or directory with results to load.  The filenames or directory
    names may contain wildcards.  Each path must be absolute or resolved to the
    current directory.

    As many of the matching filenames will be loaded as possible.  No errors
    will be given for files that cannot be loaded.

    **Returns:**

    1. :class:`~simres.SimResList` of simulations

    2. :class:`~linres.LinResList` of linearizations

    Either may be an empty list.

    **Example:**

    .. code-block:: python

       # Get the mean values of the first capacitor's voltage from two runs of
       # the Chua circuit.
       >>> sims, __ = load('examples/ChuaCircuit/*/')
       >>> sims.sort()

       >>> sims['C1.v'].mean()
       [-1.6083468, 0.84736514]

       # The voltage is different because the inductance is different:
       >>> sims['L.L'].value()
       [15.0, 21.0]
    """
    from natu.util import multiglob

    # Get the set of matching filenames.
    fnames = multiglob(args)

    # Load the files and append each result onto the appropriate list.
    sims = SimResList()
    lins = LinResList()
    for fname in fnames:
        try:
            sims.append(SimRes(fname))
        except IOError:
            continue
        except (AssertionError, IndexError, KeyError, TypeError, ValueError):
            try:
                lins.append(LinRes(fname))
            except (AssertionError, IndexError, IOError, KeyError, TypeError,
                    ValueError):
                continue

    return sims, lins
Exemple #4
0
    def append(self, item):
        """Add linearization(s) to the end of the list of linearizations.

        **Parameters:**

        - *item*: :class:`LinRes` instance or a file specification

             The file specification may be a filename or directory, possibly
             with wildcards a la `glob
             <https://docs.python.org/2/library/glob.html>`_, where
             linearization results can be loaded by :class:`LinRes`.  The
             filename or directory must include the absolute path or be resolved
             to the current directory.  An error is only raised if no files can
             be loaded.

         Unlike the `append
         <https://docs.python.org/2/tutorial/datastructures.html>`_ method of a
         standard Python_ list, this method may add more than one item.  If
         *item* is a directory or a wildcarded filename, it may match multiple
         valid files.

         Linearization results will be appended to the list even if they are
         already included.

        **Example:**

        >>> lins = LinResList('examples/PID/*/')
        >>> lins.append('examples/PID.mat')
        >>> print(lins) # doctest: +SKIP
        List of linearization results (LinRes instances) from the following files
        in the .../examples directory:
           PID/1/dslin.mat
           PID/2/dslin.mat
           PID.mat

        .. testcleanup::

           >>> lins.sort()
           >>> print(lins) # doctest: +ELLIPSIS
           List of linearization results (LinRes instances) from the following files
           in the .../examples directory:
              PID.mat
              PID/1/dslin.mat
              PID/2/dslin.mat
        """
        if isinstance(item, LinRes):
            list.append(self, item)
        else:
            assert isinstance(item, string_types), (
                "The linearization list can only be appended by providing a "
                "LinRes instance, filename, or directory.")
            fnames = multiglob(item)
            self.extend(LinResList(_get_lins(fnames)))
Exemple #5
0
def release():
    """Release/publish the documentation to the webpage.
    """
    # Save the current state.
    branch = git('rev-parse', '--abbrev-ref', 'HEAD').stdout.rstrip()
    git.stash('save', "Work in progress while updating gh-pages branch")

    # Check out the gh-pages branch.
    try:
        git.checkout('gh-pages')
    except ErrorReturnCode_128:  # Create the branch if necessary.
        git.checkout('-b', 'gh-pages')

    # Remove the existing files in the base folder.
    extensions = ['*.html', '*.inv']
    fnames = util.multiglob('..', extensions)
    for fname in fnames:
        os.remove(fname)

    # Copy the new files to the base folder.
    fnames = util.multiglob(BUILD_DIR, extensions)
    for fname in fnames:
        shutil.copy(fname, '..')

    # Track the new files.
    fnames = util.multiglob('..', extensions)
    git.add(*fnames)

    # Copy but rename the folders referenced in the HTML files.
    # Github only recognizes images, stylesheets, and javascripts as folders.
    folders = [('_images', 'images'),
               ('_static', 'javascripts'),
              ]
    for (src, dst) in folders:
        dst = os.path.join('..', dst)
        # Remove the existing folder.
        shutil.rmtree(dst, ignore_errors=True)
        # Copy the new folder.
        shutil.copytree(os.path.join(BUILD_DIR, src), dst)
        # Track the new folder.
        git.add(dst)
    # Update the HTML files to reference the new folder names.
    html_fnames = glob(os.path.join('..', '*.html'))
    util.replace(html_fnames, folders)

    # Copy and rename the examples folder.
    src = os.path.join(BUILD_DIR, 'examples')
    dst = '../examples2'
    # Remove the existing folder.
    shutil.rmtree(dst, ignore_errors=True)
    # Copy the new files.
    os.mkdir(dst)
    for fname in os.listdir(src):
        shutil.copy(os.path.join(src, fname), os.path.join(dst, fname))
    # Track the new folder.
    git.add(dst)
    # Update the HTML files to reference the new folder names.
    util.replace(html_fnames, [(r'"\./examples/', r'"./examples2/')])

    # Update the sitemap.
    print(python('sitemap_gen.py', config="sitemap_conf.xml"))

    # Commit the changes.
    try:
        git.commit('-a', m="Rebuilt documentation")
    except ErrorReturnCode_1:
        pass  # No changes to commit

    # If desired, rebase and push the changes to origin.
    print("The gh-pages branch has been updated and is currently checked out.")
    if util.yes("Do you want to rebase it and push the changes to "
                "origin (y/n)?"):
        git.rebase('-i', 'origin/gh-pages')
        git.push.origin('gh-pages')

    # Return to the original state.
    git.checkout(branch)
    try:
        git.stash.pop()
    except ErrorReturnCode_1:
        pass  # No stash was necessary in the first place.
    print("Now back on " + branch)
Exemple #6
0
def release():
    """Release/publish the documentation to the webpage.
    """
    # Save the current state.
    branch = git('rev-parse', '--abbrev-ref', 'HEAD').stdout.rstrip()
    git.stash('save', "Work in progress while updating gh-pages branch")

    # Check out the gh-pages branch.
    try:
        git.checkout('gh-pages')
    except ErrorReturnCode_128:  # Create the branch if necessary.
        git.checkout('-b', 'gh-pages')

    # Remove the existing files in the base folder.
    extensions = ['*.html', '*.inv']
    fnames = util.multiglob('..', extensions)
    for fname in fnames:
        os.remove(fname)

    # Copy the new files to the base folder.
    fnames = util.multiglob(BUILD_DIR, extensions)
    for fname in fnames:
        shutil.copy(fname, '..')

    # Track the new files.
    fnames = util.multiglob('..', extensions)
    git.add(*fnames)

    # Copy but rename the folders referenced in the HTML files.
    # Github only recognizes images, stylesheets, and javascripts as folders.
    folders = [
        ('_images', 'images'),
        ('_static', 'javascripts'),
    ]
    for (src, dst) in folders:
        dst = os.path.join('..', dst)
        # Remove the existing folder.
        shutil.rmtree(dst, ignore_errors=True)
        # Copy the new folder.
        shutil.copytree(os.path.join(BUILD_DIR, src), dst)
        # Track the new folder.
        git.add(dst)
    # Update the HTML files to reference the new folder names.
    html_fnames = glob(os.path.join('..', '*.html'))
    util.replace(html_fnames, folders)

    # Copy and rename the examples folder.
    src = os.path.join(BUILD_DIR, 'examples')
    dst = '../examples2'
    # Remove the existing folder.
    shutil.rmtree(dst, ignore_errors=True)
    # Copy the new files.
    os.mkdir(dst)
    for fname in os.listdir(src):
        shutil.copy(os.path.join(src, fname), os.path.join(dst, fname))
    # Track the new folder.
    git.add(dst)
    # Update the HTML files to reference the new folder names.
    util.replace(html_fnames, [(r'"\./examples/', r'"./examples2/')])

    # Update the sitemap.
    print((python('sitemap_gen.py', config="sitemap_conf.xml")))

    # Commit the changes.
    try:
        git.commit('-a', m="Rebuilt documentation")
    except ErrorReturnCode_1:
        pass  # No changes to commit

    # If desired, rebase and push the changes to origin.
    print("The gh-pages branch has been updated and is currently checked out.")
    if util.yes("Do you want to rebase it and push the changes to "
                "origin (y/n)?"):
        git.rebase('-i', 'origin/gh-pages')
        git.push.origin('gh-pages')

    # Return to the original state.
    git.checkout(branch)
    try:
        git.stash.pop()
    except ErrorReturnCode_1:
        pass  # No stash was necessary in the first place.
    print(("Now back on " + branch))