Python numpy.atleast_2d() Examples

The following are 30 code examples for showing how to use numpy.atleast_2d(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: fuku-ml   Author: fukuball   File: Utility.py    License: MIT License 6 votes vote down vote up
def kernel_matrix_xX(svm_model, original_x, original_X):

        if (svm_model.svm_kernel == 'polynomial_kernel' or svm_model.svm_kernel == 'soft_polynomial_kernel'):
            K = (svm_model.zeta + svm_model.gamma * np.dot(original_x, original_X.T)) ** svm_model.Q
        elif (svm_model.svm_kernel == 'gaussian_kernel' or svm_model.svm_kernel == 'soft_gaussian_kernel'):
            K = np.exp(-svm_model.gamma * (cdist(original_X, np.atleast_2d(original_x), 'euclidean').T ** 2)).ravel()

        '''
        K = np.zeros((svm_model.data_num, svm_model.data_num))

        for i in range(svm_model.data_num):
            for j in range(svm_model.data_num):
                if (svm_model.svm_kernel == 'polynomial_kernel' or svm_model.svm_kernel == 'soft_polynomial_kernel'):
                    K[i, j] = Kernel.polynomial_kernel(svm_model, original_x, original_X[j])
                elif (svm_model.svm_kernel == 'gaussian_kernel' or svm_model.svm_kernel == 'soft_gaussian_kernel'):
                    K[i, j] = Kernel.gaussian_kernel(svm_model, original_x, original_X[j])
        '''

        return K 
Example 2
Project: ZIFA   Author: epierson9   File: ZIFA.py    License: MIT License 6 votes vote down vote up
def invertFast(A, d):
	"""
	given an array A of shape d x k and a d x 1 vector d, computes (A * A.T + diag(d)) ^{-1}
	Checked.
	"""
	assert(A.shape[0] == d.shape[0])
	assert(d.shape[1] == 1)

	k = A.shape[1]
	A = np.array(A)
	d_vec = np.array(d)
	d_inv = np.array(1 / d_vec[:, 0])

	inv_d_squared = np.dot(np.atleast_2d(d_inv).T, np.atleast_2d(d_inv))
	M = np.diag(d_inv) - inv_d_squared * np.dot(np.dot(A, np.linalg.inv(np.eye(k, k) + np.dot(A.T, mult_diag(d_inv, A)))), A.T)

	return M 
Example 3
Project: pymoo   Author: msu-coinlab   File: population.py    License: Apache License 2.0 6 votes vote down vote up
def pop_from_array_or_individual(array, pop=None):
    # the population type can be different - (different type of individuals)
    if pop is None:
        pop = Population()

    # provide a whole population object - (individuals might be already evaluated)
    if isinstance(array, Population):
        pop = array
    elif isinstance(array, np.ndarray):
        pop = pop.new("X", np.atleast_2d(array))
    elif isinstance(array, Individual):
        pop = Population(1)
        pop[0] = array
    else:
        return None

    return pop 
Example 4
Project: pymoo   Author: msu-coinlab   File: so_gradient_descent.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 X,
                 dX=None,
                 objective=0,
                 display=SingleObjectiveDisplay(),
                 **kwargs) -> None:
        super().__init__(display=display, **kwargs)

        self.objective = objective
        self.n_restarts = 0
        self.default_termination = SingleObjectiveDefaultTermination()

        self.X, self.dX = X, dX
        self.F, self.CV = None, None

        if self.X.ndim == 1:
            self.X = np.atleast_2d(X) 
