Python numpy.full() Examples

The following are 30 code examples of numpy.full(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: so_cmaes.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def initialize(self, problem, seed=None, **kwargs):
        super().initialize(problem, **kwargs)
        self.n_gen = 0

        xl = problem.xl.tolist() if problem.xl is not None else None
        xu = problem.xu.tolist() if problem.xu is not None else None

        self.options['bounds'] = [xl, xu]
        self.options['seed'] = seed

        if isinstance(self.termination, MaximumGenerationTermination):
            self.options['maxiter'] = self.termination.n_max_gen
        elif isinstance(self.termination, MaximumFunctionCallTermination):
            self.options['maxfevals'] = self.termination.n_max_evals

        # if self.problem.n_constr > 0:
        #     _al = AugmentedLagrangian(problem.n_var)
        #     _al.set_m(problem.n_constr)
        #     _al._equality = np.full(problem.n_constr, False)
        #     self.al = _al
        #     kwargs.setdefault('options', {}).setdefault('tolstagnation', 0) 
Example #2
Source File: retinotopy.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def _retinotopic_field_sign_triangles(m, retinotopy):
    t = m.tess if isinstance(m, geo.Mesh) or isinstance(m, geo.Topology) else m
    # get the polar angle and eccen data as a complex number in degrees
    if pimms.is_str(retinotopy):
        (x,y) = as_retinotopy(retinotopy_data(m, retinotopy), 'geographical')
    elif retinotopy is Ellipsis:
        (x,y) = as_retinotopy(retinotopy_data(m, 'any'),      'geographical')
    else:
        (x,y) = as_retinotopy(retinotopy,                     'geographical')
    # Okay, now we want to make some coordinates...
    coords = np.asarray([x, y])
    us = coords[:, t.indexed_faces[1]] - coords[:, t.indexed_faces[0]]
    vs = coords[:, t.indexed_faces[2]] - coords[:, t.indexed_faces[0]]
    (us,vs) = [np.concatenate((xs, np.full((1, t.face_count), 0.0))) for xs in [us,vs]]
    xs = np.cross(us, vs, axis=0)[2]
    xs[np.isclose(xs, 0)] = 0
    return np.sign(xs) 
Example #3
Source File: core.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def cos_edge(f=Ellipsis, width=np.pi, offset=0, scale=1):
    '''
    cos_edge() yields a potential function g(x) that calculates 0 for x < pi/2, 1 for x > pi/2, and
      0.5*(1 + cos(pi/2*(1 - x))) for x between -pi/2 and pi/2.
    
    The full formulat of the cosine well is, including optional arguments:
      scale/2 * (1 + cos(pi*(0.5 - (x - offset)/width)

    The following optional arguments may be given:
      * width (default: pi) specifies that the frequency of the cos-curve should be pi/width; the
        width is the distance between the points on the cos-curve with the value of 1.
      * offset (default: 0) specifies the offset of the minimum value of the coine curve on the
        x-axis.
      * scale (default: 1) specifies the height of the cosine well.
    '''
    f = to_potential(f)
    freq = np.pi/2
    (xmn,xmx) = (offset - width/2, offset + width/2)
    F = piecewise(scale,
                  ((-np.inf, xmn), 0),
                  ((xmn,xmx), scale/2 * (1 + cos(np.pi*(0.5 - (identity - offset)/width)))))
    if   is_const_potential(f):    return const_potential(F.value(f.c))
    elif is_identity_potential(f): return F
    else:                          return compose(F, f) 
Example #4
Source File: files.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def find_subject_path(sid, check_path=True):
    '''
    find_subject_path(sub) yields the full path of a HCP subject with the name given by the string
      sub, if such a subject can be found in the HCP search paths. See also add_subject_path.

    If no subject is found, then None is returned.
    '''
    # if it's a full/relative path already, use it:
    sub = str(sid)
    if ((not check_path or is_hcp_subject_path(sub)) and
        (check_path is None or os.path.isdir(sub))):
        return sub
    # check the subject directories:
    sdirs = config['hcp_subject_paths']
    return next((os.path.abspath(p) for sd in sdirs
                 for p in [os.path.join(sd, sub)]
                 if ((not check_path or is_hcp_subject_path(p)) and
                     (check_path is None or os.path.isdir(p)))),
                None) 
Example #5
Source File: core.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def face_areas(faces, axis=1):
    '''
    face_areas(faces) yields a potential function f(x) that calculates the unsigned area of each
      faces represented by the simplices matrix faces.

    If faces is None, then the parameters must arrive in the form of a flattened (n x 3 x 2) matrix
    where n is the number of triangles. Otherwise, the faces matrix must be either (n x 3) or (n x 3
    x s); if the former, each row must list the vertex indices for the faces where the vertex matrix
    is presumed to be shaped (V x 2). Alternately, faces may be a full (n x 3 x 2) simplex array of
    the indices into the parameters.

    The optional argument axis (default: 1) may be set to 0 if the faces argument is a matrix but
    the coordinate matrix will be (2 x V) instead of (V x 2).
    '''
    faces = np.asarray(faces)
    if len(faces.shape) == 2:
        if faces.shape[1] != 3: faces = faces.T
        n = 2 * (np.max(faces) + 1)
        if axis == 0: tmp = np.reshape(np.arange(n), (2,-1)).T
        else:         tmp = np.reshape(np.arange(n), (-1,2))
        faces = np.reshape(tmp[faces.flat], (-1,3,2))
    faces = faces.flatten()
    return compose(TriangleArea2DPotential(), part(Ellipsis, faces)) 
Example #6
Source File: core.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def signed_face_areas(faces, axis=1):
    '''
    signed_face_areas(faces) yields a potential function f(x) that calculates the signed area of
      each face represented by the simplices matrix faces.

    If faces is None, then the parameters must arrive in the form of a flattened (n x 3 x 2) matrix
    where n is the number of triangles. Otherwise, the faces matrix must be either (n x 3) or (n x 3
    x s); if the former, each row must list the vertex indices for the faces where the vertex matrix
    is presumed to be shaped (V x 2). Alternately, faces may be a full (n x 3 x 2) simplex array of
    the indices into the parameters.

    The optional argument axis (default: 1) may be set to 0 if the faces argument is a matrix but
    the coordinate matrix will be (2 x V) instead of (V x 2).
    '''
    faces = np.asarray(faces)
    if len(faces.shape) == 2:
        if faces.shape[1] != 3: faces = faces.T
        n = 2 * (np.max(faces) + 1)
        if axis == 0: tmp = np.reshape(np.arange(n), (2,-1)).T
        else:         tmp = np.reshape(np.arange(n), (-1,2))
        faces = np.reshape(tmp[faces.flat], (-1,3,2))
    faces = faces.flatten()
    return compose(TriangleSignedArea2DPotential(), part(Ellipsis, faces)) 
Example #7
Source File: dist_sync_kvstore.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def test_gluon_trainer_step():
    def check_trainer_step():
        ctx = mx.cpu(0)
        shape = (10, 1)
        x = mx.gluon.Parameter('x', shape=shape)
        x.initialize(ctx=ctx, init='ones')
        trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 1.0, 'multi_precision': False}, kvstore=kv)
        with mx.autograd.record():
            w = x.data(ctx)
            y = (my_rank + 1) * w
            y.backward()
        trainer.step(1)
        expected = 1 - (1 + nworker) * nworker / 2
        assert_almost_equal(x.data(ctx).asnumpy(), np.full(shape, expected))
    check_trainer_step()
    print('worker ' + str(my_rank) + ' passed test_gluon_trainer_step') 
