Python numpy.append() Examples

The following are 30 code examples for showing how to use numpy.append(). 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: models   Author: kipoi   File: gtf_utils.py    License: MIT License 6 votes vote down vote up
def add_exon(self, chrom, strand, start, stop):
        if strand != self.strand or chrom != self.chrom:
            print("The exon has different chrom or strand to the transcript.")
            return
        _exon = np.array([start, stop], "int").reshape(1, 2)
        self.exons = np.append(self.exons, _exon, axis=0)
        self.exons = np.sort(self.exons, axis=0)
        self.tranL += abs(int(stop) - int(start) + 1)
        self.exonNum += 1

        self.seglen = np.zeros(self.exons.shape[0] * 2 - 1, "int")
        self.seglen[0] = self.exons[0, 1] - self.exons[0, 0] + 1
        for i in range(1, self.exons.shape[0]):
            self.seglen[i * 2 - 1] = self.exons[i, 0] - self.exons[i - 1, 1] - 1
            self.seglen[i * 2] = self.exons[i, 1] - self.exons[i, 0] + 1

        if ["-", "-1", "0", 0, -1].count(self.strand) > 0:
            self.seglen = self.seglen[::-1] 
Example 2
Project: models   Author: kipoi   File: gtf_utils.py    License: MIT License 6 votes vote down vote up
def add_exon(self, chrom, strand, start, stop):
        if strand != self.strand or chrom != self.chrom:
            print("The exon has different chrom or strand to the transcript.")
            return
        _exon = np.array([start, stop], "int").reshape(1, 2)
        self.exons = np.append(self.exons, _exon, axis=0)
        self.exons = np.sort(self.exons, axis=0)
        self.tranL += abs(int(stop) - int(start) + 1)
        self.exonNum += 1

        self.seglen = np.zeros(self.exons.shape[0] * 2 - 1, "int")
        self.seglen[0] = self.exons[0, 1] - self.exons[0, 0] + 1
        for i in range(1, self.exons.shape[0]):
            self.seglen[i * 2 - 1] = self.exons[i, 0] - self.exons[i - 1, 1] - 1
            self.seglen[i * 2] = self.exons[i, 1] - self.exons[i, 0] + 1

        if ["-", "-1", "0", 0, -1].count(self.strand) > 0:
            self.seglen = self.seglen[::-1] 
Example 3
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 6 votes vote down vote up
def add_exon(self, chrom, strand, start, stop):
        if strand != self.strand or chrom != self.chrom:
            print("The exon has different chrom or strand to the transcript.")
            return
        _exon = np.array([start, stop], "int").reshape(1,2)
        self.exons = np.append(self.exons, _exon, axis=0)
        self.exons = np.sort(self.exons, axis=0)
        self.tranL += abs(int(stop) - int(start) + 1)
        self.exonNum += 1


        self.seglen = np.zeros(self.exons.shape[0] * 2 - 1, "int")
        self.seglen[0] = self.exons[0,1]-self.exons[0,0] + 1
        for i in range(1, self.exons.shape[0]):
            self.seglen[i*2-1] = self.exons[i,0]-self.exons[i-1,1] - 1
            self.seglen[i*2] = self.exons[i,1]-self.exons[i,0] + 1

        if ["-","-1","0",0,-1].count(self.strand) > 0:
            self.seglen = self.seglen[::-1] 
Example 4
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 6 votes vote down vote up
def add_exon(self, chrom, strand, start, stop):
        if strand != self.strand or chrom != self.chrom:
            print("The exon has different chrom or strand to the transcript.")
            return
        _exon = np.array([start, stop], "int").reshape(1,2)
        self.exons = np.append(self.exons, _exon, axis=0)
        self.exons = np.sort(self.exons, axis=0)
        self.tranL += abs(int(stop) - int(start) + 1)
        self.exonNum += 1


        self.seglen = np.zeros(self.exons.shape[0] * 2 - 1, "int")
        self.seglen[0] = self.exons[0,1]-self.exons[0,0] + 1
        for i in range(1, self.exons.shape[0]):
            self.seglen[i*2-1] = self.exons[i,0]-self.exons[i-1,1] - 1
            self.seglen[i*2] = self.exons[i,1]-self.exons[i,0] + 1

        if ["-","-1","0",0,-1].count(self.strand) > 0:
            self.seglen = self.seglen[::-1] 