Example 5
Project: me-ica   Author: ME-ICA   File: tedana.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def makeadmask(cdat,min=True,getsum=False):

	nx,ny,nz,Ne,nt = cdat.shape

	mask = np.ones((nx,ny,nz),dtype=np.bool)

	if min:
		mask = cdat[:,:,:,:,:].prod(axis=-1).prod(-1)!=0
		return mask
	else:
		#Make a map of longest echo that a voxel can be sampled with,
		#with minimum value of map as X value of voxel that has median
		#value in the 1st echo. N.b. larger factor leads to bias to lower TEs
		emeans = cdat[:,:,:,:,:].mean(-1)
		medv = emeans[:,:,:,0] == stats.scoreatpercentile(emeans[:,:,:,0][emeans[:,:,:,0]!=0],33,interpolation_method='higher')
		lthrs = np.squeeze(np.array([ emeans[:,:,:,ee][medv]/3 for ee in range(Ne) ]))
		if len(lthrs.shape)==1: lthrs = np.atleast_2d(lthrs).T
		lthrs = lthrs[:,lthrs.sum(0).argmax()]
		mthr = np.ones([nx,ny,nz,ne])
		for ee in range(Ne): mthr[:,:,:,ee]*=lthrs[ee]
		mthr = np.abs(emeans[:,:,:,:])>mthr
		masksum = np.array(mthr,dtype=np.int).sum(-1)
		mask = masksum!=0
		if getsum: return mask,masksum
		else: return mask 
Example 6
Project: simnibs   Author: simnibs   File: electrode_placement.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _move_point(new_position, to_be_moved, nodes, triangles, min_angle=0.25,
                edge_list=None, kdtree=None):
    '''Moves one point to the new_position. The angle of the patch should not become less
    than min_angle (in radians) '''
    # Certify that the new_position is inside the patch
    tr = _triangle_with_points(np.atleast_2d(new_position), triangles, nodes,
                               edge_list=edge_list, kdtree=kdtree)
    tr_with_node = np.where(np.any(triangles == to_be_moved, axis=1))[0]
    patch = triangles[tr_with_node]
    if not np.in1d(tr, tr_with_node):
        return None, None
    new_nodes = np.copy(nodes)
    position = nodes[to_be_moved]
    d = new_position - position
    # Start from the full move and go back
    for t in np.linspace(0, 1, num=10)[::-1]:
        new_nodes[to_be_moved] = position + t*d
        angle = np.min(_calc_triangle_angles(new_nodes[patch]))
        if angle > min_angle:
            break
    # Return the new node list and the minimum angle in the patch
    return new_nodes, angle 
Example 7
Project: simnibs   Author: simnibs   File: fem.py    License: GNU General Public License v3.0 6 votes vote down vote up
def apply_to_solution(self, x, dof_map):
        ''' Applies the dirichlet BC to a solution
        Parameters:
        -------
        x: numpy array
            Righ-hand side
        dof_map: dofMap
            Mapping of node indexes to rows and columns in A and b

        Returns:
        ------
        x: numpy array
            Righ-hand side, modified
        dof_map: dofMap
            Mapping of node indexes to rows and columns in A and b, modified
        '''
        if np.any(np.in1d(self.nodes, dof_map.inverse)):
            raise ValueError('Found DOFs already defined')
        dof_inverse = np.hstack((dof_map.inverse, self.nodes))
        x = np.atleast_2d(x)
        if x.shape[0] < x.shape[1]:
            x = x.T
        x = np.vstack((x, np.tile(self.values, (x.shape[1], 1)).T))
        return x, dofMap(dof_inverse) 
Example 8
Project: simnibs   Author: simnibs   File: test_optimization_methods.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_bb_full(self, optimization_variables_avg):
        l, Q, A = optimization_variables_avg
        m = 2e-3
        m1 = 4e-3
        f = 1e-2
        max_active = 2
        init = optimization_methods.bb_state([], [], list(range(len(l))))
        bf = functools.partial(
            optimization_methods._bb_bounds_function,
            np.atleast_2d(l), Q, f, m1, m, max_active)
        final_state = optimization_methods._branch_and_bound(
            init, bf, 1e-2, 100)
        x = final_state.x_lb
        assert np.linalg.norm(x, 1) <= 2 * m1 + 1e-4
        assert np.linalg.norm(x, 0) <= max_active
        assert np.all(np.abs(x) <= m + 1e-4)
        assert np.isclose(np.sum(x), 0)
        assert np.isclose(l.dot(x), f) 