Example #8
Source File: dist_sync_kvstore.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def test_gluon_trainer_sparse_step():
    def check_trainer_sparse_step():
        ctx = mx.cpu(0)
        shape = (2, 10)
        all_rows = mx.nd.arange(0, shape[0], ctx=ctx)
        x = mx.gluon.Parameter('x', shape=shape, stype='row_sparse', grad_stype='row_sparse')
        x.initialize(ctx=ctx, init='ones')
        trainer = mx.gluon.Trainer([x], 'sgd', {'learning_rate': 1.0}, kvstore=kv)
        with mx.autograd.record():
            w = x.row_sparse_data(all_rows)
            y = (my_rank + 1) * w
            y.backward()
        trainer.step(1)
        expected = 1 - (1 + nworker) * nworker / 2
        assert_almost_equal(x.row_sparse_data(all_rows).asnumpy(), np.full(shape, expected))
    check_trainer_sparse_step()
    print('worker ' + str(my_rank) + ' passed test_gluon_trainer_sparse_step') 
Example #9
Source File: visualization_utils_test.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def create_colorful_test_image(self):
    """This function creates an image that can be used to test vis functions.

    It makes an image composed of four colored rectangles.

    Returns:
      colorful test numpy array image.
    """
    ch255 = np.full([100, 200, 1], 255, dtype=np.uint8)
    ch128 = np.full([100, 200, 1], 128, dtype=np.uint8)
    ch0 = np.full([100, 200, 1], 0, dtype=np.uint8)
    imr = np.concatenate((ch255, ch128, ch128), axis=2)
    img = np.concatenate((ch255, ch255, ch0), axis=2)
    imb = np.concatenate((ch255, ch0, ch255), axis=2)
    imw = np.concatenate((ch128, ch128, ch128), axis=2)
    imu = np.concatenate((imr, img), axis=1)
    imd = np.concatenate((imb, imw), axis=1)
    image = np.concatenate((imu, imd), axis=0)
    return image 
