text stringlengths 18 773k |
|---|
def ip_address_list(ips):
""" IP address range validation and expansion. """
# first, try it as a single IP address
try:
return ip_address(ips)
except ValueError:
pass
# then, consider it as an ipaddress.IPv[4|6]Network instance and expand it
return list(ipaddress.ip_network(u(ip... |
def port_number(port):
""" Port number validation. """
try:
port = int(port)
except ValueError:
raise ValueError("Bad port number")
if not 0 <= port < 2 ** 16:
raise ValueError("Bad port number")
return port |
def port_number_range(prange):
""" Port number range validation and expansion. """
# first, try it as a normal port number
try:
return port_number(prange)
except ValueError:
pass
# then, consider it as a range with the format "x-y" and expand it
try:
bounds = list(map(int... |
def parse_header_part(self, data):
"""Extracts and converts the RFX common header part of all valid
packets to a plain dictionary. RFX header part is the 4 bytes prior
the sensor vendor specific data part.
The RFX common header part contains respectively:
- packet length
... |
def load(self, data):
"""This is the entrance method for all data which is used to store the
raw data and start parsing the data.
:param data: The raw untouched bytearray as recieved by the RFXtrx
:type data: bytearray
:return: The parsed data represented in a dictionary
... |
def validate_packet(self, data):
"""Validate a packet against this packet handler and determine if it
meets the requirements. This is done by checking the following
conditions are true.
- The length of the packet is equal to the first byte.
- The second byte is in the set of def... |
def _enforce_instance(model_or_class):
"""
It's a common mistake to not initialize a
schematics class. We should handle that by just
calling the default constructor.
"""
if isinstance(model_or_class, type) and issubclass(model_or_class, BaseType):
return model_or_class()
return model... |
def render(file):
"""Generate the result HTML."""
fp = file.open()
content = fp.read()
fp.close()
notebook = nbformat.reads(content.decode('utf-8'), as_version=4)
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
(body, resources) = html_exporter.from_notebook_node(n... |
def preview(file):
"""Render the IPython Notebook."""
body, resources = render(file)
default_ipython_style = resources['inlining']['css'][1]
return render_template(
'invenio_previewer/ipynb.html',
file=file,
content=body,
style=default_ipython_style
) |
def transmute_route(app, fn, context=default_context):
"""
this is the main interface to transmute. It will handle
adding converting the python function into the a flask-compatible route,
and adding it to the application.
"""
transmute_func = TransmuteFunction(fn)
routes, handler = create_ro... |
def create_routes_and_handler(transmute_func, context):
"""
return back a handler that is the api generated
from the transmute_func, and a list of routes
it should be mounted to.
"""
@wraps(transmute_func.raw_func)
def handler():
exc, result = None, None
try:
args... |
def _convert_paths_to_flask(transmute_paths):
"""
convert transmute-core's path syntax (which uses {var} as the
variable wildcard) into flask's <var>.
"""
paths = []
for p in transmute_paths:
paths.append(p.replace("{", "<").replace("}", ">"))
return paths |
def add_swagger(app, json_route, html_route, **kwargs):
"""
add a swagger html page, and a swagger.json generated
from the routes added to the app.
"""
spec = getattr(app, SWAGGER_ATTR_NAME)
if spec:
spec = spec.swagger_definition(**kwargs)
else:
spec = {}
encoded_spec = ... |
def _log_enabled_protocols(self, flags, protocols):
"""Given a list of single character strings of 1's and 0's and a list
of protocol names. Log the status of each protocol where ``"1"`` is
enabled and ``"0"`` is disabled. The order of the lists here is
important as they need to be zippe... |
def parse(self, data):
"""Parse a 13 byte packet in the Status format.
:param data: bytearray to be parsed
:type data: bytearray
:return: Data dictionary containing the parsed values
:rtype: dict
"""
self.validate_packet(data)
packet_length = data[0]
... |
def set_time_items(glob):
"""
This function prepares the benchmark items for inclusion in main script's
global scope.
:param glob: main script's global scope dictionary reference
"""
a = glob['args']
l = glob['logger']
class __TimeManager(object):
def __init__(self):
... |
def set_step_items(glob):
"""
This function prepares the stepping items for inclusion in main script's
global scope.
:param glob: main script's global scope dictionary reference
"""
a = glob['args']
l = glob['logger']
enabled = getattr(a, a._collisions.get("step") or "step", False)... |
def _capture_variable(iterator, parameters):
"""
return the replacement string.
this assumes the preceeding {{ has already been
popped off.
"""
key = ""
next_c = next(iterator)
while next_c != "}":
key += next_c
next_c = next(iterator)
# remove the final "}"
next(... |
def rgb_distance(rgb1, rgb2):
'''
Calculate the distance between two RGB sequences.
'''
return sum(map(lambda c: (c[0] - c[1]) ** 2,
zip(rgb1, rgb2))) |
def rgb_reduce(r, g, b, mode=8):
'''
Convert an RGB colour to 8 or 16 colour ANSI graphics.
'''
colours = ANSI_COLOURS[:mode]
matches = [(rgb_distance(c, map(int, [r, g, b])), i)
for i, c in enumerate(colours)]
matches.sort()
return sequence('m')(str(30 + matches[0][1])) |
def rgb256(r, g, b):
'''
Convert an RGB colour to 256 colour ANSI graphics.
'''
grey = False
poss = True
step = 2.5
while poss: # As long as the colour could be grey scale
if r < step or g < step or b < step:
grey = r < step and g < step and b < step
poss = F... |
def uri(self):
"""Get file download link.
.. note::
The URI generation assumes that you can download the file using the
view ``invenio_records_ui.<pid_type>_files``.
"""
return url_for(
'.{0}_files'.format(self.pid.pid_type),
pid_value=s... |
def has_extensions(self, *exts):
"""Check if file has one of the extensions."""
file_ext = splitext(self.filename)[1]
file_ext = file_ext.lower()
for e in exts:
if file_ext == e:
return True
return False |
def render(file):
"""Pretty print the JSON file for rendering."""
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, ind... |
def validate_json(file):
"""Validate a JSON file."""
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'))
re... |
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 measurem... |
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 E... |
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 measure... |
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 matr... |
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 (Nx... |
def url_spec(transmute_path, handler, *args, **kwargs):
"""
convert the transmute_path
to a tornado compatible regex,
and return a tornado url object.
"""
p = _to_tornado_pattern(transmute_path)
for m in METHODS:
method = getattr(handler, m)
if hasattr(method, "transmute_func... |
def set_points(self, mode='', points=None, range_=RANGE, size=1):
""" Initialize points according to predefined modes.
:param range_:[xmin, xmax, ymin, ymax], range of point sets
"""
if mode == 'last':
if points is None:
print('Error: empty last point specifi... |
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.
"""
import itertools
from pylocus.basics_angles import from_0_to_pi
theta = ... |
def get_orientation(k, i, j):
from pylocus.basics_angles import from_0_to_2pi
"""calculate angles theta_ik and theta_jk theta produce point Pk.
Should give the same as get_absolute_angle! """
theta_ij = own.abs_angles[i, j]
theta_ji = own.abs_angles[j, i]
# complicated
... |
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: Li... |
def get_G(self, k, add_noise=True):
""" get G matrix from angles. """
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... |
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.
"""
convex_polygons = []
for corners in itertools.combinations(np.arange(self.N), m):
... |
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
... |
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
"""
rows_b = []
rows_A = []
m = len(polygons_m[0])
... |
def get_KE_constraints(self):
"""Get linear constraints on KE matrix.
"""
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... |
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,
... |
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
"""
return ((bytes_[0] * pow(2, 40)) + (bytes_[1] * pow(2, 3... |
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,
... |
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
'''
key = '{}_{}'.format(path, site_id)
key = hashlib.sha224(key.encode('utf-8')).he... |
def validate_csv(file):
"""Return dialect information about given csv file."""
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_BYT... |
def preview(file):
"""Render appropiate template with embed flag."""
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_b... |
def make_tree(file):
"""Create tree structure from ZIP archive."""
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 encod... |
def children_to_list(node):
"""Organize children structure."""
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'])
... |
def preview(file):
"""Return appropriate template and pass the file and an embed flag."""
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... |
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 Gaussia... |
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 ... |
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... |
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
"""
app.router.add_route('GET', json_route, create_swagger_json_handler(app))
add_swagger_api_route(app, html_route, json_route) |
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.
"""
st... |
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.
"""
spec = get_swagger_spec(app).swagger_definition(**kwargs)
encoded_spec... |
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)
Re... |
def change_angles(method, theta, tol=1e-10):
""" Function used by all angle conversion functions (from_x_to_x_pi(...))"""
try:
theta_new = np.zeros(theta.shape)
for i, thet in enumerate(theta):
try:
# theta is vector
theta_new[i] = method(thet, tol)
... |
def rmse_2pi(x, xhat):
''' 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 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... |
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.
"""
return_value = []
f... |
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 (inclu... |
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.
"""
params = set()
for path in paths:
parts = PART_R... |
def _build_body_schema(serializer, body_parameters):
""" body is built differently, since it's a single argument no matter what. """
description = ""
if isinstance(body_parameters, Param):
schema = serializer.to_json_schema(body_parameters.arginfo.type)
description = body_parameters.descript... |
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,
'... |
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.
... |
def reconstruct_emds(edm, Om, all_points, method=None, **kwargs):
""" Reconstruct point set using E(dge)-MDS.
"""
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, __ = s... |
def reconstruct_cdm(dm, absolute_angles, all_points, W=None):
""" Reconstruct point set from angle and distance measurements, using coordinate difference matrices.
"""
from pylocus.point_set import dmi_from_V, sdm_from_dmi, get_V
from pylocus.mds import signedMDS
N = all_points.shape[0]
V = ge... |
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.
"""
from .point_set import dm_from_edm
from .mds import MDS
N = all_points.shape[0]
d = all_points.shape[1]
... |
def reconstruct_sdp(edm, all_points, W=None, print_out=False, lamda=1000, **kwargs):
""" Reconstruct point set using semi-definite rank relaxation.
"""
from .edm_completion import semidefinite_relaxation
edm_complete = semidefinite_relaxation(
edm, lamda=lamda, W=W, print_out=print_out, **kwargs... |
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.
"""
from .lateration import SRLS, get_lateration_parameters
Y = all_points.copy()
indices = range(n)
for index... |
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 consecu... |
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.o... |
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,
'... |
def get_lateration_parameters(all_points, indices, index, edm, W=None):
""" Get parameters relevant for lateration from full all_points, edm and W.
"""
if W is None:
W = np.ones(edm.shape)
# delete points that are not considered anchors
anchors = np.delete(all_points, indices, axis=0)
r... |
def SRLS(anchors, w, r2, rescale=False, z=None, print_out=False):
'''Squared range least squares (SRLS)
Algorithm written by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems".
:param anchors: anchor points (Nxd)
:param w: weights for the measurements (Nx1)
:para... |
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.
'''
N = anchors.shape[0]
anc... |
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 poi... |
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 po... |
def _join_parameters(base, nxt):
""" join parameters from the lhs to the rhs, if compatible. """
if nxt is None:
return base
if isinstance(base, set) and isinstance(nxt, set):
return base | nxt
else:
return nxt |
def get_swagger_operation(self, context=default_context):
"""
get the swagger_schema operation representation.
"""
consumes = produces = context.contenttype_serializers.keys()
parameters = get_swagger_parameters(self.parameters, context)
responses = {
"400": R... |
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.
"""
return process_result(self, context, result_body, exc, content_type) |
def _parse_response_types(argspec, attrs):
"""
from the given parameters, return back the response type dictionaries.
"""
return_type = argspec.annotations.get("return") or None
type_description = attrs.parameter_descriptions.get("return", "")
response_types = attrs.respo... |
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.
"""
tmpl = _get_template("swagger.html")
return tmpl.render(
swagger_root=swagger_st... |
def add_func(self, transmute_func, transmute_context):
""" add a transmute function's swagger definition to the spec """
swagger_path = transmute_func.get_swagger_path(transmute_context)
for p in transmute_func.paths:
self.add_path(p, swagger_path) |
def add_path(self, path, path_item):
""" for a given path, add the path items. """
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.... |
def swagger_definition(self, base_path=None, **kwargs):
"""
return a valid swagger spec, with the values passed.
"""
return Swagger(
{
"info": Info(
{
key: kwargs.get(key, self.DEFAULT_INFO.get(key))
... |
def _call_spy(self, *args, **kwargs):
'''
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_si... |
def side_effect(self, func, *args, **kwargs):
'''
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 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
"""
a, l = glob['args'], glob['logger']
enabled = getattr(a, a._collisions.get("interact") or "intera... |
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 deb... |
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 ... |
def opt_space(M_E, r=None, niter=50, tol=1e-6, print_out=False):
'''
Implementation of the OptSpace matrix completion algorithm.
An algorithm for Matrix Reconstruction from a partially revealed set.
Sparse treatment of matrices are removed because of indexing problems in Python.
Args:
... |
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... |
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... |
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 |
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
... |
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... |
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 + ... |
def MDS(D, dim, method='simple', theta=False):
""" recover points from euclidean distance matrix using classic MDS algorithm.
"""
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) + n... |
def superMDS(X0, N, d, **kwargs):
""" Find the set of points from an edge kernel.
"""
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. Continu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.