Example 9
Project: tangent   Author: google   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def grad_dot(dy, x1, x2):
  """Gradient of NumPy dot product w.r.t. to the left hand side.

  Args:
    dy: The gradient with respect to the output.
    x1: The left hand side of the `numpy.dot` function.
    x2: The right hand side

  Returns:
    The gradient with respect to `x1` i.e. `x2.dot(dy.T)` with all the
    broadcasting involved.
  """
  if len(numpy.shape(x1)) == 1:
    dy = numpy.atleast_2d(dy)
  elif len(numpy.shape(x2)) == 1:
    dy = numpy.transpose(numpy.atleast_2d(dy))
    x2 = numpy.transpose(numpy.atleast_2d(x2))
  x2_t = numpy.transpose(numpy.atleast_2d(
      numpy.sum(x2, axis=tuple(numpy.arange(numpy.ndim(x2) - 2)))))
  dy_x2 = numpy.sum(dy, axis=tuple(-numpy.arange(numpy.ndim(x2) - 2) - 2))
  return numpy.reshape(numpy.dot(dy_x2, x2_t), numpy.shape(x1)) 
Example 10
Project: recordlinkage   Author: J535D165   File: nb_sklearn.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def predict_log_proba(self, X):
        """
        Return log-probability estimates for the test vector X.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]

        Returns
        -------
        C : array-like, shape = [n_samples, n_classes]
            Returns the log-probability of the samples for each class in
            the model. The columns correspond to the classes in sorted
            order, as they appear in the attribute `classes_`.
        """
        jll = self._joint_log_likelihood(X)

        # normalize by P(x) = P(f_1, ..., f_n)
        log_prob_x = logsumexp(jll, axis=1)  # return shape = (2,)

        return jll - np.atleast_2d(log_prob_x).T 
Example 11
Project: 3D-R2N2   Author: chrischoy   File: binvox_rw.py    License: MIT License 6 votes vote down vote up
def sparse_to_dense(voxel_data, dims, dtype=np.bool):
    if voxel_data.ndim != 2 or voxel_data.shape[0] != 3:
        raise ValueError('voxel_data is wrong shape; should be 3xN array.')
    if np.isscalar(dims):
        dims = [dims] * 3
    dims = np.atleast_2d(dims).T
    # truncate to integers
    xyz = voxel_data.astype(np.int)
    # discard voxels that fall outside dims
    valid_ix = ~np.any((xyz < 0) | (xyz >= dims), 0)
    xyz = xyz[:, valid_ix]
    out = np.zeros(dims.flatten(), dtype=dtype)
    out[tuple(xyz)] = True
    return out

# def get_linear_index(x, y, z, dims):
# """ Assuming xzy order. (y increasing fastest.
# TODO ensure this is right when dims are not all same
# """
# return x*(dims[1]*dims[2]) + z*dims[1] + y 
Example 12
Project: recruit   Author: Frank-qlu   File: blocks.py    License: Apache License 2.0 6 votes vote down vote up
def to_native_types(self, slicer=None, na_rep=None, date_format=None,
                        quoting=None, **kwargs):
        """ convert to our native types format, slicing if desired """

        values = self.values
        i8values = self.values.view('i8')

        if slicer is not None:
            i8values = i8values[..., slicer]

        from pandas.io.formats.format import _get_format_datetime64_from_values
        fmt = _get_format_datetime64_from_values(values, date_format)

        result = tslib.format_array_from_datetime(
            i8values.ravel(), tz=getattr(self.values, 'tz', None),
            format=fmt, na_rep=na_rep).reshape(i8values.shape)
        return np.atleast_2d(result) 
Example 13
Project: IDEA   Author: armor-ai   File: onlineLDA.py    License: MIT License 6 votes vote down vote up
def fit_transform(self, X, y=None):
        """Apply dimensionality reduction on X

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            New data, where n_samples in the number of samples
            and n_features is the number of features. Sparse matrix allowed.

        Returns
        -------
        doc_topic : array-like, shape (n_samples, n_topics)
            Point estimate of the document-topic distributions

        """

        if isinstance(X, np.ndarray):
            # in case user passes a (non-sparse) array of shape (n_features,)
            # turn it into an array of shape (1, n_features)
            X = np.atleast_2d(X)
        self._fit(X)
        return self.doc_topic_ 