Example #10
Source File: auto_complete_fixed.py    From post--memorization-in-rnns with MIT License 6 votes vote down vote up
def make_source_target_alignment(self, sequence):
        space_char_code = self._char_map_inverse[' ']
        unknown_word_code = self._word_map_inverse['<unknown>']

        source = []
        target = []
        length = 0

        for word in sequence.split(' '):
            source.append(
                np.array([space_char_code] + self.encode_source(word),
                         dtype='int32')
            )
            target.append(
                np.full(len(word) + 1, self.encode_target([word])[0],
                        dtype='int32')
            )
            length += 1 + len(word)

        # concatenate data
        return (
            length,
            np.concatenate(source),
            np.concatenate(target)
        ) 
Example #11
Source File: running_mean_std.py    From HardRLWithYoutube with MIT License 6 votes vote down vote up
def __init__(self, epsilon=1e-4, shape=(), scope=''):
        sess = get_session()

        self._new_mean = tf.placeholder(shape=shape, dtype=tf.float64)
        self._new_var = tf.placeholder(shape=shape, dtype=tf.float64)
        self._new_count = tf.placeholder(shape=(), dtype=tf.float64)

        
        with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
            self._mean  = tf.get_variable('mean',  initializer=np.zeros(shape, 'float64'),      dtype=tf.float64)
            self._var   = tf.get_variable('std',   initializer=np.ones(shape, 'float64'),       dtype=tf.float64)    
            self._count = tf.get_variable('count', initializer=np.full((), epsilon, 'float64'), dtype=tf.float64)

        self.update_ops = tf.group([
            self._var.assign(self._new_var),
            self._mean.assign(self._new_mean),
            self._count.assign(self._new_count)
        ])

        sess.run(tf.variables_initializer([self._mean, self._var, self._count]))
        self.sess = sess
        self._set_mean_var_count() 
