jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def modify(self, name, value):
        """ Change the value of an attribute while preserving its type.

        Differs from __setitem__ in that if the attribute already exists, its
        type is preserved.  This can be very useful for interacting with
        externally generated files.

        If the attribute doesn't exist, it will be automatically created.
        """
        with phil:
            if not name in self:
                self[name] = value
            else:
                value = numpy.asarray(value, order='C')

                attr = h5a.open(self._id, self._e(name))

                if is_empty_dataspace(attr):
                    raise IOError("Empty attributes can't be modified")

                # Allow the case of () <-> (1,)
                if (value.shape != attr.shape) and not \
                   (numpy.prod(value.shape) == 1 and numpy.prod(attr.shape) == 1):
                    raise TypeError("Shape of data is incompatible with existing attribute")
                attr.write(value)
//  [python]
def test_relate_and_make_new_objects(self):
        """Relate one parent to one child, but save children as a new set"""
        parent_labels = numpy.ones((10, 10), int)
        child_labels = numpy.zeros((10, 10), int)
        child_labels[3:5, 4:7] = 1
        workspace, module = self.make_workspace(parent_labels, child_labels)
        module.wants_child_objects_saved.value = True
        module.output_child_objects_name.value = "outputobjects"
        module.wants_per_parent_means.value = False
        module.run(workspace)
        m = workspace.measurements
        parents_of = m.get_current_measurement(
            CHILD_OBJECTS, "Parent_%s" % PARENT_OBJECTS
        )
        self.assertEqual(numpy.product(parents_of.shape), 1)
        self.assertEqual(parents_of[0], 1)
        child_count = m.get_current_measurement(
            PARENT_OBJECTS, "Children_%s_Count" % CHILD_OBJECTS
        )
        self.assertEqual(numpy.product(child_count.shape), 1)
        self.assertEqual(child_count[0], 1)
        self.features_and_columns_match(workspace)
//  [python]
def test_relate_and_make_new_objects(self):
        """Relate one parent to one child, but save children as a new set"""
        parent_labels = numpy.ones((10, 10), int)
        child_labels = numpy.zeros((10, 10), int)
        child_labels[3:5, 4:7] = 1
        workspace, module = self.make_workspace(parent_labels, child_labels)
        module.wants_child_objects_saved.value = True
        module.output_child_objects_name.value = "outputobjects"
        module.wants_per_parent_means.value = False
        module.run(workspace)
        m = workspace.measurements
        parents_of = m.get_current_measurement(
            CHILD_OBJECTS, "Parent_%s" % PARENT_OBJECTS
        )
        self.assertEqual(numpy.prod(parents_of.shape), 1)
        self.assertEqual(parents_of[0], 1)
        child_count = m.get_current_measurement(
            PARENT_OBJECTS, "Children_%s_Count" % CHILD_OBJECTS
        )
        self.assertEqual(numpy.prod(child_count.shape), 1)
        self.assertEqual(child_count[0], 1)
        self.features_and_columns_match(workspace)
//  [python]
def numpy_irfft(af, a=None, inplace=0, copy=1):
    #if a is None:
    #    return _N.fft.irfftn(af)
    #else:
        a[:] = _N.fft.irfftn(af)
        a *= _N.product(a.shape)
//  [python]
def numpy_irfft(af, a=None, inplace=0, copy=1):
    #if a is None:
    #    return _N.fft.irfftn(af)
    #else:
        a[:] = _N.fft.irfftn(af)
        a *= _N.prod(a.shape)
//  [python]
def numpy_ifft(af, a=None, inplace=0):
    #if a is None:
    #    return _N.fft.ifftn(af)
    #else:
        a[:] = _N.fft.ifftn(af)
        a *= _N.product(a.shape)
//  [python]
def numpy_ifft(af, a=None, inplace=0):
    #if a is None:
    #    return _N.fft.ifftn(af)
    #else:
        a[:] = _N.fft.ifftn(af)
        a *= _N.prod(a.shape)
//  [python]
def basis_element(self, x, i, d=0):
        """
        Evaluate a particular basis element of the BSpline,
        or its derivative.

        INPUTS:
           x  -- x values at which to evaluate the basis element
           i  -- which element of the BSpline to return
           d  -- the order of derivative

        OUTPUTS: y
           y  -- value of d-th derivative of the i-th basis element
                 of the BSpline at specified x values

        """

        x = np.asarray(x, np.float64)
        _shape = x.shape
        if _shape == ():
            x.shape = (1,)
        x.shape = (np.product(_shape,axis=0),)
        if i < self.tau.shape[0] - 1:
           ## TODO: OWNDATA flags...
            v = _hbspline.evaluate(x, self.tau, self.m, d, i, i+1)
        else:
            return np.zeros(x.shape, np.float64)

        if (i == self.tau.shape[0] - self.m):
            v = np.where(np.equal(x, self.tau[-1]), 1, v)
        v.shape = _shape
        return v
//  [python]
def basis_element(self, x, i, d=0):
        """
        Evaluate a particular basis element of the BSpline,
        or its derivative.

        INPUTS:
           x  -- x values at which to evaluate the basis element
           i  -- which element of the BSpline to return
           d  -- the order of derivative

        OUTPUTS: y
           y  -- value of d-th derivative of the i-th basis element
                 of the BSpline at specified x values

        """

        x = np.asarray(x, np.float64)
        _shape = x.shape
        if _shape == ():
            x.shape = (1,)
        x.shape = (np.prod(_shape,axis=0),)
        if i < self.tau.shape[0] - 1:
           ## TODO: OWNDATA flags...
            v = _hbspline.evaluate(x, self.tau, self.m, d, i, i+1)
        else:
            return np.zeros(x.shape, np.float64)

        if (i == self.tau.shape[0] - self.m):
            v = np.where(np.equal(x, self.tau[-1]), 1, v)
        v.shape = _shape
        return v