Example 5
Project: models   Author: kipoi   File: gtf_utils.py    License: MIT License 6 votes vote down vote up
def add_exon(self, chrom, strand, start, stop):
        if strand != self.strand or chrom != self.chrom:
            print("The exon has different chrom or strand to the transcript.")
            return
        _exon = np.array([start, stop], "int").reshape(1, 2)
        self.exons = np.append(self.exons, _exon, axis=0)
        self.exons = np.sort(self.exons, axis=0)
        self.tranL += abs(int(stop) - int(start) + 1)
        self.exonNum += 1

        self.seglen = np.zeros(self.exons.shape[0] * 2 - 1, "int")
        self.seglen[0] = self.exons[0, 1] - self.exons[0, 0] + 1
        for i in range(1, self.exons.shape[0]):
            self.seglen[i * 2 - 1] = self.exons[i, 0] - self.exons[i - 1, 1] - 1
            self.seglen[i * 2] = self.exons[i, 1] - self.exons[i, 0] + 1

        if ["-", "-1", "0", 0, -1].count(self.strand) > 0:
            self.seglen = self.seglen[::-1] 
Example 6
def test_elementwisesum_with_type():
    dev_types = [[mx.gpu(0), [np.float64, np.float32, np.float16]],
                 [mx.cpu(0), [np.float64, np.float32]] ]
    for num_args in range(1, 6):
        ews_arg_shape = {}
        for i in range(num_args):
            ews_arg_shape['ews_arg'+str(i)] = (2, 10)
        sym = mx.sym.ElementWiseSum(name='ews', num_args=num_args)
        ctx_list = []
        for dev, types in dev_types:
            for dtype in types:
                ews_arg_dtype = {'type_dict':{}}
                for i in range(num_args):
                    ews_arg_dtype['type_dict']['ews_arg'+str(i)] = dtype
                ctx_elem = {'ctx': dev}
                ctx_elem.update(ews_arg_shape)
                ctx_elem.update(ews_arg_dtype)
                ctx_list.append(ctx_elem)
    check_consistency(sym, ctx_list) 
Example 7
def test_embedding_with_type():
    def test_embedding_helper(data_types, weight_types, low_pad, high_pad):
        NVD = [[20, 10, 20], [200, 10, 300]]
        for N, V, D in NVD:
            sym = mx.sym.Embedding(name='embedding', input_dim=V, output_dim=D)
            ctx_list = []
            for data_type in data_types:
                for weight_type in weight_types:
                    ctx_list.append({'ctx': mx.gpu(0), 'embedding_data': (N,),
                        'type_dict': {'embedding_data': data_type, 'embedding_weight': weight_type}})
                    ctx_list.append({'ctx': mx.cpu(0), 'embedding_data': (N,),
                        'type_dict': {'embedding_data': data_type, 'embedding_weight': weight_type}})
            arg_params = {'embedding_data': np.random.randint(low=-low_pad, high=V+high_pad, size=(N,))}
            check_consistency(sym, ctx_list, grad_req={'embedding_data': 'null','embedding_weight': 'write'},
                              arg_params=arg_params)

    data_types = [np.float16, np.float32, np.float64, np.int32]
    weight_types = [np.float16, np.float32, np.float64]
    test_embedding_helper(data_types, weight_types, 5, 5)
    data_types = [np.uint8]
    weight_types = [np.float16, np.float32, np.float64]
    test_embedding_helper(data_types, weight_types, 0, 5) 
Example 8
Project: PyOptiX   Author: ozen   File: buffers_of_buffers.py    License: MIT License 6 votes vote down vote up
def create_random_buffer(max_width, max_height):
    scale = randf()
    w = int(max(max_width * scale, 1))
    h = int(max(max_height * scale, 1))

    arr = []
    red, green, blue = randf(), randf(), randf()

    for y in range(h):
        arr.append([])
        for x in range(w):
            if randf() < 0.1:
                arr[y].append([red * 255.0, green * 255.0, blue * 255.0, 255])
            else:
                arr[y].append([255, 255, 255, 0])

    return Buffer.from_array(np.array(arr, dtype=np.uint8), buffer_type='i', drop_last_dim=True) 
Example 9
Project: Face-Recognition   Author: anubhavshrimal   File: create_encodings.py    License: MIT License 6 votes vote down vote up
def create_dataset(training_dir_path, labels):
    X = []
    for i in _zipped_folders_labels_images(training_dir_path, labels):
        for fileName in i[2]:
            file_path = os.path.join(i[0], fileName)
            img = face_recognition_api.load_image_file(file_path)
            imgEncoding = face_recognition_api.face_encodings(img)

            if len(imgEncoding) > 1:
                print('\x1b[0;37;43m' + 'More than one face found in {}. Only considering the first face.'.format(file_path) + '\x1b[0m')
            if len(imgEncoding) == 0:
                print('\x1b[0;37;41m' + 'No face found in {}. Ignoring file.'.format(file_path) + '\x1b[0m')
            else:
                print('Encoded {} successfully.'.format(file_path))
                X.append(np.append(imgEncoding[0], i[1]))
    return X 