Example 14
Project: svviz   Author: svviz   File: kde.py    License: MIT License 5 votes vote down vote up
def __init__(self, dataset):
        self.dataset = atleast_2d(dataset)
        if not self.dataset.size > 1:
            raise ValueError("`dataset` input should have multiple elements.")

        self.d, self.n = self.dataset.shape
        self._compute_covariance() 
Example 15
Project: svviz   Author: svviz   File: kde.py    License: MIT License 5 votes vote down vote up
def evaluate(self, points):
        points = atleast_2d(points)

        d, m = points.shape
        if d != self.d:
            if d == 1 and m == self.d:
                # points was passed in as a row vector
                points = reshape(points, (self.d, 1))
                m = 1
            else:
                msg = "points have dimension %s, dataset has dimension %s" % (d,
                    self.d)
                raise ValueError(msg)

        result = zeros((m,), dtype=np.float)

        if m >= self.n:
            # there are more points than data, so loop over data
            for i in range(self.n):
                diff = self.dataset[:, i, newaxis] - points
                tdiff = dot(self.inv_cov, diff)
                energy = sum(diff*tdiff,axis=0) / 2.0
                result = result + exp(-energy)
        else:
            # loop over points
            for i in range(m):
                diff = self.dataset - points[:, i, newaxis]
                tdiff = dot(self.inv_cov, diff)
                energy = sum(diff * tdiff, axis=0) / 2.0
                result[i] = sum(exp(-energy), axis=0)

        result = result / self._norm_factor

        return result 
Example 16
Project: svviz   Author: svviz   File: kde.py    License: MIT License 5 votes vote down vote up
def _compute_covariance(self):
        self.factor = self.scotts_factor()
        # Cache covariance and inverse covariance of the data
        if not hasattr(self, '_data_inv_cov'):
            self._data_covariance = atleast_2d(np.cov(self.dataset, rowvar=1,
                                               bias=False))
            self._data_inv_cov = linalg.inv(self._data_covariance)

        self.covariance = self._data_covariance * self.factor**2
        self.inv_cov = self._data_inv_cov / self.factor**2
        self._norm_factor = sqrt(linalg.det(2*pi*self.covariance)) * self.n 
Example 17
Project: libTLDA   Author: wmkouw   File: util.py    License: MIT License 5 votes vote down vote up
def nullspace(A, atol=1e-13, rtol=0):
    """
    Compute an approximate basis for the nullspace of A.

    INPUT   (1) array 'A': 1-D array with length k will be treated
                as a 2-D with shape (1, k).
            (2) float 'atol': the absolute tolerance for a zero singular value.
                Singular values smaller than `atol` are considered to be zero.
            (3) float 'rtol': relative tolerance. Singular values less than
                rtol*smax are considered to be zero, where smax is the largest
                singular value.

                If both `atol` and `rtol` are positive, the combined tolerance
                is the maximum of the two; tol = max(atol, rtol * smax)
                Singular values smaller than `tol` are considered to be zero.
    OUTPUT  (1) array 'B': if A is an array with shape (m, k), then B will be
                an array with shape (k, n), where n is the estimated dimension
                of the nullspace of A.  The columns of B are a basis for the
                nullspace; each element in np.dot(A, B) will be
                approximately zero.
    """
    # Expand A to a matrix
    A = np.atleast_2d(A)

    # Singular value decomposition
    u, s, vh = al.svd(A)

    # Set tolerance
    tol = max(atol, rtol * s[0])

    # Compute the number of non-zero entries
    nnz = (s >= tol).sum()

    # Conjugate and transpose to ensure real numbers
    ns = vh[nnz:].conj().T

    return ns 
Example 18
Project: mlearn   Author: materialsvirtuallab   File: test_models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.x_train = np.atleast_2d([1., 3., 5., 6., 7., 8.]).T
        self.y_train = (self.x_train * np.sin(self.x_train)).ravel()

        class DummyDescriber():
            def describe(self, obj):
                pass

            def describe_all(self, n):
                return pd.DataFrame(n)

        self.gpr = GaussianProcessRegressionModel(describer=DummyDescriber(),
                                                  kernel_category='RBF') 