Example #12
Source File: wfg.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def _positional_to_optimal(self, K):
        k, l = self.k, self.l

        suffix = np.full((len(K), self.l), 0.0)
        X = np.column_stack([K, suffix])
        X[:, self.k + self.l - 1] = 0.35

        for i in range(self.k + self.l - 2, self.k - 1, -1):
            m = X[:, i + 1:k + l]
            val = m.sum(axis=1) / m.shape[1]
            X[:, i] = 0.35 ** ((0.02 + 1.96 * val) ** -1)

        ret = X * (2 * (np.arange(self.n_var) + 1))
        return ret


# ---------------------------------------------------------------------------------------------------------
# TRANSFORMATIONS
# --------------------------------------------------------------------------------------------------------- 
Example #13
Source File: replacement.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def _do(self, problem, pop, off, **kwargs):
        ret = np.full((len(pop), 1), False)

        pop_F, pop_CV, pop_feasible = pop.get("F", "CV", "feasible")
        off_F, off_CV, off_feasible = off.get("F", "CV", "feasible")

        if problem.n_constr > 0:

            # 1) Both infeasible and constraints have been improved
            ret[(~pop_feasible & ~off_feasible) & (off_CV < pop_CV)] = True

            # 2) A solution became feasible
            ret[~pop_feasible & off_feasible] = True

            # 3) Both feasible but objective space value has improved
            ret[(pop_feasible & off_feasible) & (off_F < pop_F)] = True

        else:
            ret[off_F < pop_F] = True

        return ret[:, 0] 
Example #14
Source File: usage_ga_custom.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def _do(self, problem, X, **kwargs):
        n_parents, n_matings, n_var = X.shape

        _X = np.full((self.n_offsprings, n_matings, problem.n_var), False)

        for k in range(n_matings):
            p1, p2 = X[0, k], X[1, k]

            both_are_true = np.logical_and(p1, p2)
            _X[0, k, both_are_true] = True

            n_remaining = problem.n_max - np.sum(both_are_true)

            I = np.where(np.logical_xor(p1, p2))[0]

            S = I[np.random.permutation(len(I))][:n_remaining]
            _X[0, k, S] = True

        return _X 
Example #15
Source File: mixed_variable_operator.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def _do(self, problem, X, **kwargs):

        _, n_matings, n_var = X.shape

        def fun(mask, operator):
            return operator._do(problem, X[..., mask], **kwargs)

        ret = apply_mixed_variable_operation(problem, self.process, fun)

        # for the crossover the concatenation is different through the 3d arrays.
        X = np.full((self.n_offsprings, n_matings, n_var), np.nan, dtype=np.object)
        for i in range(len(self.process)):
            mask, _X = self.process[i]["mask"], ret[i]
            X[..., mask] = _X

        return X 
Example #16
Source File: visualization_utils_test.py    From object_detector_app with MIT License 6 votes vote down vote up
def create_colorful_test_image(self):
    """This function creates an image that can be used to test vis functions.

    It makes an image composed of four colored rectangles.

    Returns:
      colorful test numpy array image.
    """
    ch255 = np.full([100, 200, 1], 255, dtype=np.uint8)
    ch128 = np.full([100, 200, 1], 128, dtype=np.uint8)
    ch0 = np.full([100, 200, 1], 0, dtype=np.uint8)
    imr = np.concatenate((ch255, ch128, ch128), axis=2)
    img = np.concatenate((ch255, ch255, ch0), axis=2)
    imb = np.concatenate((ch255, ch0, ch255), axis=2)
    imw = np.concatenate((ch128, ch128, ch128), axis=2)
    imu = np.concatenate((imr, img), axis=1)
    imd = np.concatenate((imb, imw), axis=1)
    image = np.concatenate((imu, imd), axis=0)
    return image 
Example #17
Source File: point_crossover.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def _do(self, problem, X, **kwargs):

        # get the X of parents and count the matings
        _, n_matings, n_var = X.shape

        # start point of crossover
        r = np.row_stack([np.random.permutation(n_var - 1) + 1 for _ in range(n_matings)])[:, :self.n_points]
        r.sort(axis=1)
        r = np.column_stack([r, np.full(n_matings, n_var)])

        # the mask do to the crossover
        M = np.full((n_matings, n_var), False)

        # create for each individual the crossover range
        for i in range(n_matings):

            j = 0
            while j < r.shape[1] - 1:
                a, b = r[i, j], r[i, j + 1]
                M[i, a:b] = True
                j += 2

        _X = crossover_mask(X, M)

        return _X 