Example 10
Project: EXOSIMS   Author: dsavransky   File: TargetList.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def stellar_mass(self):
        """Populates target list with 'true' and 'approximate' stellar masses
        
        This method calculates stellar mass via the formula relating absolute V
        magnitude and stellar mass.  The values are in units of solar mass.

        Function called by reset sim
        
        """
        
        # 'approximate' stellar mass
        self.MsEst = (10.**(0.002456*self.MV**2 - 0.09711*self.MV + 0.4365))*u.solMass
        # normally distributed 'error'
        err = (np.random.random(len(self.MV))*2. - 1.)*0.07
        self.MsTrue = (1. + err)*self.MsEst
        
        # if additional filters are desired, need self.catalog_atts fully populated
        if not hasattr(self.catalog_atts,'MsEst'):
            self.catalog_atts.append('MsEst')
        if not hasattr(self.catalog_atts,'MsTrue'):
            self.catalog_atts.append('MsTrue') 
Example 11
Project: EXOSIMS   Author: dsavransky   File: TargetList.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def loadAliasFile(self):
        """
        Args:
        Returns:
            alias ():
                list 
        """
        #OLD aliasname = 'alias_4_11_2019.pkl'
        aliasname = 'alias_10_07_2019.pkl'
        tmp1 = inspect.getfile(self.__class__).split('/')[:-2]
        tmp1.append('util')
        self.classpath = '/'.join(tmp1)
        #self.classpath = os.path.split(inspect.getfile(self.__class__))[0]
        #vprint(inspect.getfile(self.__class__))
        self.alias_datapath = os.path.join(self.classpath, aliasname)
        #Load pkl and outspec files
        try:
            with open(self.alias_datapath, 'rb') as f:#load from cache
                alias = pickle.load(f, encoding='latin1')
        except:
            vprint('Failed to open fullPathPKL %s'%self.alias_datapath)
            pass
        return alias
    ########################################################## 
Example 12
Project: pymesh   Author: taxpon   File: base.py    License: MIT License 6 votes vote down vote up
def join(self, another):
        """

        :param m: BaseMesh
        :return:
        """
        if another is None:
            raise AttributeError("another BaseMesh instance is required")

        if not isinstance(another, BaseMesh):
            raise TypeError("anther must be an instance of BaseMesh")

        self.data = numpy.append(self.data, another.data)
        self.normals = numpy.append(self.normals, another.normals, axis=0)
        self.vectors = numpy.append(self.vectors, another.vectors, axis=0)
        self.attr = numpy.append(self.attr, another.attr, axis=0)
        return self 
Example 13
Project: Modeling-Cloth   Author: the3dadvantage   File: ModelingCloth.py    License: MIT License 6 votes vote down vote up
def zxy_grid(co_y, tymin, tymax, subs, c, t, c_peat, t_peat):
    # create linespace grid between bottom and top of tri z
    #subs = 7
    t_min = np.min(tymin)
    t_max = np.max(tymax)
    divs = np.linspace(t_min, t_max, num=subs, dtype=np.float32)            
    
    # figure out which triangles and which co are in each section
    co_bools = (co_y > divs[:-1][:, nax]) & (co_y < divs[1:][:, nax])
    tri_bools = (tymin < divs[1:][:, nax]) & (tymax > divs[:-1][:, nax])

    for i, j in zip(co_bools, tri_bools):
        if (np.sum(i) > 0) & (np.sum(j) > 0):
            c3 = c[i]
            t3 = t[j]
        
            c_peat.append(np.repeat(c3, t3.shape[0]))
            t_peat.append(np.tile(t3, c3.shape[0])) 
Example 14
Project: Caffe-Python-Data-Layer   Author: liuxianming   File: bcfstore.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, filename):
        self._filename = filename
        print 'Loading BCF file to memory ... '+filename
        file = open(filename, 'rb')
        size = numpy.fromstring(file.read(8), dtype=numpy.uint64)
        file_sizes = numpy.fromstring(file.read(8*size), dtype=numpy.uint64)
        self._offsets = numpy.append(numpy.uint64(0),
                                     numpy.add.accumulate(file_sizes))
        self._memory = file.read()
        file.close() 