Example 19
Project: mlearn   Author: materialsvirtuallab   File: test_models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fit_predict(self):
        self.gpr.fit(inputs=self.x_train, outputs=self.y_train)
        x_test = np.atleast_2d(np.linspace(0, 9, 1000)).T
        y_test = x_test * np.sin(x_test)
        y_pred, sigma = self.gpr.predict(x_test, return_std=True)
        upper_bound = y_pred + 1.96 * sigma
        lower_bound = y_pred - 1.96 * sigma
        self.assertTrue(np.all([l < y and y < u for u, y, l in zip(upper_bound, y_test, lower_bound)])) 
Example 20
Project: mlearn   Author: materialsvirtuallab   File: calcs.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _parse(self):
        element = np.atleast_1d(_read_dump('dump.element', 'unicode'))
        b = np.atleast_2d(_read_dump('dump.sna'))
        db = np.atleast_2d(_read_dump('dump.snad'))
        vb = np.atleast_2d(_read_dump('dump.snav'))
        return b, db, vb, element 
Example 21
Project: QCElemental   Author: MolSSI   File: misc.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _norm(points) -> float:
    """
    Return the Frobenius norm across axis=-1, NumPy's internal norm is crazy slow (~4x)
    """

    tmp = np.atleast_2d(points)
    return np.sqrt(np.einsum("ij,ij->i", tmp, tmp)) 
Example 22
Project: QCElemental   Author: MolSSI   File: misc.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def measure_coordinates(coordinates, measurements, degrees=False):
    """
    Measures a geometry array based on 0-based indices provided, automatically detects distance, angle,
    and dihedral based on length of measurement input.
    """

    coordinates = np.atleast_2d(coordinates)
    num_coords = coordinates.shape[0]

    single = False
    if isinstance(measurements[0], int):
        measurements = [measurements]
        single = True

    ret = []
    for num, m in enumerate(measurements):
        if any(x >= num_coords for x in m):
            raise ValueError(f"An index of measurement {num} is out of bounds.")

        kwargs = {}
        if len(m) == 2:
            func = compute_distance
        elif len(m) == 3:
            func = compute_angle
            kwargs = {"degrees": degrees}
        elif len(m) == 4:
            func = compute_dihedral
            kwargs = {"degrees": degrees}
        else:
            raise KeyError(f"Unrecognized number of arguments for measurement {num}, found {len(m)}, expected 2-4.")

        val = func(*[coordinates[x] for x in m], **kwargs)
        ret.append(float(val))

    if single:
        return ret[0]
    else:
        return ret 
Example 23
Project: QCElemental   Author: MolSSI   File: misc.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def compute_distance(points1, points2) -> np.ndarray:
    """
    Computes the distance between the provided points on a per-row basis.

    Parameters
    ----------
    points1 : array-like
        The first list of points, can be 1D or 2D
    points2 : array-like
        The second list of points, can be 1D or 2D

    Returns
    -------
    distances : np.ndarray
        The array of distances between points1 and points2

    Notes
    -----
    Units are not considered inside these expressions, please preconvert to the same units before using.

    See Also
    --------
    distance_matrix
        Computes the distance between the provided points in all rows.
        compute_distance result is the diagonal of the distance_matrix result.

    """
    points1 = np.atleast_2d(points1)
    points2 = np.atleast_2d(points2)

    return _norm(points1 - points2) 
Example 24
Project: QCElemental   Author: MolSSI   File: misc.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def compute_angle(points1, points2, points3, *, degrees: bool = False) -> np.ndarray:
    """
    Computes the angle (p1, p2 [vertex], p3) between the provided points on a per-row basis.

    Parameters
    ----------
    points1 : np.ndarray
        The first list of points, can be 1D or 2D
    points2 : np.ndarray
        The second list of points, can be 1D or 2D
    points3 : np.ndarray
        The third list of points, can be 1D or 2D
    degrees : bool, options
        Returns the angle in degrees rather than radians if True

    Returns
    -------
    angles : np.ndarray
        The angle between the three points in radians

    Notes
    -----
    Units are not considered inside these expressions, please preconvert to the same units before using.
    """

    points1 = np.atleast_2d(points1)
    points2 = np.atleast_2d(points2)
    points3 = np.atleast_2d(points3)

    v12 = points1 - points2
    v23 = points2 - points3

    denom = _norm(v12) * _norm(v23)
    cosine_angle = np.einsum("ij,ij->i", v12, v23) / denom

    angle = np.pi - np.arccos(cosine_angle)

    if degrees:
        return np.degrees(angle)
    else:
        return angle 