Example #18
Source File: half_uniform_crossover.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def _do(self, problem, X, **kwargs):
        _, n_matings, n_var = X.shape

        # the mask do to the crossover
        M = np.full((n_matings, n_var), False)

        not_equal = X[0] != X[1]

        # create for each individual the crossover range
        for i in range(n_matings):
            I = np.where(not_equal[i])[0]

            n = math.ceil(len(I) / 2)
            if n > 0:
                _I = I[np.random.permutation(len(I))[:n]]
                M[i, _I] = True

        _X = crossover_mask(X, M)
        return _X 
Example #19
Source File: ctaea.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def comp_by_cv_dom_then_random(pop, P, **kwargs):
    S = np.full(P.shape[0], np.nan)

    for i in range(P.shape[0]):
        a, b = P[i, 0], P[i, 1]

        if pop[a].CV <= 0.0 and pop[b].CV <= 0.0:
            rel = Dominator.get_relation(pop[a].F, pop[b].F)
            if rel == 1:
                S[i] = a
            elif rel == -1:
                S[i] = b
            else:
                S[i] = np.random.choice([a, b])
        elif pop[a].CV <= 0.0:
            S[i] = a
        elif pop[b].CV <= 0.0:
            S[i] = b
        else:
            S[i] = np.random.choice([a, b])

    return S[:, None].astype(np.int) 
Example #20
Source File: rnsga2.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def __init__(self, ref_points,
                 epsilon,
                 weights,
                 normalization,
                 extreme_points_as_reference_points
                 ) -> None:

        super().__init__(True)
        self.n_obj = ref_points.shape[1]
        self.ref_points = ref_points
        self.epsilon = epsilon
        self.extreme_points_as_reference_points = extreme_points_as_reference_points

        self.weights = weights
        if self.weights is None:
            self.weights = np.full(self.n_obj, 1 / self.n_obj)

        self.normalization = normalization
        self.ideal_point = np.full(self.n_obj, np.inf)
        self.nadir_point = np.full(self.n_obj, -np.inf) 
Example #21
Source File: sfd.py    From dustmaps with GNU General Public License v2.0 6 votes vote down vote up
def query(self, coords, order=1):
        """
        Returns the map value at the specified location(s) on the sky.

        Args:
            coords (`astropy.coordinates.SkyCoord`): The coordinates to query.
            order (Optional[int]): Interpolation order to use. Defaults to `1`,
                for linear interpolation.

        Returns:
            A float array containing the map value at every input coordinate.
            The shape of the output will be the same as the shape of the
            coordinates stored by `coords`.
        """
        out = np.full(len(coords.l.deg), np.nan, dtype='f4')

        for pole in self.poles:
            m = (coords.b.deg >= 0) if pole == 'ngp' else (coords.b.deg < 0)

            if np.any(m):
                data, w = self._data[pole]
                x, y = w.wcs_world2pix(coords.l.deg[m], coords.b.deg[m], 0)
                out[m] = map_coordinates(data, [y, x], order=order, mode='nearest')

        return out 
Example #22
Source File: random_permutation_sampling.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def _do(self, problem, n_samples, **kwargs):
        X = np.full((n_samples, problem.n_var), 0, dtype=np.int)
        for i in range(n_samples):
            X[i, :] = np.random.permutation(problem.n_var)
        return X 