//  [python]
def LL_gradient(x_name, x_val, param_name, param_val, y_train):
    
    shapes = tf.shape_n(param_val)
    n_tensors = len(shapes)

    count = 0
    idx =  [] 
    part = []

    for i, shape in enumerate(shapes):
        n = numpy.product(shape)
        idx.append(tf.reshape(tf.range(count, count+n, dtype=tf.int32), shape))
        part.extend([i]*n)
        count += n
  
    @tf.function
    def assign_new_model_parameters(params_1d):

        updated_params = tf.dynamic_partition(params_1d, part, n_tensors)

        for i, (shape, param) in enumerate(zip(shapes, updated_params)):
            param_val[i].assign(tf.reshape(param, shape))
                   
    @tf.function 
    def est_grad(params_1d):
        
        # Derive the Tensorflow gradient
        with tf.GradientTape() as tape: 
            
            # Call the function to update and convert the shape of parameters
            assign_new_model_parameters(params_1d)
            
            # Estimated Choice Probability 
            yhat = model_fun(x_name, x_val, param_name, param_val, avail_val)
            
            # Call the cost function
            loss_value = cost_fun(y_train, yhat)
            
        # Calculate the gradient for each parameter
        estimated_grad = tape.gradient(loss_value, param_val)

        grads_1dim = tf.dynamic_stitch(idx, estimated_grad)
        return loss_value, grads_1dim
    
    est_grad.idx = idx
    
    return est_grad
//  [python]
def LL_gradient(x_name, x_val, param_name, param_val, y_train):
    
    shapes = tf.shape_n(param_val)
    n_tensors = len(shapes)

    count = 0
    idx =  [] 
    part = []

    for i, shape in enumerate(shapes):
        n = numpy.prod(shape)
        idx.append(tf.reshape(tf.range(count, count+n, dtype=tf.int32), shape))
        part.extend([i]*n)
        count += n
  
    @tf.function
    def assign_new_model_parameters(params_1d):

        updated_params = tf.dynamic_partition(params_1d, part, n_tensors)

        for i, (shape, param) in enumerate(zip(shapes, updated_params)):
            param_val[i].assign(tf.reshape(param, shape))
                   
    @tf.function 
    def est_grad(params_1d):
        
        # Derive the Tensorflow gradient
        with tf.GradientTape() as tape: 
            
            # Call the function to update and convert the shape of parameters
            assign_new_model_parameters(params_1d)
            
            # Estimated Choice Probability 
            yhat = model_fun(x_name, x_val, param_name, param_val, avail_val)
            
            # Call the cost function
            loss_value = cost_fun(y_train, yhat)
            
        # Calculate the gradient for each parameter
        estimated_grad = tape.gradient(loss_value, param_val)

        grads_1dim = tf.dynamic_stitch(idx, estimated_grad)
        return loss_value, grads_1dim
    
    est_grad.idx = idx
    
    return est_grad
//  [python]
def basis(self, x, d=0, lower=None, upper=None):
        """
        Evaluate the basis of the BSpline or its derivative.
        If lower or upper is specified, then only
        the [lower:upper] elements of the basis are returned.

        INPUTS:
           x     -- x values at which to evaluate the basis element
           i     -- which element of the BSpline to return
           d     -- the order of derivative
           lower -- optional lower limit of the set of basis
                    elements
           upper -- optional upper limit of the set of basis
                    elements

        OUTPUTS: y
           y  -- value of d-th derivative of the basis elements
                 of the BSpline at specified x values

        """
        x = np.asarray(x)
        _shape = x.shape
        if _shape == ():
            x.shape = (1,)
        x.shape = (np.product(_shape,axis=0),)

        if upper is None:
            upper = self.tau.shape[0] - self.m
        if lower is None:
            lower = 0
        upper = min(upper, self.tau.shape[0] - self.m)
        lower = max(0, lower)

        d = np.asarray(d)
        if d.shape == ():
            v = _hbspline.evaluate(x, self.tau, self.m, int(d), lower, upper)
        else:
            if d.shape[0] != 2:
                raise ValueError("if d is not an integer, expecting a jx2 \
                   array with first row indicating order \
                   of derivative, second row coefficient in front.")
            v = 0
            for i in range(d.shape[1]):
                v += d[1,i] * _hbspline.evaluate(x, self.tau, self.m, d[0,i], lower, upper)

        v.shape = (upper-lower,) + _shape
        if upper == self.tau.shape[0] - self.m:
            v[-1] = np.where(np.equal(x, self.tau[-1]), 1, v[-1])
        return v
//  [python]
def basis(self, x, d=0, lower=None, upper=None):
        """
        Evaluate the basis of the BSpline or its derivative.
        If lower or upper is specified, then only
        the [lower:upper] elements of the basis are returned.

        INPUTS:
           x     -- x values at which to evaluate the basis element
           i     -- which element of the BSpline to return
           d     -- the order of derivative
           lower -- optional lower limit of the set of basis
                    elements
           upper -- optional upper limit of the set of basis
                    elements

        OUTPUTS: y
           y  -- value of d-th derivative of the basis elements
                 of the BSpline at specified x values

        """
        x = np.asarray(x)
        _shape = x.shape
        if _shape == ():
            x.shape = (1,)
        x.shape = (np.prod(_shape,axis=0),)

        if upper is None:
            upper = self.tau.shape[0] - self.m
        if lower is None:
            lower = 0
        upper = min(upper, self.tau.shape[0] - self.m)
        lower = max(0, lower)

        d = np.asarray(d)
        if d.shape == ():
            v = _hbspline.evaluate(x, self.tau, self.m, int(d), lower, upper)
        else:
            if d.shape[0] != 2:
                raise ValueError("if d is not an integer, expecting a jx2 \
                   array with first row indicating order \
                   of derivative, second row coefficient in front.")
            v = 0
            for i in range(d.shape[1]):
                v += d[1,i] * _hbspline.evaluate(x, self.tau, self.m, d[0,i], lower, upper)

        v.shape = (upper-lower,) + _shape
        if upper == self.tau.shape[0] - self.m:
            v[-1] = np.where(np.equal(x, self.tau[-1]), 1, v[-1])
        return v