Example 25
Project: pymoo   Author: msu-coinlab   File: misc.py    License: Apache License 2.0 5 votes vote down vote up
def project_onto(y, p, n):
    """

    Project a point onto a plane.

    Parameters
    ----------
    y : The point that should be project
    p : A point which lies on the plane
    n : The normal vector of the plane

    Returns
    -------

    proj_y : The projection onto the plane

    """

    is_1d = False
    if len(y.shape) == 1:
        is_1d = True
        y = np.atleast_2d(y)

    # make sure the plane vector is normalized
    n = n / np.linalg.norm(n)

    proj_y = y - n[None, :] * ((y - p) @ n)[:, None]

    if is_1d:
        proj_y = proj_y[0]

    return proj_y 
Example 26
Project: pymoo   Author: msu-coinlab   File: so_cmaes.py    License: Apache License 2.0 5 votes vote down vote up
def _next(self):

        if self.pop is None or len(self.pop) == 0:
            X = next(self.es)

        else:
            F = self.pop.get("F")[:, 0].tolist()
            #
            # if self.problem.n_constr > 0:
            #     G = self.pop.get("G").tolist()
            #     self.al.set_coefficients(F, G)
            #
            #     x = self.es.gi_frame.f_locals["es"].ask(1, sigma_fac=0)[0]
            #     ind = Individual(X=x)
            #     self.evaluator.eval(self.problem, ind, algorithm=self)
            #     self.al.update(ind.F[0], ind.G)
            #
            #     F = F + sum(self.al(G))

            if not self.send_array_to_yield:
                F = F[0]

            try:
                X = self.es.send(F)
            except StopIteration:
                X = None
                self.termination.force_termination = True

        if X is not None:
            X = np.array(X)
            self.send_array_to_yield = X.ndim > 1
            X = np.atleast_2d(X)

            # evaluate the population
            self.pop = Population().new("X", X)
            self.evaluator.eval(self.problem, self.pop, algorithm=self)

            # set infeasible individual's objective values to np.nan - then CMAES can handle it
            for ind in self.pop:
                if not ind.feasible[0]:
                    ind.F[0] = np.nan 
Example 27
Project: pymoo   Author: msu-coinlab   File: go_funcs_T.py    License: Apache License 2.0 5 votes vote down vote up
def fun(self, x, *args):
        self.nfev += 1
        i = atleast_2d(arange(1.0, self.N + 1)).T
        inner = cos(x) + i * (1 - cos(x) - sin(x))
        return sum((self.N - sum(inner, axis=1)) ** 2) 
Example 28
Project: pymoo   Author: msu-coinlab   File: go_funcs_H.py    License: Apache License 2.0 5 votes vote down vote up
def fun(self, x, *args):
        self.nfev += 1

        XX = np.atleast_2d(x)
        d = sum(self.a * (XX - self.p) ** 2, axis=1)
        return -sum(self.c * exp(-d)) 
Example 29
Project: pymoo   Author: msu-coinlab   File: go_funcs_H.py    License: Apache License 2.0 5 votes vote down vote up
def fun(self, x, *args):
        self.nfev += 1

        XX = np.atleast_2d(x)
        d = sum(self.a * (XX - self.p) ** 2, axis=1)
        return -sum(self.c * exp(-d)) 
Example 30
Project: pymoo   Author: msu-coinlab   File: go_funcs_W.py    License: Apache License 2.0 5 votes vote down vote up
def fun(self, x, *args):
        self.nfev += 1

        i = atleast_2d(arange(30.)).T
        a = i / 29.
        j = arange(5.)
        k = arange(6.)

        t1 = sum((j + 1) * a ** j * x[1:], axis=1)
        t2 = sum(a ** k * x, axis=1)

        inner = (t1 - t2 ** 2 - 1) ** 2

        return sum(inner) + x[0] ** 2