Repository: wright-group/WrightTools

Issue:
pcov TypeError in kit._leastsq
In kit._leastsq, if the line 62 if statement is not passed, the consequent else statement makes pcov data type float, triggering"TypeError: 'int' object is not subscriptable" in line 72-73:

72:      try:
73:                error.append(np.absolute(pcov[i][i]) ** 0.5)

Line 74 picks up index out of bound errors, not sure if it was meant to catch the type error.

74:      except IndexError:
75:                 error.append(0.00)

Error is bypassed if I put a 2D array into line 68, but have not spent the time considering what this array should look like.

Discussion:
darienmorrow: First things that comes to mind is to try to fit two variables which are anticorrelated with eachother. Or to fit a single variable which does not change the output of the function.

Patch:
diff --git a/WrightTools/kit/_leastsq.py b/WrightTools/kit/_leastsq.py
index 1c93935..d448ba3 100644
--- a/WrightTools/kit/_leastsq.py
+++ b/WrightTools/kit/_leastsq.py
@@ -65,7 +65,7 @@ def leastsqfitter(p0, datax, datay, function, verbose=False, cov_verbose=False):
             if cov_verbose:
                 print(pcov)
         else:
-            pcov = np.inf
+            pcov = np.array(np.inf)
         # calculate and write errors
         error = []
         for i in range(len(pfit_leastsq)):


Test patch:
diff --git a/tests/kit/leastsqfitter.py b/tests/kit/leastsqfitter.py
new file mode 100644
index 0000000..184eaba
--- /dev/null
+++ b/tests/kit/leastsqfitter.py
@@ -0,0 +1,19 @@
+import numpy as np
+import WrightTools as wt
+
+
+def test_leastsq():
+    x = np.linspace(0, 10)
+    y = np.linspace(10, 0)
+    fit, cov = wt.kit.leastsqfitter([0, 0], x, y, lambda p, x: p[0] * x + p[1])
+    assert np.allclose(fit, [-1, 10])
+    assert np.allclose(cov, [0, 0])
+
+
+def test_leastsq_no_corr():
+    x = np.linspace(0, 10)
+    y = np.linspace(10, 0)
+    # The third parameter does not determine output, this caused an exception in wt <= 3.2.1
+    fit, cov = wt.kit.leastsqfitter([0, 0, 0], x, y, lambda p, x: p[0] * x + p[1])
+    assert np.allclose(fit, [-1, 10, 0])
+    assert np.allclose(cov, [0, 0, 0])