Migrated from GitHub
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- data/.travis.yml +17 -0
- data/CONTRIBUTING.md +71 -0
- data/LICENSE +674 -0
- data/assets/demo-cli.gif +3 -0
- data/assets/icons/16x16.png +3 -0
- data/assets/icons/32x32.png +3 -0
- data/assets/icons/64x64.png +3 -0
- data/bin/visma +5 -0
- data/main.py +73 -0
- data/requirements.txt +10 -0
- data/run +89 -0
- data/setup.cfg +14 -0
- data/setup.py +45 -0
- data/tests/__init__.py +0 -0
- data/tests/test_calculus.py +79 -0
- data/tests/test_discrete.py +39 -0
- data/tests/test_functions.py +281 -0
- data/tests/test_io.py +127 -0
- data/tests/test_matrix.py +409 -0
- data/tests/test_simplify.py +110 -0
- data/tests/test_solvers.py +93 -0
- data/tests/test_transform.py +51 -0
- data/tests/test_utils.py +29 -0
- data/tests/tester.py +48 -0
- data/visma/__init__.py +0 -0
- data/visma/calculus/__init__.py +0 -0
- data/visma/calculus/differentiation.py +107 -0
- data/visma/calculus/integration.py +105 -0
- data/visma/config/__init__.py +0 -0
- data/visma/config/values.py +11 -0
- data/visma/discreteMaths/__init__.py +0 -0
- data/visma/discreteMaths/boolean.py +110 -0
- data/visma/discreteMaths/combinatorics.py +135 -0
- data/visma/discreteMaths/probability.py +35 -0
- data/visma/discreteMaths/statistics.py +111 -0
- data/visma/functions/__init__.py +0 -0
- data/visma/functions/constant.py +255 -0
- data/visma/functions/exponential.py +81 -0
- data/visma/functions/hyperbolic.py +101 -0
- data/visma/functions/operator.py +116 -0
- data/visma/functions/structure.py +301 -0
- data/visma/functions/trigonometry.py +300 -0
- data/visma/functions/variable.py +280 -0
- data/visma/gui/__init__.py +0 -0
- data/visma/gui/cli.py +267 -0
- data/visma/gui/logger.py +59 -0
- data/visma/gui/plotter.py +412 -0
- data/visma/gui/qsolver.py +108 -0
- data/visma/gui/settings.py +92 -0
- data/visma/gui/steps.py +65 -0
data/.travis.yml
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
language: python
|
2 |
+
python: "3.6"
|
3 |
+
|
4 |
+
install :
|
5 |
+
- pip install pylama==7.6.6
|
6 |
+
- pip install pytest==4.1.1
|
7 |
+
- pip install coverage
|
8 |
+
- pip install coveralls
|
9 |
+
- pip install PyQt5==5.11.3
|
10 |
+
|
11 |
+
script :
|
12 |
+
- pylama
|
13 |
+
- coverage run --source ./ -m pytest -v
|
14 |
+
- coverage report
|
15 |
+
|
16 |
+
after_success:
|
17 |
+
- coveralls
|
data/CONTRIBUTING.md
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
This is a brief guide on using **visma(VISualMAth)** and for making any contributions to the repo. Since visma is in its early stage, there are many features which can be implemented and many places where it can be improved/optimized.
|
2 |
+
|
3 |
+
**NOTE:** VISualMAth is supported for **python3** and above only.
|
4 |
+
|
5 |
+
### Currently, visma supports the following features
|
6 |
+
|
7 |
+
* **Simplify** - simplify the whole expression/equation or perform sub-simplifications i.e. addition, subtraction, multiplication and division
|
8 |
+
* **Find roots** - find roots for a quadratic equation
|
9 |
+
* **Factorize** - factorize a given polynomial
|
10 |
+
* **Solve** - solve the equation wrt a variable from a given equation, e.g. x^2 + y = 1, solve for x or y gives x = (1 - y)^0.5 or y = 1 - x^2
|
11 |
+
* **Integration** - integrate a polynomial expression wrt a chosen variable
|
12 |
+
* **Differentiation** - differentiate a polynomial expression wrt a chosen variable
|
13 |
+
* **Plot** - plots an interactive 2D or 3D graph
|
14 |
+
|
15 |
+

