当前位置: 首页>>代码示例>>Python>>正文


Python numpy.str方法代码示例

本文整理汇总了Python中numpy.str方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.str方法的具体用法?Python numpy.str怎么用?Python numpy.str使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在numpy的用法示例。


在下文中一共展示了numpy.str方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: write_param

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def write_param(self, xml_filename='gap.xml'):
        """
        Write xml file to perform lammps calculation.

        Args:
            xml_filename (str): Filename to store xml formatted parameters.
        """
        if not self.param:
            raise RuntimeError("The xml and parameters should be provided.")
        tree = self.param.get('xml')
        root = tree.getroot()
        gpcoordinates = list(root.iter('gpCoordinates'))[0]
        param_filename = "{}.soapparam".format(self.name)
        gpcoordinates.set('sparseX_filename', param_filename)
        np.savetxt(param_filename, self.param.get('param'), fmt='%.20e')
        tree.write(xml_filename)
        pair_coeff = self.pair_coeff.format(xml_filename,
                                            '\"Potential xml_label={}\"'.
                                            format(self.param.get('potential_label')),
                                            self.specie.Z)
        ff_settings = [self.pair_style, pair_coeff]
        return ff_settings 
开发者ID:materialsvirtuallab,项目名称:mlearn,代码行数:24,代码来源:gap.py

示例2: tensor2state

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def tensor2state(tensor_frd, tensor_emy):
    '''
    transform tensor 2 state
    tensor_frd, tensor_emy ndarray [9,10,16]
    return state ndarray [10,9]
    '''
    assert tensor_frd.shape == tensor_emy.shape
    state = np.zeros((10,9), dtype=np.str)
    chessfrdplayer = 'KAABBNNRRCCPPPPP'
    chessemyplayer = 'kaabbnnrrccppppp'
    for i in range(tensor_frd.shape[0]):
        for j in range(tensor_frd.shape[1]):
            if ~(tensor_frd[i][j] == 0).all():
                layer = np.argmax(tensor_frd[i][j])
                state[j][i] = chessfrdplayer[layer]
            elif ~(tensor_emy[i][j] == 0).all():
                layer = np.argmax(tensor_emy[i][j])
                state[j][i] = chessemyplayer[layer]
            else:
                state[j][i] = ' '
    return state 
开发者ID:milkpku,项目名称:BetaElephant,代码行数:23,代码来源:tensor2fen.py

示例3: compat_as_text

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def compat_as_text(str_):
    """Converts strings into `unicode` (Python 2) or `str` (Python 3).

    Args:
        str\_: A string or other data types convertible to string, or an
            `n`-D numpy array or (possibly nested) list of such elements.

    Returns:
        The converted strings of the same structure/shape as :attr:`str_`.
    """
    def _recur_convert(s):
        if isinstance(s, (list, tuple, np.ndarray)):
            s_ = [_recur_convert(si) for si in s]
            return _maybe_list_to_array(s_, s)
        else:
            try:
                return tf.compat.as_text(s)
            except TypeError:
                return tf.compat.as_text(str(s))

    text = _recur_convert(str_)

    return text 
开发者ID:qkaren,项目名称:Counterfactual-StoryRW,代码行数:25,代码来源:dtypes.py

示例4: load_annoataion

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def load_annoataion(p):
    '''
    load annotation from the text file
    :param p:
    :return:
    '''
    text_polys = []
    text_tags = []
    if not os.path.exists(p):
        return np.array(text_polys, dtype=np.float32)
    with open(p, 'r') as f:
        reader = csv.reader(f)
        for line in reader:
            label = 'text'
            # strip BOM. \ufeff for python3,  \xef\xbb\bf for python2
            line = [i.strip('\ufeff').strip('\xef\xbb\xbf') for i in line]

            x1, y1, x2, y2, x3, y3, x4, y4 = list(map(float, line[:8]))
            text_polys.append([x1, y1, x2, y2, x3, y3, x4, y4])
            text_tags.append(label)

        return np.array(text_polys, dtype=np.int32), np.array(text_tags, dtype=np.str) 
开发者ID:DetectionTeamUCAS,项目名称:R2CNN_Faster-RCNN_Tensorflow,代码行数:24,代码来源:txt2xml.py

示例5: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def __init__(
        self,
        save_path: str = "data/",
        genes_to_keep: Optional[List[str]] = None,
        total_genes: Optional[int] = 558,
        delayed_populating: bool = False,
    ):
        self.genes_to_keep = genes_to_keep
        self.total_genes = total_genes

        self.precise_labels = None

        super().__init__(
            urls="https://storage.googleapis.com/linnarsson-lab-www-blobs/blobs"
            "/cortex/expression_mRNA_17-Aug-2014.txt",
            filenames="expression.bin",
            save_path=save_path,
            delayed_populating=delayed_populating,
        ) 
