Repository: einsteinpy/einsteinpy

Issue:
Integrate Sympy's Lambdify in EinsteinPy
 Our tensors should have the ability to represent arrays of numpy-like functions rather than sympy expressions

Discussion:
pep8speaks: Hello @OVSofia! Thanks for opening this PR. We checked the lines you've touched for [PEP 8](https://www.python.org/dev/peps/pep-0008) issues, and found:



* In the file [`src/einsteinpy/symbolic/stress_energy_momentum.py`](https://github.com/einsteinpy/einsteinpy/blob/0f0bffc36e5b7dbbe462d9d1e24d78aee74f4613/src/einsteinpy/symbolic/stress_energy_momentum.py):

> [Line 25:121](https://github.com/einsteinpy/einsteinpy/blob/0f0bffc36e5b7dbbe462d9d1e24d78aee74f4613/src/einsteinpy/symbolic/stress_energy_momentum.py#L25): [E501](https://duckduckgo.com/?q=pep8%20E501) line too long (134 > 120 characters)
> [Line 54:13](https://github.com/einsteinpy/einsteinpy/blob/0f0bffc36e5b7dbbe462d9d1e24d78aee74f4613/src/einsteinpy/symbolic/stress_energy_momentum.py#L54): [W503](https://duckduckgo.com/?q=pep8%20W503) line break before binary operator
> [Line 55:13](https://github.com/einsteinpy/einsteinpy/blob/0f0bffc36e5b7dbbe462d9d1e24d78aee74f4613/src/einsteinpy/symbolic/stress_energy_momentum.py#L55): [W503](https://duckduckgo.com/?q=pep8%20W503) line break before binary operator








OVSofia: @ritzvik Can I change the Cognitive Complexity? 
ritzvik: > @ritzvik Can I change the Cognitive Complexity?

Don't worry about that!
codecov[bot]: # [Codecov](https://codecov.io/gh/einsteinpy/einsteinpy/pull/325?src=pr&el=h1) Report
> Merging [#325](https://codecov.io/gh/einsteinpy/einsteinpy/pull/325?src=pr&el=desc) into [master](https://codecov.io/gh/einsteinpy/einsteinpy/commit/befc0879c65a53b811e7d6a9ec47675ae28a08c5?src=pr&el=desc) will **increase** coverage by `0.03%`.
> The diff coverage is `100%`.

[![Impacted file tree graph](https://codecov.io/gh/einsteinpy/einsteinpy/pull/325/graphs/tree.svg?width=650&token=H3oDVYA11f&height=150&src=pr)](https://codecov.io/gh/einsteinpy/einsteinpy/pull/325?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master     #325      +/-   ##
==========================================
+ Coverage   94.12%   94.15%   +0.03%     
==========================================
  Files          40       40              
  Lines        1531     1540       +9     
==========================================
+ Hits         1441     1450       +9     
  Misses         90       90
```


| [Impacted Files](https://codecov.io/gh/einsteinpy/einsteinpy/pull/325?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [src/einsteinpy/symbolic/tensor.py](https://codecov.io/gh/einsteinpy/einsteinpy/pull/325/diff?src=pr&el=tree#diff-c3JjL2VpbnN0ZWlucHkvc3ltYm9saWMvdGVuc29yLnB5) | `97.91% <100%> (+1.1%)` | :arrow_up: |
| [src/einsteinpy/symbolic/constants.py](https://codecov.io/gh/einsteinpy/einsteinpy/pull/325/diff?src=pr&el=tree#diff-c3JjL2VpbnN0ZWlucHkvc3ltYm9saWMvY29uc3RhbnRzLnB5) | `100% <100%> (ø)` | :arrow_up: |
| [src/einsteinpy/symbolic/ricci.py](https://codecov.io/gh/einsteinpy/einsteinpy/pull/325/diff?src=pr&el=tree#diff-c3JjL2VpbnN0ZWlucHkvc3ltYm9saWMvcmljY2kucHk=) | `96.96% <0%> (-1.37%)` | :arrow_down: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/einsteinpy/einsteinpy/pull/325?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/einsteinpy/einsteinpy/pull/325?src=pr&el=footer). Last update [befc087...a68d993](https://codecov.io/gh/einsteinpy/einsteinpy/pull/325?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).

OVSofia: > > @ritzvik Can I change the Cognitive Complexity?
> 
> Don't worry about that!

So, should I change something or it's ok?
ritzvik: > > > @ritzvik Can I change the Cognitive Complexity?
> > 
> > 
> > Don't worry about that!
> 
> So, should I change something or it's ok?

Enough procrastination on my side! I am reviewing it 😄 
ritzvik: Meanwhile, @OVSofia , why don't you write a blog. It's been a long time since you wrote one, right?
OVSofia: > Meanwhile, @OVSofia , why don't you write a blog. It's been a long time since you wrote one, right?

Yes. Sure! ^.^
ritzvik: > Got it! Should I make the test?

Yups
ritzvik: Also, start working on the tests! @OVSofia 
ritzvik: Ok, leave it here, I will take care of the rest.
ritzvik: I've done the required changes. Have a look at them.
Squash n rebase!

And one more thing, you can learn how to make somebody co-author in a commit. Not that I want the credits xD, but it's something you should learn when working in a collaborative environment.
https://github.blog/2018-01-29-commit-together-with-co-authors/

cc @OVSofia 

Patch:
diff --git a/src/einsteinpy/symbolic/tensor.py b/src/einsteinpy/symbolic/tensor.py
index fbd55ff..80dfcc9 100644
--- a/src/einsteinpy/symbolic/tensor.py
+++ b/src/einsteinpy/symbolic/tensor.py
@@ -272,6 +272,7 @@ class BaseRelativityTensor(Tensor):
                 self.variables = [
                     v for v in self.arr.free_symbols if v not in self.syms
                 ]
+                self.variables.sort(key=(lambda var: var.name))
             else:
                 self.variables = list(variables)
             if not functions:
@@ -307,3 +308,33 @@ class BaseRelativityTensor(Tensor):
         
         """
         return self.syms
+
+    def tensor_lambdify(self, *args):
+        """
+        Returns lambdified function of symbolic tensors.
+        This means that the returned functions can accept numerical values and return numerical quantities.
+
+        Parameters
+        ----------
+            *args
+                The variable number of arguments accept sympy symbols.
+                The returned function accepts arguments in same order as initially defined in ``*args``.
+                Uses sympy symbols from class attributes ``syms`` and ``variables``(in the same order) if no ``*args`` is passed
+                Leaving ``*args`` empty is recommended.
+
+        Returns
+        -------
+            tuple
+                arguments to be passed in the returned function in exact order.
+            function
+                Lambdified function which accepts and returns numerical quantities.
+
+        """
+
+        if len(args) == 0:
+            numeric_arr = sympy.lambdify([*self.syms, *self.variables], self.arr, np)
+            arg_list = (*self.syms, *self.variables)
+        else:
+            numeric_arr = sympy.lambdify(args, self.arr, np)
+            arg_list = tuple(args)
+        return arg_list, numeric_arr


Test patch:
diff --git a/src/einsteinpy/tests/test_symbolic/test_tensor.py b/src/einsteinpy/tests/test_symbolic/test_tensor.py
index 7d85b44..82f705e 100644
--- a/src/einsteinpy/tests/test_symbolic/test_tensor.py
+++ b/src/einsteinpy/tests/test_symbolic/test_tensor.py
@@ -1,9 +1,10 @@
 import numpy as np
 import pytest
+from numpy.testing import assert_allclose
 from sympy import Array, Function, cos, simplify, sin, symbols
 from sympy.abc import y, z
 
-from einsteinpy.symbolic.tensor import BaseRelativityTensor, Tensor
+from einsteinpy.symbolic import BaseRelativityTensor, MetricTensor, Tensor
 
 
 def schwarzschild_tensor():
@@ -21,6 +22,21 @@ def schwarzschild_tensor():
     return sch
 
 
+def schwarzschild_metric():
+    symbolstr = "t r theta phi"
+    syms = symbols(symbolstr)
+    G, M, c, a = symbols("G M c a")
+    # using metric values of schwarschild space-time
+    # a is schwarzschild radius
+    list2d = np.zeros((4, 4), dtype=int).tolist()
+    list2d[0][0] = 1 - (a / syms[1])
+    list2d[1][1] = -1 / ((1 - (a / syms[1])) * (c ** 2))
+    list2d[2][2] = -1 * (syms[1] ** 2) / (c ** 2)
+    list2d[3][3] = -1 * (syms[1] ** 2) * (sin(syms[2]) ** 2) / (c ** 2)
+    sch = MetricTensor(list2d, syms)
+    return sch
+
+
 def arbitrary_tensor1():
     symbolstr = "x0 x1 x2 x3"
     syms = symbols(symbolstr)
@@ -149,3 +165,34 @@ def test_BaseRelativityTensor_automatic_calculation_of_free_variables():
 def test_tensor_scalar(scalar):
     scalar_tensor = Tensor(scalar)
     assert scalar_tensor.tensor().rank() == 0
+
+
+# tests for lambdify
+
+
+def test_lambdify_on_schwarzschild_metric_without_args():
+    sch = schwarzschild_metric()
+    # values of t, r, theta, phi, a, c
+    vals = (0.0, 3.0, np.pi / 2, np.pi / 3, 2, 1)
+    f = sch.tensor_lambdify()[1]
+    # print(sch.variables)
+    result_arr = np.array(f(*vals))
+    cmp_arr = np.zeros((4, 4), dtype=float)
+    cmp_arr[0, 0], cmp_arr[1, 1], cmp_arr[2, 2], cmp_arr[3, 3] = (
+        1 - (vals[4] / vals[1]),
+        -1 / ((1 - (vals[4] / vals[1])) * (vals[5] ** 2)),
+        -1 * (vals[1] ** 2) / (vals[5] ** 2),
+        -1 * (vals[1] ** 2) * (np.sin(vals[2]) ** 2) / (vals[5] ** 2),
+    )
+    assert_allclose(cmp_arr, result_arr, atol=1e-7, rtol=0.0)
+
+
+def test_lambdify_with_args():
+    x, y = symbols("x y")
+    T = BaseRelativityTensor([x + y, x], (x, y), config="l")
+    args, f = T.tensor_lambdify(y, x)
+    arr = np.array(f(2, 1))
+    cmp_arr = np.array([3, 1])
+    assert_allclose(arr, cmp_arr, rtol=0.0, atol=1e-7)
+    for e1, e2 in zip(args, (y, x)):
+        assert simplify(e1 - e2) == 0