├── .hgignore ├── docs ├── requirements.rtd.txt ├── images │ ├── waves_spectrum.png │ └── waves_drift_ratios.png ├── pages │ ├── installation.rst │ └── getting_started.rst ├── Makefile ├── index.rst └── conf.py ├── eigentools ├── __init__.py ├── tools.py ├── criticalfinder.py └── eigenproblem.py ├── .gitignore ├── .github └── workflows │ └── build.yml ├── setup.py ├── CONTRIBUTING.md ├── tests ├── non_constant_test.py └── test_rbc_growth.py ├── README.md ├── examples ├── orr_sommerfeld.py ├── rayleigh_benard_2d.py └── mri.py └── license.txt /.hgignore: -------------------------------------------------------------------------------- 1 | # use glob syntax. 2 | syntax: glob 3 | *~ 4 | *__pycache__/* 5 | *.ipynb_checkpoints/* -------------------------------------------------------------------------------- /docs/requirements.rtd.txt: -------------------------------------------------------------------------------- 1 | setuptools >= 18.0 2 | sphinx-autoapi 3 | nbsphinx 4 | pygments>=2.4.1 5 | -------------------------------------------------------------------------------- /docs/images/waves_spectrum.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dpsanders/eigentools/master/docs/images/waves_spectrum.png -------------------------------------------------------------------------------- /docs/images/waves_drift_ratios.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dpsanders/eigentools/master/docs/images/waves_drift_ratios.png -------------------------------------------------------------------------------- /eigentools/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2016, Jeffrey S. Oishi & Susan E. Clark 2 | 3 | # This file is part of Dedalus, which is free software distributed 4 | # under the terms of the GPLv3 license. A copy of the license should 5 | # have been included in the file 'LICENSE.txt', and is also available 6 | # online at . 7 | 8 | from .eigenproblem import Eigenproblem 9 | from .criticalfinder import CriticalFinder 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # ipython 30 | .ipynb_checkpoints/ 31 | 32 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | pull_request: 5 | branches: [ master ] 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | container: dedalusproject/dedalus-conda 11 | steps: 12 | - uses: actions/checkout@v2 13 | with: 14 | ref: 'v2.0-refactor' 15 | - name: build 16 | run: /opt/conda/envs/dedalus/bin/pip install -e . 17 | 18 | - name: test 19 | run: /opt/conda/envs/dedalus/bin/pytest 20 | 21 | 22 | -------------------------------------------------------------------------------- /docs/pages/installation.rst: -------------------------------------------------------------------------------- 1 | Installing eigentools 2 | ********************* 3 | 4 | eigentools requires Dedalus, which you can install via any of the methods found in `the Dedalus installation instructions `_. 5 | 6 | Once Dedalus is installed, eigentools is `pip` installable:: 7 | 8 | pip install eigentools 9 | 10 | If you would like the development version, you can clone the repository and install locally:: 11 | 12 | git clone https://github.com/DedalusProject/eigentools.git 13 | pip install -e eigentools 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SPHINXPROJ = Eigentools 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="eigentools", 8 | version="2.2012", 9 | author="J. S. Oishi", 10 | author_email="jsoishi@gmail.com", 11 | description="A toolkit for solving eigenvalue problems with Dedalus", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/dedalusproject/eigentools", 15 | packages=setuptools.find_packages(), 16 | classifiers=[ 17 | "Programming Language :: Python :: 3", 18 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)" 19 | ], 20 | python_requires='>=3.5', 21 | ) 22 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Eigentools # 2 | 3 | We welcome contributions, including issue reports, bug fixes, and feature implementations. 4 | Contributions are reviewed on Github via pull request; to get started, fork the repository, make changes, and issue a pull request. 5 | You can also contribute by submitting an issue. 6 | 7 | ## Reporting issues ## 8 | 9 | If you find a bug or unexpected behavior, please file an issue report on [github](https://github.com/DedalusProject/eigentools/issues). 10 | Please provide as much detail as possible, including version of both eigentools and dedalus, platform (Mac/Linux), and a stand alone `.py` file that demonstrates the problem in as simple a manner as possible. 11 | 12 | ## Proposing features ## 13 | 14 | You can propose new features on the issue tracker using the "enhancement" tag. 15 | 16 | ## Contributing code ## 17 | 18 | Code contributions ranging from fixing typos to implementing additional features are most welcome! We use [pull requests](https://github.com/DedalusProject/eigentools/pulls) to integrate contributions into the main codebase. If you would like to contribute and are looking for a place to start, please don't hesitate to contact the authors (emails are in [readme.md](readme.md)). 19 | 20 | -------------------------------------------------------------------------------- /eigentools/tools.py: -------------------------------------------------------------------------------- 1 | import dedalus.public as de 2 | 3 | # these are the currently supported dedalus eigenvalue bases 4 | bases_register = {"Chebyshev": de.Chebyshev, "Fourier": de.Fourier, "Legendre": de.Legendre} 5 | 6 | def update_EVP_params(EVP, key, value): 7 | # Dedalus workaround: must change values in two places 8 | vv = EVP.namespace[key] 9 | vv.value = value 10 | EVP.parameters[key] = value 11 | 12 | def basis_from_basis(basis, factor): 13 | """duplicates input basis with number of modes multiplied by input factor. 14 | 15 | the new number of modes will be cast to an integer 16 | 17 | inputs 18 | ------ 19 | basis : a dedalus basis 20 | factor : a float that will multiply the grid size by basis 21 | 22 | """ 23 | basis_type = basis.__class__.__name__ 24 | n_hi = int(basis.base_grid_size*factor) 25 | 26 | if type(basis) == de.Compound: 27 | sub_bases = [] 28 | for sub_basis in basis.subbases: 29 | sub_basis_type = sub_basis.__class__.__name__ 30 | try: 31 | nb = bases_register[sub_basis_type](basis.name, n_hi, interval=sub_basis.interval) 32 | except KeyError: 33 | raise KeyError("Don't know how to make a basis of type {}".format(basis_type)) 34 | sub_bases.append(nb) 35 | new_basis = de.Compound(basis.name, tuple(sub_bases)) 36 | else: 37 | try: 38 | new_basis = bases_register[basis_type](basis.name, n_hi, interval=basis.interval) 39 | except KeyError: 40 | raise KeyError("Don't know how to make a basis of type {}".format(basis_type)) 41 | 42 | return new_basis 43 | -------------------------------------------------------------------------------- /tests/non_constant_test.py: -------------------------------------------------------------------------------- 1 | """test problem for eigentools for non-constant coefficients: 2 | 3 | problem from equation 26 of 4 | 5 | Huang, Chen, and Luo, Applied Mathematics Letters (2013) 6 | https://www.sciencedirect.com/science/article/pii/S0893965913000748 7 | 8 | y''''(x) - 0.02 x^2 y'' - 0.04 x y' + (0.0001 x^4 - 0.02) y = lambda y 9 | 10 | with boundary conditions 11 | 12 | y(0) = y(5) = y'(0) = y'(5) = 0 13 | 14 | this is their Case 1 15 | 16 | NB: I corrected a typo 17 | 18 | Table 3 from that paper gives 19 | 0.86690250239956 20 | 6.35768644786998 21 | 23.99274694653769 22 | 64.97869559403952 23 | 144.2841396045761 24 | 25 | NB: THIS IS NOT A HIGH PRECISION TEST! It's unclear from the reference what the "true" values actually are. We agree much more closely with their reference 14, but I'm not sure if that is a more trustworthy calculation anyway. 26 | 27 | """ 28 | import pytest 29 | import numpy as np 30 | import dedalus.public as de 31 | from eigentools import Eigenproblem, CriticalFinder 32 | 33 | @pytest.mark.parametrize('Nx', [60]) 34 | @pytest.mark.parametrize('sparse', [False]) 35 | @pytest.mark.parametrize('ordinal', [False, True]) 36 | def test_non_constant(Nx, sparse, ordinal): 37 | x = de.Chebyshev('x',Nx,interval=(0,5)) 38 | d = de.Domain([x,]) 39 | 40 | prob = de.EVP(d,['y','yx','yxx','yxxx'],'sigma') 41 | 42 | prob.add_equation("dx(yxxx) -0.02*x*x*yxx -0.04*x*yx + (0.0001*x*x*x*x - 0.02)*y - sigma*y = 0") 43 | prob.add_equation("dx(yxx) - yxxx = 0") 44 | prob.add_equation("dx(yx) - yxx = 0") 45 | prob.add_equation("dx(y) - yx = 0") 46 | 47 | prob.add_bc("left(y) = 0") 48 | prob.add_bc("right(y) = 0") 49 | prob.add_bc("left(yx) = 0") 50 | prob.add_bc("right(yx) = 0") 51 | 52 | EP = Eigenproblem(prob, use_ordinal=ordinal) 53 | 54 | EP.solve(sparse=sparse) 55 | indx = EP.evalues_good.argsort() 56 | 57 | five_evals = EP.evalues_good[indx][0:5] 58 | print("First five good eigenvalues are: ") 59 | print(five_evals) 60 | print(five_evals[-1]) 61 | 62 | reference = np.array([0.86690250239956+0j, 6.35768644786998+0j, 23.99274694653769+0j, 64.97869559403952+0j, 144.2841396045761+0j]) 63 | 64 | assert np.allclose(reference, five_evals,rtol=1e-4) 65 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Eigentools 2 | 3 | Eigentools is a set of tools for studying linear eigenvalue problems. The underlying eigenproblems are solved using [Dedalus](http://dedalus-project.org), which provides a domain-specific language for partial differential equations. Eigentools extends Dedalus's `EigenvalueProblem` object and provides 4 | 5 | * automatic rejection of unresolved eigenvalues 6 | * simple plotting of specified eigenmodes 7 | * simple plotting of spectra 8 | * computation of pseudospectra for any Differential-Algebraic Equations with **user-specifiable norms** 9 | * tools to find critical parameters for linear stability analysis 10 | * ability to project eigenmode onto 2- or 3-D domain for visualization 11 | * ability to output projected eigenmodes as Dedalus-formatted HDF5 file to be used as initial conditions for Initial Value Problems 12 | * simple plotting of drift ratios (both ordinal and nearest) to evaluate tolerance for eigenvalue rejection 13 | 14 | ## Installation 15 | 16 | Eigentools can be `pip` installed, though it requires [Dedalus](http://dedalus-project.org/), which has non-`pip` installable dependencies. See the [installation instructions](https://eigentools.readthedocs.io/en/latest/pages/installation.html) for details. 17 | 18 | ## Documentation 19 | 20 | Documentation (including detailed API documentation) can be found at [Read the Docs](https://eigentools.readthedocs.io/). 21 | 22 | ## Contributing 23 | 24 | Eigentools welcomes community contributions from issue reports to code contributions. For details, please see [our contribution policy](CONTRIBUTING.md). 25 | 26 | ## Developers 27 | The core development team consists of 28 | 29 | * Jeff Oishi () 30 | * Keaton Burns () 31 | * Susan Clark () 32 | * Evan Anders () 33 | * Ben Brown () 34 | * Geoff Vasil () 35 | * Daniel Lecoanet () 36 | 37 | ## Support 38 | Eigentools was developed with support from the Research Corporation under award Scialog Collaborative Award (TDA) ID# 24231. 39 | 40 | 41 | 43 | 45 | 47 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Eigentools 2 | ********** 3 | 4 | Eigentools is a set of tools for studying linear eigenvalue problems. The underlying eigenproblems are solved using `Dedalus `_, which provides a domain-specific language for partial differential equations. Each entry in the following list of features links to a Jupyter notebook giving an example of its use. 5 | 6 | * :ref:`automatic rejection of unresolved eigenvalues ` 7 | * :ref:`simple plotting of drift ratios (both ordinal and nearest) to evaluate tolerance for eigenvalue rejection ` 8 | 9 | * :ref:`simple plotting of specified eigenmodes ` 10 | * :ref:`simple plotting of spectra ` 11 | * :ref:`computation of pseudospectra for any Differential-Algebraic Equations ` with :ref:`user-specifiable norms ` 12 | * :ref:`tools to find critical parameters for linear stability analysis ` with :ref:`user-specifiable definitions of growth and stability ` 13 | * :ref:`ability to project eigenmode onto 2- or 3-D domain for visualization ` 14 | * :ref:`ability to output projected eigenmodes as Dedalus-formatted HDF5 file to be used as initial conditions for Initial Value Problems ` 15 | 16 | Contents 17 | ======== 18 | 19 | .. toctree:: 20 | :maxdepth: 2 21 | 22 | pages/installation 23 | pages/getting_started 24 | 25 | Example notebooks 26 | ----------------- 27 | 28 | .. toctree:: 29 | :maxdepth: 1 30 | 31 | Example 1: Orr-Somerfield pseudospectra 32 | Example 2: Mixed Layer instability 33 | 34 | API reference 35 | ------------- 36 | 37 | .. toctree:: 38 | :maxdepth: 2 39 | 40 | Eigentools API reference 41 | 42 | Developers 43 | ========== 44 | The core development team consists of 45 | 46 | * Jeff Oishi () 47 | * Keaton Burns () 48 | * Susan Clark () 49 | * Evan Anders () 50 | * Ben Brown () 51 | * Geoff Vasil () 52 | * Daniel Lecoanet () 53 | 54 | Support 55 | ======= 56 | Eigentools was developed with support from the Research Corporation under award Scialog Collaborative Award (TDA) ID# 24231. 57 | 58 | -------------------------------------------------------------------------------- /examples/orr_sommerfeld.py: -------------------------------------------------------------------------------- 1 | """finds the critical Renoylds number, wave number, and frequency for the 2 | Orr-Somerfeld eigenvalue equation. 3 | 4 | NB: This formulation uses a slightly different scaling of the eigenvalue than Orszag (1971). In order to convert, use 5 | 6 | sigma = -1j*alpha*Re*lambda, 7 | 8 | where sigma is our eigenvalue and Lambda is Orszag's. 9 | 10 | """ 11 | import matplotlib 12 | matplotlib.use('Agg') 13 | from mpi4py import MPI 14 | from eigentools import Eigenproblem, CriticalFinder 15 | import time 16 | import dedalus.public as de 17 | import numpy as np 18 | import matplotlib.pylab as plt 19 | import sys 20 | import logging 21 | logger = logging.getLogger(__name__.split('.')[-1]) 22 | 23 | file_name = sys.argv[0].strip('.py') 24 | comm = MPI.COMM_WORLD 25 | 26 | 27 | # Define the Orr-Somerfeld problem in Dedalus: 28 | 29 | z = de.Chebyshev('z',50) 30 | d = de.Domain([z],comm=MPI.COMM_SELF) 31 | 32 | orr_somerfeld = de.EVP(d,['w','wz','wzz','wzzz'],'sigma') 33 | orr_somerfeld.parameters['alpha'] = 1. 34 | orr_somerfeld.parameters['Re'] = 10000. 35 | 36 | orr_somerfeld.add_equation('dz(wzzz) - 2*alpha**2*wzz + alpha**4*w - sigma*(wzz-alpha**2*w)-1j*alpha*(Re*(1-z**2)*(wzz-alpha**2*w) + 2*Re*w) = 0 ') 37 | orr_somerfeld.add_equation('dz(w)-wz = 0') 38 | orr_somerfeld.add_equation('dz(wz)-wzz = 0') 39 | orr_somerfeld.add_equation('dz(wzz)-wzzz = 0') 40 | 41 | orr_somerfeld.add_bc('left(w) = 0') 42 | orr_somerfeld.add_bc('right(w) = 0') 43 | orr_somerfeld.add_bc('left(wz) = 0') 44 | orr_somerfeld.add_bc('right(wz) = 0') 45 | 46 | # create an Eigenproblem object 47 | EP = Eigenproblem(orr_somerfeld) 48 | 49 | # create a shim function to translate (x, y) to the parameters for the eigenvalue problem: 50 | 51 | cf = CriticalFinder(EP,("alpha", "Re"), comm, find_freq=True) 52 | 53 | # generating the grid is the longest part 54 | start = time.time() 55 | nx = 20 56 | ny = 20 57 | xpoints = np.linspace(1.0, 1.1, nx) 58 | ypoints = np.linspace(5500, 6000, ny) 59 | try: 60 | cf.load_grid('{}.h5'.format(file_name)) 61 | except: 62 | cf.grid_generator((xpoints, ypoints), sparse=True) 63 | if comm.rank == 0: 64 | cf.save_grid(file_name) 65 | end = time.time() 66 | if comm.rank == 0: 67 | logger.info("grid generation time: {:10.5f} sec".format(end-start)) 68 | 69 | crit = cf.crit_finder(polish_roots=True, tol=1e-5, method='Nelder-Mead') 70 | 71 | Re_orszag = 5772.22 72 | alpha_orszag = 1.02056 73 | omega_orszag = -1555.2070 74 | 75 | if comm.rank == 0: 76 | alpha = crit[0] 77 | Re = crit[1] 78 | omega = crit[2] 79 | 80 | Re_err = (Re-Re_orszag)/Re_orszag 81 | alpha_err = (alpha-alpha_orszag)/alpha_orszag 82 | L2 = np.sqrt((Re-Re_orszag)**2 + (alpha-alpha_orszag)**2) 83 | logger.info("critical wavenumber alpha = {:10.5f}".format(alpha)) 84 | logger.info("critical Re = {:10.5f}".format(Re)) 85 | logger.info("critical omega = {:10.5f}".format(omega)) 86 | logger.info("critical Re error = {:10.5e}".format(Re_err)) 87 | logger.info("critical alpha error = {:10.5}".format(alpha_err)) 88 | logger.info("L2 norm from Orszag 71 solution = {:10.5e}".format(L2)) 89 | 90 | cf.save_grid('orr_sommerfeld_growth_rates') 91 | cf.plot_crit() 92 | 93 | -------------------------------------------------------------------------------- /docs/pages/getting_started.rst: -------------------------------------------------------------------------------- 1 | Getting Started 2 | *************** 3 | 4 | eigentools comes with several `examples `_ to get you started, but let's outline some basics in a very simple problem, the 1-D wave equation with :math:`u = 0` at both ends. 5 | This is not quite as trivial a problem as it might seem, because we are expanding the solution in Chebyshev polynomials, but the eigenmodes are sines and cosines. 6 | 7 | 8 | .. code-block:: python 9 | 10 | from eigentools import Eigenproblem 11 | import dedalus.public as de 12 | 13 | Nx = 128 14 | x = de.Chebyshev('x',Nx, interval=(-1, 1)) 15 | d = de.Domain([x]) 16 | 17 | string = de.EVP(d, ['u','u_x'], eigenvalue='omega') 18 | string.add_equation("omega*u + dx(u_x) = 0") 19 | string.add_equation("u_x - dx(u) = 0") 20 | string.add_bc("left(u) = 0") 21 | string.add_bc("right(u) = 0") 22 | 23 | EP = Eigenproblem(string) 24 | EP.solve(sparse=False) 25 | ax = EP.plot_spectrum() 26 | print("there are {} good eigenvalues.".format(len(EP.evalues))) 27 | ax.set_ylim(-1,1) 28 | ax.figure.savefig('waves_spectrum.png') 29 | 30 | ax = EP.plot_drift_ratios() 31 | ax.figure.savefig('waves_drift_ratios.png') 32 | 33 | That code takes about 10 seconds to run on a 2020 Core-i7 laptop, produces about 68 "good" eigenvalues, and produces the following output: 34 | 35 | .. image:: ../images/waves_spectrum.png 36 | :width: 400 37 | :alt: A spectrum for waves on a string 38 | 39 | eigentools has taken a Dedalus eigenvalue problem, automatically run it at 1.5 times the specified resolution, rejected any eigenvalues that do not agree to a default precision of one part in :math:`10^{-6}` and plotted a spectrum in six extra lines of code! 40 | 41 | Most of the plotting functions in eigentools return a `matplotlib` `axes` object, making it easy to modify the plot defaults. 42 | Here, we set the y-limits manually, because the eigenvalues of a string are real. 43 | Try removing the `ax.set_ylim(-1,1)` line and see what happens. 44 | 45 | Mode Rejection 46 | -------------- 47 | One of the most important tasks eigentools performs is spurious mode rejection. It does so by computing the "drift ratio" [Boyd2000]_ between the eigenvalues at the given resolution and a higher resolution problem that eigentools automatically assembles. By default, the "high" resolution case is 1.5 times the given resolution, though this is user configurable via the `factor` keyword option to `Eigenproblem()`. 48 | 49 | The drift ratio :math:`\delta` is calculated using either the **ordinal** (e.g. first mode of low resolution to first mode of high resolution) or **nearest** (mode with smallest difference between a given high mode and all low modes). In order to visualize this, `EP.plot_drift_ratios()` in the above code returns an `axes` object making a plot of the *inverse drift ratio* (:math:`1/\delta`), 50 | 51 | .. image:: ../images/waves_drift_ratios.png 52 | :width: 400 53 | :alt: Plot of inverse drift ratios vs. mode number for waves on a string. 54 | 55 | Good modes are those *above* the horizontal line at :math:`10^{6}`; bad modes are also grayed out. In this case, the **nearest** and **ordinal** methods produce identical results. If the problem contains more than one wave *family*, **nearest** typically fails. For an example, see the `MRI example script `_. Note that **nearest** is the default criterion used by eigentools. 56 | 57 | 58 | .. [Boyd2000] Boyd, J (2000). "Chebyshev and Fourier Spectral Methods." Dover. ``_ 59 | -------------------------------------------------------------------------------- /tests/test_rbc_growth.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import dedalus.public as de 3 | import eigentools as eig 4 | import numpy as np 5 | from mpi4py import MPI 6 | 7 | def rbc_problem(problem_type, domain, stress_free=False): 8 | problems = {'EVP': de.EVP, 'IVP': de.IVP} 9 | 10 | try: 11 | args = [domain,['p', 'b', 'u', 'w', 'bz', 'uz', 'wz']] 12 | if problem_type == 'EVP': 13 | args.append('omega') 14 | rayleigh_benard = problems[problem_type](*args) 15 | except KeyError: 16 | raise ValueError("problem_type must be one of 'EVP' or 'IVP', not {}".format(problem)) 17 | 18 | rayleigh_benard.parameters['k'] = 3.117 #horizontal wavenumber 19 | rayleigh_benard.parameters['Ra'] = 1708. #Rayleigh number, rigid-rigid 20 | rayleigh_benard.parameters['Pr'] = 1 #Prandtl number 21 | rayleigh_benard.parameters['dzT0'] = 1 22 | if problem_type == 'EVP': 23 | rayleigh_benard.substitutions['dt(A)'] = 'omega*A' 24 | rayleigh_benard.substitutions['dx(A)'] = '1j*k*A' 25 | 26 | rayleigh_benard.add_equation("dx(u) + wz = 0") 27 | rayleigh_benard.add_equation("dt(u) - Pr*(dx(dx(u)) + dz(uz)) + dx(p) = -u*dx(u) - w*uz") 28 | rayleigh_benard.add_equation("dt(w) - Pr*(dx(dx(w)) + dz(wz)) + dz(p) - Ra*Pr*b = -u*dx(w) - w*wz") 29 | rayleigh_benard.add_equation("dt(b) - w*dzT0 - (dx(dx(b)) + dz(bz)) = -u*dx(b) - w*bz") 30 | rayleigh_benard.add_equation("dz(u) - uz = 0") 31 | rayleigh_benard.add_equation("dz(w) - wz = 0") 32 | rayleigh_benard.add_equation("dz(b) - bz = 0") 33 | rayleigh_benard.add_bc('left(b) = 0') 34 | rayleigh_benard.add_bc('right(b) = 0') 35 | rayleigh_benard.add_bc('left(w) = 0') 36 | rayleigh_benard.add_bc('right(w) = 0') 37 | if stress_free: 38 | rayleigh_benard.add_bc('left(uz) = 0') 39 | rayleigh_benard.add_bc('right(uz) = 0') 40 | else: 41 | rayleigh_benard.add_bc('left(u) = 0') 42 | rayleigh_benard.add_bc('right(u) = 0') 43 | 44 | return rayleigh_benard 45 | 46 | @pytest.mark.parametrize('z', [de.Chebyshev('z',16, interval=(0, 1)), de.Compound('z',(de.Chebyshev('z',10, interval=(0, 0.5)),de.Chebyshev('z',10, interval=(0.5, 1))))]) 47 | @pytest.mark.parametrize('sparse', [True, False]) 48 | def test_rbc_growth(z, sparse): 49 | d = de.Domain([z]) 50 | 51 | rayleigh_benard = rbc_problem('EVP',d) 52 | 53 | EP = eig.Eigenproblem(rayleigh_benard) 54 | 55 | growth, index, freq = EP.growth_rate(sparse=sparse) 56 | assert np.allclose((growth, freq), (0.0018125573647729994,0.)) 57 | 58 | @pytest.mark.parametrize('z', [de.Chebyshev('z',16, interval=(0, 1))]) 59 | def test_rbc_output(z): 60 | d = de.Domain([z]) 61 | rb_evp = rbc_problem('EVP',d) 62 | EP = eig.Eigenproblem(rb_evp) 63 | 64 | growth, index, freq = EP.growth_rate(sparse=False) 65 | 66 | x = de.Fourier('x', 32) 67 | ivp_domain = de.Domain([x,z],grid_dtype=np.float64) 68 | 69 | fields = EP.project_mode(index, ivp_domain, [1,]) 70 | EP.write_global_domain(fields) 71 | 72 | rb_IVP = rbc_problem('IVP', ivp_domain) 73 | solver = rb_IVP.build_solver(de.timesteppers.RK222) 74 | solver.load_state("IVP_output/IVP_output_s1.h5",-1) 75 | 76 | @pytest.mark.parametrize('z', [de.Chebyshev('z',16, interval=(0, 1))]) 77 | def test_rbc_crit_find(z): 78 | d = de.Domain([z], comm=MPI.COMM_SELF) 79 | rb_evp = rbc_problem('EVP', d, stress_free=True) 80 | EP = eig.Eigenproblem(rb_evp) 81 | comm = MPI.COMM_WORLD 82 | cf = eig.CriticalFinder(EP, ("k", "Ra"), comm, find_freq=True) 83 | 84 | nx = 10 85 | ny = 10 86 | xpoints = np.linspace(2, 2.4, nx) 87 | ypoints = np.linspace(550, 700, ny) 88 | 89 | cf.grid_generator((xpoints, ypoints),sparse=True) 90 | crit = cf.crit_finder(polish_roots=True, tol=1e-6, method='Powell') 91 | 92 | Rac = 27*np.pi**4/4. 93 | kc = 2*np.pi/2**1.5 94 | 95 | assert np.allclose(crit, [kc, Rac, 0.], rtol=1e-5) 96 | -------------------------------------------------------------------------------- /examples/rayleigh_benard_2d.py: -------------------------------------------------------------------------------- 1 | """ 2 | Finds the critical Rayleigh number and wavenumber for the 2-dimensional, 3 | incompressible, Boussinesq Navier-Stokes equations in order to determine 4 | the onset of convection in such a system. 5 | """ 6 | import matplotlib 7 | matplotlib.use('Agg') 8 | from mpi4py import MPI 9 | from eigentools import Eigenproblem, CriticalFinder 10 | import time 11 | import dedalus.public as de 12 | import numpy as np 13 | import sys 14 | import logging 15 | 16 | logger = logging.getLogger(__name__.split('.')[-1]) 17 | 18 | 19 | comm = MPI.COMM_WORLD 20 | 21 | 22 | no_slip = False 23 | stress_free = True 24 | file_name = sys.argv[0].strip('.py') 25 | if no_slip: 26 | file_name += '_no_slip' 27 | elif stress_free: 28 | file_name += '_stress_free' 29 | 30 | Nz = 16 31 | z = de.Chebyshev('z',Nz, interval=(0, 1)) 32 | d = de.Domain([z],comm=MPI.COMM_SELF) 33 | 34 | rayleigh_benard = de.EVP(d,['p', 'b', 'u', 'w', 'bz', 'uz', 'wz'], eigenvalue='omega') 35 | rayleigh_benard.parameters['k'] = 3.117 #horizontal wavenumber 36 | rayleigh_benard.parameters['Ra'] = 1708. #Rayleigh number, rigid-rigid 37 | rayleigh_benard.parameters['Pr'] = 1 #Prandtl number 38 | rayleigh_benard.parameters['dzT0'] = 1 39 | rayleigh_benard.substitutions['dt(A)'] = 'omega*A' 40 | rayleigh_benard.substitutions['dx(A)'] = '1j*k*A' 41 | 42 | #Boussinesq eqns -- nondimensionalized on thermal diffusion timescale 43 | #Incompressibility 44 | rayleigh_benard.add_equation("dx(u) + wz = 0") 45 | #Momentum eqns 46 | rayleigh_benard.add_equation("dt(u) - Pr*(dx(dx(u)) + dz(uz)) + dx(p) = -u*dx(u) - w*uz") 47 | rayleigh_benard.add_equation("dt(w) - Pr*(dx(dx(w)) + dz(wz)) + dz(p) - Ra*Pr*b = -u*dx(w) - w*wz") 48 | #Temp eqn 49 | rayleigh_benard.add_equation("dt(b) - w*dzT0 - (dx(dx(b)) + dz(bz)) = -u*dx(b) - w*bz") 50 | #Derivative defns 51 | rayleigh_benard.add_equation("dz(u) - uz = 0") 52 | rayleigh_benard.add_equation("dz(w) - wz = 0") 53 | rayleigh_benard.add_equation("dz(b) - bz = 0") 54 | 55 | 56 | 57 | #fixed temperature 58 | rayleigh_benard.add_bc('left(b) = 0') 59 | rayleigh_benard.add_bc('right(b) = 0') 60 | #Impenetrable 61 | rayleigh_benard.add_bc('left(w) = 0') 62 | rayleigh_benard.add_bc('right(w) = 0') 63 | 64 | 65 | if no_slip: 66 | rayleigh_benard.add_bc('left(u) = 0') 67 | rayleigh_benard.add_bc('right(u) = 0') 68 | elif stress_free: 69 | rayleigh_benard.add_bc('left(uz) = 0') 70 | rayleigh_benard.add_bc('right(uz) = 0') 71 | 72 | # create an Eigenproblem object 73 | EP = Eigenproblem(rayleigh_benard) 74 | 75 | cf = CriticalFinder(EP, ("k","Ra"), comm, find_freq = True) 76 | 77 | # generating the grid is the longest part 78 | start = time.time() 79 | if no_slip: 80 | nx = 20 81 | ny = 20 82 | xpoints = np.linspace(2, 4, ny) 83 | ypoints = np.linspace(1000, 3000, nx) 84 | elif stress_free: 85 | #657.5, 2.221 86 | nx = 10 87 | ny = 10 88 | xpoints = np.linspace(2, 2.4, ny) 89 | ypoints = np.linspace(550, 700, nx) 90 | 91 | try: 92 | cf.load_grid('{}.h5'.format(file_name)) 93 | except: 94 | cf.grid_generator((xpoints, ypoints), sparse=True) 95 | cf.save_grid(file_name) 96 | 97 | end = time.time() 98 | if comm.rank == 0: 99 | logger.info("grid generation time: {:10.5f} sec".format(end-start)) 100 | 101 | logger.info("Beginning critical finding with root polishing...") 102 | begin = time.time() 103 | crit = cf.crit_finder(polish_roots=True, tol=1e-5) 104 | end = time.time() 105 | logger.info("critical finding/root polishing time: {:10.5f} sec".format(end-start)) 106 | 107 | if comm.rank == 0: 108 | print("crit = {}".format(crit)) 109 | print("critical wavenumber k = {:10.5f}".format(crit[0])) 110 | print("critical Ra = {:10.5f}".format(crit[1])) 111 | print("critical freq = {:10.5f}".format(crit[2])) 112 | 113 | pax, cax = cf.plot_crit(xlabel=r'$k_x$', ylabel=r'$\mathrm{Ra}$') 114 | pax.figure.savefig("rayleigh_benard_2d_growth_rates.png",dpi=300) 115 | -------------------------------------------------------------------------------- /examples/mri.py: -------------------------------------------------------------------------------- 1 | """ 2 | finds the critical magnetic Renoylds number and wave number for the magnetorotational instability (MRI). 3 | 4 | This script can be run in parallel by using 5 | 6 | $ mpirun -np 4 python3 mri.py 7 | 8 | It will parallelize over the grid generation portion and save that 9 | 10 | """ 11 | import sys 12 | from mpi4py import MPI 13 | from eigentools import Eigenproblem, CriticalFinder 14 | import time 15 | import dedalus.public as de 16 | import numpy as np 17 | import matplotlib.pylab as plt 18 | 19 | import logging 20 | 21 | logger = logging.getLogger(__name__.split('.')[-1]) 22 | 23 | comm = MPI.COMM_WORLD 24 | 25 | 26 | # Define the MRI problem in Dedalus: 27 | 28 | x = de.Chebyshev('x',64) 29 | d = de.Domain([x],comm=MPI.COMM_SELF) 30 | 31 | mri = de.EVP(d,['psi','u', 'A', 'B', 'psix', 'psixx', 'psixxx', 'ux', 'Ax', 'Bx'],'sigma') 32 | 33 | 34 | Rm = 4.879 35 | Pm = 0.001 36 | mri.parameters['q'] = 1.5 37 | mri.parameters['beta'] = 25.0 38 | mri.parameters['iR'] = Pm/Rm 39 | mri.parameters['Rm'] = Rm 40 | mri.parameters['Q'] = 0.748 41 | mri.substitutions['iRm'] = '1/Rm' 42 | 43 | mri.add_equation("sigma*psixx - Q**2*sigma*psi - iR*dx(psixxx) + 2*iR*Q**2*psixx - iR*Q**4*psi - 2*1j*Q*u - (2/beta)*1j*Q*dx(Ax) + (2/beta)*Q**3*1j*A = 0") 44 | mri.add_equation("sigma*u - iR*dx(ux) + iR*Q**2*u - (q - 2)*1j*Q*psi - (2/beta)*1j*Q*B = 0") 45 | mri.add_equation("sigma*A - iRm*dx(Ax) + iRm*Q**2*A - 1j*Q*psi = 0") 46 | mri.add_equation("sigma*B - iRm*dx(Bx) + iRm*Q**2*B - 1j*Q*u + q*1j*Q*A = 0") 47 | 48 | mri.add_equation("dx(psi) - psix = 0") 49 | mri.add_equation("dx(psix) - psixx = 0") 50 | mri.add_equation("dx(psixx) - psixxx = 0") 51 | mri.add_equation("dx(u) - ux = 0") 52 | mri.add_equation("dx(A) - Ax = 0") 53 | mri.add_equation("dx(B) - Bx = 0") 54 | 55 | mri.add_bc("left(u) = 0") 56 | mri.add_bc("right(u) = 0") 57 | mri.add_bc("left(psi) = 0") 58 | mri.add_bc("right(psi) = 0") 59 | mri.add_bc("left(A) = 0") 60 | mri.add_bc("right(A) = 0") 61 | mri.add_bc("left(psix) = 0") 62 | mri.add_bc("right(psix) = 0") 63 | mri.add_bc("left(Bx) = 0") 64 | mri.add_bc("right(Bx) = 0") 65 | 66 | # create an Eigenproblem object 67 | EP = Eigenproblem(mri) 68 | 69 | cf = CriticalFinder(EP, ("Q", "Rm"), comm, find_freq=False) 70 | 71 | # generating the grid is the longest part 72 | nx = 20 73 | ny = 20 74 | xpoints = np.linspace(0.5, 1.5, nx) 75 | ypoints = np.linspace(4.6, 5.5, ny) 76 | 77 | file_name = 'mri_growth_rate' 78 | try: 79 | cf.load_grid('{}.h5'.format(file_name)) 80 | except: 81 | start = time.time() 82 | cf.grid_generator((xpoints, ypoints), sparse=True) 83 | end = time.time() 84 | 85 | if comm.rank == 0: 86 | cf.save_grid(file_name) 87 | logger.info("grid generation time: {:10.5f} sec".format(end-start)) 88 | 89 | crit = cf.crit_finder(polish_roots=False) 90 | 91 | if comm.rank == 0: 92 | logger.info("critical Rm = {:10.5f}, Q = {:10.5f}".format(crit[1], crit[0])) 93 | # create plot of critical parameter space 94 | pax,cax = cf.plot_crit() 95 | fig = pax.figure 96 | # add an interpolated critical line 97 | x_lim = cf.parameter_grids[0][0,np.isfinite(cf.roots)] 98 | x_hires = np.linspace(x_lim[0], x_lim[-1], 100) 99 | pax.plot(x_hires, cf.root_fn(x_hires), color='k') 100 | fig.savefig('{}.png'.format(file_name), dpi=300) 101 | 102 | # plot the spectrum for the critical mode 103 | logger.info("solving dense eigenvalue problem for critical parameters") 104 | EP.solve(parameters = {"Q": crit[0], "Rm": crit[1]}, sparse=False) 105 | ax = EP.plot_spectrum() 106 | 107 | # mark critical mode 108 | eps = 1e-2 109 | mask = np.abs(EP.evalues.real) < eps 110 | ax.scatter(EP.evalues[mask].real, EP.evalues[mask].imag, c='red') 111 | ax.figure.savefig('mri_critical_spectrum.png', dpi=300) 112 | 113 | # plot drift ratio for critical mode 114 | ax = EP.plot_drift_ratios() 115 | ax.figure.savefig('mri_critical_drift_ratios.png', dpi=300) 116 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Configuration file for the Sphinx documentation builder. 4 | # 5 | # This file does only contain a selection of the most common options. For a 6 | # full list see the documentation: 7 | # http://www.sphinx-doc.org/en/master/config 8 | 9 | # -- Path setup -------------------------------------------------------------- 10 | 11 | # If extensions (or modules to document with autodoc) are in another directory, 12 | # add these directories to sys.path here. If the directory is relative to the 13 | # documentation root, use os.path.abspath to make it absolute, like shown here. 14 | # 15 | # import os 16 | # import sys 17 | # sys.path.insert(0, os.path.abspath('.')) 18 | 19 | 20 | # -- Project information ----------------------------------------------------- 21 | 22 | project = 'Eigentools' 23 | copyright = '2020 Dedalus Collaboration' 24 | author = 'Dedalus Collaboration' 25 | 26 | # The short X.Y version 27 | version = '' 28 | # The full version, including alpha/beta/rc tags 29 | release = '' 30 | 31 | 32 | # -- General configuration --------------------------------------------------- 33 | 34 | # If your documentation needs a minimal Sphinx version, state it here. 35 | # 36 | # needs_sphinx = '1.0' 37 | 38 | # Add any Sphinx extension module names here, as strings. They can be 39 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 40 | # ones. 41 | extensions = [] 42 | extensions += ['sphinx.ext.mathjax'] 43 | extensions += ['autoapi.extension'] 44 | extensions += ['sphinx.ext.viewcode'] 45 | extensions += ['sphinx.ext.napoleon'] 46 | extensions += ['nbsphinx'] 47 | 48 | add_module_names = False 49 | autoapi_type = 'python' 50 | autoapi_dirs = ['../eigentools'] 51 | autoapi_file_patterns = ['*.py'] 52 | autoapi_options = ['members', 'undoc-members'] 53 | autoapi_python_class_content = 'both' 54 | autoapi_add_toctree_entry = False 55 | 56 | napoleon_use_param = False 57 | napoleon_use_keyword = False 58 | napoleon_use_ivar = True 59 | 60 | # Add any paths that contain templates here, relative to this directory. 61 | templates_path = ['_templates'] 62 | 63 | # The suffix(es) of source filenames. 64 | # You can specify multiple suffix as a list of string: 65 | # 66 | # source_suffix = ['.rst', '.md'] 67 | source_suffix = '.rst' 68 | 69 | # The master toctree document. 70 | master_doc = 'index' 71 | 72 | # The language for content autogenerated by Sphinx. Refer to documentation 73 | # for a list of supported languages. 74 | # 75 | # This is also used if you do content translation via gettext catalogs. 76 | # Usually you set "language" from the command line for these cases. 77 | language = None 78 | 79 | # List of patterns, relative to source directory, that match files and 80 | # directories to ignore when looking for source files. 81 | # This pattern also affects html_static_path and html_extra_path . 82 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 83 | 84 | # The name of the Pygments (syntax highlighting) style to use. 85 | pygments_style = 'sphinx' 86 | 87 | 88 | # -- Options for HTML output ------------------------------------------------- 89 | 90 | # The theme to use for HTML and HTML Help pages. See the documentation for 91 | # a list of builtin themes. 92 | # 93 | html_theme = 'sphinx_rtd_theme' 94 | html_logo = 'epic12_4_exp_2_1.25.png' 95 | 96 | # Theme options are theme-specific and customize the look and feel of a theme 97 | # further. For a list of options available for each theme, see the 98 | # documentation. 99 | # 100 | # html_theme_options = {} 101 | 102 | # Add any paths that contain custom static files (such as style sheets) here, 103 | # relative to this directory. They are copied after the builtin static files, 104 | # so a file named "default.css" will overwrite the builtin "default.css". 105 | html_static_path = ['_static'] 106 | 107 | # Custom sidebar templates, must be a dictionary that maps document names 108 | # to template names. 109 | # 110 | # The default sidebars (for documents that don't match any pattern) are 111 | # defined by theme itself. Builtin themes are using these templates by 112 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', 113 | # 'searchbox.html']``. 114 | # 115 | # html_sidebars = {} 116 | 117 | 118 | # -- Options for HTMLHelp output --------------------------------------------- 119 | 120 | # Output file base name for HTML help builder. 121 | htmlhelp_basename = 'Eigentoolsdoc' 122 | 123 | 124 | # -- Options for LaTeX output ------------------------------------------------ 125 | 126 | latex_elements = { 127 | # The paper size ('letterpaper' or 'a4paper'). 128 | # 129 | # 'papersize': 'letterpaper', 130 | 131 | # The font size ('10pt', '11pt' or '12pt'). 132 | # 133 | # 'pointsize': '10pt', 134 | 135 | # Additional stuff for the LaTeX preamble. 136 | # 137 | # 'preamble': '', 138 | 139 | # Latex figure (float) alignment 140 | # 141 | # 'figure_align': 'htbp', 142 | } 143 | 144 | # Grouping the document tree into LaTeX files. List of tuples 145 | # (source start file, target name, title, 146 | # author, documentclass [howto, manual, or own class]). 147 | latex_documents = [ 148 | (master_doc, 'Eigentools.tex', 'Eigentools Documentation', 149 | 'Dedalus Collaboration', 'manual'), 150 | ] 151 | 152 | 153 | # -- Options for manual page output ------------------------------------------ 154 | 155 | # One entry per manual page. List of tuples 156 | # (source start file, name, description, authors, manual section). 157 | man_pages = [ 158 | (master_doc, 'dedalusproject', 'Eigentools Documentation', 159 | [author], 1) 160 | ] 161 | 162 | 163 | # -- Options for Texinfo output ---------------------------------------------- 164 | 165 | # Grouping the document tree into Texinfo files. List of tuples 166 | # (source start file, target name, title, author, 167 | # dir menu entry, description, category) 168 | texinfo_documents = [ 169 | (master_doc, 'Eigentools', 'Eigentools Documentation', 170 | author, 'DedalusProject', 'One line description of project.', 171 | 'Miscellaneous'), 172 | ] 173 | -------------------------------------------------------------------------------- /eigentools/criticalfinder.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import numpy as np 3 | from mpi4py import MPI 4 | import h5py 5 | from scipy import interpolate, optimize 6 | import matplotlib.pyplot as plt 7 | from matplotlib import transforms 8 | 9 | from dedalus.tools.cache import CachedAttribute 10 | 11 | logger = logging.getLogger(__name__.split('.')[-1]) 12 | 13 | class CriticalFinder: 14 | """finds critical parameters for eigenvalue problems. 15 | 16 | This class provides simple tools for finding the critical parameters 17 | for the linear (in)stability of a given flow. The parameter space must 18 | be 2D; typically this will be (k, Re), where k is a wavenumber and Re 19 | is some control parameter (e. g. Reynolds or Rayleigh). The parameters 20 | are defined by the underlying Eigenproblem object. 21 | 22 | Parameters 23 | ---------- 24 | eigenproblem: Eigenproblem 25 | An eigentools eigenproblem object over which to find critical 26 | parameters 27 | param_names : tuple of str 28 | The names of parameters to search over 29 | comm : mpi4py.MPI.Intracomm, optional 30 | The MPI comm group to share jobs across (default: MPI.COMM_WORLD) 31 | find_freq : bool, optional 32 | If True, also find frequency at critical point 33 | 34 | Attributes 35 | ---------- 36 | parameter_grids: 37 | NumPy mesh grids containing the parameter values for the EVP 38 | evalue_grid: 39 | NumPy array of complex values, containing the maximum growth rates 40 | of the EVP for the corresponding input values. 41 | roots : ndarray 42 | Array of roots along axis 1 of parameter_grid 43 | """ 44 | 45 | def __init__(self, eigenproblem, param_names, comm=MPI.COMM_WORLD, find_freq=False): 46 | self.eigenproblem = eigenproblem 47 | self.param_names = param_names 48 | self.comm = comm 49 | self.size = self.comm.size 50 | self.rank = self.comm.rank 51 | self.find_freq = find_freq 52 | 53 | self.roots = None 54 | 55 | def grid_generator(self, points, sparse=False): 56 | """Generates a grid of eigenvalues over the specified parameter 57 | space of an eigenvalue problem. 58 | 59 | Parameters 60 | ---------- 61 | points : tuple of ndarray 62 | The parameter values over which to find the critical value 63 | """ 64 | self.parameter_grids = np.meshgrid(*points) 65 | self.evalue_grid = np.zeros(self.parameter_grids[0].shape, dtype=np.complex128) 66 | dims = self.evalue_grid.shape 67 | # Split parameter load across processes 68 | index = np.arange(np.prod(dims)) 69 | load_indices = np.array_split(index,self.size) 70 | my_indices = load_indices[self.rank] 71 | 72 | # Calculate growth values for local process grid 73 | local_grid = np.empty(my_indices.size,dtype=np.complex128) 74 | for n, index in enumerate(my_indices): 75 | logger.info("Solving Local EVP {}/{}".format(n+1, len(my_indices))) 76 | unraveled_index = np.unravel_index(index, dims) 77 | values = [self.parameter_grids[i][unraveled_index] for i,v in enumerate(self.parameter_grids)] 78 | 79 | gr, indx, freq = self._growth_rate(values, sparse=sparse) 80 | local_grid[n] = gr + 1j*freq 81 | 82 | # Communicate growth modes to root 83 | data = np.empty(dims, dtype=np.complex128) 84 | rec_counts = np.array([s.size for s in load_indices]) 85 | displacements = np.cumsum(rec_counts) - rec_counts 86 | self.comm.Gatherv(local_grid,[data,rec_counts,displacements, MPI.F_DOUBLE_COMPLEX]) 87 | self.evalue_grid = data 88 | 89 | def _growth_rate(self, values, **kwargs): 90 | """Compute growth rate at values 91 | 92 | Parameters 93 | ---------- 94 | values : dict 95 | Dictionary of parameter names and values 96 | """ 97 | var_dict = {self.param_names[i]: v for i,v in enumerate(values)} 98 | return self.eigenproblem.growth_rate(var_dict, **kwargs) #solve 99 | 100 | @CachedAttribute 101 | def _interpolator(self): 102 | """Creates and then uses a 2D grid interpolator for growth rate 103 | 104 | NB: this transposes x and y for the root finding step, because that 105 | requires the function to be interpolated along the FIRST axis 106 | """ 107 | xx = self.parameter_grids[0] 108 | yy = self.parameter_grids[1] 109 | return interpolate.interp2d(yy.T, xx.T, self.evalue_grid.real.T) 110 | 111 | @CachedAttribute 112 | def _freq_interpolator(self): 113 | """Creates and then uses a 2D grid interpolator for growth rate 114 | """ 115 | xx = self.parameter_grids[0] 116 | yy = self.parameter_grids[1] 117 | return interpolate.interp2d(xx, yy, self.evalue_grid.imag) 118 | 119 | def load_grid(self, filename): 120 | """ 121 | Load a grid file, in the format as created in save_grid. 122 | 123 | Parameters 124 | ---------- 125 | filename : str 126 | The name of the .h5 file containing the grid data 127 | """ 128 | with h5py.File(filename,'r') as infile: 129 | self.parameter_grids = [k[()] for k in infile.values() if 'xyz' in k.name] 130 | self.N = len(self.parameter_grids) 131 | logger.info("Read an {}-dimensional grid".format(self.N)) 132 | self.evalue_grid = infile['/grid'][:] 133 | 134 | def save_grid(self, filename): 135 | """ 136 | Saves the grids of all input parameters as well as the growth rate 137 | grid that has been solved for. 138 | 139 | Parameters 140 | ---------- 141 | filename : str 142 | A file stem, which DOES NOT include the file type extension. The 143 | grid will be saved to a file called filen.h5 144 | """ 145 | if self.comm.rank == 0: 146 | with h5py.File(filename+'.h5','w') as outfile: 147 | outfile.create_dataset('grid',data=self.evalue_grid) 148 | for i, grid in enumerate(self.parameter_grids): 149 | outfile.create_dataset('xyz_{}'.format(i),data=grid) 150 | 151 | def _root_finder(self): 152 | """Find rooots from interpolated values at each point along zero axis of parameter_grid 153 | 154 | """ 155 | yy = self.parameter_grids[1] 156 | xx = self.parameter_grids[0] 157 | self.roots = np.zeros_like(xx[0,:]) 158 | for j,x in enumerate(xx[0,:]): 159 | try: 160 | self.roots[j] = optimize.brentq(self._interpolator,yy[0,0],yy[-1,0],args=(x)) 161 | except ValueError: 162 | self.roots[j] = np.nan 163 | 164 | def crit_finder(self, polish_roots=False, polish_sparse=True, tol=1e-3, method='Powell', maxiter=200, **kwargs): 165 | """returns parameters at which critical eigenvalue occurs and optionally frequency at that value. 166 | 167 | The critical parameter is defined as the absolute minimum of the 168 | growth rate, defined in the Eigenproblem via its grow_func. If 169 | frequency is to be found also, returns the frequnecy defined in the 170 | Eigenproblem via its freq_func. 171 | 172 | If find_freq is True, returns (critical parameter 1, critical 173 | parameter 2, frequency); otherwise returns (critical parameter 1, 174 | critical parameter 2) 175 | 176 | Parameters 177 | ---------- 178 | polish_roots : bool, optional 179 | If true, use optimization routines to polish critical value (default: False) 180 | polish_sparse : bool, optional 181 | If true, use the sparse solver when polishing roots (default: True) 182 | tol : float, optional 183 | Tolerance for polishing routine (default: 1e-3) 184 | method : str, optional 185 | Method for scipy.optimize used for polishing (default: Powell) 186 | maxiter : int, optional 187 | Maximum number of optimization iterations used for polishing (default: 200) 188 | 189 | Returns 190 | ------ 191 | tuple 192 | """ 193 | if self.rank != 0: 194 | return 195 | self._root_finder() 196 | mask = np.isfinite(self.roots) 197 | xx_root = self.parameter_grids[0][0,mask] 198 | rroot = self.roots[mask] 199 | 200 | self.root_fn = interpolate.interp1d(xx_root,rroot,kind='cubic') 201 | 202 | mid = xx_root.shape[0]//2 203 | 204 | bracket = [xx_root[0],xx_root[mid],xx_root[-1]] 205 | 206 | self.opt = optimize.minimize_scalar(self.root_fn,bracket=bracket) 207 | 208 | x_crit = self.opt['x'] 209 | y_crit = self.opt['fun'].item() 210 | if self.find_freq: 211 | crit_freq = self._freq_interpolator(x_crit, y_crit)[0] 212 | crits = (x_crit, y_crit, crit_freq) 213 | if polish_roots: 214 | crits = self.critical_polisher(crits, sparse=polish_sparse, 215 | tol=tol, method=method, maxiter=maxiter, **kwargs) 216 | 217 | return crits 218 | 219 | crits = (x_crit, y_crit) 220 | if polish_roots: 221 | crits = self.critical_polisher(crits, sparse=polish_sparse, 222 | tol=tol, method=method, maxiter=maxiter, **kwargs) 223 | 224 | return crits 225 | 226 | def critical_polisher(self, guess, sparse=True, tol=1e-3, method='Powell', maxiter=200, **kwargs): 227 | """ 228 | Polishes a guess for the critical value using scipy's optimization 229 | routines to find a more precise location of the critical value. 230 | 231 | Parameters 232 | ---------- 233 | guess : complex 234 | Initial guess for optimization routines 235 | sparse : bool, optional 236 | If true, use the sparse solver when polishing roots (default: True) 237 | tol : float, optional 238 | Tolerance for polishing routine (default: 1e-3) 239 | method : str, optional 240 | Method for scipy.optimize used for polishing (default: Powell) 241 | maxiter : int, optional 242 | Maximum number of optimization iterations used for polishing 243 | (default: 200) 244 | """ 245 | 246 | # minimize absolute value of growth rate 247 | function = lambda args: np.abs(self._growth_rate(args, sparse=sparse)[0]) 248 | if self.find_freq: 249 | x0 = guess[:-1] 250 | else: 251 | x0 = guess 252 | search_result = optimize.minimize(function, x0, 253 | tol=tol, options={'maxiter': maxiter}, method=method) 254 | 255 | logger.debug("Optimize results: {}".format(search_result)) 256 | 257 | if self.find_freq: 258 | freq = self._freq_interpolator(search_result.x[0],search_result.x[1]) 259 | 260 | if search_result.success: 261 | logger.info('Minimum growth rate of {} found'.format(search_result.fun)) 262 | results = list(search_result.x) 263 | if self.find_freq: 264 | results += list(freq) 265 | return results 266 | else: 267 | logger.warning('Optimize results not fully converged, returning crit_finder results.') 268 | return guess 269 | 270 | def plot_crit(self, axes=None, transpose=False, xlabel = None, ylabel = None, zlabel="growth rate", cmap="viridis"): 271 | """Create a 2D colormap of the grid of growth rates. 272 | 273 | If available, the root values that have been found will be plotted 274 | over the colormap. 275 | 276 | Parameters 277 | ---------- 278 | transpose : bool, optional 279 | If True, plot dim 0 on the y axis and dim 1 on the x axis. 280 | xlabel : str, optional 281 | If not None, the x-label of the plot. Otherwise, use parameter name from EVP 282 | ylabel : str, optional 283 | If not None, the y-label of the plot. Otherwise, use parameter name from EVP 284 | zlabel : str, optional 285 | Label for the colorbar. (default: growth rate) 286 | cmp : str, optional 287 | matplotlib colormap name (default: viridis) 288 | """ 289 | if self.rank != 0: 290 | return 291 | 292 | if axes is None: 293 | fig = plt.figure(figsize=[8,8]) 294 | ax = fig.add_subplot(111) 295 | else: 296 | ax = axes 297 | fig = axes.figure 298 | 299 | # Grab out grid data for colormap 300 | if transpose: 301 | xx = self.parameter_grids[1].T 302 | yy = self.parameter_grids[0].T 303 | grid = self.evalue_grid.real.T 304 | else: 305 | xx = self.parameter_grids[0] 306 | yy = self.parameter_grids[1] 307 | grid = self.evalue_grid.real 308 | # Plot colormap, only plot 2 stdevs off zero 309 | biggest_val = 2*np.abs(grid).std() 310 | 311 | # Setup axes 312 | # Bounds (left, bottom, width, height) relative-to-axes 313 | pbbox = transforms.Bbox.from_bounds(0.03, 0, 0.94, 0.94) 314 | cbbox = transforms.Bbox.from_bounds(0.03, 0.95, 0.94, 0.05) 315 | # Convert to relative-to-figure 316 | to_axes_bbox = transforms.BboxTransformTo(ax.get_position()) 317 | pbbox = pbbox.transformed(to_axes_bbox) 318 | cbbox = cbbox.transformed(to_axes_bbox) 319 | # Create new axes and suppress base axes 320 | pax = ax.figure.add_axes(pbbox) 321 | cax = ax.figure.add_axes(cbbox) 322 | 323 | plot = pax.pcolormesh(xx,yy,grid,cmap=cmap,vmin=-biggest_val,vmax=biggest_val) 324 | ax.axis('off') 325 | cbar = plt.colorbar(plot, cax=cax, label=zlabel, orientation='horizontal') 326 | cbar.outline.set_visible(False) 327 | cax.xaxis.set_ticks_position('top') 328 | cax.xaxis.set_label_position('top') 329 | # Plot root data if they're available 330 | if self.roots is not None: 331 | if transpose: 332 | x = self.roots[:] 333 | y = self.parameter_grids[0][0,:] 334 | else: 335 | x = self.parameter_grids[0][0,:] 336 | y = self.roots[:] 337 | 338 | if transpose: 339 | y, x = y[np.isfinite(x)], x[np.isfinite(x)] 340 | else: 341 | y, x = y[np.isfinite(y)], x[np.isfinite(y)] 342 | pax.scatter(x,y, color='k') 343 | 344 | # Pretty up the plot, save. 345 | pax.set_ylim(yy.min(),yy.max()) 346 | pax.set_xlim(xx.min(),xx.max()) 347 | if xlabel is None: 348 | xlabel = self.param_names[0] 349 | if ylabel is None: 350 | ylabel = self.param_names[1] 351 | pax.set_xlabel(xlabel) 352 | pax.set_ylabel(ylabel) 353 | 354 | return pax,cax 355 | -------------------------------------------------------------------------------- /eigentools/eigenproblem.py: -------------------------------------------------------------------------------- 1 | from dedalus.tools.cache import CachedAttribute 2 | import logging 3 | from dedalus.core.field import Field 4 | from dedalus.core.evaluator import Evaluator 5 | from dedalus.core.system import FieldSystem 6 | from dedalus.tools.post import merge_process_files 7 | import dedalus.public as de 8 | import matplotlib.pyplot as plt 9 | import numpy as np 10 | from scipy.interpolate import interp1d 11 | import scipy.sparse.linalg 12 | from . import tools 13 | 14 | logger = logging.getLogger(__name__.split('.')[-1]) 15 | 16 | class Eigenproblem(): 17 | def __init__(self, EVP, reject=True, factor=1.5, scales=1, drift_threshold=1e6, use_ordinal=False, grow_func=lambda x: x.real, freq_func=lambda x: x.imag): 18 | """An object for feature-rich eigenvalue analysis. 19 | 20 | Eigenproblem provides support for common tasks in eigenvalue 21 | analysis. Dedalus EVP objects compute raw eigenvalues and 22 | eigenvectors for a given problem; Eigenproblem provides support for 23 | numerous common tasks required for scientific use of those 24 | solutions. This includes rejection of inaccurate eigenvalues and 25 | analysis of those rejection criteria, plotting of eigenmodes and 26 | spectra, and projection of 1-D eigenvectors onto 2- or 3-D domains 27 | for use as initial conditions in subsequent initial value problems. 28 | 29 | Additionally, Eigenproblems can compute epsilon-pseudospectra for 30 | arbitrary Dedalus differential-algebraic equations. 31 | 32 | 33 | Parameters 34 | ---------- 35 | EVP : dedalus.core.problems.EigenvalueProblem 36 | The Dedalus EVP object containing the equations to be solved 37 | reject : bool, optional 38 | whether or not to reject spurious eigenvalues (default: True) 39 | factor : float, optional 40 | The factor by which to multiply the resolution. 41 | NB: this must be a rational number such that factor times the 42 | resolution of EVP is an integer. (default: 1.5) 43 | scales : float, optional 44 | A multiple for setting the grid resolution. (default: 1) 45 | drift_threshold : float, optional 46 | Inverse drift ratio threshold for keeping eigenvalues during 47 | rejection (default: 1e6) 48 | use_ordinal : bool, optional 49 | If true, use ordinal method from Boyd (1989); otherwise use 50 | nearest (default: False) 51 | grow_func : func 52 | A function that takes a complex input and returns the growth 53 | rate as defined by the EVP (default: uses real part) 54 | freq_func : func 55 | A function that takes a complex input and returns the frequency 56 | as defined by the EVP (default: uses imaginary part) 57 | 58 | Attributes 59 | ---------- 60 | evalues : ndarray 61 | Lists "good" eigenvalues 62 | evalues_low : ndarray 63 | Lists eigenvalues from low resolution solver (i.e. the 64 | resolution of the specified EVP) 65 | evalues_high : ndarray 66 | Lists eigenvalues from high resolution solver (i.e. factor 67 | times specified EVP resolution) 68 | pseudospectrum : ndarray 69 | epsilon-pseudospectrum computed at specified points in the 70 | complex plane 71 | ps_real : ndarray 72 | real coordinates for epsilon-pseudospectrum 73 | ps_imag : ndarray 74 | imaginary coordinates for epsilon-pseudospectrum 75 | 76 | Notes 77 | ----- 78 | See references for algorithms in individual method docstrings. 79 | 80 | """ 81 | self.reject = reject 82 | self.factor = factor 83 | self.EVP = EVP 84 | self.solver = EVP.build_solver() 85 | if self.reject: 86 | self._build_hires() 87 | 88 | self.grid_name = self.EVP.domain.bases[0].name 89 | self.evalues = None 90 | self.evalues_low = None 91 | self.evalues_high = None 92 | self.pseudospectrum = None 93 | self.ps_real = None 94 | self.ps_imag = None 95 | 96 | self.drift_threshold = drift_threshold 97 | self.use_ordinal = use_ordinal 98 | self.scales = scales 99 | self.grow_func = grow_func 100 | self.freq_func = freq_func 101 | 102 | def _set_parameters(self, parameters): 103 | """set the parameters in the underlying EVP object 104 | 105 | Parameters 106 | ---------- 107 | parameters : dict 108 | Dict of parameter names and values (keys and values 109 | respectively) to set in EVP 110 | 111 | 112 | """ 113 | for k,v in parameters.items(): 114 | tools.update_EVP_params(self.EVP, k, v) 115 | if self.reject: 116 | tools.update_EVP_params(self.EVP_hires, k, v) 117 | 118 | def grid(self): 119 | """get grid points for eigenvectors. 120 | 121 | """ 122 | return self.EVP.domain.grids(scales=self.scales)[0] 123 | 124 | def solve(self, sparse=False, parameters=None, pencil=0, N=15, target=0, **kwargs): 125 | """solve underlying eigenvalue problem. 126 | 127 | Parameters 128 | ---------- 129 | sparse : bool, optional 130 | If true, use sparse solver, otherwise use dense solver 131 | (default: False) 132 | parameters : dict, optional 133 | A dict giving parameter names and values to the EVP. If None, 134 | use values specified at EVP construction time. (default: None) 135 | pencil : int, optional 136 | The EVP pencil to be solved. (default: 0) 137 | N : int, optional 138 | The number of eigenvalues to find if using a sparse solver 139 | (default: 15) 140 | target : complex, optional 141 | The target value to search for when using sparse solver 142 | (default: 0+0j) 143 | 144 | 145 | """ 146 | if parameters: 147 | self._set_parameters(parameters) 148 | self.pencil = pencil 149 | self.N = N 150 | self.target = target 151 | self.solver_kwargs = kwargs 152 | 153 | self._run_solver(self.solver, sparse) 154 | self.evalues_low = self.solver.eigenvalues 155 | 156 | if self.reject: 157 | self._run_solver(self.hires_solver, sparse) 158 | self.evalues_high = self.hires_solver.eigenvalues 159 | self._reject_spurious() 160 | else: 161 | self.evalues = self.evalues_low 162 | self.evalues_index = np.arange(len(self.evalues),dtype=int) 163 | 164 | def _run_solver(self, solver, sparse): 165 | """wrapper method to run solver. 166 | 167 | Parameters 168 | ---------- 169 | solver : dedalus.core.problems.EigenvalueProblem 170 | The Dedalus EVP object containing the equations to be solved 171 | sparse : bool 172 | If True, use sparse solver; otherwise use dense. 173 | """ 174 | if sparse: 175 | solver.solve_sparse(solver.pencils[self.pencil], N=self.N, target=self.target, rebuild_coeffs=True, **self.solver_kwargs) 176 | else: 177 | solver.solve_dense(solver.pencils[self.pencil], rebuild_coeffs=True) 178 | 179 | def _set_eigenmode(self, index, all_modes=False): 180 | """use EVP solver's set_state to access eigenmode in grid or coefficient space 181 | 182 | The index parameter is either the index of the ordered good 183 | eigenvalues or the direct index of the low-resolution EVP depending 184 | on the all_modes option. 185 | 186 | Parameters 187 | ---------- 188 | index : int 189 | index of eigenvalue corresponding to desired eigenvector 190 | all_modes : bool, optional 191 | If True, index specifies the unsorted index of the 192 | low-resolution EVP; otherwise it is the index corresponding to 193 | the self.evalues order (default: False) 194 | """ 195 | if all_modes: 196 | good_index = index 197 | else: 198 | good_index = self.evalues_index[index] 199 | self.solver.set_state(good_index) 200 | 201 | def eigenmode(self, index, scales=None, all_modes=False): 202 | """Returns Dedalus FieldSystem object containing the eigenmode 203 | given by index. 204 | 205 | 206 | Parameters 207 | ---------- 208 | index : int 209 | index of eigenvalue corresponding to desired eigenvector 210 | scales : float 211 | A multiple for setting the grid resolution. If not None, will 212 | overwrite self.scales. (default: None) 213 | all_modes : bool, optional 214 | If True, index specifies the unsorted index of the 215 | low-resolution EVP; otherwise it is the index corresponding to 216 | the self.evalues order (default: False) 217 | """ 218 | self._set_eigenmode(index, all_modes=all_modes) 219 | if scales is not None: 220 | self.scales = scales 221 | for f in self.solver.state.fields: 222 | f.set_scales(self.scales,keep_data=True) 223 | 224 | return self.solver.state 225 | 226 | def growth_rate(self, parameters=None, **kwargs): 227 | """returns the maximum growth rate, defined by self.grow_func(), 228 | the index of the maximal mode, and the frequency of that mode. If 229 | there is no growing mode, returns the slowest decay rate. 230 | 231 | also returns the index of the fastest growing mode. If there are 232 | no good eigenvalues, returns np.nan for all three quantities. 233 | 234 | Returns 235 | ------- 236 | growth_rate, index, freqency : tuple of ints 237 | 238 | """ 239 | try: 240 | self.solve(parameters=parameters, **kwargs) 241 | gr_rate = np.max(self.grow_func(self.evalues)) 242 | gr_indx = np.where(self.grow_func(self.evalues) == gr_rate)[0] 243 | freq = self.freq_func(self.evalues[gr_indx[0]]) 244 | 245 | return gr_rate, gr_indx[0], freq 246 | 247 | except np.linalg.linalg.LinAlgError: 248 | logger.warning("Dense eigenvalue solver failed for parameters {}".format(params)) 249 | return np.nan, np.nan, np.nan 250 | except (scipy.sparse.linalg.eigen.arpack.ArpackNoConvergence, scipy.sparse.linalg.eigen.arpack.ArpackError): 251 | logger.warning("Sparse eigenvalue solver failed to converge for parameters {}".format(params)) 252 | return np.nan, np.nan, np.nan 253 | 254 | def plot_mode(self, index, fig_height=8, norm_var=None, scales=None, all_modes=False): 255 | """plots eigenvector corresponding to specified index. 256 | 257 | By default, the plot will show the real and complex parts of the 258 | unnormalized components of the eigenmode. If a norm_var is 259 | specified, all components will be scaled such that variable chosen 260 | is purely real and has unit amplitude. 261 | 262 | Parameters 263 | ---------- 264 | index : int 265 | index of eigenvalue corresponding to desired eigenvector 266 | fig_height : float, optional 267 | Height of constructed figure (default: 8) 268 | norm_var : str 269 | If not None, selects the field in the eigenmode with which to 270 | normalize. Otherwise, plots the unnormalized 271 | eigenmode. (default: None) 272 | scales : float 273 | A multiple for setting the grid resolution. If not None, will 274 | overwrite self.scales. (default: None) 275 | all_modes : bool, optional 276 | If True, index specifies the unsorted index of the 277 | low-resolution EVP; otherwise it is the index corresponding to 278 | the self.evalues order (default: False) 279 | 280 | Returns 281 | ------- 282 | matplotlib.figure.Figure 283 | 284 | """ 285 | state = self.eigenmode(index, scales=scales, all_modes=all_modes) 286 | 287 | z = self.grid() 288 | nrow = 2 289 | nvars = len(self.EVP.variables) 290 | ncol = int(np.ceil(nvars/nrow)) 291 | 292 | if norm_var: 293 | rotation = self.solver.state[norm_var]['g'].conj() 294 | else: 295 | rotation = 1. 296 | 297 | fig = plt.figure(figsize=[fig_height*ncol/nrow,fig_height]) 298 | for i,v in enumerate(self.EVP.variables): 299 | ax = fig.add_subplot(nrow,ncol,i+1) 300 | ax.plot(z, (rotation*state[v]['g']).real, label='real') 301 | ax.plot(z, (rotation*state[v]['g']).imag, label='imag') 302 | ax.set_xlabel(self.grid_name) 303 | ax.set_ylabel(v) 304 | if i == 0: 305 | ax.legend() 306 | 307 | fig.tight_layout() 308 | 309 | return fig 310 | 311 | def project_mode(self, index, domain, transverse_modes, all_modes=False): 312 | """projects a mode specified by index onto a domain of higher 313 | dimension. 314 | 315 | Parameters 316 | ---------- 317 | index : 318 | an integer giving the eigenmode to project 319 | domain : 320 | a domain to project onto 321 | transverse_modes : 322 | a tuple of mode numbers for the transverse directions 323 | 324 | Returns 325 | ------- 326 | dedalus.core.system.FieldSystem 327 | """ 328 | 329 | if len(transverse_modes) != (len(domain.bases) - 1): 330 | raise ValueError("Must specify {} transverse modes for a domain with {} bases; {} specified".format(len(domain.bases)-1, len(domain.bases), len(transverse_modes))) 331 | 332 | field_slice = tuple(i for i in [transverse_modes, slice(None)]) 333 | 334 | self._set_eigenmode(index, all_modes=all_modes) 335 | 336 | fields = [] 337 | 338 | for v in self.EVP.variables: 339 | fields.append(domain.new_field(name=v)) 340 | fields[-1]['c'][field_slice] = self.solver.state[v]['c'] 341 | field_system = FieldSystem(fields) 342 | 343 | return field_system 344 | 345 | def write_global_domain(self, field_system, base_name="IVP_output"): 346 | """Given a field system, writes a Dedalus HDF5 file. 347 | 348 | Typically, one would use this to write a field system constructed by project_mode. 349 | 350 | Parameters 351 | ---------- 352 | field_system : dedalus.core.system.FieldSystem 353 | A field system containing the data to be written 354 | base_name : str, optional 355 | The base filename of the resulting HDF5 file. (default: IVP_output) 356 | 357 | """ 358 | output_evaluator = Evaluator(field_system.domain, self.EVP.namespace) 359 | output_handler = output_evaluator.add_file_handler(base_name) 360 | output_handler.add_system(field_system) 361 | 362 | output_evaluator.evaluate_handlers(output_evaluator.handlers, timestep=0,sim_time=0, world_time=0, wall_time=0, iteration=0) 363 | 364 | merge_process_files(base_name, cleanup=True, comm=output_evaluator.domain.distributor.comm) 365 | 366 | def calc_ps(self, k, zgrid, mu=0., pencil=0, inner_product=None, norm=-2, maxiter=10, rtol=1e-3): 367 | """computes epsilon-pseudospectrum for the eigenproblem. 368 | 369 | Uses the algorithm described in section 5 of 370 | 371 | Embree & Keeler (2017). SIAM J. Matrix Anal. Appl. 38, 3: 372 | 1028-1054. 373 | 374 | to enable the approximation of epsilon-pseudospectra for arbitrary 375 | differential-algebraic equation systems. 376 | 377 | 378 | Parameters: 379 | ----------- 380 | k : int 381 | number of eigenmodes in invariant subspace 382 | zgrid : tuple 383 | (real, imag) points 384 | mu : complex 385 | center point for pseudospectrum. 386 | pencil : int 387 | pencil holding EVP 388 | inner_product : function 389 | a function that takes two field systems and computes their 390 | inner product 391 | """ 392 | 393 | self.solve(sparse=True, N=k, pencil=pencil) # O(N k)? 394 | pre_right = self.solver.pencils[pencil].pre_right 395 | pre_right_LU = scipy.sparse.linalg.splu(pre_right.tocsc()) # O(N) 396 | V = pre_right_LU.solve(self.solver.eigenvectors) # O(N k) 397 | 398 | # Orthogonalize invariant subspace 399 | Q, R = np.linalg.qr(V) # O(N k^2) 400 | 401 | # Compute approximate Schur factor 402 | E = -(self.solver.pencils[pencil].M_exp) 403 | A = (self.solver.pencils[pencil].L_exp) 404 | A_mu_E = A - mu*E 405 | A_mu_E_LU = scipy.sparse.linalg.splu(A_mu_E.tocsc()) # O(N) 406 | Ghat = Q.conj().T @ A_mu_E_LU.solve(E @ Q) # O(N k^2) 407 | 408 | # Invert-shift Schur factor 409 | I = np.identity(k) 410 | if inner_product is not None: 411 | M = self.compute_mass_matrix(pre_right@Q, inner_product) 412 | Z, S = np.linalg.qr(scipy.linalg.cholesky(M)) 413 | Gmu = S@np.linalg.inv(S@Ghat) + mu*I 414 | else: 415 | logger.warning("No inner product given. Using 2-norm of state vector coefficients. This is probably not physically meaningful, especially if you are using Chebyshev polynomials.") 416 | Gmu = np.linalg.inv(Ghat) + mu*I # O(k^3) 417 | 418 | self.pseudospectrum = self._pseudo(Gmu, zgrid, maxiter=maxiter, rtol=rtol) 419 | self.ps_real = zgrid[0] 420 | self.ps_imag = zgrid[1] 421 | 422 | def compute_mass_matrix(self, Q, inner_product): 423 | """Compute the mass matrix M using a given inner product 424 | 425 | M must be hermitian, so we compute only half the inner products. 426 | 427 | Parameters 428 | ---------- 429 | Q : ndarray 430 | Matrix of eigenvectors 431 | inner_product : function 432 | a function that takes two field systems and computes their 433 | inner product 434 | 435 | Returns 436 | ------- 437 | ndarray 438 | 439 | """ 440 | k = Q.shape[1] 441 | M = np.zeros((k,k), dtype=np.complex128) 442 | Xj = self._copy_system(self.solver.state) 443 | Xi = self._copy_system(self.solver.state) 444 | 445 | for j in range(k): 446 | self.set_state(Xj, Q[:,j]) 447 | for i in range(j,k): # M must be hermitian 448 | self.set_state(Xi, Q[:,i]) 449 | M[j,i] = inner_product(Xj, Xi) 450 | M[i,j] = M[j,i].conj() 451 | 452 | return M 453 | 454 | def set_state(self, system, evector): 455 | """ 456 | Set system to given evector 457 | 458 | Parameters 459 | ---------- 460 | system : FieldSystem 461 | system to fill in 462 | evector : ndarray 463 | eigenvector 464 | """ 465 | system.data[:] = 0 466 | system.set_pencil(self.solver.eigenvalue_pencil, evector) 467 | system.scatter() 468 | 469 | def _copy_system(self, state): 470 | """copies a field system. 471 | 472 | Parameters 473 | ---------- 474 | state : dedalus.core.system.FieldSystem 475 | 476 | Returns 477 | ------- 478 | dedalus.core.system.FieldSystem 479 | """ 480 | fields = [] 481 | for f in state.fields: 482 | field = f.copy() 483 | field.name = f.name 484 | fields.append(field) 485 | 486 | return FieldSystem(fields) 487 | 488 | def _pseudo(self, L, zgrid, maxiter=10, rtol=1e-3): 489 | """computes epsilon-pseudospectrum for a regular eigenvalue 490 | problem. 491 | 492 | If maxiter is zero, uses a direct algorithm: at point z in the 493 | complex plane, the resolvant R is calculated 494 | 495 | R = ||z*I - L||_{-2} 496 | 497 | finding the maximum singular value. 498 | 499 | If maxiter is not zero, uses the iterative algorithm from figure 500 | 39.3 (p.375) of 501 | 502 | Trefethen & Embree, "Spectra and Pseudospectra: The Behavior of 503 | Nonnormal Matrices and Operators" (2005, Princeton University 504 | Press) 505 | 506 | Parameters 507 | ---------- 508 | L : square 2D ndarray 509 | the matrix to be analyzed 510 | zgrid : tuple 511 | (real, imag) points 512 | 513 | Returns 514 | ------- 515 | ndarray 516 | """ 517 | xx = zgrid[0] 518 | yy = zgrid[1] 519 | R = np.zeros((len(xx), len(yy))) 520 | matsize = L.shape[0] 521 | T, Z = scipy.linalg.schur(L, output='complex') 522 | if maxiter == 0: 523 | logger.debug("Using direct solver for calculating pseudospectrum") 524 | else: 525 | logger.debug("Using iterative solver for calculating pseudospectrum") 526 | for j, y in enumerate(yy): 527 | for i, x in enumerate(xx): 528 | z = (x + 1j*y) 529 | # if _maxiter is set to zero 530 | if maxiter == 0: 531 | R[j,i] = np.linalg.norm((z*np.eye(matsize) - L), ord=-2) 532 | else: 533 | T1 = z*np.eye(matsize) - T 534 | T2 = T1.conj().T 535 | sigold = 0 536 | qold = np.zeros(matsize,dtype=np.complex128) 537 | beta = 0 538 | 539 | q = np.random.randn(matsize)+1j*np.random.randn(matsize) 540 | q /= np.linalg.norm(q) 541 | H = np.zeros((maxiter+1, maxiter+1), dtype=np.complex128) 542 | for p in range(maxiter): 543 | v = scipy.linalg.solve_triangular(T1, scipy.linalg.solve_triangular(T2,q,lower=True)) - beta*qold 544 | alpha = np.dot(q.conj(), v) 545 | v -= alpha*q 546 | beta = np.linalg.norm(v) 547 | qold = q 548 | q = v/beta 549 | H[p+1,p] = beta 550 | H[p,p+1] = beta 551 | H[p,p] = alpha 552 | sig = np.max(np.linalg.eigvalsh(H[:p+1,:p+1])) 553 | if np.abs(sigold/sig - 1) < rtol: 554 | break 555 | sigold = sig 556 | if p == (maxiter - 1): 557 | logger.warning("Iterative solver did not converge for (x, y) = ({},{})".format(x,y)) 558 | R[j, i] = 1/np.sqrt(sig) 559 | return R 560 | 561 | def plot_spectrum(self, axes=None, spectype='good', xlog=True, ylog=True, real_label="real", imag_label="imag"): 562 | """Plots the spectrum. 563 | 564 | The spectrum plots real parts on the x axis and imaginary parts on 565 | the y axis. 566 | 567 | Parameters 568 | ---------- 569 | spectype : {'good', 'low', 'high'}, optional 570 | specifies whether to use good, low, or high eigenvalues 571 | xlog : bool, optional 572 | Use symlog on x axis 573 | ylog : bool, optional 574 | Use symlog on y axis 575 | real_label : str, optional 576 | Label to be applied to the real axis 577 | imag_label : str, optional 578 | Label to be applied to the imaginary axis 579 | """ 580 | if spectype == 'low': 581 | ev = self.evalues_low 582 | elif spectype == 'high': 583 | ev = self.evalues_high 584 | elif spectype == 'good': 585 | ev = self.evalues_good 586 | else: 587 | raise ValueError("Spectrum type is not one of {low, high, good}") 588 | 589 | if axes is None: 590 | fig = plt.figure() 591 | ax = fig.add_subplot(111) 592 | else: 593 | ax = axes 594 | fig = axes.figure 595 | 596 | ax.scatter(ev.real, ev.imag) 597 | 598 | if xlog: 599 | ax.set_xscale('symlog') 600 | if ylog: 601 | ax.set_yscale('symlog') 602 | ax.set_xlabel(real_label) 603 | ax.set_ylabel(imag_label) 604 | if axes is None: 605 | fig.tight_layout() 606 | 607 | return ax 608 | 609 | def _reject_spurious(self): 610 | """perform eigenvalue rejection 611 | 612 | """ 613 | evg, indx = self._discard_spurious_eigenvalues() 614 | self.evalues_good = evg 615 | self.evalues_index = indx 616 | self.evalues = self.evalues_good 617 | 618 | def _build_hires(self): 619 | """builds a high-resolution EVP from the EVP passed in at 620 | construction 621 | 622 | """ 623 | old_evp = self.EVP 624 | old_x = old_evp.domain.bases[0] 625 | 626 | x = tools.basis_from_basis(old_x, self.factor) 627 | d = de.Domain([x],comm=old_evp.domain.dist.comm) 628 | self.EVP_hires = de.EVP(d,old_evp.variables,old_evp.eigenvalue, ncc_cutoff=old_evp.ncc_kw['cutoff'], max_ncc_terms=old_evp.ncc_kw['max_terms'], tolerance=self.EVP.tol) 629 | 630 | for k,v in old_evp.substitutions.items(): 631 | self.EVP_hires.substitutions[k] = v 632 | 633 | for k,v in old_evp.parameters.items(): 634 | if type(v) == Field: #NCCs 635 | new_field = d.new_field() 636 | v.set_scales(self.factor, keep_data=True) 637 | new_field['g'] = v['g'] 638 | self.EVP_hires.parameters[k] = new_field 639 | else: #scalars 640 | self.EVP_hires.parameters[k] = v 641 | 642 | for e in old_evp.equations: 643 | self.EVP_hires.add_equation(e['raw_equation']) 644 | 645 | try: 646 | for b in old_evp.boundary_conditions: 647 | self.EVP_hires.add_bc(b['raw_equation']) 648 | except AttributeError: 649 | # after version befc23584fea, Dedalus no longer 650 | # distingishes BCs from other equations 651 | pass 652 | 653 | self.hires_solver = self.EVP_hires.build_solver() 654 | 655 | def _discard_spurious_eigenvalues(self): 656 | """ Solves the linear eigenvalue problem for two different 657 | resolutions. Returns trustworthy eigenvalues using nearest delta, 658 | from Boyd chapter 7. 659 | """ 660 | eval_low = self.evalues_low 661 | eval_hi = self.evalues_high 662 | 663 | # Reverse engineer correct indices to make unsorted list from sorted 664 | reverse_eval_low_indx = np.arange(len(eval_low)) 665 | reverse_eval_hi_indx = np.arange(len(eval_hi)) 666 | 667 | eval_low_and_indx = np.asarray(list(zip(eval_low, reverse_eval_low_indx))) 668 | eval_hi_and_indx = np.asarray(list(zip(eval_hi, reverse_eval_hi_indx))) 669 | 670 | # remove nans 671 | eval_low_and_indx = eval_low_and_indx[np.isfinite(eval_low)] 672 | eval_hi_and_indx = eval_hi_and_indx[np.isfinite(eval_hi)] 673 | 674 | # Sort eval_low and eval_hi by real parts 675 | eval_low_and_indx = eval_low_and_indx[np.argsort(eval_low_and_indx[:, 0].real)] 676 | eval_hi_and_indx = eval_hi_and_indx[np.argsort(eval_hi_and_indx[:, 0].real)] 677 | 678 | eval_low_sorted = eval_low_and_indx[:, 0] 679 | eval_hi_sorted = eval_hi_and_indx[:, 0] 680 | 681 | # Compute sigmas from lower resolution run (gridnum = N1) 682 | sigmas = np.zeros(len(eval_low_sorted)) 683 | sigmas[0] = np.abs(eval_low_sorted[0] - eval_low_sorted[1]) 684 | sigmas[1:-1] = [0.5*(np.abs(eval_low_sorted[j] - eval_low_sorted[j - 1]) + np.abs(eval_low_sorted[j + 1] - eval_low_sorted[j])) for j in range(1, len(eval_low_sorted) - 1)] 685 | sigmas[-1] = np.abs(eval_low_sorted[-2] - eval_low_sorted[-1]) 686 | 687 | if not (np.isfinite(sigmas)).all(): 688 | logger.warning("At least one eigenvalue spacings (sigmas) is non-finite (np.inf or np.nan)!") 689 | 690 | # Ordinal delta 691 | self.delta_ordinal = np.array([np.abs(eval_low_sorted[j] - eval_hi_sorted[j])/sigmas[j] for j in range(len(eval_low_sorted))]) 692 | 693 | # Nearest delta 694 | self.delta_near = np.array([np.nanmin(np.abs(eval_low_sorted[j] - eval_hi_sorted)/sigmas[j]) for j in range(len(eval_low_sorted))]) 695 | 696 | # Discard eigenvalues with 1/delta_near < drift_threshold 697 | if self.use_ordinal: 698 | inverse_drift = 1/self.delta_ordinal 699 | else: 700 | inverse_drift = 1/self.delta_near 701 | eval_low_and_indx = eval_low_and_indx[np.where(inverse_drift > self.drift_threshold)] 702 | 703 | eval_low = eval_low_and_indx[:, 0] 704 | indx = eval_low_and_indx[:, 1].real.astype(np.int) 705 | 706 | return eval_low, indx 707 | 708 | def plot_drift_ratios(self, axes=None): 709 | """Plot drift ratios (both ordinal and nearest) vs. mode number. 710 | 711 | The drift ratios give a measure of how good a given eigenmode is; 712 | this can help set thresholds. 713 | 714 | Returns 715 | ------- 716 | matplotlib.figure.Figure 717 | 718 | """ 719 | if self.reject is False: 720 | raise NotImplementedError("Can't plot drift ratios unless eigenvalue rejection is True.") 721 | 722 | if axes is None: 723 | fig = plt.figure() 724 | ax = fig.add_subplot(111) 725 | else: 726 | ax = axes 727 | fig = axes.figure 728 | 729 | mode_numbers = np.arange(len(self.delta_near)) 730 | ax.semilogy(mode_numbers,1/self.delta_near,'o',alpha=0.4) 731 | ax.semilogy(mode_numbers,1/self.delta_ordinal,'x',alpha=0.4) 732 | 733 | ax.set_prop_cycle(None) 734 | good_near = 1/self.delta_near > self.drift_threshold 735 | good_ordinal = 1/self.delta_ordinal > self.drift_threshold 736 | ax.semilogy(mode_numbers[good_near],1/self.delta_near[good_near],'o', label='nearest') 737 | ax.semilogy(mode_numbers[good_ordinal],1/self.delta_ordinal[good_ordinal],'x',label='ordinal') 738 | ax.axhline(self.drift_threshold,alpha=0.4, color='black') 739 | ax.set_xlabel("mode number") 740 | ax.set_ylabel(r"$1/\delta$") 741 | ax.legend() 742 | 743 | return ax 744 | -------------------------------------------------------------------------------- /license.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------