code stringlengths 1 18.2k |
|---|
def users_list(self, *args): """Display a list of connected users""" if len(self._users) == 0: self.log('No users connected') else: self.log(self._users, pretty=True) |
def sourcess_list(self, *args): """Display a list of all registered events""" from pprint import pprint sources = {} sources.update(self.authorized_events) sources.update(self.anonymous_events) for source in sources: pprint(source) |
def events_list(self, *args): """Display a list of all registered events""" def merge(a, b, path=None): "merges b into a" if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge(a[key], b[key], path + [str(key)]) elif a[key] == b[key]: pass # same leaf value... |
= b[key] return a events = {} sources = merge(self.authorized_events, self.anonymous_events) for source, source_events in sources.items(): events[source] = [] for item in source_events: events[source].append(item) self.log(events, pretty=True) |
def who(self, *args): """Display a table of connected users and clients""" if len(self._users) == 0: self.log('No users connected') if len(self._clients) == 0: self.log('No clients connected') return Row = namedtuple("Row", ['User', 'Client', 'IP']) rows = [] for user in self._users.values(): for key, client in self._c... |
= Row('ANON', key, client.ip) rows.append(row) self.log("\n" + std_table(rows)) |
def disconnect(self, sock): """Handles socket disconnections""" self.log("Disconnect ", sock, lvl=debug) try: if sock in self._sockets: self.log("Getting socket", lvl=debug) sockobj = self._sockets[sock] self.log("Getting clientuuid", lvl=debug) clientuuid = sockobj.clientuuid self.log("getting useruuid", lvl=debug) us... |
Exception as e: self.log("Couldn't clean up logged in user! ", self._users[useruuid], e, type(e), lvl=critical) self.log("Deleting Client (", self._clients.keys, ")", lvl=debug) del self._clients[clientuuid] self.log("Deleting Socket", lvl=debug) del self._sockets[sock] except Exception as e: self.log("Error during dis... |
def _logoutclient(self, useruuid, clientuuid): """Log out a client and possibly associated user""" self.log("Cleaning up client of logged in user.", lvl=debug) try: self._users[useruuid].clients.remove(clientuuid) if len(self._users[useruuid].clients) == 0: self.log("Last client of user disconnected.", lvl=verbose) sel... |
def connect(self, *args): """Registers new sockets and their clients and allocates uuids""" self.log("Connect ", args, lvl=verbose) try: sock = args[0] ip = args[1] if sock not in self._sockets: self.log("New client connected:", ip, lvl=debug) clientuuid = str(uuid4()) self._sockets[sock] = Socket(ip, clientuuid) # Key... |
clientuuid, lvl=debug) else: self.log("Old IP reconnected!", lvl=warn) # self.fireEvent(write(sock, "Another client is # connecting from your IP!")) # self._sockets[sock] = (ip, uuid.uuid4()) except Exception as e: self.log("Error during connect: ", e, type(e), lvl=critical) |
def send(self, event): """Sends a packet to an already known user or one of his clients by UUID""" try: jsonpacket = json.dumps(event.packet, cls=ComplexEncoder) if event.sendtype == "user": # TODO: I think, caching a user name <-> uuid table would # make sense instead of looking this up all the time. if event.uuid is ... |
'uuid': event.uuid }) if userobject is None: self.log("No user by that name known.", lvl=warn) return else: uuid = userobject.uuid self.log("Broadcasting to all of users clients: '%s': '%s" % ( uuid, str(event.packet)[:20]), lvl=network) if uuid not in self._users: self.log("User not connected!", event, lvl=critical) r... |
"wsserver") else: self.log("Sending raw data to client") self.fireEvent(write(sock, event.packet), "wsserver") else: # only to client self.log("Sending to user's client: '%s': '%s'" % ( event.uuid, jsonpacket[:20]), lvl=network) if event.uuid not in self._clients: if not event.fail_quiet: self.log("Unknown client!", ev... |
e: self.log("Exception during sending: %s (%s)" % (e, type(e)), lvl=critical, exc=True) |
def broadcast(self, event): """Broadcasts an event either to all users or clients, depending on event flag""" try: if event.broadcasttype == "users": if len(self._users) > 0: self.log("Broadcasting to all users:", event.content, lvl=network) for useruuid in self._users.keys(): self.fireEvent( send(useruuid, event.conte... |
for client in self._clients.values(): self.fireEvent(write(client.sock, event.content), "wsserver") # else: # self.log("Not broadcasting, no clients # connected.", # lvl=debug) elif event.broadcasttype == "socks": if len(self._sockets) > 0: self.log("Emergency?! Broadcasting to all sockets: ", event.content) for sock i... |
def _checkPermissions(self, user, event): """Checks if the user has in any role that allows to fire the event.""" for role in user.account.roles: if role in event.roles: self.log('Access granted', lvl=verbose) return True self.log('Access denied', lvl=verbose) return False |
def _handleAuthorizedEvents(self, component, action, data, user, client): """Isolated communication link for authorized events.""" try: if component == "debugger": self.log(component, action, data, user, client, lvl=info) if not user and component in self.authorized_events.keys(): self.log("Unknown client tried to do a... |
'component': 'hfos.ui.clientmanager', 'action': 'Permission', 'data': _('You have no role that allows this action.', lang='de') } self.fireEvent(send(event.client.uuid, result)) return self.log("Firing authorized event: ", component, action, str(data)[:100], lvl=debug) # self.log("", (user, action, data, client), lvl=c... |
def _handleAnonymousEvents(self, component, action, data, client): """Handler for anonymous (public) events""" try: event = self.anonymous_events[component][action]['event'] self.log("Firing anonymous event: ", component, action, str(data)[:20], lvl=network) # self.log("", (user, action, data, client), lvl=critical) se... |
def _handleAuthenticationEvents(self, requestdata, requestaction, clientuuid, sock): """Handler for authentication events""" # TODO: Move this stuff over to ./auth.py if requestaction in ("login", "autologin"): try: self.log("Login request", lvl=verbose) if requestaction == "autologin": username = password = None reque... |
auto = False self.log("Auth request by", username, lvl=verbose) self.fireEvent(authenticationrequest( username, password, clientuuid, requestedclientuuid, sock, auto, ), "auth") return except Exception as e: self.log("Login failed: ", e, type(e), lvl=warn, exc=True) elif requestaction == "logout": self.log("User logged... |
connected!", lvl=warn) except Exception as e: self.log("Error during client logout: ", e, type(e), lvl=error, exc=True) else: self.log("Unsupported auth action requested:", requestaction, lvl=warn) |
def _reset_flood_offenders(self, *args): """Resets the list of flood offenders on event trigger""" offenders = [] # self.log('Resetting flood offenders') for offender, offence_time in self._flooding.items(): if time() - offence_time < 10: self.log('Removed offender from flood list:', offender) offenders.append(offender... |
def _check_flood_protection(self, component, action, clientuuid): """Checks if any clients have been flooding the node""" if clientuuid not in self._flood_counter: self._flood_counter[clientuuid] = 0 self._flood_counter[clientuuid] += 1 if self._flood_counter[clientuuid] > 100: packet = { 'component': 'hfos.ui.clientma... |
def read(self, *args): """Handles raw client requests and distributes them to the appropriate components""" self.log("Beginning new transaction: ", args, lvl=network) try: sock, msg = args[0], args[1] user = password = client = clientuuid = useruuid = requestdata = \ requestaction = None # self.log("", msg) clientuuid ... |
msg = json.loads(msg) self.log("Message from client received: ", msg, lvl=network) except Exception as e: self.log("JSON Decoding failed! %s (%s of %s)" % (msg, e, type(e))) return try: requestcomponent = msg['component'] requestaction = msg['action'] except (KeyError, AttributeError) as e: self.log("Unpacking error: "... |
anything from unsafe events requestdata = msg['data'] if isinstance(requestdata, (dict, list)) and 'raw' in requestdata: # self.log(requestdata['raw'], lvl=critical) requestdata['raw'] = b64decode(requestdata['raw']) # self.log(requestdata['raw']) except (KeyError, AttributeError) as e: self.log("No payload.", lvl=netw... |
self.anonymous_events and requestaction in \ self.anonymous_events[requestcomponent]: self.log('Executing anonymous event:', requestcomponent, requestaction) try: self._handleAnonymousEvents(requestcomponent, requestaction, requestdata, client) except Exception as e: self.log("Anonymous request failed:", e, type(e), lv... |
self._users[useruuid] except KeyError: if not (requestaction == 'ping' and requestcomponent == 'hfos.ui.clientmanager'): self.log("User not logged in.", lvl=warn) return self.log('Handling event:', requestcomponent, requestaction, lvl=verbose) try: self._handleAuthorizedEvents(requestcomponent, requestaction, requestda... |
def authentication(self, event): """Links the client to the granted account and profile, then notifies the client""" try: self.log("Authorization has been granted by DB check:", event.username, lvl=debug) account, profile, clientconfig = event.userdata useruuid = event.useruuid originatingclientuuid = event.clientuuid ... |
else: signedinuser = User(account, profile, useruuid) self._users[account.uuid] = signedinuser if clientuuid in signedinuser.clients: self.log("Client configuration already logged in.", lvl=critical) # TODO: What now?? # Probably senseful would be to add the socket to the # client's other socket # The clients would be ... |
(", clientuuid, ") registered to " "user", useruuid, lvl=debug) # Update socket.. socket = self._sockets[event.sock] socket.clientuuid = clientuuid self._sockets[event.sock] = socket # ..and client lists try: language = clientconfig.language except AttributeError: language = "en" # TODO: Rewrite and simplify this: newc... |
self.log("Transmitting Authorization to client", authpacket, lvl=network) self.fireEvent( write(event.sock, json.dumps(authpacket)), "wsserver" ) profilepacket = {"component": "profile", "action": "get", "data": profile.serializablefields()} self.log("Transmitting Profile to client", profilepacket, lvl=network) self.fi... |
(%s, %s) during auth grant: %s" % ( type(e), e, event), lvl=error) |
def selectlanguage(self, event): """Store client's selection of a new translation""" self.log('Language selection event:', event.client, pretty=True) if event.data not in all_languages(): self.log('Unavailable language selected:', event.data, lvl=warn) language = None else: language = event.data if language is None: la... |
def getlanguages(self, event): """Compile and return a human readable list of registered translations""" self.log('Client requests all languages.', lvl=verbose) result = { 'component': 'hfos.ui.clientmanager', 'action': 'getlanguages', 'data': language_token_to_name(all_languages()) } self.fireEvent(send(event.client.u... |
def ping(self, event): """Perform a ping to measure client <-> node latency""" self.log('Client ping received:', event.data, lvl=verbose) response = { 'component': 'hfos.ui.clientmanager', 'action': 'pong', 'data': [event.data, time() * 1000] } self.fire(send(event.client.uuid, response)) |
def convert(self, lat, lon, source, dest, height=0, datetime=None, precision=1e-10, ssheight=50*6371): """Converts between geodetic, modified apex, quasi-dipole and MLT. Parameters ========== lat : array_like Latitude lon : array_like Longitude/MLT source : {'geo', 'apex', 'qd', 'mlt'} Input coordinate system dest : {'... |
MLT conversions) precision : float, optional Precision of output (degrees) when converting to geo. A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until fee... |
coordinates being converted to geo are converted to QD first and passed through APXG2Q). ssheight : float, optional Altitude in km to use for converting the subsolar point from geographic to magnetic coordinates. A high altitude is used to ensure the subsolar point is mapped to high latitudes, which prevents the South-... |
float Converted latitude (if converting to MLT, output latitude is apex) lat : ndarray or float Converted longitude/MLT """ if datetime is None and ('mlt' in [source, dest]): raise ValueError('datetime must be given for MLT calculations') lat = helpers.checklat(lat) if source == dest: return lat, lon # from geo elif so... |
source == 'geo' and dest == 'qd': lat, lon = self.geo2qd(lat, lon, height) elif source == 'geo' and dest == 'mlt': lat, lon = self.geo2apex(lat, lon, height) lon = self.mlon2mlt(lon, datetime, ssheight=ssheight) # from apex elif source == 'apex' and dest == 'geo': lat, lon, _ = self.apex2geo(lat, lon, height, precision... |
height=height) elif source == 'apex' and dest == 'mlt': lon = self.mlon2mlt(lon, datetime, ssheight=ssheight) # from qd elif source == 'qd' and dest == 'geo': lat, lon, _ = self.qd2geo(lat, lon, height, precision=precision) elif source == 'qd' and dest == 'apex': lat, lon = self.qd2apex(lat, lon, height=height) elif so... |
datetime, ssheight=ssheight) # from mlt (input latitude assumed apex) elif source == 'mlt' and dest == 'geo': lon = self.mlt2mlon(lon, datetime, ssheight=ssheight) lat, lon, _ = self.apex2geo(lat, lon, height, precision=precision) elif source == 'mlt' and dest == 'apex': lon = self.mlt2mlon(lon, datetime, ssheight=sshe... |
other transformations are implemented else: estr = 'Unknown coordinate transformation: ' estr += '{} -> {}'.format(source, dest) raise NotImplementedError(estr) return lat, lon |
def geo2apex(self, glat, glon, height): """Converts geodetic to modified apex coordinates. Parameters ========== glat : array_like Geodetic latitude glon : array_like Geodetic longitude height : array_like Altitude in km Returns ======= alat : ndarray or float Modified apex latitude alon : ndarray or float Modified ape... |
set to -9999 where undefined ' '(apex height may be < reference height)') # if array is returned, dtype is object, so convert to float return np.float64(alat), np.float64(alon) |
def apex2geo(self, alat, alon, height, precision=1e-10): """Converts modified apex to geodetic coordinates. Parameters ========== alat : array_like Modified apex latitude alon : array_like Modified apex longitude height : array_like Altitude in km precision : float, optional Precision of output (degrees). A negative va... |
the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision. Returns ======= glat : ndarray or float Geodetic latitude glon : ndarray or float Geodetic longitude error : ndarray or float The angular difference (deg... |
and glon into geo2qd (APXG2Q) """ alat = helpers.checklat(alat, name='alat') qlat, qlon = self.apex2qd(alat, alon, height=height) glat, glon, error = self.qd2geo(qlat, qlon, height, precision=precision) return glat, glon, error |
def geo2qd(self, glat, glon, height): """Converts geodetic to quasi-dipole coordinates. Parameters ========== glat : array_like Geodetic latitude glon : array_like Geodetic longitude height : array_like Altitude in km Returns ======= qlat : ndarray or float Quasi-dipole latitude qlon : ndarray or float Quasi-dipole lon... |
convert to float return np.float64(qlat), np.float64(qlon) |
def qd2geo(self, qlat, qlon, height, precision=1e-10): """Converts quasi-dipole to geodetic coordinates. Parameters ========== qlat : array_like Quasi-dipole latitude qlon : array_like Quasi-dipole longitude height : array_like Altitude in km precision : float, optional Precision of output (degrees). A negative value o... |
routine to iterate until feeding the output geo lat/lon into geo2qd (APXG2Q) reproduces the input QD lat/lon to within the specified precision. Returns ======= glat : ndarray or float Geodetic latitude glon : ndarray or float Geodetic longitude error : ndarray or float The angular difference (degrees) between the input... |
geo2qd (APXG2Q) """ qlat = helpers.checklat(qlat, name='qlat') glat, glon, error = self._qd2geo(qlat, qlon, height, precision) # if array is returned, dtype is object, so convert to float return np.float64(glat), np.float64(glon), np.float64(error) |
def _apex2qd_nonvectorized(self, alat, alon, height): """Convert from apex to quasi-dipole (not-vectorised) Parameters ----------- alat : (float) Apex latitude in degrees alon : (float) Apex longitude in degrees height : (float) Height in km Returns --------- qlat : (float) Quasi-dipole latitude in degrees qlon : (floa... |
apex height hA = self.get_apex(alat) if hA < height: if np.isclose(hA, height, rtol=0, atol=1e-5): # allow for values that are close hA = height else: estr = 'height {:.3g} is > apex height '.format(np.max(height)) estr += '{:.3g} for alat {:.3g}'.format(hA, alat) raise ApexHeightError(estr) qlat = np.sign(alat) * np.d... |
def apex2qd(self, alat, alon, height): """Converts modified apex to quasi-dipole coordinates. Parameters ========== alat : array_like Modified apex latitude alon : array_like Modified apex longitude height : array_like Altitude in km Returns ======= qlat : ndarray or float Quasi-dipole latitude qlon : ndarray or float ... |
array is returned, the dtype is object, so convert to float return np.float64(qlat), np.float64(qlon) |
def qd2apex(self, qlat, qlon, height): """Converts quasi-dipole to modified apex coordinates. Parameters ========== qlat : array_like Quasi-dipole latitude qlon : array_like Quasi-dipole longitude height : array_like Altitude in km Returns ======= alat : ndarray or float Modified apex latitude alon : ndarray or float M... |
if array is returned, the dtype is object, so convert to float return np.float64(alat), np.float64(alon) |
def mlon2mlt(self, mlon, datetime, ssheight=50*6371): """Computes the magnetic local time at the specified magnetic longitude and UT. Parameters ========== mlon : array_like Magnetic longitude (apex and quasi-dipole longitude are always equal) datetime : :class:`datetime.datetime` Date and time ssheight : float, option... |
subsolar point is mapped to high latitudes, which prevents the South-Atlantic Anomaly (SAA) from influencing the MLT. Returns ======= mlt : ndarray or float Magnetic local time [0, 24) Notes ===== To compute the MLT, we find the apex longitude of the subsolar point at the given time. Then the MLT of the given point wil... |
from this point (1 hour = 15 degrees). """ ssglat, ssglon = helpers.subsol(datetime) ssalat, ssalon = self.geo2apex(ssglat, ssglon, ssheight) # np.float64 will ensure lists are converted to arrays return (180 + np.float64(mlon) - ssalon)/15 % 24 |
def mlt2mlon(self, mlt, datetime, ssheight=50*6371): """Computes the magnetic longitude at the specified magnetic local time and UT. Parameters ========== mlt : array_like Magnetic local time datetime : :class:`datetime.datetime` Date and time ssheight : float, optional Altitude in km to use for converting the subsolar... |
latitudes, which prevents the South-Atlantic Anomaly (SAA) from influencing the MLT. Returns ======= mlon : ndarray or float Magnetic longitude [0, 360) (apex and quasi-dipole longitude are always equal) Notes ===== To compute the magnetic longitude, we find the apex longitude of the subsolar point at the given time. T... |
magnetic local time from this point (1 hour = 15 degrees). """ ssglat, ssglon = helpers.subsol(datetime) ssalat, ssalon = self.geo2apex(ssglat, ssglon, ssheight) # np.float64 will ensure lists are converted to arrays return (15*np.float64(mlt) - 180 + ssalon + 360) % 360 |
def map_to_height(self, glat, glon, height, newheight, conjugate=False, precision=1e-10): """Performs mapping of points along the magnetic field to the closest or conjugate hemisphere. Parameters ========== glat : array_like Geodetic latitude glon : array_like Geodetic longitude height : array_like Source altitude in k... |
precision : float, optional Precision of output (degrees). A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iterate until feeding the output geo lat/lon into geo2qd ... |
Geodetic latitude of mapped point newglon : ndarray or float Geodetic longitude of mapped point error : ndarray or float The angular difference (degrees) between the input QD coordinates and the qlat/qlon produced by feeding the output glat and glon into geo2qd (APXG2Q) Notes ===== The mapping is done by converting gla... |
conjugate, use negative apex latitude when converting back) """ alat, alon = self.geo2apex(glat, glon, height) if conjugate: alat = -alat try: newglat, newglon, error = self.apex2geo(alat, alon, newheight, precision=precision) except ApexHeightError: raise ApexHeightError("newheight is > apex height") return newglat, n... |
def map_E_to_height(self, alat, alon, height, newheight, E): """Performs mapping of electric field along the magnetic field. It is assumed that the electric field is perpendicular to B. Parameters ========== alat : (N,) array_like or float Modified apex latitude alon : (N,) array_like or float Modified apex longitude h... |
altitude in km E : (3,) or (3, N) array_like Electric field (at `alat`, `alon`, `height`) in geodetic east, north, and up components Returns ======= E : (3, N) or (3,) ndarray The electric field at `newheight` (geodetic east, north, and up components) """ return self._map_EV_to_height(alat, alon, height, newheight, E, ... |
def map_V_to_height(self, alat, alon, height, newheight, V): """Performs mapping of electric drift velocity along the magnetic field. It is assumed that the electric field is perpendicular to B. Parameters ========== alat : (N,) array_like or float Modified apex latitude alon : (N,) array_like or float Modified apex lo... |
Destination altitude in km V : (3,) or (3, N) array_like Electric drift velocity (at `alat`, `alon`, `height`) in geodetic east, north, and up components Returns ======= V : (3, N) or (3,) ndarray The electric drift velocity at `newheight` (geodetic east, north, and up components) """ return self._map_EV_to_height(alat... |
def basevectors_qd(self, lat, lon, height, coords='geo', precision=1e-10): """Returns quasi-dipole base vectors f1 and f2 at the specified coordinates. The vectors are described by Richmond [1995] [2]_ and Emmert et al. [2010] [3]_. The vector components are geodetic east and north. Parameters ========== lat : (N,) arr... |
km coords : {'geo', 'apex', 'qd'}, optional Input coordinate system precision : float, optional Precision of output (degrees) when converting to geo. A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes ... |
QD lat/lon to within the specified precision (all coordinates being converted to geo are converted to QD first and passed through APXG2Q). Returns ======= f1 : (2, N) or (2,) ndarray f2 : (2, N) or (2,) ndarray References ========== .. [2] Richmond, A. D. (1995), Ionospheric Electrodynamics Using Magnetic Apex Coordina... |
T., A. D. Richmond, and D. P. Drob (2010), A computationally compact representation of Magnetic-Apex and Quasi-Dipole coordinates with smooth base vectors, J. Geophys. Res., 115(A8), A08322, :doi:`10.1029/2010JA015326`. """ glat, glon = self.convert(lat, lon, coords, 'geo', height=height, precision=precision) f1, f2 = ... |
if f1.dtype == object: f1 = np.vstack(f1).T f2 = np.vstack(f2).T return f1, f2 |
def basevectors_apex(self, lat, lon, height, coords='geo', precision=1e-10): """Returns base vectors in quasi-dipole and apex coordinates. The vectors are described by Richmond [1995] [4]_ and Emmert et al. [2010] [5]_. The vector components are geodetic east, north, and up (only east and north for `f1` and `f2`). Para... |
: (N,) array_like or float Altitude in km coords : {'geo', 'apex', 'qd'}, optional Input coordinate system return_all : bool, optional Will also return f3, g1, g2, and g3, and f1 and f2 have 3 components (the last component is zero). Requires `lat`, `lon`, and `height` to be broadcast to 1D (at least one of the paramet... |
parameters must be 1D or 0D). precision : float, optional Precision of output (degrees) when converting to geo. A negative value of this argument produces a low-precision calculation of geodetic lat/lon based only on their spherical harmonic representation. A positive value causes the underlying Fortran routine to iter... |
the specified precision (all coordinates being converted to geo are converted to QD first and passed through APXG2Q). Returns ======= f1, f2 : (2, N) or (2,) ndarray f3, g1, g2, g3, d1, d2, d3, e1, e2, e3 : (3, N) or (3,) ndarray Note ==== `f3`, `g1`, `g2`, and `g3` are not part of the Fortran code by Emmert et al. [20... |
They are calculated by this Python library according to the following equations in Richmond [1995] [4]_: * `g1`: Eqn. 6.3 * `g2`: Eqn. 6.4 * `g3`: Eqn. 6.5 * `f3`: Eqn. 6.8 References ========== .. [4] Richmond, A. D. (1995), Ionospheric Electrodynamics Using Magnetic Apex Coordinates, Journal of geomagnetism and geoel... |
P. Drob (2010), A computationally compact representation of Magnetic-Apex and Quasi-Dipole coordinates with smooth base vectors, J. Geophys. Res., 115(A8), A08322, :doi:`10.1029/2010JA015326`. """ glat, glon = self.convert(lat, lon, coords, 'geo', height=height, precision=precision) returnvals = self._geo2apexall(glat,... |
vector is an array of arrays, # so reshape to a single array if f1.dtype == object: f1 = np.vstack(f1).T f2 = np.vstack(f2).T d1 = np.vstack(d1).T d2 = np.vstack(d2).T d3 = np.vstack(d3).T e1 = np.vstack(e1).T e2 = np.vstack(e2).T e3 = np.vstack(e3).T # make sure arrays are 2D f1 = f1.reshape((2, f1.size//2)) f2 = f2.r... |
= d3.reshape((3, d3.size//3)) e1 = e1.reshape((3, e1.size//3)) e2 = e2.reshape((3, e2.size//3)) e3 = e3.reshape((3, e3.size//3)) # compute f3, g1, g2, g3 F1 = np.vstack((f1, np.zeros_like(f1[0]))) F2 = np.vstack((f2, np.zeros_like(f2[0]))) F = np.cross(F1.T, F2.T).T[-1] cosI = helpers.getcosIm(alat) k = np.array([0, 0,... |
* np.tan(np.radians(qlat))) * \ (k + ((self.RE + np.float64(height)) / (self.RE + self.refh)) * d2 / cosI) g3 = k*F f3 = np.cross(g1.T, g2.T).T if np.any(alat == -9999): warnings.warn(('Base vectors g, d, e, and f3 set to -9999 where ' 'apex latitude is undefined (apex height may be < ' 'reference height)')) f3 = np.wh... |
-9999, g1) g2 = np.where(alat == -9999, -9999, g2) g3 = np.where(alat == -9999, -9999, g3) d1 = np.where(alat == -9999, -9999, d1) d2 = np.where(alat == -9999, -9999, d2) d3 = np.where(alat == -9999, -9999, d3) e1 = np.where(alat == -9999, -9999, e1) e2 = np.where(alat == -9999, -9999, e2) e3 = np.where(alat == -9999, ... |
f2, f3, g1, g2, g3, d1, d2, d3, e1, e2, e3]) |
def get_apex(self, lat, height=None): """ Calculate apex height Parameters ----------- lat : (float) Latitude in degrees height : (float or NoneType) Height above the surface of the earth in km or NoneType to use reference height (default=None) Returns ---------- apex_height : (float) Height of the field line apex in k... |
np.cos(np.radians(lat))**2 apex_height = (self.RE + height) / cos_lat_squared - self.RE return apex_height |
def set_epoch(self, year): """Updates the epoch for all subsequent conversions. Parameters ========== year : float Decimal year """ fa.loadapxsh(self.datafile, np.float(year)) self.year = year |
def basic_parser(patterns, with_name=None): """ Basic ordered parser. """ def parse(line): output = None highest_order = 0 highest_pattern_name = None for pattern in patterns: results = pattern.findall(line) if results and any(results): if pattern.order > highest_order: output = results highest_order = pattern.order if... |
def alt_parser(patterns): """ This parser is able to handle multiple different patterns finding stuff in text-- while removing matches that overlap. """ from reparse.util import remove_lower_overlapping get_first = lambda items: [i[0] for i in items] get_second = lambda items: [i[1] for i in items] def parse(line): out... |
get_second(sorted(output)), [])) return parse |
def build_tree_parser(patterns): """ This parser_type simply outputs an array of [(tree, regex)] for use in another language. """ def output(): for pattern in patterns: yield (pattern.build_full_tree(), pattern.regex) return list(output()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.