开发者ID:YosefLab,项目名称:scVI,代码行数:21,代码来源:cortex.py

示例6: find_path_to_data

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def find_path_to_data(self) -> Tuple[str, str]:
        """Returns exact path for the data in the archive.

        This is required because 10X doesn't have a consistent way of storing their data.
        Additionally, the function returns whether the data is stored in compressed format.

        Returns
        -------
        path in which files are contains and their suffix if compressed.
        """
        for root, subdirs, files in os.walk(self.save_path):
            # do not consider hidden files
            files = [f for f in files if not f[0] == "."]
            contains_mat = [
                filename == "matrix.mtx" or filename == "matrix.mtx.gz"
                for filename in files
            ]
            contains_mat = np.asarray(contains_mat).any()
            if contains_mat:
                is_tar = files[0][-3:] == ".gz"
                suffix = ".gz" if is_tar else ""
                return root, suffix
        raise FileNotFoundError(
            "No matrix.mtx(.gz) found in path (%s)." % self.save_path
        ) 
开发者ID:YosefLab,项目名称:scVI,代码行数:27,代码来源:dataset10X.py

示例7: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def __init__(
        self,
        name: str = "cbmc",
        save_path: str = "data/citeSeq/",
        delayed_populating: bool = False,
    ):
        s = available_datasets[name]
        filenames = CiteSeqFilenames(
            rna="%s_rna.csv.gz" % name,
            adt="%s_adt.csv.gz" % name,
            adt_centered="%s_adt_centered.csv.gz" % name,
        )
        super().__init__(
            urls=[
                "ftp://ftp.ncbi.nlm.nih.gov/geo/series/GSE100nnn/GSE100866/suppl/GSE100866_%s-RNA_umi.csv.gz"
                % s,
                "ftp://ftp.ncbi.nlm.nih.gov/geo/series/GSE100nnn/GSE100866/suppl/GSE100866_%s-ADT_umi.csv.gz"
                % s,
                "ftp://ftp.ncbi.nlm.nih.gov/geo/series/GSE100nnn/GSE100866/suppl/"
                "GSE100866_%s-ADT_clr-transformed.csv.gz" % s,
            ],
            filenames=filenames,
            save_path=os.path.join(save_path, name),
            delayed_populating=delayed_populating,
        ) 
开发者ID:YosefLab,项目名称:scVI,代码行数:27,代码来源:cite_seq.py

示例8: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def __init__(
        self, save_path: str = "data/HEMATO/", delayed_populating: bool = False
    ):
        self.gene_names_filename = "bBM.filtered_gene_list.paper.txt"
        self.spring_and_pba_filename = "bBM.spring_and_pba.csv"
        self.cell_types_levels = [
            "Erythroid",
            "Granulocytic Neutrophil",
            "Lymphocytic",
            "Dendritic",
            "Megakaryocytic",
            "Monocytic",
            "Basophilic",
        ]
        super().__init__(
            urls=[
                "https://www.ncbi.nlm.nih.gov/geo/download/?acc=GSM2388072&format=file&"
                "file=GSM2388072%5Fbasal%5Fbone%5Fmarrow%2Eraw%5Fumifm%5Fcounts%2Ecsv%2Egz",
                "https://github.com/romain-lopez/scVI-reproducibility/raw/master/additional/data.zip",
            ],
            filenames=["bBM.raw_umifm_counts.csv.gz", "data.zip"],
            save_path=save_path,
            delayed_populating=delayed_populating,
        ) 
开发者ID:YosefLab,项目名称:scVI,代码行数:26,代码来源:hemato.py

示例9: __init__

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def __init__(
        self,
        mu: float = 4.0,
        theta: float = 2.0,
        dropout: float = 0.7,
        save_path: str = "data/",
    ):
        self.mu = mu
        self.theta = theta
        self.dropout = dropout
        self.simlr_metadata = None
        super().__init__(
            urls="https://github.com/YosefLab/scVI-data/raw/master/random_metadata.pickle",
            filenames=SyntheticRandomDataset.FILENAME,
            save_path=save_path,
        ) 
开发者ID:YosefLab,项目名称:scVI,代码行数:18,代码来源:synthetic.py

示例10: remap_categorical_attributes

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def remap_categorical_attributes(
        self, attributes_to_remap: Optional[List[str]] = None
    ):
        if attributes_to_remap is None:
            attributes_to_remap = self.cell_categorical_attribute_names

        for attribute_name in attributes_to_remap:
            logger.info("Remapping %s to [0,N]" % attribute_name)
            attr = getattr(self, attribute_name)
            mappings_dict = {
                name: getattr(self, name)
                for name in self.attribute_mappings[attribute_name]
            }
            new_attr, _, new_mappings_dict = remap_categories(
                attr, mappings_dict=mappings_dict
            )
            setattr(self, attribute_name, new_attr)
            for name, mapping in new_mappings_dict.items():
                setattr(self, name, mapping) 
