code stringlengths 1 18.2k |
|---|
def remove_edges(self, from_idx, to_idx, symmetric=False, copy=False): '''Removes all from->to and to->from edges. Note: the symmetric kwarg is unused.''' flat_inds = self._pairs.dot((self._num_vertices, 1)) # convert to sorted order and flatten to_remove = (np.minimum(from_idx, to_idx) * self._num_vertices + np.maximu... |
def add_edges(self, from_idx, to_idx, weight=1, symmetric=False, copy=False): '''Adds all from->to edges. weight may be a scalar or 1d array. If symmetric=True, also adds to->from edges with the same weights.''' raise NotImplementedError() |
def add_self_edges(self, weight=None, copy=False): '''Adds all i->i edges. weight may be a scalar or 1d array.''' ii = np.arange(self.num_vertices()) return self.add_edges(ii, ii, weight=weight, symmetric=False, copy=copy) |
def reweight(self, weight, edges=None, copy=False): '''Replaces existing edge weights. weight may be a scalar or 1d array. edges is a mask or index array that specifies a subset of edges to modify''' if not self.is_weighted(): warnings.warn('Cannot supply weights for unweighted graph; ' 'ignoring call to reweight') ret... |
def reweight_by_distance(self, coords, metric='l2', copy=False): '''Replaces existing edge weights by distances between connected vertices. The new weight of edge (i,j) is given by: metric(coords[i], coords[j]). coords : (num_vertices x d) array of coordinates, in vertex order metric : str or callable, see sklearn.metr... |
def degree(self, kind='out', weighted=True): '''Returns an array of vertex degrees. kind : either 'in' or 'out', useful for directed graphs weighted : controls whether to count edges or sum their weights ''' if kind == 'out': axis = 1 adj = self.matrix('dense', 'csc') else: axis = 0 adj = self.matrix('dense', 'csr') if... |
def to_igraph(self, weighted=None): '''Converts this Graph object to an igraph-compatible object. Requires the python-igraph library.''' # Import here to avoid ImportErrors when igraph isn't available. import igraph ig = igraph.Graph(n=self.num_vertices(), edges=self.pairs().tolist(), directed=self.is_directed()) if we... |
def to_graph_tool(self): '''Converts this Graph object to a graph_tool-compatible object. Requires the graph_tool library. Note that the internal ordering of graph_tool seems to be column-major.''' # Import here to avoid ImportErrors when graph_tool isn't available. import graph_tool gt = graph_tool.Graph(directed=self... |
def to_networkx(self, directed=None): '''Converts this Graph object to a networkx-compatible object. Requires the networkx library.''' import networkx as nx directed = directed if directed is not None else self.is_directed() cls = nx.DiGraph if directed else nx.Graph adj = self.matrix() if ss.issparse(adj): return nx.f... |
def _check_inputs(z, m): """Check inputs are arrays of same length or array and a scalar.""" try: nz = len(z) z = np.array(z) except TypeError: z = np.array([z]) nz = len(z) try: nm = len(m) m = np.array(m) except TypeError: m = np.array([m]) nm = len(m) if (z < 0).any() or (m < 0).any(): raise ValueError('z and m must... |
def c_Prada(z, m, h=h, Om_M=Om_M, Om_L=Om_L): """Concentration from c(M) relation published in Prada et al. (2012). Parameters ---------- z : float or array_like Redshift(s) of halos. m : float or array_like Mass(es) of halos (m200 definition), in units of solar masses. h : float, optional Hubble parameter. Default is ... |
Klypin, A.J. Cuesta, J.E. Betancort-Rijo, and J. Primack, "Halo concentrations in the standard Lambda cold dark matter cosmology," Monthly Notices of the Royal Astronomical Society, Volume 423, Issue 4, pp. 3018-3030, 2012. """ z, m = _check_inputs(z, m) # EQ 13 x = (1. / (1. + z)) * (Om_L / Om_M)**(1. / 3.) # EQ 12 in... |
y**0.333)) # EQ 21 & 22 (constants) c0 = 3.681 c1 = 5.033 alpha = 6.948 x0 = 0.424 s0 = 1.047 # sigma_0^-1 s1 = 1.646 # sigma_1^-1 beta = 7.386 x1 = 0.526 # EQ 19 & 20 cmin = c0 + (c1 - c0) * ((1. / np.pi) * np.arctan(alpha * (x - x0)) + 0.5) smin = s0 + (s1 - s0) * ((1. / np.pi) * np.arctan(beta * (x - x1)) + 0.5) # E... |
smin1393 # EQ 15 sigma_prime = B1 * sigma # EQ 17 A = 2.881 b = 1.257 c = 1.022 d = 0.06 # EQ 16 Cs = A * ((sigma_prime / b)**c + 1.) * np.exp(d / (sigma_prime**2.)) # EQ 14 concentration = B0 * Cs return concentration |
def c_DuttonMaccio(z, m, h=h): """Concentration from c(M) relation in Dutton & Maccio (2014). Parameters ---------- z : float or array_like Redshift(s) of halos. m : float or array_like Mass(es) of halos (m200 definition), in units of solar masses. h : float, optional Hubble parameter. Default is from Planck13. Returns... |
11 logc200 = a + b * np.log10(m * h / (10.**12)) # EQ 7 concentration = 10.**logc200 return concentration |
def c_Duffy(z, m, h=h): """Concentration from c(M) relation published in Duffy et al. (2008). Parameters ---------- z : float or array_like Redshift(s) of halos. m : float or array_like Mass(es) of halos (m200 definition), in units of solar masses. h : float, optional Hubble parameter. Default is from Planck13. Returns... |
0-2. This means the values of fitted parameters (A,B,C) = (5.71, -0.084,-0.47) in Table 1 of Duffy et al. (2008). """ z, m = _check_inputs(z, m) M_pivot = 2.e12 / h # [M_solar] A = 5.71 B = -0.084 C = -0.47 concentration = A * ((m / M_pivot)**B) * (1 + z)**C return concentration |
def _set_label(self, which, label, **kwargs): """Private method for setting labels. Args: which (str): The indicator of which part of the plots to adjust. This currently handles `xlabel`/`ylabel`, and `title`. label (str): The label to be added. fontsize (int, optional): Fontsize for associated label. Default is None. ... |
def _set_axis_limits(self, which, lims, d, scale, reverse=False): """Private method for setting axis limits. Sets the axis limits on each axis for an individual plot. Args: which (str): The indicator of which part of the plots to adjust. This currently handles `x` and `y`. lims (len-2 list of floats): The limits for th... |
def set_xlim(self, xlims, dx, xscale, reverse=False): """Set x limits for plot. This will set the limits for the x axis for the specific plot. Args: xlims (len-2 list of floats): The limits for the axis. dx (float): Amount to increment by between the limits. xscale (str): Scale of the axis. Either `log` or `lin`. rever... |
def set_ylim(self, xlims, dx, xscale, reverse=False): """Set y limits for plot. This will set the limits for the y axis for the specific plot. Args: ylims (len-2 list of floats): The limits for the axis. dy (float): Amount to increment by between the limits. yscale (str): Scale of the axis. Either `log` or `lin`. rever... |
def add_legend(self, labels=None, **kwargs): """Specify legend for a plot. Adds labels and basic legend specifications for specific plot. For the optional Args, refer to https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html for more information. # TODO: Add legend capabilities for Loss/Gain plots. This is po... |
Default is None. size (float, optional): Set size of legend using call to `prop` dict in legend call. See matplotlib documentaiton for more detail. Default is None. ncol (int, optional): Number of columns in the legend. Note: Other kwargs are available. See: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.h... |
def add_dataset(self, name=None, label=None, x_column_label=None, y_column_label=None, index=None, control=False): """Add a dataset to a specific plot. This method adds a dataset to a plot. Its functional use is imperative to the plot generation. It handles adding new files as well as indexing to files that are added t... |
(str, optional): Column label from input file identifying x/y values. This can override setting in "general". Default is `x`/`y`. index (int, optional): Index of plot with preloaded data. Required if not loading a file. control (bool, optional): If True, this dataset is set to the control. This is needed for Ratio plot... |
= x_column_label if y_column_label is not None: trans_dict.y_column_label = y_column_label if control: self.control = trans_dict else: # need to append file to file list. if 'file' not in self.__dict__: self.file = [] self.file.append(trans_dict) else: if control: self.control = DataImportContainer() self.control.index... |
def savefig(self, output_path, **kwargs): """Save figure during generation. This method is used to save a completed figure during the main function run. It represents a call to ``matplotlib.pyplot.fig.savefig``. # TODO: Switch to kwargs for matplotlib.pyplot.savefig Args: output_path (str): Relative path to the WORKING... |
def set_fig_size(self, width, height=None): """Set the figure size in inches. Sets the figure size with a call to fig.set_size_inches. Default in code is 8 inches for each. Args: width (float): Dimensions for figure width in inches. height (float, optional): Dimensions for figure height in inches. Default is None. """ ... |
def set_spacing(self, space): """Set the figure spacing. Sets whether in general there is space between subplots. If all axes are shared, this can be `tight`. Default in code is `wide`. The main difference is the tick labels extend to the ends if space==`wide`. If space==`tight`, the edge tick labels are cut off for cl... |
def subplots_adjust(self, **kwargs): """Adjust subplot spacing and dimensions. Adjust bottom, top, right, left, width in between plots, and height in between plots with a call to ``plt.subplots_adjust``. See https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots_adjust.html for more information. Keyword Argument... |
height reserved for space between subplots, It is expressed as a fraction of the average axis width. Default is 0.3. """ prop_default = { 'bottom': 0.1, 'top': 0.85, 'right': 0.9, 'left': 0.12, 'hspace': 0.3, 'wspace': 0.3, } if 'subplots_adjust_kwargs' in self.figure.__dict__: for key, value in self.figure.subplots_ad... |
def set_fig_x_label(self, xlabel, **kwargs): """Set overall figure x. Set label for x axis on overall figure. This is not for a specific plot. It will place the label on the figure at the left with a call to ``fig.text``. Args: xlabel (str): xlabel for entire figure. Keyword Arguments: x/y (float, optional): The x/y lo... |
str): Rotation of label. Options are angle in degrees, `horizontal`, or `vertical`. Default is `vertical`. Note: Other kwargs are available. See https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figtext """ prop_default = { 'x': 0.01, 'y': 0.51, 'fontsize': 20, 'rotation': 'vertical', 'va': 'center', } for p... |
def set_fig_y_label(self, ylabel, **kwargs): """Set overall figure y. Set label for y axis on overall figure. This is not for a specific plot. It will place the label on the figure at the left with a call to ``fig.text``. Args: ylabel (str): ylabel for entire figure. Keyword Arguments: x/y (float, optional): The x/y lo... |
str): Rotation of label. Options are angle in degrees, `horizontal`, or `vertical`. Default is `horizontal`. Note: Other kwargs are available. See https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figtext """ prop_default = { 'x': 0.45, 'y': 0.02, 'fontsize': 20, 'rotation': 'horizontal', 'ha': 'center', } f... |
def set_fig_title(self, title, **kwargs): """Set overall figure title. Set title for overall figure. This is not for a specific plot. It will place the title at the top of the figure with a call to ``fig.suptitle``. Args: title (str): Figure title. Keywork Arguments: x/y (float, optional): The x/y location of the text ... |
for prop, default in prop_default.items(): kwargs[prop] = kwargs.get(prop, default) self.figure.fig_title = title self.figure.fig_title_kwargs = kwargs return |
def set_colorbar(self, plot_type, **kwargs): """Setup colorbar for specific type of plot. Specify a plot type to customize its corresponding colorbar in the figure. See the ColorbarContainer class attributes for more specific explanations. Args: plot_type (str): Type of plot to adjust. e.g. `Ratio` label (str, optional... |
'cbar_label_fontsize': 20, 'cbar_axes': [], 'cbar_ticks': [], 'cbar_tick_labels': [], 'cbar_pos': 'use_default', 'cbar_label_pad': None, } for prop, default in prop_default.items(): kwargs[prop] = kwargs.get(prop[5:], default) if prop[5:] in kwargs: del kwargs[prop[5:]] if 'colorbars' not in self.figure.__dict__: self.... |
def set_all_file_column_labels(self, xlabel=None, ylabel=None): """Indicate general x,y column labels. This sets the general x and y column labels into data files for all plots. It can be overridden for specific plots. Args: xlabel/ylabel (str, optional): String indicating column label for x,y values into the data file... |
def _set_all_lims(self, which, lim, d, scale, fontsize=None): """Set limits and ticks for an axis for whole figure. This will set axis limits and tick marks for the entire figure. It can be overridden in the SinglePlot class. Args: which (str): The indicator of which part of the plots to adjust. This currently handles ... |
def set_all_xlims(self, xlim, dx, xscale, fontsize=None): """Set limits and ticks for x axis for whole figure. This will set x axis limits and tick marks for the entire figure. It can be overridden in the SinglePlot class. Args: xlim (len-2 list of floats): The limits for the axis. dx (float): Amount to increment by be... |
def set_all_ylims(self, ylim, dy, yscale, fontsize=None): """Set limits and ticks for y axis for whole figure. This will set y axis limits and tick marks for the entire figure. It can be overridden in the SinglePlot class. Args: ylim (len-2 list of floats): The limits for the axis. dy (float): Amount to increment by be... |
def reverse_axis(self, axis_to_reverse): """Reverse an axis in all figure plots. This will reverse the tick marks on an axis for each plot in the figure. It can be overridden in SinglePlot class. Args: axis_to_reverse (str): Axis to reverse. Supports `x` and `y`. Raises: ValueError: The string representing the axis to ... |
def return_dict(self): """Output dictionary for ``make_plot.py`` input. Iterates through the entire MainContainer class turning its contents into dictionary form. This dictionary becomes the input for ``make_plot.py``. If `print_input` attribute is True, the entire dictionary will be printed prior to returning the dici... |
def _iterate_through_class(self, class_dict): """Recursive function for output dictionary creation. Function will check each value in a dictionary to see if it is a class, list, or dictionary object. The idea is to turn all class objects into dictionaries. If it is a class object it will pass its ``class.__dict__`` rec... |
val = class_dict[key] try: val = val.__dict__ except AttributeError: pass if type(val) is dict: val = self._iterate_through_class(val) if type(val) is list: temp_val = [] for val_i in val: try: val_i = val_i.__dict__ except AttributeError: pass if type(val_i) is dict: val_i = self._iterate_through_class(val_i) temp_val... |
def txt_read_in(self): """Read in txt files. Method for reading in text or csv files. This uses ascii class from astropy.io for flexible input. It is slower than numpy, but has greater flexibility with less input. """ # read in data = ascii.read(self.WORKING_DIRECTORY + '/' + self.file_name) # find number of distinct x... |
def hdf5_read_in(self): """Method for reading in hdf5 files. """ with h5py.File(self.WORKING_DIRECTORY + '/' + self.file_name) as f: # read in data = f['data'] # find number of distinct x and y points. num_x_pts = len(np.unique(data[self.x_column_label][:])) num_y_pts = len(np.unique(data[self.y_column_label][:])) # cr... |
def set_parameters(self): """Setup all the parameters for the binaries to be evaluated. Grid values and store necessary parameters for input into the SNR function. """ # declare 1D arrays of both paramters if self.xscale != 'lin': self.xvals = np.logspace(np.log10(float(self.x_low)), np.log10(float(self.x_high)), self.... |
it is not zero else: if 'spin' in self.__dict__: self.spin_1 = self.spin self.spin_2 = self.spin for key in ['redshift', 'luminosity_distance', 'comoving_distance']: if key in self.__dict__: self.dist_type = key self.z_or_dist = getattr(self, key) if self.ecc: for key in ['start_frequency', 'start_time', 'start_separat... |
def run_snr(self): """Run the snr calculation. Takes results from ``self.set_parameters`` and other inputs and inputs these into the snr calculator. """ if self.ecc: required_kwargs = {'dist_type': self.dist_type, 'initial_cond_type': self.initial_cond_type, 'ecc': True} input_args = [self.m1, self.m2, self.z_or_dist, ... |
def event_payment(self, date, time, pid, commerce_id, transaction_id, request_ip, token, webpay_server): '''Record the payment event Official handler writes this information to TBK_EVN%Y%m%d file. ''' raise NotImplementedError("Logging Handler must implement event_payment") |
def event_confirmation(self, date, time, pid, commerce_id, transaction_id, request_ip, order_id): '''Record the confirmation event. Official handler writes this information to TBK_EVN%Y%m%d file. ''' raise NotImplementedError("Logging Handler must implement event_confirmation") |
def stop(self): """ If the manager is running, tell it to stop its process """ res = self.send_request('manager/stop', post=True) if res.status_code != 200: raise UnexpectedResponse( 'Attempted to stop manager. {res_code}: {res_text}'.format( res_code=res.status_code, res_text=res.text, ) ) if settings.VERBOSITY >= ver... |
def stop_host(self, config_file): """ Stops a managed host specified by `config_file`. """ res = self.send_json_request('host/stop', data={'config': config_file}) if res.status_code != 200: raise UnexpectedResponse( 'Attempted to stop a JSHost. Response: {res_code}: {res_text}'.format( res_code=res.status_code, res_tex... |
def get_data(self, params={}): """ Make the request and return the deserialided JSON from the response :param params: Dictionary mapping (string) query parameters to values :type params: dict :return: JSON object with the data fetched from that URL as a JSON-format object. :rtype: (dict or array) """ if self and hasatt... |
def receive(self, input): """ Add logging of state transitions to the wrapped state machine. @see: L{IFiniteStateMachine.receive} """ if IRichInput.providedBy(input): richInput = unicode(input) symbolInput = unicode(input.symbol()) else: richInput = None symbolInput = unicode(input) action = LOG_FSM_TRANSITION( self.lo... |
def init_app(self, app): """Initialize Flask application.""" prefix_len = len(self.prefix) for varname, value in os.environ.items(): if not varname.startswith(self.prefix): continue # Prepare values varname = varname[prefix_len:] value = value or app.config.get(varname) # Evaluate value try: value = ast.literal_eval(va... |
def smce_graph(X, metric='l2', sparsity_param=10, kmax=None, keep_ratio=0.95): '''Sparse graph construction from the SMCE paper. X : 2-dimensional array-like metric : str, optional sparsity_param : float, optional kmax : int, optional keep_ratio : float, optional When <1, keep edges up to (keep_ratio * total weight) Re... |
/ nbr_dist[:,None] # solve sparse optimization with ADMM c = _solve_admm(Y, nbr_dist/nbr_dist.sum(), sparsity_param) c = np.abs(c / nbr_dist) W[i,nbr_inds] = c / c.sum() W = ss.csr_matrix(W) if keep_ratio < 1: for i in range(n): row_data = W.data[W.indptr[i]:W.indptr[i+1]] order = np.argsort(row_data)[::-1] stop_idx = ... |
def sparse_regularized_graph(X, positive=False, sparsity_param=None, kmax=None): '''Sparse Regularized Graph Construction, commonly known as an l1-graph. positive : bool, optional When True, computes the Sparse Probability Graph (SPG). sparsity_param : float, optional Controls sparsity cost in the LASSO optimization. W... |
def prep_parallel(self, binary_args, other_args): """Prepare the parallel calculations Prepares the arguments to be run in parallel. It will divide up arrays according to num_splits. Args: binary_args (list): List of binary arguments for input into the SNR function. other_args (tuple of obj): tuple of other args for in... |
def run_parallel(self, para_func): """Run parallel calulation This will run the parallel calculation on self.num_processors. Args: para_func (obj): Function object to be used in parallel. Returns: (dict): Dictionary with parallel results. """ if self.timer: start_timer = time.time() # for testing # check = parallel_snr... |
def RawParserUnparserFactory(parser_name, parse_callable, *unparse_callables): """ Produces a callable object that also has callable attributes that passes its first argument to the parent callable. """ def build_unparse(f): @wraps(f) def unparse(self, source, *a, **kw): node = parse_callable(source) return f(node, *a,... |
def ParserUnparserFactory(module_name, *unparser_names): """ Produce a new parser/unparser object from the names provided. """ parse_callable = import_module(PKGNAME + '.parsers.' + module_name).parse unparser_module = import_module(PKGNAME + '.unparsers.' + module_name) return RawParserUnparserFactory(module_name, par... |
def downsample_trajectories(trajectories, downsampler, *args, **kwargs): '''Downsamples all points together, then re-splits into original trajectories. trajectories : list of 2-d arrays, each representing a trajectory downsampler(X, *args, **kwargs) : callable that returns indices into X ''' X = np.vstack(trajectories)... |
def epsilon_net(points, close_distance): '''Selects a subset of `points` to preserve graph structure while minimizing the number of points used, by removing points within `close_distance`. Returns the downsampled indices.''' num_points = points.shape[0] indices = set(range(num_points)) selected = [] while indices: idx ... |
def fuzzy_c_means(points, num_centers, m=2., tol=1e-4, max_iter=100, verbose=False): '''Uses Fuzzy C-Means to downsample `points`. m : aggregation parameter >1, larger implies smoother clusters Returns indices of downsampled points. ''' num_points = points.shape[0] if num_centers >= num_points: return np.arange(num_poi... |
in %d iterations" % max_iter) # find points closest to the selected cluster centers return d.argmin(axis=0) |
def transport_from_url(url): """ Create a transport for the given URL. """ if '/' not in url and ':' in url and url.rsplit(':')[-1].isdigit(): url = 'scgi://' + url url = urlparse.urlsplit(url, scheme="scgi", allow_fragments=False) # pylint: disable=redundant-keyword-arg try: transport = TRANSPORTS[url.scheme.lower()] ... |
def _encode_payload(data, headers=None): "Wrap data in an SCGI request." prolog = "CONTENT_LENGTH\0%d\0SCGI\x001\0" % len(data) if headers: prolog += _encode_headers(headers) return _encode_netstring(prolog) + data |
def _parse_headers(headers): "Get headers dict from header string." try: return dict(line.rstrip().split(": ", 1) for line in headers.splitlines() if line ) except (TypeError, ValueError) as exc: raise SCGIException("Error in SCGI headers %r (%s)" % (headers, exc,)) |
def _parse_response(resp): """ Get xmlrpc response from scgi response """ # Assume they care for standards and send us CRLF (not just LF) try: headers, payload = resp.split("\r\n\r\n", 1) except (TypeError, ValueError) as exc: raise SCGIException("No header delimiter in SCGI response of length %d (%s)" % (len(resp), ex... |
def scgi_request(url, methodname, *params, **kw): """ Send a XMLRPC request over SCGI to the given URL. @param url: Endpoint URL. @param methodname: XMLRPC method name. @param params: Tuple of simple python objects. @keyword deserialize: Parse XML result? (default is True) @return: XMLRPC response, or the equivalent Py... |
def send(self, data): """ Open transport, send data, and yield response chunks. """ sock = socket.socket(*self.sock_args) try: sock.connect(self.sock_addr) except socket.error as exc: raise socket.error("Can't connect to %r (%s)" % (self.url.geturl(), exc)) try: # Send request sock.send(data) # Read response while True... |
def send(self, data): """ Open transport, send data, and yield response chunks. """ try: proc = subprocess.Popen(self.cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError as exc: raise URLError("Calling %r failed (%s)!" % (' '.join(self.cmd), exc)) else: stdout, stderr = proc.commu... |
def send(self, data): """ Send data over scgi to URL and get response. """ start = time.time() try: scgi_resp = ''.join(self.transport.send(_encode_payload(data))) finally: self.latency = time.time() - start resp, self.resp_headers = _parse_response(scgi_resp) return resp |
def _frames(traceback): ''' Returns generator that iterates over frames in a traceback ''' frame = traceback while frame.tb_next: frame = frame.tb_next yield frame.tb_frame return |
def _methodInTraceback(self, name, traceback): ''' Returns boolean whether traceback contains method from this instance ''' foundMethod = False for frame in self._frames(traceback): this = frame.f_locals.get('self') if this is self and frame.f_code.co_name == name: foundMethod = True break return foundMethod |
def addStep(self, callback, *args, **kwargs): ''' Add rollback step with optional arguments. If a rollback is triggered, each step is called in LIFO order. ''' self.steps.append((callback, args, kwargs)) |
def doRollback(self): ''' Call each rollback step in LIFO order. ''' while self.steps: callback, args, kwargs = self.steps.pop() callback(*args, **kwargs) |
def neighbor_graph(X, metric='euclidean', k=None, epsilon=None, weighting='none', precomputed=False): '''Build a neighbor graph from pairwise distance information. X : two-dimensional array-like Shape must either be (num_pts, num_dims) or (num_pts, num_pts). k : int, maximum number of nearest neighbors epsilon : float,... |
if not precomputed and epsilon is None: return _sparse_neighbor_graph(X, k, binary, metric) if precomputed: D = X else: D = pairwise_distances(X, metric=metric) return _slow_neighbor_graph(D, k, epsilon, binary) |
def nearest_neighbors(query_pts, target_pts=None, metric='euclidean', k=None, epsilon=None, return_dists=False, precomputed=False): '''Find nearest neighbors of query points from a matrix of target points. Returns a list of indices of neighboring points, one list per query. If no target_pts are specified, distances are... |
None: if k is not None: # kNN filtering _, not_nn = _min_k_indices(dists, k, inv_ind=True) dists[np.arange(dists.shape[0]), not_nn.T] = np.inf # epsilon-ball is_close = dists <= epsilon if return_dists: nnis,nnds = [],[] for i,row in enumerate(is_close): nns = np.nonzero(row)[0] nnis.append(nns) nnds.append(dists[i,nns... |
def _sparse_neighbor_graph(X, k, binary=False, metric='l2'): '''Construct a sparse adj matrix from a matrix of points (one per row). Non-zeros are unweighted/binary distance values, depending on the binary arg. Doesn't include self-edges.''' knn = NearestNeighbors(n_neighbors=k, metric=metric).fit(X) mode = 'connectivi... |
def saffron(X, q=32, k=4, tangent_dim=1, curv_thresh=0.95, decay_rate=0.9, max_iter=15, verbose=False): ''' SAFFRON graph construction method. X : (n,d)-array of coordinates q : int, median number of candidate friends per vertex k : int, number of friends to select per vertex, k < q tangent_dim : int, dimensionality of... |
= np.median(dist[np.arange(n), idx]) # make candidate graph + weights W = neighbor_graph(dist, precomputed=True, epsilon=r).matrix('csr') # NOTE: this differs from the paper, where W.data[:] = 1 initially W.data[:] = 1 / W.data # row normalize normalize(W, norm='l1', axis=1, copy=False) # XXX: hacky densify W = W.toarr... |
k if excess > 0: bad_idx = np.argpartition(x, excess-1)[:excess] W[i, nbrs[bad_idx]] *= decay_rate W[i] /= W[i].sum() # update goodness measure (weighted alignment) goodness += x.dot(W[i,nbrs]) if verbose: # pragma: no cover goodness /= n print(it, goodness, goodness / prev_goodness) if goodness / prev_goodness <= 1.00... |
def _principal_angle(a, B): '''a is (d,t), B is (k,d,t)''' # TODO: check case for t = d-1 if a.shape[1] == 1: return a.T.dot(B)[0,:,0] # find normals that maximize distance when projected x1 = np.einsum('abc,adc->abd', B, B).dot(a) - a # b.dot(b.T).dot(a) - a x2 = np.einsum('ab,cad->cbd', a.dot(a.T), B) - B # a.dot(a.T... |
def show(db, encoding, no_limit, zip, case_insensitive): """Show .dbf file contents (rows).""" limit = 15 if no_limit: limit = float('inf') with open_db(db, zip, encoding=encoding, case_sensitive=not case_insensitive) as dbf: for idx, row in enumerate(dbf, 1): click.secho('') for key, val in row._asdict().items(): clic... |
def describe(db, zip, case_insensitive): """Show .dbf file statistics.""" with open_db(db, zip, case_sensitive=not case_insensitive) as dbf: click.secho('Rows count: %s' % (dbf.prolog.records_count)) click.secho('Fields:') for field in dbf.fields: click.secho(' %s: %s' % (field.type, field)) |
def clone_repo(pkg, dest, repo, repo_dest, branch): """Clone the Playdoh repo into a custom path.""" git(['clone', '--recursive', '-b', branch, repo, repo_dest]) |
def init_pkg(pkg, repo_dest): """ Initializes a custom named package module. This works by replacing all instances of 'project' with a custom module name. """ vars = {'pkg': pkg} with dir_path(repo_dest): patch("""\ diff --git a/manage.py b/manage.py index 40ebb0a..cdfe363 100755 --- a/manage.py +++ b/manage.py @@ -3,7... |
# Bundles is a dictionary of two dictionaries, css and js, which list css files # and js files that can be bundled together by the minify app. diff --git a/setup.py b/setup.py index 58dbd93..9a38628 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ import os from setuptools import setup, find_packages -setup(name='p... |
def create_settings(pkg, repo_dest, db_user, db_name, db_password, db_host, db_port): """ Creates a local settings file out of the distributed template. This also fills in database settings and generates a secret key, etc. """ vars = {'pkg': pkg, 'db_user': db_user, 'db_name': db_name, 'db_password': db_password or '',... |
DEV = True # Playdoh ships with Bcrypt+HMAC by default because it's the most secure. # To use bcrypt, fill in a secret HMAC key. It cannot be blank. HMAC_KEYS = { - #'2012-06-06': 'some secret', + '%(hmac_date)s': '%(hmac_key)s', } from django_sha2 import get_password_hashers PASSWORD_HASHERS = get_password_hashers(bas... |
def create_virtualenv(pkg, repo_dest, python): """Creates a virtualenv within which to install your new application.""" workon_home = os.environ.get('WORKON_HOME') venv_cmd = find_executable('virtualenv') python_bin = find_executable(python) if not python_bin: raise EnvironmentError('%s is not installed or not ' 'avail... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.