Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def get_for_accounts(self, accounts: List[Account]): ''' Get all splits for the given accounts ''' account_ids = [acc.guid for acc in accounts] query = ( self.query .filter(Split.account_guid.in_(account_ids)) ) ...
[]
Please provide a description of the function:def __get_model_for_portfolio_value(input_model: PortfolioValueInputModel ) -> PortfolioValueViewModel: result = PortfolioValueViewModel() result.filter = input_model ref_datum = Datum() ref_datum.from_datetime(input_model.as_of_date) ref_da...
[ " loads the data for portfolio value " ]
Please provide a description of the function:def __load_settings(self): #file_path = path.relpath(settings_file_path) #file_path = path.abspath(settings_file_path) file_path = self.file_path try: self.data = json.load(open(file_path)) except FileNotFoundErro...
[ " Load settings from .json file " ]
Please provide a description of the function:def file_exists(self) -> bool: cfg_path = self.file_path assert cfg_path return path.isfile(cfg_path)
[ " Check if the settings file exists or not " ]
Please provide a description of the function:def save(self): content = self.dumps() fileutils.save_text_to_file(content, self.file_path)
[ " Saves the settings contents " ]
Please provide a description of the function:def database_path(self): filename = self.database_filename db_path = ":memory:" if filename == ":memory:" else ( path.abspath(path.join(__file__, "../..", "..", "data", filename))) return db_path
[ "\n Full database path. Includes the default location + the database filename.\n " ]
Please provide a description of the function:def file_path(self) -> str: user_dir = self.__get_user_path() file_path = path.abspath(path.join(user_dir, self.FILENAME)) return file_path
[ " Settings file absolute path" ]
Please provide a description of the function:def dumps(self) -> str: return json.dumps(self.data, sort_keys=True, indent=4)
[ " Dumps the json content as a string " ]
Please provide a description of the function:def __copy_template(self): import shutil template_filename = "settings.json.template" template_path = path.abspath( path.join(__file__, "..", "..", "config", template_filename)) settings_path = self.file_path shut...
[ " Copy the settings template into the user's directory " ]
Please provide a description of the function:def is_not_empty(self, value, strict=False): value = stringify(value) if value is not None: return self.shout('Value %r is empty', strict, value)
[ "if value is not empty" ]
Please provide a description of the function:def is_numeric(self, value, strict=False): value = stringify(value) if value is not None: if value.isnumeric(): return self.shout('value %r is not numeric', strict, value)
[ "if value is numeric" ]
Please provide a description of the function:def is_integer(self, value, strict=False): if value is not None: if isinstance(value, numbers.Number): return value = stringify(value) if value is not None and value.isnumeric(): return self.sho...
[ "if value is an integer" ]
Please provide a description of the function:def match_date(self, value, strict=False): value = stringify(value) try: parse(value) except Exception: self.shout('Value %r is not a valid date', strict, value)
[ "if value is a date" ]
Please provide a description of the function:def match_regexp(self, value, q, strict=False): value = stringify(value) mr = re.compile(q) if value is not None: if mr.match(value): return self.shout('%r not matching the regexp %r', strict, value, q)
[ "if value matches a regexp q" ]
Please provide a description of the function:def has_length(self, value, q, strict=False): value = stringify(value) if value is not None: if len(value) == q: return self.shout('Value %r not matching length %r', strict, value, q)
[ "if value has a length of q" ]
Please provide a description of the function:def must_contain(self, value, q, strict=False): if value is not None: if value.find(q) != -1: return self.shout('Value %r does not contain %r', strict, value, q)
[ "if value must contain q" ]
Please provide a description of the function:def extract(context, data): with context.http.rehash(data) as result: file_path = result.file_path content_type = result.content_type extract_dir = random_filename(context.work_path) if content_type in ZIP_MIME_TYPES: extr...
[ "Extract a compressed file" ]
Please provide a description of the function:def size(cls, crawler): key = make_key('queue_pending', crawler) return unpack_int(conn.get(key))
[ "Total operations pending for this crawler" ]
Please provide a description of the function:def read_word(image, whitelist=None, chars=None, spaces=False): from tesserocr import PyTessBaseAPI api = PyTessBaseAPI() api.SetPageSegMode(8) if whitelist is not None: api.SetVariable("tessedit_char_whitelist", whitelist) api.SetImage(image...
[ " OCR a single word from an image. Useful for captchas.\n Image should be pre-processed to remove noise etc. " ]
Please provide a description of the function:def read_char(image, whitelist=None): from tesserocr import PyTessBaseAPI api = PyTessBaseAPI() api.SetPageSegMode(10) if whitelist is not None: api.SetVariable("tessedit_char_whitelist", whitelist) api.SetImage(image) api.Recognize() ...
[ " OCR a single character from an image. Useful for captchas." ]
Please provide a description of the function:def get(self, name, default=None): value = self.params.get(name, default) if isinstance(value, str): value = os.path.expandvars(value) return value
[ "Get a configuration value and expand environment variables." ]
Please provide a description of the function:def emit(self, rule='pass', stage=None, data={}, delay=None, optional=False): if stage is None: stage = self.stage.handlers.get(rule) if optional and stage is None: return if stage is None or stage not in ...
[ "Invoke the next stage, either based on a handling rule, or by calling\n the `pass` rule by default." ]
Please provide a description of the function:def recurse(self, data={}, delay=None): return self.emit(stage=self.stage.name, data=data, delay=delay)
[ "Have a stage invoke itself with a modified set of arguments." ]
Please provide a description of the function:def execute(self, data): if Crawl.is_aborted(self.crawler, self.run_id): return try: Crawl.operation_start(self.crawler, self.stage, self.run_id) self.log.info('[%s->%s(%s)]: %s', self.cr...
[ "Execute the crawler and create a database record of having done\n so." ]
Please provide a description of the function:def skip_incremental(self, *criteria): if not self.incremental: return False # this is pure convenience, and will probably backfire at some point. key = make_key(*criteria) if key is None: return False ...
[ "Perform an incremental check on a set of criteria.\n\n This can be used to execute a part of a crawler only once per an\n interval (which is specified by the ``expire`` setting). If the\n operation has already been performed (and should thus be skipped),\n this will return ``True``. If ...
Please provide a description of the function:def store_data(self, data, encoding='utf-8'): path = random_filename(self.work_path) try: with open(path, 'wb') as fh: if isinstance(data, str): data = data.encode(encoding) if data is n...
[ "Put the given content into a file, possibly encoding it as UTF-8\n in the process." ]
Please provide a description of the function:def check_due(self): if self.disabled: return False if self.is_running: return False if self.delta is None: return False last_run = self.last_run if last_run is None: return True...
[ "Check if the last execution of this crawler is older than\n the scheduled interval." ]
Please provide a description of the function:def flush(self): Queue.flush(self) Event.delete(self) Crawl.flush(self)
[ "Delete all run-time data generated by this crawler." ]
Please provide a description of the function:def run(self, incremental=None, run_id=None): state = { 'crawler': self.name, 'run_id': run_id, 'incremental': settings.INCREMENTAL } if incremental is not None: state['incremental'] = increment...
[ "Queue the execution of a particular crawler." ]
Please provide a description of the function:def fetch(context, data): url = data.get('url') attempt = data.pop('retry_attempt', 1) try: result = context.http.get(url, lazy=True) rules = context.get('rules', {'match_all': {}}) if not Rule.get_rule(rules).apply(result): ...
[ "Do an HTTP GET on the ``url`` specified in the inbound data." ]
Please provide a description of the function:def dav_index(context, data): # This is made to work with ownCloud/nextCloud, but some rumor has # it they are "standards compliant" and it should thus work for # other DAV servers. url = data.get('url') result = context.http.request('PROPFIND', url)...
[ "List files in a WebDAV directory." ]
Please provide a description of the function:def session(context, data): context.http.reset() user = context.get('user') password = context.get('password') if user is not None and password is not None: context.http.session.auth = (user, password) user_agent = context.get('user_agent'...
[ "Set some HTTP parameters for all subsequent requests.\n\n This includes ``user`` and ``password`` for HTTP basic authentication,\n and ``user_agent`` as a header.\n " ]
Please provide a description of the function:def save(cls, crawler, stage, level, run_id, error=None, message=None): event = { 'stage': stage.name, 'level': level, 'timestamp': pack_now(), 'error': error, 'message': message } d...
[ "Create an event, possibly based on an exception." ]
Please provide a description of the function:def get_stage_events(cls, crawler, stage_name, start, end, level=None): key = make_key(crawler, "events", stage_name, level) return cls.event_list(key, start, end)
[ "events from a particular stage" ]
Please provide a description of the function:def get_run_events(cls, crawler, run_id, start, end, level=None): key = make_key(crawler, "events", run_id, level) return cls.event_list(key, start, end)
[ "Events from a particular run" ]
Please provide a description of the function:def soviet_checksum(code): def sum_digits(code, offset=1): total = 0 for digit, index in zip(code[:7], count(offset)): total += int(digit) * index summed = (total / 11 * 11) return total - summed check = sum_digits(co...
[ "Courtesy of Sir Vlad Lavrov." ]
Please provide a description of the function:def search_results_total(html, xpath, check, delimiter): for container in html.findall(xpath): if check in container.findtext('.'): text = container.findtext('.').split(delimiter) total = int(text[-1].strip()) return total
[ " Get the total number of results from the DOM of a search index. " ]
Please provide a description of the function:def search_results_last_url(html, xpath, label): for container in html.findall(xpath): if container.text_content().strip() == label: return container.find('.//a').get('href')
[ " Get the URL of the 'last' button in a search results listing. " ]
Please provide a description of the function:def op_count(cls, crawler, stage=None): if stage: total_ops = conn.get(make_key(crawler, stage)) else: total_ops = conn.get(make_key(crawler, "total_ops")) return unpack_int(total_ops)
[ "Total operations performed for this crawler" ]
Please provide a description of the function:def index(): crawlers = [] for crawler in manager: data = Event.get_counts(crawler) data['last_active'] = crawler.last_run data['total_ops'] = crawler.op_count data['running'] = crawler.is_running data['crawler'] = crawler...
[ "Generate a list of all crawlers, alphabetically, with op counts." ]
Please provide a description of the function:def clean_html(context, data): doc = _get_html_document(context, data) if doc is None: context.emit(data=data) return remove_paths = context.params.get('remove_paths') for path in ensure_list(remove_paths): for el in doc.findall(...
[ "Clean an HTML DOM and store the changed version." ]
Please provide a description of the function:def execute(cls, stage, state, data, next_allowed_exec_time=None): try: context = Context.from_state(state, stage) now = datetime.utcnow() if next_allowed_exec_time and now < next_allowed_exec_time: # task ...
[ "Execute the operation, rate limiting allowing." ]
Please provide a description of the function:def _upsert(context, params, data): table = params.get("table") table = datastore.get_table(table, primary_id=False) unique_keys = ensure_list(params.get("unique")) data["__last_seen"] = datetime.datetime.utcnow() if len(unique_keys): updated...
[ "Insert or update data and add/update appropriate timestamps" ]
Please provide a description of the function:def _recursive_upsert(context, params, data): children = params.get("children", {}) nested_calls = [] for child_params in children: key = child_params.get("key") child_data_list = ensure_list(data.pop(key)) if isinstance(child_data_li...
[ "Insert or update nested dicts recursively into db tables" ]
Please provide a description of the function:def db(context, data): table = context.params.get("table", context.crawler.name) params = context.params params["table"] = table _recursive_upsert(context, params, data)
[ "Insert or update `data` as a row into specified db table" ]
Please provide a description of the function:def cli(debug, cache, incremental): settings.HTTP_CACHE = cache settings.INCREMENTAL = incremental settings.DEBUG = debug if settings.DEBUG: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) in...
[ "Crawler framework for documents and structured scrapers." ]
Please provide a description of the function:def run(crawler): crawler = get_crawler(crawler) crawler.run() if is_sync_mode(): TaskRunner.run_sync()
[ "Run a specified crawler." ]
Please provide a description of the function:def index(): crawler_list = [] for crawler in manager: is_due = 'yes' if crawler.check_due() else 'no' if crawler.disabled: is_due = 'off' crawler_list.append([crawler.name, crawler.description, ...
[ "List the available crawlers." ]
Please provide a description of the function:def scheduled(wait=False): manager.run_scheduled() while wait: # Loop and try to run scheduled crawlers at short intervals manager.run_scheduled() time.sleep(settings.SCHEDULER_INTERVAL)
[ "Run crawlers that are due." ]
Please provide a description of the function:def _get_directory_path(context): path = os.path.join(settings.BASE_PATH, 'store') path = context.params.get('path', path) path = os.path.join(path, context.crawler.name) path = os.path.abspath(os.path.expandvars(path)) try: os.makedirs(path)...
[ "Get the storage path fro the output." ]
Please provide a description of the function:def directory(context, data): with context.http.rehash(data) as result: if not result.ok: return content_hash = data.get('content_hash') if content_hash is None: context.emit_warning("No content hash in data.") ...
[ "Store the collected files to a given directory." ]
Please provide a description of the function:def seed(context, data): for key in ('url', 'urls'): for url in ensure_list(context.params.get(key)): url = url % data context.emit(data={'url': url})
[ "Initialize a crawler with a set of seed URLs.\n\n The URLs are given as a list or single value to the ``urls`` parameter.\n\n If this is called as a second stage in a crawler, the URL will be formatted\n against the supplied ``data`` values, e.g.:\n\n https://crawl.site/entries/%(number)s.html\n ...
Please provide a description of the function:def enumerate(context, data): items = ensure_list(context.params.get('items')) for item in items: data['item'] = item context.emit(data=data)
[ "Iterate through a set of items and emit each one of them." ]
Please provide a description of the function:def sequence(context, data): number = data.get('number', context.params.get('start', 1)) stop = context.params.get('stop') step = context.params.get('step', 1) delay = context.params.get('delay') prefix = context.params.get('tag') while True: ...
[ "Generate a sequence of numbers.\n\n It is the memorious equivalent of the xrange function, accepting the\n ``start``, ``stop`` and ``step`` parameters.\n\n This can run in two ways:\n * As a single function generating all numbers in the given range.\n * Recursively, generating numbers one by one wit...
Please provide a description of the function:def fetch(self): if self._file_path is not None: return self._file_path temp_path = self.context.work_path if self._content_hash is not None: self._file_path = storage.load_file(self._content_hash, ...
[ "Lazily trigger download of the data when requested." ]
Please provide a description of the function:def make_key(*criteria): criteria = [stringify(c) for c in criteria] criteria = [c for c in criteria if c is not None] if len(criteria): return ':'.join(criteria)
[ "Make a string key out of many criteria." ]
Please provide a description of the function:def random_filename(path=None): filename = uuid4().hex if path is not None: filename = os.path.join(path, filename) return filename
[ "Make a UUID-based file name which is extremely unlikely\n to exist already." ]
Please provide a description of the function:def box(self, bottom_left_corner, top_right_corner, paint=None, blank=False): ''' creates the visual frame/box in which we place the graph ''' path = [ bottom_left_corner, Point(bottom_left_corner.x, top_right_corner.y), to...
[]
Please provide a description of the function:def get_terminal_size(): current_os = platform.system() tuple_xy = None if current_os == 'Windows': tuple_xy = _get_terminal_size_windows() if tuple_xy is None: tuple_xy = _get_terminal_size_tput() # needed for window'...
[ " getTerminalSize()\n - get width and height of console\n - works on linux,os x,windows,cygwin(windows)\n originally retrieved from:\n http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python\n " ]
Please provide a description of the function:def sample_vMF(mu, kappa, num_samples): dim = len(mu) result = np.zeros((num_samples, dim)) for nn in range(num_samples): # sample offset from center (on sphere) with spread kappa w = _sample_weight(kappa, dim) # sample a point v on ...
[ "Generate num_samples N-dimensional samples from von Mises Fisher\n distribution around center mu \\in R^N with concentration kappa.\n " ]
Please provide a description of the function:def _sample_weight(kappa, dim): dim = dim - 1 # since S^{n-1} b = dim / (np.sqrt(4. * kappa ** 2 + dim ** 2) + 2 * kappa) x = (1. - b) / (1. + b) c = kappa * x + dim * np.log(1 - x ** 2) while True: z = np.random.beta(dim / 2., dim / 2.) ...
[ "Rejection sampling scheme for sampling distance from center on\n surface of the sphere.\n " ]
Please provide a description of the function:def _sample_orthonormal_to(mu): v = np.random.randn(mu.shape[0]) proj_mu_v = mu * np.dot(mu, v) / np.linalg.norm(mu) orthto = v - proj_mu_v return orthto / np.linalg.norm(orthto)
[ "Sample point on sphere orthogonal to mu." ]
Please provide a description of the function:def _spherical_kmeans_single_lloyd( X, n_clusters, sample_weight=None, max_iter=300, init="k-means++", verbose=False, x_squared_norms=None, random_state=None, tol=1e-4, precompute_distances=True, ): random_state = check_random...
[ "\n Modified from sklearn.cluster.k_means_.k_means_single_lloyd.\n " ]
Please provide a description of the function:def spherical_k_means( X, n_clusters, sample_weight=None, init="k-means++", n_init=10, max_iter=300, verbose=False, tol=1e-4, random_state=None, copy_x=True, n_jobs=1, algorithm="auto", return_n_iter=False, ): if n...
[ "Modified from sklearn.cluster.k_means_.k_means.\n " ]
Please provide a description of the function:def fit(self, X, y=None, sample_weight=None): if self.normalize: X = normalize(X) random_state = check_random_state(self.random_state) # TODO: add check that all data is unit-normalized self.cluster_centers_, self.label...
[ "Compute k-means clustering.\n\n Parameters\n ----------\n\n X : array-like or sparse matrix, shape=(n_samples, n_features)\n\n y : Ignored\n not used, present here for API consistency by convention.\n\n sample_weight : array-like, shape (n_samples,), optional\n ...
Please provide a description of the function:def _inertia_from_labels(X, centers, labels): n_examples, n_features = X.shape inertia = np.zeros((n_examples,)) for ee in range(n_examples): inertia[ee] = 1 - X[ee, :].dot(centers[int(labels[ee]), :].T) return np.sum(inertia)
[ "Compute inertia with cosine distance using known labels.\n " ]
Please provide a description of the function:def _labels_inertia(X, centers): n_examples, n_features = X.shape n_clusters, n_features = centers.shape labels = np.zeros((n_examples,)) inertia = np.zeros((n_examples,)) for ee in range(n_examples): dists = np.zeros((n_clusters,)) ...
[ "Compute labels and inertia with cosine distance.\n " ]
Please provide a description of the function:def _vmf_log(X, kappa, mu): n_examples, n_features = X.shape return np.log(_vmf_normalize(kappa, n_features) * np.exp(kappa * X.dot(mu).T))
[ "Computs log(vMF(X, kappa, mu)) using built-in numpy/scipy Bessel\n approximations.\n\n Works well on small kappa and mu.\n " ]
Please provide a description of the function:def _vmf_normalize(kappa, dim): num = np.power(kappa, dim / 2. - 1.) if dim / 2. - 1. < 1e-15: denom = np.power(2. * np.pi, dim / 2.) * i0(kappa) else: denom = np.power(2. * np.pi, dim / 2.) * iv(dim / 2. - 1., kappa) if np.isinf(num): ...
[ "Compute normalization constant using built-in numpy/scipy Bessel\n approximations.\n\n Works well on small kappa and mu.\n " ]
Please provide a description of the function:def _log_H_asymptotic(nu, kappa): beta = np.sqrt((nu + 0.5) ** 2) kappa_l = np.min([kappa, np.sqrt((3. * nu + 11. / 2.) * (nu + 3. / 2.))]) return _S(kappa, nu + 0.5, beta) + ( _S(kappa_l, nu, nu + 2.) - _S(kappa_l, nu + 0.5, beta) )
[ "Compute the Amos-type upper bound asymptotic approximation on H where\n log(H_\\nu)(\\kappa) = \\int_0^\\kappa R_\\nu(t) dt.\n\n See \"lH_asymptotic <-\" in movMF.R and utility function implementation notes\n from https://cran.r-project.org/web/packages/movMF/index.html\n " ]
Please provide a description of the function:def _S(kappa, alpha, beta): kappa = 1. * np.abs(kappa) alpha = 1. * alpha beta = 1. * np.abs(beta) a_plus_b = alpha + beta u = np.sqrt(kappa ** 2 + beta ** 2) if alpha == 0: alpha_scale = 0 else: alpha_scale = alpha * np.log((...
[ "Compute the antiderivative of the Amos-type bound G on the modified\n Bessel function ratio.\n\n Note: Handles scalar kappa, alpha, and beta only.\n\n See \"S <-\" in movMF.R and utility function implementation notes from\n https://cran.r-project.org/web/packages/movMF/index.html\n " ]
Please provide a description of the function:def _vmf_log_asymptotic(X, kappa, mu): n_examples, n_features = X.shape log_vfm = kappa * X.dot(mu).T + -_log_H_asymptotic(n_features / 2. - 1., kappa) return log_vfm
[ "Compute log(f(x|theta)) via Amos approximation\n\n log(f(x|theta)) = theta' x - log(H_{d/2-1})(\\|theta\\|)\n\n where theta = kappa * X, \\|theta\\| = kappa.\n\n Computing _vmf_log helps with numerical stability / loss of precision for\n for large values of kappa and n_features.\n\n See utility ...
Please provide a description of the function:def _init_unit_centers(X, n_clusters, random_state, init): n_examples, n_features = np.shape(X) if isinstance(init, np.ndarray): n_init_clusters, n_init_features = init.shape assert n_init_clusters == n_clusters assert n_init_features == ...
[ "Initializes unit norm centers.\n\n Parameters\n ----------\n X : array-like or sparse matrix, shape=(n_samples, n_features)\n\n n_clusters : int, optional, default: 8\n The number of clusters to form as well as the number of\n centroids to generate.\n\n random_state : integer or numpy....
Please provide a description of the function:def _expectation(X, centers, weights, concentrations, posterior_type="soft"): n_examples, n_features = np.shape(X) n_clusters, _ = centers.shape if n_features <= 50: # works up to about 50 before numrically unstable vmf_f = _vmf_log else: ...
[ "Compute the log-likelihood of each datapoint being in each cluster.\n\n Parameters\n ----------\n centers (mu) : array, [n_centers x n_features]\n weights (alpha) : array, [n_centers, ] (alpha)\n concentrations (kappa) : array, [n_centers, ]\n\n Returns\n ----------\n posterior : array, [n_...
Please provide a description of the function:def _maximization(X, posterior, force_weights=None): n_examples, n_features = X.shape n_clusters, n_examples = posterior.shape concentrations = np.zeros((n_clusters,)) centers = np.zeros((n_clusters, n_features)) if force_weights is None: wei...
[ "Estimate new centers, weights, and concentrations from\n\n Parameters\n ----------\n posterior : array, [n_centers, n_examples]\n The posterior matrix from the expectation step.\n\n force_weights : None or array, [n_centers, ]\n If None is passed, will estimate weights.\n If an arr...
Please provide a description of the function:def _movMF( X, n_clusters, posterior_type="soft", force_weights=None, max_iter=300, verbose=False, init="random-class", random_state=None, tol=1e-6, ): random_state = check_random_state(random_state) n_examples, n_features = n...
[ "Mixture of von Mises Fisher clustering.\n\n Implements the algorithms (i) and (ii) from\n\n \"Clustering on the Unit Hypersphere using von Mises-Fisher Distributions\"\n by Banerjee, Dhillon, Ghosh, and Sra.\n\n TODO: Currently only supports Banerjee et al 2005 approximation of kappa,\n ho...
Please provide a description of the function:def movMF( X, n_clusters, posterior_type="soft", force_weights=None, n_init=10, n_jobs=1, max_iter=300, verbose=False, init="random-class", random_state=None, tol=1e-6, copy_x=True, ): if n_init <= 0: raise Val...
[ "Wrapper for parallelization of _movMF and running n_init times.\n " ]
Please provide a description of the function:def _check_fit_data(self, X): X = check_array(X, accept_sparse="csr", dtype=[np.float64, np.float32]) n_samples, n_features = X.shape if X.shape[0] < self.n_clusters: raise ValueError( "n_samples=%d should be >= n_...
[ "Verify that the number of samples given is larger than k" ]
Please provide a description of the function:def fit(self, X, y=None): if self.normalize: X = normalize(X) self._check_force_weights() random_state = check_random_state(self.random_state) X = self._check_fit_data(X) ( self.cluster_centers_, ...
[ "Compute mixture of von Mises Fisher clustering.\n\n Parameters\n ----------\n X : array-like or sparse matrix, shape=(n_samples, n_features)\n " ]
Please provide a description of the function:def transform(self, X, y=None): if self.normalize: X = normalize(X) check_is_fitted(self, "cluster_centers_") X = self._check_test_data(X) return self._transform(X)
[ "Transform X to a cluster-distance space.\n In the new space, each dimension is the cosine distance to the cluster\n centers. Note that even if X is sparse, the array returned by\n `transform` will typically be dense.\n\n Parameters\n ----------\n X : {array-like, sparse m...
Please provide a description of the function:def predict(self, X): if self.normalize: X = normalize(X) check_is_fitted(self, "cluster_centers_") X = self._check_test_data(X) return _labels_inertia(X, self.cluster_centers_)[0]
[ "Predict the closest cluster each sample in X belongs to.\n In the vector quantization literature, `cluster_centers_` is called\n the code book and each value returned by `predict` is the index of\n the closest code in the code book.\n\n Note: Does not check that each point is on the sp...
Please provide a description of the function:def score(self, X, y=None): if self.normalize: X = normalize(X) check_is_fitted(self, "cluster_centers_") X = self._check_test_data(X) return -_labels_inertia(X, self.cluster_centers_)[1]
[ "Inertia score (sum of all distances to closest cluster).\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape = [n_samples, n_features]\n New data.\n\n Returns\n -------\n score : float\n Larger score is better.\n " ]
Please provide a description of the function:def log_likelihood(covariance, precision): assert covariance.shape == precision.shape dim, _ = precision.shape log_likelihood_ = ( -np.sum(covariance * precision) + fast_logdet(precision) - dim * np.log(2 * np.pi) ) log_likeli...
[ "Computes the log-likelihood between the covariance and precision\n estimate.\n\n Parameters\n ----------\n covariance : 2D ndarray (n_features, n_features)\n Maximum Likelihood Estimator of covariance\n\n precision : 2D ndarray (n_features, n_features)\n The precision matrix of the cov...
Please provide a description of the function:def kl_loss(covariance, precision): assert covariance.shape == precision.shape dim, _ = precision.shape logdet_p_dot_c = fast_logdet(np.dot(precision, covariance)) return 0.5 * (np.sum(precision * covariance) - logdet_p_dot_c - dim)
[ "Computes the KL divergence between precision estimate and\n reference covariance.\n\n The loss is computed as:\n\n Trace(Theta_1 * Sigma_0) - log(Theta_0 * Sigma_1) - dim(Sigma)\n\n Parameters\n ----------\n covariance : 2D ndarray (n_features, n_features)\n Maximum Likelihood Estimato...
Please provide a description of the function:def quadratic_loss(covariance, precision): assert covariance.shape == precision.shape dim, _ = precision.shape return np.trace((np.dot(covariance, precision) - np.eye(dim)) ** 2)
[ "Computes ...\n\n Parameters\n ----------\n covariance : 2D ndarray (n_features, n_features)\n Maximum Likelihood Estimator of covariance\n\n precision : 2D ndarray (n_features, n_features)\n The precision matrix of the model to be tested\n\n Returns\n -------\n Quadratic loss\n ...
Please provide a description of the function:def ebic(covariance, precision, n_samples, n_features, gamma=0): l_theta = -np.sum(covariance * precision) + fast_logdet(precision) l_theta *= n_features / 2. # is something goes wrong with fast_logdet, return large value if np.isinf(l_theta) or np.isna...
[ "\n Extended Bayesian Information Criteria for model selection.\n\n When using path mode, use this as an alternative to cross-validation for\n finding lambda.\n\n See:\n \"Extended Bayesian Information Criteria for Gaussian Graphical Models\"\n R. Foygel and M. Drton, NIPS 2010\n\n Para...
Please provide a description of the function:def lattice(prng, n_features, alpha, random_sign=False, low=0.3, high=0.7): degree = int(1 + np.round(alpha * n_features / 2.)) if random_sign: sign_row = -1.0 * np.ones(degree) + 2 * ( prng.uniform(low=0, high=1, size=degree) > .5 )...
[ "Returns the adjacency matrix for a lattice network.\n\n The resulting network is a Toeplitz matrix with random values summing\n between -1 and 1 and zeros along the diagonal.\n\n The range of the values can be controlled via the parameters low and high.\n If random_sign is false, all entries will be ne...
Please provide a description of the function:def blocks(prng, block, n_blocks=2, chain_blocks=True): n_block_features, _ = block.shape n_features = n_block_features * n_blocks adjacency = np.zeros((n_features, n_features)) dep_groups = np.eye(n_blocks) if chain_blocks: chain_alpha = np...
[ "Replicates `block` matrix n_blocks times diagonally to create a\n square matrix of size n_features = block.size[0] * n_blocks and with zeros\n along the diagonal.\n\n The graph can be made fully connected using chaining assumption when\n chain_blocks=True (default).\n\n This utility can be used to g...
Please provide a description of the function:def _to_diagonally_dominant(mat): mat += np.diag(np.sum(mat != 0, axis=1) + 0.01) return mat
[ "Make matrix unweighted diagonally dominant using the Laplacian." ]
Please provide a description of the function:def _to_diagonally_dominant_weighted(mat): mat += np.diag(np.sum(np.abs(mat), axis=1) + 0.01) return mat
[ "Make matrix weighted diagonally dominant using the Laplacian." ]
Please provide a description of the function:def _rescale_to_unit_diagonals(mat): d = np.sqrt(np.diag(mat)) mat /= d mat /= d[:, np.newaxis] return mat
[ "Rescale matrix to have unit diagonals.\n\n Note: Call only after diagonal dominance is ensured.\n " ]
Please provide a description of the function:def create(self, n_features, alpha): n_block_features = int(np.floor(1. * n_features / self.n_blocks)) if n_block_features * self.n_blocks != n_features: raise ValueError( ( "Error: n_features {} not di...
[ "Build a new graph with block structure.\n\n Parameters\n -----------\n n_features : int\n\n alpha : float (0,1)\n The complexity / sparsity factor for each graph type.\n\n Returns\n -----------\n (n_features, n_features) matrices: covariance, precision, a...
Please provide a description of the function:def trace_plot(precisions, path, n_edges=20, ground_truth=None, edges=[]): _check_path(path) assert len(path) == len(precisions) assert len(precisions) > 0 path = np.array(path) dim, _ = precisions[0].shape # determine which indices to track ...
[ "Plot the change in precision (or covariance) coefficients as a function\n of changing lambda and l1-norm. Always ignores diagonals.\n\n Parameters\n -----------\n precisions : array of len(path) 2D ndarray, shape (n_features, n_features)\n This is either precision_ or covariance_ from an Invers...
Please provide a description of the function:def fit(self, X, y=None): # default to QuicGraphicalLassoCV estimator = self.estimator or QuicGraphicalLassoCV() self.lam_ = None self.estimator_ = None X = check_array(X, ensure_min_features=2, estimator=self) X = a...
[ "Estimate the precision using an adaptive maximum likelihood estimator.\n Parameters\n ----------\n X : ndarray, shape (n_samples, n_features)\n Data from which to compute the proportion matrix.\n " ]
Please provide a description of the function:def _sample_mvn(n_samples, cov, prng): n_features, _ = cov.shape return prng.multivariate_normal(np.zeros(n_features), cov, size=n_samples)
[ "Draw a multivariate normal sample from the graph defined by cov.\n\n Parameters\n -----------\n n_samples : int\n\n cov : matrix of shape (n_features, n_features)\n Covariance matrix of the graph.\n\n prng : np.random.RandomState instance.\n " ]
Please provide a description of the function:def _fully_random_weights(n_features, lam_scale, prng): weights = np.zeros((n_features, n_features)) n_off_diag = int((n_features ** 2 - n_features) / 2) weights[np.triu_indices(n_features, k=1)] = 0.1 * lam_scale * prng.randn( n_off_diag ) + (0....
[ "Generate a symmetric random matrix with zeros along the diagonal." ]
Please provide a description of the function:def _fix_weights(weight_fun, *args): weights = weight_fun(*args) # TODO: fix this # disable checks for now return weights # if positive semidefinite, then we're good as is if _check_psd(weights): return weights # make diagonally do...
[ "Ensure random weight matrix is valid.\n\n TODO: The diagonally dominant tuning currently doesn't make sense.\n Our weight matrix has zeros along the diagonal, so multiplying by\n a diagonal matrix results in a zero-matrix.\n " ]
Please provide a description of the function:def _fit( indexed_params, penalization, lam, lam_perturb, lam_scale_, estimator, penalty_name, subsample, bootstrap, prng, X=None, ): index = indexed_params if isinstance(X, np.ndarray): local_X = X else: ...
[ "Wrapper function outside of instance for fitting a single model average\n trial.\n\n If X is None, then we assume we are using a broadcast spark object. Else,\n we expect X to get passed into this function.\n " ]
Please provide a description of the function:def _spark_map(fun, indexed_param_grid, sc, seed, X_bc): def _wrap_random_state(split_index, partition): prng = np.random.RandomState(seed + split_index) yield map(partial(fun, prng=prng, X=X_bc), partition) par_param_grid = sc.parallelize(inde...
[ "We cannot pass a RandomState instance to each spark worker since it will\n behave identically across partitions. Instead, we explictly handle the\n partitions with a newly seeded instance.\n\n The seed for each partition will be the \"seed\" (MonteCarloProfile.seed) +\n \"split_index\" which is the pa...
Please provide a description of the function:def fit(self, X, y=None): # default to QuicGraphicalLasso estimator = self.estimator or QuicGraphicalLasso() if self.penalization != "subsampling" and not hasattr( estimator, self.penalty_name ): raise ValueEr...
[ "Learn a model averaged proportion matrix for X.\n Parameters\n ----------\n X : ndarray, shape (n_samples, n_features)\n Data from which to compute the proportion matrix.\n " ]