//  [python]
def plot(self, n=None, tri_alpha=0):
        """Plot the function we want to learn, only works in 2D.

        Parameters
        ----------
        n : int
            the number of boxes in the interpolation grid along each axis
        tri_alpha : float (0 to 1)
            Opacity of triangulation lines
        """
        hv = ensure_holoviews()
        if self.vdim > 1:
            raise NotImplementedError(
                "holoviews currently does not support", "3D surface plots in bokeh."
            )
        if self.ndim != 2:
            raise NotImplementedError(
                "Only 2D plots are implemented: You can "
                "plot a 2D slice with 'plot_slice'."
            )
        x, y = self._bbox
        lbrt = x[0], y[0], x[1], y[1]

        if len(self.data) >= 4:
            if n is None:
                # Calculate how many grid points are needed.
                # factor from A=√3/4 * a² (equilateral triangle)
                scale_factor = np.product(np.diag(self._transform))
                a_sq = np.sqrt(np.min(self.tri.volumes()) * scale_factor)
                n = max(10, int(0.658 / a_sq))

            xs = ys = np.linspace(0, 1, n)
            xs = xs * (x[1] - x[0]) + x[0]
            ys = ys * (y[1] - y[0]) + y[0]
            z = self._ip()(xs[:, None], ys[None, :]).squeeze()

            im = hv.Image(np.rot90(z), bounds=lbrt)

            if tri_alpha:
                points = np.array(
                    [self.tri.get_vertices(s) for s in self.tri.simplices]
                )
                points = np.pad(
                    points[:, [0, 1, 2, 0], :],
                    pad_width=((0, 0), (0, 1), (0, 0)),
                    mode="constant",
                    constant_values=np.nan,
                ).reshape(-1, 2)
                tris = hv.EdgePaths([points])
            else:
                tris = hv.EdgePaths([])
        else:
            im = hv.Image([], bounds=lbrt)
            tris = hv.EdgePaths([])
        return im.opts(cmap="viridis") * tris.opts(
            line_width=0.5, alpha=tri_alpha, tools=[]
        )
//  [python]
def plot(self, n=None, tri_alpha=0):
        """Plot the function we want to learn, only works in 2D.

        Parameters
        ----------
        n : int
            the number of boxes in the interpolation grid along each axis
        tri_alpha : float (0 to 1)
            Opacity of triangulation lines
        """
        hv = ensure_holoviews()
        if self.vdim > 1:
            raise NotImplementedError(
                "holoviews currently does not support", "3D surface plots in bokeh."
            )
        if self.ndim != 2:
            raise NotImplementedError(
                "Only 2D plots are implemented: You can "
                "plot a 2D slice with 'plot_slice'."
            )
        x, y = self._bbox
        lbrt = x[0], y[0], x[1], y[1]

        if len(self.data) >= 4:
            if n is None:
                # Calculate how many grid points are needed.
                # factor from A=√3/4 * a² (equilateral triangle)
                scale_factor = np.prod(np.diag(self._transform))
                a_sq = np.sqrt(np.min(self.tri.volumes()) * scale_factor)
                n = max(10, int(0.658 / a_sq))

            xs = ys = np.linspace(0, 1, n)
            xs = xs * (x[1] - x[0]) + x[0]
            ys = ys * (y[1] - y[0]) + y[0]
            z = self._ip()(xs[:, None], ys[None, :]).squeeze()

            im = hv.Image(np.rot90(z), bounds=lbrt)

            if tri_alpha:
                points = np.array(
                    [self.tri.get_vertices(s) for s in self.tri.simplices]
                )
                points = np.pad(
                    points[:, [0, 1, 2, 0], :],
                    pad_width=((0, 0), (0, 1), (0, 0)),
                    mode="constant",
                    constant_values=np.nan,
                ).reshape(-1, 2)
                tris = hv.EdgePaths([points])
            else:
                tris = hv.EdgePaths([])
        else:
            im = hv.Image([], bounds=lbrt)
            tris = hv.EdgePaths([])
        return im.opts(cmap="viridis") * tris.opts(
            line_width=0.5, alpha=tri_alpha, tools=[]
        )
