idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
247,000
def poisson_errors ( self ) : graph = Graph ( self . nbins ( axis = 0 ) , type = 'asymm' ) graph . SetLineWidth ( self . GetLineWidth ( ) ) graph . SetMarkerSize ( self . GetMarkerSize ( ) ) chisqr = ROOT . TMath . ChisquareQuantile npoints = 0 for bin in self . bins ( overflow = False ) : entries = bin . effective_ent...
Return a TGraphAsymmErrors representation of this histogram where the point y errors are Poisson .
247,001
def attach_event_handler ( canvas , handler = close_on_esc_or_middlemouse ) : if getattr ( canvas , "_py_event_dispatcher_attached" , None ) : return event_dispatcher = C . TPyDispatcherProcessedEvent ( handler ) canvas . Connect ( "ProcessedEvent(int,int,int,TObject*)" , "TPyDispatcherProcessedEvent" , event_dispatche...
Attach a handler function to the ProcessedEvent slot defaulting to closing when middle mouse is clicked or escape is pressed
247,002
def _num_to_string ( self , number , pad_to_length = None ) : output = "" while number : number , digit = divmod ( number , self . _alpha_len ) output += self . _alphabet [ digit ] if pad_to_length : remainder = max ( pad_to_length - len ( output ) , 0 ) output = output + self . _alphabet [ 0 ] * remainder return outpu...
Convert a number to a string using the given alphabet .
247,003
def _string_to_int ( self , string ) : number = 0 for char in string [ : : - 1 ] : number = number * self . _alpha_len + self . _alphabet . index ( char ) return number
Convert a string to a number using the given alphabet ..
247,004
def uuid ( self , name = None , pad_length = 22 ) : if name is None : uuid = _uu . uuid4 ( ) elif "http" not in name . lower ( ) : uuid = _uu . uuid5 ( _uu . NAMESPACE_DNS , name ) else : uuid = _uu . uuid5 ( _uu . NAMESPACE_URL , name ) return self . encode ( uuid , pad_length )
Generate and return a UUID .
247,005
def fit ( self , data = 'obsData' , model_config = 'ModelConfig' , param_const = None , param_values = None , param_ranges = None , poi_const = False , poi_value = None , poi_range = None , extended = False , num_cpu = 1 , process_strategy = 0 , offset = False , print_level = None , return_nll = False , ** kwargs ) : i...
Fit a pdf to data in a workspace
247,006
def ensure_trafaret ( trafaret ) : if isinstance ( trafaret , Trafaret ) : return trafaret elif isinstance ( trafaret , type ) : if issubclass ( trafaret , Trafaret ) : return trafaret ( ) return Call ( lambda val : trafaret ( val ) ) elif callable ( trafaret ) : return Call ( trafaret ) else : raise RuntimeError ( "%r...
Helper for complex trafarets takes trafaret instance or class and returns trafaret instance
247,007
def DictKeys ( keys ) : req = [ ( Key ( key ) , Any ) for key in keys ] return Dict ( dict ( req ) )
Checks if dict has all given keys
247,008
def guard ( trafaret = None , ** kwargs ) : if ( trafaret and not isinstance ( trafaret , Dict ) and not isinstance ( trafaret , Forward ) ) : raise RuntimeError ( "trafaret should be instance of Dict or Forward" ) elif trafaret and kwargs : raise RuntimeError ( "choose one way of initialization," " trafaret or kwargs"...
Decorator for protecting function with trafarets
247,009
def _clone_args ( self ) : keys = list ( self . keys ) kw = { } if self . allow_any or self . extras : kw [ 'allow_extra' ] = list ( self . extras ) if self . allow_any : kw [ 'allow_extra' ] . append ( '*' ) kw [ 'allow_extra_trafaret' ] = self . extras_trafaret if self . ignore_any or self . ignore : kw [ 'ignore_ext...
return args to create new Dict clone
247,010
def merge ( self , other ) : ignore = self . ignore extra = self . extras if isinstance ( other , Dict ) : other_keys = other . keys ignore += other . ignore extra += other . extras elif isinstance ( other , ( list , tuple ) ) : other_keys = list ( other ) elif isinstance ( other , dict ) : return self . __class__ ( ot...
Extends one Dict with other Dict Key s or Key s list or dict instance supposed for Dict
247,011
def get_deep_attr ( obj , keys ) : cur = obj for k in keys : if isinstance ( cur , Mapping ) and k in cur : cur = cur [ k ] continue else : try : cur = getattr ( cur , k ) continue except AttributeError : pass raise DataError ( error = 'Unexistent key' ) return cur
Helper for DeepKey
247,012
def construct ( arg ) : if isinstance ( arg , t . Trafaret ) : return arg elif isinstance ( arg , tuple ) or ( isinstance ( arg , list ) and len ( arg ) > 1 ) : return t . Tuple ( * ( construct ( a ) for a in arg ) ) elif isinstance ( arg , list ) : return t . List ( construct ( arg [ 0 ] ) ) elif isinstance ( arg , di...
Shortcut syntax to define trafarets .
247,013
def subdict ( name , * keys , ** kw ) : trafaret = kw . pop ( 'trafaret' ) def inner ( data , context = None ) : errors = False preserve_output = [ ] touched = set ( ) collect = { } for key in keys : for k , v , names in key ( data , context = context ) : touched . update ( names ) preserve_output . append ( ( k , v , ...
Subdict key .
247,014
def xor_key ( first , second , trafaret ) : trafaret = t . Trafaret . _trafaret ( trafaret ) def check_ ( value ) : if ( first in value ) ^ ( second in value ) : key = first if first in value else second yield first , t . catch_error ( trafaret , value [ key ] ) , ( key , ) elif first in value and second in value : yie...
xor_key - takes first and second key names and trafaret .
247,015
def confirm_key ( name , confirm_name , trafaret ) : def check_ ( value ) : first , second = None , None if name in value : first = value [ name ] else : yield name , t . DataError ( 'is required' ) , ( name , ) if confirm_name in value : second = value [ confirm_name ] else : yield confirm_name , t . DataError ( 'is r...
confirm_key - takes name confirm_name and trafaret .
247,016
def get_capacity ( self , legacy = None ) : params = None if legacy : params = { 'legacy' : legacy } return self . call_api ( '/capacity' , params = params ) [ 'capacity' ]
Get capacity of all facilities .
247,017
def altcore_data ( self ) : ret = [ ] for symbol in self . supported_currencies ( project = 'altcore' , level = "address" ) : data = crypto_data [ symbol ] priv = data . get ( 'private_key_prefix' ) pub = data . get ( 'address_version_byte' ) hha = data . get ( 'header_hash_algo' ) shb = data . get ( 'script_hash_byte'...
Returns the crypto_data for all currencies defined in moneywagon that also meet the minimum support for altcore . Data is keyed according to the bitcore specification .
247,018
def from_unit_to_satoshi ( self , value , unit = 'satoshi' ) : if not unit or unit == 'satoshi' : return value if unit == 'bitcoin' or unit == 'btc' : return value * 1e8 convert = get_current_price ( self . crypto , unit ) return int ( value / convert * 1e8 )
Convert a value to satoshis . units can be any fiat currency . By default the unit is satoshi .
247,019
def _get_utxos ( self , address , services , ** modes ) : return get_unspent_outputs ( self . crypto , address , services = services , ** modes )
Using the service fallback engine get utxos from remote service .
247,020
def total_input_satoshis ( self ) : just_inputs = [ x [ 'input' ] for x in self . ins ] return sum ( [ x [ 'amount' ] for x in just_inputs ] )
Add up all the satoshis coming from all input tx s .
247,021
def select_inputs ( self , amount ) : sorted_txin = sorted ( self . ins , key = lambda x : - x [ 'input' ] [ 'confirmations' ] ) total_amount = 0 for ( idx , tx_in ) in enumerate ( sorted_txin ) : total_amount += tx_in [ 'input' ] [ 'amount' ] if ( total_amount >= amount ) : break sorted_txin = sorted ( sorted_txin [ :...
Maximize transaction priority . Select the oldest inputs that are sufficient to cover the spent amount . Then remove any unneeded inputs starting with the smallest in value . Returns sum of amounts of inputs selected
247,022
def onchain_exchange ( self , withdraw_crypto , withdraw_address , value , unit = 'satoshi' ) : self . onchain_rate = get_onchain_exchange_rates ( self . crypto , withdraw_crypto , best = True , verbose = self . verbose ) exchange_rate = float ( self . onchain_rate [ 'rate' ] ) result = self . onchain_rate [ 'service' ...
This method is like add_output but it sends to another
247,023
def fee ( self , value = None , unit = 'satoshi' ) : convert = None if not value : convert = get_current_price ( self . crypto , "usd" ) self . fee_satoshi = int ( 0.02 / convert * 1e8 ) verbose = "Using default fee of:" elif value == 'optimal' : self . fee_satoshi = get_optimal_fee ( self . crypto , self . estimate_si...
Set the miner fee if unit is not set assumes value is satoshi . If using optimal make sure you have already added all outputs .
247,024
def get_hex ( self , signed = True ) : total_ins_satoshi = self . total_input_satoshis ( ) if total_ins_satoshi == 0 : raise ValueError ( "Can't make transaction, there are zero inputs" ) total_outs_satoshi = sum ( [ x [ 'value' ] for x in self . outs ] ) if not self . fee_satoshi : self . fee ( ) change_satoshi = tota...
Given all the data the user has given so far make the hex using pybitcointools
247,025
def get_current_price ( crypto , fiat , services = None , convert_to = None , helper_prices = None , ** modes ) : fiat = fiat . lower ( ) args = { 'crypto' : crypto , 'fiat' : fiat , 'convert_to' : convert_to } if not services : services = get_optimal_services ( crypto , 'current_price' ) if fiat in services : try_serv...
High level function for getting current exchange rate for a cryptocurrency . If the fiat value is not explicitly defined it will try the wildcard service . if that does not work it tries converting to an intermediate cryptocurrency if available .
247,026
def get_onchain_exchange_rates ( deposit_crypto = None , withdraw_crypto = None , ** modes ) : from moneywagon . onchain_exchange import ALL_SERVICES rates = [ ] for Service in ALL_SERVICES : srv = Service ( verbose = modes . get ( 'verbose' , False ) ) rates . extend ( srv . onchain_exchange_rates ( ) ) if deposit_cry...
Gets exchange rates for all defined on - chain exchange services .
247,027
def generate_keypair ( crypto , seed , password = None ) : if crypto in [ 'eth' , 'etc' ] : raise CurrencyNotSupported ( "Ethereums not yet supported" ) pub_byte , priv_byte = get_magic_bytes ( crypto ) priv = sha256 ( seed ) pub = privtopub ( priv ) priv_wif = encode_privkey ( priv , 'wif_compressed' , vbyte = priv_by...
Generate a private key and publickey for any currency given a seed . That seed can be random or a brainwallet phrase .
247,028
def sweep ( crypto , private_key , to_address , fee = None , password = None , ** modes ) : from moneywagon . tx import Transaction tx = Transaction ( crypto , verbose = modes . get ( 'verbose' , False ) ) tx . add_inputs ( private_key = private_key , password = password , ** modes ) tx . change_address = to_address tx...
Move all funds by private key to another address .
247,029
def guess_currency_from_address ( address ) : if is_py2 : fixer = lambda x : int ( x . encode ( 'hex' ) , 16 ) else : fixer = lambda x : x first_byte = fixer ( b58decode_check ( address ) [ 0 ] ) double_first_byte = fixer ( b58decode_check ( address ) [ : 2 ] ) hits = [ ] for currency , data in crypto_data . items ( ) ...
Given a crypto address find which currency it likely belongs to . Raises an exception if it can t find a match . Raises exception if address is invalid .
247,030
def service_table ( format = 'simple' , authenticated = False ) : if authenticated : all_services = ExchangeUniverse . get_authenticated_services ( ) else : all_services = ALL_SERVICES if format == 'html' : linkify = lambda x : "<a href='{0}' target='_blank'>{0}</a>" . format ( x ) else : linkify = lambda x : x ret = [...
Returns a string depicting all services currently installed .
247,031
def find_pair ( self , crypto = "" , fiat = "" , verbose = False ) : self . fetch_pairs ( ) if not crypto and not fiat : raise Exception ( "Fiat or Crypto required" ) def is_matched ( crypto , fiat , pair ) : if crypto and not fiat : return pair . startswith ( "%s-" % crypto ) if crypto and fiat : return pair == "%s-%s...
This utility is used to find an exchange that supports a given exchange pair .
247,032
def all_balances ( currency , services = None , verbose = False , timeout = None ) : balances = { } if not services : services = [ x ( verbose = verbose , timeout = timeout ) for x in ExchangeUniverse . get_authenticated_services ( ) ] for e in services : try : balances [ e ] = e . get_exchange_balance ( currency ) exc...
Get balances for passed in currency for all exchanges .
247,033
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_authenticated_services ( ) ] for e in services : try : more_balances =...
Returns all balances for all currencies for all exchanges
247,034
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 ) ) )
Given a x y coordinate encode in compressed format Returned is always 33 bytes .
247,035
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 = scrypt . hash ( passphrase , self . addresshash , 16384 , 8 , 8 ) derivedhalf1 = key [...
BIP0038 non - ec - multiply decryption . Returns hex privkey .
247,036
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'\xe0' if privformat == 'wif_compressed' : privkey = encode_privkey ( privkey , 'he...
BIP0038 non - ec - multiply encryption . Returns BIP0038 encrypted privkey .
247,037
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 ] passpoint = payload [ 16 : - 4 ] x , y = uncompress ( passpoint )...
Given an intermediate point given to us by owner generate an address and encrypted private key that can be decoded by the passphrase used to generate the intermediate point .
247,038
def generate_address ( self , passphrase ) : inter = Bip38IntermediatePoint . create ( passphrase , ownersalt = self . ownersalt ) public_key = privtopub ( inter . passpoint ) derived = scrypt . hash ( inter . passpoint , self . addresshash + inter . ownerentropy , 1024 , 1 , 1 , 64 ) derivedhalf1 , derivedhalf2 = deri...
Make sure the confirm code is valid for the given password and address .
247,039
def push_tx ( self , crypto , tx_hex ) : url = "%s/pushtx" % self . base_url return self . post_url ( url , { 'hex' : tx_hex } ) . content
This method is untested .
247,040
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 . verbose ) if self . verbose : print ( "Latest %s block is #%s" % ( self . so...
Replay all transactions in parent currency to passed in source currency . Block_to_replay can either be an integer or a block object .
247,041
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_height / float ( intervals ) ) all_points = [ x * i...
This utility is used to determine the actual block rate . The output can be directly copied to the blocktime_adjustments setting .
247,042
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_block : blocks_this_era = block_height - start_block coins += blocks_this_era * reward break blocks...
Calculate the coin supply based on eras defined in crypto_data . Some currencies don t have a simple algorithmically defined halfing schedule so coins supply has to be defined explicitly per era .
247,043
def _prepare_consensus ( FetcherClass , results ) : if hasattr ( FetcherClass , "strip_for_consensus" ) : to_compare = [ FetcherClass . strip_for_consensus ( value ) for ( fetcher , value ) in results ] else : to_compare = [ value for fetcher , value in results ] return to_compare , [ fetcher . _successful_service for ...
Given a list of results return a list that is simplified to make consensus determination possible . Returns two item tuple first arg is simplified list the second argument is a list of all services used in making these results .
247,044
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 : fetches = { } for service in services [ ...
Does the fetching in multiple threads of needed . Used by paranoid and fast mode .
247,045
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 in addresses : k = kwargs k [ 'address' ] = address r...
Private mode is only applicable to address_balance unspent_outputs and historical_transactions . There will always be a list for the addresses argument . Each address goes to a random service . Also a random delay is performed before the external fetch for improved privacy .
247,046
def currency_to_protocol ( amount ) : if type ( amount ) in [ float , int ] : amount = "%.8f" % amount return int ( amount . replace ( "." , '' ) )
Convert a string of currency units to protocol units . For instance converts 19 . 1 bitcoin to 1910000000 satoshis .
247,047
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 [ 'txid' ] ) , 'index' : x [ 'n' ] } , 'script' : str ( x [ 'scr...
Take a tx object in the moneywagon format and convert it to the format that pybitcointools s serialize funcion takes then return in raw hex format .
247,048
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 ServiceError ( "Foiled by Cloudfare's DDoS protection" ) raise ServiceError ( "503 - Temporari...
If the service is returning an error this function should raise an exception . such as SkipThisService
247,049
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 KeyError : raise Exception ( "Can not convert %s to %s" % ( base_fiat , t...
Convert one fiat amount to another fiat . Uses the fixer . io service .
247,050
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 : if symbol == old : return new return symbol
In comes a moneywagon format symbol and returned in the symbol converted to one the service can understand .
247,051
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 ) )
In comes the market identifier directly from the service . Returned is the crypto and fiat identifier in moneywagon format .
247,052
def make_market ( self , crypto , fiat , seperator = "_" ) : return ( "%s%s%s" % ( self . fix_symbol ( crypto ) , seperator , self . fix_symbol ( fiat ) ) ) . lower ( )
Convert a crypto and fiat to a market string . All exchanges use their own format for specifying markets . Subclasses can define their own implementation .
247,053
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 ] headers = kwargs . pop ( 'headers' , None ) custom = { 'User-Agent' : useragent } if headers : headers . update ( custom ) kwargs [ 'head...
Wrapper for requests . get with useragent automatically set . And also all requests are reponses are cached .
247,054
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." )
Get block based on either block height block number or get the latest block . Only one of the previous arguments must be passed on .
247,055
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." )
This method buys or sells crypto on an exchange using fiat balance . Type can either be fill - or - kill post - only market or limit . To get what modes are supported consult make_order . supported_types if one is defined .
247,056
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 : raise CurrencyNotSupported ( "No services defined for %s ...
Try each service until one returns a response . This function only catches the bare minimum of exceptions from the service class . We want exceptions to be raised so the service classes can be debugged and fixed quickly .
247,057
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 .
247,058
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 .
247,059
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 .
247,060
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 .
247,061
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
247,062
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
247,063
def uhstack ( arrs ) : v = np . hstack ( arrs ) v = _validate_numpy_wrapper_units ( v , arrs ) return v
Stack arrays in sequence horizontally while preserving units
247,064
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
247,065
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 : continue if line [ 0 ] == comments : if next_one : units = wo...
r Load unyt_arrays with unit information from a text file . Each row in the text file must have the same number of values .
247,066
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 ( array . units ) ) else : units . append ( "dimensionless"...
r Write unyt_arrays with unit information to a text file .
247,067
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 . registry ) if any ( conv_data ) : new_units , ( conv_factor , offset )...
Convert the array to the given units in - place .
247,068
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 )
Convert the array in - place to the equivalent base units in the specified unit system .
247,069
def convert_to_cgs ( self , equivalence = None , ** kwargs ) : self . convert_to_units ( self . units . get_cgs_equivalent ( ) , equivalence = equivalence , ** kwargs )
Convert the array and in - place to the equivalent cgs units .
247,070
def convert_to_mks ( self , equivalence = None , ** kwargs ) : self . convert_to_units ( self . units . get_mks_equivalent ( ) , equivalence , ** kwargs )
Convert the array and units to the equivalent mks units .
247,071
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 ) : return float ( v ) else : return v
Creates a copy of this array with the data in the supplied units and returns it without units . Output is therefore a bare NumPy array .
247,072
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 MKSCGSConversionError : raise UnitsNotReducible ( self . units , us ) if any ( conv_data ) : to_units , ( c...
Creates a copy of this array with the data in the specified unit system and returns it in that system s base units .
247,073
def argsort ( self , axis = - 1 , kind = "quicksort" , order = None ) : return self . view ( np . ndarray ) . argsort ( axis , kind , order )
Returns the indices that would sort the array .
247,074
def from_astropy ( cls , arr , unit_registry = None ) : try : u = arr . unit _arr = arr except AttributeError : u = arr _arr = 1.0 * u ap_units = [ ] for base , exponent in zip ( u . bases , u . powers ) : unit_str = base . to_string ( ) if unit_str == "h" : unit_str = "hr" ap_units . append ( "%s**(%s)" % ( unit_str ,...
Convert an AstroPy Quantity to a unyt_array or unyt_quantity .
247,075
def to_astropy ( self , ** kwargs ) : return self . value * _astropy . units . Unit ( str ( self . units ) , ** kwargs )
Creates a new AstroPy quantity with the same unit information .
247,076
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 ) if isinstance ( arr . magnitude , np . ndarray ) : return unyt_array ( a...
Convert a Pint Quantity to a unyt_array or unyt_quantity .
247,077
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 ( ) : if str ( unit ) . endswith ( "yr" ) and len ( str ( unit ) ) in [ 2 , 3 ] : unit = str ( unit )...
Convert a unyt_array or unyt_quantity to a Pint Quantity .
247,078
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 [ "unit_registry" ] = np . void ( pickle . dumps ( self . units . registry . lut ) ) ...
r Writes a unyt_array to hdf5 file .
247,079
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 group_name is not None : g = f [ group_name ] else : g = f dataset = g [ dataset_name ] d...
r Attempts read in and convert a dataset in an hdf5 file into a unyt_array .
247,080
def copy ( self , order = "C" ) : return type ( self ) ( np . copy ( np . asarray ( self ) ) , self . units )
Return a copy of the array .
247,081
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 .
247,082
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
247,083
def _lookup_unit_symbol ( symbol_str , unit_symbol_lut ) : if symbol_str in unit_symbol_lut : return unit_symbol_lut [ symbol_str ] prefix , symbol_wo_prefix = _split_prefix ( symbol_str , unit_symbol_lut ) if prefix : unit_data = unit_symbol_lut [ symbol_wo_prefix ] prefix_value = unit_prefixes [ prefix ] [ 0 ] if sym...
Searches for the unit data tuple corresponding to the given symbol .
247,084
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" ) ) m = md5 ( ) m . update ( hash_data ) self . _unit_system_id = str ( m . hexdiges...
This is a unique identifier for the unit registry created from a FNV hash . It is needed to register a dataset s code unit system in the unit system registry .
247,085
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 if not isinstance ( base_value , float ) : raise UnitParseError ( "base_value (%s) must be a float, got a %s." % ( base_value ,...
Add a symbol to this registry .
247,086
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 ) del self . lut [ symbol ]
Remove the entry for the unit matching symbol .
247,087
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." % symbol ) if hasattr ( base_value , "in_base" ) : new_dimensions = base_value . units . dimensions base_value...
Change the base value of a unit symbol . Useful for adjusting code units after parsing parameters .
247,088
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 )
Returns a json - serialized version of the unit registry
247,089
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 cls ( lut = lut , add_default_symbols = False )
Returns a UnitRegistry object from a json - serialized unit registry
247,090
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 : to_units = Unit ( conv_unit . expr , registry = orig_units . regis...
Convert between E&M & MKS base units .
247,091
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 ) , unit . registry . lut ) else : prefix , unit_wo_prefix...
Check to see if the units contain E&M units
247,092
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_units . base_value if old_units . base_offset == 0 and new_units...
Get the conversion factor between two units of equivalent dimensions . This is the number you multiply data by to convert from values in old_units to values in new_units .
247,093
def _get_unit_data_from_expr ( unit_expr , unit_symbol_lut ) : if isinstance ( unit_expr , Number ) : if unit_expr is sympy_one : return ( 1.0 , sympy_one ) return ( float ( unit_expr ) , sympy_one ) if isinstance ( unit_expr , Symbol ) : return _lookup_unit_symbol ( unit_expr . name , unit_symbol_lut ) if isinstance (...
Grabs the total base_value and dimensions from a valid unit expression .
247,094
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 : raise RuntimeError ( "Unit symbol '%s' already exists in the provide...
Define a new unit and add it to the specified unit registry .
247,095
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 , self . registry ) return self . _latex_repr
A LaTeX representation for the unit
247,096
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?
247,097
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
247,098
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 , registry = self . registry , unit_system = unit_system ) except MKSCGSConversionError : raise ...
Create and return dimensionally - equivalent units in a specified base .
247,099
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 , ) return coeff , ret
Factor the coefficient multiplying a unit