code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') file_content = fp.read().decode(encoding) json_data = json.loads(file_content, object_pairs_hook=OrderedDict) return json.dumps(json_data, indent=4, separators=(',', ': '))
def render(file)
Pretty print the JSON file for rendering.
2.728221
2.472324
1.103505
max_file_size = current_app.config.get( 'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024) if file.size > max_file_size: return False with file.open() as fp: try: json.loads(fp.read().decode('utf-8')) return True except: return False
def validate_json(file)
Validate a JSON file.
2.782277
2.744348
1.013821
from .opt_space import opt_space N = edm_missing.shape[0] X, S, Y, __ = opt_space(edm_missing, r=rank, niter=niter, tol=tol, print_out=print_out) edm_complete = X.dot(S.dot(Y.T)) edm_complete[range(N), range(N)] = 0.0 return edm_complete
def optspace(edm_missing, rank, niter=500, tol=1e-6, print_out=False)
Complete and denoise EDM using OptSpace algorithm. Uses OptSpace algorithm to complete and denoise EDM. The problem being solved is X,S,Y = argmin_(X,S,Y) || W ° (D - XSY') ||_F^2 :param edm_missing: EDM with 0 where no measurement was taken. :param rank: expected rank of complete EDM. :param nite...
3.086283
2.886522
1.069205
from pylocus.basics import low_rank_approximation errs = [] N = edm_missing.shape[0] edm_complete = edm_missing.copy() edm_complete[edm_complete == 0] = np.mean(edm_complete[edm_complete > 0]) for i in range(niter): # impose matrix rank edm_complete = low_rank_approximation(...
def rank_alternation(edm_missing, rank, niter=50, print_out=False, edm_true=None)
Complete and denoise EDM using rank alternation. Iteratively impose rank and strucutre to complete marix entries :param edm_missing: EDM with 0 where no measurement was taken. :param rank: expected rank of complete EDM. :param niter: maximum number of iterations. :param edm: if given, the relative...
2.753413
2.502064
1.100457
from .algorithms import reconstruct_mds def kappa(gram): n = len(gram) e = np.ones(n) return np.outer(np.diag(gram), e) + np.outer(e, np.diag(gram).T) - 2 * gram def kappa_cvx(gram, n): e = np.ones((n, 1)) return reshape(diag(gram), (n, 1)) * e.T + e * reshape...
def semidefinite_relaxation(edm_missing, lamda, W=None, print_out=False, **kwargs)
Complete and denoise EDM using semidefinite relaxation. Returns solution to the relaxation of the following problem: D = argmin || W * (D - edm_missing) || s.t. D is EDM where edm_missing is measured matrix, W is a weight matrix, and * is pointwise multiplication. Refer to paper "Eu...
3.618522
3.502786
1.033041
from .algorithms import reconstruct_acd Xhat, costs = reconstruct_acd(edm, X0, W, tol=tol, sweeps=sweeps) return get_edm(Xhat)
def completion_acd(edm, X0, W=None, tol=1e-6, sweeps=3)
Complete an denoise EDM using alternating decent. The idea here is to simply run reconstruct_acd for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matrix (NxN) :param X0: starting points (Nxd) :param W: opt...
5.875488
4.834104
1.215424
from .algorithms import reconstruct_dwmds Xhat, costs = reconstruct_dwmds(edm, X0, W, n=1, tol=tol, sweeps=sweeps) return get_edm(Xhat)
def completion_dwmds(edm, X0, W=None, tol=1e-10, sweeps=100)
Complete an denoise EDM using dwMDS. The idea here is to simply run reconstruct_dwmds for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matrix (NxN) :param X0: starting points (Nxd) :param W: optional weigh...
5.521485
5.10508
1.081567
p = _to_tornado_pattern(transmute_path) for m in METHODS: method = getattr(handler, m) if hasattr(method, "transmute_func"): method.transmute_func.paths.add(transmute_path) return tornado.web.URLSpec( p, handler, *args, **kwargs )
def url_spec(transmute_path, handler, *args, **kwargs)
convert the transmute_path to a tornado compatible regex, and return a tornado url object.
3.89326
3.759751
1.03551
import itertools from pylocus.basics_angles import from_0_to_pi theta = np.empty((self.M, )) corners = np.empty((self.M, 3)) k = 0 indices = np.arange(self.N) for triangle in itertools.combinations(indices, 3): for counter, idx in enumerate(tr...
def create_theta(self)
Returns the set of inner angles (between 0 and pi) reconstructed from point coordinates. Also returns the corners corresponding to each entry of theta.
3.134419
2.895575
1.082486
from pylocus.basics_angles import from_0_to_2pi theta_ij = own.abs_angles[i, j] theta_ji = own.abs_angles[j, i] # complicated xi = own.points[i, 0] xj = own.points[j, 0] yi = own.points[i, 1] yj = own.points[j, 1] w = np.array([yi - yj, x...
def get_orientation(k, i, j)
calculate angles theta_ik and theta_jk theta produce point Pk. Should give the same as get_absolute_angle!
2.903848
2.790103
1.040767
indices_rays = [] indices_triangles = [] corners_rays = [] angles_rays = [] for t, triangle in enumerate(self.corners): if triangle[0] == k: indices_rays.append(t) corners_rays.append(triangle) angles_rays.appen...
def get_indices(self, k)
Get indices of theta vector that have k as first corner. :param k: Index of corner. :return indices_rays: Indices of ray angles in theta vector. :return indices_triangles: Indices of triangle angles in theta vector. :return corners_rays: List of corners of ray angles. :...
2.375157
1.90352
1.247771
G = np.ones((self.N - 1, self.N - 1)) if (add_noise): noise = pi * 0.1 * np.random.rand( (self.N - 1) * (self.N - 1)).reshape((self.N - 1, self.N - 1)) other_indices = np.delete(range(self.N), k) for idx, i in enumerate(other_indices): for...
def get_G(self, k, add_noise=True)
get G matrix from angles.
2.840688
2.627131
1.081289
convex_polygons = [] for corners in itertools.combinations(np.arange(self.N), m): p = np.zeros(m, np.uint) p[0] = corners[0] left = corners[1:] # loop through second corners for i, second in enumerate(corners[1:m - 1]): ...
def get_convex_polygons(self, m, print_out=False)
:param m: size of polygones (number of corners) :return: (ordered) indices of all convex polygones of size m.
3.604878
3.459409
1.04205
rows_A = [] rows_b = [] for m in range_polygones: if (print_out): print('checking {}-polygones'.format(m)) polygons = self.get_convex_polygons(m) row_A, row_b = self.get_polygon_constraints_m(polygons, print_out) rows_A.app...
def get_polygon_constraints(self, range_polygones=range(3, 5), print_out=False)
:param range_polygones: list of numbers of polygones to test. :return A, b: the constraints on the theta-vector of the form A*theta = b
2.302935
2.292702
1.004463
rows_b = [] rows_A = [] m = len(polygons_m[0]) rows_b.append((m - 2) * pi * np.ones( len(polygons_m), )) for p in polygons_m: row = np.zeros((self.theta.shape[0], )) for k in range(m): index = get_index(self.corners, p[...
def get_polygon_constraints_m(self, polygons_m, print_out=False)
:param range_polygones: list of numbers of polygones to test. :return A, b: the constraints on the theta-vector of the form A*theta = b
4.06946
3.837183
1.060533
C2 = np.eye(self.m) C2 = C2[:self.m - 2, :] to_be_deleted = [] for idx_vij_1 in range(self.m - 2): idx_vij_2 = idx_vij_1 + 1 C2[idx_vij_1, idx_vij_2] = -1 i1 = np.where(self.C[idx_vij_1, :] == 1)[0][0] i2 = np.where(self.C[idx_vij_...
def get_KE_constraints(self)
Get linear constraints on KE matrix.
2.312556
2.292181
1.008889
self.validate_packet(data) results = self.parse_header_part(data) sub_type = results['packet_subtype'] id_ = self.dump_hex(data[4:8]) unit_code = data[8] command = data[9] command_text = SUB_TYPE_COMMANDS.get(sub_type, {}).get(command) dim_lev...
def parse(self, data)
Parse a 12 bytes packet in the Lighting2 format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x111F342", 'packet_length': 10, 'packet_type': 17, ...
4.764657
3.829511
1.244195
return ((bytes_[0] * pow(2, 40)) + (bytes_[1] * pow(2, 32)) + (bytes_[2] * pow(2, 24)) + (bytes_[3] << 16) + (bytes_[4] << 8) + bytes_[4])
def _bytes_to_uint_48(self, bytes_)
Converts an array of 6 bytes to a 48bit integer. :param data: bytearray to be converted to a 48bit integer :type data: bytearray :return: the integer :rtype: int
2.221848
2.489456
0.892504
self.validate_packet(data) TOTAL_DIVISOR = 223.666 id_ = self.dump_hex(data[4:6]) count = data[6] instant = data[7:11] total = data[11:16] current_watts = self._bytes_to_uint_32(instant) total_watts = self._bytes_to_uint_48(total) / TOTAL_DIVI...
def parse(self, data)
Parse a 18 bytes packet in the Electricity format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'count': 3, 'current_watts': 692, 'id': "0x2EB2", ...
4.86228
3.933745
1.236044
''' cache key has to be < 250 chars to avoid memcache.Client.MemcachedKeyLengthError The best algoritm is SHA-224 whose output (224 chars) respects this limitations ''' key = '{}_{}'.format(path, site_id) key = hashlib.sha224(key.encode('utf-8')).hexdigest() return key
def get_key_from_path_and_site(path, site_id)
cache key has to be < 250 chars to avoid memcache.Client.MemcachedKeyLengthError The best algoritm is SHA-224 whose output (224 chars) respects this limitations
9.555419
1.81229
5.272567
try: # Detect encoding and dialect with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') sample = fp.read( current_app.config.get('PREVIEWER_CSV_VALIDATION_BYTES', 1024)) delimiter = csv.Sniffer().sniff(sample.decode(encoding...
def validate_csv(file)
Return dialect information about given csv file.
3.517842
3.33249
1.05562
file_info = validate_csv(file) return render_template( 'invenio_previewer/csv_bar.html', file=file, delimiter=file_info['delimiter'], encoding=file_info['encoding'], js_bundles=current_previewer.js_bundles + ['previewer_csv_js'], css_bundles=current_previewer...
def preview(file)
Render appropiate template with embed flag.
4.622226
4.718009
0.979699
max_files_count = current_app.config.get('PREVIEWER_ZIP_MAX_FILES', 1000) tree = {'type': 'folder', 'id': -1, 'children': {}} try: with file.open() as fp: zf = zipfile.ZipFile(fp) # Detect filenames encoding. sample = ' '.join(zf.namelist()[:max_files_count]...
def make_tree(file)
Create tree structure from ZIP archive.
2.814683
2.693874
1.044846
if node['type'] == 'item' and len(node['children']) == 0: del node['children'] else: node['type'] = 'folder' node['children'] = list(node['children'].values()) node['children'].sort(key=lambda x: x['name']) node['children'] = map(children_to_list, node['children']) ...
def children_to_list(node)
Organize children structure.
2.448196
2.295677
1.066438
tree, limit_reached, error = make_tree(file) list = children_to_list(tree)['children'] return render_template( "invenio_previewer/zip.html", file=file, tree=list, limit_reached=limit_reached, error=error, js_bundles=current_previewer.js_bundles + ['previe...
def preview(file)
Return appropriate template and pass the file and an embed flag.
5.217541
5.221181
0.999303
N = edm.shape[0] if n is None: n = N found = False max_it = 100 i = 0 while not found: i += 1 dm = np.sqrt(edm) + np.random.normal(scale=noise, size=edm.shape) dm = np.triu(dm) edm_noisy = np.power(dm + dm.T, 2) edm_noisy[range(N), range(N)] =...
def create_noisy_edm(edm, noise, n=None)
Create noisy version of edm Adds symmetric Gaussian noise to non-diagonal elements of EDM (to distances!). The output EDM is ensured to have only positive entries. :param edm: Original, noiseless EDM. :param noise: Standard deviation of Gaussian noise to be added to distances. :param n: H...
2.96747
3.030348
0.979251
weights = np.ones((N, N)) weights[range(N), range(N)] = 0 if method == 'none': return weights # create indices object to choose from elif method == 'all': all_indices = np.triu_indices(N, 1) elif method == 'first': all_indices = [np.zeros(N - 1).astype(np.int), ...
def create_mask(N, method='all', nmissing=0)
Create weight mask according to method. :param N: Dimension of square weight matrix. :param method: Method to use (default: 'all'). - none: no missing entries (only diagonal is set to 0 for dwMDS) - first: only randomly delete measurements to first point (zeros in first row/column of matrix) - all:...
2.84643
2.751767
1.034401
# if we have a single method, make it a list. if isinstance(kwargs.get("paths"), string_type): kwargs["paths"] = [kwargs["paths"]] if isinstance(kwargs.get("methods"), string_type): kwargs["methods"] = [kwargs["methods"]] attrs = TransmuteAttributes(**kwargs) def decorator(f): ...
def describe(**kwargs)
describe is a decorator to customize the rest API that transmute generates, such as choosing certain arguments to be query parameters or body parameters, or a different method. :param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a path) :param list(str) met...
3.285742
3.252323
1.010275
app.router.add_route('GET', json_route, create_swagger_json_handler(app)) add_swagger_api_route(app, html_route, json_route)
def add_swagger(app, json_route, html_route)
a convenience method for both adding a swagger.json route, as well as adding a page showing the html documentation
3.244476
3.468458
0.935423
static_root = get_swagger_static_root() swagger_body = generate_swagger_html( STATIC_ROOT, swagger_json_route ).encode("utf-8") async def swagger_ui(request): return web.Response(body=swagger_body, content_type="text/html") app.router.add_route("GET", target_route, swagger_ui)...
def add_swagger_api_route(app, target_route, swagger_json_route)
mount a swagger statics page. app: the aiohttp app object target_route: the path to mount the statics page. swagger_json_route: the path where the swagger json definitions is expected to be.
2.768303
2.848673
0.971787
spec = get_swagger_spec(app).swagger_definition(**kwargs) encoded_spec = json.dumps(spec).encode("UTF-8") async def swagger(request): return web.Response( # we allow CORS, so this can be requested at swagger.io headers={ "Access-Control-Allow-Origin": "...
def create_swagger_json_handler(app, **kwargs)
Create a handler that returns the swagger definition for an application. This method assumes the application is using the TransmuteUrlDispatcher as the router.
4.540156
4.486001
1.012072
import matplotlib.gridspec as gridspec fig = plt.figure() nrows = 1 if len(tag_ids) > 1: nrows = 2 fig.set_size_inches(10, 5*nrows) gs = gridspec.GridSpec(nrows, len(tag_ids)) ax_list = [fig.add_subplot(g) for g in gs] ax_dict = {} for i, tag_dict in enumerate(tag_ids):...
def create_multispan_plots(tag_ids)
Create detail plots (first row) and total block(second row) of experiments. Args: tag_ids: list of tag-dictionaries, where the dictionaries must have fields 'name' (used for naming) and 'id' (used for numbering axis_dict) Returns: Figure element fig, ax_di...
2.070836
1.907866
1.08542
try: theta_new = np.zeros(theta.shape) for i, thet in enumerate(theta): try: # theta is vector theta_new[i] = method(thet, tol) except: # theta is matrix for j, th in enumerate(thet): try...
def change_angles(method, theta, tol=1e-10)
Function used by all angle conversion functions (from_x_to_x_pi(...))
2.07323
2.072001
1.000593
''' Calcualte rmse between vector or matrix x and xhat, ignoring mod of 2pi.''' real_diff = from_0_to_pi(x - xhat) np.square(real_diff, out=real_diff) sum_ = np.sum(real_diff) return sqrt(sum_ / len(x))
def rmse_2pi(x, xhat)
Calcualte rmse between vector or matrix x and xhat, ignoring mod of 2pi.
6.741351
3.654551
1.844645
A = np.array([[sin(theta_ik), -cos(theta_ik)], [sin(theta_jk), -cos(theta_jk)]]) B = np.array([[sin(theta_ik), -cos(theta_ik), 0, 0], [0, 0, sin(theta_jk), -cos(theta_jk)]]) p = np.r_[Pi, Pj] Pk = np.linalg.solve(A, np.dot(B, p)) return Pk
def get_point(theta_ik, theta_jk, Pi, Pj)
Calculate coordinates of point Pk given two points Pi, Pj and inner angles. :param theta_ik: Inner angle at Pi to Pk. :param theta_jk: Inner angle at Pj to Pk. :param Pi: Coordinates of point Pi. :param Pj: Coordinates of point Pj. :return: Coordinate of point Pk.
2.041939
2.009101
1.016344
return_value = [] for s in self.serializers: return_value += s.content_type return return_value
def keys(self)
return a list of the content types this set supports. this is not a complete list: serializers can accept more than one content type. However, it is a good representation of the class of content types supported.
8.484439
4.382073
1.93617
params = Parameters() used_keys = set(arguments_to_ignore or []) # examine what variables are categorized first. for key in ["query", "header", "path"]: param_set = getattr(params, key) explicit_parameters = getattr(transmute_attrs, key + "_parameters") used_keys |= load_par...
def get_parameters(signature, transmute_attrs, arguments_to_ignore=None)
given a function, categorize which arguments should be passed by what types of parameters. The choices are: * query parameters: passed in as query parameters in the url * body parameters: retrieved from the request body (includes forms) * header parameters: retrieved from the request header * path ...
3.055668
3.010331
1.015061
params = set() for path in paths: parts = PART_REGEX.split(path) for p in parts: match = PARAM_REGEX.match(p) if match: params.add(match.group("name")) return params
def _extract_path_parameters_from_paths(paths)
from a list of paths, return back a list of the arguments present in those paths. the arguments available in all of the paths must match: if not, an exception will be raised.
3.053982
3.296311
0.926485
description = "" if isinstance(body_parameters, Param): schema = serializer.to_json_schema(body_parameters.arginfo.type) description = body_parameters.description required = True else: if len(body_parameters) == 0: return None required = set() ...
def _build_body_schema(serializer, body_parameters)
body is built differently, since it's a single argument no matter what.
2.466414
2.394638
1.029974
self.validate_packet(data) results = self.parse_header_part(data) sub_type = results['packet_subtype'] id_ = self.dump_hex(data[4:6]) direction = data[6] * 256 + data[7] if sub_type != 0x05: av_speed = (data[8] * 256 + data[9]) * 0.1 else:...
def parse(self, data)
Parse a 17 bytes packet in the Wind format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x2EB2", 'packet_length': 16, 'packet_type': 86, ...
2.409236
2.073192
1.16209
def centralize(X): n = X.shape[0] ones = np.ones((n, 1)) return X - np.multiply(1 / n * np.dot(ones.T, X), ones) m = anchors.shape[0] N, d = X.shape assert m >= d, 'Have to give at least d anchor nodes.' X_m = X[N - m:, :] ones = np.ones((m, 1)) mux = 1 / m * np...
def procrustes(anchors, X, scale=True, print_out=False)
Fit X to anchors by applying optimal translation, rotation and reflection. Given m >= d anchor nodes (anchors in R^(m x d)), return transformation of coordinates X (output of EDM algorithm) optimally matching anchors in least squares sense. :param anchors: Matrix of shape m x d, where m is number of ancho...
3.262025
3.092787
1.05472
from .point_set import dm_from_edm N = all_points.shape[0] d = all_points.shape[1] dm = dm_from_edm(edm) if method is None: from .mds import superMDS Xhat, __ = superMDS(all_points[0, :], N, d, Om=Om, dm=dm) else: C = kwargs.get('C', None) b = kwargs.get('b',...
def reconstruct_emds(edm, Om, all_points, method=None, **kwargs)
Reconstruct point set using E(dge)-MDS.
3.26264
3.184506
1.024536
from pylocus.point_set import dmi_from_V, sdm_from_dmi, get_V from pylocus.mds import signedMDS N = all_points.shape[0] V = get_V(absolute_angles, dm) dmx = dmi_from_V(V, 0) dmy = dmi_from_V(V, 1) sdmx = sdm_from_dmi(dmx, N) sdmy = sdm_from_dmi(dmy, N) points_x = signedMDS(...
def reconstruct_cdm(dm, absolute_angles, all_points, W=None)
Reconstruct point set from angle and distance measurements, using coordinate difference matrices.
3.657331
3.539901
1.033173
from .point_set import dm_from_edm from .mds import MDS N = all_points.shape[0] d = all_points.shape[1] if mask is not None: edm_missing = np.multiply(edm, mask) if completion == 'optspace': from .edm_completion import optspace edm_complete = optspace(edm...
def reconstruct_mds(edm, all_points, completion='optspace', mask=None, method='geometric', print_out=False, n=1)
Reconstruct point set using MDS and matrix completion algorithms.
4.015497
3.954388
1.015453
from .edm_completion import semidefinite_relaxation edm_complete = semidefinite_relaxation( edm, lamda=lamda, W=W, print_out=print_out, **kwargs) Xhat = reconstruct_mds(edm_complete, all_points, method='geometric') return Xhat, edm_complete
def reconstruct_sdp(edm, all_points, W=None, print_out=False, lamda=1000, **kwargs)
Reconstruct point set using semi-definite rank relaxation.
4.996075
4.393308
1.137201
from .lateration import SRLS, get_lateration_parameters Y = all_points.copy() indices = range(n) for index in indices: anchors, w, r2 = get_lateration_parameters(all_points, indices, index, edm, W) if print_out: print('S...
def reconstruct_srls(edm, all_points, W=None, print_out=False, n=1, rescale=False, z=None)
Reconstruct point set using S(quared)R(ange)L(east)S(quares) method.
4.27369
4.254146
1.004594
def get_unique_delta(delta, i, coord, print_out=False): delta_unique = delta.copy() ftest = [] for de in delta_unique: X_ktest = X_k.copy() X_ktest[i, coord] += de ftest.append(f(X_ktest, edm, W)) # choose delta_unique with lowest cost. ...
def reconstruct_acd(edm, X0, W=None, print_out=False, tol=1e-10, sweeps=10)
Reconstruct point set using alternating coordinate descent. :param X0: Nxd matrix of starting points. :param tol: Stopping criterion: if the stepsize in all coordinate directions is less than tol for 2 consecutive sweeps, we stop. :param sweep: Maximum number of sweeps. One sweep goes thr...
2.908955
2.872301
1.012761
from .basics import get_edm from .distributed_mds import get_b, get_Si N, d = X0.shape if r is None and n is None: raise ValueError('either r or n have to be given.') elif n is None: n = r.shape[0] if W is None: W = np.ones((N, N)) - np.eye(N) X_k = X0.copy() ...
def reconstruct_dwmds(edm, X0, W=None, n=None, r=None, X_bar=None, print_out=False, tol=1e-10, sweeps=100)
Reconstruct point set using d(istributed)w(eighted) MDS. Refer to paper "Distributed Weighted-Multidimensional Scaling for Node Localization in Sensor Networks" for implementation details (doi.org/10.1145/1138127.1138129) :param X0: Nxd matrix of starting points. :param n: Number of points of unknown...
3.282356
3.224011
1.018097
self.validate_packet(data) results = self.parse_header_part(data) sub_type = results['packet_subtype'] id_ = self.dump_hex(data[4:6]) rain_rate_high = data[6] rain_rate_low = data[7] if sub_type == 0x01: rain_rate = rain_rate_high * 0x100 ...
def parse(self, data)
Parse a 12 bytes packet in the Rain format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x2EB2", 'packet_length': 11, 'packet_type': 85, ...
2.661302
2.396027
1.110714
if W is None: W = np.ones(edm.shape) # delete points that are not considered anchors anchors = np.delete(all_points, indices, axis=0) r2 = np.delete(edm[index, :], indices) w = np.delete(W[index, :], indices) # set w to zero where measurements are invalid if np.isnan(r2).any()...
def get_lateration_parameters(all_points, indices, index, edm, W=None)
Get parameters relevant for lateration from full all_points, edm and W.
2.174753
2.164227
1.004863
''' Algorithm used by pozyx (https://www.pozyx.io/Documentation/how_does_positioning_work) :param anchors: anchor points :param r2: squared distances from anchors to point x. :returns: estimated position of point x. ''' N = anchors.shape[0] anchors_term = np.sum(np.power(anchors[:-1], 2), ...
def PozyxLS(anchors, W, r2, print_out=False)
Algorithm used by pozyx (https://www.pozyx.io/Documentation/how_does_positioning_work) :param anchors: anchor points :param r2: squared distances from anchors to point x. :returns: estimated position of point x.
4.084221
2.220167
1.839601
def cost_function(arr): X = np.c_[arr] r_measured = np.linalg.norm(anchors - X) mse = np.linalg.norm(r_measured - r)**2 return mse if grid is None: grid = [np.min(anchors, axis=0), np.max(anchors, axis=0)] d = anchors.shape[1] x = np.linspace(grid[0][0], gr...
def RLS(anchors, W, r, print_out=False, grid=None, num_points=10)
Range least squares (RLS) using grid search. Algorithm written by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems". :param anchors: anchor points :param r2: squared distances from anchors to point x. :param grid: where to search for solution. (min, max) where min ...
1.888516
1.830356
1.031775
from pylocus.basics import low_rank_approximation, eigendecomp from pylocus.mds import x_from_eigendecomp m = anchors.shape[0] d = anchors.shape[1] G = Variable(m + 1, m + 1) X = Variable(d + 1, d + 1) constraints = [G[m, m] == 1.0, X[d, d] == 1.0, ...
def RLS_SDR(anchors, W, r, print_out=False)
Range least squares (RLS) using SDR. Algorithm cited by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems". :param anchors: anchor points :param r2: squared distances from anchors to point x. :return: estimated position of point x.
3.099973
3.024101
1.025089
if nxt is None: return base if isinstance(base, set) and isinstance(nxt, set): return base | nxt else: return nxt
def _join_parameters(base, nxt)
join parameters from the lhs to the rhs, if compatible.
2.95855
2.798843
1.057062
consumes = produces = context.contenttype_serializers.keys() parameters = get_swagger_parameters(self.parameters, context) responses = { "400": Response( { "description": "invalid input received", "schema": Schema( ...
def get_swagger_operation(self, context=default_context)
get the swagger_schema operation representation.
2.874531
2.825874
1.017218
return process_result(self, context, result_body, exc, content_type)
def process_result(self, context, result_body, exc, content_type)
given an result body and an exception object, return the appropriate result object, or raise an exception.
3.218941
2.87932
1.117952
return_type = argspec.annotations.get("return") or None type_description = attrs.parameter_descriptions.get("return", "") response_types = attrs.response_types.copy() if return_type or len(response_types) == 0: response_types[attrs.success_code] = ResponseType( ...
def _parse_response_types(argspec, attrs)
from the given parameters, return back the response type dictionaries.
4.035606
3.833576
1.0527
tmpl = _get_template("swagger.html") return tmpl.render( swagger_root=swagger_static_root, swagger_json_url=swagger_json_url )
def generate_swagger_html(swagger_static_root, swagger_json_url)
given a root directory for the swagger statics, and a swagger json path, return back a swagger html designed to use those values.
3.154108
3.472931
0.908198
swagger_path = transmute_func.get_swagger_path(transmute_context) for p in transmute_func.paths: self.add_path(p, swagger_path)
def add_func(self, transmute_func, transmute_context)
add a transmute function's swagger definition to the spec
4.289437
3.607135
1.189154
if path not in self._swagger: self._swagger[path] = path_item else: for method, definition in path_item.items(): if definition is not None: setattr(self._swagger[path], method, definition)
def add_path(self, path, path_item)
for a given path, add the path items.
3.272462
3.063787
1.06811
return Swagger( { "info": Info( { key: kwargs.get(key, self.DEFAULT_INFO.get(key)) for key in Info.fields.keys() if key in kwargs or key in self.DEFAULT_INFO } ...
def swagger_definition(self, base_path=None, **kwargs)
return a valid swagger spec, with the values passed.
3.465373
3.141261
1.103179
''' Wrapper to call the spied-on function. Operates similar to Expectation.test. ''' if self._spy_side_effect: if self._spy_side_effect_args or self._spy_side_effect_kwargs: self._spy_side_effect( *self._spy_side_effect_args, **se...
def _call_spy(self, *args, **kwargs)
Wrapper to call the spied-on function. Operates similar to Expectation.test.
3.397964
2.207797
1.539074
''' Wrap side effects for spies. ''' self._spy_side_effect = func self._spy_side_effect_args = args self._spy_side_effect_kwargs = kwargs return self
def side_effect(self, func, *args, **kwargs)
Wrap side effects for spies.
4.249945
2.513011
1.691176
a, l = glob['args'], glob['logger'] enabled = getattr(a, a._collisions.get("interact") or "interact", False) if enabled: readline.parse_and_bind('tab: complete') # InteractiveConsole as defined in the code module, but handling a banner # using the logging of tinyscript class Inter...
def set_interact_items(glob)
This function prepares the interaction items for inclusion in main script's global scope. :param glob: main script's global scope dictionary reference
3.169853
3.213457
0.986431
levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG] \ if multi_level else [logging.INFO, logging.DEBUG] try: verbose = min(int(glob['args'].verbose), 3) except AttributeError: verbose = 0 glob['args']._debug_level = dl = levels[verbose] logger.han...
def configure_logger(glob, multi_level, relative=False, logfile=None, syslog=False)
Logger configuration function for setting either a simple debug mode or a multi-level one. :param glob: globals dictionary :param multi_level: boolean telling if multi-level debug is to be considered :param relative: use relative time for the logging messages :param logfile: log ...
3.421988
3.636935
0.940899
if isinstance(result, Response): response = result else: response = Response( result=result, code=transmute_func.success_code, success=True ) if exc: if isinstance(exc, APIException): response.result = str(exc) response.success = False...
def process_result(transmute_func, context, result, exc, content_type)
process a result: transmute_func: the transmute_func function that returned the response. context: the transmute_context to use. result: the return value of the function, which will be serialized and returned back in the API. exc: the exception object. For Python 2, the traceback should ...
3.45114
3.579296
0.964195
def svds_descending(M, k): ''' In contrast to MATLAB, numpy's svds() arranges the singular values in ascending order. In order to have matching codes, we wrap it around by a function which re-sorts the singular values and singular vectors. Args: M: 2D numpy array; the matrix whose...
In contrast to MATLAB, numpy's svds() arranges the singular values in ascending order. In order to have matching codes, we wrap it around by a function which re-sorts the singular values and singular vectors. Args: M: 2D numpy array; the matrix whose SVD is to be computed. k: Numbe...
null
null
null
def guess_rank(M_E): '''Guess the rank of the incomplete matrix ''' n, m = M_E.shape epsilon = np.count_nonzero(M_E) / np.sqrt(m * n) _, S0, _ = svds_descending(M_E, min(100, max(M_E.shape) - 1)) S0 = np.diag(S0) S1 = S0[:-1] - S0[1:] S1_ = S1 / np.mean(S1[-10:]) r1 = 0 la...
Guess the rank of the incomplete matrix
null
null
null
def F_t(X, Y, S, M_E, E, m0, rho): ''' Compute the distortion ''' r = X.shape[1] out1 = (((np.dot(np.dot(X, S), Y.T) - M_E) * E)**2).sum() / 2 out2 = rho * G(Y, m0, r) out3 = rho * G(X, m0, r) return out1 + out2 + out3
Compute the distortion
null
null
null
def gradF_t(X, Y, S, M_E, E, m0, rho): ''' Compute the gradient. ''' n, r = X.shape m, r = Y.shape XS = np.dot(X, S) YS = np.dot(Y, S.T) XSY = np.dot(XS, Y.T) Qx = np.dot(np.dot(X.T, ((M_E - XSY) * E)), YS) / n Qy = np.dot(np.dot(Y.T, ((M_E - XSY) * E).T), XS) / m ...
Compute the gradient.
null
null
null
def getoptS(X, Y, M_E, E): ''' Find Sopt given X, Y ''' n, r = X.shape C = np.dot(np.dot(X.T, M_E), Y) C = C.flatten() A = np.zeros((r * r, r * r)) for i in range(r): for j in range(r): ind = j * r + i temp = np.dot( np.dot(X.T, np...
Find Sopt given X, Y
null
null
null
def getoptT(X, W, Y, Z, S, M_E, E, m0, rho): ''' Perform line search ''' iter_max = 20 norm2WZ = np.linalg.norm(W, ord='fro')**2 + np.linalg.norm(Z, ord='fro')**2 f = np.zeros(iter_max + 1) f[0] = F_t(X, Y, S, M_E, E, m0, rho) t = -1e-1 for i in range(iter_max): f[i + ...
Perform line search
null
null
null
N = D.shape[0] if method == 'simple': d1 = D[0, :] # buf_ = d1 * np.ones([1, N]).T + (np.ones([N, 1]) * d1).T buf_ = np.broadcast_to(d1, D.shape) + np.broadcast_to(d1[:, np.newaxis], D.shape) np.subtract(D, buf_, out=buf_) G = buf_ # G = (D - d1 * np.ones([1, N]).T -...
def MDS(D, dim, method='simple', theta=False)
recover points from euclidean distance matrix using classic MDS algorithm.
2.862351
2.855276
1.002478
Om = kwargs.get('Om', None) dm = kwargs.get('dm', None) if Om is not None and dm is not None: KE = kwargs.get('KE', None) if KE is not None: print('superMDS: KE and Om, dm given. Continuing with Om, dm') factor, u = eigendecomp(Om, d) uhat = u[:, :d] ...
def superMDS(X0, N, d, **kwargs)
Find the set of points from an edge kernel.
2.932316
2.90749
1.008539
from pylocus.basics import mse, projection KE = kwargs.get('KE', None) KE_projected = KE.copy() d = len(X0) for i in range(max_it): # projection on constraints KE_projected, cost, __ = projection(KE_projected, C, b) rank = np.linalg.matrix_rank(KE_projected) # r...
def iterativeEMDS(X0, N, d, C, b, max_it=10, print_out=False, **kwargs)
Find the set of points from an edge kernel with geometric constraints, using iterative projection
3.942341
3.823012
1.031213
E = C.shape[1] X = Variable((E, E), PSD=True) constraints = [C[i, :] * X == b[i] for i in range(C.shape[0])] obj = Minimize(trace(X) + lamda * norm(KE - X)) prob = Problem(obj, constraints) try: # CVXOPT is more accurate than SCS, even though slower. total_cost = prob.sol...
def relaxedEMDS(X0, N, d, C, b, KE, print_out=False, lamda=10)
Find the set of points from an edge kernel with geometric constraints, using convex rank relaxation.
4.99194
4.674104
1.067999
N = cdm.shape[0] D_sym = (cdm - cdm.T) D_sym /= 2 if W is None: x_est = np.mean(D_sym, axis=1) x_est -= np.min(x_est) return x_est W_sub = W[1:, 1:] sum_W = np.sum(W[1:, :], axis=1) # A = np.eye(N, N-1, k=-1) - W_sub.astype(np.int) / sum_W[:, None] A ...
def signedMDS(cdm, W=None)
Find the set of points from a cdm.
2.812525
2.831441
0.993319
''' Stub an attribute of an object. Will return an existing stub if there already is one. ''' # Annoying circular reference requires importing here. Would like to see # this cleaned up. @AW from .mock import Mock # Check to see if this a property, this check is only for when dealing ...
def _stub_attr(obj, attr_name)
Stub an attribute of an object. Will return an existing stub if there already is one.
4.858233
4.666772
1.041027
''' Stub an object directly. ''' # Annoying circular reference requires importing here. Would like to see # this cleaned up. @AW from .mock import Mock # Return an existing stub if isinstance(obj, Stub): return obj # If a Mock object, stub its __call__ if isinstance(obj...
def _stub_obj(obj)
Stub an object directly.
5.242022
5.165593
1.014796
''' Assert that all expectations on the stub have been met. ''' unmet = [] for exp in self._expectations: if not exp.closed(with_counts=True): unmet.append(ExpectationNotSatisfied(exp)) return unmet
def unmet_expectations(self)
Assert that all expectations on the stub have been met.
8.042522
5.346905
1.504145
''' Clean up all expectations and restore the original attribute of the mocked object. ''' if not self._torn: self._expectations = [] self._torn = True self._teardown()
def teardown(self)
Clean up all expectations and restore the original attribute of the mocked object.
12.019148
4.221533
2.847105
''' Add an expectation to this stub. Return the expectation. ''' exp = Expectation(self) self._expectations.append(exp) return exp
def expect(self)
Add an expectation to this stub. Return the expectation.
6.529937
3.138371
2.080677
''' Add a spy to this stub. Return the spy. ''' spy = Spy(self) self._expectations.append(spy) return spy
def spy(self)
Add a spy to this stub. Return the spy.
6.926941
3.919551
1.767279
''' Calls the original function. ''' if hasattr(self._obj, '__self__') and \ inspect.isclass(self._obj.__self__) and \ self._obj.__self__ is self._instance: return self._obj.__func__(self._instance, *args, **kwargs) elif hasattr(self._o...
def call_orig(self, *args, **kwargs)
Calls the original function.
1.984916
1.86504
1.064275
''' Put the original method back in place. This will also handle the special case when it putting back a class method. The following code snippet best describe why it fails using settar, the class method would be replaced with a bound method not a class method. ...
def _teardown(self)
Put the original method back in place. This will also handle the special case when it putting back a class method. The following code snippet best describe why it fails using settar, the class method would be replaced with a bound method not a class method. >>> class Example(ob...
4.575754
1.760467
2.599171
''' Replace the original method. ''' if not self._was_object_method: setattr(self._instance, self._attr, self._obj) else: delattr(self._instance, self._attr)
def _teardown(self)
Replace the original method.
6.385675
4.21692
1.514298
''' Calls the original function. Simulates __new__ and __init__ together. ''' rval = super(StubNew, self).call_orig(self._type) rval.__init__(*args, **kwargs) return rval
def call_orig(self, *args, **kwargs)
Calls the original function. Simulates __new__ and __init__ together.
9.49165
4.516909
2.10136
''' Overload so that we can clear out the cache after a test run. ''' # __new__ is a super-special case in that even when stubbing a class # which implements its own __new__ and subclasses object, the # "Class.__new__" reference is a staticmethod and not a method (or ...
def _teardown(self)
Overload so that we can clear out the cache after a test run.
19.635128
15.554121
1.262375
''' Calls the original function. ''' return self._orig(self._obj, *args, **kwargs)
def call_orig(self, *args, **kwargs)
Calls the original function.
6.062931
4.374194
1.386068
self.log.info("Adding reader to prepare to receive.") self.loop.add_reader(self.dev.fd, self.read) self.log.info("Flushing the RFXtrx buffer.") self.flushSerialInput() self.log.info("Writing the reset packet to the RFXtrx. (blocking)") yield from self.sendRESET...
def _setup(self)
Performs the RFXtrx initialisation protocol in a Future. Currently this is the rough workflow of the interactions with the RFXtrx. We also do a few extra things - flush the buffer, and attach readers/writers to the asyncio loop. 1. Write a RESET packet (write all zeros) 2. Wait...
7.456706
5.565164
1.33989
callback, parser = self.get_callback_parser(pkt) if asyncio.iscoroutinefunction(callback): self.loop.call_soon_threadsafe(self._do_async_callback, callback, parser) else: self.loop.call_soon(callback, parser)
def do_callback(self, pkt)
Add the callback to the event loop, we use call soon because we just want it to be called at some point, but don't care when particularly.
3.586938
3.32514
1.078733
data = self.dev.read() if len(data) == 0: self.log.warning("READ : Nothing received") return if data == b'\x00': self.log.warning("READ : Empty packet (Got \\x00)") return pkt = bytearray(data) data = self.dev.read(pkt[...
def read(self)
We have been called to read! As a consumer, continue to read for the length of the packet and then pass to the callback.
4.233688
3.823617
1.107247
response = self.http.delete(url, params=params, **self.requests_params) return self.process(response)
def delete(self, url, params=None)
Executes an HTTP DELETE request for the given URL. ``params`` should be a dictionary
4.570483
7.422668
0.615747
response = self.http.get(url, headers=self.headers, params=data, **self.requests_params) return self.process(response)
def get(self, url, data=None)
Executes an HTTP GET request for the given URL. ``data`` should be a dictionary of url parameters
3.730718
5.679638
0.656858
response = self.http.post(url, headers=self.headers, data=body, **self.requests_params) return self.process(response)
def post(self, url, body=None)
Executes an HTTP POST request for the given URL.
4.115412
4.36258
0.943344
response = self.http.put(url, headers=self.headers, data=body, params=data, **self.requests_params) return self.process(response)
def put(self, url, data=None, body=None)
Executes an HTTP PUT request for the given URL.
3.920663
4.057972
0.966163
try: code = response.status_code # 204 - No Content if code == 204: body = None # add an error message to 402 errors elif code == 402: body = { "message": "Payment Required", ...
def process(self, response)
Returns HTTP backend agnostic ``Response`` data.
4.961099
4.358257
1.138322
data = {'email': email, 'terms_of_service': str(tos)} if options: data.update(options) return self.post(self.base_url, body=json.dumps(data))
def create(self, email, tos=1, options=None)
Creates an account with Zencoder, no API Key necessary. https://app.zencoder.com/docs/api/accounts/create
3.182952
3.427113
0.928756
data = {"input": input, "test": self.test} if outputs: data['outputs'] = outputs if options: data.update(options) if live_stream: data['live_stream'] = live_stream return self.post(self.base_url, body=json.dumps(data))
def create(self, input=None, live_stream=False, outputs=None, options=None)
Creates a transcoding job. Here are some examples:: job.create('s3://zencodertesting/test.mov') job.create(live_stream=True) job.create(input='http://example.com/input.mov', outputs=({'label': 'test output'},)) https://app.zencoder.com/docs/api/jobs/c...
3.043786
3.938014
0.772924
data = {"page": page, "per_page": per_page} return self.get(self.base_url, data=data)
def list(self, page=1, per_page=50)
Lists Jobs. https://app.zencoder.com/docs/api/jobs/list
3.594588
3.348354
1.073539