Python numpy.str() Examples

The following are 30 code examples for showing how to use numpy.str(). 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: BetaElephant   Author: milkpku   File: tensor2fen.py    License: MIT License 7 votes vote down vote up
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 
Example 2
Project: mlearn   Author: materialsvirtuallab   File: gap.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example 3
Project: BetaElephant   Author: milkpku   File: tensor2fen.py    License: MIT License 6 votes vote down vote up
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 
Example 4
Project: BetaElephant   Author: milkpku   File: tensor2fen.py    License: MIT License 6 votes vote down vote up
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 
Example 5
Project: BetaElephant   Author: milkpku   File: tensor2fen.py    License: MIT License 6 votes vote down vote up
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 
Example 6
Project: BetaElephant   Author: milkpku   File: tensor2fen.py    License: MIT License 6 votes vote down vote up
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 
Example 7
Project: Counterfactual-StoryRW   Author: qkaren   File: dtypes.py    License: MIT License 6 votes vote down vote up
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 
Example 8
Project: R2CNN_Faster-RCNN_Tensorflow   Author: DetectionTeamUCAS   File: txt2xml.py    License: MIT License 6 votes vote down vote up
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) 
Example 9
Project: R2CNN_Faster-RCNN_Tensorflow   Author: DetectionTeamUCAS   File: txt2xml.py    License: MIT License 6 votes vote down vote up
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) 
Example 10
Project: scVI   Author: YosefLab   File: cortex.py    License: MIT License 6 votes vote down vote up
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,
        ) 
Example 11
Project: scVI   Author: YosefLab   File: dataset10X.py    License: MIT License 6 votes vote down vote up
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
        ) 
Example 12
Project: scVI   Author: YosefLab   File: cite_seq.py    License: MIT License 6 votes vote down vote up
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,
        ) 
Example 13
Project: scVI   Author: YosefLab   File: hemato.py    License: MIT License 6 votes vote down vote up
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,
        ) 
Example 14
Project: scVI   Author: YosefLab   File: synthetic.py    License: MIT License 6 votes vote down vote up
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,
        ) 
Example 15
Project: scVI   Author: YosefLab   File: dataset.py    License: MIT License 6 votes vote down vote up
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) 
Example 16
Project: scVI   Author: YosefLab   File: dataset.py    License: MIT License 6 votes vote down vote up
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       #
    #                           #
    ############################# 
Example 17
Project: scVI   Author: YosefLab   File: dataset.py    License: MIT License 6 votes vote down vote up
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       #
    #                           #
    ############################# 
Example 18
Project: scVI   Author: YosefLab   File: dataset.py    License: MIT License 6 votes vote down vote up
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) 
Example 19
Project: scVI   Author: YosefLab   File: dataset.py    License: MIT License 6 votes vote down vote up
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) 
Example 20
Project: scVI   Author: YosefLab   File: dataset.py    License: MIT License 6 votes vote down vote up
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.           #
    #                           #
    ############################# 
Example 21
Project: coded   Author: bullocke   File: postprocess_utils.py    License: MIT License 6 votes vote down vote up
def convert_date(config, array):

    """ Convert date from years since 1970 to year """

    date_band = config['general']['date_band'] - 1
    if len(array.shape) == 3:
        array[date_band,:,:][array[date_band,:,:] > 0] += 1970
        doys = np.modf(array[date_band,:,:])[0]
        doys = ((doys * 365).astype(int)).astype(np.str)
        array[date_band,:,:] = np.core.defchararray.add(
	    		       array[date_band,:,:].astype(np.int).
			       astype(np.str), doys)
    else:
        array[array > 0] += 1970
        doys = np.modf(array)[0]
        doys = ((doys * 365).astype(int)).astype(np.str)
        array = np.core.defchararray.add(
	        array.astype(np.int).
	        astype(np.str), doys)
    return array 
Example 22
Project: coded   Author: bullocke   File: postprocess_utils.py    License: MIT License 6 votes vote down vote up
def min_max_years(config, image, before):
    """ Exclude data outside of min and max year desired """
    min_year = int(config['postprocessing']['minimum_year'])
    if not min_year:
	min_year = 1980

    max_year = int(config['postprocessing']['maximum_year'])
    if not max_year:
	max_year = 2200

    year_image = image[0,:,:].astype(np.str).view(np.chararray).ljust(4)
    year_image = np.array(year_image).astype(np.float) 

    bad_indices = np.logical_or(year_image < min_year, year_image > max_year)
    for i in range(image.shape[0] - 1):
        image[i,:,:][bad_indices] = 0

    image[image.shape[0]-1,:,:][bad_indices] = before[bad_indices]

    return image 
Example 23
Project: tmtoolkit   Author: WZBSocialScienceCenter   File: test_preprocess_tmpreproc.py    License: Apache License 2.0 6 votes vote down vote up
def test_tmpreproc_en_pos_tag(tmpreproc_en):
    tmpreproc_en.pos_tag()
    tokens = tmpreproc_en.tokens
    tokens_with_pos_tags = tmpreproc_en.tokens_with_pos_tags

    assert set(tokens.keys()) == set(tokens_with_pos_tags.keys())

    for dl, dtok in tokens.items():
        tok_pos_df = tokens_with_pos_tags[dl]
        assert len(dtok) == tok_pos_df.shape[0]
        assert list(pd_dt_colnames(tok_pos_df)) == ['token', 'meta_pos']

        if USE_DT:
            tok_pos_df = tok_pos_df.to_pandas()

        assert np.array_equal(dtok, tok_pos_df.token)
        if dl != 'empty_doc':
            assert all(tok_pos_df.meta_pos.str.len() > 0) 