Example 15
Project: Caffe-Python-Data-Layer   Author: liuxianming   File: bcfstore.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, filename):
        self._filename = filename
        print 'Opening BCF file ... '+filename
        self._file = open(filename, 'rb')
        size = numpy.fromstring(self._file.read(8), dtype=numpy.uint64)
        file_sizes = numpy.fromstring(self._file.read(8*size),
                                      dtype=numpy.uint64)
        self._offsets = numpy.append(numpy.uint64(0),
                                     numpy.add.accumulate(file_sizes)) 
Example 16
Project: FRIDA   Author: LCAV   File: tools_fri_doa_plane.py    License: MIT License 5 votes vote down vote up
def compute_b(G_lst, GtG_lst, beta_lst, Rc0, num_bands, a_ri):
    """
    compute the uniform sinusoidal samples b from the updated annihilating
    filter coeffiients.
    :param GtG_lst: list of G^H G for different subbands
    :param beta_lst: list of beta-s for different subbands
    :param Rc0: right-dual matrix, here it is the convolution matrix associated with c
    :param num_bands: number of bands
    :param L: size of b: L by 1
    :param a_ri: a 2D numpy array. each column corresponds to the measurements within a subband
    :return:
    """
    b_lst = []
    a_Gb_lst = []
    for loop in range(num_bands):
        GtG_loop = GtG_lst[loop]
        beta_loop = beta_lst[loop]
        b_loop = beta_loop - \
                 linalg.solve(GtG_loop,
                              np.dot(Rc0.T,
                                     linalg.solve(np.dot(Rc0, linalg.solve(GtG_loop, Rc0.T)),
                                                  np.dot(Rc0, beta_loop)))
                              )

        b_lst.append(b_loop)
        a_Gb_lst.append(a_ri[:, loop] - np.dot(G_lst[loop], b_loop))

    return np.column_stack(b_lst), linalg.norm(np.concatenate(a_Gb_lst)) 
Example 17
Project: animal-tracking   Author: colinlaney   File: track.py    License: Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def drawFloorCrop(event, x, y, flags, params):
    global perspectiveMatrix, name, RENEW_TETRAGON
    imgCroppingPolygon = np.zeros_like(params['imgFloorCorners'])
    if event == cv2.EVENT_RBUTTONUP:
        cv2.destroyWindow(f'Floor Corners for {name}')
    if len(params['croppingPolygons'][name]) > 4 and event == cv2.EVENT_LBUTTONUP:
        RENEW_TETRAGON = True
        h = params['imgFloorCorners'].shape[0]
        # delete 5th extra vertex of the floor cropping tetragon
        params['croppingPolygons'][name] = np.delete(params['croppingPolygons'][name], -1, 0)
        params['croppingPolygons'][name] = params['croppingPolygons'][name] - [h,0]
        
        # Sort cropping tetragon vertices counter-clockwise starting with top left
        params['croppingPolygons'][name] = counterclockwiseSort(params['croppingPolygons'][name])
        # Get the matrix of perspective transformation
        params['croppingPolygons'][name] = np.reshape(params['croppingPolygons'][name], (4,2))
        tetragonVertices = np.float32(params['croppingPolygons'][name])
        tetragonVerticesUpd = np.float32([[0,0], [0,h], [h,h], [h,0]])
        perspectiveMatrix[name] = cv2.getPerspectiveTransform(tetragonVertices, tetragonVerticesUpd)
    if event == cv2.EVENT_LBUTTONDOWN:
        if len(params['croppingPolygons'][name]) == 4 and RENEW_TETRAGON:
            params['croppingPolygons'][name] = np.array([[0,0]])
            RENEW_TETRAGON = False
        if len(params['croppingPolygons'][name]) == 1:
            params['croppingPolygons'][name][0] = [x,y]
        params['croppingPolygons'][name] = np.append(params['croppingPolygons'][name], [[x,y]], axis=0)
    if event == cv2.EVENT_MOUSEMOVE and not (len(params['croppingPolygons'][name]) == 4 and RENEW_TETRAGON):
        params['croppingPolygons'][name][-1] = [x,y]
        if len(params['croppingPolygons'][name]) > 1:
            cv2.fillPoly(
                imgCroppingPolygon,
                [np.reshape(
                    params['croppingPolygons'][name],
                    (len(params['croppingPolygons'][name]),2)
                )],
                BGR_COLOR['green'], cv2.LINE_AA)
            imgCroppingPolygon = cv2.addWeighted(params['imgFloorCorners'], 1.0, imgCroppingPolygon, 0.5, 0.)
            cv2.imshow(f'Floor Corners for {name}', imgCroppingPolygon) 
