code: def _chi2(self, theta, period, tmpid, return_gradient=False):
          
          template = self.templates[tmpid]
          phase = (self.t / period - theta[2]) % 1
          model = theta[0] + theta[1] * template(phase)
          chi2 = (((model - self.y) / self.dy) ** 2).sum()
  
          if return_gradient:
              grad = 2 * (model - self.y) / self.dy ** 2
              gradient = np.array([np.sum(grad),
                                   np.sum(grad * template(phase)),
                                   -np.sum(grad * theta[1]
                                           * template.derivative(1)(phase))])
              return chi2, gradient
          else:
              return chi2
docs: Compute the chi2 for the given parameters, period, & template
  
          Optionally return the gradient for faster optimization