Example 24
Project: tmtoolkit   Author: WZBSocialScienceCenter   File: test_preprocess_tmpreproc.py    License: Apache License 2.0 6 votes vote down vote up
def test_tmpreproc_en_filter_for_pos_none(tmpreproc_en):
    all_tok = tmpreproc_en.pos_tag().tokens_with_pos_tags
    filtered_tok = tmpreproc_en.filter_for_pos(None).tokens_with_pos_tags

    assert set(all_tok.keys()) == set(filtered_tok.keys())

    for dl, tok_pos in all_tok.items():
        tok_pos_ = filtered_tok[dl]

        assert tok_pos_.shape[0] <= tok_pos.shape[0]
        if USE_DT:
            meta_pos_ = np.array(tok_pos_.to_dict()['meta_pos'], dtype=np.str)
        else:
            meta_pos_ = np.array(tok_pos_['meta_pos'].tolist(), dtype=np.str)
        simpl_postags = [simplified_pos(pos) for pos in meta_pos_]
        assert all(pos is None for pos in simpl_postags) 
Example 25
Project: tmtoolkit   Author: WZBSocialScienceCenter   File: test_preprocess_tmpreproc.py    License: Apache License 2.0 6 votes vote down vote up
def test_tmpreproc_en_filter_for_multiple_pos2(tmpreproc_en):
    req_tags = {'N', 'V', None}
    all_tok = tmpreproc_en.pos_tag().tokens_with_pos_tags
    filtered_tok = tmpreproc_en.filter_for_pos(req_tags).tokens_with_pos_tags

    assert set(all_tok.keys()) == set(filtered_tok.keys())

    for dl, tok_pos in all_tok.items():
        tok_pos_ = filtered_tok[dl]

        assert tok_pos_.shape[0] <= tok_pos.shape[0]
        if USE_DT:
            meta_pos_ = np.array(tok_pos_.to_dict()['meta_pos'], dtype=np.str)
        else:
            meta_pos_ = np.array(tok_pos_['meta_pos'].tolist(), dtype=np.str)
        simpl_postags = [simplified_pos(pos) for pos in meta_pos_]
        assert all(pos in req_tags for pos in simpl_postags) 
Example 26
Project: mlearn   Author: materialsvirtuallab   File: gap.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, name=None, param=None):
        """

        Args:
            name (str): Name of force field.
            param (dict): The parameter configuration of potentials.
        """
        self.name = name if name else "GAPotential"
        self.param = param if param else {}
        self.specie = None 
Example 27
Project: mlearn   Author: materialsvirtuallab   File: gap.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def write_cfgs(self, filename, cfg_pool):
        """
        Write the formatted configuration file.

        Args:
            filename (str): The filename to be written.
            cfg_pool (list): The configuration pool contains
                structure and energy/forces properties.
        """
        if not filename.endswith('.xyz'):
            raise RuntimeError('The extended xyz file should end with ".xyz"')

        lines = []
        for dataset in cfg_pool:
            if isinstance(dataset['structure'], dict):
                structure = Structure.from_dict(dataset['structure'])
            else:
                structure = dataset['structure']
            energy = dataset['outputs']['energy']
            forces = dataset['outputs']['forces']
            virial_stress = dataset['outputs']['virial_stress']

            lines.append(self._line_up(structure, energy, forces, virial_stress))

        self.specie = Element(structure.symbol_set[0])

        with open(filename, 'w') as f:
            f.write('\n'.join(lines))

        return filename 
Example 28
Project: mlearn   Author: materialsvirtuallab   File: gap.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save(self, filename='param.yaml'):
        """
        Save parameters of the potentials.

        Args:
            filename (str): The file to store parameters of potentials.

        Returns:
            (str)
        """
        with open(filename, 'w') as f:
            yaml.dump(self.param, f)

        return filename 
Example 29
Project: BetaElephant   Author: milkpku   File: tensor2fen.py    License: MIT License 5 votes vote down vote up
def state2fen(state):
    '''
    transfer the chessboard to fen string
    state: state of the current chessboard
    turn: which player to play
    round: count of round
    return: fen string
    '''
    fen = ''
    [m,n] = state.shape
    for i in range(m):
        zcnt = 0
        for j in range(n):
            if state[i][j] != ' ':
                if zcnt != 0:
                    fen += str(zcnt)
                    zcnt = 0
                fen += state[i][j]
            else:
                zcnt += 1
        if zcnt != 0:
            fen += str(zcnt)
            zcnt = 0
        fen += '/'
    fen = fen[:-1]
    fen += ' w'
    fen += ' - - 0 1'
    return fen 
Example 30
Project: BetaElephant   Author: milkpku   File: tensor2fen.py    License: MIT License 5 votes vote down vote up
def state2fen(state):
    '''
    transfer the chessboard to fen string
    state: state of the current chessboard
    turn: which player to play
    round: count of round
    return: fen string
    '''
    fen = ''
    [m,n] = state.shape
    for i in range(m):
        zcnt = 0
        for j in range(n):
            if state[i][j] != ' ':
                if zcnt != 0:
                    fen += str(zcnt)
                    zcnt = 0
                fen += state[i][j]
            else:
                zcnt += 1
        if zcnt != 0:
            fen += str(zcnt)
            zcnt = 0
        fen += '/'
    fen = fen[:-1]
    fen += ' w'
    fen += ' - - 0 1'
    return fen