sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _fix_bias_shape(self, op_name, inputs, attrs): """A workaround to reshape bias term to (1, num_channel).""" if (op_name == 'Add' or op_name == 'Mul') and (int(len(self._params)) > 0) and \ ('broadcast' in attrs and attrs['broadcast'] == 1): assert len(list(inputs)) == 2 ...
A workaround to reshape bias term to (1, num_channel).
entailment
def _fix_channels(self, op, attrs, inputs): """A workaround for getting 'channels' or 'units' since onnx don't provide these attributes. We check the shape of weights provided to get the number. """ if op not in [mx.sym.Convolution, mx.sym.Deconvolution, mx.sym.FullyConnected]: ...
A workaround for getting 'channels' or 'units' since onnx don't provide these attributes. We check the shape of weights provided to get the number.
entailment
def run(self, inputs, **kwargs): """Run model inference and return the result Parameters ---------- inputs : numpy array input to run a layer on Returns ------- params : numpy array result obtained after running the inference on mxnet ...
Run model inference and return the result Parameters ---------- inputs : numpy array input to run a layer on Returns ------- params : numpy array result obtained after running the inference on mxnet
entailment
def _parse_default(self, target): """Helper function to parse default values.""" if not isinstance(target, (list, tuple)): k, v, t = target, None, lambda x: x elif len(target) == 1: k, v, t = target[0], None, lambda x: x elif len(target) == 2: k, v, t ...
Helper function to parse default values.
entailment
def _parse_bool(self, value): """Helper function to parse default boolean values.""" if isinstance(value, string_types): return value.strip().lower() in ['true', '1', 't', 'y', 'yes'] return bool(value)
Helper function to parse default boolean values.
entailment
def _required_attr(self, attr, key): """Wrapper for getting required attributes.""" assert isinstance(attr, dict) if key not in attr: raise AttributeError("Required attribute {} not found.".format(key)) return attr[key]
Wrapper for getting required attributes.
entailment
def make_graph(node, inputs): """ Created ONNX GraphProto from node""" initializer = [] tensor_input_info = [] tensor_output_info = [] # Adding input tensor info. for index in range(len(node.input)): tensor_input_info.append( helper.make_tenso...
Created ONNX GraphProto from node
entailment
def run_node(cls, node, inputs, device='CPU'): # pylint: disable=arguments-differ """Running individual node inference on mxnet engine and return the result to onnx test infrastructure. Parameters ---------- node : onnx node object loaded onnx node (individual lay...
Running individual node inference on mxnet engine and return the result to onnx test infrastructure. Parameters ---------- node : onnx node object loaded onnx node (individual layer) inputs : numpy array input to run a node on device : 'CPU' ...
entailment
def prepare(cls, model, device='CPU', **kwargs): """For running end to end model(used for onnx test backend) Parameters ---------- model : onnx ModelProto object loaded onnx graph device : 'CPU' specifying device to run test on kwargs : ...
For running end to end model(used for onnx test backend) Parameters ---------- model : onnx ModelProto object loaded onnx graph device : 'CPU' specifying device to run test on kwargs : other arguments Returns ------- ...
entailment
def _revert_caffe2_pad(attr): """Removing extra padding from Caffe2.""" if len(attr) == 4: attr = attr[:2] elif len(attr) == 2: pass else: raise ValueError("Invalid caffe2 type padding: {}".format(attr)) return attr
Removing extra padding from Caffe2.
entailment
def _pad_sequence_fix(attr, kernelDim=None): """Changing onnx's pads sequence to match with mxnet's pad_width mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end) onnx: (x1_begin, x2_begin, ... , xn_end, xn_end)""" new_attr = () if len(attr) % 2 == 0: for index in range(int(len(attr) / 2)): ...
Changing onnx's pads sequence to match with mxnet's pad_width mxnet: (x1_begin, x1_end, ... , xn_begin, xn_end) onnx: (x1_begin, x2_begin, ... , xn_end, xn_end)
entailment
def import_model(model_file): """Imports the supplied ONNX model file into MXNet symbol and parameters. Parameters ---------- model_file : ONNX model file name Returns ------- sym : mx.symbol Compatible mxnet symbol params : dict of str to mx.ndarray Dict of converted ...
Imports the supplied ONNX model file into MXNet symbol and parameters. Parameters ---------- model_file : ONNX model file name Returns ------- sym : mx.symbol Compatible mxnet symbol params : dict of str to mx.ndarray Dict of converted parameters stored in mx.ndarray forma...
entailment
def generate_hash(filepath): """Public function that reads a local file and generates a SHA256 hash digest for it""" fr = FileReader(filepath) data = fr.read_bin() return _calculate_sha256(data)
Public function that reads a local file and generates a SHA256 hash digest for it
entailment
def generate_tar_files(directory_list): """Public function that reads a list of local directories and generates tar archives from them""" tar_file_list = [] for directory in directory_list: if dir_exists(directory): _generate_tar(directory) # create the tar archive...
Public function that reads a list of local directories and generates tar archives from them
entailment
def remove_tar_files(file_list): """Public function that removes temporary tar archive files in a local directory""" for f in file_list: if file_exists(f) and f.endswith('.tar'): os.remove(f)
Public function that removes temporary tar archive files in a local directory
entailment
def _generate_tar(dir_path): """Private function that reads a local directory and generates a tar archive from it""" try: with tarfile.open(dir_path + '.tar', 'w') as tar: tar.add(dir_path) except tarfile.TarError as e: stderr("Error: tar archive creation failed [" + str(e) + "]"...
Private function that reads a local directory and generates a tar archive from it
entailment
def encrypt_file(self, inpath, force_nocompress=False, force_compress=False, armored=False, checksum=False): """public method for single file encryption with optional compression, ASCII armored formatting, and file hash digest generation""" if armored: if force_compress: comm...
public method for single file encryption with optional compression, ASCII armored formatting, and file hash digest generation
entailment
def encrypt_files(self, file_list, force_nocompress=False, force_compress=False, armored=False, checksum=False): """public method for multiple file encryption with optional compression, ASCII armored formatting, and file hash digest generation""" for the_file in file_list: self.encrypt_file(...
public method for multiple file encryption with optional compression, ASCII armored formatting, and file hash digest generation
entailment
def _is_compress_filetype(self, inpath): """private method that performs magic number and size check on file to determine whether to compress the file""" # check for common file type suffixes in order to avoid the need for file reads to check magic number for binary vs. text file if self._is_com...
private method that performs magic number and size check on file to determine whether to compress the file
entailment
def _is_common_binary(self, inpath): """private method to compare file path mime type to common binary file types""" # make local variables for the available char numbers in the suffix types to be tested two_suffix = inpath[-3:] three_suffix = inpath[-4:] four_suffix = inpath[-5:...
private method to compare file path mime type to common binary file types
entailment
def _is_common_text(self, inpath): """private method to compare file path mime type to common text file types""" # make local variables for the available char numbers in the suffix types to be tested one_suffix = inpath[-2:] two_suffix = inpath[-3:] three_suffix = inpath[-4:] ...
private method to compare file path mime type to common text file types
entailment
def knn_impute_few_observed( X, missing_mask, k, verbose=False, print_interval=100): """ Seems to be the fastest kNN implementation. Pre-sorts each rows neighbors and then filters these sorted indices using each columns mask of observed values. Important detail: If k observed values are not...
Seems to be the fastest kNN implementation. Pre-sorts each rows neighbors and then filters these sorted indices using each columns mask of observed values. Important detail: If k observed values are not available then uses fewer than k neighboring rows. Parameters ---------- X : np.ndarray...
entailment
def knn_initialize( X, missing_mask, verbose=False, min_dist=1e-6, max_dist_multiplier=1e6): """ Fill X with NaN values if necessary, construct the n_samples x n_samples distance matrix and set the self-distance of each row to infinity. Returns contents of X laid...
Fill X with NaN values if necessary, construct the n_samples x n_samples distance matrix and set the self-distance of each row to infinity. Returns contents of X laid out in row-major, the distance matrix, and an "effective infinity" which is larger than any entry of the distance matrix.
entailment
def knn_impute_optimistic( X, missing_mask, k, verbose=False, print_interval=100): """ Fill in the given incomplete matrix using k-nearest neighbor imputation. This version assumes that most of the time the same neighbors will be used so first performs the weight...
Fill in the given incomplete matrix using k-nearest neighbor imputation. This version assumes that most of the time the same neighbors will be used so first performs the weighted average of a row's k-nearest neighbors and checks afterward whether it was valid (due to possible missing values). Has been...
entailment
def all_pairs_normalized_distances(X): """ We can't really compute distances over incomplete data since rows are missing different numbers of entries. The next best thing is the mean squared difference between two vectors (a normalized distance), which gets computed only over the columns that tw...
We can't really compute distances over incomplete data since rows are missing different numbers of entries. The next best thing is the mean squared difference between two vectors (a normalized distance), which gets computed only over the columns that two vectors have in common. If two vectors have no fe...
entailment
def all_pairs_normalized_distances_reference(X): """ Reference implementation of normalized all-pairs distance, used for testing the more efficient implementation above for equivalence. """ n_samples, n_cols = X.shape # matrix of mean squared difference between between samples D = np.ones((n...
Reference implementation of normalized all-pairs distance, used for testing the more efficient implementation above for equivalence.
entailment
def knn_impute_with_argpartition( X, missing_mask, k, verbose=False, print_interval=100): """ Fill in the given incomplete matrix using k-nearest neighbor imputation. This version is a simpler algorithm meant primarily for testing but surprisingly it's faster for...
Fill in the given incomplete matrix using k-nearest neighbor imputation. This version is a simpler algorithm meant primarily for testing but surprisingly it's faster for many (but not all) dataset sizes, particularly when most of the columns are missing in any given row. The crucial bottleneck is the c...
entailment
def knn_impute_reference( X, missing_mask, k, verbose=False, print_interval=100): """ Reference implementation of kNN imputation logic. """ n_rows, n_cols = X.shape X_result, D, effective_infinity = \ knn_initialize(X, missing_mask, verbose=verbose) ...
Reference implementation of kNN imputation logic.
entailment
def active(self, registered_only=True): "Returns all active users, e.g. not logged and non-expired session." visitors = self.filter( expiry_time__gt=timezone.now(), end_time=None ) if registered_only: visitors = visitors.filter(user__isnull=False) ...
Returns all active users, e.g. not logged and non-expired session.
entailment
def stats(self, start_date, end_date, registered_only=False): """Returns a dictionary of visits including: * total visits * unique visits * return ratio * pages per visit (if pageviews are enabled) * time on site for all users, registered use...
Returns a dictionary of visits including: * total visits * unique visits * return ratio * pages per visit (if pageviews are enabled) * time on site for all users, registered users and guests.
entailment
def stats(self, start_date=None, end_date=None, registered_only=False): """Returns a dictionary of pageviews including: * total pageviews for all users, registered users and guests. """ pageviews = self.filter( visitor__start_time__lt=end_date, visit...
Returns a dictionary of pageviews including: * total pageviews for all users, registered users and guests.
entailment
def dashboard(request): "Counts, aggregations and more!" end_time = now() start_time = end_time - timedelta(days=7) defaults = {'start': start_time, 'end': end_time} form = DashboardForm(data=request.GET or defaults) if form.is_valid(): start_time = form.cleaned_data['start'] en...
Counts, aggregations and more!
entailment
def geoip_data(self): """Attempt to retrieve MaxMind GeoIP data based on visitor's IP.""" if not HAS_GEOIP or not TRACK_USING_GEOIP: return if not hasattr(self, '_geoip_data'): self._geoip_data = None try: gip = GeoIP(cache=GEOIP_CACHE_TYPE) ...
Attempt to retrieve MaxMind GeoIP data based on visitor's IP.
entailment
def escape(s): """Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string. """ if hasattr(s, '__html__'): return s.__html__() if isinstance(s, six.bi...
Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.
entailment
def iteration(obj, num_keys): """ Jade iteration supports "for 'value' [, key]?" iteration only. PyJade has implicitly supported value unpacking instead, without the list indexes. Trying to not break existing code, the following rules are applied: 1. If the object is a mapping type, return it...
Jade iteration supports "for 'value' [, key]?" iteration only. PyJade has implicitly supported value unpacking instead, without the list indexes. Trying to not break existing code, the following rules are applied: 1. If the object is a mapping type, return it as-is, and assume the caller has...
entailment
def do_evaluate(parser, token): '''Calls an arbitrary method on an object.''' code = token.contents firstspace = code.find(' ') if firstspace >= 0: code = code[firstspace+1:] return Evaluator(code)
Calls an arbitrary method on an object.
entailment
def do_set(parser, token): '''Calls an arbitrary method on an object.''' code = token.contents firstspace = code.find(' ') if firstspace >= 0: code = code[firstspace+1:] return Setter(code)
Calls an arbitrary method on an object.
entailment
def render(self, context): '''Evaluates the code in the page and returns the result''' modules = { 'pyjade': __import__('pyjade') } context['false'] = False context['true'] = True try: return six.text_type(eval('pyjade.runtime.attrs(%s)'%self.code,modules,context)) except NameE...
Evaluates the code in the page and returns the result
entailment
def render(self, context): '''Evaluates the code in the page and returns the result''' modules = { } context['false'] = False context['true'] = True new_ctx = eval('dict(%s)'%self.code,modules,context) context.update(new_ctx) return ''
Evaluates the code in the page and returns the result
entailment
def sprite_filepath_build(sprite_type, sprite_id, **kwargs): """returns the filepath of the sprite *relative to SPRITE_CACHE*""" options = parse_sprite_options(sprite_type, **kwargs) filename = '.'.join([str(sprite_id), SPRITE_EXT]) filepath = os.path.join(sprite_type, *options, filename) return ...
returns the filepath of the sprite *relative to SPRITE_CACHE*
entailment
def _make_obj(obj): """Takes an object and returns a corresponding API class. The names and values of the data will match exactly with those found in the online docs at https://pokeapi.co/docsv2/ . In some cases, the data may be of a standard type, such as an integer or string. For those cases, the...
Takes an object and returns a corresponding API class. The names and values of the data will match exactly with those found in the online docs at https://pokeapi.co/docsv2/ . In some cases, the data may be of a standard type, such as an integer or string. For those cases, the input value is simply retu...
entailment
def _load(self): """Function to collect reference data and connect it to the instance as attributes. Internal function, does not usually need to be called by the user, as it is called automatically when an attribute is requested. :return None """ data = get_...
Function to collect reference data and connect it to the instance as attributes. Internal function, does not usually need to be called by the user, as it is called automatically when an attribute is requested. :return None
entailment
def safe_make_dirs(path, mode=0o777): """Create a leaf directory and all intermediate ones in a safe way. A wrapper to os.makedirs() that handles existing leaf directories while avoiding os.path.exists() race conditions. :param path: relative or absolute directory tree to create :param mode: direc...
Create a leaf directory and all intermediate ones in a safe way. A wrapper to os.makedirs() that handles existing leaf directories while avoiding os.path.exists() race conditions. :param path: relative or absolute directory tree to create :param mode: directory permissions in octal :return: The ne...
entailment
def get_default_cache(): """Get the default cache location. Adheres to the XDG Base Directory specification, as described in https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html :return: the default cache directory absolute path """ xdg_cache_home = os.environ.get('XDG_CACH...
Get the default cache location. Adheres to the XDG Base Directory specification, as described in https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html :return: the default cache directory absolute path
entailment
def set_cache(new_path=None): """Simple function to change the cache location. `new_path` can be an absolute or relative path. If the directory does not exist yet, this function will create it. If None it will set the cache to the default cache directory. If you are going to change the cache direc...
Simple function to change the cache location. `new_path` can be an absolute or relative path. If the directory does not exist yet, this function will create it. If None it will set the cache to the default cache directory. If you are going to change the cache directory, this function should be cal...
entailment
def attach(self, lun_or_snap, skip_hlu_0=False): """ Attaches lun, snap or member snap of cg snap to host. Don't pass cg snapshot in as `lun_or_snap`. :param lun_or_snap: the lun, snap, or a member snap of cg snap :param skip_hlu_0: whether to skip hlu 0 :return: the hlu number...
Attaches lun, snap or member snap of cg snap to host. Don't pass cg snapshot in as `lun_or_snap`. :param lun_or_snap: the lun, snap, or a member snap of cg snap :param skip_hlu_0: whether to skip hlu 0 :return: the hlu number
entailment
def has_hlu(self, lun_or_snap, cg_member=None): """Returns True if `lun_or_snap` is attached to the host. :param lun_or_snap: can be lun, lun snap, cg snap or a member snap of cg snap. :param cg_member: the member lun of cg if `lun_or_snap` is cg snap. :return: True - if `lu...
Returns True if `lun_or_snap` is attached to the host. :param lun_or_snap: can be lun, lun snap, cg snap or a member snap of cg snap. :param cg_member: the member lun of cg if `lun_or_snap` is cg snap. :return: True - if `lun_or_snap` is attached, otherwise False.
entailment
def get_host_lun(self, lun_or_snap, cg_member=None): """Gets the host lun of a lun, lun snap, cg snap or a member snap of cg snap. :param lun_or_snap: can be lun, lun snap, cg snap or a member snap of cg snap. :param cg_member: the member lun of cg if `lun_or_snap` is cg sna...
Gets the host lun of a lun, lun snap, cg snap or a member snap of cg snap. :param lun_or_snap: can be lun, lun snap, cg snap or a member snap of cg snap. :param cg_member: the member lun of cg if `lun_or_snap` is cg snap. :return: the host lun object.
entailment
def get_hlu(self, resource, cg_member=None): """Gets the hlu number of a lun, lun snap, cg snap or a member snap of cg snap. :param resource: can be lun, lun snap, cg snap or a member snap of cg snap. :param cg_member: the member lun of cg if `lun_or_snap` is cg snap. ...
Gets the hlu number of a lun, lun snap, cg snap or a member snap of cg snap. :param resource: can be lun, lun snap, cg snap or a member snap of cg snap. :param cg_member: the member lun of cg if `lun_or_snap` is cg snap. :return: the hlu number.
entailment
def update_initiators(self, iqns=None, wwns=None): """Primarily for puppet-unity use. Update the iSCSI and FC initiators if needed. """ # First get current iqns iqns = set(iqns) if iqns else set() current_iqns = set() if self.iscsi_host_initiators: cu...
Primarily for puppet-unity use. Update the iSCSI and FC initiators if needed.
entailment
def list_files(tag=None, sat_id=None, data_path=None, format_str=None, supported_tags=None, fake_daily_files_from_monthly=False, two_digit_year_break=None): """Return a Pandas Series of every file for chosen satellite data. This routine is intended to be used by pysat instrume...
Return a Pandas Series of every file for chosen satellite data. This routine is intended to be used by pysat instrument modules supporting a particular NASA CDAWeb dataset. Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are <tag strings>...
entailment
def load(fnames, tag=None, sat_id=None, fake_daily_files_from_monthly=False, flatten_twod=True): """Load NASA CDAWeb CDF files. This routine is intended to be used by pysat instrument modules supporting a particular NASA CDAWeb dataset. Parameters ------------ fnames : (...
Load NASA CDAWeb CDF files. This routine is intended to be used by pysat instrument modules supporting a particular NASA CDAWeb dataset. Parameters ------------ fnames : (pandas.Series) Series of filenames tag : (str or NoneType) tag or None (default=None) sat_id : (str...
entailment
def download(supported_tags, date_array, tag, sat_id, ftp_site='cdaweb.gsfc.nasa.gov', data_path=None, user=None, password=None, fake_daily_files_from_monthly=False): """Routine to download NASA CDAWeb CDF data. This routine is intended to be used by pysat instrumen...
Routine to download NASA CDAWeb CDF data. This routine is intended to be used by pysat instrument modules supporting a particular NASA CDAWeb dataset. Parameters ----------- supported_tags : dict dict of dicts. Keys are supported tag names for download. Value is a dict with 'd...
entailment
def from_response(response, method, url): """Returns an instance of :class:`HttpError` or subclass based on response. :param response: instance of `requests.Response` class :param method: HTTP method used for request :param url: URL used for request """ req_id = response.headers.get("x-opensta...
Returns an instance of :class:`HttpError` or subclass based on response. :param response: instance of `requests.Response` class :param method: HTTP method used for request :param url: URL used for request
entailment
def create_pool(self, name, raid_groups, description=None, **kwargs): """Create pool based on RaidGroupParameter. :param name: pool name :param raid_groups: a list of *RaidGroupParameter* :param description: pool description :param alert_threshold: Threshold at which the system ...
Create pool based on RaidGroupParameter. :param name: pool name :param raid_groups: a list of *RaidGroupParameter* :param description: pool description :param alert_threshold: Threshold at which the system will generate alerts about the free space in the pool, specified a...
entailment
def get_file_port(self): """Returns ports list can be used by File File ports includes ethernet ports and link aggregation ports. """ eths = self.get_ethernet_port(bond=False) las = self.get_link_aggregation() return eths + las
Returns ports list can be used by File File ports includes ethernet ports and link aggregation ports.
entailment
def create_remote_system(self, management_address, local_username=None, local_password=None, remote_username=None, remote_password=None, connection_type=None): """ Configures a remote system for remote replication. ...
Configures a remote system for remote replication. :param management_address: the management IP address of the remote system. :param local_username: administrative username of local system. :param local_password: administrative password of local system. :param remote_usernam...
entailment
def create_replication_interface(self, sp, ip_port, ip_address, netmask=None, v6_prefix_length=None, gateway=None, vlan_id=None): """ Creates a replication interface. :param sp: `UnityStorageProcessor` object. Storage pro...
Creates a replication interface. :param sp: `UnityStorageProcessor` object. Storage processor on which the replication interface is running. :param ip_port: `UnityIpPort` object. Physical port or link aggregation on the storage processor on which the interface is running. ...
entailment
def geo2mag(incoord): """geographic coordinate to magnetic coordinate (coarse): Parameters ---------- incoord : numpy.array of shape (2,*) array([[glat0,glat1,glat2,...],[glon0,glon1,glon2,...]), where glat, glon are geographic latitude and longitude (or if you have only one po...
geographic coordinate to magnetic coordinate (coarse): Parameters ---------- incoord : numpy.array of shape (2,*) array([[glat0,glat1,glat2,...],[glon0,glon1,glon2,...]), where glat, glon are geographic latitude and longitude (or if you have only one point it is [[glat,glon]]). ...
entailment
def restore(self, res_id, backup_snap=None): """ Restores a snapshot. :param res_id: the LUN number of primary LUN or snapshot mount point to be restored. :param backup_snap: the name of a backup snapshot to be created before restoring. """ name = ...
Restores a snapshot. :param res_id: the LUN number of primary LUN or snapshot mount point to be restored. :param backup_snap: the name of a backup snapshot to be created before restoring.
entailment
def list_files(tag='', sat_id=None, data_path=None, format_str=None): """Return a Pandas Series of every file for chosen SuperMAG data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magne...
Return a Pandas Series of every file for chosen SuperMAG data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer measurements). (default='') sat_id : (string or NoneType) ...
entailment
def load(fnames, tag='', sat_id=None): """ Load the SuperMAG files Parameters ----------- fnames : (list) List of filenames tag : (str or NoneType) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer measurements). (d...
Load the SuperMAG files Parameters ----------- fnames : (list) List of filenames tag : (str or NoneType) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer measurements). (default='') sat_id : (str or NoneType) ...
entailment
def load_csv_data(fname, tag): """Load data from a comma separated SuperMAG file Parameters ------------ fname : (str) CSV SuperMAG file name tag : (str) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer measurement...
Load data from a comma separated SuperMAG file Parameters ------------ fname : (str) CSV SuperMAG file name tag : (str) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer measurements). Returns -------- data...
entailment
def load_ascii_data(fname, tag): """Load data from a self-documenting ASCII SuperMAG file Parameters ------------ fname : (str) ASCII SuperMAG filename tag : (str) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer m...
Load data from a self-documenting ASCII SuperMAG file Parameters ------------ fname : (str) ASCII SuperMAG filename tag : (str) Denotes type of file to load. Accepted types are 'indices', 'all', 'stations', and '' (for just magnetometer measurements). Returns -------- ...
entailment
def update_smag_metadata(col_name): """Update SuperMAG metadata Parameters ----------- col_name : (str) Data column name Returns -------- col_dict : (dict) Dictionary of strings detailing the units and long-form name of the data """ smag_units = {'IAGA':'non...
Update SuperMAG metadata Parameters ----------- col_name : (str) Data column name Returns -------- col_dict : (dict) Dictionary of strings detailing the units and long-form name of the data
entailment
def format_baseline_list(baseline_list): """Format the list of baseline information from the loaded files into a cohesive, informative string Parameters ------------ baseline_list : (list) List of strings specifying the baseline information for each SuperMAG file Returns --...
Format the list of baseline information from the loaded files into a cohesive, informative string Parameters ------------ baseline_list : (list) List of strings specifying the baseline information for each SuperMAG file Returns --------- base_string : (str) Single s...
entailment
def download(date_array, tag, sat_id='', data_path=None, user=None, password=None, baseline='all', delta='none', options='all', file_fmt='ascii'): """Routine to download SuperMAG data Parameters ----------- date_array : np.array Array of datetime objects tag : stri...
Routine to download SuperMAG data Parameters ----------- date_array : np.array Array of datetime objects tag : string String denoting the type of file to load, accepted values are 'indices', 'all', 'stations', and '' (for only magnetometer data) sat_id : string Not u...
entailment
def append_data(file_strings, file_fmt, tag): """ Load the SuperMAG files Parameters ----------- file_strings : array-like Lists or arrays of strings, where each string contains one file of data file_fmt : str String denoting file type (ascii or csv) tag : string String ...
Load the SuperMAG files Parameters ----------- file_strings : array-like Lists or arrays of strings, where each string contains one file of data file_fmt : str String denoting file type (ascii or csv) tag : string String denoting the type of file to load, accepted values are...
entailment
def append_ascii_data(file_strings, tag): """ Append data from multiple files for the same time period Parameters ----------- file_strings : array-like Lists or arrays of strings, where each string contains one file of data tag : string String denoting the type of file to load, acce...
Append data from multiple files for the same time period Parameters ----------- file_strings : array-like Lists or arrays of strings, where each string contains one file of data tag : string String denoting the type of file to load, accepted values are 'indices', 'all', 'station...
entailment
def append_csv_data(file_strings): """ Append data from multiple csv files for the same time period Parameters ----------- file_strings : array-like Lists or arrays of strings, where each string contains one file of data Returns ------- out_string : string String with all d...
Append data from multiple csv files for the same time period Parameters ----------- file_strings : array-like Lists or arrays of strings, where each string contains one file of data Returns ------- out_string : string String with all data, ready for output to a file
entailment
def init(self): """ Adds custom calculations to orbit simulation. This routine is run once, and only once, upon instantiation. Adds quasi-dipole coordiantes, velocity calculation in ECEF coords, adds the attitude vectors of spacecraft assuming x is ram pointing and z is generally nadir, add...
Adds custom calculations to orbit simulation. This routine is run once, and only once, upon instantiation. Adds quasi-dipole coordiantes, velocity calculation in ECEF coords, adds the attitude vectors of spacecraft assuming x is ram pointing and z is generally nadir, adds ionospheric parameters fro...
entailment
def load(fnames, tag=None, sat_id=None, obs_long=0., obs_lat=0., obs_alt=0., TLE1=None, TLE2=None): """ Returns data and metadata in the format required by pysat. Finds position of satellite in both ECI and ECEF co-ordinates. Routine is directl...
Returns data and metadata in the format required by pysat. Finds position of satellite in both ECI and ECEF co-ordinates. Routine is directly called by pysat and not the user. Parameters ---------- fnames : list-like collection File name that contains date in its name. ...
entailment
def list_files(tag=None, sat_id=None, data_path=None, format_str=None): """Produce a fake list of files spanning a year""" index = pds.date_range(pysat.datetime(2017,12,1), pysat.datetime(2018,12,1)) # file list is effectively just the date in string format - '%D' works only in Mac. '%x' workins in bo...
Produce a fake list of files spanning a year
entailment
def add_sc_attitude_vectors(inst): """ Add attitude vectors for spacecraft assuming ram pointing. Presumes spacecraft is pointed along the velocity vector (x), z is generally nadir pointing (positive towards Earth), and y completes the right handed system (generally southward). ...
Add attitude vectors for spacecraft assuming ram pointing. Presumes spacecraft is pointed along the velocity vector (x), z is generally nadir pointing (positive towards Earth), and y completes the right handed system (generally southward). Notes ----- Expects velocity and positi...
entailment
def calculate_ecef_velocity(inst): """ Calculates spacecraft velocity in ECEF frame. Presumes that the spacecraft velocity in ECEF is in the input instrument object as position_ecef_*. Uses a symmetric difference to calculate the velocity thus endpoints will be set to NaN. Routine should b...
Calculates spacecraft velocity in ECEF frame. Presumes that the spacecraft velocity in ECEF is in the input instrument object as position_ecef_*. Uses a symmetric difference to calculate the velocity thus endpoints will be set to NaN. Routine should be run using pysat data padding feature to c...
entailment
def add_quasi_dipole_coordinates(inst, glat_label='glat', glong_label='glong', alt_label='alt'): """ Uses Apexpy package to add quasi-dipole coordinates to instrument object. The Quasi-Dipole coordinate system includes both the tilt and offset of the geomag...
Uses Apexpy package to add quasi-dipole coordinates to instrument object. The Quasi-Dipole coordinate system includes both the tilt and offset of the geomagnetic field to calculate the latitude, longitude, and local time of the spacecraft with respect to the geomagnetic field. This system is ...
entailment
def add_aacgm_coordinates(inst, glat_label='glat', glong_label='glong', alt_label='alt'): """ Uses AACGMV2 package to add AACGM coordinates to instrument object. The Altitude Adjusted Corrected Geomagnetic Coordinates library is used to calculate the latitud...
Uses AACGMV2 package to add AACGM coordinates to instrument object. The Altitude Adjusted Corrected Geomagnetic Coordinates library is used to calculate the latitude, longitude, and local time of the spacecraft with respect to the geomagnetic field. Example ------- # function added...
entailment
def add_iri_thermal_plasma(inst, glat_label='glat', glong_label='glong', alt_label='alt'): """ Uses IRI (International Reference Ionosphere) model to simulate an ionosphere. Uses pyglow module to run IRI. Configured to use actual solar parameters to run model. ...
Uses IRI (International Reference Ionosphere) model to simulate an ionosphere. Uses pyglow module to run IRI. Configured to use actual solar parameters to run model. Example ------- # function added velow modifies the inst object upon every inst.load call inst.custom.add(add_i...
entailment
def add_hwm_winds_and_ecef_vectors(inst, glat_label='glat', glong_label='glong', alt_label='alt'): """ Uses HWM (Horizontal Wind Model) model to obtain neutral wind details. Uses pyglow module to run HWM. Configured to use actual solar parameters to run m...
Uses HWM (Horizontal Wind Model) model to obtain neutral wind details. Uses pyglow module to run HWM. Configured to use actual solar parameters to run model. Example ------- # function added velow modifies the inst object upon every inst.load call inst.custom.add(add_hwm_winds...
entailment
def add_igrf(inst, glat_label='glat', glong_label='glong', alt_label='alt'): """ Uses International Geomagnetic Reference Field (IGRF) model to obtain geomagnetic field values. Uses pyglow module to run IGRF. Configured to use actual solar parameters to run ...
Uses International Geomagnetic Reference Field (IGRF) model to obtain geomagnetic field values. Uses pyglow module to run IGRF. Configured to use actual solar parameters to run model. Example ------- # function added velow modifies the inst object upon every inst.load call ins...
entailment
def add_msis(inst, glat_label='glat', glong_label='glong', alt_label='alt'): """ Uses MSIS model to obtain thermospheric values. Uses pyglow module to run MSIS. Configured to use actual solar parameters to run model. Example ------- # f...
Uses MSIS model to obtain thermospheric values. Uses pyglow module to run MSIS. Configured to use actual solar parameters to run model. Example ------- # function added velow modifies the inst object upon every inst.load call inst.custom.add(add_msis, 'modify', glat_label='cus...
entailment
def project_ecef_vector_onto_sc(inst, x_label, y_label, z_label, new_x_label, new_y_label, new_z_label, meta=None): """Express input vector using s/c attitude directions x - ram pointing y - generally southward z - generally nadir ...
Express input vector using s/c attitude directions x - ram pointing y - generally southward z - generally nadir Parameters ---------- x_label : string Label used to get ECEF-X component of vector to be projected y_label : string Label used to get ECEF-Y component of...
entailment
def scatterplot(inst, labelx, labely, data_label, datalim, xlim=None, ylim=None): """Return scatterplot of data_label(s) as functions of labelx,y over a season. Parameters ---------- labelx : string data product for x-axis labely : string data product for y-axis data_label : s...
Return scatterplot of data_label(s) as functions of labelx,y over a season. Parameters ---------- labelx : string data product for x-axis labely : string data product for y-axis data_label : string, array-like of strings data product(s) to be scatter plotted datalim : ...
entailment
def enable_log(level=logging.DEBUG): """Enable console logging. This is a utils method for try run with storops. :param level: log level, default to DEBUG """ logger = logging.getLogger(__name__) logger.setLevel(level) if not logger.handlers: logger.info('enabling logging to console...
Enable console logging. This is a utils method for try run with storops. :param level: log level, default to DEBUG
entailment
def list_files(tag=None, sat_id=None, data_path=None, format_str=None): """Return a Pandas Series of every file for chosen satellite data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are '' and 'ascii'. If '' is specified, the primary d...
Return a Pandas Series of every file for chosen satellite data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are '' and 'ascii'. If '' is specified, the primary data type (ascii) is loaded. (default=None) sat_id : (string or None...
entailment
def load_files(files, tag=None, sat_id=None, altitude_bin=None): '''Loads a list of COSMIC data files, supplied by user. Returns a list of dicts, a dict for each file. ''' output = [None]*len(files) drop_idx = [] for (i,file) in enumerate(files): try: #data = net...
Loads a list of COSMIC data files, supplied by user. Returns a list of dicts, a dict for each file.
entailment
def round_60(value): """ round the number to the multiple of 60 Say a random value is represented by: 60 * n + r n is an integer and r is an integer between 0 and 60. if r < 30, the result is 60 * n. otherwise, the result is 60 * (n + 1) The use of this function is that the counter refreshment...
round the number to the multiple of 60 Say a random value is represented by: 60 * n + r n is an integer and r is an integer between 0 and 60. if r < 30, the result is 60 * n. otherwise, the result is 60 * (n + 1) The use of this function is that the counter refreshment on VNX is always 1 minut...
entailment
def utilization(prev, curr, counters): """ calculate the utilization delta_busy = curr.busy - prev.busy delta_idle = curr.idle - prev.idle utilization = delta_busy / (delta_busy + delta_idle) :param prev: previous resource :param curr: current resource :param counters: list of two, busy ti...
calculate the utilization delta_busy = curr.busy - prev.busy delta_idle = curr.idle - prev.idle utilization = delta_busy / (delta_busy + delta_idle) :param prev: previous resource :param curr: current resource :param counters: list of two, busy ticks and idle ticks :return: value, NaN if i...
entailment
def delta_ps(prev, curr, counters): """ calculate the delta per second of one counter formula: (curr - prev) / delta_time :param prev: previous resource :param curr: current resource :param counters: the counter to do delta and per second, one only :return: value, NaN if invalid. """ co...
calculate the delta per second of one counter formula: (curr - prev) / delta_time :param prev: previous resource :param curr: current resource :param counters: the counter to do delta and per second, one only :return: value, NaN if invalid.
entailment
def io_size_kb(prev, curr, counters): """ calculate the io size based on bandwidth and throughput formula: average_io_size = bandwidth / throughput :param prev: prev resource, not used :param curr: current resource :param counters: two stats, bandwidth in MB and throughput count :return: value,...
calculate the io size based on bandwidth and throughput formula: average_io_size = bandwidth / throughput :param prev: prev resource, not used :param curr: current resource :param counters: two stats, bandwidth in MB and throughput count :return: value, NaN if invalid
entailment
def list_files(tag='', sat_id=None, data_path=None, format_str=None): """Return a Pandas Series of every file for chosen satellite data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are '' and 'ascii'. If '' is specified, the primary dat...
Return a Pandas Series of every file for chosen satellite data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are '' and 'ascii'. If '' is specified, the primary data type (ascii) is loaded. (default='') sat_id : (string or NoneTy...
entailment
def load(fnames, tag=None, sat_id=None): """Load CHAMP STAR files Parameters ------------ fnames : (pandas.Series) Series of filenames tag : (str or NoneType) tag or None (default=None) sat_id : (str or NoneType) satellite id or None (default=None) Returns -----...
Load CHAMP STAR files Parameters ------------ fnames : (pandas.Series) Series of filenames tag : (str or NoneType) tag or None (default=None) sat_id : (str or NoneType) satellite id or None (default=None) Returns --------- data : (pandas.DataFrame) Objec...
entailment
def _assign_funcs(self, by_name=False, inst_module=None): """Assign all external science instrument methods to Instrument object. """ import importlib # set defaults self._list_rtn = self._pass_func self._load_rtn = self._pass_func self._default_rtn = self...
Assign all external science instrument methods to Instrument object.
entailment
def _load_data(self, date=None, fid=None): """ Load data for an instrument on given date or fid, dependng upon input. Parameters ------------ date : (dt.datetime.date object or NoneType) file date fid : (int or NoneType) filename index value ...
Load data for an instrument on given date or fid, dependng upon input. Parameters ------------ date : (dt.datetime.date object or NoneType) file date fid : (int or NoneType) filename index value Returns -------- data : (pds.DataFrame) ...
entailment
def _load_next(self): """Load the next days data (or file) without incrementing the date. Repeated calls will not advance date/file and will produce the same data Uses info stored in object to either increment the date, or the file. Looks for self._load_by_date flag. ...
Load the next days data (or file) without incrementing the date. Repeated calls will not advance date/file and will produce the same data Uses info stored in object to either increment the date, or the file. Looks for self._load_by_date flag.
entailment
def _load_prev(self): """Load the next days data (or file) without decrementing the date. Repeated calls will not decrement date/file and will produce the same data Uses info stored in object to either decrement the date, or the file. Looks for self._load_by_date flag. ...
Load the next days data (or file) without decrementing the date. Repeated calls will not decrement date/file and will produce the same data Uses info stored in object to either decrement the date, or the file. Looks for self._load_by_date flag.
entailment
def load(self, yr=None, doy=None, date=None, fname=None, fid=None, verifyPad=False): """Load instrument data into Instrument object .data. Parameters ---------- yr : integer year for desired data doy : integer day of year date : date...
Load instrument data into Instrument object .data. Parameters ---------- yr : integer year for desired data doy : integer day of year date : datetime object date to load fname : 'string' filename to be loaded verify...
entailment
def download(self, start, stop, freq='D', user=None, password=None, **kwargs): """Download data for given Instrument object from start to stop. Parameters ---------- start : pandas.datetime start date to download data stop : pandas.datetime ...
Download data for given Instrument object from start to stop. Parameters ---------- start : pandas.datetime start date to download data stop : pandas.datetime stop date to download data freq : string Stepsize between dates for season, ...
entailment
def next(self, verifyPad=False): """Manually iterate through the data loaded in Instrument object. Bounds of iteration and iteration type (day/file) are set by `bounds` attribute. Note ---- If there were no previous calls to load then the first...
Manually iterate through the data loaded in Instrument object. Bounds of iteration and iteration type (day/file) are set by `bounds` attribute. Note ---- If there were no previous calls to load then the first day(default)/file will be loaded.
entailment
def _get_var_type_code(self, coltype): '''Determines the two-character type code for a given variable type Parameters ---------- coltype : type or np.dtype The type of the variable Returns ------- str The variable type code for the given ...
Determines the two-character type code for a given variable type Parameters ---------- coltype : type or np.dtype The type of the variable Returns ------- str The variable type code for the given type
entailment