numpy.append

Here are the examples of the python api numpy.append taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1395 Examples 7

5 Source : metronome.py
with MIT License
from eupston

    def generate_metronome_audio(self):
        seconds_per_beat = 1/((self.BPM * self.subdivide)/60)
        audio = self.beep(880,seconds_per_beat*self.beat_proportion)
        audio = numpy.append(audio, numpy.zeros(
            int(seconds_per_beat*(1-self.beat_proportion)*self.RATE)))
        for x in range(self.subdivide-1):
            sub_beep = self.beep(440,seconds_per_beat*self.beat_proportion)
            audio = numpy.append(audio, sub_beep)
            audio = numpy.append(audio, numpy.zeros(
                int(seconds_per_beat*(1-self.beat_proportion)*self.RATE)))
        return audio.astype(numpy.float32)

    def start(self):

5 Source : boundary_conditions.py
with MIT License
from zfergus

    def passive_elements(self):
        """:obj:`numpy.ndarray`: Passives on the left, middle, and right."""
        X1, Y1 = numpy.mgrid[0:(self.nelx // 5),
                             (self.nely // 4):(3 * self.nely // 4)]
        X2, Y2 = numpy.mgrid[(2 * self.nelx // 5):(3 * self.nelx // 5),
                             (self.nely // 4):(3 * self.nely // 4)]
        X3, Y3 = numpy.mgrid[(4 * self.nelx // 5):self.nelx,
                             (self.nely // 4):(3 * self.nely // 4)]
        X = numpy.append(numpy.append(X1.ravel(), X2.ravel()), X3.ravel())
        Y = numpy.append(numpy.append(Y1.ravel(), Y2.ravel()), Y3.ravel())
        pairs = numpy.vstack([X.ravel(), Y.ravel()]).T
        passive_to_ids = numpy.vectorize(lambda xy: xy_to_id(
            *xy, nelx=self.nelx - 1, nely=self.nely - 1), signature="(m)->()")
        return passive_to_ids(pairs)

3 Source : vrl_model.py
with MIT License
from 95616ARG

    def disjunctive_safe_set(self):
        """Set of points in the safe_set that are not in the hole_set.

        See the comment in hole_set --- these are the only points we "actually"
        need to care about.
        """
        hole_A_ub = self.hole_set()
        safe_A_ub = self.safe_set(as_box=False)
        planes = []
        for hole_face in hole_A_ub:
            appended = np.append(safe_A_ub, [-hole_face], axis=0)
            vertices = pypoman.polygon.compute_polygon_hull(appended[:, :-1],
                                                            -appended[:, -1])
            planes.append(np.array(vertices))
            safe_A_ub = np.append(safe_A_ub, [hole_face], axis=0)
        return planes

3 Source : create_IMDB_dataframe.py
with MIT License
from Abhishek-Doshi

def appendImgToNPA(image, arr, name):
    print('Processing image ', name)
    vec = getFeatureVector(image)
    arr = np.append(arr, [vec], axis = 0)
    return arr

for filename in img_list:

3 Source : create_yale_dataframe.py
with MIT License
from Abhishek-Doshi

def appendImgToNPA(image, arr, name):
    print('Processing image ', name)
    vec = getFeatureVector(image)
    arr = np.append(arr, [vec], axis = 0)
    return arr

'''

3 Source : lfw_data.py
with MIT License
from Abhishek-Doshi

def appendImgToNPA(image, arr):
    vec = getFeatureVector(image)
    arr = np.append(arr, [vec], axis = 0)
    return arr

def generate_np_matrix(source = None):

3 Source : pposgd_simple.py
with MIT License
from AcutronicRobotics

def add_vtarg_and_adv(seg, gamma, lam):
    """
    Compute target value using TD(lambda) estimator, and advantage with GAE(lambda)
    """
    new = np.append(seg["new"], 0) # last element is only used for last vtarg, but we already zeroed it if last new = 1
    vpred = np.append(seg["vpred"], seg["nextvpred"])
    T = len(seg["rew"])
    seg["adv"] = gaelam = np.empty(T, 'float32')
    rew = seg["rew"]
    lastgaelam = 0
    for t in reversed(range(T)):
        nonterminal = 1-new[t+1]
        delta = rew[t] + gamma * vpred[t+1] * nonterminal - vpred[t]
        gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam
    seg["tdlamret"] = seg["adv"] + seg["vpred"]

def learn(env, policy_fn, *,

3 Source : pposgd_simple_local.py
with MIT License
from AcutronicRobotics

def add_vtarg_and_adv(seg, gamma, lam):
    new = np.append(seg["new"], 0) # last element is only used for last vtarg, but we already zeroed it if last new = 1
    vpred = np.append(seg["vpred"], seg["nextvpred"])
    T = len(seg["rew"])
    seg["adv"] = gaelam = np.ones(T, 'float32')
    rew = seg["rew"]
    lastgaelam = 0
    for t in reversed(range(T)):
        nonterminal = 1-new[t+1]
        delta = rew[t] + gamma * vpred[t+1] * nonterminal - vpred[t]
        gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam
    seg["tdlamret"] = seg["adv"] + seg["vpred"]

def learn(env, policy_fn, reward_giver, expert_dataset,

3 Source : trpo_mpi.py
with MIT License
from AcutronicRobotics

def add_vtarg_and_adv(seg, gamma, lam):
    new = np.append(seg["new"], 0)  # last element is only used for last vtarg, but we already zeroed it if last new = 1
    vpred = np.append(seg["vpred"], seg["nextvpred"])
    T = len(seg["rew"])
    seg["adv"] = gaelam = np.empty(T, 'float32')
    rew = seg["rew"]
    lastgaelam = 0
    for t in reversed(range(T)):
        nonterminal = 1-new[t+1]
        delta = rew[t] + gamma * vpred[t+1] * nonterminal - vpred[t]
        gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam
    seg["tdlamret"] = seg["adv"] + seg["vpred"]


def learn(env, policy_func, reward_giver, expert_dataset, rank,

3 Source : trpo_mpi_local.py
with MIT License
from AcutronicRobotics

def add_vtarg_and_adv(seg, gamma, lam):
    new = np.append(seg["new"], 0)  # last element is only used for last vtarg, but we already zeroed it if last new = 1
    vpred = np.append(seg["vpred"], seg["nextvpred"])
    T = len(seg["rew"])
    seg["adv"] = gaelam = np.empty(T, 'float32')
    rew = seg["rew"]
    lastgaelam = 0
    for t in reversed(range(T)):
        nonterminal = 1-new[t+1]
        delta = rew[t] + gamma * vpred[t+1] * nonterminal - vpred[t]
        gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam
    seg["tdlamret"] = seg["adv"] + seg["vpred"]

#                                                          0
def learn(env, policy_func, reward_giver, expert_dataset, rank,

3 Source : trpo_mpi.py
with MIT License
from AcutronicRobotics

def add_vtarg_and_adv(seg, gamma, lam):
    new = np.append(seg["new"], 0) # last element is only used for last vtarg, but we already zeroed it if last new = 1
    vpred = np.append(seg["vpred"], seg["nextvpred"])
    T = len(seg["rew"])
    seg["adv"] = gaelam = np.empty(T, 'float32')
    rew = seg["rew"]
    lastgaelam = 0
    for t in reversed(range(T)):
        nonterminal = 1-new[t+1]
        delta = rew[t] + gamma * vpred[t+1] * nonterminal - vpred[t]
        gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam
    seg["tdlamret"] = seg["adv"] + seg["vpred"]

def learn(*,

3 Source : _binary_approximation.py
with GNU Lesser General Public License v3.0
from adbuerger

    def _remove_inactive_controls(self) -> None:

        self._t = np.append(self._binapprox.t[self._t_active], self._binapprox.t[-1])

        self._b_rel = self._b_rel[np.ix_(self._b_active, self._t_active)]
        self._b_valid = self._b_valid[np.ix_(self._b_active, self._t_active)]
        self._b_adjacencies = self._b_adjacencies[np.ix_(self._b_active, self._b_active)]

        self._n_max_switches = self._n_max_switches[self._b_active]
        self._min_up_times = self._min_up_times[self._b_active]
        self._min_down_times = self._min_down_times[self._b_active]
        self._max_up_times = self._max_up_times[self._b_active]
        self._total_max_up_times = self._total_max_up_times[self._b_active]
   
        self._b_bin_pre = self._b_bin_pre[self._b_active]


    def __init__(self, binapprox: BinApprox) -> None:

3 Source : tpsolver.py
with GNU General Public License v3.0
from adtzlr

def f(Vred,V0red,j,Vmax,equilibrium,stiffness,analysis=None,statev_write=False):
    """equilibrium function, extended to (nDOF+1)"""
    
    analysis.j = j
    
    return np.append(-equilibrium(Vred,V0red,
                                  analysis=analysis,
                                  statev_write=statev_write),
                     Vred[abs(j)-1]-Vmax)

def dfdx(Vred,V0red,j,Vmax,equilibrium,stiffness,analysis=None,statev_write=False):

3 Source : bazin.py
with MIT License
from aerdem4

def get_params(object_id_list, lc_df, result_queue):
    results = {}
    for object_id in object_id_list:
        light_df = lc_df[lc_df["object_id"] == object_id]
        try:
            result = fit_scipy(light_df["mjd"].values, light_df["low_passband"].values,
                               light_df["flux"].values, light_df["flux_err"].values)
            results[object_id] = np.append(result.x, [result.cost, result.status, result.t_shift])
        except Exception as e:
            print(e)
            results[object_id] = None
    result_queue.put(results)


def parallelize(meta_df, df):

3 Source : fixed_coordinate_system.py
with GNU General Public License v3.0
from AIHunters

def homography_transformation(coords_vector, matr_H, vector_len=3):
    if len(coords_vector)   <   vector_len:
        coords_vector = np.append(coords_vector, [1])
    new_vector = np.dot(matr_H, coords_vector)
    return new_vector[:-1] / new_vector[-1]


def inverse_homography_transformation(coords_vector, matr_H, vector_len=3):

3 Source : fixed_coordinate_system.py
with GNU General Public License v3.0
from AIHunters

def inverse_homography_transformation(coords_vector, matr_H, vector_len=3):
    if len(coords_vector)   <   vector_len:
        coords_vector = np.append(coords_vector, [1])
    new_vector = np.dot(linalg.inv(matr_H), coords_vector)
    return new_vector[:-1] / new_vector[-1]


def to_fixed_coordinate_system(clean_meta, homography_dict,

3 Source : _meshing.py
with Apache License 2.0
from airinnova

    def get_all_points(self, beam_idx):
        """Return an array (n x 3) with all node coordinates"""
        xyz = self.beams[beam_idx][0].p1.coord.reshape((1, 3))
        for elem in self.beams[beam_idx].values():
            xyz = np.append(xyz, elem.p2.coord.reshape((1, 3)), axis=0)
        return xyz

    def get_lims_beam(self, beam_idx):

3 Source : utils.py
with GNU General Public License v3.0
from akpetty

def bin_oib(xptsOIB, yptsOIB, xptsG, yptsG, oibVar):
	""" Bin data using numpy histogram"""

	xbins = yptsG[:, 0]+(dx/2) # these are the columns which are actually the y values
	ybins = xptsG[0]+(dx/2) 
	xbins=np.append(xbins, xbins[-1]+dx)
	ybins=np.append(ybins, ybins[-1]+dx)

	denominator, xedges, yedges = np.histogram2d(xptsOIB, yptsOIB,bins=(xbins, ybins))
	nominator, _, _ = np.histogram2d(xptsOIB, yptsOIB,bins=(xbins, ybins), weights=oibVar)
	oibG = nominator / denominator
	
	# transpose to go from columns/rows to x/y
	oibG=oibG.T
	return oibG

def getLeapYr(year):

3 Source : TrainModel.py
with MIT License
from akshaybahadur21

def augmentData(features, labels):
    features = np.append(features, features[:, :, ::-1], axis=0)
    labels = np.append(labels, -labels, axis=0)
    return features, labels


def main():

3 Source : QD_trainer.py
with MIT License
from akshaybahadur21

def augmentData(features, labels):
    features = np.append(features, features[:, :, ::-1], axis=0)
    labels = np.append(labels, -labels, axis=0)
    return features, labels


def prepress_labels(labels):

3 Source : shear_force.py
with MIT License
from albiboni

def compute_q(position):
    Vy, Vz = get_forces(position, theta) #first entry refers to the position
    qb = get_qb(NSpS, Iyy, Izz, Vz, Vy, BrA)
    qs01 = get_Qs01(h_a, qb, Sa, t_sk, t_sp, StrinLoc)
    qs02 = get_Qs02(h_a, qb, Sa, t_sk, t_sp, StrinLoc)
    q_shear = get_q_shear(NSpS, Iyy, Izz, Vz, Vy, BrA, qs01, qs02)
    q_T=get_q_torque(position)
    q_circle = q_shear[:2]+q_T[2],
    q_spar = q_shear[9]+q_T[2]-q_T[3]
    q_triangle = q_shear[2:9] + q_T[3]
    q_tot = np.append(q_circle,np.append(q_triangle,q_spar))
    return q_tot

'''Get max shear in ribs

3 Source : Graph.py
with GNU General Public License v3.0
from alexfanjn

    def add_branch(self, branch):
        fr = int(branch[0])
        to = int(branch[1])
        self.br_limit[(fr, to)] = branch[5]
        self.edge_list.append((fr, to))
        self.matrix[fr][to] = 1
        self.branch = np.append(self.branch, [branch], axis=0)
        if fr in self.degree.keys():
            self.degree[fr] = self.degree[fr] + 1
        if to in self.degree.keys():
            self.degree[to] = self.degree[to] + 1



    def delete_bus(self, num):

3 Source : pposgd_fuse.py
with MIT License
from alexsax

def add_vtarg_and_adv(seg, gamma, lam):
    """
    Compute target value using TD(lambda) estimator, and advantage with GAE(lambda)
    """
    new = np.append(seg["new"], 0)  # last element is only used for last vtarg, but we already zeroed it if last new = 1
    vpred = np.append(seg["vpred"], seg["nextvpred"])
    T = len(seg["rew"])
    seg["adv"] = gaelam = np.empty(T, 'float32')
    rew = seg["rew"]
    lastgaelam = 0
    for t in reversed(range(T)):
        nonterminal = 1 - new[t + 1]
        delta = rew[t] + gamma * vpred[t + 1] * nonterminal - vpred[t]
        gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam
    seg["tdlamret"] = seg["adv"] + seg["vpred"]


def learn(env, policy_func, *,

3 Source : pposgd_sensor.py
with MIT License
from alexsax

def add_vtarg_and_adv(seg, gamma, lam):
    """
    Compute target value using TD(lambda) estimator, and advantage with GAE(lambda)
    """
    new = np.append(seg["new"], 0) # last element is only used for last vtarg, but we already zeroed it if last new = 1
    vpred = np.append(seg["vpred"], seg["nextvpred"])
    T = len(seg["rew"])
    seg["adv"] = gaelam = np.empty(T, 'float32')
    rew = seg["rew"]
    lastgaelam = 0
    for t in reversed(range(T)):
        nonterminal = 1-new[t+1]
        delta = rew[t] + gamma * vpred[t+1] * nonterminal - vpred[t]
        gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam
    seg["tdlamret"] = seg["adv"] + seg["vpred"]

def learn(env, policy_func, *,

3 Source : wrapping.py
with MIT License
from AlexShkarin

    def get_appended(self, val, wrapped=True):
        """
        Return a copy of the column with the data `val` appended at the end.
        
        If ``wrapped==True``, return a new wrapper contating the column; otherwise, just return the column.
        """
        new_cont=np.append(self.cont, val, axis=0)
        return Array1DWrapper(new_cont) if wrapped else new_cont
    def append(self, val):

3 Source : wrapping.py
with MIT License
from AlexShkarin

        def get_appended(self, val, wrapped=True):
            """
            Return a new table with new rows given by `val` appended to the end of the table.

            If ``wrapped==True``, return a new wrapper contating the table; otherwise, just return the table.
            """
            new_cont=np.append(self._storage, val, axis=0)
            return Array2DWrapper(new_cont) if wrapped else new_cont
        def append(self, val):

3 Source : wrapping.py
with MIT License
from AlexShkarin

        def get_appended(self, val, wrapped=True):
            """
            Return a new table with new columns given by `val` appended to the end of the table.

            If ``wrapped==True``, return a new wrapper contating the table; otherwise, just return the table.
            """
            new_cont=np.append(self._storage, val, axis=1)
            return Array2DWrapper(new_cont) if wrapped else new_cont
        def append(self, val):

3 Source : geom.py
with Apache License 2.0
from Algomorph

    def invert_pose_matrix(transform_matrix):
        translation_vector = transform_matrix[0:3, 3].reshape(3, 1)
        rotation_matrix = transform_matrix[0:3, 0:3]
        rotation_matrix_inverse = rotation_matrix.T
        translation_vector_inverse = -rotation_matrix_inverse.dot(translation_vector)
        return np.vstack((np.append(rotation_matrix_inverse, translation_vector_inverse, 1), [0, 0, 0, 1]))

    def __str__(self):

3 Source : kernels.py
with MIT License
from alvarobartt

    def theta(self):
        """Returns the (flattened, log-transformed) non-fixed hyperparameters.

        Note that theta are typically the log-transformed values of the
        kernel's hyperparameters as this representation of the search space
        is more amenable for hyperparameter search, as hyperparameters like
        length-scales naturally live on a log-scale.

        Returns
        -------
        theta : array, shape (n_dims,)
            The non-fixed, log-transformed hyperparameters of the kernel
        """
        return np.append(self.k1.theta, self.k2.theta)

    @theta.setter

3 Source : simulated_annealing.py
with MIT License
from alwaysbyx

    def get_function_value(self,x0):
        '''
        here the function value (what we are going to minimize) is the total length of path
        '''
        f = 0
        x = x0.copy()
        x = np.append(x,x[0])
        for i in range(self.n):
            u = x[i]
            v = x[i+1]
            f += (self.x[u]-self.x[v])**2 + (self.y[u]-self.y[v])**2
        return f
    
    def get_neighbor(self,x):

3 Source : utils.py
with GNU General Public License v3.0
from amandaberg

def update_dictionary(orig, new, dictInDict = False):
    for key in new.keys():
        if key in orig.keys():
            if dictInDict:
                for key2 in new[key].keys():
                    if key2 in orig[key].keys():
                        orig[key][key2] = np.append(orig[key][key2], new[key][key2])
                    else:
                        orig[key][key2] = new[key][key2]
            else:
                orig[key] = np.append(orig[key], new[key])
        else:
            orig[key] = new[key]
    return orig


# Data generation functions--------------------------------------------------------------

def generate_patch_data(file_list, patch_width, patch_height, normalize_to_interval_01 = True, convert_to_grayscale = False):

3 Source : state.py
with Apache License 2.0
from amonszpart

    def get_grid_size(self):
        out = (self.room[:, 1] - self.room[:, 0]) / self.resolution[:3]
        out = np.append(out, int(round(self.__TWO_PI / self.resolution[3])))
        assert abs(self.resolution[3] * out[-1] - self.__TWO_PI)   <   1.e-3, \
            "Wrong grid size: %s (res: %s, div: %s)" \
            % (out, self.resolution[3], self.__TWO_PI / self.resolution[3])
        assert out.shape == (4,), "No: s" % repr(out.shape)
        return np.ceil(out).astype(np.int32)

    @staticmethod

3 Source : util.py
with GNU General Public License v3.0
from aqntks

def showImg(det, names, im0s, colors, real):
    realImg, drawImg = real.copy(), im0s.copy()
    for *rect, conf, cls in reversed(det):
        label = f'{names[int(cls)]} {conf:.2f}'
        plot_one_box(rect, drawImg, label=label, color=colors[int(cls)], line_thickness=1)

    appendImg = np.append(cv2.resize(realImg, (drawImg.shape[1], drawImg.shape[0])), drawImg, axis=1)
    cv2.imshow("result", cv2.resize(appendImg, (1280, 400)))


# 디렉토리 탐색
def watchDir(path):

3 Source : augmentations.py
with GNU General Public License v3.0
from aqntks

def replicate(im, labels):
    # Replicate labels
    h, w = im.shape[:2]
    boxes = labels[:, 1:].astype(int)
    x1, y1, x2, y2 = boxes.T
    s = ((x2 - x1) + (y2 - y1)) / 2  # side length (pixels)
    for i in s.argsort()[:round(s.size * 0.5)]:  # smallest indices
        x1b, y1b, x2b, y2b = boxes[i]
        bh, bw = y2b - y1b, x2b - x1b
        yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw))  # offset x, y
        x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
        im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b]  # im4[ymin:ymax, xmin:xmax]
        labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)

    return im, labels


def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):

3 Source : sctransform.py
with BSD 3-Clause "New" or "Revised" License
from aristoteleo

def _parallel_wrapper(j):
    name = gn[genes_bin_regress[j]]
    y = umi_bin[:, j].A.flatten()
    pr = statsmodels.discrete.discrete_model.Poisson(y, mm)
    res = pr.fit(disp=False)
    mu = res.predict()
    theta = theta_ml(y, mu)
    ps[name] = np.append(res.params, theta)


def gmean(X: scipy.sparse.spmatrix, axis=0, eps=1):

3 Source : utils.py
with BSD 3-Clause "New" or "Revised" License
from aristoteleo

def get_neighbor_indices(adjacency_list, source_idx, n_order_neighbors=2, max_neighbors_num=None):
    """returns a list (np.array) of `n_order_neighbors` neighbor indices of source_idx. If `max_neighbors_num` is set and the n order neighbors of `source_idx` is larger than `max_neighbors_num`, a list of neighbors will be randomly chosen and returned."""
    _indices = [source_idx]
    for _ in range(n_order_neighbors):
        _indices = np.append(_indices, adjacency_list[_indices])
        if np.isnan(_indices).any():
            _indices = _indices[~np.isnan(_indices)]
    _indices = np.unique(_indices)
    if max_neighbors_num is not None and len(_indices) > max_neighbors_num:
        _indices = np.random.choice(_indices, max_neighbors_num, replace=False)
    return _indices


def append_iterative_neighbor_indices(indices, n_recurse_neighbors=2, max_neighbors_num=None):

3 Source : tip_calibration.py
with MIT License
from arkadeepnc

def std_tip_pos(tip_pos_gs,pose_marker_with_DPR):
	tip_pos_gs = np.append(tip_pos_gs,1.0)
	n = pose_marker_with_DPR.shape[0]
	tip_position = np.zeros((n,3))
	for j in range(n):

		tf_cam_to_cent = dodecapen.RodriguesToTransf(pose_marker_with_DPR[j,:])
		tip_loc_cam = tf_cam_to_cent.dot(tip_pos_gs.reshape(4,1))
		tip_position[j,:] = tip_loc_cam[0:3].reshape(3,) 

	a = tip_position - tip_position.mean(axis = 0)
	b = np.linalg.norm(a,axis=1)	
	# print tip_position,"tip_position"
	print tip_pos_gs,"tip_pos_gs"
	print b.sum(),"b.sum()"
	return b.sum()
	

def main():

3 Source : loss.py
with MIT License
from ArthurBernard

    def append(self, other):
        """ Append value to loss series.

        Parameters
        ----------
        other : float or array_like
            These values are append to loss series object.

        """
        if isinstance(other, (float, int)):
            other = [other]

        self.values = np.append(self.values, other)

    def reset(self):

3 Source : optimizer.py
with MIT License
from artur-deluca

    def _mutate(
        rand, p: typing.List[int], selection_size: int, n_candidates: int
    ) -> typing.List[int]:
        """Performs a swap mutation with the remaining available itens"""
        if len(p) > 1:
            # get random slice
            _slice = rand.sample(list(range(selection_size)), 2)
            start, finish = min(_slice), max(_slice)
            p_1 = np.append(p[0:start], p[finish:])
            p_2 = list(set(range(n_candidates)) - set(p_1))
            p[start:finish] = rand.sample(p_2, len(p[start:finish]))
        return p

    @staticmethod

3 Source : trpo_mpi.py
with MIT License
from ArztSamuel

def add_vtarg_and_adv(seg, gamma, lam):
    new = np.append(seg["new"], 0) # last element is only used for last vtarg, but we already zeroed it if last new = 1
    vpred = np.append(seg["vpred"], seg["nextvpred"])
    T = len(seg["rew"])
    seg["adv"] = gaelam = np.empty(T, 'float32')
    rew = seg["rew"]
    lastgaelam = 0
    for t in reversed(range(T)):
        nonterminal = 1-new[t+1]
        delta = rew[t] + gamma * vpred[t+1] * nonterminal - vpred[t]
        gaelam[t] = lastgaelam = delta + gamma * lam * nonterminal * lastgaelam
    seg["tdlamret"] = seg["adv"] + seg["vpred"]

def learn(env, policy_fn, *,

3 Source : dataset.py
with Apache License 2.0
from Ascend

def resize_column_test(img, img_shape, gt_bboxes, gt_label, gt_num, gt_mask):
    """resize operation for image of eval"""
    img_data = img
    img_data, w_scale, h_scale = mmcv.imresize(
        img_data, (config.img_width, config.img_height), return_scale=True)
    img_shape = np.append(img_shape, (h_scale, w_scale))
    img_shape = np.asarray(img_shape, dtype=np.float32)

    return  (img_data, img_shape, gt_bboxes, gt_label, gt_num, gt_mask)

def impad_to_multiple_column(img, img_shape, gt_bboxes, gt_label, gt_num, gt_mask):

3 Source : dataset.py
with Apache License 2.0
from Ascend

def rescale_column(img, gt_bboxes, gt_label, gt_num, img_shape):
    """rescale operation for image"""
    img_data, scale_factor = mmcv.imrescale(img, (config.img_width, config.img_height), return_scale=True)
    if img_data.shape[0] > config.img_height:
        img_data, scale_factor2 = mmcv.imrescale(img_data, (config.img_height, config.img_width), return_scale=True)
        scale_factor = scale_factor * scale_factor2
    img_shape = np.append(img_shape, scale_factor)
    img_shape = np.asarray(img_shape, dtype=np.float32)
    gt_bboxes = gt_bboxes * scale_factor
    gt_bboxes = split_gtbox_label(gt_bboxes)
    if gt_bboxes.shape[0] != 0:
        gt_bboxes[:, 0::2] = np.clip(gt_bboxes[:, 0::2], 0, img_shape[1] - 1)
        gt_bboxes[:, 1::2] = np.clip(gt_bboxes[:, 1::2], 0, img_shape[0] - 1)

    return (img_data, gt_bboxes, gt_label, gt_num, img_shape)


def resize_column(img, gt_bboxes, gt_label, gt_num, img_shape):

3 Source : evaluation.py
with Apache License 2.0
from Ascend

    def __init__(self, **kwargs):
        super(MaskEvaluator, self).__init__(**kwargs)

        if self.dataset_name != "OpenImages":
            raise ValueError("Mask evaluation must be performed on OpenImages.")

        self.mask_paths, self.ignore_paths = get_mask_paths(self.metadata)

        # cam_threshold_list is given as [0, bw, 2bw, ..., 1-bw]
        # Set bins as [0, bw), [bw, 2bw), ..., [1-bw, 1), [1, 2), [2, 3)
        self.num_bins = len(self.cam_threshold_list) + 2
        self.threshold_list_right_edge = np.append(self.cam_threshold_list,
                                                   [1.0, 2.0, 3.0])
        self.gt_true_score_hist = np.zeros(self.num_bins, dtype=np.float)
        self.gt_false_score_hist = np.zeros(self.num_bins, dtype=np.float)

    def accumulate(self, scoremap, image_id):

3 Source : datasets.py
with Apache License 2.0
from Ascend

def replicate(img, labels):
    # Replicate labels
    h, w = img.shape[:2]
    boxes = labels[:, 1:].astype(int)
    x1, y1, x2, y2 = boxes.T
    s = ((x2 - x1) + (y2 - y1)) / 2  # side length (pixels)
    for i in s.argsort()[:round(s.size * 0.5)]:  # smallest indices
        x1b, y1b, x2b, y2b = boxes[i]
        bh, bw = y2b - y1b, x2b - x1b
        yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw))  # offset x, y
        x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
        img[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]  # img4[ymin:ymax, xmin:xmax]
        labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)

    return img, labels


def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True):

3 Source : inception_score.py
with Apache License 2.0
from ashual

    def forward(self, imgs):
        # Get predictions
        preds_imgs = self.get_pred(imgs.to(self.device))
        self.preds = np.append(self.preds, preds_imgs, axis=0)

    def compute_score(self, splits=1):

3 Source : modea.py
with Apache License 2.0
from automl

    def ensureFullLengthRepresentation(self, representation):
        """
        Given a (partial) representation, ensure that it is padded to become a full length customizedES representation,
        consisting of the required number of structure, population and parameter values.
        >>> ensureFullLengthRepresentation([])
        [0,0,0,0,0,0,0,0,0,0,0, None,None, None,None,None,None,None,None,None,None,None,None,None,None,None]
        :param representation:  List representation of a customizedES instance to check and pad if needed
        :return:                Guaranteed full-length version of the representation
        """
        default_rep = (
            [0] * len(options) + [None, None] + [None] * len(initializable_parameters)
        )
        if len(representation)   <   len(default_rep):
            representation = np.append(
                representation, default_rep[len(representation) :]
            ).flatten()
        return representation

3 Source : experiment.py
with MIT License
from avast

    def _set_variants(self, goals):
        # what variants and goals there should be from all the goals needed to evaluate all metrics
        self.variants = (
            self.variants
            if self.variants is not None
            else np.unique(np.append(goals["exp_variant_id"], self.control_variant))
        )

    def _fix_missing_agg(self, goals: pd.DataFrame) -> pd.DataFrame:

3 Source : encoders.py
with Apache License 2.0
from aws

    def get_classes(self):
        """Returns the values of the unencoded classes.
        If ``self.include_unseen_class`` is ``True`` include ``self.fill_label_value`` as a class.

        Returns
        -------
        classes : array of shape (n_classes,)
        """
        if self.include_unseen_class and self.fill_unseen_labels:
            return np.append(self.classes_, [self.fill_label_value])

        return self.classes_


class NALabelEncoder(BaseEstimator, TransformerMixin):

3 Source : test_cut.py
with Apache License 2.0
from aws-samples

def test_bins_from_interval_index():
    c = cut(range(5), 3)
    expected = c
    result = cut(range(5), bins=expected.categories)
    tm.assert_categorical_equal(result, expected)

    expected = Categorical.from_codes(np.append(c.codes, -1),
                                      categories=c.categories,
                                      ordered=True)
    result = cut(range(6), bins=expected.categories)
    tm.assert_categorical_equal(result, expected)


def test_bins_from_interval_index_doc_example():

3 Source : sensors.py
with MIT License
from axelbr

    def space(self) -> gym.Space:
        high = np.append(self._config.linear_bounds, self._config.angular_bounds).astype(dtype=float)
        low = -high
        return gym.spaces.Box(low=low, high=high, dtype=np.float64)

    def observe(self) -> NDArray[(6,), np.float]:

See More Examples