Mathics Latest
Mathics Latest
2. Language Tutorial 8
2. Arithmetic Functions 45
3. Assignments 52
5. Binary Data 84
6. Code Compilation 88
7. Colors 90
2
20. Functional Composition and Operator Forms 223
3
50. Tensors 563
Index 784
Colophon 796
4
Part I.
Manual
5
1. Introduction
Mathics3—to be pronounced like “Mathematics” without the “emat”—is a general-purpose computer
algebra system (CAS). It is meant to be a free, open-source alternative to Mathematica®. It is free both as
in “free beer” and as in “freedom”. Mathics can be run Mathics3 locally, and to facilitate installation of
the vast amount of software need to run this, there is a docker image available on dockerhub.
The programming language of Mathics3 is meant to resemble the Wolfram Language as much as possible.
However, Mathics3 is in no way affiliated or supported by Wolfram. Mathics3 will probably never have
the power to compete with Mathematica® in industrial applications; it is an alternative though. It also
invites community development at all levels.
See the installation instructions for the most recent instructions for installing from PyPI, or the source.
For implementation details see https://mathics-development-guide.readthedocs.io/en/latest/.
Contents
History
The first alpha versions of Mathics3 were done in 2011 by Jan Pöschko. He worked on it for a couple of
years to about the v0.5 release in 2012. By then, it had 386 built-in symbols. Currently there are over a
1,000 and even more when Mathics3 modules are included.
After that, Angus Griffith took over primary leadership and rewrote the parser to pretty much the stage
it is in now. He and later Ben Jones worked on it from 2013 to about 2017 to the v1.0 release. Towards
the end of this period, Bernhard Liebl worked on this, mostly focused on graphics.
A docker image of the v.9 release can be found on dockerhub.
Around 2017, the project was largely abandoned in its largely Python 2.7 state, with support for Python
3.2-3.5 via six.
Subsequently, around mid 2020, it was picked up by the current developers. A list of authors and
contributors can be found in the AUTHORS.txt file.
6
• a Mathics3 module for Graphs (via NetworkX),
• a Mathics3 module for NLP (via nltk, spacy, and others)
• a A docker container which bundles all of the above
What is missing?
There are lots of ways in which Mathics3 could still be improved. FUTURE.rst has the current roadmap.
While we always could use help, such as in Python programming, improving Documentation. But there
are other ways to help. For example:
• Ensure this document is complete and accurate. We could use help to ensure all of the Builtin
functions described properly and fully, and that they have link to corresponding Wiki, Sympy,
WMA and/or mpath links. Make sure the builtin summaries and examples clear and useful.
• We could use help in LaTeX styling, and going over this document to remove overful boxes and
things of that nature. We could also use help and our use of Asymptote. The are some graphics
primitives such as for polyhedra that haven’t been implemented. Similar graphics options are
sometimes missing in Asymptote that we have available in other graphics backends.
• add another graphics backend: it could be a javascript library like jsfiddle
• Consider donating via Github Sponsors or some other mechanism.
7
2. Language Tutorial
The following sections are introductions to the basic principles of the language of Mathics3. A few
examples and functions are presented. Only their most common usages are listed; for a full description
of a Symbols possible arguments, options, etc., see its entry in the Reference of Built-in Symbols.
However if you google for “Mathematica Tutorials” you will find easily dozens of other tutorials which
are applicable. Be warned though that Mathics3 does not yet offer the full range and features and
capabilities of Mathematica®.
Contents
3D Graphics
Three-dimensional graphics are created using the function Graphics3D and a list of 3D primitives. The
following primitives are supported so far:
8
>> Graphics3D[Polygon[{{0,0,0}, {0,1,1}, {1,0,0}}]]
Basic calculations
Mathics3 can be used to calculate basic stuff:
>> 1 + 2
3
To submit a command to Mathics3, press Shift+Return in the Web interface or Return in the console
interface. The result will be printed in a new line below your query.
Mathics3 understands all basic arithmetic operators and applies the usual operator precedence. Use
parentheses when needed:
9
>> 1 - 2 * (3 + 5)/ 4
−3
The multiplication can be omitted:
>> 1 - 2 (3 + 5)/ 4
−3
>> 2 4
8
Powers can be entered using ^:
>> 3 ^ 4
81
Integer divisions yield rational numbers:
>> 6 / 4
3
2
To convert the result to a floating point number, apply the function N:
>> N[6 / 4]
1.5
As you can see, functions are applied using square braces [ and ], in contrast to the common notation
of ( and ). At first hand, this might seem strange, but this distinction between function application and
precedence change is necessary to allow some general syntax structures, as you will see later.
Mathics3 provides many common mathematical functions and constants, e.g.:
>> Log[E]
1
>> Sin[Pi]
0
>> Cos[0.5]
0.877583
When entering floating point numbers in your query, Mathics3 will perform a numerical evaluation and
present a numerical result, pretty much like if you had applied N.
Of course, Mathics3 has complex numbers:
>> Sqrt[-4]
2I
>> I ^ 2
−1
>> (3 + 2 I)^ 4
− 119 + 120I
>> (3 + 2 I)^ (2.5 - I)
43.663 + 8.28556I
>> Tan[I + 0.5]
0.195577 + 0.842966I
Abs calculates absolute values:
>> Abs[-3]
3
10
>> Abs[3 + 4 I]
5
Mathics3 can operate with pretty huge numbers:
>> 100!
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286
(! denotes the factorial function.) The precision of numerical evaluation can be set:
>> N[Pi, 30]
3.14159265358979323846264338328
Division by zero is forbidden:
>> 1 / 0
Infinite expression 1 / 0 encountered.
ComplexInfinity
11
>> !False
True
>> 3 < 4 && 6 > 5
True
&& has higher precedence than ||, i.e. it binds stronger:
>> True && True || False && False
True
>> True && (True || False)&& False
False
Formatting Output
The way results are formatted for output in Mathics3 is rather sophisticated, as compatibility to the way
Mathematica® does things is one of the design goals. It can be summed up in the following procedure:
1. The result of the query is calculated.
2. The result is stored in Out (which % is a shortcut for).
3. Any Format rules for the desired output form are applied to the result. In the console version of
Mathics3, the result is formatted as OutputForm; MathMLForm for the StandardForm is used in the
interactive Web version; and TeXForm for the StandardForm is used to generate the LATEX version
of this documentation.
4. MakeBoxes is applied to the formatted result, again given either OutputForm, MathMLForm, or
TeXForm depending on the execution context of Mathics3. This yields a new expression consisting
of “box constructs”.
5. The boxes are turned into an ordinary string and displayed in the console, sent to the browser, or
written to the documentation LATEX file.
As a consequence, there are various ways to implement your own formatting strategy for custom ob-
jects.
You can specify how a symbol shall be formatted by assigning values to Format:
>> Format[x] = "y";
>> x
y
>> x // TeXForm
\text{z}
Special formats might not be very relevant for individual symbols, but rather for custom functions
(objects):
>> Format[r[args___]] = "<an r object>";
>> r[1, 2, 3]
<an r object>
12
Infix[expr, op]
formats the arguments of expr with infix operator op.
Prefix[expr, op]
formats the argument of expr with prefix operator op.
Postfix[expr, op]
formats the argument of expr with postfix operator op.
StringForm[form, arg1, arg2, ...]
formats arguments using a format string.
>> r[1, 2, 3]
1∼2∼3
>> StringForm["‘1‘ and ‘2‘", n, m]
n and m
There are several methods to display expressions in 2-D:
Row[{...}]
displays expressions in a row.
Grid[{{...}}]
displays a matrix in two-dimensional form.
Subscript[expr, i1, i2, ...]
displays expr with subscript indices i1, i2, ...
Superscript[expr, exp]
displays expr with superscript (exponent) exp.
If you want even more low-level control over expression display, override MakeBoxes:
>> MakeBoxes[b, StandardForm] = "c";
>> b
c
This will even apply to TeXForm, because TeXForm implies StandardForm:
>> b // TeXForm
c
Except some other form is applied first:
>> b // OutputForm // TeXForm
b
MakeBoxes for another form:
>> MakeBoxes[b, TeXForm] = "d";
>> b // TeXForm
d
13
You can cause a much bigger mess by overriding MakeBoxes than by sticking to Format, e.g. generate
invalid XML:
>> MakeBoxes[c, MathMLForm] = "<not closed";
>> c // MathMLForm
<not closed
However, this will not affect formatting of expressions involving c:
>> c + 1 // MathMLForm
<math display="block"><mrow><mn>1</mn>
<mo>+</mo> <mi>c</mi></mrow></math>
That’s because MathMLForm will, when not overridden for a special case, call StandardForm first. Format
will produce escaped output:
>> Format[d, MathMLForm] = "<not closed";
>> d // MathMLForm
<math display="block"><mtext><not closed</mtext></math>
>> d + 1 // MathMLForm
<math display="block"><mrow><mn>1</mn> <mo>+</mo>
<mtext><not closed</mtext></mrow></math>
For instance, you can override MakeBoxes to format lists in a different way:
>> MakeBoxes[{items___}, StandardForm] := RowBox[{"[", Sequence @@
Riffle[MakeBoxes /@ {items}, " "], "]"}]
>> {1, 2, 3}
[123]
>> Clear[MakeBoxes]
By the way, MakeBoxes is the only built-in symbol that is not protected by default:
>> Attributes[MakeBoxes]
{HoldAllComplete}
>> squared[1, 2]
=
The desired effect can be achieved in the following way:
>> MakeBoxes[squared[args___], StandardForm] := SuperscriptBox[RowBox[{
MakeBoxes[squared], "[", RowBox[Riffle[MakeBoxes[#]& /@ {args},
","]], "]"}], 2]
>> squared[1, 2]
squared [1, 2]2
14
You can view the box structure of a formatted expression using ToBoxes:
>> ToBoxes[m + n]
[ ]
RowBox {m, +, n}
The list elements in this RowBox are strings, though string delimiters are not shown in the default output
form:
>> InputForm[%]
[ ]
RowBox {“m”, “+”, “n”}
This tells Mathics3 to replace every occurrence of f with one (arbitrary) parameter x with x ^ 2.
>> f[3]
9
>> f[a]
a2
The definition of f does not specify anything for two parameters, so any such call will stay unevaluated:
>> f[1, 2]
f [1, 2]
In fact, functions in Mathics3 are just one aspect of patterns: f[x_] is a pattern that matches expressions
like f[3] and f[a]. The following patterns are available:
_ or Blank[]
matches one expression.
Pattern[x, p]
matches the pattern p and stores the value in x.
x_ or Pattern[x, Blank[]]
matches one expression and stores it in x.
__ or BlankSequence[]
matches a sequence of one or more expressions.
___ or BlankNullSequence[]
matches a sequence of zero or more expressions.
_h or Blank[h]
matches one expression with head h.
x_h or Pattern[x, Blank[h]]
matches one expression with head h and stores it in x.
p | q or Alternatives[p, q]
matches either pattern p or q.
p ? t or PatternTest[p, t]
matches p if the test t[p] yields True.
p /; c or Condition[p, c]
matches p if condition c holds.
Verbatim[p]
matches an expression that equals p, without regarding patterns inside p.
15
>> g[s___] := Plus[s] ^ 2
>> g[1, 2, 3]
36
MatchQ[e, p] tests whether e matches p:
>> MatchQ[a + b, x_ + y_]
True
>> MatchQ[6, _Integer]
True
ReplaceAll (/.) replaces all occurrences of a pattern in an expression using a Rule given by ->:
>> {2, "a", 3, 2.5, "b", c} /. x_Integer -> x ^ 2
{4, a, 9, 2.5, b, c}
ReplaceRepeated (//.) applies a set of rules repeatedly, until the expression doesn’t change anymore:
>> {2, "a", 3, 2.5, "b", c} //. {x_Integer -> x ^ 2.0, y_String -> 10}
{4., 100., 9., 2.5, 100., c}
There is a “delayed” version of Rule which can be specified by :> (similar to the relation of := to =):
>> a :> 1 + 2
a:>1 + 2
>> a -> 1 + 2
a− > 3
This is useful when the right side of a rule should not be evaluated immediately (before matching):
>> {1, 2} /. x_Integer -> N[x]
{1, 2}
Here, N is applied to x before the actual matching, simply yielding x. With a delayed rule this can be
avoided:
>> {1, 2} /. x_Integer :> N[x]
{1., 2.}
ReplaceAll and ReplaceRepeated take the first possible match. However ReplaceList returns a list of
all possible matches. This can be used to get all subsequences of a list, for instance:
>> ReplaceList[{a, b, c}, {___, x__, ___} -> {x}]
{{ a} , { a, b} , { a, b, c} , {b} , {b, c} , {c}}
In addition to defining functions as rules for certain patterns, there are pure functions that can be defined
using the & postfix operator, where everything before it is treated as the function body and # can be used
as argument placeholder:
>> h = # ^ 2 &;
16
>> h[3]
9
Multiple arguments can simply be indexed:
>> sum = #1 + #2 &;
>> sum[4, 6]
10
It is also possible to name arguments using Function:
>> prod = Function[{x, y}, x * y];
>> prod[4, 6]
24
Pure functions are very handy when functions are used only locally, e.g., when combined with operators
like Map:
>> # ^ 2 & /@ Range[5]
{1, 4, 9, 16, 25}
Functions can be applied using prefix or postfix notation, in addition to using []:
>> h @ 3
9
>> 3 // h
9
Circle[{x, y}, r]
draws a circle.
Disk[{x, y}, r]
draws a filled disk.
Rectangle[{x1, y1}, {x2, y2}]
draws a filled rectangle.
Polygon[{{x1, y1}, {x2, y2}, ...}]
draws a filled polygon.
Line[{{x1, y1}, {x2, y2}, ...}]
draws a line.
Text[text, {x, y}]
draws text in a graphics.
17
>> Graphics[{Circle[{0, 0}, 1]}]
>> Graphics[{Line[{{0, 0}, {0, 1}, {1, 1}, {1, -1}}], Rectangle[{0, 0},
{-1, -1}]}]
Colors can be added in the list of graphics primitives to change the drawing color. The following ways
to specify colors are supported:
RGBColor[r, g, b]
specifies a color using red, green, and blue.
CMYKColor[c, m, y, k]
specifies a color using cyan, magenta, yellow, and black.
All
Hue[h, s, b]
specifies a color using hue, saturation, and brightness.
GrayLevel[l]
specifies a color using a gray level.
components range from 0 to 1. Each color function can be supplied with an additional argument spec-
ifying the desired opacity (“alpha”) of the color. There are many predefined colors, such as Black,
White, Red, Green, Blue, etc.
18
>> Graphics[{Red, Disk[]}]
Table of hues:
>> Graphics[Table[{Hue[h, s], Disk[{12h, 8s}]}, {h, 0, 1, 1/6}, {s, 0,
1, 1/4}]]
19
>> Graphics[{Lighter[Red], Disk[]}]
0.5
1 2 3 4 5 6
−0.5
−1.0
0.5
−0.5
20
>> DensityPlot[x ^ 2 + 1 / y, {x, -1, 1}, {y, 1, 4}]
One problem with DensityPlot is that it’s still very slow, basically due to function evaluation being
pretty slow in general—and DensityPlot has to evaluate a lot of functions.
Three-dimensional plots are supported as well:
>> Plot3D[Exp[x] Cos[y], {x, -2, 1}, {y, -Pi, 2 Pi}]
21
Precision and Accuracy
Mathics3 handles relative and absolute uncertanties in numerical quantities. The precision or relative
accuracy, is set by adding a RawBackquote character (‘) and the number of digits of precision in the
mantissa. For example:
>> 3.1416‘3
3.14
Above, two decimal places are shown in output after the decimal point, but three places of precision
are stored.
The relative uncertainty of 3.1416‘3 is 10∧ -3. It is numerically equivalent, in three places after the
decimal point, to 3.1413‘4:
>> 3.1416‘3 == 3.1413‘4
True
We can get the precision of the number by using the Mathics3 Built-in function Precision of section 4:
>> Precision[3.1413‘4]
4.
While 3.1419 not the closest approximation to Pi in 4 digits after the decimal point (or with precision 4),
for 3 digits of precision it is:
>> Pi == 3.141987654321‘3
True
<url>The absolute accuracy of a number, is set by adding a two RawBackquotes ‘‘ and the number
digits.
For example:
>> 13.1416‘‘4
13.142
is a number having a absolute uncertainty of 10∧ -4. This number is numerically equivalent to 13.1413‘‘4:
>> 13.1416‘‘4 == 13.1413‘‘4
True
The absolute accuracy for the value 0 is a fixed-precision Real number:
>> 0‘‘4
0.0000
See also Accuracy and precision.
22
If[cond, pos, neg]
returns pos if cond evaluates to True, and neg if it evaluates to False.
Which[cond1, expr1, cond2, expr2, ...]
yields expr1 if cond1 evaluates to True, expr2 if cond2 evaluates to True, etc.
Do[expr, {i, max}]
evaluates expr max times, substituting i in expr with values from 1 to max.
For[start, test, incr, body]
evaluates start, and then iteratively body and incr as long as test evaluates to True.
While[test, body]
evaluates body as long as test evaluates to True.
Nest[f , expr, n]
returns an expression with f applied n times to expr.
NestWhile[f , expr, test]
applies a function f repeatedly on an expression expr, until applying test on the result no
longer yields True.
FixedPoint[f , expr]
starting with expr, repeatedly applies f until the result no longer changes.
Inside For, While, and Do loops, Break[] exits the loop and Continue[] continues to the next iteration.
>> For[i = 1, i <= 5, i++, If[i == 4, Break[]]; Print[i]]
1
2
3
Scoping
By default, all symbols are “global” in Mathics3, i.e. they can be read and written in any part of your pro-
gram. However, sometimes “local” variables are needed in order not to disturb the global namespace.
Mathics3 provides two ways to support this:
• lexicalscoping by Module, and
• dynamicscoping by Block.
Module[{vars}, expr]
localizes variables by giving them a temporary name of the form name$number, where num-
ber is the current value of $ModuleNumber. Each time a module is evaluated, $ModuleNumber
is incremented.
Block[{vars}, expr]
temporarily stores the definitions of certain variables, evaluates expr with reset values and
restores the original definitions afterwards.
Both scoping constructs shield inner variables from affecting outer ones:
>> t = 3;
23
>> Module[{t}, t = 2]
2
>> Block[{t}, t = 2]
2
>> t
3
Module creates new variables:
>> y = x ^ 3;
It is common to use scoping constructs for function definitions with local variables:
>> fac[n_] := Module[{k, p}, p = 1; For[k = 1, k <= n, ++k, p *= k]; p]
>> fac[10]
3628800
>> 10!
3628800
Strings
Strings can be entered with " as delimiters:
>> "Hello world!"
Hello world!
As you can see, quotation marks are not printed in the output by default. This can be changed by using
InputForm:
>> InputForm["Hello world!"]
“Hello world!”
24
Strings can be joined using <>:
>> "Hello" <> " " <> "world!"
Hello world!
Numbers cannot be joined to strings:
>> "Debian" <> 6
String expected.
Debian<>6
They have to be converted to strings using ToString first:
>> "Debian" <> ToString[6]
Debian6
>> b
4
Such a dependency can be achieved by using “delayed assignment” with the := operator (which does
not return anything, as the right side is not even evaluated):
25
>> b := a ^ 2
>> b
9
>> a = 5;
>> b
25
>> Apply[Plus, a * b * c]
a+b+c
Apply can be written using the operator @@:
>> Times @@ {1, 2, 3, 4}
24
26
(This exchanges the head List of {1, 2, 3, 4} with Times, and then the expression Times[1, 2, 3,
4] is evaluated, yielding 24.) Apply can also be applied on a certain level of an expression:
>> Apply[f, {{1, 2}, {3, 4}}, {1}]
{ f [1, 2] , f [3, 4]}
The atoms of Mathics3 are numbers, symbols, and strings. AtomQ tests whether an expression is an atom:
>> AtomQ[5]
True
>> AtomQ[a + b]
False
The full form of rational and complex numbers looks like they were compound expressions:
>> FullForm[3 / 5]
Rational [3, 5]
>> FullForm[3 + 4 I]
Complex [3, 4]
However, they are still atoms, thus unaffected by applying functions, for instance:
>> f @@ Complex[3, 4]
3 + 4I
Nevertheless, every atom has a head:
>> Head /@ {1, 1/2, 2.0, I, "a string", x}
{Integer, Rational, Real, Complex, String, Symbol}
The operator === tests whether two expressions are the same on a structural level:
>> 3 === 3
True
>> 3 == 3.0
True
But:
>> 3 === 3.0
False
because 3 (an Integer) and 3.0 (a Real) are structurally different.
27
>> mylist = {a, b, c, d}
{ a, b, c, d}
>> Array[f, 4]
{ f [1] , f [2] , f [3] , f [4]}
>> ConstantArray[x, 4]
{ x, x, x, x }
>> MatrixForm[mymatrix]
1 2
3 4
5 6
>> Take[mylist, 3]
{ a, b, c}
28
>> Take[mylist, -2]
{c, d}
>> Drop[mylist, 2]
{c, d}
>> First[mymatrix]
{1, 2}
>> Last[mylist]
d
>> Most[mylist]
{ a, b, c}
>> Rest[mylist]
{b, c, d}
>> a
1
>> b
2
Operations like addition and multiplication, “thread” over lists; lists are combined element-wise:
>> {1, 2, 3} + {4, 5, 6}
{5, 7, 9}
29
3. Further Tutorial Examples
Contents
Curve sketching
Let’s sketch the function
>> f[x_] := 4 x / (x ^ 2 + 3 x + 5)
To get the extreme values of f, compute the zeroes of the first derivatives:
>> extremes = Solve[f’[x] == 0, x]
{{ √ } { √ }}
x− > − 5 , x− > 5
Thus, there is a local maximum at x = Sqrt[5] and a local minimum at x = -Sqrt[5]. Compute the
inflection points numerically, chopping imaginary parts close to 0:
>> inflections = Solve[f’’[x] == 0, x] // N // Chop
{{ x − > − 1.0852} , { x − > − 3.21463} , { x − > 4.29983}}
Being different from 0, all three points are actual inflection points. f is not defined where its denomina-
tor is 0:
>> Solve[Denominator[f[x]] == 0, x]
{{ } { }}
3 I√ 3 I√
x− > − − 11 , x − > − + 11
2 2 2 2
These are non-real numbers, consequently f is defined on all real numbers. The behaviour of f at the
boundaries of its definition:
>> Limit[f[x], x -> Infinity]
0
30
>> Limit[f[x], x -> -Infinity]
0
Finally, let’s plot f:
>> Plot[f[x], {x, -8, 6}]
0.5
−8 −6 −4 −2 2 4 6
−0.5
−1.0
−1.5
−2.0
−2.5
Dice
Let’s play with dice in this example. A Dice object shall represent the outcome of a series of rolling a
dice with six faces, e.g.:
>> Dice[1, 6, 4, 4]
Dice [1, 6, 4, 4]
Like in most games, the ordering of the individual throws does not matter. We can express this by
making Dice Orderless:
>> SetAttributes[Dice, Orderless]
>> Dice[1, 6, 4, 4]
Dice [1, 4, 4, 6]
A dice object shall be displayed as a rectangle with the given number of points in it, positioned like on
a traditional dice:
>> Format[Dice[n_Integer?(1 <= # <= 6 &)]] := Block[{p = 0.2, r = 0.05},
Graphics[{EdgeForm[Black], White, Rectangle[], Black, EdgeForm[], If
[OddQ[n], Disk[{0.5, 0.5}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk
[{p, p}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{1 - p, 1 - p}, r
]], If[MemberQ[{4, 5, 6}, n], Disk[{p, 1 - p}, r]], If[MemberQ[{4, 5,
6}, n], Disk[{1 - p, p}, r]], If[n === 6, {Disk[{p, 0.5}, r], Disk
[{1 - p, 0.5}, r]}]}, ImageSize -> Tiny]]
>> Dice[1]
31
>> Dice[]
>> Dice[1, 6, 4, 4]
Note that Mathics3 will automatically sort the given format rules according to their “generality”, so the
rule for the empty dice does not get overridden by the rule for a series of dice. We can still see the
original form by using InputForm:
>> Dice[1, 6, 4, 4] // InputForm
Dice [1, 4, 4, 6]
The ^:= (UpSetDelayed) tells Mathics3 to associate this rule with Dice instead of Plus. Plus is protected—
we would have to unprotect it first:
>> Dice[a___] + Dice[b___] := Dice[Sequence @@ {a, b}]
Tag Plus in Dice[a___] + Dice[b___] is Protected.
$Failed
Let’s write a function that returns the sum of the rolled dice:
>> DiceSum[Dice[d___]] := Plus @@ {d}
32
It is not very sophisticated from a mathematical point of view, but it’s beautiful.
Linear algebra
Let’s consider the matrix
>> A = {{1, 1, 0}, {1, 0, 1}, {0, 1, 1}};
>> MatrixForm[A]
1 1 0
1 0 1
0 1 1
>> Eigenvectors[A]
{{1, 1, 1} , {1, −2, 1} , {−1, 0, 1}}
>> % == DiagonalMatrix[Eigenvalues[A]]
True
We can solve linear systems:
>> LinearSolve[A, {1, 2, 3}]
{0, 1, 2}
>> A . %
{1, 2, 3}
>> MatrixRank[B]
2
>> s = LinearSolve[B, {1, 2, 3}]
{ }
1 2
− , ,0
3 3
33
>> NullSpace[B]
{{1, −2, 1}}
34
4. Django-based Web Interface
In the future, we plan on providing an interface to Jupyter as a separate package.
However currently as part Mathics3, we distribute a browser-based interface using long-term-release
(LTS) Django 4.
Since a Jupyter-based interface seems preferable to the home-grown interface described here, it is doubt-
ful whether there will be future improvements to the this interface.
When you enter Mathics in the top after the Mathics logo and the word “Mathics” you’ll see a menubar.
It looks like this:
These save and load worksheets, share sessions, run a gallery of examples, go to the GitHub organiza-
tion page, and provide information about the particular Mathics3 installation.
These are explained in the sections below.
Contents
Gallery Examples
We have a number of examples showing off briefly some of the capabilities of the system. These are run
when you hit hit the button that looks like this:
It is also shown in the pop-up text that appears when Mathics3 is first run.
Keyboard Commands
There are some keyboard commands you can use in the Django-based Web interface of Mathics3.
35
Shift+Return
This evaluates the current cell (the most important one, for sure). On the right-hand side you
may also see an "=" button which can be clicked to do the same thing.
Ctrl+D
This moves the cursor over to the documentation pane on the right-hand side. From here
you can perform a search for a pre-defined Mathics3 function, or symbol. Clicking on the "?"
symbol on the right-hand side does the same thing.
Ctrl+C
This moves the cursor back to document code pane area where you type Mathics3 expressions
Ctrl+S
Save worksheet
Ctrl+O
Open worksheet
Right Click on MathML output
Opens MathJax Menu
Of special note is the last item on the list: right-click to open the MathJax menu. Under “Math Set-
ting”/“Zoom Trigger”, if the zoom trigger is set to a value other then “No Zoom”, then when that
trigger is applied on MathML formatted output, the MathML formula pop up a window for the for-
mula. The window can show the formula larger. Also, this is a way to see output that is too large to fit
on the display since the window allows for scrolling.
Keyboard commands behavior depends the browser used, the operating system, desktop settings, and
customization. We hook into the desktop “Open the current document” and “Save the current docu-
ment” functions that many desktops provide. For example see: Finding keyboard shortcuts
Often, these shortcut keyboard command are only recognized when a text field has focus; otherwise,the
browser might do some browser-specific actions, like setting a bookmark etc.
For example, assuming you have a Mathics3 server running at port 8000 on localhost, and you enter
the URL http://localhost:8000/#cXVlcmllcz14, you should see a single line of input containing x
entered.
Of course, what the value of this is when evaluated depends on whether x has been previously defined.
36
Saving, Loading, and Deleting Worksheets
<subsection title=“Saving Worksheets”>
Worksheets exist in the browser window only and are not stored on the server, by default. To save all
your queries and results, use the Save button which is the middle graphic of the menu bar. It looks like
this:
Depending on browser, desktop, and OS-settings, the "Ctrl+S" key combination may do the same thing.
<subsection title=“Loading and Deleting Worksheets”>
Saved worksheets can be loaded or deleted using the FileOpen button which is the left-most button in
the menu bar. It looks like this:
Depending on browser, desktop, and OS-settings, the "Ctrl+O" key combination may do the same thing.
A pop-up menu should appear with the list of saved worksheets with an option to either load or delete
the worksheet.
Saving Worksheets
<subsection title=“Saving Worksheets”>
Worksheets exist in the browser window only and are not stored on the server, by default. To save all
your queries and results, use the Save button which is the middle graphic of the menu bar. It looks like
this:
Depending on browser, desktop, and OS-settings, the "Ctrl+S" key combination may do the same thing.
<subsection title=“Loading and Deleting Worksheets”>
Saved worksheets can be loaded or deleted using the FileOpen button which is the left-most button in
the menu bar. It looks like this:
Depending on browser, desktop, and OS-settings, the "Ctrl+O" key combination may do the same thing.
A pop-up menu should appear with the list of saved worksheets with an option to either load or delete
the worksheet.
Depending on browser, desktop, and OS-settings, the "Ctrl+S" key combination may do the same thing.
<subsection title=“Loading and Deleting Worksheets”>
Saved worksheets can be loaded or deleted using the FileOpen button which is the left-most button in
the menu bar. It looks like this:
37
Depending on browser, desktop, and OS-settings, the "Ctrl+O" key combination may do the same thing.
A pop-up menu should appear with the list of saved worksheets with an option to either load or delete
the worksheet.
URIs
For the most part, the application is a single-page application. Assuming your are running locally or on
a host called localhost using the default port, 8000, here are some URLs and what they do:
http://localhost:8000
The single-page application; the main page.
http://localhost:8000/about
A page giving:
• the software versions of this package and version information of important software this
uses.
http://localhost:8000/doc
An on-line formatted version of the documentation, which include this text. You can see this
as a right side frame of the main page, when clicking "?" on the right-hand upper corner.
38
Part II.
39
1. Applying Functions to Lists
Many computations can be conveniently specified in terms of applying functions in parallel to many
elements in a list.
Many mathematical functions are automatically taken to be “listable”, so that they are always applied
to every element in a list.
Contents
MapAt . . . . . . . . . 42 Scan . . . . . . . . . . 43
Apply (@@) . . . . . . . 41
MapIndexed . . . . . . 43 Thread . . . . . . . . . 44
List . . . . . . . . . . . 41
MapThread . . . . . . 43
Map (/@) . . . . . . . . 41
Apply (@@)
Apply[f , expr]
f @@ expr
replaces the head of expr with f.
Apply[f , expr, levelspec]
applies f on the parts specified by levelspec.
>> f @@ {1, 2, 3}
f [1, 2, 3]
Apply on level 1:
>> Apply[f, {a + b, g[c, d, e * f], 3}, {1}]
{ [ ] }
f [a, b] , f c, d, e f , 3
40
>> Apply[List, a + b * c ^ e * f[g], {0, Infinity}]
{ a, {b, { g} , {c, e}}}
List
WMA link
Map (/@)
>> f /@ {1, 2, 3}
{ f [1] , f [2] , f [3]}
Include heads:
>> Map[f, a + b + c, Heads->True]
[ ]
f [Plus] f [a] , f [b] , f [c]
41
MapAt
MapAt[f , expr, n]
applies f to the element at position n in expr. If n is negative, the position is counted from the
end.
MapAt[f, expr, {i, j ...}]
applies f to the part of expr at position {i, j, ...}.
MapAt[f ,pos]
represents an operator form of MapAt that can be applied to an expression.
MapIndexed
MapIndexed[f , expr]
applies f to each part on the first level of expr, including the part positions in the call to f.
MapIndexed[f , expr, levelspec]
applies f to each level specified by levelspec of expr.
42
>> MapIndexed[f, a + b + c * d, {0, 1}]
[ [ ] [ ] [ ] ]
f f a, {1} + f b, {2} + f cd, {3} , {}
Get the positions of atoms in an expression (convert operations to List first to disable Listable func-
tions):
>> expr = a + b * f[g] * c ^ e;
The positions are given in the same format as used by Extract. Thus, mapping Extract on the indices
given by MapIndexed re-constructs the original expression:
>> MapIndexed[Extract[expr, #2] &, listified, {-1}, Heads -> True]
[ ]
a + b f g ce
MapThread
>> MapThread[f, {{{a, b}, {c, d}}, {{e, f}, {g, h}}}, 2]
{{ [ ]} { [ ] }}
f [a, e] , f b, f , f c, g , f [d, h]
Scan
Scan[f , expr]
applies f to each element of expr and returns Null.
’Scan[f, expr, levelspec]
applies f to each level specified by levelspec of expr.
43
Thread
Thread[f [args]]
threads f over any lists that appear in args.
Thread[f [args], h]
threads over any parts with head h.
44
2. Arithmetic Functions
Arithmetic Functions are functions that work on individual numbers, lists, and arrays: in either sym-
bolic or algebraic forms.
Contents
Basic Arithmetic
Basic Arithmetic
The functions here are the basic arithmetic operations that you might find on a calculator.
CubeRoot
Cube root (WMA)
CubeRoot[n]
finds the real-valued cube root of the given n.
>> CubeRoot[16]
1
22 3
Divide (/)
Division (WMA link)
Divide[a, b]
a / b
represents the division of a by b.
>> 30 / 5
6
>> 1 / 8
>> Pi / 4
π
4
Use N or a decimal point to force numeric evaluation:
45
>> Pi / 4.0
0.785398
>> 1 / 8
>> N[%]
0.125
Nested divisions:
>> a / b / c
a
bc
>> a / (b / c)
ac
b
>> a / b / (c / (d / e))
ad
bce
>> a / (b ^ 2 * c ^ 3 / e)
ae
b2 c3
Minus (-)
Additive inverse (WMA)
Minus[expr]
is the negation of expr.
>> -a //FullForm
Times [ − 1, a]
Plus (+)
Addition (SymPy, WMA)
Plus[a, b, ...]
a + b + ...
represents the sum of the terms a, b, ...
>> 1 + 2
3
46
Plus performs basic simplification of terms:
>> a + b + a
2a + b
>> a + a + 3 * a
5a
>> a + b + 4.5 + a + b + a + 2 + 1.5 b
6.5 + 3a + 3.5b
Apply Plus on a list to sum up its elements:
>> Plus @@ {2, 4, 6}
12
The sum of the first 1000 integers:
>> Plus @@ Range[1000]
500500
Plus has default value 0:
>> DefaultValues[Plus]
{HoldPattern [Default [Plus]] :>0}
Power (^)
Exponentiation (SymPy, WMA)
Power[a, b]
a ^ b
represents a raised to the power of b.
>> 4 ^ (1/2)
2
47
>> 4 ^ (1/3)
2
23
>> 3^123
48519278097689642681155855396759336072749841943521979872827
>> (y ^ 2) ^ (1/2)
√
y2
>> (y ^ 2) ^ 3
y6
−1
−2
−3
Sqrt
Square root (SymPy, WMA)
Sqrt[expr]
returns the square root of expr.
48
>> Sqrt[4]
2
>> Sqrt[5]
√
5
>> Sqrt[5] // N
2.23607
>> Sqrt[a]^2
a
Complex numbers:
>> Sqrt[-4]
2I
>> I == Sqrt[-1]
True
>> Plot[Sqrt[a^2], {a, -2, 2}]
2.0
1.5
1.0
0.5
−2 −1 1 2
Subtract (-)
Subtraction, (WMA)
Subtract[a, b]
a-b
represents the subtraction of b from a.
>> 5 - 3
2
>> a - b // FullForm
Plus [a, Times [ − 1, b]]
>> a - b - c
a−b−c
>> a - (b - c)
a−b+c
Times (*)
Multiplication (SymPy, WMA)
49
Times[a, b, ...]
a * b * ...
a b ...
represents the product of the terms a, b, ...
>> 10 * 2
20
>> 10 2
20
>> a * a
a2
>> x ^ 10 * x ^ -2
x8
>> {1, 2, 3} * 4
{4, 8, 12}
Accumulate
WMA link
Accumulate[list]
accumulates the values of list, returning a new list.
Total
WMA link
50
Total[list]
adds all values in list.
Total[list, n]
adds all values up to level n.
Total[list, {n}]
totals only the values at level {n}.
Total[list, {n_1, n_2}]
totals at levels {n_1, n_2}.
51
3. Assignments
Assignments allow you to set or clear variables, indexed variables, structure elements, functions, and
general transformations.
You can also get assignment and documentation information about symbols.
Contents
Clearing Assignments
Clearing Assignment
Clear
WMA link
>> x = 2;
>> Clear[x]
>> x
>> x = 2;
>> y = 3;
>> Clear["Global‘*"]
>> x
52
>> y
y
The values and rules associated with built-in symbols will not get lost when applying Clear (after
unprotecting them):
>> Unprotect[Sin]
>> Clear[Sin]
>> Sin[Pi]
0
Clear does not remove attributes, messages, options, and default values associated with the symbols.
Use ClearAll to do so.
>> Attributes[r] = {Flat, Orderless};
>> Clear["r"]
>> Attributes[r]
{Flat, Orderless}
ClearAll
WMA link
>> x = 2;
>> ClearAll[x]
>> x
x
>> Attributes[r] = {Flat, Orderless};
>> ClearAll[r]
>> Attributes[r]
{}
>> ClearAll[lock]
Symbol lock is locked.
53
Remove
WMA link
Remove[x]
removes the definition associated to x.
>> a := 2
>> Names["Global‘a"]
>> Remove[a]
>> Names["Global‘a"]
Unset (=.)
WMA link
Unset[x]
x=.
removes any value belonging to x.
>> a = 2
2
>> a =.
>> a
a
Unsetting an already unset or never defined variable will not change anything:
>> a =.
>> b =.
Unset can unset particular function values. It will print a message if no corresponding rule is found.
>> f[x_] =.
>> f[x_] := x ^ 2
>> f[3]
>> f[x_] =.
>> f[3]
You can also unset OwnValues, DownValues, SubValues, and UpValues directly. This is equivalent to
setting them to {}.
>> f[x_] = x; f[0] = 1;
>> DownValues[f] =.
>> f[2]
f [2]
54
Unset threads over lists:
>> a = b = 3;
Forms of Assignment
Forms of Assignment
LoadModule
LoadModule[module]
’Load Mathics definitions from the python module module
>> LoadModule["nomodule"]
Python import errors with: No module named ’nomodule’.
$Failed
>> LoadModule["sys"]
Python module "sys" is not a Mathics3 module.
$Failed
Set (=)
WMA link
Set[expr, value]
expr = value
evaluates value and assigns it to expr.
{s1, s2, s3} = {v1, v2, v3}
sets multiple symbols (s1, s2, ...) to the corresponding values (v1, v2, ...).
55
Set evaluates its right-hand side immediately and assigns it to the left-hand side:
>> a
>> x = a
1
>> a = 2
2
>> x
1
Set always returns the right-hand side, which you can again use in an assignment:
>> a = b = c = 2;
>> a == b == c == 2
True
Set supports assignments to parts:
>> A = {{1, 2}, {3, 4}};
Set a submatrix:
>> B = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
>> B
{{1, t, u} , {4, y, z} , {7, 8, 9}}
SetDelayed (:=)
WMA link
SetDelayed[expr, value]
expr := value
assigns value to expr, without evaluating value.
SetDelayed is like Set, except it has attribute HoldAll, thus it does not evaluate the right-hand side
immediately, but evaluates it when needed.
>> Attributes[SetDelayed]
{HoldAll, Protected, SequenceHold}
>> a = 1
1
>> x := a
56
>> x
Condition (/;) can be used with SetDelayed to make an assignment that only holds if a condition is
satisfied:
>> f[x_] := p[x] /; x>0
>> f[3]
p [3]
>> f[-3]
f [ − 3]
>> F[2, 3]
2
3
>> F[3, 2]
2
3
>> F[-3, 2]
2
−
3
We can use conditional delayed assignments to define symbols with values conditioned to the context.
For example,
>> ClearAll[a,b]; a/; b>0:= 3
Set a to have a value of 3 if certain variable b is positive. So, if this variable is not set, a stays unevaluated:
>> a
a
If now we assign a positive value to b, then a is evaluated:
>> b=2; a
3
TagSet
WMA link
57
Create an upvalue without using UpSet:
>> x /: f[x] = 2
2
>> f[x]
2
>> DownValues[f]
{}
>> UpValues[x]
{ [ ] }
HoldPattern f [x] :>2
The symbol f must appear as the ultimate head of lhs or as the head of an element in lhs:
>> x /: f[g[x]] = 3;
Tag x not found or too deep for an assigned rule.
>> g /: f[g[x]] = 3;
>> f[g[x]]
3
TagSetDelayed
WMA link
UpSet (^=)
WMA link
f [x] ∧ = expression
evaluates expression and assigns it to the value of f [x], associating the value with x.
>> DownValues[a]
{}
>> UpValues[b]
{HoldPattern [a [b]] :>3}
>> a ^= 3
Nonatomic expression expected.
3
You can use UpSet to specify special values like format values. However, these values will not be saved
in UpValues:
>> Format[r] ^= "custom";
58
>> r
custom
>> UpValues[r]
{}
UpSetDelayed (^:=)
WMA link
UpSetDelayed[expression, value]
expression ^:= value
assigns expression to the value of f [x] (without evaluating expression), associating the value
with x.
>> x = 2;
>> a[b]
2
>> UpValues[b]
{HoldPattern [a [b]] :>x }
AddTo (+=)
WMA link
AddTo[x, dx]
x += dx
is equivalent to x = x + dx.
>> a = 10;
>> a += 2
12
>> a
12
59
Decrement (--)
WMA link
Decrement[x]
x--
decrements x by 1, returning the original value of x.
>> a = 5;
>> a--
5
>> a
4
DivideBy (/=)
WMA link
DivideBy[x, dx]
x /= dx
is equivalent to x = x / dx.
>> a = 10;
>> a /= 2
5
>> a
5
Increment (++)
WMA link
Increment[x]
x++
increments x by 1, returning the original value of x.
>> a = 2;
>> a++
2
>> a
3
Grouping of Increment, PreIncrement and Plus:
>> ++++a+++++2//Hold//FullForm
Hold [Plus [PreIncrement [PreIncrement [Increment [Increment [a]]]] , 2]]
PreDecrement (--)
WMA link
60
PreDecrement[x]
--x
decrements x by 1, returning the new value of x.
--a is equivalent to a = a - 1:
>> a = 2;
>> --a
1
>> a
1
PreIncrement (++)
WMA link
PreIncrement[x]
++x
increments x by 1, returning the new value of x.
++a is equivalent to a = a + 1:
>> a = 2;
>> ++a
3
>> a
3
SubtractFrom (-=)
WMA link
SubtractFrom[x, dx]
x -= dx
is equivalent to x = x - dx.
>> a = 10;
>> a -= 2
8
>> a
8
TimesBy (*=)
WMA link
TimesBy[x, dx]
x *= dx
is equivalent to x = x * dx.
61
>> a = 10;
>> a *= 2
20
>> a
20
Types of Values
Types of Value
DefaultValues
WMA link
DefaultValues[symbol]
gives the list of default values associated with symbol.
Note: this function is in Mathematica 5 but has been removed from current Mathematica.
>> Default[f, 1] = 4
4
>> DefaultValues[f]
{ [ [ ]] }
HoldPattern Default f , 1 :>4
>> Default[g, 1]
3
>> g[x_.] := {x}
>> g[a]
{ a}
>> g[]
{3}
Messages
WMA link
Messages[symbol]
gives the list of messages associated with symbol.
62
>> Messages[a] = {a::c :> "bar"};
NValues
NValues[symbol]
gives the list of numerical values associated with symbol.
Note: this function is in Mathematica 5 but has been removed from current Mathematica.
>> NValues[a]
>> N[a] = 3;
>> NValues[a]
>> N[b]
2.
Be sure to use SetDelayed, otherwise the left-hand side of the transformation rule will be evaluated
immediately, causing the head of N to get lost. Furthermore, you have to include the precision in the
rules; MachinePrecision will not be inserted automatically:
>> NValues[c] := {N[c] :> 3}
>> N[c]
c
Mathics will assign any list of rules to NValues; however, inappropriate rules will never be used:
>> NValues[d] = {foo -> bar};
>> NValues[d]
{HoldPattern [foo] :>bar}
>> N[d]
d
SubValues
WMA link
SubValues[symbol]
gives the list of subvalues associated with symbol.
Note: this function is not in current Mathematica.
>> f[1][x_] := x
>> f[2][x_] := x ^ 2
63
>> SubValues[f]
{ [ ] [ ] }
HoldPattern f [2] [x_] :>x2 , HoldPattern f [1] [x_] :>x
>> Definition[f]
f [2] [x_] = x2
f [1] [x_] = x
UpValue-related assignments
UpValue-related assignments
An <i>UpValue<i> is a definition associated with a symbols that does not appear directly its head.
See Associating Definitions with Different Symbols.
UpValues
WMA
UpValues[symbol]
gives the list of transformation rules corresponding to upvalues define with symbol.
>> a + b ^= 2
2
>> UpValues[a]
{HoldPattern [a + b] :>2}
>> UpValues[b]
{HoldPattern [a + b] :>2}
>> Sin[pi]
0
64
4. Atomic Elements of Expressions
Expressions are ultimately built from a small number of distinct types of atomic elements.
Contents
Atomic Primitives
Atomic Primitive
AtomQ
WMA link
AtomQ[expr]
returns True if expr is an expression which cannot be divided into subexpressions, or False
otherwise.
An expression that cannot be divided into subparts is called called an “atom”.
65
>> Map[AtomQ, {Pi, E, I, Degree}]
{True, True, True, True}
Note that evaluation or the binding of “x” to an expression is taken into account:
>> x = 2 + Pi; AtomQ[x]
False
Again, note that the expression evaluation to a number occurs before AtomQ evaluated:
>> AtomQ[2 + 3.1415]
True
Head
WMA link
Head[expr]
returns the head of the expression or atom expr.
>> Head[a * b]
Times
>> Head[6]
Integer
>> Head[x]
Symbol
Representation of Numbers
Representation of Numbers
Integers and Real numbers with any number of digits, automatically tagging numerical precision when
appropriate.
Precision is not “guarded” through the evaluation process. Only integer precision is supported.
However, things like N[Pi, 100] should work as expected.
Accuracy
Accuracy (WMA Accuracy)
66
Accuracy[x]
No-
examines the number of significant digits of expr after the decimal point in the number x.
tice that the result could be slightly different than the obtained in WMA, due to differencs in the internal repre-
sentation of the real numbers.
Accuracy of a real number is estimated from its value and its precision:
>> Accuracy[3.1416‘2]
1.50298
Notice that the value is not exactly equal to the obtained in WMA: This is due to the different way in
which Precision is handled in SymPy.
Accuracy for exact atoms is Infinity:
>> Accuracy[1]
∞
>> Accuracy[A]
∞
For Complex numbers, the accuracy is estimated as (minus) the base-10 log of the square root of the
squares of the errors on the real and complex parts:
>> z=Complex[3.00‘‘2, 4..00‘‘2];
ExactNumberQ
WMA link
67
ExactNumberQ[expr]
returns True if expr is an exact number, and False otherwise.
>> ExactNumberQ[10]
True
>> ExactNumberQ[4.0]
False
>> ExactNumberQ[n]
False
ExactNumberQ can be applied to complex numbers:
>> ExactNumberQ[1 + I]
True
>> ExactNumberQ[1 + 1. I]
False
InexactNumberQ
WMA link
InexactNumberQ[expr]
returns True if expr is not an exact number, and False otherwise.
>> InexactNumberQ[a]
False
>> InexactNumberQ[3.0]
True
>> InexactNumberQ[2/3]
False
InexactNumberQ can be applied to complex numbers:
>> InexactNumberQ[4.0+I]
True
IntegerExponent
WMA link
IntegerExponent[n, b]
gives the highest exponent of b that divides n.
>> IntegerExponent[16, 2]
4
>> IntegerExponent[-510000]
4
>> IntegerExponent[10, b]
IntegerExponent [10, b]
68
IntegerLength
WMA link
IntegerLength[x]
gives the number of digits in the base-10 representation of x.
IntegerLength[x, b]
gives the number of base-b digits in x.
>> IntegerLength[123456]
6
>> IntegerLength[10^10000]
10001
>> IntegerLength[-10^1000]
1001
IntegerLength with base 2:
>> IntegerLength[8, 2]
4
Check that IntegerLength is correct for the first 100 powers of 10:
>> IntegerLength /@ (10 ^ Range[100])== Range[2, 101]
True
The base must be greater than 1:
>> IntegerLength[3, -2]
Base -2 is not an integer greater than 1.
IntegerLength [3, −2]
0 is a special case:
>> IntegerLength[0]
0
$MachineEpsilon
WMA link
$MachineEpsilon
is the distance between 1.0 and the next nearest representable machine-precision number.
>> $MachineEpsilon
2.22045*∧ − 16
>> x = 1.0 + {0.4, 0.5, 0.6} $MachineEpsilon;
>> x - 1
{ }
0., 0., 2.22045*∧ − 16
MachinePrecision
WMA link
69
MachinePrecision
represents the precision of machine precision numbers.
>> N[MachinePrecision]
15.9546
>> N[MachinePrecision, 30]
15.9545897701910033463281614204
$MachinePrecision
WMA link
$MachinePrecision
is the number of decimal digits of precision for machine-precision numbers.
>> $MachinePrecision
15.9546
$MaxPrecision
WMA link
$MaxPrecision
represents the maximum number of digits of precision permitted in abitrary-precision num-
bers.
>> $MaxPrecision
∞
>> $MaxPrecision = 10;
$MinPrecision
WMA link
$MinPrecision
represents the minimum number of digits of precision permitted in abitrary-precision num-
bers.
>> $MinPrecision
0
>> $MinPrecision = 10;
70
>> N[Pi, 9]
Requested precision 9 is smaller than $MinPrecision. Using current
$MinPrecision of 10. instead.
3.141592654
Precision
Precision (WMA)
Precision[expr]
Note
examines the number of significant digits of expr.
that the result could be slightly different than the obtained in WMA, due to differencs in the internal representa-
tion of the real numbers.
The precision of an exact number, e.g. an Integer, is Infinity:
>> Precision[1]
∞
A fraction is an exact number too, so its Precision is Infinity:
>> Precision[1/2]
∞
Numbers entered in the form digits‘p are taken to have precision p:
>> Precision[1.23‘10]
10.
Precision of a machineprecision number is MachinePrecision:
>> Precision[0.5]
MachinePrecision
In compound expressions, the Precision is fixed by the number with the lowest Precision:
>> Precision[{{1, 1.‘},{1.‘5, 1.‘10}}]
5.
For non-zero Real values, it holds in general:
Accuracy[z] == Precision[z] + Log[z]
>> (Accuracy[z] == Precision[z] + Log[z])/.z-> 37.‘
True
The case of ‘0.‘ values is special. Following WMA, in a Machine Real representation, the precision is set
to MachinePrecision:
>> Precision[0.]
MachinePrecision
On the other hand, for a Precision Real with fixed accuracy, the precision is evaluated to 0.:
>> Precision[0.‘‘3]
0.
See also Accuracy of section 4.
RealDigits
WMA link
71
RealDigits[n]
returns the decimal representation of the real number n as list of digits, together with the
number of digits that are to the left of the decimal point.
RealDigits[n, b]
returns a list of base_b representation of the real number n.
RealDigits[n, b, len]
returns a list of len digits.
RealDigits[n, b, len, p]
return len digits starting with the coefficient of b∧ p
RealDigits gives Indeterminate if more digits than the precision are requested:
>> RealDigits[123.45, 10, 18]
{{1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Indeterminate, Indeterminate} , 3}
String Manipulation
String Manipulation
Alphabet
WMA link
Alphabet[]
gives the list of lowercase letters a-z in the English alphabet .
Alphabet[type]
gives the alphabet for the language or class type.
>> Alphabet[]
{a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z}
72
>> Alphabet["German"]
{a, ä, b, c, d, e, f, g, h, i, j, k, l, m, n, o, ö, p, q, r, s, SS, t, u, ü, v, w, x, y, z}
Some languages are aliases. “Russian” is the same letter set as “Cyrillic”
>> Alphabet["Russian"] == Alphabet["Cyrillic"]
True
$CharacterEncoding
WMA link
$CharacterEncoding
specifies the default raw character encoding to use for input and output when no encoding is
explicitly specified. Initially this is set to $SystemCharacterEncoding.
See the character encoding current is in effect and used in input and output functions functions like
OpenRead[]:
>> $CharacterEncoding
ASCII
See also $SystemCharacterEncoding of section 4.
$CharacterEncodings
WMA link
$CharacterEncodings
stores the list of available character encodings.
>> $CharacterEncodings
{ASCII, CP949, CP950, EUC-JP, IBM- 850, ISOLatin1, ISOLatin2, ISOLatin3, ISOLatin4, ISOLatinCyrillic, ISO8859-1,
HexadecimalCharacter
WMA link
HexadecimalCharacter
represents the characters 0-9, a-f and A-F.
InterpretedBox (\!)
WMA link
InterpretedBox[box]
is the ad hoc fullform for
! box. just for internal use...
73
>> \! \(2+2\)
4
LetterNumber
WMA link
LetterNumber[c]
returns the position of the character c in the English alphabet.
LetterNumber[‘‘string’]’
returns a list of the positions of characters in string.
LetterNumber[‘‘string’,’ alpha]
returns a list of the positions of characters in string, regarding the alphabet alpha.
>> LetterNumber["b"]
2
LetterNumber also works with uppercase characters
>> LetterNumber["B"]
2
>> LetterNumber["ss2!"]
{19, 19, 0, 0}
NumberString
WMA link
NumberString
represents the characters in a number.
RemoveDiacritics
WMA link
74
RemoveDiacritics[s]
returns a version of s with all diacritics removed.
>> RemoveDiacritics["piñata"]
pinata
StringContainsQ
WMA link
StringContainsQ["string", patt]
returns True if any part of string matches patt, and returns False otherwise.
StringContainsQ[{‘‘s1’, “s2”, ...}, patt]’
returns the list of results for each element of string list.
StringContainsQ[patt]
represents an operator form of StringContainsQ that can be applied to an expression.
StringQ
WMA link
StringQ[expr]
returns True if expr is a String, or False otherwise.
>> StringQ["abc"]
True
>> StringQ[1.5]
False
>> Select[{"12", 1, 3, 5, "yz", x, y}, StringQ]
{12, yz}
75
StringRepeat
WMA link
StringRepeat["string", n]
gives string repeated n times.
StringRepeat["string", n, max]
gives string repeated n times, but not more than max characters.
>> StringRepeat["abc", 3]
abcabcabc
>> StringRepeat["abc", 10, 7]
abcabca
String
WMA link
String
is the head of strings.
>> Head["abc"]
String
>> "abc"
abc
Use InputForm to display quotes around strings:
>> InputForm["abc"]
“abc”
FullForm also displays quotes:
>> FullForm["abc" + 2]
Plus [2, “abc”]
$SystemCharacterEncoding
WMA link
$SystemCharacterEncoding
gives the default character encoding of the system.
On startup, the value of environment variable MATHICS_CHARACTER_ENCODING sets this value.
However if that environment variable is not set, set the value is set in Python using
sys.getdefaultencoding().
>> $SystemCharacterEncoding
ASCII
ToExpression
WMA link
76
ToExpression[input]
interprets a given string as Mathics input.
ToExpression[input, form]
reads the given input in the specified form.
ToExpression[input, form, h]
applies the head h to the expression before evaluating it.
ToString
WMA link
ToString[expr]
returns a string representation of expr.
ToString[expr, form]
returns a string representation of expr in the form form.
>> ToString[2]
2
>> ToString[2] // InputForm
“2”
>> ToString[a+b]
a+b
>> "U" <> 2
String expected.
U<>2
>> "U" <> ToString[2]
U2
>> ToString[Integrate[f[x],x], TeXForm]
\int f\left[x\right] \, dx
Transliterate
WMA link
77
Transliterate[s]
transliterates a text in some script into an ASCII string.
Whitespace
WMA link
Whitespace
represents a sequence of whitespace characters.
Symbol Handling
Symbol Handling
Symbolic data. Every symbol has a unique name, exists in a certain context or namespace, and can have
a variety of type of values and attributes.
Context
WMA
Context[symbol]
yields the name of the context where symbol is defined in.
Context[]
returns the value of $Context.
>> Context[a]
Global‘
>> Context[b‘c]
b‘
>> InputForm[Context[]]
“Global‘”
Definition
WMA
78
Definition[symbol]
prints as the definitions given for symbol. This is in a form that can e stored in a package.
Definition does not print information for ReadProtected symbols. Definition uses InputForm to
format values.
>> a = 2;
>> Definition[a]
a=2
>> f[x_] := x ^ 2
>> Definition[f]
f [x_] = x2
[ ]
g f ∧ =2
>> Default[r, 1] := 2
Some usage:
>> r[z, x, y]
x∼y∼z
>> N[r]
3.5
>> r[]
{2, 3}
Its definition:
>> Definition[r]
For ReadProtected symbols, Definition just prints attributes, default values and options:
>> SetAttributes[r, ReadProtected]
>> Definition[r]
79
>> Definition[Plus]
Attributes [Plus]
= {Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected}
Default [Plus] = 0
>> Definition[Level]
Attributes [Level] = {Protected}
Options [Level] = {Heads− > False}
>> Definition[r]
>> Definition[r]
DownValues
WMA
DownValues[symbol]
gives the list of downvalues associated with symbol.
DownValues uses HoldPattern and RuleDelayed to protect the downvalues from being evaluated. More-
over, it has attribute HoldAll to get the specified symbol instead of its value.
>> f[x_] := x ^ 2
>> DownValues[f]
Mathics will sort the rules you assign to a symbol according to their specificity. If it cannot decide which
rule is more special, the newer one will get higher precedence.
>> f[x_Integer] := 2
>> f[x_Real] := 3
>> DownValues[f]
>> f[3]
2
>> f[3.]
3
>> f[a]
a2
80
The default order of patterns can be computed using Sort with PatternsOrderedQ:
>> Sort[{x_, x_Integer}, PatternsOrderedQ]
{x_Integer, x_}
>> g[2]
4
Fibonacci numbers:
>> DownValues[fib] := {fib[0] -> 0, fib[1] -> 1, fib[n_] :> fib[n - 1] +
fib[n - 2]}
>> fib[5]
5
Information (??)
WMA
Information[symbol]
Information
Prints information about a symbol
Names
WMA
Names["pattern"]
returns the list of names matching pattern.
>> Names["List"]
{List}
>> Names["Global‘*"]
{x}
81
OwnValues
WMA
OwnValues[symbol]
gives the list of ownvalue associated with symbol.
>> x = 3;
>> x = 2;
>> OwnValues[x]
>> x := y
>> OwnValues[x]
>> y = 5;
>> OwnValues[x]
SymbolName
WMA
SymbolName[s]
returns the name of the symbol s (without any leading context name).
SymbolQ
WMA
SymbolQ[x]
is True if x is a symbol, or False otherwise.
>> SymbolQ[a]
True
>> SymbolQ[1]
False
>> SymbolQ[a + b]
False
82
Symbol
WMA
Symbol
is the head of symbols.
>> Head[x]
Symbol
ValueQ
WMA
ValueQ[expr]
returns True if and only if expr is defined.
>> ValueQ[x]
>> x = 1;
>> ValueQ[x]
83
5. Binary Data
Binary data is a type of data that is represented in the binary, sequences of zeros or ones. Computer-
generated information often comes in this form.
Contents
BinaryRead
WMA link
BinaryRead[stream]
reads one byte from the stream as an integer from 0 to 255.
BinaryRead[stream, type]
reads one object of specified type from the stream.
BinaryRead[stream, {type1, type2, ...}]
reads a sequence of objects of specified types.
>> Close[strm];
>> DeleteFile[Close[strm]];
84
BinaryWrite
WMA link
BinaryWrite[channel, b]
writes a single byte given as an integer from 0 to 255.
BinaryWrite[channel, {b1, b2, ...}]
writes a sequence of byte.
BinaryWrite[channel, ‘‘string’]’
writes the raw characters in a string.
BinaryWrite[channel, x, type]
writes x as the specified type.
BinaryWrite[channel, {x1, x2, ...}, type]
writes a sequence of objects as the specified type.
BinaryWrite[channel, {x1, x2, ...}, {type1, type2, ...}]
writes a sequence of objects using a sequence of specified types.
>> Close[strm];
>> BinaryRead[strm]
39
>> BinaryRead[strm, "Byte"]
4
>> BinaryRead[strm, "Character8"]
z
>> DeleteFile[Close[strm]];
Write a String
>> strm = OpenWrite[BinaryFormat -> True]
Read as Bytes
>> strm = OpenRead[%, BinaryFormat -> True]
85
Read as Characters
>> strm = OpenRead[%, BinaryFormat -> True]
>> DeleteFile[Close[strm]];
Write Type
>> strm = OpenWrite[BinaryFormat -> True]
>> DeleteFile[Close[%]];
Binary Types
Binary Type
Byte
WMA link
Byte
is a data type for Read.
Byte Arrays
Byte Array
ByteArray
WMA link
>> A[[2]]
25
86
>> Normal[A]
{1, 25, 3}
>> ToString[A]
ByteArray[<3>]
>> ByteArray["ARkD"]
ByteArray [<3>]
>> B=ByteArray["asy"]
The first argument in Bytearray[asy] should be a B64 encoded string
or a vector of integers.
$Failed
ByteOrdering
WMA link
ByteOrdering
is an option for BinaryRead, BinaryWrite, and related functions that specifies what ordering
of bytes should be assumed for your computer system..
>> ByteOrdering
−1
$ByteOrdering
WMA link
$ByteOrdering
returns the native ordering of bytes in binary data on your computer system.
>> $ByteOrdering
−1
87
6. Code Compilation
Code compilation allows Mathics functions to be run faster.
When LLVM and Python libraries are available, compilation produces LLVM code.
Contents
CompiledFunction . . 89
Compile . . . . . . . . 88
Compile
WMA link
Compile[{x1, x2, ...}, expr]
Compiles expr assuming each xi is a Real number.
Compile[{{x1, t1} {x2, t1} ...}, expr]
Compiles assuming each xi matches type ti.
>> cf[1.4]
0.98545
Compile supports basic flow control:
>> cf = Compile[{{x, _Real}, {y, _Integer}}, If[x == 0.0 && y <= 0, 0.0,
Sin[x ^ y] + 1 / Min[x, 0.5]] + 0.5]
>> cf[3.5, 2]
2.18888
Loops and variable assignments are supported usinv Python builtin “compile” function:
>> Compile[{{a, _Integer}, {b, _Integer}}, While[b != 0, {a, b} = {b,
Mod[a, b]}]; a] (* GCD of a, b *)
CompiledFunction
WMA link
CompiledFunction[args...]
represents compiled code for evaluating a compiled function.
88
>> sqr = Compile[{x}, x x]
>> Head[sqr]
CompiledFunction
>> sqr[2]
4.
89
7. Colors
Programmatic support for symbolic colors.
Contents
Color Directives
Color Directives
There are many different way to specify color, and we support many of these.
We can convert between the different color formats.
CMYKColor
WMA link
CMYKColor[c, m, y, k]
represents a color with the specified cyan, magenta, yellow and black components.
ColorDistance
WMA link
90
ColorDistance[c1, c2]
returns a measure of color distance between the colors c1 and c2.
ColorDistance[list, c2]
returns a list of color distances between the colors in list and c2.
The option DistanceFunction specifies the method used to measure the color distance. Available options
are:
• CIE76: Euclidean distance in the LABColor space
• CIE94: Euclidean distance in the LCHColor space
• CIE2000 or CIEDE2000: CIE94 distance with corrections
• CMC: Color Measurement Committee metric (1984)
• DeltaL: difference in the L component of LCHColor
• DeltaC: difference in the C component of LCHColor
• DeltaH: difference in the H component of LCHColor
It is also possible to specify a custom distance.
>> ColorDistance[Magenta, Green]
2.2507
>> ColorDistance[{Red, Blue}, {Green, Yellow}, DistanceFunction -> {"CMC
", "Perceptibility"}]
{1.0495, 1.27455}
GrayLevel
WMA link
GrayLevel[g]
represents a shade of gray specified by g, ranging from 0 (black) to 1 (white).
GrayLevel[g, a]
represents a shade of gray specified by g with opacity a.
Hue
WMA link
Hue[h, s, l, a]
represents the color with hue h, saturation s, lightness l and opacity a.
Hue[h, s, l]
is equivalent to Hue[h, s, l, 1].
Hue[h, s]
is equivalent to Hue[h, s, 1, 1].
Hue[h]
is equivalent to Hue[h, 1, 1, 1].
91
>> Graphics[Table[{EdgeForm[Gray], Hue[h, s], Disk[{12h, 8s}]}, {h, 0,
1, 1/6}, {s, 0, 1, 1/4}]]
LABColor
WMA link
LABColor[l, a, b]
represents a color with the specified lightness, red/green and yellow/blue components in the
CIE 1976 L*a*b* (CIELAB) color space.
LCHColor
WMA link
LCHColor[l, c, h]
represents a color with the specified lightness, chroma and hue components in the CIELCh
CIELab cube color space.
LUVColor
WMA link
92
LCHColor[l, u, v]
represents a color with the specified components in the CIE 1976 L*u*v* (CIELUV) color space.
Opacity
WMA link
Opacity[level]
is a graphics directive that sets the opacity to level.
Notice that Opacity does not overwrite the value of the alpha channel if it is set in a color directive:
93
>> Graphics[{Blue, Disk[], RGBColor[1,0,0,1],Opacity[.2], Rectangle
[{0,0},{1,1}]}]
RGBColor
WMA link
RGBColor[r, g, b]
represents a color with the specified red, green and blue components.
>> RGBColor[0, 1, 0]
XYZColor
WMA link
XYZColor[x, y, z]
represents a color with the specified components in the CIE 1931 XYZ color space.
94
Color Operations
Color Operations
Functions for manipulating colors and color images.
Blend
WMA link
Blend[{c1, c2}]
represents the color between c1 and c2.
Blend[{c1, c2}, x]
represents the color formed by blending c1 and c2 with factors 1 - x and x respectively.
Blend[{c1, c2, ..., cn}, x]
blends between the colors c1 to cn according to the factor x.
ColorConvert
WMA link
ColorConvert[c, colspace]
returns the representation of c in the color space colspace. c may be a color or an image.
ColorNegate
Color Inversion (WMA)
95
ColorNegate[color]
returns the negative of a color, that is, the RGB color subtracted from white.
ColorNegate[image]
returns an image where each pixel has its color negated.
Yellow is RGBColor[1.0, 1.0, 0.0] So when inverted or subtracted from White, we get blue:
>> ColorNegate[Yellow] == Blue
True
>> ColorNegate[Import["ExampleData/sunflowers.jpg"]]
Darker
WMA link
Darker[c, f ]
is equivalent to Blend[{c, Black}, f ].
Darker[c]
is equivalent to Darker[c, 1/3].
96
>> Graphics3D[{Darker[Green], Sphere[]}]
DominantColors
WMA link
DominantColors[image]
gives a list of colors which are dominant in the given image.
DominantColors[image, n]
returns at most n colors.
DominantColors[image, n, prop]
returns the given property prop, which may be:
• “Color”: return RGB colors,
• “CoverageImage”: return a black and white image indicating with white the parts that are
covered by a dominant color.
The option “ColorCoverage” specifies the minimum amount of coverage needed to include a dominant
color in the result.
The option “MinColorDistance” specifies the distance (in LAB color space) up to which colors are
merged and thus regarded as belonging to the same dominant color.
97
>> img = Import["ExampleData/hedy.tif"]
>> DominantColors[img]
{ , , }
>> DominantColors[img, 3]
{ , , }
Lighter
WMA link
98
Lighter[c, f ]
is equivalent to Blend[{c, White}, f ].
Lighter[c]
is equivalent to Lighter[c, 1/3].
RGBColor
WMA link
RGBColor[r, g, b]
represents a color with the specified red, green and blue components.
>> RGBColor[0, 1, 0]
99
>> RGBColor[0, 1, 0] // ToBoxes
[ [{
StyleBox GraphicsBox EdgeForm [RGBColor [0, 0, 0]] , RGBColor [
[ ]}
0, 1, 0] , RectangleBox {0, 0} , AspectRatio− > Automatic, Axes
− > False, AxesStyle− > {} , Background− > Automatic, ImageSize
− > 16, LabelStyle− > {} , PlotRange− > Automatic, PlotRangePadding
]
− > Automatic, TicksStyle− > {} , ImageSizeMultipliers
]
− > {1, 1} , ShowStringCharacters− > True
Named Colors
Named Colors
Mathics has definitions for the most common color names which can be used in a graphics or style
specification.
Black
WMA link
Black
represents the color black in graphics.
WMA link
>> Black
Blue
WMA link
Blue
represents the color blue in graphics.
100
>> Graphics[{EdgeForm[Black], Blue, Disk[]}, ImageSize->Small]
WMA link
>> Blue
Brown
WMA link
Brown
represents the color brown in graphics.
WMA link
>> Brown
101
Cyan
WMA link
Cyan
represents the color cyan in graphics.
WMA link
>> Cyan
Gray
WMA link
Gray
represents the color gray in graphics.
102
>> Gray // ToBoxes
[ [{
StyleBox GraphicsBox EdgeForm [RGBColor [0, 0, 0]] , GrayLevel [
[ ]}
0.5] , RectangleBox {0, 0} , AspectRatio− > Automatic, Axes
− > False, AxesStyle− > {} , Background− > Automatic, ImageSize
− > 16, LabelStyle− > {} , PlotRange− > Automatic, PlotRangePadding
]
− > Automatic, TicksStyle− > {} , ImageSizeMultipliers
]
− > {1, 1} , ShowStringCharacters− > True
WMA link
>> Gray
Green
WMA link
Green
represents the color green in graphics.
WMA link
103
>> Green
LightBlue
WMA link
LightBlue
represents the color light blue in graphics.
1.0
0.5
1 2 3 4 5 6
−0.5
−1.0
WMA link
>> Graphics[{LightBlue, EdgeForm[Black], Disk[]}]
104
>> Plot[Sin[x], {x, 0, 2 Pi}, Background -> LightBlue]
LightBrown
WMA link
LightBrown
represents the color light brown in graphics.
LightCyan
WMA link
LightCyan
represents the color light cyan in graphics.
105
>> LightCyan // ToBoxes
[ [{
StyleBox GraphicsBox EdgeForm [RGBColor [0, 0, 0]] , RGBColor [
[ ]}
0.9, 1., 1.] , RectangleBox {0, 0} , AspectRatio− > Automatic, Axes
− > False, AxesStyle− > {} , Background− > Automatic, ImageSize
− > 16, LabelStyle− > {} , PlotRange− > Automatic, PlotRangePadding
]
− > Automatic, TicksStyle− > {} , ImageSizeMultipliers
]
− > {1, 1} , ShowStringCharacters− > True
LightGray
WMA link
LightGray
represents the color light gray in graphics.
LightGreen
WMA link
LightGreen
represents the color light green in graphics.
106
>> LightGreen // ToBoxes
[ [{
StyleBox GraphicsBox EdgeForm [RGBColor [0, 0, 0]] , RGBColor [
[ ]}
0.88, 1., 0.88] , RectangleBox {0, 0} , AspectRatio− > Automatic, Axes
− > False, AxesStyle− > {} , Background− > Automatic, ImageSize
− > 16, LabelStyle− > {} , PlotRange− > Automatic, PlotRangePadding
]
− > Automatic, TicksStyle− > {} , ImageSizeMultipliers
]
− > {1, 1} , ShowStringCharacters− > True
LightMagenta
WMA link
LightMagenta
represents the color light magenta in graphics.
LightOrange
WMA link
LightOrange
represents the color light orange in graphics.
107
>> LightOrange // ToBoxes
[ [{
StyleBox GraphicsBox EdgeForm [RGBColor [0, 0, 0]] , RGBColor [
[ ]}
1, 0.9, 0.8] , RectangleBox {0, 0} , AspectRatio− > Automatic, Axes
− > False, AxesStyle− > {} , Background− > Automatic, ImageSize
− > 16, LabelStyle− > {} , PlotRange− > Automatic, PlotRangePadding
]
− > Automatic, TicksStyle− > {} , ImageSizeMultipliers
]
− > {1, 1} , ShowStringCharacters− > True
LightPink
WMA link
LightPink
represents the color light pink in graphics.
LightPurple
WMA link
LightPurple
represents the color light purple in graphics.
108
>> LightPurple // ToBoxes
[ [{
StyleBox GraphicsBox EdgeForm [RGBColor [0, 0, 0]] , RGBColor [
[ ]}
0.94, 0.88, 0.94] , RectangleBox {0, 0} , AspectRatio− > Automatic, Axes
− > False, AxesStyle− > {} , Background− > Automatic, ImageSize
− > 16, LabelStyle− > {} , PlotRange− > Automatic, PlotRangePadding
]
− > Automatic, TicksStyle− > {} , ImageSizeMultipliers
]
− > {1, 1} , ShowStringCharacters− > True
LightRed
WMA link
LightRed
represents the color light red in graphics.
LightYellow
WMA link
LightYellow
represents the color light yellow in graphics.
109
Magenta
WMA link
Magenta
represents the color magenta in graphics.
WMA link
>> Magenta
Orange
WMA link
Orange
represents the color orange in graphics.
110
>> Orange // ToBoxes
[ [{
StyleBox GraphicsBox EdgeForm [RGBColor [0, 0, 0]] , RGBColor [
[ ]}
1, 0.5, 0] , RectangleBox {0, 0} , AspectRatio− > Automatic, Axes
− > False, AxesStyle− > {} , Background− > Automatic, ImageSize
− > 16, LabelStyle− > {} , PlotRange− > Automatic, PlotRangePadding
]
− > Automatic, TicksStyle− > {} , ImageSizeMultipliers
]
− > {1, 1} , ShowStringCharacters− > True
Pink
WMA link
Pink
represents the color pink in graphics.
Purple
WMA link
Purple
represents the color purple in graphics.
111
Red
WMA link
Red
represents the color red in graphics.
WMA link
>> Red
White
WMA link
White
represents the color white in graphics.
112
>> White // ToBoxes
[ [{
StyleBox GraphicsBox EdgeForm [RGBColor [0, 0, 0]] , GrayLevel [
[ ]}
1] , RectangleBox {0, 0} , AspectRatio− > Automatic, Axes
− > False, AxesStyle− > {} , Background− > Automatic, ImageSize
− > 16, LabelStyle− > {} , PlotRange− > Automatic, PlotRangePadding
]
− > Automatic, TicksStyle− > {} , ImageSizeMultipliers
]
− > {1, 1} , ShowStringCharacters− > True
WMA link
>> White
Yellow
WMA link
Yellow
represents the color yellow in graphics.
0pt 1pt 2pt 3pt 4pt 5pt 6pt 7pt 8pt 9pt 10pt
WMA link
>> Yellow
113
8. Date and Time
Dates and times are represented symbolically; computations can be performed on them.
Date object can also input and output dates and times in a wide range of formats, as well as handle
calendars.
Contents
$DateStringFormat
WMA link
$DateStringFormat
gives the format used for dates generated by DateString.
>> $DateStringFormat
{DateTimeShort}
$SystemTimeZone
WMA link
$SystemTimeZone
gives the current time zone for the computer system on which Mathics is being run.
>> $SystemTimeZone
−5.
$TimeZone
Time Zone (WMA)
$TimeZone
gives the current time zone to assume for dates and times.
114
>> $TimeZone
−5.
AbsoluteTime
WMA link
AbsoluteTime[]
gives the local time in seconds since epoch January 1, 1900, in your time zone.
AbsoluteTime[{y, m, d, h, m, s}]
gives the absolute time specification corresponding to a date list.
AbsoluteTime["string"]
gives the absolute time specification for a given date string.
AbsoluteTime[{"string",{e1, e2, ...}}]
takgs the date string to contain the elements "ei".
>> AbsoluteTime[]
3.88632*∧ 9
>> AbsoluteTime[{2000}]
3155673600
>> AbsoluteTime[{"01/02/03", {"Day", "Month", "YearShort"}}]
3253046400
>> AbsoluteTime["6 June 1991"]
2885155200
>> AbsoluteTime[{"6-6-91", {"Day", "Month", "YearShort"}}]
2885155200
AbsoluteTiming
WMA link
AbsoluteTiming[expr]
evaluates expr, returning a list of the absolute number of seconds in real time that have
elapsed, together with the result obtained.
>> AbsoluteTiming[50!]
{0.000150919, 30414093201713378043612608166064768844377641568960512000000000000}
>> Attributes[AbsoluteTiming]
{HoldAll, Protected}
DateDifference
WMA link
115
DateDifference[date1, date2]
returns the difference between date1 and date2 in days.
DateDifference[date1, date2, unit]
returns the difference in the specified unit.
DateDifference[date1, date2, {unit1, unit2, ...}]
represents the difference as a list of integer multiples of each unit, with any remainder ex-
pressed in the smallest unit.
DateList
WMA link
DateList[]
returns the current local time in the form {year, month, day, hour, minute, second}.
DateList[time]
returns a formatted date for the number of seconds time since epoch Jan 1 1900.
DateList[{y, m, d, h, m, s}]
converts an incomplete date list to the standard representation.
>> DateList[0]
{1900, 1, 1, 0, 0, 0.}
>> DateList[3155673600]
{2000, 1, 1, 0, 0, 0.}
>> DateList["31/10/1991"]
{1991, 10, 31, 0, 0, 0.}
>> DateList["1/10/1991"]
The interpretation of 1/10/1991 is ambiguous.
{1991, 1, 10, 0, 0, 0.}
116
>> DateList[{"31 10/91", {"Day", " ", "Month", "/", "YearShort"}}]
{1991, 10, 31, 0, 0, 0.}
DateObject
WMA link
DateObject[...]
Returns an object codifiyng DateList....
DatePlus
WMA link
DatePlus[date, n]
finds the date n days after date.
DatePlus[date, {n, "unit"}]
finds the date n units after date.
DatePlus[date, {{n1, "unit1"}, {n2, "unit2"}, ...}]
finds the date which is n_i specified units after date.
DatePlus[n]
finds the date n days after the current date.
DatePlus[offset]
finds the date which is offset from the current date.
DateString
WMA link
117
DateString[]
returns the current local time and date as a string.
DateString[elem]
returns the time formatted according to elems.
DateString[{e1, e2, ...}]
concatinates the time formatted according to elements ei.
DateString[time]
returns the date string of an AbsoluteTime.
DateString[{y, m, d, h, m, s}]
returns the date string of a date list specification.
DateString[string]
returns the formatted date string of a date string specification.
DateString[spec, elems]
formats the time in turns of elems. Both spec and elems can take any of the above formats.
>> DateString[{1991, 10, 31, 0, 0}, {"Day", " ", "MonthName", " ", "Year
"}]
31 October 1991
>> DateString[{2007, 4, 15, 0}]
Sun 15 Apr 2007 00:00:00
EasterSunday
Date of Easter (WMA link)
EasterSunday[year]
returns the date of the Gregorian Easter Sunday as {year, month, day}.
>> EasterSunday[2000]
{2000, 4, 23}
>> EasterSunday[2030]
{2030, 4, 21}
Now
WMA link
118
Now
gives the current time on the system.
>> Now
[Sat 25 Feb 2023 13:25:34 GTM − 5]
Pause
WMA link
Pause[n]
pauses for n seconds.
>> Pause[0.5]
SessionTime
WMA link
SessionTime[]
returns the total time in seconds since this session started.
>> SessionTime[]
113.223
TimeConstrained
WMA link
TimeConstrained[expr, t]
evaluates expr, stopping after t seconds.
TimeConstrained[expr, t, failexpr]
returns failexpr if the time constraint is not met.
Possible issues: for certain time-consuming functions (like simplify) which are based on sympy or other
libraries, it is possible that the evaluation continues after the timeout. However, at the end of the
evaluation, the function will return $Aborted and the results will not affect the state of the Mathics3
kernel.
TimeRemaining
WMA link
TimeRemaining[]
Gives the number of seconds remaining until the earliest enclosing TimeConstrained will
request the current computation to stop.
TimeConstrained[expr, t, failexpr]
returns failexpr if the time constraint is not met.
119
If TimeConstrained is called out of a TimeConstrained expression, returns ‘Infinity‘
>> TimeRemaining[]
∞
>> TimeConstrained[1+2; Print[TimeRemaining[]], 0.9]
0.899139
TimeUsed
WMA link
TimeUsed[]
returns the total CPU time used for this session, in seconds.
>> TimeUsed[]
116.248
Timing
WMA link
Timing[expr]
measures the processor time taken to evaluate expr. It returns a list containing the measured
time in seconds and the result of the evaluation.
>> Timing[50!]
{0.00018476, 30414093201713378043612608166064768844377641568960512000000000000}
>> Attributes[Timing]
{HoldAll, Protected}
120
9. Definition Attributes
While a definition like cube[x_] = x^3 gives a way to specify values of a function, attributes allow a
way to specify general properties of functions and symbols. This is independent of the parameters they
take and the values they produce.
The builtin-attributes having a predefined meaning in Mathics3 which are described below.
However in contrast to Mathematica®, you can set any symbol as an attribute.
Contents
Attributes
WMA link
Attributes[symbol]
returns the attributes of symbol.
Attributes["string"]
returns the attributes of Symbol["string"].
Attributes[symbol] = {attr1, attr2}
sets the attributes of symbol, replacing any existing attributes.
>> Attributes[Plus]
{Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected}
>> Attributes["Plus"]
{Flat, Listable, NumericFunction, OneIdentity, Orderless, Protected}
121
Attributes must be symbols:
>> Attributes[f] := {a + b}
Argument a + b at position 1 is expected to be a symbol.
$Failed
ClearAttributes
WMA link
ClearAttributes[symbol, attrib]
removes attrib from symbol’s attributes.
>> Attributes[f]
{Flat}
>> Attributes[f]
{}
>> Attributes[f]
{}
Constant
WMA link
Constant
is an attribute that indicates that a symbol is a constant.
122
Flat
WMA link
Flat
is an attribute that specifies that nested occurrences of a function should be automatically
flattened.
HoldAll
WMA link
HoldAll
is an attribute specifying that all arguments of a function should be left unevaluated.
>> Attributes[Function]
{HoldAll, Protected}
HoldAllComplete
WMA link
HoldAllComplete
is an attribute that includes the effects of HoldAll and SequenceHold, and also protects the
function from being affected by the upvalues of any arguments.
HoldAllComplete even prevents upvalues from being used, and includes SequenceHold.
>> SetAttributes[f, HoldAllComplete]
>> f[a] ^= 3;
>> f[a]
f [a]
HoldFirst
WMA link
123
HoldFirst
is an attribute specifying that the first argument of a function should be left unevaluated.
>> Attributes[Set]
{HoldFirst, Protected, SequenceHold}
HoldRest
WMA link
HoldRest
is an attribute specifying that all but the first argument of a function should be left unevalu-
ated.
>> Attributes[If]
{HoldRest, Protected}
Listable
WMA link
Listable
is an attribute specifying that a function should be automatically applied to each element of a
list.
Locked
WMA link
Locked
is an attribute that prevents attributes on a symbol from being modified.
124
>> Attributes[lock] = {}
Symbol lock is locked.
{}
>> Attributes[lock]
{Flat, Locked}
However, their values might be modified (as long as they are not Protected too):
>> lock = 3
3
NHoldAll
WMA link
NHoldAll
is an attribute that protects all arguments of a function from numeric evaluation.
NHoldFirst
WMA link
NHoldFirst
is an attribute that protects the first argument of a function from numeric evaluation.
NHoldRest
WMA link
NHoldRest
is an attribute that protects all but the first argument of a function from numeric evaluation.
NumericFunction
WMA link
NumericFunction
is an attribute that indicates that a symbol is the head of a numeric function.
125
>> Attributes[Sqrt]
{Listable, NumericFunction, Protected}
Expressions with a head having this attribute, and with all the elements being numeric expressions, are
considered numeric expressions:
>> NumericQ[Sqrt[1]]
True
>> NumericQ[a]=True; NumericQ[Sqrt[a]]
True
>> NumericQ[a]=False; NumericQ[Sqrt[a]]
False
OneIdentity
WMA link
OneIdentity
is an attribute assigned to a symbol, say f, indicating that f [x], f [f [x]], etc. are all equivalent
to x in pattern matching.
Orderless
WMA link
Orderless
is an attribute that can be assigned to a symbol f to indicate that the elements ei in expressions
of the form f [e1, e2, ...] should automatically be sorted into canonical order. This property is
accounted for in pattern matching.
126
>> f[c, a, b, a + b, 3, 1.0]
f [1., 3, a, b, c, a + b]
Protect
WMA link
>> Protect[A]
>> A[[2]] = 4;
Symbol A is Protected.
>> A
{1, 2, 3}
Protected
WMA link
Protected
is an attribute that prevents values on a symbol from being modified.
>> p = 2;
Symbol p is Protected.
>> f[p] ^= 3;
Tag p in f[p] is Protected.
127
>> Attributes[p]
{Flat, Protected}
>> p = 2
2
You can also use Protect or Unprotect, resp.
>> Protect[p]
>> Attributes[p]
{Protected}
>> Unprotect[p]
>> p = 2
Symbol p is Protected.
2
>> Unprotect[p]
Symbol p is locked.
ReadProtected
WMA link
ReadProtected
is an attribute that prevents values on a symbol from being read.
>> p = 3;
>> Definition[p]
p=3
>> Definition[p]
[ ]
Attributes p = {ReadProtected}
SequenceHold
WMA link
128
SequenceHold
is an attribute that prevents Sequence objects from being spliced into a function’s arguments.
>> s
Sequence [a, b]
>> Plus[s]
a+b
SetAttributes
WMA link
SetAttributes[symbol, attrib]
adds attrib to the list of symbol’s attributes.
>> Attributes[f]
{Flat}
>> Attributes[g]
{Flat, Orderless}
Unprotect
WMA link
129
10. Descriptive Statistics
Function which operate on explicit data and symbolic representations of statistical distributions.
Contents
Correlation
Pearson correlation coefficient (WMA)
Correlation[a, b]
computes Pearson’s correlation of two equal-sized vectors a and b.
Covariance
Covariance (WMA)
Covariance[a, b]
computes the covariance between the equal-sized vectors a and b.
General Statistics
General Statistic
130
CentralMoment
Central moment (WMA)
CentralMoment[list, r]
gives the the rth central moment (i.e. the rth moment about the mean) of list.
Location Statistics
Location Statistic
Mean
WMA link
Mean[list]
returns the statistical mean of list.
Order Statistics
Order Statistics
In statistics, an order statistic gives the k-th smallest value.
Together with rank statistics these are fundamental tools in non-parametric statistics and inference.
Important special cases of order statistics are finding minimum and maximum value of a sample and
sample quantiles.
Quantile
Quantile (WMA)
In statistics and probability, quantiles are cut points dividing the range of a probability distribution into
continuous intervals with equal probabilities, or dividing the observations in a sample in the same way.
Quantile is also known as value at risk (VaR) or fractile.
131
Quantile[list, q]
returns the qth quantile of list.
Quantile[list, q, {{a,b}, {c,d}}]
uses the quantile definition specified by parameters a, b, c, d.
For a list of length n, Quantile[list, q, {{a,b}, {c,d}}] depends on x=a+(n+b)q.
If x is an integer, the result is s[[x]], where s=Sort[list,Less].
Otherwise, the result is s[[Floor[x]]]+(s[[Ceiling[x]]]-s[[Floor[x]]])(c+dFractionalPart[x]),
with the indices taken to be 1 or n if they are out of range.
The default choice of parameters is {{0,0},{1,0}}.
Quartiles
Quartile (WMA)
Quartiles[list]
returns the 1/4, 1/2, and 3/4 quantiles of list.
>> Quartiles[Range[25]]
{ }
27 77
, 13,
4 4
RankedMax
WMA link
RankedMax[list, n]
returns the nth largest element of list (with n = 1 yielding the largest element, n = 2 yielding
the second largest element, and so on).
RankedMin
WMA link
132
RankedMin[list, n]
returns the nth smallest element of list (with n = 1 yielding the smallest element, n = 2 yielding
the second smallest element, and so on).
Sort
WMA link
Sort[list]
sorts list (or the elements of any other expression) according to canonical ordering.
Sort[list, p]
sorts using p to determine the order of two elements.
Sort uses OrderedQ to determine ordering by default. You can sort patterns according to their prece-
dence using PatternsOrderedQ:
>> Sort[{items___, item_, OptionsPattern[], item_symbol, item_?test},
PatternsOrderedQ]
{item_symbol, item_? test, item_, items___, OptionsPattern []}
TakeLargest
WMA link
TakeLargest[list, f , n]
returns the a sorted list of the n largest items in list.
None, Null, Indeterminate and expressions with head Missing are ignored by default:
>> TakeLargest[{-8, 150, Missing[abc]}, 2]
{150, −8}
You may specify which items are ignored using the option ExcludedForms:
133
>> TakeLargest[{-8, 150, Missing[abc]}, 2, ExcludedForms -> {}]
{Missing [abc] , 150}
TakeSmallest
WMA link
TakeSmallest[list, n]
returns the a sorted list of the n smallest items in list.
Shape Statistics
Shape Statistic
Kurtosis
Kurtosis (WMA)
Kurtosis[list]
gives the Pearson measure of kurtosis for list (a measure of existing outliers).
Skewness
Skewness (WMA)
Skewness[list]
gives Pearson’s moment coefficient of skewness for list (a measure for estimating the symme-
try of a distribution).
134
11. Distance and Similarity Measures
Different measures of distance or similarity for different types of analysis.
Contents
Cluster Analysis
Cluster Analysi
ClusteringComponents
WMA link
ClusteringComponents[list]
forms clusters from list and returns a list of cluster indices, in which each element shows the
index of the cluster in which the corresponding element in list ended up.
ClusteringComponents[list, k]
forms k clusters from list and returns a list of cluster indices, in which each element shows the
index of the cluster in which the corresponding element in list ended up.
For more detailed documentation regarding options and behavior, see FindClusters[].
>> ClusteringComponents[{1, 2, 3, 1, 2, 10, 100}]
{1, 1, 1, 1, 1, 1, 2}
FindClusters
WMA link
FindClusters[list]
returns a list of clusters formed from the elements of list. The number of cluster is determined
automatically.
FindClusters[list, k]
returns a list of k clusters formed from the elements of list.
135
>> FindClusters[{1, 2, 20, 10, 11, 40, 19, 42}]
{{1, 2, 20, 10, 11, 19} , {40, 42}}
>> FindClusters[{{1}, {5, 6}, {7}, {2, 4}}, DistanceFunction -> (Abs[
Length[#1] - Length[#2]]&)]
{{{1} , {7}} , {{5, 6} , {2, 4}}}
FindClusters’ automatic distance function detection supports scalars, numeric tensors, boolean vectors
and strings.
The Method option must be either “Agglomerate” or “Optimize”. If not specified, it defaults to “Opti-
mize”. Note that the Agglomerate and Optimize methods usually produce different clusterings.
The runtime of the Agglomerate method is quadratic in the number of clustered points n, builds the
clustering from the bottom up, and is exact (no element of randomness). The Optimize method’s run-
time is linear in n, Optimize builds the clustering from top down, and uses random sampling.
Nearest
WMA link
136
Nearest[list, x]
returns the one item in list that is nearest to x.
Nearest[list, x, n]
returns the n nearest items.
Nearest[list, x, {n, r}]
returns up to n nearest items that are not farther from x than r.
Nearest[{p1 -> q1, p2 -> q2, ...}, x]
returns q1, q2, ... but measures the distances using p1, p2, ...
Nearest[{p1, p2, ...} -> {q1, q2, ...}, x]
returns q1, q2, ... but measures the distances using p1, p2, ...
>> Nearest[{Blue -> "blue", White -> "white", Red -> "red", Green -> "
green"}, {Orange, Gray}]
{{red} , {white}}
>> Nearest[{{0, 1}, {1, 2}, {2, 3}} -> {a, b, c}, {1.1, 2}]
{b}
Numerical Data
Numerical Data
BrayCurtisDistance
Bray-Curtis Dissimilarity (WMA)
BrayCurtisDistance[u, v]
returns the Bray-Curtis distance between u and v.
CanberraDistance
Canberra distance (WMA)
CanberraDistance[u, v]
returns the canberra distance between u and v, which is a weighted version of the Manhattan
distance.
137
>> CanberraDistance[-7, 5]
1
>> CanberraDistance[{-1, -1}, {1, 1}]
2
ChessboardDistance
Chebyshev distance (WMA)
ChessboardDistance[u, v]
returns the chessboard distance (also known as Chebyshev distance) between u and v, which
is the number of moves a king on a chessboard needs to get from square u to square v.
>> ChessboardDistance[-7, 5]
12
>> ChessboardDistance[{-1, -1}, {1, 1}]
2
CosineDistance
Cosine similarity
(WMA)
CosineDistance[u, v]
returns the cosine distance between u and v.
EuclideanDistance
Euclidean similarity (WMA)
EuclideanDistance[u, v]
returns the euclidean distance between u and v.
>> EuclideanDistance[-7, 5]
12
>> EuclideanDistance[{-1, -1}, {1, 1}]
√
2 2
138
>> EuclideanDistance[{a, b}, {c, d}]
√
Abs [a − c]2 + Abs [b − d]2
ManhattanDistance
Manhattan distance (WMA)
ManhattanDistance[u, v]
returns the Manhattan distance between u and v, which is the number of horizontal or vertical
moves in the gridlike Manhattan city layout to get from u to v.
>> ManhattanDistance[-7, 5]
12
>> ManhattanDistance[{-1, -1}, {1, 1}]
4
SquaredEuclideanDistance
WMA link
SquaredEuclideanDistance[u, v]
returns squared the euclidean distance between u and v.
>> SquaredEuclideanDistance[-7, 5]
144
>> SquaredEuclideanDistance[{-1, -1}, {1, 1}]
8
DamerauLevenshteinDistance
WMA link
DamerauLevenshteinDistance[a, b]
returns the Damerau-Levenshtein distance of a and b, which is defined as the minimum num-
ber of transpositions, insertions, deletions and substitutions needed to transform one into the
other. In contrast to EditDistance, DamerauLevenshteinDistance counts transposition of ad-
jacent items (e.g. “ab” into “ba”) as one operation of change.
139
>> DamerauLevenshteinDistance["abc", "acb"]
1
>> DamerauLevenshteinDistance["azbc", "abxyc"]
3
The IgnoreCase option makes DamerauLevenshteinDistance ignore the case of letters:
>> DamerauLevenshteinDistance["time", "Thyme"]
3
>> DamerauLevenshteinDistance["time", "Thyme", IgnoreCase -> True]
2
DamerauLevenshteinDistance also works on lists:
>> DamerauLevenshteinDistance[{1, E, 2, Pi}, {1, E, Pi, 2}]
1
EditDistance
WMA link
EditDistance[a, b]
returns the Levenshtein distance of a and b, which is defined as the minimum number of
insertions, deletions and substitutions on the constituents of a and b needed to transform one
into the other.
HammingDistance
WMA link
140
HammingDistance[u, v]
returns the Hamming distance between u and v, i.e. the number of different elements. u and
v may be lists or strings.
141
12. Drawing Graphics
Contents
AbsoluteThickness
WMA link
AbsoluteThickness[p]
sets the line thickness for subsequent graphics primitives to p points.
Arrow
WMA link
142
Arrow[{p1, p2}]
represents a line from p1 to p2 that ends with an arrow at p2.
Arrow[{p1, p2}, s]
represents a line with arrow that keeps a distance of s from p1 and p2.
Arrow[{point_1, point_2}, {s1, s2}]
represents a line with arrow that keeps a distance of s1 from p1 and a distance of s2 from p2.
Arrow[{point_1, point_2}, {s1, s2}]
represents a line with arrow that keeps a distance of s1 from p1 and a distance of s2 from p2.
143
Keeping distances may happen across multiple segments:
>> Table[Graphics[{Circle[], Arrow[Table[{Cos[phi],Sin[phi]},{phi,0,2*Pi
,Pi/2}],{d, d}]}],{d,0,2,0.5}]
, ,
Arrowheads
WMA link
Arrowheads[s]
specifies that Arrow[] draws one arrow of size s (relative to width of image, defaults to 0.04).
Arrowheads[{spec1, spec2, ..., specn}]
specifies that Arrow[] draws n arrows as defined by spec1, spec2, ... specn.
Arrowheads[{{s}}]
specifies that one arrow of size s should be drawn.
Arrowheads[{{s, pos}}]
specifies that one arrow of size s should be drawn at position pos (for the arrow to be on the
line, pos has to be between 0, i.e. the start for the line, and 1, i.e. the end of the line).
Arrowheads[{{s, pos, g}}]
specifies that one arrow of size s should be drawn at position pos using Graphics g.
144
>> Graphics[{Circle[],Arrowheads[{-0.04, 0.04}], Arrow[{{0, 0}, {2, 2}},
{1,1}]}]
CMYKColor
WMA link
CMYKColor[c, m, y, k]
represents a color with the specified cyan, magenta, yellow and black components.
145
>> Graphics[MapIndexed[{CMYKColor @@ #1, Disk[2*#2 ~Join~{0}]} &,
IdentityMatrix[4]], ImageSize->Small]
1.0
0.5
−0.5
−1.0
Circle
WMA link
Circle[{cx, cy}, r]
draws a circle with center (cx, cy) and radius r.
Circle[{cx, cy}, {rx, ry}]
draws an ellipse.
Circle[{cx, cy}]
chooses radius 1.
Circle[]
chooses center (0, 0) and radius 1.
146
>> Graphics[{Circle[], Disk[{0, 0}, {1, 1}, {0, 2.1}]}]
Target practice:
>> Graphics[Circle[], Axes-> True]
Directive
WMA link
Disk
WMA link
147
Disk[{cx, cy}, r]
fills a circle with center (cx, cy) and radius r.
Disk[{cx, cy}, {rx, ry}]
fills an ellipse.
Disk[{cx, cy}]
chooses radius 1.
Disk[]
chooses center (0, 0) and radius 1.
Disk[{x, y}, ..., {t1, t2}]
is a sector from angle t1 to t2.
148
>> Graphics[Disk[{0, 0}, 1, {Pi / 3, 2 Pi / 3}]]
EdgeForm
WMA link
EdgeForm[g]
is a graphics directive that specifies that edges of filled graphics objects are to be drawn using
the graphics directive or list of directives g.
149
>> Graphics[{Style[Disk[],EdgeForm[{Thick,Red}]], Circle[{1,1}]}]
FaceForm
WMA link
FaceForm[g]
is a graphics directive that specifies that faces of filled graphics objects are to be drawn using
the graphics directive or list of directives g.
FilledCurve
WMA link
FilledCurve[{segment1, segment2 ...}]
represents a filled curve.
1.0
0.5
−0.5
−1.0
150
>> Graphics[FilledCurve[{BezierCurve[{{0, 0}, {1, 1}, {2, 0}}], Line
[{{3, 0}, {0, 2}}]}]]
FontColor
WMA link
FontColor
is an option for Style to set the font color.
Graphics
WMA link
Graphics[primitives, options]
represents a graphic.
Options include:
• Axes
• TicksStyle
• AxesStyle
• LabelStyle
• AspectRatio
• PlotRange
• PlotRangePadding
• ImageSize
• Background
151
>> Graphics[{Blue, Line[{{0,0}, {1,1}}]}]
>> Graphics[{Rectangle[],Red,Disk[{1,0}]},PlotRange->{{0,1},{0,1}}]
\begin{asy}
usepackage("amsmath");
size(5.8556cm, 5.8333cm);
draw(ellipse((175,175),175,175), rgb(0, 0, 0)+linewidth(0.66667));
clip(box((-0.33333,0.33333), (350.33,349.67)));
\end{asy}
152
GrayLevel
WMA link
GrayLevel[g]
represents a shade of gray specified by g, ranging from 0 (black) to 1 (white).
GrayLevel[g, a]
represents a shade of gray specified by g with opacity a.
Hue
WMA link
Hue[h, s, l, a]
represents the color with hue h, saturation s, lightness l and opacity a.
Hue[h, s, l]
is equivalent to Hue[h, s, l, 1].
Hue[h, s]
is equivalent to Hue[h, s, 1, 1].
Hue[h]
is equivalent to Hue[h, 1, 1, 1].
Inset
WMA link
153
Text[obj]
represents an object obj inset in a graphic.
Text[obj, pos]
represents an object obj inset in a graphic at position pos.
Text[obj, pos, $$]
represents an object obj inset in a graphic at position pos, in away that the position opos of obj
coincides with pos in the enclosing graphic.
LABColor
WMA link
LABColor[l, a, b]
represents a color with the specified lightness, red/green and yellow/blue components in the
CIE 1976 L*a*b* (CIELAB) color space.
LCHColor
WMA link
LCHColor[l, c, h]
represents a color with the specified lightness, chroma and hue components in the CIELCh
CIELab cube color space.
LUVColor
WMA link
LCHColor[l, u, v]
represents a color with the specified components in the CIE 1976 L*u*v* (CIELUV) color space.
Large
WMA link
ImageSize -> Large
produces a large image.
Line
WMA link
154
>> Graphics[Line[{{0,1},{0,0},{1,0},{1,1}}]]
>> Graphics3D[Line[{{0,0,0},{0,1,1},{1,0,0}}]]
Medium
WMA link
ImageSize -> Medium
produces a medium-sized image.
Offset
WMA link
Opacity
WMA link
Opacity[level]
is a graphics directive that sets the opacity to level.
155
>> Graphics3D[{Blue, Sphere[], Opacity[.4], Red, Cuboid[]}]
Notice that Opacity does not overwrite the value of the alpha channel if it is set in a color directive:
>> Graphics[{Blue, Disk[], RGBColor[1,0,0,1],Opacity[.2], Rectangle
[{0,0},{1,1}]}]
Point
WMA link
Points are rendered if possible as circular regions. Their diameters can be specified using PointSize.
Points can be specified as {x, y}:
156
>> Graphics[Point[{0, 0}]]
or as {x, y, z}:
>> Graphics3D[{Orange, PointSize[0.05], Point[Table[{Sin[t], Cos[t], 0},
{t, 0, 2 Pi, Pi / 15.}]]}]
PointSize
WMA link
PointSize[t]
PointSize
sets the diameter of points to t, which is relative to the overall width.
can be used for both two- and three-dimensional graphics. The initial default pointsize is 0.008 for
two-dimensional graphics and 0.01 for three-dimensional graphics.
157
>> Table[Graphics[{PointSize[r], Point[{0, 0}]}], {r, {0.02, 0.05, 0.1,
0.3}}]
, ,
158
>> Table[Graphics3D[{PointSize[r], Point[{0, 0, 0}]}], {r, {0.05, 0.1,
0.8}}]
10
8
6
4
2
2 4 6
, ,
Polygon
WMA link
A Right Triangle:
>> Graphics[Polygon[{{1,0},{0,0},{0,1}}]]
3.0
2.5
2.0
1.5
1.0
0.5
159
Notice that there is a line connecting from the last point to the first one.
A point is an element of the polygon if a ray from the point in any direction in the plane crosses the
boundary line segments an odd number of times.
>> Graphics[Polygon[{{150,0},{121,90},{198,35},{102,35},{179,90}}]]
2
1 Second
First
−2 −1 1 2
−1
−2
>> Graphics3D[Polygon[{{0,0,0},{0,1,1},{1,0,0}}]]
−4 −2 2 4
−2
−4
RGBColor
WMA link
RGBColor[r, g, b]
represents a color with the specified red, green and blue components.
160
>> Graphics[MapIndexed[{RGBColor @@ #1, Disk[2*#2 ~Join~{0}]} &,
IdentityMatrix[3]], ImageSize->Small]
1.0
0.5
−0.5
−1.0
>> RGBColor[0, 1, 0]
1.0
0.5
10 20 30 40 50
−0.5
−1.0
Rectangle
WMA link
Rectangle[{xmin, ymin}]
represents a unit square with bottom-left corner at {xmin, ymin}.
’Rectangle[{xmin, ymin}, {xmax, ymax}]
is a rectangle extending from {xmin, ymin} to {xmax, ymax}.
161
>> Graphics[Rectangle[]]
1.0
0.5
10 20 30 40 50
−0.5
−1.0
Dogs
Fish
Cats
RegularPolygon
WMA link
RegularPolygon[n]
gives the regular polygon with n edges.
RegularPolygon[r, n]
gives the regular polygon with n edges and radius r.
RegularPolygon[{r, phi}, n]
gives the regular polygon with radius r with one vertex drawn at angle phi.
RegularPolygon[{$x, $y}, r, n]
gives the regular polygon centered at the position {$x, $y}.
>> Graphics[RegularPolygon[5]]
1.0
0.5
10 20 30 40 50
−0.5
−1.0
162
>> Graphics[{Yellow, Rectangle[], Orange, RegularPolygon[{1, 1}, {0.25,
0}, 3]}]
1.0
0.5
2 4 6 8 10
−0.5
−1.0
Show
WMA link
Show[graphics, options]
shows a list of graphics with the specified options added.
163
>> Show[{Plot[x, {x, 0, 10}], ListPlot[{1,2,3}]}]
100
80
0.5
60
−4 −2
2 4
40
−0.5
20
2 4 6 8 10 , , AspectRatio
− > Automatic, Axes− > False, AxesStyle− > {} , Background
− > Automatic, ImageSize− > Automatic, LabelStyle− > {} , PlotRange
− > Automatic, PlotRangePadding− > Automatic, TicksStyle− > {}
Small
WMA link
ImageSize -> Small
produces a small image.
164
Text
WMA link
Text["text", {x, y}]
draws text centered on position {x, y}.
1.0
0.5
2 4 6 8 10 12
−0.5
−1.0
Thick
WMA link
Thick
sets the line width for subsequent graphics primitives to 2pt.
Thickness
WMA link
Thickness[t]
sets the line thickness for subsequent graphics primitives to t times the size of the plot area.
165
Thin
WMA link
Thin
sets the line width for subsequent graphics primitives to 0.5pt.
Tiny
WMA link
ImageSize -> Tiny
produces a tiny image.
XYZColor
WMA link
XYZColor[x, y, z]
represents a color with the specified components in the CIE 1931 XYZ color space.
166
13. Drawing Options and Option Values
The various common Plot and Graphics options, along with the meaning of specific option values are
described here.
Contents
Automatic
WMA link
Automatic
is used to specify an automatically computed option value.
Automatic is the default for PlotRange, ImageSize, and other graphical options:
>> Cases[Options[Plot], HoldPattern[_ :> Automatic]]
{Background:>Automatic, Exclusions:>Automatic, ImageSize:>Automatic, MaxRecursion:>Automatic, PlotRange:>
Axes
WMA link
Axes
is an option for charting and graphics functions that specifies whether axes should be drawn.
167
>> Graphics[Circle[], Axes -> True]
Axis
WMA link
Axis
is a possible value for the Filling option.
0.5
−4 −2 2 4
−0.5
Bottom
WMA link
Bottom
is a possible value for the Filling option.
168
>> ListLinePlot[Table[Sin[x], {x, -5, 5, 0.2}], Filling->Bottom]
0.5
−4 −2 2 4
−0.5
ChartLabels
WMA link
ChartLabels
is a charting option that specifies what labels should be used for chart elements.
ChartLegends
WMA link
ChartLegends
is an option for charting functions that specifies the legends to be used for chart elements.
Filling
WMA link
Filling -> [Top | Bottom| Axis]
Filling is a an option to ListPlot, Plot or Plot3D, and related functions that indicates what
filling to add under point, curves, and surfaces.
169
>> ListLinePlot[Table[Sin[x], {x, -5, 5, 0.2}], Filling->Axis]
1.0
0.5
−0.5
−1.0
Full
WMA link
Full
is a possible value for the Mesh and PlotRange options.
ImageSize
WMA link
ImageSize
is an option that specifies the overall size of an image to display.
Specifications for both width and height can be any of the following:
Automatic
determined by location or other dimension (default)
Tiny, Small, Medium, Large
pre defined absolute sizes
0.5
10 20 30 40 50
−0.5
−1.0
170
Joined
WMA link
Joined boolean
is an option for Plot that gives whether to join points to make lines.
MaxRecursion
WMA link
MaxRecursion
is an option for functions like NIntegrate and Plot that specifies how many recursive subdivi-
sions can be made.
Mesh
WMA link
Mesh
is a charting option, such as for Plot, BarChart, PieChart, etc. that specifies the mesh to be
drawn. The default is Mesh->None.
171
>> Plot[Sin[Cos[x^2]],{x,-4,4},Mesh->All]
>> DensityPlot[Sin[x y], {x, -2, 2}, {y, -2, 2}, Mesh->Full]
>> Plot3D[Sin[x y], {x, -2, 2}, {y, -2, 2}, Mesh->Full]
PlotPoints
WMA link
PlotPoints n
A number specifies how many initial sample points to use.
172
PlotRange
WMA link
PlotRange
is a charting option, such as for Plot, BarChart, PieChart, etc. that gives the range of
coordinates to include in a plot.
TicksStyle
WMA link
TicksStyle
is an option for graphics functions which specifies how ticks should be rendered.
• TicksStyle gives styles for both tick marks and tick labels.
• TicksStyle can be used in both two and three-dimensional graphics.
• TicksStyle->list specifies the colors of each of the axes.
>> Graphics[Circle[], Axes-> True, TicksStyle -> {Blue, Red}]
173
Top
WMA link
Top
is a possible value for the Filling option.
174
14. Expression Structure
Contents
ByteCount
WMA link
ByteCount[expr]
gives the internal memory space used by expr, in bytes.
Hash
Hash function (WMA link)
Hash[expr]
returns an integer hash for the given expr.
Hash[expr, type]
returns an integer hash of the specified type for the given expr.
The types supported are “MD5”, “Adler32”, “CRC32”, “SHA”, “SHA224”, “SHA256”,
“SHA384”, and “SHA512”.
Hash[expr, type, format]
Returns the hash in the specified format.
175
>> Hash[{a, b, c}, "xyzstr"]
[ ]
Hash { a, b, c} , xyzstr, Integer
LeafCount
WMA link
LeafCount[expr]
returns the total number of indivisible subexpressions in expr.
ApplyLevel (@@@)
WMA link
ApplyLevel[f , expr]
f @@@ expr
is equivalent to Apply[f , expr, {1}].
BinarySearch
Binary search algorithm (WMA)
CombinatoricaOld‘BinarySearch[l, k]
searches the list l, which has to be sorted, for key k and returns its index in l.
If k does not exist in l, BinarySearch returns (a + b) / 2, where a and b are the indices between
which k would have to be inserted in order to maintain the sorting order in l.
Please note that k and the elements in l need to be comparable under a strict total order.
CombinatoricaOld‘BinarySearch[l, k, f ]
gives the index of k in the elements of l if f is applied to the latter prior to comparison. Note
that f needs to yield a sorted sequence if applied to the elements of l.
176
Number 100 is found at exactly in the fourth place of the given list:
>> CombinatoricaOld‘BinarySearch[{3, 4, 10, 100, 123}, 100]
4
Number 7 is found in between the second and third place (3, and 9) of the given list. The numerical
difference between 3 and 9 does not figure into the .5 part of 2.5:
>> CombinatoricaOld‘BinarySearch[{2, 3, 9}, 7] // N
2.5
0.5 is what you get when the item comes before the given list:
>> CombinatoricaOld‘BinarySearch[{-10, 5, 8, 10}, -100] // N
0.5
And here is what you see when the item comes at the end of the list:
>> CombinatoricaOld‘BinarySearch[{-10, 5, 8, 10}, 20] // N
4.5
>> CombinatoricaOld‘BinarySearch[{{a, 1}, {b, 7}}, 7, #[[2]]&]
2
Depth
WMA link
Depth[expr]
gives the depth of expr.
The depth of an expression is defined as one plus the maximum number of Part indices required to
reach any part of expr, except for heads.
>> Depth[x]
1
>> Depth[x + y]
2
>> Depth[{{{{x}}}}]
5
Complex numbers are atomic, and hence have depth 1:
>> Depth[1 + 2 I]
1
Depth ignores heads:
>> Depth[f[a, b][c]]
2
FreeQ
WMA link
FreeQ[expr, x]
returns True if expr does not contain the expression x.
177
>> FreeQ[y, x]
True
>> FreeQ[a+b+c, a+b]
False
>> FreeQ[{1, 2, a^(a+b)}, Plus]
False
>> FreeQ[a+b, x_+y_+z_]
True
>> FreeQ[a+b+c, x_+y_+z_]
False
>> FreeQ[x_+y_+z_][a+b]
True
Level
WMA link
Level[expr, levelspec]
gives a list of all subexpressions of expr at the level(s) specified by levelspec.
n
levels 1 through n
Infinity
all levels from level 1
{n}
level n only
{m, n}
levels m through n
>> Level[{{{{a}}}}, 3]
{{ a} , {{ a}} , {{{ a}}}}
178
Use the option Heads -> True to include heads:
>> Level[{{{{a}}}}, 3, Heads -> True]
{List, List, List, { a} , {{ a}} , {{{ a}}}}
Null
WMA link
Null
is the implicit result of expressions that do not yield a result.
>> FullForm[a:=b]
Null
It is not displayed in StandardForm,
>> a:=b
Operate
WMA link
Operate[p, expr]
applies p to the head of expr.
Operate[p, expr, n]
applies p to the nth head of expr.
179
>> Operate[p, f[a][b][c], 0]
[ ]
p f [a] [b] [c]
Order
WMA link
Order[x, y]
returns a number indicating the canonical ordering of x and y. 1 indicates that x is before y,
-1 that y is before x. 0 indicates that there is no specific ordering. Uses the same order as Sort.
OrderedQ
WMA link
OrderedQ[{a, b}]
is True if a sorts before b according to canonical ordering.
PatternsOrderedQ
WMA link
PatternsOrderedQ[patt1, patt2]
returns True if pattern patt1 would be applied before patt2 according to canonical pattern
ordering.
180
SortBy
WMA link
SortBy[list, f ]
sorts list (or the elements of any other expression) according to canonical ordering of the keys
that are extracted from the list’s elements using $f. Chunks of elements that appear the same
under $f are sorted according to their natural order (without applying $f).
SortBy[f ]
creates an operator function that, when applied, sorts by $f.
Through
WMA link
Through[p[f ][x]]
gives p[f [x]].
>> Through[f[g][x]]
[ ]
f g [x]
181
15. File Formats
Built-in Importers.
Contents
HTML
HTML
Basic implementation for a HTML importer.
DataImport
HTML‘DataImport[‘‘filename’]’
imports data from a HTML file.
FullDataImport
HTML‘FullDataImport[‘‘filename’]’
imports data from a HTML file.
HTMLGet
HTMLGet[str]
Parses str as HTML code.
182
HTMLGetString
HTML‘Parser‘HTMLGetString[‘‘string’]’
parses HTML code contained in “string”.
HyperlinksImport
HTML‘HyperlinksImport[‘‘filename’]’
imports hyperlinks from a HTML file.
ImageLinksImport
HTML‘ImageLinksImport[‘‘filename’]’
imports links to the images included in a HTML file.
PlaintextImport
HTML‘PlaintextImport[‘‘filename’]’
imports plane text from a HTML file.
>> DeleteDuplicates[StringCases[Import["ExampleData/PrimeMeridian.html
"], RegularExpression["Wiki[a-z]+"]]]
SourceImport
HTML‘SourceImport[‘‘filename’]’
imports source code from a HTML file.
>> DeleteDuplicates[StringCases[Import["ExampleData/PrimeMeridian.html",
"Source"], RegularExpression["<t[a-z]+>"]]]
{<title>, <tr>, <th>, <td>}
TitleImport
HTML‘TitleImport[‘‘filename’]’
imports the title string from a HTML file.
183
>> Import["ExampleData/PrimeMeridian.html", "Title"]
Prime meridian - Wikipedia
XMLObjectImport
HTML‘XMLObjectImport[‘‘filename’]’
imports XML objects from a HTML file.
XML
XML
Basic implementation for an XML importer.
PlaintextImport
WMA link
XML‘PlaintextImport[‘‘string’]’
parses “string” as XML code, and returns it as plain text.
TagsImport
XML‘TagsImport[‘‘string’]’
parses “string” as XML code, and returns a list with the tags found.
XMLElement
WMA link
184
XMLGet
XMLGet[...]
Internal. Document me.
XMLGetString
XML‘Parser‘XMLGetString[‘‘string’]’
parses “string” as XML code, and returns an XMLObject.
>> Head[XML‘Parser‘XMLGetString["<a></a>"]]
XMLObject [Document]
XMLObject
WMA link
XMLObject[‘‘type’]’
represents the head of an XML object in symbolic XML.
XMLObjectImport
XML‘XMLObjectImport[‘‘string’]’
parses “string” as XML code, and returns a list of XMLObjects found.
>> Part[Import["ExampleData/Namespaces.xml"], 2]
[ ]
XMLElement title, {} , {Prime meridian - Wikipedia}
185
16. File and Stream Operations
Contents
$Input
WMA link
$Input
is the name of the stream from which input is currently being read.
>> $Input
$InputFileName
WMA link
$InputFileName
is the name of the file from which input is currently being read.
Character
WMA link
Character
is a data type for Read.
186
Close
WMA link
Close[stream]
closes an input or output stream.
>> Close[StringToStream["123abc"]]
String
>> file=Close[OpenWrite[]]
/tmp/tmp1ae0ybk7
EndOfFile
WMA link
EndOfFile
is returned by Read when the end of an input stream is reached.
Expression
WMA link
Expression
is a data type for Read.
For information about underlying data structure Expression (a kind of M-expression) that is central in
evaluation, see: AST, M-Expression, General List same thing.
FilePrint
WMA link
FilePrint[file]
prints the raw contents of file.
Find
WMA link
Find[stream, text]
find the first line in stream that contains text.
187
>> Find[stream, "uranium"]
in manuscript, leads me to expect that the element uranium may be turned into
>> Close[stream]
ExampleData/EinsteinSzilLetter.txt
>> Close[stream]
ExampleData/EinsteinSzilLetter.txt
Get (<<)
WMA link
<<name
reads a file and evaluates each expression, returning only the last one.
Get[name, Trace->True]
Runs Get tracing each line before it is evaluated.
>> Get[filename]
x+y
>> Get[filename]
Cos [x] + ISin [x]
>> DeleteFile[filename]
InputStream
WMA link
InputStream[name, n]
represents an input stream for functions such as Read or Find.
188
StringToStream opens an input stream:
>> stream = StringToStream["Mathics is cool!"]
[ ]
InputStream String, 3
>> Close[stream]
String
Number
WMA link
Number
is a data type for Read.
OpenAppend
WMA link
OpenAppend[‘‘file’]’
opens a file and returns an OutputStream to which writes are appended.
>> OpenAppend[]
[ ]
OutputStream /tmp/tmp0hi3hmgy, 3
OpenRead
WMA link
OpenRead[‘‘file’]’
opens a file and returns an InputStream.
>> Close[OpenRead["https://raw.githubusercontent.com/Mathics3/mathics-
core/master/README.rst"]];
OpenWrite
WMA link
OpenWrite[‘‘file’]’
opens a file and returns an OutputStream.
>> OpenWrite[]
[ ]
OutputStream /tmp/tmp46rnxgfg, 5
189
OutputStream
WMA link
OutputStream[name, n]
represents an output stream.
By default, the list of Streams normally OutputStream entries for stderr and stdout
>> Streams[]
{
InputStream [stdin, 0] , OutputStream [stdout, 1] , OutputStream [
[ ] [
stderr, 2] , OutputStream /tmp/tmp0hi3hmgy, 3 , InputStream
]
/src/external-vcs/github/Mathics3/mathics-core/mathics/data/ExampleData/EinsteinSzilLetter.txt, 4 , OutputS
]}
/tmp/tmp46rnxgfg, 5
Put (>>)
WMA link
>> FilePrint[filename]
815915283247897734345611269596115894272000000000
>> Get[filename]
815915283247897734345611269596115894272000000000
>> DeleteFile[filename]
>> FilePrint[filename]
3628800
2432902008176640000
265252859812191058636308480000000
>> DeleteFile[filename]
=
>> filename = $TemporaryDirectory <> "/example_file";
190
>> FilePrint[filename]
x + y
2*x^2 + 4*z!
Cos[x] + I*Sin[x]
>> DeleteFile[filename]
PutAppend (>>>)
WMA link
>> FilePrint["factorials"]
30414093201713378043612608166064768844377641568960512000000000000
>> FilePrint["factorials"]
30414093201713378043612608166064768844377641568960512000000000000
3628800
2432902008176640000
265252859812191058636308480000000
>> FilePrint["factorials"]
30414093201713378043612608166064768844377641568960512000000000000
3628800
2432902008176640000
265252859812191058636308480000000
8320987112741390144276341183223364380754172606361245952449277696409600000000000000
>> FilePrint["factorials"]
30414093201713378043612608166064768844377641568960512000000000000
3628800
2432902008176640000
265252859812191058636308480000000
8320987112741390144276341183223364380754172606361245952449277696409600000000000000
"string"
Read
WMA link
Read[stream]
reads the input stream and returns one expression.
Read[stream, type]
reads the input stream and returns an object of the given type.
type
Read[stream, type]
reads the input stream and returns an object of the given type.
Read[stream, Hold[Expression]]
reads the input stream for an Expression and puts it inside Hold.
is one of:
191
• Byte
• Character
• Expression
• HoldExpression
• Number
• Real
• Record
• String
• Word
>> stream = StringToStream["abc123"];
Read with a Hold[Expression] returns the expression it reads unevaluated so it can be later inspected
and evaluated:
>> Read[stream, Hold[Expression]]
Hold [2 + 2]
>> Close[stream];
192
Multiple lines:
>> stream = StringToStream["\"Tengo una\nvaca lechera.\""]; Read[stream]
Tengo una
vaca lechera.
ReadList
WMA link
ReadList["file"]
Reads all the expressions until the end of file.
ReadList["file", type]
Reads objects of a specified type until the end of file.
ReadList["file", {type1, type2, ...}]
Reads a sequence of specified types until the end of file.
>> ReadList[stream]
{abc123}
>> InputForm[%]
{“abc123”}
Record
WMA link
Record
is a data type for Read.
SetStreamPosition
WMA link
SetStreamPosition[stream, n]
sets the current position in a stream.
>> SetStreamPosition[stream, 8]
8
>> Read[stream, Word]
is
193
>> SetStreamPosition[stream, Infinity]
16
Skip
WMA link
Skip[stream, type]
skips ahead in an input steream by one object of the specified type.
Skip[stream, type, n]
skips ahead in an input steream by n objects of the specified type.
StreamPosition
WMA link
StreamPosition[stream]
returns the current position in a stream as an integer.
Streams
WMA link
194
Streams[]
returns a list of all open streams.
>> Streams[]
{
InputStream [stdin, 0] , OutputStream [stdout, 1] , OutputStream [
[ ] [
stderr, 2] , OutputStream /tmp/tmp0hi3hmgy, 3 , InputStream
]
/src/external-vcs/github/Mathics3/mathics-core/mathics/data/ExampleData/EinsteinSzilLetter.txt, 4 , OutputS
] [ ] [
/tmp/tmp46rnxgfg, 5 , InputStream String, 6 , InputStream
] [ ] [ ] [
String, 7 , InputStream String, 8 , InputStream String, 9 , InputStream
] [ ] [ ] [
String, 10 , InputStream String, 11 , InputStream String, 12 , InputStream
] [ ] [ ] [
String, 13 , InputStream String, 14 , InputStream String, 15 , InputStream
] [ ] [ ] [
String, 16 , InputStream String, 17 , InputStream String, 18 , InputStream
] [ ] [ ] [
String, 19 , InputStream String, 20 , InputStream String, 21 , InputStream
] [ ] [ ]}
String, 22 , InputStream String, 23 , OutputStream /tmp/tmp4wt98oxv, 24
>> Streams["stdout"]
{OutputStream [stdout, 1]}
StringToStream
WMA link
StringToStream[string]
converts a string to an open input stream.
Word
WMA link
Word
is a data type for Read.
Write
WMA link
>> Write[stream, 10 x + 15 y ^ 2]
195
>> Write[stream, 3 Sin[z]]
>> Close[stream];
>> ReadList[stream]
{ }
10x + 15y2 , 3Sin [z]
WriteString
WMA link
WriteString[stream, $str1, str2, ... ]
writes the strings to the output stream.
>> FilePrint[%]
This is a test 1This is also a test 2
>> FilePrint[%]
This is a test 1This is also a test 2
If stream is the string “stdout” or “stderr”, writes to the system standard output/ standard error chan-
nel:
>> WriteString["stdout", "Hola"]
196
17. Filesystem Operations
Contents
$BaseDirectory
WMA link
$BaseDirectory
returns the folder where user configurations are stored.
>> $BaseDirectory
/src/external-vcs/github/Mathics3/mathics-core/mathics
$HomeDirectory
WMA link
$HomeDirectory
returns the users HOME directory.
>> $HomeDirectory
/home/rocky
197
$InitialDirectory
WMA link
$InitialDirectory
returns the directory from which Mathics3 was started.
>> $InitialDirectory
/src/external-vcs/github/Mathics3/mathics-core/mathics
$InstallationDirectory
WMA link
$InstallationDirectory
returns the top-level directory in which Mathics3 was installed.
>> $InstallationDirectory
/src/external-vcs/github/Mathics3/mathics-core/mathics
$OperatingSystem
WMA link
$OperatingSystem
gives the type of operating system running Mathics.
>> $OperatingSystem
Unix
$Path
WMA link
$Path
returns the list of directories to search when looking for a file.
>> $Path
{., /home/rocky, /src/external-vcs/github/Mathics3/mathics-core/mathics/data, /src/external-vcs/github/Mat
$PathnameSeparator
WMA link
$PathnameSeparator
returns a string for the separator in paths.
198
>> $PathnameSeparator
/
$RootDirectory
WMA link
$RootDirectory
returns the system root directory.
>> $RootDirectory
/
$TemporaryDirectory
WMA link
$TemporaryDirectory
returns the directory used for temporary files.
>> $TemporaryDirectory
/tmp
$UserBaseDirectory
WMA link
$UserBaseDirectory
returns the folder where user configurations are stored.
>> $RootDirectory
/
AbsoluteFileName
WMA link
AbsoluteFileName["name"]
returns the absolute version of the given filename.
>> AbsoluteFileName["ExampleData/sunflowers.jpg"]
/src/external-vcs/github/Mathics3/mathics-core/mathics/data/ExampleData/sunflowers.jpg
CopyDirectory
WMA link
199
CopyDirectory["dir1‘‘,”dir2"]
copies directory dir1 to dir2.
CopyFile
WMA link
CopyFile["file1‘‘,”file2"]
copies file1 to file2.
>> DeleteFile["MathicsSunflowers.jpg"]
CreateDirectory
WMA link
CreateDirectory["dir"]
creates a directory called dir.
CreateDirectory[]
creates a temporary directory.
CreateFile
WMA link
CreateFile[‘‘filename’]’
Creates a file named “filename” temporary file, but do not open it.
CreateFile[]
Creates a temporary file, but do not open it.
CreateTemporary
WMA link
CreateTemporary[]
Creates a temporary file, but do not open it.
DeleteDirectory
WMA link
200
DeleteDirectory["dir"]
deletes a directory called dir.
>> DeleteDirectory[dir]
>> DirectoryQ[dir]
False
DeleteFile
WMA link
Delete["file"]
deletes file.
Delete[{"file1‘‘,”file2", ...}]
deletes a list of files.
>> DeleteFile["MathicsSunflowers.jpg"]
Directory
WMA link
Directory[]
returns the current working directory.
>> Directory[]
/src/external-vcs/github/Mathics3/mathics-core/mathics
DirectoryName
WMA link
DirectoryName["name"]
extracts the directory name from a filename.
>> DirectoryName["a/b/c"]
a/b
201
>> DirectoryName["a/b/c", 2]
a
DirectoryQ
WMA link
DirectoryQ["name"]
returns True if the directory called name exists and False otherwise.
>> DirectoryQ["ExampleData/"]
True
>> DirectoryQ["ExampleData/MythicalSubdir/"]
False
DirectoryStack
WMA link
DirectoryStack[]
returns the directory stack.
>> DirectoryStack[]
{/src/external-vcs/github/Mathics3/mathics-core/mathics}
ExpandFileName
WMA link
ExpandFileName["name"]
expands name to an absolute filename for your system.
>> ExpandFileName["ExampleData/sunflowers.jpg"]
/src/external-vcs/github/Mathics3/mathics-core/mathics/ExampleData/sunflowers.jpg
File
WMA link
File["file"]
is a symbolic representation of an element in the local file system.
FileBaseName
WMA link
202
FileBaseName["file"]
gives the base name for the specified file name.
>> FileBaseName["file.txt"]
file
>> FileBaseName["file.tar.gz"]
file.tar
FileByteCount
WMA link
FileByteCount[file]
returns the number of bytes in file.
>> FileByteCount["ExampleData/sunflowers.jpg"]
142286
FileDate
WMA link
FileDate[file, types]
returns the time and date at which the file was last modified.
>> FileDate["ExampleData/sunflowers.jpg"]
{2123, 1, 16, 3, 50, 39.9396}
FileExistsQ
WMA link
203
FileExistsQ["file"]
returns True if file exists and False otherwise.
>> FileExistsQ["ExampleData/sunflowers.jpg"]
True
>> FileExistsQ["ExampleData/sunflowers.png"]
False
FileExtension
WMA link
FileExtension["file"]
gives the extension for the specified file name.
>> FileExtension["file.txt"]
txt
>> FileExtension["file.tar.gz"]
gz
FileHash
WMA link
FileHash[file]
returns an integer hash for the given file.
FileHash[file, type]
returns an integer hash of the specified type for the given file.
The types supported are “MD5”, “Adler32”, “CRC32”, “SHA”, “SHA224”, “SHA256”,
“SHA384”, and “SHA512”.
FileHash[file, type, format]
gives a hash code in the specified format.
>> FileHash["ExampleData/sunflowers.jpg"]
109937059621979839952736809235486742106
>> FileHash["ExampleData/sunflowers.jpg", "MD5"]
109937059621979839952736809235486742106
>> FileHash["ExampleData/sunflowers.jpg", "Adler32"]
1607049478
>> FileHash["ExampleData/sunflowers.jpg", "SHA256"]
111619807552579450300684600241129773909359865098672286468229443390003894913065
FileInformation
WMA link
204
FileInformation["file"]
returns information about file.
FileNameDepth
WMA link
FileNameDepth["name"]
gives the number of path parts in the given filename.
>> FileNameDepth["a/b/c"]
3
>> FileNameDepth["a/b/c/"]
3
FileNameJoin
WMA link
FileNameJoin[{"dir_1‘‘,”dir_2", ...}]
joins the dir_i together into one path.
FileNameJoin[..., OperatingSystem->‘‘os’]’
yields a file name in the format for the specified operating system. Possible choices are “Win-
dows”, “MacOSX”, and “Unix”.
FileNameSplit
WMA link
FileNameSplit["filenames"]
splits a filename into a list of parts.
205
>> FileNameSplit["example/path/file.txt"]
{example, path, file.txt}
FileNameTake
WMA link
FileNameTake["file"]
returns the last path element in the file name name.
FileNameTake["file", n]
returns the first n path elements in the file name name.
FileNameTake["file", $-n$]
returns the last n path elements in the file name name.
FileNames
WMA link
FileNames[]
Returns a list with the filenames in the current working folder.
FileNames[form]
Returns a list with the filenames in the current working folder that matches with form.
FileNames[{form_1, form_2, ...}]
Returns a list with the filenames in the current working folder that matches with one of form_1,
form_2, ....
FileNames[{form_1, form_2, ...},{dir_1, dir_2, ...}]
Looks into the directories dir_1, dir_2, ....
FileNames[{form_1, form_2, ...},{dir_1, dir_2, ...}]
Looks into the directories dir_1, dir_2, ....
FileNames[{forms, dirs, n]
Look for files up to the level n.
FileType
WMA link
FileType["file"]
gives the type of a file, a string. This is typically File, Directory or None.
206
>> FileType["ExampleData/sunflowers.jpg"]
File
>> FileType["ExampleData"]
Directory
>> FileType["ExampleData/nonexistent"]
None
FindFile
WMA link
FindFile[name]
searches $Path for the given filename.
>> FindFile["ExampleData/sunflowers.jpg"]
/src/external-vcs/github/Mathics3/mathics-core/mathics/data/ExampleData/sunflowers.jpg
>> FindFile["VectorAnalysis‘"]
/src/external-vcs/github/Mathics3/mathics-core/mathics/packages/VectorAnalysis/Kernel/init.m
>> FindFile["VectorAnalysis‘VectorAnalysis‘"]
/src/external-vcs/github/Mathics3/mathics-core/mathics/packages/VectorAnalysis/VectorAnalysis.m
FindList
WMA link
FindList[file, text]
returns a list of all lines in file that contain text.
FindList[file, {text1, text2, ...}]
returns a list of all lines in file that contain any of the specified string.
FindList[{file1, file2, ...}, ...]
returns a list of all lines in any of the filei that contain the specified strings.
Hash
Hash function (WMA link)
207
Hash[expr]
returns an integer hash for the given expr.
Hash[expr, type]
returns an integer hash of the specified type for the given expr.
The types supported are “MD5”, “Adler32”, “CRC32”, “SHA”, “SHA224”, “SHA256”,
“SHA384”, and “SHA512”.
Hash[expr, type, format]
Returns the hash in the specified format.
Needs
WMA link
Needs["context‘"]
loads the specified context if not already in $Packages.
>> Needs["VectorAnalysis‘"]
ParentDirectory
WMA link
ParentDirectory[]
returns the parent of the current working directory.
ParentDirectory["dir"]
returns the parent dir.
>> ParentDirectory[]
/src/external-vcs/github/Mathics3/mathics-core/mathics
RenameDirectory
WMA link
RenameDirectory["dir1‘‘,”dir2"]
renames directory dir1 to dir2.
208
RenameFile
WMA link
RenameFile["file1‘‘,”file2"]
renames file1 to file2.
>> DeleteFile["MathicsSunnyFlowers.jpg"]
ResetDirectory
WMA link
ResetDirectory[]
pops a directory from the directory stack and returns it.
>> ResetDirectory[]
/src/external-vcs/github/Mathics3/mathics-core/mathics/autoload
SetDirectory
WMA link
SetDirectory[dir]
sets the current working directory to dir.
>> SetDirectory[]
/home/rocky
SetFileDate
WMA link
SetFileDate["file"]
set the file access and modification dates of file to the current date.
SetFileDate["file", date]
set the file access and modification dates of file to the specified date list.
SetFileDate["file", date, "type"]
set the file date of file to the specified date list. The "type“ can be one of ”Access“, ”Creation“,
”Modification", or All.
209
>> Close[OpenWrite[tmpfilename]];
ToFileName
WMA link
ToFileName[{"dir_1‘‘,”dir_2", ...}]
joins the dir_i together into one path.
URLSave
WMA link
URLSave[‘‘url’]’
Save “url” in a temporary file.
URLSave[‘‘url’,’ filename]
Save “url” in filename.
210
18. Forms of Input and Output
A Form format specifies the way Mathics Expression input is read or output written.
The variable $OutputForms’ of section 18 has a list of Forms defined.
See also WMA link.
Contents
Form variables
Form variables
$OutputForms
$OutputForms
contains the list of all output forms. It is updated automatically when new OutputForms are
defined by setting format values.
>> $OutputForms
{MathMLForm, TraditionalForm, FullForm, StandardForm, MatrixForm, SympyForm, PythonForm, InputForm, Tab
$PrintForms
$PrintForms
contains the list of basic print forms. It is updated automatically when new PrintForms are
defined by setting format values.
>> $PrintForms
{MathMLForm, TraditionalForm, FullForm, StandardForm, SympyForm, PythonForm, InputForm, TeXForm, MyFo
Suppose now that we want to add a new format MyForm. Initially, it does not belong to $PrintForms:
>> MemberQ[$PrintForms, MyForm]
211
Now, let’s define a format rule:
>> Format[MyForm[F[x_]]]:= "F<<" <> ToString[x] <> ">>"
BaseForm
BaseForm[expr, n]
prints numbers in expr in base n.
>> BaseForm[33, 2]
>> BaseForm[12.3, 2]
>> BaseForm[x, 2]
x
>> BaseForm[12, 3] // FullForm
BaseForm [12, 3]
FormBaseClass
Base class for a Mathics Form.
All Forms should subclass this.
FullForm
WMA link
FullForm[expr]
displays the underlying form of expr.
>> FullForm[a + b * c]
Plus [a, Times [b, c]]
212
>> FullForm[2/3]
Rational [2, 3]
GridBox
GridBox[{{...}, {...}}]
#»
is a box construct that represents a sequence of boxes arranged in a grid.
MathMLForm[TableForm[{{a,b},{c,d}}]] # = ...
InputForm
WMA link
InputForm[expr]
displays expr in an unambiguous form suitable for input.
>> InputForm[a + b * c]
a+b∗c
>> InputForm["A string"]
“A string”
>> InputForm[f’[x]]
[ ]
Derivative [1] f [x]
MakeBoxes
WMA link
MakeBoxes[expr]
is a low-level formatting primitive that converts expr to box form, without evaluating it.
\( ... \)
directly inputs box objects.
>> \( a \+ b \% c\)
UnderoverscriptBox [a, b, c]
213
>> \( a \& b \% c\)
UnderoverscriptBox [a, c, b]
>> \(x \+ y \)
[ ]
UnderscriptBox x, y
MathMLForm
WMA link
MathMLForm[expr]
displays expr as a MathML expression.
>> MathMLForm[HoldForm[Sqrt[a^3]]]
<math display="block"><msqrt> <msup><mi>a</mi>
<mn>3</mn></msup> </msqrt></math>
>> MathMLForm[\[Mu]]
<math display="block"><mi>µ</mi></math>
MatrixForm
WMA link
MatrixForm[m]
displays a matrix m, hiding the underlying list structure.
>> Array[a,{4,3}]//MatrixForm
a [1, 1] a [1, 2] a [1, 3]
a [2, 1] a [2, 2] a [2, 3]
a [3, 1] a [3, 2] a [3, 3]
a [4, 1] a [4, 2] a [4, 3]
NumberForm
NumberForm[expr, n]
prints a real number expr with n-digits of precision.
NumberForm[expr, {n, f }]
prints with n-digits and f digits to the right of the decimal point.
214
OutputForm
WMA link
OutputForm[expr]
displays expr in a plain-text form.
>> OutputForm[f’[x]]
f ′ [x]
>> OutputForm[Graphics[Rectangle[]]]
PythonForm
PythonForm[expr]
returns an approximate equivalent of expr in Python, when that is possible. We assume that
Python has SymPy imported. No explicit import will be include in the result.
>> PythonForm[Infinity]
math.inf
>> PythonForm[Pi]
sympy.pi
>> E // PythonForm
sympy.E
RowBox
WMA link
215
RowBox[{...}]
is a box construct that represents a sequence of boxes arranged in a horizontal row.
StandardForm
WMA link
StandardForm[expr]
displays expr in the default form.
>> StandardForm[a + b * c]
a + bc
>> StandardForm["A string"]
A string
>> f’[x]
f ′ [x]
SympyForm
SympyForm[expr]
returns an Sympy expr in Python. Sympy is used internally to implement a number of Mathics
functions, like Simplify.
>> SympyForm[Pi^2]
pi**2
TableForm
WMA link
TableForm[expr]
displays expr as a table.
A table of Graphics:
216
>> Table[Style[Graphics[{EdgeForm[{Black}], RGBColor[r,g,b], Rectangle
[]}], ImageSizeMultipliers->{0.2, 1}], {r,0,1,1/2}, {g,0,1,1/2}, {b
,0,1,1/2}] // TableForm
50
40
30
20
10
5 10
217
3
1
TeXForm
WMA link
TeXForm[expr]
displays expr using TeX math mode commands.
>> TeXForm[HoldForm[Sqrt[a^3]]]
\sqrt{a∧ 3}
TraditionalForm
WMA link
TraditionalForm[expr]
displays expr in a format similar to the traditional mathematical notation, where function
evaluations are represented by brackets instead of square brackets.
FormBaseClass
Base class for a Mathics Form.
All Forms should subclass this.
MakeBoxes
WMA link
MakeBoxes[expr]
is a low-level formatting primitive that converts expr to box form, without evaluating it.
\( ... \)
directly inputs box objects.
>> \( a \+ b \% c\)
UnderoverscriptBox [a, b, c]
218
>> \(x \+ y \)
[ ]
UnderscriptBox x, y
RowBox
WMA link
RowBox[{...}]
is a box construct that represents a sequence of boxes arranged in a horizontal row.
StringForm
WMA link
StringForm[str, expr1, expr2, ...]
displays the string str, replacing placeholders in str with the corresponding expressions.
219
19. Function Application
Contents
Function (&)
Function[body]
body &
represents a pure function with parameters #1, #2, etc.
Function[{x1, x2, ...}, body]
represents a pure function with parameters x1, x2, etc.
Function[{x1, x2, ...}, body, attr]
assume that the function has the attributes attr.
>> f := # ^ 2 &
>> f[3]
9
>> #^3& /@ {1, 2, 3}
{1, 8, 27}
>> #1+#2&[4, 5]
9
You can use Function with named parameters:
>> Function[{x, y}, x * y][2, 3]
6
Parameters are renamed, when necessary, to avoid confusion:
>> Function[{x}, Function[{y}, f[x, y]]][y]
[ [ ]]
Function {y$} , f y, y$
220
>> g[#] & [h[#]] & [5]
g [h [5]]
In the evaluation process, the attributes associated with an Expression are determined by its Head. If
the Head is also a non-atomic Expression, in general, no Attribute is assumed. In particular, it is what
happens when the head of the expression has the form:
“Function[body]“ or: “Function[vars, body]“
>> h := Function[{x}, Hold[1+x]]
>> h[1 + 1]
Hold [1 + 2]
Notice that Hold in the body prevents the evaluation of $1+x$, but not the evaluation of $1+1$. To avoid
that evaluation, of its arguments, the Head should have the attribute HoldAll. This behavior can be
obtained by using the three arguments form version of this expression:
>> h:= Function[{x}, Hold[1+x], HoldAll]
>> h[1+1]
Hold [1 + (1 + 1)]
In this case, the attribute HoldAll is assumed, preventing the evaluation of the argument $1+1$ before
passing it to the function body.
Slot
#n
represents the nth argument to a pure function.
#
is short-hand for #1.
#0
represents the pure function itself.
>> #
#1
Unused arguments are simply ignored:
>> {#1, #2, #3}&[1, 2, 3, 4, 5]
{1, 2, 3}
SlotSequence
##
is the sequence of arguments supplied to a pure function.
##n
starts with the nth argument.
221
>> Plus[##]& [1, 2, 3]
6
>> Plus[##2]& [1, 2, 3]
5
>> FullForm[##]
SlotSequence [1]
222
20. Functional Composition and Operator
Forms
Functional Composition is a way to combine simple functions to build more complicated ones. Like the
usual composition of functions in mathematics, the result of each function is passed as the argument of
the next, and the result of the last one is the result of the whole.
The symbolic structure of Mathics3 makes it easy to create “operators” that can be composed and ma-
nipulated symbolically-forming “pipelines” of operations-and then applied to arguments.
Some built-in functions also directly support a “curried” form, in which they can immediately be given
as symbolic operators.
Contents
Identity . . . . . . . . 224
Composition . . . . . . 223
Composition
WMA link
Composition[f , g]
returns the composition of two functions f and g.
>> Composition[]
Identity
>> Composition[][x]
x
>> Attributes[Composition]
{Flat, OneIdentity, Protected}
Identity
WMA link
223
Identity[x]
is the identity function, which returns x unchanged.
>> Identity[x]
x
>> Identity[x, y]
[ ]
Identity x, y
224
21. Functional Programming
Functional programming is a programming paradigm where programs are constructed by applying
and composing functions.
It is made richer by expressions like f [x] being treating as symbolic data.
This is term is often used in contrast to Procedural programming.
Contents
Apply (@@)
Apply[f , expr]
f @@ expr
replaces the head of expr with f.
Apply[f , expr, levelspec]
applies f on the parts specified by levelspec.
>> f @@ {1, 2, 3}
f [1, 2, 3]
225
Apply on level 1:
>> Apply[f, {a + b, g[c, d, e * f], 3}, {1}]
{ [ ] }
f [a, b] , f c, d, e f , 3
List
WMA link
Map (/@)
>> f /@ {1, 2, 3}
{ f [1] , f [2] , f [3]}
Include heads:
226
>> Map[f, a + b + c, Heads->True]
[ ]
f [Plus] f [a] , f [b] , f [c]
MapAt
MapAt[f , expr, n]
applies f to the element at position n in expr. If n is negative, the position is counted from the
end.
MapAt[f, expr, {i, j ...}]
applies f to the part of expr at position {i, j, ...}.
MapAt[f ,pos]
represents an operator form of MapAt that can be applied to an expression.
MapIndexed
MapIndexed[f , expr]
applies f to each part on the first level of expr, including the part positions in the call to f.
MapIndexed[f , expr, levelspec]
applies f to each level specified by levelspec of expr.
227
>> MapIndexed[f, {a, b, c}, Heads->True]
[ ][ [ ] [ ] [ ]]
f List, {0} f a, {1} , f b, {2} , f c, {3}
Get the positions of atoms in an expression (convert operations to List first to disable Listable func-
tions):
>> expr = a + b * f[g] * c ^ e;
The positions are given in the same format as used by Extract. Thus, mapping Extract on the indices
given by MapIndexed re-constructs the original expression:
>> MapIndexed[Extract[expr, #2] &, listified, {-1}, Heads -> True]
[ ]
a + b f g ce
MapThread
>> MapThread[f, {{{a, b}, {c, d}}, {{e, f}, {g, h}}}, 2]
{{ [ ]} { [ ] }}
f [a, e] , f b, f , f c, g , f [d, h]
Scan
Scan[f , expr]
applies f to each element of expr and returns Null.
’Scan[f, expr, levelspec]
applies f to each level specified by levelspec of expr.
228
Thread
Thread[f [args]]
threads f over any lists that appear in args.
Thread[f [args], h]
threads over any parts with head h.
Function Application
Function Application
Function (&)
Function[body]
body &
represents a pure function with parameters #1, #2, etc.
Function[{x1, x2, ...}, body]
represents a pure function with parameters x1, x2, etc.
Function[{x1, x2, ...}, body, attr]
assume that the function has the attributes attr.
>> f := # ^ 2 &
>> f[3]
9
>> #^3& /@ {1, 2, 3}
{1, 8, 27}
>> #1+#2&[4, 5]
9
You can use Function with named parameters:
>> Function[{x, y}, x * y][2, 3]
6
Parameters are renamed, when necessary, to avoid confusion:
229
>> Function[{x}, Function[{y}, f[x, y]]][y]
[ [ ]]
Function {y$} , f y, y$
In the evaluation process, the attributes associated with an Expression are determined by its Head. If
the Head is also a non-atomic Expression, in general, no Attribute is assumed. In particular, it is what
happens when the head of the expression has the form:
“Function[body]“ or: “Function[vars, body]“
>> h := Function[{x}, Hold[1+x]]
>> h[1 + 1]
Hold [1 + 2]
Notice that Hold in the body prevents the evaluation of $1+x$, but not the evaluation of $1+1$. To avoid
that evaluation, of its arguments, the Head should have the attribute HoldAll. This behavior can be
obtained by using the three arguments form version of this expression:
>> h:= Function[{x}, Hold[1+x], HoldAll]
>> h[1+1]
Hold [1 + (1 + 1)]
In this case, the attribute HoldAll is assumed, preventing the evaluation of the argument $1+1$ before
passing it to the function body.
Slot
#n
represents the nth argument to a pure function.
#
is short-hand for #1.
#0
represents the pure function itself.
>> #
#1
Unused arguments are simply ignored:
>> {#1, #2, #3}&[1, 2, 3, 4, 5]
{1, 2, 3}
230
>> If[#1<=1, 1, #1 #0[#1-1]]& [10]
3628800
SlotSequence
##
is the sequence of arguments supplied to a pure function.
##n
starts with the nth argument.
Composition
WMA link
Composition[f , g]
returns the composition of two functions f and g.
>> Composition[]
Identity
>> Composition[][x]
x
>> Attributes[Composition]
{Flat, OneIdentity, Protected}
231
>> Composition[f, Composition[g, h]]
[ ]
Composition f , g, h
Identity
WMA link
Identity[x]
is the identity function, which returns x unchanged.
>> Identity[x]
x
>> Identity[x, y]
[ ]
Identity x, y
FixedPoint
FixedPoint[f , expr]
starting with expr, iteratively applies f until the result no longer changes.
FixedPoint[f , expr, n]
performs at most n iterations. The same that using $MaxIterations->n$
FixedPointList
FixedPointList[f , expr]
starting with expr, iteratively applies f until the result no longer changes, and returns a list of
all intermediate results.
FixedPointList[f , expr, n]
performs at most n iterations.
232
>> newton[9]
{1., 5., 3.4, 3.02353, 3.00009, 3., 3., 3.}
>> collatz[x_] := 3 x + 1;
>> ListLinePlot[list]
Fold
Fold[f , x, list]
returns the result of iteratively applying the binary operator f to each element of list, starting
with x.
Fold[f , list]
is equivalent to Fold[f , First[list], Rest[list]].
FoldList
FoldList[f , x, list]
returns a list starting with x, where each element is the result of applying the binary operator
f to the previous result and the next element of list.
FoldList[f , list]
is equivalent to FoldList[f , First[list], Rest[list]].
233
>> FoldList[f, x, {1, 2, 3}]
{ [ ] [ [ ] ]}
x, f [x, 1] , f f [x, 1] , 2 , f f f [x, 1] , 2 , 3
Nest
Nest[f , expr, n]
starting with expr, iteratively applies f n times and returns the final result.
>> Nest[f, x, 3]
[ [ ]]
f f f [x]
NestList
NestList[f , expr, n]
starting with expr, iteratively applies f n times and returns a list of all intermediate results.
>> NestList[f, x, 3]
{ [ ] [ [ ]]}
x, f [x] , f f [x] , f f f [x]
234
NestWhile
371
235
22. Functions used in Quantum Mechanics
Contents
Angular Momentum
Angular Momentum
Angular momentum in physics is the rotational analog of linear momentum. It is an important quantity
in physics because it is a conserved quantity the total angular momentum of a closed system remains
constant.
ClebschGordan
Clebsch-Gordan coefficients matrices (SymPy, WMA)
PauliMatrix
Pauli matrices (SymPy, WMA)
PauliMatrix[k]
returns the kth Pauli spin matrix).
236
>> Table[PauliMatrix[i], {i, 1, 3}]
{{{0, 1} , {1, 0}} , {{0, − I } , { I, 0}} , {{1, 0} , {0, −1}}}
SixJSymbol
6-j symbol (SymPy, WMA)
237
ThreeJSymbol
3-j symbol (SymPy, WMA)
238
23. Global System Information
Contents
$CommandLine
WMA link
$CommandLine
is a list of strings passed on the command line to launch the Mathics session.
>> $CommandLine
{docpipeline.py, –output, –keep-going, –want-sorting, –load-module, pymathics.graph,pymathics.natlang}
$Machine
WMA link
$Machine
returns a string describing the type of computer system on which the Mathics is being run.
>> $Machine
linux
$MachineName
WMA link
$MachineName
is a string that gives the assigned name of the computer on which Mathics is being run, if such
a name is defined.
>> $MachineName
muffin
239
$Packages
WMA link
$Packages
returns a list of the contexts corresponding to all packages which have been loaded into Math-
ics.
>> $Packages
{ImportExport‘, XML‘, Internal‘, System‘, Global‘}
$ParentProcessID
WMA link
$ParentProcesID
gives the ID assigned to the process which invokes the Mathics3 by the operating system under
which it is run.
>> $ParentProcessID
83042
$ProcessID
WMA link
$ProcessID
gives the ID assigned to the Mathics3 process by the operating system under which it is run.
>> $ProcessID
83043
$ProcessorType
WMA link
$ProcessorType
gives a string giving the architecture of the processor on which the Mathics3 is being run.
>> $ProcessorType
x86_64
$PythonImplementation
$PythonImplementation
gives a string indication the Python implementation used to run Mathics3.
240
>> $PythonImplementation
CPython 3.10.10.final.0
$ScriptCommandLine
WMA link
$ScriptCommandLine
is a list of string arguments when running the kernel is script mode.
>> $ScriptCommandLine
{}
$SystemID
WMA link
$SystemID
is a short string that identifies the type of computer system on which the Mathics3 is being
run.
>> $SystemID
linux
$SystemMemory
WMA link
$SystemMemory
Returns the total amount of physical memory.
>> $SystemMemory
33611120640
$SystemWordLength
WMA link
$SystemWordLength
gives the effective number of bits in raw machine words on the computer system where Math-
ics3 is running.
>> $SystemWordLength
64
241
$UserName
WMA link
$UserName
returns the login name, according to the operative system, of the user that started the current
Mathics3 session.
>> $UserName
rocky
$Version
WMA link
$Version
returns a string with the current Mathics version and the versions of relevant libraries.
>> $Version
Mathics 6.0.0 on CPython 3.10.10 (main, Feb 22 2023, 17:18:27) [GCC 11.3.0]
using SymPy 1.11.1, mpmath 1.2.1, numpy 1.24.0, cython Not installed
$VersionNumber
WMA link
$VersionNumber
is a real number which gives the current Wolfram Language version that Mathics3 tries to be
compatible with.
>> $VersionNumber
10.
Environment
WMA link
Environment[var]
gives the value of an operating system environment variable.
>> Environment["HOME"]
/home/rocky
GetEnvironment
WMA link
GetEnvironment["var"]
gives the setting corresponding to the variable “var” in the operating system environment.
242
>> GetEnvironment["HOME"]
MathicsVersion
MathicsVersion
this string is the version of Mathics we are running.
>> MathicsVersion
6.0.0
MemoryAvailable
WMA link
MemoryAvailable
Returns the amount of the available physical memory.
>> MemoryAvailable[]
21087191040
The relationship between $SystemMemory, MemoryAvailable, and MemoryInUse:
>> $SystemMemory > MemoryAvailable[] > MemoryInUse[]
True
MemoryInUse
WMA link
MemoryInUse[]
Returns the amount of memory used by all of the definitions objects if we can determine that;
-1 otherwise.
>> MemoryInUse[]
48
Run
WMA link
Run[command]
runs command as an external operating system command, returning the exit code obtained.
>> Run["date"]
0
243
Share
WMA link
Share[]
release memory forcing Python to do garbage collection. If Python package is psutil installed
is the amount of released memoryis returned. Otherwise returns 0. This function differs from
WMA which tries to reduce the amount of memory required to store definitions, by reducing
duplicated definitions.
Share[Symbol]
Does the same thing as Share[]; Note: this function differs from WMA which tries to reduce
the amount of memory required to store definitions associated to Symbol.
>> Share[]
1904640
244
24. Graphics and Drawing
Showing something visually can be done in a number of ways:
• Starting with complete images and modifying them using the Image Built-in function.
• Use pre-defined 2D or 3D objects like Circle of section 12 and Cuboid of section ?? and place
them in a coordinate space.
• Compute the points of the space using a function. This is done using functions like Plot of sec-
tion ?? and ListPlot of section ??.
Contents
Plotting Data
Plotting Data
Plotting functions take a function as a parameter and data, often a range of points, as another parameter,
and plot or show the function applied to the data.
BarChart
WMA link
BarChart[{b1, b2 ...}]
Draw-
makes a bar chart with lengths b1, b2, ....
245
• Axes (default {False, True})
• AspectRatio: (default 1 / GoldenRatio)
A bar chart of a list of heights:
>> BarChart[{1, 4, 2}]
20
15
10
20 40 60 80 100
246
>> BarChart[{{1, 2, 3}, {2, 3, 4}}, ChartLabels -> {"a", "b", "c"}]
25
20
15
10
20 40 60 80 100
0.5
10 20 30
−0.5
−1.0
ColorData
WMA link
ColorData["name"]
returns a color function with the given name.
247
>> {DensityPlot[x + y, {x, -1, 1}, {y, -1, 1}], DensityPlot[x + y, {x,
-1, 1}, {y, -1, 1}, ColorFunction->"test"]}
12 5
10
4
8
3
6
2
4
1
2
200 400 600 800 1000 , 20 40 60 80 100 120
ColorDataFunction
WMA link
ColorDataFunction[range, ...]
is a function that represents a color scheme.
DensityPlot
WMA link
3.0
2.5
2.0
1.5
1.0
0.5
2 4 6 8 10
248
>> DensityPlot[1 / x, {x, 0, 1}, {y, 0, 1}]
−1
31.6228
10
3.16228
2 4 6 8 10
>> DensityPlot[1/(x^2 + y^2 + 1), {x, -1, 1}, {y, -2,2}, Mesh->Full]
1000000
100000
10000
1000
100
10
2 4 6 8 10
100
80
60
40
20
5 10 15 20 25 30
DiscretePlot
WMA link
249
DiscretePlot[expr, {x, n_max}]
plots expr with x ranging from 1 to n_max.
DiscretePlot[expr, {x, n_min, n_max}]
plots expr with x ranging from n_min to n_max.
DiscretePlot[expr, {x, n_min, n_max, dn}]
plots expr with x ranging from n_min to n_max usings steps dn.
DiscretePlot[{expr1, expr2, ...}, ...]
plots the values of all expri.
100
80
60
40
20
5 10 15 20 25 30
800
600
400
200
5 10 15 20 25 30
Notice in the above that when the starting value, n_min, is 1, we can omit it.
A plot can contain several functions, using the same parameter, here x:
>> DiscretePlot[{Sin[Pi x/20], Cos[Pi x/20]}, {x, 0, 40}]
800
600
400
200
5 10 15 20 25 30
Graphics
WMA link
250
Graphics[primitives, options]
represents a graphic.
Options include:
• Axes
• TicksStyle
• AxesStyle
• LabelStyle
• AspectRatio
• PlotRange
• PlotRangePadding
• ImageSize
• Background
>> Graphics[{Blue, Line[{{0,0}, {1,1}}]}]
3162.28
1000
316.228
100
31.6228
10
3.16228
1 2 3 4 5
316.228
100
31.6228
10
3.16228
1 2 3 4 5
>> Graphics[{Rectangle[],Red,Disk[{1,0}]},PlotRange->{{0,1},{0,1}}]
5 10 15 20 25
251
>> Graphics[Circle[]] // TeXForm
\begin{asy}
usepackage("amsmath");
size(5.8556cm, 5.8333cm);
draw(ellipse((175,175),175,175), rgb(0, 0, 0)+linewidth(0.66667));
clip(box((-0.33333,0.33333), (350.33,349.67)));
\end{asy}
Graphics3D
WMA link
Graphics3D[primitives, options]
represents a three-dimensional graphic.
See also the Section “Plotting” for a list of Plot options.
20 40 60 80 100
\begin{asy}
import three;
import solids;
size(6.6667cm, 6.6667cm);
currentprojection=perspective(2.6,-4.8,4.0);
currentlight=light(rgb(0.5,0.5,1), specular=red, (2,0,2), (2,2,2), (0,2,2));
// Sphere3DBox
draw(surface(sphere((0, 0, 0), 1)), rgb(1,1,1)+opacity(1));
draw(((-1,-1,-1)–(1,-1,-1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,1,-1)–(1,1,-1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,-1,1)–(1,-1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,1,1)–(1,1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,-1,-1)–(-1,1,-1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((1,-1,-1)–(1,1,-1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,-1,1)–(-1,1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((1,-1,1)–(1,1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,-1,-1)–(-1,-1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((1,-1,-1)–(1,-1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,1,-1)–(-1,1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((1,1,-1)–(1,1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
\end{asy}
252
Histogram
Histogram (WMA link)
Histogram[{x1, x2 ...}]
plots a histogram using the values x1, x2, ....
>> Histogram[{3, 8, 10, 100, 1000, 500, 300, 200, 10, 20, 200, 100, 200,
300, 500}]
1.0
0.5
−0.5
−1.0
>> Histogram[{{1, 2, 10, 5, 50, 20}, {90, 100, 101, 120, 80}}]
0.4
0.2
−0.2
−0.4
ListLinePlot
WMA link
ListLinePlot[{y_1, y_2, ...}]
plots a line through a list of y-values, assuming integer x-values 1, 2, 3, ...
ListLinePlot[{{x_1, y_1}, {x_2, y_2}, ...}]
plots a line through a list of x, y pairs.
ListLinePlot[{list_1, list_2, ...}]
plots several lines.
253
>> ListLinePlot[Table[{n, n ^ 0.5}, {n, 10}]]
1.0
0.5
−0.5
−1.0
Dogs
Fish
Cats
ListLogPlot
WMA link
ListLogPlot[{y_1, y_2, ...}]
log plots a list of y-values, assuming integer x-values 1, 2, 3, ...
ListLogPlot[{{x_1, y_1}, {x_2, y_2}, ...}]
log plots a list of x, y pairs.
ListLogPlot[{list_1, list_2, ...}]
log plots several lists of points.
254
>> ListLogPlot[Table[Fibonacci[n], {n, 10}]]
we see that Fibonacci numbers grow exponentially. So when plotted using on a log scale the result fits
points of a sloped line.
>> ListLogPlot[Table[n!, {n, 10}], Joined -> True]
ListPlot
WMA link
ListPlot[{y_1, y_2, ...}]
plots a list of y-values, assuming integer x-values 1, 2, 3, ...
ListPlot[{{x_1, y_1}, {x_2, y_2}, ...}]
plots a list of x, y pairs.
ListPlot[{list_1, list_2, ...}]
plots several lists of points.
255
>> ListPlot[Prime[Range[30]]]
A B
256
>> ListPlot[Table[n ^ 2, {n, 30}], Filling->Axis]
1.0
0.5
−3 −2 −1 1 2 3
−0.5
−1.0
LogPlot
Semi-log plot (WMA link)
1.0
0.5
2 4 6 8 10 12
10
−6 −4 −2 2 4 6
−5
−10
−15
NumberLinePlot
WMA link
NumberLinePlot[{v_1, v_2, ...}]
plots a list of values along a line.
257
>> NumberLinePlot[Prime[Range[10]]]
0.8
0.6
0.4
0.2
Compare with:
>> NumberLinePlot[Table[x^2, {x, 10}]]
1.5
1.0
0.5
1 2 3 4 5
−0.5
−1.0
ParametricPlot
WMA link
10
−1 1 2 3 4 5
258
>> ParametricPlot[{Cos[u] / u, Sin[u] / u}, {u, 0, 50}, PlotRange->0.5]
6
PieChart
Pie Chart (WMA link)
PieChart[{a1, a2 ...}]
draws a pie chart with sector angles proportional to a1, a2, ....
259
>> PieChart[{30, 20, 10}, ChartLabels -> {Dogs, Cats, Fish}]
Same as the above, but without gaps between the groups of data:
260
>> PieChart[{{10, 20, 30}, {15, 22, 30}}, SectorSpacing -> None]
0.5
−0.5
−1.0
Negative values are removed, the data below is the same as {1, 3}:
>> PieChart[{1, -1, 3}]
1.0
0.8
0.6
0.4
0.2
Plot
WMA link
261
Plot[f , {x, xmin, xmax}]
plots f with x ranging from xmin to xmax.
Plot[{f1, f2, ...}, {x, xmin, xmax}]
plots several functions f1, f2, ...
1.0
0.5
−0.5
−1.0
−5 5
−5
262
>> Plot[Log[x], {x, 0, 5}, MaxRecursion->0]
A constant function:
263
>> Plot[3, {x, 0, 1}]
Plot3D
WMA link
264
>> Plot3D[Sin[y + Sin[3 x]], {x, -2, 2}, {y, -2, 2}, PlotPoints->20]
>> Plot3D[x / (x ^ 2 + y ^ 2 + 1), {x, -2, 2}, {y, -2, 2}, Mesh->None]
>> Plot3D[Sin[x y] /(x y), {x, -3, 3}, {y, -3, 3}, Mesh->All]
265
>> Plot3D[Log[x + y^2], {x, -1, 1}, {y, -1, 1}]
PolarPlot
WMA link
266
>> PolarPlot[Abs[Cos[5t]], {t, 0, Pi}]
267
>> PolarPlot[Sqrt[t], {t, 0, 16 Pi}]
Splines
Splines
A Spline is a mathematical function used for interpolation or smoothing. Splines are used both in
graphics and computation
BernsteinBasis
Bernstein polynomial basis (SciPy :WMA:
A Bernstein is a polynomial that is a linear combination of Bernstein basis polynomials. With the ad-
vent of computer graphics, Bernstein polynomials, restricted to the interval [0, 1], became important in
the form of Bézier curves. BernsteinBasis[d,n,x] equals Binomial[d, n] x^n (1-x)^(d-n) in the
interval [0, 1] and zero elsewhere.
BernsteinBasis[d,n,x]
returns the nth Bernstein basis of degree d at x.
BezierCurve
WMA link
BezierCurve[{pt_1, pt_2 ...}]
represents a Bézier curve with control points p_i.
The result is a curve by combining the Bézier curves when points are taken triples at a time.
Option:
• SplineDegree->d specifies that the underlying polynomial basis should have maximal degree d.
Set up some points to form a simple zig-zag...
>> pts = {{0, 0}, {1, 1}, {2, -1}, {3, 0}};
268
>> Graphics[{Line[pts], Red, Point[pts]}]
A composite Bézier curve, shown in blue, smooths the zig zag. Control points are shown in red:
>> Graphics[{BezierCurve[pts], Blue, Line[pts], Red, Point[pts]}]
Extend points...
>> pts = {{0, 0}, {1, 1}, {2, -1}, {3, 0}, {5, 2}, {6, -1}, {7, 3}};
=
A longer composite Bézier curve and its control points:
>> Graphics[{BezierCurve[pts], Blue, Line[pts], Red, Point[pts]}]
Notice how the curve from the first to third point is not changed by any points outside the interval. The
same is true for points three to five, and so on.
BezierFunction
WMA link
BezierFunction[{pt_1, pt_2, ...}]
returns a Bézier function for the curve defined by points pt_i. The embedding dimension for
the curve represented by BezierFunction[{pt_1,pt_2,...}] is given by the length of the lists
pt_i.
=
>> f[.5]
{1.5, 0.625}
=
Plotting the Bézier Function accoss a Bézier curve:
269
>> Module[{p={{0, 0},{1, 1},{2, -1},{4, 0}}}, Graphics[{BezierCurve[p],
Red, Point[Table[BezierFunction[p][x], {x, 0, 1, 0.1}]]}]]
Three-Dimensional Graphics
Three-Dimensional Graphics
Functions for working with 3D graphics.
Cone
WMA link
Cone[{{x1, y1, z1}, {x2, y2, z2}}]
represents a cone of radius 1.
Cone[{{x1, y1, z1}, {x2, y2, z2}}, r]
is a cone of radius r starting at (x1, y1, z1) and ending at (x2, y2, z2).
Cone[{{x1, y1, z1}, {x2, y2, z2}, ... }, r]
is a collection cones of radius r.
270
>> Graphics3D[{Yellow, Cone[{{-1, 0, 0}, {1, 0, 0}, {0, 0, Sqrt[3]}, {1,
1, Sqrt[3]}}, 1]}]
Cuboid
WMA link
Cuboid also known as interval, rectangle, square, cube, rectangular parallelepiped, tesseract, orthotope,
and box.
Cuboid[p_min]
is a unit cube/square with its lower corner at point p_min.
’Cuboid[p_min, p_max]
is a 2d square with with lower corner p_min and upper corner p_max.
Cuboid[{p_min, p_max}]
is a cuboid with lower corner p_min and upper corner p_max.
Cuboid[{p1_min, p1_max, ...}]
is a collection of cuboids.
Cuboid[] is equivalent to Cuboid[{0,0,0}].
271
>> Graphics3D[{Red, Cuboid[{{0, 0, 0}, {1, 1, 0.5}}], Blue, Cuboid
[{{0.25, 0.25, 0.5}, {0.75, 0.75, 1}}]}]
15
10
Cylinder
WMA link
Cylinder[{{x1, y1, z1}, {x2, y2, z2}}]
represents a cylinder of radius 1.
Cylinder[{{x1, y1, z1}, {x2, y2, z2}}, r]
is a cylinder of radius r starting at (x1, y1, z1) and ending at (x2, y2, z2).
Cylinder[{{x1, y1, z1}, {x2, y2, z2}, ... }, r]
is a collection cylinders of radius r.
1.5
1.0
0.5
1 2 3 4 5
−0.5
−1.0
272
>> Graphics3D[{Yellow, Cylinder[{{-1, 0, 0}, {1, 0, 0}, {0, 0, Sqrt[3]},
{1, 1, Sqrt[3]}}, 1]}]
1.5
1.0
0.5
−10 −5 5 10
−0.5
−1.0
−1.5
Graphics
WMA link
Graphics[primitives, options]
represents a graphic.
Options include:
• Axes
• TicksStyle
• AxesStyle
• LabelStyle
• AspectRatio
• PlotRange
• PlotRangePadding
• ImageSize
• Background
>> Graphics[{Blue, Line[{{0,0}, {1,1}}]}]
−6 −4 −2 2 4 6
−1
−2
273
>> Graphics[{Rectangle[{1, 1}]}, Axes -> True, PlotRange -> {{-2, 1.5},
{-1, 1.5}}]
>> Graphics[{Rectangle[],Red,Disk[{1,0}]},PlotRange->{{0,1},{0,1}}]
\begin{asy}
usepackage("amsmath");
size(5.8556cm, 5.8333cm);
draw(ellipse((175,175),175,175), rgb(0, 0, 0)+linewidth(0.66667));
clip(box((-0.33333,0.33333), (350.33,349.67)));
\end{asy}
Graphics3D
WMA link
Graphics3D[primitives, options]
represents a three-dimensional graphic.
See also the Section “Plotting” for a list of Plot options.
274
>> Graphics3D[Polygon[{{0,0,0}, {0,1,1}, {1,0,0}}]]
1.0
0.5
−3 −2 −1 1 2 3
−0.5
−1.0
\begin{asy}
import three;
import solids;
size(6.6667cm, 6.6667cm);
currentprojection=perspective(2.6,-4.8,4.0);
currentlight=light(rgb(0.5,0.5,1), specular=red, (2,0,2), (2,2,2), (0,2,2));
// Sphere3DBox
draw(surface(sphere((0, 0, 0), 1)), rgb(1,1,1)+opacity(1));
draw(((-1,-1,-1)–(1,-1,-1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,1,-1)–(1,1,-1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,-1,1)–(1,-1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,1,1)–(1,1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,-1,-1)–(-1,1,-1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((1,-1,-1)–(1,1,-1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,-1,1)–(-1,1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((1,-1,1)–(1,1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,-1,-1)–(-1,-1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((1,-1,-1)–(1,-1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((-1,1,-1)–(-1,1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
draw(((1,1,-1)–(1,1,1)), rgb(0.4, 0.4, 0.4)+linewidth(1));
\end{asy}
RGBColor
WMA link
RGBColor[r, g, b]
represents a color with the specified red, green and blue components.
275
>> Graphics[MapIndexed[{RGBColor @@ #1, Disk[2*#2 ~Join~{0}]} &,
IdentityMatrix[3]], ImageSize->Small]
−4 −2 2 4
>> RGBColor[0, 1, 0]
1.0
0.5
1 2 3 4 5 6
−0.5
−1.0
Sphere
WMA link
Sphere[{x, y, z}]
is a sphere of radius 1 centered at the point {x, y, z}.
Sphere[{x, y, z}, r]
is a sphere of radius r centered at the point {x, y, z}.
Sphere[{{x1, y1, z1}, {x2, y2, z2}, ... }, r]
is a collection spheres of radius r centered at the points {x1, y2, z2}, {x2, y2, z2}, ...
276
>> Graphics3D[Sphere[{0, 0, 0}, 1]]
0.5
−0.5
−1.0
−1.5
−2.0
1.0
0.5
1 2 3 4 5 6
−0.5
−1.0
Tube
WMA link
Tube[{p1, p2, ...}]
represents a tube passing through p1, p2, ... with radius 1.
Tube[{p1, p2, ...}, r]
represents a tube with radius r.
1.5
1.0
0.5
277
>> Graphics3D[Tube[{{0,0,0}, {1,1,1}, {0, 0, 1}}, 0.1]]
250
200
150
100
50
20 40 60 80 100 120
Uniform Polyhedra
Uniform Polyhedra
Uniform polyhedra is the grouping of platonic solids, Archimedean solids,and regular star polyhedra.
Dodecahedron
WMA link
Dodecahedron[]
a regular dodecahedron centered at the origin with unit edge length.
>> Graphics3D[Dodecahedron[]]
0.4
0.2
−10 −5 5 10
−0.2
−0.4
Icosahedron
WMA link
Icosahedron[]
a regular Icosahedron centered at the origin with unit edge length.
278
>> Graphics3D[Icosahedron[]]
1.5
1.0
0.5
−10 −8 −6 −4 −2 2
−0.5
Octahedron
WMA link
Octahedron[]
a regular octahedron centered at the origin with unit edge length.
0.4
0.2
−10 −5 5 10
−0.2
−0.4
−0.6
Tetrahedron
WMA link
Tetrahedron[]
a regular tetrahedron centered at the origin with unit edge length.
15
10
1 2 3 4 5
279
UniformPolyhedron
WMA link
UniformPolyhedron[‘‘name’]’
return a uniform polyhedron with the given name.
Names are “tetrahedron”, “octahedron”, “dodecahedron”, or “icosahedron”.
>> Graphics3D[UniformPolyhedron["octahedron"]]
0.8
0.6
0.4
0.2
2 4 6 8 10
−0.2
−0.4
>> Graphics3D[UniformPolyhedron["dodecahedron"]]
1.2
1.0
0.8
0.6
0.4
0.2
1 2 3 4 5
280
25. Image Manipulation
For the full compliment of functions, you need to have scikit-image installed.
Contents
Blur
WMA link
Blur[image]
gives a blurred version of image.
Blur[image, r]
blurs image with a kernel of size r.
281
>> Blur[hedy]
>> Blur[hedy, 5]
ImageAdjust
WMA link
282
ImageAdjust[image]
adjusts the levels in image.
ImageAdjust[image, c]
adjusts the contrast in image by c.
ImageAdjust[image, {c, b}]
adjusts the contrast c, and brightness b in image.
ImageAdjust[image, {c, b, g}]
adjusts the contrast c, brightness b, and gamma g in image.
>> ImageAdjust[hedy]
ImagePartition
WMA link
ImagePartition[image, s]
Partitions an image into an array of s x s pixel subimages.
ImagePartition[image, {w, h}]
Partitions an image into an array of w x h pixel subimages.
>> ImageDimensions[hedy]
{646, 800}
283
Sharpen
WMA link
Sharpen[image]
gives a sharpened version of image.
Sharpen[image, r]
sharpens image with a kernel of size r.
>> Sharpen[hedy]
>> Sharpen[hedy, 5]
284
Threshold
WMA link
Threshold[image]
gives a value suitable for binarizing image.
The option “Method” may be “Cluster” (use Otsu’s threshold), “Median”, or “Mean”.
>> img = Import["ExampleData/hedy.tif"];
>> Threshold[img]
0.408203
>> Binarize[img, %]
Geometric Operations
Geometric Operation
ImageReflect
WMA link
285
ImageReflect[image]
Flips image top to bottom.
ImageReflect[image, side]
Flips image so that side is interchanged with its opposite.
ImageReflect[image, side_1 -> side_2]
Flips image so that side_1 is interchanged with side_2.
>> ImageReflect[ein]
286
ImageResize
WMA link
ImageResize[image, width]
ImageResize[image, {width, height}]
The Resampling option can be used to specify how to resample the image. Options are:
• Automatic
• Bicubic
• Bilinear
• Box
• Hamming
• Lanczos
• Nearest
See Pillow Filters for a description of these.
>> alice = Import["ExampleData/MadTeaParty.gif"]
The default sampling method is “Bicubic” which has pretty good upscaling and downscaling quality.
However “Box” is the fastest:
>> ImageResize[alice, shape / 2, Resampling -> "Box"]
287
ImageRotate
WMA link
ImageRotate[image]
Rotates image 90 degrees counterclockwise.
ImageRotate[image, theta]
Rotates image by a given angle theta
>> ImageRotate[ein]
288
>> ImageRotate[ein, Pi / 4]
Image Colors
Image Color
Binarize
WMA link
Binarize[image]
gives a binarized version of image, in which each pixel is either 0 or 1.
Binarize[image, t]
map values x > t to 1, and values x <= t to 0.
Binarize[image, {t1, t2}]
map t1 < x < t2 to 1, and all other values to 0.
289
>> Binarize[hedy]
290
>> Binarize[hedy, {0.2, 0.6}]
ColorCombine
WMA link
ColorCombine[channels, colorspace]
Gives an image with colorspace and the respective components described by the given chan-
nels.
>> ColorCombine[{{{1, 0}, {0, 0.75}}, {{0, 1}, {0, 0.25}}, {{0, 0}, {1,
0.5}}}, "RGB"]
ColorQuantize
WMA link
ColorQuantize[image, n]
gives a version of image using only n colors.
291
>> ColorQuantize[img, 6]
ColorSeparate
WMA link
ColorSeparate[image]
Gives each channel of image as a separate grayscale image.
>> ColorSeparate[img]
Colorize
WMA link
Colorize[values]
returns an image where each number in the rectangular matrix values is a pixel and each
occurrence of the same number is displayed in the same unique color, which is different from
the colors of all non-identical numbers.
Colorize[image]
gives a colorized version of image.
>> Colorize[{{1.3, 2.1, 1.5}, {1.3, 1.3, 2.1}, {1.3, 2.1, 1.5}}]
292
>> Colorize[{{1, 2}, {2, 2}, {2, 3}}, ColorFunction -> (Blend[{White,
Blue}, #]&)]
ImageColorSpace
WMA link
ImageColorSpace[image]
gives image’s color space, e.g. “RGB” or “CMYK”.
>> ImageColorSpace[img]
>> ImageColorSpace[img]
Image Compositions
Image Composition
ImageAdd
WMA link
>> i = Image[{{0, 0.5, 0.2, 0.1, 0.9}, {1.0, 0.1, 0.3, 0.8, 0.6}}];
>> ImageAdd[i, i]
293
>> ImageAdd[noise, ein]
ImageMultiply
WMA link
294
>> i = Image[{{0, 0.5, 0.2, 0.1, 0.9}, {1.0, 0.1, 0.3, 0.8, 0.6}}];
>> ImageMultiply[i, i]
ImageSubtract
WMA link
>> i = Image[{{0, 0.5, 0.2, 0.1, 0.9}, {1.0, 0.1, 0.3, 0.8, 0.6}}];
>> ImageSubtract[i, i]
WordCloud
WMA link
295
WordCloud[{word1, word2, ...}]
Gives a word cloud with the given list of words.
WordCloud[{weight1 -> word1, weight2 -> word2, ...}]
Gives a word cloud with the words weighted using the given weights.
WordCloud[{weight1, weight2, ...} -> {word1, word2, ...}]
Also gives a word cloud with the words weighted using the given weights.
WordCloud[{{word1, weight1}, {word2, weight2}, ...}]
Gives a word cloud with the words weighted using the given weights.
>> WordCloud[StringSplit[Import["ExampleData/EinsteinSzilLetter.txt",
CharacterEncoding->"UTF8"]]]
Image Filters
Image Filter
GaussianFilter
WMA link
296
GaussianFilter[image, r]
blurs image using a Gaussian blur filter of radius r.
ImageConvolve
WMA link
ImageConvolve[image, kernel]
Computes the convolution of image using kernel.
297
>> ImageConvolve[hedy, DiamondMatrix[5] / 61]
298
>> ImageConvolve[hedy, BoxMatrix[5] / 121]
MaxFilter
WMA link
MaxFilter[image, r]
gives image with a maximum filter of radius r applied on it. This always picks the largest
value in the filter’s area.
>> MaxFilter[hedy, 5]
299
MedianFilter
WMA link
MedianFilter[image, r]
gives image with a median filter of radius r applied on it. This always picks the median value
in the filter’s area.
>> MedianFilter[hedy, 5]
MinFilter
WMA link
MinFilter[image, r]
gives image with a minimum filter of radius r applied on it. This always picks the smallest
value in the filter’s area.
300
>> MinFilter[hedy, 5]
Image Properties
Image Propertie
ImageAspectRatio
WMA link
ImageAspectRatio[image]
gives the aspect ratio of image.
>> ImageAspectRatio[img]
400
323
>> ImageAspectRatio[Image[{{0, 1}, {1, 0}, {1, 1}}]]
3
2
ImageChannels
WMA link
ImageChannels[image]
gives the number of channels in image.
301
>> img = Import["ExampleData/hedy.tif"];
>> ImageChannels[img]
3
ImageData
WMA link
ImageData[image]
gives a list of all color values of image as a matrix.
ImageData[image, stype]
gives a list of color values in type stype.
>> ImageData[img]
{{0.2, 0.4} , {0.9, 0.6} , {0.5, 0.8}}
ImageDimensions
WMA link
ImageDimensions[image]
Returns the dimensions {width, height} of image in pixels.
>> ImageDimensions[hedy]
{646, 800}
ImageType
WMA link
ImageType[image]
gives the interval storage type of image, e.g. “Real”, “Bit32”, or “Bit”.
>> ImageType[img]
Byte
302
>> ImageType[Image[{{0, 1}, {1, 0}}]]
Real
>> ImageType[Binarize[img]]
Bit
Image testing
Image testing
BinaryImageQ
WMA link
BinaryImageQ[$image]
returns True if the pixels of $image are binary bit values, and False otherwise.
>> BinaryImageQ[img]
False
>> BinaryImageQ[Binarize[img]]
True
ImageQ
WMA link
ImageQ[Image[$pixels]]
returns True if $pixels has dimensions from which an Image can be constructed, and False
otherwise.
303
EdgeDetect
WMA link
EdgeDetect[image]
returns an image showing the edges in image.
>> EdgeDetect[hedy]
>> EdgeDetect[hedy, 5]
304
>> EdgeDetect[hedy, 4, 0.5]
RandomImage
WMA link
RandomImage[max]
creates an image of random pixels with values 0 to max.
RandomImage[{min, max}]
creates an image of random pixels with values min to max.
RandomImage[..., size]
creates an image of the given size.
TextRecognize
WMA link
TextRecognize[image]
Recognizes text in image and returns it as a String.
305
>> TextRecognize[textimage]
TextRecognize[ image]
Closing
WMA link
Closing[image, ker]
Gives the morphological closing of image with respect to structuring element ker.
Dilation
WMA link
Dilation[image, ker]
Gives the morphological dilation of image with respect to structuring element ker.
306
>> Dilation[ein, 2.5]
Erosion
WMA link
Erosion[image, ker]
Gives the morphological erosion of image with respect to structuring element ker.
MorphologicalComponents
WMA link
307
MorphologicalComponents[image]
Builds a 2-D array in which each pixel of image is replaced by an integer index representing
the connected foreground image component in which the pixel lies.
MorphologicalComponents[image, threshold]
consider any pixel with a value above threshold as the foreground.
Opening
WMA link
Opening[image, ker]
Gives the morphological opening of image with respect to structuring element ker.
ImageTake
Extract Image parts WMA link
ImageTake[image, n]
gives the first n rows of image.
ImageTake[image, -n]
gives the last n rows of image.
ImageTake[image, {r1, r2}]
gives rows r1, ..., r2 of image.
ImageTake[image, {r1, r2}, {c1, c2}]
gives a cropped version of image.
308
Crop to the include only the upper half (244 rows) of an image:
>> alice = Import["ExampleData/MadTeaParty.gif"]; ImageTake[alice, 244]
Pixel Operations
Pixel Operation
PixelValue
WMA link
PixelValuePositions
WMA link
PixelValuePositions[image, val]
gives the positions of all pixels in image that have value val.
309
>> PixelValuePositions[Image[{{0.2, 0.4}, {0.9, 0.6}, {0.3, 0.8}}], 0.5,
0.15]
{{2, 2} , {2, 3}}
310
26. Importing and Exporting
Many kinds data formats can be read into Mathics3. Variable $ExportFormats of section 26 contains a
list of file formats that are supported by Export of section 26, while $InputFormats of section ?? does
the corresponding thing for Import of section 26.
Contents
$ExportFormats
WMA link
$ExportFormats
returns a list of file formats supported by Export.
>> $ExportFormats
{BMP, Base64, CSV, GIF, JPEG, JPEG2000, PBM, PCX, PGM, PNG, PPM, SVG, TIFF, Text, asy}
$ExtensionMappings
System‘ConvertersDump‘$ExtensionMappings
Returns a list of associations between file extensions and file types.
$FormatMappings
System‘ConverterDump$FormatMappings
Returns a list of associations between file extensions and file types.
311
>> Select[System‘ConvertersDump‘$FormatMappings,(#1[[2]]=="JPEG")&][[All
, 1]]
{APPLICATION/JPG, APPLICATION/X-JPG, IMAGE/JPEG, IMAGE/JPG, IMAGE/PJPEG, JPEG, JPG}
$ImportFormats
WMA link
$ImportFormats
returns a list of file formats supported by Import.
>> $ImportFormats
{BMP, Base64, CSV, GIF, HTML, ICO, JPEG, JPEG2000, JSON, PBM, PCX, PGM, PNG, PPM, Package, TGA, TIFF, Te
B64Decode
WMA link
System‘Convert‘B64Dump‘B64Decode[string]
Decode string in Base64 coding to an expression.
>> System‘Convert‘B64Dump‘B64Decode["R!="]
String "R!=" is not a valid b64 encoded string.
$Failed
B64Encode
WMA link
System‘Convert‘B64Dump‘B64Encode[expr]
Encodes expr in Base64 coding
>> System‘Convert‘B64Dump‘B64Decode[%]
Hello world
>> System‘Convert‘B64Dump‘B64Encode[Integrate[f[x],{x,0,2}]]
SW50ZWdyYXRlW2ZbeF0sIHt4LCAwLCAyfV0=
>> System‘Convert‘B64Dump‘B64Decode[%]
Integrate[f[x], {x, 0, 2}]
Export
WMA link
312
Export["file.ext", expr]
exports expr to a file, using the extension ext to determine the format.
Export["file", expr, "format"]
exports expr to a file in the specified format.
Export["file", exprs, elems]
exports exprs to a file as elements specified by elems.
ExportString
WMA link
ExportString[expr, form]
exports expr to a string, in the format form.
Export["file", exprs, elems]
exports exprs to a string as elements specified by elems.
FileFormat
WMA link
FileFormat["name"]
attempts to determine what format Import should use to import specified file.
>> FileFormat["ExampleData/sunflowers.jpg"]
JPEG
>> FileFormat["ExampleData/EinsteinSzilLetter.txt"]
Text
>> FileFormat["ExampleData/hedy.tif"]
TIFF
313
Import
WMA link
Import["file"]
imports data from a file.
Import["file", elements]
imports the specified elements from a file.
Import["http://url", ...] and Import["ftp://url", ...]
imports from a URL.
>> Import["ExampleData/colors.json"]
{colorsArray− > {{colorName− > black, rgbValue− > (0, 0,
0), hexValue− > #000000} , {colorName− > red, rgbValue− > (255, 0,
0), hexValue− > #FF0000} , {colorName− > green, rgbValue− > (0, 255,
0), hexValue− > #00FF00} , {colorName− > blue, rgbValue− > (0, 0,
255), hexValue− > #0000FF} , {colorName− > yellow, rgbValue− > (255, 255,
0), hexValue− > #FFFF00} , {colorName− > cyan, rgbValue− > (0, 255,
255), hexValue− > #00FFFF} , {colorName− > magenta, rgbValue− > (255, 0,
255), hexValue− > #FF00FF} , {colorName− > white, rgbValue− > (255,
255, 255), hexValue− > #FFFFFF}}}
ImportString
WMA link
ImportString["data‘‘,”format"]
imports data in the specified format from a string.
ImportString["file", elements]
imports the specified elements from a string.
ImportString["data"]
attempts to determine the format of the string from its content.
314
RegisterExport
RegisterExport["format", func]
register func as the default function used when exporting from a file of type "format".
>> FilePrint["sample.txt"]
Encode this string!
>> FilePrint["sample.txt"]
rapbqrguvffgevat
RegisterImport
RegisterImport["format", defaultFunction]
register defaultFunction as the default function used when importing from a file of type "
format".
RegisterImport["format", {"elem1" :> conditionalFunction1, "elem2" :> conditionalFunc-
tion2, ..., defaultFunction}]
registers multiple elements (elem1, ...) and their corresponding converter functions (condition-
alFunction1, ...) in addition to the defaultFunction.
RegisterImport["format", {"conditionalFunctions, defaultFunction, "elem3" :> postFunction3,
"elem4" :> postFunction4, ...}]
also registers additional elements (elem3, ...) whose converters (postFunction3, ...) act on output
from the low-level functions.
RegisterImport is then used to register the above function to a new data format.
>> ImportExport‘RegisterImport["ExampleFormat1", ExampleFormat1Import]
315
>> FilePrint["ExampleData/ExampleData.txt"]
Example File Format
Created by Angus
0.629452 0.586355
0.711009 0.687453
0.246540 0.433973
0.926871 0.887255
0.825141 0.940900
0.847035 0.127464
0.054348 0.296494
0.838545 0.247025
0.838697 0.436220
0.309496 0.833591
Conditional Importer:
>> ExampleFormat2DefaultImport[filename_String] := Module[{stream, head
}, stream = OpenRead[filename]; head = ReadList[stream, String, 2];
Close[stream]; {"Header" -> head}]
URLFetch
WMA link
URLFetch[URL]
#=
Returns the content of URL as a string.
316
...
317
27. Input and Output
Contents
Print . . . . . . . . . . 318
$Echo . . . . . . . . . 318
$Echo
WMA link
$Echo
gives a list of files and pipes to which all input is echoed.
Print
WMA link
Print[expr, ...]
prints each expr in string form.
318
28. Input/Output, Files, and Filesystem
Contents
319
Character
WMA link
Character
is a data type for Read.
Close
WMA link
Close[stream]
closes an input or output stream.
>> Close[StringToStream["123abc"]]
String
>> file=Close[OpenWrite[]]
/tmp/tmpkj3wsqyo
EndOfFile
WMA link
EndOfFile
is returned by Read when the end of an input stream is reached.
Expression
WMA link
Expression
is a data type for Read.
For information about underlying data structure Expression (a kind of M-expression) that is central in
evaluation, see: AST, M-Expression, General List same thing.
FilePrint
WMA link
FilePrint[file]
prints the raw contents of file.
Find
WMA link
320
Find[stream, text]
find the first line in stream that contains text.
>> Close[stream]
>> Close[stream]
Get (<<)
WMA link
<<name
reads a file and evaluates each expression, returning only the last one.
Get[name, Trace->True]
Runs Get tracing each line before it is evaluated.
>> Get[filename]
>> Get[filename]
>> DeleteFile[filename]
$InputFileName
WMA link
$InputFileName
is the name of the file from which input is currently being read.
321
InputStream
WMA link
InputStream[name, n]
represents an input stream for functions such as Read or Find.
>> Close[stream]
String
$Input
WMA link
$Input
is the name of the stream from which input is currently being read.
>> $Input
Number
WMA link
Number
is a data type for Read.
OpenAppend
WMA link
OpenAppend[‘‘file’]’
opens a file and returns an OutputStream to which writes are appended.
>> OpenAppend[]
[ ]
OutputStream /tmp/tmpcnh6fney, 27
OpenRead
WMA link
OpenRead[‘‘file’]’
opens a file and returns an InputStream.
322
>> Close[OpenRead["https://raw.githubusercontent.com/Mathics3/mathics-
core/master/README.rst"]];
OpenWrite
WMA link
OpenWrite[‘‘file’]’
opens a file and returns an OutputStream.
>> OpenWrite[]
[ ]
OutputStream /tmp/tmpcqq_7ips, 29
OutputStream
WMA link
OutputStream[name, n]
represents an output stream.
By default, the list of Streams normally OutputStream entries for stderr and stdout
>> Streams[]
{
InputStream [stdin, 0] , OutputStream [stdout, 1] , OutputStream [
[ ] [
stderr, 2] , OutputStream /tmp/tmp0hi3hmgy, 3 , InputStream
]
/src/external-vcs/github/Mathics3/mathics-core/mathics/data/ExampleData/EinsteinSzilLetter.txt, 4 , OutputS
] [ ] [
/tmp/tmp46rnxgfg, 5 , InputStream String, 6 , InputStream
] [ ] [ ] [
String, 7 , InputStream String, 8 , InputStream String, 9 , InputStream
] [ ] [ ] [
String, 10 , InputStream String, 11 , InputStream String, 12 , InputStream
] [ ] [ ] [
String, 13 , InputStream String, 14 , InputStream String, 15 , InputStream
] [ ] [ ] [
String, 16 , InputStream String, 17 , InputStream String, 18 , InputStream
] [ ] [ ] [
String, 19 , InputStream String, 20 , InputStream String, 21 , InputStream
] [ ] [
String, 22 , InputStream String, 23 , OutputStream
] [ ] [
/tmp/tmp4wt98oxv, 24 , InputStream String, 25 , InputStream
] [ ] [
/tmp/tmppyn8jvk0, 26 , OutputStream /tmp/tmpcnh6fney, 27 , InputStream
]
/src/external-vcs/github/Mathics3/mathics-core/mathics/data/ExampleData/EinsteinSzilLetter.txt, 28 , Outpu
]}
/tmp/tmpcqq_7ips, 29
Put (>>)
WMA link
323
>> filename = $TemporaryDirectory <> "/fortyfactorial";
>> FilePrint[filename]
>> Get[filename]
815915283247897734345611269596115894272000000000
>> DeleteFile[filename]
>> FilePrint[filename]
>> DeleteFile[filename]
=
>> filename = $TemporaryDirectory <> "/example_file";
>> FilePrint[filename]
>> DeleteFile[filename]
PutAppend (>>>)
WMA link
>> FilePrint["factorials"]
>> FilePrint["factorials"]
>> FilePrint["factorials"]
>> FilePrint["factorials"]
324
Read
WMA link
Read[stream]
reads the input stream and returns one expression.
Read[stream, type]
reads the input stream and returns an object of the given type.
type
Read[stream, type]
reads the input stream and returns an object of the given type.
Read[stream, Hold[Expression]]
reads the input stream for an Expression and puts it inside Hold.
is one of:
• Byte
• Character
• Expression
• HoldExpression
• Number
• Real
• Record
• String
• Word
>> stream = StringToStream["abc123"];
Read with a Hold[Expression] returns the expression it reads unevaluated so it can be later inspected
and evaluated:
>> Read[stream, Hold[Expression]]
325
>> Close[stream];
Multiple lines:
>> stream = StringToStream["\"Tengo una\nvaca lechera.\""]; Read[stream]
Tengo una
vaca lechera.
ReadList
WMA link
ReadList["file"]
Reads all the expressions until the end of file.
ReadList["file", type]
Reads objects of a specified type until the end of file.
ReadList["file", {type1, type2, ...}]
Reads a sequence of specified types until the end of file.
>> ReadList[stream]
{abc123}
>> InputForm[%]
{“abc123”}
Record
WMA link
Record
is a data type for Read.
SetStreamPosition
WMA link
SetStreamPosition[stream, n]
sets the current position in a stream.
326
>> SetStreamPosition[stream, 8]
8
>> Read[stream, Word]
is
>> SetStreamPosition[stream, Infinity]
16
Skip
WMA link
Skip[stream, type]
skips ahead in an input steream by one object of the specified type.
Skip[stream, type, n]
skips ahead in an input steream by n objects of the specified type.
StreamPosition
WMA link
StreamPosition[stream]
returns the current position in a stream as an integer.
Streams
WMA link
327
Streams[]
returns a list of all open streams.
>> Streams[]
{
InputStream [stdin, 0] , OutputStream [stdout, 1] , OutputStream [
[ ] [
stderr, 2] , OutputStream /tmp/tmp0hi3hmgy, 3 , InputStream
]
/src/external-vcs/github/Mathics3/mathics-core/mathics/data/ExampleData/EinsteinSzilLetter.txt, 4 , OutputS
] [ ] [
/tmp/tmp46rnxgfg, 5 , InputStream String, 6 , InputStream
] [ ] [ ] [
String, 7 , InputStream String, 8 , InputStream String, 9 , InputStream
] [ ] [ ] [
String, 10 , InputStream String, 11 , InputStream String, 12 , InputStream
] [ ] [ ] [
String, 13 , InputStream String, 14 , InputStream String, 15 , InputStream
] [ ] [ ] [
String, 16 , InputStream String, 17 , InputStream String, 18 , InputStream
] [ ] [ ] [
String, 19 , InputStream String, 20 , InputStream String, 21 , InputStream
] [ ] [
String, 22 , InputStream String, 23 , OutputStream
] [ ] [
/tmp/tmp4wt98oxv, 24 , InputStream String, 25 , InputStream
] [ ] [
/tmp/tmppyn8jvk0, 26 , OutputStream /tmp/tmpcnh6fney, 27 , InputStream
]
/src/external-vcs/github/Mathics3/mathics-core/mathics/data/ExampleData/EinsteinSzilLetter.txt, 28 , Outpu
] [ ] [
/tmp/tmpcqq_7ips, 29 , InputStream String, 30 , InputStream
] [ ] [ ] [
String, 31 , InputStream String, 32 , InputStream String, 33 , InputStream
] [ ] [ ] [
String, 34 , InputStream String, 35 , InputStream String, 36 , InputStream
] [ ] [ ] [
String, 37 , InputStream String, 38 , InputStream String, 39 , InputStream
] [ ] [ ] [
String, 40 , InputStream String, 41 , InputStream String, 42 , InputStream
] [ ] [ ] [
String, 43 , InputStream String, 44 , InputStream String, 45 , InputStream
] [ ] [ ]}
String, 46 , InputStream String, 47 , OutputStream /tmp/tmpo9yseybx, 48
>> Streams["stdout"]
{OutputStream [stdout, 1]}
StringToStream
WMA link
StringToStream[string]
converts a string to an open input stream.
Word
WMA link
Word
is a data type for Read.
Write
WMA link
328
Write[channel, expr1, expr2, ...]
writes the expressions to the output channel followed by a newline.
>> Write[stream, 10 x + 15 y ^ 2]
>> Close[stream];
>> ReadList[stream]
{ }
10x + 15y2 , 3Sin [z]
WriteString
WMA link
WriteString[stream, $str1, str2, ... ]
writes the strings to the output stream.
>> FilePrint[%]
>> FilePrint[%]
If stream is the string “stdout” or “stderr”, writes to the system standard output/ standard error chan-
nel:
>> WriteString["stdout", "Hola"]
Filesystem Operations
Filesystem Operation
329
AbsoluteFileName
WMA link
AbsoluteFileName["name"]
returns the absolute version of the given filename.
>> AbsoluteFileName["ExampleData/sunflowers.jpg"]
/src/external-vcs/github/Mathics3/mathics-core/mathics/data/ExampleData/sunflowers.jpg
$BaseDirectory
WMA link
$BaseDirectory
returns the folder where user configurations are stored.
>> $BaseDirectory
/src/external-vcs/github/Mathics3/mathics-core/mathics
CopyDirectory
WMA link
CopyDirectory["dir1‘‘,”dir2"]
copies directory dir1 to dir2.
CopyFile
WMA link
CopyFile["file1‘‘,”file2"]
copies file1 to file2.
>> DeleteFile["MathicsSunflowers.jpg"]
CreateDirectory
WMA link
CreateDirectory["dir"]
creates a directory called dir.
CreateDirectory[]
creates a temporary directory.
330
CreateFile
WMA link
CreateFile[‘‘filename’]’
Creates a file named “filename” temporary file, but do not open it.
CreateFile[]
Creates a temporary file, but do not open it.
CreateTemporary
WMA link
CreateTemporary[]
Creates a temporary file, but do not open it.
DeleteDirectory
WMA link
DeleteDirectory["dir"]
deletes a directory called dir.
>> DeleteDirectory[dir]
>> DirectoryQ[dir]
False
DeleteFile
WMA link
Delete["file"]
deletes file.
Delete[{"file1‘‘,”file2", ...}]
deletes a list of files.
>> DeleteFile["MathicsSunflowers.jpg"]
331
Directory
WMA link
Directory[]
returns the current working directory.
>> Directory[]
/home/rocky
DirectoryName
WMA link
DirectoryName["name"]
extracts the directory name from a filename.
>> DirectoryName["a/b/c"]
a/b
>> DirectoryName["a/b/c", 2]
a
DirectoryQ
WMA link
DirectoryQ["name"]
returns True if the directory called name exists and False otherwise.
>> DirectoryQ["ExampleData/"]
True
>> DirectoryQ["ExampleData/MythicalSubdir/"]
False
DirectoryStack
WMA link
DirectoryStack[]
returns the directory stack.
>> DirectoryStack[]
{/src/external-vcs/github/Mathics3/mathics-core/mathics, /home/rocky, /home/rocky}
ExpandFileName
WMA link
ExpandFileName["name"]
expands name to an absolute filename for your system.
332
>> ExpandFileName["ExampleData/sunflowers.jpg"]
/home/rocky/ExampleData/sunflowers.jpg
File
WMA link
File["file"]
is a symbolic representation of an element in the local file system.
FileBaseName
WMA link
FileBaseName["file"]
gives the base name for the specified file name.
>> FileBaseName["file.txt"]
file
>> FileBaseName["file.tar.gz"]
file.tar
FileByteCount
WMA link
FileByteCount[file]
returns the number of bytes in file.
>> FileByteCount["ExampleData/sunflowers.jpg"]
142286
FileDate
WMA link
FileDate[file, types]
returns the time and date at which the file was last modified.
>> FileDate["ExampleData/sunflowers.jpg"]
{2123, 1, 16, 3, 50, 39.9396}
333
>> FileDate["ExampleData/sunflowers.jpg", "Modification"]
{2123, 1, 16, 3, 50, 39.9396}
FileExistsQ
WMA link
FileExistsQ["file"]
returns True if file exists and False otherwise.
>> FileExistsQ["ExampleData/sunflowers.jpg"]
True
>> FileExistsQ["ExampleData/sunflowers.png"]
False
FileExtension
WMA link
FileExtension["file"]
gives the extension for the specified file name.
>> FileExtension["file.txt"]
txt
>> FileExtension["file.tar.gz"]
gz
FileHash
WMA link
FileHash[file]
returns an integer hash for the given file.
FileHash[file, type]
returns an integer hash of the specified type for the given file.
The types supported are “MD5”, “Adler32”, “CRC32”, “SHA”, “SHA224”, “SHA256”,
“SHA384”, and “SHA512”.
FileHash[file, type, format]
gives a hash code in the specified format.
>> FileHash["ExampleData/sunflowers.jpg"]
109937059621979839952736809235486742106
>> FileHash["ExampleData/sunflowers.jpg", "MD5"]
109937059621979839952736809235486742106
334
>> FileHash["ExampleData/sunflowers.jpg", "Adler32"]
1607049478
>> FileHash["ExampleData/sunflowers.jpg", "SHA256"]
111619807552579450300684600241129773909359865098672286468229443390003894913065
FileInformation
WMA link
FileInformation["file"]
returns information about file.
FileNameDepth
WMA link
FileNameDepth["name"]
gives the number of path parts in the given filename.
>> FileNameDepth["a/b/c"]
3
>> FileNameDepth["a/b/c/"]
3
FileNameJoin
WMA link
FileNameJoin[{"dir_1‘‘,”dir_2", ...}]
joins the dir_i together into one path.
FileNameJoin[..., OperatingSystem->‘‘os’]’
yields a file name in the format for the specified operating system. Possible choices are “Win-
dows”, “MacOSX”, and “Unix”.
335
FileNameSplit
WMA link
FileNameSplit["filenames"]
splits a filename into a list of parts.
>> FileNameSplit["example/path/file.txt"]
{example, path, file.txt}
FileNameTake
WMA link
FileNameTake["file"]
returns the last path element in the file name name.
FileNameTake["file", n]
returns the first n path elements in the file name name.
FileNameTake["file", $-n$]
returns the last n path elements in the file name name.
FileNames
WMA link
FileNames[]
Returns a list with the filenames in the current working folder.
FileNames[form]
Returns a list with the filenames in the current working folder that matches with form.
FileNames[{form_1, form_2, ...}]
Returns a list with the filenames in the current working folder that matches with one of form_1,
form_2, ....
FileNames[{form_1, form_2, ...},{dir_1, dir_2, ...}]
Looks into the directories dir_1, dir_2, ....
FileNames[{form_1, form_2, ...},{dir_1, dir_2, ...}]
Looks into the directories dir_1, dir_2, ....
FileNames[{forms, dirs, n]
Look for files up to the level n.
336
FileType
WMA link
FileType["file"]
gives the type of a file, a string. This is typically File, Directory or None.
>> FileType["ExampleData/sunflowers.jpg"]
File
>> FileType["ExampleData"]
Directory
>> FileType["ExampleData/nonexistent"]
None
FindFile
WMA link
FindFile[name]
searches $Path for the given filename.
>> FindFile["ExampleData/sunflowers.jpg"]
/src/external-vcs/github/Mathics3/mathics-core/mathics/data/ExampleData/sunflowers.jpg
>> FindFile["VectorAnalysis‘"]
/src/external-vcs/github/Mathics3/mathics-core/mathics/packages/VectorAnalysis/Kernel/init.m
>> FindFile["VectorAnalysis‘VectorAnalysis‘"]
/src/external-vcs/github/Mathics3/mathics-core/mathics/packages/VectorAnalysis/VectorAnalysis.m
FindList
WMA link
FindList[file, text]
returns a list of all lines in file that contain text.
FindList[file, {text1, text2, ...}]
returns a list of all lines in file that contain any of the specified string.
FindList[{file1, file2, ...}, ...]
returns a list of all lines in any of the filei that contain the specified strings.
Hash
Hash function (WMA link)
337
Hash[expr]
returns an integer hash for the given expr.
Hash[expr, type]
returns an integer hash of the specified type for the given expr.
The types supported are “MD5”, “Adler32”, “CRC32”, “SHA”, “SHA224”, “SHA256”,
“SHA384”, and “SHA512”.
Hash[expr, type, format]
Returns the hash in the specified format.
$HomeDirectory
WMA link
$HomeDirectory
returns the users HOME directory.
>> $HomeDirectory
/home/rocky
$InitialDirectory
WMA link
$InitialDirectory
returns the directory from which Mathics3 was started.
>> $InitialDirectory
/src/external-vcs/github/Mathics3/mathics-core/mathics
$InstallationDirectory
WMA link
$InstallationDirectory
returns the top-level directory in which Mathics3 was installed.
>> $InstallationDirectory
/src/external-vcs/github/Mathics3/mathics-core/mathics
338
Needs
WMA link
Needs["context‘"]
loads the specified context if not already in $Packages.
>> Needs["VectorAnalysis‘"]
$OperatingSystem
WMA link
$OperatingSystem
gives the type of operating system running Mathics.
>> $OperatingSystem
Unix
ParentDirectory
WMA link
ParentDirectory[]
returns the parent of the current working directory.
ParentDirectory["dir"]
returns the parent dir.
>> ParentDirectory[]
/src/external-vcs/github/Mathics3/mathics-core/mathics
$Path
WMA link
$Path
returns the list of directories to search when looking for a file.
>> $Path
{., /home/rocky, /src/external-vcs/github/Mathics3/mathics-core/mathics/data, /src/external-vcs/github/Mat
$PathnameSeparator
WMA link
$PathnameSeparator
returns a string for the separator in paths.
>> $PathnameSeparator
/
339
RenameDirectory
WMA link
RenameDirectory["dir1‘‘,”dir2"]
renames directory dir1 to dir2.
RenameFile
WMA link
RenameFile["file1‘‘,”file2"]
renames file1 to file2.
>> DeleteFile["MathicsSunnyFlowers.jpg"]
ResetDirectory
WMA link
ResetDirectory[]
pops a directory from the directory stack and returns it.
>> ResetDirectory[]
/src/external-vcs/github/Mathics3/mathics-core/mathics/autoload
$RootDirectory
WMA link
$RootDirectory
returns the system root directory.
>> $RootDirectory
/
SetDirectory
WMA link
SetDirectory[dir]
sets the current working directory to dir.
>> SetDirectory[]
/home/rocky
340
SetFileDate
WMA link
SetFileDate["file"]
set the file access and modification dates of file to the current date.
SetFileDate["file", date]
set the file access and modification dates of file to the specified date list.
SetFileDate["file", date, "type"]
set the file date of file to the specified date list. The "type“ can be one of ”Access“, ”Creation“,
”Modification", or All.
>> Close[OpenWrite[tmpfilename]];
$TemporaryDirectory
WMA link
$TemporaryDirectory
returns the directory used for temporary files.
>> $TemporaryDirectory
/tmp
ToFileName
WMA link
ToFileName[{"dir_1‘‘,”dir_2", ...}]
joins the dir_i together into one path.
URLSave
WMA link
341
URLSave[‘‘url’]’
Save “url” in a temporary file.
URLSave[‘‘url’,’ filename]
Save “url” in filename.
$UserBaseDirectory
WMA link
$UserBaseDirectory
returns the folder where user configurations are stored.
>> $RootDirectory
/
B64Decode
WMA link
System‘Convert‘B64Dump‘B64Decode[string]
Decode string in Base64 coding to an expression.
>> System‘Convert‘B64Dump‘B64Decode["R!="]
String "R!=" is not a valid b64 encoded string.
$Failed
B64Encode
WMA link
System‘Convert‘B64Dump‘B64Encode[expr]
Encodes expr in Base64 coding
>> System‘Convert‘B64Dump‘B64Decode[%]
>> System‘Convert‘B64Dump‘B64Encode[Integrate[f[x],{x,0,2}]]
SW50ZWdyYXRlW2ZbeF0sIHt4LCAwLCAyfV0=
>> System‘Convert‘B64Dump‘B64Decode[%]
342
$ExtensionMappings
System‘ConvertersDump‘$ExtensionMappings
Returns a list of associations between file extensions and file types.
$FormatMappings
System‘ConverterDump$FormatMappings
Returns a list of associations between file extensions and file types.
Export
WMA link
Export["file.ext", expr]
exports expr to a file, using the extension ext to determine the format.
Export["file", expr, "format"]
exports expr to a file in the specified format.
Export["file", exprs, elems]
exports exprs to a file as elements specified by elems.
$ExportFormats
WMA link
$ExportFormats
returns a list of file formats supported by Export.
>> $ExportFormats
{BMP, Base64, CSV, ExampleFormat1, ExampleFormat2, GIF, JPEG, JPEG2000, PBM, PCX, PGM, PNG, PPM, SVG, T
ExportString
WMA link
ExportString[expr, form]
exports expr to a string, in the format form.
Export["file", exprs, elems]
exports exprs to a string as elements specified by elems.
343
>> ExportString[{{1,2,3,4},{3},{2},{4}}, "CSV"]
1,2,3,4
3,
2,
4,
FileFormat
WMA link
FileFormat["name"]
attempts to determine what format Import should use to import specified file.
>> FileFormat["ExampleData/sunflowers.jpg"]
JPEG
>> FileFormat["ExampleData/EinsteinSzilLetter.txt"]
Text
>> FileFormat["ExampleData/hedy.tif"]
TIFF
Import
WMA link
Import["file"]
imports data from a file.
Import["file", elements]
imports the specified elements from a file.
Import["http://url", ...] and Import["ftp://url", ...]
imports from a URL.
344
>> Import["ExampleData/colors.json"]
{colorsArray− > {{colorName− > black, rgbValue− > (0, 0,
0), hexValue− > #000000} , {colorName− > red, rgbValue− > (255, 0,
0), hexValue− > #FF0000} , {colorName− > green, rgbValue− > (0, 255,
0), hexValue− > #00FF00} , {colorName− > blue, rgbValue− > (0, 0,
255), hexValue− > #0000FF} , {colorName− > yellow, rgbValue− > (255, 255,
0), hexValue− > #FFFF00} , {colorName− > cyan, rgbValue− > (0, 255,
255), hexValue− > #00FFFF} , {colorName− > magenta, rgbValue− > (255, 0,
255), hexValue− > #FF00FF} , {colorName− > white, rgbValue− > (255,
255, 255), hexValue− > #FFFFFF}}}
$ImportFormats
WMA link
$ImportFormats
returns a list of file formats supported by Import.
>> $ImportFormats
{BMP, Base64, CSV, ExampleFormat1, ExampleFormat2, GIF, HTML, ICO, JPEG, JPEG2000, JSON, PBM, PCX, PGM
ImportString
WMA link
ImportString["data‘‘,”format"]
imports data in the specified format from a string.
ImportString["file", elements]
imports the specified elements from a string.
ImportString["data"]
attempts to determine the format of the string from its content.
RegisterExport
RegisterExport["format", func]
register func as the default function used when exporting from a file of type "format".
345
>> ImportExport‘RegisterExport["ExampleFormat1", ExampleExporter1]
>> FilePrint["sample.txt"]
>> FilePrint["sample.txt"]
RegisterImport
RegisterImport["format", defaultFunction]
register defaultFunction as the default function used when importing from a file of type "
format".
RegisterImport["format", {"elem1" :> conditionalFunction1, "elem2" :> conditionalFunc-
tion2, ..., defaultFunction}]
registers multiple elements (elem1, ...) and their corresponding converter functions (condition-
alFunction1, ...) in addition to the defaultFunction.
RegisterImport["format", {"conditionalFunctions, defaultFunction, "elem3" :> postFunction3,
"elem4" :> postFunction4, ...}]
also registers additional elements (elem3, ...) whose converters (postFunction3, ...) act on output
from the low-level functions.
RegisterImport is then used to register the above function to a new data format.
>> ImportExport‘RegisterImport["ExampleFormat1", ExampleFormat1Import]
>> FilePrint["ExampleData/ExampleData.txt"]
Example File Format
Created by Angus
0.629452 0.586355
0.711009 0.687453
0.246540 0.433973
0.926871 0.887255
0.825141 0.940900
0.847035 0.127464
0.054348 0.296494
0.838545 0.247025
0.838697 0.436220
0.309496 0.833591
346
>> Import["ExampleData/ExampleData.txt", {"ExampleFormat1", "Header"}]
{Example File Format, Created by Angus}
Conditional Importer:
>> ExampleFormat2DefaultImport[filename_String] := Module[{stream, head
}, stream = OpenRead[filename]; head = ReadList[stream, String, 2];
Close[stream]; {"Header" -> head}]
URLFetch
WMA link
URLFetch[URL]
#=
Returns the content of URL as a string.
...
347
29. Integer Functions
Integer Functions can work on integers of any size.
Contents
Combinatorial Functions
Combinatorial Functions
Combinatorics is an area of mathematics primarily concerned with counting, both as a means and an
end in obtaining results, and certain properties of finite structures.
It is closely related to many other areas of Mathematics and has many applications ranging from logic
to statistical physics, from evolutionary biology to computer science, etc.
Binomial
Binomial Coefficient (SymPy, WMA)
Binomial[n, k]
gives the binomial coefficient n choose k.
>> Binomial[5, 3]
10
Binomial supports inexact numbers:
>> Binomial[10.5,3.2]
165.286
Some special cases:
>> Binomial[10, -2]
0
>> Binomial[-10.5, -3.5]
0.
348
CatalanNumber
Catalan Number (SymPy, WMA)
CatalanNumber[n]
gives the nth Catalan number.
DiceDissimilarity
Sørensen–Dice coefficient (Sympy, DiceDissimilarity)
DiceDissimilarity[u, v]
returns the Dice dissimilarity between the two boolean 1-D lists u and v. This is defined as
(c_tf + c_ft) / (2 * c_tt + c_ft + c_tf). n is len(u) and c_ij is the number of occurrences of u[k]=i
and v[k]=j for k < n.
JaccardDissimilarity
Jaccard index (SciPy, WMA)
JaccardDissimilarity[u, v]
returns the Jaccard-Needham dissimilarity between the two boolean 1-D lists u and v, which
is defined as (c_tf + c_ft) / (c_tt + c_ft + c_tf ), where n is len(u) and c_ij is the number of
occurrences of u[k]=i and v[k]=j for k < n.
MatchingDissimilarity
WMA link
MatchingDissimilarity[u, v]
returns the Matching dissimilarity between the two boolean 1-D lists u and v, which is defined
as (c_tf + c_ft) / n, where n is len(u) and c_ij is the number of occurrences of u[k]=i and v[k]=j
for k < n.
349
Multinomial
Multinomial distribution (WMA)
>> Multinomial[2, 3, 4, 5]
2522520
>> Multinomial[]
1
Multinomial is expressed in terms of Binomial:
>> Multinomial[a, b, c]
Binomial [a, a] Binomial [a + b, b] Binomial [a + b + c, c]
RogersTanimotoDissimilarity
WMA link
RogersTanimotoDissimilarity[u, v]
returns the Rogers-Tanimoto dissimilarity between the two boolean 1-D lists u and v, which
is defined as R / (c_tt + c_ff + R) where n is len(u), c_ij is the number of occurrences of u[k]=i
and v[$k]$=j for k<n, and R = 2 * (c_tf + c_ft).
RussellRaoDissimilarity
WMA link
RussellRaoDissimilarity[u, v]
returns the Russell-Rao dissimilarity between the two boolean 1-D lists u and v, which is
defined as (n - c_tt) / c_tt where n is len(u) and c_ij is the number of occurrences of u[k]=i and
v[k]=j for k < n.
SokalSneathDissimilarity
WMA link
350
SokalSneathDissimilarity[u, v]
returns the Sokal-Sneath dissimilarity between the two boolean 1-D lists u and v, which is
defined as R / (c_tt + R) where n is len(u), c_ij is the number of occurrences of u[k]=i and
v[k]=j for k < n, and R = 2 * (c_tf + c_ft).
Subsets
WMA link
Subsets[list]
finds a list of all possible subsets of list.
Subsets[list, n]
finds a list of all possible subsets containing at most n elements.
Subsets[list, {n}]
finds a list of all possible subsets containing exactly n elements.
Subsets[list, {min, max}]
finds a list of all possible subsets containing between min and max elements.
Subsets[list, spec, n]
finds a list of the first n possible subsets.
Subsets[list, spec, {n}]
finds the nth possible subset.
351
>> Subsets[{a, b, c, d}, All, {15, 1, -2}]
{{b, c, d} , { a, b, d} , {c, d} , {b, c} , { a, c} , {d} , {b} , {}}
YuleDissimilarity
WMA link
YuleDissimilarity[u, v]
returns the Yule dissimilarity between the two boolean 1-D lists u and v, which is defined as
R / (c_tt * c_ff + R / 2) where n is len(u), c_ij is the number of occurrences of u[k]=i and v[k]=j
for k<n, and R = 2 * c_tf * c_ft.
Division-Related Functions
Division-Related Function
CompositeQ
WMA link
CompositeQ[n]
returns True if n is a composite number
• A composite number is a positive number that is the product of two integers other than 1.
• For negative integer n, CompositeQ[n] is effectively equivalent to CompositeQ[-n].
>> Table[CompositeQ[n], {n, 0, 10}]
{False, False, False, False, True, False, True, False, True, True, True}
Divisible
WMA link
Divisible[n, m]
returns True if n is divisible by m, and False otherwise.
352
GCD
WMA link
GCD[n1, n2, ...]
computes the greatest common divisor of the given integers.
GCD is Listable:
>> GCD[4, {10, 11, 12, 13, 14}]
{2, 1, 4, 1, 2}
GCD does not work for rational numbers and Gaussian integers yet.
LCM
WMA link
LCM[n1, n2, ...]
computes the least common multiple of the given integers.
Mod
WMA link
Mod[x, m]
returns x modulo m.
>> Mod[14, 6]
2
>> Mod[-3, 4]
1
>> Mod[-3, -4]
−3
>> Mod[5, 0]
The argument 0 should be nonzero.
Mod [5, 0]
353
ModularInverse
Modular multiplicative inverse (SymPy, WMA)
ModularInverse[k, n]
returns the modular inverse k∧ (-1) mod n.
ModularInverse[k,n] gives the smallest positive integer r where the remainder of the division of r x k
by n is equal to 1.
>> ModularInverse[2, 3]
2
The following is be True for all values n, k which have a modular inverse:
>> k = 2; n = 3; Mod[ModularInverse[k, n] * k, n] == 1
True
Some modular inverses just do not exists. For example when k is a multiple of n:
>> ModularInverse[k, k]
ModularInverse [2, 2]
PowerMod
Modular exponentiaion. See https://en.wikipedia.org/wiki/Modular_exponentiation.
PowerMod[x, y, m]
computes x∧ y modulo m.
>> PowerMod[5, 2, 0]
The argument 0 should be nonzero.
PowerMod [5, 2, 0]
Quotient
WMA link
Quotient[m, n]
computes the integer quotient of m and n.
>> Quotient[23, 7]
3
354
QuotientRemainder
WMA link
QuotientRemainder[m, n]
computes a list of the quotient and remainder from division of m by n.
>> QuotientRemainder[23, 7]
{3, 2}
Fibonacci
WMA link
Fibonacci[n]
computes the nth Fibonacci number.
>> Fibonacci[0]
0
>> Fibonacci[1]
1
>> Fibonacci[10]
55
>> Fibonacci[200]
280571172992510140037611932413038677189525
HarmonicNumber
Harmonic Number
( WMA link)
HarmonicNumber[n]
returns the nth harmonic number.
>> HarmonicNumber[3.8]
2.03806
355
StirlingS1
Stirling numbers of first kind (WMA link)
StirlingS1[n, m]
gives the Stirling number of the first kind $ _n∧ m$.
Integer mathematical function, suitable for both symbolic and numerical manipulation. gives the num-
ber of permutations of n elements that contain exactly m cycles.
>> StirlingS1[50, 1]
− 608 281 864 034 267 560 872 252 163 321 295 376 887 552 831 379 210 240 000 000 000
StirlingS2
Stirling numbers of second kind (WMA link )
StirlingS2[n, m]
gives the Stirling number of the second kind _n∧ m.
returns the number of ways of partitioning a set of n elements into m non empty subsets.
>> Table[StirlingS2[10, m], {m, 10}]
{1, 511, 9330, 34105, 42525, 22827, 5880, 750, 45, 1}
356
30. Integer and Number-Theoretical Functions
Contents
357
MantissaExponent 406 RandomInteger . . 411 ArcSin . . . . . . 416
NextPrime . . . . 406 RandomReal . . . 411 ArcTan . . . . . . 416
PartitionsP . . . . 406 RandomSample . 412 Cos . . . . . . . . 416
Prime . . . . . . . 407 $RandomState . . 412 Cot . . . . . . . . 416
PrimePi . . . . . . 407 SeedRandom . . . 413 Csc . . . . . . . . 417
PrimePowerQ . . 408 Trigonometric Functions 413 Haversine . . . . 417
RandomPrime . . 408 AnglePath . . . . 414 InverseHaversine . 417
Random number ArcCos . . . . . . 414 Sec . . . . . . . . 418
generation . . . . 408
ArcCot . . . . . . 415 Sin . . . . . . . . 418
Random . . . . . 408
ArcCsc . . . . . . 415 Tan . . . . . . . . 418
RandomChoice . . 409
ArcSec . . . . . . 415
RandomComplex . 410
Algebraic Transformations
Algebraic Transformations
There are a number of built-in functions that perform:
• Structural Operations on Polynomials
• Finding the Structure of a Polynomial
• Structural Operations on Rational Expressions
• Polynomials over Algebraic Number Fields
• Simplification with or without Assumptions
Apart
WMA link
Apart[expr]
writes expr as a sum of individual fractions.
Apart[expr, var]
treats var as the main variable.
Apart is Listable:
>> Apart[{1 / (x^2 + 5x + 6)}]
{ }
1 1
−
2+x 3+x
358
>> Sin[1 / (x ^ 2 - y ^ 2)] // Apart
[ ]
1
Sin 2
x − y2
Cancel
WMA link
Cancel[expr]
cancels out common factors in numerators and denominators.
>> Cancel[x / x ^ 2]
1
x
Cancel threads over sums:
>> Cancel[x / x ^ 2 + y / y ^ 2]
1 1
+
x y
Coefficient
WMA link
Coefficient[expr, form]
returns the coefficient of form in the polynomial expr.
Coefficient[expr, form, n]
return the coefficient of form∧ n in expr.
359
>> Coefficient[(x + 1)^3, x, 2]
3
>> Coefficient[a x^2 + b y^3 + c x + d y + 5, y, 3]
b
Find the free term in a polynomial:
>> Coefficient[(x + 2)^3 + (x + 3)^2, x, 0]
17
>> Coefficient[(x + 2)^3 + (x + 3)^2, y, 0]
(2 + x)3 + (3 + x)2
CoefficientArrays
WMA link
CoefficientArrays[polys, vars]
returns a list of arrays of coefficients of the variables vars in the polynomial poly.
CoefficientList
WMA link
CoefficientList[poly, var]
returns a list of coefficients of powers of var in poly, starting with power 0.
CoefficientList[poly, {var1, var2, ...}]
returns an array of coefficients of the vari.
360
>> CoefficientList[(x + 3)^5, x]
{243, 405, 270, 90, 15, 1}
Collect
WMA link
Collect[expr, x]
Expands expr and collect together terms having the same power of x.
Collect[expr, {x_1, x_2, ...}]
Expands expr and collect together terms having the same powers of x_1, x_2, ....
Collect[expr, {x_1, x_2, ...}, filter]
After collect the terms, applies filter to each coefficient.
>> Collect[(x+y)^3, y]
x3 + 3x2 y + 3xy2 + y3
361
Denominator
WMA link
Denominator[expr]
gives the denominator in expr.
>> Denominator[a / b]
b
>> Denominator[2 / 3]
3
>> Denominator[a + b]
1
Expand
WMA link
Expand[expr]
expands out positive integer powers and products of sums in expr, as well as trigonometric
identities.
Expand[expr, target]
just expands those parts involving target.
362
>> Expand[Tanh[x + y], Trig -> True]
[ ] [ ]
Cosh [x] Sinh y Cosh y Sinh [x]
[ ] [ ]+ [ ] [ ]
Cosh [x] Cosh y + Sinh [x] Sinh y Cosh [x] Cosh y + Sinh [x] Sinh y
Using the second argument, the expression only expands those subexpressions containing pat:
>> Expand[(x+a)^2+(y+a)^2+(x+y)(x+a), y]
a2 + 2ay + x (a + x) + y (a + x) + y2 + (a + x)2
ExpandAll
WMA link
ExpandAll[expr]
expands out negative integer powers and products of sums in expr.
ExpandAll[expr, target]
just expands those parts involving target.
>> ExpandAll[Sin[(x+y)^2]]
[ ]
Sin x2 + 2xy + y2
363
>> ExpandAll[(1 + a)^ 6 / (x + y)^3, Modulus -> 3]
1 + 2a3 + a6
x 3 + y3
ExpandDenominator
WMA link
ExpandDenominator[expr]
expands out negative integer powers and products of sums in expr.
Exponent
WMA link
Exponent[expr, form]
returns the maximum power with which form appears in the expanded form of expr.
Exponent[expr, form, h]
applies h to the set of exponents with which form appears in expr.
>> Exponent[x / y, y]
−1
>> Exponent[(x^2 + 1)^3 - 1, x, Min]
2
>> Exponent[0, x]
−∞
>> Exponent[1, x]
0
Factor
WMA link
Factor[expr]
factors the polynomial expression expr.
364
>> Factor[x ^ 2 + 2 x + 1]
(1 + x)2
And lists:
>> Factor[{x + x^2, 2 x + 2 y + 2}]
{ ( )}
x (1 + x) , 2 1 + x + y
FactorTermsList
WMA link
FactorTermsList[poly]
returns a list of 2 elements. The first element is the numerical factor in poly. The second one is
the remaining of the polynomial with numerical factor removed.
FactorTermsList[poly, {x1, x2, ...}]
returns a list of factors in poly. The first element is the numerical factor in poly. The next ones
are factors that are independent of variables lists which are created by removing each variable
xi from right to left. The last one is the remaining of polynomial after dividing poly to all
previous factors.
>> FactorTermsList[x^2 - 2 x + 1]
{ }
1, 1 − 2x + x2
>> FactorTermsList[f]
{−3, −1 + a − 2ax − ay + 2x + y − 2xy + 2axy}
>> FactorTermsList[f, x]
{−3, 1 − a − y + ay, −1 + 2x }
365
FullSimplify
WMA link
FullSimplify[expr]
simplifies expr using an extended set of simplification rules.
TODO:
FullSimplify[expr, assump]
simplifies expr assuming assump instead of Assumptions.
implement the extension. By now, this does the same than Simplify...
>> FullSimplify[2*Sin[x]^2 + 2*Cos[x]^2]
2
MinimalPolynomial
WMA link
MinimalPolynomial[s, x]
gives the minimal polynomial in x for which the algebraic number s is a root.
>> MinimalPolynomial[7, x]
−7 + x
>> MinimalPolynomial[Sqrt[2] + Sqrt[3], x]
1 − 10x2 + x4
>> MinimalPolynomial[Sqrt[1 + Sqrt[3]], x]
−2 − 2x2 + x4
>> MinimalPolynomial[Sqrt[I + Sqrt[6]], x]
49 − 10x4 + x8
Numerator
WMA link
Numerator[expr]
gives the numerator in expr.
>> Numerator[a / b]
a
>> Numerator[2 / 3]
2
>> Numerator[a + b]
a+b
PolynomialQ
WMA link
366
PolynomialQ[expr, var]
returns True if expr is a polynomial in var, and returns False otherwise.
PolynomialQ[expr, {var1, ...}]
tests whether expr is a polynomial in the vari.
PowerExpand
WMA link
PowerExpand[expr]
expands out powers of the form (x^y)^z and (x*y)^z in expr.
Simplify
WMA link
Simplify[expr]
simplifies expr.
Simplify[expr, assump]
simplifies expr assuming assump instead of Assumptions.
367
>> Simplify[f[x]]
f [x]
Passing both options overwrites $Assumptions with the union of assump the option
>> Simplify[ConditionalExpression[1, a > 0] ConditionalExpression[1, b >
0], {a>0},Assumptions -> { b > 0 }]
1
>> $Assumptions={};
Together
WMA link
Together[expr]
writes sums of fractions in expr together.
>> Together[a / c + b / c]
a+b
c
Together operates on lists:
368
>> Together[{x / (y+1)+ x / (y+1)^2}]
{ ( )}
x 2+y
( )2
1+y
Variables
WMA link
Variables[expr]
gives a list of the variables that appear in the polynomial expr.
Calculus
Calculus
Originally called infinitesimal calculus or “the calculus of infinitesimals”, is the mathematical study of
continuous change, in the same way that geometry is the study of shape and algebra is the study of
generalizations of arithmetic operations.
Complexes
WMA link
Complexes
the domain of complex numbers, as in x in Complexes.
D
Derivative (WMA)
369
D[f , x]
gives the partial derivative of f with respect to x.
D[f , x, y, ...]
differentiates successively with respect to x, y, etc.
D[f , {x, n}]
gives the multiple derivative of order n.
D[f , {{x1, x2, ...}}]
gives the vector derivative of f with respect to x1, x2, etc.
Chain rule:
>> D[f[2x+1, 2y, x+y], x]
[ ] [ ]
2 f (1,0,0) 1 + 2x, 2y, x + y + f (0,0,1) 1 + 2x, 2y, x + y
370
Compute the gradient vector of a function:
>> D[x ^ 3 * Cos[y], {{x, y}}]
{ [ ] [ ]}
3x2 Cos y , − x3 Sin y
Hesse matrix:
>> D[Sin[x] * Cos[y], {{x,y}, 2}]
{{ [ ] [ ]} { [ ] [ ] }}
−Cos y Sin [x] , −Cos [x] Sin y , −Cos [x] Sin y , −Cos y Sin [x]
Derivative (’)
WMA link
Derivative[n][f ]
represents the nth derivative of the function f.
Derivative[n1, n2, ...][f ]
represents a multivariate derivative.
>> Derivative[1][Sin]
Cos [#1] &
>> Derivative[3][Sin]
−Cos [#1] &
>> (# ^ 4&)’’
12#12 &
>> f’[x] // InputForm
[ ]
Derivative [1] f [x]
371
>> f’[x]
2x
Unknown derivatives:
>> Derivative[2, 1][h]
h(2,1)
>> Derivative[2, 0, 1, 0][h[g]]
[ ](2,0,1,0)
h g
DiscreteLimit
WMA link
DiscreteLimit[f , k->Infinity]
gives the limit of the sequence f as k tends to infinity.
FindMaximum
WMA link
>> Clear[phi];
372
For a not so well behaving function, the result can be less accurate:
>> FindMaximum[-Exp[-1/x^2]+1., {x,1.2}, MaxIterations->10]
The maximum number of iterations was exceeded. The result might be
inaccurate.
[ [ ] ]
1
FindMaximum − Exp − 2 + 1., { x, 1.2} , MaxIterations− > 10
x
FindMinimum
WMA link
>> Clear[phi];
For a not so well behaving function, the result can be less accurate:
>> FindMinimum[Exp[-1/x^2]+1., {x,1.2}, MaxIterations->10]
The maximum number of iterations was exceeded. The result might be
inaccurate.
[ [ ] ]
1
FindMinimum Exp − 2 + 1., { x, 1.2} , MaxIterations− > 10
x
FindRoot
WMA link
373
should have a first derivative.
>> FindRoot[Cos[x], {x, 1}]
{ x − > 1.5708}
FindRoot has attribute HoldAll and effectively uses Block to localize x. However, in the result x will
eventually still be replaced by its value.
>> x = "I am the result!";
>> Clear[x]
Integers
WMA link
Integers
the domain of integer numbers, as in x in Integers.
374
>> Solve[x^4 == 4, x, Integers]
{}
Integrate
WMA link
Integrate[f , x]
integrates f with respect to x. The result does not contain the
additive integration constant.
Integrate[f , {x, a, b}]
computes the definite integral of f with respect to x from a to b.
Integrate a polynomial:
>> Integrate[6 x ^ 2 + 3 x ^ 2 - 4 x + 10, x]
( )
x 10 − 2x + 3x2
Definite integrals:
>> Integrate[x ^ 2 + x, {x, 1, 3}]
38
3
>> Integrate[Sin[x], {x, 0, Pi/2}]
1
Some other integrals:
>> Integrate[1 / (1 - 4 x + x^2), x]
√ ( [ √ ] [ √ ])
3 Log − 2 − 3 + x − Log − 2 + 3 + x
6
>> Integrate[4 Sin[x] Cos[x], x]
2Sin [x]2
Sometimes there is a loss of precision during integration. You can check the precision of your result
with the following sequence of commands.
>> Integrate[Abs[Sin[phi]], {phi, 0, 2Pi}] // N
4.
>> % // Precision
MachinePrecision
375
>> Integrate[ArcSin[x / 3], x]
[x] √
xArcSin + 9 − x2
3
>> Integrate[f’[x], {x, a, b}]
f [b] − f [a]
and,
>> D[Integrate[f[u, x],{u, a[x], b[x]}], x]
∫ b[x]
f (0,1) [u, x] du + f [b [x] , x] b′ [x] − f [a [x] , x] a′ [x]
a[x]
Limit
WMA link
Limit[expr, x->x0]
gives the limit of expr as x approaches x0.
Limit[expr, x->x0, Direction->1]
approaches x0 from smaller values.
Limit[expr, x->x0, Direction->-1]
approaches x0 from larger values.
NIntegrate
WMA link
NIntegrate[expr, interval]
returns a numeric approximation to the definite integral of expr with limits interval and with
a precision of prec digits.
NIntegrate[expr, interval1, interval2, ...]
returns a numeric approximation to the multiple integral of expr with limits interval1, interval2
and with a precision of prec digits.
376
>> NIntegrate[Exp[x],{x,-Infinity, 0},Tolerance->1*^-6, Method->"
Internal"]
1.
>> NIntegrate[Exp[-x^2/2.],{x,-Infinity, Infinity},Tolerance->1*^-6,
Method->"Internal"]
2.50664
O
WMA link
O[x]^n
Represents a term of order $x∧ n$.
O[x]∧ n is generated to represent omitted higher order terms in power series.
>> Series[1/(1-x),{x,0,2}]
1 + x + x2 + O [x]3
Reals
WMA link
Reals
is the domain real numbers, as in x in Reals.
Root
WMA link
Root[f , i]
represents the i-th complex root of the polynomial f.
377
Series
WMA link
For elementary expressions, Series returns the explicit power series as a SeriesData expression:
>> Series[Exp[x], {x,0,2}]
1
1 + x + x2 + O [x]3
2
>> % // FullForm
[ ]
SeriesData x, 0, {1, 1, Rational [1, 2]} , 0, 3, 1
Replacing the variable by a value, the series will not be evaluated as an expression, but as a SeriesData
object:
>> s = Series[Exp[x^2],{x,0,2}]
1 + x2 + O [x]3
>> s /. x->4
1 + 42 + O [4]3
SeriesData
WMA link
SeriesData[...]
Represents a series expansion.
378
>> Series[f[x],{x,0,2}] * g[w]
g [w] f ′′ [0] 2
f [0] g [w] + g [w] f ′ [0] x + x + O [x]3
2
The product of two series on the same neighbourhood of the same variable are multiplied
>> Series[Exp[-a x],{x,0,2}] * Series[Exp[-b x],{x,0,2}]
( 2 )
a b2
1 + (− a − b) x + + ab + x2 + O [x]3
2 2
Solve
Equation solving (SymPy, WMA)
Solve[equation, vars]
attempts to solve equation for the variables vars.
Solve[equation, vars, domain]
restricts variables to domain, which can be Complexes or Reals or Integers.
>> Solve[x ^ 2 - 3 x == 4, x]
{{ x − > −1} , { x − > 4}}
>> Solve[4 y - 8 == 0, y]
{{y− > 2}}
>> x /. sol
{−1, 6}
Contradiction:
>> Solve[x + 1 == x, x]
{}
Tautology:
>> Solve[x ^ 2 == x ^ 2, x]
{{}}
Rational equations:
>> Solve[x / (x ^ 2 + 1)== 1, x]
{{ } { }}
1 I√ 1 I√
x− > − 3 , x− > + 3
2 2 2 2
Transcendental equations:
379
>> Solve[Cos[x] == 0, x]
{{ { }}
π} 3π
x− > , x− >
2 2
>> Solve[a + b == 2, a + b]
a + b is not a valid variable.
Solve [a + b==2, a + b]
>> Solve[x == 2, x]
3 is not a valid variable.
Solve [False, 3]
>> Clear[x]
380
>> Solve[4 - 4 * x^2 - x^4 + x^6 == 0, x, Integers]
{{ x − > −1} , { x − > 1}}
Differential Equations
Differential Equation
C
WMA link
C[n]
represents the nth constant in a solution to a differential equation.
DSolve
WMA link
DSolve[eq, y[x], x]
solves a differential equation for the function y[x].
Exponential Functions
Exponential Functions
Numerical values and derivatives can be computed; however, most special exact values and simplifica-
tion rules are not implemented yet.
381
Exp
WMA link
Exp[z]
returns the exponential function of z.
>> Exp[1]
E
>> Exp[10.0]
22026.5
>> Exp[x] //FullForm
Power [E, x]
0.4
0.2
2 4 6 8 10
−0.2
−0.4
Log
WMA link
Log[z]
returns the natural logarithm of z.
>> Log[0.]
Indeterminate
>> Plot[Log[x], {x, 0, 5}]
10
2 4 6 8 10
−10
−20
−30
382
Log10
WMA link
Log10[z]
returns the base-10 logarithm of z.
>> Log10[1000]
3
>> Log10[{2., 5.}]
{0.30103, 0.69897}
>> Log10[E ^ 3]
3
Log [10]
Log2
WMA link
Log2[z]
returns the base-2 logarithm of z.
>> Log2[4 ^ 8]
16
>> Log2[5.6]
2.48543
>> Log2[E ^ 2]
2
Log [2]
LogisticSigmoid
WMA link
LogisticSigmoid[z]
returns the logistic sigmoid of z.
>> LogisticSigmoid[0.5]
0.622459
>> LogisticSigmoid[0.5 + 2.3 I]
1.06475 + 0.808177I
>> LogisticSigmoid[{-0.2, 0.1, 0.3}]
{0.450166, 0.524979, 0.574443}
383
Hyperbolic Functions
Hyperbolic Functions
Hyperbolic functions are analogues of the ordinary trigonometric functions, but defined using the hy-
perbola rather than the circle.
Numerical values and derivatives can be computed; however, most special exact values and simplifica-
tion rules are not implemented yet.
ArcCosh
Inverse hyperbolic cosine (SymPy, mpmath, WMA)
ArcCosh[z]
returns the inverse hyperbolic cosine of z.
>> ArcCosh[0]
I
π
2
>> ArcCosh[0.]
0. + 1.5708I
>> ArcCosh[0.00000000000000000000000000000000000000]
1.5707963267948966192313216916397514421I
ArcCoth
Inverse hyperbolic cotangent (SymPy, mpmath, WMA)
ArcCoth[z]
returns the inverse hyperbolic cotangent of z.
>> ArcCoth[0]
I
π
2
>> ArcCoth[1]
∞
>> ArcCoth[0.0]
0. + 1.5708I
>> ArcCoth[0.5]
0.549306 − 1.5708I
ArcCsch
Inverse hyperbolic cosecant (SymPy, mpmath, WMA)
ArcCsch[z]
returns the inverse hyperbolic cosecant of z.
>> ArcCsch[0]
ComplexInfinity
384
>> ArcCsch[1.0]
0.881374
ArcSech
WMA link
ArcSech[z]
returns the inverse hyperbolic secant of z.
>> ArcSech[0]
∞
>> ArcSech[1]
0
>> ArcSech[0.5]
1.31696
ArcSinh
WMA link
ArcSinh[z]
returns the inverse hyperbolic sine of z.
>> ArcSinh[0]
0
>> ArcSinh[0.]
0.
>> ArcSinh[1.0]
0.881374
ArcTanh
WMA link
ArcTanh[z]
returns the inverse hyperbolic tangent of z.
>> ArcTanh[0]
>> ArcTanh[1]
∞
>> ArcTanh[0]
>> ArcTanh[.5 + 2 I]
0.0964156 + 1.12656I
>> ArcTanh[2 + I]
ArcTanh [2 + I]
385
Cosh
WMA link
Cosh[z]
returns the hyperbolic cosine of z.
>> Cosh[0]
1
Coth
WMA link
Coth[z]
returns the hyperbolic cotangent of z.
>> Coth[0]
ComplexInfinity
Gudermannian
Gudermannian function (WMA, MathWorld)
Gudermannian[z]
returns the Gudermannian function gd(z).
>> Gudermannian[4.2]
1.54081
Gudermannian[-z] == - Gudermannian[z]:
>> Gudermannian[-4.2] == -Gudermannian[4.2]
True
>> Plot[Gudermannian[x], {x, -10, 10}]
80
60
40
20
2 4 6 8 10
InverseGudermannian
Inverse Gudermannian function (WMA, MathWorld)
InverseGudermannian[z]
returns the inverse Gudermannian function gd∧ -1(z).
386
>> InverseGudermannian[.5]
0.522238
InverseGudermannian[-z] == -InversGudermannian[z]:
>> InverseGudermannian[-.5] == -InverseGudermannian[.5]
True
InverseGudermannian is 0 at multiples of 8 Pi: = 0
>> Plot[InverseGudermannian[x], {x, -2 Pi, 2 Pi}]
2 4 6 8 10
−0.1
−0.2
−0.3
−0.4
−0.5
Sech
WMA link
Sech[z]
returns the hyperbolic secant of z.
>> Sech[0]
1
Sinh
WMA link
Sinh[z]
returns the hyperbolic sine of z.
>> Sinh[0]
0
Tanh
WMA link
Tanh[z]
returns the hyperbolic tangent of z.
>> Tanh[0]
0
387
Integer Functions
Integer Function
BitLength
WMA link
BitLength[x]
gives the number of bits needed to represent the integer x. x’s sign is ignored.
>> BitLength[1023]
10
>> BitLength[100]
7
>> BitLength[-5]
3
>> BitLength[0]
0
Ceiling
WMA link
Ceiling[x]
gives the smallest integer greater than or equal to x.
>> Ceiling[1.2]
2
>> Ceiling[3/2]
2
For complex x, take the ceiling of real an imaginary parts.
>> Ceiling[1.3 + 0.7 I]
2+I
DigitCount
WMA link
DigitCount[n, b, d]
returns the number of times digit d occurs in the base b representation of n.
DigitCount[n, b]
returns a list indicating the number of times each digit occurs in the base b representation of
n.
DigitCount[n, b]
returns a list indicating the number of times each digit occurs in the decimal representation of
n.
388
>> DigitCount[1022]
{1, 2, 0, 0, 0, 0, 0, 0, 0, 1}
>> DigitCount[1022, 2]
{9, 1}
>> DigitCount[1022, 2, 1]
9
Floor
WMA link
Floor[x]
gives the greatest integer less than or equal to x.
Floor[x, a]
gives the greatest multiple of a less than or equal to x.
>> Floor[10.4]
10
>> Floor[10/3]
3
>> Floor[10]
10
>> Floor[21, 2]
20
>> Floor[2.6, 0.5]
2.5
>> Floor[-10.4]
−11
For complex x, take the floor of real an imaginary parts.
>> Floor[1.5 + 2.7 I]
1 + 2I
For negative a, the smallest multiple of a greater than or equal to x is returned.
>> Floor[10.4, -1]
11
>> Floor[-10.4, -1]
−10
FromDigits
WMA link
389
FromDigits[l]
returns the integer corresponding to the decimal representation given by l. l can be a list of
digits or a string.
FromDigits[l, b]
returns the integer corresponding to the base b representation given by l. l can be a list of
digits or a string.
>> FromDigits["123"]
123
>> FromDigits[{1, 2, 3}]
123
>> FromDigits[{1, 0, 1}, 1000]
1000001
FromDigits can handle symbolic input:
>> FromDigits[{a, b, c}, 5]
c + 5 (5a + b)
Note that FromDigits does not automatically detect if you are providing a non-decimal representation:
>> FromDigits["a0"]
100
>> FromDigits["a0", 16]
160
FromDigits on empty lists or strings returns 0:
>> FromDigits[{}]
0
>> FromDigits[""]
0
IntegerDigits
WMA link
IntegerDigits[n]
returns the decimal representation of integer x as list of digits. x’s sign is ignored.
IntegerDigits[n, b]
returns the base b representation of integer x as list of digits. x’s sign is ignored.
IntegerDigits[n, b, length]
returns a list of length length. If the number is too short, the list gets padded with 0 on the left.
If the number is too long, the length least significant digits are returned.
>> IntegerDigits[76543]
{7, 6, 5, 4, 3}
390
The sign is discarded:
>> IntegerDigits[-76543]
{7, 6, 5, 4, 3}
A geeky way to relate Christmas with Halloween is to note that Dec(imal) 25 is Oct(al) 31
>> IntegerDigits[25, 8]
{3, 1}
IntegerReverse
WMA link
IntegerReverse[n]
returns the integer that has the reverse decimal representation of x without sign.
IntegerReverse[n, b]
returns the integer that has the reverse base b representation of x without sign.
>> IntegerReverse[1234]
4321
>> IntegerReverse[1022, 2]
511
>> IntegerReverse[-123]
321
IntegerString
WMA link
IntegerString[n]
returns the decimal representation of integer x as string. x’s sign is ignored.
IntegerString[n, b]
returns the base b representation of integer x as string. x’s sign is ignored.
IntegerString[n, b, length]
returns a string of length length. If the number is too short, the string gets padded with 0 on
the left. If the number is too long, the length least significant digits are returned.
For bases > 10, alphabetic characters a, b, ... are used to represent digits 11, 12, ... . Note that base must
be an integer in the range from 2 to 36.
>> IntegerString[12345]
12345
>> IntegerString[-500]
500
>> IntegerString[12345, 10, 8]
00012345
391
>> IntegerString[12345, 10, 3]
345
>> IntegerString[11, 2]
1011
>> IntegerString[123, 8]
173
>> IntegerString[32767, 16]
7fff
>> IntegerString[98765, 20]
c6i5
Linear algebra
Linear algebra
DesignMatrix
WMA link
DesignMatrix[m, f , x]
returns the design matrix for a linear model f in the variables x.
>> DesignMatrix[{{2, 1}, {3, 4}, {5, 3}, {7, 6}}, f[x], x]
{{1, f [2]} , {1, f [3]} , {1, f [5]} , {1, f [7]}}
Det
Matrix Determinant (WMA link)
Det[m]
computes the determinant of the matrix m.
Eigensystem
Matrix Eigenvalues (WMA)
392
Eigensystem[m]
returns the list {Eigenvalues[m], Eigenvectors[m]}.
Eigenvalues
Matrix Eigenvalues (WMA link)
Eigenvalues[m]
computes the eigenvalues of the matrix m. By default Sympy’s routine is used. Sometimes
this is slow and less good than the corresponding mpmath routine. Use option Method-
>“mpmath” if you want to use mpmath’s routine instead.
Symbolic eigenvalues:
>> Eigenvalues[{{Cos[theta],Sin[theta],0},{-Sin[theta],Cos[theta
],0},{0,0,1}}] // Sort
{ √
1, Cos [theta] + (−1 + Cos [theta]) (1 + Cos [theta]), Cos [
√ }
theta] − (−1 + Cos [theta]) (1 + Cos [theta])
Eigenvectors
Matrix Eigenvalues (WMA link)
Eigenvectors[m]
computes the eigenvectors of the matrix m.
393
FittedModel
WMA link
FittedModel[...]
Result of a linear fit
Inverse
WMA link
Inverse[m]
computes the inverse of the matrix m.
LeastSquares
WMA link
LeastSquares[m, b]
computes the least squares solution to m x = b, finding an x that solves for b optimally.
LinearModelFit
WMA link
LinearModelFit[m, f , x]
fits a linear model f in the variables x to the dataset m.
>> m = LinearModelFit[{{2, 1}, {3, 4}, {5, 3}, {7, 6}}, x, x];
>> m["BasisFunctions"]
394
>> m["BestFit"]
0.186441 + 0.779661x
>> m["BestFitParameters"]
{0.186441, 0.779661}
>> m["DesignMatrix"]
{{1, 2} , {1, 3} , {1, 5} , {1, 7}}
>> m["Function"]
>> m["Response"]
{1, 4, 3, 6}
>> m["FitResiduals"]
>> m = LinearModelFit[{{2, 2, 1}, {3, 2, 4}, {5, 6, 3}, {7, 9, 6}}, {Sin
[x], Cos[y]}, {x, y}];
>> m["BasisFunctions"]
>> m["Function"]
>> m["BasisFunctions"]
>> m["FitResiduals"]
LinearSolve
WMA link
LinearSolve[matrix, right]
solves the linear equation system matrix . x = right and returns one corresponding solution
x.
395
MatrixExp
WMA link
MatrixExp[m]
computes the exponential of the matrix m.
MatrixPower
WMA link
MatrixPower[m, n]
computes the nth power of a matrix m.
MatrixRank
WMA link
MatrixRank[matrix]
returns the rank of matrix.
NullSpace
Kernel (null space) (WMA link)
NullSpace[matrix]
returns a list of vectors that span the nullspace of matrix.
396
>> A = {{1, 1, 0}, {1, 0, 1}, {0, 1, 1}};
>> NullSpace[A]
{}
>> MatrixRank[A]
3
PseudoInverse
WMA link
PseudoInverse[m]
computes the Moore-Penrose pseudoinverse of the matrix m. If m is invertible, the pseudoin-
verse equals the inverse.
QRDecomposition
QR Decomposition (WMA link)
QRDecomposition[m]
computes the QR decomposition of the matrix m.
RowReduce
WMA link
RowReduce[matrix]
returns the reduced row-echelon form of matrix.
397
SingularValueDecomposition
Singular Value Decomposition (WMA link)
SingularValueDecomposition[m]
calculates the singular value decomposition for the matrix m.
Tr
Matrix trace (WMA link)
Tr[m]
computes the trace of the matrix m.
Mathematical Constants
Mathematical Constants
Numeric, Arithmetic, or Symbolic constants like Pi, E, or Infinity.
Catalan
Catalan’s constant (SymPy, WMA)
Catalan
is Catalan’s constant with numerical value ≃ 0.915966.
>> Catalan // N
0.915966
>> N[Catalan, 20]
0.91596559417721901505
ComplexInfinity
Complex Infinity is an infinite number in the complex plane whose complex argument is unknown or
undefined. (SymPy, MathWorld, WMA)
398
ComplexInfinity
represents an infinite complex quantity of undetermined direction.
>> 1 / ComplexInfinity
0
>> ComplexInfinity * Infinity
ComplexInfinity
>> FullForm[ComplexInfinity]
DirectedInfinity []
Degree
Degree (angle) (WMA)
Degree
is the number of radians in one degree. It has a numerical value of π / 180.
E
Euler’s number (SymPy, WMA)
E
is the constant e with numerical value ≃ 2.71828.
>> N[E]
2.71828
>> N[E, 50]
2.7182818284590452353602874713526624977572470937000
EulerGamma
Euler’s constant (SymPy, WMA)
EulerGamma
is Euler’s constant γ with numerical value ≃ 0.577216.
>> EulerGamma // N
0.577216
399
>> N[EulerGamma, 40]
0.5772156649015328606065120900824024310422
Glaisher
Glaisher–Kinkelin constant (mpmath, WMA)
Glaisher
is Glaisher’s constant, with numerical value ≃ 1.28243.
>> N[Glaisher]
1.28243
>> N[Glaisher, 50]
1.2824271291006226368753425688697917277676889273250
# 1.2824271291006219541941391071304678916931152343750
GoldenRatio
Golden ratio (mpmath, WMA)
GoldenRatio
is the golden ratio, ϕ = (1+Sqrt[5])/2.
>> GoldenRatio // N
1.61803
>> N[GoldenRatio, 40]
1.618033988749894848204586834365638117720
Indeterminate
Indeterminate form (SymPy, WMA)
Indeterminate
represents an indeterminate result.
>> 0^0
Indeterminate expression 0 ^ 0 encountered.
Indeterminate
>> Tan[Indeterminate]
Indeterminate
Infinity
Infinity (SymPy, WMA)
Infinity
a symbol that represents an infinite real quantity.
400
>> 1 / Infinity
0
>> Infinity + 100
∞
Use Infinity in sum and limit calculations:
>> Sum[1/x^2, {x, 1, Infinity}]
π2
6
Khinchin
Khinchin’s constant (mpmath, WMA)
Khinchin
is Khinchin’s constant, with numerical value ≃ 2.68545.
>> N[Khinchin]
2.68545
>> N[Khinchin, 50]
2.6854520010653064453097148354817956938203822939945
# = 2.6854520010653075701156922150403261184692382812500
$MaxMachineNumber
Largest normalizable machine number (WMA)
$MaxMachineNumber
Represents the largest positive number that can be represented as a normalized machine num-
ber in the system.
$MinMachineNumber
Smallest normalizable machine number (WMA)
$MinMachineNumber
Represents the smallest positive number that can be represented as a normalized machine
number in the system.
MachinePrecision minus the Log base 10 of this number is the Accuracy of 0‘:
>> MachinePrecision -Log[10., $MinMachineNumber]==Accuracy[0‘]
True
401
Overflow
Numeric Overflow (WMA)
See also Integer Overflow.
Overflow[]
represents a number too large to be represented by Mathics.
>> Exp[10.*^20]
Overflow occurred in computation.
Overflow []
>> 1 / Underflow[]
Overflow []
Pi
Pi, π (SymPy, WMA)
Pi
is the constant π.
>> Pi
π
>> N[Pi]
3.14159
Pi to a numeric precision of 20 digits:
>> N[Pi, 20]
3.1415926535897932385
Note that the above is not the same thing as the number of digits after the decimal point. This may differ
from similar concepts from other mathematical libraries, including those which Mathics uses!
Use numpy to compute Pi to 20 digits:
>> N[Pi, 20, Method->"numpy"]
3.1415926535897930000
“sympy” is the default method.
>> Attributes[Pi]
{Constant, Protected, ReadProtected}
Undefined
Undefined symbol/value (WMA)
Undefined
a symbol that represents a quantity with no defined value.
402
>> ConditionalExpression[a, False]
Undefined
>> Attributes[Undefined]
{Protected}
Underflow
Arithmetic underflow (WMA)
Overflow[]
represents a number too small to be represented by Mathics.
>> 1 / Overflow[]
Underflow []
>> 5 * Underflow[]
5Underflow []
>> % // N
Underflow[] is kept symbolic in operations against integer numbers, but taken as 0. in numeric evalua-
tions:
>> 1 - Underflow[]
1 − Underflow []
>> % // N
ContinuedFraction
Continued fraction (SymPy, WMA)
ContinuedFraction[x, n]
generate the first n terms in the continued fraction representation of x.
ContinuedFraction[x]
the complete continued fraction representation for a rational or quadradic irrational number.
>> ContinuedFraction[Sqrt[70]]
{8, {2, 1, 2, 1, 2, 16}}
403
Divisors
WMA link
Divisors[n]
returns a list of the integers that divide n.
>> Divisors[96]
{1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 96}
>> Divisors[704]
{1, 2, 4, 8, 11, 16, 22, 32, 44, 64, 88, 176, 352, 704}
EulerPhi
Euler’s totient function (SymPy, WMA) This function counts positive integers up to n that are relatively
prime to n. It is typically used in cryptography and in many applications in elementary number theory.
EulerPhi[n]
returns the Euler totient function .
FactorInteger
WMA link
FactorInteger[n]
returns the factorization of n as a list of factors and exponents.
404
>> factors = FactorInteger[2010]
{{2, 1} , {3, 1} , {5, 1} , {67, 1}}
FractionalPart
WMA link
FractionalPart[n]
finds the fractional part of n.
>> FractionalPart[4.1]
0.1
>> FractionalPart[-5.25]
− 0.25
FromContinuedFraction
WMA link
FromContinuedFraction[list]
reconstructs a number from the list of its continued fraction terms.
MantissaExponent
WMA link
MantissaExponent[n]
finds a list containing the mantissa and exponent of a given number n.
MantissaExponent[n, b]
finds the base b mantissa and exponent of n.
>> MantissaExponent[2.5*10^20]
{0.25, 21}
405
>> MantissaExponent[125.24]
{0.12524, 3}
>> MantissaExponent[125., 2]
{0.976563, 7}
>> MantissaExponent[10, b]
MantissaExponent [10, b]
NextPrime
WMA link
NextPrime[n]
gives the next prime after n.
NextPrime[n,k]
gives the kth prime after n.
>> NextPrime[10000]
10007
>> NextPrime[100, -5]
73
>> NextPrime[10, -5]
−2
>> NextPrime[100, 5]
113
>> NextPrime[5.5, 100]
563
>> NextPrime[5, 10.5]
NextPrime [5, 10.5]
PartitionsP
WMA link
PartitionsP[n]
return the number p(n) of unrestricted partitions of the integer n.
Prime
WMA link
406
Prime[n]
Prime[{n0, n1, ...}]
returns the nth prime number where n is an positive Integer. If given a list of integers, the
return value is a list with Prime applied to each.
PrimePi
Prime numbers
PrimePi[x]
gives the number of primes less than or equal to x.
PrimePowerQ
Prime numbers
PrimePowerQ[n]
returns True if n is a power of a prime number.
407
>> PrimePowerQ[9]
True
>> PrimePowerQ[52142]
False
>> PrimePowerQ[-8]
True
>> PrimePowerQ[371293]
True
RandomPrime
Prime numbers
RandomPrime[{imin, $imax}]
gives a random prime between imin and imax.
RandomPrime[imax]
gives a random prime between 2 and imax.
RandomPrime[range, n]
gives a list of n random primes in range.
>> RandomPrime[{8,12}, 3]
{11, 11, 11}
Random
WMA
Random[]
gives a uniformly distributed pseudorandom Real number in the range 0 to 1.
Random[type, range] Legacy
gives a uniformly distributed pseudorandom number of the type type, in the specified interval
range. Possible types are Integer, Real or Complex.
408
RandomChoice
WMA
RandomChoice[items]
randomly picks one item from items.
RandomChoice[items, n]
randomly picks n items from items. Each pick in the n picks happens from the given set of
items, so each item can be picked any number of times.
RandomChoice[items, {n1, n2, ...}]
randomly picks items from items and arranges the picked items in the nested list structure
described by {n1, n2, ...}.
RandomChoice[weights -> items, n]
randomly picks n items from items and uses the corresponding numeric values in weights to
determine how probable it is for each item in items to get picked (in the long run, items with
higher weights will get picked more often than ones with lower weight).
RandomChoice[weights -> items]
randomly picks one items from items using weights weights.
RandomChoice[weights -> items, {n1, n2, ...}]
randomly picks a structured list of items from items using weights weights.
Note: SeedRandom is used below so we get repeatable “random” numbers that we can test.
>> SeedRandom[42]
>> SeedRandom[42]
>> SeedRandom[42]
>> SeedRandom[42]
RandomComplex
WMA)
409
RandomComplex[{z_min, z_max}]
yields a pseudorandom complex number in the rectangle with complex corners z_min and
z_max.
RandomComplex[z_max]
yields a pseudorandom complex number in the rectangle with corners at the origin and at
z_max.
RandomComplex[]
yields a pseudorandom complex number with real and imaginary parts from 0 to 1.
RandomComplex[range, n]
gives a list of n pseudorandom complex numbers.
RandomComplex[range, {n1, n2, ...}]
gives a nested list of pseudorandom complex numbers.
>> RandomComplex[]
0.734271 + 0.391106I
>> RandomComplex[{1+I, 5+5I}]
1.33561 + 4.18874I
>> RandomComplex[1+I, 5]
{0.519712 + 0.663766I, 0.53529 + 0.903976I, 0.824985
+ 0.659807I, 0.566475 + 0.175172I, 0.749211 + 0.748907I }
RandomInteger
WMA)
RandomInteger[{min, max}]
yields a pseudorandom integer in the range from min to max inclusive.
RandomInteger[max]
yields a pseudorandom integer in the range from 0 to max inclusive.
RandomInteger[]
gives 0 or 1.
RandomInteger[range, n]
gives a list of n pseudorandom integers.
RandomInteger[range, {n1, n2, ...}]
gives a nested list of pseudorandom integers.
>> RandomInteger[]
0
410
>> $RandomState != previousState
True
RandomReal
WMA)
RandomReal[{min, max}]
yields a pseudorandom real number in the range from min to max.
RandomReal[max]
yields a pseudorandom real number in the range from 0 to max.
RandomReal[]
yields a pseudorandom real number in the range from 0 to 1.
RandomReal[range, n]
gives a list of n pseudorandom real numbers.
RandomReal[range, {n1, n2, ...}]
gives an n1 x n2 array of pseudorandom real numbers.
>> RandomReal[]
0.579255
>> RandomReal[{1, 5}]
4.14801
RandomSample
WMA
RandomSample[items]
randomly picks one item from items.
RandomSample[items, n]
randomly picks n items from items. Each pick in the n picks happens after the previous items
picked have been removed from items, so each item can be picked at most once.
RandomSample[items, {n1, n2, ...}]
randomly picks items from items and arranges the picked items in the nested list structure
described by {n1, n2, ...}. Each item gets picked at most once.
RandomSample[weights -> items, n]
randomly picks n items from items and uses the corresponding numeric values in weights
to determine how probable it is for each item in items to get picked (in the long run, items
with higher weights will get picked more often than ones with lower weight). Each item gets
picked at most once.
RandomSample[weights -> items]
randomly picks one items from items using weights weights. Each item gets picked at most
once.
RandomSample[weights -> items, {n1, n2, ...}]
randomly picks a structured list of items from items using weights weights. Each item gets
picked at most once.
>> SeedRandom[42]
411
>> SeedRandom[42]
>> SeedRandom[42]
>> SeedRandom[42]
>> RandomSample[Range[10]]
{9, 2, 6, 1, 8, 3, 10, 5, 4, 7}
>> SeedRandom[42]
>> SeedRandom[42]
$RandomState
WMA
$RandomState
is a long number representing the internal state of the pseudo-random number generator.
SeedRandom
WMA)
412
SeedRandom[n]
resets the pseudorandom generator with seed n.
SeedRandom[]
uses the current date and time as the seed.
>> RandomInteger[100]
>> RandomInteger[100]
>> SeedRandom[42]
>> RandomInteger[100]
>> RandomInteger[100]
>> RandomInteger[100]
Calling SeedRandom without arguments will seed the random number generator to a random state:
>> SeedRandom[]
>> RandomInteger[100]
Trigonometric Functions
Trigonometric Functions
Numerical values and derivatives can be computed; however, most special exact values and simplifica-
tion rules are not implemented yet.
AnglePath
WMA link
413
>> AnglePath[{90 Degree, 90 Degree, 90 Degree, 90 Degree}]
{{0, 0} , {0, 1} , {−1, 1} , {−1, 0} , {0, 0}}
0.5
0.4
0.3
0.2
0.1
2 4 6 8 10
−0.1
0.4
0.3
0.2
0.1
2 4 6 8 10
−0.1
−0.2
ArcCos
Inverse cosine, arccosine (SymPy, mpmath, WMA)
ArcCos[z]
returns the inverse cosine of z.
>> ArcCos[1]
0
>> ArcCos[0]
π
2
>> Integrate[ArcCos[x], {x, -1, 1}]
π
414
ArcCot
Inverse cotangent, arccotangent (SymPy, mpmath, WMA)
ArcCot[z]
returns the inverse cotangent of z.
>> ArcCot[0]
π
2
>> ArcCot[1]
π
4
ArcCsc
Inverse cosecant, arccosecant (SymPy, mpmath, WMA)
ArcCsc[z]
returns the inverse cosecant of z.
>> ArcCsc[1]
π
2
>> ArcCsc[-1]
π
−
2
ArcSec
Inverse secant, arcsecant (SymPy, mpmath, WMA)
ArcSec[z]
returns the inverse secant of z.
>> ArcSec[1]
0
>> ArcSec[-1]
π
ArcSin
Inverse sine, arcsine (SymPy, mpmath, WMA)
ArcSin[z]
returns the inverse sine of z.
>> ArcSin[0]
0
415
>> ArcSin[1]
π
2
ArcTan
Inverse tangent, arctangent (SymPy, mpmath, WMA)
ArcTan[z]
returns the inverse tangent of z.
>> ArcTan[1]
π
4
>> ArcTan[1.0]
0.785398
>> ArcTan[-1.0]
− 0.785398
>> ArcTan[1, 1]
π
4
Cos
Cosine (SymPy, mpmath, WMA)
Cos[z]
returns the cosine of z.
Cot
Cotangent (SymPy, mpmath, WMA)
Cot[z]
returns the cotangent of z.
>> Cot[0]
ComplexInfinity
>> Cot[1.]
0.642093
Csc
Cosecant (SymPy, mpmath, WMA)
416
Csc[z]
returns the cosecant of z.
>> Csc[0]
ComplexInfinity
>> Csc[1.]
1.1884
Haversine
WMA link
Haversine[z]
returns the haversine function of z.
>> Haversine[1.5]
0.464631
>> Haversine[0.5 + 2I]
− 1.15082 + 0.869405I
InverseHaversine
WMA link
InverseHaversine[z]
returns the inverse haversine function of z.
>> InverseHaversine[0.5]
1.5708
>> InverseHaversine[1 + 2.5 I]
1.76459 + 2.33097I
Sec
Secant (SymPy, mpmath, WMA)
Sec[z]
returns the secant of z.
>> Sec[0]
1
>> Sec[1] (* Sec[1] in Mathematica *)
1
Cos [1]
417
>> Sec[1.]
1.85082
Sin
Sine (SymPy, mpmath, WMA)
Sin[z]
returns the sine of z.
>> Sin[0]
0
>> Sin[0.5]
0.479426
>> Sin[3 Pi]
0
>> Sin[1.0 + I]
1.29846 + 0.634964I
>> Plot[Sin[x], {x, -Pi, Pi}]
2 4 6 8 10
−2
−4
−6
−8
Tan
Tangent (SymPy, mpmath, WMA)
Tan[z]
returns the tangent of z.
>> Tan[0]
0
>> Tan[Pi / 2]
ComplexInfinity
418
31. Interactive Manipulation
419
32. Layout
This module contains symbols used to define the high level layout for expression formatting.
For instance, to represent a set of consecutive expressions in a row, we can use Row.
Contents
Center
WMA link
Center
is used with the ColumnAlignments option to Grid or TableForm to specify a centered column.
Format
WMA link
Format[expr]
holds values specifying how expr should be printed.
Assign values to Format to control how particular expressions should be formatted when printed to the
user.
>> Format[f[x___]] := Infix[{x}, "~"]
>> f[1, 2, 3]
1∼2∼3
>> f[1]
1
Raw objects cannot be formatted:
>> Format[3] = "three";
Cannot assign to raw object 3.
420
>> f /: Format[g[f]] = "my f";
Tag f not found or too deep for an assigned rule.
Grid
WMA link
If the sublists have different sizes, the grid has the number of columns of the largest one. Incomplete
rows are completed with empty strings:
>> Grid[{{"first", "second", "third"},{a},{1, 2, 3}}]
first second third
a
1 2 3
If the list is a mixture of lists and other expressions, the non-list expressions are shown as rows:
>> Grid[{"This is a long title", {"first", "second", "third"},{a},{1, 2,
3}}]
This is a long title
first second third
a
1 2 3
Infix
WMA link
Infix[expr, oper, prec, assoc]
displays expr with the infix operator oper, with precedence prec and associativity assoc.
Infix can be used with Format to display certain forms with user-defined infix notation:
>> Format[g[x_, y_]] := Infix[{x, y}, "#", 350, Left]
421
>> g[a + b, c]
(a + b) #c
>> g[a * b, c]
ab#c
>> g[a, b] + c
c + a#b
>> g[a, b] * c
c (a#b)
Left
WMA link
Left
is used with operator formatting constructs to specify a left-associative operator.
MakeBoxes
WMA link
MakeBoxes[expr]
is a low-level formatting primitive that converts expr to box form, without evaluating it.
\( ... \)
directly inputs box objects.
>> \( a \+ b \% c\)
UnderoverscriptBox [a, b, c]
>> \(x \+ y \)
[ ]
UnderscriptBox x, y
422
NonAssociative
on, logic, comparison, datentime, attributes and binary)
NonAssociative
is used with operator formatting constructs to specify a non-associative operator.
Postfix (//)
WMA link
x // f
is equivalent to f [x].
>> b // a
a [b]
>> c // b // a
a [b [c]]
Precedence
on, logic, comparison, datentime, attributes and binary)
Precedence[op]
returns the precedence of the built-in operator op.
>> Precedence[Plus]
310.
>> Precedence[Plus] < Precedence[Times]
True
Unknown symbols have precedence 670:
>> Precedence[f]
670.
Other expressions have precedence 1000:
>> Precedence[a + b]
1000.
Prefix (@)
WMA link
f @ x
is equivalent to f [x].
423
>> a @ b
a [b]
>> a @ b @ c
a [b [c]]
>> p[3]
∗3
>> Format[q[x_]] := Prefix[{x}, "~", 350]
>> q[a+b]
∼ (a + b)
>> q[a*b]
∼ ab
>> q[a]+b
b+ ∼ a
The prefix operator @ is parsed to an expression before evaluation:
>> Hold[a @ b @ c @ d @ e @ f @ x]
[ [ [ [ [ [ ]]]]]]
Hold a b c d e f [x]
Right
WMA link
Right
is used with operator formatting constructs to specify a right-associative operator.
Row
WMA link
Row[{expr, ...}]
formats several expressions inside a RowBox.
Style
WMA link
424
Style[expr, options]
displays expr formatted using the specified option settings.
Style[expr, ‘‘style’]’
uses the option settings for the specified style in the current notebook.
Style[expr, color]
displays using the specified color.
Style[expr, Bold]
displays with fonts made bold.
Style[expr, Italic]
displays with fonts made italic.
Style[expr, Underlined]
displays with fonts underlined.
’Style[expr, Larger]
displays with fonts made larger.
Style[expr, Smaller]
displays with fonts made smaller.
Style[expr, n]
displays with font size n.
Style[expr, Tiny]
Style[expr, Small], etc.
display with fonts that are tiny, small, etc.
Subscript
WMA link
Subscript[a, i]
displays as a_i.
Subsuperscript
WMA link
Subsuperscript[a, b, c]
displays as $a_b∧ c$.
Superscript
WMA link
Superscript[x, y]
displays as x∧ y.
425
>> Superscript[x,3] // TeXForm
x∧ 3
426
33. List Functions
Generalized Lists make up a core part of Mathics. In fact, to first approximation Evaluation works on a
special kind of List called an M-Expression.
As a result, there about a hundred list functions.
Contents
Associations
Associations
An Association maps keys to values and is similar to a dictionary in Python; it is often sparse in that
their key space is much larger than the number of actual keys found in the collection.
Association
WMA link
427
Association[key1 -> val1, key2 -> val2, ...]
<|key1 -> val1, key2 -> val2, ...|>
represents an association between keys and values.
AssociationQ
WMA link
AssociationQ[expr]
return True if expr is a valid Association object, and False otherwise.
Key
WMA link
Key[key]
represents a key used to access a value in an association.
Key[key][assoc]
Keys
WMA link
428
>> Keys[{a -> x, b -> y}]
{ a, b}
Lookup
WMA link
Lookup[assoc, key]
looks up the value associated with key in the association assoc, or Missing[KeyAbsent].
Missing
WMA link
Missing[]
represents a data that is missing.
>> ElementData["Meitnerium","MeltingPoint"]
Missing [NotAvailable]
RowBox
WMA link
RowBox[{...}]
is a box construct that represents a sequence of boxes arranged in a horizontal row.
Values
WMA link
429
Values automatically threads over lists:
>> Values[{<|a -> x, b -> y|>, {c -> z, {}}}]
{{ x, y} , {z, {}}}
Constructing Lists
Constructing Lists
Functions for constructing lists of various sizes and structure.
See also Constructing Vectors.
Array
WMA link
Array[f , n]
returns the n-element list {f [1], ..., f [n]}.
Array[f , n, a]
returns the n-element list {f [a], ..., f [a + n]}.
Array[f , {n, m}, {a, b}]
returns an n-by-m matrix created by applying f to indices ranging from (a, b) to (a + n, b
+ m).
Array[f , dims, origins, h]
returns an expression with the specified dimensions and index origins, with head h (instead
of List).
>> Array[f, 4]
{ f [1] , f [2] , f [3] , f [4]}
ConstantArray
WMA link
ConstantArray[expr, n]
returns a list of n copies of expr.
430
>> ConstantArray[a, 3]
{ a, a, a}
List
WMA link
Normal
WMA link
Normal[expr_]
Brings especial expressions to a normal expression from different especial forms.
Permutations
WMA link
Permutations[list]
gives all possible orderings of the items in list.
Permutations[list, n]
gives permutations up to length n.
Permutations[list, {n}]
gives permutations of length n.
431
>> Permutations[{1, 2, 3}, {2}]
{{1, 2} , {1, 3} , {2, 1} , {2, 3} , {3, 1} , {3, 2}}
Range
WMA link
Range[n]
returns a list of integers from 1 to n.
Range[a, b]
returns a list of integers from a to b.
>> Range[5]
{1, 2, 3, 4, 5}
>> Range[-3, 2]
{−3, −2, −1, 0, 1, 2}
Reap
WMA link
Reap[expr]
gives the result of evaluating expr, together with all values sown during this evaluation. Val-
ues sown with different tags are given in different lists.
Reap[expr, pattern]
only yields values sown with a tag matching pattern. Reap[expr] is equivalent to Reap[
expr, _].
Reap[expr, {pattern1, pattern2, ...}]
uses multiple patterns.
Reap[expr, pattern, f ]
applies f on each tag and the corresponding values sown in the form
f [tag, {e1, e2, ...}].
>> Reap[Sow[2, {x, x, x}]; Sow[3, x]; Sow[4, y]; Sow[4, 1], {_Symbol,
_Integer, x}, f]
{ {{ [ ] [ ]} { [ ]} { [ ]}}}
4, f x, {2, 2, 2, 3} , f y, {4} , f 1, {4} , f x, {2, 2, 2, 3}
432
>> Reap[Reap[Sow[a, x]; Sow[b, 1], _Symbol, Print["Inner: ", #1]&];, _,
f]
Inner: x
{ { [ ]}}
Null, f 1, {b}
RowBox
WMA link
RowBox[{...}]
is a box construct that represents a sequence of boxes arranged in a horizontal row.
Sow
WMA link
Sow[e]
sends the value e to the innermost Reap.
Sow[e, tag]
sows e using tag. Sow[e] is equivalent to Sow[e, Null].
Sow[e, {tag1, tag2, ...}]
uses multiple tags.
Table
WMA link
Table[expr, n]
generates a list of n copies of expr.
Table[expr, {i, n}]
generates a list of the values of expr when i runs from 1 to n.
Table[expr, {i, start, stop, step}]
evaluates expr with i ranging from start to stop, incrementing by step.
Table[expr, {i, {e1, e2, ..., ei}}]
evaluates expr with i taking on the values e1, e2, ..., ei.
>> Table[x, 3]
{ x, x, x }
433
>> Table[i, {i, 2, 6, 2}]
{2, 4, 6}
Tuples
WMA link
Tuples[list, n]
returns a list of all n-tuples of elements in list.
Tuples[{list1, list2, ...}]
returns a list of tuples with elements from the given lists.
>> Tuples[{}, 2]
{}
Elements of Lists
Elements of Lists
Functions for accessing elements of lists using either indices, positions, or patterns of criteria.
434
Append
WMA link
Append[expr, elem]
returns expr with elem appended.
AppendTo
WMA link
AppendTo[s, elem]
append elem to value of s and sets s to the result.
>> s = {};
>> AppendTo[s, 1]
{1}
>> s
{1}
>> AppendTo[y, x]
f [x]
>> y
f [x]
Cases
WMA link
Cases[list, pattern]
returns the elements of list that match pattern.
Cases[list, pattern, ls]
returns the elements matching at levelspec ls.
Cases[list, pattern, Heads->bool]
Match including the head of the expression in the search.
435
>> Cases[{a, 1, 2.5, "string"}, _Integer|_Real]
{1, 2.5}
Count
WMA link
Count[list, pattern]
returns the number of times pattern appears in list.
Count[list, pattern, ls]
counts the elements matching at levelspec ls.
Delete
WMA link
Delete[expr, i]
deletes the element at position i in expr. The position is counted from the end if i is negative.
Delete[expr, {m, n, ...}]
deletes the element at position {m, n, ...}.
Delete[expr, {{m1, n1, ...}, {m2, n2, ...}, ...}]
deletes the elements at several positions.
436
Delete in a 2D array:
>> Delete[{{a, b}, {c, d}}, {2, 1}]
{{ a, b} , {d}}
DeleteCases
WMA link
DeleteCases[list, pattern]
returns the elements of list that do not match pattern.
DeleteCases[list, pattern, levelspec]
removes all parts of $list on levels specified by levelspec that match pattern (not fully imple-
mented).
DeleteCases[list, pattern, levelspec, n]
removes the first n parts of list that match pattern.
437
>> DeleteCases[{a, b, 1, c, 2, 3}, _Symbol]
{1, 2, 3}
Drop
WMA link
Drop[expr, n]
returns expr with the first n elements removed.
Drop a submatrix:
>> A = Table[i*10 + j, {i, 4}, {j, 4}]
{{11, 12, 13, 14} , {21, 22, 23, 24} , {31, 32, 33, 34} , {41, 42, 43, 44}}
Extract
WMA link
Extract[expr, list]
extracts parts of expr specified by list.
Extract[expr, {list1, list2, ...}]
extracts a list of parts.
First
WMA link
First[expr]
returns the first element in expr.
438
>> First[{a, b, c}]
a
>> First[a + b + c]
a
>> First[x]
Nonatomic expression expected.
First [x]
>> First[{}]
{} has zero length and no first element.
[ ]
First {}
FirstCase
WMA link
FirstPosition
WMA link
FirstPosition[expr, pattern]
gives the position of the first element in expr that matches pattern, or Missing[“NotFound”] if
no such element is found.
FirstPosition[expr, pattern, default]
gives default if no element matching pattern is found.
FirstPosition[expr, pattern, default, levelspec]
finds only objects that appear on levels specified by levelspec.
439
>> FirstPosition[{1 + x^2, 5, x^4, a + (1 + x^2)^2}, x^2]
{1, 2}
Insert
WMA link
Insert[list, elem, n]
inserts elem at position n in list. When n is negative, the position is counted from the end.
>> Insert[{a,b,c,d,e}, x, 3]
{ a, b, x, c, d, e}
Last
WMA link
Last[expr]
returns the last element in expr.
>> Last[{}]
{} has zero length and no last element.
[ ]
Last {}
Length
WMA link
Length[expr]
returns the number of elements in expr.
Length of a list:
>> Length[{1, 2, 3}]
3
Length operates on the FullForm of expressions:
>> Length[Exp[x]]
2
>> FullForm[Exp[x]]
Power [E, x]
440
The length of atoms is 0:
>> Length[a]
0
Note that rational and complex numbers are atoms, although their FullForm might suggest the oppo-
site:
>> Length[1/3]
0
>> FullForm[1/3]
Rational [1, 3]
Most
WMA link
Most[expr]
returns expr with the last element removed.
>> Most[a + b + c]
a+b
>> Most[x]
Nonatomic expression expected.
Most [x]
Part
WMA link
Part[expr, i]
returns part i of expr.
>> A[[3]]
c
Negative indices count from the end:
>> {a, b, c}[[-2]]
b
Part can be applied on any expression, not necessarily lists.
>> (a + b + c)[[2]]
b
expr[[0]] gives the head of expr:
>> (a + b + c)[[0]]
Plus
441
Parts of nested lists:
>> M = {{a, b}, {c, d}};
Extract a submatrix of 1st and 3rd row and the two last columns:
>> B = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
Further examples:
>> (a+b+c+d)[[-1;;-2]]
0
>> x[[2]]
Part specification is longer than depth of object.
x [ [2]]
>> B[[1;;-2]] = t;
>> B
442
>> F = Table[i*j*k, {i, 1, 3}, {j, 1, 3}, {k, 1, 3}];
>> F
>> F
Pick
WMA link
Pick[list, sel]
returns those items in list that are True in sel.
Pick[list, sel, patt]
returns those items in list that match patt in sel.
Position
WMA link
Position[expr, patt]
returns the list of positions for which expr matches patt.
Position[expr, patt, ls]
returns the positions on levels specified by levelspec ls.
443
Use Position as an operator:
>> Position[_Integer][{1.5, 2, 2.5}]
{{2}}
Prepend
WMA link
Prepend[expr, item]
returns expr with item prepended to its elements.
Prepend[expr]
Prepend[elem][expr] is equivalent to Prepend[expr,elem].
PrependTo
WMA link
PrependTo[s, item]
prepends item to value of s and sets s to the result.
Assign s to a list
>> s = {1, 2, 4, 9}
{1, 2, 4, 9}
>> PrependTo[y, x]
f [x, a, b, c]
444
>> y
f [x, a, b, c]
ReplacePart
WMA link
>> ReplacePart[{{a, b}, {c, d}}, {{2, 1} -> t, {1, 1} -> t}]
{{t, b} , {t, d}}
Rest
WMA link
Rest[expr]
returns expr with the first element removed.
445
>> Rest[{a, b, c}]
{b, c}
>> Rest[a + b + c]
b+c
>> Rest[x]
Nonatomic expression expected.
Rest [x]
>> Rest[{}]
Cannot take Rest of expression {} with length zero.
[ ]
Rest {}
RowBox
WMA link
RowBox[{...}]
is a box construct that represents a sequence of boxes arranged in a horizontal row.
Select
WMA link
Span (;;)
WMA link
Span
is the head of span ranges like 1;;3.
>> ;; // FullForm
Span [1, All]
446
>> 1;;4;;2 // FullForm
Span [1, 4, 2]
Take
WMA link
Take[expr, n]
returns expr with all but the first n elements removed.
Take a submatrix:
>> A = {{a, b, c}, {d, e, f}};
>> Take[A, 2, 2]
{{ a, b} , {d, e}}
UpTo
WMA link
Upto[n]
is a symbolic specification that represents up to n objects or positions. If n objects or positions are
available, all are used. If fewer are available, only those available are used.
TakeLargestBy
WMA link
447
TakeLargestBy[list, f , n]
returns the a sorted list of the n largest items in list using f to retrieve the items’ keys to
compare them.
TakeSmallestBy
WMA link
TakeSmallestBy[list, f , n]
returns the a sorted list of the n smallest items in list using f to retrieve the items’ keys to
compare them.
Predicates on Lists
Predicates on List
ContainsOnly
WMA link
ContainsOnly[list1, list2]
yields True if list1 contains only elements that appear in list2.
448
Rearranging and Restructuring Lists
Rearranging and Restructuring Lists
These functions reorder and rearrange lists.
Catenate
WMA link
Complement
WMA link
The sets all, e1, etc can have any head, which must all match.
The returned expression has the same head as the input expressions. The expression will be sorted and
each element will only occur once.
>> Complement[{a, b, c}, {a, c}]
{b}
DeleteDuplicates
WMA link
DeleteDuplicates[list]
deletes duplicates from list.
DeleteDuplicates[list, test]
deletes elements from list based on whether the function test yields True on pairs of elements.
DeleteDuplicates does not change the order of the remaining elements.
449
>> DeleteDuplicates[{3,2,1,2,3,4}, Less]
{3, 2, 1}
Flatten
WMA link
Flatten[expr]
flattens out nested lists in expr.
Flatten[expr, n]
stops flattening at level n.
Flatten[expr, n, h]
flattens expressions with head h instead of List.
Gather
WMA link
Gather[list, test]
gathers elements of list into sub lists of items that are the same according to test.
Gather[list]
gathers elements of list into sub lists of items that are the same.
The order of the items inside the sub lists is the same as in the original list.
>> Gather[{1, 7, 3, 7, 2, 3, 9}]
{{1} , {7, 7} , {3, 3} , {2} , {9}}
450
GatherBy
WMA link
GatherBy[list, f ]
gathers elements of list into sub lists of items whose image under f identical.
GatherBy[list, {f , g, ...}]
gathers elements of list into sub lists of items whose image under f identical. Then, gathers
these sub lists again into sub sub lists, that are identical under $g.
>> GatherBy[{{1, 2}, {2, 1}, {3, 5}, {5, 1}, {2, 2, 2}}, {Total, Length
}]
{{{{1, 2} , {2, 1}}} , {{{3, 5}}} , {{{5, 1}} , {{2, 2, 2}}}}
Intersection
WMA link
Intersection[a, b, ...]
gives the intersection of the sets. The resulting list will be sorted and each element will only
occur once.
>> Intersection[{{a, b}, {x, y}}, {{x, x}, {x, y}, {x, z}}]
{{ x, y}}
Join
WMA link
Join[l1, l2]
concatenates the lists l1 and l2.
451
>> Join[{a, b}, {c, d, e}]
{ a, b, c, d, e}
PadLeft
WMA link
PadLeft[list, n]
pads list to length n by adding 0 on the left.
PadLeft[list, n, x]
pads list to length n by adding x on the left.
PadLeft[list, {n1, $n2, ...}, x]
pads list to lengths n1, n2 at levels 1, 2, ... respectively by adding x on the left.
PadLeft[list, n, x, m]
pads list to length n by adding x on the left and adding a margin of m on the right.
PadLeft[list, n, x, {m1, m2, ...}]
pads list to length n by adding x on the left and adding margins of m1, m2, ... on levels 1, 2, ...
on the right.
PadLeft[list]
turns the ragged list list into a regular list by adding 0 on the left.
452
PadRight
WMA link
PadRight[list, n]
pads list to length n by adding 0 on the right.
PadRight[list, n, x]
pads list to length n by adding x on the right.
PadRight[list, {n1, $n2, ...}, x]
pads list to lengths n1, n2 at levels 1, 2, ... respectively by adding x on the right.
PadRight[list, n, x, m]
pads list to length n by adding x on the left and adding a margin of m on the left.
PadRight[list, n, x, {m1, m2, ...}]
pads list to length n by adding x on the right and adding margins of m1, m2, ... on levels 1, 2,
... on the left.
PadRight[list]
turns the ragged list list into a regular list by adding 0 on the right.
Partition
WMA link
Partition[list, n]
partitions list into sublists of length n.
Parition[list, n, d]
partitions list into sublists of length n which overlap d indices.
453
Reverse
WMA link
Reverse[expr]
reverses the order of expr’s items (on the top level)
Reverse[expr, n]
reverses the order of items in expr on level n
Reverse[expr, {n1, n2, ...}]
reverses the order of items in expr on levels n1, n2, ...
Riffle
WMA link
Riffle[list, x]
inserts a copy of x between each element of list.
Riffle[{a1, a2, ...}, {b1, b2, ...}]
interelements the elements of both lists, returning {a1, b1, a2, b2, ...}.
RotateLeft
WMA link
454
RotateLeft[expr]
rotates the items of expr’ by one item to the left.
RotateLeft[expr, n]
rotates the items of expr’ by n items to the left.
RotateLeft[expr, {n1, n2, ...}]
rotates the items of expr’ by n1 items to the left at the first level, by n2 items to the left at the
second level, and so on.
>> RotateLeft[Range[10], 3]
{4, 5, 6, 7, 8, 9, 10, 1, 2, 3}
RotateRight
WMA link
RotateRight[expr]
rotates the items of expr’ by one item to the right.
RotateRight[expr, n]
rotates the items of expr’ by n items to the right.
RotateRight[expr, {n1, n2, ...}]
rotates the items of expr’ by n1 items to the right at the first level, by n2 items to the right at
the second level, and so on.
>> RotateRight[Range[10], 3]
{8, 9, 10, 1, 2, 3, 4, 5, 6, 7}
Split
WMA link
Split[list]
splits list into collections of consecutive identical elements.
Split[list, test]
splits list based on whether the function test yields True on consecutive elements.
455
>> Split[{x, x, x, y, x, y, y, z}]
{{ x, x, x } , {y} , { x } , {y, y} , {z}}
SplitBy
WMA link
SplitBy[list, f ]
splits list into collections of consecutive elements that give the same result when f is applied.
Tally
WMA link
Tally[list]
counts and returns the number of occurrences of objects and returns the result as a list of pairs
{object, count}.
Tally[list, test]
counts the number of occurrences of objects and uses $test to determine if two objects should
be counted in the same bin.
Tally always returns items in the order as they first appear in list:
>> Tally[{b, b, a, a, a, d, d, d, d, c}]
{{b, 2} , { a, 3} , {d, 4} , {c, 1}}
Union
WMA link
456
Union[a, b, ...]
gives the union of the given set or sets. The resulting list will be sorted and each element will
only occur once.
>> Union[{{a, 1}, {b, 2}}, {{c, 1}, {d, 3}}, SameTest->(SameQ[Last[#1],
Last[#2]]&)]
{{b, 2} , {c, 1} , {d, 3}}
457
34. Low level Format definitions
Contents
$BoxForms
WMA link
>> $BoxForms
{StandardForm, TraditionalForm}
MakeBoxes
WMA link
MakeBoxes[expr]
is a low-level formatting primitive that converts expr to box form, without evaluating it.
\( ... \)
directly inputs box objects.
>> \( a \+ b \% c\)
UnderoverscriptBox [a, b, c]
>> \(x \+ y \)
[ ]
UnderscriptBox x, y
458
ToBoxes
WMA link
ToBoxes[expr]
evaluates expr and converts the result to box form.
>> ToBoxes[a + b]
[ ]
RowBox {a, +, b}
459
35. Mathematical Functions
Basic arithmetic functions, including complex number arithmetic.
Contents
$Assumptions
WMA link
$Assumptions
is the default setting for the Assumptions option used in such functions as Simplify, Refine,
and Integrate.
Abs
Absolute value (SymPy, WMA)
Abs[x]
returns the absolute value of x.
>> Abs[-3]
3
>> Plot[Abs[x], {x, -4, 4}]
0.8
0.6
0.4
0.2
2 4 6 8 10
−0.2
460
>> Abs[3 + I]
√
10
>> Abs[3.0 + I]
3.16228
All of the below evaluate to Infinity:
>> Abs[Infinity] == Abs[I Infinity] == Abs[ComplexInfinity]
True
Arg
Argument (complex analysis) (WMA link)
Arg[z, method_option]
returns the argument of a complex value z.
Assuming
WMA link
Assuming[cond, expr]
Evaluates expr assuming the conditions cond.
461
>> $Assumptions = { x > 0 }
{ x > 0}
Boole
WMA link
Boole[expr]
returns 1 if expr is True and 0 if expr is False.
>> Boole[2 == 2]
1
>> Boole[7 < 5]
0
>> Boole[a == 7]
Boole [a==7]
Complex
WMA link
Complex
is the head of complex numbers.
Complex[a, b]
constructs the complex number a + I b.
ConditionalExpression
WMA link
462
ConditionalExpression[expr, cond]
returns expr if cond evaluates to True, Undefined if cond evaluates to False.
>> f /. x -> 2
4
>> f /. x -> -2
Undefined
ConditionalExpression uses assumptions to evaluate the condition:
>> $Assumptions = x > 0;
Conjugate
Complex Conjugate (WMA)
Conjugate[z]
returns the complex conjugate of the complex number z.
>> Conjugate[3 + 4 I]
3 − 4I
>> Conjugate[3]
3
>> Conjugate[a + b * I]
Conjugate [a] − IConjugate [b]
463
DirectedInfinity
WMA link
DirectedInfinity[z]
represents an infinite multiple of the complex number z.
DirectedInfinity[]
is the same as ComplexInfinity.
>> DirectedInfinity[1]
∞
>> DirectedInfinity[]
ComplexInfinity
>> DirectedInfinity[1 + I]
( )
1 I √
+ 2∞
2 2
>> 1 / DirectedInfinity[1 + I]
0
>> DirectedInfinity[1] + DirectedInfinity[-1]
Indeterminate expression -Infinity + Infinity encountered.
Indeterminate
>> DirectedInfinity[0]
Indeterminate expression 0 Infinity encountered.
Indeterminate
I
Imaginary unit (WMA)
I
represents the imaginary number Sqrt[-1].
>> I^2
−1
>> (3+I)*(3-I)
10
Im
WMA link
Im[z]
returns the imaginary component of the complex number z.
>> Im[3+4I]
4
464
>> Plot[{Sin[a], Im[E^(I a)]}, {a, 0, 2 Pi}]
20
15
10
1 2 3 4 5
Integer
WMA link
Integer
is the head of integers.
>> Head[5]
Integer
Piecewise
WMA link
Piecewise[{{expr1, cond1}, ...}]
represents a piecewise function.
Piecewise[{{expr1, cond1}, ...}, expr]
represents a piecewise function with default expr.
Heaviside function
>> Piecewise[{{0, x <= 0}}, 1]
[ ]
Piecewise {{0, x<=0}} , 1
>> Integrate[Piecewise[{{1, x <= 0}, {-1, x > 0}}], {x, -1, 2}]
−1
Piecewise defaults to 0 if no other case is matching.
>> Piecewise[{{1, False}}]
0
465
>> Plot[Piecewise[{{Log[x], x > 0}, {x*-0.5, x < 0}}], {x, -1, 1}]
0.6
0.4
0.2
−10 −5 5 10
−0.2
−0.4
Product
WMA link
466
>> primorial[12]
7420738134810
Rational
WMA link
Rational
is the head of rational numbers.
Rational[a, b]
constructs the rational number a / b.
>> Head[1/2]
Rational
>> Rational[1, 2]
1
2
Re
WMA link
Re[z]
returns the real component of the complex number z.
>> Re[3+4I]
3
>> Plot[{Cos[a], Re[E^(I a)]}, {a, 0, 2 Pi}]
2.0
1.5
1.0
0.5
−2 −1 1 2
Real
WMA link
Real
is the head of real (inexact) numbers.
>> x = 3. ^ -20;
467
>> InputForm[x]
2.8679719907924413*∧ − 10
>> Head[x]
Real
RealNumberQ
RealNumberQ[expr]
returns True if expr is an explicit number with no imaginary component.
>> RealNumberQ[10]
True
>> RealNumberQ[4.0]
True
>> RealNumberQ[1+I]
False
>> RealNumberQ[0 * I]
True
>> RealNumberQ[0.0 * I]
True
Sign
WMA link
Sign[x]
return -1, 0, or 1 depending on whether x is negative, zero, or positive.
>> Sign[19]
1
>> Sign[-6]
−1
>> Sign[0]
0
>> Sign[{-5, -10, 15, 20, 0}]
{−1, −1, 1, 1, 0}
468
Sum
WMA link
469
>> Sum[f[i], {i, 1, 7}]
f [1] + f [2] + f [3] + f [4] + f [5] + f [6] + f [7]
470
36. Mathematical Optimization
Mathematical optimization is the selection of a best element, with regard to some criterion, from some
set of available alternatives.
Optimization problems of sorts arise in all quantitative disciplines from computer science and engi-
neering to operations research and economics, and the development of solution methods has been of
interest in mathematics for centuries.
We intend to provide local and global optimization techniques, both numeric and symbolic.
Contents
Minimize . . . . . . . 471
Maximize . . . . . . . 471
Maximize
WMA link
Maximize[f , x]
compute the maximum of f respect x that change between a and b.
Minimize
WMA link
Minimize[f , x]
compute the minimum of f respect x that change between a and b.
471
37. Matrices and Linear Algebra
Construction and manipulation of Matrices.
Contents
Constructing Matrices
Constructing Matrices
Methods for constructing Matrices.
BoxMatrix
WMA link
BoxMatrix[$s]
Gives a box shaped kernel of size 2 s + 1.
>> BoxMatrix[3]
{{1, 1, 1, 1, 1, 1, 1} , {1, 1, 1, 1, 1, 1, 1} , {1, 1, 1, 1, 1, 1, 1} , {1, 1, 1, 1, 1, 1, 1} , {1, 1, 1, 1, 1, 1, 1} , {1, 1, 1, 1, 1, 1, 1} , {1, 1, 1
DiagonalMatrix
WMA link
DiagonalMatrix[list]
gives a matrix with the values in list on its diagonal and zeroes elsewhere.
>> MatrixForm[%]
1 0 0
0 2 0
0 0 3
DiamondMatrix
WMA link
472
DiamondMatrix[$s]
Gives a diamond shaped kernel of size 2 s + 1.
>> DiamondMatrix[3]
{{0, 0, 0, 1, 0, 0, 0} , {0, 0, 1, 1, 1, 0, 0} , {0, 1, 1, 1, 1, 1, 0} , {1, 1, 1, 1, 1, 1, 1} , {0, 1, 1, 1, 1, 1, 0} , {0, 0, 1, 1, 1, 0, 0} , {0, 0, 0
DiskMatrix
WMA link
DiskMatrix[$s]
Gives a disk shaped kernel of size 2 s + 1.
>> DiskMatrix[3]
{{0, 0, 1, 1, 1, 0, 0} , {0, 1, 1, 1, 1, 1, 0} , {1, 1, 1, 1, 1, 1, 1} , {1, 1, 1, 1, 1, 1, 1} , {1, 1, 1, 1, 1, 1, 1} , {0, 1, 1, 1, 1, 1, 0} , {0, 0, 1
IdentityMatrix
WMA link
IdentityMatrix[n]
gives the identity matrix with n rows and columns.
>> IdentityMatrix[3]
{{1, 0, 0} , {0, 1, 0} , {0, 0, 1}}
Parts of Matrices
Parts of Matrices
Methods for manipulating Matrices.
Diagonal
WMA link
Diagonal[m]
gives a list with the values in the diagonal of the matrix m.
Diagonal[m, k]
gives a list with the values in the k diagonal of the matrix m.
473
Get the diagonal of a nonsquare matrix:
>> Diagonal[{{1, 2, 3}, {4, 5, 6}}]
{1, 5}
474
38. Message-related functions.
Contents
$Aborted
WMA link
$Aborted
is returned by a calculation that has been aborted.
$Failed
WMA link
$Failed
is returned by some functions in the event of an error.
Check
WMA link
Check[expr, failexpr]
evaluates expr, and returns the result, unless messages were generated, in which case it eval-
uates and failexpr will be returned.
Check[expr, failexpr, {s1::t1,s2::t2,...}]
checks only for the specified messages.
475
>> Check[1/0, err, Power::infy]
Infinite expression 1 / 0 encountered.
err
Failure
WMA link
Failure[tag, assoc]
represents a failure of a type indicated by tag, with details given by the association assoc.
General
WMA link
General
is a symbol to which all general-purpose messages are assigned.
>> General::argr
‘1‘ called with 1 argument; ‘2‘ arguments are expected.
Message
WMA link
MessageName (::)
WMA link
MessageName[symbol, tag]
symbol::tag
identifies a message.
476
MessageName is the head of message IDs of the form symbol::tag.
>> FullForm[a::b]
MessageName [a, “b”]
Off
WMA link
Off[symbol::tag]
turns a message off so it is no longer printed.
>> Off[Power::infy]
>> 1 / 0
ComplexInfinity
>> {0 ^ 0,}
{Indeterminate, Null}
On
WMA link
On[symbol::tag]
turns a message on for printing.
>> Off[Power::infy]
>> 1 / 0
ComplexInfinity
>> On[Power::infy]
>> 1 / 0
Infinite expression 1 / 0 encountered.
ComplexInfinity
Quiet
WMA link
477
Quiet[expr, {s1::t1, ...}]
evaluates expr, without messages {s1::t1, ...} being displayed.
Quiet[expr, All]
evaluates expr, without any messages being displayed.
Quiet[expr, None]
evaluates expr, without all messages being displayed.
Quiet[expr, off , on]
evaluates expr, with messages off being suppressed, but messages on being displayed.
Same as above:
>> Quiet[1/0, All]
ComplexInfinity
Syntax
WMA link
Syntax
is a symbol to which all syntax messages are assigned.
>> 1 +
>> Sin[1)
>> ^ 2
>> 1.5‘‘
478
39. Numerical Functions
Support for approximate real numbers and exact real numbers represented in algebraic or symbolic
form.
Contents
Chop
WMA link
Chop[expr]
replaces floating point numbers close to 0 by 0.
Chop[expr, delta]
uses a tolerance of delta. The default tolerance is 10^-10.
N
WMA link
N[expr, prec]
evaluates expr numerically with a precision of prec digits.
479
You can manually assign numerical values to symbols. When you do not specify a precision, MachinePrecision
is taken.
>> N[a] = 10.9
10.9
>> a
a
N automatically threads over expressions, except when a symbol has attributes NHoldAll, NHoldFirst,
or NHoldRest.
>> N[a + b]
10.9 + b
>> N[a, 20]
a
>> N[a, 20] = 11;
>> N[c, 3]
c
>> N[c, 11]
11.000000000
You can also use UpSet or TagSet to specify values for N:
>> N[d] ^= 5;
However, the value will not be stored in UpValues, but in NValues (as for Set):
>> UpValues[d]
{}
>> NValues[d]
{HoldPattern [N [d, MachinePrecision]] :>5}
>> e /: N[e] = 6;
>> N[e]
6.
Values for N[expr] must be associated with the head of expr:
>> f /: N[e[f]] = 7;
Tag f not found or too deep for an assigned rule.
480
You can use Condition:
>> N[g[x_, y_], p_] := x + y * Pi /; x + y > 3
Rationalize
WMA link
Rationalize[x]
converts a real number x to a nearby rational number with small denominator.
Rationalize[x, dx]
finds the rational number lies within dx of x.
>> Rationalize[2.2]
11
5
For negative x, -Rationalize[-x] == Rationalize[x] which gives symmetric results:
>> Rationalize[-11.5, 1]
−11
481
Not all numbers can be well approximated.
>> Rationalize[N[Pi]]
3.14159
Find the exact rational representation of N[Pi]
>> Rationalize[N[Pi], 0]
245850922
78256779
Round
WMA link
Round[expr]
rounds expr to the nearest integer.
Round[expr, k]
rounds expr to the closest multiple of k.
>> Round[10.6]
11
>> Round[0.06, 0.1]
0.1
>> Round[0.04, 0.1]
0.
Constants can be rounded too
>> Round[Pi, .5]
3.
>> Round[Pi^2]
10
Round to exact value
>> Round[2.6, 1/3]
8
3
>> Round[10, Pi]
3π
Round complex numbers
>> Round[6/(2 + 3 I)]
1−I
>> Round[1 + 2 I, 2 I]
2I
Round Negative numbers too
>> Round[-1.4]
−1
Expressions other than numbers remain unevaluated:
482
>> Round[x]
Round [x]
>> Round[1.5, k]
Round [1.5, k]
483
40. Operations on Vectors
In mathematics and physics, a vector is a term that refers colloquially to some quantities that cannot be
expressed by a single number. It is also a row or column of a matrix.
In computer science, it is an array data structure consisting of collection of elements identified by at
least on array index or key.
In Mathics3 vectors as are Lists. One never needs to distinguish between row and column vectors. As
with other objects vectors can mix number and symbolic elements.
Vectors can be long, dense, or sparse.
Here are the grouping we have for Vector Operations:
Contents
Constructing Vectors
Constructing Vectors
Functions for constructing lists of various sizes and structure.
See also Constructing Lists.
AngleVector
WMA link
AngleVector[phi]
returns the point at angle phi on the unit circle.
AngleVector[{r, phi}]
returns the point at angle phi on a circle of radius r.
AngleVector[{x, y}, phi]
returns the point at angle phi on a circle of radius 1 centered at {x, y}.
AngleVector[{x, y}, {r, phi}]
returns point at angle phi on a circle of radius r centered at {x, y}.
484
Mathematical Operations
Mathematical Operation
Cross
Cross product (SymPy, WMA)
Cross[a, b]
computes the vector cross product of a and b.
Visualize this:
>> Graphics[{Arrow[{{0, 0}, v1}], Red, Arrow[{{0, 0}, v2}]}, Axes ->
True]
2.5
2.0
1.5
1.0
0.5
Curl
Curl (SymPy, WMA)
485
Two-dimensional Curl:
>> Curl[{y, -x}, {x, y}]
−2
>> v[x_, y_] := {Cos[x] Sin[y], Cos[y] Sin[x]}
Norm
Matrix norms induced by vector p-norms (SymPy, WMA)
Norm[m, p]
computes the p-norm of matrix m.
Norm[m]
computes the 2-norm of matrix m.
486
Vector Space Operations
Vector Space Operation
KroneckerProduct
Kronecker product (SymPy, WMA)
Show symbolically how the Kronecker product works on two two-dimensional arrays:
>> a = {{a11, a12}, {a21, a22}}; b = {{b11, b12}, {b21, b22}};
>> KroneckerProduct[a, b]
{{a11b11, a11b12, a12b11, a12b12} , {a11b21, a11b22, a12b21, a12b22} , {a21b11, a21b12, a22b11, a22b12} , {a21b21, a
Normalize
WMA link
Normalize[v]
calculates the normalized vector v.
Normalize[z]
calculates the normalized complex number z.
>> Normalize[1 + I]
( )
1 I √
+ 2
2 2
Projection
WMA link
Projection[u, v]
gives the projection of the vector u onto v
487
Projection of two three-dimensional Integer vectors:
>> Projection[{5, 6, 7}, {1, 0, 0}]
{5, 0, 0}
UnitVector
Unit vector (WMA)
UnitVector[n, k]
returns the n-dimensional unit vector with a 1 in position k.
UnitVector[k]
is equivalent to UnitVector[2, k].
>> UnitVector[2]
{0, 1}
>> UnitVector[4, 3]
{0, 0, 1, 0}
VectorAngle
WMA link
VectorAngle[u, v]
gives the angles between vectors u and v
488
>> VectorAngle[{1, 0}, {0, 1}]
π
2
>> VectorAngle[{1, 2}, {3, 1}]
π
4
>> VectorAngle[{1, 1, 0}, {1, 0, 1}]
π
3
489
41. Options Management
A number of functions have various options which control the behavior or the default behavior that
function. Default options can be queried or set.
WMA link
Contents
All
WMA link
All
is an option value for a number of functions indicating to include everything.
While in Take of section 33, All extracts as a column matrix the first element as a list for each of the list
elements:
>> Take[{{1, 3}, {5, 7}}, All, {1}]
{{1} , {5}}
In Plot of section 24 </url>, setting the Mesh of section 13 option to All will show the specific plot
points:
>> Plot[x^2, {x, -1, 1}, MaxRecursion->5, Mesh->All]
1.0
0.5
−2 −1 1 2
−0.5
−1.0
490
Default
WMA link
Default[f ]
gives the default value for an omitted parameter of f.
Default[f , k]
gives the default value for a parameter on the kth position.
Default[f , k, n]
gives the default value for the kth parameter out of n.
>> f[]
1
Default values are stored in DefaultValues:
>> DefaultValues[f]
{ [ [ ]] }
HoldPattern Default f :>1
Note that the position of a parameter is relative to the pattern, not the matching expression:
>> h[] /. h[___, ___, x_., y_., ___] -> {x, y}
{{3, 5} , {4, 5}}
FilterRules
WMA link
FilterRules[rules, pattern]
gives those rules that have a left side that matches pattern.
FilterRules[rules, {pattern1, pattern2, ...}]
gives those rules that have a left side that match at least one of pattern1, pattern2, ...
>> FilterRules[{x -> 100, y -> 1000, z -> 10000}, {a, b, x, z}]
{ x − > 100, z− > 10000}
None
WMA link
None
is a setting value for many options.
491
Plot3D shows the mesh grid between computed points by default. This the Mesh of section ?? option.
However, you hide the mesh by setting the Mesh option value to None:
>> Plot3D[{x^2 + y^2, -x^2 - y^2}, {x, -2, 2}, {y, -2, 2}, BoxRatios->
Automatic, Mesh->None]
2.0
1.5
1.0
0.5
−2 −1 1 2
NotOptionQ
WMA link
NotOptionQ[expr]
returns True if expr does not have the form of a valid option specification.
>> NotOptionQ[x]
True
>> NotOptionQ[2]
True
>> NotOptionQ["abc"]
True
>> NotOptionQ[a -> True]
False
OptionQ
WMA link
OptionQ[expr]
returns True if expr has the form of a valid option specification.
492
>> OptionQ[{a :> True}]
True
Options lists are flattened when are applied, so
>> OptionQ[{a -> True, {b->1, "c"->2}}]
True
>> OptionQ[{a -> True, {b->1, c}}]
False
>> OptionQ[{a -> True, F[b->1,c->2]}]
False
OptionQ returns False if its argument is not a valid option specification:
>> OptionQ[x]
False
OptionValue
WMA link
OptionValue[name]
gives the value of the option name as specified in a call to a function with OptionsPattern.
OptionValue[f , name]
recover the value of the option name associated to the symbol f.
OptionValue[f , optvals, name]
recover the value of the option name associated to the symbol f, extracting the values from
optvals if available.
OptionValue[..., list]
recover the value of the options in list .
Options
WMA link
493
Options[f ]
gives a list of optional arguments to f and their default values.
>> Options[f]
{n:>2}
>> f[x]
x2
>> f[x, n -> 3]
x3
Delayed option rules are evaluated just when the corresponding OptionValue is called:
>> f[a :> Print["value"]] /. f[OptionsPattern[{}]] :> (OptionValue[a];
Print["between"];
value
OptionValue[a]);
between
value
SetOptions
WMA link
SetOptions[s, name1 -> value1, name2 -> value2, ...]
sets the specified default options for a symbol s. The entire set of options for s is returned.
494
One way to find the default options for a symbol is to use SetOptions passing no association pairs:
>> SetOptions[Plot]
{
1
AspectRatio− > , Axes− > True, AxesStyle
GoldenRatio
− > {} , Background− > Automatic, Exclusions− > Automatic, ImageSize
− > Automatic, LabelStyle− > {} , MaxRecursion
− > Automatic, Mesh− > None, PlotPoints− > None, PlotRange
}
− > Automatic, PlotRangePadding− > Automatic, TicksStyle− > {}
495
42. Physical and Chemical data
Contents
ElementData . . . . . . 497
ElementData
WMA link
ElementData["name‘‘,”property"]
gives the value of the property for the chemical specified by name.
ElementData[n, "property"]
gives the value of the property for the nth chemical element.
>> ElementData[74]
Tungsten
496
>> ListPlot[Table[ElementData[z, "AtomicWeight"], {z, 118}]]
1.0
0.5
−0.5
−1.0
497
43. Procedural Programming
Procedural programming is a programming paradigm, derived from imperative programming, based
on the concept of the procedure call. This term is sometimes compared and contrasted with Functional
Programming.
Procedures (a type of routine or subroutine) simply contain a series of computational steps to be carried
out. Any given procedure might be called at any point during a program’s execution, including by other
procedures or itself.
Procedural functions are integrated into Mathics3 symbolic programming environment.
Contents
Abort
WMA link
Abort[]
aborts an evaluation completely and returns $Aborted.
$Aborted
Break
WMA link
Break[]
exits a For, While, or Do loop.
>> n = 0;
>> n
11
498
Catch
WMA link
Catch[expr]
returns the argument of the first Throw generated in the evaluation of expr.
Catch[expr, form]
returns value from the first Throw[value, tag] for which form matches tag.
Catch[expr, form, f ]
returns f [value, tag].
CompoundExpression (;)
WMA link
CompoundExpression[e1, e2, ...]
e1; e2; ...
evaluates its arguments in turn, returning the last result.
>> a; b; c; d
d
If the last argument is omitted, Null is taken:
>> a;
Continue
WMA link
Continue[]
continues with the next iteration in a For, While, or Do loop.
499
Do
WMA link
Do[expr, {max}]
evaluates expr max times.
Do[expr, {i, max}]
evaluates expr max times, substituting i in expr with values from 1 to max.
Do[expr, {i, min, max}]
starts with i = max.
Do[expr, {i, min, max, step}]
uses a step size of step.
Do[expr, {i, {i1, i2, ...}}]
uses values i1, i2, ... for i.
Do[expr, {i, imin, imax}, {j, jmin, jmax}, ...]
evaluates expr for each j from jmin to jmax, for each i from imin to imax, etc.
For
WMA link
>> n
3628800
>> n == 10!
True
500
If
WMA link
>> If[1<2, a, b]
a
If the second branch is not specified, Null is taken:
>> If[1<2, a]
a
>> If[False, a] //FullForm
Null
You might use comments (inside (* and *)) to make the branches of If more readable:
>> If[a, (*then*)b, (*else*)c];
Interrupt
WMA link
Interrupt[]
Interrupt an evaluation and returns $Aborted.
$Aborted
Return
WMA link
Return[expr]
aborts a function call and returns expr.
>> f[-1]
0
>> Do[If[i > 3, Return[]]; Print[i], {i, 10}]
1
2
3
501
>> g[-1]
−1
Switch
WMA link
>> Switch[2, 1, x, 2, y, 3, z]
y
>> Switch[5, 1, x, 2, y]
[ ]
Switch 5, 1, x, 2, y
>> Switch[5, 1, x, 2, a, _, b]
b
>> Switch[2, 1]
Switch called with 2 arguments. Switch must be called with an odd
number of arguments.
Switch [2, 1]
Throw
WMA link
Throw[‘value‘]
stops evaluation and returns ‘value‘ as the value of the nearest enclosing Catch.
Catch[‘value‘, ‘tag‘]
is caught only by ‘Catch[expr,form]‘, where tag matches form.
Which
WMA link
502
>> n = 5;
>> Which[n == 3, x, n == 5, y]
y
>> f[-3]
3
If no test yields True, Which returns Null:
>> Which[False, a]
If a test does not evaluate to True or False, evaluation stops and a Which expression containing the
remaining cases is returned:
>> Which[False, a, x, b, True, c]
Which [x, b, True, c]
While
WMA link
While[test, body]
evaluates body as long as test evaluates to True.
While[test]
runs the loop without any body.
>> a
3
503
44. Rules and Patterns
The concept of transformation rules for arbitrary symbolic patterns is key in Mathics3.
Also, functions can get applied or transformed depending on whether or not functions arguments
match.
Some examples: » a + b + c /. a + b -> t = c + t » a + 2 + b + c + x * y /. n_Integer + s__Symbol + rest_ ->
{n, s, rest} = {2, a, b + c + x y} » f[a, b, c, d] /. f[first_, rest___] -> {first, {rest}} = {a, {b, c, d}}
Tests and Conditions: » f[4] /. f[x_?(# > 0&)] -> x ∧ 2 = 16 » f[4] /. f[x_] /; x > 0 -> x ∧ 2 = 16
Elements in the beginning of a pattern rather match fewer elements: » f[a, b, c, d] /. f[start__, end__] ->
{{start}, {end}} = {{a}, {b, c, d}}
Optional arguments using Optional: » f[a] /. f[x_, y_:3] -> {x, y} = {a, 3}
Options using OptionsPattern and OptionValue: » f[y, a->3] /. f[x_, OptionsPattern[{a->2, b->5}]] ->
{x, OptionValue[a], OptionValue[b]} = {y, 3, 5}
The attributes Flat, Orderless, and OneIdentity affect pattern matching.
Contents
Alternatives (|)
WMA link
>> a+b+c+d/.(a|b)->t
c + d + 2t
Alternatives can also be used for string expressions
>> StringReplace["0123 3210", "1" | "2" -> "X"]
0XX3 3XX0
Blank
WMA link
504
Blank[]
_
represents any single expression in a pattern.
Blank[h]
_h
represents any expression with head h.
>> MatchQ[a + b, _]
True
Patterns of the form _h can be used to test the types of objects:
>> MatchQ[42, _Integer]
True
>> MatchQ[1.0, _Integer]
False
>> {42, 1.0, x} /. {_Integer -> "integer", _Real -> "real"} // InputForm
{“integer”, “real”, x }
BlankNullSequence
WMA link
BlankNullSequence[]
___
represents any sequence of expression elements in a pattern, including an empty sequence.
BlankSequence
WMA link
BlankSequence[]
__
represents any non-empty sequence of expression elements in a pattern.
BlankSequence[h]
__h
represents any sequence of elements, all of which have head h.
505
>> MatchQ[f[], f[__]]
False
__h will match only if all elements have head h:
>> MatchQ[f[1, 2, 3], f[__Integer]]
True
>> MatchQ[f[1, 2.0, 3], f[__Integer]]
False
The value captured by a named BlankSequence pattern is a Sequence object:
>> f[1, 2, 3] /. f[x__] -> x
Sequence [1, 2, 3]
Condition (/;)
WMA link
Condition[pattern, expr]
pattern /; expr
places an additional constraint on pattern that only allows it to match if expr evaluates to True.
The controlling expression of a Condition can use variables from the pattern:
>> f[3] /. f[x_] /; x>0 -> t
t
>> f[-3] /. f[x_] /; x>0 -> t
f [ − 3]
>> f[3]
p [3]
>> f[-3]
f [ − 3]
Dispatch
WMA link
Dispatch[rulelist]
Introduced for compatibility. Currently, it just return rulelist. In the future, it should return an
optimized DispatchRules atom, containing an optimized set of rules.
506
>> dispatchrules = Dispatch[rules]
[{ }]
Dispatch {a_, b_} − > ab , {1, 2} − > 3., F [x_] − > x2
Except
WMA link
Except[c]
represents a pattern object that matches any expression except those matching c.
Except[c, p]
represents a pattern object that matches p but not c.
HoldPattern
WMA link
HoldPattern[expr]
is equivalent to expr for pattern matching, but maintains it in an unevaluated form.
>> HoldPattern[x + x]
HoldPattern [x + x]
Longest
WMA link
Longest[pat]
is a pattern object that matches the longest sequence consistent with the pattern p.
507
>> StringCases["aabaaab", Longest["a" ~~__ ~~"b"]]
{aabaaab}
Optional (:)
WMA link
Optional[patt, default]
patt : default
is a pattern which matches patt, which if omitted should be replaced by default.
>> f[1, 2]
{1, 2}
>> f[a]
{ a, 1}
Note that symb : patt represents a Pattern object. However, there is no disambiguity, since symb has
to be a symbol in this case.
>> x:_ // FullForm
Pattern [x, Blank []]
s_. is equivalent to Optional[s_] and represents an optional parameter which, if omitted, gets its value
from Default.
>> FullForm[s_.]
Optional [Pattern [s, Blank []]]
OptionsPattern
WMA link
508
OptionsPattern[f ]
is a pattern that stands for a sequence of options given to a function, with default values taken
from Options[f ]. The options can be of the form opt->value or opt:>value, and might be in
arbitrarily nested lists.
OptionsPattern[{opt1->value1, ...}]
takes explicit default values from the given list. The list may also contain symbols f, for which
Options[f ] is taken into account; it may be arbitrarily nested. OptionsPattern[{}] does not
use any default values.
>> f[x]
x2
>> f[x, n->3]
x3
Delayed rules as options:
>> e = f[x, n:>a]
xa
>> a = 5;
>> e
x5
Options might be given in nested lists:
>> f[x, {{{n->4}}}]
x4
Pattern
WMA link
Pattern[symb, patt]
symb : patt
assigns the name symb to the pattern patt.
symb_head
is equivalent to symb : _head (accordingly with __ and ___).
symb : patt : default
is a pattern with name symb and default value default, equivalent to Optional[patt : symb,
default].
>> FullForm[a_b]
Pattern [a, Blank [b]]
>> FullForm[a:_:b]
Optional [Pattern [a, Blank []] , b]
509
>> x_
x_
Nested Pattern assign multiple names to the same pattern. Still, the last parameter is the default value.
>> f[y] /. f[a:b,_:d] -> {a, b}
[ ]
f y
PatternTest (?)
WMA link
PatternTest[pattern, test]
pattern ? test
constrains pattern to match expr only if the evaluation of test[expr] yields True.
Repeated (..)
WMA link
Repeated[pattern]
matches one or more occurrences of pattern.
>> 0..1//FullForm
Repeated [0]
510
>> {{}, {a}, {a, b}, {a, a, a}, {a, a, a, a}} /. {Repeated[x : a | b,
3]} -> x
{{} , a, { a, b} , a, { a, a, a, a}}
RepeatedNull (...)
WMA link
RepeatedNull[pattern]
matches zero or more occurrences of pattern.
>> a___Integer...//FullForm
[ [ [ ]]]
RepeatedNull Pattern a, BlankNullSequence Integer
Replace
WMA link
Replace[expr, x -> y]
yields the result of replacing expr with y if it matches the pattern x.
Replace[expr, x -> y, levelspec]
replaces only subexpressions at levels specified through levelspec.
Replace[expr, {x -> y, ...}]
performs replacement with multiple rules, yielding a single result expression.
Replace[expr, {{a -> b, ...}, {c -> d, ...}, ...}]
returns a list containing the result of performing each set of replacements.
511
By default, heads are not replaced
>> Replace[x[x[y]], x -> z, All]
[ [ ]]
x x y
ReplaceAll (/.)
WMA link
ReplaceAll[expr, x -> y]
expr /. x -> y
yields the result of replacing all subexpressions of expr matching the pattern x with y.
expr /. {x -> y, ...}
performs replacement with multiple rules, yielding a single result expression.
expr /. {{a -> b, ...}, {c -> d, ...}, ...}
returns a list containing the result of performing each set of replacements.
512
>> ReplaceAll[x[1], {x[1] -> y, 1 -> 2}]
y
ReplaceList
WMA link
ReplaceList[expr, rules]
returns a list of all possible results of applying rules to expr.
ReplaceRepeated (//.)
WMA link
ReplaceRepeated[expr, x -> y]
expr //. x -> y
repeatedly applies the rule x -> y to expr until the result no longer changes.
513
>> f[a+b+c]
a+b+d
>> Clear[f];
Simplification of logarithms:
>> logrules = {Log[x_ * y_] :> Log[x] + Log[y], Log[x_ ^ y_] :> y * Log[
x]};
Rule (->)
WMA link
Rule[x, y]
x -> y
represents a rule replacing x with y.
RuleDelayed (:>)
WMA link
RuleDelayed[x, y]
x :> y
represents a rule replacing x with y, with y held unevaluated.
>> Attributes[RuleDelayed]
{HoldRest, Protected, SequenceHold}
Shortest
WMA link
Shortest[pat]
is a pattern object that matches the shortest sequence consistent with the pattern p.
514
>> StringCases["aabaaab", Shortest["a" ~~__ ~~"b"]]
{aab, aaab}
Verbatim
WMA link
Verbatim[expr]
prevents pattern constructs in expr from taking effect, allowing them to match themselves.
515
45. Scoping Constructs
Contents
$Context
WMA link
$Context
is the current context.
>> $Context
Global‘
$ContextPath
WMA link
$ContextPath
is the search path for contexts.
$ContextPathStack
WMA link
System‘Private‘$ContextPathStack
is an internal variable tracking the values of $ContextPath saved by Begin and
BeginPackage.
$ContextStack
WMA link
516
System‘Private‘$ContextStack
is an internal variable tracking the values of $Context saved by Begin and BeginPackage.
$ModuleNumber
WMA link
$ModuleNumber
is the current “serial number” to be used for local module variables.
<ul> <li>$ModuleNumber is incremented every time Module or Unique is called. <li> a Mathics session
starts with $ModuleNumber set to 1. <li> You can reset $ModuleNumber to a positive machine integer,
but if you do so, naming conflicts may lead to inefficiencies. </li>
Begin
WMA link
Begin[context]
temporarily sets the current context to context.
>> Begin["test‘"]
test‘
>> End[]
test‘
>> End[]
No previous context defined.
Global‘
BeginPackage
WMA link
BeginPackage[context]
starts the package given by context.
The context argument must be a valid context name. BeginPackage changes the values of $Context and
$ContextPath, setting the current context to context.
Block
WMA link
Block[{x, y, ...}, expr]
temporarily removes the definitions of the given variables, evaluates expr, and restores the
original definitions afterwards.
Block[{x=x0, y=y0, ...}, expr]
assigns temporary values to the variables during the evaluation of expr.
517
>> n = 10
10
>> Block[{n = 5}, n ^ 2]
25
>> n
10
Values assigned to block variables are evaluated at the beginning of the block. Keep in mind that the
result of Block is evaluated again, so a returned block variable will get its original value.
>> Block[{x = n+2, n}, {x, n}]
{12, 10}
If the variable specification is not of the described form, an error message is raised.
>> Block[{x + y}, x]
Local variable specification contains x + y, which is not a symbol or
an assignment to a symbol.
x
Variable names may not appear more than once:
>> Block[{x, x}, x]
Duplicate local variable x found in local variable specification.
x
Contexts
WMA link
Contexts[]
yields a list of all contexts.
End
WMA link
End[]
ends a context started by Begin.
EndPackage
WMA link
EndPackage[]
marks the end of a package, undoing a previous BeginPackage.
After EndPackage, the values of $Context and $ContextPath at the time of the BeginPackage call are
restored, with the new package’s context prepended to $ContextPath.
518
Module
WMA link
Module[{vars}, expr]
localizes variables by giving them a temporary name of the form name$number, where num-
ber is the current value of $ModuleNumber. Each time a module is evaluated, $ModuleNumber
is incremented.
Unique
WMA link
Unique[]
generates a new symbol and gives a name of the form $number.
Unique[x]
generates a new symbol and gives a name of the form x$number.
Unique[{x, y, ...}]
generates a list of new symbols.
Unique[‘‘xxx’]’
generates a new symbol and gives a name of the form xxxnumber.
With
WMA link
With[{x=x0, y=y0, ...}, expr]
specifies that all occurrences of the symbols x, y, ... in expr should be replaced by x0, y0, ...
519
46. Solving Recurrence Equations
Contents
RSolve . . . . . . . . . 520
RSolve
WMA link
RSolve[eqn, a[n], n]
solves a recurrence equation for the function a[n].
520
47. Sparse Array Functions
Contents
SparseArray . . . . . . 521
SparseArray
WMA link
SparseArray[rules]
Builds a sparse array according to the list of rules.
SparseArray[rules, dims]
Builds a sparse array of dimensions dims according to the rules.
SparseArray[list]
Builds a sparse representation of list.
>> M //Normal
{{0, a} , {b, 0}}
521
48. Special Functions
There are a number of functions found in mathematical physics and found in standard handbooks.
One thing to note is that the technical literature often contains several conflicting definitions. So beware
and check for conformance with the Mathics documentation.
A number of special functions can be evaluated for arbitrary complex values of their arguments. How-
ever defining relations may apply only for some special choices of arguments. Here, the full function
corresponds to an extension or “analytic continuation” of the defining relation.
For example, integral representations of functions are only valid when the integral exists, but the func-
tions can usually be defined by analytic continuation.
Contents
AiryAi
Airy function of the first kind (SymPy, WMA)
522
AiryAi[x]
returns the Airy function Ai(x).
Exact values:
>> AiryAi[0]
1
33
[ ]
3Gamma 23
1.0
0.8
0.6
0.4
0.2
−0.2
AiryAiPrime
Derivative of Airy function (Sympy, WMA link)
AiryAiPrime[x]
returns the derivative of the Airy function AiryAi[x].
Exact values:
>> AiryAiPrime[0]
2
33
− [ ]
1
3Gamma 3
Numeric evaluation:
>> AiryAiPrime[0.5]
− 0.224911
AiryAiZero
WMA link
AiryAiZero[k]
returns the kth zero of the Airy function Ai(z).
523
>> N[AiryAiZero[1]]
− 2.33811
AiryBi
WMA link
AiryBi[x]
returns the Airy function of the second kind Bi(x).
Exact values:
>> AiryBi[0]
5
36
[ ]
3Gamma 23
Numeric evaluation:
>> AiryBi[0.5]
0.854277
>> AiryBi[0.5 + I]
0.688145 + 0.370815I
>> Plot[AiryBi[x], {x, -10, 2}]
12
10
1 2 3 4
AiryBiPrime
WMA link
AiryBiPrime[x]
returns the derivative of the Airy function of the second kind AiryBi[x].
Exact values:
>> AiryBiPrime[0]
1
36
[ ]
1
Gamma 3
Numeric evaluation:
>> AiryBiPrime[0.5]
0.544573
524
AiryBiZero
WMA link
AiryBiZero[k]
returns the kth zero of the Airy function Bi(z).
>> N[AiryBiZero[1]]
− 1.17371
AngerJ
Anger function (mpmath, WMA)
AngerJ[n, z]
returns the Anger function J_n(z).
0.4
0.2
−0.2
−0.4
−0.6
BesselI
Modified Bessel function of the first kind (Sympy, WMA)
BesselI[n, z]
returns the modified Bessel function of the first kind I_n(z).
>> BesselI[1.5, 4]
8.17263
>> Plot[BesselI[0, x], {x, 0, 5}]
100
80
60
40
20
5 10 15
525
BesselJ
Bessel function of the first kind (SymPy, WMA)
BesselJ[n, z]
returns the Bessel function of the first kind J_n(z).
BesselJZero
WMA link
BesselJZero[n, k]
returns the kth zero of the Bessel function of the first kind J_n(z).
BesselK
Modified Bessel function of the second kind (SymPy, WMA)
BesselK[n, z]
returns the modified Bessel function of the second kind K_n(z).
>> BesselK[1.5, 4]
0.014347
526
>> Plot[BesselK[0, x], {x, 0, 5}]
BesselY
Bessel function of the second kind (SymPy, WMA)
BesselY[n, z]
returns the Bessel function of the second kind Y_n(z).
>> BesselY[1.5, 4]
0.367112
>> Plot[BesselY[0, x], {x, 0, 10}]
0.4
0.2
2 4 6 8 10
−0.2
−0.4
BesselYZero
WMA link
BesselYZero[n, k]
returns the kth zero of the Bessel function of the second kind Y_n(z).
527
HankelH1
WMA link
HankelH1[n, z]
returns the Hankel function of the first kind H_n∧ 1 (z).
>> HankelH1[1.5, 4]
0.185286 + 0.367112I
HankelH2
WMA link
HankelH2[n, z]
returns the Hankel function of the second kind H_n∧ 2 (z).
>> HankelH2[1.5, 4]
0.185286 − 0.367112I
KelvinBei
Kelvin function bei (mpmath, WMA)
KelvinBei[z]
returns the Kelvin function bei(z).
KelvinBei[n, z]
returns the Kelvin function bei_n(z).
>> KelvinBei[0.5]
0.0624932
>> KelvinBei[1.5 + I]
0.326323 + 0.755606I
>> KelvinBei[0.5, 0.25]
0.370153
>> Plot[KelvinBei[x], {x, 0, 10}]
10
2 4 6 8 10
−10
−20
−30
KelvinBer
Kelvin function ber (mpmath, WMA)
528
KelvinBer[z]
returns the Kelvin function ber(z).
KelvinBer[n, z]
returns the Kelvin function ber_n(z).
>> KelvinBer[0.5]
0.999023
>> KelvinBer[1.5 + I]
1.1162 − 0.117944I
>> KelvinBer[0.5, 0.25]
0.148824
>> Plot[KelvinBer[x], {x, 0, 10}]
80
60
40
20
2 4 6 8 10
KelvinKei
Kelvin function kei (mpmath, WMA)
KelvinKei[z]
returns the Kelvin function kei(z).
KelvinKei[n, z]
returns the Kelvin function kei_n(z).
>> KelvinKei[0.5]
− 0.671582
>> KelvinKei[1.5 + I]
− 0.248994 + 0.303326I
>> KelvinKei[0.5, 0.25]
− 2.0517
>> Plot[KelvinKei[x], {x, 0, 10}]
2 4 6 8 10
−0.1
−0.2
−0.3
−0.4
−0.5
529
KelvinKer
Kelvin function ker (mpmath, WMA)
KelvinKer[z]
returns the Kelvin function ker(z).
KelvinKer[n, z]
returns the Kelvin function ker_n(z).
>> KelvinKer[0.5]
0.855906
>> KelvinKer[1.5 + I]
− 0.167162 − 0.184404I
>> KelvinKer[0.5, 0.25]
0.450023
>> Plot[KelvinKer[x], {x, 0, 10}]
0.5
0.4
0.3
0.2
0.1
2 4 6 8 10
−0.1
SphericalBesselJ
Spherical Bessel function of the first kind (Sympy, WMA)
SphericalBesselJ[n, z]
returns the spherical Bessel function of the first kind Y_n(z).
0.4
0.3
0.2
0.1
2 4 6 8 10
−0.1
−0.2
530
SphericalBesselY
Spherical Bessel function of the first kind (Sympy, WMA)
SphericalBesselY[n, z]
returns the spherical Bessel function of the second kind Y_n(z).
2 4 6 8 10
−2
−4
−6
−8
SphericalHankelH1
Spherical Bessel function of the first kind (WMA link)
SphericalHankelH1[n, z]
returns the spherical Hankel function of the first kind h_n∧ (1)(z).
SphericalHankelH2
Spherical Bessel function of the second kind (WMA link)
SphericalHankelH1[n, z]
returns the spherical Hankel function of the second kind h_n∧ (2)(z).
StruveH
Struve functions H (WMA)
StruveH[n, z]
returns the Struve function H_n(z).
531
>> Plot[StruveH[0, x], {x, 0, 10}]
0.8
0.6
0.4
0.2
2 4 6 8 10
−0.2
StruveL
Modified Struve functions L
StruveL[n, z]
returns the modified Struve function L_n(z).
15
10
1 2 3 4 5
WeberE
WMA link
WeberE[n, z]
returns the Weber function E_n(z).
532
>> Plot[WeberE[1, x], {x, -10, 10}]
0.6
0.4
0.2
−10 −5 5 10
−0.2
−0.4
Elliptic Integrals
Elliptic Integrals
In integral calculus, an elliptic integral is one of a number of related functions defined as the value of
certain integral. Their name originates from their originally arising in connection with the problem of
finding the arc length of an ellipse.
These functions often are used in cryptography to encode and decode messages.
EllipticE
Elliptic complete elliptic integral of the second kind (SymPy, WMA)
EllipticE[m]
computes the complete elliptic integral E(m).
EllipticE[phi|m]
computes the complete elliptic integral of the second kind E(m|phi).
2.0
1.5
1.0
0.5
−2 −1 1 2
533
EllipticF
Complete elliptic integral of the first kind (SymPy, WMA)
EllipticF[phi, m]
computes the elliptic integral of the first kind F(ϕ|m).
EllipticK
Complete elliptic integral of the first kind (SymPy, WMA)
EllipticK[m]
computes the elliptic integral of the first kind K(m).
>> EllipticK[0.5]
1.85407
Elliptic curves give Pi / 2 when evaluated at zero:
>> EllipticK[0]
π
2
Plot over a reals around 0:
>> Plot[EllipticK[n], {n, -1, 1}]
2.5
2.0
1.5
1.0
0.5
EllipticPi
Complete elliptic integral of the third kind (SymPy, WMA)
EllipticPi[n, m]
computes the elliptic integral of the third kind Pi(m).
534
>> EllipticPi[0, 0]
π
2
Erf
Error function (SymPy, WMA)
Erf[z]
returns the error function of z.
Erf[z0, z1]
returns the result of Erf[z1] - Erf[z0].
>> Erf[1.0]
0.842701
>> Erf[0]
0
>> {Erf[0, x], Erf[x, 0]}
{Erf [x] , −Erf [x]}
0.5
−2 −1 1 2
−0.5
−1.0
Erfc
Complementary Error function (SymPy, WMA)
Erfc[z]
returns the complementary error function of z.
>> Erfc[-x] / 2
2 − Erfc [x]
2
535
>> Erfc[1.0]
0.157299
>> Erfc[0]
1
>> Plot[Erfc[x], {x, -2, 2}]
2.0
1.5
1.0
0.5
−2 −1 1 2
FresnelC
Fresnel integral (mpmath, WMA)
FresnelC[z]
is the Fresnel C integral C(z).
FresnelS
Fresnel integral (mpmath, WMA)
FresnelS[z]
is the Fresnel S integral S(z).
InverseErf
Inverse error function (SymPy, WMA)
536
InverseErf[z]
returns the inverse error function of z.
1.0
0.5
−0.5
−1.0
InverseErfc
Complementary error function (SymPy, WMA)
InverseErfc[z]
returns the inverse complementary error function of z.
ExpIntegralE
WMA link
ExpIntegralE[n, z]
returns the exponential integral function $E_n(z)$.
ExpIntegralEi
WMA link
537
ExpIntegralEi[z]
returns the exponential integral function $Ei(z)$.
>> ExpIntegralEi[2.0]
4.95423
ProductLog
WMA link
ProductLog[z]
returns the value of the Lambert W function at z.
1.0
0.8
0.6
0.4
0.2
−0.2
Beta
Euler beta function (SymPy, WMA)
Beta[a, b]
is the Euler’s Beta function.
The
Beta[z, a, b]
gives the incomplete Beta function.
Beta function satisfies the property Beta[x, y] = Integrate[t∧ (x-1)(1-t)∧ (y-1),{t,0,1}] = Gamma[a] Gamma[b]
/ Gamma[a + b]
538
>> Beta[2, 3]
1
12
>> 12* Beta[1., 2, 3]
1.
Factorial (!)
Factorial (SymPy, mpmath, WMA)
Factorial[n]
n!
computes the factorial of n.
>> 20!
2432902008176640000
Factorial handles numeric (real and complex) values using the gamma function:
>> 10.5!
1.18994*∧ 7
>> (-3.0+1.5*I)!
0.0427943 − 0.00461565I
Factorial has the same operator (!) as Not, but with higher precedence:
>> !a! //FullForm
Not [Factorial [a]]
Factorial2 (!!)
WMA link
Factorial2[n]
n!! The
computes the double factorial of n.
double factorial or semifactorial of a number n, is the product of all the integers from 1 up to n that have
the same parity (odd or even) as n.
>> 5!!
15.
>> Factorial2[-3]
−1.
Factorial2 accepts Integers, Rationals, Reals, or Complex Numbers:
>> I!! + 1
3.71713 + 0.279527I
Irrationals can be handled by using numeric approximation:
539
>> N[Pi!!, 6]
3.35237
Gamma
Gamma function (SymPy, mpmath, WMA)
The gamma function is one commonly used extension of the factorial function applied to complex
numbers, and is defined for all complex numbers except the non-positive integers.
Gamma[z]
is the gamma function on the complex number z.
Gamma[z, x]
is the upper incomplete gamma function.
Gamma[z, x0, x1]
is equivalent to Gamma[z, x0] - Gamma[z, x1].
>> Gamma[1, x]
E− x
>> Gamma[0, x]
ExpIntegralE [1, x]
Numeric arguments:
>> Gamma[123.78]
4.21078*∧ 204
>> Gamma[1. + I]
0.498016 − 0.15495I
10
1 2 3 4
540
LogGamma
log-gamma function (SymPy, WMA)
LogGamma[z]
is the logarithm of the gamma function on the complex number z.
>> LogGamma[3]
Log [2]
Pochhammer
Rising factorial (SymPy, WMA)
The Pochhammer symbol or rising factorial often appears in series expansions for hypergeometric func-
tions.
The Pochammer symbol has a definite value even when the gamma functions which appear in its defi-
nition are infinite.
Pochhammer[a, n]
is the Pochhammer symbol a_n.
541
>> Pochhammer[1.001, 3] == 1.001 2.001 3.001
True
PolyGamma
Polygamma function (SymPy, WMA)
PolyGamma is a meromorphic function on the complex numbers and is defined as a derivative of the
logarithm of the gamma function.
PolyGamma[z]
returns the digamma function.
PolyGamma[n,z]
gives the n∧ (th) derivative of the digamma function.
>> PolyGamma[5]
25
− EulerGamma
12
>> PolyGamma[3, 5]
22369 π 4
− +
3456 15
StieltjesGamma
Stieltjes constants (SymPy, WMA)
StieltjesGamma[n]
returns the Stieltjes constant for n.
StieltjesGamma[n, a]
gives the generalized Stieltjes constant of its parameters
Orthogonal Polynomials
Orthogonal Polynomial
ChebyshevT
Chebyshev polynomial of the first kind (Sympy, WMA)
ChebyshevT[n, x]
returns the Chebyshev polynomial of the first kind T_n(x).
>> ChebyshevT[8, x]
1 − 32x2 + 160x4 − 256x6 + 128x8
>> ChebyshevT[1 - I, 0.5]
0.800143 + 1.08198I
542
ChebyshevU
Chebyshev polynomial of the second kind (Sympy, WMA)
ChebyshevU[n, x]
returns the Chebyshev polynomial of the second kind U_n(x).
>> ChebyshevU[8, x]
1 − 40x2 + 240x4 − 448x6 + 256x8
>> ChebyshevU[1 - I, 0.5]
1.60029 + 0.721322I
GegenbauerC
Gegenbauer polynomials (SymPy, WMA)
GegenbauerC[n, m, x]
returns the Gegenbauer polynomial C_n∧ (m)(x).
>> GegenbauerC[6, 1, x]
−1 + 24x2 − 80x4 + 64x6
>> GegenbauerC[4 - I, 1 + 2 I, 0.7]
− 3.2621 − 24.9739I
HermiteH
Hermite polynomial (SymPy, WMA)
HermiteH[n, x]
returns the Hermite polynomial H_n(x).
>> HermiteH[8, x]
1680 − 13 440x2 + 13440x4 − 3 584x6 + 256x8
>> HermiteH[3, 1 + I]
−28 + 4I
>> HermiteH[4.2, 2]
77.5291
JacobiP
Jacobi polynomials (SymPy, WMA)
JacobiP[n, a, b, x]
returns the Jacobi polynomial P_n∧ (a,b)(x).
543
>> JacobiP[1, a, b, z]
( )
a b a b
− +z 1+ +
2 2 2 2
>> JacobiP[3.5 + I, 3, 2, 4 - I]
1410.02 + 5797.3I
LaguerreL
Laguerre polynomials (SymPy, WMA)
LaguerreL[n, x]
returns the Laguerre polynomial L_n(x).
LaguerreL[n, a, x]
returns the generalised Laguerre polynomial L∧ a_n(x).
>> LaguerreL[8, x]
28x3 35x4 7x5 7x6 x7 x8
1 − 8x + 14x2 − + − + − +
3 12 15 180 630 40320
>> LaguerreL[3/2, 1.7]
− 0.947134
>> LaguerreL[5, 2, x]
35x2 7x3 7x4 x5
21 − 35x + − + −
2 2 24 120
LegendreP
Lengendre polynomials (SymPy, WMA)
LegendreP[n, x]
returns the Legendre polynomial P_n(x).
LegendreP[n, m, x]
returns the associated Legendre polynomial P∧ m_n(x).
>> LegendreP[4, x]
3 15x2 35x4
− +
8 4 8
>> LegendreP[5/2, 1.5]
4.17762
>> LegendreP[1.75, 1.4, 0.53]
− 1.32619
>> LegendreP[1.6, 3.1, 1.5]
− 0.303998 − 1.91937I
LegendreP can be used to draw generalized Lissajous figures:
544
>> ParametricPlot[ {LegendreP[7, x], LegendreP[5, x]}, {x, -1, 1}]
0.6
0.4
0.2
−0.2
−0.4
−0.6
LegendreQ
Legendre functions of the second kind (mpmath, WMA)
LegendreQ[n, x]
returns the Legendre function of the second kind Q_n(x).
LegendreQ[n, m, x]
returns the associated Legendre function of the second Q∧ m_n(x).
SphericalHarmonicY
Spherical Harmonic https (mpmath, WMA)
545
LerchPhi
WMA link
LerchPhi[z,s,a]
gives the Lerch transcendent
Phi(z,s,a).
Zeta
WMA link
Zeta[z]
returns the Riemann zeta function of z.
>> Zeta[2]
π2
6
>> Zeta[-2.5 + I]
0.0235936 + 0.0014078I
546
49. Strings and Characters
Contents
Character Codes
Character Code
FromCharacterCode
WMA link
FromCharacterCode[n]
returns the character corresponding to Unicode codepoint n.
FromCharacterCode[{n1, n2, ...}]
returns a string with characters corresponding to n_i.
FromCharacterCode[{{n11, n12, ...}, {n21, n22, ...}, ...}]
returns a list of strings.
>> FromCharacterCode[100]
d
>> FromCharacterCode[228, "ISO8859-1"]
ä
>> FromCharacterCode[{100, 101, 102}]
def
>> ToCharacterCode[%]
{100, 101, 102}
547
>> FromCharacterCode[{{97, 98, 99}, {100, 101, 102}}]
{abc, def}
ToCharacterCode
WMA link
ToCharacterCode["string"]
converts the string to a list of character codes (Unicode codepoints).
ToCharacterCode[{"string1‘‘,”string2", ...}]
converts a list of strings to character codes.
>> ToCharacterCode["abc"]
{97, 98, 99}
>> FromCharacterCode[%]
abc
>> ToCharacterCode["\[Alpha]\[Beta]\[Gamma]"]
{945, 946, 947}
100
80
60
40
20
5 10 15
548
Characters in Strings
Characters in String
CharacterRange
WMA link
CharacterRange["a‘‘,”b"]
returns a list of the Unicode characters from a to b inclusive.
Characters
WMA link
Characters["string"]
returns a list of the characters in string.
>> Characters["abc"]
{a, b, c}
DigitQ
WMA link
DigitQ[string]
yields True if all the characters in the string are digits, and yields False otherwise.
>> DigitQ["9"]
True
>> DigitQ["a"]
False
>> DigitQ["01001101011000010111010001101000011010010110001101110011"]
True
>> DigitQ["-123456789"]
False
LetterQ
WMA link
LetterQ[string]
yields True if all the characters in the string are letters, and yields False otherwise.
549
>> LetterQ["m"]
True
>> LetterQ["9"]
False
>> LetterQ["Mathics"]
True
>> LetterQ["Welcome to Mathics"]
False
LowerCaseQ
WMA link
LowerCaseQ[s]
returns True if s consists wholly of lower case characters.
>> LowerCaseQ["abc"]
True
An empty string returns True.
>> LowerCaseQ[""]
True
ToLowerCase
WMA link
ToLowerCase[s]
returns s in all lower case.
ToUpperCase
WMA link
ToUpperCase[s]
returns s in all upper case.
UpperCaseQ
WMA link
UpperCaseQ[s]
returns True if s consists wholly of upper case characters.
550
>> UpperCaseQ["ABC"]
True
An empty string returns True.
>> UpperCaseQ[""]
True
Operations on Strings
Operations on String
StringDrop
WMA link
StringDrop["string", n]
gives string with the first n characters dropped.
StringDrop["string", -n]
gives string with the last n characters dropped.
StringDrop["string", {n}]
gives string with the nth character dropped.
StringDrop["string", {m, n}]
gives string with the characters m through n dropped.
>> StringDrop["abcde", 2]
cde
>> StringDrop["abcde", -2]
abc
>> StringDrop["abcde", {2}]
acde
>> StringDrop["abcde", {2,3}]
ade
>> StringDrop["abcd",{3,2}]
abcd
>> StringDrop["abcd",0]
abcd
StringInsert
WMA link
551
StringInsert["string‘‘,”snew", n]
yields a string with snew inserted starting at position n in string.
StringInsert["string‘‘,”snew", -n]
inserts a at position n from the end of "string".
StringInsert["string‘‘,”snew", {n_1, n_2, ...}]
inserts a copy of snew at each position n_i in string; the n_i are taken before any insertion is
done.
StringInsert[{s_1, s_2, ...}, "snew", n]
gives the list of results for each of the s_i.
StringJoin (<>)
WMA link
StringJoin["s1‘‘,”s2", ...]
returns the concatenation of the strings s1, s2, .
StringLength
WMA link
552
StringLength["string"]
gives the length of string.
>> StringLength["abc"]
3
StringLength is listable:
>> StringLength[{"a", "bc"}]
{1, 2}
>> StringLength[x]
String expected.
StringLength [x]
StringPosition
WMA link
StringPosition["string", patt]
gives a list of starting and ending positions where patt matches "string".
StringPosition["string", patt, n]
returns the first n matches only.
StringPosition["string", {patt1, patt2, ...}, n]
matches multiple patterns.
StringPosition[{s1, s2, ...}, patt]
returns a list of matches for multiple strings.
StringReplace
WMA link
StringReplace["string‘‘,”a"->"b"]
replaces each occurrence of old with new in string.
StringReplace["string", {"s1"->"sp1‘‘,”s2"->"sp2"}]
performs multiple replacements of each si by the corresponding spi in string.
StringReplace["string", srules, n]
only performs the first n replacements.
StringReplace[{"string1‘‘,”string2", ...}, srules]
performs the replacements specified by srules on a list of strings.
553
StringReplace replaces all occurrences of one substring with another:
>> StringReplace["xyxyxyyyxxxyyxy", "xy" -> "A"]
AAAyyxxAyA
StringReverse
WMA link
StringReverse["string"]
reverses the order of the characters in “string”.
>> StringReverse["live"]
evil
StringRiffle
WMA link
StringRiffle[{s1, s2, s3, ...}]
returns a new string by concatenating all the si, with spaces inserted between them.
StringRiffle[list, sep]
inserts the separator sep between all elements in list.
StringRiffle[list, {‘‘left’, “sep”, “right”}]’
use left and right as delimiters after concatenation.
554
>> StringRiffle[{"a", "b", "c", "d", "e"}, {"(", " ", ")"}]
(a b c d e)
StringSplit
WMA link
StringSplit[s]
splits the string s at whitespace, discarding the whitespace and returning a list of strings.
StringSplit[s, pattern]
splits s into substrings separated by delimiters matching the string expression pattern.
StringSplit[s, {p_1, p_2, ...}]
splits s at any of the p_i patterns.
StringSplit[{s_1, s_2, ...}, {d_1, d_2, ...}]
returns a list with the result of applying the function to each element.
However if you want instead to use only a single character for each delimiter, use WhiteSpaceCharacter:
>> StringSplit[" abc 123 ", WhitespaceCharacter]
{, , abc, , , , 123, , }
StringTake
WMA link
555
StringTake["string", n]
gives the first n characters in string.
StringTake["string", -n]
gives the last n characters in string.
StringTake["string", {n}]
gives the nth character in string.
StringTake["string", {m, n}]
gives characters m through n in string.
StringTake["string", {m, n, s}]
gives characters m through n in steps of s.
StringTake[{s1, s2, ...} spec}]
gives the list of results for each of the si.
>> StringTake["abcde", 2]
ab
>> StringTake["abcde", 0]
StringTrim
WMA link
StringTrim[s]
returns a version of s with whitespace removed from start and end.
556
Regular Expressions
Regular Expression
RegularExpression
WMA link
RegularExpression[‘‘regex’]’
represents the regex specified by the string $“regex”$.
String Patterns
String Pattern
DigitCharacter
WMA link
DigitCharacter
represents the digits 0-9.
EndOfLine
WMA link
EndOfLine
represents the end of a line in a string.
557
>> StringSplit["abc\ndef\nhij", EndOfLine]
{abc,
def,
hij}
EndOfString
WMA link
EndOfString
represents the end of a string.
LetterCharacter
WMA link
LetterCharacter
represents letters.
>> StringMatchQ[#, LetterCharacter] & /@ {"a", "1", "A", " ", "."}
{True, False, True, False, False}
StartOfLine
WMA link
StartOfLine
represents the start of a line in a string.
558
>> StringSplit["abc\ndef\nhij", StartOfLine]
{abc
, def
, hij}
StartOfString
WMA link
StartOfString
represents the start of a string.
StringCases
WMA link
StringCases["string", pattern]
gives all occurrences of pattern in string.
StringReplace["string", pattern -> form]
gives all instances of form that stem from occurrences of pattern in string.
StringCases["string", {pattern1, pattern2, ...}]
gives all occurrences of pattern1, pattern2, ....
StringReplace["string", pattern, n]
gives only the first n occurrences.
StringReplace[{"string1‘‘,”string2", ...}, pattern]
gives occurrences in string1, string2, ...
559
>> StringCases["abc-abc xyz-uvw", Shortest[x : WordCharacter .. ~~"-" ~~
x_] -> x]
{abc}
StringExpression (~~)
WMA link
StringExpression[s_1, s_2, ...]
represents a sequence of strings and symbolic string objects s_i.
StringFreeQ
WMA link
StringFreeQ["string", patt]
returns True if no substring in string matches the string expression patt, and returns False
otherwise.
StringFreeQ[{‘‘s1’, “s2”, ...}, patt]’
returns the list of results for each element of string list.
StringFreeQ[‘‘string’, {p1, p2, ...}]’
returns True if no substring matches any of the pi.
StringFreeQ[patt]
represents an operator form of StringFreeQ that can be applied to an expression.
560
>> StringFreeQ[{"A", "Galaxy", "Far", "Far", "Away"}, {"F" ~~__ ~~"r", "
aw" ~~___}, IgnoreCase -> True]
{True, True, False, False, False}
StringMatchQ
WMA link
StringMatchQ[‘‘string’,’ pattern]
checks is “string” matches pattern
WhitespaceCharacter
WMA link
WhitespaceCharacter
represents a single whitespace character.
WordBoundary
WMA link
WordBoundary
represents the boundary between words.
561
>> StringReplace["apple banana orange artichoke", "e" ~~WordBoundary ->
"E"]
applE banana orangE artichokE
WordCharacter
WMA link
WordCharacter
represents a single letter or digit character.
>> StringMatchQ[#, WordCharacter] &/@ {"1", "a", "A", ",", " "}
{True, True, True, False, False}
562
50. Tensors
A tensor is an algebraic object that describes a (multilinear) relationship between sets of algebraic objects
related to a vector space. Objects that tensors may map between include vectors and scalars, and even
other tensors.
There are many types of tensors, including scalars and vectors (which are the simplest tensors), dual
vectors, multilinear maps between vector spaces, and even some operations such as the dot product.
Tensors are defined independent of any basis, although they are often referred to by their components
in a basis related to a particular coordinate system.
Mathics3 represents tensors of vectors and matrices as lists; tensors of any rank can be handled.
Contents
ArrayDepth
WMA link
ArrayDepth[a]
returns the depth of the non-ragged array a, defined as Length[Dimensions[a]].
>> ArrayDepth[{{a,b},{c,d}}]
2
>> ArrayDepth[x]
0
Dimensions
WMA
Dimensions[expr]
returns a list of the dimensions of the expression expr.
A vector of length 3:
>> Dimensions[{a, b, c}]
{3}
A 3x2 matrix:
>> Dimensions[{{a, b}, {c, d}, {e, f}}]
{3, 2}
563
Ragged arrays are not taken into account:
>> Dimensions[{{a, b}, {b, c}, {c, d, e}}]
{3}
Dot (.)
Dot product (WMA link)
Dot[x, y]
x . y
computes the vector dot product or matrix product x . y.
Matrix product:
>> {{a, b}, {c, d}} . {{r, s}, {t, u}}
{{ ar + bt, as + bu} , {cr + dt, cs + du}}
>> a . b
a.b
Inner
WMA link
Inner[f , x, y, g]
computes a generalised inner product of x and y, using a multiplication function f and an
addition function g.
564
Inner works with tensors of any depth:
>> Inner[f, {{{a, b}}, {{c, d}}}, {{1}, {2}}, g]
{{{ [ ]}} {{ [ ]}}}
g f [a, 1] , f [b, 2] , g f [c, 1] , f [d, 2]
Outer
Outer product (WMA link)
Outer[f , x, y]
computes a generalised outer product of x and y, using the function f in place of multiplica-
tion.
Word combinations:
>> Outer[StringJoin, {"", "re", "un"}, {"cover", "draw", "wind"}, {"", "
ing", "s"}] // InputForm
{{{“cover”, “covering”, “covers”} , {“draw”, “drawing”, “draws”} ,
{“wind”, “winding”, “winds”}} , {{“recover”, “recovering”, “recovers”} ,
{“redraw”, “redrawing”, “redraws”} , {“rewind”, “rewinding”,
“rewinds”}} , {{“uncover”, “uncovering”, “uncovers”} , {“undraw”,
“undrawing”, “undraws”} , {“unwind”, “unwinding”, “unwinds”}}}
Evaluate at 0:
>> Map[#[0] &, trigs, {2}]
{{0, 1, 0} , {1, 0, 1} , {0, ComplexInfinity, 0}}
565
RotationTransform
WMA link
RotationTransform[phi]
gives a rotation by phi.
RotationTransform[phi, p]
gives a rotation by phi around the point p.
ScalingTransform
WMA link
ScalingTransform[v]
gives a scaling transform of v. v may be a scalar or a vector.
ScalingTransform[phi, p]
gives a scaling transform of v that is centered at the point p.
ShearingTransform
WMA link
TransformationFunction
WMA link
TransformationFunction[m]
represents a transformation.
TranslationTransform
WMA link
TranslationTransform[v]
gives a TransformationFunction that translates points by vector v.
566
>> t = TranslationTransform[{x0, y0}]
[ ]
TransformationFunction {{1, 0, x0} , {0, 1, y0} , {0, 0, 1}}
From Creating a Sierpinsky gasket with the missing triangles filled in:
>> Show[Graphics[Table[Polygon[TranslationTransform[{Sqrt[3] (i - j/2),
3 j/2}] /@ {{Sqrt[3]/2, -1/2}, {0, 1}, {-Sqrt[3]/2, -1/2}}], {i, 7},
{j, i}]]]
Transpose
Transpose (WMA)
Tranpose[m]
transposes rows and columns in the matrix m.
>> MatrixForm[%]
1 4
2 5
3 6
Transpose is its own inverse. Transposing a matrix twice will give you back the same thing you started
out with:
>> Transpose[Transpose[matrix]] == matrix
True
567
51. Testing Expressions
There are a number of functions for testing Expressions.
Functions that “ask a question” have names that end in “Q”. They return True for an explicit answer,
and False otherwise.
Contents
BooleanQ
WMA link
BooleanQ[expr]
returns True if expr is either True or False.
>> BooleanQ[True]
True
>> BooleanQ[False]
True
>> BooleanQ[a]
False
568
>> BooleanQ[1 < 2]
True
Equal (==)
WMA link
Equal[x, y]
x == y
is True if x and y are known to be equal, or False if x and y are known to be unequal, in which
case case, Not[x == y] will be True.
Commutative properties apply, so if x == y then y == x.
For any expression x and y, Equal[x, y] == Not[Unequal[x, y]].
For any expression SameQ[x, y] implies Equal[x, y].
x == y == z == ...
express a chain of equalities.
Numerical Equalities:
>> 1 == 1.
True
>> 5/3 == 3/2
False
Comparisons are done using the lower precision:
>> N[E, 100] == N[E, 150]
True
Compare an exact numeric expression and its corresponding approximate number:
>> Pi == N[Pi, 20]
True
Symbolic constants are compared numerically:
>> Pi == 3.14
False
Compare two exact numeric expressions; a numeric test may suffice to disprove equality:
>> Pi ^ E == E ^ Pi
False
Compare an exact expression against an approximate real number:
>> Pi == 3.1415‘‘4
True
Real values are considered equal if they only differ in their last digits:
>> 0.739085133215160642 == 0.739085133215160641
True
>> 0.73908513321516064200000000 == 0.73908513321516064100000000
False
Numeric evaluation using Equal:
>> {Mod[6, 2] == 0, Mod[6, 4] == 0}
{True, False}
String equalities:
569
>> Equal["11", "11"]
True
>> Equal["121", "11"]
False
When we have symbols without values, the values are equal only if the symbols are equal:
>> Clear[a, b]; a == b
a==b
>> a == a
True
>> a = b; a == b
True
Comparison to mismatched types is False:
>> Equal[11, "11"]
False
Lists are compared based on their elements:
>> {{1}, {2}} == {{1}, {2}}
True
>> {1, 2} == {1, 2, 3}
False
For chains of equalities, the comparison is done amongst all the pairs. The evaluation is successful only
if the equality is satisfied over all the pairs:
>> g[1] == g[1] == g[1]
True
>> g[1] == g[1] == g[r]
g [1] ==g [1] ==g [r]
This degenerate behavior is the same for Unequal; empty or single-element lists are both Equal and
Unequal.
570
Greater (>)
WMA link
Greater[x, y] or x > y
yields True if x is known to be greater than y.
GreaterEqual (>=)
WMA link
GreaterEqual[x, y]
x y or x >= y
yields True if x is known to be greater than or equal to y.
Inequality
WMA link
Inequality
is the head of expressions involving different inequality operators (at least temporarily). Thus,
it is possible to write chains of inequalities.
Less (<)
WMA link
571
Less[x, y] or x < y
yields True if x is known to be less than y.
>> 1 < 0
False
LessEqual operator can be chained:
>> 2/18 < 1/5 < Pi/10
True
Using less on an undefined symbol value:
>> 1 < 3 < x < 2
1<3<x<2
LessEqual (<=)
WMA link
LessEqual[x, y, ...] or x <= y or x ≤ y
yields True if x is known to be less than or equal to y.
Max
WMA link
572
With no arguments, Max gives -Infinity:
>> Max[]
−∞
Max does not compare strings or symbols:
>> Max[-1.37, 2, "a", b]
Max [2, a, b]
Min
WMA link
SameQ (===)
WMA link
SameQ[x, y]
x === y
returns True if x and y are structurally identical. Commutative properties apply, so if x === y
then y === x.
• SameQ requires exact correspondence between expressions, expect that it still considers Real num-
bers equal if they differ in their last binary digit.
• e1 === e2 === e3 gives True if all the ei’s are identical.
• SameQ[] and SameQ[expr] always yield True.
Any object is the same as itself:
>> a === a
True
573
Degenerate cases of SameQ showing off how you can chain ===:
>> SameQ[a] === SameQ[] === True
True
Unlike Equal, SameQ only yields True if x and y have the same type:
>> {1==1., 1===1.}
{True, False}
TrueQ
WMA link
TrueQ[expr]
returns True if and only if expr is True.
>> TrueQ[True]
True
>> TrueQ[False]
False
>> TrueQ[a]
False
Unequal (!=)
WMA link
Unequal[x, y] or x != y or x ̸= y
is False if x and y are known to be equal, or True if x and y are known to be unequal.
Commutative properties apply so if x != y then y != x.
For any expression x and y, Unequal[x, y] == Not[Equal[x, y]].
>> 1 != 1.
False
Comparisons can be chained:
>> 1 != 2 != 3
True
>> 1 != 2 != x
1!=2!=x
574
Strings are allowed:
>> Unequal["11", "11"]
False
Comparison to mismatched types is True:
>> Unequal[11, "11"]
True
Lists are compared based on their elements:
>> {1} != {2}
True
>> {1, 2} != {1, 2}
False
>> {a} != {a}
False
>> "a" != "b"
True
>> "a" != "a"
False
Unequal using an empty parameter or list, or a list with one element is True. This is the same as ’Equal".
>> {Unequal[], Unequal[x], Unequal[1]}
{True, True, True}
UnsameQ (=!=)
WMA link
UnsameQ[x, y]
x =!= y
returns True if x and y are not structurally identical. Commutative properties apply, so if x
=!= y, then y =!= x.
>> a =!= a
False
>> 1 =!= 1.
True
UnsameQ accepts any number of arguments and returns True if all expressions are structurally distinct:
>> 1 =!= 2 =!= 3 =!= 4
True
UnsameQ returns False if any expression is identical to another:
>> 1 =!= 2 =!= 1 =!= 4
False
UnsameQ[] and UnsameQ[expr] return True:
>> UnsameQ[]
True
575
>> UnsameQ[expr]
True
Expression Tests
Expression Test
ListQ
WMA link
ListQ[expr]
tests whether expr is a List.
MatchQ
WMA link
MatchQ[expr, form]
tests whether expr matches form.
List-Oriented Tests
List-Oriented Test
ArrayQ
WMA
576
ArrayQ[expr]
tests whether expr is a full array.
ArrayQ[expr, pattern]
also tests whether the array depth of expr matches pattern.
ArrayQ[expr, pattern, test]
furthermore tests whether test yields True for all elements of expr. ArrayQ[expr] is equivalent
to ArrayQ[expr, _, True&].
>> ArrayQ[a]
False
>> ArrayQ[{a}]
True
>> ArrayQ[{{{a}},{{b,c}}}]
False
>> ArrayQ[{{a, b}, {c, d}}, 2, SymbolQ]
True
DisjointQ
WMA link
DisjointQ[a, b]
gives True if a and b are disjoint, or False if a and b have any common elements.
IntersectingQ
WMA link
IntersectingQ[a, b]
gives True if there are any common elements in $a and $b, or False if $a and $b are disjoint.
LevelQ
LevelQ[expr]
tests whether expr is a valid level specification. This function is primarily used in function
patterns for specifying type of a parameter.
>> LevelQ[2]
True
>> LevelQ[{2, 4}]
True
>> LevelQ[Infinity]
True
>> LevelQ[a + b]
False
577
We will define MyMap with the “level” parameter as a synonym for the Builtin Map equivalent:
>> MyMap[f_, expr_, Pattern[levelspec, _?LevelQ]] := Map[f, expr,
levelspec]
But notice that when we pass an invalid level specification, MyMap does not match and therefore does
not pass the arguments through to Map. So we do not see the error message that Map would normally
produce
>> Map[f, {{a, b}, {c, d}}, x]
Level specification x is not of the form n, {n}, or {m, n}.
[ ]
Map f , {{ a, b} , {c, d}} , x
MatrixQ
WMA link
MatrixQ[m]
gives True if m is a list of equal-length lists.
MatrixQ[m, f ]
gives True only if f [x] returns True for when applied to element x of the matrix m.
MemberQ
WMA link
MemberQ[list, pattern]
returns True if pattern matches any element of list, or False otherwise.
578
>> MemberQ[{a, b, c}, b]
True
>> MemberQ[{a, b, c}, d]
False
>> MemberQ[{"a", b, f[x]}, _?NumericQ]
False
>> MemberQ[_List][{{}}]
True
NotListQ
NotListQ[expr]
returns True if expr is not a list. This function is primarily used in function patterns for speci-
fying type of a parameter.
=
We use “MyD” above to distinguish it from the Builtin D. Now let’s try it:
>> MyD[Sin[2 x], x]
2Cos [2x]
Note however the pattern only matches if the x parameter is not a list:
>> MyD[{Sin[2], Sin[4]}, {1, 2}]
[ ]
MyD {Sin [2] , Sin [4]} , {1, 2}
SubsetQ
WMA link
SubsetQ[list1, list2]
returns True if list2 is a subset of list1, and False otherwise.
579
>> SubsetQ[{1, 2, 3}, {1, 2, 3}]
True
VectorQ
WMA link
VectorQ[v]
returns True if v is a list of elements which are not themselves lists.
VectorQ[v, f ]
returns True if v is a vector and f [x] returns True for each element x of v.
Logical Combinations
Logical Combination
AllTrue
WMA link
AllTrue[{expr1, expr2, ...}, test]
returns True if all applications of test to expr1, expr2, ... evaluate to True.
AllTrue[list, test, level]
returns True if all applications of test to items of list at level evaluate to True.
AllTrue[test]
gives an operator that may be applied to expressions.
And (&&)
WMA link
And[expr1, expr2, ...]
expr1 && expr2 && ...
evaluates each expression in turn, returning False as soon as an expression evaluates to
False. If all expressions evaluate to True, And returns True.
580
AnyTrue
WMA link
AnyTrue[{expr1, expr2, ...}, test]
returns True if any application of test to expr1, expr2, ... evaluates to True.
AnyTrue[list, test, level]
returns True if any application of test to items of list at level evaluates to True.
AnyTrue[test]
gives an operator that may be applied to expressions.
Equivalent (\Equiv)
WMA link
Equivalent[expr1, expr2, ...]
expr1
Equiv expr2
Equiv ...
is equivalent to (expr1 && expr2 && ...) || (!expr1 && !expr2 && ...)
False
WMA link
False
represents the Boolean false value.
Implies (⇒)
WMA link
581
Implies[expr1, expr2]
expr1 ⇒ expr2
evaluates each expression in turn, returning True as soon as the first expression evaluates to
False. If the first expression evaluates to True, Implies returns the second expression.
>> Implies[False, a]
True
>> Implies[True, a]
a
If an expression does not evaluate to True or False, Implies returns a result in symbolic form:
>> Implies[a, Implies[b, Implies[True, c]]]
aImpliesbImpliesc
Nand
WMA link
Nand[expr1, expr2, ...]
expr1 ⊼ expr2 ⊼ ...
Implements the logical NAND function. The same as Not[And[expr1, expr2, ...]]
NoneTrue
WMA link
NoneTrue[{expr1, expr2, ...}, test]
returns True if no application of test to expr1, expr2, ... evaluates to True.
NoneTrue[list, test, level]
returns True if no application of test to items of list at level evaluates to True.
NoneTrue[test]
gives an operator that may be applied to expressions.
Nor
WMA link
Nor[expr1, expr2, ...]
expr1 ⊻ expr2 ⊻ ...
Implements the logical NOR function. The same as Not[Or[expr1, expr2, ...]]
582
>> Nor[True, False]
False
Not (!)
WMA link
Not[expr]
!expr
negates the logical expression expr.
>> !True
False
>> !False
True
>> !b
!b
Or (||)
WMA link
Or[expr1, expr2, ...]
expr1 || expr2 || ...
evaluates each expression in turn, returning True as soon as an expression evaluates to True.
If all expressions evaluate to False, Or returns False.
True
WMA link
True
represents the Boolean true value.
Xor (xor)
WMA link
Xor[expr1, expr2, ...]
expr1 ⊕ expr2 ⊕ ...
evaluates each expression in turn, returning True as soon as not all expressions evaluate to
the same value. If all expressions evaluate to the same value, Xor returns False.
583
>> Xor[False, True]
True
>> Xor[True, True]
False
If an expression does not evaluate to True or False, Xor returns a result in symbolic form:
>> Xor[a, False, b]
a\[Xor]b
Numerical Properties
Numerical Propertie
CoprimeQ
WMA link
CoprimeQ[x, y]
tests whether x and y are coprime by computing their greatest common divisor.
>> CoprimeQ[7, 9]
True
>> CoprimeQ[-4, 9]
True
>> CoprimeQ[12, 15]
False
CoprimeQ also works for complex numbers
>> CoprimeQ[1+2I, 1-I]
True
>> CoprimeQ[4+2I, 6+3I]
True
>> CoprimeQ[2, 3, 5]
True
>> CoprimeQ[2, 4, 5]
False
EvenQ
WMA link
EvenQ[x]
returns True if x is even, and False otherwise.
>> EvenQ[4]
True
584
>> EvenQ[-3]
False
>> EvenQ[n]
False
IntegerQ
WMA link
IntegerQ[expr]
returns True if expr is an integer, and False otherwise.
>> IntegerQ[3]
True
>> IntegerQ[Pi]
False
MachineNumberQ
WMA link
MachineNumberQ[expr]
returns True if expr is a machine-precision real or complex number.
= True
>> MachineNumberQ[3.14159265358979324]
False
>> MachineNumberQ[1.5 + 2.3 I]
True
>> MachineNumberQ[2.71828182845904524 + 3.14159265358979324 I]
False
Negative
WMA link
Negative[x]
returns True if x is a negative real number.
>> Negative[0]
False
>> Negative[-3]
True
>> Negative[10/7]
False
585
>> Negative[1+2I]
False
>> Negative[a + b]
Negative [a + b]
NonNegative
WMA link
NonNegative[x]
returns True if x is a positive real number or zero.
NonPositive
WMA link
NonPositive[x]
returns True if x is a negative real number or zero.
NumberQ
WMA link
NumberQ[expr]
returns True if expr is an explicit number, and False otherwise.
>> NumberQ[3+I]
True
>> NumberQ[5!]
True
>> NumberQ[Pi]
False
NumericQ
WMA link
NumericQ[expr]
tests whether expr represents a numeric quantity.
>> NumericQ[2]
True
586
>> NumericQ[Sqrt[Pi]]
True
>> NumberQ[Sqrt[Pi]]
False
It is possible to set that a symbol is numeric or not by assign a boolean value to “NumericQ“
>> NumericQ[a]=True
True
>> NumericQ[a]
True
>> NumericQ[Sin[a]]
True
Clear and ClearAll do not restore the default value.
>> Clear[a]; NumericQ[a]
True
>> ClearAll[a]; NumericQ[a]
True
>> NumericQ[a]=False; NumericQ[a]
False
NumericQ can only set to True or False
>> NumericQ[a] = 37
Cannot set NumericQ[a] to 37; the lhs argument must be a symbol and
the rhs must be True or False.
37
OddQ
WMA link
OddQ[x]
returns True if x is odd, and False otherwise.
>> OddQ[-3]
True
>> OddQ[0]
False
Positive
WMA link
Positive[x]
returns True if x is a positive real number.
>> Positive[1]
True
587
Positive returns False if x is zero or a complex number:
>> Positive[0]
False
>> Positive[1 + 2 I]
False
PossibleZeroQ
WMA link
PossibleZeroQ[expr]
returns True if basic symbolic and numerical methods suggest that expr has value zero, and
False otherwise.
PrimeQ
WMA link
PrimeQ[n]
returns True if n is a prime number.
For very large numbers, PrimeQ uses probabilistic prime testing, so it might be wrong sometimes (a
number might be composite even though PrimeQ says it is prime). The algorithm might be changed in
the future.
>> PrimeQ[2]
True
588
>> PrimeQ[-3]
True
>> PrimeQ[137]
True
>> PrimeQ[2 ^ 127 - 1]
True
All prime numbers between 1 and 100:
>> Select[Range[100], PrimeQ]
{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97}
589
52. The Main Loop
An interactive session operates a loop, called the “main loop” in this way:
• read input
• process input
• format and print results
• repeat
As part of this loop, various global objects in this section are consulted.
There are a variety of “hooks” that allow you to insert functions to be applied to the expressions at
various stages in the main loop.
If you assign a function to the global variable $PreRead it will be applied with the input that is read in
the first step listed above.
Similarly, if you assign a function to global variable $Pre, it will be applied with the input before
processing the input, the second step listed above.
Contents
$HistoryLength
WMA
$HistoryLength
specifies the maximum number of In and Out entries.
>> $HistoryLength
100
>> $HistoryLength = 1;
>> 42
42
>> %
42
>> %%
%3
>> $HistoryLength = 0;
>> 42
42
590
>> %
%7
$Line
WMA
$Line
holds the current input line number.
>> $Line
1
>> $Line
2
>> $Line = 12;
>> 2 * 5
10
>> Out[13]
10
>> $Line = -1;
Non-negative integer expected.
$Post
WMA
$Post
is a global variable whose value, if set, is applied to every output expression.
$Pre
WMA
$Pre
is a global variable whose value, if set, is applied to every input expression.
Set Timing as the $Pre function, stores the elapsed time in a variable, stores just the result in Out[$Line]
and print a formatted version showing the elapsed time
>> $Pre := (Print["[Processing input...]"];#1)&
591
>> 2 + 2
[Processing input...]
[Storing result...]
The result is:
{389.354, 4}
>> 2 + 2
4
$PrePrint
WMA
$PrePrint
is a global variable whose value, if set, is applied to every output expression before it is
printed.
$PreRead
WMA
$PreRead
is a global variable whose value, if set, is applied to the text or box form of every input ex-
pression before it is fed to the parser.
(Not implemented yet)
$SyntaxHandler
WMA
$SyntaxHandler
is a global variable whose value, if set, is applied to any input string that is found to contain a
syntax error.
(Not implemented yet)
In
WMA
In[k]
gives the kth line of input.
>> x = 1
1
>> x = x + 1
2
592
>> Do[In[2], {3}]
>> x
5
>> In[-1]
5
>> Definition[In]
Attributes [In] = {Listable, Protected}
In [6] = Definition [In]
In [5] = In [ − 1]
In [4] = x
[ ]
In [3] = Do In [2] , {3}
In [2] = x = x + 1
In [1] = x = 1
Out
WMA
Out[k]
%k
gives the result of the kth input line.
%, %%, etc.
gives the result of the previous input line, of the line before the previous input line, etc.
>> 42
42
>> %
42
>> 43;
>> %
43
>> 44
44
>> %1
42
>> %%
44
>> Hold[Out[-1]]
Hold [%]
>> Hold[%4]
Hold [%4]
>> Out[0]
Out [0]
593
53. Tracing Built-in Functions
Built-in Function Tracing provides one high-level way understand what is getting evaluated and where
the time is spent in evaluation.
With this, it may be possible for both users and implementers to follow how Mathics3 arrives at its
results, or guide how to speed up expression evaluation.
Contents
$TraceBuiltins
$TraceBuiltins
A Boolean Built-in variable when True collects function evaluation statistics.
Setting this variable True will enable statistics collection for Built-in functions that are evaluated. In
contrast to TraceBuiltins[] statistics are accumulated and over several inputs, and are not shown
after each input is evaluated. By default this setting is False.
>> $TraceBuiltins = True
True
Tracing is enabled, so the expressions entered and evaluated will have statistics collected for the evalu-
ations.
>> x
x
To print the statistics collected, use PrintTrace[]:
>> PrintTrace[]
$TraceEvaluation
$TraceEvaluation
A Boolean variable which when set True traces Expression evaluation calls and returns.
594
>> $TraceEvaluation = True
-> System‘True
Evaluating: System‘MakeBoxes[System‘StandardForm[System‘True], System‘TeXForm]
Evaluating: System‘MakeBoxes
Evaluating: System‘MakeBoxes[System‘StandardForm[System‘True]]
Evaluating: System‘MakeBoxes
-> System‘MakeBoxes[System‘StandardForm[System‘True], System‘StandardForm]
Evaluating: System‘MakeBoxes
-> System‘MakeBoxes[System‘True, System‘StandardForm]
Evaluating: System‘MakeBoxes
-> System‘RowBox[<ListExpression: (<String: "
text{True}">,)>]
Evaluating: System‘RowBox
Evaluating: <ListExpression: (<String: "
text{True}">,)>
True
>> a + a
Evaluating: System‘Plus[Global‘a, Global‘a]
Evaluating: System‘Plus
Evaluating: Global‘a
Evaluating: Global‘a
-> System‘Times[2, Global‘a]
Evaluating: System‘Times
Global‘a
Evaluating: System‘HoldForm[System‘Infix[<ListExpression: (<Expression: System‘HoldForm[2]>, <Expression:
System‘HoldForm[Global‘a]>)>,
Evaluating: System‘HoldForm " ", 400, System‘None]]
System‘MakeBoxes[System‘StandardForm[System‘HoldForm[System‘Infix[<ListExpression: (<Expression: System‘HoldForm[2]>,
<Expression: System‘MakeBoxes[System‘StandardForm[System‘HoldForm[System‘Infix[<ListExpression:
Evaluating:
Evaluating: System‘HoldForm[Global‘a]>)>, " ", 400, System‘None]]], System‘TeXForm]
System‘MakeBoxes (<Expression: System‘HoldForm[2]>,
<Expression:
Evaluating: System‘HoldForm[Global‘a]>)>, " ", 400, System‘None]]]]
System‘MakeBoxes
-> System‘MakeBoxes[System‘StandardForm[System‘HoldForm[System‘Infix[<ListExpression: (<Expression: System‘HoldForm[2]>, <Expression:
System‘HoldForm[Global‘a]>)>,
Evaluating:
-> System‘MakeBoxes " ", 400, System‘None]]], System‘StandardForm]
System‘MakeBoxes[System‘HoldForm[System‘Infix[<ListExpression: (<Expression: System‘HoldForm[2]>, <Expression:
System‘HoldForm[Global‘a]>)>,
Evaluating: System‘MakeBoxes " ", 400, System‘None]],
-> System‘MakeBoxes[System‘Infix[<ListExpression: System‘StandardForm]
(<Expression: System‘HoldForm[2]>, <Expression: System‘HoldForm[Global‘a]>)>, " ",
400,
-> System‘None],
Evaluating: System‘StandardForm]
System‘MakeBoxes
System‘RowBox[<ListExpression: (<Expression: System‘MakeBoxes[System‘HoldForm[2], System‘StandardForm]>, <String: " ">, <Expression:
System‘MakeBoxes[System‘HoldForm[Global‘a],
Evaluating: <ListExpression: (<Expression:System‘StandardForm]>)>]
System‘RowBox System‘MakeBoxes[System‘HoldForm[2], System‘StandardForm]>, <String: " ">, <Expression:
System‘MakeBoxes[System‘HoldForm[Global‘a],
Evaluating: System‘StandardForm]>)>
System‘MakeBoxes[System‘HoldForm[2], System‘StandardForm]
Evaluating: System‘MakeBoxes
-> System‘MakeBoxes[2, System‘StandardForm]
Evaluating: System‘MakeBoxes
Evaluating: System‘MakeBoxes[System‘HoldForm[Global‘a], System‘StandardForm]
Evaluating: System‘MakeBoxes
-> System‘MakeBoxes[Global‘a, System‘StandardForm]
Evaluating: System‘MakeBoxes
Evaluating: <ListExpression: (<String: "2">, <String: " ">, <String: "a">)>
-> System‘RowBox[<ListExpression: (<String: "2 a">,)>]
Evaluating: System‘RowBox
Evaluating: <ListExpression: (<String: "2 a">,)>
2a
Setting it to False again recovers the normal behaviour:
>> $TraceEvaluation = False
Evaluating: System‘Set[System‘$TraceEvaluation, System‘False]
Evaluating: System‘Set
Evaluating: System‘False
False
>> $TraceEvaluation
False
>> a + a
2a
$TraceEvaluation cannot be set to a non-boolean value.
>> $TraceEvaluation = x
x should be True or False.
x
ClearTrace
ClearTrace[]
Clear the statistics collected for Built-in Functions
595
First, set up Builtin-function tracing:
>> $TraceBuiltins = True
True
Dump Builtin-Function statistics gathered in running that assignment:
>> PrintTrace[]
>> ClearTrace[]
PrintTrace
PrintTrace[]
Print statistics collected for Built-in Functions
Sort Options:
• count
• name
• time
Note that in a browser the information only appears in a console.
If $TraceBuiltins was never set to True, this will print an empty list.
>> PrintTrace[]
TraceBuiltins
TraceBuiltins[expr]
Evaluate expr and then print a list of the Built-in Functions called in evaluating expr along
with the number of times is each called, and combined elapsed time in milliseconds spent in
each.
Sort Options:
• count
• name
• time
596
>> TraceBuiltins[Graphics3D[Tetrahedron[]]]
By default, the output is sorted by the number of calls of the builtin from highest to lowest:
>> TraceBuiltins[Times[x, x], SortBy->"count"]
x2
You can have results ordered by name, or time.
Trace an expression and list the result by time from highest to lowest.
>> TraceBuiltins[Times[x, x], SortBy->"time"]
x2
TraceEvaluation
TraceEvaluation[expr]
Evaluate expr and print each step of the evaluation.
4x2
597
>> TraceEvaluation[(x + x)^2, ShowTimeBySteps->True]
0.000375271
Evaluating: System‘Power[System‘Plus[Global‘x, Global‘x], 2]
0.00413585
Evaluating: System‘Power
0.00782394
Evaluating: System‘Plus[Global‘x, Global‘x]
0.0114872
Evaluating: System‘Plus
0.0151558
Evaluating: Global‘x
0.0188198
Evaluating: Global‘x
-> System‘Times[2, Global‘x]
0.024493
Evaluating: System‘Times
0.0282567
Evaluating: Global‘x
0.0326107
Evaluating: System‘Power[Global‘x, 2]
0.0362749
Evaluating: System‘Power
0.0399296
Evaluating: Global‘x
0.0439322
Evaluating: Global‘x
-> System‘Times[4, System‘Power[Global‘x, 2]]
0.0496171
Evaluating: System‘Times
0.0533211
Evaluating: System‘Power[Global‘x, 2]
4x2
598
54. Units and Quantities
Contents
KnownUnitQ
WMA link
KnownUnitQ[unit]
returns True if unit is a canonical unit, and False otherwise.
>> KnownUnitQ["Feet"]
True
>> KnownUnitQ["Foo"]
False
Quantity
WMA link
Quantity[magnitude, unit]
represents a quantity with size magnitude and unit specified by unit.
Quantity[unit]
assumes the magnitude of the specified unit to be 1.
>> Quantity["Kilogram"]
1kilogram
QuantityMagnitude
WMA link
599
QuantityMagnitude[quantity]
gives the amount of the specified quantity.
QuantityMagnitude[quantity, unit]
gives the value corresponding to quantity when converted to unit.
>> QuantityMagnitude[Quantity["Kilogram"]]
1
>> QuantityMagnitude[Quantity[10, "Meters"]]
10
>> QuantityMagnitude[Quantity[{10,20}, "Meters"]]
{10, 20}
QuantityQ
WMA link
QuantityQ[expr]
return True if expr is a valid Association object, and False otherwise.
QuantityUnit
WMA link
QuantityUnit[quantity]
returns the unit associated with the specified quantity.
>> QuantityUnit[Quantity["Kilogram"]]
kilogram
UnitConvert
WMA link
600
UnitConvert[quantity, targetunit]
converts the specified quantity to the specified targetunit.
UnitConvert[quantity]
converts the specified quantity to its “SIBase” units.
601
Part III.
Mathics3 Modules
602
1. Graphs - Vertices and Edges
A Graph is a tuple of a set of Nodes and Edges.
Mathics3 Module that provides functions and variables for working with graphs.
Examples:
>> LoadModule["pymathics.graph"]
pymathics.graph
>> BalancedTree[3, 3]
603
>> g = Graph[{1 -> 2, 2 -> 3, 3 <-> 4}, VertexLabels->True]
>> ConnectedComponents[g]
{{3, 4} , {2} , {1}}
>> WeaklyConnectedComponents[g]
{{1, 2, 3, 4}}
>> GraphDistance[g, 1, 4]
3
>> GraphDistance[g, 3, 2]
∞
NetworkX does the heavy lifting here.
Contents
604
CompleteGraph . 629 KaryTree . . . . . 633 Random Graphs . . . . 635
CompleteKaryTree 630 LadderGraph . . . 633 RandomGraph . . 635
CycleGraph . . . . 630 PathGraph . . . . 634 Trees . . . . . . . . . . 635
GraphAtlas . . . . 631 RandomTree . . . 634 TreeGraph . . . . 636
HknHararyGraph 631 StarGraph . . . . 635 TreeGraphQ . . . 636
HmnHararyGraph 632
Centralities
Centralities
Centralities
Routines to evaluate centralities of a graph.
In graph theory and network analysis, the centrality is a ranking between pairs of node according some
metric.
BetweennessCentrality
Betweenness centrality (NetworkX, WMA)
BetweennessCentrality[g]
gives a list of betweenness centralities for the vertices in a Graph or a list of edges g.
>> BetweennessCentrality[g]
605
>> g = Graph[{a -> b, b -> c, c -> d, d -> e, e -> c, e -> a}]
>> BetweennessCentrality[g]
ClosenessCentrality
Betweenness centrality (NetworkX, WMA)
ClosenessCentrality[g]
gives a list of closeness centralities for the vertices in a Graph or a list of edges g.
>> ClosenessCentrality[g]
606
>> g = Graph[{a -> b, b -> c, c -> d, d -> e, e -> c, e -> a}]
>> ClosenessCentrality[g]
DegreeCentrality
Degree centrality (NetworkX, WMA)
DegreeCentrality[g]
gives a list of degree centralities for the vertices in a Graph or a list of edges g.
>> DegreeCentrality[g]
{2, 4, 3, 5, 2}
607
EigenvectorCentrality
Eigenvector Centrality (NetworkX,WMA)
EigenvectorCentrality[g]
gives a list of eigenvector centralities for the vertices in the graph g.
EigenvectorCentrality[g, “In”]
gives a list of eigenvector in-centralities for the vertices in the graph g.
EigenvectorCentrality[g, “Out”]
gives a list of eigenvector out-centralities for the vertices in the graph g.
HITSCentrality
NetworkX, WMA
HITSCentrality[g]
gives a list of authority and hub centralities for the vertices in the graph g.
KatzCentrality
Katz Centrality (NetworkX, WMA)
KatzCentrality[g, alpha]
gives a list of Katz centralities for the vertices in the graph g and weight alpha.
KatzCentrality[g, alpha, beta]
gives a list of Katz centralities for the vertices in the graph g and weight alpha and initial
centralities beta.
608
>> g = Graph[{a -> b, b -> c, c -> d, d -> e, e -> c, e -> a}]
PageRankCentrality
Pagerank Centrality (NetworkX, WMA)
PageRankCentrality[g, alpha]
gives a list of page rank centralities for the vertices in the graph g and weight alpha.
PageRankCentrality[g, alpha, beta]
gives a list of page rank centralities for the vertices in the graph g and weight alpha and initial
centralities beta.
609
Core routines for working with Graphs.
Core routines for working with Graphs.
AdjacencyList
Adjacency list (NetworkX, WMA)
AdjacencyList[graph, v]
gives a list of vertices adjacent to v in a Graph or a list of edges g.
AdjacencyList[graph, pattern]
gives a list of vertices adjacent to vertices matching pattern.
>> AdjacencyList[{x -> 2, x -> 3, x -> 4, 2 -> 10, 2 -> 11, 4 -> 20, 4
-> 21, 10 -> 100}, 10, 2]
{2, 11, 100, x }
DirectedEdge
Edge of a Directed graph (NetworkX, WMA)
DirectedEdge[u, v]
create a directed edge from u to v.
EdgeConnectivity
Edge connectivity (NetworkX, WMA)
EdgeConnectivity[g]
gives the edge connectivity of the graph g.
610
EdgeDelete
Delete an Edge (WMA)
EdgeDelete[g, edge]
remove the edge edge.
EdgeIndex
WMA link
EdgeIndex[graph, edge]
gives the position of the edge in the list of edges associated to the graph.
EdgeList
WMA link
EdgeList[g]
gives the list of edges that defines g
EdgeRules
WMA link
EdgeRules[g]
gives the list of edge rules for the graph g.
FindShortestPath
Shortest path problem (NetworkX, WMA)
611
FindShortestPath[g, src, tgt]
List the vertices in the shortest path connecting the source src with the target tgt in the graph
g.
>> g = Graph[{1 -> 2, 2 -> 3, 1 -> 3}, EdgeWeight -> {0.5, a, 3}];
FindVertexCut
Minimum cut (NetworkX, WMA)
FindVertexCut[g]
finds a set of vertices of minimum cardinality that, if removed, renders g disconnected.
FindVertexCut[g, s, t]
finds a vertex cut that disconnects all paths from s to t.
Graph
Graph (WMA)
612
>> Graph[{1->2, 2->3, 3->1}]
# » Graph[{1->2, 2->3, 3->1}, VertexStyle -> {1 -> Green, 3 -> Blue}] # = -Graph-
>> Graph[x]
Graph [x]
>> Graph[{1}]
[ ]
Graph {1}
HighlightGraph
WMA link
HighlightGraph[graph, what]
highlight in graph the elements enumerated in what by adding style marks.
613
Property
WMA link
PropertyValue
WMA link
UndirectedEdge
WMA link
UndirectedEdge[u, v]
create an undirected edge between u and v.
>> a <-> b
UndirectedEdge [a, b]
VertexAdd
WMA link
VertexAdd[g, ver]
create a new graph from g, by adding the vertex ver.
614
>> g2 = VertexAdd[g1, 4]
VertexConnectivity
WMA link
615
VertexConnectivity[g]
gives the vertex connectivity of the graph g.
VertexDelete
WMA link
VertexDelete[g, vert]
remove the vertex vert and their associated edges.
>> VertexDelete[g1, 3]
616
>> VertexDelete[{a -> b, b -> c, c -> d, d -> a}, {a, c}]
>> VertexDelete[{1 -> 2, 2 -> 3, 3 -> 4, 4 -> 6, 6 -> 8, 8 -> 2}, _?OddQ
]
VertexIndex
WMA link
VertexIndex[g, v]
gives the integer index of the vertex v in the graph g.
>> a=.;
VertexList
WMA link
VertexList[edgelist]
list the vertices from a list of directed edges.
617
>> a=.;
Curated Graphs
Curated Graph
GraphData
WMA link
GraphData[name]
Returns a graph with the specified name.
>> GraphData["PappusGraph"]
ConnectedComponents
Strongly connected components (NetworkX, WMA)
ConnectedComponents[g]
gives the connected components of the graph g.
618
>> g = Graph[{1 -> 2, 2 -> 3, 3 <-> 4}, VertexLabels->True]
>> ConnectedComponents[g]
>> ConnectedComponents[g]
>> ConnectedComponents[g]
619
WeaklyConnectedComponents
Weak components (NetworkX, WMA)
WeaklyConnectedComponents[g]
gives the weakly connected components of the graph g.
>> WeaklyConnectedComponents[g]
>> WeaklyConnectedComponents[g]
620
>> g = Graph[{1 <-> 2, 2 <-> 3, 3 -> 4, 4 <-> 5, 6 <-> 7, 7 <-> 8},
VertexLabels->True]
>> WeaklyConnectedComponents[g]
EdgeCount
NetworkX, WMA
EdgeCount[g]
returns a count of the number of edges in graph g.
EdgeCount[g, patt]
returns the number of edges that match the pattern patt.
EdgeCount[{v->$w}, ...}, ...]
uses rules v->w to specify the graph g.
GraphDistance
NetworkX, WMA
GraphDistance[g, s, t]
returns the distance from source vertex s to target vertex t in the graph g.
GraphDistance[g, s]
returns the distance from source vertex s to all vertices in the graph g.
621
GraphDistance[{v->w, ...}, ...]
use rules v->w to specify the graph g.
>> GraphDistance[g, 1, 5]
3
>> GraphDistance[g, 4, 2]
1
>> GraphDistance[g, 5, 4]
∞
>> GraphDistance[g, 5]
{∞, ∞, ∞, ∞, 0}
>> GraphDistance[g, 3]
{∞, 1, 2, 0, 3}
>> GraphDistance[g, 4]
{∞, 1, 0, 1, 1}
VertexCount
NetworkX, WMA
VertexCount[g]
returns a count of the number of vertices in graph g.
VertexCount[g, patt]
returns the number of vertices that match the pattern patt.
VertexCount[{v->$w}, ...}, ...]
uses rules v->w to specify the graph g.
622
>> VertexCount[{1 -> x, x -> 3}, _Integer]
2
VertexDegree
NetworkX, WMA
VertexDegree[g]
returns a list of the degrees of each of the vertices in graph g.
EdgeCount[g, patt]
returns the number of edges that match the pattern patt.
EdgeCount[{v->$w}, ...}, ...]
uses rules v->w to specify the graph g.
FindSpanningTree
Spanning Tree (NetworkX, WMA)
FindSpanningTree[g]
finds a spanning tree of the graph g.
>> FindSpanningTree[CycleGraph[4]]
623
AcyclicGraphQ
Acyclic graph test (NetworkX, WMA)
AcyclicGraphQ[graph]
check if graph is an acyclic graph.
>> AcyclicGraphQ[g]
>> AcyclicGraphQ[g]
ConnectedGraphQ
Connected graph test (NetworkX, WMA)
ConnectedGraphQ[graph]
check if graph is a connected graph.
624
DirectedGraphQ
Directed graph test (NetworkX, WMA)
DirectedGraphQ[graph]
True if graph is a Graph and all the edges are directed.
LoopFreeGraphQ
Loop-Free graph test (NetworkX, WMA)
LoopFreeGraphQ[graph]
True if graph is a Graph and the edges do not close any loop.
MixedGraphQ
Mixed Graph test (WMA)
MixedGraphQ[graph]
returns True if graph is a Graph with both directed and undirected edges, and False otherwise.
MultigraphQ
Multigraph test (NetworkX, WMA)
MultigraphQ[graph]
True if graph is a Graph and there vertices connected by more than one edge.
625
>> g = Graph[{1 -> 2, 2 -> 3}]; MultigraphQ[g]
False
>> g = Graph[{1 -> 2, 2 -> 3, 1 -> 2}]; MultigraphQ[g]
True
PathGraphQ
Path graph test (WMA)
LoopFreeGraphQ[graph]
True if graph is a Graph and it becomes disconnected by removing a single edge.
PlanarGraphQ
Planar Graph test (NetworkX, WMA)
PlanarGraphQ[g]
Returns True if g is a planar graph and False otherwise.
>> PlanarGraphQ[CycleGraph[4]]
True
>> PlanarGraphQ[CompleteGraph[5]]
False
>> PlanarGraphQ["abc"]
Expected a graph at position 1 in PlanarGraphQ[abc].
False
SimpleGraphQ
Simple (not multigraph)graph test (WMA)
626
LoopFreeGraphQ[graph]
True if graph is a Graph, loop-free and each pair of vertices are connected at most by a single
edge.
Parametric Graphs
Parametric Graph
BalancedTree
WMA
BalancedTree[r, h]
Returns the perfectly balanced r-ary tree of height h.
In this tree produced, all non-leaf nodes will have r children and the height of the path from root r
to any leaf will be h.
>> BalancedTree[2, 3]
BarbellGraph
Barbell graph (NetworkX, Wolfram MathWorld)
BarbellGraph[m1, m2]
Barbell Graph: two complete graphs connected by a path.
627
>> BarbellGraph[4, 1]
BinomialTree
Binomial tree (NetworkX, WMA)
BinomialTree[n]
Returns the Binomial Tree of order n.
The binomial tree of order n with root R is defined as:
If k=0, B[k] = B[0] = {R}. i.e., the binomial tree of order zero consists of a single node, R.
If k>0, B[k] = {R, B[0], B[1] ... B[k]}, i.e., the binomial tree of order k>0 comprises the root R, and
k binomial subtrees, B[0] to B[k].
Binomial trees are the underlying data structure in Binomial heaps.
>> BinomialTree[3]
CompleteGraph
Complete Multipartite Graph (NetworkX, WMA)
CompleteGraph[n]
Returns the complete graph with n vertices, K_n.
628
>> CompleteGraph[8]
CompleteKaryTree
M-ary Tree (NetworkX, WMA)
CompleteKaryTree[n, k]
Creates a complete k-ary tree of n levels.
In the returned tree, with n nodes, the from root R to any leaf be k.
>> CompleteKaryTree[2, 3]
629
>> CompleteKaryTree[3]
CycleGraph
Cycle Graph (WMA)
CycleGraph[n]
Returns the cycle graph with n vertices C_n.
GraphAtlas
NetworkX
GraphAtlas[n]
Returns graph number i from the NetworkX’s Graph Atlas. There are about 1200 of them and
get large as i increases.
630
>> GraphAtlas[1000]
HknHararyGraph
NetworkX, WMA
HknHararyGraph[k, n]
Returns the Harary graph with given node connectivity and node number.
This second generator gives the Harary graph that minimizes the number of edges in the graph
with given node connectivity and number of nodes.
Harary, F. The Maximum Connectivity of a Graph. Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
HmnHararyGraph
NetworkX, WMA
HmnHararyGraph[m, n]
Returns the Harary graph with given numbers of nodes and edges.
This generator gives the Harary graph that maximizes the node connectivity with given number
of nodes and given number of edges.
Harary, F. The Maximum Connectivity of a Graph. Proc. Nat. Acad. Sci. USA 48, 1142-1146, 1962.
631
>> HmnHararyGraph[5, 10]
KaryTree
M-ary Tree
KaryTree[r, n]
Creates binary tree of n vertices.
KaryTree[n, k]
Creates k-ary tree with n vertices.
>> KaryTree[10]
632
>> KaryTree[3, 10]
LadderGraph
Ladder graph (NetworkX)
LadderGraph[n]
Returns the Ladder graph of length n.
>> LadderGraph[8]
PathGraph
Path graph (WMA)
633
>> PathGraph[{1, 2, 3}]
RandomTree
NetworkX, WMA
RandomTree[n]
Returns a uniformly random tree on n nodes.
>> RandomTree[3]
StarGraph
Star graph(NetworkX, WMA)
StarGraph[n]
Returns a star graph with n vertices.
634
>> StarGraph[8]
Random Graphs
Random Graph
RandomGraph
WMA link
RandomGraph[{n, m}]
Returns a pseudorandom graph with n vertices and m edges.
RandomGraph[{n, m}, k]
Returns list of k RandomGraph[{n, m}].
Trees
Tree
TreeGraph
Tree Graph (WMA)
TreeGraph[edges]
Build a Tree-like graph from the list of edges edges.
TreeGraph[vert, edges]
build a Tree-like graph from the list of vertices vert and edges edges.
635
>> TreeGraph[{1->2, 2->3, 2->4}]
If the edges does not match with a tree-like pattern, the evaluation fails:
>> TreeGraph[{1->2, 2->3, 3->1}]
Graph is not a tree.
[ ]
TreeGraph {1− > 2, 2− > 3, 3− > 1}
TreeGraphQ
Tree Graph (WMA)
TreeGraphQ[g]
returns True if the graph g is a tree and False otherwise.
>> TreeGraphQ[StarGraph[3]]
True
>> TreeGraphQ[CompleteGraph[2]]
True
>> TreeGraphQ[CompleteGraph[3]]
False
636
2. Natural Language Processing
Mathics3 Module module provides functions and variables to work with expressions in natural lan-
guage, using the Python libraries:
• spacy for parsing natural languages</url>
• nltk for functions using WordNet-related builtins
• pyenchant and pycountry for language identification
Examples:
>> LoadModule["pymathics.natlang"]
pymathics.natlang
>> Pluralize["try"]
tries
>> LanguageIdentify["eins zwei drei"]
German
>> WordFrequency["Apple Tree and apple", "apple", IgnoreCase -> True]
0.5
>> TextCases["I was in London last year.", "Pronoun"]
{I}
Contents
Language Translation
Language Translation
637
LanguageIdentify
WMA link
LanguageIdentify[text]
returns the name of the language used in text.
Linguistic Data
Linguistic Data
See the corresponding WMA guide.
DictionaryLookup
WMA link
DictionaryLookup[word]
lookup words that match the given word or pattern.
DictionaryLookup[word, n]
lookup first n words that match the given word or pattern.
DictionaryWordQ
WMA link
DictionaryWordQ[word]
returns True if word is a word usually found in dictionaries, and False otherwise.
>> DictionaryWordQ["couch"]
True
>> DictionaryWordQ["meep-meep"]
False
RandomWord
WMA link
<dl> <dt>RandomWord[] <dd>returns a random word.
<dt>RandomWord[type] <dd>returns a random word of the given type, e.g. of type “Noun” or “Adverb”.
<dt>RandomWord[type, n] <dd>returns n random words of the given type.
>> RandomWord["Noun"]
dacrymycetaceae
638
>> RandomWord["Noun", 3]
{winter crookneck squash, benzyl radical, emile durkheim}
</dl>
WordData
WMA link
WordData[word]
returns a list of possible senses of a word.
WordData[word, property]
returns detailed information about a word regarding property, e.g. “Definitions” or “Exam-
ples”.
WordDefinition
WMA link
WordDefinition[word]
returns a definition of word or Missing[“Available”] if word is not known.
>> WordDefinition["gram"]
{a metric unit of weight equal to one thousandth of a kilogram}
WordList
WMA link
WordList[]
returns a list of common words.
WordList[type]
returns a list of common words of type type.
Evaluate the average length over all the words in the dictionary:
639
>> N[Mean[StringLength /@ WordList[]], 3]
11.6
Now, restricted to adjectives:
>> N[Mean[StringLength /@ WordList["Adjective"]], 2]
9.3
WordStem
WMA link
WordStem[word]
returns a stemmed form of word, thereby reducing an inflected form to its root.
WordStem[{word1, word2, ...}]
returns a stemmed form for list of word, thereby reducing an inflected form to its root.
>> WordStem["towers"]
tower
>> WordStem[{"heroes", "roses", "knights", "queens"}]
{hero, rose, knight, queen}
Text Analysis
Text Analysis
See the corresponding WMA guide.
Containing
WMA link
Containing[outer, inner]
Containing
represents an object of the type outer containing objects of type inner.
SpellingCorrectionList
WMA link
640
SpellingCorrectionList[word]
returns a list of suggestions for spelling corrected versions of word.
WordCount
WMA link
WordCount[string]
returns the number of words in string.
WordFrequency
WMA link
WordFrequency[text, word]
returns the relative frequency of word in text.
WordSimilarity
WMA link
WordSimilarity[text1, text2]
returns a real-valued measure of semantic similarity of two texts or words.
WordSimilarity[{text1, i1}, {text2, j1}]
returns a measure of similarity of two words within two texts.
WordSimilarity[{text1, {i1, i2, ...}}, {text2, {j1, j2, ...}}]
returns a measure of similarity of multiple words within two texts.
641
>> NumberForm[WordSimilarity[{"An ocean full of water.", {2, 2}}, { "A
desert full of sand.", {2, 5}}], 3]
{0.505, 0.481}
WordStem
WMA link
WordStem[word]
returns a stemmed form of word, thereby reducing an inflected form to its root.
WordStem[{word1, word2, ...}]
returns a stemmed form for list of word, thereby reducing an inflected form to its root.
>> WordStem["towers"]
tower
>> WordStem[{"heroes", "roses", "knights", "queens"}]
{hero, rose, knight, queen}
Text Normalization
Text Normalization
See the corresponding WMA guide.
This module uses spacy as a backend.
DeleteStopwords
Delete stop words( WMA )
DeleteStopwords[list]
returns the words in list without stopwords.
DeleteStopwords[string]
returns string without stopwords.
TextCases
WMA link
TextCases[text, form]
returns all elements of type form in text in order of their appearance.
642
>> TextCases["I was in London last year.", "City"]
{London}
TextPosition
WMA link
TextPosition[text, form]
returns the positions of elements of type form in text in order of their appearance.
TextSentences
Sentences in a text ( WMA )
TextSentences[string]
returns the sentences in string.
TextSentences[string, n]
returns the first n sentences in string
TextStructure
WMA link
TextStructure[text, form]
returns the grammatical structure of text as form.
643
TextWords
WMA link
TextWords[string]
returns the words in string.
TextWords[string, n]
returns the first n words in string
Word manipulation
Word manipulation
This module uses pattern.en to change the form of a word.
Pluralize
WMA link
Pluralize[word]
returns the plural form of word.
>> Pluralize["potato"]
potatoes
644
Part IV.
License
645
A. GNU General Public License
Version 3, 29 June 2007
Copyright l’ 2007 Free Software Foundation, Inc. http://fsf.org/
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it
is not allowed.
You should have received a copy of the GNU General Public License along
with this program . If not , see \ href { http :// www . gnu . org / licenses
/}{ Licenses }.
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:
< program > Copyright ( C ) < year > < name of author >
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 Licences.
646
The GNU General Public License does not permit incorporating your program into proprietary pro-
grams. 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 Why you shouldn’t use the Lesser GPL for
your next library.
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 sur-
render 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 soft-
ware, 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.
647
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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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
648
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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
649
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 distribu-
tion 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
650
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 re-
moval 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 ma-
terial 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
651
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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 contrib-
utor’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.
652
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.
653
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
0. Definitions.
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.
654
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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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.
655
Conveying under any other circumstances is permitted solely under the conditions stated below. Sub-
licensing is not allowed; section 10 makes it unnecessary.
656
• a) Convey the object code in, or embodied in, a physical product (including a physical distribu-
tion 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
657
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 re-
moval 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 ma-
terial 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
658
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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 contrib-
utor’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
659
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.
660
Later license versions may give you additional or different permissions. However, no additional obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
1. Source Code.
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.
661
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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
662
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 technologi-
cal 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 works users, your or third parties legal rights to forbid
circumvention of technological measures.
663
• 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.
664
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 re-
moval 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 ma-
terial 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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
665
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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 contrib-
utor’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
666
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.
667
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 EX-
PRESSED 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.
2. Basic Permissions.
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 con-
venient 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
668
licensees may convey the work under this License, and how to view a copy of this License. If the inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
669
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 works users, your or third parties legal rights to forbid
circumvention of technological measures.
670
• 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.
671
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 re-
moval 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 ma-
terial 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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
672
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.
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 contrib-
utor’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
673
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.
674
PRESSED 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.
675
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 gener-
ate, 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 dynami-
cally 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 per-
mission 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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
676
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program’s source code as you receive it, in any medium, pro-
vided 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 sec-
tion 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.
677
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 re-
moval 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
678
(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 ma-
terial 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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
679
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 pre-
decessor 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 contrib-
utor’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
680
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.
681
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 GEN-
ERAL, 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.
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
682
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 gener-
ate, 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 dynami-
cally 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 per-
mission 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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
683
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 addi-
tional 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; how-
ever, 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 compila-
tion 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.
684
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 re-
moval 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 ma-
terial 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
685
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
686
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 contrib-
utor’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.
687
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.
688
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
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 gener-
ate, 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 dynami-
689
cally 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 per-
mission 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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
690
• 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 addi-
tional 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; how-
ever, 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 compila-
tion 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.
691
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 re-
moval 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 ma-
terial 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
692
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
693
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 contrib-
utor’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.
694
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any cov-
ered 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.
695
END OF TERMS AND CONDITIONS
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 gener-
ate, 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 dynami-
cally 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.
696
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 per-
mission 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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
697
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 compila-
tion 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.
698
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 re-
moval 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 ma-
terial 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.
699
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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.
700
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contrib-
utor’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.
701
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
7. Additional Terms.
0. Definitions.
“This License refers to version 3 of the GNU General Public License.
702
“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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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
703
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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
704
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.
705
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 re-
moval 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 ma-
terial 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.
706
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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.
707
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contrib-
utor’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.
708
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
8. Termination.
0. Definitions.
“This License refers to version 3 of the GNU General Public License.
709
“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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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
710
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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
711
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.
712
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 re-
moval 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 ma-
terial 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.
713
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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.
714
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contrib-
utor’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.
715
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
716
“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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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
717
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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
718
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.
719
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 re-
moval 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 ma-
terial 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.
720
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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.
721
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contrib-
utor’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.
722
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
723
“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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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
724
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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
725
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.
726
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 re-
moval 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 ma-
terial 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.
727
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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.
728
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contrib-
utor’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.
729
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
11. Patents.
0. Definitions.
“This License refers to version 3 of the GNU General Public License.
730
“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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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
731
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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
732
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.
733
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 re-
moval 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 ma-
terial 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.
734
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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.
735
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contrib-
utor’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.
736
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
737
“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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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
738
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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
739
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.
740
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 re-
moval 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 ma-
terial 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.
741
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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.
742
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contrib-
utor’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.
743
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
744
“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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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
745
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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
746
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.
747
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 re-
moval 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 ma-
terial 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.
748
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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.
749
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contrib-
utor’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.
750
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
751
“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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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
752
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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
753
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.
754
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 re-
moval 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 ma-
terial 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.
755
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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.
756
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contrib-
utor’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.
757
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
758
“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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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
759
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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
760
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.
761
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 re-
moval 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 ma-
terial 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.
762
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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.
763
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contrib-
utor’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.
764
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
765
“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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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
766
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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
767
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.
768
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 re-
moval 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 ma-
terial 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.
769
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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.
770
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contrib-
utor’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.
771
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
772
“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 con-
venient 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 inter-
face 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 gener-
ate, 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 dynami-
cally 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 per-
mission 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
773
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. Sub-
licensing is not allowed; section 10 makes it unnecessary.
774
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.
775
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 re-
moval 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 ma-
terial 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.
776
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 re-
ceived copies or rights from you under this License. If your rights have been terminated and not per-
manently reinstated, you do not qualify to receive new licenses for the same material under section
10.
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.
777
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contrib-
utor’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.
778
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 obli-
gations are imposed on any author or copyright holder as a result of your choosing to follow a later
version.
779
B. Included software and data
Included data
Mathics3 includes data from Wikipedia that is published under the Creative Commons Attribution-
Sharealike 3.0 Unported License and the GNU Free Documentation License contributed by the respec-
tive authors that are listed on the websites specified in "data/elements.txt".
MathJax
Copyright l’ 2009-2010 Design Science, Inc.
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is
distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied. See the License for the specific language governing permissions and limitations
under the License.
Prototype
Copyright l’ 2005-2010 Sam Stephenson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associ-
ated documentation files (the “Software”), to deal in the Software without restriction, including without
limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
conditions:
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FIT-
NESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AU-
THORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABIL-
ITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
SciPy
Copyright l’ 2001, 2002 Enthought, Inc. All rights reserved.
Copyright l’ 2003-2019 SciPy Developers. All rights reserved. Redistribution and use in source and
binary forms, with or without modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
780
Neither the name of Enthought nor the names of the SciPy Developers may be used to endorse or
promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IM-
PLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (IN-
CLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Three.js
Copyright l’ 2010-2020 Three.js authors.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associ-
ated documentation files (the “Software”), to deal in the Software without restriction, including without
limitation the rights copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FIT-
NESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AU-
THORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABIL-
ITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
mpmath
Copyright (c) 2005-2018 Fredrik Johansson and mpmath contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted pro-
vided that the following conditions are met:
<ol> <li>Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer. <li>Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution. <li>Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from this software without specific
prior written permission. </ul>
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IM-
PLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (IN-
CLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
781
pymimemagic
Copyright (c) 2009, Xiaohai Lu All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted pro-
vided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the
following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS”
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IM-
PLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAM-
AGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SER-
VICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
782
Appendices
783
Index
784
AnglePath, 413 BesselY, 527
AngleVector, 484 BesselYZero, 527
Angular Momentum, 236 Beta, 538
AnyTrue, 581 BetweennessCentrality, 605
Apart, 358 BezierCurve, 268
Append, 435 BezierFunction, 269
AppendTo, 435 Binarize, 289
Apply, 40, 225 Binary Reading and Writing, 84
Applying Functions to Lists, 225 Binary Types, 86
ApplyLevel, 176 BinaryImageQ, 303
ArcCos, 414 BinaryRead, 84
ArcCosh, 384 BinarySearch, 176
ArcCot, 415 BinaryWrite, 85
ArcCoth, 384 Binomial, 348
ArcCsc, 415 BinomialTree, 628
ArcCsch, 384 BitLength, 388
ArcSec, 415 Black, 100
ArcSech, 385 Blank, 504
ArcSin, 415 BlankNullSequence, 505
ArcSinh, 385 BlankSequence, 505
ArcTan, 416 Blend, 95
ArcTanh, 385 Block, 517
Arg, 461 Blue, 100
Array, 430 Blur, 281
ArrayDepth, 563 Boole, 462
ArrayQ, 576 BooleanQ, 568
Arrow, 142 Bottom, 168
Arrowheads, 144 BoxMatrix, 472
Association, 427 BrayCurtisDistance, 137
AssociationQ, 428 Break, 498
Associations, 427 Brown, 101
Assuming, 461 Byte, 86
Atomic Primitives, 65 Byte Arrays, 86
AtomQ, 65 ByteArray, 86
Attributes, 121 ByteCount, 175
Automatic, 167 ByteOrdering, 87
Axes, 167
Axis, 168 C, 381
Calculus, 369
B64Decode, 312, 342 CanberraDistance, 137
B64Encode, 312, 342 Cancel, 359
BalancedTree, 627 Cases, 435
BarbellGraph, 627 Catalan, 398
BarChart, 245 CatalanNumber, 349
BaseForm, 212 Catch, 499
Basic Arithmetic, 45 Catenate, 449
Basic Image Processing, 281 Ceiling, 388
Begin, 517 Center, 420
BeginPackage, 517 Centralities, 605
BernsteinBasis, 268 CentralMoment, 131
Bessel and Related Functions, 522 Character, 186, 320
BesselI, 525 Character Codes, 547
BesselJ, 526 CharacterRange, 549
BesselJZero, 526 Characters, 549
BesselK, 526 Characters in Strings, 549
785
ChartLabels, 169 Constructing Lists, 430
ChartLegends, 169 Constructing Matrices, 472
ChebyshevT, 542 Constructing Vectors, 484
ChebyshevU, 543 Containing, 640
Check, 475 ContainsOnly, 448
ChessboardDistance, 138 Context, 78
Chop, 479 Contexts, 518
Circle, 146 Continue, 499
Clear, 52 ContinuedFraction, 403
ClearAll, 53 CoprimeQ, 584
ClearAttributes, 122 CopyDirectory, 199, 330
Clearing Assignments, 52 CopyFile, 200, 330
ClearTrace, 595 Core routines for working with Graphs., 610
ClebschGordan, 236 Correlation, 130
Close, 187, 320 Cos, 416
ClosenessCentrality, 606 Cosh, 386
Closing, 306 CosineDistance, 138
Cluster Analysis, 135 Cot, 416
ClusteringComponents, 135 Coth, 386
CMYKColor, 90, 145 Count, 436
Coefficient, 359 Covariance, 130
CoefficientArrays, 360 CreateDirectory, 200, 330
CoefficientList, 360 CreateFile, 200, 331
Collect, 361 CreateTemporary, 200, 331
Color Directives, 90 Cross, 485
Color Operations, 95 Csc, 416
ColorCombine, 291 CubeRoot, 45
ColorConvert, 95 Cuboid, 271
ColorData, 247 Curated Graphs, 618
ColorDataFunction, 248 Curl, 485
ColorDistance, 90 Cyan, 102
Colorize, 292 CycleGraph, 630
ColorNegate, 95 Cylinder, 272
ColorQuantize, 291
ColorSeparate, 292 D, 369
Combinatorial Functions, 348 DamerauLevenshteinDistance, 139
Compile, 88 Darker, 96
CompiledFunction, 88 DataImport, 182
Complement, 449 DateDifference, 115
CompleteGraph, 628 DateList, 116
CompleteKaryTree, 629 DateObject, 117
Complex, 462 DatePlus, 117
Complexes, 369 DateString, 117
ComplexInfinity, 398 Decrement, 60
CompositeQ, 352 Default, 491
Composition, 223, 231 DefaultValues, 62
CompoundExpression, 499 Definition, 78
Condition, 506 Degree, 399
ConditionalExpression, 462 DegreeCentrality, 607
Cone, 270 Delete, 436
Conjugate, 463 DeleteCases, 437
ConnectedComponents, 618 DeleteDirectory, 200, 331
ConnectedGraphQ, 624 DeleteDuplicates, 449
Constant, 122 DeleteFile, 201, 331
ConstantArray, 430 DeleteStopwords, 642
786
Denominator, 362 EdgeRules, 611
DensityPlot, 248 EditDistance, 140
Dependency and Dispursion Statistics, 130 Eigensystem, 392
Depth, 177 Eigenvalues, 393
Derivative, 371 EigenvectorCentrality, 608
DesignMatrix, 392 Eigenvectors, 393
Det, 392 ElementData, 496
Diagonal, 473 Elements of Lists, 434
DiagonalMatrix, 472 Elliptic Integrals, 533
DiamondMatrix, 472 EllipticE, 533
DiceDissimilarity, 349 EllipticF, 534
DictionaryLookup, 638 EllipticK, 534
DictionaryWordQ, 638 EllipticPi, 534
Differential Equations, 381 End, 518
DigitCharacter, 557 EndOfFile, 187, 320
DigitCount, 388 EndOfLine, 557
DigitQ, 549 EndOfString, 558
Dilation, 306 EndPackage, 518
Dimensions, 563 Environment, 242
DirectedEdge, 610 Equal, 569
DirectedGraphQ, 625 Equality and Inequality, 568
DirectedInfinity, 464 Equivalent, 581
Directive, 147 Erf, 535
Directory, 201, 332 Erfc, 535
DirectoryName, 201, 332 Erosion, 307
DirectoryQ, 202, 332 Error Function and Related Functions, 535
DirectoryStack, 202, 332 EuclideanDistance, 138
DiscreteLimit, 372 EulerGamma, 399
DiscretePlot, 249 EulerPhi, 404
DisjointQ, 577 EvenQ, 584
Disk, 147 ExactNumberQ, 67
DiskMatrix, 473 Except, 507
Dispatch, 506 Exp, 382
Divide, 45 Expand, 362
DivideBy, 60 ExpandAll, 363
Divisible, 352 ExpandDenominator, 364
Division-Related Functions, 352 ExpandFileName, 202, 332
Divisors, 404 ExpIntegralE, 537
Do, 500 ExpIntegralEi, 537
Dodecahedron, 278 Exponent, 364
DominantColors, 97 Exponential Functions, 381
Dot, 564 Exponential Integral and Special Functions, 537
DownValues, 80 Export, 312, 343
Drop, 438 ExportString, 313, 343
DSolve, 381 Expression, 187, 320
Expression Sizes and Signatures, 175
E, 399 Expression Tests, 576
EasterSunday, 118 Extract, 438
EdgeConnectivity, 610
EdgeCount, 621 FaceForm, 150
EdgeDelete, 611 Factor, 364
EdgeDetect, 304 Factorial, 539
EdgeForm, 149 Factorial2, 539
EdgeIndex, 611 FactorInteger, 404
EdgeList, 611 FactorTermsList, 365
787
Failure, 476 FresnelC, 536
False, 581 FresnelS, 536
Fibonacci, 355 FromCharacterCode, 547
File, 202, 333 FromContinuedFraction, 405
File and Stream Operations, 319 FromDigits, 389
FileBaseName, 202, 333 Full, 170
FileByteCount, 203, 333 FullDataImport, 182
FileDate, 203, 333 FullForm, 212
FileExistsQ, 203, 334 FullSimplify, 366
FileExtension, 204, 334 Function, 220, 229
FileFormat, 313, 344 Function Application, 229
FileHash, 204, 334 Functional Composition and Operator Forms,
FileInformation, 204, 335 231
FileNameDepth, 205, 335
FileNameJoin, 205, 335 Gamma, 540
FileNames, 206, 336 Gamma and Related Functions, 538
FileNameSplit, 205, 336 Gather, 450
FileNameTake, 206, 336 GatherBy, 451
FilePrint, 187, 320 GaussianFilter, 296
Filesystem Operations, 329 GCD, 353
FileType, 206, 337 GegenbauerC, 543
FilledCurve, 150 General, 476
Filling, 169 General Statistics, 130
FilterRules, 491 General Structural Expression Functions, 176
Find, 187, 320 Geometric Operations, 285
FindClusters, 135 Get, 188, 321
FindFile, 207, 337 GetEnvironment, 242
FindList, 207, 337 Glaisher, 400
FindMaximum, 372 GoldenRatio, 400
FindMinimum, 373 Graph, 612
FindRoot, 373 Graph Components and Connectivity, 618
FindShortestPath, 611 Graph Measures and Metrics, 621
FindSpanningTree, 623 Graph Operations and Modifications, 623
FindVertexCut, 612 Graph Properties and Measurements, 623
First, 438 GraphAtlas, 630
FirstCase, 439 GraphData, 618
FirstPosition, 439 GraphDistance, 621
FittedModel, 394 Graphics, 151, 250, 273
FixedPoint, 232 Graphics3D, 252, 274
FixedPointList, 232 Gray, 102
Flat, 123 GrayLevel, 91, 153
Flatten, 450 Greater, 571
Floor, 389 GreaterEqual, 571
Fold, 233 Green, 103
FoldList, 233 Grid, 421
FontColor, 151 GridBox, 213
For, 500 Gudermannian, 386
Form variables, 211
Format, 420 HammingDistance, 140
FormBaseClass, 212, 218 HankelH1, 528
Forms of Assignment, 55 HankelH2, 528
Forms which appear in $OutputForms., 212 HarmonicNumber, 355
Forms which are not in $OutputForms, 218 Hash, 175, 207, 337
FractionalPart, 405 Haversine, 417
FreeQ, 177 Head, 66
788
HermiteH, 543 Increment, 60
HexadecimalCharacter, 73 Indeterminate, 400
HighlightGraph, 613 Inequality, 571
Histogram, 253 InexactNumberQ, 68
HITSCentrality, 608 Infinity, 400
HknHararyGraph, 631 Infix, 421
HmnHararyGraph, 631 Information, 81
HoldAll, 123 Inner, 564
HoldAllComplete, 123 InputForm, 213
HoldFirst, 123 InputStream, 188, 322
HoldPattern, 507 Insert, 440
HoldRest, 124 Inset, 153
HTML, 182 Integer, 465
HTMLGet, 182 Integer Functions, 388
HTMLGetString, 183 IntegerDigits, 390
Hue, 91, 153 IntegerExponent, 68
Hyperbolic Functions, 384 IntegerLength, 69
HyperlinksImport, 183 IntegerQ, 585
IntegerReverse, 391
I, 464 Integers, 374
Icosahedron, 278 IntegerString, 391
Identity, 223, 232 Integrate, 375
IdentityMatrix, 473 InterpretedBox, 73
If, 501 Interrupt, 501
Im, 464 IntersectingQ, 577
Image Colors, 289 Intersection, 451
Image Compositions, 293 Inverse, 394
Image Filters, 296 InverseErf, 536
Image Properties, 301 InverseErfc, 537
Image testing, 303 InverseGudermannian, 386
ImageAdd, 293 InverseHaversine, 417
ImageAdjust, 282 Iteratively Applying Functions, 232
ImageAspectRatio, 301
ImageChannels, 301 JaccardDissimilarity, 349
ImageColorSpace, 293 JacobiP, 543
ImageConvolve, 297 Join, 451
ImageData, 302 Joined, 171
ImageDimensions, 302
ImageLinksImport, 183 KaryTree, 632
ImageMultiply, 294 KatzCentrality, 608
ImagePartition, 283 KelvinBei, 528
ImageQ, 303 KelvinBer, 528
ImageReflect, 285 KelvinKei, 529
ImageResize, 287 KelvinKer, 530
ImageRotate, 288 Key, 428
ImageSize, 170 Keys, 428
ImageSubtract, 295 Khinchin, 401
ImageTake, 308 KnownUnitQ, 599
ImageType, 302 KroneckerProduct, 487
Implies, 581 Kurtosis, 134
Import, 314, 344
Importing and Exporting, 342 LABColor, 92, 154
ImportString, 314, 345 LadderGraph, 633
In, 592 LaguerreL, 544
In-place binary assignment operator, 59 Language Translation, 637
789
LanguageIdentify, 638 Lookup, 429
Large, 154 LoopFreeGraphQ, 625
Last, 440 LowerCaseQ, 550
LCHColor, 92, 154 LUVColor, 92, 154
LCM, 353
LeafCount, 176 MachineNumberQ, 585
LeastSquares, 394 MachinePrecision, 69
Left, 422 Magenta, 110
LegendreP, 544 MakeBoxes, 213, 218, 422, 458
LegendreQ, 545 ManhattanDistance, 139
Length, 440 MantissaExponent, 405
LerchPhi, 546 Map, 41, 226
Less, 571 MapAt, 42, 227
LessEqual, 572 MapIndexed, 42, 227
LetterCharacter, 558 MapThread, 43, 228
LetterNumber, 74 MatchingDissimilarity, 349
LetterQ, 549 MatchQ, 576
Level, 178 Math & Counting Operations on Lists, 447
LevelQ, 577 Mathematical Constants, 398
LightBlue, 104 Mathematical Operations, 485
LightBrown, 105 MathicsVersion, 243
LightCyan, 105 MathMLForm, 214
Lighter, 98 MatrixExp, 396
LightGray, 106 MatrixForm, 214
LightGreen, 106 MatrixPower, 396
LightMagenta, 107 MatrixQ, 578
LightOrange, 107 MatrixRank, 396
LightPink, 108 Max, 572
LightPurple, 108 MaxFilter, 299
LightRed, 109 Maximize, 471
LightYellow, 109 MaxRecursion, 171
Limit, 376 Mean, 131
Line, 154 MedianFilter, 300
Linear algebra, 392 Medium, 155
LinearModelFit, 394 MemberQ, 578
LinearSolve, 395 MemoryAvailable, 243
Linguistic Data, 638 MemoryInUse, 243
List, 41, 226, 431 Mesh, 171
List-Oriented Tests, 576 Message, 476
Listable, 124 MessageName, 476
ListLinePlot, 253 Messages, 62
ListLogPlot, 254 Min, 573
ListPlot, 255 MinFilter, 300
ListQ, 576 MinimalPolynomial, 366
LoadModule, 55 Minimize, 471
Location Statistics, 131 Minus, 46
Locked, 124 Miscellaneous image-related functions, 303
Log, 382 Missing, 429
Log10, 383 MixedGraphQ, 625
Log2, 383 Mod, 353
LogGamma, 541 ModularInverse, 354
Logical Combinations, 580 Module, 519
LogisticSigmoid, 383 Morphological Image Processing, 306
LogPlot, 257 MorphologicalComponents, 307
Longest, 507 Most, 441
790
MultigraphQ, 625 Opening, 308
Multinomial, 350 OpenRead, 189, 322
OpenWrite, 189, 323
N, 479 Operate, 179
Named Colors, 100 Operations on Image Structure, 308
Names, 81 Operations on Strings, 551
Nand, 582 Optional, 508
Nearest, 136 OptionQ, 492
Needs, 208, 339 Options, 493
Negative, 585 OptionsPattern, 508
Nest, 234 OptionValue, 493
NestList, 234 Or, 583
NestWhile, 235 Orange, 110
NextPrime, 406 Order, 180
NHoldAll, 125 Order Statistics, 131
NHoldFirst, 125 OrderedQ, 180
NHoldRest, 125 Orderless, 126
NIntegrate, 376 Orthogonal Polynomials, 542
NonAssociative, 423 Out, 593
None, 491 Outer, 565
NoneTrue, 582 OutputForm, 215
NonNegative, 586 OutputStream, 190, 323
NonPositive, 586 Overflow, 402
Nor, 582 OwnValues, 82
Norm, 486
Normal, 431 PadLeft, 452
Normalize, 487 PadRight, 453
Not, 583 PageRankCentrality, 609
NotListQ, 579 Parametric Graphs, 627
NotOptionQ, 492 ParametricPlot, 258
Now, 118 ParentDirectory, 208, 339
Null, 179 Part, 441
NullSpace, 396 Partition, 453
Number, 189, 322 PartitionsP, 406
Number theoretic functions, 403 Parts of Matrices, 473
NumberForm, 214 PathGraph, 633
NumberLinePlot, 257 PathGraphQ, 626
NumberQ, 586 Pattern, 509
NumberString, 74 PatternsOrderedQ, 180
Numerator, 366 PatternTest, 510
Numerical Data, 137 PauliMatrix, 236
Numerical Properties, 584 Pause, 119
NumericFunction, 125 Permutations, 431
NumericQ, 586 Pi, 402
NValues, 63 Pick, 443
Piecewise, 465
O, 377 PieChart, 259
Octahedron, 279 Pink, 111
OddQ, 587 Pixel Operations, 309
Off, 477 PixelValue, 309
Offset, 155 PixelValuePositions, 309
On, 477 PlaintextImport, 183, 184
OneIdentity, 126 PlanarGraphQ, 626
Opacity, 93, 155 Plot, 261
OpenAppend, 189, 322 Plot3D, 264
791
PlotPoints, 172 QuotientRemainder, 355
PlotRange, 173
Plotting Data, 245 Random, 408
Pluralize, 644 Random Graphs, 635
Plus, 46 Random number generation, 408
Pochhammer, 541 RandomChoice, 409
Point, 156 RandomComplex, 409
PointSize, 157 RandomGraph, 635
PolarPlot, 266 RandomImage, 305
PolyGamma, 542 RandomInteger, 410
Polygon, 159 RandomPrime, 408
PolynomialQ, 366 RandomReal, 411
Position, 443 RandomSample, 411
Positive, 587 RandomTree, 634
PossibleZeroQ, 588 RandomWord, 638
Postfix, 423 Range, 432
Power, 47 RankedMax, 132
PowerExpand, 367 RankedMin, 132
PowerMod, 354 Rational, 467
Precedence, 423 Rationalize, 481
Precision, 71 Re, 467
PreDecrement, 60 Read, 191, 325
Predicates on Lists, 448 ReadList, 193, 326
Prefix, 423 ReadProtected, 128
PreIncrement, 61 Real, 467
Prepend, 444 RealDigits, 71
PrependTo, 444 RealNumberQ, 468
Prime, 406 Reals, 377
PrimePi, 407 Reap, 432
PrimePowerQ, 407 Rearranging and Restructuring Lists, 449
PrimeQ, 588 Record, 193, 326
Print, 318 Rectangle, 161
PrintTrace, 596 Recurrence and Sum Functions, 355
Product, 466 Red, 112
ProductLog, 538 RegisterExport, 315, 345
Projection, 487 RegisterImport, 315, 346
Property, 614 Regular Expressions, 557
PropertyValue, 614 RegularExpression, 557
Protect, 127 RegularPolygon, 162
Protected, 127 Remove, 54
PseudoInverse, 397 RemoveDiacritics, 74
Purple, 111 RenameDirectory, 208, 340
Put, 190, 323 RenameFile, 209, 340
PutAppend, 191, 324 Repeated, 510
PythonForm, 215 RepeatedNull, 511
Replace, 511
QRDecomposition, 397 ReplaceAll, 512
Quantile, 131 ReplaceList, 513
Quantity, 599 ReplacePart, 445
QuantityMagnitude, 599 ReplaceRepeated, 513
QuantityQ, 600 Representation of Numbers, 66
QuantityUnit, 600 ResetDirectory, 209, 340
Quartiles, 132 Rest, 445
Quiet, 477 Return, 501
Quotient, 354 Reverse, 454
792
RGBColor, 94, 99, 160, 275 Solve, 379
Riffle, 454 Sort, 133
Right, 424 SortBy, 181
RogersTanimotoDissimilarity, 350 SourceImport, 183
Root, 377 Sow, 433
RotateLeft, 454 Span, 446
RotateRight, 455 SparseArray, 521
RotationTransform, 566 SpellingCorrectionList, 640
Round, 482 Sphere, 276
Row, 424 SphericalBesselJ, 530
RowBox, 215, 219, 429, 433, 446 SphericalBesselY, 531
RowReduce, 397 SphericalHankelH1, 531
RSolve, 520 SphericalHankelH2, 531
Rule, 514 SphericalHarmonicY, 545
RuleDelayed, 514 Splines, 268
Run, 243 Split, 455
RussellRaoDissimilarity, 350 SplitBy, 456
Sqrt, 48
SameQ, 573 SquaredEuclideanDistance, 139
ScalingTransform, 566 StandardForm, 216
Scan, 43, 228 StarGraph, 634
Sec, 417 StartOfLine, 558
Sech, 387 StartOfString, 559
SeedRandom, 412 StieltjesGamma, 542
Select, 446 StirlingS1, 356
SequenceHold, 128 StirlingS2, 356
Series, 378 StreamPosition, 194, 327
SeriesData, 378 Streams, 194, 327
SessionTime, 119 String, 76
Set, 55 String Distances and Similarity Measures, 139
SetAttributes, 129 String Manipulation, 72
SetDelayed, 56 String Patterns, 557
SetDirectory, 209, 340 StringCases, 559
SetFileDate, 209, 341 StringContainsQ, 75
SetOptions, 494 StringDrop, 551
SetStreamPosition, 193, 326 StringExpression, 560
Shape Statistics, 134 StringForm, 219
Share, 244 StringFreeQ, 560
Sharpen, 284 StringInsert, 551
ShearingTransform, 566 StringJoin, 552
Shortest, 514 StringLength, 552
Show, 163 StringMatchQ, 561
Sign, 468 StringPosition, 553
SimpleGraphQ, 626 StringQ, 75
Simplify, 367 StringRepeat, 76
Sin, 418 StringReplace, 553
SingularValueDecomposition, 398 StringReverse, 554
Sinh, 387 StringRiffle, 554
SixJSymbol, 237 StringSplit, 555
Skewness, 134 StringTake, 555
Skip, 194, 327 StringToStream, 195, 328
Slot, 221, 230 StringTrim, 556
SlotSequence, 221, 231 StruveH, 531
Small, 164 StruveL, 532
SokalSneathDissimilarity, 350 Style, 424
793
Subscript, 425 Times, 49
SubsetQ, 579 TimesBy, 61
Subsets, 351 TimeUsed, 120
Subsuperscript, 425 Timing, 120
Subtract, 49 Tiny, 166
SubtractFrom, 61 TitleImport, 183
SubValues, 63 ToBoxes, 459
Sum, 469 ToCharacterCode, 548
Sums, Simple Statistics, 50 ToExpression, 76
Superscript, 425 ToFileName, 210, 341
Switch, 502 Together, 368
Symbol, 83 ToLowerCase, 550
Symbol Handling, 78 Top, 174
SymbolName, 82 ToString, 77
SymbolQ, 82 Total, 50
SympyForm, 216 ToUpperCase, 550
Syntax, 478 Tr, 398
System-related binary handling, 87 TraceBuiltins, 596
TraceEvaluation, 597
Table, 433 TraditionalForm, 218
TableForm, 216 TransformationFunction, 566
TagSet, 57 TranslationTransform, 566
TagSetDelayed, 58 Transliterate, 77
TagsImport, 184 Transpose, 567
Take, 447 TreeGraph, 635
TakeLargest, 133 TreeGraphQ, 636
TakeLargestBy, 447 Trees, 635
TakeSmallest, 134 Trigonometric Functions, 413
TakeSmallestBy, 448 True, 583
Tally, 456 TrueQ, 574
Tan, 418 Tube, 277
Tanh, 387 Tuples, 434
Tetrahedron, 279 Types of Values, 62
TeXForm, 218
Text, 165 Undefined, 402
Text Analysis, 640 Underflow, 403
Text Normalization, 642 UndirectedEdge, 614
TextCases, 642 Unequal, 574
TextPosition, 643 Uniform Polyhedra, 278
TextRecognize, 305 UniformPolyhedron, 280
TextSentences, 643 Union, 456
TextStructure, 643 Unique, 519
TextWords, 644 UnitConvert, 600
Thick, 165 UnitVector, 488
Thickness, 165 Unprotect, 129
Thin, 166 UnsameQ, 575
Thread, 44, 229 Unset, 54
Three-Dimensional Graphics, 270 UpperCaseQ, 550
ThreeJSymbol, 238 UpSet, 58
Threshold, 285 UpSetDelayed, 59
Through, 181 UpTo, 447
Throw, 502 UpValue-related assignments, 64
TicksStyle, 173 UpValues, 64
TimeConstrained, 119 URLFetch, 316, 347
TimeRemaining, 119 URLSave, 210, 341
794
ValueQ, 83
Values, 429
Variables, 369
Vector Space Operations, 487
VectorAngle, 488
VectorQ, 580
Verbatim, 515
VertexAdd, 614
VertexConnectivity, 615
VertexCount, 622
VertexDegree, 623
VertexDelete, 616
VertexIndex, 617
VertexList, 617
WeaklyConnectedComponents, 620
WeberE, 532
Which, 502
While, 503
White, 112
Whitespace, 78
WhitespaceCharacter, 561
With, 519
Word, 195, 328
Word manipulation, 644
WordBoundary, 561
WordCharacter, 562
WordCloud, 295
WordCount, 641
WordData, 639
WordDefinition, 639
WordFrequency, 641
WordList, 639
WordSimilarity, 641
WordStem, 640, 642
Write, 195, 328
WriteString, 196, 329
XML, 184
XMLElement, 184
XMLGet, 185
XMLGetString, 185
XMLObject, 185
XMLObjectImport, 184, 185
Xor, 583
XYZColor, 94, 166
Yellow, 113
YuleDissimilarity, 352
Zeta, 546
Zeta Functions and Polylogarithms, 545
795
C OLOPHON
Mathics3 Core
6.0.0
Python
3.8.16 (default, Dec 13 2022, 19:27:23) [GCC 11.3.0]
mpmath
1.2.1
NumpyPy
1.24.0
SymPy
1.10.1
XeTeX
XeTeX 3.141592653-2.6-0.999993 (TeX Live 2022/dev/Debian)
Asymptote
Asymptote version 2.83 [(C) 2004 Andy Hammerlindl, John C.
Bowman, Tom Prince]
Ghostscript
9.56.1