//  [python]
def execute(self, si_sequence_data_item: API_1_0.DataItem, haadf_sequence_data_item: API_1_0.DataItem,
                align_index: int, align_region: typing.Optional[API_1_0.Graphic]=None):
        haadf_xdata = haadf_sequence_data_item.xdata
        si_xdata = si_sequence_data_item.xdata
        bounds = None
        if align_region:
            bounds = align_region.bounds
        translations = Core.function_sequence_measure_relative_translation(haadf_xdata,
                                                                           haadf_xdata[align_index],
                                                                           10, True, bounds=bounds)
        sequence_shape = haadf_sequence_data_item.xdata.sequence_dimension_shape
        data_zeros = (0,) * si_xdata.datum_dimension_count
        c = int(numpy.product(sequence_shape))
        haadf_result_data = numpy.empty_like(haadf_xdata.data)
        si_result_data = numpy.empty_like(si_xdata.data)
        for i in range(c):
            ii = numpy.unravel_index(i, sequence_shape)
            current_xdata = DataAndMetadata.new_data_and_metadata(haadf_xdata.data[ii])
            translation = translations.data[ii]
            haadf_result_data[ii] = Core.function_shift(current_xdata, tuple(translation)).data
            current_xdata = DataAndMetadata.new_data_and_metadata(si_xdata.data[ii])
            si_result_data[ii] = Core.function_shift(current_xdata, tuple(translation) + data_zeros).data
            self.progress_updated_event.fire(0, c, i+1)

        self.__aligned_haadf_sequence = DataAndMetadata.new_data_and_metadata(haadf_result_data,
                                                                              intensity_calibration=haadf_xdata.intensity_calibration,
                                                                              dimensional_calibrations=haadf_xdata.dimensional_calibrations,
                                                                              metadata=haadf_xdata.metadata,
                                                                              data_descriptor=haadf_xdata.data_descriptor)
        self.__aligned_si_sequence = DataAndMetadata.new_data_and_metadata(si_result_data,
                                                                           intensity_calibration=si_xdata.intensity_calibration,
                                                                           dimensional_calibrations=si_xdata.dimensional_calibrations,
                                                                           metadata=si_xdata.metadata,
                                                                           data_descriptor=si_xdata.data_descriptor)
//  [python]
def execute(self, si_sequence_data_item: API_1_0.DataItem, haadf_sequence_data_item: API_1_0.DataItem,
                align_index: int, align_region: typing.Optional[API_1_0.Graphic]=None):
        haadf_xdata = haadf_sequence_data_item.xdata
        si_xdata = si_sequence_data_item.xdata
        bounds = None
        if align_region:
            bounds = align_region.bounds
        translations = Core.function_sequence_measure_relative_translation(haadf_xdata,
                                                                           haadf_xdata[align_index],
                                                                           10, True, bounds=bounds)
        sequence_shape = haadf_sequence_data_item.xdata.sequence_dimension_shape
        data_zeros = (0,) * si_xdata.datum_dimension_count
        c = int(numpy.prod(sequence_shape))
        haadf_result_data = numpy.empty_like(haadf_xdata.data)
        si_result_data = numpy.empty_like(si_xdata.data)
        for i in range(c):
            ii = numpy.unravel_index(i, sequence_shape)
            current_xdata = DataAndMetadata.new_data_and_metadata(haadf_xdata.data[ii])
            translation = translations.data[ii]
            haadf_result_data[ii] = Core.function_shift(current_xdata, tuple(translation)).data
            current_xdata = DataAndMetadata.new_data_and_metadata(si_xdata.data[ii])
            si_result_data[ii] = Core.function_shift(current_xdata, tuple(translation) + data_zeros).data
            self.progress_updated_event.fire(0, c, i+1)

        self.__aligned_haadf_sequence = DataAndMetadata.new_data_and_metadata(haadf_result_data,
                                                                              intensity_calibration=haadf_xdata.intensity_calibration,
                                                                              dimensional_calibrations=haadf_xdata.dimensional_calibrations,
                                                                              metadata=haadf_xdata.metadata,
                                                                              data_descriptor=haadf_xdata.data_descriptor)
        self.__aligned_si_sequence = DataAndMetadata.new_data_and_metadata(si_result_data,
                                                                           intensity_calibration=si_xdata.intensity_calibration,
                                                                           dimensional_calibrations=si_xdata.dimensional_calibrations,
                                                                           metadata=si_xdata.metadata,
                                                                           data_descriptor=si_xdata.data_descriptor)
