code stringlengths 1 18.2k |
|---|
def archive(self): """Archives an experiment""" pipe = self.redis.pipeline(transaction=True) pipe.srem(ACTIVE_EXPERIMENTS_REDIS_KEY, self.name) pipe.sadd(ARCHIVED_EXPERIMENTS_REDIS_KEY, self.name) pipe.execute() |
def add_choice(self, choice_name): """Adds a choice for the experiment""" if not ALLOWED_NAMES.match(choice_name): raise ExperimentException(self.name, "Illegal choice name: %s" % choice_name) if choice_name in self.choice_names: raise ExperimentException(self.name, "Choice already exists: %s" % choice_name) self.choic... |
def remove_choice(self, choice_name): """Adds a choice for the experiment""" self.choice_names.remove(choice_name) self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "choices", escape.json_encode(self.choice_names)) self.refresh() |
def add_play(self, choice, count=1): """Increments the play count for a given experiment choice""" self.redis.hincrby(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "%s:plays" % choice, count) self._choices = None |
def compute_default_choice(self): """Computes and sets the default choice""" choices = self.choices if len(choices) == 0: return None high_choice = max(choices, key=lambda choice: choice.performance) self.redis.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "default-choice", high_choice.name) self.refresh() return hig... |
def refresh(self): """Re-pulls the data from redis""" redis_key = EXPERIMENT_REDIS_KEY_TEMPLATE % self.experiment.name self.plays = int(self.experiment.redis.hget(redis_key, "%s:plays" % self.name) or 0) self.rewards = int(self.experiment.redis.hget(redis_key, "%s:rewards" % self.name) or 0) self.performance = float(se... |
def fetch(self, pageNum, itemsPerPage): """Intermediate fetching Args: pageNum (int): Page number itemsPerPage (int): Number of Users per Page Returns: dict: Response payload """ return self.get_all_alerts(self.status, pageNum, itemsPerPage) |
async def await_all(): ''' Simple utility function that drains all pending tasks ''' tasks = asyncio.Task.all_tasks() for task in tasks: try: await task except RuntimeError as e: # Python 3.5.x: Error if attempting to await parent task if 'Task cannot await on itself' not in str(e): raise e except AssertionError as e: ... |
def coerce_to_synchronous(func): ''' Given a function that might be async, wrap it in an explicit loop so it can be run in a synchronous context. ''' if inspect.iscoroutinefunction(func): @functools.wraps(func) def sync_wrapper(*args, **kwargs): loop = asyncio.get_event_loop() try: loop.run_until_complete(func(*args, *... |
def diff(a, b, segmenter=None): """ Performs a diff comparison between two sequences of tokens (`a` and `b`) using `segmenter` to cluster and match :class:`deltas.MatchableSegment`. :Example: >>> from deltas import segment_matcher, text_split >>> >>> a = text_split.tokenize("This is some text. This is some other text."... |
a, b = list(a), list(b) segmenter = segmenter or SEGMENTER # Cluster the input tokens a_segments = segmenter.segment(a) b_segments = segmenter.segment(b) return diff_segments(a_segments, b_segments) |
def diff_segments(a_segments, b_segments): """ Performs a diff comparison between two pre-clustered :class:`deltas.Segment` trees. In most cases, segmentation takes 100X more time than actually performing the diff. :Parameters: a_segments : :class:`deltas.Segment` An initial sequence b_segments : :class:`deltas.Segment... |
def process(texts, *args, **kwargs): """ Processes a single sequence of texts with a :class:`~deltas.SegmentMatcher`. :Parameters: texts : `iterable`(`str`) sequence of texts args : `tuple` passed to :class:`~deltas.SegmentMatcher`'s constructor kwaths : `dict` passed to :class:`~deltas.SegmentMatcher`'s constructor ""... |
def _get_matchable_segments(segments): """ Performs a depth-first search of the segment tree to get all matchable segments. """ for subsegment in segments: if isinstance(subsegment, Token): break # No tokens allowed next to segments if isinstance(subsegment, Segment): if isinstance(subsegment, MatchableSegment): yield ... |
def forwards(self, orm): "Write your forwards methods here." for document in orm['document_library.Document'].objects.all(): self.migrate_placeholder( orm, document, 'content', 'document_library_content', 'content') |
def make_command_line(predictions='/dev/stdout', quiet=True, save_resume=True, q_colon=None, **kwargs ): """Construct a command line for VW, with each named argument corresponding to a VW option. Single character keys are mapped to single-dash options, e.g. 'b=20' yields '-b 20', while multiple character keys map to do... |
to validate the inputs or ensure they are compatible with Wabbit Wappa. Outputs a command line string. """ args = ['vw'] if q_colon: kwargs['q:'] = q_colon kwargs['predictions'] = predictions kwargs['quiet'] = quiet kwargs['save_resume'] = save_resume for key, value in kwargs.items(): if len(key)==1: option = '-{}'.for... |
def add_features(self, features): """Add features to this namespace. features: An iterable of features. A feature may be either 1) A VW label (not containing characters from escape_dict.keys(), unless 'escape' mode is on) 2) A tuple (label, value) where value is any float """ for feature in features: if isinstance(feat... |
def add_feature(self, label, value=None): """ label: A VW label (not containing characters from escape_dict.keys(), unless 'escape' mode is on) value: float giving the weight or magnitude of this feature """ if self.escape: label = escape_vw_string(label) elif self.validate: validate_vw_string(label) feature = (label, ... |
def to_string(self): """Export this namespace to a string suitable for incorporation in a VW example line, e.g. 'MetricFeatures:3.28 height:1.5 length:2.0 ' """ if self._string is None: tokens = [] if self.name: if self.scale: token = self.name + ':' + str(self.scale) else: token = self.name else: token = '' # Spacing ... |
def export_features(self, delimiter='\\'): """Export the features from this namespace as a list of feature tokens with the namespace name prepended (delimited by 'delimiter'). Example: >>> namespace = Namespace('name1', features=['feature1', 'feature2']) >>> print namespace.export_features() ['name1\\feature1', 'name1\... |
def send_line(self, line, parse_result=True): """Submit a raw line of text to the VW instance, returning a VWResult() object. If 'parse_result' is False, ignore the result and return None. """ self.vw_process.sendline(line) # Send line, along with newline result = self._get_response(parse_result=parse_result) return re... |
def _get_response(self, parse_result=True): """If 'parse_result' is False, ignore the received output and return None.""" # expect_exact is faster than just exact, and fine for our purpose # (http://pexpect.readthedocs.org/en/latest/api/pexpect.html#pexpect.spawn.expect_exact) # searchwindowsize and other attributes ma... |
def send_example(self, *args, **kwargs ): """Send a labeled or unlabeled example to the VW instance. If 'parse_result' kwarg is False, ignore the result and return None. All other parameters are passed to self.send_line(). Returns a VWResult object. """ # Pop out the keyword argument 'parse_result' if given parse_resul... |
def make_line(self, response=None, importance=None, base=None, tag=None, features=None, namespaces=None, ): """Makes and returns an example string in VW syntax. If given, 'response', 'importance', 'base', and 'tag' are used to label the example. Features for the example come from any given features or namespaces, as we... |
# Tags are unambiguous if given a ' prefix tokens.append(token) else: token = "" # Spacing element to avoid ambiguity in parsing tokens.append(token) substring = ' '.join(tokens) substrings.append(substring) if self.namespaces: for namespace in self.namespaces: substring = namespace.to_string() substrings.append(substr... |
def add_namespace(self, *args, **kwargs): """Accepts two calling patterns: add_namespace(namespace): queue a preexisting namespace onto this VW instance. add_namespace(name, scale, features, ...): Pass all args and kwargs to the Namespace constructor to make a new Namespace instance, and queue it to this VW instance. R... |
def get_prediction(self, features=None, tag=None, namespaces=None): """Send an unlabeled example to the trained VW instance. Uses any given features or namespaces, as well as any previously added namespaces (using them up in the process). Returns a VWResult object.""" if features is not None: namespace = Namespace(feat... |
def save_model(self, model_filename): """Pass a "command example" to the VW subprocess requesting that the current model be serialized to model_filename immediately. """ line = "save_{}|".format(model_filename) self.vw_process.sendline(line) |
def route_path(self, path): ''' Hacky function that's presently only useful for testing, gets the view that handles the given path. Later may be incorporated into the URL routing ''' path = path.strip('/') name, _, subpath = path.partition('/') for service in singletons.settings.load_all('SERVICES'): if service.SERVICE... |
def assign_taxonomy(dataPath, reference_sequences_fp, id_to_taxonomy_fp, read_1_seqs_fp, read_2_seqs_fp, single_ok=False, no_single_ok_generic=False, header_id_regex=None, read_id_regex = "\S+\s+(\S+)", amplicon_id_regex = "(\S+)\s+(\S+?)\/", output_fp=None, log_path=None, HALT_EXEC=False, base_tmp_dir = '/tmp'): """As... |
case is that the regex extracts the amplicon ID from the second field # Use lookup table read_1_id_to_orig_id = {} readIdExtractor = re.compile(read_id_regex) # OTU clustering produces ">clusterID read_1_id" data = open(dataPath,'r') for seq_id, seq in parse_fasta(data): # apply the regex extract = readIdExtractor.matc... |
{} ampliconIdExtractor = re.compile(amplicon_id_regex) # split_libraries produces >read_1_id ampliconID/1 ... // see also assign_taxonomy 631 read_1_data = open(read_1_seqs_fp,'r') for seq_id, seq in parse_fasta(read_1_data): # apply the regex extract = ampliconIdExtractor.match(seq_id) if extract is None: stderr.write... |
errString=''.join(app_result['StdErr'].readlines()) + '\n' f.write(errString) f.close() assignments = {} # restore original sequence IDs with spaces for line in app_result['Assignments']: toks = line.strip().split('\t') rtax_id = toks.pop(0) if len(toks): bestpcid = toks.pop(0) # ignored lineage = toks # RTAX does not ... |
raise OSError("Can't open output file for writing: %s" % output_fp) for seq_id, assignment in assignments.items(): lineage, confidence = assignment output_file.write( '%s\t%s\t%1.3f\n' % (seq_id, lineage, confidence)) output_file.close() return None else: return assignments finally: try: rmtree(my_tmp_dir) except OSErr... |
def pair_looper(iterator): ''' Loop through iterator yielding items in adjacent pairs ''' left = START for item in iterator: if left is not START: yield (left, item) left = item |
def batch_gen(data, batch_size): ''' Usage:: for batch in batch_gen(iter, 100): do_something(batch) ''' data = data or [] for i in range(0, len(data), batch_size): yield data[i:i + batch_size] |
def clear_stale_pids(pids, pid_dir='/tmp', prefix='', multi=False): 'check for and remove any pids which have no corresponding process' if isinstance(pids, (int, float, long)): pids = [pids] pids = str2list(pids, map_=unicode) procs = map(unicode, os.listdir('/proc')) running = [pid for pid in pids if pid in procs] log... |
def daemonize(pid_file=None, cwd=None): """ Detach a process from the controlling terminal and run it in the background as a daemon. Modified version of: code.activestate.com/recipes/278731-creating-a-daemon-the-python-way/ author = "Chad J. Schroeder" copyright = "Copyright (C) 2005 Chad J. Schroeder" """ cwd = cwd or... |
through and close all file descriptors. for fd in range(0, maxfd): try: os.close(fd) except OSError: # ERROR, fd wasn't open to begin with (ignored) pass os.open('/dev/null', os.O_RDWR) # standard input (0) # Duplicate standard input to standard output and standard error. os.dup2(0, 1) # standard output (1) os.dup2(0, ... |
def cube_pkg_mod_cls(cube): ''' Used to dynamically importing cube classes based on string slug name. Converts 'pkg_mod' -> pkg, mod, Cls eg: tw_tweet -> tw, tweet, Tweet Assumes `Metrique Cube Naming Convention` is used :param cube: cube name to use when searching for cube pkg.mod.class to load ''' _cube = cube.split(... |
def debug_setup(logger=None, level=None, log2file=None, log_file=None, log_format=None, log_dir=None, log2stdout=None, truncate=False): ''' Local object instance logger setup. Verbosity levels are determined as such:: if level in [-1, False]: logger.setLevel(logging.WARN) elif level in [0, None]: logger.setLevel(loggin... |
[] if log2file: log_dir = log_dir or LOGS_DIR log_file = log_file or 'metrique' log_file = os.path.join(log_dir, log_file) if truncate: # clear the existing data before writing (truncate) open(log_file, 'w+').close() hdlr = logging.FileHandler(log_file) hdlr.setFormatter(log_format) logger.addHandler(hdlr) else: log2st... |
def dt2ts(dt, drop_micro=False): ''' convert datetime objects to timestamp seconds (float) ''' is_true(HAS_DATEUTIL, "`pip install python_dateutil` required") if is_empty(dt, except_=False): ts = None elif isinstance(dt, (int, long, float)): # its a ts already ts = float(dt) elif isinstance(dt, basestring): # convert t... |
def get_cube(cube, init=False, pkgs=None, cube_paths=None, config=None, backends=None, **kwargs): ''' Dynamically locate and load a metrique cube :param cube: name of the cube class to import from given module :param init: flag to request initialized instance or uninitialized class :param config: config dict to pass on... |
paths which don't already exist in sys.path to sys.path [sys.path.append(path) for path in cube_paths if path not in sys.path] pkgs = pkgs + DEFAULT_PKGS err = False for pkg in pkgs: try: _cube = _load_cube_pkg(pkg, cube) except ImportError as err: _cube = None if _cube: break else: logger.error(err) raise RuntimeError... |
def get_timezone_converter(from_timezone, to_tz=None, tz_aware=False): ''' return a function that converts a given datetime object from a timezone to utc :param from_timezone: timezone name as string ''' if not from_timezone: return None is_true(HAS_DATEUTIL, "`pip install python_dateutil` required") is_true(HAS_PYTZ, ... |
def git_clone(uri, pull=True, reflect=False, cache_dir=None, chdir=True): ''' Given a git repo, clone (cache) it locally. :param uri: git repo uri :param pull: whether to pull after cloning (or loading cache) ''' cache_dir = cache_dir or CACHE_DIR # make the uri safe for filesystems repo_path = os.path.expanduser(os.pa... |
def is_empty(value, msg=None, except_=None, inc_zeros=True): ''' is defined, but null or empty like value ''' if hasattr(value, 'empty'): # dataframes must check for .empty # since they don't define truth value attr # take the negative, since below we're # checking for cases where value 'is_null' value = not bool(value... |
def is_null(value, msg=None, except_=None): ''' ie, "is not defined" ''' # dataframes, even if empty, are not considered null value = False if hasattr(value, 'empty') else value result = bool( value is None or value != value or repr(value) == 'NaT') if except_: return is_true(result, msg=msg, except_=except_) else: ret... |
def json_encode_default(obj): ''' Convert datetime.datetime to timestamp :param obj: value to (possibly) convert ''' if isinstance(obj, (datetime, date)): result = dt2ts(obj) else: result = json_encoder.default(obj) return to_encoding(result) |
def jsonhash(obj, root=True, exclude=None, hash_func=_jsonhash_sha1): ''' calculate the objects hash based on all field values ''' if isinstance(obj, Mapping): # assumption: using in against set() is faster than in against list() if root and exclude: obj = {k: v for k, v in obj.iteritems() if k not in exclude} # frozen... |
= obj if root: result = unicode(hash_func(result)) return result |
def load(path, filetype=None, as_df=False, retries=None, _oid=None, quiet=False, **kwargs): '''Load multiple files from various file types automatically. Supports glob paths, eg:: path = 'data/*.csv' Filetypes are autodetected by common extension strings. Currently supports loadings from: * csv (pd.read_csv) * json (pd... |
% path) _path = urlretrieve(path, retries) logger.debug('%s saved to tmp file: %s' % (path, _path)) try: objects = load_file(_path, filetype, **kwargs) finally: remove_file(_path) else: path = re.sub('^file://', '', path) path = os.path.expanduser(path) # assume relative to cwd if not already absolute path path = path ... |
else: return objects |
def _load_cube_pkg(pkg, cube): ''' NOTE: all items in fromlist must be strings ''' try: # First, assume the cube module is available # with the name exactly as written fromlist = map(str, [cube]) mcubes = __import__(pkg, fromlist=fromlist) return getattr(mcubes, cube) except AttributeError: # if that fails, try to gues... |
def read_file(rel_path, paths=None, raw=False, as_list=False, as_iter=False, *args, **kwargs): ''' find a file that lives somewhere within a set of paths and return its contents. Default paths include 'static_dir' ''' if not rel_path: raise ValueError("rel_path can not be null!") paths = str2list(paths) # try looking t... |
= fd.readlines() if as_list: return fd_lines else: return ''.join(fd_lines) |
def rupdate(source, target): ''' recursively update nested dictionaries see: http://stackoverflow.com/a/3233356/1289080 ''' for k, v in target.iteritems(): if isinstance(v, Mapping): r = rupdate(source.get(k, {}), v) source[k] = r else: source[k] = target[k] return source |
def safestr(str_): ''' get back an alphanumeric only version of source ''' str_ = str_ or "" return "".join(x for x in str_ if x.isalnum()) |
def ts2dt(ts, milli=False, tz_aware=False): ''' convert timestamp int's (seconds) to datetime objects ''' # anything already a datetime will still be returned # tz_aware, if set to true is_true(HAS_DATEUTIL, "`pip install python_dateutil` required") if isinstance(ts, (datetime, date)): pass elif is_empty(ts, except_=Fa... |
def urlretrieve(uri, saveas=None, retries=3, cache_dir=None): '''urllib.urlretrieve wrapper''' retries = int(retries) if retries else 3 # FIXME: make random filename (saveas) in cache_dir... # cache_dir = cache_dir or CACHE_DIR while retries: try: _path, headers = urllib.urlretrieve(uri, saveas) except Exception as e: ... |
def forwards(self, orm): "Write your forwards methods here." for category in orm['document_library.DocumentCategory'].objects.all(): category.is_published = True category.save() |
def reverse_media_url(target_type, url_string, *args, **kwargs): ''' Given a target type and an resource URL, generates a valid URL to this via ''' args_str = '<%s>' % '><'.join(args) kwargs_str = '<%s>' % '><'.join('%s:%s' % pair for pair in kwargs.items()) url_str = ''.join([url_string, args_str, kwargs_str]) normali... |
def _isbn_cleanse(isbn, checksum=True): """Check ISBN is a string, and passes basic sanity checks. Args: isbn (str): SBN, ISBN-10 or ISBN-13 checksum (bool): ``True`` if ``isbn`` includes checksum character Returns: ``str``: ISBN with hyphenation removed, including when called with a SBN Raises: TypeError: ``isbn`` is ... |
(isbn[-1].isdigit() or isbn[-1] in 'Xx'): raise IsbnError('non-digit or X checksum') elif len(isbn) == 13: if not isbn[-1].isdigit(): raise IsbnError('non-digit checksum') if not isbn.startswith(('978', '979')): raise IsbnError('invalid Bookland region') else: raise IsbnError('ISBN must be either 10 or 13 characters lo... |
def calculate_checksum(isbn): """Calculate ISBN checksum. Args: isbn (str): SBN, ISBN-10 or ISBN-13 Returns: ``str``: Checksum for given ISBN or SBN """ isbn = [int(i) for i in _isbn_cleanse(isbn, checksum=False)] if len(isbn) == 9: products = [x * y for x, y in zip(isbn, range(1, 10))] check = sum(products) % 11 if ch... |
def convert(isbn, code='978'): """Convert ISBNs between ISBN-10 and ISBN-13. Note: No attempt to hyphenate converted ISBNs is made, because the specification requires that *any* hyphenation must be correct but allows ISBNs without hyphenation. Args: isbn (str): SBN, ISBN-10 or ISBN-13 code (str): EAN Bookland code Retu... |
def calculate_checksum(self): """Calculate ISBN checksum. Returns: ``str``: ISBN checksum value """ if len(self.isbn) in (9, 12): return calculate_checksum(self.isbn) else: return calculate_checksum(self.isbn[:-1]) |
def to_url(self, site='amazon', country='us'): """Generate a link to an online book site. Args: site (str): Site to create link to country (str): Country specific version of ``site`` Returns: ``str``: URL on ``site`` for book Raises: SiteError: Unknown site value CountryError: Unknown country value """ try: try: url, t... |
def _tokenize(self, text, token_class=None): """ Tokenizes a text :Returns: A `list` of tokens """ token_class = token_class or Token tokens = {} for i, match in enumerate(self.regex.finditer(text)): value = match.group(0) try: token = tokens[value] except KeyError: type = match.lastgroup token = token_class(value, typ... |
def _parse_cli_facter_results(facter_results): '''Parse key value pairs printed with "=>" separators. YAML is preferred output scheme for facter. >>> list(_parse_cli_facter_results("""foo => bar ... baz => 1 ... foo_bar => True""")) [('foo', 'bar'), ('baz', '1'), ('foo_bar', 'True')] >>> list(_parse_cli_facter_results(... |
def run_facter(self, key=None): """Run the facter executable with an optional specfic fact. Output is parsed to yaml if available and selected. Puppet facts are always selected. Returns a dictionary if no key is given, and the value if a key is passed.""" args = [self.facter_path] #this seems to not cause problems, but... |
def has_cache(self): """Intended to be called before any call that might access the cache. If the cache is not selected, then returns False, otherwise the cache is build if needed and returns True.""" if not self.cache_enabled: return False if self._cache is None: self.build_cache() return True |
def lookup(self, fact, cache=True): """Return the value of a given fact and raise a KeyError if it is not available. If `cache` is False, force the lookup of the fact.""" if (not cache) or (not self.has_cache()): val = self.run_facter(fact) if val is None or val == '': raise KeyError(fact) return val return self._cache... |
def _reset(self) -> None: """Reset some of the state in the class for multi-searches.""" self.project: str = namesgenerator.get_random_name() self._processed: List = list() self.results: List = list() |
def _config_bootstrap(self) -> None: """Handle the basic setup of the tool prior to user control. Bootstrap will load all the available modules for searching and set them up for use by this main class. """ if self.output: self.folder: str = os.getcwd() + "/" + self.project os.mkdir(self.folder) |
def _dyn_loader(self, module: str, kwargs: str): """Dynamically load a specific module instance.""" package_directory: str = os.path.dirname(os.path.abspath(__file__)) modules: str = package_directory + "/modules" module = module + ".py" if module not in os.listdir(modules): raise Exception("Module %s is not valid" % m... |
def _job_handler(self) -> bool: """Process the work items.""" while True: try: task = self._unfullfilled.get_nowait() except queue.Empty: break else: self._log.debug("Job: %s" % str(task)) engine = self._dyn_loader(task['engine'], task) task['start_time'] = now_time() results = engine.search() task['end_time'] = now_ti... |
def _save(self) -> None: """Save output to a directory.""" self._log.info("Saving results to '%s'" % self.folder) path: str = self.folder + "/" for job in self.results: if job['domain'] in self.saved: continue job['start_time'] = str_datetime(job['start_time']) job['end_time'] = str_datetime(job['end_time']) jid: int =... |
def search(self, jobs: List[Dict[str, str]]) -> None: """Perform searches based on job orders.""" if not isinstance(jobs, list): raise Exception("Jobs must be of type list.") self._log.info("Project: %s" % self.project) self._log.info("Processing jobs: %d", len(jobs)) for _, job in enumerate(jobs): self._unfullfilled.p... |
def geocentric_to_ecef(latitude, longitude, altitude): """Convert geocentric coordinates into ECEF Parameters ---------- latitude : float or array_like Geocentric latitude (degrees) longitude : float or array_like Geocentric longitude (degrees) altitude : float or array_like Height (km) above presumed spherical Earth w... |
def ecef_to_geocentric(x, y, z, ref_height=None): """Convert ECEF into geocentric coordinates Parameters ---------- x : float or array_like ECEF-X in km y : float or array_like ECEF-Y in km z : float or array_like ECEF-Z in km ref_height : float or array_like Reference radius used for calculating height. Defaults to av... |
def geodetic_to_ecef(latitude, longitude, altitude): """Convert WGS84 geodetic coordinates into ECEF Parameters ---------- latitude : float or array_like Geodetic latitude (degrees) longitude : float or array_like Geodetic longitude (degrees) altitude : float or array_like Geodetic Height (km) above WGS84 reference ell... |
def ecef_to_geodetic(x, y, z, method=None): """Convert ECEF into Geodetic WGS84 coordinates Parameters ---------- x : float or array_like ECEF-X in km y : float or array_like ECEF-Y in km z : float or array_like ECEF-Z in km method : 'iterative' or 'closed' ('closed' is deafult) String selects method of conversion. Clo... |
np.sqrt(x ** 2 + y ** 2) # closed form solution # a source, http://www.epsg.org/Portals/0/373-07-2.pdf , page 96 section 2.2.1 if method == 'closed': e_prime = np.sqrt((earth_a**2 - earth_b**2) / earth_b**2) theta = np.arctan2(z*earth_a, p*earth_b) latitude = np.arctan2(z + e_prime**2*earth_b*np.sin(theta)**3, p - e2*e... |
height update h = p / np.cos(latitude) - r_n return np.rad2deg(latitude), np.rad2deg(longitude), h |
def enu_to_ecef_vector(east, north, up, glat, glong): """Converts vector from East, North, Up components to ECEF Position of vector in geospace may be specified in either geocentric or geodetic coordinates, with corresponding expression of the vector using radial or ellipsoidal unit vectors. Parameters ---------- east ... |
= east*np.cos(rlon) - north*np.sin(rlon)*np.sin(rlat) + up*np.sin(rlon)*np.cos(rlat) z = north*np.cos(rlat) + up*np.sin(rlat) return x, y, z |
def project_ecef_vector_onto_basis(x, y, z, xx, xy, xz, yx, yy, yz, zx, zy, zz): """Projects vector in ecef onto different basis, with components also expressed in ECEF Parameters ---------- x : float or array-like ECEF-X component of vector y : float or array-like ECEF-Y component of vector z : float or array-like ECE... |
def normalize_vector(x, y, z): """ Normalizes vector to produce a unit vector. Parameters ---------- x : float or array-like X component of vector y : float or array-like Y component of vector z : float or array-like Z component of vector Returns ------- x, y, z Unit vector x,y,z components """ mag = np.sqrt(x**2 + y**... |
def cross_product(x1, y1, z1, x2, y2, z2): """ Cross product of two vectors, v1 x v2 Parameters ---------- x1 : float or array-like X component of vector 1 y1 : float or array-like Y component of vector 1 z1 : float or array-like Z component of vector 1 x2 : float or array-like X component of vector 2 y2 : float or arr... |
def field_line_trace(init, date, direction, height, steps=None, max_steps=1E4, step_size=10., recursive_loop_count=None, recurse=True): """Perform field line tracing using IGRF and scipy.integrate.odeint. Parameters ---------- init : array-like of floats Position to begin field line tracing from in ECEF (x,y,z) km date... |
should be taken step_size : float Distance in km for each large integration step. Multiple substeps are taken as determined by scipy.integrate.odeint Returns ------- numpy array 2D array. [0,:] has the x,y,z location for initial point [:,0] is the x positions over the integration. Positions are reported in ECEF (km). "... |
check that we reached final altitude check = trace_north[-1, :] x, y, z = ecef_to_geodetic(*check) if height == 0: check_height = 1. else: check_height = height # fortran integration gets close to target height if recurse & (z > check_height*1.000001): if (recursive_loop_count < 1000): # When we have not reached the re... |
below target # height # code also introduces a variable length return, though I suppose # that already exists with the recursive functionality # x, y, z = ecef_to_geodetic(trace_north[:,0], trace_north[:,1], trace_north[:,2]) # idx = np.argmin(np.abs(check_height - z)) return trace_north |
def full_field_line(init, date, height, step_size=100., max_steps=1000, steps=None, **kwargs): """Perform field line tracing using IGRF and scipy.integrate.odeint. Parameters ---------- init : array-like of floats Position to begin field line tracing from in ECEF (x,y,z) km date : datetime or float Date to perform trac... |
steps=np.arange(max_steps). Two traces are made, one north, the other south, thus the output array could have double max_steps, or more via recursion. Returns ------- numpy array 2D array. [0,:] has the x,y,z location for southern footpoint [:,0] is the x positions over the integration. Positions are reported in ECEF (... |
def calculate_mag_drift_unit_vectors_ecef(latitude, longitude, altitude, datetimes, steps=None, max_steps=1000, step_size=100., ref_height=120., filter_zonal=True): """Calculates unit vectors expressing the ion drift coordinate system organized by the geomagnetic field. Unit vectors are expressed in ECEF coordinates. N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.