code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
return generate_navigator(os=os, navigator=navigator, platform=platform, device_type=device_type)['user_agent']
def generate_user_agent(os=None, navigator=None, platform=None, device_type=None)
Generates HTTP User-Agent header :param os: limit list of os for generation :type os: string or list/tuple or None :param navigator: limit list of browser engines for generation :type navigator: string or list/tuple or None :param device_type: limit possible oses by device type :type device_typ...
3.297552
6.552937
0.503217
config = generate_navigator(os=os, navigator=navigator, platform=platform, device_type=device_type) return { 'appCodeName': config['app_code_name'], 'appName': config['app_name'], 'appVersion': config['app_version'], ...
def generate_navigator_js(os=None, navigator=None, platform=None, device_type=None)
Generates web navigator's config with keys corresponding to keys of `windows.navigator` JavaScript object. :param os: limit list of oses for generation :type os: string or list/tuple or None :param navigator: limit list of browser engines for generation :type navigator: string or list/tuple or None...
1.987879
2.001627
0.993132
r, _, _ = select.select([pipe_out], [], [], 0) return bool(r)
def more_data(pipe_out)
Check if there is more data left on the pipe :param pipe_out: The os pipe_out :rtype: bool
5.142322
5.503861
0.934312
out = b'' while more_data(pipe_out): out += os.read(pipe_out, 1024) return out.decode('utf-8')
def read_pipe(pipe_out)
Read data on a pipe Used to capture stdout data produced by libiperf :param pipe_out: The os pipe_out :rtype: unicode string
3.550748
3.729167
0.952156
try: self._role = c_char( self.lib.iperf_get_test_role(self._test) ).value.decode('utf-8') except TypeError: self._role = c_char( chr(self.lib.iperf_get_test_role(self._test)) ).value.decode('utf-8') return ...
def role(self)
The iperf3 instance role valid roles are 'c'=client and 's'=server :rtype: 'c' or 's'
3.454085
3.170116
1.089577
result = c_char_p( self.lib.iperf_get_test_bind_address(self._test) ).value if result: self._bind_address = result.decode('utf-8') else: self._bind_address = '*' return self._bind_address
def bind_address(self)
The bind address the iperf3 instance will listen on use * to listen on all available IPs :rtype: string
4.347639
3.777331
1.150982
self._port = self.lib.iperf_get_test_server_port(self._test) return self._port
def port(self)
The port the iperf3 server is listening on
11.066677
6.567014
1.685192
enabled = self.lib.iperf_get_test_json_output(self._test) if enabled: self._json_output = True else: self._json_output = False return self._json_output
def json_output(self)
Toggles json output of libiperf Turning this off will output the iperf3 instance results to stdout/stderr :rtype: bool
5.057151
4.366437
1.158187
enabled = self.lib.iperf_get_verbose(self._test) if enabled: self._verbose = True else: self._verbose = False return self._verbose
def verbose(self)
Toggles verbose output for the iperf3 instance :rtype: bool
6.181125
5.200041
1.188668
# TODO: Is there a better way to get the const char than allocating 30? VersionType = c_char * 30 return VersionType.in_dll(self.lib, "version").value.decode('utf-8')
def iperf_version(self)
Returns the version of the libiperf library :rtype: string
8.994636
9.083707
0.990194
strerror = self.lib.iperf_strerror strerror.restype = c_char_p return strerror(error_id).decode('utf-8')
def _error_to_string(self, error_id)
Returns an error string from libiperf :param error_id: The error_id produced by libiperf :rtype: string
5.824847
4.506574
1.292522
result = c_char_p( self.lib.iperf_get_test_server_hostname(self._test) ).value if result: self._server_hostname = result.decode('utf-8') else: self._server_hostname = None return self._server_hostname
def server_hostname(self)
The server hostname to connect to. Accepts DNS entries or IP addresses. :rtype: string
3.674965
4.165926
0.882148
proto_id = self.lib.iperf_get_test_protocol_id(self._test) if proto_id == SOCK_STREAM: self._protocol = 'tcp' elif proto_id == SOCK_DGRAM: self._protocol = 'udp' return self._protocol
def protocol(self)
The iperf3 instance protocol valid protocols are 'tcp' and 'udp' :rtype: str
4.405099
4.114792
1.070552
self._omit = self.lib.iperf_get_test_omit(self._test) return self._omit
def omit(self)
The test startup duration to omit in seconds.
11.596251
8.709617
1.331431
self._duration = self.lib.iperf_get_test_duration(self._test) return self._duration
def duration(self)
The test duration in seconds.
8.981411
6.785962
1.323528
self._bandwidth = self.lib.iperf_get_test_rate(self._test) return self._bandwidth
def bandwidth(self)
Target bandwidth in bits/sec
11.423946
9.805802
1.165019
self._blksize = self.lib.iperf_get_test_blksize(self._test) return self._blksize
def blksize(self)
The test blksize.
7.731538
5.565975
1.389072
self._num_streams = self.lib.iperf_get_test_num_streams(self._test) return self._num_streams
def num_streams(self)
The number of streams to use.
6.262015
6.05546
1.034111
enabled = self.lib.iperf_get_test_reverse(self._test) if enabled: self._reverse = True else: self._reverse = False return self._reverse
def reverse(self)
Toggles direction of test :rtype: bool
7.044331
6.319915
1.114624
if self.json_output: output_to_pipe(self._pipe_in) # Disable stdout error = self.lib.iperf_run_client(self._test) if not self.iperf_version.startswith('iperf 3.1'): data = read_pipe(self._pipe_out) if data.startswith('Control connect...
def run(self)
Run the current test client. :rtype: instance of :class:`TestResult`
6.224816
5.807966
1.071772
def _run_in_thread(self, data_queue): output_to_pipe(self._pipe_in) # disable stdout error = self.lib.iperf_run_server(self._test) output_to_screen(self._stdout_fd, self._stderr_fd) # enable stdout # TODO json_output_string not available ...
def run(self)
Run the iperf3 server instance. :rtype: instance of :class:`TestResult`
5.064636
4.683078
1.081476
# Plot the planes lines = ax.plane(strikes, dips, 'k-', lw=0.5) # Calculate the position of the rake of the lineations, but don't plot yet x, y = mplstereonet.rake(strikes, dips, rakes) # Calculate the direction the arrows should point # These are all normal faults, so the arrows point aw...
def fault_and_striae_plot(ax, strikes, dips, rakes)
Makes a fault-and-striae plot (a.k.a. "Ball of String") for normal faults with the given strikes, dips, and rakes.
6.403668
6.29205
1.017739
# Calculate the position of the rake of the lineations, but don't plot yet rake_x, rake_y = mplstereonet.rake(strikes, dips, rakes) # Calculate the direction the arrows should point # These are all normal faults, so the arrows point away from the center # Because we're plotting at the pole loc...
def tangent_lineation_plot(ax, strikes, dips, rakes)
Makes a tangent lineation plot for normal faults with the given strikes, dips, and rakes.
5.683382
5.569663
1.020418
# Get the data file relative to this file's location... datadir = os.path.dirname(__file__) filename = os.path.join(datadir, 'angelier_data.txt') data = [] with open(filename, 'r') as infile: for line in infile: # Skip comments if line.startswith('#'): ...
def load()
Read data from a text file on disk.
3.942379
3.914458
1.007133
lons = np.atleast_1d(np.squeeze(lons)) lats = np.atleast_1d(np.squeeze(lats)) if not weights: weights = 1 # Normalize the weights weights = np.asarray(weights, dtype=np.float) weights /= weights.mean() # Generate a regular grid of "counters" to measure on... bound = np.pi ...
def _count_points(lons, lats, func, sigma, gridsize=(100,100), weights=None)
This function actually calculates the point density of the input ("lons" and "lats") points at a series of counter stations. Creates "gridsize" regular grid of counter stations in lat-long space, calculates the distance to all input points at each counter station, and then calculates the density using "...
3.645199
3.630156
1.004144
n = float(cos_dist.size) f = 2 * (1.0 + n / sigma**2) count = np.exp(f * (cos_dist - 1)) units = np.sqrt(n * (f/2.0 - 1) / f**2) return count, units
def _exponential_kamb(cos_dist, sigma=3)
Kernel function from Vollmer for exponential smoothing.
5.03101
4.837152
1.040077
n = float(cos_dist.size) radius = _kamb_radius(n, sigma) f = 2 / (1 - radius) cos_dist = cos_dist[cos_dist >= radius] count = (f * (cos_dist - radius)) return count, _kamb_units(n, radius)
def _linear_inverse_kamb(cos_dist, sigma=3)
Kernel function from Vollmer for linear smoothing.
5.21025
4.833479
1.07795
n = float(cos_dist.size) dist = _kamb_radius(n, sigma) count = (cos_dist >= dist).astype(float) return count, _kamb_units(n, dist)
def _kamb_count(cos_dist, sigma=3)
Original Kamb kernel function (raw count within radius).
4.732205
4.715384
1.003567
radius = 0.01 count = ((1 - cos_dist) <= radius).astype(float) # To offset the count.sum() - 0.5 required for the kamb methods... count = 0.5 / count.size + count return count, (cos_dist.size * radius)
def _schmidt_count(cos_dist, sigma=None)
Schmidt (a.k.a. 1%) counting kernel function.
13.651571
12.066324
1.131378
return self._base_transform(self._center_longitude, self._center_latitude, resolution)
def _get_core_transform(self, resolution)
The projection for the stereonet as a matplotlib transform. This is primarily called by LambertAxes._set_lim_and_transforms.
7.621147
7.338308
1.038543
# How big is the projected globe? # In the case of a stereonet, it's actually constant. xscale = yscale = self._scale # Create an affine transform to stretch the projection from 0-1 return Affine2D() \ .rotate(np.radians(self.rotation)) \ .scale(0...
def _get_affine_transform(self)
The affine portion of the base transform. This is called by LambertAxes._set_lim_and_transforms.
6.474895
5.725163
1.130954
# Most of the transforms are set up correctly by LambertAxes LambertAxes._set_lim_and_transforms(self) # Transform for latitude ticks. These are typically unused, but just # in case we need them... yaxis_stretch = Affine2D().scale(4 * self.horizon, 1.0) yaxis_st...
def _set_lim_and_transforms(self)
Setup the key transforms for the axes.
4.039845
3.852446
1.048644
number = (360.0 / degrees) + 1 locs = np.linspace(-np.pi, np.pi, number, True)[1:] locs[-1] -= 0.01 # Workaround for "back" gridlines showing. self.xaxis.set_major_locator(FixedLocator(locs)) self._logitude_degrees = degrees self.xaxis.set_major_formatter(self.Th...
def set_longitude_grid(self, degrees)
Set the number of degrees between each longitude grid.
6.105117
6.099596
1.000905
self._polar.set_position(pos, which) if self._overlay_axes is not None: self._overlay_axes.set_position(pos, which) LambertAxes.set_position(self, pos, which)
def set_position(self, pos, which='both')
Identical to Axes.set_position (This docstring is overwritten).
3.781403
3.343349
1.131022
self._rotation = np.radians(rotation) self._polar.set_theta_offset(self._rotation + np.pi / 2.0) self.transData.invalidate() self.transAxes.invalidate() self._set_lim_and_transforms()
def set_rotation(self, rotation)
Set the rotation of the stereonet in degrees clockwise from North.
4.48028
4.794937
0.934377
Axes.cla(self) # Set grid defaults... self.set_longitude_grid(10) self.set_latitude_grid(10) self.set_longitude_grid_ends(80) # Hide all ticks and tick labels for the "native" lon and lat axes self.xaxis.set_minor_locator(NullLocator()) self.yax...
def cla(self)
Identical to Axes.cla (This docstring is overwritten).
3.482372
3.405149
1.022679
p, b = stereonet_math.geographic2plunge_bearing(x, y) s, d = stereonet_math.geographic2pole(x, y) pb = u'P/B={:0.0f}\u00b0/{:03.0f}\u00b0'.format(p[0], b[0]) sd = u'S/D={:03.0f}\u00b0/{:0.0f}\u00b0'.format(s[0], d[0]) return u'{}, {}'.format(pb, sd)
def format_coord(self, x, y)
Format displayed coordinates during mouseover of axes.
3.313482
3.206468
1.033374
grid_on = self._gridOn Axes.grid(self, False) if kind == 'polar': center = 0, 0 if self._overlay_axes is not None: self._overlay_axes.remove() self._overlay_axes = None if not b and b is not None: return if b is...
def grid(self, b=None, which='major', axis='both', kind='arbitrary', center=None, **kwargs)
Usage is identical to a normal axes grid except for the ``kind`` and ``center`` kwargs. ``kind="polar"`` will add a polar overlay. The ``center`` and ``kind`` arguments allow you to add a grid from a differently-centered stereonet. This is useful for making "polar stereonets" that stil...
3.650898
3.648387
1.000688
plunge, bearing = stereonet_math.geographic2plunge_bearing(*center) lon0, lat0 = center fig = self.get_figure() self._overlay_axes = fig.add_axes(self.get_position(True), frameon=False, projection=self.name, ...
def _add_overlay(self, center)
Add a grid from a differently-centered stereonet. This is useful for making "polar stereonets" that still use the same coordinate system as a standard stereonet. (i.e. a plane/line/whatever will have the same representation on both, but the grid is displayed differently.) To display a ...
4.576893
4.034513
1.134435
# This will be called inside LambertAxes.__init__ as well as every # time the axis is cleared, so we need the try/except to avoid having # multiple hidden axes when `cla` is _manually_ called. try: return self._hidden_polar_axes except AttributeError: ...
def _polar(self)
The "hidden" polar axis used for azimuth labels.
5.681203
4.710695
1.206022
return self._polar.set_thetagrids(angles, labels, frac, **kwargs)
def set_azimuth_ticks(self, angles, labels=None, frac=None, **kwargs)
Sets the azimuthal tick locations (Note: tick lines are not currently drawn or supported.). Parameters ---------- angles : sequence of numbers The tick locations in degrees. labels : sequence of strings The tick label at each location. Defaults to a form...
7.236153
9.941264
0.727891
return self._polar.set_xticklabels(labels, fontdict, **kwargs)
def set_azimuth_ticklabels(self, labels, fontdict=None, **kwargs)
Sets the labels for the azimuthal ticks. Parameters ---------- labels : A sequence of strings Azimuth tick labels **kwargs Additional parameters are text properties for the labels.
6.611332
9.942521
0.664955
plunge, bearing, angle = np.atleast_1d(plunge, bearing, angle) patches = [] lons, lats = stereonet_math.cone(plunge, bearing, angle, segments) codes = mpath.Path.LINETO * np.ones(segments, dtype=np.uint8) codes[0] = mpath.Path.MOVETO if bidirectional: ...
def cone(self, plunge, bearing, angle, segments=100, bidirectional=True, **kwargs)
Plot a polygon of a small circle (a.k.a. a cone) with an angular radius of *angle* centered at a p/b of *plunge*, *bearing*. Additional keyword arguments are passed on to the ``PathCollection``. (e.g. to have an unfilled small small circle, pass "facecolor='none'".) Parameters ...
2.382069
2.32994
1.022373
segments = kwargs.pop('segments', 100) center = self._center_latitude, self._center_longitude lon, lat = stereonet_math.plane(strike, dip, segments, center) return self.plot(lon, lat, *args, **kwargs)
def plane(self, strike, dip, *args, **kwargs)
Plot lines representing planes on the axes. Additional arguments and keyword arguments are passed on to `ax.plot`. Parameters ---------- strike, dip : number or sequences of numbers The strike and dip of the plane(s) in degrees. The dip direction is defined by th...
4.281604
5.186736
0.825491
lon, lat = stereonet_math.pole(strike, dip) args, kwargs = self._point_plot_defaults(args, kwargs) return self.plot(lon, lat, *args, **kwargs)
def pole(self, strike, dip, *args, **kwargs)
Plot points representing poles to planes on the axes. Additional arguments and keyword arguments are passed on to `ax.plot`. Parameters ---------- strike, dip : numbers or sequences of numbers The strike and dip of the plane(s) in degrees. The dip direction is de...
5.253277
6.276392
0.83699
lon, lat = stereonet_math.rake(strike, dip, rake_angle) args, kwargs = self._point_plot_defaults(args, kwargs) return self.plot(lon, lat, *args, **kwargs)
def rake(self, strike, dip, rake_angle, *args, **kwargs)
Plot points representing lineations along planes on the axes. Additional arguments and keyword arguments are passed on to `plot`. Parameters ---------- strike, dip : number or sequences of numbers The strike and dip of the plane(s) in degrees. The dip direction is ...
4.989502
6.307664
0.791022
lon, lat = stereonet_math.line(plunge, bearing) args, kwargs = self._point_plot_defaults(args, kwargs) return self.plot([lon], [lat], *args, **kwargs)
def line(self, plunge, bearing, *args, **kwargs)
Plot points representing linear features on the axes. Additional arguments and keyword arguments are passed on to `plot`. Parameters ---------- plunge, bearing : number or sequence of numbers The plunge and bearing of the line(s) in degrees. The plunge is measur...
5.828675
6.742789
0.864431
if args: return args, kwargs if 'ls' not in kwargs and 'linestyle' not in kwargs: kwargs['linestyle'] = 'none' if 'marker' not in kwargs: kwargs['marker'] = 'o' return args, kwargs
def _point_plot_defaults(self, args, kwargs)
To avoid confusion for new users, this ensures that "scattered" points are plotted by by `plot` instead of points joined by a line. Parameters ---------- args : tuple Arguments representing additional parameters to be passed to `self.plot`. kwargs : dict ...
2.691807
3.20917
0.838786
contour_kwargs = {} contour_kwargs['measurement'] = kwargs.pop('measurement', 'poles') contour_kwargs['method'] = kwargs.pop('method', 'exponential_kamb') contour_kwargs['sigma'] = kwargs.pop('sigma', 3) contour_kwargs['gridsize'] = kwargs.pop('gridsize', 100) co...
def _contour_helper(self, args, kwargs)
Unify defaults and common functionality of ``density_contour`` and ``density_contourf``.
3.788737
4.016853
0.94321
fig, ax = mplstereonet.subplots() strike, dip = 315, 30 ax.plane(strike, dip, color='lightblue') ax.pole(strike, dip, color='green', markersize=15) ax.rake(strike, dip, 40, marker='*', markersize=20, color='green') # Make a bit of room for the title... fig.subplots_adjust(top=0.8) ...
def basic()
Set up a basic stereonet and plot the same data each time.
5.050362
4.877199
1.035505
fig, axes = mplstereonet.subplots(ncols=2, figsize=(20,10)) for ax in axes: # Make the grid lines solid. ax.grid(ls='-') # Make the longitude grids continue all the way to the poles ax.set_longitude_grid_ends(90) return fig, axes
def setup_figure()
Setup the figure and axes
6.09124
5.852777
1.040744
ax.set_title('Dip and Azimuth', y=1.1, size=18) # Set the azimuth ticks to be just "N", "E", etc. ax.set_azimuth_ticks(range(0, 360, 10)) # Hackishly set some of the azimuth labels to North, East, etc... fmt = ax.yaxis.get_major_formatter() labels = [fmt(item) for item in ax.get_azimuth_t...
def stereonet_projection_explanation(ax)
Example to explain azimuth and dip on a lower-hemisphere stereonet.
3.561306
3.513786
1.013524
ax.set_title('Longitude and Latitude', size=18, y=1.1) # Hide the azimuth labels ax.set_azimuth_ticklabels([]) # Make the axis tick labels visible: ax.set_xticks(np.radians(np.arange(-80, 90, 10))) ax.tick_params(label1On=True) ax.set_xlabel('Longitude') xlabel_halo(ax) retu...
def native_projection_explanation(ax)
Example showing how the "native" longitude and latitude relate to the stereonet projection.
5.950478
5.857135
1.015937
import matplotlib.patheffects as effects for tick in ax.get_xticklabels() + [ax.xaxis.label]: tick.set_path_effects([effects.withStroke(linewidth=4, foreground='w')])
def xlabel_halo(ax)
Add a white "halo" around the xlabels.
2.726326
2.514949
1.084048
strike = parse_azimuth(strike) dip, direction = split_trailing_letters(dip) if direction is not None: expected_direc = strike + 90 if opposite_end(expected_direc, direction): strike += 180 if strike > 360: strike -= 360 return strike, dip
def parse_strike_dip(strike, dip)
Parses strings of strike and dip and returns strike and dip measurements following the right-hand-rule. Dip directions are parsed, and if the measurement does not follow the right-hand-rule, the opposite end of the strike measurement is returned. Accepts either quadrant-formatted or azimuth-formatted ...
5.505898
6.684478
0.823684
strike, dip = parse_strike_dip(strike, dip) rake, direction = split_trailing_letters(rake) if direction is not None: if opposite_end(strike, direction): rake = -rake if rake < 0: rake += 180 elif rake > 180: rake -= 180 return strike, dip, rake
def parse_rake(strike, dip, rake)
Parses strings of strike, dip, and rake and returns a strike, dip, and rake measurement following the right-hand-rule, with the "end" of the strike that the rake is measured from indicated by the sign of the rake (positive rakes correspond to the strike direction, negative rakes correspond to the opposi...
3.74626
4.037937
0.927766
bearing = parse_azimuth(bearing) plunge, direction = split_trailing_letters(plunge) if direction is not None: if opposite_end(bearing, direction): bearing +=180 if plunge < 0: bearing += 180 plunge = -plunge if plunge > 90: bearing += 180 pl...
def parse_plunge_bearing(plunge, bearing)
Parses strings of plunge and bearing and returns a consistent plunge and bearing measurement as floats. Plunge angles returned by this function will always be between 0 and 90. If no direction letter(s) is present, the plunge is assumed to be measured from the end specified by the bearing. If a directi...
3.038453
3.450126
0.880679
azimuth = parse_azimuth(azimuth) strike = azimuth - 90 if strike < 0: strike += 360 return strike
def dip_direction2strike(azimuth)
Converts a planar measurment of dip direction using the dip-azimuth convention into a strike using the right-hand-rule. Parameters ---------- azimuth : number or string The dip direction of the plane in degrees. This can be either a numerical azimuth in the 0-360 range or a string repre...
2.883986
5.176676
0.557112
strike = parse_azimuth(strike) dip_direction = strike + 90 if dip_direction > 360: dip_direction -= 360 return dip_direction
def strike2dip_direction(strike)
Converts a planar measurement of strike using the right-hand-rule into the dip direction (i.e. the direction that the plane dips). Parameters ---------- strike : number or string The strike direction of the plane in degrees. This can be either a numerical azimuth in the 0-360 range or a...
3.062573
4.517028
0.678006
try: azimuth = float(azimuth) except ValueError: if not azimuth[0].isalpha(): raise ValueError('Ambiguous azimuth: {}'.format(azimuth)) azimuth = parse_quadrant_measurement(azimuth) return azimuth
def parse_azimuth(azimuth)
Parses an azimuth measurement in azimuth or quadrant format. Parameters ----------- azimuth : string or number An azimuth measurement in degrees or a quadrant measurement of azimuth. Returns ------- azi : float The azimuth in degrees clockwise from north (range: 0-360) See...
3.60846
2.941319
1.226817
def rotation_direction(first, second): return np.cross(_azimuth2vec(first), _azimuth2vec(second)) # Parse measurement quad_azimuth = quad_azimuth.strip() try: first_dir = quadrantletter_to_azimuth(quad_azimuth[0].upper()) sec_dir = quadrantletter_to_azimuth(quad_azimuth[-1]...
def parse_quadrant_measurement(quad_azimuth)
Parses a quadrant measurement of the form "AxxB", where A and B are cardinal directions and xx is an angle measured relative to those directions. In other words, it converts a measurement such as E30N into an azimuth of 60 degrees, or W10S into an azimuth of 260 degrees. For ambiguous quadrant measure...
3.122884
2.904189
1.075303
# This is a bit of hackery so that we can put a single "inverse" # function here. If we just made "self._inverse_type" point to the class # in question, it wouldn't be defined yet. This way, it's done at # at runtime and we avoid the definition problem. Hackish, but better ...
def inverted(self)
Return the inverse of the transform.
12.405845
12.037848
1.03057
x = np.cos(lat)*np.cos(lon) y = np.cos(lat)*np.sin(lon) z = np.sin(lat) return x, y, z
def sph2cart(lon, lat)
Converts a longitude and latitude (or sequence of lons and lats) given in _radians_ to cartesian coordinates, `x`, `y`, `z`, where x=0, y=0, z=0 is the center of the globe. Parameters ---------- lon : array-like Longitude in radians lat : array-like Latitude in radians Retu...
1.56314
2.184137
0.715679
r = np.sqrt(x**2 + y**2 + z**2) lat = np.arcsin(z/r) lon = np.arctan2(y, x) return lon, lat
def cart2sph(x, y, z)
Converts cartesian coordinates `x`, `y`, `z` into a longitude and latitude. x=0, y=0, z=0 is assumed to correspond to the center of the globe. Returns lon and lat in radians. Parameters ---------- `x`, `y`, `z` : Arrays of cartesian coordinates Returns ------- lon : Longitude in radian...
1.652521
2.118608
0.780003
# Convert input to numpy arrays in radians lon, lat = np.atleast_1d(lon, lat) lon, lat = map(np.radians, [lon, lat]) theta = np.radians(theta) # Convert to cartesian coords for the rotation x, y, z = sph2cart(lon, lat) lookup = {'x':_rotate_x, 'y':_rotate_y, 'z':_rotate_z} X, Y, Z...
def _rotate(lon, lat, theta, axis='x')
Rotate "lon", "lat" coords (in _degrees_) about the X-axis by "theta" degrees. This effectively simulates rotating a physical stereonet. Returns rotated lon, lat coords in _radians_).
3.1582
3.068612
1.029195
x, y, z = sph2cart(lon, lat) return cart2sph(-x, -y, -z)
def antipode(lon, lat)
Calculates the antipode (opposite point on the globe) of the given point or points. Input and output is expected to be in radians. Parameters ---------- lon : number or sequence of numbers Longitude in radians lat : number or sequence of numbers Latitude in radians Returns ...
3.090461
6.368273
0.48529
lon0, lat0 = center strikes, dips = np.atleast_1d(strike, dip) lons = np.zeros((segments, strikes.size), dtype=np.float) lats = lons.copy() for i, (strike, dip) in enumerate(zip(strikes, dips)): # We just plot a line of constant longitude and rotate it by the strike. dip = 90 - ...
def plane(strike, dip, segments=100, center=(0, 0))
Calculates the longitude and latitude of `segments` points along the stereonet projection of each plane with a given `strike` and `dip` in degrees. Returns points for one hemisphere only. Parameters ---------- strike : number or sequence of numbers The strike of the plane(s) in degrees, wi...
2.899438
3.034957
0.955347
strike, dip = np.atleast_1d(strike, dip) mask = dip > 90 dip[mask] = 180 - dip[mask] strike[mask] += 180 # Plot the approriate point for a strike of 0 and rotate it lon, lat = -dip, 0.0 lon, lat = _rotate(lon, lat, strike) return lon, lat
def pole(strike, dip)
Calculates the longitude and latitude of the pole(s) to the plane(s) specified by `strike` and `dip`, given in degrees. Parameters ---------- strike : number or sequence of numbers The strike of the plane(s) in degrees, with dip direction indicated by the azimuth (e.g. 315 vs. 135) spec...
4.514705
5.519168
0.818005
strike, dip, rake_angle = np.atleast_1d(strike, dip, rake_angle) # Plot the approriate point for a strike of 0 and rotate it dip = 90 - dip lon = dip rake_angle = rake_angle.copy() rake_angle[rake_angle < 0] += 180 lat = 90 - rake_angle lon, lat = _rotate(lon, lat, strike) ret...
def rake(strike, dip, rake_angle)
Calculates the longitude and latitude of the linear feature(s) specified by `strike`, `dip`, and `rake_angle`. Parameters ---------- strike : number or sequence of numbers The strike of the plane(s) in degrees, with dip direction indicated by the azimuth (e.g. 315 vs. 135) specified fol...
4.290929
5.216165
0.822621
plunge, bearing = np.atleast_1d(plunge, bearing) # Plot the approriate point for a bearing of 0 and rotate it lat = 90 - plunge lon = 0 lon, lat = _rotate(lon, lat, bearing) return lon, lat
def line(plunge, bearing)
Calculates the longitude and latitude of the linear feature(s) specified by `plunge` and `bearing`. Parameters ---------- plunge : number or sequence of numbers The plunge of the line(s) in degrees. The plunge is measured in degrees downward from the end of the feature specified by the ...
5.072968
6.344127
0.799632
plunges, bearings, angles = np.atleast_1d(plunge, bearing, angle) lons, lats = [], [] for plunge, bearing, angle in zip(plunges, bearings, angles): lat = (90 - angle) * np.ones(segments, dtype=float) lon = np.linspace(-180, 180, segments) lon, lat = _rotate(lon, lat, -plunge, ax...
def cone(plunge, bearing, angle, segments=100)
Calculates the longitude and latitude of the small circle (i.e. a cone) centered at the given *plunge* and *bearing* with an apical angle of *angle*, all in degrees. Parameters ---------- plunge : number or sequence of numbers The plunge of the center of the cone(s) in degrees. The plunge i...
2.129515
2.256748
0.943621
plunge, bearing = np.atleast_1d(plunge, bearing) strike = bearing + 90 dip = 90 - plunge strike[strike >= 360] -= 360 return strike, dip
def plunge_bearing2pole(plunge, bearing)
Converts the given `plunge` and `bearing` in degrees to a strike and dip of the plane whose pole would be parallel to the line specified. (i.e. The pole to the plane returned would plot at the same point as the specified plunge and bearing.) Parameters ---------- plunge : number or sequence of ...
2.692521
3.143868
0.856436
strike, dip = np.atleast_1d(strike, dip) bearing = strike - 90 plunge = 90 - dip bearing[bearing < 0] += 360 return plunge, bearing
def pole2plunge_bearing(strike, dip)
Converts the given *strike* and *dip* in dgrees of a plane(s) to a plunge and bearing of its pole. Parameters ---------- strike : number or sequence of numbers The strike of the plane(s) in degrees, with dip direction indicated by the azimuth (e.g. 315 vs. 135) specified following the "...
2.838179
3.799164
0.747053
xyz = sph2cart(lons, lats) xyz = np.vstack(xyz).T mean_vec = xyz.mean(axis=0) r_value = np.linalg.norm(mean_vec) mean_vec = cart2sph(*mean_vec) return mean_vec, r_value
def mean_vector(lons, lats)
Returns the resultant vector from a series of longitudes and latitudes Parameters ---------- lons : array-like A sequence of longitudes (in radians) lats : array-like A sequence of latitudes (in radians) Returns ------- mean_vec : tuple (lon, lat) in radians r_v...
3.180847
2.83144
1.123402
xyz = sph2cart(lons, lats) xyz = np.vstack(xyz).T mean_vec = xyz.mean(axis=0) r_value = np.linalg.norm(mean_vec) num = xyz.shape[0] mean_vec = cart2sph(*mean_vec) if num > 1: p = (100.0 - conf) / 100.0 vector_sum = xyz.sum(axis=0) result_vect = np.sqrt(np.sum(np...
def fisher_stats(lons, lats, conf=95)
Returns the resultant vector from a series of longitudes and latitudes. If a confidence is set the function additionally returns the opening angle of the confidence small circle (Fisher, 19..) and the dispersion factor (kappa). Parameters ---------- lons : array-like A sequence of longi...
3.438732
3.187938
1.07867
plunge, bearing = geographic2plunge_bearing(lon, lat) strike = bearing + 90 strike[strike >= 360] -= 360 dip = 90 - plunge return strike, dip
def geographic2pole(lon, lat)
Converts a longitude and latitude (from a stereonet) into the strike and dip of the plane whose pole lies at the given longitude(s) and latitude(s). Parameters ---------- lon : array-like A sequence of longitudes (or a single longitude) in radians lat : array-like A sequence of lati...
3.425525
5.314806
0.644525
lon, lat = np.atleast_1d(lon, lat) x, y, z = sph2cart(lon, lat) # Bearing will be in the y-z plane... bearing = np.arctan2(z, y) # Plunge is the angle between the line and the y-z plane r = np.sqrt(x*x + y*y + z*z) r[r == 0] = 1e-15 plunge = np.arcsin(x / r) # Convert back to...
def geographic2plunge_bearing(lon, lat)
Converts longitude and latitude in stereonet coordinates into a plunge/bearing. Parameters ---------- lon, lat : numbers or sequences of numbers Longitudes and latitudes in radians as measured from a lower-hemisphere stereonet Returns ------- plunge : array The plun...
2.874029
3.057028
0.940138
norm1 = sph2cart(*pole(strike1, dip1)) norm2 = sph2cart(*pole(strike2, dip2)) norm1, norm2 = np.array(norm1), np.array(norm2) lon, lat = cart2sph(*np.cross(norm1, norm2, axis=0)) return geographic2plunge_bearing(lon, lat)
def plane_intersection(strike1, dip1, strike2, dip2)
Finds the intersection of two planes. Returns a plunge/bearing of the linear intersection of the two planes. Also accepts sequences of strike1s, dip1s, strike2s, dip2s. Parameters ---------- strike1, dip1 : numbers or sequences of numbers The strike and dip (in degrees, following the right...
3.062198
3.223473
0.949968
# Project the line onto the plane norm = sph2cart(*pole(strike, dip)) feature = sph2cart(*line(plunge, bearing)) norm, feature = np.array(norm), np.array(feature) perp = np.cross(norm, feature, axis=0) on_plane = np.cross(perp, norm, axis=0) on_plane /= np.sqrt(np.sum(on_plane**2, axis=...
def project_onto_plane(strike, dip, plunge, bearing)
Projects a linear feature(s) onto the surface of a plane. Returns a rake angle(s) along the plane. This is also useful for finding the rake angle of a feature that already intersects the plane in question. Parameters ---------- strike, dip : numbers or sequences of numbers The strike a...
3.804278
3.724231
1.021493
plunge, bearing = plane_intersection(strike, dip, azimuth, 90) rake = project_onto_plane(strike, dip, plunge, bearing) return rake
def azimuth2rake(strike, dip, azimuth)
Projects an azimuth of a linear feature onto a plane as a rake angle. Parameters ---------- strike, dip : numbers The strike and dip of the plane in degrees following the right-hand-rule. azimuth : numbers The azimuth of the linear feature in degrees clockwise from north (i.e. ...
5.768988
6.747647
0.854963
x, y, z = np.atleast_1d(x, y, z) return cart2sph(-z, x, y)
def xyz2stereonet(x, y, z)
Converts x, y, z in _world_ cartesian coordinates into lower-hemisphere stereonet coordinates. Parameters ---------- x, y, z : array-likes Sequences of world coordinates Returns ------- lon, lat : arrays Sequences of longitudes and latitudes (in radians)
3.747877
8.1452
0.460133
lon, lat = np.atleast_1d(lon, lat) x, y, z = sph2cart(lon, lat) return y, z, -x
def stereonet2xyz(lon, lat)
Converts a sequence of longitudes and latitudes from a lower-hemisphere stereonet into _world_ x,y,z coordinates. Parameters ---------- lon, lat : array-likes Sequences of longitudes and latitudes (in radians) from a lower-hemisphere stereonet Returns ------- x, y, z : arra...
3.302502
5.132492
0.64345
lon1, lat1 = first lon2, lat2 = second lon1, lat1, lon2, lat2 = np.atleast_1d(lon1, lat1, lon2, lat2) xyz1 = sph2cart(lon1, lat1) xyz2 = sph2cart(lon2, lat2) # This is just a dot product, but we need to work with multiple measurements # at once, so einsum is quicker than apply_along_axi...
def angular_distance(first, second, bidirectional=True)
Calculate the angular distance between two linear features or elementwise angular distance between two sets of linear features. (Note: a linear feature in this context is a point on a stereonet represented by a single latitude and longitude.) Parameters ---------- first : (lon, lat) 2xN array-l...
3.273063
3.633491
0.900804
vec3 = sph2cart(*center) vec3 = np.squeeze(vec3) if not np.allclose(vec3, [0, 0, 1]): vec1 = np.cross(vec3, [0, 0, 1]) else: vec1 = np.cross(vec3, [1, 0, 0]) vec2 = np.cross(vec3, vec1) vecs = [item / np.linalg.norm(item) for item in [vec1, vec2, vec3]] basis = np.column...
def _repole(lon, lat, center)
Reproject data such that ``center`` is the north pole. Returns lon, lat in the new, rotated reference frame. This is currently a sketch for a later function. Do not assume it works correctly.
2.592028
2.625711
0.987172
lon, lat = _convert_measurements(data, measurement) vals, vecs = cov_eig(lon, lat, bidirectional) x, y, z = vecs[:, vec] s, d = stereonet_math.geographic2pole(*stereonet_math.cart2sph(x, y, z)) return s[0], d[0]
def _sd_of_eigenvector(data, vec, measurement='poles', bidirectional=True)
Unifies ``fit_pole`` and ``fit_girdle``.
6.229185
6.1844
1.007242
lon, lat = _convert_measurements(args, kwargs.get('measurement', 'poles')) vals, vecs = cov_eig(lon, lat, kwargs.get('bidirectional', True)) lon, lat = stereonet_math.cart2sph(*vecs) plunges, bearings = stereonet_math.geographic2plunge_bearing(lon, lat) # Largest eigenvalue first... return ...
def eigenvectors(*args, **kwargs)
Finds the 3 eigenvectors and eigenvalues of the 3D covariance matrix of a series of geometries. This can be used to fit a plane/pole to a dataset or for shape fabric analysis (e.g. Flinn/Hsu plots). Input arguments will be interpreted as poles, lines, rakes, or "raw" longitudes and latitudes based on ...
7.270768
4.918126
1.478361
lon, lat = _convert_measurements(args, kwargs.get('measurement', 'lines')) vector, r_value = stereonet_math.mean_vector(lon, lat) plunge, bearing = stereonet_math.geographic2plunge_bearing(*vector) return (plunge[0], bearing[0]), r_value
def find_mean_vector(*args, **kwargs)
Returns the mean vector for a set of measurments. By default, this expects the input to be plunges and bearings, but the type of input can be controlled through the ``measurement`` kwarg. Parameters ---------- *args : 2 or 3 sequences of measurements By default, this will be expected to be...
7.443583
4.625436
1.609272
# How the heck did this wind up as a separate function? lon, lat = _convert_measurements(args, kwargs.get('measurement', 'lines')) conf = kwargs.get('conf', 95) center, stats = stereonet_math.fisher_stats(lon, lat, conf) plunge, bearing = stereonet_math.geographic2plunge_bearing(*center) me...
def find_fisher_stats(*args, **kwargs)
Returns the mean vector and summary statistics for a set of measurements. By default, this expects the input to be plunges and bearings, but the type of input can be controlled through the ``measurement`` kwarg. Parameters ---------- *args : 2 or 3 sequences of measurements By default, this...
8.654612
5.251937
1.647889
lon, lat = _convert_measurements(args, kwargs.get('measurement', 'poles')) num = kwargs.get('num', 2) bidirectional = kwargs.get('bidirectional', True) tolerance = kwargs.get('tolerance', 1e-5) points = lon, lat dist = lambda x: stereonet_math.angular_distance(x, points, bidirectional) ...
def kmeans(*args, **kwargs)
Find centers of multi-modal clusters of data using a kmeans approach modified for spherical measurements. Parameters ---------- *args : 2 or 3 sequences of measurements By default, this will be expected to be ``strike`` & ``dip``, both array-like sequences representing poles to planes....
3.515978
2.991183
1.175448
if isinstance(e, OperationalError): # these error messages from libpq: interfaces/libpq/fe-misc.c. # TODO: these are sent through gettext in libpq and we can't # check within other locales - consider using connection.closed return 'terminating connection' in str(e) or \ ...
def is_disconnect(e, connection, cursor)
Connection state check from SQLAlchemy: https://bitbucket.org/sqlalchemy/sqlalchemy/src/tip/lib/sqlalchemy/dialects/postgresql/psycopg2.py
6.521688
6.293531
1.036253
self.close() # _DBProxy.dispose doesn't actually call dispose on the pool conn_params = self.get_connection_params() key = db_pool._serialize(**conn_params) try: pool = db_pool.pools[key] except KeyError: pass else: poo...
def _dispose(self)
Dispose of the pool for this instance, closing all connections.
5.630919
4.563919
1.23379
'''Calculates shape of data after encoding. Parameters ---------- img_height : int Height of input image. img_width : int Width of input image. Returns ------- encoded_shape : tuple(int) Gives back 3-tuple with new dims. ''' height, width = img_height, i...
def calc_fc_size(img_height, img_width)
Calculates shape of data after encoding. Parameters ---------- img_height : int Height of input image. img_width : int Width of input image. Returns ------- encoded_shape : tuple(int) Gives back 3-tuple with new dims.
4.750748
2.753993
1.72504
'''Calculates shape of data after decoding. Parameters ---------- img_height : int Height of encoded data. img_width : int Width of encoded data. Returns ------- encoded_shape : tuple(int) Gives back 2-tuple with decoded image dimensions. ''' height, wid...
def calc_im_size(img_height, img_width)
Calculates shape of data after decoding. Parameters ---------- img_height : int Height of encoded data. img_width : int Width of encoded data. Returns ------- encoded_shape : tuple(int) Gives back 2-tuple with decoded image dimensions.
4.399926
2.357345
1.866476
'''Gets all the paths of non-hidden files in a directory and returns a list of those paths. Parameters ---------- directory : str The directory whose contents you wish to grab. Returns ------- paths : List[str] ''' fnames = [os.path.join(directory, f) f...
def get_paths(directory)
Gets all the paths of non-hidden files in a directory and returns a list of those paths. Parameters ---------- directory : str The directory whose contents you wish to grab. Returns ------- paths : List[str]
2.877195
1.902711
1.512156
'''Resizes all images with given paths to new dimensions. Uses up/downscaling with antialiasing. Parameters ---------- file_paths : List[str] List of path strings for image to resize. new_dir : str Directory to place resized images. width : int Target width of ne...
def image_resize(file_paths, new_dir, width, height)
Resizes all images with given paths to new dimensions. Uses up/downscaling with antialiasing. Parameters ---------- file_paths : List[str] List of path strings for image to resize. new_dir : str Directory to place resized images. width : int Target width of new resiz...
2.368083
1.557812
1.520134
'''Transform latent vectors into images. Parameters ---------- data : array-like shape (n_images, latent_width) Input numpy array of images. test [optional] : bool Controls the test boolean for batch normalization. Returns ------- ...
def inverse_transform(self, data, test=False)
Transform latent vectors into images. Parameters ---------- data : array-like shape (n_images, latent_width) Input numpy array of images. test [optional] : bool Controls the test boolean for batch normalization. Returns ------- images : a...
2.917955
2.155266
1.353872
'''Load in image files from list of paths. Parameters ---------- filepaths : List[str] List of file paths of images to be loaded. Returns ------- images : array-like shape (n_images, n_colors, image_width, image_height) Images normalized...
def load_images(self, filepaths)
Load in image files from list of paths. Parameters ---------- filepaths : List[str] List of file paths of images to be loaded. Returns ------- images : array-like shape (n_images, n_colors, image_width, image_height) Images normalized to have pi...
3.410784
2.129327
1.601813
'''Saves model as a sequence of files in the format: {path}/{name}_{'model', 'opt', 'meta'}.h5 Parameters ---------- path : str The directory of the file you wish to save the model to. name : str The name prefix of the model and optimizer file...
def save(self, path, name, save_meta=True)
Saves model as a sequence of files in the format: {path}/{name}_{'model', 'opt', 'meta'}.h5 Parameters ---------- path : str The directory of the file you wish to save the model to. name : str The name prefix of the model and optimizer files you wish ...
3.854162
1.590031
2.423954
'''Loads in model as a class instance with with the specified model and optimizer states. Parameters ---------- model : str Path to the model state file. opt : str Path to the optimizer state file. meta : str Path to the cla...
def load(cls, model, opt, meta, flag_gpu=None)
Loads in model as a class instance with with the specified model and optimizer states. Parameters ---------- model : str Path to the model state file. opt : str Path to the optimizer state file. meta : str Path to the class metadata...
2.651856
1.721816
1.54015
'''Saves model as a sequence of files in the format: {path}/{name}_{'dec', 'disc', 'dec_opt', 'disc_opt', 'meta'}.h5 Parameters ---------- path : str The directory of the file you wish to save the model to. name : str The name pref...
def save(self, path, name, save_meta=True)
Saves model as a sequence of files in the format: {path}/{name}_{'dec', 'disc', 'dec_opt', 'disc_opt', 'meta'}.h5 Parameters ---------- path : str The directory of the file you wish to save the model to. name : str The name prefix of the m...
3.086295
1.407966
2.192024