//  [python]
def test_testAddSumProd(self):
        # Test add, sum, product.
        (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
        self.assertTrue(eq(np.add.reduce(x), add.reduce(x)))
        self.assertTrue(eq(np.add.accumulate(x), add.accumulate(x)))
        self.assertTrue(eq(4, sum(array(4), axis=0)))
        self.assertTrue(eq(4, sum(array(4), axis=0)))
        self.assertTrue(eq(np.sum(x, axis=0), sum(x, axis=0)))
        self.assertTrue(eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
        self.assertTrue(eq(np.sum(x, 0), sum(x, 0)))
        self.assertTrue(eq(np.product(x, axis=0), product(x, axis=0)))
        self.assertTrue(eq(np.product(x, 0), product(x, 0)))
        self.assertTrue(eq(np.product(filled(xm, 1), axis=0),
                           product(xm, axis=0)))
        if len(s) > 1:
            self.assertTrue(eq(np.concatenate((x, y), 1),
                               concatenate((xm, ym), 1)))
            self.assertTrue(eq(np.add.reduce(x, 1), add.reduce(x, 1)))
            self.assertTrue(eq(np.sum(x, 1), sum(x, 1)))
            self.assertTrue(eq(np.product(x, 1), product(x, 1)))
//  [python]
def test_testAddSumProd(self):
        # Test add, sum, product.
        (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
        self.assertTrue(eq(np.add.reduce(x), add.reduce(x)))
        self.assertTrue(eq(np.add.accumulate(x), add.accumulate(x)))
        self.assertTrue(eq(4, sum(array(4), axis=0)))
        self.assertTrue(eq(4, sum(array(4), axis=0)))
        self.assertTrue(eq(np.sum(x, axis=0), sum(x, axis=0)))
        self.assertTrue(eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
        self.assertTrue(eq(np.sum(x, 0), sum(x, 0)))
        self.assertTrue(eq(np.prod(x, axis=0), product(x, axis=0)))
        self.assertTrue(eq(np.prod(x, 0), product(x, 0)))
        self.assertTrue(eq(np.prod(filled(xm, 1), axis=0),
                           product(xm, axis=0)))
        if len(s) > 1:
            self.assertTrue(eq(np.concatenate((x, y), 1),
                               concatenate((xm, ym), 1)))
            self.assertTrue(eq(np.add.reduce(x, 1), add.reduce(x, 1)))
            self.assertTrue(eq(np.sum(x, 1), sum(x, 1)))
            self.assertTrue(eq(np.prod(x, 1), product(x, 1)))
//  [python]
def test_product(self):
        with pytest.raises(u.UnitsError):
            np.product(self.q)
//  [python]
def test_product(self):
        with pytest.raises(u.UnitsError):
            np.prod(self.q)
//  [python]
def __array__(self, dtype=None):
        """ Create a Numpy array containing the whole dataset.  DON'T THINK
        THIS MEANS DATASETS ARE INTERCHANGEABLE WITH ARRAYS.  For one thing,
        you have to read the whole dataset every time this method is called.
        """
        arr = numpy.empty(self.shape, dtype=self.dtype if dtype is None else dtype)

        # Special case for (0,)*-shape datasets
        if numpy.product(self.shape, dtype=numpy.ulonglong) == 0:
            return arr

        self.read_direct(arr)
        return arr
//  [python]
def __array__(self, dtype=None):
        """ Create a Numpy array containing the whole dataset.  DON'T THINK
        THIS MEANS DATASETS ARE INTERCHANGEABLE WITH ARRAYS.  For one thing,
        you have to read the whole dataset every time this method is called.
        """
        arr = numpy.empty(self.shape, dtype=self.dtype if dtype is None else dtype)

        # Special case for (0,)*-shape datasets
        if numpy.prod(self.shape, dtype=numpy.ulonglong) == 0:
            return arr

        self.read_direct(arr)
        return arr
//  [python]
def _arc_jac_sn(w, m):
    """Inverse Jacobian elliptic sn

    Solve for z in w = sn(z, m)

    Parameters
    ----------
    w : complex scalar
        argument

    m : scalar
        modulus; in interval [0, 1]


    See [1], Eq. (56)

    References
    ----------
    .. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design",
           https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf

    """

    def _complement(kx):
        # (1-k**2) ** 0.5; the expression below
        # works for small kx
        return ((1 - kx) * (1 + kx)) ** 0.5

    k = m ** 0.5

    if k > 1:
        return np.nan
    elif k == 1:
        return np.arctanh(w)

    ks = [k]
    niter = 0
    while ks[-1] != 0:
        k_ = ks[-1]
        k_p = _complement(k_)
        ks.append((1 - k_p) / (1 + k_p))
        niter += 1
        if niter > _ARC_JAC_SN_MAXITER:
            raise ValueError('Landen transformation not converging')

    K = np.product(1 + np.array(ks[1:])) * np.pi/2

    wns = [w]

    for kn, knext in zip(ks[:-1], ks[1:]):
        wn = wns[-1]
        wnext = (2 * wn /
                 ((1 + knext) * (1 + _complement(kn * wn))))
        wns.append(wnext)

    u = 2 / np.pi * np.arcsin(wns[-1])

    z = K * u
    return z
//  [python]
def _arc_jac_sn(w, m):
    """Inverse Jacobian elliptic sn

    Solve for z in w = sn(z, m)

    Parameters
    ----------
    w : complex scalar
        argument

    m : scalar
        modulus; in interval [0, 1]


    See [1], Eq. (56)

    References
    ----------
    .. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design",
           https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf

    """

    def _complement(kx):
        # (1-k**2) ** 0.5; the expression below
        # works for small kx
        return ((1 - kx) * (1 + kx)) ** 0.5

    k = m ** 0.5

    if k > 1:
        return np.nan
    elif k == 1:
        return np.arctanh(w)

    ks = [k]
    niter = 0
    while ks[-1] != 0:
        k_ = ks[-1]
        k_p = _complement(k_)
        ks.append((1 - k_p) / (1 + k_p))
        niter += 1
        if niter > _ARC_JAC_SN_MAXITER:
            raise ValueError('Landen transformation not converging')

    K = np.prod(1 + np.array(ks[1:])) * np.pi/2

    wns = [w]

    for kn, knext in zip(ks[:-1], ks[1:]):
        wn = wns[-1]
        wnext = (2 * wn /
                 ((1 + knext) * (1 + _complement(kn * wn))))
        wns.append(wnext)

    u = 2 / np.pi * np.arcsin(wns[-1])

    z = K * u
    return z
//  [python]
def handle_monocular(self, msg):

        (image, camera) = msg
        gray = self.mkgray(image)
        C = self.image_corners(gray)
        if C is not None:
            linearity_rms = self.mc.linear_error(C, self.board)

            # Add in reprojection check
            image_points = C
            object_points = self.mc.mk_object_points([self.board], use_board_size=True)[0]
            dist_coeffs = numpy.zeros((4, 1))
            camera_matrix = numpy.array( [ [ camera.P[0], camera.P[1], camera.P[2]  ],
                                           [ camera.P[4], camera.P[5], camera.P[6]  ],
                                           [ camera.P[8], camera.P[9], camera.P[10] ] ] )
            ok, rot, trans = cv2.solvePnP(object_points, image_points, camera_matrix, dist_coeffs)
            # Convert rotation into a 3x3 Rotation Matrix
            rot3x3, _ = cv2.Rodrigues(rot)
            # Reproject model points into image
            object_points_world = numpy.asmatrix(rot3x3) * numpy.asmatrix(object_points.squeeze().T) + numpy.asmatrix(trans)
            reprojected_h = camera_matrix * object_points_world
            reprojected   = (reprojected_h[0:2, :] / reprojected_h[2, :])
            reprojection_errors = image_points.squeeze().T - reprojected

            reprojection_rms = numpy.sqrt(numpy.sum(numpy.array(reprojection_errors) ** 2) / numpy.product(reprojection_errors.shape))

            # Print the results
            print("Linearity RMS Error: %.3f Pixels      Reprojection RMS Error: %.3f Pixels" % (linearity_rms, reprojection_rms))
        else:
            print('no chessboard')
//  [python]
def handle_monocular(self, msg):

        (image, camera) = msg
        gray = self.mkgray(image)
        C = self.image_corners(gray)
        if C is not None:
            linearity_rms = self.mc.linear_error(C, self.board)

            # Add in reprojection check
            image_points = C
            object_points = self.mc.mk_object_points([self.board], use_board_size=True)[0]
            dist_coeffs = numpy.zeros((4, 1))
            camera_matrix = numpy.array( [ [ camera.P[0], camera.P[1], camera.P[2]  ],
                                           [ camera.P[4], camera.P[5], camera.P[6]  ],
                                           [ camera.P[8], camera.P[9], camera.P[10] ] ] )
            ok, rot, trans = cv2.solvePnP(object_points, image_points, camera_matrix, dist_coeffs)
            # Convert rotation into a 3x3 Rotation Matrix
            rot3x3, _ = cv2.Rodrigues(rot)
            # Reproject model points into image
            object_points_world = numpy.asmatrix(rot3x3) * numpy.asmatrix(object_points.squeeze().T) + numpy.asmatrix(trans)
            reprojected_h = camera_matrix * object_points_world
            reprojected   = (reprojected_h[0:2, :] / reprojected_h[2, :])
            reprojection_errors = image_points.squeeze().T - reprojected

            reprojection_rms = numpy.sqrt(numpy.sum(numpy.array(reprojection_errors) ** 2) / numpy.prod(reprojection_errors.shape))

            # Print the results
            print("Linearity RMS Error: %.3f Pixels      Reprojection RMS Error: %.3f Pixels" % (linearity_rms, reprojection_rms))
        else:
            print('no chessboard')
//  [python]
def __getitem__(self, ind):
        """Get the parameters that would be ``ind``th in iteration

        Parameters
        ----------
        ind : int
            The iteration index

        Returns
        -------
        params : dict of string to any
            Equal to list(self)[ind]
        """
        # This is used to make discrete sampling without replacement memory
        # efficient.
        for sub_grid in self.param_grid:
            # XXX: could memoize information used here
            if not sub_grid:
                if ind == 0:
                    return {}
                else:
                    ind -= 1
                    continue

            # Reverse so most frequent cycling parameter comes first
            keys, values_lists = zip(*sorted(sub_grid.items())[::-1])
            sizes = [len(v_list) for v_list in values_lists]
            total = np.product(sizes)

            if ind >= total:
                # Try the next grid
                ind -= total
            else:
                out = {}
                for key, v_list, n in zip(keys, values_lists, sizes):
                    ind, offset = divmod(ind, n)
                    out[key] = v_list[offset]
                return out

        raise IndexError('ParameterGrid index out of range')
//  [python]
def __getitem__(self, ind):
        """Get the parameters that would be ``ind``th in iteration

        Parameters
        ----------
        ind : int
            The iteration index

        Returns
        -------
        params : dict of string to any
            Equal to list(self)[ind]
        """
        # This is used to make discrete sampling without replacement memory
        # efficient.
        for sub_grid in self.param_grid:
            # XXX: could memoize information used here
            if not sub_grid:
                if ind == 0:
                    return {}
                else:
                    ind -= 1
                    continue

            # Reverse so most frequent cycling parameter comes first
            keys, values_lists = zip(*sorted(sub_grid.items())[::-1])
            sizes = [len(v_list) for v_list in values_lists]
            total = np.prod(sizes)

            if ind >= total:
                # Try the next grid
                ind -= total
            else:
                out = {}
                for key, v_list, n in zip(keys, values_lists, sizes):
                    ind, offset = divmod(ind, n)
                    out[key] = v_list[offset]
                return out

        raise IndexError('ParameterGrid index out of range')
//  [python]
def _get_val(self, dtype, optional=False, arraydims=()):
        # Unpack one value of the specified type from the table,
        # and advance the position pointer appropriately.  dtype
        # uses values compatible with numpy, ie i4, f4, etc.
        string_val = False
        if dtype == 'i4':
            unpack = self._unpack_int
        elif dtype == 'i8':
            unpack = self._unpack_long
        elif dtype == 'f4':
            unpack = self._unpack_float
        elif dtype == 'f8':
            unpack = self._unpack_double
        elif dtype == 'b':
            unpack = self._unpack_byte
        elif dtype[0] == 'S':
            unpack = None
            string_val = True
        else:
            raise RuntimeError("Unknown data dtype (dtype='%s')" % dtype)
        try:
            if optional:
                has_data = self._readtab(1) != b'\0'
                if not has_data:
                    # Return some default values..
                    if string_val:
                        return ''
                    else:
                        return 0
            ndim = len(arraydims)
            if string_val: 
                ndim = 1
            dims = []
            for i in range(ndim):
                nval = self._unpack_int.unpack_from(self._readtab(4))[0]
                dims.append(nval)
            if string_val:
                val = self._readtab(dims[0])
                # Return a str in python3
                if val is not None and not isinstance(val,str):
                    val = val.decode('utf-8')
                return val
            dsize = unpack.size
            if ndim:
                ntot = numpy.product(dims)
                return numpy.array([unpack.unpack_from(self._readtab(dsize))[0]
                        for i in range(ntot)]).reshape(dims)
            else:
                return unpack.unpack_from(self._readtab(dsize))[0]
        except struct.error:
            # Not enough bytes to unpack probably means we are at the end of
            # the table.
            return None
//  [python]
def _get_val(self, dtype, optional=False, arraydims=()):
        # Unpack one value of the specified type from the table,
        # and advance the position pointer appropriately.  dtype
        # uses values compatible with numpy, ie i4, f4, etc.
        string_val = False
        if dtype == 'i4':
            unpack = self._unpack_int
        elif dtype == 'i8':
            unpack = self._unpack_long
        elif dtype == 'f4':
            unpack = self._unpack_float
        elif dtype == 'f8':
            unpack = self._unpack_double
        elif dtype == 'b':
            unpack = self._unpack_byte
        elif dtype[0] == 'S':
            unpack = None
            string_val = True
        else:
            raise RuntimeError("Unknown data dtype (dtype='%s')" % dtype)
        try:
            if optional:
                has_data = self._readtab(1) != b'\0'
                if not has_data:
                    # Return some default values..
                    if string_val:
                        return ''
                    else:
                        return 0
            ndim = len(arraydims)
            if string_val: 
                ndim = 1
            dims = []
            for i in range(ndim):
                nval = self._unpack_int.unpack_from(self._readtab(4))[0]
                dims.append(nval)
            if string_val:
                val = self._readtab(dims[0])
                # Return a str in python3
                if val is not None and not isinstance(val,str):
                    val = val.decode('utf-8')
                return val
            dsize = unpack.size
            if ndim:
                ntot = numpy.prod(dims)
                return numpy.array([unpack.unpack_from(self._readtab(dsize))[0]
                        for i in range(ntot)]).reshape(dims)
            else:
                return unpack.unpack_from(self._readtab(dsize))[0]
        except struct.error:
            # Not enough bytes to unpack probably means we are at the end of
            # the table.
            return None
//  [python]
def param_norm(parameters):
    size = 0.0
    norm = 0.0
    for key in parameters:
        if(len(numpy.shape(parameters[key])) > 0):
            size += numpy.product(parameters[key].shape)
        else:
            size += 1
        norm += numpy.sum(parameters[key] * parameters[key])
    return numpy.sqrt(norm/size)
//  [python]
def param_norm(parameters):
    size = 0.0
    norm = 0.0
    for key in parameters:
        if(len(numpy.shape(parameters[key])) > 0):
            size += numpy.prod(parameters[key].shape)
        else:
            size += 1
        norm += numpy.sum(parameters[key] * parameters[key])
    return numpy.sqrt(norm/size)
//  [python]
def _binary_erosion(input, structure, iterations, mask, output,
                    border_value, origin, invert, brute_force):
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError('Complex type not supported')
    if structure is None:
        structure = generate_binary_structure(input.ndim, 1)
    else:
        structure = numpy.asarray(structure)
        structure = structure.astype(bool)
    if structure.ndim != input.ndim:
        raise RuntimeError('structure and input must have same dimensionality')
    if not structure.flags.contiguous:
        structure = structure.copy()
    if numpy.product(structure.shape,axis=0) < 1:
        raise RuntimeError('structure must not be empty')
    if mask is not None:
        mask = numpy.asarray(mask)
        if mask.shape != input.shape:
            raise RuntimeError('mask and input must have equal sizes')
    origin = _ni_support._normalize_sequence(origin, input.ndim)
    cit = _center_is_true(structure, origin)
    if isinstance(output, numpy.ndarray):
        if numpy.iscomplexobj(output):
            raise TypeError('Complex output type not supported')
    else:
        output = bool
    output, return_value = _ni_support._get_output(output, input)

    if iterations == 1:
        _nd_image.binary_erosion(input, structure, mask, output,
                                     border_value, origin, invert, cit, 0)
        return return_value
    elif cit and not brute_force:
        changed, coordinate_list = _nd_image.binary_erosion(input,
             structure, mask, output, border_value, origin, invert, cit, 1)
        structure = structure[tuple([slice(None, None, -1)] *
                                    structure.ndim)]
        for ii in range(len(origin)):
            origin[ii] = -origin[ii]
            if not structure.shape[ii] & 1:
                origin[ii] -= 1
        if mask is not None:
            msk = numpy.asarray(mask)
            msk = mask.astype(numpy.int8)
            if msk is mask:
                msk = mask.copy()
            mask = msk
        if not structure.flags.contiguous:
            structure = structure.copy()
        _nd_image.binary_erosion2(output, structure, mask, iterations - 1,
                                  origin, invert, coordinate_list)
        return return_value
    else:
        tmp_in = numpy.zeros(input.shape, bool)
        if return_value is None:
            tmp_out = output
        else:
            tmp_out = numpy.zeros(input.shape, bool)
        if not iterations & 1:
            tmp_in, tmp_out = tmp_out, tmp_in
        changed = _nd_image.binary_erosion(input, structure, mask,
                            tmp_out, border_value, origin, invert, cit, 0)
        ii = 1
        while (ii < iterations) or (iterations < 1) and changed:
            tmp_in, tmp_out = tmp_out, tmp_in
            changed = _nd_image.binary_erosion(tmp_in, structure, mask,
                            tmp_out, border_value, origin, invert, cit, 0)
            ii += 1
        if return_value is not None:
            return tmp_out
//  [python]
def _binary_erosion(input, structure, iterations, mask, output,
                    border_value, origin, invert, brute_force):
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError('Complex type not supported')
    if structure is None:
        structure = generate_binary_structure(input.ndim, 1)
    else:
        structure = numpy.asarray(structure)
        structure = structure.astype(bool)
    if structure.ndim != input.ndim:
        raise RuntimeError('structure and input must have same dimensionality')
    if not structure.flags.contiguous:
        structure = structure.copy()
    if numpy.prod(structure.shape) < 1:
        raise RuntimeError('structure must not be empty')
    if mask is not None:
        mask = numpy.asarray(mask)
        if mask.shape != input.shape:
            raise RuntimeError('mask and input must have equal sizes')
    origin = _ni_support._normalize_sequence(origin, input.ndim)
    cit = _center_is_true(structure, origin)
    if isinstance(output, numpy.ndarray):
        if numpy.iscomplexobj(output):
            raise TypeError('Complex output type not supported')
    else:
        output = bool
    output, return_value = _ni_support._get_output(output, input)

    if iterations == 1:
        _nd_image.binary_erosion(input, structure, mask, output,
                                     border_value, origin, invert, cit, 0)
        return return_value
    elif cit and not brute_force:
        changed, coordinate_list = _nd_image.binary_erosion(input,
             structure, mask, output, border_value, origin, invert, cit, 1)
        structure = structure[tuple([slice(None, None, -1)] *
                                    structure.ndim)]
        for ii in range(len(origin)):
            origin[ii] = -origin[ii]
            if not structure.shape[ii] & 1:
                origin[ii] -= 1
        if mask is not None:
            msk = numpy.asarray(mask)
            msk = mask.astype(numpy.int8)
            if msk is mask:
                msk = mask.copy()
            mask = msk
        if not structure.flags.contiguous:
            structure = structure.copy()
        _nd_image.binary_erosion2(output, structure, mask, iterations - 1,
                                  origin, invert, coordinate_list)
        return return_value
    else:
        tmp_in = numpy.zeros(input.shape, bool)
        if return_value is None:
            tmp_out = output
        else:
            tmp_out = numpy.zeros(input.shape, bool)
        if not iterations & 1:
            tmp_in, tmp_out = tmp_out, tmp_in
        changed = _nd_image.binary_erosion(input, structure, mask,
                            tmp_out, border_value, origin, invert, cit, 0)
        ii = 1
        while (ii < iterations) or (iterations < 1) and changed:
            tmp_in, tmp_out = tmp_out, tmp_in
            changed = _nd_image.binary_erosion(tmp_in, structure, mask,
                            tmp_out, border_value, origin, invert, cit, 0)
            ii += 1
        if return_value is not None:
            return tmp_out
//  [python]
def __init__(self, **kw_args):
        kw_args["writable"] = True
        super(Hebbian4, self).__init__(**kw_args)
        l = numpy.product(self.output_shape)

        self.add_parameter((self.n_clusters, 4), "Cluster")
        self.add_parameter((l,), "hash_map", is_static=True)
//  [python]
def __init__(self, **kw_args):
        kw_args["writable"] = True
        super(Hebbian4, self).__init__(**kw_args)
        l = numpy.prod(self.output_shape)

        self.add_parameter((self.n_clusters, 4), "Cluster")
        self.add_parameter((l,), "hash_map", is_static=True)
//  [python]
def forward(self, inputs=None, **kw_args):
        if("pre_syn" not in kw_args or "post_syn" not in kw_args):
            return numpy.copy(self.memory)
        pre_syn = kw_args["pre_syn"]
        post_syn = kw_args["post_syn"]
        assert((post_syn.shape[0], pre_syn.shape[0]) == self.output_shape and len(post_syn.shape)==1 and len(pre_syn.shape)==1),\
                "the pre-synaptic and post-synaptic dimensions do not match"
        post_unit = numpy.ones_like(post_syn)
        pre_unit = numpy.ones_like(pre_syn)
        deta_whts = 0.05 * (numpy.outer(post_syn, pre_syn) * self.parameter("A") 
                + numpy.outer(post_syn, pre_unit) * self.parameter("B")
                + numpy.outer(post_unit, pre_syn) * self.parameter("C")
                + numpy.outer(post_unit, pre_unit) * self.parameter("D"))

        if("modulator" in kw_args):
            mod = kw_args["modulator"]
            if(mod.shape==(self.output_shape[0], )):
                pre_unit = numpy.ones_like(pre_syn)
                assert mod.shape == post_syn.shape, "the shape of modulator and post synaptic signals do not match"
                self.memory += numpy.outer(mod, pre_unit) * deta_whts
            elif(numpy.product(mod.shape)==1):
                self.memory += mod * deta_whts
            else:
                raise Exception("modulator shape illegal")
        else:
            self.memory += deta_whts 

        return numpy.copy(self.memory)
//  [python]
def forward(self, inputs=None, **kw_args):
        if("pre_syn" not in kw_args or "post_syn" not in kw_args):
            return numpy.copy(self.memory)
        pre_syn = kw_args["pre_syn"]
        post_syn = kw_args["post_syn"]
        assert((post_syn.shape[0], pre_syn.shape[0]) == self.output_shape and len(post_syn.shape)==1 and len(pre_syn.shape)==1),\
                "the pre-synaptic and post-synaptic dimensions do not match"
        post_unit = numpy.ones_like(post_syn)
        pre_unit = numpy.ones_like(pre_syn)
        deta_whts = 0.05 * (numpy.outer(post_syn, pre_syn) * self.parameter("A") 
                + numpy.outer(post_syn, pre_unit) * self.parameter("B")
                + numpy.outer(post_unit, pre_syn) * self.parameter("C")
                + numpy.outer(post_unit, pre_unit) * self.parameter("D"))

        if("modulator" in kw_args):
            mod = kw_args["modulator"]
            if(mod.shape==(self.output_shape[0], )):
                pre_unit = numpy.ones_like(pre_syn)
                assert mod.shape == post_syn.shape, "the shape of modulator and post synaptic signals do not match"
                self.memory += numpy.outer(mod, pre_unit) * deta_whts
            elif(numpy.prod(mod.shape)==1):
                self.memory += mod * deta_whts
            else:
                raise Exception("modulator shape illegal")
        else:
            self.memory += deta_whts 

        return numpy.copy(self.memory)