Example 18
Project: models   Author: kipoi   File: gtf_utils.py    License: MIT License 5 votes vote down vote up
def add_transcipt(self, transcript):
        self.trans.append(transcript)
        self.tranNum += 1 
Example 19
Project: models   Author: kipoi   File: gtf_utils.py    License: MIT License 5 votes vote down vote up
def get_gene_info(self):
        RV = [self.geneID, self.geneName, self.chrom, self.strand, self.start,
              self.stop, self.biotype]
        _trans = []
        for t in self.trans:
            _trans.append(t.tranID)
        RV.append(",".join(_trans))
        return RV 
Example 20
Project: models   Author: kipoi   File: gtf_utils.py    License: MIT License 5 votes vote down vote up
def add_premRNA(self):
        _tran = Transcript(self.chrom, self.strand, self.start, self.stop,
                           self.geneID + ".p", self.geneName, self.biotype)
        _tran.add_exon(self.chrom, self.strand, self.start, self.stop)
        self.trans.append(_tran)
        self.tranNum += 1 
Example 21
Project: models   Author: kipoi   File: gtf_utils.py    License: MIT License 5 votes vote down vote up
def add_transcipt(self, transcript):
        self.trans.append(transcript)
        self.tranNum += 1 
Example 22
Project: models   Author: kipoi   File: gtf_utils.py    License: MIT License 5 votes vote down vote up
def get_gene_info(self):
        RV = [self.geneID, self.geneName, self.chrom, self.strand, self.start,
              self.stop, self.biotype]
        _trans = []
        for t in self.trans:
            _trans.append(t.tranID)
        RV.append(",".join(_trans))
        return RV 
Example 23
Project: models   Author: kipoi   File: gtf_utils.py    License: MIT License 5 votes vote down vote up
def add_premRNA(self):
        _tran = Transcript(self.chrom, self.strand, self.start, self.stop,
                           self.geneID + ".p", self.geneName, self.biotype)
        _tran.add_exon(self.chrom, self.strand, self.start, self.stop)
        self.trans.append(_tran)
        self.tranNum += 1 
Example 24
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def get_gene_info(self):
        RV = [self.geneID, self.geneName, self.chrom, self.strand, self.start,
              self.stop, self.biotype]
        _trans = []
        for t in self.trans:
            _trans.append(t.tranID)
        RV.append(",".join(_trans))
        return RV 
Example 25
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def add_premRNA(self):
        _tran = Transcript(self.chrom, self.strand, self.start, self.stop, 
                           self.geneID+".p", self.geneName, self.biotype)
        _tran.add_exon(self.chrom, self.strand, self.start, self.stop)
        self.trans.append(_tran)
        self.tranNum += 1 
Example 26
Project: models   Author: kipoi   File: gtf_utils.py    License: MIT License 5 votes vote down vote up
def add_transcipt(self, transcript):
        self.trans.append(transcript)
        self.tranNum += 1 
Example 27
Project: models   Author: kipoi   File: gtf_utils.py    License: MIT License 5 votes vote down vote up
def add_premRNA(self):
        _tran = Transcript(self.chrom, self.strand, self.start, self.stop,
                           self.geneID + ".p", self.geneName, self.biotype)
        _tran.add_exon(self.chrom, self.strand, self.start, self.stop)
        self.trans.append(_tran)
        self.tranNum += 1 
Example 28
Project: neural-pipeline   Author: toodef   File: train_config.py    License: MIT License 5 votes vote down vote up
def _calc(self, output: Tensor, target: Tensor):
        """
        Calculate metric by output from model and target. Method for internal use

        :param output: output from model
        :param target: ground truth
        """
        self._values = np.append(self._values, self.calc(output, target)) 
Example 29
Project: neural-pipeline   Author: toodef   File: train_config.py    License: MIT License 5 votes vote down vote up
def add(self, item: AbstractMetric or 'MetricsGroup') -> 'MetricsGroup':
        """
        Add :class:`AbstractMetric` or :class:`MetricsGroup`

        :param item: object to add
        :return: self object
        :rtype: :class:`MetricsGroup`
        """
        if isinstance(item, type(self)):
            item._set_level(self.__lvl + 1)
            self.__metrics_groups.append(item)
        else:
            self.__metrics.append(item)
        return self 
Example 30
Project: neural-pipeline   Author: toodef   File: train_config.py    License: MIT License 5 votes vote down vote up
def add_metric(self, metric: AbstractMetric) -> AbstractMetric:
        """
        Add :class:`AbstractMetric` object

        :param metric: metric to add
        :return: metric object
        :rtype: :class:`AbstractMetric`
        """
        self._metrics.append(metric)
        return metric