开发者ID:YosefLab,项目名称:scVI,代码行数:21,代码来源:dataset.py

示例11: collate_fn_base

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def collate_fn_base(
        self, attributes_and_types: Dict[str, type], batch: Union[List[int], np.ndarray]
    ) -> Tuple[torch.Tensor, ...]:
        """Given indices and attributes to batch, returns a full batch of ``Torch.Tensor``
        """
        indices = np.asarray(batch)
        data_numpy = [
            getattr(self, attr)[indices].astype(dtype)
            if isinstance(getattr(self, attr), np.ndarray)
            else getattr(self, attr)[indices].toarray().astype(dtype)
            for attr, dtype in attributes_and_types.items()
        ]

        data_torch = tuple(torch.from_numpy(d) for d in data_numpy)
        return data_torch

    #############################
    #                           #
    #      GENE FILTERING       #
    #                           #
    ############################# 
开发者ID:YosefLab,项目名称:scVI,代码行数:23,代码来源:dataset.py

示例12: genes_to_index

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def genes_to_index(
        self, genes: Union[List[str], List[int], np.ndarray], on: str = None
    ):
        """Returns the index of a subset of genes, given their ``on`` attribute in ``genes``.

        If integers are passed in ``genes``, the function returns ``genes``.
        If ``on`` is None, it defaults to ``gene_names``.
        """
        if type(genes[0]) is not int:
            on = "gene_names" if on is None else on
            genes_idx = [np.where(getattr(self, on) == gene)[0][0] for gene in genes]
        else:
            genes_idx = genes
        return np.asarray(genes_idx, dtype=np.int64)

    #############################
    #                           #
    #      CELL FILTERING       #
    #                           #
    ############################# 
开发者ID:YosefLab,项目名称:scVI,代码行数:22,代码来源:dataset.py

示例13: filter_cell_types

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def filter_cell_types(self, cell_types: Union[List[str], List[int], np.ndarray]):
        """Performs in-place filtering of cells by keeping cell types in ``cell_types``.

        Parameters
        ----------
        cell_types
            numpy array of type np.int (indices) or np.str (cell-types names)
        """
        cell_types = np.asarray(cell_types)
        if isinstance(cell_types[0], str):
            labels_to_keep = self.cell_types_to_labels(cell_types)
        elif isinstance(cell_types[0], (int, np.integer)):
            labels_to_keep = cell_types
        else:
            raise ValueError(
                "Wrong dtype for cell_types. Should be either str or int (labels)."
            )

        subset_cells = self._get_cells_filter_mask_by_attribute(
            attribute_name="labels",
            attribute_values_to_keep=labels_to_keep,
            return_data=False,
        )

        self.update_cells(subset_cells) 
开发者ID:YosefLab,项目名称:scVI,代码行数:27,代码来源:dataset.py

示例14: map_cell_types

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def map_cell_types(
        self,
        cell_types_dict: Dict[Union[int, str, Tuple[int, ...], Tuple[str, ...]], str],
    ):
        """Performs in-place filtering of cells using a cell type mapping.

        Cell types in the keys of ``cell_types_dict`` are merged and given the name of the associated value

        Parameters
        ----------
        cell_types_dict
            dictionary with tuples of cell types to merge as keys
            and new cell type names as values.
        """
        for cell_types, new_cell_type_name in cell_types_dict.items():
            self.merge_cell_types(cell_types, new_cell_type_name) 
开发者ID:YosefLab,项目名称:scVI,代码行数:18,代码来源:dataset.py

示例15: reorder_cell_types

# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import str [as 别名]
def reorder_cell_types(self, new_order: Union[List[str], np.ndarray]):
        """Reorder in place the cell-types. The cell-types provided will be added at the beginning of `cell_types`
        attribute, such that if some existing cell-types are omitted in `new_order`, they will be left after the
        new given order
        """
        if isinstance(new_order, np.ndarray):
            new_order = new_order.tolist()

        for cell_type in self.cell_types:
            if cell_type not in new_order:
                new_order.append(cell_type)

        cell_types = OrderedDict([((x,), x) for x in new_order])
        self.map_cell_types(cell_types)
        self.remap_categorical_attributes(["labels"])

    #############################
    #                           #
    #           MISC.           #
    #                           #
    ############################# 
开发者ID:YosefLab,项目名称:scVI,代码行数:23,代码来源:dataset.py


注:本文中的numpy.str方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。