code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def query(self, coords, **kwargs): return self._scale * super(PlanckQuery, self).query(coords, **kwargs)
Returns E(B-V) (or a different Planck dust inference, depending on how the class was intialized) at the specified location(s) on the sky. Args: coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query. Returns: A float array of the selected Planck componen...
def expand_action(data): # when given a string, assume user wants to index raw json if isinstance(data, string_types): return '{"index":{}}', data # make sure we don't alter the action data = data.copy() op_type = data.pop('_op_type', 'index') action = {op_type: {}} for key in ...
From one document or action definition passed in by the user extract the action/data lines needed for elasticsearch's :meth:`~elasticsearch.Elasticsearch.bulk` api.
def _chunk_actions(actions, chunk_size, max_chunk_bytes, serializer): bulk_actions = [] size, action_count = 0, 0 for action, data in actions: action = serializer.dumps(action) cur_size = len(action) + 1 if data is not None: data = serializer.dumps(data) ...
Split actions into chunks by number or size, serialize them into strings in the process.
def streaming_bulk(client, actions, chunk_size=500, max_chunk_bytes=100 * 1014 * 1024, raise_on_error=True, expand_action_callback=expand_action, raise_on_exception=True, **kwargs): actions = map(expand_action_callback, actions) for bulk_actions in _chunk_actions(actions, chunk_size, max_c...
Streaming bulk consumes actions from the iterable passed in and yields results per action. For non-streaming usecases use :func:`~elasticsearch.helpers.bulk` which is a wrapper around streaming bulk that returns summary information about the bulk operation once the entire input is consumed and sent. ...
def bulk(client, actions, stats_only=False, **kwargs): success, failed = 0, 0 # list of errors to be collected is not stats_only errors = [] for ok, item in streaming_bulk(client, actions, **kwargs): # go through request-reponse pairs and detect failures if not ok: if ...
Helper for the :meth:`~elasticsearch.Elasticsearch.bulk` api that provides a more human friendly interface - it consumes an iterator of actions and sends them to elasticsearch in chunks. It returns a tuple with summary information - number of successfully executed actions and either list of errors or nu...
def parallel_bulk(client, actions, thread_count=4, chunk_size=500, max_chunk_bytes=100 * 1014 * 1024, expand_action_callback=expand_action, **kwargs): # Avoid importing multiprocessing unless parallel_bulk is used # to avoid exceptions on restricted environments like App Engine from mul...
Parallel version of the bulk helper run in multiple threads at once. :arg client: instance of :class:`~elasticsearch.Elasticsearch` to use :arg actions: iterator containing the actions :arg thread_count: size of the threadpool to use for the bulk requests :arg chunk_size: number of docs in one chunk sen...
def setcontext(context, _local=local): oldcontext = getcontext() _local.__bigfloat_context__ = oldcontext + context
Set the current context to that given. Attributes provided by ``context`` override those in the current context. If ``context`` doesn't specify a particular attribute, the attribute from the current context shows through.
def _apply_function_in_context(cls, f, args, context): rounding = context.rounding bf = mpfr.Mpfr_t.__new__(cls) mpfr.mpfr_init2(bf, context.precision) args = (bf,) + args + (rounding,) ternary = f(*args) with _temporary_exponent_bounds(context.emin, context.emax): ternary = mpfr.mp...
Apply an MPFR function 'f' to the given arguments 'args', rounding to the given context. Returns a new Mpfr object with precision taken from the current context.
def p_filter_expr_predicate(p): if not hasattr(p[1], 'append_predicate'): p[1] = ast.PredicatedExpression(p[1]) p[1].append_predicate(p[2]) p[0] = p[1]
FilterExpr : FilterExpr Predicate
def p_function_call(p): # FIXME: This production also matches NodeType() or # processing-instruction("foo"), which are technically NodeTest qname = p[1] p[0] = ast.FunctionCall(qname[0], qname[1], p[2])
FunctionCall : FuncQName FormalArguments
def get_logger(name=None): level = logging.CRITICAL if DEBUG: logging.disable(logging.NOTSET) level = logging.DEBUG if name is None: name = "<unknown>" log = logging.getLogger(name=name) log.setLevel( level ) console = logging.StreamHandler() console.setLevel(...
Get virtualchain's logger
def get_config_filename(impl, working_dir): config_filename = impl.get_virtual_chain_name() + ".ini" return os.path.join(working_dir, config_filename)
Get the absolute path to the config file.
def get_db_filename(impl, working_dir): db_filename = impl.get_virtual_chain_name() + ".db" return os.path.join(working_dir, db_filename)
Get the absolute path to the last-block file.
def get_snapshots_filename(impl, working_dir): snapshots_filename = impl.get_virtual_chain_name() + ".snapshots" return os.path.join(working_dir, snapshots_filename)
Get the absolute path to the chain's consensus snapshots file.
def get_lockfile_filename(impl, working_dir): lockfile_name = impl.get_virtual_chain_name() + ".lock" return os.path.join(working_dir, lockfile_name)
Get the absolute path to the chain's indexing lockfile
def query(self, coords, order=1): out = np.full(len(coords.l.deg), np.nan, dtype='f4') for pole in self.poles: m = (coords.b.deg >= 0) if pole == 'ngp' else (coords.b.deg < 0) if np.any(m): data, w = self._data[pole] x, y = w.wcs_world2p...
Returns the map value at the specified location(s) on the sky. Args: coords (`astropy.coordinates.SkyCoord`): The coordinates to query. order (Optional[int]): Interpolation order to use. Defaults to `1`, for linear interpolation. Returns: A float arr...
def query(self, coords, order=1): return super(SFDQuery, self).query(coords, order=order)
Returns E(B-V) at the specified location(s) on the sky. See Table 6 of Schlafly & Finkbeiner (2011) for instructions on how to convert this quantity to extinction in various passbands. Args: coords (`astropy.coordinates.SkyCoord`): The coordinates to query. order (Option...
def is_empty(self): return all(date.is_empty() for date in [self.created, self.issued]) \ and not self.publisher
Returns True if all child date elements present are empty and other nodes are not set. Returns False if any child date elements are not empty or other nodes are set.
def is_empty(self): non_type_attributes = [attr for attr in self.node.attrib.keys() if attr != 'type'] return len(self.node) == 0 and len(non_type_attributes) == 0 \ and not self.node.text and not self.node.tail
Returns True if the root node contains no child elements, no text, and no attributes other than **type**. Returns False if any are present.
def is_empty(self): '''Returns True if all titleInfo subfields are not set or empty; returns False if any of the fields are not empty.''' return not bool(self.title or self.subtitle or self.part_number \ or self.part_name or self.non_sort or self.typef is_empty(self): ...
Returns True if all titleInfo subfields are not set or empty; returns False if any of the fields are not empty.
def is_empty(self): '''Returns True if details, extent, and type are not set or return True for ``is_empty``; returns False if any of the fields are not empty.''' return all(field.is_empty() for field in [self.details, self.extent] if field is not None) \ ...
Returns True if details, extent, and type are not set or return True for ``is_empty``; returns False if any of the fields are not empty.
def batch_(self, rpc_calls): batch_data = [] for rpc_call in rpc_calls: AuthServiceProxy.__id_count += 1 m = rpc_call.pop(0) batch_data.append({"jsonrpc":"2.0", "method":m, "params":rpc_call, "id":AuthServiceProxy.__id_count}) postdata = json.dumps(b...
Batch RPC call. Pass array of arrays: [ [ "method", params... ], ... ] Returns array of results.
def getinfo(self): try: old_getinfo = AuthServiceProxy(self.__service_url, 'getinfo', self.__timeout, self.__conn, True) res = old_getinfo() if 'error' not in res: # 0.13 and earlier return res except JSONRPCException: ...
Backwards-compatibility for 0.14 and later
def get_cartesian(self): coords = ['x', 'y', 'z'] eq_sets = self._metadata['eq']['eq_sets'] sym_ops = self._metadata['eq']['sym_ops'] frame = pd.DataFrame(index=[i for v in eq_sets.values() for i in v], columns=['atom', 'x', 'y', 'z'], dtype='f8') ...
Return a :class:`~Cartesian` where all members of a symmetry equivalence class are inserted back in. Args: None Returns: Cartesian: A new cartesian instance.
def btc_script_to_hex(script): hex_script = '' parts = script.split(' ') for part in parts: if part[0:3] == 'OP_': value = OPCODE_VALUES.get(part) if not value: raise ValueError("Unrecognized opcode {}".format(part)) hex_script += "%0.2x" % ...
Parse the string representation of a script and return the hex version. Example: "OP_DUP OP_HASH160 c629...a6db OP_EQUALVERIFY OP_CHECKSIG"
def btc_script_deserialize(script): if isinstance(script, str) and re.match('^[0-9a-fA-F]*$', script): script = binascii.unhexlify(script) # output buffer out = [] pos = 0 while pos < len(script): # next script op... code = encoding.from_byte_to_int(script[pos]) ...
Given a script (hex or bin), decode it into its list of opcodes and data. Return a list of strings and ints. Based on code in pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin
def _btc_script_serialize_unit(unit): if isinstance(unit, int): # cannot be less than -1, since btc_script_deserialize() never returns such numbers if unit < -1: raise ValueError('Invalid integer: {}'.format(unit)) if unit < 16: if unit == 0: ...
Encode one item of a BTC script Return the encoded item (as a string) Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin
def btc_script_serialize(_script): script = _script if encoding.json_is_base(_script, 16): # hex-to-bin all hex strings in this script script = encoding.json_changebase(_script, lambda x: binascii.unhexlify(x)) # encode each item and return the concatenated list return encoding.saf...
Given a deserialized script (i.e. an array of Nones, ints, and strings), or an existing script, turn it back into a hex script Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin
def btc_make_payment_script( address, segwit=None, **ignored ): if segwit is None: segwit = get_features('segwit') # is address bech32-encoded? witver, withash = segwit_addr_decode(address) if witver is not None and withash is not None: # bech32 segwit address if not s...
Make a pay-to-address script.
def btc_make_data_script( data, **ignored ): if len(data) >= MAX_DATA_LEN * 2: raise ValueError("Data hex string is too long") # note: data is a hex string if len(data) % 2 != 0: raise ValueError("Data hex string is not even length") return "6a{:02x}{}".format(len(data)/2, data)
Make a data-bearing transaction output. Data must be a hex string Returns a hex string.
def btc_script_hex_to_address( script_hex, segwit=None ): # TODO: make this support more than bitcoin-like scripts if script_hex.startswith("76a914") and script_hex.endswith("88ac") and len(script_hex) == 50: # p2pkh script hash160_bin = binascii.unhexlify(script_hex[6:-4]) return b...
Examine a script (hex-encoded) and extract an address. Return the address on success Return None on error
def btc_make_p2sh_address( script_hex ): h = hashing.bin_hash160(binascii.unhexlify(script_hex)) addr = bin_hash160_to_address(h, version_byte=multisig_version_byte) return addr
Make a P2SH address from a hex script
def btc_make_p2wpkh_address( pubkey_hex ): pubkey_hex = keylib.key_formatting.compress(pubkey_hex) hash160_bin = hashing.bin_hash160(pubkey_hex.decode('hex')) return segwit_addr_encode(hash160_bin)
Make a p2wpkh address from a hex pubkey
def btc_make_p2sh_p2wpkh_redeem_script( pubkey_hex ): pubkey_hash = hashing.bin_hash160(pubkey_hex.decode('hex')).encode('hex') redeem_script = btc_script_serialize(['0014' + pubkey_hash]) return redeem_script
Make the redeem script for a p2sh-p2wpkh witness script
def btc_make_p2sh_p2wsh_redeem_script( witness_script_hex ): witness_script_hash = hashing.bin_sha256(witness_script_hex.decode('hex')).encode('hex') redeem_script = btc_script_serialize(['0020' + witness_script_hash]) return redeem_script
Make the redeem script for a p2sh-p2wsh witness script
def btc_is_p2sh_address( address ): vb = keylib.b58check.b58check_version_byte( address ) if vb == multisig_version_byte: return True else: return False
Is the given address a p2sh address?
def btc_is_p2pkh_address( address ): vb = keylib.b58check.b58check_version_byte( address ) if vb == version_byte: return True else: return False
Is the given address a p2pkh address?
def btc_is_p2wpkh_address( address ): wver, whash = segwit_addr_decode(address) if whash is None: return False if len(whash) != 20: return False return True
Is the given address a p2wpkh address?
def btc_is_p2wsh_address( address ): wver, whash = segwit_addr_decode(address) if whash is None: return False if len(whash) != 32: return False return True
Is the given address a p2wsh address?
def btc_is_p2sh_script( script_hex ): if script_hex.startswith("a914") and script_hex.endswith("87") and len(script_hex) == 46: return True else: return False
Is the given scriptpubkey a p2sh script?
def btc_is_multisig(privkey_info, **blockchain_opts): try: jsonschema.validate(privkey_info, PRIVKEY_MULTISIG_SCHEMA) return not privkey_info.get('segwit', False) except ValidationError as e: return False
Does the given private key info represent a multisig bundle? For Bitcoin, this is true for multisig p2sh (not p2sh-p2wsh)
def btc_is_multisig_segwit(privkey_info): try: jsonschema.validate(privkey_info, PRIVKEY_MULTISIG_SCHEMA) if len(privkey_info['private_keys']) == 1: return False return privkey_info.get('segwit', False) except ValidationError as e: return False
Does the given private key info represent a multisig bundle? For Bitcoin, this is true for multisig p2sh (not p2sh-p2wsh)
def btc_is_singlesig(privkey_info, **blockchain_opts): try: jsonschema.validate(privkey_info, PRIVKEY_SINGLESIG_SCHEMA) return True except ValidationError as e: return False
Does the given private key info represent a single signature bundle? (i.e. one private key)? i.e. is this key a private key string?
def btc_is_singlesig_segwit(privkey_info): try: jsonschema.validate(privkey_info, PRIVKEY_MULTISIG_SCHEMA) if len(privkey_info['private_keys']) > 1: return False return privkey_info.get('segwit', False) except ValidationError: return False
Is the given key bundle a p2sh-p2wpkh key bundle?
def btc_get_privkey_address(privkey_info, **blockchain_opts): from .multisig import make_multisig_segwit_address_from_witness_script if btc_is_singlesig(privkey_info): return btc_address_reencode( ecdsalib.ecdsa_private_key(privkey_info).public_key().address() ) if btc_is_multisig(pr...
Get the address for a given private key info bundle (be it multisig or singlesig) Return the address on success Raise exception on error
def segwit_addr_decode(addr, hrp=bech32_prefix): hrpgot, data = bech32_decode(addr) if hrpgot != hrp: return (None, None) decoded = convertbits(data[1:], 5, 8, False) if decoded is None or len(decoded) < 2 or len(decoded) > 40: return (None, None) if data[0] > 16: return...
Decode a segwit address. Returns (version, hash_bin) on success Returns (None, None) on error
def segwit_addr_encode(witprog_bin, hrp=bech32_prefix, witver=bech32_witver): witprog_bytes = [ord(c) for c in witprog_bin] ret = bech32_encode(hrp, [int(witver)] + convertbits(witprog_bytes, 8, 5)) assert segwit_addr_decode(hrp, ret) is not (None, None) return ret
Encode a segwit script hash to a bech32 address. Returns the bech32-encoded string on success
def format_git_describe(git_str, pep440=False): if git_str is None: return None if "-" not in git_str: # currently at a tag return git_str else: # formatted as version-N-githash # want to convert to version.postN-githash git_str = git_str.replace("-", ".post", 1...
format the result of calling 'git describe' as a python version
def read_release_version(): try: with open(VERSION_FILE, "r") as infile: version = str(infile.read().strip()) if len(version) == 0: version = None return version except IOError: return None
Read version information from VERSION file
def update_release_version(): version = get_version(pep440=True) with open(VERSION_FILE, "w") as outfile: outfile.write(version) outfile.write("\n")
Update VERSION file
def get_version(pep440=False): git_version = format_git_describe(call_git_describe(), pep440=pep440) if git_version is None: # not a git repository return read_release_version() return git_version
Tracks the version number. pep440: bool When True, this function returns a version string suitable for a release as defined by PEP 440. When False, the githash (if available) will be appended to the version string. The file VERSION holds the version information. If this is not a git ...
def call_git_branch(): try: with open(devnull, "w") as fnull: arguments = [GIT_COMMAND, 'rev-parse', '--abbrev-ref', 'HEAD'] return check_output(arguments, cwd=CURRENT_DIRECTORY, stderr=fnull).decode("ascii").strip() except (OSError, CalledPro...
return the string output of git desribe
def read_git_branch(): try: with open(CC_INIT, "r") as f: found = False while not found: line = f.readline().strip().split() try: found = True if line[0] == '_git_branch' else False except IndexError: ...
Read version information from VERSION file
def parseUri(stream, uri=None): return etree.parse(stream, parser=_get_xmlparser(), base_url=uri)
Read an XML document from a URI, and return a :mod:`lxml.etree` document.
def parseString(string, uri=None): return etree.fromstring(string, parser=_get_xmlparser(), base_url=uri)
Read an XML document provided as a byte string, and return a :mod:`lxml.etree` document. String cannot be a Unicode string. Base_uri should be provided for the calculation of relative URIs.
def loadSchema(uri, base_uri=None): # uri to use for reporting errors - include base uri if any if uri in _loaded_schemas: return _loaded_schemas[uri] error_uri = uri if base_uri is not None: error_uri += ' (base URI %s)' % base_uri try: logger.debug('Loading schema ...
Load an XSD XML document (specified by filename or URL), and return a :class:`lxml.etree.XMLSchema`.
def load_xslt(filename=None, xsl=None): '''Load and compile an XSLT document (specified by filename or string) for repeated use in transforming XML. ''' parser = _get_xmlparser() if filename is not None: xslt_doc = etree.parse(filename, parser=parser) if xsl is not None: xslt_doc...
Load and compile an XSLT document (specified by filename or string) for repeated use in transforming XML.
def _get_xmlparser(xmlclass=XmlObject, validate=False, resolver=None): if validate: if hasattr(xmlclass, 'XSD_SCHEMA') and xmlclass.XSD_SCHEMA is not None: # If the schema has already been loaded, use that. # (since we accessing the *class*, accessing 'xmlschema' returns a prope...
Initialize an instance of :class:`lxml.etree.XMLParser` with appropriate settings for validation. If validation is requested and the specified instance of :class:`XmlObject` has an XSD_SCHEMA defined, that will be used. Otherwise, uses DTD validation. Switched resolver to None to skip validation.
def load_xmlobject_from_string(string, xmlclass=XmlObject, validate=False, resolver=None): parser = _get_xmlparser(xmlclass=xmlclass, validate=validate, resolver=resolver) element = etree.fromstring(string, parser) return xmlclass(element)
Initialize an XmlObject from a string. If an xmlclass is specified, construct an instance of that class instead of :class:`~eulxml.xmlmap.XmlObject`. It should be a subclass of XmlObject. The constructor will be passed a single node. If validation is requested and the specified subclass of :class:`Xml...
def load_xmlobject_from_file(filename, xmlclass=XmlObject, validate=False, resolver=None): parser = _get_xmlparser(xmlclass=xmlclass, validate=validate, resolver=resolver) tree = etree.parse(filename, parser) return xmlclass(tree.getroot())
Initialize an XmlObject from a file. See :meth:`load_xmlobject_from_string` for more details; behaves exactly the same, and accepts the same parameters, except that it takes a filename instead of a string. :param filename: name of the file that should be loaded as an xmlobject. :meth:`etree.lx...
def to_string(self, buf=None, format_abs_ref_as='string', upper_triangle=True, header=True, index=True, **kwargs): out = self._sympy_formatter() out = out._abs_ref_formatter(format_as=format_abs_ref_as) if not upper_triangle: out = out._remove_upper_triangl...
Render a DataFrame to a console-friendly tabular output. Wrapper around the :meth:`pandas.DataFrame.to_string` method.
def to_latex(self, buf=None, upper_triangle=True, **kwargs): out = self._sympy_formatter() out = out._abs_ref_formatter(format_as='latex') if not upper_triangle: out = out._remove_upper_triangle() return out._frame.to_latex(buf=buf, **kwargs)
Render a DataFrame to a tabular environment table. You can splice this into a LaTeX document. Requires ``\\usepackage{booktabs}``. Wrapper around the :meth:`pandas.DataFrame.to_latex` method.
def to_zmat(self, buf=None, upper_triangle=True, implicit_index=True, float_format='{:.6f}'.format, overwrite=True, header=False): out = self.copy() if implicit_index: out = out.change_numbering(new_index=range(1, len(self) + 1)) if not upper_...
Write zmat-file Args: buf (str): StringIO-like, optional buffer to write to implicit_index (bool): If implicit_index is set, the zmat indexing is changed to ``range(1, len(self) + 1)``. Using :meth:`~chemcoord.Zmat.change_numbering` Beside...
def write(self, *args, **kwargs): message = 'Will be removed in the future. Please use to_zmat().' with warnings.catch_warnings(): warnings.simplefilter("always") warnings.warn(message, DeprecationWarning) return self.to_zmat(*args, **kwargs)
Deprecated, use :meth:`~chemcoord.Zmat.to_zmat`
def to_latex(self, buf=None, columns=None, col_space=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=None, index_names=True, bold_rows=True, column_format=None, longtable=None, escape=None, encoding=None, decim...
Render a DataFrame to a tabular environment table. You can splice this into a LaTeX document. Requires ``\\usepackage{booktabs}``. Wrapper around the :meth:`pandas.DataFrame.to_latex` method.
def to_xyz(self, buf=None, sort_index=True, index=False, header=False, float_format='{:.6f}'.format, overwrite=True): if sort_index: molecule_string = self.sort_index().to_string( header=header, index=index, float_format=float_format) el...
Write xyz-file Args: buf (str): StringIO-like, optional buffer to write to sort_index (bool): If sort_index is true, the :class:`~chemcoord.Cartesian` is sorted by the index before writing. float_format (one-parameter function): Formatter func...
def write_xyz(self, *args, **kwargs): message = 'Will be removed in the future. Please use to_xyz().' with warnings.catch_warnings(): warnings.simplefilter("always") warnings.warn(message, DeprecationWarning) return self.to_xyz(*args, **kwargs)
Deprecated, use :meth:`~chemcoord.Cartesian.to_xyz`
def read_xyz(cls, buf, start_index=0, get_bonds=True, nrows=None, engine=None): frame = pd.read_table(buf, skiprows=2, comment='#', nrows=nrows, delim_whitespace=True, names=['atom', 'x', 'y', 'z'...
Read a file of coordinate information. Reads xyz-files. Args: inputfile (str): start_index (int): get_bonds (bool): nrows (int): Number of rows of file to read. Note that the first two rows are implicitly excluded. engine (str...
def to_cjson(self, buf=None, **kwargs): cjson_dict = {'chemical json': 0} cjson_dict['atoms'] = {} atomic_number = constants.elements['atomic_number'].to_dict() cjson_dict['atoms'] = {'elements': {}} cjson_dict['atoms']['elements']['number'] = [ int(atomic_...
Write a cjson file or return dictionary. The cjson format is specified `here <https://github.com/OpenChemistry/chemicaljson>`_. Args: buf (str): If it is a filepath, the data is written to filepath. If it is None, a dictionary with the cjson informat...
def read_cjson(cls, buf): if isinstance(buf, dict): data = buf.copy() else: with open(buf, 'r') as f: data = json.load(f) assert data['chemical json'] == 0 n_atoms = len(data['atoms']['coords']['3d']) metadata = {} _me...
Read a cjson file or a dictionary. The cjson format is specified `here <https://github.com/OpenChemistry/chemicaljson>`_. Args: buf (str, dict): If it is a filepath, the data is read from filepath. If it is a dictionary, the dictionary is interpreted ...
def view(self, viewer=None, use_curr_dir=False): if viewer is None: viewer = settings['defaults']['viewer'] if use_curr_dir: TEMP_DIR = os.path.curdir else: TEMP_DIR = tempfile.gettempdir() def give_filename(i): filename = 'ChemCo...
View your molecule. .. note:: This function writes a temporary file and opens it with an external viewer. If you modify your molecule afterwards you have to recall view in order to see the changes. Args: viewer (str): The external viewer to use. If it is...
def get_pymatgen_molecule(self): from pymatgen import Molecule return Molecule(self['atom'].values, self.loc[:, ['x', 'y', 'z']].values)
Create a Molecule instance of the pymatgen library .. warning:: The `pymatgen library <http://pymatgen.org>`_ is imported locally in this function and will raise an ``ImportError`` exception, if it is not installed. Args: None Returns: :class:`p...
def from_pymatgen_molecule(cls, molecule): new = cls(atoms=[el.value for el in molecule.species], coords=molecule.cart_coords) return new._to_numeric()
Create an instance of the own class from a pymatgen molecule Args: molecule (:class:`pymatgen.core.structure.Molecule`): Returns: Cartesian:
def from_ase_atoms(cls, atoms): return cls(atoms=atoms.get_chemical_symbols(), coords=atoms.positions)
Create an instance of the own class from an ase molecule Args: molecule (:class:`ase.atoms.Atoms`): Returns: Cartesian:
def _convert_eq(self, eq): rename = dict(enumerate(self.index)) eq['eq_sets'] = {rename[k]: {rename[x] for x in v} for k, v in eq['eq_sets'].items()} eq['sym_ops'] = {rename[k]: {rename[x]: v[x] for x in v} for k, v in eq['sym_ops'].item...
WORKS INPLACE on eq
def get_pointgroup(self, tolerance=0.3): PA = self._get_point_group_analyzer(tolerance=tolerance) return PointGroupOperations(PA.sch_symbol, PA.symmops)
Returns a PointGroup object for the molecule. Args: tolerance (float): Tolerance to generate the full set of symmetry operations. Returns: :class:`~PointGroupOperations`
def get_equivalent_atoms(self, tolerance=0.3): PA = self._get_point_group_analyzer(tolerance=tolerance) eq = PA.get_equivalent_atoms() self._convert_eq(eq) return eq
Returns sets of equivalent atoms with symmetry operations Args: tolerance (float): Tolerance to generate the full set of symmetry operations. Returns: dict: The returned dictionary has two possible keys: ``eq_sets``: A dictionary of indi...
def symmetrize(self, max_n=10, tolerance=0.3, epsilon=1e-3): mg_mol = self.get_pymatgen_molecule() eq = iterative_symmetrize(mg_mol, max_n=max_n, tolerance=tolerance, epsilon=epsilon) self._convert_eq(eq) return eq
Returns a symmetrized molecule The equivalent atoms obtained via :meth:`~Cartesian.get_equivalent_atoms` are rotated, mirrored... unto one position. Then the average position is calculated. The average position is rotated, mirrored... back with the inverse of the previou...
def read_tx_body(ptr, tx): _obj = {"ins": [], "outs": [], 'locktime': None} # number of inputs ins = read_var_int(ptr, tx) # all inputs for i in range(ins): _obj["ins"].append({ "outpoint": { "hash": read_bytes(ptr, tx, 32)[::-1], "index": r...
Returns {'ins': [...], 'outs': [...]}
def read_tx_witnesses(ptr, tx, num_witnesses): witnesses = [] for i in xrange(0, num_witnesses): witness_stack_len = read_var_int(ptr, tx) witness_stack = [] for j in xrange(0, witness_stack_len): stack_item = read_var_string(ptr, tx) witness_stack.append(...
Returns an array of witness scripts. Each witness will be a bytestring (i.e. encoding the witness script)
def make_var_string(string): s = None if isinstance(string, str) and re.match('^[0-9a-fA-F]*$', string): # convert from hex to bin, safely s = binascii.unhexlify(string) else: s = string[:] buf = encoding.num_to_var_int(len(s)) + s return buf.encode('hex')
Make a var-string (a var-int with the length, concatenated with the data) Return the hex-encoded string
def _btc_witness_serialize_unit(unit): if isinstance(unit, int): # pass literal return encoding.from_int_to_byte(unit) elif unit is None: # None means OP_0 return b'\x00' else: # return as a varint-prefixed string return make_var_string(unit)
Encode one item of a BTC witness script Return the encoded item (as a string) Returns a byte string with the encoded unit Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin
def btc_witness_script_serialize(_stack): stack = _stack if encoding.json_is_base(_stack, 16): # hex-to-bin all hex strings stack = encoding.json_changebase(_stack, lambda x: binascii.unhexlify(x)) return encoding.safe_hexlify(_btc_witness_serialize_unit(len(stack)) + ''.join(map(lamb...
Given a deserialized witness script stack (i.e. the input-specific witness, as an array of Nones, ints, and strings), turn it back into a hex-encoded script
def btc_witness_script_deserialize(_script): script = None if isinstance(_script, str) and re.match('^[0-9a-fA-F]*$', _script): # convert from hex to bin, safely script = binascii.unhexlify(_script) else: script = _script[:] # pointer to byte offset in _script (as an array...
Given a hex-encoded serialized witness script, turn it into a witness stack (i.e. an array of Nones, ints, and strings)
def btc_bitcoind_tx_serialize( tx ): tx_ins = [] tx_outs = [] try: for inp in tx['vin']: next_inp = { "outpoint": { "index": int(inp['vout']), "hash": str(inp['txid']) } } if 'sequ...
Convert a *Bitcoind*-given transaction into its hex string. tx format is {'vin': [...], 'vout': [...], 'locktime': ..., 'version': ...}, with the same formatting rules as getrawtransaction. (in particular, each value in vout is a Decimal, in BTC)
def btc_tx_is_segwit( tx_serialized ): marker_offset = 4 # 5th byte is the marker byte flag_offset = 5 # 6th byte is the flag byte marker_byte_string = tx_serialized[2*marker_offset:2*(marker_offset+1)] flag_byte_string = tx_serialized[2*flag_offset:2*(flag_offset+1)] if mar...
Is this serialized (hex-encoded) transaction a segwit transaction?
def btc_tx_witness_strip( tx_serialized ): if not btc_tx_is_segwit(tx_serialized): # already strippped return tx_serialized tx = btc_tx_deserialize(tx_serialized) for inp in tx['ins']: del inp['witness_script'] tx_stripped = btc_tx_serialize(tx) return tx_stripped
Strip the witness information from a serialized transaction
def btc_tx_get_hash( tx_serialized, hashcode=None ): if btc_tx_is_segwit(tx_serialized): raise ValueError('Segwit transaction: {}'.format(tx_serialized)) tx_bin = binascii.unhexlify(tx_serialized) if hashcode: return binascii.hexlify( hashing.bin_double_sha256(tx_bin + encoding.encode(...
Make a transaction hash (txid) from a hex tx, optionally along with a sighash. This DOES NOT WORK for segwit transactions
def btc_tx_script_to_asm( script_hex ): if len(script_hex) == 0: return "" try: script_array = btc_script_deserialize(script_hex) except: log.error("Failed to convert '%s' to assembler" % script_hex) raise script_tokens = [] for token in script_array: i...
Decode a script into assembler
def btc_tx_extend(partial_tx_hex, new_inputs, new_outputs, **blockchain_opts): # recover tx tx = btc_tx_deserialize(partial_tx_hex) tx_inputs, tx_outputs = tx['ins'], tx['outs'] locktime, version = tx['locktime'], tx['version'] tx_inputs += new_inputs tx_outputs += new_outputs new_tx...
Given an unsigned serialized transaction, add more inputs and outputs to it. @new_inputs and @new_outputs will be virtualchain-formatted: * new_inputs[i] will have {'outpoint': {'index':..., 'hash':...}, 'script':..., 'witness_script': ...} * new_outputs[i] will have {'script':..., 'value':... (in fundament...
def btc_tx_der_encode_length(l): if l < 0: raise ValueError("length cannot be negative") if l < 0x80: return int2byte(l) s = ("%x" % l).encode() if len(s) % 2: s = b("0") + s s = binascii.unhexlify(s) llen = len(s) return int2byte(0x80 | llen) + s
Return a DER-encoded length field Based on code from python-ecdsa (https://github.com/warner/python-ecdsa) by Brian Warner. Subject to the MIT license.
def btc_tx_der_encode_sequence(*encoded_pieces): # borrowed from python-ecdsa total_len = sum([len(p) for p in encoded_pieces]) return b('\x30') + btc_tx_der_encode_length(total_len) + b('').join(encoded_pieces)
Return a DER-encoded sequence Based on code from python-ecdsa (https://github.com/warner/python-ecdsa) by Brian Warner. Subject to the MIT license.
def btc_tx_make_input_signature(tx, idx, prevout_script, privkey_str, hashcode): if btc_tx_is_segwit(tx): raise ValueError('tried to use the standard sighash to sign a segwit transaction') pk = ecdsalib.ecdsa_private_key(str(privkey_str)) priv = pk.to_hex() # get the parts of the tx we ac...
Sign a single input of a transaction, given the serialized tx, the input index, the output's scriptPubkey, and the hashcode. tx must be a hex-encoded string privkey_str must be a hex-encoded private key Return the hex signature. THIS DOES NOT WORK WITH SEGWIT TRANSACTIONS
def btc_tx_make_input_signature_segwit(tx, idx, prevout_amount, prevout_script, privkey_str, hashcode): # always compressed if len(privkey_str) == 64: privkey_str += '01' pk = ecdsalib.ecdsa_private_key(str(privkey_str)) pubk = pk.public_key() priv = pk.to_hex() # must always...
Sign a single input of a transaction, given the serialized tx, the input index, the output's scriptPubkey, and the hashcode. tx must be a hex-encoded string privkey_str must be a hex-encoded private key Return the hex signature.
def btc_tx_sign_multisig(tx, idx, redeem_script, private_keys, hashcode=SIGHASH_ALL): from .multisig import parse_multisig_redeemscript # sign in the right order. map all possible public keys to their private key txobj = btc_tx_deserialize(str(tx)) privs = {} for pk in private_keys: ...
Sign a p2sh multisig input (not segwit!). @tx must be a hex-encoded tx Return the signed transaction
def btc_script_classify(scriptpubkey, private_key_info=None): if scriptpubkey.startswith("76a914") and scriptpubkey.endswith("88ac") and len(scriptpubkey) == 50: return 'p2pkh' elif scriptpubkey.startswith("a914") and scriptpubkey.endswith("87") and len(scriptpubkey) == 46: # maybe p2sh-p2...
Classify a scriptpubkey, optionally also using the private key info that will generate the corresponding scriptsig/witness Return None if not known (nonstandard)
def btc_privkey_scriptsig_classify(private_key_info): if btc_is_singlesig(private_key_info): return 'p2pkh' if btc_is_multisig(private_key_info): return 'p2sh' if btc_is_singlesig_segwit(private_key_info): return 'p2sh-p2wpkh' if btc_is_multisig_segwit(private_key_info): ...
What kind of scriptsig can this private key make?
def btc_tx_sign_input(tx, idx, prevout_script, prevout_amount, private_key_info, hashcode=SIGHASH_ALL, hashcodes=None, segwit=None, scriptsig_type=None, redeem_script=None, witness_script=None, **blockchain_opts): if segwit is None: segwit = get_features('segwit') if scriptsig_type is None: ...
Sign a particular input in the given transaction. @private_key_info can either be a private key, or it can be a dict with 'redeem_script' and 'private_keys' defined Returns the tx with the signed input
def block_header_serialize( inp ): # concatenate to form header o = encoding.encode(inp['version'], 256, 4)[::-1] + \ inp['prevhash'].decode('hex')[::-1] + \ inp['merkle_root'].decode('hex')[::-1] + \ encoding.encode(inp['timestamp'], 256, 4)[::-1] + \ encoding.encode(i...
Given block header information, serialize it and return the hex hash. inp has: * version (int) * prevhash (str) * merkle_root (str) * timestamp (int) * bits (int) * nonce (int) Based on code from pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin
def block_header_to_hex( block_data, prev_hash ): header_info = { "version": block_data['version'], "prevhash": prev_hash, "merkle_root": block_data['merkleroot'], "timestamp": block_data['time'], "bits": int(block_data['bits'], 16), "nonce": block_data['nonce'], ...
Calculate the hex form of a block's header, given its getblock information from bitcoind.