|
16 |
+
|
17 |
+
### If interested in making any contributions make sure to go through these steps
|
18 |
+
|
19 |
+
- Clone/fork the **dev** branch of the repo.
|
20 |
+
- Before [building from source](https://github.com/aerospaceresearch/visma/wiki/Beginner's-Guide#To-build-from-source) make sure to install all [dependencies](https://github.com/aerospaceresearch/visma/wiki/Beginner's-Guide#Dependencies)
|
21 |
+
- Make necessary changes(follow the [syntax guide](https://github.com/aerospaceresearch/visma/wiki/Beginner's-Guide#Syntax-guide))
|
22 |
+
- Before making a PR or commit, run [all modules test](https://github.com/aerospaceresearch/visma/wiki/Beginner's-Guide#Make-sure-all-tests-pass-before-making-a-PR)
|
23 |
+
- If all tests pass, make a PR or merge to **dev** branch
|
24 |
+
|
25 |
+
### How to contribute
|
26 |
+
|
27 |
+
Go through the source code, use visma and checkout the io, simplify and solver modules to get an idea of its working.
|
28 |
+
- Look for **TODOs**(simple tasks/features) and **FIXMEs**(mostly failing edge cases) throughout the code and try to strike them off
|
29 |
+
- Fix already raised [issues](https://github.com/aerospaceresearch/visma/wiki/Install)
|
30 |
+
- Add test cases to the relevant test modules for increasing code coverage through unit tests(coverage report can be viewed in htmlcov/index.html folder after running `./run test`)
|
31 |
+
- Try adding support for new functions and extend the existing modules(calculus, matrix etc)
|
32 |
+
- Add new modules(for ex, multivariable linear equation solver)
|
33 |
+
|
34 |
+
### To build from source
|
35 |
+
|
36 |
+
- [Download](https://github.com/aerospaceresearch/visma/archive/dev.zip) the source code zip
|
37 |
+
- Extract files
|
38 |
+
- From project folder, do `$ ./run install` or `$ pip install -r requirements.txt`(make sure to check if the pip exists in python3 library by checking the pip version, use `$ pip --version`)
|
39 |
+
- For launching visma do
|
40 |
+
```bash
|
41 |
+
$ python main.py
|
42 |
+
>>> gui
|
43 |
+
```
|
44 |
+
|
45 |
+
### Dependencies
|
46 |
+
|
47 |
+
- The following packages are required for using visma:
|
48 |
+
- PyQt5
|
49 |
+
- matplotlib
|
50 |
+
- numpy
|
51 |
+
- The following packages are required for testing visma:
|
52 |
+
- pytest
|
53 |
+
- pylama
|
54 |
+
- coverage
|
55 |
+
|
56 |
+
### Syntax guide
|
57 |
+
|
58 |
+
- Follow **_camelCase_** for naming variables, functions etc. For example:
|
59 |
+
- variables: _symTokens_, _axisRange_ etc
|
60 |
+
- functions: _tokenizer_, _getLevelVariables_ etc
|
61 |
+
- classes: _Function_, _SquareMatrix_ etc
|
62 |
+
- Use 4 spaces for tabs
|
63 |
+
- Add relevant code to the respective modules
|
64 |
+
|
65 |
+
### Make sure all tests pass before making a PR
|
66 |
+
|
67 |
+
- To run all tests do `./run test`
|
68 |
+
- To run only linter/syntax test(pylama) do `./run test syntax`
|
69 |
+
- To test all modules(pytest) do `./run test modules`
|
70 |
+
|
71 |
+
PRs are welcomed. If there are any issues or ideas they can be addressed through the [issues](https://github.com/aerospaceresearch/visma/issues) or in [chat room](https://gitter.im/aerospaceresearch/visma).
|
data/LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
{one line to give the program's name and a brief idea of what it does.}
|
635 |
+
Copyright (C) {year} {name of author}
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
{project} Copyright (C) {year} {fullname}
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<http://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
data/assets/demo-cli.gif
ADDED
![]() |
Git LFS Details
|
data/assets/icons/16x16.png
ADDED
![]() |
Git LFS Details
|
data/assets/icons/32x32.png
ADDED
![]() |
Git LFS Details
|
data/assets/icons/64x64.png
ADDED
![]() |
Git LFS Details
|
data/bin/visma
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
|
3 |
+
if __name__ == "__main__":
|
4 |
+
from visma.main import initGUI
|
5 |
+
initGUI()
|
data/main.py
ADDED
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from cmd import Cmd
|
3 |
+
from visma.gui.cli import commandExec
|
4 |
+
from visma.gui.window import initGUI
|
5 |
+
from visma.gui import logger
|
6 |
+
|
7 |
+
|
8 |
+
def init():
|
9 |
+
open(os.path.abspath("log.txt"), "w").close()
|
10 |
+
logger.setLevel(10)
|
11 |
+
logger.setLogName('main')
|
12 |
+
logger.info('Initialising VisMa...(currently in CLI mode)')
|
13 |
+
|
14 |
+
class VisMa_Prompt(Cmd):
|
15 |
+
'''This inititates the main VisMa Prompt from where user may move to CLI/GUI'''
|
16 |
+
|
17 |
+
userManual = "|_________________________________________________________________________________________________|\n"\
|
18 |
+
"| gui ->> opens Visma in GUI mode. |\n"\
|
19 |
+
"| Ctrl + D ->> Closes the prompt. |\n"\
|
20 |
+
"| exit ->> Closes the prompt. |\n"\
|
21 |
+
"|-------------------------------------------------------------------------------------------------|\n"\
|
22 |
+
"| simplify( equation or expression ) ->> Simplifies the given equation. |\n"\
|
23 |
+
"| addition( equation or expression ) ->> Adds the elements used. |\n"\
|
24 |
+
"| subtraction( equation or expression ) ->> Subtracts the elements used. |\n"\
|
25 |
+
"| multiplication( equation or expression ) ->> Multiplies the elements used. |\n"\
|
26 |
+
"| division( equation or expression ) ->> Divides the elements used. |\n"\
|
27 |
+
"|-------------------------------------------------------------------------------------------------|\n"\
|
28 |
+
"| factorize( expression ) ->> Factorizes the expression. |\n"\
|
29 |
+
"| find-roots( equation ) ->> Solves the quadratic equation for the variable in the equation. |\n"\
|
30 |
+
"| solve( equation , variable ) ->> Solves the equation for the given variable. |\n"\
|
31 |
+
"|-------------------------------------------------------------------------------------------------|\n"\
|
32 |
+
"| integrate( expression , variable ) ->> Integrates the expression by the given variable. |\n"\
|
33 |
+
"| differentiate( expression , variable ) ->> Differentiates the expression by the given variable. |\n"\
|
34 |
+
"|_________________________________________________________________________________________________|\n"\
|
35 |
+
|
36 |
+
prompt = '>>> '
|
37 |
+
intro = "Welcome! This is Visual Maths Interactive Shell...\n" + "type 'help' for a User Manual and Ctrl + D to Exit prompt\n"
|
38 |
+
|
39 |
+
def do_exit(self, inp):
|
40 |
+
'''Exits VisMa Prompt'''
|
41 |
+
print("Exiting VisMa...")
|
42 |
+
logger.info('Exiting VisMa...')
|
43 |
+
return True
|
44 |
+
|
45 |
+
def emptyline(self):
|
46 |
+
logger.error('Empty line received as input')
|
47 |
+
print('Empty line received as input\n')
|
48 |
+
|
49 |
+
def do_manual(self, inp):
|
50 |
+
'''Displays a list of commands that can be used'''
|
51 |
+
print(self.userManual)
|
52 |
+
|
53 |
+
def do_gui(self, inp):
|
54 |
+
'''Starts GUI of VisMa'''
|
55 |
+
initGUI()
|
56 |
+
print("Initiating GUI...")
|
57 |
+
logger.info("Initiating GUI...")
|
58 |
+
|
59 |
+
def default(self, inp):
|
60 |
+
'''Directs to CommandExec and performs operations thereafter'''
|
61 |
+
try:
|
62 |
+
commandExec(inp)
|
63 |
+
except Exception:
|
64 |
+
logger.error('Invalid Expression: ' + inp)
|
65 |
+
print('Invalid Expression: ' + inp + '\n')
|
66 |
+
|
67 |
+
do_EOF = do_exit
|
68 |
+
|
69 |
+
VisMa_Prompt().cmdloop()
|
70 |
+
|
71 |
+
|
72 |
+
if __name__ == '__main__':
|
73 |
+
init()
|
data/requirements.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# required
|
2 |
+
matplotlib>=2.0.0
|
3 |
+
numpy>=1.12
|
4 |
+
PyQt5>=5
|
5 |
+
PyQtWebEngine>=5.12
|
6 |
+
|
7 |
+
# for testing
|
8 |
+
pylama
|
9 |
+
pytest>=3.5
|
10 |
+
coverage>=4.0
|
data/run
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
|
3 |
+
from __future__ import print_function
|
4 |
+
import sys
|
5 |
+
import subprocess
|
6 |
+
import threading
|
7 |
+
import glob
|
8 |
+
|
9 |
+
|
10 |
+
def Str(value):
|
11 |
+
if isinstance(value, list):
|
12 |
+
return " ".join(value)
|
13 |
+
if isinstance(value, basestring):
|
14 |
+
return value
|
15 |
+
return str(value)
|
16 |
+
|
17 |
+
|
18 |
+
def Glob(value):
|
19 |
+
ret = glob.glob(value)
|
20 |
+
if(len(ret) < 1):
|
21 |
+
ret = [value]
|
22 |
+
return ret
|
23 |
+
|
24 |
+
|
25 |
+
for i in range(4-len(sys.argv)):
|
26 |
+
sys.argv.append("")
|
27 |
+
|
28 |
+
if(str(sys.argv[1]) == ""):
|
29 |
+
print("")
|
30 |
+
print("Enter command arguments with run")
|
31 |
+
print(" ./run install - Install all dependencies for visma")
|
32 |
+
print(" ./run visma - Open visma GUI")
|
33 |
+
print(" ./run test - Run all the tests and generates coverage report")
|
34 |
+
print(" ./run test path/to/test_file.py - Runs all tests and shows coverage for given file")
|
35 |
+
print(" ./run test syntax - Run syntax test using pylama")
|
36 |
+
print(" ./run test modules - Run tests using pytest for all modules")
|
37 |
+
print(" ./run test coverage - After running all the tests, open coverage report")
|
38 |
+
print(" ./run pack - Generate builds for visma package")
|
39 |
+
print(" ./run pack upload - Generate builds and then upload to test.pypi.org")
|
40 |
+
print(" ./run pack final - Generate builds and upload final build to pypi.org")
|
41 |
+
print(" ./run clean - Clean all cache, reports and builds")
|
42 |
+
print("")
|
43 |
+
|
44 |
+
elif (str(sys.argv[1]) == "install"):
|
45 |
+
subprocess.call("python3 -m pip install -r requirements.txt", shell=True)
|
46 |
+
|
47 |
+
elif (str(sys.argv[1]) == "visma"):
|
48 |
+
subprocess.call("python3 main.py", shell=True)
|
49 |
+
|
50 |
+
elif str(sys.argv[1]) == "test":
|
51 |
+
if str(sys.argv[2]) == "syntax" or str(sys.argv[2]) == "":
|
52 |
+
print("Python Syntax Test ...")
|
53 |
+
subprocess.call("pylama", shell=True)
|
54 |
+
elif (str(sys.argv[2]) == "modules"):
|
55 |
+
print("Python Modules Test ...")
|
56 |
+
subprocess.call("pytest", shell=True)
|
57 |
+
|
58 |
+
if str(sys.argv[2]) != "" and str(sys.argv[2]) != "coverage" and str(sys.argv[2]) != "syntax" and str(sys.argv[2]) != "modules":
|
59 |
+
print("Python Test for " + str(sys.argv[2]) + " ...")
|
60 |
+
subprocess.call("coverage run --source ./ -m pytest " + str(sys.argv[2]) + " -v", shell=True)
|
61 |
+
|
62 |
+
elif str(sys.argv[2]) == "":
|
63 |
+
print("Python Modules Test with Coverage ...")
|
64 |
+
subprocess.call("coverage run --source ./ -m pytest -v", shell=True)
|
65 |
+
|
66 |
+
if str(sys.argv[2]) == "" or str(sys.argv[2]) == "coverage" or str(sys.argv[3]) == "coverage":
|
67 |
+
subprocess.call("coverage report", shell=True)
|
68 |
+
subprocess.call("coverage html", shell=True)
|
69 |
+
|
70 |
+
if str(sys.argv[2]) == "coverage" or str(sys.argv[3]) == "coverage":
|
71 |
+
def thread1():
|
72 |
+
subprocess.call("nohup xdg-open ./htmlcov/index.html", shell=True)
|
73 |
+
threading.Thread(target=thread1).start()
|
74 |
+
|
75 |
+
elif str(sys.argv[1]) == "pack":
|
76 |
+
subprocess.call("mv main.py visma", shell=True)
|
77 |
+
subprocess.call("python3 setup.py sdist bdist_wheel", shell=True)
|
78 |
+
subprocess.call("mv ./visma/main.py ./", shell=True)
|
79 |
+
|
80 |
+
if str(sys.argv[2]) == "upload":
|
81 |
+
subprocess.call("twine upload --repository-url https://test.pypi.org/legacy/", Str(Glob("dist/*")), shell=True)
|
82 |
+
elif str(sys.argv[2]) == "final":
|
83 |
+
subprocess.call("twine upload", Str(Glob("dist/*")), shell=True)
|
84 |
+
|
85 |
+
elif str(sys.argv[1]) == "clean":
|
86 |
+
subprocess.call("git clean -xdf", shell=True)
|
87 |
+
|
88 |
+
else:
|
89 |
+
print("Invalid arguments")
|
data/setup.cfg
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[pylama]
|
2 |
+
ignore = C901,E0602,E501,W605
|
3 |
+
# C901: 'xyz' is too complex
|
4 |
+
# E0602: undefined name 'xyz'
|
5 |
+
# E501: E501 line too long (> 79 chars)
|
6 |
+
# W605: Invalid escape sequence
|
7 |
+
|
8 |
+
[tool:pytest]
|
9 |
+
|
10 |
+
[coverage:run]
|
11 |
+
omit = main.py, setup.py, */__init__.py, visma/gui/*, visma/testbed/*, run
|
12 |
+
|
13 |
+
[coverage:report]
|
14 |
+
omit = main.py, setup.py, */__init__.py, visma/gui/*, visma/testbed/*, run
|
data/setup.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import setuptools
|
2 |
+
|
3 |
+
with open("README.md", "r") as fh:
|
4 |
+
long_description = fh.read()
|
5 |
+
|
6 |
+
setuptools.setup(
|
7 |
+
name="VISualMAth",
|
8 |
+
description="visma - VISual MAth : A math equation solver and visualizer",
|
9 |
+
version="1.0.0.0",
|
10 |
+
author="Siddharth Kothiyal, Shantanu Mishra, Mayank Dhiman",
|
11 |
+
author_email="[email protected], [email protected], [email protected]",
|
12 |
+
long_description=long_description,
|
13 |
+
long_description_content_type="text/markdown",
|
14 |
+
url="https://github.com/aerospaceresearch/visma",
|
15 |
+
project_urls={
|
16 |
+
'Documentation': 'https://github.com/aerospaceresearch/visma/wiki',
|
17 |
+
'Source': 'https://github.com/aerospaceresearch/visma',
|
18 |
+
'Issues': 'https://github.com/aerospaceresearch/visma/issues',
|
19 |
+
'Chat': 'https://gitter.im/aerospaceresearch/visma'
|
20 |
+
},
|
21 |
+
packages=setuptools.find_packages(),
|
22 |
+
scripts=['bin/visma'],
|
23 |
+
classifiers=(
|
24 |
+
"Programming Language :: Python :: 3",
|
25 |
+
"Programming Language :: Python :: 3.4",
|
26 |
+
"Programming Language :: Python :: 3.5",
|
27 |
+
"Programming Language :: Python :: 3.6",
|
28 |
+
"Programming Language :: Python :: 3.7",
|
29 |
+
"Operating System :: OS Independent",
|
30 |
+
"Topic :: Scientific/Engineering",
|
31 |
+
"Topic :: Scientific/Engineering :: Mathematics",
|
32 |
+
"Topic :: Scientific/Engineering :: Visualization",
|
33 |
+
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)"
|
34 |
+
),
|
35 |
+
python_requires='>=3',
|
36 |
+
install_requires=[
|
37 |
+
"PyQt5",
|
38 |
+
"matplotlib",
|
39 |
+
"numpy"
|
40 |
+
],
|
41 |
+
tests_require=[
|
42 |
+
"pytest",
|
43 |
+
"coverage"
|
44 |
+
]
|
45 |
+
)
|
data/tests/__init__.py
ADDED
File without changes
|
data/tests/test_calculus.py
ADDED
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from visma.calculus.differentiation import differentiate, differentiationProductRule
|
2 |
+
from visma.calculus.integration import integrate
|
3 |
+
from tests.tester import quickTest
|
4 |
+
|
5 |
+
############################
|
6 |
+
# calculus.differentiation #
|
7 |
+
############################
|
8 |
+
|
9 |
+
|
10 |
+
def test_differentiate():
|
11 |
+
|
12 |
+
assert quickTest("x^2 + x", differentiate, 'x') == "2.0x+1.0"
|
13 |
+
|
14 |
+
assert quickTest("x + 2y + 3z + 4", differentiate, 'x') == "1.0"
|
15 |
+
assert quickTest("x + 2y + 3z + 4", differentiate, 'y') == "2.0"
|
16 |
+
assert quickTest("x + 2y + 3z + 4", differentiate, 'z') == "3.0"
|
17 |
+
|
18 |
+
assert quickTest("xy + xy^2 + xyz", differentiate, 'x') == "y+y^(2.0)+yz"
|
19 |
+
assert quickTest("xy + xy^2 + xyz", differentiate, 'y') == "x+2.0xy+xz"
|
20 |
+
assert quickTest("xy + xy^2 + xyz", differentiate, 'z') == "xy"
|
21 |
+
|
22 |
+
assert quickTest("xy + z", differentiate, 'z') == "1.0"
|
23 |
+
assert quickTest("z + xy", differentiate, 'z') == "1.0"
|
24 |
+
assert quickTest("z - xy", differentiate, 'z') == "1.0"
|
25 |
+
assert quickTest("xy - z", differentiate, 'z') == "-1.0"
|
26 |
+
|
27 |
+
assert quickTest("sin(x)", differentiate, 'x') == "cos(x)*1.0"
|
28 |
+
assert quickTest("sin(x)", differentiate, 'y') == "0.0"
|
29 |
+
assert quickTest("sin(xxx)", differentiate, 'x') == "cos(x^(3.0))*3.0x^(2.0)"
|
30 |
+
assert quickTest("sin(log(xx))", differentiate, 'x') == "cos(log(x^(2.0)))*x^(-1.0)*2.0x"
|
31 |
+
|
32 |
+
assert quickTest("cos(x)", differentiate, 'x') == "-1.0*sin(x)*1.0"
|
33 |
+
assert quickTest("cos(x)", differentiate, 'y') == "0.0"
|
34 |
+
assert quickTest("cos(xxx)", differentiate, 'x') == "-1.0*sin(x^(3.0))*3.0x^(2.0)"
|
35 |
+
assert quickTest("cos(log(xx))", differentiate, 'x') == "-1.0*sin(log(x^(2.0)))*x^(-1.0)*2.0x"
|
36 |
+
|
37 |
+
assert quickTest("tan(x)", differentiate, 'x') == "sec(x)*1.0"
|
38 |
+
# FIXME: Simplify module simplifies sec^2(x) as sec(x) and cosec^2(x) as cosec(x), however differentiation modules give correct output
|
39 |
+
assert quickTest("tan(x)", differentiate, 'y') == "0.0"
|
40 |
+
|
41 |
+
assert quickTest("cot(x)", differentiate, 'x') == "-1.0*csc(x)*1.0"
|
42 |
+
# FIXME: Simplify module simplifies sec^2(x) as sec(x) and cosec^2(x) as cosec(x), however differentiation modules give correct output
|
43 |
+
assert quickTest("cot(x)", differentiate, 'y') == "0.0"
|
44 |
+
|
45 |
+
assert quickTest("csc(x)", differentiate, 'x') == "-1.0*csc(x)*cot(x)*1.0"
|
46 |
+
assert quickTest("csc(x)", differentiate, 'y') == "0.0"
|
47 |
+
|
48 |
+
assert quickTest("sec(x)", differentiate, 'x') == "sec(x)*tan(x)*1.0"
|
49 |
+
assert quickTest("sec(x)", differentiate, 'y') == "0.0"
|
50 |
+
|
51 |
+
assert quickTest("log(x)", differentiate, 'x') == "x^(-1.0)"
|
52 |
+
assert quickTest("log(xx)", differentiate, 'x') == "2.0"
|
53 |
+
|
54 |
+
# Tests for Product Rule of Differentiation.
|
55 |
+
assert quickTest("sin(x)*cos(x)", differentiationProductRule, 'x') == "(cos(x)*1.0)*cos(x)+sin(x)*(-1.0*sin(x)*1.0)"
|
56 |
+
assert quickTest("sin(x)*x", differentiationProductRule, 'x') == "(cos(x)*1.0)*x+sin(x)*(1.0)"
|
57 |
+
assert quickTest("sin(x)*y", differentiationProductRule, 'x') == "(cos(x)*1.0)*y+sin(x)*(0.0)"
|
58 |
+
assert quickTest("sin(x)*cos(x)*sec(x)", differentiationProductRule, 'x') == "(cos(x)*1.0)*cos(x)*sec(x)+sin(x)*(-1.0*sin(x)*1.0)*sec(x)+sin(x)*cos(x)*(sec(x)*tan(x)*1.0)"
|
59 |
+
|
60 |
+
|
61 |
+
########################
|
62 |
+
# calculus.integration #
|
63 |
+
########################
|
64 |
+
|
65 |
+
|
66 |
+
def test_integrate():
|
67 |
+
|
68 |
+
assert quickTest("x + 1", integrate, 'x') == "0.5x^(2.0)+x"
|
69 |
+
|
70 |
+
assert quickTest("xyz + xy/z + x + 1 + 1/x", integrate, 'x') == "0.5x^(2.0)yz+0.5x^(2.0)yz^(-1.0)+0.5x^(2.0)+x+1.0*log(x)" # FIXME(integration.py): Ignore coeff if 1
|
71 |
+
assert quickTest("xyz + xy/z + x + 1 + 1/x", integrate, 'y') == "0.5xy^(2.0)z+0.5xy^(2.0)z^(-1.0)+xy+y+x^(-1.0)y"
|
72 |
+
assert quickTest("xyz + xy/z + x + 1 + 1/x", integrate, 'z') == "0.5xyz^(2.0)+xy*log(z)+xz+z+x^(-1.0)z"
|
73 |
+
|
74 |
+
assert quickTest("sin(x)", integrate, 'x') == "-1.0*cos(x)"
|
75 |
+
assert quickTest("cos(x)", integrate, 'x') == "sin(x)"
|
76 |
+
assert quickTest("tan(x)", integrate, 'x') == "-1.0*ln(cos(x))"
|
77 |
+
assert quickTest("csc(x)", integrate, 'x') == "-1.0*ln((csc(x)+cot(x)))"
|
78 |
+
assert quickTest("sec(x)", integrate, 'x') == "ln((sec(x)+tan(x)))"
|
79 |
+
assert quickTest("cot(x)", integrate, 'x') == "ln(sin(x))"
|
data/tests/test_discrete.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from tests.tester import quickTest
|
2 |
+
from visma.discreteMaths.combinatorics import factorial, permutation, combination
|
3 |
+
from visma.discreteMaths.statistics import ArithemeticMean, Mode, Median
|
4 |
+
|
5 |
+
|
6 |
+
def test_factorial():
|
7 |
+
|
8 |
+
assert quickTest("5", factorial) == "120.0"
|
9 |
+
assert quickTest("0", factorial) == "1"
|
10 |
+
assert quickTest("11", factorial) == "39916800.0"
|
11 |
+
assert quickTest("11 - 11", factorial) == "1"
|
12 |
+
|
13 |
+
|
14 |
+
def test_permutation():
|
15 |
+
|
16 |
+
assert quickTest("5;2", permutation) == "20.0"
|
17 |
+
assert quickTest("12;3", permutation) == "1320.0"
|
18 |
+
assert quickTest("10 + 2;5 - 2", permutation) == "1320.0"
|
19 |
+
assert quickTest("11;11", permutation) == "39916800.0"
|
20 |
+
|
21 |
+
|
22 |
+
def test_combination():
|
23 |
+
|
24 |
+
assert quickTest("5;2", combination) == "10.0"
|
25 |
+
assert quickTest("2;2", permutation) == "2.0"
|
26 |
+
assert quickTest("11;0", permutation) == "1.0"
|
27 |
+
assert quickTest("11;11 - 11", permutation) == "1.0"
|
28 |
+
|
29 |
+
|
30 |
+
def test_statistics():
|
31 |
+
|
32 |
+
assert quickTest([12, 1, -12, -1, 0], ArithemeticMean) == "0.0"
|
33 |
+
assert quickTest([11, 1, -2, -1, 0], ArithemeticMean) == "1.8"
|
34 |
+
|
35 |
+
assert quickTest([12, 12, 12, 12, 1, -12, -1, 0], Mode) == "Mode=12;ModeFrequency=4"
|
36 |
+
assert quickTest([-1, -1, 2, 3, 4, 5, 6], Mode) == "Mode=-1;ModeFrequency=2"
|
37 |
+
|
38 |
+
assert quickTest([1, 2, 3, 4, 5], Median) == "3"
|
39 |
+
assert quickTest([1, 2, 3, 4, 5, 12], Median) == "3.5"
|
data/tests/test_functions.py
ADDED
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from visma.functions.constant import Constant
|
2 |
+
from visma.functions.variable import Variable
|
3 |
+
from visma.functions.structure import Expression
|
4 |
+
from visma.functions.operator import Plus, Minus
|
5 |
+
from visma.io.parser import tokensToString
|
6 |
+
|
7 |
+
######################
|
8 |
+
# functions.constant #
|
9 |
+
######################
|
10 |
+
|
11 |
+
|
12 |
+
def test_Constant():
|
13 |
+
|
14 |
+
# Tests for Calculus operations for Constant Class.
|
15 |
+
|
16 |
+
constant1 = Constant(10)
|
17 |
+
assert constant1.__str__() == "{10}"
|
18 |
+
constant1.differentiate()
|
19 |
+
assert constant1.value == 0
|
20 |
+
|
21 |
+
constant2 = Constant(5, 2)
|
22 |
+
constant2.integrate('x')
|
23 |
+
assert isinstance(constant2, Variable)
|
24 |
+
assert constant2.__str__() == "25{x}"
|
25 |
+
|
26 |
+
# Tests for Add/Sub operations (using Overloading) for Constant Class.
|
27 |
+
|
28 |
+
constant4 = Constant(2, 2)
|
29 |
+
constant5 = Constant(7)
|
30 |
+
constant3 = constant4 - constant5
|
31 |
+
assert constant3.__str__() == "{-3}"
|
32 |
+
|
33 |
+
constant4 = Constant(7, 2)
|
34 |
+
constant0 = Constant(5)
|
35 |
+
constant6 = constant4 - constant3 - constant5 + constant0
|
36 |
+
assert constant6.__str__() == "{50}"
|
37 |
+
|
38 |
+
constant0 = Constant(5, 2, 2)
|
39 |
+
constant2 = constant0
|
40 |
+
variable0 = Variable(5, 'X', 3)
|
41 |
+
summation0 = constant0 - variable0 + constant2
|
42 |
+
assert summation0.__str__() == "{({100}-5{X}^{3})}"
|
43 |
+
|
44 |
+
constant0 = Constant(5, 2, 2)
|
45 |
+
constant2 = constant0
|
46 |
+
variable0 = Variable(5, 'X', 3)
|
47 |
+
summation0 = constant0 + variable0 + constant2
|
48 |
+
assert summation0.__str__() == "{({100}+5{X}^{3})}"
|
49 |
+
|
50 |
+
var1 = Variable(3, 'x', 3)
|
51 |
+
const1 = Constant(5)
|
52 |
+
expr1 = Expression([var1, Minus(), const1])
|
53 |
+
constant2 = Constant(2, 2)
|
54 |
+
sub1 = constant2 - expr1
|
55 |
+
assert sub1.__str__() == "{({9}-3{x}^{3})}"
|
56 |
+
|
57 |
+
constant1 = Constant(2)
|
58 |
+
constant2 = Constant(7)
|
59 |
+
constant3 = constant1 + constant2
|
60 |
+
assert constant3.__str__() == "{9}"
|
61 |
+
|
62 |
+
constant1 = Constant(2)
|
63 |
+
constant2 = Constant(7)
|
64 |
+
constant3 = constant1 - constant2
|
65 |
+
assert constant3.__str__() == "{-5}"
|
66 |
+
|
67 |
+
constant1 = Constant(5)
|
68 |
+
variable1 = Variable(5, 'x', 3)
|
69 |
+
summation = constant1 + variable1
|
70 |
+
assert summation.__str__() == "{({5}+5{x}^{3})}"
|
71 |
+
|
72 |
+
constant1 = Constant(5)
|
73 |
+
variable1 = Variable(5, 'x', 3)
|
74 |
+
summation = constant1 - variable1
|
75 |
+
assert summation.__str__() == "{({5}-5{x}^{3})}"
|
76 |
+
|
77 |
+
# Tests for Add/Sub operations (using Overloading) for Constant Class.
|
78 |
+
|
79 |
+
constant0 = Constant(0, 2)
|
80 |
+
constant1 = Constant(5)
|
81 |
+
mul1 = constant0 * constant1
|
82 |
+
assert mul1.calculate() == 0
|
83 |
+
mul1 = constant1 * constant0
|
84 |
+
assert mul1.calculate() == 0
|
85 |
+
mul1 = constant1 * constant1 + constant0 * constant1 + constant0 * constant1
|
86 |
+
assert mul1.calculate() == 25
|
87 |
+
|
88 |
+
constant1 = Constant(5, 2)
|
89 |
+
constant2 = Constant(4, 2)
|
90 |
+
variable0 = Variable(3, 'X', 3)
|
91 |
+
mul3 = constant1 * (constant2 + variable0)
|
92 |
+
assert mul3.__str__() == "{({400}+75{X}^{3})}"
|
93 |
+
|
94 |
+
constant1 = Constant(5, 2)
|
95 |
+
constant2 = Constant(4, 2)
|
96 |
+
variable0 = Variable(3, 'X', 3)
|
97 |
+
mul3 = constant1 / (constant2 + variable0)
|
98 |
+
assert mul3.__str__() == "{25}*{({16}+3{X}^{3})}^{-1}"
|
99 |
+
|
100 |
+
constant1 = Constant(5)
|
101 |
+
constant2 = Constant(4)
|
102 |
+
div1 = constant1 / constant2
|
103 |
+
assert div1.__str__() == "{1.25}"
|
104 |
+
|
105 |
+
constant1 = Constant(3, 2)
|
106 |
+
constant2 = Constant(4, 2)
|
107 |
+
variable0 = Variable(3, 'X', 3)
|
108 |
+
mul3 = constant1 - constant1/(constant2/variable0 + constant1)
|
109 |
+
assert mul3.__str__() == "{({9}-{9}*{(5.333333333333333{X}^{-3}+{9})}^{-1})}"
|
110 |
+
|
111 |
+
constant1 = Constant(2, 2)
|
112 |
+
constant2 = Constant(2, 2)
|
113 |
+
mul3 = constant1 ** constant2
|
114 |
+
assert mul3.__str__() == "{256}"
|
115 |
+
|
116 |
+
constant1 = Constant(5)
|
117 |
+
constant2 = Constant(5)
|
118 |
+
summation = constant1 * constant2
|
119 |
+
assert summation.__str__() == "{25}"
|
120 |
+
|
121 |
+
constant1 = Constant(5)
|
122 |
+
variable1 = Variable(5, 'x', 3)
|
123 |
+
exp1 = Expression([constant1, Plus(), variable1])
|
124 |
+
constant2 = Constant(10)
|
125 |
+
summation = constant2 + exp1
|
126 |
+
assert summation.__str__() == "{({15}+5{x}^{3})}"
|
127 |
+
|
128 |
+
constant1 = Constant(5)
|
129 |
+
variable1 = Variable(5, 'x', 3)
|
130 |
+
exp1 = Expression([constant1, Plus(), variable1])
|
131 |
+
constant2 = Constant(10)
|
132 |
+
summation = constant2 - exp1
|
133 |
+
assert summation.__str__() == "{({5}-5{x}^{3})}"
|
134 |
+
|
135 |
+
constant1 = Constant(5)
|
136 |
+
variable1 = Variable(5, 'x', 3)
|
137 |
+
exp1 = Expression([constant1, Plus(), variable1])
|
138 |
+
constant2 = Constant(10)
|
139 |
+
summation = exp1 - constant2
|
140 |
+
assert summation.__str__() == "{({-5}+5{x}^{3})}"
|
141 |
+
|
142 |
+
constant1 = Constant(5)
|
143 |
+
variable1 = Variable(5, 'x', 3)
|
144 |
+
summation = constant1 * variable1
|
145 |
+
assert summation.__str__() == "25{x}^{3}"
|
146 |
+
|
147 |
+
constant1 = Constant(5)
|
148 |
+
variable1 = Variable(5, 'x', 3)
|
149 |
+
exp1 = Expression([constant1, Plus(), variable1])
|
150 |
+
constant2 = Constant(10)
|
151 |
+
summation = constant2 * exp1
|
152 |
+
assert summation.__str__() == "{({50}+50{x}^{3})}"
|
153 |
+
|
154 |
+
constant1 = Constant(5)
|
155 |
+
constant2 = Constant(5)
|
156 |
+
summation = constant1 / constant2
|
157 |
+
assert summation.__str__() == "{1.0}"
|
158 |
+
|
159 |
+
constant1 = Constant(5)
|
160 |
+
variable1 = Variable(5, 'x', 3)
|
161 |
+
summation = constant1 / variable1
|
162 |
+
assert summation.__str__() == "{x}^{-3}"
|
163 |
+
|
164 |
+
constant1 = Constant(5)
|
165 |
+
variable1 = Variable(5, 'x', 3)
|
166 |
+
exp1 = Expression([constant1, Plus(), variable1])
|
167 |
+
constant2 = Constant(10)
|
168 |
+
summation = constant2 / exp1
|
169 |
+
assert summation.__str__() == "{10}*{({5}+5{x}^{3})}^{-1}"
|
170 |
+
|
171 |
+
constant1 = Constant(5)
|
172 |
+
variable1 = Variable(5, 'x', 3)
|
173 |
+
exp1 = Expression([constant1, Plus(), variable1])
|
174 |
+
constant2 = Constant(10)
|
175 |
+
summation = exp1 / constant2
|
176 |
+
assert summation.__str__() == "{({0.5}+0.5{x}^{3})}"
|
177 |
+
|
178 |
+
|
179 |
+
######################
|
180 |
+
# functions.variable #
|
181 |
+
######################
|
182 |
+
|
183 |
+
|
184 |
+
def test_Variable():
|
185 |
+
|
186 |
+
variable1 = Variable(2, 'x', 3)
|
187 |
+
assert variable1.__str__() == "2{x}^{3}"
|
188 |
+
variable1, _ = variable1.integrate('x')
|
189 |
+
assert variable1.__str__() == "0.5{x}^{4}"
|
190 |
+
|
191 |
+
constant = Constant(3)
|
192 |
+
variable = Variable(2, 'x', 3)
|
193 |
+
add = variable + constant
|
194 |
+
assert add.__str__() == "{(2{x}^{3}+{3})}"
|
195 |
+
|
196 |
+
variable1 = Variable(2, 'x', 3)
|
197 |
+
variable2 = Variable(4, 'x', 3)
|
198 |
+
add1 = variable1 + variable2
|
199 |
+
assert add1.__str__() == "6{x}^{3}"
|
200 |
+
|
201 |
+
variable1 = Variable(2, 'x', 3)
|
202 |
+
constant = Constant(3)
|
203 |
+
exp1 = Expression([variable1, Plus(), constant])
|
204 |
+
variable2 = Variable(4, 'x', 3)
|
205 |
+
add2 = variable2 + exp1
|
206 |
+
assert add2.__str__() == "{(6{x}^{3}+{3})}"
|
207 |
+
|
208 |
+
variable1 = Variable(2, 'x', 3)
|
209 |
+
constant = Constant(3)
|
210 |
+
exp1 = variable1 + constant
|
211 |
+
variable2 = Variable(4, 'x', 3)
|
212 |
+
add2 = variable2 - exp1
|
213 |
+
assert add2.__str__() == "{(2{x}^{3}-{3})}"
|
214 |
+
|
215 |
+
variable1 = Variable(2, 'x', 3)
|
216 |
+
constant = Constant(3)
|
217 |
+
exp1 = Expression([variable1, Plus(), constant])
|
218 |
+
variable2 = Variable(4, 'x', 3)
|
219 |
+
add2 = exp1 - variable2
|
220 |
+
assert add2.__str__() == "{(-2{x}^{3}+{3})}"
|
221 |
+
|
222 |
+
constant = Constant(3)
|
223 |
+
variable = Variable(2, 'x', 3)
|
224 |
+
add = variable - constant
|
225 |
+
assert add.__str__() == "{(2{x}^{3}-{3})}"
|
226 |
+
|
227 |
+
variable1 = Variable(2, 'x', 3)
|
228 |
+
variable2 = Variable(4, 'x', 3)
|
229 |
+
variable3 = Variable(2, 'x', 4)
|
230 |
+
variable4 = Variable(2, 'x', 3)
|
231 |
+
add1 = variable1 - variable2
|
232 |
+
add2 = variable3 - variable4
|
233 |
+
assert add1.__str__() == "-2{x}^{3}"
|
234 |
+
assert add2.__str__() == "{(2{x}^{4}-2{x}^{3})}"
|
235 |
+
|
236 |
+
constant = Constant(3)
|
237 |
+
variable = Variable(2, 'x', 3)
|
238 |
+
add = variable * constant
|
239 |
+
assert add.__str__() == "6{x}^{3}"
|
240 |
+
|
241 |
+
variable1 = Variable(2, 'x', 3)
|
242 |
+
variable2 = Variable(4, 'x', 3)
|
243 |
+
add2 = variable1 * variable2
|
244 |
+
assert add2.__str__() == "8{x}^{6}"
|
245 |
+
|
246 |
+
variable1 = Variable(2, 'x', 3)
|
247 |
+
variable2 = Variable(4, 'y', 3)
|
248 |
+
add2 = variable1 * variable2
|
249 |
+
assert add2.__str__() == "8{x}^{3}{y}^{3}"
|
250 |
+
|
251 |
+
variable1 = Variable(2, 'x', 3)
|
252 |
+
variable2 = Variable(4, 'y', 4)
|
253 |
+
add1 = variable1 / variable2
|
254 |
+
assert add1.__str__() == "0.5{x}^{3}{y}^{-4}"
|
255 |
+
|
256 |
+
variable1 = Variable(2, 'x', 3)
|
257 |
+
constant = Constant(3)
|
258 |
+
exp1 = variable1 - constant
|
259 |
+
variable2 = Variable(4, 'x', 3)
|
260 |
+
add2 = variable2 / exp1
|
261 |
+
assert add2.__str__() == "{(4.0{x}^{3}*{(2{x}^{3}-{3})}^{-1})}"
|
262 |
+
|
263 |
+
variable1 = Variable(2, 'x', 3)
|
264 |
+
constant = Constant(3)
|
265 |
+
exp1 = variable1 - constant
|
266 |
+
variable2 = Variable(4, 'x', 3)
|
267 |
+
add2 = variable2 * exp1
|
268 |
+
assert add2.__str__() == "{(8{x}^{6}-12{x}^{3})}"
|
269 |
+
|
270 |
+
variable1 = Variable(2, 'x', 3)
|
271 |
+
constant1 = Constant(3)
|
272 |
+
exp1 = variable1 - constant1
|
273 |
+
variable2 = Variable(4, 'x', 3)
|
274 |
+
constant2 = Constant(4)
|
275 |
+
exp2 = variable2 - constant2
|
276 |
+
add2 = exp1 * exp2
|
277 |
+
assert add2.__str__() == "{({(8{x}^{6}-8{x}^{3})}-{(12{x}^{3}-{12})})}"
|
278 |
+
|
279 |
+
variable2 = Variable(3, 'x', -1)
|
280 |
+
variable2, _ = variable2.integrate('x')
|
281 |
+
assert tokensToString(variable2) == '3 * log(x)'
|
data/tests/test_io.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from visma.io.checks import getVariables, areTokensEqual, isTokenInToken
|
2 |
+
from visma.io.parser import tokensToString, tokensToLatex
|
3 |
+
from visma.io.tokenize import getTerms, normalize
|
4 |
+
from visma.functions.operator import Operator, Plus
|
5 |
+
from visma.functions.structure import Expression
|
6 |
+
from tests.tester import getTokens
|
7 |
+
|
8 |
+
#############
|
9 |
+
# io.checks #
|
10 |
+
#############
|
11 |
+
|
12 |
+
|
13 |
+
def test_getVariables():
|
14 |
+
|
15 |
+
varA = getTokens("x")
|
16 |
+
assert getVariables([varA]) == ['x']
|
17 |
+
|
18 |
+
varB = getTokens("xy+ xy^2 +yz^3")
|
19 |
+
assert getVariables(varB) == ['x', 'y', 'z']
|
20 |
+
|
21 |
+
varC = getTokens("x + sin(x) + cos(y) + tan(2*z)*2 + tanh(z) + e^2")
|
22 |
+
# FIXME: getVariables() in visma.io.checks
|
23 |
+
# varC = getTokens("x + sin(x) + cos(y) + tan(2*z)*2 + tanh(z) + e^2")
|
24 |
+
# assert getVariables(varC) == ['x', 'y', 'z']
|
25 |
+
assert getVariables(varC) == ['x']
|
26 |
+
|
27 |
+
|
28 |
+
def test_areTokensEqual():
|
29 |
+
|
30 |
+
varA = getTokens("3xy")
|
31 |
+
varB = getTokens("3yx")
|
32 |
+
varC = getTokens("3yz")
|
33 |
+
assert areTokensEqual(varA, varB)
|
34 |
+
assert not areTokensEqual(varA, varC)
|
35 |
+
|
36 |
+
opA = Operator()
|
37 |
+
opA.value = '+'
|
38 |
+
opB = Plus()
|
39 |
+
assert areTokensEqual(opA, opB)
|
40 |
+
|
41 |
+
|
42 |
+
def test_isTokenInToken():
|
43 |
+
|
44 |
+
varA = getTokens("x^3")
|
45 |
+
varB = getTokens("xy^2")
|
46 |
+
varC = Expression(getTokens("1 + w + x"))
|
47 |
+
varD = Expression(getTokens("w + y"))
|
48 |
+
assert isTokenInToken(varA, varB)
|
49 |
+
assert isTokenInToken(varA, varC)
|
50 |
+
assert not isTokenInToken(varA, varD)
|
51 |
+
|
52 |
+
varA = getTokens("xy^2")
|
53 |
+
varB = getTokens("x^(2)y^(4)z")
|
54 |
+
varC = getTokens("yx^0.5")
|
55 |
+
varD = getTokens("xy^(3)z")
|
56 |
+
varE = getTokens("2")
|
57 |
+
assert isTokenInToken(varA, varB)
|
58 |
+
assert isTokenInToken(varA, varC)
|
59 |
+
assert not isTokenInToken(varA, varD)
|
60 |
+
assert not isTokenInToken(varA, varE)
|
61 |
+
|
62 |
+
|
63 |
+
#############
|
64 |
+
# io.parser #
|
65 |
+
#############
|
66 |
+
|
67 |
+
|
68 |
+
def test_tokensToString():
|
69 |
+
|
70 |
+
# Matrix token to string
|
71 |
+
mat = getTokens("[1+x, 2; \
|
72 |
+
3 , 4]")
|
73 |
+
assert tokensToString([mat]) == "[1.0 + x,2.0;3.0,4.0]"
|
74 |
+
|
75 |
+
mat = getTokens("[1+x, 2] + [1, y + z^2]")
|
76 |
+
assert tokensToString(mat) == "[1.0 + x,2.0] + [1.0,y + z^(2.0)]"
|
77 |
+
|
78 |
+
|
79 |
+
def test_tokensToLatex():
|
80 |
+
|
81 |
+
# Matrix token to latex
|
82 |
+
mat = getTokens("[1+x, 2; \
|
83 |
+
3 , 4]")
|
84 |
+
assert tokensToLatex([mat]) == "\\begin{bmatrix}{1.0}+{x}&{2.0}\\\\{3.0}&{4.0}\\end{bmatrix}"
|
85 |
+
|
86 |
+
mat = getTokens("[1+x, 2] + [1, y + z^2]")
|
87 |
+
assert tokensToLatex(mat) == "\\begin{bmatrix}{1.0}+{x}&{2.0}\\end{bmatrix}+\\begin{bmatrix}{1.0}&{y}+{z}^{2.0}\\end{bmatrix}"
|
88 |
+
|
89 |
+
|
90 |
+
###############
|
91 |
+
# io.tokenize #
|
92 |
+
###############
|
93 |
+
|
94 |
+
|
95 |
+
def test_getTerms():
|
96 |
+
|
97 |
+
assert getTerms("1 + 2 * 3 - sqrt(2) / 5") == ['1', '+', '2', '*', '3', '-', 'sqrt', '(', '2', ')', '/', '5']
|
98 |
+
assert getTerms("x + x^2*y + y^2 + y/z = -z") == ['x', '+', 'x', '^', '2', '*', 'y', '+', 'y', '^', '2', '+', 'y', '/', 'z', '=', '-', 'z']
|
99 |
+
|
100 |
+
assert getTerms("sin^2(x) + cos^2(x) = 1") == ['sin', '^', '2', '(', 'x', ')', '+', 'cos', '^', '2', '(', 'x', ')', '=', '1']
|
101 |
+
assert getTerms("1 + tan^2(x) = sec^2(x)") == ['1', '+', 'tan', '^', '2', '(', 'x', ')', '=', 'sec', '^', '2', '(', 'x', ')']
|
102 |
+
assert getTerms("1 + cot^2(x) = csc^2(x)") == ['1', '+', 'cot', '^', '2', '(', 'x', ')', '=', 'csc', '^', '2', '(', 'x', ')']
|
103 |
+
|
104 |
+
assert getTerms("cosh^2(x)-sinh^2(x)=1") == ['cosh', '^', '2', '(', 'x', ')', '-', 'sinh', '^', '2', '(', 'x', ')', '=', '1']
|
105 |
+
assert getTerms("1 - tanh^2(x) = sech^2(x)") == ['1', '-', 'tanh', '^', '2', '(', 'x', ')', '=', 'sech', '^', '2', '(', 'x', ')']
|
106 |
+
assert getTerms("coth^2(x)-csch^2(x)=1") == ['coth', '^', '2', '(', 'x', ')', '-', 'csch', '^', '2', '(', 'x', ')', '=', '1']
|
107 |
+
|
108 |
+
assert getTerms("e = 2.71828") == ['exp', '=', '2.71828']
|
109 |
+
assert getTerms("log_10(100) = 2") == ['log_', '10', '(', '100', ')', '=', '2']
|
110 |
+
assert getTerms("ln(e) = 1") == ['ln', '(', 'exp', ')', '=', '1']
|
111 |
+
assert getTerms("e^(i*pi)=1") == ['exp', '^', '(', 'iota', '*', 'pi', ')', '=', '1']
|
112 |
+
|
113 |
+
assert getTerms("a = b") == ['a', '=', 'b']
|
114 |
+
assert getTerms("a < b") == ['a', '<', 'b']
|
115 |
+
assert getTerms("a > b") == ['a', '>', 'b']
|
116 |
+
assert getTerms("a <= b") == ['a', '<=', 'b']
|
117 |
+
assert getTerms("a >= b") == ['a', '>=', 'b']
|
118 |
+
|
119 |
+
assert getTerms("[1,0;0,1]") == ['[', '1', ',', '0', ';', '0', ',', '1', ']']
|
120 |
+
assert getTerms("2*[2,3;2,3]+[1,2;1,2]") == ['2', '*', '[', '2', ',', '3', ';', '2', ',', '3', ']', '+', '[', '1', ',', '2', ';', '1', ',', '2', ']']
|
121 |
+
|
122 |
+
assert getTerms(r"$\frac {3}{x}-\frac{x}{y}$") == ['$', 'frac', '{', '3', '}', '{', 'x', '}', '-', 'frac', '{', 'x', '}', '{', 'y', '}', '$']
|
123 |
+
|
124 |
+
|
125 |
+
def test_normalize():
|
126 |
+
|
127 |
+
assert normalize(['$', 'frac', '{', '3', '}', '{', 'x', '}', '-', 'frac', '{', 'x', '}', '{', 'y', '}', '$']) == ['$', '3', '/', 'x', '-', 'x', '/', 'y', '$']
|
data/tests/test_matrix.py
ADDED
@@ -0,0 +1,409 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from visma.matrix.checks import isMatrix, dimCheck, multiplyCheck, isEqual
|
2 |
+
from visma.matrix.operations import simplifyMatrix, addMatrix, subMatrix, scalarAdd, scalarSub, scalarMult, scalarDiv, gauss_elim, row_echelon
|
3 |
+
from visma.matrix.structure import DiagMat, IdenMat
|
4 |
+
from visma.functions.constant import Constant
|
5 |
+
from tests.tester import getTokens
|
6 |
+
from visma.io.parser import tokensToString
|
7 |
+
|
8 |
+
|
9 |
+
####################
|
10 |
+
# matrix.structure #
|
11 |
+
####################
|
12 |
+
|
13 |
+
|
14 |
+
def test_strMatrix():
|
15 |
+
|
16 |
+
mat = getTokens("[1+x, 2; \
|
17 |
+
3 , 4]")
|
18 |
+
assert mat.__str__() == "[{1.0}+{x},{2.0};{3.0},{4.0}]"
|
19 |
+
|
20 |
+
|
21 |
+
def test_traceMat():
|
22 |
+
|
23 |
+
mat = getTokens("[1, 2, 3; \
|
24 |
+
3, 4, 7; \
|
25 |
+
4, 6, 9]")
|
26 |
+
mat.isSquare()
|
27 |
+
trace = mat.traceMat()
|
28 |
+
assert tokensToString(trace) == "14.0"
|
29 |
+
|
30 |
+
mat = getTokens("[7, 5; \
|
31 |
+
2, 0]")
|
32 |
+
mat.isSquare()
|
33 |
+
trace = mat.traceMat()
|
34 |
+
assert tokensToString(trace) == "7.0"
|
35 |
+
|
36 |
+
|
37 |
+
def test_isSquare():
|
38 |
+
|
39 |
+
mat = getTokens("[1, 0, 3; \
|
40 |
+
2, 1, 2]")
|
41 |
+
assert not mat.isSquare()
|
42 |
+
|
43 |
+
mat = getTokens("[1, 2; \
|
44 |
+
x, z]")
|
45 |
+
assert mat.isSquare()
|
46 |
+
|
47 |
+
mat = getTokens("[1, 2; \
|
48 |
+
1, 3; \
|
49 |
+
1, 4]")
|
50 |
+
assert not mat.isSquare()
|
51 |
+
|
52 |
+
|
53 |
+
def test_transposeMat():
|
54 |
+
mat = getTokens("[1, 3; \
|
55 |
+
2, 6]")
|
56 |
+
matTranspose = mat.transposeMat()
|
57 |
+
assert matTranspose.__str__() == "[{1.0},{2.0};{3.0},{6.0}]"
|
58 |
+
|
59 |
+
mat = getTokens("[5,8,2;\
|
60 |
+
12,30,9;\
|
61 |
+
4,17,7]")
|
62 |
+
matTranspose = mat.transposeMat()
|
63 |
+
assert matTranspose.__str__() == "[{5.0},{12.0},{4.0};{8.0},{30.0},{17.0};{2.0},{9.0},{7.0}]"
|
64 |
+
|
65 |
+
mat = getTokens("[5,8,2;\
|
66 |
+
2,3,4]")
|
67 |
+
matTranspose = mat.transposeMat()
|
68 |
+
assert matTranspose.__str__() == "[{5.0},{2.0};{8.0},{3.0};{2.0},{4.0}]"
|
69 |
+
|
70 |
+
mat = getTokens("[1, 2; \
|
71 |
+
3, 4]")
|
72 |
+
matTranspose = mat.transposeMat()
|
73 |
+
assert matTranspose.__str__() == "[{1.0},{3.0};{2.0},{4.0}]"
|
74 |
+
|
75 |
+
|
76 |
+
def test_isDiagonal():
|
77 |
+
|
78 |
+
mat = getTokens("[1, 0; \
|
79 |
+
0, z]")
|
80 |
+
assert mat.isDiagonal()
|
81 |
+
|
82 |
+
mat = getTokens("[1+x, 0+y; \
|
83 |
+
0, z]")
|
84 |
+
assert not mat.isDiagonal()
|
85 |
+
|
86 |
+
mat = getTokens("[1, 2; \
|
87 |
+
1, 3; \
|
88 |
+
1, 4]")
|
89 |
+
assert not mat.isDiagonal()
|
90 |
+
|
91 |
+
mat = DiagMat([3, 3], [[Constant(1)], [Constant(5)], [Constant(2)]])
|
92 |
+
assert mat.isDiagonal()
|
93 |
+
|
94 |
+
mat = IdenMat([2, 2])
|
95 |
+
assert mat.isDiagonal()
|
96 |
+
|
97 |
+
|
98 |
+
def test_isIdentity():
|
99 |
+
|
100 |
+
mat = getTokens("[1, 0; \
|
101 |
+
0, 1]")
|
102 |
+
assert mat.isIdentity()
|
103 |
+
|
104 |
+
mat = getTokens("[1+x, 0+y; \
|
105 |
+
0, 1]")
|
106 |
+
assert not mat.isIdentity()
|
107 |
+
|
108 |
+
mat = getTokens("[1, 2; \
|
109 |
+
1, 3; \
|
110 |
+
1, 4]")
|
111 |
+
assert not mat.isIdentity()
|
112 |
+
|
113 |
+
|
114 |
+
#################
|
115 |
+
# matrix.checks #
|
116 |
+
#################
|
117 |
+
|
118 |
+
|
119 |
+
def test_isMatrix():
|
120 |
+
|
121 |
+
mat = getTokens("[1, 2, 3; \
|
122 |
+
x, z, 3]")
|
123 |
+
assert isMatrix(mat)
|
124 |
+
|
125 |
+
mat = getTokens("[1, 2; \
|
126 |
+
1, 3; \
|
127 |
+
1]")
|
128 |
+
assert mat == [] # not a matrix; returns empty matrix
|
129 |
+
|
130 |
+
|
131 |
+
def test_dimCheck():
|
132 |
+
|
133 |
+
matA = getTokens("[2, x; \
|
134 |
+
3, y]")
|
135 |
+
matB = getTokens("[1, 2, x; \
|
136 |
+
2, 3, y]")
|
137 |
+
assert not dimCheck(matA, matB)
|
138 |
+
|
139 |
+
matA = getTokens("[2, x; \
|
140 |
+
3, y]")
|
141 |
+
matB = getTokens("[1, 2; \
|
142 |
+
2, 3]")
|
143 |
+
assert dimCheck(matA, matB)
|
144 |
+
|
145 |
+
|
146 |
+
def test_multiplyCheck():
|
147 |
+
|
148 |
+
matA = getTokens("[2, x; \
|
149 |
+
3, y; \
|
150 |
+
3, y]")
|
151 |
+
matB = getTokens("[2, x; \
|
152 |
+
3, y]")
|
153 |
+
assert multiplyCheck(matA, matB)
|
154 |
+
|
155 |
+
matA = getTokens("[2, x, 1; \
|
156 |
+
3, y, z]")
|
157 |
+
matB = getTokens("[1, 2; 2, 3]")
|
158 |
+
assert not multiplyCheck(matA, matB)
|
159 |
+
|
160 |
+
|
161 |
+
def test_isEqual():
|
162 |
+
|
163 |
+
matA = getTokens("[1, 2; \
|
164 |
+
x, z]")
|
165 |
+
matB = getTokens("[1, 2; \
|
166 |
+
x, z]")
|
167 |
+
|
168 |
+
assert isEqual(matA, matB)
|
169 |
+
|
170 |
+
matA = getTokens("[2, x, 1; \
|
171 |
+
3, y, z]")
|
172 |
+
matB = getTokens("[1, 2; 2, 3]")
|
173 |
+
assert not isEqual(matA, matB)
|
174 |
+
|
175 |
+
|
176 |
+
#####################
|
177 |
+
# matrix.operations #
|
178 |
+
#####################
|
179 |
+
|
180 |
+
|
181 |
+
def test_simplifyMatrix():
|
182 |
+
|
183 |
+
mat = getTokens("[x + y + x, x^2 + x^2; \
|
184 |
+
1 + 4/2 , z^3/z^2 ]")
|
185 |
+
matRes = simplifyMatrix(mat)
|
186 |
+
assert matRes.__str__() == "[2{x}+{y},2{x}^{2.0};{3.0},{z}]"
|
187 |
+
|
188 |
+
mat = getTokens("[1 + x^2 + 2]")
|
189 |
+
matRes = simplifyMatrix(mat)
|
190 |
+
assert matRes.__str__() == "[{3.0}+{x}^{2.0}]"
|
191 |
+
|
192 |
+
|
193 |
+
def test_addMatrix():
|
194 |
+
|
195 |
+
matA = getTokens("[2x + y, 2x]")
|
196 |
+
matB = getTokens("[-x, -x]")
|
197 |
+
matSum = addMatrix(matA, matB)
|
198 |
+
# assert matSum.__str__() == "[2{x}+{y}]" # BUG: Strange simplification for matSum
|
199 |
+
|
200 |
+
matA = getTokens("[ x , x^2; \
|
201 |
+
3 + x^2, xy ]")
|
202 |
+
matB = getTokens("[ y + 1 , x^2; \
|
203 |
+
2 - x^2, xy - 1 ]")
|
204 |
+
matSum = addMatrix(matA, matB)
|
205 |
+
assert matSum.__str__() == "[{x}+{y}+{1.0},2{x}^{2.0};{5.0},2{x}{y}-{1.0}]"
|
206 |
+
|
207 |
+
|
208 |
+
def test_subMatrix():
|
209 |
+
|
210 |
+
matA = getTokens("[y, 2x]")
|
211 |
+
matB = getTokens("[-x, -x]")
|
212 |
+
matSub = subMatrix(matA, matB)
|
213 |
+
assert matSub.__str__() == "[{y}--1.0{x},3.0{x}]"
|
214 |
+
|
215 |
+
|
216 |
+
def test_scalarAddMatrix():
|
217 |
+
|
218 |
+
mat = getTokens("[1, 2; \
|
219 |
+
2, 1]")
|
220 |
+
const = 2
|
221 |
+
matSum = scalarAdd(const, mat)
|
222 |
+
assert matSum.__str__() == "[{3.0},{2.0};{2.0},{3.0}]"
|
223 |
+
|
224 |
+
mat = getTokens("[1, 2, 3;\
|
225 |
+
4, 5, 6;\
|
226 |
+
7, 8, 9]")
|
227 |
+
const = 3
|
228 |
+
matSum = scalarAdd(const, mat)
|
229 |
+
assert matSum.__str__() == "[{4.0},{2.0},{3.0};{4.0},{8.0},{6.0};{7.0},{8.0},{12.0}]"
|
230 |
+
|
231 |
+
|
232 |
+
def test_scalarSubMatrix():
|
233 |
+
|
234 |
+
mat = getTokens("[8,6;\
|
235 |
+
1,9]")
|
236 |
+
const = 2
|
237 |
+
matSub = scalarSub(const, mat)
|
238 |
+
assert matSub.__str__() == "[{6.0},{6.0};{1.0},{7.0}]"
|
239 |
+
|
240 |
+
mat = getTokens("[5,8,2;\
|
241 |
+
12,30,9;\
|
242 |
+
4,17,7]")
|
243 |
+
const = 10
|
244 |
+
matSub = scalarSub(const, mat)
|
245 |
+
assert matSub.__str__() == "[{-5.0},{8.0},{2.0};{12.0},{20.0},{9.0};{4.0},{17.0},{-3.0}]"
|
246 |
+
|
247 |
+
|
248 |
+
def test_scalarMultMatrix():
|
249 |
+
|
250 |
+
mat = getTokens("[1, 2]")
|
251 |
+
const = 2
|
252 |
+
matSum = scalarMult(const, mat)
|
253 |
+
assert matSum.__str__() == "[{2.0},{4.0}]"
|
254 |
+
|
255 |
+
mat = getTokens("[2,4;\
|
256 |
+
-5,7]")
|
257 |
+
const = 2
|
258 |
+
matSum = scalarMult(const, mat)
|
259 |
+
assert matSum.__str__() == "[{4.0},{8.0};{-10.0},{14.0}]"
|
260 |
+
|
261 |
+
|
262 |
+
def test_scalarDivMatrix():
|
263 |
+
|
264 |
+
mat = getTokens("[4, 2]")
|
265 |
+
const = 2
|
266 |
+
matSum = scalarDiv(const, mat)
|
267 |
+
assert matSum.__str__() == "[{2.0},{1.0}]"
|
268 |
+
|
269 |
+
mat = getTokens("[48,36;\
|
270 |
+
24,-3]")
|
271 |
+
const = 6
|
272 |
+
matSum = scalarDiv(const, mat)
|
273 |
+
assert matSum.__str__() == "[{8.0},{6.0};{4.0},{-0.5}]"
|
274 |
+
|
275 |
+
|
276 |
+
def test_multiplyMatrix():
|
277 |
+
"""
|
278 |
+
# FIXME: Fixing addition fixes multiplication
|
279 |
+
matA = getTokens("[1, 0; 0, 1]")
|
280 |
+
matB = getTokens("[2; 3]")
|
281 |
+
matPro = multiplyMatrix(matA, matB)
|
282 |
+
# assert matPro.__str__() == ""
|
283 |
+
|
284 |
+
matA = getTokens("[1, 2; x, 2; 3, y]")
|
285 |
+
matB = getTokens("[2, x; 3, y]")
|
286 |
+
matPro = multiplyMatrix(matA, matB)
|
287 |
+
# assert matPro.__str__() == ""
|
288 |
+
|
289 |
+
matA = getTokens("[2, x, 1; \
|
290 |
+
3, y, z]")
|
291 |
+
matB = getTokens("[1, 2; 2, 3; 5, 6]")
|
292 |
+
matPro = multiplyMatrix(matA, matB)
|
293 |
+
# assert matPro.__str__() == ""
|
294 |
+
"""
|
295 |
+
pass
|
296 |
+
|
297 |
+
|
298 |
+
def test_determinant():
|
299 |
+
mat = getTokens('[1,2;3,4]')
|
300 |
+
if mat.isSquare():
|
301 |
+
a = ''
|
302 |
+
for i in mat.determinant():
|
303 |
+
a += i.__str__()
|
304 |
+
assert a == "{-2.0}"
|
305 |
+
mat = getTokens('[1,2,3;4,5,6;7,8,9]')
|
306 |
+
if mat.isSquare():
|
307 |
+
a = ''
|
308 |
+
for i in mat.determinant():
|
309 |
+
a += i.__str__()
|
310 |
+
assert a == "{0}"
|
311 |
+
mat = getTokens('[1]')
|
312 |
+
if mat.isSquare():
|
313 |
+
a = ''
|
314 |
+
for i in mat.determinant():
|
315 |
+
a += i.__str__()
|
316 |
+
assert a == "{1.0}"
|
317 |
+
|
318 |
+
|
319 |
+
def test_inverse():
|
320 |
+
mat = getTokens("[5, 7, 9;\
|
321 |
+
4, 3, 8;\
|
322 |
+
7, 5, 6]")
|
323 |
+
if mat.isSquare():
|
324 |
+
assert mat.inverse().__str__() == "[{-0.20977011494252873},{0.028735632183908046},{0.27586206896551724};{0.3023255813953489},{-0.3139534883720931},{-0.03779069767441861};{-0.009111617312072894},{0.22779043280182235},{-0.12300683371298407}]"
|
325 |
+
|
326 |
+
mat = getTokens("[4, 5;\
|
327 |
+
7, 3]")
|
328 |
+
if mat.isSquare():
|
329 |
+
assert mat.inverse().__str__() == "[{-0.1301859799713877},{0.21745350500715305};{0.303951367781155},{-0.17325227963525833}]"
|
330 |
+
|
331 |
+
mat = getTokens("[4, 5, 6, 8;\
|
332 |
+
3, 25, 4, 6;\
|
333 |
+
5, 1, 8, 4;\
|
334 |
+
1, 3, 5, 8]")
|
335 |
+
if mat.isSquare():
|
336 |
+
assert mat.inverse().__str__() == "[{0.49400000000000005},{-0.044000000000000004},{-0.08600000000000001},{-0.42400000000000004};{-0.057142857142857134},{0.049999999999999996},{0.014285714285714284},{0.0047619047619047615};{-0.40131578947368424},{0.03947368421052632},{0.25},{0.2565789473684211};{0.21321177223288548},{-0.03854766474728087},{-0.15067178502879078},{0.01599488163787588}]"
|
337 |
+
|
338 |
+
mat = getTokens("[1,1;1,1]")
|
339 |
+
if mat.isSquare():
|
340 |
+
assert mat.inverse().__str__() == "-1"
|
341 |
+
|
342 |
+
|
343 |
+
def test_cofactor():
|
344 |
+
mat = getTokens('[1,2;3,4]')
|
345 |
+
if mat.isSquare():
|
346 |
+
assert str(mat.cofactor()) == '[{4.0},{-3.0};{-2.0},{1.0}]'
|
347 |
+
mat = getTokens('[1,2,3;0,4,5;1,0,6]')
|
348 |
+
if mat.isSquare():
|
349 |
+
assert str(mat.cofactor()) == '[{24.0},{5.0},{-4.0};{-12.0},{3.0},{2.0};{-2.0},{-5.0},{4.0}]'
|
350 |
+
mat = getTokens('[1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16]')
|
351 |
+
if mat.isSquare():
|
352 |
+
assert str(mat.cofactor()) == '[{0},{0},{0},{0};{0},{0},{0},{0};{0},{0},{0},{0};{0},{0},{0},{0}]'
|
353 |
+
|
354 |
+
|
355 |
+
def test_echelon():
|
356 |
+
mat = getTokens("[1, 4, 2;\
|
357 |
+
5, 7, 6;\
|
358 |
+
2, 4, 9]")
|
359 |
+
assert row_echelon(mat).__str__() == "[{1.0},{4.0},{2.0};{0.0},{-13.0},{-4.0};{0.0},{0.0},{6.24}]"
|
360 |
+
|
361 |
+
mat = getTokens("[1, 2, 3, 1;\
|
362 |
+
4, 5, 6, 1;\
|
363 |
+
7, 8, 9, 2]")
|
364 |
+
assert row_echelon(mat).__str__() == "[{1.0},{2.0},{3.0},{1.0};{0.0},{-3.0},{-6.0},{-3.0};{0.0},{0.0},{0.0},{1.0}]"
|
365 |
+
|
366 |
+
mat = getTokens("[1, 2, 3, 1;\
|
367 |
+
4, 5, 6, 1;\
|
368 |
+
7, 8, 9, 1;\
|
369 |
+
2, 3 ,1 ,4]")
|
370 |
+
assert row_echelon(mat).__str__() == "[{1.0},{2.0},{3.0},{1.0};{0.0},{-3.0},{-6.0},{-3.0};{0.0},{0.0},{-3.02},{2.99};{0.0},{0.0},{0.0},{0.0}]"
|
371 |
+
|
372 |
+
mat = getTokens("[6,2,8,26;\
|
373 |
+
3,5,2,8;\
|
374 |
+
0,8,2,-7]")
|
375 |
+
assert row_echelon(mat).__str__() == "[{6.0},{2.0},{8.0},{26.0};{0.0},{4.0},{-2.0},{-5.0};{0.0},{0.0},{6.0},{3.0}]"
|
376 |
+
|
377 |
+
|
378 |
+
def test_multi_variable_solve():
|
379 |
+
mat = getTokens("[1, 2, 3, 1;\
|
380 |
+
4, 5, 6, 1;\
|
381 |
+
7, 8, 2, 2]")
|
382 |
+
assert gauss_elim(mat).__str__() == "[{-1.14};{1.2799999999999998};{-0.14285714285714285}]"
|
383 |
+
|
384 |
+
mat = getTokens("[6,2,8,26;\
|
385 |
+
3,5,2,8;\
|
386 |
+
0,8,2,-7]")
|
387 |
+
assert gauss_elim(mat).__str__() == "[{4.0};{-1.0};{0.5}]"
|
388 |
+
|
389 |
+
#######################
|
390 |
+
# Operator Overloading
|
391 |
+
#######################
|
392 |
+
|
393 |
+
|
394 |
+
def test_addoverload():
|
395 |
+
|
396 |
+
matA = getTokens("[ x , x^2; \
|
397 |
+
3 + x^2, xy ]")
|
398 |
+
matB = getTokens("[ y + 1 , x^2; \
|
399 |
+
2 - x^2, xy - 1 ]")
|
400 |
+
matSum = matA + matB
|
401 |
+
assert matSum.__str__() == "[{x}+{y}+{1.0},2{x}^{2.0};{5.0},2{x}{y}-{1.0}]"
|
402 |
+
|
403 |
+
|
404 |
+
def test_suboverload():
|
405 |
+
|
406 |
+
matA = getTokens("[y, 2x]")
|
407 |
+
matB = getTokens("[-x, -x]")
|
408 |
+
matSub = matA - matB
|
409 |
+
assert matSub.__str__() == "[{y}--1.0{x},3.0{x}]"
|
data/tests/test_simplify.py
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from visma.simplify.simplify import simplify, simplifyEquation
|
2 |
+
from visma.simplify.addsub import addition, additionEquation, subtraction, subtractionEquation
|
3 |
+
from visma.simplify.muldiv import multiplication, division
|
4 |
+
from tests.tester import quickTest
|
5 |
+
|
6 |
+
#####################
|
7 |
+
# simplify.simplify #
|
8 |
+
#####################
|
9 |
+
|
10 |
+
|
11 |
+
def test_simplify():
|
12 |
+
|
13 |
+
assert quickTest("1 + 2 - 3", simplify) == "0"
|
14 |
+
assert quickTest("1 + 2 - 4", simplify) == "-1.0"
|
15 |
+
assert quickTest("0 + 0 + 1", simplify) == "1.0"
|
16 |
+
assert quickTest("0 + 0 + xyz", simplify) == "xyz"
|
17 |
+
|
18 |
+
assert quickTest("(2 + 3) * (4 + 5) * (6 + 7)", simplify) == "585.0"
|
19 |
+
assert quickTest("3 * (3 * (3 * ( 3 * 3)))", simplify) == "243.0"
|
20 |
+
assert quickTest("3 + (3 + (3 * 1))", simplify) == "9.0"
|
21 |
+
assert quickTest("3 - (1 - 3 - (1 + 2))", simplify) == "8.0"
|
22 |
+
|
23 |
+
assert quickTest("3*2 + 4*2 - 3*4", simplify) == "2.0"
|
24 |
+
assert quickTest("3*x + 4*x - 2*y", simplify) == "7.0x-2.0y"
|
25 |
+
assert quickTest("x*y + x*x + x*x^2 + x^2*x + x*y^2 + x^2*y", simplify) == "xy+x^(2)+2x^(3.0)+xy^(2.0)+x^(2.0)y"
|
26 |
+
|
27 |
+
assert quickTest("3/2 + 4/2 - 2/4", simplify) == "3.0"
|
28 |
+
assert quickTest("x/5 + x/4 - 2/y", simplify) == "0.45x-2.0y^(-1)"
|
29 |
+
assert quickTest("x/y + x/x + x/x^2 + x^2/x + x/y^2 + x^2/y + x + 1", simplify) == "xy^(-1)+x^(-1.0)+xy^(-2.0)+x^(2.0)y^(-1)+2.0x+2.0"
|
30 |
+
|
31 |
+
assert quickTest("1 + 2 = 3", simplifyEquation) == "=0" # FIXME: Vanishing zero
|
32 |
+
assert quickTest("1 + 2 = 4", simplifyEquation) == "-1.0=0"
|
33 |
+
|
34 |
+
assert quickTest("3*2 + 4*2 = 3*4", simplifyEquation) == "2.0=0"
|
35 |
+
assert quickTest("3*x = 4*x + 2*y", simplifyEquation) == "-x-2.0y=0"
|
36 |
+
assert quickTest("1 - 1 = 3*x + 4*x + 2*y", simplifyEquation) == "7.0x+2.0y=0"
|
37 |
+
|
38 |
+
assert quickTest("x = y --1 --x^2", simplifyEquation) == "x-y-1.0-x^(2.0)=0" # FIXME: Valid but silly input case
|
39 |
+
|
40 |
+
assert quickTest("4 = 3x - 4x - 1 + 2", simplifyEquation) == "3.0+x=0"
|
41 |
+
assert quickTest("z = x^2 - x + 1 - 2", simplifyEquation) == "z-x^(2.0)+x+1.0=0"
|
42 |
+
assert quickTest("x = -1 + 2", simplifyEquation) == "x+1.0-2.0=0" # FIXME: Further simplification required (simplification in RHS)
|
43 |
+
assert quickTest("x*y + x*x + x*x^2 = x^2*x + x*y^2 + x^2*y", simplifyEquation) == "xy+x^(2)-xy^(2.0)-x^(2.0)y=0"
|
44 |
+
|
45 |
+
assert quickTest("3/2 + 4/2 = 2/4", simplifyEquation) == "3.0=0"
|
46 |
+
assert quickTest("x/5 + x/4 = 2/y", simplifyEquation) == "0.45x-2.0y^(-1)=0"
|
47 |
+
assert quickTest("x/y + x/x + x/x^2 + x^2/x = x/y^2 + x^2/y + x - 1", simplifyEquation) == "xy^(-1)+2.0+x^(-1.0)-xy^(-2.0)-x^(2.0)y^(-1)=0"
|
48 |
+
|
49 |
+
# Tests regarding Expression used in equations
|
50 |
+
assert quickTest("(1 + 2) = ( 3 + 44)", simplifyEquation) == "-44.0=0"
|
51 |
+
assert quickTest("x = -1 * (z + 10)", simplifyEquation) == "x+z+10.0=0"
|
52 |
+
assert quickTest("x = 2*(z + q)", simplifyEquation) == "x-2.0z-2.0q=0"
|
53 |
+
|
54 |
+
# Tests regarding Expression Simplifications
|
55 |
+
assert quickTest("(x + 1) * (x + 1) * (x + 1)", simplify) == "x^(3.0)+3x^(2.0)+3x+1.0"
|
56 |
+
assert quickTest("(x + 1) * (x - 1) + (x + 2)", simplify) == "x^(2.0)+1.0+x"
|
57 |
+
assert quickTest("(x + 1) + (x - 1)", simplify) == "2x"
|
58 |
+
assert quickTest("(x + 1) * (x * (1 + x))", simplify) == "2x^(2.0)+x^(3.0)+x"
|
59 |
+
assert quickTest("(x + 1) * (x - 1) + (100 + 1)", simplify) == "x^(2.0)+100.0"
|
60 |
+
assert quickTest("((x + 1) * (x - 1) + (100 + 1))", simplify) == "x^(2.0)+100.0"
|
61 |
+
# assert quickTest("-1 * (- x - 1)", simplify) == "x--1" FIXME: case should have a probably fix with the overlaoding of Constant Function
|
62 |
+
|
63 |
+
# Tests regarding Exponents & Expressions
|
64 |
+
assert quickTest("(x + 1)^3", simplify) == "x^(3.0)+3x^(2.0)+3x+1.0"
|
65 |
+
assert quickTest("(x + 1)^2*x", simplify) == "x^(3.0)+2x^(2.0)+x"
|
66 |
+
assert quickTest("x*(x + 1)^2*x", simplify) == "x^(4.0)+2x^(3.0)+x^(2.0)"
|
67 |
+
assert quickTest("(x+1)^2*(x + 2)^3*x", simplify) == "x^(6.0)+8.0x^(5.0)+25.0x^(4.0)+38.0x^(3.0)+28.0x^(2.0)+8.0x"
|
68 |
+
assert quickTest("(x + 1)^(1 + 1)*x", simplify) == "x^(3.0)+2x^(2.0)+x"
|
69 |
+
assert quickTest("(x + 1)^(3 + 0 + 0)", simplify) == "x^(3.0)+3x^(2.0)+3x+1.0"
|
70 |
+
|
71 |
+
assert quickTest("3^(1 + 1)", simplify) == "9.0"
|
72 |
+
assert quickTest("2^(3/2) + 12", simplify) == "2.0^1.5+12.0"
|
73 |
+
assert quickTest("2^(4/2) + 12", simplify) == "16.0"
|
74 |
+
assert quickTest("(1 + 2)^(1 + 1)", simplify) == "9.0"
|
75 |
+
assert quickTest("(1 + 3)^(x) + (2 + 3)^(x)", simplify) == "4.0^x+5.0^x"
|
76 |
+
assert quickTest("(1 + 3)^(1/3) + (2 + 3)^(2/3)", simplify) == "4.0^0.33+5.0^0.67"
|
77 |
+
|
78 |
+
|
79 |
+
def test_addsub():
|
80 |
+
|
81 |
+
assert quickTest("1 + 2", addition) == "3.0"
|
82 |
+
assert quickTest("x + 2x", addition) == "3.0x"
|
83 |
+
assert quickTest("xy^2 + 2xy^2", addition) == "3.0xy^(2.0)"
|
84 |
+
assert quickTest("-1 + 2", addition) == "1.0"
|
85 |
+
assert quickTest("-x + 2x", addition) == "x"
|
86 |
+
assert quickTest("-xy^2 + 3xy^2", addition) == "2.0xy^(2.0)"
|
87 |
+
assert quickTest("1 + 0", addition) == "1.0"
|
88 |
+
assert quickTest("1 + 2 + 3", addition) == "6.0"
|
89 |
+
assert quickTest("1 + 2 + x + 3x", addition) == "3.0+4.0x"
|
90 |
+
|
91 |
+
assert quickTest("1 + 2 = x + 3x", additionEquation) == "3.0=4.0x"
|
92 |
+
assert quickTest("y + 2 = -x + x", additionEquation) == "y+2.0=0"
|
93 |
+
|
94 |
+
assert quickTest("1 - 2", subtraction) == "-1.0"
|
95 |
+
assert quickTest("x - 2x", subtraction) == "-x"
|
96 |
+
assert quickTest("xy^2 - 3xy^2", subtraction) == "-2.0xy^(2.0)"
|
97 |
+
|
98 |
+
assert quickTest("1 - 2 = x - 3x", subtractionEquation) == "-1.0=-2.0x"
|
99 |
+
assert quickTest("y + 2 = -x - x", subtractionEquation) == "y+2.0=-2.0x"
|
100 |
+
|
101 |
+
|
102 |
+
def test_muldiv():
|
103 |
+
|
104 |
+
assert quickTest("3*y + x*2", multiplication) == "3.0y+2.0x"
|
105 |
+
assert quickTest("x^3 * x^2", multiplication) == "x^(5.0)"
|
106 |
+
assert quickTest("x^(-1)y^2 * zx^2", multiplication) == "xy^(2.0)z"
|
107 |
+
|
108 |
+
assert quickTest("x^2 / x^2", division) == "1.0"
|
109 |
+
assert quickTest("x^2 / x^4", division) == "x^(-2.0)"
|
110 |
+
assert quickTest("x^(-1)y^2 / zx^2", division) == "x^(-3.0)y^(2.0)z^(-1)"
|
data/tests/test_solvers.py
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from visma.solvers.polynomial.roots import rootFinder
|
2 |
+
from visma.solvers.simulEqn import simulSolver
|
3 |
+
from visma.solvers.solve import solveFor
|
4 |
+
from tests.tester import quickTest
|
5 |
+
|
6 |
+
############################
|
7 |
+
# solvers.polynomial.roots #
|
8 |
+
############################
|
9 |
+
|
10 |
+
|
11 |
+
def test_rootFinder():
|
12 |
+
|
13 |
+
# Tests for Quadratic (2nd Degree) Equations
|
14 |
+
assert quickTest("x^2 + 2x + 1 = 0", rootFinder) == "(x+1.0)^(2)=0"
|
15 |
+
assert quickTest("x^2 + 2x = - 1", rootFinder) == "(x+1.0)^(2)=0"
|
16 |
+
assert quickTest("x^2 = - 2x - 1", rootFinder) == "(x+1.0)^(2)=0"
|
17 |
+
assert quickTest("0 = x^2 + 2x + 1", rootFinder) == "(x+1.0)^(2)=0"
|
18 |
+
|
19 |
+
assert quickTest("x^2 + 1 - 2x = 0", rootFinder) == "(x-1.0)^(2)=0"
|
20 |
+
assert quickTest("x^2 + 1 = 2x", rootFinder) == "(x-1.0)^(2)=0"
|
21 |
+
assert quickTest("x^2 = 2x - 1", rootFinder) == "(x-1.0)^(2)=0"
|
22 |
+
assert quickTest("-2x = - x^2 - 1", rootFinder) == "(x-1.0)^(2)=0"
|
23 |
+
# FIXME: assert quickTest("0 = 2x - x^2 - 1", rootFinder) == "(x-1.0)^(2)=0"
|
24 |
+
# assert quickTest("0 = 2x - x^2 - 1", rootFinder) == "(x-1.0)^(2)=0"
|
25 |
+
|
26 |
+
assert quickTest("2x^2 - 4x - 6 = 0", rootFinder) == "(x+1.0)*(x-3.0)=0"
|
27 |
+
assert quickTest("3x^2 + 7x + 1 = 0", rootFinder) == "(x+2.18)*(x+0.15)=0"
|
28 |
+
assert quickTest("3x^2 - 7x + 1 = 0", rootFinder) == "(x-0.15)*(x-2.18)=0"
|
29 |
+
|
30 |
+
assert quickTest("x^2 + x + 1 = 0", rootFinder) == "(x+0.5+0.87*sqrt[2](-1))*(x+0.5-0.87*sqrt[2](-1))=0"
|
31 |
+
assert quickTest("x^2 - x + 1 = 0", rootFinder) == "(x-0.5+0.87*sqrt[2](-1))*(x-0.5-0.87*sqrt[2](-1))=0"
|
32 |
+
|
33 |
+
# Tests for Cubic (3rd Degree) Equations
|
34 |
+
assert quickTest("2x^3 - 4x^2 - 22x + 24 = 0", rootFinder) == "(x-4.0)*(x+3.0)*(x-1.0)=0"
|
35 |
+
assert quickTest("x^3 + 6x^2 + 12x + 8 = 0", rootFinder) == "(x+2.0)^(3)=0"
|
36 |
+
assert quickTest("x^3 = 1", rootFinder) == "(x-1.0)*(x-(-0.5+0.87*sqrt[2](-1)))*(x-(-0.5-0.87*sqrt[2](-1)))=0"
|
37 |
+
|
38 |
+
# Tests for Quartic (4th Degree) Equations
|
39 |
+
assert quickTest("3x^4 + 6x^3 - 123x^2 - 126x + 1080 = 0", rootFinder) == "(x-5.0)*(x+4.0)*(x-3.0)*(x+6.0)=0"
|
40 |
+
assert quickTest("-20x^4 + 5x^3 + 17x^2 - 29x + 87 = 0", rootFinder) == "(x-1.49)*(x-(0.22+1.3*sqrt[2](-1)))*(x-(0.22-1.3*sqrt[2](-1)))*(x+1.69)=0"
|
41 |
+
assert quickTest("2x^4 + 4x^3 + 6x^2 + 8x + 10 = 0", rootFinder) == "(x-(0.28+1.42*sqrt[2](-1)))*(x-(-1.28+0.85*sqrt[2](-1)))*(x-(-1.28-0.85*sqrt[2](-1)))*(x-(0.28-1.42*sqrt[2](-1)))=0"
|
42 |
+
|
43 |
+
###############################
|
44 |
+
# solvers.simulEqn #
|
45 |
+
###############################
|
46 |
+
|
47 |
+
|
48 |
+
def test_simulSolvers():
|
49 |
+
assert quickTest("1000x + 2y + 3z = 4; 5x + 6y + 7z = 8; 9x + 10y + 1100z = 12", simulSolver, 'x') == "x=0.0"
|
50 |
+
assert quickTest("1000x + 2y + 3z = 4; 5x + 6y + 7z = 8; 9x + 10y + 1100z = 12", simulSolver, 'y') == "y=1.33"
|
51 |
+
assert quickTest("1000x + 2y + 3z = 4; 5x + 6y + 7z = 8; 9x + 10y + 1100z = 12", simulSolver, 'z') == "z=-0.0"
|
52 |
+
|
53 |
+
assert quickTest("1000x + 2y + 3z = 4; 5x + 6y + 7z = 8; 9x + 10y + 11z = 12", simulSolver, 'x') == "x=-0.0"
|
54 |
+
assert quickTest("1000x + 2y + 3z = 4; 5x + 6y + 7z = 8; 9x + 10y + 11z = 12", simulSolver, 'y') == "y=-1.0"
|
55 |
+
assert quickTest("1000x + 2y + 3z = 4; 5x + 6y + 7z = 8; 9x + 10y + 11z = 12", simulSolver, 'z') == "z=2.0"
|
56 |
+
|
57 |
+
assert quickTest("1x + 2y + 3z = 4; 5x + 6y + 7z = 8; 9x + 10y + 11z = 12", simulSolver, 'x') == "NoTrivialSolution"
|
58 |
+
assert quickTest("1x + 2y + 3z = 4; 5x + 6y + 7z = 8; 9x + 10y + 11z = 12", simulSolver, 'y') == "NoTrivialSolution"
|
59 |
+
assert quickTest("1x + 2y + 3z = 4; 5x + 6y + 7z = 8; 9x + 10y + 11z = 12", simulSolver, 'z') == "NoTrivialSolution"
|
60 |
+
|
61 |
+
assert quickTest("1000a + 2y + 3w = 4; 5a + 6y + 7w = 8; 9a + 10y + 1100w = 12", simulSolver, 'a') == "a=0.0"
|
62 |
+
assert quickTest("1000a + 2y + 3w = 4; 5a + 6y + 7w = 8; 9a + 10y + 1100w = 12", simulSolver, 'y') == "y=1.33"
|
63 |
+
assert quickTest("1000a + 2y + 3w = 4; 5a + 6y + 7w = 8; 9a + 10y + 1100w = 12", simulSolver, 'w') == "w=-0.0"
|
64 |
+
|
65 |
+
assert quickTest("1000a + 2y + 3w = 4; 5a + 6y + 7w = 8; 10y = 12", simulSolver, 'a') == "a=0.0"
|
66 |
+
assert quickTest("1000a + 2y + 3w = 4; 5a + 6y + 7w = 8; 10y = 12", simulSolver, 'y') == "y=1.2"
|
67 |
+
assert quickTest("1000a + 2y + 3w = 4; 5a + 6y + 7w = 8; 10y = 12", simulSolver, 'w') == "w=0.11"
|
68 |
+
|
69 |
+
# Tests for testing 'solve for all variable' option in case no variable is specified by user.
|
70 |
+
assert quickTest("1000x + 2y + 3z = 4; 5x + 6y + 7z = 8; 9x + 10y + 1100z = 12", simulSolver) == "z=-0.0;y=1.33;x=0.0"
|
71 |
+
assert quickTest("1000x + 2y + 3z = 4; 5x + 6y + 7z = 8; 9x + 10y + 11z = 12", simulSolver) == "z=2.0;y=-1.0;x=-0.0"
|
72 |
+
assert quickTest("1000a + 2y + 3w = 4; 5a + 6y + 7w = 8; 9a + 10y + 1100w = 12", simulSolver) == "y=1.33;w=-0.0;a=0.0"
|
73 |
+
assert quickTest("1000a + 2y + 3w = 4; 5a + 6y + 7w = 8; 10y = 12", simulSolver) == "y=1.2;w=0.11;a=0.0"
|
74 |
+
|
75 |
+
#################
|
76 |
+
# solvers.solve #
|
77 |
+
#################
|
78 |
+
|
79 |
+
|
80 |
+
def test_solveFor():
|
81 |
+
|
82 |
+
assert quickTest("x - 1 + 2 = 0", solveFor, 'x') == "x=(-1.0)"
|
83 |
+
assert quickTest("1 + y^2 = 0", solveFor, 'y') == "y=(-1.0)^(0.5)"
|
84 |
+
assert quickTest("x^2 - 1 = 0", solveFor, 'x') == "x=(1.0)^(0.5)"
|
85 |
+
|
86 |
+
assert quickTest("x - yz + 1= 0", solveFor, 'x') == "x=(-1.0+yz)"
|
87 |
+
assert quickTest("x - 2yz + 1= 0", solveFor, 'y') == "y=-0.5*((-1.0-x)/z)"
|
88 |
+
assert quickTest("x - 5yz + 1= 0", solveFor, 'z') == "z=-0.2*((-1.0-x)/y)"
|
89 |
+
|
90 |
+
assert quickTest("w + x^2 + yz^3 = 1", solveFor, 'w') == "w=(-x^(2.0)-yz^(3.0)+1.0)"
|
91 |
+
assert quickTest("w + x^2 + yz^3 = 1", solveFor, 'x') == "x=(-w-yz^(3.0)+1.0)^(0.5)"
|
92 |
+
assert quickTest("w + x^2 + yz^3 = 1", solveFor, 'y') == "y=((-w-x^(2.0)+1.0)/z^(3.0))"
|
93 |
+
assert quickTest("w + x^2 + yz^3 = 1", solveFor, 'z') == "z=((-w-x^(2.0)+1.0)/y)^(0.3333333333333333)"
|
data/tests/test_transform.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from visma.transform.factorization import factorize
|
2 |
+
from visma.transform.substitution import substitute
|
3 |
+
from visma.io.parser import tokensToString
|
4 |
+
from visma.functions.structure import Expression
|
5 |
+
from tests.tester import quickTest, getTokens
|
6 |
+
|
7 |
+
###########################
|
8 |
+
# transform.factorization #
|
9 |
+
###########################
|
10 |
+
|
11 |
+
|
12 |
+
def test_factorize():
|
13 |
+
assert quickTest("x", factorize) == "x"
|
14 |
+
assert quickTest("x^2 + 2x + 1", factorize) == "(x+1.0)*(x+1.0)"
|
15 |
+
assert quickTest("2x^2 - 4x + 2", factorize) == "2.0*(x-1.0)*(x-1.0)"
|
16 |
+
assert quickTest("x^4 - 1", factorize) == "(x+1.0)*(x-1.0)*(x^(2)+1.0)"
|
17 |
+
assert quickTest("1 - x^3", factorize) == "(x-1.0)*(-x^(2)-x-1.0)"
|
18 |
+
assert quickTest("x^4 - 5x^2 + 4", factorize) == "(x+2.0)*(x+1.0)*(x-1.0)*(x-2.0)"
|
19 |
+
|
20 |
+
|
21 |
+
##########################
|
22 |
+
# transform.substitution #
|
23 |
+
##########################
|
24 |
+
|
25 |
+
|
26 |
+
def test_substitute():
|
27 |
+
|
28 |
+
init_tok = getTokens("x")
|
29 |
+
subs_tok = getTokens("2")
|
30 |
+
tok_list = getTokens("3zx^2 + x^3 + 5x")
|
31 |
+
assert tokensToString(substitute(init_tok, subs_tok, tok_list)) == "12.0z + 8.0 + 10.0"
|
32 |
+
|
33 |
+
init_tok = getTokens("2x")
|
34 |
+
subs_tok = getTokens("4yz^2")
|
35 |
+
tok_list = getTokens("3 + 2x + zx^4 + 3xyz")
|
36 |
+
assert tokensToString(substitute(init_tok, subs_tok, tok_list)) == "3.0 + 4.0yz^(2.0) + 16.0z^(9.0)y^(4.0) + 6.0y^(2.0)z^(3.0)"
|
37 |
+
|
38 |
+
init_tok = getTokens("4x^2")
|
39 |
+
subs_tok = getTokens("9yz")
|
40 |
+
tok_list = getTokens("2x + zx^3 + 3xyz")
|
41 |
+
assert tokensToString(substitute(init_tok, subs_tok, tok_list)) == "3.0y^(0.5)z^(0.5) + 3.375z^(2.5)y^(1.5) + 4.5y^(1.5)z^(1.5)"
|
42 |
+
|
43 |
+
init_tok = getTokens("2xy^3")
|
44 |
+
subs_tok = getTokens("4z")
|
45 |
+
tok_list = getTokens("3 + 2xy^3 + z + 3x^(2)y^(6)z")
|
46 |
+
assert tokensToString(substitute(init_tok, subs_tok, tok_list)) == "3.0 + 4.0z + z + 12.0z^(3.0)"
|
47 |
+
|
48 |
+
init_tok = getTokens("5x")
|
49 |
+
subs_tok = Expression(getTokens("y + 2"))
|
50 |
+
tok_list = getTokens("3 + 4x + 2xy^3 + 3x^(2)y^(3)z")
|
51 |
+
assert tokensToString(substitute(init_tok, subs_tok, tok_list)) == "3.0 + 0.8*(y + 2.0) + (0.4y^(3.0) * (y + 2.0)) + (0.12y^(3.0)z * (y + 2.0)^(2.0))"
|
data/tests/test_utils.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from visma.utils.integers import gcd, factors
|
2 |
+
from visma.utils.polynomials import syntheticDivision
|
3 |
+
|
4 |
+
##################
|
5 |
+
# utils.integers #
|
6 |
+
##################
|
7 |
+
|
8 |
+
|
9 |
+
def test_gcd():
|
10 |
+
assert gcd([1]) == 1
|
11 |
+
assert gcd([3, 6, 12, 24]) == 3
|
12 |
+
assert gcd([-2, 4, 8]) == -2
|
13 |
+
assert gcd([2, -4, 8]) == 2
|
14 |
+
|
15 |
+
|
16 |
+
def test_factors():
|
17 |
+
assert factors(24) == [1, 2, 3, 4, 6, 8, 12, 24]
|
18 |
+
assert factors(0.5) == [] # Invalid input
|
19 |
+
|
20 |
+
|
21 |
+
#####################
|
22 |
+
# utils.polynomials #
|
23 |
+
#####################
|
24 |
+
|
25 |
+
def test_syntheticDivision():
|
26 |
+
assert syntheticDivision([1, 2, 1], -1) == ([1.0, 1.0], 0.0)
|
27 |
+
# (x^2 + 2x + 1)/(x+1)
|
28 |
+
assert syntheticDivision([3, 2, 1, 3], 2) == ([3.0, 8.0, 17.0], 37.0)
|
29 |
+
# (3x^2 + 2x + x + 3)/(x-2)
|
data/tests/tester.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from visma.io.tokenize import tokenizer, getLHSandRHS, removeSpaces
|
2 |
+
from visma.io.checks import checkTypes
|
3 |
+
from visma.discreteMaths.statistics import sampleSpace
|
4 |
+
|
5 |
+
|
6 |
+
# TODO: Categorize all test cases into COVERAGE and BASIS
|
7 |
+
def quickTest(inp, operation, wrtVar=None):
|
8 |
+
if operation.__name__ not in ['ArithemeticMean', 'Mode', 'Median']:
|
9 |
+
if (inp.count(';') == 2):
|
10 |
+
afterSplit = inp.split(';')
|
11 |
+
eqStr1 = afterSplit[0]
|
12 |
+
eqStr2 = afterSplit[1]
|
13 |
+
eqStr3 = afterSplit[2]
|
14 |
+
tokens = [tokenizer(eqStr1), tokenizer(eqStr2), tokenizer(eqStr3)]
|
15 |
+
token_string, _, _ = operation(tokens[0], tokens[1], tokens[2], wrtVar)
|
16 |
+
return removeSpaces(token_string)
|
17 |
+
elif (inp.count(';') == 1):
|
18 |
+
afterSplit = inp.split(';')
|
19 |
+
eqStr1 = afterSplit[0]
|
20 |
+
eqStr2 = afterSplit[1]
|
21 |
+
tokens = [tokenizer(eqStr1), tokenizer(eqStr2)]
|
22 |
+
_, _, token_string, _, _ = operation(tokens[0], tokens[1])
|
23 |
+
return removeSpaces(token_string)
|
24 |
+
else:
|
25 |
+
lhs, rhs = getLHSandRHS(tokenizer(inp))
|
26 |
+
_, inpType = checkTypes(lhs, rhs)
|
27 |
+
if inpType == "equation":
|
28 |
+
if wrtVar is not None:
|
29 |
+
_, _, _, token_string, _, _ = operation(lhs, rhs, wrtVar)
|
30 |
+
else:
|
31 |
+
_, _, _, token_string, _, _ = operation(lhs, rhs)
|
32 |
+
elif inpType == "expression":
|
33 |
+
if wrtVar is not None:
|
34 |
+
_, _, token_string, _, _ = operation(lhs, wrtVar)
|
35 |
+
else:
|
36 |
+
_, _, token_string, _, _ = operation(lhs)
|
37 |
+
else:
|
38 |
+
sampleSpaceObject = sampleSpace(inp)
|
39 |
+
token_string, _, _ = operation(sampleSpaceObject)
|
40 |
+
output = removeSpaces(token_string)
|
41 |
+
return output
|
42 |
+
|
43 |
+
|
44 |
+
def getTokens(eqString):
|
45 |
+
tokens = tokenizer(eqString)
|
46 |
+
if len(tokens) == 1:
|
47 |
+
tokens = tokens[0]
|
48 |
+
return tokens
|
data/visma/__init__.py
ADDED
File without changes
|
data/visma/calculus/__init__.py
ADDED
File without changes
|
data/visma/calculus/differentiation.py
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
|
3 |
+
from visma.functions.structure import Function, Expression
|
4 |
+
from visma.functions.constant import Constant, Zero
|
5 |
+
from visma.functions.operator import Operator, Multiply, Plus
|
6 |
+
from visma.simplify.simplify import simplify
|
7 |
+
from visma.functions.variable import Variable
|
8 |
+
from visma.functions.exponential import Logarithm, Exponential
|
9 |
+
from visma.functions.trigonometry import Trigonometric
|
10 |
+
from visma.io.parser import tokensToString
|
11 |
+
|
12 |
+
###################
|
13 |
+
# Differentiation #
|
14 |
+
###################
|
15 |
+
|
16 |
+
|
17 |
+
def differentiate(tokens, wrtVar):
|
18 |
+
"""Simplifies and then differentiates given tokens wrt given variable
|
19 |
+
|
20 |
+
Arguments:
|
21 |
+
tokens {list} -- list of function tokens
|
22 |
+
wrtVar {string} -- with respect to variable
|
23 |
+
|
24 |
+
Returns:
|
25 |
+
tokens {list} -- list of differentiated tokens
|
26 |
+
availableOperations {list} -- list of operations
|
27 |
+
token_string {string} -- output equation string
|
28 |
+
animation {list} -- equation tokens for step-by-step
|
29 |
+
comments {list} -- comments for step-by-step
|
30 |
+
"""
|
31 |
+
animation = []
|
32 |
+
comments = []
|
33 |
+
tokens, availableOperations, token_string, animation, comments = simplify(tokens)
|
34 |
+
tokens, animNew, commentsNew = differentiateTokens(tokens, wrtVar)
|
35 |
+
animation.append(animNew)
|
36 |
+
comments.append(commentsNew)
|
37 |
+
tokens, availableOperations, token_string, animation2, comments2 = simplify(tokens)
|
38 |
+
animation2.pop(0)
|
39 |
+
comments2.pop(0)
|
40 |
+
animation.extend(animation2)
|
41 |
+
comments.extend(comments2)
|
42 |
+
return tokens, availableOperations, token_string, animation, comments
|
43 |
+
|
44 |
+
|
45 |
+
def differentiateTokens(funclist, wrtVar):
|
46 |
+
"""Differentiates given tokens wrt given variable
|
47 |
+
|
48 |
+
Arguments:
|
49 |
+
funclist {list} -- list of function tokens
|
50 |
+
wrtVar {string} -- with respect to variable
|
51 |
+
|
52 |
+
Returns:
|
53 |
+
diffFunc {list} -- list of differentiated tokens
|
54 |
+
animNew {list} -- equation tokens for step-by-step
|
55 |
+
commentsNew {list} -- comments for step-by-step
|
56 |
+
"""
|
57 |
+
diffFunc = []
|
58 |
+
animNew = []
|
59 |
+
commentsNew = ["Differentiating with respect to " + r"$" + wrtVar + r"$" + "\n"]
|
60 |
+
for func in funclist:
|
61 |
+
if isinstance(func, Operator):
|
62 |
+
diffFunc.append(func)
|
63 |
+
else:
|
64 |
+
newExpression = Expression()
|
65 |
+
newfunc = []
|
66 |
+
while(isinstance(func, Function)):
|
67 |
+
commentsNew[0] += r"$" + "\\frac{d}{d" + wrtVar + "} ( " + func.__str__() + ")" + r"$"
|
68 |
+
funcCopy = copy.deepcopy(func)
|
69 |
+
if wrtVar in funcCopy.functionOf():
|
70 |
+
if isinstance(funcCopy, Trigonometric) or isinstance(funcCopy, Logarithm) or isinstance(funcCopy, Variable) or isinstance(funcCopy, Exponential):
|
71 |
+
funcCopy = funcCopy.differentiate(wrtVar)
|
72 |
+
newfunc.append(funcCopy)
|
73 |
+
commentsNew[0] += r"$" + r"= " + funcCopy.__str__() + r"\ ;\ " + r"$"
|
74 |
+
else:
|
75 |
+
funcCopy = Zero()
|
76 |
+
newfunc.append(funcCopy)
|
77 |
+
commentsNew[0] += r"$" + r"= " + funcCopy.__str__() + r"\ ;\ " + r"$"
|
78 |
+
newfunc.append(Multiply())
|
79 |
+
if func.operand is None:
|
80 |
+
break
|
81 |
+
else:
|
82 |
+
func = func.operand
|
83 |
+
if isinstance(func, Constant):
|
84 |
+
diffFunc = Zero()
|
85 |
+
break
|
86 |
+
newfunc.pop()
|
87 |
+
newExpression.tokens = newfunc
|
88 |
+
diffFunc.extend([newExpression])
|
89 |
+
animNew.extend(diffFunc)
|
90 |
+
return diffFunc, animNew, commentsNew
|
91 |
+
|
92 |
+
|
93 |
+
def differentiationProductRule(tokens, wrtVar):
|
94 |
+
resultTokens = []
|
95 |
+
for i in range(0, len(tokens), 2):
|
96 |
+
currentDiff = Expression()
|
97 |
+
currentDiffTokens, _, _, _, _ = differentiate([tokens[i]], wrtVar)
|
98 |
+
currentDiff.tokens = currentDiffTokens
|
99 |
+
tempTokens = copy.deepcopy(tokens)
|
100 |
+
tempTokens[i] = currentDiff
|
101 |
+
resultTokens.extend(tempTokens)
|
102 |
+
resultTokens.append(Plus())
|
103 |
+
resultTokens.pop()
|
104 |
+
token_string = tokensToString(resultTokens)
|
105 |
+
# TODO: Make simplify module to simplify expressions involving Trigonometric Expressions (to some extent)
|
106 |
+
# resultTokens, _, token_string, _, _ = simplify(resultTokens)
|
107 |
+
return tokens, [], token_string, [], []
|
data/visma/calculus/integration.py
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
from visma.functions.constant import Constant
|
3 |
+
from visma.functions.variable import Variable
|
4 |
+
from visma.functions.operator import Operator, Binary
|
5 |
+
from visma.simplify.simplify import simplify
|
6 |
+
from visma.functions.trigonometry import Trigonometric
|
7 |
+
from visma.calculus.differentiation import differentiate
|
8 |
+
from visma.io.parser import tokensToString
|
9 |
+
|
10 |
+
###############
|
11 |
+
# Integration #
|
12 |
+
###############
|
13 |
+
|
14 |
+
|
15 |
+
def integrate(tokens, wrtVar):
|
16 |
+
"""Simplifies and then integrates given tokens wrt given variable
|
17 |
+
|
18 |
+
Arguments:
|
19 |
+
tokens {list} -- list of function tokens
|
20 |
+
wrtVar {string} -- with respect to variable
|
21 |
+
|
22 |
+
Returns:
|
23 |
+
tokens {list} -- list of integrated tokens
|
24 |
+
availableOperations {list} -- list of operations
|
25 |
+
token_string {string} -- output equation string
|
26 |
+
animation {list} -- equation tokens for step-by-step
|
27 |
+
comments {list} -- comments for step-by-step
|
28 |
+
"""
|
29 |
+
|
30 |
+
tokens, availableOperations, token_string, animation, comments = simplify(tokens)
|
31 |
+
tokens, animNew, commentsNew = (integrateTokens(tokens, wrtVar))
|
32 |
+
animation.append(animNew)
|
33 |
+
comments.append(commentsNew)
|
34 |
+
tokens, availableOperations, token_string, animation2, comments2 = simplify(tokens)
|
35 |
+
animation2.pop(0)
|
36 |
+
comments2.pop(0)
|
37 |
+
animation.extend(animation2)
|
38 |
+
comments.extend(comments2)
|
39 |
+
return tokens, availableOperations, token_string, animation, comments
|
40 |
+
|
41 |
+
|
42 |
+
def integrateTokens(funclist, wrtVar):
|
43 |
+
"""Integrates given tokens wrt given variable
|
44 |
+
|
45 |
+
Arguments:
|
46 |
+
funclist {list} -- list of function tokens
|
47 |
+
wrtVar {string} -- with respect to variable
|
48 |
+
|
49 |
+
Returns:
|
50 |
+
intFunc {list} -- list of integrated tokens
|
51 |
+
animNew {list} -- equation tokens for step-by-step
|
52 |
+
commentsNew {list} -- comments for step-by-step
|
53 |
+
"""
|
54 |
+
intFunc = []
|
55 |
+
animNew = []
|
56 |
+
commentsNew = ["Integrating with respect to " + r"$" + wrtVar + r"$" + "\n"]
|
57 |
+
for func in funclist:
|
58 |
+
if isinstance(func, Operator): # add isfunctionOf
|
59 |
+
intFunc.append(func)
|
60 |
+
else:
|
61 |
+
newfunc = []
|
62 |
+
commentsNew[0] += r"$" + r"\int \ " + r"( " + func.__str__() + ")" + r" d" + wrtVar + r"$"
|
63 |
+
funcCopy = copy.deepcopy(func)
|
64 |
+
if wrtVar in funcCopy.functionOf():
|
65 |
+
if isinstance(funcCopy, Variable):
|
66 |
+
log = False
|
67 |
+
funcCopy, log = funcCopy.integrate(wrtVar)
|
68 |
+
if log:
|
69 |
+
commentsNew[0] += r"$" + r"= " + funcCopy[0].__str__() + r"*" + funcCopy[2].__str__() + r"\ ;\ " + r"$"
|
70 |
+
newfunc.extend(funcCopy)
|
71 |
+
else:
|
72 |
+
commentsNew[0] += r"$" + r"= " + funcCopy.__str__() + r"\ ;\ " + r"$"
|
73 |
+
newfunc.append(funcCopy)
|
74 |
+
elif isinstance(funcCopy, Trigonometric):
|
75 |
+
funcCopy = funcCopy.integrate(wrtVar)
|
76 |
+
newfunc.append(funcCopy)
|
77 |
+
commentsNew[0] += r"$" + r"= " + funcCopy.__str__() + r"\ ;\ " + r"$"
|
78 |
+
else:
|
79 |
+
if isinstance(funcCopy, Variable):
|
80 |
+
funcCopy.value.append(wrtVar)
|
81 |
+
funcCopy.power.append(1)
|
82 |
+
if isinstance(funcCopy, Constant):
|
83 |
+
coeff = funcCopy.value
|
84 |
+
funcCopy = Variable()
|
85 |
+
funcCopy.coefficient = coeff
|
86 |
+
funcCopy.value.append(wrtVar)
|
87 |
+
funcCopy.power.append(1)
|
88 |
+
newfunc.append(funcCopy)
|
89 |
+
commentsNew[0] += r"$" + r"= " + funcCopy.__str__() + r"\ ;\ " + r"$"
|
90 |
+
intFunc.extend(newfunc)
|
91 |
+
animNew.extend(intFunc)
|
92 |
+
return intFunc, animNew, commentsNew
|
93 |
+
|
94 |
+
|
95 |
+
def integrationByParts(tokens, wrtVar):
|
96 |
+
if (isinstance(tokens[1], Binary) and tokens[1].value == '*'):
|
97 |
+
u = tokens[0]
|
98 |
+
v = tokens[2]
|
99 |
+
vIntegral, _, _, _, _ = integrate(v, wrtVar)
|
100 |
+
uDerivative, _, _, _, _ = differentiate(u, wrtVar)
|
101 |
+
term1 = u * vIntegral
|
102 |
+
term2, _, _, _, _ = integrate(uDerivative * vIntegral, 'x')
|
103 |
+
resultToken = term1 - term2
|
104 |
+
token_string = tokensToString(resultToken)
|
105 |
+
return resultToken, [], token_string, [], []
|
data/visma/config/__init__.py
ADDED
File without changes
|
data/visma/config/values.py
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
|
3 |
+
# config
|
4 |
+
ROUNDOFF = 2
|
5 |
+
# FIXME: Make ROUNDOFF global
|
6 |
+
INPUT_TYPE = "Greek"
|
7 |
+
|
8 |
+
# constants
|
9 |
+
PI = math.pi
|
10 |
+
EXP = math.exp(1)
|
11 |
+
IOTA = complex(0, 1)
|
data/visma/discreteMaths/__init__.py
ADDED
File without changes
|
data/visma/discreteMaths/boolean.py
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from visma.simplify.simplify import simplify
|
2 |
+
from visma.functions.constant import Constant
|
3 |
+
from visma.io.tokenize import tokenizer
|
4 |
+
|
5 |
+
# TODO: Test cases.
|
6 |
+
# TODO: Implement GUI/CLI.
|
7 |
+
|
8 |
+
|
9 |
+
def logicalAND(token1, token2):
|
10 |
+
"""Implements Bitwise AND
|
11 |
+
Arguments:
|
12 |
+
token1 -- {list} -- List of tokens of a constant number
|
13 |
+
token2 -- {list} -- List of tokens of a constant number
|
14 |
+
|
15 |
+
Returns:
|
16 |
+
token_string {string} -- final result stored in a string
|
17 |
+
animation {list} -- list of equation solving process
|
18 |
+
comments {list} -- list of comments in equation solving process
|
19 |
+
"""
|
20 |
+
|
21 |
+
comments = []
|
22 |
+
animations = []
|
23 |
+
token1, _, _, _, _ = simplify(token1)
|
24 |
+
token2, _, _, _, _ = simplify(token2)
|
25 |
+
if isinstance(token1, Constant) and isinstance(token2, Constant):
|
26 |
+
comments += [['Converting numbers to Binary Illustrations: ']]
|
27 |
+
animations += [[]]
|
28 |
+
binaryValue1 = token1.binary()
|
29 |
+
binaryValue2 = token2.binary()
|
30 |
+
comments += [[]]
|
31 |
+
animations += [[tokenizer('a = ' + str(binaryValue1))]]
|
32 |
+
comments += [[]]
|
33 |
+
animations += [[tokenizer('b = ' + str(binaryValue2))]]
|
34 |
+
comments += [['Doing AND operation for each of the consecutive bit']]
|
35 |
+
animations += [[]]
|
36 |
+
resultValue = token1.calculate() & token2.calculate()
|
37 |
+
comments += [['Final result is']]
|
38 |
+
animations += [[tokenizer('r = ' + str(resultValue))]]
|
39 |
+
token_string = 'r = ' + str(resultValue)
|
40 |
+
return token_string, animations, comments
|
41 |
+
else:
|
42 |
+
return '', [], []
|
43 |
+
|
44 |
+
|
45 |
+
def logicalOR(token1, token2):
|
46 |
+
"""Implements Bitwise OR
|
47 |
+
Arguments:
|
48 |
+
token1 -- {list} -- List of tokens of a constant number
|
49 |
+
token2 -- {list} -- List of tokens of a constant number
|
50 |
+
|
51 |
+
Returns:
|
52 |
+
token_string {string} -- final result stored in a string
|
53 |
+
animation {list} -- list of equation solving process
|
54 |
+
comments {list} -- list of comments in equation solving process
|
55 |
+
"""
|
56 |
+
|
57 |
+
comments = []
|
58 |
+
animations = []
|
59 |
+
token1, _, _, _, _ = simplify(token1)
|
60 |
+
token2, _, _, _, _ = simplify(token2)
|
61 |
+
if isinstance(token1, Constant) and isinstance(token2, Constant):
|
62 |
+
comments += [['Converting numbers to Binary Illustrations: ']]
|
63 |
+
animations += [[]]
|
64 |
+
binaryValue1 = token1.binary()
|
65 |
+
binaryValue2 = token2.binary()
|
66 |
+
comments += [[]]
|
67 |
+
animations += [[tokenizer('a = ' + str(binaryValue1))]]
|
68 |
+
comments += [[]]
|
69 |
+
animations += [[tokenizer('b = ' + str(binaryValue2))]]
|
70 |
+
comments += [['Doing OR operation for each of the consecutive bit']]
|
71 |
+
animations += [[]]
|
72 |
+
resultValue = token1.calculate() | token2.calculate()
|
73 |
+
comments += [['Final result is']]
|
74 |
+
animations += [[tokenizer('r = ' + str(resultValue))]]
|
75 |
+
token_string = 'r = ' + str(resultValue)
|
76 |
+
return token_string, animations, comments
|
77 |
+
else:
|
78 |
+
return '', [], []
|
79 |
+
|
80 |
+
|
81 |
+
def logicalNOT(token1):
|
82 |
+
"""Implements Bitwise NOT
|
83 |
+
Arguments:
|
84 |
+
token1 -- {list} -- List of tokens of a constant number
|
85 |
+
|
86 |
+
Returns:
|
87 |
+
token_string {string} -- final result stored in a string
|
88 |
+
animation {list} -- list of equation solving process
|
89 |
+
comments {list} -- list of comments in equation solving process
|
90 |
+
"""
|
91 |
+
|
92 |
+
comments = []
|
93 |
+
animations = []
|
94 |
+
token1, _, _, _, _ = simplify(token1)
|
95 |
+
if isinstance(token1, Constant):
|
96 |
+
comments += [['Converting numbers to Binary Illustrations: ']]
|
97 |
+
animations += [[]]
|
98 |
+
binaryValue1 = token1.binary()
|
99 |
+
comments += [[]]
|
100 |
+
animations += [[tokenizer('a = ' + str(binaryValue1))]]
|
101 |
+
resultValueBinary = bin((1 << 8) - 1 - int(binaryValue1, 2))
|
102 |
+
resultValue = int(resultValueBinary, 2)
|
103 |
+
comments += [['Final binary is']]
|
104 |
+
animations += [[tokenizer('r = ' + str(resultValueBinary))]]
|
105 |
+
comments += [['Final result is']]
|
106 |
+
animations += [[tokenizer('r = ' + str(resultValue))]]
|
107 |
+
token_string = 'r = ' + str(resultValue)
|
108 |
+
return token_string, animations, comments
|
109 |
+
else:
|
110 |
+
return '', [], []
|
data/visma/discreteMaths/combinatorics.py
ADDED
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
'''This module is supposed to contain all the combinatorics related stuff which can be performed by VisualMath (VisMa)
|
2 |
+
|
3 |
+
Note: Please try to maintain proper documentation
|
4 |
+
'''
|
5 |
+
|
6 |
+
from visma.io.tokenize import tokenizer
|
7 |
+
from visma.simplify.simplify import simplify
|
8 |
+
from visma.io.parser import tokensToString
|
9 |
+
from visma.functions.constant import Constant
|
10 |
+
|
11 |
+
|
12 |
+
def factorial(tokens):
|
13 |
+
'''Used to get factorial of tokens provided
|
14 |
+
|
15 |
+
Argument:
|
16 |
+
tokens {list} -- list of tokens
|
17 |
+
|
18 |
+
Returns:
|
19 |
+
result {list} -- list of result tokens
|
20 |
+
{empty list}
|
21 |
+
token_string {string} -- final result stored in a string
|
22 |
+
animation {list} -- list of equation solving process
|
23 |
+
comments {list} -- list of comments in equation solving process
|
24 |
+
'''
|
25 |
+
tokens, _, _, _, _ = simplify(tokens)
|
26 |
+
animation = []
|
27 |
+
comments = []
|
28 |
+
if (isinstance(tokens[0], Constant) & len(tokens) == 1):
|
29 |
+
value = int(tokens[0].calculate())
|
30 |
+
if value == 0:
|
31 |
+
result = [Constant(1)]
|
32 |
+
comments += [['Factorial of ZERO is defined to be 1']]
|
33 |
+
animation += [tokenizer('f = ' + str(1))]
|
34 |
+
else:
|
35 |
+
resultString = ''
|
36 |
+
for i in range(1, value + 1):
|
37 |
+
resultString += (str(i) + '*')
|
38 |
+
resultString = resultString[:-1]
|
39 |
+
resultTokens = tokenizer(resultString)
|
40 |
+
comments += [['Expanding the factorial as']]
|
41 |
+
animation += [resultTokens]
|
42 |
+
result, _, _, _, _ = simplify(resultTokens)
|
43 |
+
token_string = tokensToString(result)
|
44 |
+
comments += [['Hence result: ']]
|
45 |
+
animation += [tokenizer('f = ' + token_string)]
|
46 |
+
return result, [], token_string, animation, comments
|
47 |
+
|
48 |
+
|
49 |
+
def permutation(nTokens, rTokens):
|
50 |
+
'''Used to get Permutation (nPr)
|
51 |
+
|
52 |
+
Argument:
|
53 |
+
nTokens {list} -- list of tokens of "n" in nPr
|
54 |
+
rTokens {list} -- list of tokens of "r" in nPr
|
55 |
+
|
56 |
+
Returns:
|
57 |
+
result {list} -- list of result tokens
|
58 |
+
{empty list}
|
59 |
+
token_string {string} -- final result stored in a string
|
60 |
+
animation {list} -- list of equation solving process
|
61 |
+
comments {list} -- list of comments in equation solving process
|
62 |
+
'''
|
63 |
+
nTokens, _, _, _, _ = simplify(nTokens)
|
64 |
+
rTokens, _, _, _, _ = simplify(rTokens)
|
65 |
+
animation = []
|
66 |
+
comments = []
|
67 |
+
if (isinstance(nTokens[0], Constant) & len(nTokens) == 1) & (isinstance(rTokens[0], Constant) & len(rTokens) == 1):
|
68 |
+
comments += [['nCr is defined as (n!)/(r!)*(n-r)!']]
|
69 |
+
animation += [[]]
|
70 |
+
comments += [['Solving for n!']]
|
71 |
+
animation += [[]]
|
72 |
+
numerator, _, _, animNew1, commentNew1 = factorial(nTokens)
|
73 |
+
commentNew1[1] = ['(n)! is thus solved as: ']
|
74 |
+
animation.extend(animNew1)
|
75 |
+
comments.extend(commentNew1)
|
76 |
+
denominator = nTokens[0] - rTokens[0]
|
77 |
+
comments += [['Solving for (n - r)!']]
|
78 |
+
animation += [[]]
|
79 |
+
denominator, _, _, animNew2, commentNew2 = factorial([denominator])
|
80 |
+
commentNew2[1] = ['(n - r)! is thus solved as: ']
|
81 |
+
comments.extend(commentNew2)
|
82 |
+
animation.extend(animNew2)
|
83 |
+
result = [numerator[0] / denominator[0]]
|
84 |
+
comments += [['On placing values in (n!)/(n-r)!']]
|
85 |
+
animation += [tokenizer('r = ' + tokensToString(result))]
|
86 |
+
token_string = tokensToString(result)
|
87 |
+
return result, [], token_string, animation, comments
|
88 |
+
|
89 |
+
|
90 |
+
def combination(nTokens, rTokens):
|
91 |
+
'''Used to get Combination (nCr)
|
92 |
+
|
93 |
+
Argument:
|
94 |
+
nTokens {list} -- list of tokens of "n" in nCr
|
95 |
+
rTokens {list} -- list of tokens of "r" in nCr
|
96 |
+
|
97 |
+
Returns:
|
98 |
+
result {list} -- list of result tokens
|
99 |
+
{empty list}
|
100 |
+
token_string {string} -- final result stored in a string
|
101 |
+
animation {list} -- list of equation solving process
|
102 |
+
comments {list} -- list of comments in equation solving process
|
103 |
+
'''
|
104 |
+
nTokens, _, _, _, _ = simplify(nTokens)
|
105 |
+
rTokens, _, _, _, _ = simplify(rTokens)
|
106 |
+
animation = []
|
107 |
+
comments = []
|
108 |
+
if (isinstance(nTokens[0], Constant) & len(nTokens) == 1) & (isinstance(rTokens[0], Constant) & len(rTokens) == 1):
|
109 |
+
comments += [['nCr is defined as (n!)/(r!)*(n-r)!']]
|
110 |
+
animation += [[]]
|
111 |
+
comments += [['Solving for n!']]
|
112 |
+
animation += [[]]
|
113 |
+
numerator, _, _, animNew1, commentNew1 = factorial(nTokens)
|
114 |
+
commentNew1[1] = ['(n)! is thus solved as: ']
|
115 |
+
animation.extend(animNew1)
|
116 |
+
comments.extend(commentNew1)
|
117 |
+
denominator1 = nTokens[0] - rTokens[0]
|
118 |
+
comments += [['Solving for (n - r)!']]
|
119 |
+
animation += [[]]
|
120 |
+
denominator1, _, _, animNew2, commentNew2 = factorial([denominator1])
|
121 |
+
commentNew2[1] = ['(n - r)! is thus solved as: ']
|
122 |
+
comments.extend(commentNew2)
|
123 |
+
animation.extend(animNew2)
|
124 |
+
comments += [['Solving for r!']]
|
125 |
+
animation += [[]]
|
126 |
+
denominator2, _, _, animNew3, commentNew3 = factorial([rTokens[0]])
|
127 |
+
commentNew3[1] = ['r! is thus solved as: ']
|
128 |
+
comments.extend(commentNew3)
|
129 |
+
animation.extend(animNew3)
|
130 |
+
denominator = denominator1[0] * denominator2[0]
|
131 |
+
result = [numerator[0] / denominator]
|
132 |
+
comments += [['On placing values in (n!)/(r!)*(n-r)!']]
|
133 |
+
animation += [tokenizer('r = ' + tokensToString(result))]
|
134 |
+
token_string = tokensToString(result)
|
135 |
+
return result, [], token_string, animation, comments
|
data/visma/discreteMaths/probability.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from visma.io.tokenize import tokenizer
|
2 |
+
|
3 |
+
|
4 |
+
def simpleProbability(sampleSpace, requiredEvent=None):
|
5 |
+
"""Implements simple probability
|
6 |
+
|
7 |
+
Arguments:
|
8 |
+
sampleSpace -- {visma.discreteMaths.statistics.ArithemeticMean}
|
9 |
+
requiredEvent -- {Event whose probability is to be calculated}
|
10 |
+
|
11 |
+
Returns:
|
12 |
+
token_string {string} -- final result stored in a string
|
13 |
+
animation {list} -- list of equation solving process
|
14 |
+
comments {list} -- list of comments in equation solving process
|
15 |
+
"""
|
16 |
+
|
17 |
+
animations = []
|
18 |
+
comments = []
|
19 |
+
events = []
|
20 |
+
token_string = ''
|
21 |
+
if sampleSpace.values is not []:
|
22 |
+
events.extend(sampleSpace.values)
|
23 |
+
totalOccurances = len(events)
|
24 |
+
animations += [[]]
|
25 |
+
comments += [['The total occurances are ' + str(totalOccurances)]]
|
26 |
+
requiredOccurances = events.count(requiredEvent)
|
27 |
+
animations += [[]]
|
28 |
+
comments += [['The occurances of required event are ' + str(requiredOccurances)]]
|
29 |
+
probability = requiredOccurances/totalOccurances
|
30 |
+
comments += [['Hence, Required probability is: ']]
|
31 |
+
animations += [tokenizer('P = ' + str(probability))]
|
32 |
+
token_string = 'P = ' + str(probability)
|
33 |
+
return token_string, animations, comments
|
34 |
+
else:
|
35 |
+
return '', [], []
|
data/visma/discreteMaths/statistics.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import Counter
|
2 |
+
from visma.io.tokenize import tokenizer
|
3 |
+
from visma.simplify.simplify import simplify
|
4 |
+
from visma.io.parser import tokensToString
|
5 |
+
from visma.functions.constant import Constant
|
6 |
+
|
7 |
+
# TODO: Implement this module in GUI/CLI
|
8 |
+
|
9 |
+
|
10 |
+
class sampleSpace(object):
|
11 |
+
"""Class used to represent sample space of a data.
|
12 |
+
"""
|
13 |
+
values = []
|
14 |
+
size = 0
|
15 |
+
|
16 |
+
def __init__(self, values):
|
17 |
+
if values is not None:
|
18 |
+
self.values = values
|
19 |
+
self.size = len(values)
|
20 |
+
|
21 |
+
|
22 |
+
def ArithemeticMean(sampleSpace):
|
23 |
+
"""Implements arithemetic mean
|
24 |
+
|
25 |
+
Arguments:
|
26 |
+
sampleSpace -- {visma.discreteMaths.statistics.ArithemeticMean}
|
27 |
+
|
28 |
+
Returns:
|
29 |
+
token_string {string} -- final result stored in a string
|
30 |
+
animation {list} -- list of equation solving process
|
31 |
+
comments {list} -- list of comments in equation solving process
|
32 |
+
"""
|
33 |
+
animations = []
|
34 |
+
comments = []
|
35 |
+
if sampleSpace.values is not []:
|
36 |
+
sm = sum(sampleSpace.values)
|
37 |
+
animations += [[]]
|
38 |
+
comments += [['Sum of all the values of the sample space provided by user: ' + str(sm)]]
|
39 |
+
summationString = ''
|
40 |
+
for val in sampleSpace.values:
|
41 |
+
summationString += str(val) + '+'
|
42 |
+
summationString = summationString[:-1]
|
43 |
+
summationTokens = tokenizer(summationString)
|
44 |
+
resultTokens, _, _, _, _ = simplify(summationTokens)
|
45 |
+
if len(resultTokens) == 1 and isinstance(resultTokens[0], Constant):
|
46 |
+
ArithemeticMean = resultTokens[0]/Constant(len(sampleSpace.values))
|
47 |
+
animations += [[]]
|
48 |
+
comments += [['Considering ' + str(len(sampleSpace.values)) + ' values.']]
|
49 |
+
animations += [[tokenizer('mean = ' + str(ArithemeticMean.calculate))]]
|
50 |
+
token_string = tokensToString([ArithemeticMean])
|
51 |
+
return token_string, animations, comments
|
52 |
+
else:
|
53 |
+
return '', [], []
|
54 |
+
|
55 |
+
|
56 |
+
def Mode(sampleSpace):
|
57 |
+
"""Implements Mode
|
58 |
+
|
59 |
+
Arguments:
|
60 |
+
sampleSpace -- {visma.discreteMaths.statistics.ArithemeticMean}
|
61 |
+
|
62 |
+
Returns:
|
63 |
+
token_string {string} -- final result stored in a string
|
64 |
+
animation {list} -- list of equation solving process
|
65 |
+
comments {list} -- list of comments in equation solving process
|
66 |
+
"""
|
67 |
+
|
68 |
+
animations = []
|
69 |
+
comments = []
|
70 |
+
token_string = ''
|
71 |
+
if sampleSpace.values is not []:
|
72 |
+
mode, frequency = Counter(sampleSpace.values).most_common(1)[0]
|
73 |
+
comments += [['The mode refers to the most occuring element']]
|
74 |
+
animations += [[]]
|
75 |
+
comments += [['Mode = ' + str(mode) + '; Mode Frequency = ' + str(frequency)]]
|
76 |
+
animations += [[]]
|
77 |
+
token_string = 'Mode = ' + str(mode) + '; Mode Frequency = ' + str(frequency)
|
78 |
+
return token_string, animations, comments
|
79 |
+
else:
|
80 |
+
return '', [], []
|
81 |
+
|
82 |
+
|
83 |
+
def Median(sampleSpace):
|
84 |
+
"""Implements Median
|
85 |
+
|
86 |
+
Arguments:
|
87 |
+
sampleSpace -- {visma.discreteMaths.statistics.ArithemeticMean}
|
88 |
+
|
89 |
+
Returns:
|
90 |
+
token_string {string} -- final result stored in a string
|
91 |
+
animation {list} -- list of equation solving process
|
92 |
+
comments {list} -- list of comments in equation solving process
|
93 |
+
"""
|
94 |
+
|
95 |
+
animations = []
|
96 |
+
comments = []
|
97 |
+
token_string = ''
|
98 |
+
if sampleSpace.values is not []:
|
99 |
+
sizeSampleSpace = sampleSpace.size
|
100 |
+
if sizeSampleSpace % 2 == 1:
|
101 |
+
medianValue = sorted(sampleSpace.values)[sizeSampleSpace//2]
|
102 |
+
else:
|
103 |
+
medianValue = sum(sorted(sampleSpace.values)[sizeSampleSpace//2-1: sizeSampleSpace//2+1])/2.0
|
104 |
+
comments += [['The median refers to the middle element in sorted sample space']]
|
105 |
+
animations += [[]]
|
106 |
+
comments += [['Median = ' + str(medianValue)]]
|
107 |
+
animations += [[]]
|
108 |
+
token_string = str(medianValue)
|
109 |
+
return token_string, animations, comments
|
110 |
+
else:
|
111 |
+
return '', [], []
|
data/visma/functions/__init__.py
ADDED
File without changes
|
data/visma/functions/constant.py
ADDED
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
from visma.functions.structure import Function, Expression
|
3 |
+
from visma.functions.variable import Variable
|
4 |
+
from visma.functions.exponential import Exponential
|
5 |
+
from visma.functions.operator import Plus, Minus
|
6 |
+
|
7 |
+
#############
|
8 |
+
# Constant #
|
9 |
+
#############
|
10 |
+
|
11 |
+
|
12 |
+
class Constant(Function):
|
13 |
+
"""Class for constant type tokens
|
14 |
+
|
15 |
+
Example:
|
16 |
+
1, -2, 3.14, 4i + 5 etc
|
17 |
+
|
18 |
+
Extends:
|
19 |
+
Function
|
20 |
+
"""
|
21 |
+
|
22 |
+
def __init__(self, value=None, power=1, coefficient=1):
|
23 |
+
super().__init__()
|
24 |
+
self.coefficient = coefficient
|
25 |
+
self.power = power
|
26 |
+
if value is not None:
|
27 |
+
self.value = value
|
28 |
+
if self.value is not None:
|
29 |
+
self.value = self.calculate()
|
30 |
+
self.coefficient = 1
|
31 |
+
self.power = 1
|
32 |
+
|
33 |
+
def inverse(self, RHS):
|
34 |
+
pass
|
35 |
+
|
36 |
+
def differentiate(self):
|
37 |
+
super().differentiate()
|
38 |
+
self.value = 0
|
39 |
+
|
40 |
+
def integrate(self, intwrt):
|
41 |
+
self.coefficient = self.value ** self.power
|
42 |
+
self.__class__ = Variable
|
43 |
+
self.power = [1]
|
44 |
+
self.value = [intwrt]
|
45 |
+
|
46 |
+
def __radd__(self, other):
|
47 |
+
return self + other
|
48 |
+
|
49 |
+
def __add__(self, other):
|
50 |
+
if isinstance(other, Constant):
|
51 |
+
if self.before == '-':
|
52 |
+
result = Constant(self.calculate() - other.calculate(), self.power)
|
53 |
+
else:
|
54 |
+
result = Constant(self.calculate() + other.calculate(), self.power)
|
55 |
+
self.value = result.value
|
56 |
+
if result.value == 0 and result.power == 0:
|
57 |
+
result.value = 1
|
58 |
+
result.power = 1
|
59 |
+
result.scope = self.scope
|
60 |
+
result.value = result.calculate()
|
61 |
+
return result
|
62 |
+
elif self.isZero():
|
63 |
+
return other
|
64 |
+
elif other.isZero():
|
65 |
+
return self
|
66 |
+
elif isinstance(other, Expression):
|
67 |
+
if other.power == 1 and other.coefficient == 1:
|
68 |
+
constFound = False
|
69 |
+
for i, var in enumerate(other.tokens):
|
70 |
+
if isinstance(var, Constant):
|
71 |
+
if other.tokens[i-1].value == '+' or i == 0:
|
72 |
+
other.tokens[i] = self + var
|
73 |
+
elif other.tokens[i-1].value == '-':
|
74 |
+
other.tokens[i-1] = self - var
|
75 |
+
constFound = True
|
76 |
+
break
|
77 |
+
if not constFound:
|
78 |
+
other.tokens.extend([Plus(), self])
|
79 |
+
return other
|
80 |
+
else:
|
81 |
+
pass
|
82 |
+
self.value = self.calculate()
|
83 |
+
self.power = 1
|
84 |
+
self.coefficient = 1
|
85 |
+
exprAdd = Expression([self, Plus(), other]) # Make an Expression and assign the Tokens attribute with the Constant and the Other Variable, Trig. function,...etc.
|
86 |
+
return exprAdd
|
87 |
+
|
88 |
+
def __rsub__(self, other):
|
89 |
+
return Constant(0) - self + other
|
90 |
+
|
91 |
+
def __sub__(self, other):
|
92 |
+
if isinstance(other, Constant):
|
93 |
+
self = self + Constant(-1, 1, 1) * other
|
94 |
+
return self
|
95 |
+
elif isinstance(other, Variable):
|
96 |
+
if self.value == 0:
|
97 |
+
other.coefficient *= -1
|
98 |
+
return other
|
99 |
+
expression = Expression()
|
100 |
+
expression.tokens = [self]
|
101 |
+
expression.tokens.extend([Minus(), other])
|
102 |
+
elif isinstance(other, Expression):
|
103 |
+
expression = Expression()
|
104 |
+
expression.tokens = [self]
|
105 |
+
if other.power == 1:
|
106 |
+
coeff = other.coefficient
|
107 |
+
for i, token in enumerate(other.tokens):
|
108 |
+
print(expression, " ", type(token), other.tokens[i-1])
|
109 |
+
if isinstance(token, Constant):
|
110 |
+
if other.tokens[i-1].value == '+' or i == 0:
|
111 |
+
expression.tokens[0] = Constant(self.calculate() - token.calculate()*coeff)
|
112 |
+
elif other.tokens[i-1].value == '-':
|
113 |
+
expression.tokens[0] = Constant(self.calculate() + token.calculate()*coeff)
|
114 |
+
elif isinstance(token, Variable):
|
115 |
+
if other.tokens[i-1].value == '+' or i == 0:
|
116 |
+
expression.tokens.extend([Minus(), Variable(token)])
|
117 |
+
elif other.tokens[i-1].value == '-':
|
118 |
+
expression.tokens.extend([Plus(), Variable(token)])
|
119 |
+
else:
|
120 |
+
expression.tokens.extend([Minus(), other])
|
121 |
+
self = expression
|
122 |
+
return expression
|
123 |
+
|
124 |
+
def __rmul__(self, other):
|
125 |
+
return self * other
|
126 |
+
|
127 |
+
def __mul__(self, other):
|
128 |
+
if other.isZero():
|
129 |
+
return other
|
130 |
+
elif self.isZero():
|
131 |
+
return self
|
132 |
+
elif isinstance(other, Constant):
|
133 |
+
const = Constant(self.calculate() * other.calculate())
|
134 |
+
return const
|
135 |
+
elif isinstance(other, Variable):
|
136 |
+
variable = Variable()
|
137 |
+
variable.coefficient = self.calculate() * other.coefficient
|
138 |
+
variable.value.extend(other.value)
|
139 |
+
variable.power.extend(other.power)
|
140 |
+
self = variable
|
141 |
+
return variable
|
142 |
+
elif isinstance(other, Expression):
|
143 |
+
if other.power == 1:
|
144 |
+
other.tokens[0] = self * other.tokens[0]
|
145 |
+
for i, var in enumerate(other.tokens):
|
146 |
+
if other.tokens[i-1].value == '+' or other.tokens[i-1].value == '-':
|
147 |
+
other.tokens[i] = self * var
|
148 |
+
else:
|
149 |
+
if isinstance(other.power, Constant) or isinstance(other.power, int) or isinstance(other.power, float):
|
150 |
+
self = self ** (-1 * other.power)
|
151 |
+
for i, var in enumerate(other.tokens):
|
152 |
+
if other.tokens[i - 1].value == '+' or other.tokens[i - 1].value == '-':
|
153 |
+
other.tokens[i] = self * var
|
154 |
+
else:
|
155 |
+
other.coefficient = self * other.coefficient
|
156 |
+
else:
|
157 |
+
other.coefficient = self.calculate() * other.coefficient
|
158 |
+
return other
|
159 |
+
|
160 |
+
def __rtruediv__(self, other):
|
161 |
+
return Constant(1) / self * other
|
162 |
+
|
163 |
+
def __truediv__(self, other):
|
164 |
+
if other.value in ['+', '-', '*', '/']:
|
165 |
+
return other
|
166 |
+
elif self.isZero():
|
167 |
+
return self
|
168 |
+
elif isinstance(other, Constant):
|
169 |
+
result = Constant()
|
170 |
+
power = Constant(-1, 1, 1)
|
171 |
+
result = self * (other ** power)
|
172 |
+
return result
|
173 |
+
|
174 |
+
elif isinstance(other, Variable):
|
175 |
+
power = Constant(-1, 1, 1)
|
176 |
+
self = self * (other ** power)
|
177 |
+
return self
|
178 |
+
elif isinstance(other, Expression):
|
179 |
+
other.power = -1 * other.power
|
180 |
+
newCoeff = self * Constant(other.coefficient)
|
181 |
+
other.coefficient = newCoeff
|
182 |
+
return other
|
183 |
+
else:
|
184 |
+
if other.isZero(): # ToDo: Raise a Division by Zero Error
|
185 |
+
return other
|
186 |
+
other.coefficient = self.calculate() / other.coefficient
|
187 |
+
other.power = [-1 * eachPower for eachPower in other.power]
|
188 |
+
return other
|
189 |
+
|
190 |
+
def __pow__(self, val):
|
191 |
+
if isinstance(val, int) or isinstance(val, float):
|
192 |
+
if self.power == 0 and self.value == 0:
|
193 |
+
self.power = 1
|
194 |
+
self.value = 1
|
195 |
+
else:
|
196 |
+
self.value = (self.value ** self.power)
|
197 |
+
self.power = 1
|
198 |
+
return self
|
199 |
+
elif isinstance(val, Constant):
|
200 |
+
self.value = self.calculate() ** val.calculate()
|
201 |
+
self.coefficient = 1
|
202 |
+
self.power = 1
|
203 |
+
return self
|
204 |
+
else:
|
205 |
+
constExponent = Exponential()
|
206 |
+
constExponent.base = self.value
|
207 |
+
constExponent.coefficient = self.coefficient
|
208 |
+
constExponent.power = val
|
209 |
+
return constExponent
|
210 |
+
|
211 |
+
def calculate(self):
|
212 |
+
return self.coefficient * (self ** self.power).value
|
213 |
+
|
214 |
+
def functionOf(self):
|
215 |
+
return []
|
216 |
+
|
217 |
+
def binary(self):
|
218 |
+
'''Returns a binary string of the given constant
|
219 |
+
'''
|
220 |
+
return bin(self.calculate())[2:]
|
221 |
+
|
222 |
+
|
223 |
+
class Zero(Constant):
|
224 |
+
|
225 |
+
def __init__(self):
|
226 |
+
super().__init__()
|
227 |
+
self.value = 0
|
228 |
+
|
229 |
+
|
230 |
+
class One(Constant):
|
231 |
+
|
232 |
+
def __init__(self):
|
233 |
+
super().__init__()
|
234 |
+
self.value = 1
|
235 |
+
|
236 |
+
|
237 |
+
class Pi(Constant):
|
238 |
+
|
239 |
+
def __init__(self):
|
240 |
+
super().__init__()
|
241 |
+
self.value = math.pi
|
242 |
+
|
243 |
+
|
244 |
+
class Euler(Constant):
|
245 |
+
|
246 |
+
def __init__(self):
|
247 |
+
super().__init__()
|
248 |
+
self.value = math.e
|
249 |
+
|
250 |
+
|
251 |
+
class Iota(Constant):
|
252 |
+
|
253 |
+
def __init__(self):
|
254 |
+
super().__init__()
|
255 |
+
self.value = 1j
|
data/visma/functions/exponential.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import copy
|
3 |
+
from visma.functions.structure import FuncOp
|
4 |
+
|
5 |
+
#########################
|
6 |
+
# Exponential Functions #
|
7 |
+
#########################
|
8 |
+
|
9 |
+
|
10 |
+
class Logarithm(FuncOp):
|
11 |
+
"""Class for log function -- log(...)
|
12 |
+
|
13 |
+
Input examples:
|
14 |
+
log(2) [without base, default base 10]
|
15 |
+
log_4(x+y) [with base]
|
16 |
+
|
17 |
+
Extends:
|
18 |
+
FuncOp
|
19 |
+
"""
|
20 |
+
|
21 |
+
def __init__(self, operand=None):
|
22 |
+
super().__init__()
|
23 |
+
self.base = 10
|
24 |
+
self.value = 'log'
|
25 |
+
|
26 |
+
def inverse(self, rToken, wrtVar, inverseFunction=None):
|
27 |
+
inverseFunction = Exponential()
|
28 |
+
super().inverse(self, rToken, wrtVar, inverseFunction)
|
29 |
+
|
30 |
+
def calculate(self, val):
|
31 |
+
return self.coefficient * ((math.log(val, self.base)))
|
32 |
+
|
33 |
+
def differentiate(self, wrtVar=None):
|
34 |
+
from visma.functions.variable import Variable
|
35 |
+
result = copy.deepcopy(self)
|
36 |
+
result.__class__ = Variable
|
37 |
+
result.coefficient = 1
|
38 |
+
result.value = wrtVar
|
39 |
+
result.power = [-1]
|
40 |
+
result.operand = None
|
41 |
+
return result
|
42 |
+
|
43 |
+
|
44 |
+
class NaturalLog(Logarithm):
|
45 |
+
"""Class for ln function -- ln(...) or use log_e(...)
|
46 |
+
|
47 |
+
Extends:
|
48 |
+
Logarithm
|
49 |
+
"""
|
50 |
+
|
51 |
+
def __init__(self, operand=None):
|
52 |
+
super().__init__()
|
53 |
+
self.base = math.exp(1)
|
54 |
+
self.value = 'ln'
|
55 |
+
|
56 |
+
|
57 |
+
class Exponential(FuncOp):
|
58 |
+
"""Class for all constant exponential functions -- as exp(...) or 5^(...)
|
59 |
+
|
60 |
+
Extends:
|
61 |
+
FuncOp
|
62 |
+
"""
|
63 |
+
|
64 |
+
def __init__(self, val=None):
|
65 |
+
super().__init__()
|
66 |
+
self.value = 'exp'
|
67 |
+
if not val:
|
68 |
+
self.base = val
|
69 |
+
else:
|
70 |
+
self.base = math.e
|
71 |
+
|
72 |
+
def calculate(self):
|
73 |
+
from visma.functions.constant import Constant
|
74 |
+
if isinstance(self.power, int) or isinstance(self.power, float) or isinstance(self.power, Constant):
|
75 |
+
const = Constant()
|
76 |
+
if isinstance(self.power, Constant):
|
77 |
+
self.power = self.power.calculate()
|
78 |
+
const.value = self.coefficient * (self.base ** self.power)
|
79 |
+
return const
|
80 |
+
else:
|
81 |
+
return self
|
data/visma/functions/hyperbolic.py
ADDED
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from visma.functions.structure import FuncOp
|
2 |
+
from visma.functions.exponential import NaturalLog
|
3 |
+
import math
|
4 |
+
|
5 |
+
########################
|
6 |
+
# Hyberbolic Functions #
|
7 |
+
########################
|
8 |
+
|
9 |
+
|
10 |
+
class Sinh(FuncOp):
|
11 |
+
"""Class for sinh function -- sinh(...)
|
12 |
+
|
13 |
+
Extends:
|
14 |
+
FuncOp
|
15 |
+
"""
|
16 |
+
|
17 |
+
def __init__(self):
|
18 |
+
super().__init__()
|
19 |
+
self.value = 'sinh'
|
20 |
+
|
21 |
+
def inverse(self, RHS):
|
22 |
+
super().inverse(RHS)
|
23 |
+
self.__class__ = ArcSinh
|
24 |
+
|
25 |
+
def differentiate(self):
|
26 |
+
super().differentiate()
|
27 |
+
self.__class__ = Cosh
|
28 |
+
|
29 |
+
def integrate(self):
|
30 |
+
self.__class__ = Cosh
|
31 |
+
|
32 |
+
def calculate(self, val):
|
33 |
+
return self.coefficient * ((math.sinh(val))**self.power)
|
34 |
+
|
35 |
+
|
36 |
+
class Cosh(FuncOp):
|
37 |
+
"""Class for cosh function -- cosh(...)
|
38 |
+
|
39 |
+
Extends:
|
40 |
+
FuncOp
|
41 |
+
"""
|
42 |
+
|
43 |
+
def __init__(self):
|
44 |
+
super().__init__()
|
45 |
+
self.value = 'cosh'
|
46 |
+
|
47 |
+
def inverse(self, RHS):
|
48 |
+
super().inverse(RHS)
|
49 |
+
self.__class__ = ArcCosh
|
50 |
+
|
51 |
+
def differentiate(self):
|
52 |
+
super().differentiate()
|
53 |
+
self.__class__ = Sinh
|
54 |
+
|
55 |
+
def integrate(self):
|
56 |
+
self.__class__ = Sinh
|
57 |
+
|
58 |
+
def calculate(self, val):
|
59 |
+
return self.coefficient * ((math.cosh(val))**self.power)
|
60 |
+
|
61 |
+
|
62 |
+
class Tanh(FuncOp):
|
63 |
+
"""Class for tanh function -- tanh(...)
|
64 |
+
|
65 |
+
Extends:
|
66 |
+
FuncOp
|
67 |
+
"""
|
68 |
+
|
69 |
+
def __init__(self):
|
70 |
+
super().__init__()
|
71 |
+
self.value = 'tanh'
|
72 |
+
|
73 |
+
def inverse(self, RHS):
|
74 |
+
super().inverse(RHS)
|
75 |
+
self.__class__ = ArcTanh
|
76 |
+
|
77 |
+
def differentiate(self):
|
78 |
+
super().differentiate()
|
79 |
+
self.__class__ = Cosh # Derivative of Tanh(x) is equal to 1-Tanh^2(x) = Sech^2(x) = Cosh^-2(x), So Class is Cosh, and Power is to be set to (-2).
|
80 |
+
|
81 |
+
def integrate(self):
|
82 |
+
self.__class__ = NaturalLog # Ln(Cosh(x)), value is to be set to Cosh(...).
|
83 |
+
|
84 |
+
def calculate(self, val):
|
85 |
+
return self.coefficient * ((math.tanh(val)) ** self.power)
|
86 |
+
|
87 |
+
################################
|
88 |
+
# Inverse Hyperbolic Functions #
|
89 |
+
################################
|
90 |
+
|
91 |
+
|
92 |
+
class ArcSinh(FuncOp):
|
93 |
+
pass
|
94 |
+
|
95 |
+
|
96 |
+
class ArcCosh(FuncOp):
|
97 |
+
pass
|
98 |
+
|
99 |
+
|
100 |
+
class ArcTanh(FuncOp):
|
101 |
+
pass
|
data/visma/functions/operator.py
ADDED
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
class Operator(object):
|
2 |
+
"""The Operator class is for operators(+, -, *, / etc)
|
3 |
+
|
4 |
+
Example:
|
5 |
+
'+', '-', '*' etc
|
6 |
+
|
7 |
+
Note:
|
8 |
+
Not to be confused with 'operator' and 'operand' properties of 'Function' class
|
9 |
+
"""
|
10 |
+
|
11 |
+
def __init__(self):
|
12 |
+
self.tid = None
|
13 |
+
self.scope = None
|
14 |
+
self.value = None
|
15 |
+
|
16 |
+
def __str__(self):
|
17 |
+
represent = ""
|
18 |
+
represent += str(self.value)
|
19 |
+
return represent
|
20 |
+
|
21 |
+
def differentiate(self):
|
22 |
+
return self
|
23 |
+
|
24 |
+
|
25 |
+
class Binary(Operator):
|
26 |
+
"""Binary operator takes two operands
|
27 |
+
|
28 |
+
Example:
|
29 |
+
'2 + 2', '5/6' etc
|
30 |
+
|
31 |
+
Extends:
|
32 |
+
Operator
|
33 |
+
"""
|
34 |
+
|
35 |
+
def __init__(self, value=None):
|
36 |
+
super().__init__()
|
37 |
+
if value is not None:
|
38 |
+
self.value = value
|
39 |
+
|
40 |
+
|
41 |
+
class Sqrt(Operator):
|
42 |
+
|
43 |
+
def __init__(self, power=None, operand=None):
|
44 |
+
super().__init__()
|
45 |
+
if power is not None:
|
46 |
+
self.power = power
|
47 |
+
if operand is not None:
|
48 |
+
self.operand = operand
|
49 |
+
|
50 |
+
def __str__(self):
|
51 |
+
represent = ""
|
52 |
+
if self.operand.value == -1:
|
53 |
+
represent += r"\iota "
|
54 |
+
else:
|
55 |
+
represent += r"\sqrt" + self.operand.__str__()
|
56 |
+
return represent
|
57 |
+
|
58 |
+
|
59 |
+
class Plus(Binary):
|
60 |
+
"""Class for '+'
|
61 |
+
|
62 |
+
Extends:
|
63 |
+
Binary
|
64 |
+
"""
|
65 |
+
|
66 |
+
def __init__(self):
|
67 |
+
super().__init__()
|
68 |
+
self.value = '+'
|
69 |
+
|
70 |
+
|
71 |
+
class Minus(Binary):
|
72 |
+
"""Class for '-'
|
73 |
+
|
74 |
+
Extends:
|
75 |
+
Binary
|
76 |
+
"""
|
77 |
+
|
78 |
+
def __init__(self):
|
79 |
+
super().__init__()
|
80 |
+
self.value = '-'
|
81 |
+
|
82 |
+
|
83 |
+
class Multiply(Binary):
|
84 |
+
"""Class for '*'
|
85 |
+
|
86 |
+
Extends:
|
87 |
+
Binary
|
88 |
+
"""
|
89 |
+
|
90 |
+
def __init__(self):
|
91 |
+
super().__init__()
|
92 |
+
self.value = '*'
|
93 |
+
|
94 |
+
|
95 |
+
class Divide(Binary):
|
96 |
+
"""Class for '/'
|
97 |
+
|
98 |
+
Extends:
|
99 |
+
Binary
|
100 |
+
"""
|
101 |
+
|
102 |
+
def __init__(self):
|
103 |
+
super().__init__()
|
104 |
+
self.value = '/'
|
105 |
+
|
106 |
+
|
107 |
+
class EqualTo(Binary):
|
108 |
+
"""Class for '='
|
109 |
+
|
110 |
+
Extends:
|
111 |
+
Binary
|
112 |
+
"""
|
113 |
+
|
114 |
+
def __init__(self):
|
115 |
+
super().__init__()
|
116 |
+
self.value = '='
|
data/visma/functions/structure.py
ADDED
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
|
3 |
+
|
4 |
+
class Function(object):
|
5 |
+
"""Basis function class for all functions
|
6 |
+
|
7 |
+
The Function class forms the basis for the functions tokens of all types.
|
8 |
+
"""
|
9 |
+
|
10 |
+
def __init__(self):
|
11 |
+
self.tid = None
|
12 |
+
self.scope = None
|
13 |
+
self.value = None
|
14 |
+
self.coefficient = 1
|
15 |
+
self.power = 1
|
16 |
+
self.operand = None
|
17 |
+
self.operator = None
|
18 |
+
self.before = None
|
19 |
+
self.after = None
|
20 |
+
self.beforeScope = None
|
21 |
+
self.afterScope = None
|
22 |
+
|
23 |
+
def __str__(self, nv=None, np=None, nc=None):
|
24 |
+
"""Equation token to string
|
25 |
+
|
26 |
+
Coverts equation tokens to string for text and LaTeX rendering
|
27 |
+
|
28 |
+
Keyword Arguments:
|
29 |
+
nv {int} -- number of values (default: {None})
|
30 |
+
np {int} -- number of powers (default: {None})
|
31 |
+
nc {int} -- number of coefficients (default: {None})
|
32 |
+
|
33 |
+
Returns:
|
34 |
+
represent {string} -- string/latex representation of equation
|
35 |
+
"""
|
36 |
+
# OPTIMIZE: Works but a mess. Organize and add comments
|
37 |
+
represent = ""
|
38 |
+
|
39 |
+
if np is None and nv is None and nc is None:
|
40 |
+
if self.coefficient != 1:
|
41 |
+
represent += str(self.coefficient)
|
42 |
+
elif nc is not None:
|
43 |
+
if self.coefficient[nc] != 1:
|
44 |
+
represent += str(self.coefficient[nc])
|
45 |
+
|
46 |
+
if isinstance(self.value, list):
|
47 |
+
if nv is None and np is None:
|
48 |
+
for eachValue, eachPower in zip(self.value, self.power):
|
49 |
+
represent += "{" + str(eachValue) + "}"
|
50 |
+
if eachPower != 1:
|
51 |
+
represent += "^" + "{" + str(eachPower) + "}"
|
52 |
+
elif nc is None:
|
53 |
+
represent += "{" + str(self.value[nv]) + "}"
|
54 |
+
if self.power[np] != 1:
|
55 |
+
represent += "^" + "{" + str(self.power[np]) + "}"
|
56 |
+
elif nc is not None:
|
57 |
+
for i, val in enumerate(self.value):
|
58 |
+
represent += "{" + str(val) + "}"
|
59 |
+
if self.power[np][i] != 1:
|
60 |
+
represent += "^" + "{" + str(self.power[np][i]) + "}"
|
61 |
+
elif self.operand is not None:
|
62 |
+
represent += "\\" + self.value
|
63 |
+
if self.power != 1:
|
64 |
+
represent += "^" + "{" + str(self.power) + "}"
|
65 |
+
represent += "({" + self.operand.__str__() + "})"
|
66 |
+
else:
|
67 |
+
represent += "{" + str(self.value) + "}"
|
68 |
+
if self.power != 1:
|
69 |
+
represent += "^" + "{" + str(self.power) + "}"
|
70 |
+
|
71 |
+
return represent
|
72 |
+
|
73 |
+
def prop(self, tid=None, scope=None, value=None, coeff=None, power=None, operand=None, operator=None):
|
74 |
+
"""Set function token properties
|
75 |
+
|
76 |
+
Keyword Arguments:
|
77 |
+
tid {[type]} -- Token ID (default: {None})
|
78 |
+
scope {int} -- Scope (default: {None})
|
79 |
+
value {int or list} -- Value (default: {None})
|
80 |
+
coeff {int} -- Coefficient (default: {None})
|
81 |
+
power {int or list} -- Power (default: {None})
|
82 |
+
operand {visma.functions.structure.Function} -- Operand (default: {None})
|
83 |
+
operator {visma.functions.structure.Function} -- Operator (default: {None})
|
84 |
+
"""
|
85 |
+
if tid is not None:
|
86 |
+
self.tid = tid
|
87 |
+
if scope is not None:
|
88 |
+
self.scope = scope
|
89 |
+
if value is not None:
|
90 |
+
self.value = value
|
91 |
+
if coeff is not None:
|
92 |
+
self.coefficient = coeff
|
93 |
+
if power is not None:
|
94 |
+
self.power = power
|
95 |
+
if operand is not None:
|
96 |
+
self.operand = operand
|
97 |
+
if operator is not None:
|
98 |
+
self.operator = operator
|
99 |
+
|
100 |
+
def differentiate(self):
|
101 |
+
"""Differentiate function token
|
102 |
+
"""
|
103 |
+
self.power = 1
|
104 |
+
self.coefficient = 1
|
105 |
+
|
106 |
+
def level(self):
|
107 |
+
"""Level of function token
|
108 |
+
"""
|
109 |
+
return (int((len(self.tid)) / 2)), 5
|
110 |
+
|
111 |
+
def functionOf(self):
|
112 |
+
inst = copy.deepcopy(self)
|
113 |
+
while inst.operand is not None:
|
114 |
+
inst = inst.operand
|
115 |
+
return inst.value
|
116 |
+
|
117 |
+
def isZero(self):
|
118 |
+
"""
|
119 |
+
It checks if the Function is equal to Zero or not, to decide it should be Added, Subtracted,...etc. or not.
|
120 |
+
:returns: bool
|
121 |
+
"""
|
122 |
+
if (self.value == 0 and self.power != 0) or self.coefficient == 0:
|
123 |
+
return True
|
124 |
+
return False
|
125 |
+
|
126 |
+
|
127 |
+
##########
|
128 |
+
# FuncOp #
|
129 |
+
##########
|
130 |
+
|
131 |
+
class FuncOp(Function):
|
132 |
+
"""Defined for functions of form sin(...), log(...), exp(...) etc which take a function(operand) as argument
|
133 |
+
"""
|
134 |
+
def __init__(self, operand=None):
|
135 |
+
super().__init__()
|
136 |
+
if operand is not None:
|
137 |
+
self.operand = operand
|
138 |
+
|
139 |
+
def __str__(self):
|
140 |
+
represent = ""
|
141 |
+
represent += "\\" + self.value
|
142 |
+
if self.power != 1:
|
143 |
+
represent += "^" + "{" + str(self.power) + "}"
|
144 |
+
if self.operand is not None:
|
145 |
+
represent += "{(" + str(self.operand) + ")}"
|
146 |
+
return represent
|
147 |
+
|
148 |
+
def inverse(self, rToken, wrtVar, inverseFunction):
|
149 |
+
"""Returns inverse of function
|
150 |
+
|
151 |
+
Applies inverse of function to RHS and LHS.
|
152 |
+
|
153 |
+
Arguments:
|
154 |
+
rToken {visma.functions.structure.Function} -- RHS token
|
155 |
+
wrtVar {string} -- with respect to variable
|
156 |
+
inverseFunction {visma.functions.structure.Function} -- inverse of the function itself
|
157 |
+
|
158 |
+
Returns:
|
159 |
+
self {visma.functions.structure.Function} -- function itself(operand before inverse)
|
160 |
+
rToken {visma.functions.structure.Function} -- new RHS token
|
161 |
+
comment {string} -- steps comment
|
162 |
+
"""
|
163 |
+
rToken.coefficient /= self.coefficient
|
164 |
+
rToken.power /= self.power
|
165 |
+
invFunc = copy.deepcopy(inverseFunction)
|
166 |
+
invFunc.operand = rToken
|
167 |
+
self = self.operand
|
168 |
+
comment = "Applying inverse function on LHS and RHS"
|
169 |
+
return self, rToken, comment
|
170 |
+
|
171 |
+
|
172 |
+
###################
|
173 |
+
# Mixed Functions #
|
174 |
+
###################
|
175 |
+
# For example: sec(x)*tan(x) or sin(x)*log(x) or e^(x)*cot(x)
|
176 |
+
# Will be taken care by function Expression
|
177 |
+
|
178 |
+
|
179 |
+
class Expression(Function):
|
180 |
+
"""Class for expression type
|
181 |
+
"""
|
182 |
+
|
183 |
+
def __init__(self, tokens=None, coefficient=None, power=None):
|
184 |
+
super().__init__()
|
185 |
+
if coefficient is not None:
|
186 |
+
self.coefficient = coefficient
|
187 |
+
else:
|
188 |
+
self.coefficient = 1
|
189 |
+
if power is not None:
|
190 |
+
self.power = power
|
191 |
+
else:
|
192 |
+
self.power = 1
|
193 |
+
self.tokens = []
|
194 |
+
if tokens is not None:
|
195 |
+
self.tokens.extend(tokens)
|
196 |
+
|
197 |
+
def __str__(self):
|
198 |
+
represent = ""
|
199 |
+
if self.coefficient != 1:
|
200 |
+
represent += str(self.coefficient) + "*"
|
201 |
+
represent += "{("
|
202 |
+
for token in self.tokens:
|
203 |
+
represent += token.__str__()
|
204 |
+
represent += ")}"
|
205 |
+
if self.power != 1:
|
206 |
+
represent += "^" + "{" + str(self.power) + "}"
|
207 |
+
if self.operand is not None:
|
208 |
+
represent += "{(" + str(self.operand) + ")}"
|
209 |
+
return represent
|
210 |
+
|
211 |
+
def __mul__(self, other):
|
212 |
+
from visma.functions.constant import Constant
|
213 |
+
from visma.functions.variable import Variable
|
214 |
+
|
215 |
+
if isinstance(other, Expression):
|
216 |
+
result = Expression()
|
217 |
+
for i, _ in enumerate(self.tokens):
|
218 |
+
c = copy.deepcopy(self)
|
219 |
+
d = copy.deepcopy(other)
|
220 |
+
if isinstance(c.tokens[i], Constant) or isinstance(c.tokens[i], Variable):
|
221 |
+
result.tokens.extend([c.tokens[i] * d])
|
222 |
+
else:
|
223 |
+
result.tokens.extend([c.tokens[i]])
|
224 |
+
return result
|
225 |
+
|
226 |
+
def __add__(self, other):
|
227 |
+
from visma.functions.constant import Constant
|
228 |
+
from visma.functions.variable import Variable
|
229 |
+
from visma.functions.operator import Plus
|
230 |
+
if isinstance(other, Expression):
|
231 |
+
result = Expression()
|
232 |
+
for tok1 in self.tokens:
|
233 |
+
result.tokens.append(tok1)
|
234 |
+
result.tokens.append(Plus())
|
235 |
+
if (other.tokens[0], Constant):
|
236 |
+
if (other.tokens[0].value < 0):
|
237 |
+
result.tokens.pop()
|
238 |
+
elif (other.tokens[0], Variable):
|
239 |
+
if (other.tokens[0].coefficient < 0):
|
240 |
+
result.tokens.pop()
|
241 |
+
for tok2 in other.tokens:
|
242 |
+
result.tokens.append(tok2)
|
243 |
+
return result
|
244 |
+
elif isinstance(other, Constant):
|
245 |
+
result = self
|
246 |
+
constFound = False
|
247 |
+
for i, _ in enumerate(self.tokens):
|
248 |
+
if isinstance(self.tokens[i], Constant):
|
249 |
+
self.tokens[i] += other
|
250 |
+
constFound = True
|
251 |
+
if constFound:
|
252 |
+
return result
|
253 |
+
else:
|
254 |
+
result.tokens += other
|
255 |
+
return result
|
256 |
+
elif isinstance(other, Variable):
|
257 |
+
result = Expression()
|
258 |
+
result = other + self
|
259 |
+
return result
|
260 |
+
|
261 |
+
def __sub__(self, other):
|
262 |
+
from visma.functions.constant import Constant
|
263 |
+
from visma.functions.variable import Variable
|
264 |
+
from visma.functions.operator import Plus, Minus
|
265 |
+
if isinstance(other, Expression):
|
266 |
+
result = Expression()
|
267 |
+
for tok1 in self.tokens:
|
268 |
+
result.tokens.append(tok1)
|
269 |
+
for _, x in enumerate(other.tokens):
|
270 |
+
if x.value == '+':
|
271 |
+
x.value = '-'
|
272 |
+
elif x.value == '-':
|
273 |
+
x.value = '+'
|
274 |
+
result.tokens.append(Minus())
|
275 |
+
if (isinstance(other.tokens[0], Constant)):
|
276 |
+
if (other.tokens[0].value < 0):
|
277 |
+
result.tokens[-1] = Plus()
|
278 |
+
other.tokens[0].value = abs(other.tokens[0].value)
|
279 |
+
elif (isinstance(other.tokens[0], Variable)):
|
280 |
+
if (other.tokens[0].coefficient < 0):
|
281 |
+
result.tokens[-1] = Plus()
|
282 |
+
other.tokens[0].coefficient = abs(other.tokens[0].coefficient)
|
283 |
+
return result
|
284 |
+
elif isinstance(other, Constant):
|
285 |
+
result = self
|
286 |
+
result += (Constant(0) - other)
|
287 |
+
return result
|
288 |
+
elif isinstance(other, Variable):
|
289 |
+
result = self
|
290 |
+
a = Constant(0) - other
|
291 |
+
result = a + result
|
292 |
+
return result
|
293 |
+
|
294 |
+
|
295 |
+
class Equation(Expression):
|
296 |
+
"""Class for equation type
|
297 |
+
"""
|
298 |
+
|
299 |
+
def __init__(self):
|
300 |
+
super().__init__()
|
301 |
+
self.tokens = None
|
data/visma/functions/trigonometry.py
ADDED
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import copy
|
3 |
+
from visma.functions.structure import FuncOp, Expression
|
4 |
+
from visma.functions.operator import Multiply, Plus
|
5 |
+
from visma.functions.constant import Constant
|
6 |
+
from visma.functions. exponential import NaturalLog
|
7 |
+
|
8 |
+
##########################
|
9 |
+
# Trignometric Functions #
|
10 |
+
##########################
|
11 |
+
|
12 |
+
|
13 |
+
class Trigonometric(FuncOp):
|
14 |
+
"""Parent Class for all the Trigonometric Classes like Sine, Cosine, Tangent etc.
|
15 |
+
|
16 |
+
"""
|
17 |
+
pass
|
18 |
+
|
19 |
+
|
20 |
+
class Sine(Trigonometric):
|
21 |
+
"""Class for sin function -- sin(...)
|
22 |
+
|
23 |
+
Extends:
|
24 |
+
Trigonometric
|
25 |
+
"""
|
26 |
+
|
27 |
+
def __init__(self):
|
28 |
+
super().__init__()
|
29 |
+
self.value = 'sin'
|
30 |
+
|
31 |
+
def inverse(self, rToken, wrtVar, inverseFunction=None):
|
32 |
+
inverseFunction = ArcSin()
|
33 |
+
super().inverse(self, rToken, wrtVar, inverseFunction)
|
34 |
+
|
35 |
+
def calculate(self, val):
|
36 |
+
return self.coefficient * ((math.sin(val))**self.power)
|
37 |
+
|
38 |
+
def differentiate(self, wrtVar=None):
|
39 |
+
super().differentiate()
|
40 |
+
result = copy.deepcopy(self)
|
41 |
+
result.__class__ = Cosine
|
42 |
+
result.value = 'cos'
|
43 |
+
result.coefficient = 1
|
44 |
+
return result
|
45 |
+
|
46 |
+
def integrate(self, wrtVar=None):
|
47 |
+
term1 = Constant(-1, 1, 1)
|
48 |
+
term2 = copy.deepcopy(self)
|
49 |
+
term2.__class__ = Cosine
|
50 |
+
term2.value = 'cos'
|
51 |
+
term2.coefficient = 1
|
52 |
+
result = Expression()
|
53 |
+
result.tokens = [term1, Multiply(), term2]
|
54 |
+
return result
|
55 |
+
|
56 |
+
|
57 |
+
class Cosine(Trigonometric):
|
58 |
+
"""Class for cos function -- cos(...)
|
59 |
+
|
60 |
+
Extends:
|
61 |
+
Trigonometric
|
62 |
+
"""
|
63 |
+
|
64 |
+
def __init__(self):
|
65 |
+
super().__init__()
|
66 |
+
self.value = 'cos'
|
67 |
+
|
68 |
+
def inverse(self, RHS):
|
69 |
+
super().inverse(RHS)
|
70 |
+
self.__class__ = ArcCos
|
71 |
+
|
72 |
+
def differentiate(self, wrtVar):
|
73 |
+
term1 = Constant(-1, 1, 1)
|
74 |
+
term2 = copy.deepcopy(self)
|
75 |
+
term2.__class__ = Sine
|
76 |
+
term2.value = 'sin'
|
77 |
+
result = Expression()
|
78 |
+
result.tokens = [term1, Multiply(), term2]
|
79 |
+
return result
|
80 |
+
|
81 |
+
def integrate(self, wrtVar):
|
82 |
+
result = copy.deepcopy(self)
|
83 |
+
result.__class__ = Sine
|
84 |
+
result.value = 'sin'
|
85 |
+
result.coefficient = 1
|
86 |
+
return result
|
87 |
+
|
88 |
+
def calculate(self, val):
|
89 |
+
return self.coefficient * ((math.cos(val))**self.power)
|
90 |
+
|
91 |
+
|
92 |
+
class Tangent(Trigonometric):
|
93 |
+
"""Class for tan function -- tan(...)
|
94 |
+
|
95 |
+
Extends:
|
96 |
+
Trigonometric
|
97 |
+
"""
|
98 |
+
|
99 |
+
def __init__(self):
|
100 |
+
super().__init__()
|
101 |
+
self.value = 'tan'
|
102 |
+
|
103 |
+
def inverse(self, RHS):
|
104 |
+
super().inverse(RHS)
|
105 |
+
self.__class__ = ArcTan
|
106 |
+
|
107 |
+
def differentiate(self, wrtVar):
|
108 |
+
result = copy.deepcopy(self)
|
109 |
+
result.__class__ = Secant
|
110 |
+
result.value = 'sec'
|
111 |
+
result.coefficient = 1
|
112 |
+
result.power = 2
|
113 |
+
return result
|
114 |
+
|
115 |
+
def integrate(self, wrtVar):
|
116 |
+
term1 = Constant(-1, 1, 1)
|
117 |
+
term2 = NaturalLog()
|
118 |
+
term3 = Cosine()
|
119 |
+
term3.operand = self.operand
|
120 |
+
term2.operand = term3
|
121 |
+
term2.power = 1
|
122 |
+
term2.coefficient = 1
|
123 |
+
result = Expression()
|
124 |
+
result.tokens = [term1, Multiply(), term2]
|
125 |
+
return result
|
126 |
+
|
127 |
+
def calculate(self, val):
|
128 |
+
return self.coefficient * ((math.tan(val))**self.power)
|
129 |
+
|
130 |
+
|
131 |
+
class Cotangent(Trigonometric):
|
132 |
+
"""Class for cot function -- cot(...)
|
133 |
+
|
134 |
+
Extends:
|
135 |
+
Trigonometric
|
136 |
+
"""
|
137 |
+
|
138 |
+
def __init__(self):
|
139 |
+
super().__init__()
|
140 |
+
self.value = 'cot'
|
141 |
+
|
142 |
+
def inverse(self, RHS):
|
143 |
+
super().inverse(RHS)
|
144 |
+
self.__class__ = ArcCot
|
145 |
+
|
146 |
+
def differentiate(self, wrtVar):
|
147 |
+
term1 = Constant(-1, 1, 1)
|
148 |
+
term2 = copy.deepcopy(self)
|
149 |
+
term2.__class__ = Cosecant
|
150 |
+
term2.value = 'csc'
|
151 |
+
term2.coefficient = 1
|
152 |
+
term2.power = 2
|
153 |
+
result = Expression()
|
154 |
+
result.tokens = [term1, Multiply(), term2]
|
155 |
+
return result
|
156 |
+
|
157 |
+
def integrate(self, wrtVar):
|
158 |
+
result = NaturalLog()
|
159 |
+
term1 = Sine()
|
160 |
+
term1.operand = self.operand
|
161 |
+
term1.power = 1
|
162 |
+
term1.coefficient = 1
|
163 |
+
result.operand = term1
|
164 |
+
return result
|
165 |
+
|
166 |
+
def calculate(self, val):
|
167 |
+
return self.coefficient * ((math.cot(val))**self.power)
|
168 |
+
|
169 |
+
|
170 |
+
class Cosecant(Trigonometric):
|
171 |
+
"""Class for csc function -- csc(...)
|
172 |
+
|
173 |
+
Extends:
|
174 |
+
Trigonometric
|
175 |
+
"""
|
176 |
+
|
177 |
+
def __init__(self):
|
178 |
+
super().__init__()
|
179 |
+
self.value = 'csc'
|
180 |
+
|
181 |
+
def inverse(self, RHS):
|
182 |
+
super().inverse(RHS)
|
183 |
+
self.__class__ = ArcCosec
|
184 |
+
|
185 |
+
def differentiate(self, wrtVar):
|
186 |
+
term1 = Constant(-1, 1, 1)
|
187 |
+
term2 = Cosecant()
|
188 |
+
term2.operand = self.operand
|
189 |
+
term2.coefficient = 1
|
190 |
+
term3 = Cotangent()
|
191 |
+
term3.operand = self.operand
|
192 |
+
term3.coefficient = 1
|
193 |
+
result = Expression()
|
194 |
+
result.tokens = [term1, Multiply(), term2, Multiply(), term3]
|
195 |
+
return result
|
196 |
+
|
197 |
+
def integrate(self, wrtVar):
|
198 |
+
term1 = Constant(-1, 1, 1)
|
199 |
+
term2 = NaturalLog()
|
200 |
+
result = Expression()
|
201 |
+
term3 = Cosecant()
|
202 |
+
term3.operand = self.operand
|
203 |
+
term4 = Cotangent()
|
204 |
+
term4.operand = self.operand
|
205 |
+
inExpression = Expression()
|
206 |
+
inExpression.tokens = [term3, Plus(), term4]
|
207 |
+
term2.operand = inExpression
|
208 |
+
term2.power = 1
|
209 |
+
term2.coefficient = 1
|
210 |
+
result.tokens = [term1, Multiply(), term2]
|
211 |
+
return result
|
212 |
+
|
213 |
+
def __mul__(self, other):
|
214 |
+
if isinstance(other, Cotangent):
|
215 |
+
result = Expression()
|
216 |
+
result.coefficient = self.coefficient * other.coefficient
|
217 |
+
c = copy.deepcopy(self)
|
218 |
+
d = copy.deepcopy(other)
|
219 |
+
result.tokens.extend([c, Multiply(), d])
|
220 |
+
return result
|
221 |
+
|
222 |
+
def calculate(self, val):
|
223 |
+
return self.coefficient * ((math.cosec(val))**self.power)
|
224 |
+
|
225 |
+
|
226 |
+
class Secant(Trigonometric):
|
227 |
+
"""Class for sec function -- sec(...)
|
228 |
+
|
229 |
+
Extends:
|
230 |
+
Trigonometric
|
231 |
+
"""
|
232 |
+
|
233 |
+
def __init__(self):
|
234 |
+
super().__init__()
|
235 |
+
self.value = 'sec'
|
236 |
+
|
237 |
+
def inverse(self, RHS):
|
238 |
+
super().inverse(RHS)
|
239 |
+
self.__class__ = ArcSec
|
240 |
+
|
241 |
+
def differentiate(self, wrtVar):
|
242 |
+
term1 = Tangent()
|
243 |
+
term1.operand = self.operand
|
244 |
+
term2 = Secant()
|
245 |
+
term2.operand = self.operand
|
246 |
+
resultTerm = term2 * term1
|
247 |
+
return resultTerm
|
248 |
+
|
249 |
+
def integrate(self, wrtVar):
|
250 |
+
resultTerm = NaturalLog()
|
251 |
+
term3 = Secant()
|
252 |
+
term3.operand = self.operand
|
253 |
+
term4 = Tangent()
|
254 |
+
term4.operand = self.operand
|
255 |
+
inExpression = Expression()
|
256 |
+
inExpression.tokens = [term3, Plus(), term4]
|
257 |
+
resultTerm.operand = inExpression
|
258 |
+
resultTerm.power = 1
|
259 |
+
resultTerm.coefficient = 1
|
260 |
+
return resultTerm
|
261 |
+
|
262 |
+
def __mul__(self, other):
|
263 |
+
if isinstance(other, Tangent):
|
264 |
+
result = Expression()
|
265 |
+
Expression.coefficient = self.coefficient * other.coefficient
|
266 |
+
c = copy.deepcopy(self)
|
267 |
+
d = copy.deepcopy(other)
|
268 |
+
result.tokens.extend([c, Multiply(), d])
|
269 |
+
return result
|
270 |
+
|
271 |
+
def calculate(self, val):
|
272 |
+
return self.coefficient * ((math.sec(val))**self.power)
|
273 |
+
|
274 |
+
##################################
|
275 |
+
# Inverse Trignometric Functions #
|
276 |
+
##################################
|
277 |
+
|
278 |
+
|
279 |
+
class ArcSin(Trigonometric):
|
280 |
+
pass
|
281 |
+
|
282 |
+
|
283 |
+
class ArcCos(Trigonometric):
|
284 |
+
pass
|
285 |
+
|
286 |
+
|
287 |
+
class ArcTan(Trigonometric):
|
288 |
+
pass
|
289 |
+
|
290 |
+
|
291 |
+
class ArcCot(Trigonometric):
|
292 |
+
pass
|
293 |
+
|
294 |
+
|
295 |
+
class ArcSec(Trigonometric):
|
296 |
+
pass
|
297 |
+
|
298 |
+
|
299 |
+
class ArcCsc(Trigonometric):
|
300 |
+
pass
|
data/visma/functions/variable.py
ADDED
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
from visma.functions.structure import Function, Expression
|
3 |
+
from visma.functions.exponential import Logarithm
|
4 |
+
from visma.functions.operator import Plus, Minus, Multiply, Divide, Binary
|
5 |
+
|
6 |
+
|
7 |
+
############
|
8 |
+
# Variable #
|
9 |
+
############
|
10 |
+
|
11 |
+
|
12 |
+
class Variable(Function):
|
13 |
+
"""Class for variable function type
|
14 |
+
|
15 |
+
Examples:
|
16 |
+
x
|
17 |
+
2x^2
|
18 |
+
3xyz^3
|
19 |
+
|
20 |
+
Extends:
|
21 |
+
Function
|
22 |
+
"""
|
23 |
+
|
24 |
+
def __init__(self, coeff=None, value=None, power=None):
|
25 |
+
super().__init__()
|
26 |
+
# Report
|
27 |
+
self.coefficient = 1
|
28 |
+
if coeff is not None:
|
29 |
+
self.coefficient = coeff
|
30 |
+
self.value = []
|
31 |
+
if value is not None:
|
32 |
+
self.value.append(value)
|
33 |
+
self.power = []
|
34 |
+
if power is not None:
|
35 |
+
self.power.append(power)
|
36 |
+
|
37 |
+
def inverse(self, rToken, wrtVar):
|
38 |
+
l2rVar = Variable()
|
39 |
+
for i, var in enumerate(self.value):
|
40 |
+
if var != wrtVar:
|
41 |
+
l2rVar.value.append(self.value.pop(i))
|
42 |
+
l2rVar.power.append(self.power.pop(i))
|
43 |
+
if l2rVar.value != []:
|
44 |
+
rToken = Expression([rToken, Divide(), l2rVar])
|
45 |
+
rToken.coefficient /= (self.coefficient)**(1/self.power[0])
|
46 |
+
rToken.power /= self.power[0]
|
47 |
+
self.coefficient = 1
|
48 |
+
self.power[0] = 1
|
49 |
+
comment = "Therefore, " + r"$" + wrtVar + r"$" + " can be written as:"
|
50 |
+
return self, rToken, comment
|
51 |
+
|
52 |
+
def differentiate(self, wrtVar):
|
53 |
+
from visma.functions.constant import Constant, Zero
|
54 |
+
result = copy.deepcopy(self)
|
55 |
+
if wrtVar in result.functionOf():
|
56 |
+
for i, var in enumerate(result.value):
|
57 |
+
if var == wrtVar:
|
58 |
+
result.coefficient *= result.power[i]
|
59 |
+
result.power[i] -= 1
|
60 |
+
if(result.power[i] == 0):
|
61 |
+
del result.power[i]
|
62 |
+
del result.value[i]
|
63 |
+
if result.value == []:
|
64 |
+
result.__class__ = Constant
|
65 |
+
result.value = result.coefficient
|
66 |
+
result.coefficient = 1
|
67 |
+
result.power = 1
|
68 |
+
else:
|
69 |
+
result = Zero()
|
70 |
+
return result
|
71 |
+
|
72 |
+
def integrate(self, wrtVar=None):
|
73 |
+
from visma.functions.constant import Constant
|
74 |
+
result = copy.deepcopy(self)
|
75 |
+
log = False
|
76 |
+
for i, var in enumerate(result.value):
|
77 |
+
if var == wrtVar:
|
78 |
+
if(result.power[i] == -1):
|
79 |
+
log = True
|
80 |
+
funcLog = Logarithm()
|
81 |
+
funcLog.operand = Variable()
|
82 |
+
funcLog.operand.coefficient = 1
|
83 |
+
funcLog.operand.value.append(result.value[i])
|
84 |
+
funcLog.operand.power.append(1)
|
85 |
+
del result.power[i]
|
86 |
+
del result.value[i]
|
87 |
+
if result.value == []:
|
88 |
+
result.__class__ = Constant
|
89 |
+
result.value = result.coefficient
|
90 |
+
result.coefficient = 1
|
91 |
+
result.power = 1
|
92 |
+
result = [result]
|
93 |
+
funcJoin = Binary()
|
94 |
+
funcJoin.value = '*'
|
95 |
+
result.append(funcJoin)
|
96 |
+
result.append(funcLog)
|
97 |
+
else:
|
98 |
+
result.power[i] += 1
|
99 |
+
result.coefficient /= result.power[i]
|
100 |
+
print(result)
|
101 |
+
return result, log
|
102 |
+
|
103 |
+
def calculate(self, val):
|
104 |
+
return self.coefficient * ((val**(self.power)))
|
105 |
+
|
106 |
+
def __radd__(self, other):
|
107 |
+
return self + other
|
108 |
+
|
109 |
+
def __add__(self, other):
|
110 |
+
from visma.functions.constant import Constant
|
111 |
+
if isinstance(other, Variable):
|
112 |
+
sortedValuesSelf = sorted(self.value)
|
113 |
+
sortedValuesOther = sorted(other.value)
|
114 |
+
if self.coefficient == 0:
|
115 |
+
return Constant(0, 1, 1)
|
116 |
+
if (self.power == other.power) & (sortedValuesSelf == sortedValuesOther):
|
117 |
+
if self.before == '-':
|
118 |
+
self.coefficient -= other.coefficient
|
119 |
+
else:
|
120 |
+
self.coefficient += other.coefficient
|
121 |
+
return self
|
122 |
+
elif isinstance(other, Constant):
|
123 |
+
expression = Expression()
|
124 |
+
expression.tokens = [self]
|
125 |
+
expression.tokens.extend([Plus(), other])
|
126 |
+
self = expression
|
127 |
+
return expression
|
128 |
+
elif isinstance(other, Expression):
|
129 |
+
expression = Expression()
|
130 |
+
expression.tokens = [self]
|
131 |
+
for i, token in enumerate(other.tokens):
|
132 |
+
if isinstance(token, Variable):
|
133 |
+
tokenValueSorted = sorted(token.value)
|
134 |
+
selfValueSorted = sorted(self.value)
|
135 |
+
if (token.power == self.power) & (tokenValueSorted == selfValueSorted):
|
136 |
+
if other.tokens[i - 1].value == '+' or (i == 0):
|
137 |
+
self.coefficient += other.tokens[i].coefficient
|
138 |
+
elif other.tokens[i - 1].value == '-':
|
139 |
+
self.coefficient -= other.tokens[i].coefficient
|
140 |
+
else:
|
141 |
+
if other.tokens[i-1].value == '+' or i == 0:
|
142 |
+
expression.tokens.extend([Plus(), Variable(token)])
|
143 |
+
elif other.tokens[i-1].value == '-':
|
144 |
+
expression.tokens.extend([Minus(), Variable(token)])
|
145 |
+
elif not isinstance(token, Binary):
|
146 |
+
if other.tokens[i - 1].value == '+' or (i == 0):
|
147 |
+
expression.tokens.extend([Plus(), token])
|
148 |
+
elif other.tokens[i - 1].value == '-':
|
149 |
+
expression.tokens.extend([Minus(), token])
|
150 |
+
expression.tokens[0] = self
|
151 |
+
self = expression
|
152 |
+
return expression
|
153 |
+
|
154 |
+
def __rsub__(self, other):
|
155 |
+
from visma.functions.constant import Constant
|
156 |
+
return Constant(0, 1, 1) - self + other
|
157 |
+
|
158 |
+
def __sub__(self, other):
|
159 |
+
from visma.functions.constant import Constant
|
160 |
+
if isinstance(other, Variable):
|
161 |
+
otherValueSorted = sorted(other.value)
|
162 |
+
selfValueSorted = sorted(self.value)
|
163 |
+
if (other.power == self.power) & (selfValueSorted == otherValueSorted):
|
164 |
+
self = self + Constant(-1, 1, 1) * other
|
165 |
+
return self
|
166 |
+
else:
|
167 |
+
expression = Expression()
|
168 |
+
expression.tokens = [self]
|
169 |
+
expression.tokens.extend([Minus(), other])
|
170 |
+
self = expression
|
171 |
+
return expression
|
172 |
+
elif isinstance(other, Constant):
|
173 |
+
if other.isZero():
|
174 |
+
return self
|
175 |
+
expression = Expression()
|
176 |
+
expression.tokens = [self]
|
177 |
+
expression.tokens.extend([Minus(), other])
|
178 |
+
self = expression
|
179 |
+
return expression
|
180 |
+
elif isinstance(other, Expression):
|
181 |
+
expression = Expression()
|
182 |
+
expression.tokens = [self]
|
183 |
+
for i, token in enumerate(other.tokens):
|
184 |
+
if isinstance(token, Variable):
|
185 |
+
tokenValueSorted = sorted(token.value)
|
186 |
+
selfValueSorted = sorted(self.value)
|
187 |
+
if (token.power == self.power) & (tokenValueSorted == selfValueSorted):
|
188 |
+
if other.tokens[i - 1].value == '+' or (i == 0):
|
189 |
+
self.coefficient -= other.tokens[i].coefficient
|
190 |
+
elif other.tokens[i - 1].value == '-':
|
191 |
+
self.coefficient += other.tokens[i].coefficient
|
192 |
+
else:
|
193 |
+
if other.tokens[i-1].value == '+' or i == 0:
|
194 |
+
expression.tokens.extend([Plus(), Variable(token)])
|
195 |
+
elif other.tokens[i-1].value == '-':
|
196 |
+
expression.tokens.extend([Minus(), Variable(token)])
|
197 |
+
elif not isinstance(token, Binary):
|
198 |
+
if other.tokens[i - 1].value == '+' or (i == 0):
|
199 |
+
expression.tokens.extend([Minus(), token])
|
200 |
+
elif other.tokens[i - 1].value == '-':
|
201 |
+
expression.tokens.extend([Plus(), token])
|
202 |
+
expression.tokens[0] = self
|
203 |
+
self = expression
|
204 |
+
return expression
|
205 |
+
|
206 |
+
def __rmul__(self, other):
|
207 |
+
return self * other
|
208 |
+
|
209 |
+
def __mul__(self, other):
|
210 |
+
from visma.io.checks import isNumber
|
211 |
+
from visma.functions.constant import Constant
|
212 |
+
|
213 |
+
if isinstance(other, Variable):
|
214 |
+
for j, var in enumerate(other.value):
|
215 |
+
found = False
|
216 |
+
for k, var2 in enumerate(self.value):
|
217 |
+
self.coefficient *= other.coefficient
|
218 |
+
if var == var2:
|
219 |
+
if isNumber(other.power[j]) and isNumber(self.power[k]):
|
220 |
+
self.power[k] += other.power[j]
|
221 |
+
if self.power[k] == 0:
|
222 |
+
del self.power[k]
|
223 |
+
del self.value[k]
|
224 |
+
found = True
|
225 |
+
break
|
226 |
+
if not found:
|
227 |
+
self.value.append(other.value[j])
|
228 |
+
self.power.append(other.power[j])
|
229 |
+
|
230 |
+
if len(self.value) == 0:
|
231 |
+
result = Constant(self.coefficient)
|
232 |
+
result.scope = self.scope
|
233 |
+
result.power = 1
|
234 |
+
result.value = self.coefficient
|
235 |
+
self = result
|
236 |
+
return self
|
237 |
+
elif isinstance(other, Constant):
|
238 |
+
self.coefficient *= other.calculate()
|
239 |
+
return self
|
240 |
+
elif isinstance(other, Expression):
|
241 |
+
result = Expression()
|
242 |
+
for _, token in enumerate(other.tokens):
|
243 |
+
if isinstance(token, Variable) or isinstance(token, Constant):
|
244 |
+
c = copy.deepcopy(self)
|
245 |
+
result.tokens.extend([c * token])
|
246 |
+
else:
|
247 |
+
result.tokens.extend([token])
|
248 |
+
return result
|
249 |
+
|
250 |
+
def __pow__(self, other):
|
251 |
+
from visma.functions.constant import Constant
|
252 |
+
|
253 |
+
if isinstance(other, Constant):
|
254 |
+
if other.value == -1:
|
255 |
+
one = Constant(1, 1, 1)
|
256 |
+
result = Variable()
|
257 |
+
result.value = self.value
|
258 |
+
result.coefficient = one.calculate() / self.coefficient
|
259 |
+
result.power = []
|
260 |
+
for pows in self.power:
|
261 |
+
result.power.append(-pows)
|
262 |
+
return result
|
263 |
+
|
264 |
+
def __rtruediv__(self, other):
|
265 |
+
pass # TODO : Add code for expression / variable
|
266 |
+
|
267 |
+
def __truediv__(self, other):
|
268 |
+
from visma.functions.constant import Constant
|
269 |
+
if isinstance(other, Variable) or isinstance(other, Constant):
|
270 |
+
self = self * (other ** Constant(-1, 1, 1))
|
271 |
+
return self
|
272 |
+
|
273 |
+
elif isinstance(other, Expression):
|
274 |
+
expression = Expression()
|
275 |
+
self.coefficient /= other.coefficient
|
276 |
+
other.power *= -1
|
277 |
+
expression.tokens = [self]
|
278 |
+
expression.tokens.extend([Multiply(), other])
|
279 |
+
self = expression
|
280 |
+
return expression
|
data/visma/gui/__init__.py
ADDED
File without changes
|
data/visma/gui/cli.py
ADDED
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import sys
|
3 |
+
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QTabWidget, QVBoxLayout
|
4 |
+
from visma.calculus.differentiation import differentiate
|
5 |
+
from visma.calculus.integration import integrate
|
6 |
+
from visma.discreteMaths.combinatorics import factorial, combination, permutation
|
7 |
+
from visma.io.checks import checkTypes
|
8 |
+
from visma.io.tokenize import tokenizer, getLHSandRHS
|
9 |
+
from visma.io.parser import resultStringCLI, resultMatrixString
|
10 |
+
from visma.simplify.simplify import simplify, simplifyEquation
|
11 |
+
from visma.simplify.addsub import addition, additionEquation, subtraction, subtractionEquation
|
12 |
+
from visma.simplify.muldiv import multiplication, multiplicationEquation, division, divisionEquation
|
13 |
+
from visma.solvers.solve import solveFor
|
14 |
+
from visma.solvers.polynomial.roots import rootFinder
|
15 |
+
from visma.solvers.simulEqn import simulSolver
|
16 |
+
from visma.transform.factorization import factorize
|
17 |
+
from visma.matrix.structure import Matrix, SquareMat
|
18 |
+
from visma.matrix.operations import simplifyMatrix, addMatrix, subMatrix, multiplyMatrix
|
19 |
+
from visma.gui.plotter import plotFigure2D, plotFigure3D, plot
|
20 |
+
|
21 |
+
|
22 |
+
class App(QMainWindow):
|
23 |
+
def __init__(self, tokens):
|
24 |
+
super().__init__()
|
25 |
+
self.setWindowTitle('Plots')
|
26 |
+
self.setGeometry(300, 300, 450, 450)
|
27 |
+
self.table_widget = PlotWindow(self, tokens)
|
28 |
+
self.setCentralWidget(self.table_widget)
|
29 |
+
self.show()
|
30 |
+
|
31 |
+
|
32 |
+
class PlotWindow(QWidget):
|
33 |
+
def __init__(self, parent, tokens):
|
34 |
+
super(QWidget, self).__init__(parent)
|
35 |
+
self.layout = QVBoxLayout(self)
|
36 |
+
self.tabPlot = QTabWidget()
|
37 |
+
self.tabPlot.tab1 = QWidget()
|
38 |
+
self.tabPlot.tab2 = QWidget()
|
39 |
+
self.tabPlot.resize(300, 200)
|
40 |
+
self.tabPlot.addTab(self.tabPlot.tab1, "2D-Plot")
|
41 |
+
self.tabPlot.addTab(self.tabPlot.tab2, "3D-Plot")
|
42 |
+
self.tabPlot.tab1.setLayout(plotFigure2D(self))
|
43 |
+
self.tabPlot.tab2.setLayout(plotFigure3D(self))
|
44 |
+
self.layout.addWidget(self.tabPlot)
|
45 |
+
plot(self, tokens)
|
46 |
+
|
47 |
+
|
48 |
+
def commandExec(command):
|
49 |
+
operation = command.split('(', 1)[0]
|
50 |
+
inputEquation = command.split('(', 1)[1][:-1]
|
51 |
+
matrix = False # True when matrices operations are present in the code.
|
52 |
+
if operation[0:4] == 'mat_':
|
53 |
+
matrix = True
|
54 |
+
|
55 |
+
if not matrix:
|
56 |
+
"""
|
57 |
+
This part handles the cases when VisMa is NOT dealing with matrices.
|
58 |
+
|
59 |
+
Boolean flags used in code below:
|
60 |
+
simul -- {True} when VisMa is dealing with simultaneous equations & {False} in all other cases
|
61 |
+
"""
|
62 |
+
varName = None
|
63 |
+
if ',' in inputEquation:
|
64 |
+
varName = inputEquation.split(',')[1]
|
65 |
+
varName = "".join(varName.split())
|
66 |
+
inputEquation = inputEquation.split(',')[0]
|
67 |
+
|
68 |
+
simul = False # True when simultaneous equation is present
|
69 |
+
if (inputEquation.count(';') == 2) and (operation == 'solve'):
|
70 |
+
simul = True
|
71 |
+
afterSplit = inputEquation.split(';')
|
72 |
+
eqStr1 = afterSplit[0]
|
73 |
+
eqStr2 = afterSplit[1]
|
74 |
+
eqStr3 = afterSplit[2]
|
75 |
+
|
76 |
+
lhs = []
|
77 |
+
rhs = []
|
78 |
+
solutionType = ''
|
79 |
+
lTokens = []
|
80 |
+
rTokens = []
|
81 |
+
equationTokens = []
|
82 |
+
comments = []
|
83 |
+
if simul:
|
84 |
+
tokens = [tokenizer(eqStr1), tokenizer(eqStr2), tokenizer(eqStr3)]
|
85 |
+
else:
|
86 |
+
tokens = tokenizer(inputEquation)
|
87 |
+
if '=' in inputEquation:
|
88 |
+
lhs, rhs = getLHSandRHS(tokens)
|
89 |
+
lTokens = lhs
|
90 |
+
rTokens = rhs
|
91 |
+
_, solutionType = checkTypes(lhs, rhs)
|
92 |
+
else:
|
93 |
+
solutionType = 'expression'
|
94 |
+
lhs, rhs = getLHSandRHS(tokens)
|
95 |
+
lTokens = lhs
|
96 |
+
rTokens = rhs
|
97 |
+
|
98 |
+
if operation == 'plot':
|
99 |
+
app = QApplication(sys.argv)
|
100 |
+
App(tokens)
|
101 |
+
sys.exit(app.exec_())
|
102 |
+
elif operation == 'simplify':
|
103 |
+
if solutionType == 'expression':
|
104 |
+
tokens, _, _, equationTokens, comments = simplify(tokens)
|
105 |
+
else:
|
106 |
+
lTokens, rTokens, _, _, equationTokens, comments = simplifyEquation(lTokens, rTokens)
|
107 |
+
elif operation == 'addition':
|
108 |
+
if solutionType == 'expression':
|
109 |
+
tokens, _, _, equationTokens, comments = addition(tokens, True)
|
110 |
+
else:
|
111 |
+
lTokens, rTokens, _, _, equationTokens, comments = additionEquation(lTokens, rTokens, True)
|
112 |
+
elif operation == 'subtraction':
|
113 |
+
if solutionType == 'expression':
|
114 |
+
tokens, _, _, equationTokens, comments = subtraction(tokens, True)
|
115 |
+
else:
|
116 |
+
lTokens, rTokens, _, _, equationTokens, comments = subtractionEquation(lTokens, rTokens, True)
|
117 |
+
elif operation == 'multiplication':
|
118 |
+
if solutionType == 'expression':
|
119 |
+
tokens, _, _, equationTokens, comments = multiplication(tokens, True)
|
120 |
+
else:
|
121 |
+
lTokens, rTokens, _, _, equationTokens, comments = multiplicationEquation(lTokens, rTokens, True)
|
122 |
+
elif operation == 'division':
|
123 |
+
if solutionType == 'expression':
|
124 |
+
tokens, _, _, equationTokens, comments = division(tokens, True)
|
125 |
+
else:
|
126 |
+
lTokens, rTokens, _, _, equationTokens, comments = divisionEquation(lTokens, rTokens, True)
|
127 |
+
elif operation == 'factorize':
|
128 |
+
tokens, _, _, equationTokens, comments = factorize(tokens)
|
129 |
+
elif operation == 'find-roots':
|
130 |
+
lTokens, rTokens, _, _, equationTokens, comments = rootFinder(lTokens, rTokens)
|
131 |
+
elif operation == 'solve':
|
132 |
+
if simul:
|
133 |
+
if varName is not None:
|
134 |
+
_, equationTokens, comments = simulSolver(tokens[0], tokens[1], tokens[2], varName)
|
135 |
+
else:
|
136 |
+
_, equationTokens, comments = simulSolver(tokens[0], tokens[1], tokens[2])
|
137 |
+
solutionType = equationTokens
|
138 |
+
else:
|
139 |
+
lhs, rhs = getLHSandRHS(tokens)
|
140 |
+
lTokens, rTokens, _, _, equationTokens, comments = solveFor(lTokens, rTokens, varName)
|
141 |
+
elif operation == 'factorial':
|
142 |
+
tokens, _, _, equationTokens, comments = factorial(tokens)
|
143 |
+
elif operation == 'combination':
|
144 |
+
n = tokenizer(inputEquation)
|
145 |
+
r = tokenizer(varName)
|
146 |
+
tokens, _, _, equationTokens, comments = combination(n, r)
|
147 |
+
elif operation == 'permutation':
|
148 |
+
n = tokenizer(inputEquation)
|
149 |
+
r = tokenizer(varName)
|
150 |
+
tokens, _, _, equationTokens, comments = permutation(n, r)
|
151 |
+
elif operation == 'integrate':
|
152 |
+
lhs, rhs = getLHSandRHS(tokens)
|
153 |
+
lTokens, _, _, equationTokens, comments = integrate(lTokens, varName)
|
154 |
+
elif operation == 'differentiate':
|
155 |
+
lhs, rhs = getLHSandRHS(tokens)
|
156 |
+
lTokens, _, _, equationTokens, comments = differentiate(lTokens, varName)
|
157 |
+
if operation != 'plot':
|
158 |
+
# FIXME: when either plotting window or GUI window is opened from CLI and after it is closed entire CLI exits, it would be better if it is avoided
|
159 |
+
final_string = resultStringCLI(equationTokens, operation, comments, solutionType, simul)
|
160 |
+
print(final_string)
|
161 |
+
else:
|
162 |
+
"""
|
163 |
+
This part handles the cases when VisMa is dealing with matrices.
|
164 |
+
|
165 |
+
Boolean flags used in code below:
|
166 |
+
dualOperand -- {True} when the matrix operations require two operands (used in operations like addition, subtraction etc)
|
167 |
+
nonMatrixResult -- {True} when the result after performing operations on the Matrix is not a Matrix (in operations like Determinant, Trace etc.)
|
168 |
+
scalarOperations -- {True} when one of the operand in a scalar (used in operations like Scalar Addition, Scalar Subtraction etc.)
|
169 |
+
"""
|
170 |
+
operation = operation[4:]
|
171 |
+
dualOperand = False
|
172 |
+
nonMatrixResult = False
|
173 |
+
scalarOperations = False
|
174 |
+
if ', ' in inputEquation:
|
175 |
+
dualOperand = True
|
176 |
+
[inputEquation1, inputEquation2] = inputEquation.split(', ')
|
177 |
+
if '[' in inputEquation1:
|
178 |
+
inputEquation1 = inputEquation1[1:][:-1]
|
179 |
+
inputEquation1 = inputEquation1.split('; ')
|
180 |
+
matrixOperand1 = []
|
181 |
+
for row in inputEquation1:
|
182 |
+
row1 = row.split(' ')
|
183 |
+
for i, _ in enumerate(row1):
|
184 |
+
row1[i] = tokenizer(row1[i])
|
185 |
+
matrixOperand1.append(row1)
|
186 |
+
Matrix1 = Matrix()
|
187 |
+
Matrix1.value = matrixOperand1
|
188 |
+
inputEquation2 = inputEquation2[1:][:-1]
|
189 |
+
inputEquation2 = inputEquation2.split('; ')
|
190 |
+
matrixOperand2 = []
|
191 |
+
for row in inputEquation2:
|
192 |
+
row1 = row.split(' ')
|
193 |
+
for i, _ in enumerate(row1):
|
194 |
+
row1[i] = tokenizer(row1[i])
|
195 |
+
matrixOperand2.append(row1)
|
196 |
+
Matrix2 = Matrix()
|
197 |
+
Matrix2.value = matrixOperand2
|
198 |
+
Matrix1_copy = copy.deepcopy(Matrix1)
|
199 |
+
Matrix2_copy = copy.deepcopy(Matrix2)
|
200 |
+
else:
|
201 |
+
scalarOperations = True
|
202 |
+
scalar = inputEquation1
|
203 |
+
scalarTokens = scalar
|
204 |
+
# scalarTokens = tokenizer(scalar)
|
205 |
+
inputEquation2 = inputEquation2[1:][:-1]
|
206 |
+
inputEquation2 = inputEquation2.split('; ')
|
207 |
+
matrixOperand2 = []
|
208 |
+
for row in inputEquation2:
|
209 |
+
row1 = row.split(' ')
|
210 |
+
for i, _ in enumerate(row1):
|
211 |
+
row1[i] = tokenizer(row1[i])
|
212 |
+
matrixOperand2.append(row1)
|
213 |
+
Matrix2 = Matrix()
|
214 |
+
Matrix2.value = matrixOperand2
|
215 |
+
scalarTokens_copy = copy.deepcopy(scalarTokens)
|
216 |
+
Matrix2_copy = copy.deepcopy(Matrix2)
|
217 |
+
|
218 |
+
else:
|
219 |
+
inputEquation = inputEquation[1:][:-1]
|
220 |
+
inputEquation = inputEquation.split('; ')
|
221 |
+
|
222 |
+
matrixOperand = []
|
223 |
+
for row in inputEquation:
|
224 |
+
row1 = row.split(' ')
|
225 |
+
for i, _ in enumerate(row1):
|
226 |
+
row1[i] = tokenizer(row1[i])
|
227 |
+
matrixOperand.append(row1)
|
228 |
+
|
229 |
+
Matrix0 = Matrix()
|
230 |
+
Matrix0.value = matrixOperand
|
231 |
+
Matrix0_copy = copy.deepcopy(Matrix0)
|
232 |
+
if operation == 'simplify':
|
233 |
+
MatrixResult = simplifyMatrix(Matrix0)
|
234 |
+
elif operation == 'add':
|
235 |
+
MatrixResult = addMatrix(Matrix1, Matrix2)
|
236 |
+
elif operation == 'sub':
|
237 |
+
MatrixResult = subMatrix(Matrix1, Matrix2)
|
238 |
+
elif operation == 'mult':
|
239 |
+
MatrixResult = multiplyMatrix(Matrix1, Matrix2)
|
240 |
+
elif operation == 'determinant':
|
241 |
+
nonMatrixResult = True
|
242 |
+
sqMatrix = SquareMat()
|
243 |
+
sqMatrix.value = Matrix0.value
|
244 |
+
result = sqMatrix.determinant()
|
245 |
+
elif operation == 'trace':
|
246 |
+
nonMatrixResult = True
|
247 |
+
sqMatrix = SquareMat()
|
248 |
+
sqMatrix.value = Matrix0.value
|
249 |
+
result = sqMatrix.traceMat()
|
250 |
+
elif operation == 'inverse':
|
251 |
+
sqMatrix = SquareMat()
|
252 |
+
sqMatrix.value = Matrix0.value
|
253 |
+
MatrixResult = SquareMat()
|
254 |
+
MatrixResult = sqMatrix.inverse()
|
255 |
+
|
256 |
+
finalCLIstring = ''
|
257 |
+
if dualOperand:
|
258 |
+
if not scalarOperations:
|
259 |
+
finalCLIstring = resultMatrixString(operation=operation, operand1=Matrix1_copy, operand2=Matrix2_copy, result=MatrixResult)
|
260 |
+
else:
|
261 |
+
finalCLIstring = resultMatrixString(operation=operation, operand1=scalarTokens_copy, operand2=Matrix2_copy, result=MatrixResult)
|
262 |
+
else:
|
263 |
+
if nonMatrixResult:
|
264 |
+
finalCLIstring = resultMatrixString(operation=operation, operand1=Matrix0_copy, nonMatrixResult=True, result=result)
|
265 |
+
else:
|
266 |
+
finalCLIstring = resultMatrixString(operation=operation, operand1=Matrix0_copy, result=MatrixResult)
|
267 |
+
print(finalCLIstring)
|
data/visma/gui/logger.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import datetime
|
3 |
+
from PyQt5.QtWidgets import QTextEdit, QVBoxLayout
|
4 |
+
|
5 |
+
|
6 |
+
INFO = 20
|
7 |
+
WARNING = 30
|
8 |
+
ERROR = 40
|
9 |
+
CRITICAL = 50
|
10 |
+
THRES_LEV = 0
|
11 |
+
NAME = ''
|
12 |
+
logString = ''
|
13 |
+
now = datetime.datetime.now()
|
14 |
+
|
15 |
+
|
16 |
+
def logTextBox(workspace):
|
17 |
+
workspace.logBox = QTextEdit()
|
18 |
+
workspace.logBox.setReadOnly(True)
|
19 |
+
textLayout = QVBoxLayout()
|
20 |
+
textLayout.addWidget(workspace.logBox)
|
21 |
+
return textLayout
|
22 |
+
|
23 |
+
|
24 |
+
def setLogName(name):
|
25 |
+
global NAME
|
26 |
+
NAME = name
|
27 |
+
|
28 |
+
|
29 |
+
def setLevel(level):
|
30 |
+
global THRES_LEV
|
31 |
+
THRES_LEV = level
|
32 |
+
|
33 |
+
|
34 |
+
def info(msg, *args):
|
35 |
+
if INFO >= THRES_LEV:
|
36 |
+
info = logWriter('INFO', msg, *args)
|
37 |
+
return info
|
38 |
+
|
39 |
+
|
40 |
+
def warn(msg, *args):
|
41 |
+
if WARNING >= THRES_LEV:
|
42 |
+
warn = logWriter('WARNING', msg, *args)
|
43 |
+
return warn
|
44 |
+
|
45 |
+
|
46 |
+
def error(msg, *args):
|
47 |
+
if ERROR >= THRES_LEV:
|
48 |
+
error = logWriter('ERROR', msg, *args)
|
49 |
+
return error
|
50 |
+
|
51 |
+
|
52 |
+
def logWriter(levType, msg, *args):
|
53 |
+
try:
|
54 |
+
f = open(os.path.abspath("log.txt"), "a")
|
55 |
+
except IOError:
|
56 |
+
print('Can\'t open the log file')
|
57 |
+
logString = now.strftime("%Y-%m-%d %H:%M") + ' - ' + NAME + ' - ' + '%s: %s' % (levType, msg % args) + '\n'
|
58 |
+
f.write(logString)
|
59 |
+
return logString
|
data/visma/gui/plotter.py
ADDED
@@ -0,0 +1,412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
from matplotlib.figure import Figure
|
4 |
+
from mpl_toolkits.mplot3d import Axes3D
|
5 |
+
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
|
6 |
+
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
|
7 |
+
from PyQt5.QtCore import Qt
|
8 |
+
from PyQt5.QtWidgets import QVBoxLayout, QLabel, QSlider, QSpinBox, QPushButton, QSplitter
|
9 |
+
|
10 |
+
from visma.io.checks import getVariables, getTokensType
|
11 |
+
from visma.io.tokenize import getLHSandRHS
|
12 |
+
from visma.functions.constant import Constant
|
13 |
+
from visma.functions.operator import Binary
|
14 |
+
from visma.functions.structure import FuncOp
|
15 |
+
from visma.functions.variable import Variable
|
16 |
+
|
17 |
+
|
18 |
+
def graphPlot(workspace, again, tokens):
|
19 |
+
"""Function for plotting graphs in 2D and 3D space
|
20 |
+
|
21 |
+
2D graphs are plotted for expression in one variable and equations in two variables. 3D graphs are plotted for expressions in two variables and equations in three variables.
|
22 |
+
|
23 |
+
Arguments:
|
24 |
+
workspace {QtWidgets.QWidget} -- main layout
|
25 |
+
|
26 |
+
Returns:
|
27 |
+
graphVars {list} -- variables to be plotted on the graph
|
28 |
+
func {numpy.array(2D)/function(3D)} -- equation converted to compatible data type for plotting
|
29 |
+
variables {list} -- variables in given equation
|
30 |
+
again {bool} -- True when an equation can be plotted in 2D and 3D both else False
|
31 |
+
|
32 |
+
Note:
|
33 |
+
The func obtained from graphPlot() function is of different type for 2D and 3D plots. For 2D, func is a numpy array, and for 3D, func is a function.
|
34 |
+
"""
|
35 |
+
if tokens is None:
|
36 |
+
axisRange = workspace.axisRange
|
37 |
+
tokens = workspace.eqToks[-1]
|
38 |
+
else:
|
39 |
+
axisRange = [10, 10, 10, 30]
|
40 |
+
eqType = getTokensType(tokens)
|
41 |
+
LHStok, RHStok = getLHSandRHS(tokens)
|
42 |
+
variables = sorted(getVariables(LHStok, RHStok))
|
43 |
+
dim = len(variables)
|
44 |
+
if (dim == 1) or ((dim == 2) and eqType == "equation"):
|
45 |
+
if again:
|
46 |
+
variables.append('f(' + variables[0] + ')')
|
47 |
+
graphVars, func = plotIn3D(LHStok, RHStok, variables, axisRange)
|
48 |
+
else:
|
49 |
+
graphVars, func = plotIn2D(LHStok, RHStok, variables, axisRange)
|
50 |
+
if dim == 1:
|
51 |
+
variables.append('f(' + variables[0] + ')')
|
52 |
+
elif (dim == 2 and eqType == "expression") or ((dim == 3) and eqType == "equation"):
|
53 |
+
graphVars, func = plotIn3D(LHStok, RHStok, variables, axisRange)
|
54 |
+
if dim == 2:
|
55 |
+
variables.append('f(' + variables[0] + ',' + variables[1] + ')')
|
56 |
+
else:
|
57 |
+
return [], None, None
|
58 |
+
return graphVars, func, variables
|
59 |
+
|
60 |
+
|
61 |
+
def plotIn2D(LHStok, RHStok, variables, axisRange):
|
62 |
+
"""Returns function array for 2D plots
|
63 |
+
|
64 |
+
Arguments:
|
65 |
+
LHStok {list} -- expression tokens
|
66 |
+
RHStok {list} -- expression tokens
|
67 |
+
variables {list} -- variables in equation
|
68 |
+
axisRange {list} -- axis limits
|
69 |
+
|
70 |
+
Returns:
|
71 |
+
graphVars {list} -- variables for plotting
|
72 |
+
func {numpy.array} -- equation to be plotted in 2D
|
73 |
+
"""
|
74 |
+
xmin = -axisRange[0]
|
75 |
+
xmax = axisRange[0]
|
76 |
+
ymin = -axisRange[1]
|
77 |
+
ymax = axisRange[1]
|
78 |
+
xdelta = 0.01 * (xmax - xmin)
|
79 |
+
ydelta = 0.01 * (ymax - ymin)
|
80 |
+
xrange = np.arange(xmin, xmax, xdelta)
|
81 |
+
yrange = np.arange(ymin, ymax, ydelta)
|
82 |
+
graphVars = np.meshgrid(xrange, yrange)
|
83 |
+
function = getFunction(LHStok, RHStok, variables, graphVars, 2)
|
84 |
+
return graphVars, function
|
85 |
+
|
86 |
+
|
87 |
+
def plotIn3D(LHStok, RHStok, variables, axisRange):
|
88 |
+
"""Returns function for 3D plots
|
89 |
+
|
90 |
+
Arguments:
|
91 |
+
LHStok {list} -- expression tokens
|
92 |
+
RHStok {list} -- expression tokens
|
93 |
+
variables {list} -- variables in equation
|
94 |
+
axisRange {list} -- axis limits
|
95 |
+
|
96 |
+
Returns:
|
97 |
+
graphVars {list} -- variables for plotting
|
98 |
+
func {function} -- equation to be plotted in 3D
|
99 |
+
"""
|
100 |
+
|
101 |
+
xmin = -axisRange[0]
|
102 |
+
xmax = axisRange[0]
|
103 |
+
ymin = -axisRange[1]
|
104 |
+
ymax = axisRange[1]
|
105 |
+
zmin = -axisRange[2]
|
106 |
+
zmax = axisRange[2]
|
107 |
+
meshLayers = axisRange[3]
|
108 |
+
xrange = np.linspace(xmin, xmax, meshLayers)
|
109 |
+
yrange = np.linspace(ymin, ymax, meshLayers)
|
110 |
+
zrange = np.linspace(zmin, zmax, meshLayers)
|
111 |
+
graphVars = [xrange, yrange, zrange]
|
112 |
+
|
113 |
+
def func(x, y, z):
|
114 |
+
graphVars = [x, y, z]
|
115 |
+
return getFunction(LHStok, RHStok, variables, graphVars, 3)
|
116 |
+
|
117 |
+
return graphVars, func
|
118 |
+
|
119 |
+
|
120 |
+
def getFunction(LHStok, RHStok, eqnVars, graphVars, dim):
|
121 |
+
"""Returns function for plotting
|
122 |
+
|
123 |
+
Arguments:
|
124 |
+
LHStok {list} -- expression tokens
|
125 |
+
RHStok {list} -- expression tokens
|
126 |
+
eqnVars {list} -- variables in equation
|
127 |
+
graphVars {list} -- variables for plotting
|
128 |
+
dim {int} -- dimenion of plot
|
129 |
+
|
130 |
+
Returns:
|
131 |
+
(LHS - RHS) {numpy.array(2D)/function(3D)} -- equation converted to compatible data type for plotting
|
132 |
+
"""
|
133 |
+
LHS = getFuncExpr(LHStok, eqnVars, graphVars)
|
134 |
+
if len(eqnVars) == dim:
|
135 |
+
RHS = getFuncExpr(RHStok, eqnVars, graphVars)
|
136 |
+
elif len(eqnVars) == dim - 1:
|
137 |
+
RHS = graphVars[-1]
|
138 |
+
return LHS - RHS
|
139 |
+
|
140 |
+
|
141 |
+
def getFuncExpr(exprTok, eqnVars, graphVars):
|
142 |
+
"""Allocates variables in equation to graph variables to give final function compatible for plotting
|
143 |
+
|
144 |
+
Arguments:
|
145 |
+
exprTok {list} -- expression tokens
|
146 |
+
eqnVars {list} -- variables in equation
|
147 |
+
graphVars {list} -- variables for plotting
|
148 |
+
|
149 |
+
Returns:
|
150 |
+
expr {numpy.array(2D)/function(3D)} -- expression converted to compatible data type for plotting
|
151 |
+
"""
|
152 |
+
expr = 0
|
153 |
+
coeff = 1
|
154 |
+
for token in exprTok:
|
155 |
+
if isinstance(token, Variable):
|
156 |
+
varProduct = 1
|
157 |
+
for value, power in zip(token.value, token.power):
|
158 |
+
varProduct *= graphVars[eqnVars.index(value)]**power
|
159 |
+
expr += coeff * token.coefficient * varProduct
|
160 |
+
elif isinstance(token, Constant):
|
161 |
+
expr += coeff * token.value
|
162 |
+
elif isinstance(token, FuncOp):
|
163 |
+
pass
|
164 |
+
elif isinstance(token, Binary) and token.value == '-':
|
165 |
+
coeff = -1
|
166 |
+
elif isinstance(token, Binary) and token.value == '+':
|
167 |
+
coeff = 1
|
168 |
+
return expr
|
169 |
+
|
170 |
+
|
171 |
+
#######
|
172 |
+
# GUI #
|
173 |
+
#######
|
174 |
+
|
175 |
+
|
176 |
+
def plotFigure2D(workspace):
|
177 |
+
"""GUI layout for plot figure
|
178 |
+
|
179 |
+
Arguments:
|
180 |
+
workspace {QtWidgets.QWidget} -- main layout
|
181 |
+
|
182 |
+
Returns:
|
183 |
+
layout {QtWidgets.QVBoxLayout} -- contains matplot figure
|
184 |
+
"""
|
185 |
+
workspace.figure2D = Figure()
|
186 |
+
workspace.canvas2D = FigureCanvas(workspace.figure2D)
|
187 |
+
# workspace.figure2D.patch.set_facecolor('white')
|
188 |
+
|
189 |
+
class NavigationCustomToolbar(NavigationToolbar):
|
190 |
+
toolitems = [t for t in NavigationToolbar.toolitems if t[0] in ()]
|
191 |
+
|
192 |
+
workspace.toolbar2D = NavigationCustomToolbar(workspace.canvas2D, workspace)
|
193 |
+
layout = QVBoxLayout()
|
194 |
+
layout.addWidget(workspace.canvas2D)
|
195 |
+
layout.addWidget(workspace.toolbar2D)
|
196 |
+
return layout
|
197 |
+
|
198 |
+
|
199 |
+
def plotFigure3D(workspace):
|
200 |
+
"""GUI layout for plot figure
|
201 |
+
|
202 |
+
Arguments:
|
203 |
+
workspace {QtWidgets.QWidget} -- main layout
|
204 |
+
|
205 |
+
Returns:
|
206 |
+
layout {QtWidgets.QVBoxLayout} -- contains matplot figure
|
207 |
+
"""
|
208 |
+
workspace.figure3D = Figure()
|
209 |
+
workspace.canvas3D = FigureCanvas(workspace.figure3D)
|
210 |
+
# workspace.figure3D.patch.set_facecolor('white')
|
211 |
+
|
212 |
+
class NavigationCustomToolbar(NavigationToolbar):
|
213 |
+
toolitems = [t for t in NavigationToolbar.toolitems if t[0] in ()]
|
214 |
+
|
215 |
+
workspace.toolbar3D = NavigationCustomToolbar(workspace.canvas3D, workspace)
|
216 |
+
layout = QVBoxLayout()
|
217 |
+
layout.addWidget(workspace.canvas3D)
|
218 |
+
layout.addWidget(workspace.toolbar3D)
|
219 |
+
return layout
|
220 |
+
|
221 |
+
|
222 |
+
def renderPlot(workspace, graphVars, func, variables, tokens=None):
|
223 |
+
"""Renders plot for functions in 2D and 3D
|
224 |
+
|
225 |
+
Maps points from the numpy arrays for variables in given equation on the 2D/3D plot figure
|
226 |
+
|
227 |
+
Arguments:
|
228 |
+
workspace {QtWidgets.QWidget} -- main layout
|
229 |
+
graphVars {list} -- variables for plotting
|
230 |
+
dim {int} -- dimenion of plot
|
231 |
+
variables {list} -- variables in equation
|
232 |
+
"""
|
233 |
+
if len(graphVars) == 2:
|
234 |
+
X, Y = graphVars[0], graphVars[1]
|
235 |
+
ax = workspace.figure2D.add_subplot(111)
|
236 |
+
ax.clear()
|
237 |
+
ax.contour(X, Y, func, [0])
|
238 |
+
ax.grid()
|
239 |
+
ax.set_xlabel(r'$' + variables[0] + '$')
|
240 |
+
ax.set_ylabel(r'$' + variables[1] + '$')
|
241 |
+
workspace.figure2D.set_tight_layout({"pad": 1}) # removes extra padding
|
242 |
+
workspace.canvas2D.draw()
|
243 |
+
workspace.tabPlot.setCurrentIndex(0)
|
244 |
+
elif len(graphVars) == 3:
|
245 |
+
xrange = graphVars[0]
|
246 |
+
yrange = graphVars[1]
|
247 |
+
zrange = graphVars[2]
|
248 |
+
ax = Axes3D(workspace.figure3D)
|
249 |
+
for z in zrange:
|
250 |
+
X, Y = np.meshgrid(xrange, yrange)
|
251 |
+
Z = func(X, Y, z)
|
252 |
+
ax.contour(X, Y, Z + z, [z], zdir='z')
|
253 |
+
for y in yrange:
|
254 |
+
X, Z = np.meshgrid(xrange, zrange)
|
255 |
+
Y = func(X, y, Z)
|
256 |
+
ax.contour(X, Y + y, Z, [y], zdir='y')
|
257 |
+
for x in xrange:
|
258 |
+
Y, Z = np.meshgrid(yrange, zrange)
|
259 |
+
X = func(x, Y, Z)
|
260 |
+
ax.contour(X + x, Y, Z, [x], zdir='x')
|
261 |
+
if tokens is None:
|
262 |
+
axisRange = workspace.axisRange
|
263 |
+
else:
|
264 |
+
axisRange = [10, 10, 10, 30]
|
265 |
+
xmin = -axisRange[0]
|
266 |
+
xmax = axisRange[0]
|
267 |
+
ymin = -axisRange[1]
|
268 |
+
ymax = axisRange[1]
|
269 |
+
zmin = -axisRange[2]
|
270 |
+
zmax = axisRange[2]
|
271 |
+
ax.set_xlim3d(xmin, xmax)
|
272 |
+
ax.set_ylim3d(ymin, ymax)
|
273 |
+
ax.set_zlim3d(zmin, zmax)
|
274 |
+
ax.set_xlabel(r'$' + variables[0] + '$')
|
275 |
+
ax.set_ylabel(r'$' + variables[1] + '$')
|
276 |
+
ax.set_zlabel(r'$' + variables[2] + '$')
|
277 |
+
workspace.canvas3D.draw()
|
278 |
+
workspace.tabPlot.setCurrentIndex(1)
|
279 |
+
|
280 |
+
|
281 |
+
def plot(workspace, tokens=None):
|
282 |
+
"""When called from window.py it initiates rendering of equations.
|
283 |
+
|
284 |
+
Arguments:
|
285 |
+
workspace {QtWidgets.QWidget} -- main layout
|
286 |
+
"""
|
287 |
+
from visma.io.tokenize import tokenizer
|
288 |
+
|
289 |
+
workspace.figure2D.clear()
|
290 |
+
workspace.figure3D.clear()
|
291 |
+
if tokens is None:
|
292 |
+
tokens = workspace.eqToks[-1]
|
293 |
+
eqType = getTokensType(tokens)
|
294 |
+
LHStok, RHStok = getLHSandRHS(tokens)
|
295 |
+
variables = sorted(getVariables(LHStok, RHStok))
|
296 |
+
dim = len(variables)
|
297 |
+
graphVars, func, variables = graphPlot(workspace, False, tokens)
|
298 |
+
renderPlot(workspace, graphVars, func, variables, tokens)
|
299 |
+
if (dim == 1):
|
300 |
+
var2, var3 = selectAdditionalVariable(variables[0])
|
301 |
+
if tokens is None:
|
302 |
+
workspace.eqToks[-1] += tokenizer("0" + var2 + "+" + "0" + var3)
|
303 |
+
else:
|
304 |
+
tokens += tokenizer("0" + var2 + "+" + "0" + var3)
|
305 |
+
if (((dim == 2) or (dim == 1)) & (eqType == 'equation')):
|
306 |
+
graphVars, func, variables = graphPlot(workspace, True, tokens)
|
307 |
+
renderPlot(workspace, graphVars, func, variables, tokens)
|
308 |
+
|
309 |
+
|
310 |
+
def selectAdditionalVariable(var1):
|
311 |
+
if var1 == 'z':
|
312 |
+
var2 = 'a'
|
313 |
+
var3 = 'b'
|
314 |
+
return var2, var3
|
315 |
+
if var1 == 'Z':
|
316 |
+
var2 = 'A'
|
317 |
+
var3 = 'B'
|
318 |
+
return var2, var3
|
319 |
+
var2 = chr(ord(var1) + 1)
|
320 |
+
var3 = chr(ord(var1) + 2)
|
321 |
+
return var2, var3
|
322 |
+
|
323 |
+
|
324 |
+
def refreshPlot(workspace):
|
325 |
+
if workspace.resultOut is True and workspace.showPlotter is True:
|
326 |
+
plot(workspace)
|
327 |
+
|
328 |
+
|
329 |
+
###############
|
330 |
+
# preferences #
|
331 |
+
###############
|
332 |
+
# TODO: Add status tips, Fix docstrings
|
333 |
+
|
334 |
+
def plotPref(workspace):
|
335 |
+
|
336 |
+
prefLayout = QSplitter(Qt.Horizontal)
|
337 |
+
|
338 |
+
workspace.xLimitValue = QLabel(
|
339 |
+
"X-axis range: (-" + str(workspace.axisRange[0]) + ", " + str(workspace.axisRange[0]) + ")")
|
340 |
+
workspace.yLimitValue = QLabel(
|
341 |
+
"Y-axis range: (-" + str(workspace.axisRange[1]) + ", " + str(workspace.axisRange[1]) + ")")
|
342 |
+
workspace.zLimitValue = QLabel(
|
343 |
+
"Z-axis range: (-" + str(workspace.axisRange[2]) + ", " + str(workspace.axisRange[2]) + ")")
|
344 |
+
|
345 |
+
def customSlider():
|
346 |
+
limitSlider = QSlider(Qt.Horizontal)
|
347 |
+
limitSlider.setMinimum(-3)
|
348 |
+
limitSlider.setMaximum(3)
|
349 |
+
limitSlider.setValue(1)
|
350 |
+
limitSlider.setTickPosition(QSlider.TicksBothSides)
|
351 |
+
limitSlider.setTickInterval(1)
|
352 |
+
limitSlider.valueChanged.connect(lambda: valueChange(workspace))
|
353 |
+
limitSlider.setStatusTip("Change axes limit")
|
354 |
+
return limitSlider
|
355 |
+
|
356 |
+
workspace.xLimitSlider = customSlider()
|
357 |
+
workspace.yLimitSlider = customSlider()
|
358 |
+
workspace.zLimitSlider = customSlider()
|
359 |
+
|
360 |
+
workspace.meshDensityValue = QLabel(
|
361 |
+
"Mesh Layers: " + str(workspace.axisRange[3]))
|
362 |
+
workspace.meshDensityValue.setStatusTip("Increment for a denser mesh in 3D plot")
|
363 |
+
workspace.meshDensity = QSpinBox()
|
364 |
+
workspace.meshDensity.setFixedSize(200, 30)
|
365 |
+
workspace.meshDensity.setRange(10, 75)
|
366 |
+
workspace.meshDensity.setValue(30)
|
367 |
+
workspace.meshDensity.valueChanged.connect(lambda: valueChange(workspace))
|
368 |
+
workspace.meshDensity.setStatusTip("Incrementing mesh density may affect performance")
|
369 |
+
|
370 |
+
refreshPlotterText = QLabel("Apply plotter settings")
|
371 |
+
refreshPlotter = QPushButton('Apply')
|
372 |
+
refreshPlotter.setFixedSize(200, 30)
|
373 |
+
refreshPlotter.clicked.connect(lambda: refreshPlot(workspace))
|
374 |
+
refreshPlotter.setStatusTip("Apply modified settings to plotter.")
|
375 |
+
|
376 |
+
axisPref = QSplitter(Qt.Vertical)
|
377 |
+
axisPref.addWidget(workspace.xLimitValue)
|
378 |
+
axisPref.addWidget(workspace.xLimitSlider)
|
379 |
+
axisPref.addWidget(workspace.yLimitValue)
|
380 |
+
axisPref.addWidget(workspace.yLimitSlider)
|
381 |
+
axisPref.addWidget(workspace.zLimitValue)
|
382 |
+
axisPref.addWidget(workspace.zLimitSlider)
|
383 |
+
|
384 |
+
plotSetPref = QSplitter(Qt.Vertical)
|
385 |
+
plotSetPref.addWidget(workspace.meshDensityValue)
|
386 |
+
plotSetPref.addWidget(workspace.meshDensity)
|
387 |
+
plotSetPref.addWidget(refreshPlotterText)
|
388 |
+
plotSetPref.addWidget(refreshPlotter)
|
389 |
+
|
390 |
+
prefLayout.addWidget(plotSetPref)
|
391 |
+
prefLayout.addWidget(axisPref)
|
392 |
+
prefLayout.setFixedWidth(400)
|
393 |
+
|
394 |
+
return prefLayout
|
395 |
+
|
396 |
+
|
397 |
+
def valueChange(workspace):
|
398 |
+
|
399 |
+
xlimit = 10**workspace.xLimitSlider.value()
|
400 |
+
ylimit = 10**workspace.yLimitSlider.value()
|
401 |
+
zlimit = 10**workspace.zLimitSlider.value()
|
402 |
+
meshLayers = workspace.meshDensity.value()
|
403 |
+
workspace.axisRange = [xlimit, ylimit, zlimit, meshLayers]
|
404 |
+
|
405 |
+
workspace.xLimitValue.setText(
|
406 |
+
"X-axis range: (-" + str(workspace.axisRange[0]) + ", " + str(workspace.axisRange[0]) + ")")
|
407 |
+
workspace.yLimitValue.setText(
|
408 |
+
"Y-axis range: (-" + str(workspace.axisRange[1]) + ", " + str(workspace.axisRange[1]) + ")")
|
409 |
+
workspace.zLimitValue.setText(
|
410 |
+
"Z-axis range: (-" + str(workspace.axisRange[2]) + ", " + str(workspace.axisRange[2]) + ")")
|
411 |
+
workspace.meshDensityValue.setText(
|
412 |
+
"Mesh Layers: " + str(workspace.axisRange[3]))
|
data/visma/gui/qsolver.py
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from matplotlib.figure import Figure
|
2 |
+
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
|
3 |
+
from PyQt5 import QtWidgets
|
4 |
+
|
5 |
+
from visma.io.tokenize import removeSpaces, getTerms, normalize, tokenizeSymbols, removeUnary, getToken, getLHSandRHS
|
6 |
+
from visma.io.checks import checkEquation, checkTypes
|
7 |
+
from visma.io.parser import tokensToLatex
|
8 |
+
# from visma.gui.plotter import plot
|
9 |
+
from visma.simplify.simplify import simplify, simplifyEquation
|
10 |
+
from visma.gui import logger
|
11 |
+
|
12 |
+
|
13 |
+
def quickSimplify(workspace):
|
14 |
+
"""Dynamic simplifier for simplifying expression as it is being typed
|
15 |
+
|
16 |
+
Arguments:
|
17 |
+
workspace {QtWidgets.QWidget} -- main layout
|
18 |
+
|
19 |
+
Returns:
|
20 |
+
qSolution/log {string} -- quick solution or error log
|
21 |
+
enableInteraction {bool} -- if False disables 'visma'(interaction) button
|
22 |
+
"""
|
23 |
+
# FIXME: Crashes for some cases. Find and fix.
|
24 |
+
logger.setLogName('qsolver')
|
25 |
+
logger.setLevel(0)
|
26 |
+
qSolution = ""
|
27 |
+
strIn = workspace.textedit.toPlainText()
|
28 |
+
cleanInput = removeSpaces(strIn)
|
29 |
+
if ';' in cleanInput:
|
30 |
+
return "", True, True
|
31 |
+
terms = getTerms(cleanInput)
|
32 |
+
normalizedTerms = normalize(terms)
|
33 |
+
symTokens = tokenizeSymbols(normalizedTerms)
|
34 |
+
normalizedTerms, symTokens = removeUnary(normalizedTerms, symTokens)
|
35 |
+
if checkEquation(normalizedTerms, symTokens) is True and strIn != "":
|
36 |
+
if symTokens and symTokens[-1] is not False:
|
37 |
+
tokens = getToken(normalizedTerms, symTokens)
|
38 |
+
tokens = tokens.tokens
|
39 |
+
lhs, rhs = getLHSandRHS(tokens)
|
40 |
+
_, solutionType = checkTypes(lhs, rhs)
|
41 |
+
lhs, rhs = getLHSandRHS(tokens)
|
42 |
+
if solutionType == 'expression':
|
43 |
+
_, _, _, equationTokens, _ = simplify(tokens)
|
44 |
+
qSolution = r'$ ' + '= \ '
|
45 |
+
else:
|
46 |
+
_, _, _, _, equationTokens, _ = simplifyEquation(lhs, rhs)
|
47 |
+
qSolution = r'$ ' + '\Rightarrow \ '
|
48 |
+
qSolution += tokensToLatex(equationTokens[-1]) + ' $'
|
49 |
+
# workspace.eqToks = equationTokens
|
50 |
+
# plot(workspace)
|
51 |
+
return qSolution, True, False
|
52 |
+
elif symTokens:
|
53 |
+
log = "Invalid Expression"
|
54 |
+
workspace.logBox.append(logger.error(log))
|
55 |
+
return log, False, _
|
56 |
+
else:
|
57 |
+
log = ""
|
58 |
+
workspace.logBox.append(logger.error(log))
|
59 |
+
return log, False, _
|
60 |
+
else:
|
61 |
+
log = ""
|
62 |
+
if strIn != "":
|
63 |
+
_, log = checkEquation(normalizedTerms, symTokens)
|
64 |
+
workspace.logBox.append(logger.error(log))
|
65 |
+
return log, False, _
|
66 |
+
|
67 |
+
|
68 |
+
#######
|
69 |
+
# GUI #
|
70 |
+
#######
|
71 |
+
|
72 |
+
|
73 |
+
def qSolveFigure(workspace):
|
74 |
+
"""GUI layout for quick simplifier
|
75 |
+
|
76 |
+
Arguments:
|
77 |
+
workspace {QtWidgets.QWidget} -- main layout
|
78 |
+
|
79 |
+
Returns:
|
80 |
+
qSolLayout {QtWidgets.QVBoxLayout} -- quick simplifier layout
|
81 |
+
"""
|
82 |
+
|
83 |
+
bg = workspace.palette().window().color()
|
84 |
+
bgcolor = (bg.redF(), bg.greenF(), bg.blueF())
|
85 |
+
workspace.qSolveFigure = Figure(edgecolor=bgcolor, facecolor=bgcolor)
|
86 |
+
workspace.solcanvas = FigureCanvas(workspace.qSolveFigure)
|
87 |
+
workspace.qSolveFigure.clear()
|
88 |
+
qSolLayout = QtWidgets.QVBoxLayout()
|
89 |
+
qSolLayout.addWidget(workspace.solcanvas)
|
90 |
+
|
91 |
+
return qSolLayout
|
92 |
+
|
93 |
+
|
94 |
+
def renderQuickSol(workspace, log, showQSolver):
|
95 |
+
"""Renders quick solution in matplotlib figure
|
96 |
+
|
97 |
+
Arguments:
|
98 |
+
workspace {QtWidgets.QWidget} -- main layout
|
99 |
+
"""
|
100 |
+
if showQSolver is True:
|
101 |
+
quickSolution = log
|
102 |
+
else:
|
103 |
+
quickSolution = ""
|
104 |
+
workspace.qSolveFigure.suptitle(quickSolution, x=0.01,
|
105 |
+
horizontalalignment='left',
|
106 |
+
verticalalignment='top')
|
107 |
+
# size=qApp.font().pointSize()*1.5)
|
108 |
+
workspace.solcanvas.draw()
|
data/visma/gui/settings.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PyQt5.QtWidgets import QHBoxLayout, QCheckBox, QSplitter, QComboBox, QLabel
|
2 |
+
from PyQt5.QtCore import Qt
|
3 |
+
|
4 |
+
from visma.gui.steps import stepsPref
|
5 |
+
from visma.gui.plotter import plotPref
|
6 |
+
|
7 |
+
#######
|
8 |
+
# GUI #
|
9 |
+
#######
|
10 |
+
|
11 |
+
|
12 |
+
def preferenceLayout(workspace):
|
13 |
+
"""GUI layout for preferences
|
14 |
+
|
15 |
+
Arguments:
|
16 |
+
workspace {QtWidgets.QWidget} -- main layout
|
17 |
+
|
18 |
+
Returns:
|
19 |
+
hbox {QtWidgets.QHBoxLayout} -- preferences layout
|
20 |
+
"""
|
21 |
+
|
22 |
+
hbox = QHBoxLayout()
|
23 |
+
|
24 |
+
workspace.QSCheckBox = QCheckBox("Quick Simplifier")
|
25 |
+
workspace.QSCheckBox.setChecked(True)
|
26 |
+
workspace.QSCheckBox.toggled.connect(lambda: buttonState(workspace.QSCheckBox, workspace))
|
27 |
+
|
28 |
+
workspace.SSSCheckBox = QCheckBox("Step-by-step Solution")
|
29 |
+
workspace.SSSCheckBox.setFixedSize(200, 30)
|
30 |
+
workspace.SSSCheckBox.setChecked(True)
|
31 |
+
workspace.SSSCheckBox.toggled.connect(lambda: buttonState(workspace.SSSCheckBox, workspace))
|
32 |
+
|
33 |
+
workspace.GPCheckBox = QCheckBox("Graph Plotter")
|
34 |
+
workspace.GPCheckBox.setChecked(False)
|
35 |
+
workspace.GPCheckBox.toggled.connect(lambda: buttonState(workspace.GPCheckBox, workspace))
|
36 |
+
|
37 |
+
splitter1 = QSplitter(Qt.Vertical)
|
38 |
+
splitter1.addWidget(workspace.QSCheckBox) # Quick Simplifier
|
39 |
+
splitter1.addWidget(workspace.SSSCheckBox) # Step-by-step Solution
|
40 |
+
splitter1.addWidget(workspace.GPCheckBox) # Graph Plotter
|
41 |
+
|
42 |
+
# Input Type Box
|
43 |
+
comboLabel = QLabel()
|
44 |
+
comboLabel.setText("Input Type:")
|
45 |
+
combo = QComboBox(workspace)
|
46 |
+
combo.setFixedSize(200, 30)
|
47 |
+
combo.addItem("Greek")
|
48 |
+
combo.addItem("LaTeX")
|
49 |
+
combo.activated[str].connect(workspace.onActivated)
|
50 |
+
stepspref1, stepspref2 = stepsPref(workspace)
|
51 |
+
inputTypeSplitter = QSplitter(Qt.Vertical)
|
52 |
+
inputTypeSplitter.addWidget(stepspref1)
|
53 |
+
inputTypeSplitter.addWidget(stepspref2)
|
54 |
+
inputTypeSplitter.addWidget(comboLabel)
|
55 |
+
inputTypeSplitter.addWidget(combo)
|
56 |
+
|
57 |
+
splitter = QSplitter(Qt.Horizontal)
|
58 |
+
splitter.addWidget(splitter1)
|
59 |
+
splitter.addWidget(inputTypeSplitter)
|
60 |
+
splitter.addWidget(plotPref(workspace))
|
61 |
+
|
62 |
+
hbox.addWidget(splitter)
|
63 |
+
return hbox
|
64 |
+
|
65 |
+
|
66 |
+
def buttonState(button, workspace):
|
67 |
+
"""Takes action according to button and its state change trigger
|
68 |
+
|
69 |
+
Arguments:
|
70 |
+
button {QtWidgets.QCheckBox} -- preference checkbox
|
71 |
+
workspace {QtWidgets.QWidget} -- main layout
|
72 |
+
"""
|
73 |
+
|
74 |
+
workspace.clearAll()
|
75 |
+
|
76 |
+
if button.text() == "Quick Simplifier":
|
77 |
+
if button.isChecked() is True:
|
78 |
+
workspace.showQSolver = True
|
79 |
+
else:
|
80 |
+
workspace.showQSolver = False
|
81 |
+
|
82 |
+
elif button.text() == "Step-by-step Solution":
|
83 |
+
if button.isChecked() is True:
|
84 |
+
workspace.showStepByStep = True
|
85 |
+
else:
|
86 |
+
workspace.showStepByStep = False
|
87 |
+
|
88 |
+
elif button.text() == "Graph Plotter":
|
89 |
+
if button.isChecked() is True:
|
90 |
+
workspace.showPlotter = True
|
91 |
+
else:
|
92 |
+
workspace.showPlotter = False
|
data/visma/gui/steps.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from matplotlib.figure import Figure
|
2 |
+
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
|
3 |
+
from PyQt5.QtWidgets import QVBoxLayout, qApp, QLabel, QDoubleSpinBox, QScrollArea
|
4 |
+
|
5 |
+
#######
|
6 |
+
# GUI #
|
7 |
+
#######
|
8 |
+
|
9 |
+
|
10 |
+
def stepsFigure(workspace):
|
11 |
+
"""GUI layout for step-by-step solution
|
12 |
+
|
13 |
+
Arguments:
|
14 |
+
workspace {QtWidgets.QWidget} -- main layout
|
15 |
+
|
16 |
+
Returns:
|
17 |
+
stepslayout {QtWidgets.QVBoxLayout} -- step-by-step solution layout
|
18 |
+
"""
|
19 |
+
workspace.stepsfigure = Figure()
|
20 |
+
workspace.stepscanvas = FigureCanvas(workspace.stepsfigure)
|
21 |
+
workspace.stepsfigure.clear()
|
22 |
+
workspace.scroll = QScrollArea()
|
23 |
+
workspace.scroll.setWidget(workspace.stepscanvas)
|
24 |
+
stepslayout = QVBoxLayout()
|
25 |
+
stepslayout.addWidget(workspace.scroll)
|
26 |
+
return stepslayout
|
27 |
+
|
28 |
+
|
29 |
+
def showSteps(workspace):
|
30 |
+
"""Renders step-by-step solution in matplotlib figure
|
31 |
+
|
32 |
+
Arguments:
|
33 |
+
workspace {QtWidgets.QWidget} -- main layout
|
34 |
+
"""
|
35 |
+
workspace.stepsfigure.suptitle(workspace.output, y=0.98,
|
36 |
+
horizontalalignment='center',
|
37 |
+
verticalalignment='top', size=qApp.font().pointSize()*workspace.stepsFontSize)
|
38 |
+
workspace.stepscanvas.draw()
|
39 |
+
hbar = workspace.scroll.horizontalScrollBar()
|
40 |
+
hbar.setValue((hbar.minimum()+hbar.maximum())/2)
|
41 |
+
|
42 |
+
|
43 |
+
###############
|
44 |
+
# preferences #
|
45 |
+
###############
|
46 |
+
|
47 |
+
|
48 |
+
def stepsPref(workspace):
|
49 |
+
|
50 |
+
workspace.sizeChangeText = QLabel("Steps font size: " + str(round(workspace.stepsFontSize, 1)) + "x")
|
51 |
+
workspace.sizeChangeBox = QDoubleSpinBox()
|
52 |
+
workspace.sizeChangeBox.setFixedSize(200, 30)
|
53 |
+
workspace.sizeChangeBox.setRange(0.1, 10)
|
54 |
+
workspace.sizeChangeBox.setValue(1)
|
55 |
+
workspace.sizeChangeBox.setSingleStep(0.1)
|
56 |
+
workspace.sizeChangeBox.setSuffix('x')
|
57 |
+
workspace.sizeChangeBox.valueChanged.connect(lambda: sizeChange(workspace))
|
58 |
+
return workspace.sizeChangeText, workspace.sizeChangeBox
|
59 |
+
|
60 |
+
|
61 |
+
def sizeChange(workspace):
|
62 |
+
workspace.stepsFontSize = workspace.sizeChangeBox.value()
|
63 |
+
workspace.sizeChangeText.setText("Steps font size: " + str(round(workspace.stepsFontSize, 1)) + "x")
|
64 |
+
if workspace.resultOut is True:
|
65 |
+
showSteps(workspace)
|