Example #23
Source File: exponential_crossover.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def _do(self, problem, X, **kwargs):

        # get the X of parents and count the matings
        _, n_matings, n_var = X.shape

        # the mask do to the crossover
        M = np.full((n_matings, n_var), False)

        # start point of crossover
        n = np.random.randint(0, n_var, size=X.shape[1])

        # the probabilities are calculated beforehand
        r = np.random.random((n_matings, n_var)) < self.prob_exp

        # create for each individual the crossover range
        for i in range(n_matings):

            # the actual index where we start
            start = n[i]
            for j in range(problem.n_var):

                # the current position where we are pointing to
                current = (start + j) % problem.n_var

                # replace only if random value keeps being smaller than CR
                if r[i, current]:
                    M[i, current] = True
                else:
                    break

        _X = crossover_mask(X, M)
        return _X 
Example #24
Source File: edge_recombination_crossover.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def _do(self, problem, X, **kwargs):
        _, n_matings, n_var = X.shape
        Y = np.full((self.n_offsprings, n_matings, n_var), -1, dtype=np.int)

        for i in range(n_matings):
            a, b = X[:, i, :]
            Y[0, i, :] = erx(a, b)

        return Y 
Example #25
Source File: nelder_mead_crossover.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def do(self, problem, pop, parents, **kwargs):
        n = problem.n_var - 1

        # obtain the matrices from the population
        X = pop.get("X")[parents]
        F = pop.get("F")[parents][..., 0]

        # the array to fill
        _X = np.full((len(X), problem.n_var), np.nan)

        for k, P in enumerate(parents):
            # sort the x values by their corresponding F values
            x = X[k, :][np.argsort(F[k])]

            # calculate the centroid of n best points
            centroid = x[:n + 1].mean(axis=0)

            # calculate the vector from the worst to the centroid
            v = centroid - x[n + 1]

            # maximum factor until the boundaries are hit
            max_factor = max_expansion_factor(centroid, v, problem)

            # randomly chose the extension, expansion or contraction through a factor
            factor = np.random.random() * min(3, max_factor)

            # calculate the offspring
            _X[k] = x[n + 1] + factor * v

        return pop.new("X", _X) 
Example #26
Source File: non_dominated_sorting.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def rank_from_fronts(fronts, n):
    # create the rank array and set values
    rank = np.full(n, 1e16, dtype=np.int)
    for i, front in enumerate(fronts):
        rank[front] = i

    return rank


# Returns all indices of F that are not dominated by the other objective values 
Example #27
Source File: reference_direction.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def das_dennis(n_partitions, n_dim):
    if n_partitions == 0:
        return np.full((1, n_dim), 1 / n_dim)
    else:
        ref_dirs = []
        ref_dir = np.full(n_dim, np.nan)
        das_dennis_recursion(ref_dirs, ref_dir, n_partitions, n_partitions, 0)
        return np.concatenate(ref_dirs, axis=0) 
Example #28
Source File: clearing.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def __init__(self,
                 D,
                 epsilon) -> None:
        super().__init__()

        if isinstance(D, tuple):
            self.n, self.D = D
        else:
            self.D = D
            self.n = len(D)

        self.epsilon = epsilon

        self.S = []
        self.C = np.full(self.n, False) 
Example #29
Source File: clearing.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def reset(self):
        self.C = np.full(self.n, False)
        self.C[self.S] = True 
Example #30
Source File: das_dennis.py    From pymoo with Apache License 2.0 5 votes vote down vote up
def traverse(self, func, n_points=None):

        if self.n_partitions == 0:
            return np.full((1, self.n_dim), 1 / self.n_dim)

        counter = 0

        while (n_points is None or counter < n_points) and len(self.stack) > 0:

            point, beta = self.stack.pop()

            if len(point) + 1 == self.n_dim:
                point.append(beta / (1.0 * self.n_partitions))

                if self.scaling is not None:
                    point = [p * self.scaling + ((1 - self.scaling) / len(point)) for p in point]

                func(point)
                counter += 1
            else:
                for i in range(beta + 1):
                    _point = list(point)
                    _point.append(1.0 * i / (1.0 * self.n_partitions))
                    self.stack.append((_point, beta - i))

        return counter