diff -Nru ufl-1.2.0/.gitignore ufl-1.3.0/.gitignore --- ufl-1.2.0/.gitignore 1970-01-01 00:00:00.000000000 +0000 +++ ufl-1.3.0/.gitignore 2014-01-07 13:29:26.000000000 +0000 @@ -0,0 +1,2 @@ +*.pyc +build/ diff -Nru ufl-1.2.0/ChangeLog ufl-1.3.0/ChangeLog --- ufl-1.2.0/ChangeLog 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ChangeLog 2014-01-07 13:29:26.000000000 +0000 @@ -1,3 +1,11 @@ +1.3.0 [2014-01-07] + - Add cell_avg and facet_avg operators, can be applied to a Coefficient or Argument or restrictions thereof + - Fix bug in cofactor: now it is transposed the correct way. + - Add cell.min_facet_edge_length + - Add cell.max_facet_edge_length + - Simplify 0^f -> 0 if f is a non-negative scalar value + - Add atan2 function + - Allow form+0 -> form 1.2.0 [2013-03-24] - NB! Using shapes such as (1,) and (1,1) instead of () for 1D tensor quantities I, x, grad(f) - Add cell.facet_diameter diff -Nru ufl-1.2.0/README ufl-1.3.0/README --- ufl-1.2.0/README 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/README 2014-01-07 13:29:26.000000000 +0000 @@ -1,97 +1,121 @@ +=========================== UFL - Unified Form Language ---------------------------- +=========================== + +The Unified Form Language (UFL) is a domain specific language for +declaration of finite element discretizations of variational +forms. More precisely, it defines a flexible interface for choosing +finite element spaces and defining expressions for weak forms in a +notation close to mathematical notation. Authors: - Martin Sandve Alnæs - Anders Logg + | Martin Sandve Alnæs + | Anders Logg Contributors: - Kristian Ølgaard - Garth Wells - Marie Rognes - Kent-Andre Mardal - Johan Hake + | Kristian B. Ølgaard + | Garth N. Wells + | Marie E. Rognes + | Kent-Andre Mardal + | Johan Hake Installation ------------- +============ + +Linux:: -Linux: sudo python setup.py install Directories ------------ +=========== - ufl/ + All source code for the UFL implementation. - scripts/ + Commandline utilities like "ufl-analyse", "ufl-convert" and "form2ufl". - demo/ + Several ufl form files which demonstrates the use of the form language. - doc/ + The UFL manual resides here. - test/ + Unit tests for the UFL implementation. Run all tests by typing "python test.py" inside the test/ directory. - sandbox/ + A place for experimental scripts and other unofficial code. Utilities ---------- +========= + +For more information about the utilities, type:: -For more information about the utilities, type ufl-analyse -h ufl-convert -h form2ufl -h + after installation. About the Python modules ------------------------- +======================== + +The global namespace of the module ufl contains the entire UFL language:: -The global namespace of the module ufl contains the entire UFL language: from ufl import * -Form compilers may want to import additional implementation details like +Form compilers may want to import additional implementation details like:: + from ufl.classes import * -and + +and:: + from ufl.algorithms import * -Importing a .ufl file can be done easily from Python: +Importing a .ufl file can be done easily from Python:: + from ufl.algorithms import load_ufl_file filedata = load_ufl_file("filename.ufl") forms = filedata.forms elements = filedata.elements -to get lists of forms and elements from the .ufl file, or + +to get lists of forms and elements from the .ufl file, or:: + from ufl.algorithms import load_forms forms = load_forms("filename.ufl") + to get a list of forms in the .ufl file. Contact -------- +======= + +Send feature requests and questions to + + fenics@fenicsproject.org -Send bug reports, feature requests, and questions to - ufl@lists.launchpad.net +The Git source repository for UFL is located at -The Bazaar source repository for UFL is located at - lp:ufl + https://bitbucket.org/fenics-project/ufl -The latest code can be obtained by - bzr branch lp:ufl +and bugs can be registered at -A wiki page with a brief overview of UFL exists at - http://www.fenicsproject.org + https://bitbucket.org/fenics-project/ufl/issues License -------- +======= UFL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by diff -Nru ufl-1.2.0/TODO ufl-1.3.0/TODO --- ufl-1.2.0/TODO 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/TODO 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -TODO items and suggsted features can be found at - - https://blueprints.launchpad.net/ufl diff -Nru ufl-1.2.0/debian/changelog ufl-1.3.0/debian/changelog --- ufl-1.2.0/debian/changelog 2013-06-26 12:43:36.000000000 +0000 +++ ufl-1.3.0/debian/changelog 2014-01-10 12:04:31.000000000 +0000 @@ -1,3 +1,13 @@ +ufl (1.3.0-1) unstable; urgency=low + + * New upstream release. + * debian/watch: Update URL for move to Bitbucket. + * debian/docs: Remove TODO. + * debian/python-ufl-doc.docs: Remove ufl-user-manual.pdf. + * Remove debian/python-ufl-doc.doc-base. + + -- Johannes Ring Wed, 26 Jun 2013 14:46:16 +0200 + ufl (1.2.0-1) unstable; urgency=low * New upstream release. diff -Nru ufl-1.2.0/debian/docs ufl-1.3.0/debian/docs --- ufl-1.2.0/debian/docs 2013-06-26 12:43:36.000000000 +0000 +++ ufl-1.3.0/debian/docs 2014-01-10 12:04:31.000000000 +0000 @@ -1,2 +1 @@ README -TODO diff -Nru ufl-1.2.0/debian/python-ufl-doc.doc-base ufl-1.3.0/debian/python-ufl-doc.doc-base --- ufl-1.2.0/debian/python-ufl-doc.doc-base 2013-06-26 12:43:36.000000000 +0000 +++ ufl-1.3.0/debian/python-ufl-doc.doc-base 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -Document: python-ufl-doc -Title: UFL Specification and User Manual -Author: Martin Sandve Alnæs, Anders Logg -Abstract: UFL (Unified Form Language) is a unified language for definition of - variational forms intended for finite element discretization. More precisely, - it defines a fixed interface for choosing finite element spaces and defining - expressions for weak forms in a notation close to mathematical notation. - The form compilers FFC and SyFi use UFL as their end-user interface, - producing UFC implementations as their output. -Section: Programming/Python - -Format: pdf -Files: /usr/share/doc/python-ufl-doc/ufl-user-manual.pdf diff -Nru ufl-1.2.0/debian/python-ufl-doc.docs ufl-1.3.0/debian/python-ufl-doc.docs --- ufl-1.2.0/debian/python-ufl-doc.docs 2013-06-26 12:43:36.000000000 +0000 +++ ufl-1.3.0/debian/python-ufl-doc.docs 2014-01-10 12:04:31.000000000 +0000 @@ -1,2 +1 @@ -doc/manual/ufl-user-manual.pdf demo diff -Nru ufl-1.2.0/debian/watch ufl-1.3.0/debian/watch --- ufl-1.2.0/debian/watch 2013-06-26 12:43:36.000000000 +0000 +++ ufl-1.3.0/debian/watch 2014-01-10 12:04:31.000000000 +0000 @@ -1,2 +1,2 @@ version=3 -https://launchpad.net/ufl/+download https://launchpad.net/ufl/.*/ufl-(.*)\.tar\.gz +https://bitbucket.org/fenics-project/ufl/downloads/ufl-(.*)\.tar\.gz diff -Nru ufl-1.2.0/doc/manual/bibliography.bib ufl-1.3.0/doc/manual/bibliography.bib --- ufl-1.2.0/doc/manual/bibliography.bib 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/manual/bibliography.bib 1970-01-01 00:00:00.000000000 +0000 @@ -1,112 +0,0 @@ - -@misc{www:fenics, - author = {J. Hoffman and J. Jansson and C. Johnson and M. G. Knepley and R. C. Kirby and A. Logg and L. R. Scott and G. N. Wells}, - title = {{FE}ni{CS}}, - year = {2006}, - note = {URL: \url{http://www.fenics.org/}}, -} - -@misc{www:dolfin, - title = {{DOLFIN}}, - author = {J. Hoffman and J. Jansson and A. Logg and G. N. Wells}, - year = {2006}, - note = {URL: \url{http://www.fenics.org/dolfin/}} -} - -@misc{www:ffc, - author = {A. Logg}, - title = {{FFC}}, - year = {2007}, - note = {URL: \url{http://www.fenics.org/ffc/}}, -} - -@misc{www:syfi, - author = {M. Aln\ae{}s and K--A Mardal}, - title = {{S}y{F}i}, - year = {2007}, - note = {URL: \url{http://www.fenics.org/syfi/}}, -} - -@misc{www:ufc, - author = {Aln{\ae}s, Martin Sandve and Logg, Anders and Mardal, Kent-Andre and Skavhaug, Ola and Langtangen, Hans Petter}, - title = {{UFC}}, - year = {2009}, - note = {URL: \url{http://www.fenics.org/ufc/}}, -} - -@misc{www:ufl, - author = {Aln{\ae}s, Martin Sandve and Logg, Anders}, - title = {{UFL}}, - year = {2009}, - note = {URL: \url{http://www.fenics.org/ufl/}}, -} - -@Article{Simula.SC.96, - author = {Aln{\ae}s, Martin Sandve and Logg, Anders and Mardal, Kent-Andre and Skavhaug, Ola and Langtangen, Hans Petter}, - title = {Unified Framework for Finite Element Assembly}, - year = {2009}, - abstract = {}, - journal = {International Journal of Computational Science and Engineering} -} - -@misc{www:sundance, - author = {Kevin Long}, - title = {Sundance}, - year = {2006}, - note = {URL: \url{http://software.sandia.gov/sundance/}} -} - -@misc{www:deal.II, - author = {Wolfgang Bangerth and Ralf Hartmann and Guido Kanschat}, - title = {{\tt deal.{I}{I}} {D}ifferential {E}quations {A}nalysis {L}ibrary}, - year = {2006}, - note = {URL: \url{http://www.dealii.org/}} -} - -@misc{www:petsc, - author = {Satish Balay and Kris Buschelman and William D. Gropp and Dinesh Kaushik and Matthew G. Knepley and Lois Curfman McInnes and Barry F. Smith and Hong Zhang}, - title = {{PETS}c}, - year = {2006}, - note = {URL: \url{http://www.mcs.anl.gov/petsc/}} -} - -@misc{www:trilinos, - title = {Trilinos}, - note = {URL: \url{http://software.sandia.gov/trilinos/}}, -} - -@manual{www:diffpack, - title = {{Diffpack}}, - author = {A. M. Bruaset and H. P. Langtangen and others}, - year = {2006}, - note = {URL: \url{http://www.diffpack.com/}} -} - -@book{Lan99, - author = {H. P. Langtangen}, - title = {Computational Partial Differential Equations -- Numerical Methods and Diffpack Programming}, - publisher = {Springer}, - year = {1999}, - series = {Lecture Notes in Computational Science and Engineering}, -} - -@book{ZieTay67, - author = {O. C. Zienkiewicz and R. L. Taylor and J. Z. Zhu}, - title = {The Finite Element Method --- Its Basis and Fundamentals, 6th edition}, - publisher = {Elsevier}, - year = {2005, first published in 1967}, -} - -@book{Hug87, - author = {T. J. R. Hughes}, - title = {The Finite Element Method: Linear Static and Dynamic Finite Element Analysis}, - publisher = {Prentice-Hall}, - year = {1987}, -} - -@book{Cia78, - author = {P. G. Ciarlet}, - title = {The Finite Element Method for Elliptic Problems}, - publisher = {North-Holland, Amsterdam, New York, Oxford}, - year = {1978}, -} diff -Nru ufl-1.2.0/doc/manual/chapters/contributing-ufl.tex ufl-1.3.0/doc/manual/chapters/contributing-ufl.tex --- ufl-1.2.0/doc/manual/chapters/contributing-ufl.tex 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/manual/chapters/contributing-ufl.tex 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -% UFL-specific part of chapter contributing.tex - -%------------------------------------------------------------------------------ - -\section{License agreement} -\index{license} - -By contributing a patch to \package{}, you agree to license your -contributed code under the GNU General Public License (a condition -also built into the GPL license of the code you have modified). Before -creating the patch, please update the author and date information of -the file(s) you have modified according to the following example: - -\begin{code} -__author__ = "Anders Logg (logg@simula.no)" -__date__ = "2004-11-17 -- 2005-09-09" -__copyright__ = "Copyright (C) 2004, 2005 Anders Logg" -__license__ = "GNU GPL Version 3 or any later version" - -# Modified by Your Name 2007 -\end{code} - -As a rule of thumb, the original author of a file holds the copyright. diff -Nru ufl-1.2.0/doc/manual/chapters/contributing.tex ufl-1.3.0/doc/manual/chapters/contributing.tex --- ufl-1.2.0/doc/manual/chapters/contributing.tex 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/manual/chapters/contributing.tex 1970-01-01 00:00:00.000000000 +0000 @@ -1,224 +0,0 @@ -% This chapter is common to the DOLFIN and FFC manuals. - -\chapter{Contributing code} -\index{contributing} - -If you have created a new module, fixed a bug somewhere, or have made -a small change which you want to contribute to \package{}, then the -best way to do so is to send us your contribution in the form of a -patch. A patch is a file which describes how to transform a file or -directory structure into another. The patch is built by comparing a -version which both parties have against the modified version which -only you have. Patches can be created with Mercurial -or \texttt{diff}. - -%------------------------------------------------------------------------------ -\section{Creating bundles/patches} -%------------------------------------------------------------------------------ -\subsection{Creating a Mercurial (hg) bundle} -\index{hg} -\index{Mercurial} -\index{bundle} - -Creating bundles is the preferred way of submitting patches. It has -several advantages over plain diffs. If you are a frequent -contributor, consider publishing your source tree so that the \package{} -maintainers (and other users) may pull your changes directly from your -tree. - -A bundle contains your contribution to \package{} in the form of a -binary patch file generated by Mercurial~\cite{www:Mercurial}, -the revision control system used by \package{}. -Follow the procedure described below to create your bundle. -\begin{enumerate} -\item - Clone the \package{} repository: - \begin{macrocode} -# hg clone http://www.fenics.org/hg/\packagett{} - \end{macrocode} -\item \label{label:AddFilesHg} If your contribution consists of new files, - add them to the - correct location in the \package{} directory tree. Enter the \package{} - directory and add these files to the local repository by typing: - \begin{macrocode} -# hg add - \end{macrocode} - where \texttt{} is the list of new files. - You do not have to take any action for previously existing files - which have been modified. Do not add temporary or binary files. -\item Enter the \package{} directory and commit your contribution: - \begin{macrocode} -# hg commit -m "" - \end{macrocode} - where \texttt{} is a short description of what - your patch accomplishes. -\item Create the bundle: - \begin{macrocode} -# hg bundle \packagett{}--.hg - http://www.fenics.org/hg/\packagett{} - \end{macrocode} - written as one line, where \texttt{} is a keyword that - can be used to identify the bundle as coming from you (your username, - last name, first name, a nickname etc) and \texttt{} is - today's date in the format \texttt{yyyy-mm-dd}.\\ - The bundle now exists as \texttt{\packagett{}--.hg}. -\end{enumerate} - -When you add your contribution at point~\ref{label:AddFilesHg}, -make sure that only the files -that you want to share are present by typing: -\begin{macrocode} -# hg status -\end{macrocode} -This will produce a list of files. Those marked with a question mark -are not tracked by Mercurial. You can track them by using the -\texttt{add} command as shown above. Once you have -added these files, their status changes form \texttt{?} to \texttt{A}. - - -%------------------------------------------------------------------------------ -\subsection{Creating a standard (diff) patch file} -\index{diff} -\index{patch} - -The tool used to create a patch is called \texttt{diff} and the tool -used to apply the patch is called \texttt{patch}. - -Here's an example of how it works. Start from the latest release of -\package{}, which we here assume is release x.y.z. You then have a -directory structure under \texttt{\packagett{}-x.y.z} where you have made -modifications to some files which you think could be useful to -other users. - -\begin{enumerate} -\item - Clean up your modified directory structure to remove temporary and binary - files which will be rebuilt anyway: - \begin{code} -# make clean - \end{code} -\item - From the parent directory, rename the \package{} directory to something else: - \begin{macrocode} -# mv \packagett{}-x.y.z \packagett{}-x.y.z-mod - \end{macrocode} -\item - Unpack the version of \package{} that you started from: - \begin{macrocode} -# tar zxfv \packagett{}-x.y.z.tar.gz - \end{macrocode} -\item - You should now have two \package{} directory structures in your current directory: - \begin{macrocode} -# ls -\packagett{}-x.y.z -\packagett{}-x.y.z-mod - \end{macrocode} -\item - Now use the \texttt{diff} tool to create the patch: - \begin{macrocode} -# diff -u --new-file --recursive \packagett{}-x.y.z - \packagett{}-x.y.z-mod > \packagett{}--.patch - \end{macrocode} - written as one line, where \texttt{} is a keyword that - can be used to identify the patch as coming from you (your username, - last name, first name, a nickname etc) and \texttt{} is - today's date in the format \texttt{yyyy-mm-dd}. -\item - The patch now exists as \texttt{\packagett{}--.patch} - and can be distributed to other people who already have - \texttt{\packagett{}-x.y.z} to easily create your modified version. If the - patch is large, compressing it with for example \texttt{gzip} is - advisable: - \begin{macrocode} -# gzip \packagett{}--.patch - \end{macrocode} -\end{enumerate} - -%------------------------------------------------------------------------------ -\section{Sending bundles/patches} -\index{patch} -\index{bundle} - -Patch and bundle files should be sent to the \package{} mailing list at the address -\begin{macrocode} -\packagett{}-dev@fenics.org -\end{macrocode} -Include a short description of what your patch/bundle accomplishes. Small -patches/bundles have a better chance of being accepted, so if you are making a -major contribution, please consider breaking your changes up into -several small self-contained patches/bundles if possible. - -%------------------------------------------------------------------------------ -\section{Applying changes} -%------------------------------------------------------------------------------ -\subsection{Applying a Mercurial bundle} -\index{bundle} -\index{hg} -\index{Mercurial} - -You have received a patch in the form of a Mercurial bundle. The following -procedure shows how to apply the patch to your version of \package{}. -\begin{enumerate} -\item Before applying the patch, you can check - its content by entering the \package{} directory and typing: - \begin{macrocode} -# hg incoming -p - bundle:///\packagett{}--.hg - \end{macrocode} - written as one line, where \texttt{} is the path to the - bundle. \texttt{} can be omitted if the bundle is in the - \package{} directory. The option \texttt{-p} can be omitted if you - are only interested in a short summary of the changesets found in - the bundle. -\item To apply the patch to your version of \package{} type: - \begin{macrocode} -# hg unbundle /\packagett{}--.hg - \end{macrocode} - followed by: - \begin{macrocode} - # hg update - \end{macrocode} -\end{enumerate} - -%------------------------------------------------------------------------------ -\subsection{Applying a standard patch file} -\index{patch} - -Let's say that a patch has been built relative to \package{} release x.y.z. -The following description then shows how to apply the patch to a clean -version of release x.y.z. - -\begin{enumerate} -\item - Unpack the version of \package{} which the patch is built relative to: - \begin{macrocode} -# tar zxfv \packagett{}-x.y.z.tar.gz - \end{macrocode} -\item - Check that you have the patch \texttt{\packagett{}--.patch} and the \package{} - directory structure in the current directory: - \begin{macrocode} -# ls -\packagett{}-x.y.z -\packagett{}--.patch - \end{macrocode} - Unpack the patch file using \texttt{gunzip} if necessary. -\item - Enter the \package{} directory structure: - \begin{macrocode} -# cd \packagett{}-x.y.z - \end{macrocode} -\item - Apply the patch: - \begin{macrocode} -# patch -p1 < ../\packagett{}--.patch - \end{macrocode} - The option \texttt{-p1} strips the leading directory from the filename - references in the patch, to match the fact that we are applying the - patch from inside the directory. Another useful option to - \texttt{patch} is \texttt{--dry-run} which can be used to test the - patch without actually applying it. -\item - The modified version now exists as \texttt{\packagett{}-x.y.z}. -\end{enumerate} diff -Nru ufl-1.2.0/doc/manual/chapters/license.tex ufl-1.3.0/doc/manual/chapters/license.tex --- ufl-1.2.0/doc/manual/chapters/license.tex 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/manual/chapters/license.tex 1970-01-01 00:00:00.000000000 +0000 @@ -1,690 +0,0 @@ -\chapter{License} -\index{GPL} -\index{GNU General Public License} -\index{license} - -\package{} is free software: you can redistribute it and/or modify it -under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -The GNU GPL is included verbatim below. - -\footnotesize -\begin{verbatim} - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. -\end{verbatim} -\normalsize Binary files /tmp/_SsVKR_4gW/ufl-1.2.0/doc/manual/ufl-user-manual.pdf and /tmp/pn3SATuH3l/ufl-1.3.0/doc/manual/ufl-user-manual.pdf differ diff -Nru ufl-1.2.0/doc/sphinx/scripts/generate_index.py ufl-1.3.0/doc/sphinx/scripts/generate_index.py --- ufl-1.2.0/doc/sphinx/scripts/generate_index.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/sphinx/scripts/generate_index.py 2014-01-07 13:29:26.000000000 +0000 @@ -34,11 +34,6 @@ Documentation for UFL v%s ############################################# -UFL User Manual -=============== - -* :ref:`UFL User Manual ` (Start here) - .. UFL Language Reference .. ====================== .. @@ -53,7 +48,6 @@ :hidden: :maxdepth: 1 - user/user_manual modules @@ -90,7 +84,7 @@ def main(input_dir, version): - files = ["ufl.rst", "ufl.algorithms.rst"] + files = ["ufl.rst", "ufl.finiteelement.rst", "ufl.algorithms.rst"] insert_labels(input_dir, files) generate_index_file(input_dir, version) diff -Nru ufl-1.2.0/doc/sphinx/source/conf.py ufl-1.3.0/doc/sphinx/source/conf.py --- ufl-1.2.0/doc/sphinx/source/conf.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/sphinx/source/conf.py 2014-01-07 13:29:26.000000000 +0000 @@ -16,11 +16,12 @@ # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +needs_sphinx = '1.1' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.pngmath'] +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', + 'sphinx.ext.mathjax'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -36,16 +37,16 @@ # General information about the project. project = u'UFL' -copyright = u'UFL Core, https://launchpad.net/~ufl-core' +copyright = u'FEniCS Project, http://www.fenicsproject.org/' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = '1.1' +version = '1.2' # The full version, including alpha/beta/rc tags. -release = '1.1.0-alpha' +release = '1.2.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -79,7 +80,7 @@ pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. -modindex_common_prefix = ["ufl.", "ufl.algorithms."] +modindex_common_prefix = ["ufl.", "ufl.finiteelement", "ufl.algorithms."] # -- Options for HTML output --------------------------------------------------- diff -Nru ufl-1.2.0/doc/sphinx/source/user/algorithms.rst ufl-1.3.0/doc/sphinx/source/user/algorithms.rst --- ufl-1.2.0/doc/sphinx/source/user/algorithms.rst 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/sphinx/source/user/algorithms.rst 1970-01-01 00:00:00.000000000 +0000 @@ -1,413 +0,0 @@ -********** -Algorithms -********** -\label{chapter:algorithms} - -Algorithms to work with UFL forms and expressions can be found in the -submodule \texttt{ufl.algorithms}. You can import all of them with -the line:: - - from ufl.algorithms import * - -This chapter gives an overview of (most of) the implemented algorithms. -The intended audience is primarily developers, but advanced users may -find information here useful for debugging. - -While domain specific languages introduce notation to express particular -ideas more easily, which can reduce the probability of bugs in user code, -they also add yet another layer of abstraction which can make debugging -more difficult when the need arises. Many of the utilities described -here can be useful in that regard. - - -Formatting expressions -====================== - -Expressions can be formatted in various ways for inspection, which is -particularly useful for debugging. We use the following as an example -form for the formatting sections below:: - - element = FiniteElement("CG", triangle, 1) - v = TestFunction(element) - u = TrialFunction(element) - c = Coefficient(element) - f = Coefficient(element) - a = c*u*v*dx + f*v*ds - - -str ---- -Compact human readable pretty printing. Useful in interactive Python -sessions. Example output of \texttt{str(a)}:: - - TODO - -repr ----- -Accurate description of expression, with the property that -\texttt{eval(repr(a)) == a}. Useful to see which representation types -occur in an expression, especially if \texttt{str(a)} is ambiguous. -Example output of \texttt{repr(a)}:: - - TODO - - -Tree formatting ---------------- - -Ascii tree formatting, useful to inspect the tree structure of -an expression in interactive Python sessions. Example output of -\texttt{tree\_format(a)}:: - - TODO - - -LaTeX formatting ----------------- - -See chapter about commandline utilities. - - -Dot formatting --------------- - -See chapter about commandline utilities. - - -Inspecting and manipulating the expression tree -=============================================== - -This subsection is mostly for form compiler developers and technically -interested users. - -TODO: More details about traversal and transformation algorithms for -developers. - -Traversing expressions ----------------------- - -``iter\_expressions`` -^^^^^^^^^^^^^^^^^^^^^ - -Example usage:: - - q = f*v - r = g*v - s = u*v - a = q*dx(0) + r*dx(1) + s*ds(0) - for e in iter_expressions(a): - print str(e) - -``post\_traversal`` -^^^^^^^^^^^^^^^^^^^ - -TODO: traversal.py - -``pre\_traversal`` -^^^^^^^^^^^^^^^^^^ - -TODO: traversal.py - - -``walk`` -^^^^^^^^ - -TODO: traversal.py - - -``traverse\_terminals`` -^^^^^^^^^^^^^^^^^^^^^^^ - -TODO: traversal.py - - -Extracting information ----------------------- - -TODO: analysis.py - - -Transforming expressions ------------------------- - -So far the algorithms presented has been about inspecting expressions -in various ways. Some recurring patterns occur when writing algorithms -to modify expressions, either to apply mathematical transformations or -to change their representation. Usually, different expression node types -need different treatment. - -To assist in such algorithms, UFL provides the \texttt{Transformer} -class. This implements a variant of the Visitor pattern to enable easy -definition of transformation rules for the types you wish to handle. - -Shown here is maybe the simplest transformer possible:: - - class Printer(Transformer): - def __init__(self): - Transformer.__init__(self) - - def expr(self, o, *operands): - print "Visiting", str(o), "with operands:" - print ", ".join(map(str,operands)) - return o - - element = FiniteElement("CG", triangle, 1) - v = TestFunction(element) - u = TrialFunction(element) - a = u*v - - p = Printer() - p.visit(a) - -The call to \texttt{visit} will traverse \texttt{a} and call -\texttt{Printer.expr} on all expression nodes in post--order, with the -argument \texttt{operands} holding the return values from visits to the -operands of \texttt{o}. The output is:: - - TODO - -Implementing \texttt{expr} above provides a default handler for any -expression node type. For each subclass of \texttt{Expr} you can -define a handler function to override the default by using the name -of the type in underscore notation, e.g. \texttt{vector\_constant} -for \texttt{VectorConstant}. The constructor of \texttt{Transformer} -and implementation of \texttt{Transformer.visit} handles the mapping -from type to handler function automatically. - -Here is a simple example to show how to override default behaviour:: - - class CoefficientReplacer(Transformer): - def __init__(self): - Transformer.__init__(self) - - expr = Transformer.reuse_if_possible - terminal = Transformer.always_reuse - - def coefficient(self, o): - return FloatValue(3.14) - - element = FiniteElement("CG", triangle, 1) - v = TestFunction(element) - f = Coefficient(element) - a = f*v - - r = CoefficientReplacer() - b = r.visit(a) - print b - -The output of this code is the transformed expression \texttt{b == -3.14*v}. This code also demonstrates how to reuse existing handlers. -The handler \texttt{Transformer.reuse\_if\_possible} will return the -input object if the operands have not changed, and otherwise reconstruct -a new instance of the same type but with the new transformed operands. -The handler \texttt{Transformer.always\_reuse} always reuses the instance -without recursing into its children, usually applied to terminals. -To set these defaults with less code, inherit \texttt{ReuseTransformer} -instead of \texttt{Transformer}. This ensures that the parts of the -expression tree that are not changed by the transformation algorithms -always reuse the same instances. - -We have already mentioned the difference between pre--traversal -and post--traversal, and some times you need to combine the -two. \texttt{Transformer} makes this easy by checking the number of -arguments to your handler functions to see if they take transformed -operands as input or not. If a handler function does not take more -than a single argument in addition to self, its children are not visited -automatically, and the handler function must call \texttt{visit} on its -operands itself. - -Here is an example of mixing pre- and post-traversal:: - - class Traverser(ReuseTransformer): - def __init__(self): - ReuseTransformer.__init__(self) - - def sum(self, o): - operands = o.operands() - newoperands = [] - for e in operands: - newoperands.append( self.visit(e) ) - return sum(newoperands) - - element = FiniteElement("CG", triangle, 1) - f = Coefficient(element) - g = Coefficient(element) - h = Coefficient(element) - a = f+g+h - - r = Traverser() - b = r.visit(a) - print b - -This code inherits the \texttt{ReuseTransformer} like explained above, -so the default behaviour is to recurse into children first and then call -\texttt{Transformer.reuse\_if\_possible} to reuse or reconstruct each -expression node. Since \texttt{sum} only takes \texttt{self} and the -expression node instance \texttt{o} as arguments, its children are not -visited automatically, and \texttt{sum} calls on \texttt{self.visit} -to do this explicitly. - - -Automatic differentiation implementation -======================================== - -This subsection is mostly for form compiler developers and technically -interested users. - -TODO: More details about AD algorithms for developers. - - -Forward mode ------------- - -TODO: forward\_ad.py - - -Reverse mode ------------- - -TODO: reverse\_ad.py - -Mixed derivatives ------------------ - -TODO: ad.py - - -Computational graphs -==================== - -This section is for form compiler developers and is probably of no -interest to end-users. - -An expression tree can be seen as a directed acyclic graph (DAG). -To aid in the implementation of form compilers, UFL includes tools to -build a linearized\footnote{Linearized as in a linear datastructure, -do not confuse this with automatic differentiation.} computational graph -from the abstract expression tree. - -A graph can be partitioned into subgraphs based on dependencies of -subexpressions, such that a quadrature based compiler can easily place -subexpressions inside the right sets of loops. - -% TODO: Finish and test this before writing about it :) -%The vertices of a graph can be reordered to improve the efficiency -%of the generated code, an operation usually called operation scheduling. - -The computational graph ------------------------ - -TODO: finish graph.py: - - TODO - -Consider the expression: - -.. math: - - f = (a + b) * (c + d) - -where a, b, c, d are arbitrary scalar expressions. The \emph{expression -tree} for f looks like this:: - - TODO: Make figures. - a b c d - \ / \ / - + + - \ / - * - -In UFL f is represented like this expression tree. If a,b,c,d are all -distinct Coefficient instances, the UFL representation will look like this:: - - Coefficient Coefficient Coefficient Coefficient - \ / \ / - Sum Sum - \ / - Product - -If we instead have the expression - -.. math: - - f = (a + b) * (a - b) - -the tree will in fact look like this, with the functions a and b only -represented once:: - - Coefficient Coefficient - | \ / | - | Sum Product -- IntValue(-1) - | | | - | Product | - | | | - |---------- Sum ------| - -The expression tree is a directed acyclic graph (DAG) where the vertices -are Expr instances and each edge represents a direct dependency between -two vertices, i.e. that one vertex is among the operands of another. -A graph can also be represented in a linearized data structure, consisting -of an array of vertices and an array of edges. This representation is -convenient for many algorithms. An example to illustrate this graph -representation:: - - G = V, E - V = [a, b, a+b, c, d, c+d, (a+b)*(c+d)] - E = [(6,2), (6,5), (5,3), (5,4), (2,0), (2,1)] - -In the following this representation of an expression will be called -the \emph{computational graph}. To construct this graph from a UFL -expression, simply do:: - - G = Graph(expression) - V, E = G - -The Graph class can build some useful data structures for use in -algorithms:: - - Vin = G.Vin() # Vin[i] = list of vertex indices j such that there is an edge from V[j] to V[i] - Vout = G.Vout() # Vout[i] = list of vertex indices j such that there is an edge from V[i] to V[j] - Ein = G.Ein() # Ein[i] = list of edge indices j such that E[j] is an edge to V[i], e.g. E[j][1] == i - Eout = G.Eout() # Eout[i] = list of edge indices j such that E[j] is an edge from V[i], e.g. E[j][0] == i - -The ordering of the vertices in the graph can in principle be arbitrary, -but here they are ordered such that - -.. math: - - v_i \prec v_j, \quad \forall j > i, - -where $a \prec b$ means that $a$ does not depend on $b$ directly or -indirectly. - -Another property of the computational graph built by UFL is that no -identical expression is assigned to more than one vertex. This is -achieved efficiently by inserting expressions in a dict (a hash map) -during graph building. - -In principle, correct code can be generated for an expression from its -computational graph simply by iterating over the vertices and generating -code for each one separately. However, we can do better than that. - - -Partitioning the graph ----------------------- - -To help generate better code efficiently, we can partition vertices by -their dependencies, which allows us to, e.g., place expressions outside -the quadrature loop if they don't depend (directly or indirectly) on -the spatial coordinates. This is done simply by:: - - P = partition(G) # TODO - -TODO: finish dependencies.py - - - -%\subsection{Reordering graph vertices} -%TODO: finish scheduling.py - -%\begin{code} -%TODO -%\end{code} - diff -Nru ufl-1.2.0/doc/sphinx/source/user/command_line_utils.rst ufl-1.3.0/doc/sphinx/source/user/command_line_utils.rst --- ufl-1.2.0/doc/sphinx/source/user/command_line_utils.rst 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/sphinx/source/user/command_line_utils.rst 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -********************* -Commandline utilities -********************* - - -Validation and debugging: ``ufl-analyse`` -========================================= -\index{\ttt{ufl-analyse}} - -The command \ttt{ufl-analyse} loads all forms found in a \ttt{.ufl} -file, tries to discover any errors in them, and prints various kinds of -information about each form. Basic usage is:: - - # ufl-analyse myform.ufl - -For more information, type:: - - # ufl-analyse --help - -Formatting and visualization: ``ufl-convert`` -============================================= -\index{\ttt{ufl-convert}} - -The command \ttt{ufl-convert} loads all forms found in a \ttt{.ufl} -file, compiles them into a different form or extracts some information -from them, and writes the result in a suitable file format. - -To try this tool, go to the \ttt{demo/} directory of the UFL source -tree. Some of the features to try are basic printing of \ttt{str} and -\ttt{repr} string representations of each form:: - - # ufl-convert --format=str stiffness.ufl - # ufl-convert --format=repr stiffness.ufl - -compilation of forms to mathematical notation in LaTeX:: - - # ufl-convert --filetype=pdf --format=tex --show=1 stiffness.ufl - -LaTeX output of forms after processing with UFL compiler utilities:: - - # ufl-convert -tpdf -ftex -s1 --compile=1 stiffness.ufl - -and visualization of expression trees using graphviz via compilation of -forms to the dot format:: - - # ufl-convert -tpdf -fdot -s1 stiffness.ufl - -Type \ttt{ufl-convert --help} for more details. - -Conversion from FFC form files: ``form2ufl`` -============================================ -\index{\ttt{form2ufl}} - -The command \ttt{form2ufl} can be used to convert old FFC \ttt{.form} -files to UFL format. To convert a form file named \ttt{myform.form} -to UFL format, simply type:: - - # form2ufl myform.ufl - -Note that although, the \ttt{form2ufl} script may be helpful as a guide -to converting old FFC \ttt{.form} files, it is not foolproof and may -not always yield valid UFL files. - diff -Nru ufl-1.2.0/doc/sphinx/source/user/examples.rst ufl-1.3.0/doc/sphinx/source/user/examples.rst --- ufl-1.2.0/doc/sphinx/source/user/examples.rst 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/sphinx/source/user/examples.rst 1970-01-01 00:00:00.000000000 +0000 @@ -1,565 +0,0 @@ -************* -Example forms -************* -\label{chapter:examples} -\index{examples} - -The following examples illustrate basic usage of the form language -for the definition of a collection of standard multilinear forms. We -assume that ``dx`` has been declared as an integral over the interior of -:math:`\Omega` and that both ``i`` and ``j`` have been declared as a free -``Index``. - -The examples presented below can all be found in the subdirectory -``demo/`` of the UFL source tree together with numerous -other examples. - -The mass matrix -=============== -\index{mass matrix} - -As a first example, consider the bilinear form corresponding to a -mass matrix, - -.. math: - - a(v, u) = \int_{\Omega} v \, u \dx, - -which can be implemented in UFL as follows:: - - element = FiniteElement("Lagrange", triangle, 1) - - v = TestFunction(element) - u = TrialFunction(element) - - a = v*u*dx - -This example is implemented in the file ``mass.ufl`` in the collection -of demonstration forms included with the UFL source distribution. - -Poisson equation -================ -\index{Poisson's equation} - -The bilinear and linear forms form for Poisson's equation, - -.. math: - a(v, u) &=& \int_{\Omega} \nabla v \cdot \nabla u \dx, \\ - L(v; f) &=& \int_{\Omega} v \, f \dx, - -can be implemented as follows:: - - element = FiniteElement("Lagrange", triangle, 1) - - v = TestFunction(element) - u = TrialFunction(element) - f = Coefficient(element) - - a = dot(grad(v), grad(u))*dx - L = v*f*dx - -Alternatively, index notation can be used to express the scalar product -like this:: - - a = Dx(v, i)*Dx(u, i)*dx - -or like this:: - - a = v.dx(i)*u.dx(i)*dx - -This example is implemented in the file ``poisson.ufl`` in the collection -of demonstration forms included with the UFL source distribution. - - -Vector-valued Poisson -===================== -\index{vector-valued Poisson} - -The bilinear and linear forms for a system of (independent) Poisson -equations, - -.. math: - - a(v, u) &=& \int_{\Omega} \nabla v : \nabla u \dx, \\ - L(v; f) &=& \int_{\Omega} v \cdot f \dx, - -with :math:`v`, :math:`u` and :math:`f` vector-valued can be implemented -as follows:: - - element = VectorElement("Lagrange", triangle, 1) - - v = TestFunction(element) - u = TrialFunction(element) - f = Coefficient(element) - - a = inner(grad(v), grad(u))*dx - L = dot(v, f)*dx - -Alternatively, index notation may be used like this:: - - a = Dx(v[i], j)*Dx(u[i], j)*dx - L = v[i]*f[i]*dx - -or like this:: - - a = v[i].dx(j)*u[i].dx(j)*dx - L = v[i]*f[i]*dx - -This example is implemented in the file ``poisson\_system.ufl`` in -the collection of demonstration forms included with the UFL source -distribution. - - -The strain-strain term of linear elasticity -=========================================== -\index{elasticity} -\index{linear elasticity} -\index{strain} - -The strain-strain term of linear elasticity, - -.. math: - - a(v, u) = \int_{\Omega} \epsilon(v) : \epsilon(u) \dx, - -where - -.. math: - - \epsilon(v) = \frac{1}{2}(\nabla v + (\nabla v)^{\top}) - -can be implemented as follows:: - - element = VectorElement("Lagrange", tetrahedron, 1) - - v = TestFunction(element) - u = TrialFunction(element) - - def epsilon(v): - Dv = grad(v) - return 0.5*(Dv + Dv.T) - - a = inner(epsilon(v), epsilon(u))*dx - -Alternatively, index notation can be used to define the form:: - - a = 0.25*(Dx(v[j], i) + Dx(v[i], j))* \ - (Dx(u[j], i) + Dx(u[i], j))*dx - -or like this:: - - a = 0.25*(v[j].dx(i) + v[i].dx(j))* \ - (u[j].dx(i) + u[i].dx(j))*dx - -This example is implemented in the file ``elasticity.ufl`` in the -collection of demonstration forms included with the UFL source -distribution. - - -The nonlinear term of Navier--Stokes -==================================== -\index{Navier-Stokes} -\index{fixed-point iteration} - -The bilinear form for fixed-point iteration on the nonlinear term of -the incompressible Navier--Stokes equations, - -.. math: - - a(v, u; w) = \int_{\Omega} (w \cdot \nabla u) \cdot v \dx, - -with :math:`w` the frozen velocity from a previous iteration, can be -implemented as follows:: - - element = VectorElement("Lagrange", tetrahedron, 1) - - v = TestFunction(element) - u = TrialFunction(element) - w = Coefficient(element) - - a = dot(grad(u)*w, v)*dx - -alternatively using index notation like this:: - - a = v[i]*w[j]*Dx(u[i], j)*dx - -or like this:: - - a = v[i]*w[j]*u[i].dx(j)*dx - -This example is implemented in the file ``navier\_stokes.ufl`` in -the collection of demonstration forms included with the UFL source -distribution. - -The heat equation -================= -\index{heat equation} -\index{time-stepping} -\index{backward Euler} - -Discretizing the heat equation, - -.. math: - - \dot{u} - \nabla \cdot (c \nabla u) = f, - -in time using the :math:`\mathrm{dG}(0)` method (backward Euler), we -obtain the following variational problem for the discrete solution :math:`u_h -= u_h(x, t)`: Find :math:`u_h^n = u_h(\cdot, t_n)` with -:math:`u_h^{n-1} = u_h(\cdot, t_{n-1})` given such that - -.. math: - - \frac{1}{k_n} \int_{\Omega} v \, (u_h^n - u_h^{n-1}) \dx + - \int_{\Omega} c \, \nabla v \cdot \nabla u_h^n \dx = - \int_{\Omega} v \, f^n \dx - -for all test functions :math:`v`, where :math:`k = t_n - t_{n-1}` -denotes the time step . In the example below, we implement this -variational problem with piecewise linear test and trial functions, -but other choices are possible (just choose another finite element). - -Rewriting the variational problem in the standard form :math:`a(v, u_h) -= L(v)` for all :math:`v`, we obtain the following pair of bilinear and -linear forms: - -.. math: .. - - a(v, u_h^n; c, k) &=& \int_{\Omega} v \, u_h^n \dx + - k_n \int_{\Omega} c \, \nabla v \cdot \nabla u_h^n \dx, \\ - L(v; u_h^{n-1}, f, k) &=& \int_{\Omega} v \, u_h^{n-1} \dx + k_n \int_{\Omega} v \, f^n \dx, - -which can be implemented as follows:: - - element = FiniteElement("Lagrange", triangle, 1) - - v = TestFunction(element) # Test function - u1 = TrialFunction(element) # Value at t_n - u0 = Coefficient(element) # Value at t_n-1 - c = Coefficient(element) # Heat conductivity - f = Coefficient(element) # Heat source - k = Constant("triangle") # Time step - - a = v*u1*dx + k*c*dot(grad(v), grad(u1))*dx - L = v*u0*dx + k*v*f*dx - -This example is implemented in the file ``heat.ufl`` in the collection -of demonstration forms included with the UFL source distribution. - - -Mixed formulation of Stokes -=========================== -\index{Stokes' equations} -\index{mixed formulation} -\index{Taylor-Hood element} - -To solve Stokes' equations, - -.. math: - - \Delta u + \nabla p &=& f, \\ - \nabla \cdot u &=& 0, - -we write the variational problem in standard form :math:`a(v, u) = -L(v)` for all :math:`v` to obtain the following pair of bilinear and -linear forms: - -.. math: - - a((v, q), (u, p)) &=& \int_{\Omega} \nabla v : \nabla u - (\nabla \cdot v) \, p + - q \, (\nabla \cdot u) \dx, \\ - L((v, q); f) &=& \int_{\Omega} v \cdot f \dx. - -Using a mixed formulation with Taylor-Hood elements, this can be -implemented as follows:: - - cell = triangle - P2 = VectorElement("Lagrange", cell, 2) - P1 = FiniteElement("Lagrange", cell, 1) - TH = P2 * P1 - - (v, q) = TestFunctions(TH) - (u, p) = TrialFunctions(TH) - - f = Coefficient(P2) - - a = (inner(grad(v), grad(u)) - div(v)*p + q*div(u))*dx - L = dot(v, f)*dx - -This example is implemented in the file ``stokes.ufl`` in the collection -of demonstration forms included with the UFL source distribution. - -Mixed formulation of Poisson -============================ -\index{mixed Poisson} -\index{BDM elements} -\index{Brezzi--Douglas--Marini elements} - -We next consider the following formulation of Poisson's equation as a -pair of first order equations for :math:`\sigma \in H(\mathrm{div})` -and :math:`u \in L_2`: - -.. math: - \sigma + \nabla u &= 0, \\ - \nabla \cdot \sigma &= f. - -We multiply the two equations by a pair of test functions $\tau$ and -$w$ and integrate by parts to obtain the following variational -problem: Find $(\sigma, u) \in V = H(\mathrm{div}) \times L_2$ such that - -.. math: - - a((\tau, w), (\sigma, u)) = L((\tau, w)) \quad \forall \, (\tau, w) \in V, - -where - -.. math: - - a((\tau, w), (\sigma, u)) &=& \int_{\Omega} \tau \cdot \sigma - \nabla \cdot \tau \, u - + w \nabla \cdot \sigma \dx, - \\ - L((\tau, w); f) &=& \int_{\Omega} w \cdot f \dx. - -We may implement the corresponding forms in our form language using -first order BDM :math:`H(\mathrm{div})`-conforming elements for $\sigma$ -and piecewise constant $L_2$-conforming elements for $u$ as follows:: - - cell = triangle - BDM1 = FiniteElement("Brezzi-Douglas-Marini", cell, 1) - DG0 = FiniteElement("Discontinuous Lagrange", cell, 0) - - element = BDM1 * DG0 - - (tau, w) = TestFunctions(element) - (sigma, u) = TrialFunctions(element) - - f = Coefficient(DG0) - - a = (dot(tau, sigma) - div(tau)*u + w*div(sigma))*dx - L = w*f*dx - -This example is implemented in the file ``mixed\_poisson.ufl`` in -the collection of demonstration forms included with the UFL source -distribution. - -Poisson equation with DG elements -================================= -\index{Discontinuous Galerkin} - -We consider again Poisson's equation, but now in an (interior penalty) -discontinuous Galerkin formulation: Find :math:`u \in V = L_2` such that - -.. math .. - - a(v, u) = L(v) \quad \forall v \in V, - -where - -.. math .. - - a(v, u; h) &= \int_{\Omega} \nabla v \cdot \nabla u \dx \\ - &+ \sum_S \int_S - - \langle \nabla v \rangle \cdot \llbracket u \rrbracket_n - - \llbracket v \rrbracket_n \cdot \langle \nabla u \rangle - + (\alpha/h) \llbracket v \rrbracket_n \cdot \llbracket u \rrbracket_n \dS \\ - &+ \int_{\partial\Omega} - - \nabla v \cdot \llbracket u \rrbracket_n - \llbracket v \rrbracket_n \cdot \nabla u - + (\gamma/h) v u \ds \\ - L(v; f, g) &= \int_{\Omega} v f \dx + \int_{\partial\Omega} v g \ds. - -The corresponding finite element variational problem for discontinuous -first order elements may be implemented as follows:: - - cell = triangle - DG1 = FiniteElement("Discontinuous Lagrange", cell, 1) - - v = TestFunction(DG1) - u = TrialFunction(DG1) - - f = Coefficient(DG1) - g = Coefficient(DG1) - #h = MeshSize(cell) # TODO: Do we include MeshSize in UFL? - h = Constant(cell) - alpha = 1 # TODO: Set to proper value - gamma = 1 # TODO: Set to proper value - - a = dot(grad(v), grad(u))*dx \ - - dot(avg(grad(v)), jump(u))*dS \ - - dot(jump(v), avg(grad(u)))*dS \ - + alpha/h('+')*dot(jump(v), jump(u))*dS \ - - dot(grad(v), jump(u))*ds \ - - dot(jump(v), grad(u))*ds \ - + gamma/h*v*u*ds - L = v*f*dx + v*g*ds - -This example is implemented in the file ``poisson\_dg.ufl`` in -the collection of demonstration forms included with the UFL source -distribution. - -Quadrature elements -=================== -\index{FE and QE} - -*FIXME: The code examples in this section have been mostly converted -to UFL syntax, but the quadrature elements need some more updating, as -well as the text. In UFL, I think we should define the element order -and not the number of points for quadrature elements, and let the form -compiler choose a quadrature rule. This way the form depends less on -the cell in use.* - -We consider here a nonlinear version of the Poisson's equation to -illustrate the main point of the ``Quadrature`` finite element -family. The strong equation looks as follows: - -.. math: - - - \nabla \cdot (1+u^2)\nabla u = f. - -The linearised bilinear and linear forms for this equation, - -.. math: - - a(v, u; u_0) &=& \int_{\Omega} (1+u_{0}^2) \nabla v \cdot \nabla u \dx - + \int_{\Omega} 2u_0 u \nabla v \cdot \nabla u_0 \dx, - \\ - L(v; u_0, f) &=& \int_{\Omega} v \, f \dx - - \int_{\Omega} (1+u_{0}^2) \nabla v \cdot \nabla u_0 \dx, - -can be implemented in a single form file as follows:: - - element = FiniteElement("Lagrange", triangle, 1) - - v = TestFunction(element) - u = TrialFunction(element) - u0 = Coefficient(element) - f = Coefficient(element) - - a = (1+u0**2)*dot(grad(v), grad(u))*dx + 2*u0*u*dot(grad(v), grad(u0))*dx - L = v*f*dx - (1+u0**2)*dot(grad(v), grad(u0))*dx - -Here, :math:`u_0` represents the solution from the previous Newton-Raphson -iteration. - -The above form will be denoted REF1 and serve as our reference -implementation for linear elements. A similar form (REF2) using quadratic -elements will serve as a reference for quadratic elements. - -Now, assume that we want to treat the quantities :math:`C = (1 + u_{0}^2)` -and :math:`\sigma_0 = (1+u_{0}^2) \nabla u_0` as given functions (to be -computed elsewhere). Substituting into bilinear linear forms, we obtain - -.. math: - a(v, u) &=& \int_{\Omega} \text{C} \nabla v \cdot \nabla u \dx - + \int_{\Omega} 2u_0 u \nabla v \cdot \nabla u_0 \dx, - \\ - L(v; \sigma_0, f) &=& \int_{\Omega} v \, f \dx - - \int_{\Omega} \nabla v \cdot \sigma_0 \dx. - -Then, two additional forms are created to compute the tangent C and -the gradient of :math:`u_0`. This situation shows up in plasticity and -other problems where certain quantities need to be computed elsewhere -(in user-defined functions). The three forms using the standard -``FiniteElement`` (linear elements) can then be implemented as:: - - element = FiniteElement("Lagrange", triangle, 1) - DG = FiniteElement("Discontinuous Lagrange", triangle, 0) - sig = VectorElement("Discontinuous Lagrange", triangle, 0) - - v = TestFunction(element) - u = TrialFunction(element) - u0 = Coefficient(element) - C = Coefficient(DG) - sig0 = Coefficient(sig) - f = Coefficient(element) - - a = v.dx(i)*C*u.dx(i)*dx + v.dx(i)*2*u0*u*u0.dx(i)*dx - L = v*f*dx - dot(grad(v), sig0)*dx - -and:: - - element = FiniteElement("Lagrange", triangle, 1) - DG = FiniteElement("Discontinuous Lagrange", triangle, 0) - - v = TestFunction(DG) - u = TrialFunction(DG) - u0= Coefficient(element) - - a = v*u*dx - L = v*(1.0 + u0**2)*dx - -and:: - - element = FiniteElement("Lagrange", triangle, 1) - DG = VectorElement("Discontinuous Lagrange", triangle, 0) - - v = TestFunction(DG) - u = TrialFunction(DG) - u0 = Coefficient(element) - - a = dot(v, u)*dx - L = dot(v, grad(u0))*dx - -The three forms can be implemented using the \texttt{QuadratureElement} -in a similar fashion in which only the element declaration is different:: - - # QE1NonlinearPoisson.ufl - element = FiniteElement("Lagrange", triangle, 1) - QE = FiniteElement("Quadrature", triangle, 2) - sig = VectorElement("Quadrature", triangle, 2) - -and:: - - # QE1Tangent.ufl - element = FiniteElement("Lagrange", triangle, 1) - QE = FiniteElement("Quadrature", triangle, 2) - -and:: - - # QE1Gradient.ufl - element = FiniteElement("Lagrange", triangle, 1) - QE = VectorElement("Quadrature", triangle, 2) - -Note that we use two points when declaring the ``QuadratureElement``. This -is because the RHS of the ``Tangent.form`` is second order and therefore -we need two points for exact integration. Due to consistency issues, -when passing functions around between the forms, we also need to use -two points when declaring the ``QuadratureElement`` in the other forms. - -Typical values of the relative residual for each Newton iteration for all -three approaches are shown in Table~\ref{tab:convergence1}. It is noted -that the convergence rate is quadratic as it should be for all 3 methods. - -Relative residuals for each approach for linear elements (label tab:convergence1): - - Iteration REF1 FE1 QE1 - ========= ==== === === - 1 6.3e-02 6.3e-02 6.3e-02 - 2 5.3e-04 5.3e-04 5.3e-04 - 3 3.7e-08 3.7e-08 3.7e-08 - 4 2.9e-16 2.9e-16 2.5e-16 - - - -However, if quadratic elements are used to interpolate the unknown field u, -the order of all elements in the above forms is increased by 1. This influences -the convergence rate as seen in Table (tab:convergence2). Clearly, using -the standard ``FiniteElement`` leads to a poor convergence whereas -the ``QuadratureElement`` still leads to quadratic convergence. - -Relative residuals for each approach for quadratic elements (label tab:convergence2): - - Iteration REF2 FE2 QE2 - ========= ==== === === - 1 2.6e-01 3.9e-01 2.6e-01 - 2 1.1e-02 4.6e-02 1.1e-02 - 3 1.2e-05 1.1e-02 1.6e-05 - 4 1.1e-11 7.2e-04 9.1e-09 - - -More examples -============= - -Feel free to send additional demo form files for your favourite PDE to -the UFL mailing list. - -%TODO: Modify rest of FFC example forms to UFL syntax and add here. - diff -Nru ufl-1.2.0/doc/sphinx/source/user/form_language.rst ufl-1.3.0/doc/sphinx/source/user/form_language.rst --- ufl-1.2.0/doc/sphinx/source/user/form_language.rst 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/sphinx/source/user/form_language.rst 1970-01-01 00:00:00.000000000 +0000 @@ -1,1899 +0,0 @@ -************* -Form language -************* - -UFL consists of a set of operators and atomic expressions that can be -used to express variational forms and functionals. Below we will define -all these operators and atomic expressions in detail. - -UFL is built on top of, or embedded in, the high level language Python. -Since the form language is built on top of Python, any Python code is -valid in the definition of a form (but not all Python code defines a -multilinear form). In particular, comments (lines starting with ``#`` -and functions (keyword \texttt{def}, see Section \ref{sec:user-defined} -below) are useful in the definition of a form. However, it is usually a -good idea to avoid using advanced Python features in the form definition, -to stay close to the mathematical notation. - -The entire form language can be imported in Python with the line - -.. code-block:: python - - from ufl import * - -which is assumed in all examples below and can be omitted in ``.ufl`` -files. This can be useful for experimenting with the language in an -interactive Python interpreter. - - -Forms and integrals -=================== - -UFL is designed to express forms in the following generalized format: - -.. math:: - - a(v_1, \ldots, v_r; w_1, \ldots, w_n) - = - \sum_{k=1}^{n_c} \int_{\Omega_k} - I^c_k(v_1, \ldots, v_r; w_1, \ldots w_n) dx - + \sum_{k=1}^{n_e} \int_{\partial\Omega_k} - I^e_k(v_1, \ldots, v_r; w_1, \ldots, w_n) ds - + \sum_{k=1}^{n_i} \int_{\Gamma_k} - I^i_k(v_1, \ldots, v_r; w_1, \ldots, w_n) dS. - -Here the form :math:`a` depends on the *form arguments* :math:`v_1, -\ldots, v_r` and the *form coefficients* :math:`w_1, \ldots, w_n`, -and its expression is a sum of integrals. Each term of a valid form -expression must be a scalar-valued expression integrated exactly once. How -to define form arguments and integrand expressions is detailed in the -rest of this chapter. - -Integrals are expressed through multiplication with a measure, -representing an integral over either of - -* the interior of the domain :math:`\Omega` (:math:`dx`, cell integral); - -* the boundary :math:`\partial\Omega` of :math:`\Omega` (:math:`ds`, - exterior facet integral); - -* the set of interior facets :math:`\Gamma` (:math:`dS`, interior facet - integral). - -UFL declares the measures ``dx`` :math:`\leftrightarrow dx`, ``ds`` -:math:`\leftrightarrow ds`, and ``dS`` :math:`\leftrightarrow dS`. - -As a basic example, assume ``v`` is a scalar-valued expression and -consider the integral of ``v`` over the interior of :math:`\Omega`. This -may be expressed as:: - - a = v*dx - -and the integral of ``v`` over :math:`\partial\Omega` is written as:: - - a = v*ds - -Alternatively, measures can be redefined to represent numbered subsets of -a domain, such that a form can take on different expressions on different -parts of the domain. If ``c``, ``e0`` and ``e1`` are scalar-valued -expressions, then:: - - a = c*dx + e0*ds(0) + e1*ds(1) - -represents - -.. math:: - - a = \int_\Omega c\,dx + \int_{\partial\Omega_0} e_0 \, ds + \int_{\partial\Omega_1} e_1 \, ds. - -where - -.. math:: - - \partial\Omega_0 \subset \partial\Omega, \qquad \partial\Omega_1 \subset \partial\Omega. - -Generalizing this further we end up with the expression \eqref{eq:form_integrals}. -Note that the domain :math:`\Omega` and its subdomains and boundaries -are not known to UFL. These will not enter the stage until -you start using UFL in a problem solving environment like DOLFIN. - -.. topic:: Advanced usage - - A feature for advanced users is attaching metadata to integrals. - This can be used to define different quadrature degrees for different - terms in a form, and to override other form compiler specific options - separately for different terms:: - - a = c0*dx(0, metadata0) + c1*dx(1, metadata1) - - The convention is that metadata should be a dict with any of the - following keys: - - * ``"integration_order"``: Integer defining the polynomial order - that should be integrated exactly. This is a compilation hint, and the - form compiler is free to ignore this if for example exact integration - is being used. - - * ``"ffc"``: A dict with further FFC specific options, see the - FFC manual. - - * ``"sfc"``: A dict with further SFC specific options, see the - SFC manual. - - * Other string: A dict with further options specific to some other - external code. - - Other standardized options may be added in later versions. :: - - metadata0 = {"ffc": {"representation": "quadrature"}} - metadata1 = {"integration_order": 7, - "ffc": {"representation": "tensor"}} - - a = v*u*dx(0, metadata1) + f*v*dx(0, metadata2) - - -Finite element spaces -===================== - -Before we can explain how form arguments are declared, we need to show how -to define function spaces. UFL can represent very flexible general -hierarchies of mixed finite elements, and has predefined names for most -common element families. - - -Cells ------ - -A polygonal cell is defined by a basic shape and a degree (note -that the other components of FEniCS do not yet handle cells of higher -degree, so this will only be useful in the future), written like:: - - cell = Cell(shape, degree) - -Valid shapes are "interval", "triangle", "tetrahedron", "quadrilateral", -and "hexahedron". Some examples:: - - # Cubic triangle cell - cell = Cell("triangle", 3) - - # Quadratic tetrahedron cell - cell = Cell("tetrahedron", 2) - -Objects for linear cells of all basic shapes are predefined:: - - # Predefined linear cells - cell = interval - cell = triangle - cell = tetrahedron - cell = quadrilateral - cell = hexahedron - -In the rest of this document, a variable name ``cell`` will be used where -any cell is a valid argument, to make the examples dimension independent -wherever possible. Using a variable ``cell`` to hold the cell type used -in a form is highly recommended, since this makes most form definitions -dimension independent. - - -Element families ----------------- - -UFL predefines a set of names of known element families. When defining -a finite element below, the argument ``family`` is a string and its -possible values include: - -* ``"Lagrange"`` or ``"CG"``, representing standard scalar - Lagrange finite elements (continuous piecewise polynomial functions); - -* ``"Discontinuous Lagrange"`` or ``"DG"``, representing - scalar discontinuous Lagrange finite elements (discontinuous piecewise - polynomial functions); - -* ``"Crouzeix-Raviart"`` or ``"CR"``, representing scalar - Crouzeix--Raviart elements; - -* ``"Brezzi-Douglas-Marini"`` or ``"BDM"``, representing - vector-valued Brezzi--Douglas--Marini :math:`H(\mathrm{div})` elements; - -* ``"Brezzi-Douglas-Fortin-Marini`` or ``"BDFM"``, representing - vector-valued Brezzi--Douglas--Fortin--Marini :math:`H(\mathrm{div})` - elements; - -* ``"Raviart-Thomas"`` or ``"RT"``, representing - vector-valued Raviart--Thomas :math:`H(\mathrm{div})` elements. - -* ``"Nedelec 1st kind H(div)"`` or ``"N1div"``, - representing vector-valued Nedelec :math:`H(\mathrm{div})` elements - (of the first kind). - -* ``"Nedelec 2st kind H(div)"`` or ``"N2div"``, - representing vector-valued Nedelec :math:`H(\mathrm{div})` elements - (of the second kind). - -* ``"Nedelec 1st kind H(curl)"`` or ``"N1curl"``, representing - vector-valued Nedelec :math:`H(\mathrm{curl})` elements - (of the first kind). - -* ``"Nedelec 2st kind H(curl)"`` or ``"N2curl"``, - representing vector-valued Nedelec :math:`H(\mathrm{curl})` elements - (of the second kind). - - %\item - % \texttt{"Bubble"} or \texttt{"B"}, representing FIXME; - -* ``"Quadrature"`` or ``"Q"``, representing artificial ``finite elements`` - with degrees of freedom being function evaluation at quadrature points; - -* ``"Boundary Quadrature"`` or ``"BQ"``, representing artificial - ``finite elements'' with degrees of freedom being function evaluation - at quadrature points on the boundary; - - -.. topic:: Advanced usage - - New elements can be added dynamically by the form compiler using the - function ``register_element``. See the docstring for details. - To see which elements are registered (including the standard built in - ones listed above) call the function ``show_elements``. - - -Basic elements --------------- - -A ``FiniteElement``, sometimes called a basic element, represents a -finite element in some family on a given cell with a certain polynomial -degree. Valid families and cells are explained above. -The notation is:: - - element = FiniteElement(family, cell, degree) - -Some examples:: - - element = FiniteElement("Lagrange", interval, 3) - element = FiniteElement("DG", tetrahedron, 0) - element = FiniteElement("BDM", triangle, 1) - - -Vector elements ---------------- - -A ``VectorElement`` represents a combination of basic elements such that -each component of a vector is represented by the basic element. The size -is usually omitted, the default size equals the geometry dimension. -The notation is:: - - element = VectorElement(family, cell, degree[, size]) - -Some examples:: - - element = VectorElement("CG", triangle, 2) - element = VectorElement("DG", tetrahedron, 0, size=6) - - -Tensor elements ---------------- - -A ``TensorElement`` represents a combination of basic elements such that -each component of a tensor is represented by the basic element. The -shape is usually omitted, the default shape is (d, d) where d is the -geometry dimension. The notation is:: - - element = TensorElement(family, cell, degree[, shape, symmetry]) - -Any shape tuple consisting of positive integers is valid, -and the optional symmetry can either be set to ``True`` -which means standard matrix symmetry (like :math:`A_{ij} = A_{ji}`), -or a ``dict`` like ``{ (0,1):(1,0), (0,2):(2,0) }`` -where the ``dict`` keys are index tuples that are -represented by the corresponding ``dict`` value. - -Examples:: - - element = TensorElement("CG", cell, 2) - element = TensorElement("DG", cell, 0, shape=(6,6)) - element = TensorElement("DG", cell, 0, symmetry=True) - element = TensorElement("DG", cell, 0, symmetry={(0,0): (1,1)}) - - -Mixed elements --------------- - -A ``MixedElement` represents an arbitrary combination of other elements. -``VectorElement`` and ``TensorElement`` are special cases of a -``MixedElement`` where all sub-elements are equal. - -General notation for an arbitrary number of subelements:: - - element = MixedElement(element1, element2[, element3, ...]) - -Shorthand notation for two subelements:: - - element = element1 * element2 - -Note: Multiplication is a binary operator, such that :: - - element = element1 * element2 * element3 - -represents ``(e1 * e2) * e3}, i.e. this is a mixed element with two -sub-elements ``(e1 * e2)`` and ``e3``. - -See section~\ref{sec:formarguments} for details on how defining -functions on mixed spaces can differ from functions on other -finite element spaces. - -Examples:: - - # Taylor-Hood element - V = VectorElement("Lagrange", cell, 2) - P = FiniteElement("Lagrange", cell, 1) - TH = V * P - - # A tensor-vector-scalar element - T = TensorElement("Lagrange", cell, 2, symmetry=True) - V = VectorElement("Lagrange", cell, 1) - P = FiniteElement("DG", cell, 0) - ME = MixedElement(T, V, P) - -EnrichedElement ---------------- - -The data type ``EnrichedElement`` represents the vector sum of two -(or more) finite elements. - -Example: The Mini element can be constructed as:: - - P1 = VectorElement("Lagrange", "triangle", 1) - B = VectorElement("Bubble", "triangle", 3) - Q = FiniteElement("Lagrange", "triangle", 1) - - Mini = (P1 + B) * Q - -Form arguments -============== - -Form arguments are divided in two groups, arguments and -coefficients. An ``Argument`` represents an -arbitrary basis function in a given discrete finite element space, -while a ``Coefficient`` represents a function in a discrete finite -element space that will be provided by the user at a later stage. The -number of ``Argument``\ s that occur in a ``Form`` equals -the arity of the form. - -Basis functions ---------------- - -The data type ``Argument`` represents a basis function on a -given finite element. An ``Argument`` must be created for a -previously declared finite element (simple or mixed):: - - v = Argument(element) - -Note that more than one ``Argument`` can be declared for the same -``FiniteElement``. Basis functions are associated with the arguments of -a multilinear form in the order of declaration. - -For a ``MixedElement``, the function ``Arguments`` can be used to -construct tuples of ``Argument``\ s, as illustrated here for a mixed -Taylor--Hood element:: - - v, q = Arguments(TH) - u, p = Arguments(TH) - -For a ``Argument`` on a ``MixedElement`` (or ``VectorElement`` -or ``TensorElement``), the function ``split`` can be used to extract -basis function values on subspaces, as illustrated here for a mixed -Taylor--Hood element:: - - vq = Argument(TH) - v, q = split(up) - -A shorthand for this is in place called ``Arguments``:: - - v, q = Arguments(TH) - -For convenience, ``TestFunction`` and ``TrialFunction`` are special -instances of ``Argument`` with the property that a ``TestFunction`` -will always be the first argument in a form and ``TrialFunction`` will -always be the second argument in a form (order of declaration does -not matter). Their usage is otherwise the same as for ``Argument``:: - - v = TestFunction(element) - u = TrialFunction(element) - v, q = TestFunctions(TH) - u, p = TrialFunctions(TH) - - -Coefficient functions ---------------------- - -The data type ``Coefficient`` represents a function belonging to a given -finite element space, that is, a linear combination of basis functions -of the finite element space. A ``Coefficient`` must be declared for a -previously declared ``FiniteElement``:: - - f = Coefficient(element) - -Note that the order in which ``Coefficient``\ s are declared is important, -directly reflected in the ordering they have among the arguments to each -``Form`` they are part of. - -``Coefficient`` is used to represent user-defined functions, including, e.g., -source terms, body forces, variable coefficients and stabilization terms. -UFL treats each ``Coefficient`` as a linear combination of unknown basis -functions with unknown coefficients, that is, UFL knows nothing about -the concrete basis functions of the element and nothing about the value -of the function. - -Note that more than one function can be declared for the same -``FiniteElement``. The following example declares two ``Argument``_s -and two ``Coefficient``\ s for the same ``FiniteElement``:: - - v = Argument(element) - u = Argument(element) - f = Coefficient(element) - g = Coefficient(element) - -For a ``Coefficient` on a ``MixedElement`` (or ``VectorElement`` or -``TensorElement``), the function ``split`` can be used to extract function -values on subspaces, as illustrated here for a mixed Taylor--Hood element:: - - up = Coefficient(TH) - u, p = split(up) - -A shorthand for this is in place called ``Coefficients``:: - - u, p = Coefficient(TH) - -Spatially constant (or discontinuous piecewise constant) functions can -conveniently be represented by ``Constant``, ``VectorConstant``, and -``TensorConstant``:: - - c0 = Constant(cell) - v0 = VectorConstant(cell) - t0 = TensorConstant(cell) - -These three lines are equivalent with first defining -DG0 elements and then defining a ``Coefficient`` -on each, illustrated here:: - - DG0 = FiniteElement("Discontinuous Lagrange", cell, 0) - DG0v = VectorElement("Discontinuous Lagrange", cell, 0) - DG0t = TensorElement("Discontinuous Lagrange", cell, 0) - - c1 = Coefficient(DG0) - v1 = Coefficient(DG0v) - t1 = Coefficient(DG0t) - -Basic Datatypes -=============== - -UFL expressions can depend on some other quantities in addition to the -functions and basis functions described above. - -Literals and geometric quantities ---------------------------------- - -Some atomic quantities are derived from the cell. For example, the -(global) spatial coordinates are available as a vector valued expression -``cell.x``:: - - # Linear form for a load vector with a sin(y) coefficient - v = TestFunction(element) - x = cell.x - L = sin(x[1])*v*dx - -Another quantity is the (outwards pointing) facet normal ``cell.n``. -The normal vector is only defined on the boundary, so it can't be used -in a cell integral. - -Example functional ``M``, an integral of the normal component of a -function ``g`` over the boundary:: - - n = cell.n - g = Coefficient(VectorElement("CG", cell, 1)) - M = dot(n, g)*ds - -Python scalars (int, float) can be used anywhere a scalar expression -is allowed. Another literal constant type is ``Identity`` which -represents an :math:`n\times n` unit matrix of given size :math:`n`, as in this example:: - - # Geometric dimension - d = cell.d - - # d x d identiy matrix - I = Identity(d) - - # Kronecker delta - delta_ij = I[i,j] - -.. note: Advanced usage - - Note that there are some differences from FFC. - In particular, using ``FacetNormal`` or ``cell.n`` - does not implicitly add another coefficient Coefficient to the form, - the normal should be automatically computed in UFC code. - Note also that ``MeshSize`` has been removed because the - meaning is ambiguous (does it mean min, max, avg, cell radius?), - so use a ``Constant`` instead. - - -Indexing and tensor components -============================== - -UFL supports index notation, which is often a convenient way to -express forms. The basic principle of index notation is that summation -is implicit over indices repeated twice in each term of an expression. -The following examples illustrate the index notation, assuming that -each of the variables ``i`` and ``j`` have been declared as -a free ``Index``: - -* ``v[i]*w[i]``: :math:`\sum_{i=0}^{n-1} v_i w_i = \mathbf{v}\cdot\mathbf{w}` - -* ``Dx(v, i)*Dx(w, i)``: - :math:`\sum_{i=0}^{d-1} \frac{\partial v}{\partial x_i} \frac{\partial w}{\partial x_i} - = \nabla v \cdot \nabla w` - -* ``Dx(v[i], i)``: :math:`\sum_{i=0}^{d-1} - \frac{\partial v_i}{\partial x_i} = \nabla \cdot v` - -* ``Dx(v[i], j)*Dx(w[i], j)```: :math:`\sum_{i=0}^{n-1} \sum_{j=0}^{d-1} - \frac{\partial v_i}{\partial x_j} \frac{\partial w_i}{\partial x_j} - = \nabla \mathbf{v} : \nabla \mathbf{w}` - -Here we will try to very briefly summarize the basic concepts of tensor -algebra and index notation, just enough to express the operators in UFL. - -Assuming an Euclidean space in :math:`d` dimensions with :math:`1 \le -d 3`, and a set of orthonormal basis vectors :math:`\mathbf{i}_i` for :math:`i -\in {0, \ldots, d-1 }`, we can define the dot product of any two basis -functions as - -.. math:: - - \mathbf{i}_{i} \cdot \mathbf{i}_{j} = \delta_{ij}, - -where :math:`\delta_{ij}` is the Kronecker delta - -.. math:: - - \delta_{ij} - \equiv - \begin{cases} - 1, \quad i = j, \\ - 0, \quad \text{otherwise}. - \end{cases} - -A rank 1 tensor (vector) quantity :math:`\mathbf{v}` can be represented in -terms of unit vectors and its scalar components in that basis. In tensor -algebra it is common to assume implicit summation over indices repeated -twice in a product:: - -.. math:: - - \mathbf{v} = v_k \mathbf{i}_k \equiv \sum_k v_k \mathbf{i}_k. - -Similarly, a rank two tensor (matrix) quantity :math:`\mathbf{A}` can -be represented in terms of unit matrices, that is outer products of -unit vectors: - -.. math:: - - \mathbf{A} = A_{ij} \mathbf{i}_i \mathbf{i}_j \equiv \sum_i \sum_j A_{ij} \mathbf{i}_i \mathbf{i}_j . - -This generalizes to tensors of arbitrary rank: - -.. math:: - - \mathcal{C} &= C_\iota \mathbf{i}_{\iota_0} \otimes \cdots \otimes \mathbf{i}_{\iota_{r-1}} \\ - &\equiv \sum_{\iota_0} \cdots \sum_{\iota_{r-1}} - C_\iota \mathbf{i}_{\iota_0}\otimes\cdots \otimes \mathbf{i}_{\iota_{r-1}}, - -where :math:`\mathcal{C}` is a rank :math:`r` tensor and :math:`\iota` -is a multi-index of length :math:`r`. - -%TODO: More about tensor algebra concepts to better support -% the following sections? I don't know how much we can -% assume people knows about this? - -When writing equations on paper, a mathematician can easily switch -between the :math:`\mathbf{v}` and :math:`v_i` representations without -stating it explicitly. This is possible because of flexible notation -and conventions. In a programming language, we can't use the boldface -notation which associates :math:`\mathbf{v}` and :math:`v` by convention, -and we can't always interpret such conventions unambiguously. Therefore, -UFL requires that an expression is explicitly mapped from its tensor -representation (:math:`\mathbf{v}`, :math:`\mathbf{A}`) to its component -representation (:math:`v_i`, :math:`A_{ij}`) and back. This is done using -``Index`` objects, the indexing operator (``v[i]``), and the function -``as_tensor``. More details on these follow. - -In the following descriptions of UFL operator syntax, i-l and p-s are -assumed to be predefined indices, and unless otherwise specified the name -v refers to some vector valued expression, and the name A refers to some -matrix valued expression. The name C refers to a tensor expression of -arbitrary rank. - -Defining indices ----------------- - -A set of indices ``i``, ``j``, ``k``, ``l`` and ``p``, ``q``, ``r``, -``s`` are predefined, and these should be enough for many applications. -Examples will usually use these objects instead of creating new ones to -conserve space. - -The data type ``Index`` represents an index used for subscripting -derivatives or taking components of non-scalar expressions. -To create indices, you can either make a single using ``Index()`` -or make several at once conveniently using ``indices(n)``:: - - i = Index() - j, k, l = indices(3) - -Each of these represents an ``index range`` determined by the context; -if used to subscript a tensor-valued expression, the range is given -by the shape of the expression, and if used to subscript a derivative, -the range is given by the dimension :math:`d` of the underlying shape -of the finite element space. As we shall see below, indices can be a -powerful tool when used to define forms in tensor notation. - - -.. note: Advanced usage - - If using UFL inside PyDOLFIN or another larger programming environment, - it is a good idea to define your indices explicitly just before your - form uses them, to avoid name collisions. The definition of the - predefined indices is simply:: - - i, j, k, l = indices(4) - p, q, r, s = indices(4) - -.. note: Advanced usage - - Note that in the old FFC notation, the definition :: - - i = Index(0) - - meant that the value of the index remained constant. This does not mean - the same in UFL, and this notation is only meant for internal usage. - Fixed indices are simply integers instead:: - - i = 0 - - -Taking components of tensors ----------------------------- -% TODO: Explain in more words - -Basic fixed indexing of a vector valued expression v or matrix valued -expression A: - -* ``v[0]``: component access, representing the scalar value of the first - component of v - -* ``A[0,1]``: component access, representing the scalar value of the - first row, second column of A - - -Basic indexing: -* ``v[i]``: component access, representing the scalar value of some - component of v -* ``A[i,j]``: component access, representing the scalar value of some - component i,j of A - -More advanced indexing: - -* ``A[i,0]``: component access, representing the scalar value of some - component i of the first column of A - -* ``A[i,:]``: row access, representing some row i of A, i.e. rank(A[i,:]) == 1 - -* ``A[:,j]``: column access, representing some column j of A, - i.e. rank(A[:,j]) == 1 - -* ``C[...,0]``: subtensor access, representing the subtensor of A with - the last axis fixed, e.g., A[...,0] == A[:,0] - -* ``C[j,...]``: subtensor access, representing the subtensor of A with - the last axis fixed, e.g., A[j,...] == A[j,:] - - -Making tensors from components ------------------------------- - -If you have expressions for scalar components of a tensor and wish to -convert them to a tensor, there are two ways to do it. If you have a -single expression with free indices that should map to tensor axes, -like mapping :math:`v_k` to :math:`\mathbf{v}` or :math:`A_{ij}` to -:math:`\mathbf{A}`, the following examples show how this is done:: - - vk = Identity(cell.d)[0,k] - v = as_tensor(vk, (k,)) - - Aij = v[i]*u[j] - A = as_tensor(Aij, (i,j)) - -Here ``v`` will represent unit vector :math:`\mathbf{i}_0`, and ``A`` -will represent the outer product of ``v`` and ``u``. - -If you have multiple expressions without indices, you can build tensors -from them just as easily, as illustrated here:: - - v = as_vector([1.0, 2.0, 3.0]) - A = as_matrix([[u[0], 0], [0, u[1]]]) - B = as_matrix([[a+b for b in range(2)] for a in range(2)]) - -Here ``v``, ``A`` and ``B`` will represent the expressions - -.. math:: - - \mathbf{v} &= \mathbf{i}_0 + 2 \mathbf{i}_1 + 3 \mathbf{i}_2, \\ - \mathbf{A} &= \begin{bmatrix} u_0 & 0 \\ 0 & u_1 \end{bmatrix}, \\ - \mathbf{B} &= \begin{bmatrix} 0 & 1 \\ 1 & 2 \end{bmatrix}. - -Note that the function ``as_tensor`` generalizes from vectors to tensors -of arbitrary rank, while the alternative functions ``as_vector`` and -``as_matrix`` work the same way but are only for constructing vectors -and matrices. They are included for readability and convenience. - - -Implicit summation ------------------- - -Implicit summation can occur in only a few situations. A product of -two terms that shares the same free index is implicitly treated as a -sum over that free index: - -* ``v[i]*v[i]``: :math:`\sum_i v_i v_i` -* ``A[i,j]*v[i]*v[j]``: :math:`\sum_j (\sum_i A_{ij} v_i) v_j` - -A tensor valued expression indexed twice with the same free index is -treated as a sum over that free index: - -* ``A[i,i]``: :math:`\sum_i A_{ii}` -* ``C[i,j,j,i]``: :math:`\sum_i \sum_j C_{ijji}` - -The spatial derivative, in the direction of a free index, of an expression -with the same free index, is treated as a sum over that free index: - -* ``v[i].dx(i)``: :math:`\sum_i v_i` -* ``A[i,j].dx(i)``: :math:`\sum_i \frac{d(A_{ij})}{dx_i}` - -Note that these examples are some times written :math:`v_{i,i}` and -:math:`A_{ij,i}` in pen-and-paper index notation. - - -Basic algebraic operators -========================= - -The basic algebraic operators ``+``, ``-``, ``*``, ``/`` can be used -freely on UFL expressions. They do have some requirements on their -operands, summarized here: - -Addition or subtraction, ``a + b`` or ``a - b``: - -* The operands a and b must have the same shape. -* The operands a and b must have the same set of free indices. - -Division, ``a / b``: - -* The operand b must be a scalar expression. - -* The operand b must have no free indices. - -* The operand a can be non-scalar with free indices, in which division - represents scalar division of all components with the scalar b. - -Multiplication, ``a * b``: - -* The only non-scalar operations allowed is scalar-tensor, - matrix-vector and matrix-matrix multiplication. - -* If either of the operands have any free indices, both must be scalar. - -* If any free indices are repeated, summation is implied. - - -Basic nonlinear functions -========================= - -Some basic nonlinear functions are also available, their meaning mostly -obvious. - -* ``abs(f)``: the absolute value of f. - -* ``sign(f)``: the sign of f (+1 or -1). - -* ``pow(f, g)`` or ``f**g`` - -* ``sqrt(f)`` - -* ``exp(f)`` - -* ``ln(f)`` - -* ``cos(f)`` - -* ``sin(f)`` - -These functions do not accept non-scalar operands or operands with free -indices or ``Argument`` dependencies. - - -Tensor algebra operators -======================== - -``transpose`` -------------- - -The transpose of a matrix A can be written as:: - - AT = transpose(A) - AT = A.T - AT = as_matrix(A[i,j], (j,i)) - -The definition of the transpose is -\begin{align} - \mbox{\texttt{AT[i,j]}} \leftrightarrow (\AA^{\top})_{ij} = \AA_{ji}. -\end{align} - -For transposing higher order tensor expressions, index notation can -be used:: - - AT = as_tensor(A[i,j,k,l], (l,k,j,i)) - -``tr`` ------- - -The trace of a matrix A is the sum of the diagonal entries. This can -be written as:: - - t = tr(A) - t = A[i,i] - -The definition of the trace is - -.. math:: - - \mbox{\texttt{tr}(A)} \leftrightarrow \mathrm{tr} \mathbf{A} = A_{ii} = \sum_{i=0}^{n-1} A_{ii}. - - -``dot`` -------- - -The dot product of two tensors a and b can be written:: - - # General tensors - f = dot(a, b) - - # Vectors a and b - f = a[i]*b[i] - - # Matrices a and b - f = as_matrix(a[i,k]*b[k,j], (i,j)) - -The definition of the dot product of unit vectors is (assuming an -orthonormal basis for a Euclidean space): - -.. math:: - - \mathbf{i}_i \cdot \mathbf{i}_j = \delta_{ij} - -where :math:`\delta_{ij}` is the Kronecker delta as explained earlier. -The dot product of higher order tensors follow from this, as illustrated -with the following examples. - -An example with two vectors - -.. math:: - - \mathbf{v} \cdot \mathbf{u} = (v_i \mathbf{i}_i) \cdot (u_j \mathbf{i}_j) - = v_i u_j (\mathbf{i}_i \cdot \mathbf{i}_j) = v_i u_j \delta_{ij} = v_i u_i - -An example with a tensor of rank two - -.. math:: - - \mathbf{A} \cdot \mathbf{B} - &= (A_{ij} \mathbf{i}_i \mathbf{i}_j) \cdot (B_{kl} \mathbf{i}_k \mathbf{i}_l) \\ - &= (A_{ij}B_{kl}) \mathbf{i}_i(\mathbf{i}_j \cdot \mathbf{i}_k) \mathbf{i}_l \\ - &= (A_{ij}B_{kl}\delta_{jk}) \mathbf{i}_i \mathbf{i}_l \\ - &= A_{ik}B_{kl} \mathbf{i}_i \mathbf{i}_l. - -This is the same as to matrix-matrix multiplication. - -An example with a vector and a tensor of rank two - -.. math:: - - \mathbf{v} \cdot \mathbf{A} - &= (v_j \mathbf{i}_j) \cdot (A_{kl} \mathbf{i}_k \mathbf{i}_l) \\ - &= (v_j A_{kl}) (\mathbf{i}_j \cdot \mathbf{i}_k) \mathbf{i}_l \\ - &= (v_j A_{kl}\delta_{jk}) \mathbf{i}_l \\ - &= v_k A_{kl} \mathbf{i}_l - -This is the same as to vector-matrix multiplication. - -% TODO: Is 'contraction' or 'axis' obvious and exactly correctly used? -% Get a better formulation from somewhere? -This generalizes to tensors of arbitrary rank: -%The dot product is a contraction over the -The dot product applies to the last axis of a and the first axis of b. -The tensor rank of the product is rank(a)+rank(b)-2. - -%and generalized to tensors of arbitrary rank you get this crazy expression: -%\begin{align} -%(A_\iota^a \ii_{\iota^a_0}\otimes\cdots\otimes\ii_{\iota^a_{r-1}}) -%\cdot -%(B_\iota^b \ii_{\iota^b_0}\otimes\cdots\otimes\ii_{\iota^b_{r-1}}) -%\\ -%= -%(A_\iota^a B_\iota^b) -%(\ii_{\iota^a_{r-1}} \cdot \ii_{\iota^b_0}) -%\ii_{\iota^a_0}\otimes\cdots\otimes\ii_{\iota^a_{r-2}} -%\otimes -%\ii_{\iota^b_1}\otimes\cdots\otimes\ii_{\iota^b_{r-1}} -%\\ -%= -%(A_\iota^a B_\iota^b \delta_{\iota^a_{r-1} \iota^b_0}) -%\ii_{\iota^a_0}\otimes\cdots\otimes\ii_{\iota^a_{r-2}} -%\otimes -%\ii_{\iota^b_1}\otimes\cdots\otimes\ii_{\iota^b_{r-1}} -%\end{align} -%\begin{align} -%\ii_i\cdot\ii_j = \delta_{ij} -%\end{align} - -``inner`` ---------- - -The inner product is a contraction over all axes of a and b, that is -the sum of all componentwise products. The operands must have the exact -same dimensions. For two vectors it is equivalent to the dot product. - -If :math:`\mathbf{A}` and :math:`\mathbf{B}` are rank two tensors and -:math:`\mathcal{C}` and :math:`\mathcal{D}` are rank 3 tensors -their inner products are - -.. math:: - \mathbf{A} : \mathbf{B} &= A_{ij} B_{ij} - \\ - \mathcal{C} : \mathcal{D} &= C_{ijk} D_{ijk} - -Using UFL notation, the following pairs of declarations are equivalent:: - - # Vectors - f = inner(a, b) - f = v[i]*b[i] - - # Matrices - f = inner(A, B) - f = A[i,j]*B[i,j] - - # Rank 3 tensors - f = inner(C, D) - f = C[i,j,k]*D[i,j,k] - - -``outer`` ---------- - -The outer product of two tensors a and b can be written:: - - A = outer(a, b) - -The general definition of the outer product of two tensors -:math:`\mathcal{C}` of rank :math:`r` and :math:`\mathcal{D}` of rank -:math:`s` is - -.. math:: - - \mathcal{C} \otimes \mathcal{D} - = - C_{\iota^a_0 \ldots \iota^a_{r-1}} D_{\iota^b_0 \ldots\iota^b_{s-1}} - \mathbf{i}_{\iota^a_0}\otimes\cdots\otimes\mathbf{i}_{\iota^a_{r-2}} - \otimes - \mathbf{i}_{\iota^b_1} \otimes \cdots \otimes \mathbf{i}_{\iota^b_{s-1}} - -Some examples with vectors and matrices are easier to understand - -.. math:: - - \mathbf{v} \otimes \mathbf{u} = v_i u_j \mathbf{i}_i \mathbf{i}_j, \\ - \mathbf{v} \otimes \mathbf{v} = v_i B_{kl} \mathbf{i}_i \mathbf{i}_k \mathbf{i}_l, \\ - \mathbf{A} \otimes \mathbf{B} = A_{ij} B_{kl} \mathbf{i}_i \mathbf{i}_j \mathbf{i}_k \mathbf{i}_l . - -The outer product of vectors is often written simply as - -.. math:: - - \mathbf{v} \otimes \mathbf{u} = \mathbf{v} \mathbf{u}, - -which is what we have done with $\mathbf{i}_i \mathbf{i}_j$ above. - -The rank of the outer product is the sum of the ranks of the operands. - -``cross`` ---------- - -The operator ``cross`` accepts as arguments two logically vector-valued -expressions and returns a vector which is the cross product (vector -product) of the two vectors: - -* ``cross(v, w)``: :math:`\mathbf{v} \times \mathbf{w} - = (v_1 w_2 - v_2 w_1, v_2 w_0 - v_0 w_2, v_0 w_1 - v_1 w_0)`. - -Note that this operator is only defined for vectors of length three. - -``det`` -------- - -The determinant of a matrix A can be written:: - - d = det(A) - -``dev`` -------- - -The deviatoric part of matrix A can be written:: - - B = dev(A) - -``sym`` -------- - -The symmetric part of A can be written:: - - B = sym(A) - -The definition is - -.. math:: - - {\rm sym} \mathbf{A} = \frac 1 2 (\mathbf{A} + \mathbf{A}^T) - -``skew`` --------- - -The skew symmetric part of A can be written:: - - B = skew(A) - -The definition is - -.. math:: - - {\rm skew} \mathbf{A} = \frac{1}{2}(\mathbf{A} - \mathbf{A}^T) - - -``cofac`` ---------- - -The cofactor of a matrix A can be written:: - - B = cofac(A) - -The definition is - -.. math:: - - {\rm cofac} \mathbf{A} = \det (\mathbf{A}) \mathbf{A}^{-1} - -The implementation of this is currently rather crude, with a hardcoded -symbolic expression for the cofactor. Therefore, this is limited to 1x1, -2x2 and 3x3 matrices. - -``inv`` -------- - -The inverse of matrix A can be written:: - - Ainv = inv(A) - -The implementation of this is currently rather crude, with a hardcoded -symbolic expression for the inverse. Therefore, this is limited to 1x1, -2x2 and 3x3 matrices. - - -Differential Operators -====================== - -Three different kinds of derivatives are currently supported: spatial -derivatives, derivatives w.r.t. user defined variables, and derivatives -of a form or functional w.r.t. a function. - - -Basic spatial derivatives -------------------------- - -Spatial derivatives hold a special place in partial differential equations -from physics and there are several ways to express those. The basic way is:: - - # Derivative w.r.t. x_2 - f = Dx(v, 2) - f = v.dx(2) - # Derivative w.r.t. x_i - g = Dx(v, i) - g = v.dx(i) - -% TODO: Document this below -%# Derivative w.r.t. x -%x = cell.x -%h = diff(v, x) - -If ``v`` is a scalar expression, ``f`` here is the scalar derivative of -``v`` w.r.t. spatial direction z. If ``v`` has no free-indices, ``g`` -is the scalar derivative w.r.t. spatial direction :math:`x_i`, and ``g`` -has the free-index ``i``. Written as formulas, this can be expressed -compactly using the :math:`v_{,i}` notation: - -.. math:: - - f = \frac{\partial v}{\partial x_2} = v_{,2}, \\ - g = \frac{\partial v}{\partial x_i} = v_{,i}. - -Note the resemblance of :math:`v_{,i}` and :math:`v.dx(i)`. - -If the expression to be differentiated w.r.t. :math:`x_i` has ``i`` -as a free-index, implicit summation is implied:: - - # Sum of derivatives w.r.t. x_i for all i - g = Dx(v[i], i) - g = v[i].dx(i) - -Here ``g`` will represent the sum of derivatives -w.r.t. :math:`x_i` for all ``i``, that is - -.. math:: - - g = \sum_i \frac{\partial v}{\partial x_i} = v_{i,i}. - -Note the compact index notation :math:`v_{i,i}` with implicit summation. - - -Compound spatial derivatives ----------------------------- - -UFL implements several common differential operators. The notation is -simple and their names should be self explaining:: - - Df = grad(f) - df = div(f) - cf = curl(v) - rf = rot(f) - -The operand ``f`` can have no free indices. - -%NB! Although their general meaning is well defined, pay -%attention to their exact definition here, because there -%are different traditional ways to interpret them. -%For example, UFL transposes the gradient of a vector -%compared to the old \ffc{} notation. The definition used in -%UFL is consistent with the traditions of fluid mechanics, -%allowing for example writing the convection term -%$\ww\cdot\nabla\uu\cdot\vv$ in a natural fashion like -%\begin{code} -%dot( dot(w, grad(u)), v ) -%\end{code} - -%The definition of these operators follow from -%the vector of partial derivatives -%\[ -%\nabla \equiv \frac{\partial}{\partial x_k} \mathbf{i}_k -% = \sum_{k=0}^{d-1} \frac{\partial}{\partial x_k} \mathbf{i}_k, -%\] -%and the definition of the dot product, outer product, -%and cross product from the previous section. - -Gradient --------- - -The gradient of a scalar :math:`u` is defined as - -.. math:: - - {\rm grad}(u) \equiv \nabla u = - \sum_{k=0}^{d-1} \frac{\partial u}{\partial x_k} \mathbf{i}_k, - -which is a vector of all spatial partial derivatives of :math:`u`. - -The gradient of a vector :math:`\mathbf{v}` is defined as - -.. math:: - - {\rm grad}(\mathbf{v}) \equiv \nabla \mathbf{v} - = \frac{\partial v_i}{\partial x_j} \mathbf{i}_i \mathbf{i}_j, - -which written componentwise is - -.. math:: - - \mathbf{A} = \nabla \mathbf{v}, \qquad A_{ij} = v_{i,j} - -In general for a tensor :math:`\mathbf{A}` of rank :math:`r` the definition is - -.. math:: - - {\rm grad}(\mathbf{A}) \equiv \nabla \mathbf{A} - = (\frac{\partial}{\partial x_i}) (A_\iota\mathbf{i}_{\iota_0} - \otimes\cdots\otimes \mathbf{i}_{\iota_{r-1}}) \otimes \mathbf{i}_i - = \frac{\partial A_\iota}{\partial x_i} \mathbf{i}_{\iota_0} - \otimes \cdots \otimes \mathbf{i}_{\iota_{r-1}} \otimes \mathbf{i}_i, - -where :math:`\iota` is a multiindex of length :math:`r`. - -In UFL, the following pairs of declarations are equivalent:: - - Dfi = grad(f)[i] - Dfi = f.dx(i) - - Dvi = grad(v)[i, j] - Dvi = v[i].dx(j) - - DAi = grad(A)[..., i] - DAi = A.dx(i) - -for a scalar expression ``f``, a vector expression ``v``, and a tensor -expression ``A`` of arbitrary rank. - -Divergence ----------- - -The divergence of any nonscalar (vector or tensor) expression $\AA$ -is defined as the contraction of the partial derivative over the last -axis of the expression. - -TODO: Detailed examples like for gradient. - -In UFL, the following declarations are equivalent:: - - dv = div(v) - dv = v[i].dx(i) - - dA = div(A) - dA = A[..., i].dx(i) - -for a vector expression v and a tensor expression A. - -Curl and rot ------------- - -\index{rotation} -\index{curl} -\index{\texttt{curl}} -\index{\texttt{rot}} - -The operator ``curl`` accepts as argument a vector-valued expression -and returns its curl: - -* ``curl(v)``: :math:`\mathrm{curl} \, \mathbf{v} = \nabla \times \mathbf{v} - = (\frac{\partial v_2}{\partial x_1} - \frac{\partial v_1}{\partial x_2}, - \frac{\partial v_0}{\partial x_2} - \frac{\partial v_2}{\partial x_0}, - \frac{\partial v_1}{\partial x_0} - \frac{\partial v_0}{\partial x_1}). - -Note that this operator is only defined for vectors of length three. - -%Alternatively, the name \texttt{rot} can be used for this operator. -%TODO: Define rot. - -Variable derivatives --------------------- - -UFL also supports differentiation with respect to user defined -variables. A user defined variable can be any expression that is defined -as a variable. - -TODO: There are probably some things that don't make sense. - -The notation is illustrated here:: - - # Define some arbitrary expression - u = Coefficient(element) - w = sin(u**2) - - # Annotate expression w as a variable that can be used in diff - w = variable(w) - - # This expression is a function of w - F = I + diff(u, x) - - # The derivative of expression f w.r.t. the variable w - df = diff(f, w) - -Note that the variable ``w`` still represents the same expression. - -This can be useful for example to implement material laws in -hyperelasticity where the stress tensor is derived from a Helmholtz -strain energy function. - -Currently, UFL does not implement time in any particular way, -but differentiation w.r.t. time can be done without this support -through the use of a constant variable t:: - - t = variable(Constant(cell)) - f = sin(x[0])**2 * cos(t) - dfdt = diff(f, t) - - -Functional derivatives ----------------------- - -The third and final kind of derivatives are derivatives of functionals -or forms w.r.t. to a ``Coefficient``. This is described in more detail in -section \ref{subsec:AD} about form transformations. - -DG operators -============ -\index{DG operators} -\index{discontinuous Galerkin} -\index{jump} -\index{avg} -\index{restriction} - -UFL provides operators for implementation of discontinuous Galerkin -methods. These include the evaluation of the jump and average -of a function (or in general an expression) over the interior facets -(edges or faces) of a mesh. - -Restriction: ``v('+')`` and ``v('-')}`` ------------------------------------------------------------ - -When integrating over interior facets (``*dS``), one may restrict -expressions to the positive or negative side of the facet::P - - element = FiniteElement("Discontinuous Lagrange", "tetrahedron", 0) - - v = TestFunction(element) - u = TrialFunction(element) - - f = Coefficient(element) - - a = f('+')*dot(grad(v)('+'), grad(u)('-'))*dS - -Restriction may be applied to functions of any finite element space but -will only have effect when applied to expressions that are discontinuous -across facets. - -Jump: ``jump(v)`` ------------------ - -The operator ``jump`` may be used to express the jump of a -function across a common facet of two cells. Two versions of the -``jump`` operator are provided. - -If called with only one argument, then the ``jump`` operator -evaluates to the difference between the restrictions of the given -expression on the positive and negative sides of the facet: - -.. math:: - - \mbox{\texttt{jump(v)}} \leftrightarrow \llbracket v \rrbracket = v^+ - v^-. - -If the expression ``v`` is scalar, then ``jump(v)`` will also be -scalar, and if ``v`` is vector-valued, then ``jump(v)`` will also be -vector-valued. - -If called with two arguments, \texttt{jump(v, n)} evaluates to the -jump in \texttt{v} weighted by \texttt{n}. Typically, \texttt{n} will -be chosen to represent the unit outward normal of the facet (as seen -from each of the two neighboring cells). If \texttt{v} is scalar, then -\texttt{jump(v, n)} is given by - -.. math:: - - \mbox{\texttt{jump(v, n)}} \leftrightarrow \llbracket v \rrbracket_n = v^+ n^+ + v^- n^-. - -If \texttt{v} is vector-valued, then \texttt{jump(v, n)} is given by - -.. math:: - - \mbox{\texttt{jump(v, n)}} \leftrightarrow \llbracket v \rrbracket_n = v^+ \cdot n^+ + v^- \cdot n^-. - -Thus, if the expression \texttt{v} is scalar, then \texttt{jump(v, n)} will -be vector-valued, and if \texttt{v} is vector-valued, then -\texttt{jump(v, n)} will be scalar. - -Average: ``avg(v)`` -------------------- - -The operator \texttt{avg} may be used to express the average -of an expression across a common facet of two cells: - -.. math:: - - \mbox{avg(v)} - \leftrightarrow - \langle v \rangle = \frac{1}{2} (v^+ + v^-). - -The expression ``avg(v)`` has the same value shape as the expression ``v``. - -Conditional Operators -===================== -\index{conditional operators} - -Conditional ------------ - -UFL has limited support for branching, but for some PDEs it is needed. -The expression \texttt{c} in:: - - c = conditional(condition, true_value, false_value) - -evaluates to \texttt{true\_value} at run-time if \texttt{condition} -evaluates to true, or to \texttt{false\_value} otherwise. - -This corresponds to the C++ syntax \texttt{(condition ? true\_value: false\_value)}, -or the Python syntax \texttt{(true\_value if condition else false\_value)}, - -Conditions ----------- - -* \texttt{eq(a, b)} represents the condition that a == b -* \texttt{ne(a, b)} represents the condition that a != b -* \texttt{le(a, b)} represents the condition that a <= b -* \texttt{ge(a, b)} represents the condition that a >= b -* \texttt{lt(a, b)} represents the condition that a < b -* \texttt{gt(a, b)} represents the condition that a > b - -TODO: This is rather limited, probably need the operations -"and" and "or" as well, the syntax will be rather convoluted... -Can we improve? Low priority though. - -.. topic:: Advanced usage - - Because of details in the way Python behaves, we cannot overload - the builtin comparison operators for this purpose, hence these named - operators. - - -User-defined operators -====================== -\label{sec:user-defined} -\index{user-defined operators} - -A user may define new operators, using standard Python syntax. As an -example, consider the strain-rate operator $\epsilon$ of linear elasticity, -defined by - -.. math:: - - \epsilon(v) = \frac{1}{2} (\nabla v + (\nabla v)^{\top}). - -This operator can be implemented as a function using the Python ``def`` -keyword:: - - def epsilon(v): - return 0.5*(grad(v) + grad(v).T) - -Alternatively, using the shorthand \texttt{lambda} notation, the -strain operator may be defined as follows:: - - epsilon = lambda v: 0.5*(grad(v) + grad(v).T) - -\index{def}\index{lambda} - -Form Transformations -==================== -\index{form transformations} - -When you have defined a ``Form``, you can derive new related -forms from it automatically. UFL defines a set of common -form transformations described in this section. - - -Replacing arguments of a Form ------------------------------ - -The function \texttt{replace} lets you replace terminal objects with -other values, using a mapping defined by a Python dict. This can be -used for example to replace a \texttt{Coefficient} with a fixed value for -optimized runtime evaluation. - -Example:: - - f = Coefficient(element) - g = Coefficient(element) - c = Constant(cell) - a = f*g*v*dx - b = replace(a, { f: 3.14, g: c }) - -The replacement values must have the same basic properties as the original -values, in particular value shape and free indices. - - -Action of a form on a function ------------------------------- - -The action of a bilinear form :math:`a` is defined as - -.. math: - - b(v; w) = a(v, w), - -The action of a linear form :math:`L` is defined as - -.. math: - - f(;w) = L(w) - -This operation is implemented in UFL simply by replacing the rightmost -basis function (trial function for $a$, test function for $L$) -in a \texttt{Form}, and is used like this:: - - L = action(a, w) - f = action(L, w) - -To give a concrete example, these declarations are equivalent:: - - a = inner(grad(u), grad(v))*dx - L = action(a, w) - - a = inner(grad(u), grad(v))*dx - L = inner(grad(w), grad(v))*dx - -If a is a rank 2 form used to assemble the matrix A, L is a rank 1 -form that can be used to assemble the vector :math:`b = Ax` directly. -This can be used to define both the form of a matrix and the form of its -action without code duplication, and for the action of a Jacobi matrix -computed using derivative. - -If L is a rank 1 form used to assemble the vector b, f is a functional -that can be used to assemble the scalar value :math:`f = b \cdot w` -directly. This operation is sometimes used in, e.g., error control with L -being the residual equation and w being the solution to the dual problem. -(However, the discrete vector for the assembled residual equation will -typically be available, so doing the dot product using linear algebra -would be faster than using this feature.) FIXME: Is this right? - - -Energy norm of a bilinear form -------------------------------- - -The functional representing the energy norm :math:`|v|_A = v^T A v` of -a matrix A assembled from a form :math:`a` can be computed like this:: - - f = energy_norm(a, w) - -which is equivalent to:: - - f = action(action(a, w), w) - - -Adjoint of a bilinear form ---------------------------- - -The adjoint :math:`a'` of a bilinear form :math:`a`is defined as - -.. math: - - a'(u,v) = a(v,u). - -This operation is implemented in UFL simply by swapping test and trial -functions in a ``Form``, and is used like this:: - - aprime = adjoint(a) - - -Linear and bilinear parts of a form ------------------------------------ - -Some times it is useful to write an equation on the format - -.. math: - - a(v,u) - L(v) = 0. - -Before we can assemble the linear equation - -.. math: - - A u = b, - -we need to extract the forms corresponding to the left hand side and -right hand side. This corresponds to extracting the bilinear and linear -terms of the form respectively, or the terms that depend on both a test -and a trial function on one side and the terms that depend on only a -test function on the other. - -This is easily done in UFL using ``lhs`` and ``rhs`:: - - b = u*v*dx - f*v*dx - a, L = lhs(b), rhs(b) - -Note that ``rhs`` multiplies the extracted terms by :math:`-1`, -corresponding to moving them from left to right, so this is equivalent to:: - - a = u*v*dx - L = f*v*dx - -As a slightly more complicated example, this formulation:: - - F = v*(u - w)*dx + k*dot(grad(v), grad(0.5*(w + u)))*dx - a, L = lhs(F), rhs(F) - -is equivalent to:: - - a = v*u*dx + k*dot(grad(v), 0.5*grad(u))*dx - L = v*w*dx - k*dot(grad(v), 0.5*grad(w))*dx - -%\subsection{Splitting integrals by polygon degree} -%TODO: Implement "integrals = split_by_degree(a)" - - -%\subsection{Blocks of a form on mixed element spaces} -%TODO: Implement A, B, C, D = blocks(a) - - -Automatic functional differentiation ------------------------------------- -\label{subsec:AD} - -UFL can compute derivatives of functionals or forms w.r.t. to a -``Coefficient``. This functionality can be used for example to linearize -your nonlinear residual equation automatically, or derive a linear system -from a functional, or compute sensitivity vectors w.r.t. some coefficient. - -A functional can be differentiated to obtain a linear form, - -.. math: - - F(v; w) = \frac{d}{dw} f(;w) -and a linear form - \footnote{Note that by ``linear form'' we only mean a form that is linear - in its test function, not in the function you differentiate with respect to.} -can be differentiated to obtain the bilinear form -corresponding to its Jacobi matrix: - -.. math: - - J(v, u; w) = \frac{d}{dw} F(v; w). - -The UFL code to express this is (for a simple functional -:math:`f(w)=\int_\Omega \frac 1 2 w^2\,dx`):: - - f = (w**2)/2 * dx - F = derivative(f, w, v) - J = derivative(F, w, u) - -which is equivalent to:: - - f = (w**2)/2 * dx - F = w*v*dx - J = u*v*dx - -Assume in the following examples that:: - - v = TestFunction(element) - u = TrialFunction(element) - w = Coefficient(element) - -The stiffness matrix can be computed from the functional -:math:`\int_\Omega \nabla w : \nabla w \, dx`, by the lines:: - - f = inner(grad(w), grad(w))/2 * dx - F = derivative(f, w, v) - J = derivative(F, w, u) - -which is equivalent to:@ - - f = inner(grad(w), grad(w))/2 * dx - F = inner(grad(w), grad(v)) * dx - J = inner(grad(u), grad(v)) * dx - -Note that here the basis functions are provided explicitly, which is -some times necessary, e.g., if part of the form is linearlized manually -like in (*TODO: An example that makes sense would be nicer, this -is just a random form.*):: - - g = Coefficient(element) - f = inner(grad(w), grad(w))*dx - F = derivative(f, w, v) + dot(w-g,v)*dx - J = derivative(F, w, u) - -Derivatives can also be computed w.r.t. functions in mixed spaces. -Consider this example, an implementation of the harmonic map equations -using automatic differentiation:: - - X = VectorElement("Lagrange", cell, 1) - Y = FiniteElement("Lagrange", cell, 1) - - x = Coefficient(X) - y = Coefficient(Y) - - L = inner(grad(x), grad(x))*dx + dot(x,x)*y*dx - - F = derivative(L, (x,y)) - J = derivative(F, (x,y)) - -Here ``L`` is defined as a functional with two coefficient functions -``x`` and ``y`` from separate finite element spaces. However, ``F`` and -``J`` become linear and bilinear forms respectively with basis functions -defined on the mixed finite element:: - - M = X + Y - -There is a subtle difference between defining ``x`` and ``y`` -separately and this alternative implementation -(reusing the elements ``X`, ``Y``, ``M``):: - - u = Coefficient(M) - x, y = split(u) - - L = inner(grad(x), grad(x))*dx + dot(x,x)*y*dx - - F = derivative(L, u) - J = derivative(F, u) - -The difference is that the forms here have *one* coefficient function -``u`` in the mixed space, and the forms above have *two* coefficient -functions ``x`` and ``y``. - -TODO: Move this to implementation part? -If you wonder how this is all done, a brief explanation follows. -Recall that a \texttt{Coefficient} represents a -sum of unknown coefficients multiplied with unknown -basis functions in some finite element space. - -.. math: - - w(x) = \sum_k w_k \phi_k(x) - -Also recall that a ``Argument`` represents any (unknown) basis -function in some finite element space. - -.. math: - - v(x) = \phi_k(x), \qquad \phi_k \in V_h . - -A form :math:`L(v; w)` implemented in UFL is intended for discretization -like - -.. math: - - b_i = L(\phi_i; \sum_k w_k \phi_k), \qquad \forall \phi_i \in V_h . - -The Jacobi matrix $A_{ij}$ of this vector can be obtained by -differentiation of $b_i$ w.r.t. $w_j$, which can be written - -.. math: - - A_{ij} = \frac{d b_i}{d w_j} = a(\phi_i, \phi_j; \sum_k w_k \phi_k), \qquad \forall \phi_i \in V_h, \quad \forall \phi_j \in V_h , - -for some form $a$. In UFL, the form $a$ can be obtained by -differentiating $L$. To manage this, we note that as long as the domain -$\Omega$ is independent of $w_j$, $\int_\Omega$ commutes with $\frac{d}{d -w_j}$, and we can differentiate the integrand expression instead, e.g., - -.. math: - - L(v; w) = \int_\Omega I_c(v; w) \, dx + \int_{\partial\Omega} I_e(v; w) \, ds, \\ - \frac{d}{d w_j} L(v; w) = \int_\Omega \frac{d I_c}{d w_j} \, dx + \int_{\partial\Omega} \frac{d I_e}{d w_j} \, ds. - -In addition, we need that - -.. math: - - \frac{d w}{d w_j} = \phi_j, \qquad \forall \phi_j \in V_h , - -which in UFL can be represented as - -.. math: - - w &= \text{\texttt{Coefficient(element)}}, \\ - v &= \text{\texttt{Argument(element)}}, \\ - \frac{dw}{d w_j} &= v, - -since :math:`w` represents the sum and :math`v` represents any and all -basis functions in :math:`V_h`. - -Other operators have well defined derivatives, and by repeatedly applying -the chain rule we can differentiate the integrand automatically. - -*The notation here has potential for improvement, feel free to ask if -something is unclear, or suggest improvements.* - - -Combining form transformations ------------------------------- - -Form transformations can be combined freely. Note that to do this, -derivatives are usually be evaluated before applying e.g. the action of -a form, because ``derivative`` changes the arity of the form:: - - element = FiniteElement("CG", cell, 1) - w = Coefficient(element) - f = w**4/4*dx(0) + inner(grad(w), grad(w))*dx(1) - F = derivative(f, w) - J = derivative(F, w) - Ja = action(J, w) - Jp = adjoint(J) - Jpa = action(Jp, w) - g = Coefficient(element) - Jnorm = energy_norm(J, g) - -TODO: Find some more examples, e.g. from error control! - - -Tuple notation -============== -\index{tuple notation} - -In addition to the standard integrand notation described above, UFL -supports a simplified \emph{tuple notation} by which :math:`L^2` inner -products may be expressed as tuples. Consider for example the following -bilinear form as part of a variational problem for a reaction--diffusion -problem: - -.. math: - - a(v, u) - &= \int_{\Omega} \nabla v \cdot \nabla u + v u \dx \\ - &= (\nabla v, \nabla u) + (v, u) - -In standard UFL notation, this bilinear form may be expressed as:: - - a = inner(grad(v), grad(u))*dx + v*u*dx - -In tuple notation, this may alternatively be expressed as:: - - a = (grad(v), grad(u)) + (v, u) - -In general, a form may be expressed as a sum of tuples or triples of -the form:: - - (v, w) - (v, w, dm) - -where ``v`` and ``w`` are expressions of matching rank (so that ``inner(v, -w)`` makes sense), and ``dm`` is a measure. If the measure is left out, -it is assumed that it is ``dx``. - -The following example illustrates how to express a form containing -integrals over subdomains and facets:: - - a = (grad(v), grad(u)) + (v, b*grad(u), dx(2)) + (v, u, ds) + (jump(v), jump(u), dS) - -The following caveats should be noted: -* The only operation allowed on a tuple is addition. In particular, - tuples may not subtracted. Thus, - \texttt{a = (grad(v), grad(u)) - (v, u)} must be expressed as - \texttt{a = (grad(v), grad(u)) + (-v, u)}. - -* Tuple notation may not be mixed with standard UFL integrand - notation. Thus, \texttt{a = (grad(v), grad(u)) + inner(v, u)*dx} is not - valid. - -.. topic:: Advanced usage - - Tuple notation is strictly speaking not a part of the form - language, but tuples may be converted to UFL forms using - the function \texttt{tuple2form} available from the module - \texttt{ufl.algorithms}. This is normally handled automatically by - form compilers, but the \texttt{tuple2form} utility may useful when - working with UFL from a Python script. Automatic conversion is also - carried out by UFL form operators such as \texttt{lhs} and \texttt{rhs}. - - -Form files -========== -\index{form files} -\index{ufl files} - -UFL forms and elements can be collected in a *form file* with the -extension *.ufl*. Form compilers will typically execute this file with -the global UFL namespace available, and extract forms and elements -that are defined after execution. The compilers do not compile all -forms and elements that are defined in file, but only those that -are *exported}. A finite element with the variable name ``element`` -is exported by default, as are forms with the names ``M``, ``L``, and -``a``. The default form names are intended for a functional, linear form, -and bilinear form respectively. - -To export multiple forms and elements or use other names, an explicit -list with the forms and elements to export can be defined. Simply write:: - - elements = [V, P, TH] - forms = [a, L, F, J, L2, H1] - -at the end of the file to export the elements and forms held by these -variables. - diff -Nru ufl-1.2.0/doc/sphinx/source/user/installation.rst ufl-1.3.0/doc/sphinx/source/user/installation.rst --- ufl-1.2.0/doc/sphinx/source/user/installation.rst 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/sphinx/source/user/installation.rst 1970-01-01 00:00:00.000000000 +0000 @@ -1,116 +0,0 @@ -************ -Installation -************ -\label{app:installation} -\index{installation} - -The source code of UFL is portable and should work on any system with -a standard Python installation. Questions, bug reports and patches -concerning the installation should be directed to the UFL mailing list -at the address: - - ufl-dev@fenics.org - -UFL must currently be installed directly from source, but Debian (Ubuntu) -packages will be available in the future, for UFL and other FEniCS -components. - -Installing from source -====================== - -Dependencies and requirements ------------------------------ -\index{dependencies} - -UFL currently has no external dependencies apart from a working Python -installation. - -%UFL depends on the Python NumPy module. -%In addition, you need to have a working Python installation on your system. - -Installing Python ------------------ - -UFL is developed for Python 2.5, and does not work with previous versions. -To check which version of Python you have installed, issue the command -\texttt{python~-V}:: - - # python -V - Python 2.5.1 - -If Python is not installed on your system, it can be downloaded from:: - - http://www.python.org/ - -Follow the installation instructions for Python given on the Python -web page. For Debian (Ubuntu) users, the package to install is named -\texttt{python}. - -%\subsubsection{Installing NumPy} -% -%In addition to Python itself, UFL depends on the Python package NumPy, -%which is used by UFL to process multidimensional arrays (tensors). -%Python NumPy can be downloaded from -%\begin{code} -%http://www.scipy.org/ -%\end{code} -%For Debian (Ubuntu) users, the package to install is \texttt{python-numpy}. - -% Input section shared with DOLFIN manual -\input{chapters/installation-downloading.tex} - -Installing UFL --------------- - -UFL follows the standard installation procedure for Python packages. Enter -the source directory of UFL and issue the following command:: - - # python setup.py install - -This will install the UFL Python package in a subdirectory called -\texttt{ufl} in the default location for user-installed Python packages -(usually something like \texttt{/usr/lib/python2.5/site-packages}). - -In addition, the executable \texttt{ufl-analyse} (a Python script) will -be installed in the default directory for user-installed Python scripts -(usually in \texttt{/usr/bin}). - -To see a list of optional parameters to the installation script, type:: - - # python setup.py install --help - -If you don't have root access to the system you are using, you can pass -the \texttt{--home} option to the installation script to install UFL in -your home directory:: - - # mkdir ~/local - # python setup.py install --home ~/local - -This installs the UFL package in the directory -\texttt{\~{}/local/lib/python} and the UFL executables in -\texttt{\~{}/local/bin}. If you use this option, make sure to set the -environment variable \texttt{PYTHONPATH} to \texttt{\~{}/local/lib/python} -and to add \texttt{\~{}/local/bin} to the \texttt{PATH} environment -variable. - - -Running the test suite ----------------------- - -To verify that the installation is correct, you may run the test suite. -Enter the sub directory \texttt{test/} from within the UFL source tree -and run the script \texttt{test.py}:: - - # python test.py - -This script runs all unit tests and imports UFL in the process. - -% TODO: Add regression tests on ufl-analyse output from demos? Perhaps -% when ufl-analyse stabilises. - -Debian/Ubuntu packages -====================== -\index{Debian package} -\index{Ubuntu package} - -In preparation. diff -Nru ufl-1.2.0/doc/sphinx/source/user/internal_representation.rst ufl-1.3.0/doc/sphinx/source/user/internal_representation.rst --- ufl-1.2.0/doc/sphinx/source/user/internal_representation.rst 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/sphinx/source/user/internal_representation.rst 1970-01-01 00:00:00.000000000 +0000 @@ -1,193 +0,0 @@ -******************************* -Internal representation details -******************************* -\label{chapter:representation} - -This chapter explains how UFL forms and expressions are represented -in detail. Most operations are mirrored by a representation class, -e.g., \texttt{Sum} and \texttt{Product}, all which are subclasses -of \texttt{Expr}. You can import all of them from the submodule -\texttt{ufl.classes} by:: - - from ufl.classes import * - -TODO: Automate the construction of class hierarchy figures using ptex2tex. - -Structure of a form -=================== - -TODO: Add class relations figure with Form, Integral, Expr, Terminal, -Operator. - -Each \ttt{Form} owns multiple \ttt{Integral} instances, each associated -with a different \ttt{Measure}. An \ttt{Integral} owns a \ttt{Measure} -and an \ttt{Expr}, which represents the integrand expression. The -\ttt{Expr} is the base class of all expressions. It has two direct -subclasses \ttt{Terminal} and \ttt{Operator}. - -Subclasses of \ttt{Terminal} represent atomic quantities which -terminate the expression tree, e.g. they have no subexpressions. -Subclasses of \ttt{Operator} represent operations on one or more -other expressions, which may usually be \ttt{Expr} subclasses of -arbitrary type. Different \ttt{Operator}s may have restrictions -on some properties of their arguments. - -All the types mentioned here are conceptually immutable, i.e. they -should never be modified over the course of their entire lifetime. When a -modified expression, measure, integral, or form is needed, a new instance -must be created, possibly sharing some data with the old one. Since the -shared data is also immutable, sharing can cause no problems. - -General properties of expressions -================================= - -Any UFL expression has certain properties, defined by functions that -every \ttt{Expr} subclass must implement. In the following, \ttt{u} -represents an arbitrary UFL expression, i.e. an instance of an -arbitrary \ttt{Expr} subclass. - -``operands`` ------------- - -``u.operands()`` returns a tuple with all the operands of u, which should -all be \ttt{Expr} instances. - -``reconstruct`` ---------------- - -\ttt{u.reconstruct(operands)} returns a new \ttt{Expr} instance -representing the same operation as \ttt{u} but with other -operands. Terminal objects may simply return \ttt{self} since all -\ttt{Expr} instance are immutable. An important invariant is that -\ttt{u.reconstruct(u.operands()) == u}. - -``cell`` --------- - -\ttt{u.cell()} returns the first \ttt{Cell} instance found in \ttt{u}. It -is currently assumed in UFL that no two different cells are used in -a single form. Not all expression define a cell, in which case this -returns \ttt{None} and \ttt{u} is spatially constant. Note that this -property is used in some algorithms. - - -``shape`` ---------- - -\ttt{u.shape()} returns a tuple of integers, which is the tensor shape -of \ttt{u}. - - -``free\_indices`` ------------------ - -\ttt{u.free\_indices()} returns a tuple of \ttt{Index} objects, which -are the unassigned, free indices of \ttt{u}. - - -``index\_dimensions`` ---------------------- - -\ttt{u.index\_dimensions()} returns a \ttt{dict} mapping from each -\ttt{Index} instance in \ttt{u.free\_indices()} to the integer dimension -of the value space each index can range over. - - -``str(u)`` ----------- - -\ttt{str(u)} returns a human-readable string representation of \ttt{u}. - - -''repr(u)'' ------------ - -\ttt{repr(u)} returns a Python string representation of \ttt{u}, such -that \ttt{eval(repr(u)) == u} holds in Python. - - -``hash(u)`` ------------ - -\ttt{hash(u)} returns a hash code for \ttt{u}, which is used extensively -(indirectly) in algorithms whenever \ttt{u} is placed in a Python -\ttt{dict} or \ttt{set}. - - -``u == v`` ----------- - -\ttt{u == v} returns true if and only if \ttt{u} and \ttt{v} represents -the same expression in the exact same way. This is used extensively -(indirectly) in algorithms whenever \ttt{u} is placed in a Python -\ttt{dict} or \ttt{set}. - - -About other relational operators --------------------------------- - -In general, UFL expressions are not possible to fully evaluate since the -cell and the values of form arguments are not available. Implementing -relational operators for immediate evaluation is therefore impossible. - -Overloading relational operators as a part of the form language is not -possible either, since it interferes with the correct use of container -types in Python like \ttt{dict} or \ttt{set}. - - -Elements -======== - -All finite element classes have a common base class -\texttt{FiniteElementBase}. The class hierarchy looks like this: - -TODO: Class figure. - -TODO: Describe all FiniteElementBase subclasses here. - - -Terminals -========= - -All \texttt{Terminal} subclasses have some non-\texttt{Expr} data attached -to them. \texttt{ScalarValue} has a Python scalar, \texttt{Coefficient} -has a \texttt{FiniteElement}, etc. - -Therefore, a unified implementation of \texttt{reconstruct} is -not possible, but since all \texttt{Expr} instances are immutable, -\texttt{reconstruct} for terminals can simply return self. This feature -and the immutability property is used extensively in algorithms. - -TODO: Describe all Terminal representation classes here. - - -Operators -========= - -All instances of \texttt{Operator} subclasses are fully specified -by their type plus the tuple of \texttt{Expr} instances that are -the operands. Their constructors should take these operands as the -positional arguments, and only that. This way, a unified implementation -of \texttt{reconstruct} is possible, by simply calling the constructor -with new operands. This feature is used extensively in algorithms. - -TODO: Describe all Operator representation classes here. - - -Extending UFL -============= - -Adding new types to the UFL class hierarchy must be done with care. If -you can get away with implementing a new operator as a combination of -existing ones, that is the easiest route. The reason is that only some -of the properties of an operator is represented by the \texttt{Expr} -subclass. Other properties are part of the various algorithms in -UFL. One example is derivatives, which are defined in the differentiation -algorithm, and how to render a type to the \LaTeX{} or dot formats. These -properties could be merged into the class hierarchy, but other properties -like how to map a UFL type to some \ffc{} or \sfc{} or \dolfin{} type -can not be part of UFL. So before adding a new class, consider that doing -so may require changes in multiple algorithms and even other projects. - -TODO: More issues to consider when adding stuff to ufl. - diff -Nru ufl-1.2.0/doc/sphinx/source/user/introduction.rst ufl-1.3.0/doc/sphinx/source/user/introduction.rst --- ufl-1.2.0/doc/sphinx/source/user/introduction.rst 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/sphinx/source/user/introduction.rst 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -************ -Introduction -************ - -The Unified Form Language (UFL) is a domain specific language for -defining discrete variational forms and functionals in a notation close -to pen-and-paper formulation. - -UFL is part of the FEniCS Project, and is usually used in combination -with other components from this project to compute solutions to partial -differential equations. The form compilers FFC and SFC use UFL as their -end-user interface, producing implementations of the UFC interface as -their output. See the DOLFIN manual for more details about using UFL in -an integrated problem solving environment. - -This manual is intended for different audiences. If you are an end user -and all you want to do is to solve your PDEs with the FEniCS framework, -Chapters XX and XX are for -you. These two chapters explain how to use all operators available in -the language and present a number of examples to illustrate the use of -the form language in applications. The rest of the chapters contain more -technical details intended for developers who need to understand what -is happening behind the scenes and modify or extend UFL in the future. - -Chapter XX details the implementation of the language, in particular -how expressions are represented internally by UFL. This can also be -useful knowledge to understand error messages and debug errors in your -form files. - -Chapter XX explains many algorithms to work with UFL expressions, -mostly intended to aid developers of form compilers. The algorithms -available includes helper functions for easy and efficient iteration -over expression trees, formatting tools to present expressions as text or -images of different kinds, utilities to analyse properties of expressions -or checking their validity, automatic differentiation algorithms, as -well as algorithms to work with the computational graphs of expressions. - diff -Nru ufl-1.2.0/doc/sphinx/source/user/user_manual.rst ufl-1.3.0/doc/sphinx/source/user/user_manual.rst --- ufl-1.2.0/doc/sphinx/source/user/user_manual.rst 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/doc/sphinx/source/user/user_manual.rst 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -.. UFL user manual - -.. _ufl_user_manual: - -############### -UFL user manual -############### - -.. note:: - - This manual was was copied from LaTeX. It needs - updating and reformatting. (MER, 09.06.2011) - -.. toctree:: - :maxdepth: 1 - - introduction - form_language - examples - internal_representation - algorithms - command_line_utils - installation - -***************** -About this manual -***************** - -Intended audience -================= - -This manual is written both for the beginning and the advanced user. -There is also some useful information for developers. More advanced -topics are treated at the end of the manual or in the appendix. - -Typographic conventions -======================= - -Code is written in monospace ``like this``. Commands that should be -entered in a Unix shell:: - - # ./configure - # make - -Commands are written in the dialect of the ``bash`` shell. For other -shells, such as ``tcsh``, appropriate translations may be needed. - - - -Enumeration and list indices -============================ - -Throughout this manual, elements :math:`x_i` of sets :math:`\{x_i\}` -of size :math:`n` are enumerated from :math:`i = 0` to :math:`i = -n-1`. Derivatives in :math:`\mathbb{R}^n` are enumerated similarly -:math:`\frac{\partial}{\partial x_0}, \frac{\partial}{\partial x_1}, \ldots, \frac{\partial}{\partial x_{n-1}}`. - -Contact -======= - -Comments, corrections and contributions to this manual are most welcome -and should be sent to ufl@lists.launchpad.net - diff -Nru ufl-1.2.0/release.conf ufl-1.3.0/release.conf --- ufl-1.2.0/release.conf 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/release.conf 2014-01-07 13:29:26.000000000 +0000 @@ -1,6 +1,6 @@ # Configuration file for fenics-release PACKAGE="ufl" -LP_PACKAGE="ufl/1.2.x" +BRANCH="master" FILES="ChangeLog ufl/__init__.py setup.py" POST_FILES="ChangeLog ufl/__init__.py setup.py" diff -Nru ufl-1.2.0/sandbox/scripts/tensoralgebrastrings.py ufl-1.3.0/sandbox/scripts/tensoralgebrastrings.py --- ufl-1.2.0/sandbox/scripts/tensoralgebrastrings.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/sandbox/scripts/tensoralgebrastrings.py 2014-01-07 13:29:26.000000000 +0000 @@ -14,7 +14,7 @@ return "Matrix(%s)" % res[0] def cofac(A): - return A.determinant() * A.inverse() + return A.determinant() * A.inverse().transpose() def cofacstr(d): A = symbolic_matrix(d, d, "A") diff -Nru ufl-1.2.0/setup.py ufl-1.3.0/setup.py --- ufl-1.2.0/setup.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/setup.py 2014-01-07 13:29:26.000000000 +0000 @@ -8,9 +8,9 @@ # Version number major = 1 -minor = 2 -maintenance = '0' -#maintenance = 0 +minor = 3 +#maintenance = '0+' +maintenance = 0 #maintenance = '-alpha' #maintenance = '-beta' #maintenance = '-rc' @@ -47,7 +47,7 @@ version = version, description = "Unified Form Language", author = "Martin Sandve Alnes, Anders Logg", - author_email = "ufl@lists.launchpad.net", + author_email = "fenics@fenicsproject.org", url = "http://www.fenicsproject.org", classifiers=[ 'Development Status :: 5 - Production/Stable', diff -Nru ufl-1.2.0/test/test_algorithms.py ufl-1.3.0/test/test_algorithms.py --- ufl-1.2.0/test/test_algorithms.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/test/test_algorithms.py 2014-01-07 13:29:26.000000000 +0000 @@ -166,99 +166,6 @@ # TODO: Compare a1, a2, a3 # TODO: Test something more - def test_max_degree_estimation(self): - V1 = FiniteElement("CG", triangle, 1) - V2 = FiniteElement("CG", triangle, 2) - VV = VectorElement("CG", triangle, 3) - VM = V1 * V2 - v1 = Argument(V1) - v2 = Argument(V2) - f1, f2 = Coefficients(VM) - vv = Argument(VV) - vu = Argument(VV) - - self.assertEqual(estimate_max_polynomial_degree(vv[0]), 3) - self.assertEqual(estimate_max_polynomial_degree(v2*vv[0]), 3) - self.assertEqual(estimate_max_polynomial_degree(vu[0]*vv[0]), 3) - self.assertEqual(estimate_max_polynomial_degree(vu[i]*vv[i]), 3) - - self.assertEqual(estimate_max_polynomial_degree(v1), 1) - self.assertEqual(estimate_max_polynomial_degree(v2), 2) - - # TODO: This should be 1, but 2 is expected behaviour now - # because f1 is part of a mixed element with max degree 2. - self.assertEqual(estimate_max_polynomial_degree(f1), 2) - - self.assertEqual(estimate_max_polynomial_degree(f2), 2) - self.assertEqual(estimate_max_polynomial_degree(v2*v1), 2) - - # TODO: This should be 1, but 2 is expected behaviour now - # because f1 is part of a mixed element with max degree 2. - self.assertEqual(estimate_max_polynomial_degree(f1*v1), 2) - - self.assertEqual(estimate_max_polynomial_degree(f2*v1), 2) - self.assertEqual(estimate_max_polynomial_degree(f2*v2*v1), 2) - self.assertEqual(estimate_max_polynomial_degree(f1*f2*v2.dx(0)*v1.dx(0)), 2) - self.assertEqual(estimate_max_polynomial_degree(f2**3*v1 + f1*v1), 2) - - def test_total_degree_estimation(self): - V1 = FiniteElement("CG", triangle, 1) - V2 = FiniteElement("CG", triangle, 2) - VV = VectorElement("CG", triangle, 3) - VM = V1 * V2 - v1 = Argument(V1) - v2 = Argument(V2) - f1, f2 = Coefficients(VM) - vv = Argument(VV) - vu = Argument(VV) - - x, y = triangle.x - self.assertEqual(estimate_total_polynomial_degree(x), 1) - self.assertEqual(estimate_total_polynomial_degree(x*y), 2) - self.assertEqual(estimate_total_polynomial_degree(x**3), 3) - self.assertEqual(estimate_total_polynomial_degree(x**3), 3) - self.assertEqual(estimate_total_polynomial_degree((x-1)**4), 4) - - self.assertEqual(estimate_total_polynomial_degree(vv[0]), 3) - self.assertEqual(estimate_total_polynomial_degree(v2*vv[0]), 5) - self.assertEqual(estimate_total_polynomial_degree(vu[0]*vv[0]), 6) - self.assertEqual(estimate_total_polynomial_degree(vu[i]*vv[i]), 6) - - self.assertEqual(estimate_total_polynomial_degree(v1), 1) - self.assertEqual(estimate_total_polynomial_degree(v2), 2) - - # TODO: This should be 1, but 2 is expected behaviour now - # because f1 is part of a mixed element with max degree 2. - self.assertEqual(estimate_total_polynomial_degree(f1), 2) - - self.assertEqual(estimate_total_polynomial_degree(f2), 2) - self.assertEqual(estimate_total_polynomial_degree(v2*v1), 3) - - # TODO: This should be 2, but 3 is expected behaviour now - # because f1 is part of a mixed element with max degree 2. - self.assertEqual(estimate_total_polynomial_degree(f1*v1), 3) - - self.assertEqual(estimate_total_polynomial_degree(f2*v1), 3) - self.assertEqual(estimate_total_polynomial_degree(f2*v2*v1), 5) - - self.assertEqual(estimate_total_polynomial_degree(f2+3), 2) - self.assertEqual(estimate_total_polynomial_degree(f2*3), 2) - self.assertEqual(estimate_total_polynomial_degree(f2**3), 6) - self.assertEqual(estimate_total_polynomial_degree(f2/3), 2) - self.assertEqual(estimate_total_polynomial_degree(f2/v2), 4) - self.assertEqual(estimate_total_polynomial_degree(f2/(x-1)), 3) - - self.assertEqual(estimate_total_polynomial_degree(v1.dx(0)), 0) - self.assertEqual(estimate_total_polynomial_degree(f2.dx(0)), 1) - - self.assertEqual(estimate_total_polynomial_degree(f2*v2.dx(0)*v1.dx(0)), 2+1) - self.assertEqual(estimate_total_polynomial_degree(f2**3*v1 + f1*v1), 7) - - # Based on the arbitrary chosen math function heuristics... - nx, ny = triangle.n - self.assertEqual(estimate_total_polynomial_degree(sin(nx**2)), 0) - self.assertEqual(estimate_total_polynomial_degree(sin(x**3)), 3+2) - def test_adjoint(self): cell = triangle diff -Nru ufl-1.2.0/test/test_classcoverage.py ufl-1.3.0/test/test_classcoverage.py --- ufl-1.2.0/test/test_classcoverage.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/test/test_classcoverage.py 2014-01-07 13:29:26.000000000 +0000 @@ -474,19 +474,32 @@ test_object(a, (), ()) #a = PositiveRestricted(v0) - test_object(a, (), ()) + #test_object(a, (), ()) a = v0('+') test_object(a, (), ()) a = v0('+')*f0 test_object(a, (), ()) #a = NegativeRestricted(v0) - test_object(a, (), ()) + #test_object(a, (), ()) a = v0('-') test_object(a, (), ()) a = v0('-') + f0 test_object(a, (), ()) + a = cell_avg(v0) + test_object(a, (), ()) + a = facet_avg(v0) + test_object(a, (), ()) + a = cell_avg(v1) + test_object(a, (dim,), ()) + a = facet_avg(v1) + test_object(a, (dim,), ()) + a = cell_avg(v1)[i] + test_object(a, (), (i,)) + a = facet_avg(v1)[i] + test_object(a, (), (i,)) + # --- Integrals: a = v0*dx diff -Nru ufl-1.2.0/test/test_degree_estimation.py ufl-1.3.0/test/test_degree_estimation.py --- ufl-1.2.0/test/test_degree_estimation.py 1970-01-01 00:00:00.000000000 +0000 +++ ufl-1.3.0/test/test_degree_estimation.py 2014-01-07 13:29:26.000000000 +0000 @@ -0,0 +1,113 @@ +#!/usr/bin/env python + +__authors__ = "Martin Sandve Alnes" +__date__ = "2008-03-12 -- 2009-01-28" + +from ufltestcase import UflTestCase, main +from pprint import * + +from ufl import * +from ufl.algorithms import * + +class TestDegreeEstimation(UflTestCase): + + def test_total_degree_estimation(self): + V1 = FiniteElement("CG", triangle, 1) + V2 = FiniteElement("CG", triangle, 2) + VV = VectorElement("CG", triangle, 3) + VM = V1 * V2 + v1 = Argument(V1) + v2 = Argument(V2) + f1, f2 = Coefficients(VM) + vv = Argument(VV) + vu = Argument(VV) + + x, y = triangle.x + self.assertEqual(estimate_total_polynomial_degree(x), 1) + self.assertEqual(estimate_total_polynomial_degree(x*y), 2) + self.assertEqual(estimate_total_polynomial_degree(x**3), 3) + self.assertEqual(estimate_total_polynomial_degree(x**3), 3) + self.assertEqual(estimate_total_polynomial_degree((x-1)**4), 4) + + self.assertEqual(estimate_total_polynomial_degree(vv[0]), 3) + self.assertEqual(estimate_total_polynomial_degree(v2*vv[0]), 5) + self.assertEqual(estimate_total_polynomial_degree(vu[0]*vv[0]), 6) + self.assertEqual(estimate_total_polynomial_degree(vu[i]*vv[i]), 6) + + self.assertEqual(estimate_total_polynomial_degree(v1), 1) + self.assertEqual(estimate_total_polynomial_degree(v2), 2) + + # TODO: This should be 1, but 2 is expected behaviour now + # because f1 is part of a mixed element with max degree 2. + self.assertEqual(estimate_total_polynomial_degree(f1), 2) + + self.assertEqual(estimate_total_polynomial_degree(f2), 2) + self.assertEqual(estimate_total_polynomial_degree(v2*v1), 3) + + # TODO: This should be 2, but 3 is expected behaviour now + # because f1 is part of a mixed element with max degree 2. + self.assertEqual(estimate_total_polynomial_degree(f1*v1), 3) + + self.assertEqual(estimate_total_polynomial_degree(f2*v1), 3) + self.assertEqual(estimate_total_polynomial_degree(f2*v2*v1), 5) + + self.assertEqual(estimate_total_polynomial_degree(f2+3), 2) + self.assertEqual(estimate_total_polynomial_degree(f2*3), 2) + self.assertEqual(estimate_total_polynomial_degree(f2**3), 6) + self.assertEqual(estimate_total_polynomial_degree(f2/3), 2) + self.assertEqual(estimate_total_polynomial_degree(f2/v2), 4) + self.assertEqual(estimate_total_polynomial_degree(f2/(x-1)), 3) + + self.assertEqual(estimate_total_polynomial_degree(v1.dx(0)), 0) + self.assertEqual(estimate_total_polynomial_degree(f2.dx(0)), 1) + + self.assertEqual(estimate_total_polynomial_degree(f2*v2.dx(0)*v1.dx(0)), 2+1) + + self.assertEqual(estimate_total_polynomial_degree(f2), 2) + self.assertEqual(estimate_total_polynomial_degree(f2**2), 4) + self.assertEqual(estimate_total_polynomial_degree(f2**3), 6) + self.assertEqual(estimate_total_polynomial_degree(f2**3*v1), 7) + self.assertEqual(estimate_total_polynomial_degree(f2**3*v1 + f1*v1), 7) + + # Based on the arbitrary chosen math function heuristics... + nx, ny = triangle.n + self.assertEqual(estimate_total_polynomial_degree(sin(nx**2)), 0) + self.assertEqual(estimate_total_polynomial_degree(sin(x**3)), 3+2) + + def test_some_compound_types(self): + + # NB! Although some compound types are supported here, + # some derivatives and compounds must be preprocessed + # prior to degree estimation. In generic code, this algorithm + # should only be applied after preprocessing. + + etpd = estimate_total_polynomial_degree + + P2 = FiniteElement("CG", triangle, 2) + V2 = VectorElement("CG", triangle, 2) + + u = Coefficient(P2) + v = Coefficient(V2) + + self.assertEqual(etpd(u.dx(0)), 2-1) + self.assertEqual(etpd(grad(u)), 2-1) + self.assertEqual(etpd(nabla_grad(u)), 2-1) + self.assertEqual(etpd(div(u)), 2-1) + + self.assertEqual(etpd(v.dx(0)), 2-1) + self.assertEqual(etpd(grad(v)), 2-1) + self.assertEqual(etpd(nabla_grad(v)), 2-1) + self.assertEqual(etpd(div(v)), 2-1) + self.assertEqual(etpd(nabla_div(v)), 2-1) + + self.assertEqual(etpd(dot(v, v)), 2+2) + self.assertEqual(etpd(inner(v, v)), 2+2) + + self.assertEqual(etpd(dot(grad(u), grad(u))), 2-1 + 2-1) + self.assertEqual(etpd(inner(grad(u), grad(u))), 2-1 + 2-1) + + self.assertEqual(etpd(dot(grad(v), grad(v))), 2-1 + 2-1) + self.assertEqual(etpd(inner(grad(v), grad(v))), 2-1 + 2-1) + +if __name__ == "__main__": + main() diff -Nru ufl-1.2.0/test/test_elements.py ufl-1.3.0/test/test_elements.py --- ufl-1.2.0/test/test_elements.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/test/test_elements.py 2014-01-07 13:29:26.000000000 +0000 @@ -1,6 +1,6 @@ #!/usr/bin/env python -# Last changed: 2009-12-08 +# Last changed: 2013-04-04 from ufltestcase import UflTestCase, main @@ -165,5 +165,23 @@ element = VectorElement("CG", cell, degree) self.assertEqual(element, eval(repr(element))) + def test_lobatto(self): + cell = interval + for degree in (1, 2, None): + element = FiniteElement("Lob", cell, degree) + self.assertEqual(element, eval(repr(element))) + + element = FiniteElement("Lobatto", cell, degree) + self.assertEqual(element, eval(repr(element))) + + def test_radau(self): + cell = interval + for degree in (0, 1, 2, None): + element = FiniteElement("Rad", cell, degree) + self.assertEqual(element, eval(repr(element))) + + element = FiniteElement("Radau", cell, degree) + self.assertEqual(element, eval(repr(element))) + if __name__ == "__main__": main() diff -Nru ufl-1.2.0/test/test_tensoralgebra.py ufl-1.3.0/test/test_tensoralgebra.py --- ufl-1.2.0/test/test_tensoralgebra.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/test/test_tensoralgebra.py 2014-01-07 13:29:26.000000000 +0000 @@ -24,6 +24,16 @@ self.assertEqual(A.shape(), B.shape()) self.assertEqual(inner(A-B, A-B)(None), 0) + def test_repeated_as_tensor(self): + A = as_tensor(self.A) + B = as_matrix(self.B) + u = as_tensor(self.u) + v = as_vector(self.v) + self.assertEqual(A, self.A) + self.assertEqual(B, self.B) + self.assertEqual(u, self.u) + self.assertEqual(v, self.v) + def test_outer(self): C = outer(self.u, self.v) D = as_matrix([[10*30, 10*40], [20*30, 20*40]]) @@ -149,4 +159,3 @@ # Don't touch these lines, they allow you to run this file directly if __name__ == "__main__": main() - diff -Nru ufl-1.2.0/ufl/__init__.py ufl-1.3.0/ufl/__init__.py --- ufl-1.2.0/ufl/__init__.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/__init__.py 2014-01-07 13:29:26.000000000 +0000 @@ -4,7 +4,7 @@ finite element spaces and defining expressions for weak forms in a notation close to mathematical notation. -This python module contains the language as well as algorithms to work +This Python module contains the language as well as algorithms to work with it. * To import the language, type:: @@ -28,9 +28,13 @@ http://www.fenicsproject.org +and + + http://arxiv.org/abs/1211.4047 + The development version can be found in the repository at - https://launchpad.net/ufl/ + https://www.bitbucket.org/fenics-project/ufl A very brief overview of the language contents follows: @@ -72,7 +76,7 @@ SpatialCoordinate, FacetNormal, CellVolume, Circumradius, CellSurfaceArea, - FacetArea, FacetDiameter, + FacetArea, MinFacetEdgeLength, MaxFacetEdgeLength, FacetDiameter, LocalCoordinate, GeometryJacobi, GeometryJacobiDeterminant, InverseGeometryJacobi @@ -113,12 +117,12 @@ abs, sign, sqrt, exp, ln, erf, cos, sin, tan, - acos, asin, atan, + acos, asin, atan, atan_2, cosh, sinh, tanh, bessel_J, bessel_Y, bessel_I, bessel_K * Discontinuous Galerkin operators: - jump, avg, v('+'), v('-') + jump, avg, v('+'), v('-'), cell_avg, facet_avg * Conditional operators:: @@ -157,10 +161,11 @@ # # Modified by Kristian B. Oelgaard, 2009, 2011 # Modified by Anders Logg, 2009. +# Modified by Johannes Ring, 2014. # -# Last changed: 2013-03-15 +# Last changed: 2014-01-07 -__version__ = "1.2.0" +__version__ = "1.3.0" ########## README # Imports here should be what the user sees when doing "from ufl import *", @@ -181,7 +186,7 @@ from ufl.geometry import (Cell, ProductCell, SpatialCoordinate, FacetNormal, CellVolume, Circumradius, CellSurfaceArea, - FacetArea, FacetDiameter, + FacetArea, MinFacetEdgeLength, MaxFacetEdgeLength, FacetDiameter, LocalCoordinate, GeometryJacobi, GeometryJacobiDeterminant, InverseGeometryJacobi) @@ -229,14 +234,14 @@ dev, skew, sym, \ sqrt, exp, ln, erf, \ cos, sin, tan, \ - acos, asin, atan, \ + acos, asin, atan, atan_2, \ cosh, sinh, tanh, \ bessel_J, bessel_Y, bessel_I, bessel_K, \ eq, ne, le, ge, lt, gt, And, Or, Not, \ conditional, sign, Max, Min, \ variable, diff, \ Dx, grad, div, curl, rot, nabla_grad, nabla_div, Dn, exterior_derivative, \ - jump, avg, \ + jump, avg, cell_avg, facet_avg, \ elem_mult, elem_div, elem_pow, elem_op # Form class @@ -266,7 +271,7 @@ 'Cell', 'ProductCell', 'SpatialCoordinate', 'FacetNormal', 'CellVolume', 'Circumradius', 'CellSurfaceArea', - 'FacetArea', 'FacetDiameter', + 'FacetArea', 'MinFacetEdgeLength', 'MaxFacetEdgeLength', 'FacetDiameter', 'LocalCoordinate', 'GeometryJacobi', 'GeometryJacobiDeterminant', 'InverseGeometryJacobi', 'Domain', 'Region', @@ -289,14 +294,14 @@ 'transpose', 'tr', 'diag', 'diag_vector', 'dev', 'skew', 'sym', 'sqrt', 'exp', 'ln', 'erf', 'cos', 'sin', 'tan', - 'acos', 'asin', 'atan', + 'acos', 'asin', 'atan', 'atan_2', 'cosh', 'sinh', 'tanh', 'bessel_J', 'bessel_Y', 'bessel_I', 'bessel_K', 'eq', 'ne', 'le', 'ge', 'lt', 'gt', 'And', 'Or', 'Not', 'conditional', 'sign', 'Max', 'Min', 'variable', 'diff', 'Dx', 'grad', 'div', 'curl', 'rot', 'nabla_grad', 'nabla_div', 'Dn', 'exterior_derivative', - 'jump', 'avg', + 'jump', 'avg', 'cell_avg', 'facet_avg', 'elem_mult', 'elem_div', 'elem_pow', 'elem_op', 'Form', 'Integral', 'Measure', 'register_domain_type', 'ProductMeasure', diff -Nru ufl-1.2.0/ufl/algebra.py ufl-1.3.0/ufl/algebra.py --- ufl-1.2.0/ufl/algebra.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algebra.py 2014-01-07 13:29:26.000000000 +0000 @@ -29,7 +29,7 @@ from ufl.common import product, mergedicts, subdict, EmptyDict from ufl.expr import Expr from ufl.operatorbase import AlgebraOperator -from ufl.constantvalue import Zero, ScalarValue, IntValue, is_ufl_scalar, is_true_ufl_scalar, as_ufl +from ufl.constantvalue import Zero, zero, ScalarValue, IntValue, is_ufl_scalar, is_true_ufl_scalar, as_ufl from ufl.indexutils import unique_indices from ufl.sorting import sorted_expr from ufl.precedence import parstr @@ -386,6 +386,12 @@ if isinstance(a, ScalarValue) and isinstance(b, ScalarValue): return as_ufl(a._value ** b._value) + if a == 0 and isinstance(b, ScalarValue): + bf = float(b) + if bf < 0: + error("Division by zero, annot raise 0 to a negative power.") + else: + return zero() if b == 1: return a if b == 0: diff -Nru ufl-1.2.0/ufl/algorithms/__init__.py ufl-1.3.0/ufl/algorithms/__init__.py --- ufl-1.2.0/ufl/algorithms/__init__.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/__init__.py 2014-01-07 13:29:26.000000000 +0000 @@ -59,8 +59,7 @@ from ufl.algorithms.expand_compounds import CompoundExpander, expand_compounds, \ CompoundExpanderPreDiff, expand_compounds_prediff, \ CompoundExpanderPostDiff, expand_compounds_postdiff -from ufl.algorithms.estimate_degrees import MaxDegreeEstimator, estimate_max_polynomial_degree, \ - SumDegreeEstimator, estimate_total_polynomial_degree +from ufl.algorithms.estimate_degrees import SumDegreeEstimator, estimate_total_polynomial_degree from ufl.algorithms.argument_dependencies import ArgumentDependencyExtracter, extract_argument_dependencies, NotMultiLinearException from ufl.algorithms.deprecated import TreeFlattener, flatten, \ DuplicationMarker, mark_duplications, \ diff -Nru ufl-1.2.0/ufl/algorithms/analysis.py ufl-1.3.0/ufl/algorithms/analysis.py --- ufl-1.2.0/ufl/algorithms/analysis.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/analysis.py 2014-01-07 13:29:26.000000000 +0000 @@ -29,6 +29,7 @@ from ufl.log import error, warning, info from ufl.assertions import ufl_assert from ufl.sorting import topological_sorting +from ufl.common import sorted_by_count from ufl.expr import Expr from ufl.terminal import Terminal, FormArgument @@ -83,9 +84,6 @@ for o in post_traversal(e) \ if isinstance(o, Terminal)) -def sorted_by_count(seq): - return sorted(seq, key=lambda x: x._count) - def extract_arguments(a): """Build a sorted list of all arguments in a, which can be a Form, Integral or Expr.""" diff -Nru ufl-1.2.0/ufl/algorithms/argument_dependencies.py ufl-1.3.0/ufl/algorithms/argument_dependencies.py --- ufl-1.2.0/ufl/algorithms/argument_dependencies.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/argument_dependencies.py 2014-01-07 13:29:26.000000000 +0000 @@ -72,6 +72,8 @@ skew = linear positive_restricted = linear negative_restricted = linear + cell_avg = linear + facet_avg = linear def indexed(self, o, f, i): return f diff -Nru ufl-1.2.0/ufl/algorithms/domain_analysis.py ufl-1.3.0/ufl/algorithms/domain_analysis.py --- ufl-1.2.0/ufl/algorithms/domain_analysis.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/domain_analysis.py 2014-01-07 13:29:26.000000000 +0000 @@ -7,6 +7,8 @@ # Transitional helper constructor from ufl.integral import Integral +from ufl.common import sorted_items + def integral_domain_ids(integral): did = integral.measure().domain_id() if isinstance(did, int): @@ -125,7 +127,7 @@ assert Measure.DOMAIN_ID_OTHERWISE not in sub_integrals sub_integrals[Measure.DOMAIN_ID_OTHERWISE] = [] # Restrict everywhere integral to each subdomain and append to each integral list - for did, itglist in sub_integrals.iteritems(): + for did, itglist in sorted_items(sub_integrals): for itg in ei: # Restrict integral to this subdomain! itglist.append(itg.reconstruct(domain_description=did)) @@ -163,8 +165,8 @@ from ufl.algorithms.analysis import IntegralData def convert_sub_integral_data_to_integral_data(sub_integral_data): integral_data = [] - for domain_type, domain_type_data in sub_integral_data.iteritems(): - for domain_id, sub_domain_integrands in domain_type_data.iteritems(): + for domain_type, domain_type_data in sorted_items(sub_integral_data): + for domain_id, sub_domain_integrands in sorted_items(domain_type_data): integrals = [Integral(integrand, domain_type, domain_id, compiler_data, None) for integrand, compiler_data in sub_domain_integrands] ida = IntegralData(domain_type, domain_id, integrals, {}) @@ -175,9 +177,9 @@ # Print output for inspection: def print_sub_integral_data(sub_integral_data): print - for domain_type, domain_type_data in sub_integral_data.iteritems(): + for domain_type, domain_type_data in sorted_items(sub_integral_data): print "======", domain_type - for domain_id, sub_domain_integrands in domain_type_data.iteritems(): + for domain_id, sub_domain_integrands in sorted_items(domain_type_data): print '---', domain_id, for integrand, compiler_data in sub_domain_integrands: print diff -Nru ufl-1.2.0/ufl/algorithms/estimate_degrees.py ufl-1.3.0/ufl/algorithms/estimate_degrees.py --- ufl-1.2.0/ufl/algorithms/estimate_degrees.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/estimate_degrees.py 2014-01-07 13:29:26.000000000 +0000 @@ -38,14 +38,24 @@ self.default_degree = default_degree self.element_replace_map = element_replace_map - def terminal(self, v): - "Most terminals are spatially constant." + def constant_value(self, v): + "Constant values are constant. Duh." + return 0 + + def geometric_quantity(self, v): + "Most geometric quantities are cellwise constant." + ufl_assert(v.is_cellwise_constant(), + "Missing handler for non-constant geometry type %s." % v._uflclass.__name__) return 0 def spatial_coordinate(self, v): "A coordinate provides one additional degree." return 1 + def local_coordinate(self, v): + "A coordinate provides one additional degree." + return 1 + def form_argument(self, v): """A form argument provides a degree depending on the element, or the default degree if the element has no degree.""" @@ -54,21 +64,88 @@ d = e.degree() # FIXME: Use component to improve accuracy return self.default_degree if d is None else d + def _reduce_degree(self, v, f): + return max(f - 1, 0) + def _add_degrees(self, v, *ops): + return sum(ops) + def _max_degrees(self, v, *ops): + return max(ops + (0,)) + def _not_handled(self, v, *args): + error("Missing degree handler for type %s" % v._uflclass.__name__) + def expr(self, v, *ops): "For most operators we take the max degree of its operands." - return max(ops) + warning("Missing degree estimation handler for type %s" % v._uflclass.__name__) + return self._add_degrees(v, *ops) - def spatial_derivative(self, v, f, i): - "A spatial derivative reduces the degree with one." - return max(f - 1, 0) + # Utility types with no degree concept + def multi_index(self, v): + return None + def label(self, v): + return None + # Fall-through, indexing and similar types + def variable(self, v, e, l): + return e + def transposed(self, v, A): + return A + def index_sum(self, v, A, ii): + return A + def indexed(self, v, A, ii): + return A + def component_tensor(self, v, A, ii): + return A + list_tensor = _max_degrees + def positive_restricted(self, v, a): + return a + def negative_restricted(self, v, a): + return a + + # A sum takes the max degree of its operands: + sum = _max_degrees + + # A spatial derivative reduces the degree with one + grad = _reduce_degree + # Handling these types although they should not occur... please apply preprocessing before using this algorithm: + nabla_grad = _reduce_degree + div = _reduce_degree + nabla_div = _reduce_degree + curl = _reduce_degree - def grad(self, v, f): - "A spatial derivative reduces the degree with one." - return max(f - 1, 0) + def cell_avg(self, v, a): + "Cell average of a function is always cellwise constant." + return 0 - def product(self, v, *ops): - "Using the sum here is exact." - return sum(ops) + def facet_avg(self, v, a): + "Facet average of a function is always cellwise constant." + return 0 + + # A product accumulates the degrees of its operands: + product = _add_degrees + # Handling these types although they should not occur... please apply preprocessing before using this algorithm: + inner = _add_degrees + dot = _add_degrees + outer = _add_degrees + cross = _add_degrees + + # Explicitly not handling these types, please apply preprocessing before using this algorithm: + derivative = _not_handled # base type + compound_derivative = _not_handled # base type + compound_tensor_operator = _not_handled # base class + variable_derivative = _not_handled + trace = _not_handled + determinant = _not_handled + cofactor = _not_handled + inverse = _not_handled + deviatoric = _not_handled + skew = _not_handled + sym = _not_handled + + def abs(self, v, a): + "This is a heuristic, correct if there is no " + if a == 0: + return a + else: + return a def division(self, v, *ops): "Using the sum here is a heuristic. Consider e.g. (x+1)/(x-1)." @@ -81,13 +158,27 @@ degree(a**b) == degree(a)*2""" f, g = v.operands() try: - gi = int(g) + gi = abs(int(g)) return a*gi except: pass # Something to a non-integer power, this is just a heuristic with no background return a*2 + def atan_2(self, v, a, b): + """Using the heuristic + degree(atan2(const,const)) == 0 + degree(atan2(a,b)) == max(degree(a),degree(b))+2 + which can be wildly inaccurate but at least + gives a somewhat high integration degree. + """ + #print "estimate",a,b + if a or b: + return max(a,b)+2 + else: + return max(a,b) + + def math_function(self, v, a): """Using the heuristic degree(sin(const)) == 0 @@ -112,6 +203,9 @@ else: return x + def condition(self, v, *args): + return None + def conditional(self, v, c, t, f): """Degree of condition does not influence degree of values which @@ -124,51 +218,17 @@ quadrature order must be adjusted manually.""" return max(t, f) -class MaxDegreeEstimator(Transformer): - def __init__(self, default_degree, element_replace_map): - Transformer.__init__(self) - self.default_degree = default_degree - self.element_replace_map = element_replace_map - - def terminal(self, v): - return 0 - - def expr(self, v, *ops): - return max(ops) - - def form_argument(self, v): - e = v.element() - e = self.element_replace_map.get(e,e) - return e.degree() # FIXME: Use component to improve accuracy - - #def spatial_derivative(self, v, f, i): - # return max(f - 1, 0) - #def grad(self, v, f): - # return max(f - 1, 0) - - def product(self, v, *ops): - degrees = [op for op in ops if not op is None] - nones = [op for op in ops if op is None] - return max(degrees + [self.default_degree]) - -def estimate_max_polynomial_degree(e, default_degree=1, element_replace_map={}): - """Estimate the maximum polymomial degree of all functions in the - expression. For coefficients defined on an element with unspecified - degree (None), the degree is set to the given default degree.""" - de = MaxDegreeEstimator(default_degree, element_replace_map) - if isinstance(e, Form): - ufl_assert(e.integrals(), "Got form with no integrals!") - degrees = [de.visit(integral.integrand()) for integral in e.integrals()] - elif isinstance(e, Integral): - degrees = [de.visit(e.integrand())] - else: - degrees = [de.visit(e)] - return max(degrees + [0]) - def estimate_total_polynomial_degree(e, default_degree=1, element_replace_map={}): - """Estimate total polynomial degree of integrand. For coefficients - defined on an element with unspecified degree (None), the degree - is set to the given default degree.""" + """Estimate total polynomial degree of integrand. + + NB! Although some compound types are supported here, + some derivatives and compounds must be preprocessed + prior to degree estimation. In generic code, this algorithm + should only be applied after preprocessing. + + For coefficients defined on an element with unspecified degree (None), + the degree is set to the given default degree. + """ de = SumDegreeEstimator(default_degree, element_replace_map) if isinstance(e, Form): ufl_assert(e.integrals(), "Got form with no integrals!") diff -Nru ufl-1.2.0/ufl/algorithms/expand_compounds.py ufl-1.3.0/ufl/algorithms/expand_compounds.py --- ufl-1.2.0/ufl/algorithms/expand_compounds.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/expand_compounds.py 2014-01-07 13:29:26.000000000 +0000 @@ -57,7 +57,7 @@ def _square_matrix_shape(self, A): sh = A.shape() if self._dim is not None: - sh = complete_shape(sh, self._dim) + sh = complete_shape(sh, self._dim) # FIXME: Does this ever happen? Pretty sure other places assume shapes are always "complete". ufl_assert(sh[0] == sh[1], "Expecting square matrix.") ufl_assert(sh[0] is not None, "Unknown dimension.") return sh @@ -123,6 +123,39 @@ error("Determinant not implemented for dimension %d." % self._dim) def cofactor(self, o, A): + # TODO: Find common subexpressions here. + # TODO: Better implementation? + sh = self._square_matrix_shape(A) + if sh[0] == 2: + return as_matrix([[A[1,1],-A[1,0]],[-A[0,1],A[0,0]]]) + elif sh[0] == 3: + return as_matrix([ + [A[1,1]*A[2,2] - A[2,1]*A[1,2],A[2,0]*A[1,2] - A[1,0]*A[2,2], - A[2,0]*A[1,1] + A[1,0]*A[2,1]], + [A[2,1]*A[0,2] - A[0,1]*A[2,2],A[0,0]*A[2,2] - A[2,0]*A[0,2], - A[0,0]*A[2,1] + A[2,0]*A[0,1]], + [A[0,1]*A[1,2] - A[1,1]*A[0,2],A[1,0]*A[0,2] - A[0,0]*A[1,2], - A[1,0]*A[0,1] + A[0,0]*A[1,1]] + ]) + elif sh[0] == 4: + return as_matrix([ + [-A[3,1]*A[2,2]*A[1,3] - A[3,2]*A[2,3]*A[1,1] + A[1,3]*A[3,2]*A[2,1] + A[3,1]*A[2,3]*A[1,2] + A[2,2]*A[1,1]*A[3,3] - A[3,3]*A[2,1]*A[1,2], + -A[1,0]*A[2,2]*A[3,3] + A[2,0]*A[3,3]*A[1,2] + A[2,2]*A[1,3]*A[3,0] - A[2,3]*A[3,0]*A[1,2] + A[1,0]*A[3,2]*A[2,3] - A[1,3]*A[3,2]*A[2,0], + A[1,0]*A[3,3]*A[2,1] + A[2,3]*A[1,1]*A[3,0] - A[2,0]*A[1,1]*A[3,3] - A[1,3]*A[3,0]*A[2,1] - A[1,0]*A[3,1]*A[2,3] + A[3,1]*A[1,3]*A[2,0], + A[3,0]*A[2,1]*A[1,2] + A[1,0]*A[3,1]*A[2,2] + A[3,2]*A[2,0]*A[1,1] - A[2,2]*A[1,1]*A[3,0] - A[3,1]*A[2,0]*A[1,2] - A[1,0]*A[3,2]*A[2,1]], + [ A[3,1]*A[2,2]*A[0,3] + A[0,2]*A[3,3]*A[2,1] + A[0,1]*A[3,2]*A[2,3] - A[3,1]*A[0,2]*A[2,3] - A[0,1]*A[2,2]*A[3,3] - A[3,2]*A[0,3]*A[2,1], + -A[2,2]*A[0,3]*A[3,0] - A[0,2]*A[2,0]*A[3,3] - A[3,2]*A[2,3]*A[0,0] + A[2,2]*A[3,3]*A[0,0] + A[0,2]*A[2,3]*A[3,0] + A[3,2]*A[2,0]*A[0,3], + A[3,1]*A[2,3]*A[0,0] - A[0,1]*A[2,3]*A[3,0] - A[3,1]*A[2,0]*A[0,3] - A[3,3]*A[0,0]*A[2,1] + A[0,3]*A[3,0]*A[2,1] + A[0,1]*A[2,0]*A[3,3], + A[3,2]*A[0,0]*A[2,1] - A[0,2]*A[3,0]*A[2,1] + A[0,1]*A[2,2]*A[3,0] + A[3,1]*A[0,2]*A[2,0] - A[0,1]*A[3,2]*A[2,0] - A[3,1]*A[2,2]*A[0,0]], + [ A[3,1]*A[1,3]*A[0,2] - A[0,2]*A[1,1]*A[3,3] - A[3,1]*A[0,3]*A[1,2] + A[3,2]*A[1,1]*A[0,3] + A[0,1]*A[3,3]*A[1,2] - A[0,1]*A[1,3]*A[3,2], + A[1,3]*A[3,2]*A[0,0] - A[1,0]*A[3,2]*A[0,3] - A[1,3]*A[0,2]*A[3,0] + A[0,3]*A[3,0]*A[1,2] + A[1,0]*A[0,2]*A[3,3] - A[3,3]*A[0,0]*A[1,2], + -A[1,0]*A[0,1]*A[3,3] + A[0,1]*A[1,3]*A[3,0] - A[3,1]*A[1,3]*A[0,0] - A[1,1]*A[0,3]*A[3,0] + A[1,0]*A[3,1]*A[0,3] + A[1,1]*A[3,3]*A[0,0], + A[0,2]*A[1,1]*A[3,0] - A[3,2]*A[1,1]*A[0,0] - A[0,1]*A[3,0]*A[1,2] - A[1,0]*A[3,1]*A[0,2] + A[3,1]*A[0,0]*A[1,2] + A[1,0]*A[0,1]*A[3,2]], + [ A[0,3]*A[2,1]*A[1,2] + A[0,2]*A[2,3]*A[1,1] + A[0,1]*A[2,2]*A[1,3] - A[2,2]*A[1,1]*A[0,3] - A[1,3]*A[0,2]*A[2,1] - A[0,1]*A[2,3]*A[1,2], + A[1,0]*A[2,2]*A[0,3] + A[1,3]*A[0,2]*A[2,0] - A[1,0]*A[0,2]*A[2,3] - A[2,0]*A[0,3]*A[1,2] - A[2,2]*A[1,3]*A[0,0] + A[2,3]*A[0,0]*A[1,2], + -A[0,1]*A[1,3]*A[2,0] + A[2,0]*A[1,1]*A[0,3] + A[1,3]*A[0,0]*A[2,1] - A[1,0]*A[0,3]*A[2,1] + A[1,0]*A[0,1]*A[2,3] - A[2,3]*A[1,1]*A[0,0], + A[1,0]*A[0,2]*A[2,1] - A[0,2]*A[2,0]*A[1,1] + A[0,1]*A[2,0]*A[1,2] + A[2,2]*A[1,1]*A[0,0] - A[1,0]*A[0,1]*A[2,2] - A[0,0]*A[2,1]*A[1,2]] + ]) + error("Cofactor not implemented for dimension %s." % sh[0]) + + def _cofactor_transposed(self, o, A): sh = self._square_matrix_shape(A) if sh[0] == 2: @@ -165,7 +198,7 @@ def inverse(self, o, A): if A.rank() == 0: return 1.0 / A - return self.cofactor(None, A) / self.determinant(None, A) + return self._cofactor_transposed(None, A) / self.determinant(None, A) # ------------ Compound differential operators diff -Nru ufl-1.2.0/ufl/algorithms/formfiles.py ufl-1.3.0/ufl/algorithms/formfiles.py --- ufl-1.2.0/ufl/algorithms/formfiles.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/formfiles.py 2014-01-07 13:29:26.000000000 +0000 @@ -27,6 +27,7 @@ import os, re from ufl.log import error, warning +from ufl.common import sorted_items from ufl.assertions import ufl_assert from ufl.form import Form from ufl.finiteelement import FiniteElementBase @@ -109,7 +110,7 @@ # The use of id(obj) as key in object_names is necessary # because we need to distinguish between instances, # and not just between objects with different values. - for name, value in namespace.iteritems(): + for name, value in sorted_items(namespace): # Store objects by reserved name OR instance id reserved_names = ("unknown",) # Currently only one reserved name if name in reserved_names: diff -Nru ufl-1.2.0/ufl/algorithms/formtransformations.py ufl-1.3.0/ufl/algorithms/formtransformations.py --- ufl-1.2.0/ufl/algorithms/formtransformations.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/formtransformations.py 2014-01-07 13:29:26.000000000 +0000 @@ -151,7 +151,7 @@ # 3. Return the terms that provide the biggest set most_provided = frozenset() - for (provideds, parts) in parts_that_provide.iteritems(): + for (provideds, parts) in parts_that_provide.iteritems(): # TODO: Just sort instead? # Throw error if size of sets are equal (and not zero) if len(provideds) == len(most_provided) and len(most_provided): @@ -244,6 +244,10 @@ positive_restricted = linear_operator negative_restricted = linear_operator + # Cell and facet average are linear operators + cell_avg = linear_operator + facet_avg = linear_operator + # Grad is a linear operator grad = linear_operator diff -Nru ufl-1.2.0/ufl/algorithms/forward_ad.py ufl-1.3.0/ufl/algorithms/forward_ad.py --- ufl-1.2.0/ufl/algorithms/forward_ad.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/forward_ad.py 2014-01-07 13:29:26.000000000 +0000 @@ -23,7 +23,7 @@ # Modified by Jan Blechta, 2012. # # First added: 2008-08-19 -# Last changed: 2012-10-03 +# Last changed: 2013-08-12 from itertools import izip from math import pi @@ -46,15 +46,16 @@ from ufl.algebra import Sum, Product, Division, Power, Abs from ufl.tensoralgebra import Transposed, Outer, Inner, Dot, Cross, Trace, \ Determinant, Inverse, Deviatoric, Cofactor -from ufl.mathfunctions import MathFunction, Sqrt, Exp, Ln, Cos, Sin, Tan, Acos, Asin, Atan, Erf, BesselJ, BesselY, BesselI, BesselK +from ufl.mathfunctions import MathFunction, Sqrt, Exp, Ln, Cos, Sin, Tan, Acos, Asin, Atan, Atan2, Erf, BesselJ, BesselY, BesselI, BesselK from ufl.restriction import Restricted, PositiveRestricted, NegativeRestricted from ufl.differentiation import Derivative, CoefficientDerivative,\ VariableDerivative, Grad from ufl.conditional import EQ, NE, LE, GE, LT, GT, Conditional from ufl.operators import dot, inner, outer, lt, eq, conditional, sign, \ - sqrt, exp, ln, cos, sin, tan, cosh, sinh, tanh, acos, asin, atan, \ - erf, bessel_J, bessel_Y, bessel_I, bessel_K + sqrt, exp, ln, cos, sin, tan, cosh, sinh, tanh, acos, asin, atan, atan_2, \ + erf, bessel_J, bessel_Y, bessel_I, bessel_K, \ + cell_avg, facet_avg from ufl.algorithms.transformer import Transformer @@ -483,6 +484,13 @@ op = fp/(1.0 + f**2) return (o, op) + def atan_2(self, o, a, b): + f, fp = a + g, gp = b + o = self.reuse_if_possible(o, f, g) + op = (g*fp-f*gp)/(f**2+g**2) + return (o, op) + def erf(self, o, a): f, fp = a o = self.reuse_if_possible(o, f) @@ -548,6 +556,24 @@ else: return (o, fp(o._side)) # (f+-)' == (f')+- + def cell_avg(self, o, a): + # Cell average of a single function and differentiation commutes. + f, fp = a + o = self.reuse_if_possible(o, f) + if isinstance(fp, ConstantValue): + return (o, fp) # TODO: Necessary? Can't CellAvg simplify directly instead? + else: + return (o, cell_avg(fp)) + + def facet_avg(self, o, a): + # Facet average of a single function and differentiation commutes. + f, fp = a + o = self.reuse_if_possible(o, f) + if isinstance(fp, ConstantValue): + return (o, fp) # TODO: Necessary? Can't FacetAvg simplify directly instead? + else: + return (o, facet_avg(fp)) + # --- Conditionals def binary_condition(self, o, l, r): @@ -908,20 +934,17 @@ self._variable_cache[l] = c return c -def compute_grad_forward_ad(expr, dim): - f, = expr.operands() +def compute_grad_forward_ad(f, dim): alg = GradAD(dim) e, ediff = alg.visit(f) return ediff -def compute_variable_forward_ad(expr, dim): - f, v = expr.operands() +def compute_variable_forward_ad(f, v, dim): alg = VariableAD(dim, v) e, ediff = alg.visit(f) return ediff -def compute_coefficient_forward_ad(expr, dim): - f, w, v, cd = expr.operands() +def compute_coefficient_forward_ad(f, w, v, cd, dim): alg = CoefficientAD(dim, w, v, cd) e, ediff = alg.visit(f) return ediff @@ -930,36 +953,35 @@ if isinstance(expr, Terminal): # A terminal needs no differentiation applied return expr - else: - # Store the original expression here, because - # reconstruct below may simplify and make expr - # get the type of a child, which may be a derivative, - # even if preexpr here is not a derivative. - preexpr = expr - + elif not isinstance(expr, Derivative): # Apply AD recursively to children preops = expr.operands() postops = tuple(apply_nested_forward_ad(o, dim) for o in preops) - + # Reconstruct if necessary need_reconstruct = not (preops == postops) # FIXME: Is this efficient? O(n)? if need_reconstruct: expr = expr.reconstruct(*postops) - - # Preliminary result - result = expr - - # Check if this node is a derivative, if so apply AD to it - if isinstance(preexpr, Derivative): - if isinstance(expr, Grad): - result = compute_grad_forward_ad(expr, dim) - elif isinstance(preexpr, VariableDerivative): - result = compute_variable_forward_ad(expr, dim) - elif isinstance(preexpr, CoefficientDerivative): - result = compute_coefficient_forward_ad(expr, dim) - else: - error("This shouldn't happen: expr is %s" % repr(expr)) - # Return the expanded result - return result + return expr + elif isinstance(expr, Grad): + # Apply AD recursively to children + f, = expr.operands() + f = apply_nested_forward_ad(f, dim) + # Apply Grad-specialized AD to expanded child + return compute_grad_forward_ad(f, dim) + elif isinstance(expr, VariableDerivative): + # Apply AD recursively to children + f, v = expr.operands() + f = apply_nested_forward_ad(f, dim) + # Apply Variable-specialized AD to expanded child + return compute_variable_forward_ad(f, v, dim) + elif isinstance(expr, CoefficientDerivative): + # Apply AD recursively to children + f, w, v, cd = expr.operands() + f = apply_nested_forward_ad(f, dim) + # Apply Coefficient-specialized AD to expanded child + return compute_coefficient_forward_ad(f, w, v, cd, dim) + else: + error("Unknown type.") # TODO: We could expand only the compound objects that have no rule # before differentiating, to allow the AD to work on a coarser graph diff -Nru ufl-1.2.0/ufl/algorithms/pdiffs.py ufl-1.3.0/ufl/algorithms/pdiffs.py --- ufl-1.2.0/ufl/algorithms/pdiffs.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/pdiffs.py 2014-01-07 13:29:26.000000000 +0000 @@ -151,6 +151,16 @@ x, = f.operands() return (1.0/(1.0 + x**2),) + def atan_2(self, f): + """ + f = atan2(x,y) + d/dx atan2(x,y) = y / (x**2 + y**2 ) + d/dy atan2(x,y) = -x / (x**2 + y**2) + """ + x,y = f.operands() + d = x**2 + y**2 + return (y/d,-x/d) + def erf(self, f): "d/dx erf x = 2/sqrt(pi)*exp(-x^2)" x, = f.operands() @@ -195,6 +205,12 @@ _1 = IntValue(1) return (_1,) # or _1('-')? TODO: is this right? + def cell_avg(self, f): + error("Not sure how to implement partial derivative of this operator at all actually.") + + def facet_avg(self, f): + error("Not sure how to implement partial derivative of this operator at all actually.") + # --- Conditionals def condition(self, f): diff -Nru ufl-1.2.0/ufl/algorithms/printing.py ufl-1.3.0/ufl/algorithms/printing.py --- ufl-1.2.0/ufl/algorithms/printing.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/printing.py 2014-01-07 13:29:26.000000000 +0000 @@ -30,7 +30,7 @@ from ufl.expr import Expr from ufl.terminal import Terminal from ufl.form import Form -from ufl.integral import Integral +from ufl.integral import Integral, Measure from ufl.algorithms.analysis import extract_arguments, extract_coefficients #--- Utilities for constructing informative strings from UFL objects --- @@ -122,7 +122,7 @@ s += ind + "Integral:\n" ind = _indent_string(indentation+1) s += ind + "domain type: %s\n" % expression.measure().domain_type() - s += ind + "domain id: %d\n" % expression.measure().domain_id() + s += ind + "domain id: %s\n" % expression.measure().domain_id() s += ind + "integrand:\n" s += tree_format(expression._integrand, indentation+2, parentheses) diff -Nru ufl-1.2.0/ufl/algorithms/propagate_restrictions.py ufl-1.3.0/ufl/algorithms/propagate_restrictions.py --- ufl-1.2.0/ufl/algorithms/propagate_restrictions.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/propagate_restrictions.py 2014-01-07 13:29:26.000000000 +0000 @@ -63,7 +63,7 @@ # return o return o(self.current_restriction) - # facet_area and facet_diameter are the same from both sides of a facet + # facet_area, facet_diameter, max_facet_edge_length are all the same from both sides of a facet def form_argument(self, o): ufl_assert(self.current_restriction is not None, "Form argument must be restricted.") diff -Nru ufl-1.2.0/ufl/algorithms/replace.py ufl-1.3.0/ufl/algorithms/replace.py --- ufl-1.2.0/ufl/algorithms/replace.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/replace.py 2014-01-07 13:29:26.000000000 +0000 @@ -51,7 +51,7 @@ @param mapping: A dict with from:to replacements to perform. """ - mapping2 = dict((k, as_ufl(v)) for (k,v) in mapping.iteritems()) + mapping2 = dict((k, as_ufl(v)) for (k,v) in mapping.iteritems()) # TODO: Should this be sorted? # Workaround for problem with delayed derivative evaluation if extract_type(e, CoefficientDerivative): diff -Nru ufl-1.2.0/ufl/algorithms/signature.py ufl-1.3.0/ufl/algorithms/signature.py --- ufl-1.2.0/ufl/algorithms/signature.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/signature.py 2014-01-07 13:29:26.000000000 +0000 @@ -24,7 +24,7 @@ from ufl.classes import Index, MultiIndex, Coefficient, Argument, Terminal, Label from ufl.log import error from ufl.algorithms.traversal import traverse_terminals2 -from ufl.common import fast_pre_traversal +from ufl.common import fast_pre_traversal, sorted_by_count def compute_multiindex_hashdata(expr, index_numbering): data = [] @@ -77,8 +77,8 @@ # Apply renumbering of form arguments # (Note: some duplicated work here and in preprocess, # to allow using this function without preprocess.) - coefficients = sorted(coefficients, key=lambda x: x.count()) - arguments = sorted(arguments, key=lambda x: x.count()) + coefficients = sorted_by_count(coefficients) + arguments = sorted_by_count(arguments) for i, e in enumerate(coefficients): er = function_replace_map.get(e) or e.reconstruct(count=i) terminal_hashdata[e] = repr(er) diff -Nru ufl-1.2.0/ufl/algorithms/transformations.py ufl-1.3.0/ufl/algorithms/transformations.py --- ufl-1.2.0/ufl/algorithms/transformations.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/transformations.py 2014-01-07 13:29:26.000000000 +0000 @@ -33,7 +33,6 @@ from ufl.algorithms.transformer import VariableStripper, strip_variables from ufl.algorithms.replace import Replacer, replace from ufl.algorithms.expand_compounds import CompoundExpander, expand_compounds -from ufl.algorithms.estimate_degrees import MaxDegreeEstimator, estimate_max_polynomial_degree from ufl.algorithms.estimate_degrees import SumDegreeEstimator, estimate_total_polynomial_degree from ufl.algorithms.argument_dependencies import ArgumentDependencyExtracter, extract_argument_dependencies, NotMultiLinearException from ufl.algorithms.deprecated import TreeFlattener, flatten diff -Nru ufl-1.2.0/ufl/algorithms/ufl2dot.py ufl-1.3.0/ufl/algorithms/ufl2dot.py --- ufl-1.2.0/ufl/algorithms/ufl2dot.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/ufl2dot.py 2014-01-07 13:29:26.000000000 +0000 @@ -70,6 +70,8 @@ return "cell volume" def cell_surface_area(self, e): return "surface area" + def max_facet_edge_length(self, e): + return "max facet edge length" def facet_area(self, e): return "facet area" def facet_diameter(self, e): @@ -96,6 +98,10 @@ return "[-]" def positive_restricted(self, e): return "[+]" + def cell_avg(self, e): # TODO: Understandable short notation for this? + return "_K_" + def facet_avg(self, e): # TODO: Understandable short notation for this? + return "_F_" def inner(self, e): return "inner" diff -Nru ufl-1.2.0/ufl/algorithms/ufl2latex.py ufl-1.3.0/ufl/algorithms/ufl2latex.py --- ufl-1.2.0/ufl/algorithms/ufl2latex.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/algorithms/ufl2latex.py 2014-01-07 13:29:26.000000000 +0000 @@ -40,8 +40,8 @@ from ufl.algebra import Sum, Product, Division, Power, Abs from ufl.indexsum import IndexSum from ufl.tensoralgebra import Transposed, Outer, Inner, Dot, Cross, Trace, Determinant, Inverse, Deviatoric, Cofactor -from ufl.mathfunctions import Sqrt, Exp, Ln, Cos, Sin, Tan, Cosh, Sinh, Tanh, Acos, Asin, Atan, Erf, BesselJ, BesselY, BesselI, BesselK -from ufl.restriction import PositiveRestricted, NegativeRestricted +from ufl.mathfunctions import Sqrt, Exp, Ln, Cos, Sin, Tan, Cosh, Sinh, Tanh, Acos, Asin, Atan, Atan2, Erf, BesselJ, BesselY, BesselI, BesselK +from ufl.restriction import PositiveRestricted, NegativeRestricted, CellAvg, FacetAvg from ufl.differentiation import VariableDerivative, Grad, Div, Curl, NablaGrad, NablaDiv from ufl.conditional import EQ, NE, LE, GE, LT, GT, Conditional from ufl.form import Form @@ -73,6 +73,7 @@ # TODO: What to do with these? precedence_list.append((ListTensor, ComponentTensor)) + precedence_list.append((CellAvg, )) precedence_list.append((NegativeRestricted, PositiveRestricted)) precedence_list.append((Conditional,)) precedence_list.append((LE, GT, GE, NE, EQ, LT)) @@ -81,7 +82,7 @@ Determinant, Trace, Cofactor, Inverse, Deviatoric)) precedence_list.append((Product, Division, Cross, Dot, Outer, Inner)) precedence_list.append((Indexed, Transposed, Power)) - precedence_list.append((Abs, Cos, Cosh, Exp, Ln, Sin, Sinh, Sqrt, Tan, Tanh, Acos, Asin, Atan, Erf, BesselJ, BesselY, BesselI, BesselK)) + precedence_list.append((Abs, Cos, Cosh, Exp, Ln, Sin, Sinh, Sqrt, Tan, Tanh, Acos, Asin, Atan, Atan2, Erf, BesselJ, BesselY, BesselI, BesselK)) precedence_list.append((Variable,)) precedence_list.append(terminal_classes) @@ -249,6 +250,9 @@ def atan(self, o, f): return r"\arctan{%s}" % par(f) + def atan2(self, o, f1, f2): + return r"\arctan_2{%s,%s}" % (par(f1), par(f2)) + def erf(self, o, f): return r"\erf{%s}" % par(f) @@ -325,6 +329,9 @@ def negative_restricted(self, o, f): return "{%s}^-" % par(f) + def cell_avg(self, o, f): + return "{%s}_K" % par(f) + def eq(self, o, a, b): return "(%s = %s)" % (a, b) @@ -399,27 +406,27 @@ # Define elements lines = [] - for i, f in enumerate(formdata.arguments): + for i, f in enumerate(formdata.original_arguments): lines.append(r"\mathcal{P}_{%d} = \{%s\} " % (i, element2latex(f.element()))) - for i, f in enumerate(formdata.coefficients): + for i, f in enumerate(formdata.original_coefficients): lines.append(r"\mathcal{Q}_{%d} = \{%s\} " % (i, element2latex(f.element()))) if lines: sections.append(("Finite elements", align(lines))) # Define function spaces lines = [] - for i, f in enumerate(formdata.arguments): + for i, f in enumerate(formdata.original_arguments): lines.append("V_h^{%d} = \\{v : v \\vert_K \\in \\mathcal{P}_{%d}(K) \\quad \\forall K \\in \\mathcal{T}\\} " % (i, i)) - for i, f in enumerate(formdata.coefficients): + for i, f in enumerate(formdata.original_coefficients): lines.append("W_h^{%d} = \\{v : v \\vert_K \\in \\mathcal{Q}_{%d}(K) \\quad \\forall K \\in \\mathcal{T}\\} " % (i, i)) if lines: sections.append(("Function spaces", align(lines))) # Define arguments and coefficients lines = [] - for i, f in enumerate(formdata.arguments): + for i, f in enumerate(formdata.original_arguments): lines.append("%s = %s \\in V_h^{%d} " % (argument_names[i], bfname(i), i)) - for i, f in enumerate(formdata.coefficients): + for i, f in enumerate(formdata.original_coefficients): lines.append("%s = %s \\in W_h^{%d} " % (coefficient_names[i], cfname(i), i)) if lines: sections.append(("Form arguments", align(lines))) diff -Nru ufl-1.2.0/ufl/classes.py ufl-1.3.0/ufl/classes.py --- ufl-1.2.0/ufl/classes.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/classes.py 2014-01-07 13:29:26.000000000 +0000 @@ -25,7 +25,7 @@ # Modified by Kristian B. Oelgaard, 2011 # # First added: 2008-08-15 -# Last changed: 2013-03-04 +# Last changed: 2013-03-29 from ufl.assertions import ufl_assert @@ -48,7 +48,7 @@ GeometricQuantity, SpatialCoordinate, FacetNormal, CellVolume, Circumradius, CellSurfaceArea, - FacetArea, FacetDiameter, + FacetArea, MinFacetEdgeLength, MaxFacetEdgeLength, FacetDiameter, LocalCoordinate, GeometryJacobi, GeometryJacobiDeterminant, InverseGeometryJacobi) from ufl.indexing import IndexBase, FixedIndex, Index, MultiIndex @@ -63,14 +63,14 @@ from ufl.tensoralgebra import CompoundTensorOperator, Transposed, Outer,\ Inner, Dot, Cross, Trace, Determinant, Cofactor, Inverse, Deviatoric, Skew, Sym from ufl.mathfunctions import MathFunction, Sqrt, Exp, Ln, Erf,\ - Cos, Sin, Tan, Cosh, Sinh, Tanh, Acos, Asin, Atan,\ + Cos, Sin, Tan, Cosh, Sinh, Tanh, Acos, Asin, Atan, Atan2, \ BesselFunction, BesselJ, BesselY, BesselI, BesselK from ufl.differentiation import Derivative, CompoundDerivative, CoefficientDerivative,\ VariableDerivative, Grad, Div, Curl, NablaGrad, NablaDiv from ufl.conditional import Condition, BinaryCondition,\ EQ, NE, LE, GE, LT, GT,\ AndCondition, OrCondition, NotCondition, Conditional -from ufl.restriction import Restricted, PositiveRestricted, NegativeRestricted +from ufl.restriction import Restricted, PositiveRestricted, NegativeRestricted, CellAvg, FacetAvg # Higher level abstractions from ufl.integral import Measure, ProductMeasure, Integral diff -Nru ufl-1.2.0/ufl/common.py ufl-1.3.0/ufl/common.py --- ufl-1.2.0/ufl/common.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/common.py 2014-01-07 13:29:26.000000000 +0000 @@ -68,6 +68,12 @@ error("This is a frozen unique empty dictionary object, inserting values is an error.") EmptyDict = EmptyDictType() +def sorted_by_count(seq): + return sorted(seq, key=lambda x: x._count) + +def sorted_items(mapping): + return sorted(mapping.iteritems(), key=lambda x: x[0]) + def mergedicts(dicts): d = dict(dicts[0]) for d2 in dicts[1:]: diff -Nru ufl-1.2.0/ufl/exprequals.py ufl-1.3.0/ufl/exprequals.py --- ufl-1.2.0/ufl/exprequals.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/exprequals.py 2014-01-07 13:29:26.000000000 +0000 @@ -79,8 +79,7 @@ def print_collisions(): print print "Collision statistics:" - keys = equalscalls.keys() - keys = sorted(keys, key=lambda x: collisions.get(x,0)) + keys = sorted(equalscalls.keys(), key=lambda x: collisions.get(x,0)) for k in keys: co = collisions.get(k,0) ca = equalscalls[k] diff -Nru ufl-1.2.0/ufl/finiteelement/elementlist.py ufl-1.3.0/ufl/finiteelement/elementlist.py --- ufl-1.2.0/ufl/finiteelement/elementlist.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/finiteelement/elementlist.py 2014-01-07 13:29:26.000000000 +0000 @@ -126,6 +126,10 @@ "interval", "triangle", "tetrahedron", "quadrilateral", "hexahedron")) +register_element("Lobatto", "Lob", 0, (1, None), ("interval",)) + +register_element("Radau", "Rad", 0, (0, None), ("interval",)) + # Let Nedelec H(div) elements be aliases to BDMs/RTs register_alias("Nedelec 1st kind H(div)", lambda family, cell, order, degree: ("Raviart-Thomas", cell, order)) diff -Nru ufl-1.2.0/ufl/form.py ufl-1.3.0/ufl/form.py --- ufl-1.2.0/ufl/form.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/form.py 2014-01-07 13:29:26.000000000 +0000 @@ -29,6 +29,7 @@ from ufl.integral import Integral, Measure, is_scalar_constant_expression from ufl.equation import Equation from ufl.expr import Expr +from ufl.constantvalue import Zero # --- The Form class, representing a complete variational form or functional --- @@ -141,6 +142,9 @@ elif isinstance(other, (int,float)) and other == 0: # Allow adding 0 or 0.0 as a no-op, needed for sum([a,b]) return self + elif isinstance(other, Zero) and not (other.shape() or other.free_indices()): + # Allow adding ufl Zero as a no-op, needed for sum([a,b]) + return self else: # Let python protocols do their job if we don't handle it return NotImplemented diff -Nru ufl-1.2.0/ufl/geometry.py ufl-1.3.0/ufl/geometry.py --- ufl-1.2.0/ufl/geometry.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/geometry.py 2014-01-07 13:29:26.000000000 +0000 @@ -22,7 +22,7 @@ # Modified by Marie E. Rognes 2012 # # First added: 2008-03-14 -# Last changed: 2012-11-30 +# Last changed: 2013-04-29 from ufl.log import warning, error from ufl.assertions import ufl_assert @@ -53,7 +53,7 @@ "hexahedron": "quadrilateral"} # Valid UFL cellnames -ufl_cellnames = tuple(cellname2dim.keys()) +ufl_cellnames = tuple(sorted(cellname2dim.keys())) # FIXME DOMAIN: Figure out which quantities to make available from Domain. # Need deprecation warnings for a while from the cell. @@ -271,7 +271,10 @@ return "FacetArea(%r)" % self._cell class FacetDiameter(GeometricQuantity): - "Representation of the diameter of a facet." + """(EXPERIMENTAL) Representation of the diameter of a facet. + + This is not yet defined. + """ __slots__ = () def __init__(self, cell): GeometricQuantity.__init__(self, cell) @@ -285,6 +288,37 @@ def __repr__(self): return "FacetDiameter(%r)" % self._cell +class MinFacetEdgeLength(GeometricQuantity): + "Representation of the minimum edge length of a facet." + __slots__ = () + def __init__(self, cell): + GeometricQuantity.__init__(self, cell) + + def shape(self): + return () + + def __str__(self): + return "minfacetedgelength" + + def __repr__(self): + return "MinFacetEdgeLength(%r)" % self._cell + +class MaxFacetEdgeLength(GeometricQuantity): + "Representation of the maximum edge length of a facet." + __slots__ = () + def __init__(self, cell): + GeometricQuantity.__init__(self, cell) + + def shape(self): + return () + + def __str__(self): + return "maxfacetedgelength" + + def __repr__(self): + return "MaxFacetEdgeLength(%r)" % self._cell + + # TODO: If we include this here, we must define exactly what is meant by the mesh size, possibly adding multiple kinds of mesh sizes (hmin, hmax, havg, ?) #class MeshSize(GeometricQuantity): # __slots__ = () @@ -318,6 +352,8 @@ "_circumradius", "_cellsurfacearea", "_facetarea", + "_minfacetedgelength", + "_maxfacetedgelength", "_facetdiameter", # Cell local coordinates and mapping "_xi", @@ -365,6 +401,8 @@ self._circumradius = Circumradius(self) self._cellsurfacearea = CellSurfaceArea(self) self._facetarea = FacetArea(self) + self._minfacetedgelength = MinFacetEdgeLength(self) + self._maxfacetedgelength = MaxFacetEdgeLength(self) self._facetdiameter = FacetDiameter(self) #self._h = MeshSize(self) @@ -417,6 +455,16 @@ return self._facetdiameter @property + def min_facet_edge_length(self): + "UFL geometry value: The minimum edge length of a facet of the cell." + return self._minfacetedgelength + + @property + def max_facet_edge_length(self): + "UFL geometry value: The maximum edge length of a facet of the cell." + return self._maxfacetedgelength + + @property def facet_area(self): "UFL geometry value: The area of a facet of the cell." return self._facetarea diff -Nru ufl-1.2.0/ufl/mathfunctions.py ufl-1.3.0/ufl/mathfunctions.py --- ufl-1.2.0/ufl/mathfunctions.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/mathfunctions.py 2014-01-07 13:29:26.000000000 +0000 @@ -33,9 +33,6 @@ """ TODO: Include additional functions available in (need derivatives as well): -Trigonometric functions: -atan2 Compute arc tangent with two parameters (function) - Exponential and logarithmic functions: log10 Compute common logarithm (function) @@ -217,6 +214,50 @@ def __init__(self, argument): MathFunction.__init__(self, "atan", argument) +class Atan2(Operator): + __slots__ = ("_name", "_arg1", "_arg2", "_classname") + def __new__(cls, arg1, arg2): + if isinstance(arg1, (ScalarValue, Zero)) and isinstance(arg2, (ScalarValue, Zero)): + return FloatValue(math.atan2(float(arg1), float(arg2))) + return Operator.__new__(cls) + + def __init__(self, arg1, arg2): + Operator.__init__(self) + ufl_assert(is_true_ufl_scalar(arg1), "Expecting scalar argument 1.") + ufl_assert(is_true_ufl_scalar(arg2), "Expecting scalar argument 2.") + self._name = "atan_2" + self._arg1 = arg1 + self._arg2 = arg2 + + def operands(self): + return (self._arg1, self._arg2) + + def free_indices(self): + return () + + def index_dimensions(self): + return EmptyDict + + def shape(self): + return () + + def evaluate(self, x, mapping, component, index_values): + a = self._arg1.evaluate(x, mapping, component, index_values) + b = self._arg2.evaluate(x, mapping, component, index_values) + try: + res = math.atan2(a,b) + except ValueError: + warning('Value error in evaluation of function %s with arguments %s, %s.' % (self._name, a,b)) + raise + return res + + def __str__(self): + return "%s(%s,%s)" % (self._name, self._arg1, self._arg2) + + def __repr__(self): + return "%s(%s,%s)" % (self._name, self._arg1, self._arg2) + + def _find_erf(): import math if hasattr(math, 'erf'): diff -Nru ufl-1.2.0/ufl/operators.py ufl-1.3.0/ufl/operators.py --- ufl-1.2.0/ufl/operators.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/operators.py 2014-01-07 13:29:26.000000000 +0000 @@ -38,8 +38,9 @@ from ufl.conditional import EQ, NE, LE, GE, LT, GT, \ AndCondition, OrCondition, NotCondition, Conditional from ufl.mathfunctions import Sqrt, Exp, Ln, Erf,\ - Cos, Sin, Tan, Cosh, Sinh, Tanh, Acos, Asin, Atan,\ + Cos, Sin, Tan, Cosh, Sinh, Tanh, Acos, Asin, Atan, Atan2,\ BesselJ, BesselY, BesselI, BesselK +from ufl.restriction import CellAvg, FacetAvg from ufl.indexing import indices from ufl.indexed import Indexed from ufl.geometry import SpatialCoordinate @@ -399,6 +400,18 @@ v = as_ufl(v) return 0.5*(v('+') + v('-')) +def cell_avg(f): + "UFL operator: Take the average of v over a cell." + #ufl_assert((isinstance(f, Restricted) and isinstance(f.operands()[0], FormArgument)) or + # isinstance(f, FormArgument), "Can only take the cell average of a (optionally restricted) Coefficient or Argument.") + return CellAvg(f) + +def facet_avg(f): + "UFL operator: Take the average of v over a facet." + #ufl_assert((isinstance(f, Restricted) and isinstance(f.operands()[0], FormArgument)) or + # isinstance(f, FormArgument), "Can only take the cell average of a (optionally restricted) Coefficient or Argument.") + return FacetAvg(f) + #--- Other operators --- def variable(e): @@ -521,6 +534,15 @@ "UFL operator: Take the inverse tangent of f." return _mathfunction(f, Atan) +def atan_2(f1,f2): + "UFL operator: Take the inverse tangent of f." + f1 = as_ufl(f1) + f2 = as_ufl(f2) + r = Atan2(f1, f2) + if isinstance(r, (ScalarValue, Zero, int, float)): + return float(r) + return r + def erf(f): "UFL operator: Take the error function of f." return _mathfunction(f, Erf) diff -Nru ufl-1.2.0/ufl/precedence.py ufl-1.3.0/ufl/precedence.py --- ufl-1.2.0/ufl/precedence.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/precedence.py 2014-01-07 13:29:26.000000000 +0000 @@ -99,7 +99,7 @@ def assign_precedences(precedence_list): "Given a precedence list, assign ints to class._precedence." pm, missing = build_precedence_mapping(precedence_list) - for c, p in pm.iteritems(): + for c, p in sorted(pm.iteritems(), key=lambda x: x[0].__name__): c._precedence = p if missing: msg = "Missing precedence levels for classes:\n" +\ diff -Nru ufl-1.2.0/ufl/restriction.py ufl-1.3.0/ufl/restriction.py --- ufl-1.2.0/ufl/restriction.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/restriction.py 2014-01-07 13:29:26.000000000 +0000 @@ -23,12 +23,15 @@ from ufl.log import error from ufl.operatorbase import Operator from ufl.precedence import parstr +from ufl.common import EmptyDict #--- Restriction operators --- class Restricted(Operator): __slots__ = ("_f", "_side") + # TODO: Add __new__ operator here, e.g. restricted(literal) == literal + def __init__(self, f, side): Operator.__init__(self) self._f = f @@ -67,3 +70,69 @@ def __repr__(self): return "NegativeRestricted(%r)" % self._f + + +# TODO: Place in a better file? +class CellAvg(Operator): + __slots__ = ("_f",) + + # TODO: Add __new__ operator here, e.g. cell_avg(literal) == literal + + def __init__(self, f): + Operator.__init__(self) + self._f = f + + def shape(self): + return self._f.shape() + + def operands(self): + return (self._f,) + + def free_indices(self): + return () + + def index_dimensions(self): + return EmptyDict + + def evaluate(self, x, mapping, component, index_values): + "Performs an approximate symbolic evaluation, since we dont have a cell." + return self._f.evaluate(x, mapping, component, index_values) + + def __str__(self): + return "cell_avg(%s)" % (self._f,) + + def __repr__(self): + return "CellAvg(%r)" % self._f + + +# TODO: Place in a better file? +class FacetAvg(Operator): + __slots__ = ("_f",) + + # TODO: Add __new__ operator here, e.g. facet_avg(literal) == literal + + def __init__(self, f): + Operator.__init__(self) + self._f = f + + def shape(self): + return self._f.shape() + + def operands(self): + return (self._f,) + + def free_indices(self): + return () + + def index_dimensions(self): + return EmptyDict + + def evaluate(self, x, mapping, component, index_values): + "Performs an approximate symbolic evaluation, since we dont have a cell." + return self._f.evaluate(x, mapping, component, index_values) + + def __str__(self): + return "facet_avg(%s)" % (self._f,) + + def __repr__(self): + return "FacetAvg(%r)" % self._f diff -Nru ufl-1.2.0/ufl/tensors.py ufl-1.3.0/ufl/tensors.py --- ufl-1.2.0/ufl/tensors.py 2013-03-24 14:50:22.000000000 +0000 +++ ufl-1.3.0/ufl/tensors.py 2014-01-07 13:29:26.000000000 +0000 @@ -278,6 +278,10 @@ of recursively nested lists to build higher rank tensors. """ if indices is None: + # Allow as_tensor(as_tensor(A)) and as_vector(as_vector(v)) in user code + if isinstance(expressions, Expr): + return expressions + # Support numpy array, but avoid importing numpy if not needed if not isinstance(expressions, (list, tuple)): expressions = from_numpy_to_lists(expressions) @@ -311,28 +315,44 @@ def as_matrix(expressions, indices = None): "UFL operator: As as_tensor(), but limited to rank 2 tensors." if indices is None: + # Allow as_matrix(as_matrix(A)) in user code + if isinstance(expressions, Expr): + ufl_assert(expressions.rank() == 2, "Expecting rank 2 tensor.") + return expressions + # To avoid importing numpy unneeded, it's quite slow... if not isinstance(expressions, (list, tuple)): - try: - import numpy - if isinstance(expressions, numpy.ndarray): - expressions = numpy2nestedlists(expressions) - except: - pass + expressions = from_numpy_to_lists(expressions) + + # Check for expected list structure ufl_assert(isinstance(expressions, (list, tuple)), "Expecting nested list or tuple of Exprs.") ufl_assert(isinstance(expressions[0], (list, tuple)), "Expecting nested list or tuple of Exprs.") - return as_tensor(expressions) + else: + ufl_assert(len(indices) == 2, "Expecting exactly two indices.") - ufl_assert(len(indices) == 2, "Expecting exactly two indices.") return as_tensor(expressions, indices) def as_vector(expressions, index = None): "UFL operator: As as_tensor(), but limited to rank 1 tensors." - if index is not None: - ufl_assert(isinstance(index, Index), "Expecting Index object.") + if index is None: + # Allow as_vector(as_vector(v)) in user code + if isinstance(expressions, Expr): + ufl_assert(expressions.rank() == 1, "Expecting rank 1 tensor.") + return expressions + + # To avoid importing numpy unneeded, it's quite slow... + if not isinstance(expressions, (list, tuple)): + expressions = from_numpy_to_lists(expressions) + + # Check for expected list structure + ufl_assert(isinstance(expressions, (list, tuple)), + "Expecting nested list or tuple of Exprs.") + else: + ufl_assert(isinstance(index, Index), "Expecting a single Index object.") index = (index,) + return as_tensor(expressions, index) def as_scalar(expression):