Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def total_exchange_balances(services=None, verbose=None, timeout=None, by_service=False): balances = defaultdict(lambda: 0) if not services: services = [ x(verbose=verbose, timeout=timeout) for x in ExchangeUniverse.get_authentica...
[ "\n Returns all balances for all currencies for all exchanges\n " ]
Please provide a description of the function:def _trim(self, book, balances, side): new_book = [] for service, balance in balances.items(): accumulation = 0 for order in book: if order[2].name == service.name: if side == 'crypto': ...
[ "\n >>> m = MultiOrderbook()\n >>> book = [\n [7800, 1.1, GDAX()],\n [7805, 3.2, Poloniex()],\n [7810, 0.3, GDAX()],\n [7900, 7.0, GDAX()]\n ]\n >>> m._trim(book, {GDAX(): 1.2, Poloniex(): 1.0}, 'crypto')\n [[7800, 1.1, <Service: GDAX (0...
Please provide a description of the function:def compress(x, y): polarity = "02" if y % 2 == 0 else "03" wrap = lambda x: x if not is_py2: wrap = lambda x: bytes(x, 'ascii') return unhexlify(wrap("%s%0.64x" % (polarity, x)))
[ "\n Given a x,y coordinate, encode in \"compressed format\"\n Returned is always 33 bytes.\n " ]
Please provide a description of the function:def uncompress(payload): payload = hexlify(payload) even = payload[:2] == b"02" x = int(payload[2:], 16) beta = pow(int(x ** 3 + A * x + B), int((P + 1) // 4), int(P)) y = (P-beta) if even else beta return x, y
[ "\n Given a compressed ec key in bytes, uncompress it using math and return (x, y)\n " ]
Please provide a description of the function:def decrypt(self, passphrase, wif=False): passphrase = normalize('NFC', unicode(passphrase)) if is_py2: passphrase = passphrase.encode('utf8') if self.ec_multiply: raise Exception("Not supported yet") key = s...
[ "\n BIP0038 non-ec-multiply decryption. Returns hex privkey.\n " ]
Please provide a description of the function:def encrypt(cls, crypto, privkey, passphrase): pub_byte, priv_byte = get_magic_bytes(crypto) privformat = get_privkey_format(privkey) if privformat in ['wif_compressed','hex_compressed']: compressed = True flagbyte = b...
[ "\n BIP0038 non-ec-multiply encryption. Returns BIP0038 encrypted privkey.\n " ]
Please provide a description of the function:def create_from_intermediate(cls, crypto, intermediate_point, seed, compressed=True, include_cfrm=True): flagbyte = b'\x20' if compressed else b'\x00' payload = b58decode_check(str(intermediate_point)) ownerentropy = payload[8:16] pa...
[ "\n Given an intermediate point, given to us by \"owner\", generate an address\n and encrypted private key that can be decoded by the passphrase used to generate\n the intermediate point.\n " ]
Please provide a description of the function:def generate_address(self, passphrase): inter = Bip38IntermediatePoint.create(passphrase, ownersalt=self.ownersalt) public_key = privtopub(inter.passpoint) # from Bip38EncryptedPrivateKey.create_from_intermediate derived = scrypt.h...
[ "\n Make sure the confirm code is valid for the given password and address.\n " ]
Please provide a description of the function:def push_tx(self, crypto, tx_hex): url = "%s/pushtx" % self.base_url return self.post_url(url, {'hex': tx_hex}).content
[ "\n This method is untested.\n " ]
Please provide a description of the function:def fetch_wallet_balances(wallets, fiat, **modes): price_fetch = set([x[0] for x in wallets]) balances = {} prices = {} fetch_length = len(wallets) + len(price_fetch) helpers = {fiat.lower(): {}} if not modes.get('async', False): # sync...
[ "\n Wallets must be list of two item lists. First item is crypto, second item\n is the address. example:\n\n [\n ['btc', '1PZ3Ps9RvCmUW1s1rHE25FeR8vtKUrhEai'],\n ['ltc', 'Lb78JDGxMcih1gs3AirMeRW6jaG5V9hwFZ']\n ]\n " ]
Please provide a description of the function:def replay_block(self, block_to_replay, limit=5): if block_to_replay == 'latest': if self.verbose: print("Getting latest %s block header" % source.upper()) block = get_block(self.source, latest=True, verbose=self.verb...
[ "\n Replay all transactions in parent currency to passed in \"source\" currency.\n Block_to_replay can either be an integer or a block object.\n " ]
Please provide a description of the function:def get_block_adjustments(crypto, points=None, intervals=None, **modes): from moneywagon import get_block all_points = [] if intervals: latest_block_height = get_block(crypto, latest=True, **modes)['block_number'] interval = int(latest_block...
[ "\n This utility is used to determine the actual block rate. The output can be\n directly copied to the `blocktime_adjustments` setting.\n " ]
Please provide a description of the function:def get_block_currencies(): return ['btc', 'ltc', 'ppc', 'dash', 'doge', 'ric'] currencies = [] for currency, data in crypto_data.items(): if type(data) is list: continue block_services = data.get('services', {}).get('get_block', ...
[ "\n Returns a list of all curencies (by code) that have a service defined that\n implements `get_block`.\n " ]
Please provide a description of the function:def _per_era_supply(self, block_height): coins = 0 for era in self.supply_data['eras']: end_block = era['end'] start_block = era['start'] reward = era['reward'] if not end_block or block_height <= end_...
[ "\n Calculate the coin supply based on 'eras' defined in crypto_data. Some\n currencies don't have a simple algorithmically defined halfing schedule\n so coins supply has to be defined explicitly per era.\n " ]
Please provide a description of the function:def _standard_supply(self, block_height): start_coins_per_block = self.supply_data['start_coins_per_block'] minutes_per_block = self.supply_data['minutes_per_block'] blocks_per_era = self.supply_data['blocks_per_era'] full_cap = self....
[ "\n Calculate the supply of coins for a given time (in either datetime, or\n block height) for coins that use the \"standard\" method of halfing.\n " ]
Please provide a description of the function:def enforce_service_mode(services, FetcherClass, kwargs, modes): fast_level = modes.get('fast', 0) average_level = modes.get('average', 0) paranoid_level = modes.get('paranoid', 0) private_level = modes.get('private', 0) verbose = modes.get('verbose'...
[ "\n Fetches the value according to the mode of execution desired.\n `FetcherClass` must be a class that is subclassed from AutoFallbackFetcher.\n `services` must be a list of Service classes.\n `kwargs` is a list of arguments used to make the service call, usually\n something like {crypto: 'btc', a...
Please provide a description of the function:def _prepare_consensus(FetcherClass, results): # _get_results returns lists of 2 item list, first element is service, second is the returned value. # when determining consensus amoung services, only take into account values returned. if hasattr(FetcherClass,...
[ "\n Given a list of results, return a list that is simplified to make consensus\n determination possible. Returns two item tuple, first arg is simplified list,\n the second argument is a list of all services used in making these results.\n " ]
Please provide a description of the function:def _get_results(FetcherClass, services, kwargs, num_results=None, fast=0, verbose=False, timeout=None): results = [] if not num_results or fast: num_results = len(services) with futures.ThreadPoolExecutor(max_workers=len(services)) as executor: ...
[ "\n Does the fetching in multiple threads of needed. Used by paranoid and fast mode.\n " ]
Please provide a description of the function:def _do_private_mode(FetcherClass, services, kwargs, random_wait_seconds, timeout, verbose): addresses = kwargs.pop('addresses') results = {} with futures.ThreadPoolExecutor(max_workers=len(addresses)) as executor: fetches = {} for address i...
[ "\n Private mode is only applicable to address_balance, unspent_outputs, and\n historical_transactions. There will always be a list for the `addresses`\n argument. Each address goes to a random service. Also a random delay is\n performed before the external fetch for improved privacy.\n " ]
Please provide a description of the function:def currency_to_protocol(amount): if type(amount) in [float, int]: amount = "%.8f" % amount return int(amount.replace(".", ''))
[ "\n Convert a string of 'currency units' to 'protocol units'. For instance\n converts 19.1 bitcoin to 1910000000 satoshis.\n\n Input is a float, output is an integer that is 1e8 times larger.\n\n It is hard to do this conversion because multiplying\n floats causes rounding nubers which will mess up t...
Please provide a description of the function:def decompile_scriptPubKey(asm): asm = asm.split(" ") hex = "" if asm[0] == 'OP_DUP': hex += "76" if asm[1] == 'OP_HASH160': hex += 'a9' if len(asm[2]) == 40: hex += asm[2] if asm[3] == 'OP_EQUALVERIFY': hex += '88...
[ "\n >>> decompile_scriptPubKey('OP_DUP OP_HASH160 cef3550ff9e637ddd120717d43fc21f8a563caf8 OP_EQUALVERIFY OP_CHECKSIG')\n '76a914cef3550ff9e637ddd120717d43fc21f8a563caf888ac'\n " ]
Please provide a description of the function:def to_rawtx(tx): if tx.get('hex'): return tx['hex'] new_tx = {} locktime = tx.get('locktime', 0) new_tx['locktime'] = locktime new_tx['version'] = tx.get('version', 1) new_tx['ins'] = [ { 'outpoint': {'hash': str(x[...
[ "\n Take a tx object in the moneywagon format and convert it to the format\n that pybitcointools's `serialize` funcion takes, then return in raw hex\n format.\n " ]
Please provide a description of the function:def check_error(self, response): if response.status_code == 500: raise ServiceError("500 - " + response.content) if response.status_code == 503: if "DDoS protection by Cloudflare" in response.content: raise Se...
[ "\n If the service is returning an error, this function should raise an exception.\n such as SkipThisService\n " ]
Please provide a description of the function:def convert_currency(self, base_fiat, base_amount, target_fiat): url = "http://api.fixer.io/latest?base=%s" % base_fiat data = self.get_url(url).json() try: return data['rates'][target_fiat.upper()] * base_amount except Ke...
[ "\n Convert one fiat amount to another fiat. Uses the fixer.io service.\n " ]
Please provide a description of the function:def fix_symbol(self, symbol, reverse=False): if not self.symbol_mapping: return symbol for old, new in self.symbol_mapping: if reverse: if symbol == new: return old else: ...
[ "\n In comes a moneywagon format symbol, and returned in the symbol converted\n to one the service can understand.\n " ]
Please provide a description of the function:def parse_market(self, market, split_char='_'): crypto, fiat = market.lower().split(split_char) return ( self.fix_symbol(crypto, reverse=True), self.fix_symbol(fiat, reverse=True) )
[ "\n In comes the market identifier directly from the service. Returned is\n the crypto and fiat identifier in moneywagon format.\n " ]
Please provide a description of the function:def make_market(self, crypto, fiat, seperator="_"): return ("%s%s%s" % ( self.fix_symbol(crypto), seperator, self.fix_symbol(fiat)) ).lower()
[ "\n Convert a crypto and fiat to a \"market\" string. All exchanges use their\n own format for specifying markets. Subclasses can define their own\n implementation.\n " ]
Please provide a description of the function:def _external_request(self, method, url, *args, **kwargs): self.last_url = url if url in self.responses.keys() and method == 'get': return self.responses[url] # return from cache if its there headers = kwargs.pop('headers', None)...
[ "\n Wrapper for requests.get with useragent automatically set.\n And also all requests are reponses are cached.\n " ]
Please provide a description of the function:def get_block(self, crypto, block_hash='', block_number='', latest=False): raise NotImplementedError( self.name + " does not support getting getting block data. " "Or rather it has no defined 'get_block' method." )
[ "\n Get block based on either block height, block number or get the latest\n block. Only one of the previous arguments must be passed on.\n\n Returned is a dictionary object with the following keys:\n\n * required fields:\n\n block_number - int\n size - size of block\n ...
Please provide a description of the function:def make_order(self, crypto, fiat, amount, price, type="limit"): raise NotImplementedError( self.name + " does not support making orders. " "Or rather it has no defined 'make_order' method." )
[ "\n This method buys or sells `crypto` on an exchange using `fiat` balance.\n Type can either be \"fill-or-kill\", \"post-only\", \"market\", or \"limit\".\n To get what modes are supported, consult make_order.supported_types\n if one is defined.\n " ]
Please provide a description of the function:def _try_services(self, method_name, *args, **kwargs): crypto = ((args and args[0]) or kwargs['crypto']).lower() address = kwargs.get('address', '').lower() fiat = kwargs.get('fiat', '').lower() if not self.services: rais...
[ "\n Try each service until one returns a response. This function only\n catches the bare minimum of exceptions from the service class. We want\n exceptions to be raised so the service classes can be debugged and\n fixed quickly.\n " ]
Please provide a description of the function:def eight_decimal_places(amount, format="str"): if type(amount) == str: return amount if format == 'str': return "%.8f" % amount if format == 'float': return float("%.8f" % amount)
[ "\n >>> eight_decimal_places(3.12345678912345)\n \"3.12345679\"\n >>> eight_decimal_places(\"3.12345678912345\")\n \"3.12345679\"\n >>> eight_decimal_places(3.12345678912345, format='float')\n 3.12345679\n >>> eight_decimal_places(\"3.12345678912345\", format='float')\n 3.12345679\n " ]
Please provide a description of the function:def get_historical_price(self, crypto, fiat, at_time): # represents the 'width' of the quandl data returned (one day) # if quandl ever supports data hourly or something, this can be changed interval = datetime.timedelta(hours=48) cryp...
[ "\n Using the quandl.com API, get the historical price (by day).\n The CRYPTOCHART source claims to be from multiple exchange sources\n for price (they say best exchange is most volume).\n " ]
Please provide a description of the function:def _get_all_services(crypto=None, just_exchange=False): from moneywagon.crypto_data import crypto_data if not crypto: # no currency specified, get all services to_iterate = crypto_data.items() else: # limit to one currency t...
[ "\n Go through the crypto_data structure and return all list of all (unique)\n installed services. Optionally filter by crypto-currency.\n " ]
Please provide a description of the function:def extract_crypto_data(github_path): data = {'github_link': 'https://github.com/%s' % github_path} content = get_content_from_github(github_path, "chainparams.cpp") if content: data.update(_get_from_chainparams(content)) else: content =...
[ "\n github_path can must be path on github, such as\n \"bitcoin/bitcoin\" or \"litecoin-project/litecoin\"\n " ]
Please provide a description of the function:def uconcatenate(arrs, axis=0): v = np.concatenate(arrs, axis=axis) v = _validate_numpy_wrapper_units(v, arrs) return v
[ "Concatenate a sequence of arrays.\n\n This wrapper around numpy.concatenate preserves units. All input arrays\n must have the same units. See the documentation of numpy.concatenate for\n full details.\n\n Examples\n --------\n >>> from unyt import cm\n >>> A = [1, 2, 3]*cm\n >>> B = [2, 3,...
Please provide a description of the function:def ucross(arr1, arr2, registry=None, axisa=-1, axisb=-1, axisc=-1, axis=None): v = np.cross(arr1, arr2, axisa=axisa, axisb=axisb, axisc=axisc, axis=axis) units = arr1.units * arr2.units arr = unyt_array(v, units, registry=registry) return arr
[ "Applies the cross product to two YT arrays.\n\n This wrapper around numpy.cross preserves units.\n See the documentation of numpy.cross for full\n details.\n " ]
Please provide a description of the function:def uintersect1d(arr1, arr2, assume_unique=False): v = np.intersect1d(arr1, arr2, assume_unique=assume_unique) v = _validate_numpy_wrapper_units(v, [arr1, arr2]) return v
[ "Find the sorted unique elements of the two input arrays.\n\n A wrapper around numpy.intersect1d that preserves units. All input arrays\n must have the same units. See the documentation of numpy.intersect1d for\n full details.\n\n Examples\n --------\n >>> from unyt import cm\n >>> A = [1, 2,...
Please provide a description of the function:def uunion1d(arr1, arr2): v = np.union1d(arr1, arr2) v = _validate_numpy_wrapper_units(v, [arr1, arr2]) return v
[ "Find the union of two arrays.\n\n A wrapper around numpy.intersect1d that preserves units. All input arrays\n must have the same units. See the documentation of numpy.intersect1d for\n full details.\n\n Examples\n --------\n >>> from unyt import cm\n >>> A = [1, 2, 3]*cm\n >>> B = [2, 3, ...
Please provide a description of the function:def unorm(data, ord=None, axis=None, keepdims=False): norm = np.linalg.norm(data, ord=ord, axis=axis, keepdims=keepdims) if norm.shape == (): return unyt_quantity(norm, data.units) return unyt_array(norm, data.units)
[ "Matrix or vector norm that preserves units\n\n This is a wrapper around np.linalg.norm that preserves units. See\n the documentation for that function for descriptions of the keyword\n arguments.\n\n Examples\n --------\n >>> from unyt import km\n >>> data = [1, 2, 3]*km\n >>> print(unorm(d...
Please provide a description of the function:def udot(op1, op2): dot = np.dot(op1.d, op2.d) units = op1.units * op2.units if dot.shape == (): return unyt_quantity(dot, units) return unyt_array(dot, units)
[ "Matrix or vector dot product that preserves units\n\n This is a wrapper around np.dot that preserves units.\n\n Examples\n --------\n >>> from unyt import km, s\n >>> a = np.eye(2)*km\n >>> b = (np.ones((2, 2)) * 2)*s\n >>> print(udot(a, b))\n [[2. 2.]\n [2. 2.]] km*s\n " ]
Please provide a description of the function:def uvstack(arrs): v = np.vstack(arrs) v = _validate_numpy_wrapper_units(v, arrs) return v
[ "Stack arrays in sequence vertically (row wise) while preserving units\n\n This is a wrapper around np.vstack that preserves units.\n\n Examples\n --------\n >>> from unyt import km\n >>> a = [1, 2, 3]*km\n >>> b = [2, 3, 4]*km\n >>> print(uvstack([a, b]))\n [[1 2 3]\n [2 3 4]] km\n "...
Please provide a description of the function:def uhstack(arrs): v = np.hstack(arrs) v = _validate_numpy_wrapper_units(v, arrs) return v
[ "Stack arrays in sequence horizontally while preserving units\n\n This is a wrapper around np.hstack that preserves units.\n\n Examples\n --------\n >>> from unyt import km\n >>> a = [1, 2, 3]*km\n >>> b = [2, 3, 4]*km\n >>> print(uhstack([a, b]))\n [1 2 3 2 3 4] km\n >>> a = [[1],[2],[3]...
Please provide a description of the function:def ustack(arrs, axis=0): v = np.stack(arrs, axis=axis) v = _validate_numpy_wrapper_units(v, arrs) return v
[ "Join a sequence of arrays along a new axis while preserving units\n\n The axis parameter specifies the index of the new axis in the\n dimensions of the result. For example, if ``axis=0`` it will be the\n first dimension and if ``axis=-1`` it will be the last dimension.\n\n This is a wrapper around np.s...
Please provide a description of the function:def loadtxt(fname, dtype="float", delimiter="\t", usecols=None, comments="#"): r f = open(fname, "r") next_one = False units = [] num_cols = -1 for line in f.readlines(): words = line.strip().split() if len(words) == 0: con...
[ "\n Load unyt_arrays with unit information from a text file. Each row in the\n text file must have the same number of values.\n\n Parameters\n ----------\n fname : str\n Filename to read.\n dtype : data-type, optional\n Data-type of the resulting array; default: float.\n delimiter...
Please provide a description of the function:def savetxt( fname, arrays, fmt="%.18e", delimiter="\t", header="", footer="", comments="#" ): r if not isinstance(arrays, list): arrays = [arrays] units = [] for array in arrays: if hasattr(array, "units"): units.append(str(ar...
[ "\n Write unyt_arrays with unit information to a text file.\n\n Parameters\n ----------\n fname : str\n The file to write the unyt_arrays to.\n arrays : list of unyt_arrays or single unyt_array\n The array(s) to write to the file.\n fmt : str or sequence of strs, optional\n A ...
Please provide a description of the function:def convert_to_units(self, units, equivalence=None, **kwargs): units = _sanitize_units_convert(units, self.units.registry) if equivalence is None: conv_data = _check_em_conversion( self.units, units, registry=self.units.re...
[ "\n Convert the array to the given units in-place.\n\n Optionally, an equivalence can be specified to convert to an\n equivalent quantity which is not in the same dimensions.\n\n Parameters\n ----------\n units : Unit object or string\n The units you want to conv...
Please provide a description of the function:def convert_to_base(self, unit_system=None, equivalence=None, **kwargs): self.convert_to_units( self.units.get_base_equivalent(unit_system), equivalence=equivalence, **kwargs )
[ "\n Convert the array in-place to the equivalent base units in\n the specified unit system.\n\n Optionally, an equivalence can be specified to convert to an\n equivalent quantity which is not in the same dimensions.\n\n Parameters\n ----------\n unit_system : string,...
Please provide a description of the function:def convert_to_cgs(self, equivalence=None, **kwargs): self.convert_to_units( self.units.get_cgs_equivalent(), equivalence=equivalence, **kwargs )
[ "\n Convert the array and in-place to the equivalent cgs units.\n\n Optionally, an equivalence can be specified to convert to an\n equivalent quantity which is not in the same dimensions.\n\n Parameters\n ----------\n equivalence : string, optional\n The equivale...
Please provide a description of the function:def convert_to_mks(self, equivalence=None, **kwargs): self.convert_to_units(self.units.get_mks_equivalent(), equivalence, **kwargs)
[ "\n Convert the array and units to the equivalent mks units.\n\n Optionally, an equivalence can be specified to convert to an\n equivalent quantity which is not in the same dimensions.\n\n Parameters\n ----------\n equivalence : string, optional\n The equivalence...
Please provide a description of the function:def in_units(self, units, equivalence=None, **kwargs): units = _sanitize_units_convert(units, self.units.registry) if equivalence is None: conv_data = _check_em_conversion( self.units, units, registry=self.units.registry ...
[ "\n Creates a copy of this array with the data converted to the\n supplied units, and returns it.\n\n Optionally, an equivalence can be specified to convert to an\n equivalent quantity which is not in the same dimensions.\n\n Parameters\n ----------\n units : Unit ob...
Please provide a description of the function:def to(self, units, equivalence=None, **kwargs): return self.in_units(units, equivalence=equivalence, **kwargs)
[ "\n Creates a copy of this array with the data converted to the\n supplied units, and returns it.\n\n Optionally, an equivalence can be specified to convert to an\n equivalent quantity which is not in the same dimensions.\n\n .. note::\n\n All additional keyword argumen...
Please provide a description of the function:def to_value(self, units=None, equivalence=None, **kwargs): if units is None: v = self.value else: v = self.in_units(units, equivalence=equivalence, **kwargs).value if isinstance(self, unyt_quantity): retur...
[ "\n Creates a copy of this array with the data in the supplied\n units, and returns it without units. Output is therefore a\n bare NumPy array.\n\n Optionally, an equivalence can be specified to convert to an\n equivalent quantity which is not in the same dimensions.\n\n .....
Please provide a description of the function:def in_base(self, unit_system=None): us = _sanitize_unit_system(unit_system, self) try: conv_data = _check_em_conversion( self.units, unit_system=us, registry=self.units.registry ) except MKSCGSConversi...
[ "\n Creates a copy of this array with the data in the specified unit\n system, and returns it in that system's base units.\n\n Parameters\n ----------\n unit_system : string, optional\n The unit system to be used in the conversion. If not specified,\n the con...
Please provide a description of the function:def convert_to_equivalent(self, unit, equivalence, **kwargs): conv_unit = Unit(unit, registry=self.units.registry) if self.units.same_dimensions_as(conv_unit): self.convert_to_units(conv_unit) return this_equiv = equiv...
[ "\n Return a copy of the unyt_array in the units specified units, assuming\n the given equivalency. The dimensions of the specified units and the\n dimensions of the original array need not match so long as there is an\n appropriate conversion in the specified equivalency.\n\n Par...
Please provide a description of the function:def to_equivalent(self, unit, equivalence, **kwargs): conv_unit = Unit(unit, registry=self.units.registry) if self.units.same_dimensions_as(conv_unit): return self.in_units(conv_unit) this_equiv = equivalence_registry[equivalence]...
[ "\n Return a copy of the unyt_array in the units specified units, assuming\n the given equivalency. The dimensions of the specified units and the\n dimensions of the original array need not match so long as there is an\n appropriate conversion in the specified equivalency.\n\n Par...
Please provide a description of the function:def argsort(self, axis=-1, kind="quicksort", order=None): return self.view(np.ndarray).argsort(axis, kind, order)
[ "\n Returns the indices that would sort the array.\n\n See the documentation of ndarray.argsort for details about the keyword\n arguments.\n\n Example\n -------\n >>> from unyt import km\n >>> data = [3, 8, 7]*km\n >>> print(np.argsort(data))\n [0 2 1]\...
Please provide a description of the function:def from_astropy(cls, arr, unit_registry=None): # Converting from AstroPy Quantity try: u = arr.unit _arr = arr except AttributeError: u = arr _arr = 1.0 * u ap_units = [] for ba...
[ "\n Convert an AstroPy \"Quantity\" to a unyt_array or unyt_quantity.\n\n Parameters\n ----------\n arr : AstroPy Quantity\n The Quantity to convert from.\n unit_registry : yt UnitRegistry, optional\n A yt unit registry to use in the conversion. If one is not...
Please provide a description of the function:def to_astropy(self, **kwargs): return self.value * _astropy.units.Unit(str(self.units), **kwargs)
[ "\n Creates a new AstroPy quantity with the same unit information.\n\n Example\n -------\n >>> from unyt import g, cm\n >>> data = [3, 4, 5]*g/cm**3\n >>> data.to_astropy()\n <Quantity [3., 4., 5.] g / cm3>\n " ]
Please provide a description of the function:def from_pint(cls, arr, unit_registry=None): p_units = [] for base, exponent in arr._units.items(): bs = convert_pint_units(base) p_units.append("%s**(%s)" % (bs, Rational(exponent))) p_units = "*".join(p_units) ...
[ "\n Convert a Pint \"Quantity\" to a unyt_array or unyt_quantity.\n\n Parameters\n ----------\n arr : Pint Quantity\n The Quantity to convert from.\n unit_registry : yt UnitRegistry, optional\n A yt unit registry to use in the conversion. If one is not\n ...
Please provide a description of the function:def to_pint(self, unit_registry=None): if unit_registry is None: unit_registry = _pint.UnitRegistry() powers_dict = self.units.expr.as_powers_dict() units = [] for unit, pow in powers_dict.items(): # we have to...
[ "\n Convert a unyt_array or unyt_quantity to a Pint Quantity.\n\n Parameters\n ----------\n arr : unyt_array or unyt_quantity\n The unitful quantity to convert from.\n unit_registry : Pint UnitRegistry, optional\n The Pint UnitRegistry to use in the conversio...
Please provide a description of the function:def write_hdf5(self, filename, dataset_name=None, info=None, group_name=None): r from unyt._on_demand_imports import _h5py as h5py import pickle if info is None: info = {} info["units"] = str(self.units) info["uni...
[ "Writes a unyt_array to hdf5 file.\n\n Parameters\n ----------\n filename: string\n The filename to create and write a dataset to\n\n dataset_name: string\n The name of the dataset to create in the file.\n\n info: dictionary\n A dictionary of suppl...
Please provide a description of the function:def from_hdf5(cls, filename, dataset_name=None, group_name=None): r from unyt._on_demand_imports import _h5py as h5py import pickle if dataset_name is None: dataset_name = "array_data" f = h5py.File(filename) if g...
[ "Attempts read in and convert a dataset in an hdf5 file into a\n unyt_array.\n\n Parameters\n ----------\n filename: string\n The filename to of the hdf5 file.\n\n dataset_name: string\n The name of the dataset to read from. If the dataset has a units\n ...
Please provide a description of the function:def copy(self, order="C"): return type(self)(np.copy(np.asarray(self)), self.units)
[ "\n Return a copy of the array.\n\n Parameters\n ----------\n order : {'C', 'F', 'A', 'K'}, optional\n Controls the memory layout of the copy. 'C' means C-order,\n 'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,\n 'C' otherwise. 'K' means m...
Please provide a description of the function:def dot(self, b, out=None): res_units = self.units * getattr(b, "units", NULL_UNIT) ret = self.view(np.ndarray).dot(np.asarray(b), out=out) * res_units if out is not None: out.units = res_units return ret
[ "dot product of two arrays.\n\n Refer to `numpy.dot` for full documentation.\n\n See Also\n --------\n numpy.dot : equivalent function\n\n Examples\n --------\n >>> from unyt import km, s\n >>> a = np.eye(2)*km\n >>> b = (np.ones((2, 2)) * 2)*s\n ...
Please provide a description of the function:def as_rest_table(data, full=False): data = data if data else [["No Data"]] table = [] # max size of each column sizes = list(map(max, zip(*[[len(str(elt)) for elt in member] for member in data]))) num_elts = len(sizes) if full: start_of...
[ "\n Originally from ActiveState recipes, copy/pasted from GitHub\n where it is listed with an MIT license.\n\n https://github.com/ActiveState/code/tree/master/recipes/Python/579054_Generate_Sphinx_table\n\n " ]
Please provide a description of the function:def import_units(module, namespace): for key, value in module.__dict__.items(): if isinstance(value, (unyt_quantity, Unit)): namespace[key] = value
[ "Import Unit objects from a module into a namespace" ]
Please provide a description of the function:def add_symbols(namespace, registry): import unyt.unit_symbols as us from unyt.unit_object import Unit for name, unit in vars(us).items(): if name.startswith("_"): continue namespace[name] = Unit(unit.expr, registry=registry) ...
[ "Adds the unit symbols from :mod:`unyt.unit_symbols` to a namespace\n\n Parameters\n ----------\n\n namespace : dict\n The dict to insert unit symbols into. The keys will be string\n unit names and values will be the corresponding unit objects.\n registry : :class:`unyt.unit_registry.UnitReg...
Please provide a description of the function:def add_constants(namespace, registry): from unyt.array import unyt_quantity for constant_name in physical_constants: value, unit_name, alternate_names = physical_constants[constant_name] for name in alternate_names + [constant_name]: ...
[ "Adds the quantities from :mod:`unyt.physical_constants` to a namespace\n\n Parameters\n ----------\n\n namespace : dict\n The dict to insert quantities into. The keys will be string names\n and values will be the corresponding quantities.\n registry : :class:`unyt.unit_registry.UnitRegistry...
Please provide a description of the function:def _lookup_unit_symbol(symbol_str, unit_symbol_lut): if symbol_str in unit_symbol_lut: # lookup successful, return the tuple directly return unit_symbol_lut[symbol_str] # could still be a known symbol with a prefix prefix, symbol_wo_prefix ...
[ "\n Searches for the unit data tuple corresponding to the given symbol.\n\n Parameters\n ----------\n symbol_str : str\n The unit symbol to look up.\n unit_symbol_lut : dict\n Dictionary with symbols as keys and unit data tuples as values.\n\n " ]
Please provide a description of the function:def unit_system_id(self): if self._unit_system_id is None: hash_data = bytearray() for k, v in sorted(self.lut.items()): hash_data.extend(k.encode("utf8")) hash_data.extend(repr(v).encode("utf8")) ...
[ "\n This is a unique identifier for the unit registry created\n from a FNV hash. It is needed to register a dataset's code\n unit system in the unit system registry.\n " ]
Please provide a description of the function:def add( self, symbol, base_value, dimensions, tex_repr=None, offset=None, prefixable=False, ): from unyt.unit_object import _validate_dimensions self._unit_system_id = None # Vali...
[ "\n Add a symbol to this registry.\n\n Parameters\n ----------\n\n symbol : str\n The name of the unit\n base_value : float\n The scaling from the units value to the equivalent SI unit\n with the same dimensions\n dimensions : expr\n ...
Please provide a description of the function:def remove(self, symbol): self._unit_system_id = None if symbol not in self.lut: raise SymbolNotFoundError( "Tried to remove the symbol '%s', but it does not exist " "in this registry." % symbol ...
[ "\n Remove the entry for the unit matching `symbol`.\n\n Parameters\n ----------\n\n symbol : str\n The name of the unit symbol to remove from the registry.\n\n " ]
Please provide a description of the function:def modify(self, symbol, base_value): self._unit_system_id = None if symbol not in self.lut: raise SymbolNotFoundError( "Tried to modify the symbol '%s', but it does not exist " "in this registry." % symbo...
[ "\n Change the base value of a unit symbol. Useful for adjusting code\n units after parsing parameters.\n\n Parameters\n ----------\n\n symbol : str\n The name of the symbol to modify\n base_value : float\n The new base_value for the symbol.\n\n ...
Please provide a description of the function:def to_json(self): sanitized_lut = {} for k, v in self.lut.items(): san_v = list(v) repr_dims = str(v[1]) san_v[1] = repr_dims sanitized_lut[k] = tuple(san_v) return json.dumps(sanitized_lut)
[ "\n Returns a json-serialized version of the unit registry\n " ]
Please provide a description of the function:def from_json(cls, json_text): data = json.loads(json_text) lut = {} for k, v in data.items(): unsan_v = list(v) unsan_v[1] = sympify(v[1], locals=vars(unyt_dims)) lut[k] = tuple(unsan_v) return cl...
[ "\n Returns a UnitRegistry object from a json-serialized unit registry\n\n Parameters\n ----------\n\n json_text : str\n A string containing a json represention of a UnitRegistry\n " ]
Please provide a description of the function:def list_same_dimensions(self, unit_object): equiv = [k for k, v in self.lut.items() if v[1] is unit_object.dimensions] equiv = list(sorted(set(equiv))) return equiv
[ "\n Return a list of base unit names that this registry knows about that\n are of equivalent dimensions to *unit_object*.\n " ]
Please provide a description of the function:def _em_conversion(orig_units, conv_data, to_units=None, unit_system=None): conv_unit, canonical_unit, scale = conv_data if conv_unit is None: conv_unit = canonical_unit new_expr = scale * canonical_unit.expr if unit_system is not None: #...
[ "Convert between E&M & MKS base units.\n\n If orig_units is a CGS (or MKS) E&M unit, conv_data contains the\n corresponding MKS (or CGS) unit and scale factor converting between them.\n This must be done by replacing the expression of the original unit\n with the new one in the unit expression and multi...
Please provide a description of the function:def _check_em_conversion(unit, to_unit=None, unit_system=None, registry=None): em_map = () if unit == to_unit or unit.dimensions not in em_conversion_dims: return em_map if unit.is_atomic: prefix, unit_wo_prefix = _split_prefix(str(unit), uni...
[ "Check to see if the units contain E&M units\n\n This function supports unyt's ability to convert data to and from E&M\n electromagnetic units. However, this support is limited and only very\n simple unit expressions can be readily converted. This function tries\n to see if the unit is an atomic base un...
Please provide a description of the function:def _get_conversion_factor(old_units, new_units, dtype): if old_units.dimensions != new_units.dimensions: raise UnitConversionError( old_units, old_units.dimensions, new_units, new_units.dimensions ) ratio = old_units.base_value / new...
[ "\n Get the conversion factor between two units of equivalent dimensions. This\n is the number you multiply data by to convert from values in `old_units` to\n values in `new_units`.\n\n Parameters\n ----------\n old_units: str or Unit object\n The current units.\n new_units : str or Unit...
Please provide a description of the function:def _get_unit_data_from_expr(unit_expr, unit_symbol_lut): # Now for the sympy possibilities if isinstance(unit_expr, Number): if unit_expr is sympy_one: return (1.0, sympy_one) return (float(unit_expr), sympy_one) if isinstance(u...
[ "\n Grabs the total base_value and dimensions from a valid unit expression.\n\n Parameters\n ----------\n unit_expr: Unit object, or sympy Expr object\n The expression containing unit symbols.\n unit_symbol_lut: dict\n Provides the unit data for each valid unit symbol.\n\n " ]
Please provide a description of the function:def define_unit( symbol, value, tex_repr=None, offset=None, prefixable=False, registry=None ): from unyt.array import unyt_quantity, _iterable import unyt if registry is None: registry = default_unit_registry if symbol in registry: r...
[ "\n Define a new unit and add it to the specified unit registry.\n\n Parameters\n ----------\n symbol : string\n The symbol for the new unit.\n value : tuple or :class:`unyt.array.unyt_quantity`\n The definition of the new unit in terms of some other units. For\n example, one wou...
Please provide a description of the function:def latex_repr(self): if self._latex_repr is not None: return self._latex_repr if self.expr.is_Atom: expr = self.expr else: expr = self.expr.copy() self._latex_repr = _get_latex_representation(expr,...
[ "A LaTeX representation for the unit\n\n Examples\n --------\n >>> from unyt import g, cm\n >>> (g/cm**3).units.latex_repr\n '\\\\\\\\frac{\\\\\\\\rm{g}}{\\\\\\\\rm{cm}^{3}}'\n " ]
Please provide a description of the function:def same_dimensions_as(self, other_unit): # test first for 'is' equality to avoid expensive sympy operation if self.dimensions is other_unit.dimensions: return True return (self.dimensions / other_unit.dimensions) == sympy_one
[ "Test if the dimensions of *other_unit* are the same as this unit\n\n Examples\n --------\n >>> from unyt import Msun, kg, mile\n >>> Msun.units.same_dimensions_as(kg.units)\n True\n >>> Msun.units.same_dimensions_as(mile.units)\n False\n " ]
Please provide a description of the function:def is_code_unit(self): for atom in self.expr.atoms(): if not (str(atom).startswith("code") or atom.is_Number): return False return True
[ "Is this a \"code\" unit?\n\n Returns\n -------\n True if the unit consists of atom units that being with \"code\".\n False otherwise\n\n " ]
Please provide a description of the function:def list_equivalencies(self): from unyt.equivalencies import equivalence_registry for k, v in equivalence_registry.items(): if self.has_equivalent(k): print(v())
[ "Lists the possible equivalencies associated with this unit object\n\n Examples\n --------\n >>> from unyt import km\n >>> km.units.list_equivalencies()\n spectral: length <-> spatial_frequency <-> frequency <-> energy\n schwarzschild: mass <-> length\n compton: mass...
Please provide a description of the function:def has_equivalent(self, equiv): try: this_equiv = equivalence_registry[equiv]() except KeyError: raise KeyError('No such equivalence "%s".' % equiv) old_dims = self.dimensions return old_dims in this_equiv._di...
[ "\n Check to see if this unit object as an equivalent unit in *equiv*.\n\n Example\n -------\n >>> from unyt import km\n >>> km.has_equivalent('spectral')\n True\n >>> km.has_equivalent('mass_energy')\n False\n " ]
Please provide a description of the function:def get_base_equivalent(self, unit_system=None): from unyt.unit_registry import _sanitize_unit_system unit_system = _sanitize_unit_system(unit_system, self) try: conv_data = _check_em_conversion( self.units, regis...
[ "Create and return dimensionally-equivalent units in a specified base.\n\n >>> from unyt import g, cm\n >>> (g/cm**3).get_base_equivalent('mks')\n kg/m**3\n >>> (g/cm**3).get_base_equivalent('solar')\n Mearth/AU**3\n " ]
Please provide a description of the function:def as_coeff_unit(self): coeff, mul = self.expr.as_coeff_Mul() coeff = float(coeff) ret = Unit( mul, self.base_value / coeff, self.base_offset, self.dimensions, self.registry, ...
[ "Factor the coefficient multiplying a unit\n\n For units that are multiplied by a constant dimensionless\n coefficient, returns a tuple containing the coefficient and\n a new unit object for the unmultiplied unit.\n\n Example\n -------\n\n >>> import unyt as u\n >>> ...
Please provide a description of the function:def simplify(self): expr = self.expr self.expr = _cancel_mul(expr, self.registry) return self
[ "Return a new equivalent unit object with a simplified unit expression\n\n >>> import unyt as u\n >>> unit = (u.m**2/u.cm).simplify()\n >>> unit\n 100*m\n " ]
Please provide a description of the function:def _auto_positive_symbol(tokens, local_dict, global_dict): result = [] tokens.append((None, None)) # so zip traverses all tokens for tok, nextTok in zip(tokens, tokens[1:]): tokNum, tokVal = tok nextTokNum, nextTokVal = nextTok if ...
[ "\n Inserts calls to ``Symbol`` for undefined variables.\n Passes in positive=True as a keyword argument.\n Adapted from sympy.sympy.parsing.sympy_parser.auto_symbol\n " ]
Please provide a description of the function:def intersection(self, range): if self.worksheet != range.worksheet: # Different worksheet return None start = (max(self._start[0], range._start[0]), max(self._start[1], range._start[1])) end = (min(se...
[ "\n\t\tCalculates the intersection with another range object\n\t\t" ]
Please provide a description of the function:def _ensure_tree(path): try: os.makedirs(path) except OSError as e: if e.errno == errno.EEXIST: if not os.path.isdir(path): raise else: return False elif e.errno == errno.EISDIR: ...
[ "Create a directory (and any ancestor directories required).\n\n :param path: Directory to create\n " ]
Please provide a description of the function:def interprocess_locked(path): lock = InterProcessLock(path) def decorator(f): @six.wraps(f) def wrapper(*args, **kwargs): with lock: return f(*args, **kwargs) return wrapper return decorator
[ "Acquires & releases a interprocess lock around call into\n decorated function." ]
Please provide a description of the function:def acquire(self, blocking=True, delay=DELAY_INCREMENT, max_delay=MAX_DELAY, timeout=None): if delay < 0: raise ValueError("Delay must be greater than or equal to zero") if timeout is not None and timeout <...
[ "Attempt to acquire the given lock.\n\n :param blocking: whether to wait forever to try to acquire the lock\n :type blocking: bool\n :param delay: when blocking this is the delay time in seconds that\n will be added after each failed acquisition\n :type delay: int/fl...
Please provide a description of the function:def release(self): if not self.acquired: raise threading.ThreadError("Unable to release an unacquired" " lock") try: self.unlock() except IOError: self.logger.excepti...
[ "Release the previously acquired lock." ]
Please provide a description of the function:def canonicalize_path(path): if isinstance(path, six.binary_type): return path if isinstance(path, six.text_type): return _fsencode(path) else: return canonicalize_path(str(path))
[ "Canonicalizes a potential path.\n\n Returns a binary string encoded into filesystem encoding.\n " ]
Please provide a description of the function:def read_locked(*args, **kwargs): def decorator(f): attr_name = kwargs.get('lock', '_lock') @six.wraps(f) def wrapper(self, *args, **kwargs): rw_lock = getattr(self, attr_name) with rw_lock.read_lock(): ...
[ "Acquires & releases a read lock around call into decorated method.\n\n NOTE(harlowja): if no attribute name is provided then by default the\n attribute named '_lock' is looked for (this attribute is expected to be\n a :py:class:`.ReaderWriterLock`) in the instance object this decorator\n is attached to...
Please provide a description of the function:def write_locked(*args, **kwargs): def decorator(f): attr_name = kwargs.get('lock', '_lock') @six.wraps(f) def wrapper(self, *args, **kwargs): rw_lock = getattr(self, attr_name) with rw_lock.write_lock(): ...
[ "Acquires & releases a write lock around call into decorated method.\n\n NOTE(harlowja): if no attribute name is provided then by default the\n attribute named '_lock' is looked for (this attribute is expected to be\n a :py:class:`.ReaderWriterLock` object) in the instance object this\n decorator is att...
Please provide a description of the function:def try_lock(lock): # NOTE(harlowja): the keyword argument for 'blocking' does not work # in py2.x and only is fixed in py3.x (this adjustment is documented # and/or debated in http://bugs.python.org/issue10789); so we'll just # stick to the format that ...
[ "Attempts to acquire a lock, and auto releases if acquired (on exit)." ]