repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
rcbops/osa_differ | osa_differ/osa_differ.py | checkout | python | def checkout(repo, ref):
# Delete local branch if it exists, remote branch will be tracked
# automatically. This prevents stale local branches from causing problems.
# It also avoids problems with appending origin/ to refs as that doesn't
# work with tags, SHAs, and upstreams not called origin.
if r... | Checkout a repoself. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L222-L245 | null | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | get_roles | python | def get_roles(osa_repo_dir, commit, role_requirements):
repo = Repo(osa_repo_dir)
checkout(repo, commit)
log.info("Looking for file {f} in repo {r}".format(r=osa_repo_dir,
f=role_requirements))
filename = "{0}/{1}".format(osa_repo_dir, role_requir... | Read OSA role information at a particular commit. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L248-L260 | [
"def checkout(repo, ref):\n \"\"\"Checkout a repoself.\"\"\"\n # Delete local branch if it exists, remote branch will be tracked\n # automatically. This prevents stale local branches from causing problems.\n # It also avoids problems with appending origin/ to refs as that doesn't\n # work with tags, ... | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | make_osa_report | python | def make_osa_report(repo_dir, old_commit, new_commit,
args):
update_repo(repo_dir, args.osa_repo_url, args.update)
# Are these commits valid?
validate_commits(repo_dir, [old_commit, new_commit])
# Do we have a valid commit range?
validate_commit_range(repo_dir, old_commit, new_... | Create initial RST report header for OpenStack-Ansible. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L263-L286 | [
"def get_commits(repo_dir, old_commit, new_commit, hide_merges=True):\n \"\"\"Find all commits between two commit SHAs.\"\"\"\n repo = Repo(repo_dir)\n commits = repo.iter_commits(rev=\"{0}..{1}\".format(old_commit, new_commit))\n if hide_merges:\n return [x for x in commits if not x.summary.star... | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | make_report | python | def make_report(storage_directory, old_pins, new_pins, do_update=False,
version_mappings=None):
report = ""
version_mappings = version_mappings or {}
for new_pin in new_pins:
repo_name, repo_url, commit_sha = new_pin
commit_sha = version_mappings.get(repo_name, {}
... | Create RST report from a list of projects/roles. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L289-L329 | [
"def get_commits(repo_dir, old_commit, new_commit, hide_merges=True):\n \"\"\"Find all commits between two commit SHAs.\"\"\"\n repo = Repo(repo_dir)\n commits = repo.iter_commits(rev=\"{0}..{1}\".format(old_commit, new_commit))\n if hide_merges:\n return [x for x in commits if not x.summary.star... | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | normalize_yaml | python | def normalize_yaml(yaml):
if isinstance(yaml, list):
# Normalize the roles YAML data
normalized_yaml = [(x['name'], x['src'], x.get('version', 'HEAD'))
for x in yaml]
else:
# Extract the project names from the roles YAML and create a list of
# tuples.
... | Normalize the YAML from project and role lookups.
These are returned as a list of tuples. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L332-L351 | null | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | post_gist | python | def post_gist(report_data, old_sha, new_sha):
payload = {
"description": ("Changes in OpenStack-Ansible between "
"{0} and {1}".format(old_sha, new_sha)),
"public": True,
"files": {
"osa-diff-{0}-{1}.rst".format(old_sha, new_sha): {
"conten... | Post the report to a GitHub Gist and return the URL of the gist. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L361-L376 | null | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | prepare_storage_dir | python | def prepare_storage_dir(storage_directory):
storage_directory = os.path.expanduser(storage_directory)
if not os.path.exists(storage_directory):
os.mkdir(storage_directory)
return storage_directory | Prepare the storage directory. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L399-L405 | null | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | render_template | python | def render_template(template_file, template_vars):
# Load our Jinja templates
template_dir = "{0}/templates".format(
os.path.dirname(os.path.abspath(__file__))
)
jinja_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_dir),
trim_blocks=True
)
rendered = ji... | Render a jinja template. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L408-L420 | null | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | repo_pull | python | def repo_pull(repo_dir, repo_url, fetch=False):
# Make sure the repository is reset to the master branch.
repo = Repo(repo_dir)
repo.git.clean("-df")
repo.git.reset("--hard")
repo.git.checkout("master")
repo.head.reset(index=True, working_tree=True)
# Compile the refspec appropriately to en... | Reset repository and optionally update it. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L429-L456 | null | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | update_repo | python | def update_repo(repo_dir, repo_url, fetch=False):
repo_exists = os.path.exists(repo_dir)
if not repo_exists:
log.info("Cloning repo {}".format(repo_url))
repo = repo_clone(repo_dir, repo_url)
# Make sure the repo is properly prepared
# and has all the refs required
log.info("Fetchin... | Clone the repo if it doesn't exist already, otherwise update it. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L459-L471 | [
"def repo_clone(repo_dir, repo_url):\n \"\"\"Clone repository to this host.\"\"\"\n repo = Repo.clone_from(repo_url, repo_dir)\n return repo\n",
"def repo_pull(repo_dir, repo_url, fetch=False):\n \"\"\"Reset repository and optionally update it.\"\"\"\n # Make sure the repository is reset to the mas... | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | validate_commits | python | def validate_commits(repo_dir, commits):
log.debug("Validating {c} exist in {r}".format(c=commits, r=repo_dir))
repo = Repo(repo_dir)
for commit in commits:
try:
commit = repo.commit(commit)
except Exception:
msg = ("Commit {commit} could not be found in repo {repo}. ... | Test if a commit is valid for the repository. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L474-L488 | null | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | validate_commit_range | python | def validate_commit_range(repo_dir, old_commit, new_commit):
# Are there any commits between the two commits that were provided?
try:
commits = get_commits(repo_dir, old_commit, new_commit)
except Exception:
commits = []
if len(commits) == 0:
# The user might have gotten their co... | Check if commit range is valid. Flip it if needed. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L491-L516 | [
"def get_commits(repo_dir, old_commit, new_commit, hide_merges=True):\n \"\"\"Find all commits between two commit SHAs.\"\"\"\n repo = Repo(repo_dir)\n commits = repo.iter_commits(rev=\"{0}..{1}\".format(old_commit, new_commit))\n if hide_merges:\n return [x for x in commits if not x.summary.star... | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | get_release_notes | python | def get_release_notes(osa_repo_dir, osa_old_commit, osa_new_commit):
repo = Repo(osa_repo_dir)
# Get a list of tags, sorted
tags = repo.git.tag().split('\n')
tags = sorted(tags, key=LooseVersion)
# Currently major tags are being printed after rc and
# b tags. We need to fix the list so that maj... | Get release notes between the two revisions. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L519-L614 | [
"def checkout(repo, ref):\n \"\"\"Checkout a repoself.\"\"\"\n # Delete local branch if it exists, remote branch will be tracked\n # automatically. This prevents stale local branches from causing problems.\n # It also avoids problems with appending origin/ to refs as that doesn't\n # work with tags, ... | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
rcbops/osa_differ | osa_differ/osa_differ.py | run_osa_differ | python | def run_osa_differ():
# Get our arguments from the command line
args = parse_arguments()
# Set up DEBUG logging if needed
if args.debug:
log.setLevel(logging.DEBUG)
elif args.verbose:
log.setLevel(logging.INFO)
# Create the storage directory if it doesn't exist already.
try... | Start here. | train | https://github.com/rcbops/osa_differ/blob/b3452436655ba3db8cc6602390fd7fdf4ef30f01/osa_differ/osa_differ.py#L646-L720 | [
"def get_projects(osa_repo_dir, commit):\n \"\"\"Get all projects from multiple YAML files.\"\"\"\n # Check out the correct commit SHA from the repository\n repo = Repo(osa_repo_dir)\n checkout(repo, commit)\n\n yaml_files = glob.glob(\n '{0}/playbooks/defaults/repo_packages/*.yml'.format(osa_... | #!/usr/bin/env python
# Copyright 2016, Major Hayden
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
pudo/normality | normality/paths.py | _safe_name | python | def _safe_name(file_name, sep):
file_name = stringify(file_name)
if file_name is None:
return
file_name = ascii_text(file_name)
file_name = category_replace(file_name, UNICODE_CATEGORIES)
file_name = collapse_spaces(file_name)
if file_name is None or not len(file_name):
return
... | Convert the file name to ASCII and normalize the string. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/paths.py#L11-L21 | [
"def collapse_spaces(text):\n \"\"\"Remove newlines, tabs and multiple spaces with single spaces.\"\"\"\n if not isinstance(text, six.string_types):\n return text\n return COLLAPSE_RE.sub(WS, text).strip(WS)\n",
"def category_replace(text, replacements=UNICODE_CATEGORIES):\n \"\"\"Remove charac... | import os
from banal import decode_path
from normality.stringify import stringify
from normality.cleaning import collapse_spaces, category_replace
from normality.constants import UNICODE_CATEGORIES, WS
from normality.transliteration import ascii_text
MAX_LENGTH = 254
def safe_filename(file_name, sep='_', default=No... |
pudo/normality | normality/paths.py | safe_filename | python | def safe_filename(file_name, sep='_', default=None, extension=None):
if file_name is None:
return decode_path(default)
file_name = decode_path(file_name)
file_name = os.path.basename(file_name)
file_name, _extension = os.path.splitext(file_name)
file_name = _safe_name(file_name, sep=sep)
... | Create a secure filename for plain file system storage. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/paths.py#L24-L40 | [
"def _safe_name(file_name, sep):\n \"\"\"Convert the file name to ASCII and normalize the string.\"\"\"\n file_name = stringify(file_name)\n if file_name is None:\n return\n file_name = ascii_text(file_name)\n file_name = category_replace(file_name, UNICODE_CATEGORIES)\n file_name = collaps... | import os
from banal import decode_path
from normality.stringify import stringify
from normality.cleaning import collapse_spaces, category_replace
from normality.constants import UNICODE_CATEGORIES, WS
from normality.transliteration import ascii_text
MAX_LENGTH = 254
def _safe_name(file_name, sep):
"""Convert th... |
pudo/normality | normality/stringify.py | stringify | python | def stringify(value, encoding_default='utf-8', encoding=None):
if value is None:
return None
if not isinstance(value, six.text_type):
if isinstance(value, (date, datetime)):
return value.isoformat()
elif isinstance(value, (float, Decimal)):
return Decimal(value).... | Brute-force convert a given object to a string.
This will attempt an increasingly mean set of conversions to make a given
object into a unicode string. It is guaranteed to either return unicode or
None, if all conversions failed (or the value is indeed empty). | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/stringify.py#L10-L38 | null | import six
from datetime import datetime, date
from decimal import Decimal
from normality.cleaning import remove_byte_order_mark
from normality.cleaning import remove_unsafe_chars
from normality.encoding import guess_encoding
|
pudo/normality | normality/encoding.py | normalize_encoding | python | def normalize_encoding(encoding, default=DEFAULT_ENCODING):
if encoding is None:
return default
encoding = encoding.lower().strip()
if encoding in ['', 'ascii']:
return default
try:
codecs.lookup(encoding)
return encoding
except LookupError:
return default | Normalize the encoding name, replace ASCII w/ UTF-8. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/encoding.py#L8-L19 | null | import io
import codecs
import chardet
DEFAULT_ENCODING = 'utf-8'
def normalize_result(result, default, threshold=0.2):
"""Interpret a chardet result."""
if result is None:
return default
if result.get('confidence') is None:
return default
if result.get('confidence') < threshold:
... |
pudo/normality | normality/encoding.py | normalize_result | python | def normalize_result(result, default, threshold=0.2):
if result is None:
return default
if result.get('confidence') is None:
return default
if result.get('confidence') < threshold:
return default
return normalize_encoding(result.get('encoding'),
defa... | Interpret a chardet result. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/encoding.py#L22-L31 | [
"def normalize_encoding(encoding, default=DEFAULT_ENCODING):\n \"\"\"Normalize the encoding name, replace ASCII w/ UTF-8.\"\"\"\n if encoding is None:\n return default\n encoding = encoding.lower().strip()\n if encoding in ['', 'ascii']:\n return default\n try:\n codecs.lookup(en... | import io
import codecs
import chardet
DEFAULT_ENCODING = 'utf-8'
def normalize_encoding(encoding, default=DEFAULT_ENCODING):
"""Normalize the encoding name, replace ASCII w/ UTF-8."""
if encoding is None:
return default
encoding = encoding.lower().strip()
if encoding in ['', 'ascii']:
... |
pudo/normality | normality/encoding.py | guess_encoding | python | def guess_encoding(text, default=DEFAULT_ENCODING):
result = chardet.detect(text)
return normalize_result(result, default=default) | Guess string encoding.
Given a piece of text, apply character encoding detection to
guess the appropriate encoding of the text. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/encoding.py#L34-L41 | [
"def normalize_result(result, default, threshold=0.2):\n \"\"\"Interpret a chardet result.\"\"\"\n if result is None:\n return default\n if result.get('confidence') is None:\n return default\n if result.get('confidence') < threshold:\n return default\n return normalize_encoding(r... | import io
import codecs
import chardet
DEFAULT_ENCODING = 'utf-8'
def normalize_encoding(encoding, default=DEFAULT_ENCODING):
"""Normalize the encoding name, replace ASCII w/ UTF-8."""
if encoding is None:
return default
encoding = encoding.lower().strip()
if encoding in ['', 'ascii']:
... |
pudo/normality | normality/encoding.py | guess_file_encoding | python | def guess_file_encoding(fh, default=DEFAULT_ENCODING):
start = fh.tell()
detector = chardet.UniversalDetector()
while True:
data = fh.read(1024 * 10)
if not data:
detector.close()
break
detector.feed(data)
if detector.done:
break
fh.se... | Guess encoding from a file handle. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/encoding.py#L44-L58 | [
"def normalize_result(result, default, threshold=0.2):\n \"\"\"Interpret a chardet result.\"\"\"\n if result is None:\n return default\n if result.get('confidence') is None:\n return default\n if result.get('confidence') < threshold:\n return default\n return normalize_encoding(r... | import io
import codecs
import chardet
DEFAULT_ENCODING = 'utf-8'
def normalize_encoding(encoding, default=DEFAULT_ENCODING):
"""Normalize the encoding name, replace ASCII w/ UTF-8."""
if encoding is None:
return default
encoding = encoding.lower().strip()
if encoding in ['', 'ascii']:
... |
pudo/normality | normality/encoding.py | guess_path_encoding | python | def guess_path_encoding(file_path, default=DEFAULT_ENCODING):
with io.open(file_path, 'rb') as fh:
return guess_file_encoding(fh, default=default) | Wrapper to open that damn file for you, lazy bastard. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/encoding.py#L61-L64 | [
"def guess_file_encoding(fh, default=DEFAULT_ENCODING):\n \"\"\"Guess encoding from a file handle.\"\"\"\n start = fh.tell()\n detector = chardet.UniversalDetector()\n while True:\n data = fh.read(1024 * 10)\n if not data:\n detector.close()\n break\n detector.... | import io
import codecs
import chardet
DEFAULT_ENCODING = 'utf-8'
def normalize_encoding(encoding, default=DEFAULT_ENCODING):
"""Normalize the encoding name, replace ASCII w/ UTF-8."""
if encoding is None:
return default
encoding = encoding.lower().strip()
if encoding in ['', 'ascii']:
... |
pudo/normality | normality/cleaning.py | decompose_nfkd | python | def decompose_nfkd(text):
if text is None:
return None
if not hasattr(decompose_nfkd, '_tr'):
decompose_nfkd._tr = Transliterator.createInstance('Any-NFKD')
return decompose_nfkd._tr.transliterate(text) | Perform unicode compatibility decomposition.
This will replace some non-standard value representations in unicode and
normalise them, while also separating characters and their diacritics into
two separate codepoints. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/cleaning.py#L17-L28 | null | # coding: utf-8
from __future__ import unicode_literals
import re
import six
from icu import Transliterator
from unicodedata import category
from normality.constants import UNICODE_CATEGORIES, CONTROL_CODES, WS
COLLAPSE_RE = re.compile(r'\s+', re.U)
BOM_RE = re.compile('^\ufeff', re.U)
UNSAFE_RE = re.compile('\x00',... |
pudo/normality | normality/cleaning.py | compose_nfc | python | def compose_nfc(text):
if text is None:
return None
if not hasattr(compose_nfc, '_tr'):
compose_nfc._tr = Transliterator.createInstance('Any-NFC')
return compose_nfc._tr.transliterate(text) | Perform unicode composition. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/cleaning.py#L31-L37 | null | # coding: utf-8
from __future__ import unicode_literals
import re
import six
from icu import Transliterator
from unicodedata import category
from normality.constants import UNICODE_CATEGORIES, CONTROL_CODES, WS
COLLAPSE_RE = re.compile(r'\s+', re.U)
BOM_RE = re.compile('^\ufeff', re.U)
UNSAFE_RE = re.compile('\x00',... |
pudo/normality | normality/cleaning.py | category_replace | python | def category_replace(text, replacements=UNICODE_CATEGORIES):
if text is None:
return None
characters = []
for character in decompose_nfkd(text):
cat = category(character)
replacement = replacements.get(cat, character)
if replacement is not None:
characters.append(... | Remove characters from a string based on unicode classes.
This is a method for removing non-text characters (such as punctuation,
whitespace, marks and diacritics) from a piece of text by class, rather
than specifying them individually. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/cleaning.py#L47-L62 | [
"def decompose_nfkd(text):\n \"\"\"Perform unicode compatibility decomposition.\n\n This will replace some non-standard value representations in unicode and\n normalise them, while also separating characters and their diacritics into\n two separate codepoints.\n \"\"\"\n if text is None:\n ... | # coding: utf-8
from __future__ import unicode_literals
import re
import six
from icu import Transliterator
from unicodedata import category
from normality.constants import UNICODE_CATEGORIES, CONTROL_CODES, WS
COLLAPSE_RE = re.compile(r'\s+', re.U)
BOM_RE = re.compile('^\ufeff', re.U)
UNSAFE_RE = re.compile('\x00',... |
pudo/normality | normality/cleaning.py | remove_unsafe_chars | python | def remove_unsafe_chars(text):
if isinstance(text, six.string_types):
text = UNSAFE_RE.sub('', text)
return text | Remove unsafe unicode characters from a piece of text. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/cleaning.py#L70-L74 | null | # coding: utf-8
from __future__ import unicode_literals
import re
import six
from icu import Transliterator
from unicodedata import category
from normality.constants import UNICODE_CATEGORIES, CONTROL_CODES, WS
COLLAPSE_RE = re.compile(r'\s+', re.U)
BOM_RE = re.compile('^\ufeff', re.U)
UNSAFE_RE = re.compile('\x00',... |
pudo/normality | normality/cleaning.py | collapse_spaces | python | def collapse_spaces(text):
if not isinstance(text, six.string_types):
return text
return COLLAPSE_RE.sub(WS, text).strip(WS) | Remove newlines, tabs and multiple spaces with single spaces. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/cleaning.py#L82-L86 | null | # coding: utf-8
from __future__ import unicode_literals
import re
import six
from icu import Transliterator
from unicodedata import category
from normality.constants import UNICODE_CATEGORIES, CONTROL_CODES, WS
COLLAPSE_RE = re.compile(r'\s+', re.U)
BOM_RE = re.compile('^\ufeff', re.U)
UNSAFE_RE = re.compile('\x00',... |
pudo/normality | normality/__init__.py | normalize | python | def normalize(text, lowercase=True, collapse=True, latinize=False, ascii=False,
encoding_default='utf-8', encoding=None,
replace_categories=UNICODE_CATEGORIES):
text = stringify(text, encoding_default=encoding_default,
encoding=encoding)
if text is None:
... | The main normalization function for text.
This will take a string and apply a set of transformations to it so
that it can be processed more easily afterwards. Arguments:
* ``lowercase``: not very mysterious.
* ``collapse``: replace multiple whitespace-like characters with a
single whitespace. Th... | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/__init__.py#L9-L57 | [
"def collapse_spaces(text):\n \"\"\"Remove newlines, tabs and multiple spaces with single spaces.\"\"\"\n if not isinstance(text, six.string_types):\n return text\n return COLLAPSE_RE.sub(WS, text).strip(WS)\n",
"def category_replace(text, replacements=UNICODE_CATEGORIES):\n \"\"\"Remove charac... | from normality.cleaning import collapse_spaces, category_replace
from normality.constants import UNICODE_CATEGORIES, WS
from normality.transliteration import latinize_text, ascii_text
from normality.encoding import guess_encoding, guess_file_encoding # noqa
from normality.stringify import stringify # noqa
from normal... |
pudo/normality | normality/__init__.py | slugify | python | def slugify(text, sep='-'):
text = stringify(text)
if text is None:
return None
text = text.replace(sep, WS)
text = normalize(text, ascii=True)
if text is None:
return None
return text.replace(WS, sep) | A simple slug generator. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/__init__.py#L60-L69 | [
"def normalize(text, lowercase=True, collapse=True, latinize=False, ascii=False,\n encoding_default='utf-8', encoding=None,\n replace_categories=UNICODE_CATEGORIES):\n \"\"\"The main normalization function for text.\n\n This will take a string and apply a set of transformations to it... | from normality.cleaning import collapse_spaces, category_replace
from normality.constants import UNICODE_CATEGORIES, WS
from normality.transliteration import latinize_text, ascii_text
from normality.encoding import guess_encoding, guess_file_encoding # noqa
from normality.stringify import stringify # noqa
from normal... |
pudo/normality | normality/transliteration.py | latinize_text | python | def latinize_text(text, ascii=False):
if text is None or not isinstance(text, six.string_types) or not len(text):
return text
if ascii:
if not hasattr(latinize_text, '_ascii'):
# Transform to latin, separate accents, decompose, remove
# symbols, compose, push to ASCII
... | Transliterate the given text to the latin script.
This attempts to convert a given text to latin script using the
closest match of characters vis a vis the original script. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/transliteration.py#L18-L36 | null | # coding: utf-8
"""
Transliterate the given text to the latin script.
This attempts to convert a given text to latin script using the
closest match of characters vis a vis the original script.
Transliteration requires an extensive unicode mapping. Since all
Python implementations are either GPL-licensed (and thus mor... |
pudo/normality | normality/transliteration.py | ascii_text | python | def ascii_text(text):
text = latinize_text(text, ascii=True)
if isinstance(text, six.text_type):
text = text.encode('ascii', 'ignore').decode('ascii')
return text | Transliterate the given text and make sure it ends up as ASCII. | train | https://github.com/pudo/normality/blob/b53cc2c6e5c6205573d2010f72d90808710a4b58/normality/transliteration.py#L39-L44 | [
"def latinize_text(text, ascii=False):\n \"\"\"Transliterate the given text to the latin script.\n\n This attempts to convert a given text to latin script using the\n closest match of characters vis a vis the original script.\n \"\"\"\n if text is None or not isinstance(text, six.string_types) or not... | # coding: utf-8
"""
Transliterate the given text to the latin script.
This attempts to convert a given text to latin script using the
closest match of characters vis a vis the original script.
Transliteration requires an extensive unicode mapping. Since all
Python implementations are either GPL-licensed (and thus mor... |
UDST/osmnet | osmnet/config.py | format_check | python | def format_check(settings):
valid_keys = ['logs_folder', 'log_file', 'log_console', 'log_name',
'log_filename', 'keep_osm_tags']
for key in list(settings.keys()):
assert key in valid_keys, \
('{} not found in list of valid configuation keys').format(key)
assert is... | Check the format of a osmnet_config object.
Parameters
----------
settings : dict
osmnet_config as a dictionary
Returns
-------
Nothing | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/config.py#L2-L30 | null |
class osmnet_config(object):
"""
A set of configuration variables to initiate the configuration settings
for osmnet.
Parameters
----------
logs_folder : str
location to write log files
log_file : bool
if true, save log output to a log file in logs_folder
log_console ... |
UDST/osmnet | osmnet/config.py | osmnet_config.to_dict | python | def to_dict(self):
return {'logs_folder': self.logs_folder,
'log_file': self.log_file,
'log_console': self.log_console,
'log_name': self.log_name,
'log_filename': self.log_filename,
'keep_osm_tags': self.keep_osm_tags
... | Return a dict representation of an osmnet osmnet_config instance. | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/config.py#L73-L83 | null | class osmnet_config(object):
"""
A set of configuration variables to initiate the configuration settings
for osmnet.
Parameters
----------
logs_folder : str
location to write log files
log_file : bool
if true, save log output to a log file in logs_folder
log_console : bo... |
UDST/osmnet | osmnet/utils.py | great_circle_dist | python | def great_circle_dist(lat1, lon1, lat2, lon2):
radius = 6372795 # meters
lat1 = math.radians(lat1)
lon1 = math.radians(lon1)
lat2 = math.radians(lat2)
lon2 = math.radians(lon2)
dlat = lat2 - lat1
dlon = lon2 - lon1
# formula from:
# http://en.wikipedia.org/wiki/Haversine_formula#... | Get the distance (in meters) between two lat/lon points
via the Haversine formula.
Parameters
----------
lat1, lon1, lat2, lon2 : float
Latitude and longitude in degrees.
Returns
-------
dist : float
Distance in meters. | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/utils.py#L17-L49 | null | # The following logging functions were modified from the osmnx library and
# used with permission from the author Geoff Boeing:
# log, get_logger: https://github.com/gboeing/osmnx/blob/master/osmnx/utils.py
from __future__ import division
import math
import logging as lg
import unicodedata
import sys
import datetime ... |
UDST/osmnet | osmnet/load.py | osm_filter | python | def osm_filter(network_type):
filters = {}
# drive: select only roads that are drivable by normal 2 wheel drive
# passenger vehicles both private and public
# roads. Filter out un-drivable roads and service roads tagged as parking,
# driveway, or emergency-access
filters['drive'] = ('["highway"... | Create a filter to query Overpass API for the specified OSM network type.
Parameters
----------
network_type : string, {'walk', 'drive'} denoting the type of street
network to extract
Returns
-------
osm_filter : string | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L29-L67 | null | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | osm_net_download | python | def osm_net_download(lat_min=None, lng_min=None, lat_max=None, lng_max=None,
network_type='walk', timeout=180, memory=None,
max_query_area_size=50*1000*50*1000,
custom_osm_filter=None):
# create a filter to exclude certain kinds of ways based on the re... | Download OSM ways and nodes within a bounding box from the Overpass API.
Parameters
----------
lat_min : float
southern latitude of bounding box
lng_min : float
eastern longitude of bounding box
lat_max : float
northern latitude of bounding box
lng_max : float
we... | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L70-L200 | [
"def log(message, level=None, name=None, filename=None):\n \"\"\"\n Write a message to the log file and/or print to the console.\n\n Parameters\n ----------\n message : string\n the content of the message to log\n level : int\n one of the logger.level constants\n name : string\n ... | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | overpass_request | python | def overpass_request(data, pause_duration=None, timeout=180,
error_pause_duration=None):
# define the Overpass API URL, then construct a GET-style URL
url = 'http://www.overpass-api.de/api/interpreter'
start_time = time.time()
log('Posting to {} with timeout={}, "{}"'.format(url, ... | Send a request to the Overpass API via HTTP POST and return the
JSON response
Parameters
----------
data : dict or OrderedDict
key-value pairs of parameters to post to Overpass API
pause_duration : int
how long to pause in seconds before requests, if None, will query
Overpas... | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L203-L270 | [
"def log(message, level=None, name=None, filename=None):\n \"\"\"\n Write a message to the log file and/or print to the console.\n\n Parameters\n ----------\n message : string\n the content of the message to log\n level : int\n one of the logger.level constants\n name : string\n ... | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | get_pause_duration | python | def get_pause_duration(recursive_delay=5, default_duration=10):
try:
response = requests.get('http://overpass-api.de/api/status')
status = response.text.split('\n')[3]
status_first_token = status.split(' ')[0]
except Exception:
# if status endpoint cannot be reached or output par... | Check the Overpass API status endpoint to determine how long to wait until
next slot is available.
Parameters
----------
recursive_delay : int
how long to wait between recursive calls if server is currently
running a query
default_duration : int
if fatal error, function fall... | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L273-L328 | [
"def log(message, level=None, name=None, filename=None):\n \"\"\"\n Write a message to the log file and/or print to the console.\n\n Parameters\n ----------\n message : string\n the content of the message to log\n level : int\n one of the logger.level constants\n name : string\n ... | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | consolidate_subdivide_geometry | python | def consolidate_subdivide_geometry(geometry, max_query_area_size):
# let the linear length of the quadrats (with which to subdivide the
# geometry) be the square root of max area size
quadrat_width = math.sqrt(max_query_area_size)
if not isinstance(geometry, (Polygon, MultiPolygon)):
raise Val... | Consolidate a geometry into a convex hull, then subdivide it into
smaller sub-polygons if its area exceeds max size (in geometry's units).
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to consolidate and subdivide
max_query_area_size : float
max area ... | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L331-L373 | null | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | quadrat_cut_geometry | python | def quadrat_cut_geometry(geometry, quadrat_width, min_num=3,
buffer_amount=1e-9):
# create n evenly spaced points between the min and max x and y bounds
lng_max, lat_min, lng_min, lat_max = geometry.bounds
x_num = math.ceil((lng_min-lng_max) / quadrat_width) + 1
y_num = math.ce... | Split a Polygon or MultiPolygon up into sub-polygons of a specified size,
using quadrats.
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to split up into smaller sub-polygons
quadrat_width : float
the linear width of the quadrats with which to cut up t... | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L376-L421 | null | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | project_geometry | python | def project_geometry(geometry, crs, to_latlong=False):
gdf = gpd.GeoDataFrame()
gdf.crs = crs
gdf.name = 'geometry to project'
gdf['geometry'] = None
gdf.loc[0, 'geometry'] = geometry
gdf_proj = project_gdf(gdf, to_latlong=to_latlong)
geometry_proj = gdf_proj['geometry'].iloc[0]
return g... | Project a shapely Polygon or MultiPolygon from WGS84 to UTM, or vice-versa
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to project
crs : int
the starting coordinate reference system of the passed-in geometry
to_latlong : bool
if True, project... | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L424-L450 | [
"def project_gdf(gdf, to_latlong=False, verbose=False):\n \"\"\"\n Project a GeoDataFrame to the UTM zone appropriate for its geometries'\n centroid. The calculation works well for most latitudes,\n however it will not work well for some far northern locations.\n\n Parameters\n ----------\n gdf... | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | process_node | python | def process_node(e):
node = {'id': e['id'],
'lat': e['lat'],
'lon': e['lon']}
if 'tags' in e:
if e['tags'] is not np.nan:
for t, v in list(e['tags'].items()):
if t in config.settings.keep_osm_tags:
node[t] = v
return node | Process a node element entry into a dict suitable for going into a
Pandas DataFrame.
Parameters
----------
e : dict
individual node element in downloaded OSM json
Returns
-------
node : dict | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L514-L539 | null | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | process_way | python | def process_way(e):
way = {'id': e['id']}
if 'tags' in e:
if e['tags'] is not np.nan:
for t, v in list(e['tags'].items()):
if t in config.settings.keep_osm_tags:
way[t] = v
# nodes that make up a way
waynodes = []
for n in e['nodes']:
... | Process a way element entry into a list of dicts suitable for going into
a Pandas DataFrame.
Parameters
----------
e : dict
individual way element in downloaded OSM json
Returns
-------
way : dict
waynodes : list of dict | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L542-L572 | null | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | parse_network_osm_query | python | def parse_network_osm_query(data):
if len(data['elements']) == 0:
raise RuntimeError('OSM query results contain no data.')
nodes = []
ways = []
waynodes = []
for e in data['elements']:
if e['type'] == 'node':
nodes.append(process_node(e))
elif e['type'] == 'way'... | Convert OSM query data to DataFrames of ways and way-nodes.
Parameters
----------
data : dict
Result of an OSM query.
Returns
-------
nodes, ways, waynodes : pandas.DataFrame | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L575-L608 | [
"def process_node(e):\n \"\"\"\n Process a node element entry into a dict suitable for going into a\n Pandas DataFrame.\n\n Parameters\n ----------\n e : dict\n individual node element in downloaded OSM json\n\n Returns\n -------\n node : dict\n\n \"\"\"\n node = {'id': e['id... | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | ways_in_bbox | python | def ways_in_bbox(lat_min, lng_min, lat_max, lng_max, network_type,
timeout=180, memory=None,
max_query_area_size=50*1000*50*1000,
custom_osm_filter=None):
return parse_network_osm_query(
osm_net_download(lat_max=lat_max, lat_min=lat_min, lng_min=lng_min,
... | Get DataFrames of OSM data in a bounding box.
Parameters
----------
lat_min : float
southern latitude of bounding box
lng_min : float
eastern longitude of bounding box
lat_max : float
northern latitude of bounding box
lng_max : float
western longitude of bounding... | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L611-L658 | [
"def osm_net_download(lat_min=None, lng_min=None, lat_max=None, lng_max=None,\n network_type='walk', timeout=180, memory=None,\n max_query_area_size=50*1000*50*1000,\n custom_osm_filter=None):\n \"\"\"\n Download OSM ways and nodes within a bounding ... | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | intersection_nodes | python | def intersection_nodes(waynodes):
counts = waynodes.node_id.value_counts()
return set(counts[counts > 1].index.values) | Returns a set of all the nodes that appear in 2 or more ways.
Parameters
----------
waynodes : pandas.DataFrame
Mapping of way IDs to node IDs as returned by `ways_in_bbox`.
Returns
-------
intersections : set
Node IDs that appear in 2 or more ways. | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L661-L677 | null | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | node_pairs | python | def node_pairs(nodes, ways, waynodes, two_way=True):
start_time = time.time()
def pairwise(l):
return zip(islice(l, 0, len(l)), islice(l, 1, None))
intersections = intersection_nodes(waynodes)
waymap = waynodes.groupby(level=0, sort=False)
pairs = []
for id, row in ways.iterrows():
... | Create a table of node pairs with the distances between them.
Parameters
----------
nodes : pandas.DataFrame
Must have 'lat' and 'lon' columns.
ways : pandas.DataFrame
Table of way metadata.
waynodes : pandas.DataFrame
Table linking way IDs to node IDs. Way IDs should be in ... | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L680-L764 | [
"def log(message, level=None, name=None, filename=None):\n \"\"\"\n Write a message to the log file and/or print to the console.\n\n Parameters\n ----------\n message : string\n the content of the message to log\n level : int\n one of the logger.level constants\n name : string\n ... | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
UDST/osmnet | osmnet/load.py | network_from_bbox | python | def network_from_bbox(lat_min=None, lng_min=None, lat_max=None, lng_max=None,
bbox=None, network_type='walk', two_way=True,
timeout=180, memory=None,
max_query_area_size=50*1000*50*1000,
custom_osm_filter=None):
start_time = ti... | Make a graph network from a bounding lat/lon box composed of nodes and
edges for use in Pandana street network accessibility calculations.
You may either enter a lat/long box via the four lat_min,
lng_min, lat_max, lng_max parameters or the bbox parameter as a tuple.
Parameters
----------
lat_m... | train | https://github.com/UDST/osmnet/blob/155110a8e38d3646b9dbc3ec729063930cab3d5f/osmnet/load.py#L767-L873 | [
"def log(message, level=None, name=None, filename=None):\n \"\"\"\n Write a message to the log file and/or print to the console.\n\n Parameters\n ----------\n message : string\n the content of the message to log\n level : int\n one of the logger.level constants\n name : string\n ... | # The following functions to download osm data, setup a recursive api request
# and subdivide bbox queries into smaller bboxes were modified from the
# osmnx library and used with permission from the author Geoff Boeing
# osm_net_download, overpass_request, get_pause_duration,
# consolidate_subdivide_geometry, quadrat_... |
fictorial/pygameui | pygameui/kvc.py | value_for_keypath | python | def value_for_keypath(obj, path):
val = obj
for part in path.split('.'):
match = re.match(list_index_re, part)
if match is not None:
val = _extract(val, match.group(1))
if not isinstance(val, list) and not isinstance(val, tuple):
raise TypeError('expected ... | Get value from walking key path with start object obj. | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/kvc.py#L58-L74 | [
"def _extract(val, key):\n if isinstance(val, dict):\n return val[key]\n return getattr(val, key, None)\n"
] | """This module lets you set/get attribute values by walking
a "key path" from a root or start object.
A key path is a string with path part specs delimited by period '.'.
Multiple path part specs are concatenated together to form the
entire path spec.
Each path part spec takes one of two forms:
- identifier
- identi... |
fictorial/pygameui | pygameui/kvc.py | set_value_for_keypath | python | def set_value_for_keypath(obj, path, new_value, preserve_child = False):
parts = path.split('.')
last_part = len(parts) - 1
dst = obj
for i, part in enumerate(parts):
match = re.match(list_index_re, part)
if match is not None:
dst = _extract(dst, match.group(1))
i... | Set attribute value new_value at key path of start object obj. | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/kvc.py#L77-L107 | [
"def _extract(val, key):\n if isinstance(val, dict):\n return val[key]\n return getattr(val, key, None)\n"
] | """This module lets you set/get attribute values by walking
a "key path" from a root or start object.
A key path is a string with path part specs delimited by period '.'.
Multiple path part specs are concatenated together to form the
entire path spec.
Each path part spec takes one of two forms:
- identifier
- identi... |
fictorial/pygameui | pygameui/imageview.py | view_for_image_named | python | def view_for_image_named(image_name):
image = resource.get_image(image_name)
if not image:
return None
return ImageView(pygame.Rect(0, 0, 0, 0), image) | Create an ImageView for the given image. | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/imageview.py#L64-L72 | [
"def get_image(name):\n try:\n img = image_cache[name]\n except KeyError:\n path = 'resources/images/%s.png' % name\n path = pkg_resources.resource_filename(package_name, path)\n try:\n logger.debug('loading image %s' % path)\n img = pygame.image.load(path)\n ... | import pygame
import view
import resource
SCALE_TO_FILL = 0
class ImageView(view.View):
"""A view for displaying an image.
The only 'content scaling mode' currently supported is 'scale-to-fill'.
"""
def __init__(self, frame, img, content_mode=SCALE_TO_FILL):
"""Create an image view from ... |
fictorial/pygameui | distribute_setup.py | main | python | def main(argv, version=DEFAULT_VERSION):
tarball = download_setuptools()
_install(tarball, _build_install_args(argv)) | Install or upgrade setuptools and EasyInstall | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/distribute_setup.py#L487-L490 | [
"def _install(tarball, install_args=()):\n # extracting the tarball\n tmpdir = tempfile.mkdtemp()\n log.warn('Extracting in %s', tmpdir)\n old_wd = os.getcwd()\n try:\n os.chdir(tmpdir)\n tar = tarfile.open(tarball)\n _extractall(tar)\n tar.close()\n\n # going in th... | #!python
"""Bootstrap distribute installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from distribute_setup import use_setuptools
use_setuptools()
If you want to require a specific version of se... |
fictorial/pygameui | pygameui/render.py | fill_gradient | python | def fill_gradient(surface, color, gradient,
rect=None, vertical=True, forward=True):
if rect is None:
rect = surface.get_rect()
x1, x2 = rect.left, rect.right
y1, y2 = rect.top, rect.bottom
if vertical:
h = y2 - y1
else:
h = x2 - x1
assert h > 0
... | Fill a surface with a linear gradient pattern.
color
starting color
gradient
final color
rect
area to fill; default is surface's rect
vertical
True=vertical; False=horizontal
forward
True=forward; False=reverse
See http://www.pygame.org/wiki/Gra... | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/render.py#L4-L66 | null | import pygame
def fillrect(surface, color, rect, vertical=True):
if len(color) == 2: # gradient
fill_gradient(surface, color[0], color[1],
rect=rect, vertical=vertical)
else:
surface.fill(color, rect)
|
fictorial/pygameui | pygameui/label.py | Label.shrink_wrap | python | def shrink_wrap(self):
self.frame.size = (self.text_size[0] + self.padding[0] * 2,
self.text_size[1] + self.padding[1] * 2) | Tightly bound the current text respecting current padding. | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/label.py#L187-L191 | null | class Label(view.View):
"""Multi-line, word-wrappable, uneditable text view.
Attributes:
halign
CENTER, LEFT, or RIGHT. Horizontal alignment of
text.
valign
CENTER, TOP, or BOTTOM. Vertical alignment of text.
wrap_mode
WORD_WRAP or ... |
fictorial/pygameui | pygameui/view.py | View.layout | python | def layout(self):
if self.shadowed:
shadow_size = theme.current.shadow_size
shadowed_frame_size = (self.frame.w + shadow_size,
self.frame.h + shadow_size)
self.surface = pygame.Surface(
shadowed_frame_size, pygame.SRCALPHA, 3... | Call to have the view layout itself.
Subclasses should invoke this after laying out child
views and/or updating its own frame. | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L74-L91 | [
"def scale_image(image, size):\n return pygame.transform.smoothscale(image, size)\n",
"def get_image(name):\n try:\n img = image_cache[name]\n except KeyError:\n path = 'resources/images/%s.png' % name\n path = pkg_resources.resource_filename(package_name, path)\n try:\n ... | class View(object):
"""A rectangular portion of the window.
Views may have zero or more child views contained within it.
Signals
on_mouse_down(view, button, point)
on_mouse_up(view, button, point)
on_mouse_motion(view, point)
on_mouse_drag(view, point, delta)
on_k... |
fictorial/pygameui | pygameui/view.py | View.stylize | python | def stylize(self):
# do children first in case parent needs to override their style
for child in self.children:
child.stylize()
style = theme.current.get_dict(self)
preserve_child = False
try:
preserve_child = getattr(theme.current, 'preserve_child')
... | Apply theme style attributes to this instance and its children.
This also causes a relayout to occur so that any changes in padding
or other stylistic attributes may be handled. | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L209-L227 | [
"def set_value_for_keypath(obj, path, new_value, preserve_child = False):\n \"\"\"Set attribute value new_value at key path of start object obj.\n \"\"\"\n parts = path.split('.')\n last_part = len(parts) - 1\n dst = obj\n for i, part in enumerate(parts):\n match = re.match(list_index_re, p... | class View(object):
"""A rectangular portion of the window.
Views may have zero or more child views contained within it.
Signals
on_mouse_down(view, button, point)
on_mouse_up(view, button, point)
on_mouse_motion(view, point)
on_mouse_drag(view, point, delta)
on_k... |
fictorial/pygameui | pygameui/view.py | View.draw | python | def draw(self):
if self.hidden:
return False
if self.background_color is not None:
render.fillrect(self.surface, self.background_color,
rect=pygame.Rect((0, 0), self.frame.size))
for child in self.children:
if not child.hidden:
... | Do not call directly. | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L229-L278 | [
"def fillrect(surface, color, rect, vertical=True):\n if len(color) == 2: # gradient\n fill_gradient(surface, color[0], color[1],\n rect=rect, vertical=vertical)\n else:\n surface.fill(color, rect)\n"
] | class View(object):
"""A rectangular portion of the window.
Views may have zero or more child views contained within it.
Signals
on_mouse_down(view, button, point)
on_mouse_up(view, button, point)
on_mouse_motion(view, point)
on_mouse_drag(view, point, delta)
on_k... |
fictorial/pygameui | pygameui/view.py | View.get_border_widths | python | def get_border_widths(self):
if type(self.border_widths) is int: # uniform size
return [self.border_widths] * 4
return self.border_widths | Return border width for each side top, left, bottom, right. | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L280-L284 | null | class View(object):
"""A rectangular portion of the window.
Views may have zero or more child views contained within it.
Signals
on_mouse_down(view, button, point)
on_mouse_up(view, button, point)
on_mouse_motion(view, point)
on_mouse_drag(view, point, delta)
on_k... |
fictorial/pygameui | pygameui/view.py | View.hit | python | def hit(self, pt):
if self.hidden or not self._enabled:
return None
if not self.frame.collidepoint(pt):
return None
local_pt = (pt[0] - self.frame.topleft[0],
pt[1] - self.frame.topleft[1])
for child in reversed(self.children): # front to... | Find the view (self, child, or None) under the point `pt`. | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L286-L303 | null | class View(object):
"""A rectangular portion of the window.
Views may have zero or more child views contained within it.
Signals
on_mouse_down(view, button, point)
on_mouse_up(view, button, point)
on_mouse_motion(view, point)
on_mouse_drag(view, point, delta)
on_k... |
fictorial/pygameui | pygameui/view.py | View.bring_to_front | python | def bring_to_front(self):
if self.parent is not None:
ch = self.parent.children
index = ch.index(self)
ch[-1], ch[index] = ch[index], ch[-1] | TODO: explain depth sorting | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/view.py#L347-L352 | null | class View(object):
"""A rectangular portion of the window.
Views may have zero or more child views contained within it.
Signals
on_mouse_down(view, button, point)
on_mouse_up(view, button, point)
on_mouse_motion(view, point)
on_mouse_drag(view, point, delta)
on_k... |
fictorial/pygameui | pygameui/theme.py | use_theme | python | def use_theme(theme):
global current
current = theme
import scene
if scene.current is not None:
scene.current.stylize() | Make the given theme current.
There are two included themes: light_theme, dark_theme. | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/theme.py#L176-L185 | null | from itertools import chain
import resource
from colors import *
class Theme(object):
"""A theme is a hierarchical set of view style attributes.
Each view may have a set of attributes that control its
visual style when rendered. These style attributes are stored
in a Theme.
Style attributes ar... |
fictorial/pygameui | pygameui/theme.py | Theme.set | python | def set(self, class_name, state, key, value):
self._styles.setdefault(class_name, {}).setdefault(state, {})
self._styles[class_name][state][key] = value | Set a single style value for a view class and state.
class_name
The name of the class to be styled; do not
include the package name; e.g. 'Button'.
state
The name of the state to be stylized. One of the
following: 'normal', 'focused', 'selected', 'disa... | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/theme.py#L71-L97 | null | class Theme(object):
"""A theme is a hierarchical set of view style attributes.
Each view may have a set of attributes that control its
visual style when rendered. These style attributes are stored
in a Theme.
Style attributes are hierarchical in that a view class
may override the style attri... |
fictorial/pygameui | pygameui/theme.py | Theme.get_dict_for_class | python | def get_dict_for_class(self, class_name, state=None, base_name='View'):
classes = []
klass = class_name
while True:
classes.append(klass)
if klass.__name__ == base_name:
break
klass = klass.__bases__[0]
if state is None:
s... | The style dict for a given class and state.
This collects the style attributes from parent classes
and the class of the given object and gives precedence
to values thereof to the children.
The state attribute of the view instance is taken as
the current state if state is None.
... | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/theme.py#L99-L149 | null | class Theme(object):
"""A theme is a hierarchical set of view style attributes.
Each view may have a set of attributes that control its
visual style when rendered. These style attributes are stored
in a Theme.
Style attributes are hierarchical in that a view class
may override the style attri... |
fictorial/pygameui | pygameui/theme.py | Theme.get_dict | python | def get_dict(self, obj, state=None, base_name='View'):
return self.get_dict_for_class(class_name=obj.__class__,
state=obj.state,
base_name=base_name) | The style dict for a view instance. | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/theme.py#L151-L157 | [
"def get_dict_for_class(self, class_name, state=None, base_name='View'):\n \"\"\"The style dict for a given class and state.\n\n This collects the style attributes from parent classes\n and the class of the given object and gives precedence\n to values thereof to the children.\n\n The state attribute... | class Theme(object):
"""A theme is a hierarchical set of view style attributes.
Each view may have a set of attributes that control its
visual style when rendered. These style attributes are stored
in a Theme.
Style attributes are hierarchical in that a view class
may override the style attri... |
fictorial/pygameui | pygameui/theme.py | Theme.get_value | python | def get_value(self, class_name, attr, default_value=None,
state='normal', base_name='View'):
styles = self.get_dict_for_class(class_name, state, base_name)
try:
return styles[attr]
except KeyError:
return default_value | Get a single style attribute value for the given class. | train | https://github.com/fictorial/pygameui/blob/af6a35f347d6fafa66c4255bbbe38736d842ff65/pygameui/theme.py#L159-L168 | [
"def get_dict_for_class(self, class_name, state=None, base_name='View'):\n \"\"\"The style dict for a given class and state.\n\n This collects the style attributes from parent classes\n and the class of the given object and gives precedence\n to values thereof to the children.\n\n The state attribute... | class Theme(object):
"""A theme is a hierarchical set of view style attributes.
Each view may have a set of attributes that control its
visual style when rendered. These style attributes are stored
in a Theme.
Style attributes are hierarchical in that a view class
may override the style attri... |
brianhie/scanorama | bin/unsupervised.py | silhouette_score | python | def silhouette_score(X, labels, metric='euclidean', sample_size=None,
random_state=None, **kwds):
if sample_size is not None:
X, labels = check_X_y(X, labels, accept_sparse=['csc', 'csr'])
random_state = check_random_state(random_state)
indices = random_state.permutation... | Compute the mean Silhouette Coefficient of all samples.
The Silhouette Coefficient is calculated using the mean intra-cluster
distance (``a``) and the mean nearest-cluster distance (``b``) for each
sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a,
b)``. To clarify, ``b`` is the di... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/bin/unsupervised.py#L27-L106 | [
"def silhouette_samples(X, labels, metric='euclidean', **kwds):\n \"\"\"Compute the Silhouette Coefficient for each sample.\n\n The Silhouette Coefficient is a measure of how well samples are clustered\n with samples that are similar to themselves. Clustering models with a high\n Silhouette Coefficient ... | """Unsupervised evaluation metrics."""
# Modified by Brian Hie <brianhie@mit.edu> to allow for multicore
# pairwise distance matrix computation.
# Original source code available at:
# https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/metrics/cluster/unsupervised.py
# Authors: Robert Layton <robertlay... |
brianhie/scanorama | bin/unsupervised.py | silhouette_samples | python | def silhouette_samples(X, labels, metric='euclidean', **kwds):
X, labels = check_X_y(X, labels, accept_sparse=['csc', 'csr'])
le = LabelEncoder()
labels = le.fit_transform(labels)
check_number_of_labels(len(le.classes_), X.shape[0])
distances = pairwise_distances(X, metric=metric, **kwds)
uniqu... | Compute the Silhouette Coefficient for each sample.
The Silhouette Coefficient is a measure of how well samples are clustered
with samples that are similar to themselves. Clustering models with a high
Silhouette Coefficient are said to be dense, where samples in the same
cluster are similar to each oth... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/bin/unsupervised.py#L109-L213 | [
"def check_number_of_labels(n_labels, n_samples):\n if not 1 < n_labels < n_samples:\n raise ValueError(\"Number of labels is %d. Valid values are 2 \"\n \"to n_samples - 1 (inclusive)\" % n_labels)\n"
] | """Unsupervised evaluation metrics."""
# Modified by Brian Hie <brianhie@mit.edu> to allow for multicore
# pairwise distance matrix computation.
# Original source code available at:
# https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/metrics/cluster/unsupervised.py
# Authors: Robert Layton <robertlay... |
brianhie/scanorama | bin/unsupervised.py | calinski_harabaz_score | python | def calinski_harabaz_score(X, labels):
X, labels = check_X_y(X, labels)
le = LabelEncoder()
labels = le.fit_transform(labels)
n_samples, _ = X.shape
n_labels = len(le.classes_)
check_number_of_labels(n_labels, n_samples)
extra_disp, intra_disp = 0., 0.
mean = np.mean(X, axis=0)
fo... | Compute the Calinski and Harabaz score.
The score is defined as ratio between the within-cluster dispersion and
the between-cluster dispersion.
Read more in the :ref:`User Guide <calinski_harabaz_index>`.
Parameters
----------
X : array-like, shape (``n_samples``, ``n_features``)
List... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/bin/unsupervised.py#L216-L263 | [
"def check_number_of_labels(n_labels, n_samples):\n if not 1 < n_labels < n_samples:\n raise ValueError(\"Number of labels is %d. Valid values are 2 \"\n \"to n_samples - 1 (inclusive)\" % n_labels)\n"
] | """Unsupervised evaluation metrics."""
# Modified by Brian Hie <brianhie@mit.edu> to allow for multicore
# pairwise distance matrix computation.
# Original source code available at:
# https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/metrics/cluster/unsupervised.py
# Authors: Robert Layton <robertlay... |
brianhie/scanorama | scanorama/utils.py | handle_zeros_in_scale | python | def handle_zeros_in_scale(scale, copy=True):
''' Makes sure that whenever scale is zero, we handle it correctly.
This happens in most scalers when we have constant features.
Adapted from sklearn.preprocessing.data'''
# if we are fitting on 1D arrays, scale might be a scalar
if np.isscalar(scale):
... | Makes sure that whenever scale is zero, we handle it correctly.
This happens in most scalers when we have constant features.
Adapted from sklearn.preprocessing.data | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/utils.py#L124-L139 | null | import errno
from fbpca import pca
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = [10.0, 9.0]
mpl.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import os
import sys
np.random.seed(0)
def dispersion(X):
mean = X.mean(0)
dispersion = np.zeros(mean.shape)
... |
brianhie/scanorama | scanorama/t_sne_approx.py | _joint_probabilities | python | def _joint_probabilities(distances, desired_perplexity, verbose):
# Compute conditional probabilities such that they approximately match
# the desired perplexity
distances = distances.astype(np.float32, copy=False)
conditional_P = _utils._binary_search_perplexity(
distances, None, desired_perple... | Compute joint probabilities p_ij from distances.
Parameters
----------
distances : array, shape (n_samples * (n_samples-1) / 2,)
Distances of samples are stored as condensed matrices, i.e.
we omit the diagonal and duplicate entries and store everything
in a one-dimensional array.
... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L39-L68 | null | # Modified by Brian Hie <brianhie@mit.edu> to use an approximate nearest
# neighbors search.
# Original source code available at:
# https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/manifold/t_sne.py
# Author: Alexander Fabisch -- <afabisch@informatik.uni-bremen.de>
# Author: Christopher Moody <chris... |
brianhie/scanorama | scanorama/t_sne_approx.py | _joint_probabilities_nn | python | def _joint_probabilities_nn(distances, neighbors, desired_perplexity, verbose):
t0 = time()
# Compute conditional probabilities such that they approximately match
# the desired perplexity
n_samples, k = neighbors.shape
distances = distances.astype(np.float32, copy=False)
neighbors = neighbors.as... | Compute joint probabilities p_ij from distances using just nearest
neighbors.
This method is approximately equal to _joint_probabilities. The latter
is O(N), but limiting the joint probability to nearest neighbors improves
this substantially to O(uN).
Parameters
----------
distances : arra... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L71-L124 | null | # Modified by Brian Hie <brianhie@mit.edu> to use an approximate nearest
# neighbors search.
# Original source code available at:
# https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/manifold/t_sne.py
# Author: Alexander Fabisch -- <afabisch@informatik.uni-bremen.de>
# Author: Christopher Moody <chris... |
brianhie/scanorama | scanorama/t_sne_approx.py | _kl_divergence | python | def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components,
skip_num_points=0):
X_embedded = params.reshape(n_samples, n_components)
# Q is a heavy-tailed distribution: Student's t-distribution
dist = pdist(X_embedded, "sqeuclidean")
dist += 1.
dist /= degrees_of_f... | t-SNE objective function: gradient of the KL divergence
of p_ijs and q_ijs and the absolute error.
Parameters
----------
params : array, shape (n_params,)
Unraveled embedding.
P : array, shape (n_samples * (n_samples-1) / 2,)
Condensed joint probability matrix.
degrees_of_free... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L127-L189 | null | # Modified by Brian Hie <brianhie@mit.edu> to use an approximate nearest
# neighbors search.
# Original source code available at:
# https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/manifold/t_sne.py
# Author: Alexander Fabisch -- <afabisch@informatik.uni-bremen.de>
# Author: Christopher Moody <chris... |
brianhie/scanorama | scanorama/t_sne_approx.py | _kl_divergence_bh | python | def _kl_divergence_bh(params, P, degrees_of_freedom, n_samples, n_components,
angle=0.5, skip_num_points=0, verbose=False):
params = params.astype(np.float32, copy=False)
X_embedded = params.reshape(n_samples, n_components)
val_P = P.data.astype(np.float32, copy=False)
neighbors =... | t-SNE objective function: KL divergence of p_ijs and q_ijs.
Uses Barnes-Hut tree methods to calculate the gradient that
runs in O(NlogN) instead of O(N^2)
Parameters
----------
params : array, shape (n_params,)
Unraveled embedding.
P : csr sparse matrix, shape (n_samples, n_sample)
... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L192-L258 | null | # Modified by Brian Hie <brianhie@mit.edu> to use an approximate nearest
# neighbors search.
# Original source code available at:
# https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/manifold/t_sne.py
# Author: Alexander Fabisch -- <afabisch@informatik.uni-bremen.de>
# Author: Christopher Moody <chris... |
brianhie/scanorama | scanorama/t_sne_approx.py | _gradient_descent | python | def _gradient_descent(objective, p0, it, n_iter,
n_iter_check=1, n_iter_without_progress=300,
momentum=0.8, learning_rate=200.0, min_gain=0.01,
min_grad_norm=1e-7, verbose=0, args=None, kwargs=None):
if args is None:
args = []
if kwargs i... | Batch gradient descent with momentum and individual gains.
Parameters
----------
objective : function or callable
Should return a tuple of cost and gradient for a given parameter
vector. When expensive to compute, the cost can optionally
be None and can be computed every n_iter_chec... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L261-L383 | null | # Modified by Brian Hie <brianhie@mit.edu> to use an approximate nearest
# neighbors search.
# Original source code available at:
# https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/manifold/t_sne.py
# Author: Alexander Fabisch -- <afabisch@informatik.uni-bremen.de>
# Author: Christopher Moody <chris... |
brianhie/scanorama | scanorama/t_sne_approx.py | trustworthiness | python | def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False):
if precomputed:
dist_X = X
else:
dist_X = pairwise_distances(X, squared=True)
dist_X_embedded = pairwise_distances(X_embedded, squared=True)
ind_X = np.argsort(dist_X, axis=1)
ind_X_embedded = np.argsort(dist_X_emb... | Expresses to what extent the local structure is retained.
The trustworthiness is within [0, 1]. It is defined as
.. math::
T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1}
\sum_{j \in U^{(k)}_i} (r(i, j) - k)
where :math:`r(i, j)` is the rank of the embedded datapoint j
accordi... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L386-L445 | null | # Modified by Brian Hie <brianhie@mit.edu> to use an approximate nearest
# neighbors search.
# Original source code available at:
# https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/manifold/t_sne.py
# Author: Alexander Fabisch -- <afabisch@informatik.uni-bremen.de>
# Author: Christopher Moody <chris... |
brianhie/scanorama | scanorama/t_sne_approx.py | TSNEApprox._fit | python | def _fit(self, X, skip_num_points=0):
if self.method not in ['barnes_hut', 'exact']:
raise ValueError("'method' must be 'barnes_hut' or 'exact'")
if self.angle < 0.0 or self.angle > 1.0:
raise ValueError("'angle' must be between 0.0 - 1.0")
if self.metric == "precomputed"... | Fit the model using X as training data.
Note that sparse arrays can only be handled by method='exact'.
It is recommended that you convert your sparse array to dense
(e.g. `X.toarray()`) if it fits in memory, or otherwise using a
dimensionality reduction technique (e.g. TruncatedSVD).
... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L621-L784 | null | class TSNEApprox(BaseEstimator):
"""t-distributed Stochastic Neighbor Embedding.
t-SNE [1] is a tool to visualize high-dimensional data. It converts
similarities between data points to joint probabilities and tries
to minimize the Kullback-Leibler divergence between the joint
probabilities of the l... |
brianhie/scanorama | scanorama/t_sne_approx.py | TSNEApprox._tsne | python | def _tsne(self, P, degrees_of_freedom, n_samples, random_state, X_embedded,
neighbors=None, skip_num_points=0):
# t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P
# and the Student's t-distributions Q. The optimization algorithm that
# we use is batch gradient desc... | Runs t-SNE. | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L792-L853 | null | class TSNEApprox(BaseEstimator):
"""t-distributed Stochastic Neighbor Embedding.
t-SNE [1] is a tool to visualize high-dimensional data. It converts
similarities between data points to joint probabilities and tries
to minimize the Kullback-Leibler divergence between the joint
probabilities of the l... |
brianhie/scanorama | scanorama/t_sne_approx.py | TSNEApprox.fit_transform | python | def fit_transform(self, X, y=None):
embedding = self._fit(X)
self.embedding_ = embedding
return self.embedding_ | Fit X into an embedded space and return that transformed
output.
Parameters
----------
X : array, shape (n_samples, n_features) or (n_samples, n_samples)
If the metric is 'precomputed' X must be a square distance
matrix. Otherwise it contains a sample per row.
... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/t_sne_approx.py#L855-L872 | null | class TSNEApprox(BaseEstimator):
"""t-distributed Stochastic Neighbor Embedding.
t-SNE [1] is a tool to visualize high-dimensional data. It converts
similarities between data points to joint probabilities and tries
to minimize the Kullback-Leibler divergence between the joint
probabilities of the l... |
brianhie/scanorama | scanorama/scanorama.py | correct | python | def correct(datasets_full, genes_list, return_dimred=False,
batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None,
dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN,
return_dense=False, hvg=None, union=False,
geosketch=False, geosketch_max=20000):
datase... | Integrate and batch correct a list of data sets.
Parameters
----------
datasets_full : `list` of `scipy.sparse.csr_matrix` or of `numpy.ndarray`
Data sets to integrate and correct.
genes_list: `list` of `list` of `string`
List of genes for each data set.
return_dimred: `bool`, optio... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L37-L111 | [
"def merge_datasets(datasets, genes, ds_names=None, verbose=True,\n union=False):\n if union:\n sys.stderr.write(\n 'WARNING: Integrating based on the union of genes is '\n 'highly discouraged, consider taking the intersection '\n 'or requantifying gene e... | from annoy import AnnoyIndex
from intervaltree import IntervalTree
from itertools import cycle, islice
import numpy as np
import operator
import random
import scipy
from scipy.sparse import csc_matrix, csr_matrix, vstack
from sklearn.manifold import TSNE
from sklearn.metrics.pairwise import rbf_kernel, euclidean_distan... |
brianhie/scanorama | scanorama/scanorama.py | integrate | python | def integrate(datasets_full, genes_list, batch_size=BATCH_SIZE,
verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX,
sigma=SIGMA, alpha=ALPHA, knn=KNN, geosketch=False,
geosketch_max=20000, n_iter=1, union=False, hvg=None):
datasets_full = check_datasets(datasets_f... | Integrate a list of data sets.
Parameters
----------
datasets_full : `list` of `scipy.sparse.csr_matrix` or of `numpy.ndarray`
Data sets to integrate and correct.
genes_list: `list` of `list` of `string`
List of genes for each data set.
batch_size: `int`, optional (default: `5000`)
... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L114-L169 | [
"def merge_datasets(datasets, genes, ds_names=None, verbose=True,\n union=False):\n if union:\n sys.stderr.write(\n 'WARNING: Integrating based on the union of genes is '\n 'highly discouraged, consider taking the intersection '\n 'or requantifying gene e... | from annoy import AnnoyIndex
from intervaltree import IntervalTree
from itertools import cycle, islice
import numpy as np
import operator
import random
import scipy
from scipy.sparse import csc_matrix, csr_matrix, vstack
from sklearn.manifold import TSNE
from sklearn.metrics.pairwise import rbf_kernel, euclidean_distan... |
brianhie/scanorama | scanorama/scanorama.py | correct_scanpy | python | def correct_scanpy(adatas, **kwargs):
if 'return_dimred' in kwargs and kwargs['return_dimred']:
datasets_dimred, datasets, genes = correct(
[adata.X for adata in adatas],
[adata.var_names.values for adata in adatas],
**kwargs
)
else:
datasets, genes = ... | Batch correct a list of `scanpy.api.AnnData`.
Parameters
----------
adatas : `list` of `scanpy.api.AnnData`
Data sets to integrate and/or correct.
kwargs : `dict`
See documentation for the `correct()` method for a full list of
parameters to use for batch correction.
Returns... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L172-L216 | [
"def correct(datasets_full, genes_list, return_dimred=False,\n batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None,\n dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN,\n return_dense=False, hvg=None, union=False,\n geosketch=False, geosketch_max=20000):\n... | from annoy import AnnoyIndex
from intervaltree import IntervalTree
from itertools import cycle, islice
import numpy as np
import operator
import random
import scipy
from scipy.sparse import csc_matrix, csr_matrix, vstack
from sklearn.manifold import TSNE
from sklearn.metrics.pairwise import rbf_kernel, euclidean_distan... |
brianhie/scanorama | scanorama/scanorama.py | integrate_scanpy | python | def integrate_scanpy(adatas, **kwargs):
datasets_dimred, genes = integrate(
[adata.X for adata in adatas],
[adata.var_names.values for adata in adatas],
**kwargs
)
return datasets_dimred | Integrate a list of `scanpy.api.AnnData`.
Parameters
----------
adatas : `list` of `scanpy.api.AnnData`
Data sets to integrate.
kwargs : `dict`
See documentation for the `integrate()` method for a full list of
parameters to use for batch correction.
Returns
-------
... | train | https://github.com/brianhie/scanorama/blob/57aafac87d07a8d682f57450165dd07f066ebb3c/scanorama/scanorama.py#L219-L242 | [
"def integrate(datasets_full, genes_list, batch_size=BATCH_SIZE,\n verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX,\n sigma=SIGMA, alpha=ALPHA, knn=KNN, geosketch=False,\n geosketch_max=20000, n_iter=1, union=False, hvg=None):\n \"\"\"Integrate a list of data s... | from annoy import AnnoyIndex
from intervaltree import IntervalTree
from itertools import cycle, islice
import numpy as np
import operator
import random
import scipy
from scipy.sparse import csc_matrix, csr_matrix, vstack
from sklearn.manifold import TSNE
from sklearn.metrics.pairwise import rbf_kernel, euclidean_distan... |
chrisspen/weka | weka/arff.py | convert_weka_to_py_date_pattern | python | def convert_weka_to_py_date_pattern(p):
# https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
# https://www.cs.waikato.ac.nz/ml/weka/arff.html
p = p.replace('yyyy', r'%Y')
p = p.replace('MM', r'%m')
p = p.replace('dd', r'%d')
p = p.replace('HH', r'%H')
p = p.replace('m... | Converts the date format pattern used by Weka to the date format pattern used by Python's datetime.strftime(). | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L87-L99 | null | # Copyright (c) 2008, Mikio L. Braun, Cheng Soon Ong, Soeren Sonnenburg
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
#... |
chrisspen/weka | weka/arff.py | ArffFile.get_attribute_value | python | def get_attribute_value(self, name, index):
if index == MISSING:
return
elif self.attribute_types[name] in NUMERIC_TYPES:
at = self.attribute_types[name]
if at == TYPE_INTEGER:
return int(index)
return Decimal(str(index))
else:
... | Returns the value associated with the given value index
of the attribute with the given name.
This is only applicable for nominal and string types. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L320-L342 | null | class ArffFile(object):
"""An ARFF File object describes a data set consisting of a number
of data points made up of attributes. The whole data set is called
a 'relation'. Supported attributes are:
- 'numeric': floating point numbers
- 'string': strings
- 'nominal': taking one of a number of po... |
chrisspen/weka | weka/arff.py | ArffFile.load | python | def load(cls, filename, schema_only=False):
o = open(filename)
s = o.read()
a = cls.parse(s, schema_only=schema_only)
if not schema_only:
a._filename = filename
o.close()
return a | Load an ARFF File from a file. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L357-L367 | [
"def parse(cls, s, schema_only=False):\n \"\"\"\n Parse an ARFF File already loaded into a string.\n \"\"\"\n a = cls()\n a.state = 'comment'\n a.lineno = 1\n for l in s.splitlines():\n a.parseline(l)\n a.lineno += 1\n if schema_only and a.state == 'data':\n # Do... | class ArffFile(object):
"""An ARFF File object describes a data set consisting of a number
of data points made up of attributes. The whole data set is called
a 'relation'. Supported attributes are:
- 'numeric': floating point numbers
- 'string': strings
- 'nominal': taking one of a number of po... |
chrisspen/weka | weka/arff.py | ArffFile.parse | python | def parse(cls, s, schema_only=False):
a = cls()
a.state = 'comment'
a.lineno = 1
for l in s.splitlines():
a.parseline(l)
a.lineno += 1
if schema_only and a.state == 'data':
# Don't parse data if we're only loading the schema.
... | Parse an ARFF File already loaded into a string. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L370-L383 | [
"def parseline(self, l):\n if self.state == 'comment':\n if l and l[0] == '%':\n self.comment.append(l[2:])\n else:\n self.comment = '\\n'.join(self.comment)\n self.state = 'in_header'\n self.parseline(l)\n elif self.state == 'in_header':\n ll =... | class ArffFile(object):
"""An ARFF File object describes a data set consisting of a number
of data points made up of attributes. The whole data set is called
a 'relation'. Supported attributes are:
- 'numeric': floating point numbers
- 'string': strings
- 'nominal': taking one of a number of po... |
chrisspen/weka | weka/arff.py | ArffFile.copy | python | def copy(self, schema_only=False):
o = type(self)()
o.relation = self.relation
o.attributes = list(self.attributes)
o.attribute_types = self.attribute_types.copy()
o.attribute_data = self.attribute_data.copy()
if not schema_only:
o.comment = list(self.comment)... | Creates a deepcopy of the instance.
If schema_only is True, the data will be excluded from the copy. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L385-L398 | null | class ArffFile(object):
"""An ARFF File object describes a data set consisting of a number
of data points made up of attributes. The whole data set is called
a 'relation'. Supported attributes are:
- 'numeric': floating point numbers
- 'string': strings
- 'nominal': taking one of a number of po... |
chrisspen/weka | weka/arff.py | ArffFile.open_stream | python | def open_stream(self, class_attr_name=None, fn=None):
if fn:
self.fout_fn = fn
else:
fd, self.fout_fn = tempfile.mkstemp()
os.close(fd)
self.fout = open(self.fout_fn, 'w')
if class_attr_name:
self.class_attr_name = class_attr_name
s... | Save an arff structure to a file, leaving the file object
open for writing of new data samples.
This prevents you from directly accessing the data via Python,
but when generating a huge file, this prevents all your data
from being stored in memory. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L404-L422 | [
"def write(self,\n fout=None,\n fmt=SPARSE,\n schema_only=False,\n data_only=False):\n \"\"\"\n Write an arff structure to a string.\n \"\"\"\n assert not (schema_only and data_only), 'Make up your mind.'\n assert fmt in FORMATS, 'Invalid format \"%s\". Should be one of: %s' % (fmt, ', '.... | class ArffFile(object):
"""An ARFF File object describes a data set consisting of a number
of data points made up of attributes. The whole data set is called
a 'relation'. Supported attributes are:
- 'numeric': floating point numbers
- 'string': strings
- 'nominal': taking one of a number of po... |
chrisspen/weka | weka/arff.py | ArffFile.close_stream | python | def close_stream(self):
if self.fout:
fout = self.fout
fout_fn = self.fout_fn
self.fout.flush()
self.fout.close()
self.fout = None
self.fout_fn = None
return fout_fn | Terminates an open stream and returns the filename
of the file containing the streamed data. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L424-L436 | null | class ArffFile(object):
"""An ARFF File object describes a data set consisting of a number
of data points made up of attributes. The whole data set is called
a 'relation'. Supported attributes are:
- 'numeric': floating point numbers
- 'string': strings
- 'nominal': taking one of a number of po... |
chrisspen/weka | weka/arff.py | ArffFile.save | python | def save(self, filename=None):
filename = filename or self._filename
o = open(filename, 'w')
o.write(self.write())
o.close() | Save an arff structure to a file. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L438-L445 | [
"def write(self,\n fout=None,\n fmt=SPARSE,\n schema_only=False,\n data_only=False):\n \"\"\"\n Write an arff structure to a string.\n \"\"\"\n assert not (schema_only and data_only), 'Make up your mind.'\n assert fmt in FORMATS, 'Invalid format \"%s\". Should be one of: %s' % (fmt, ', '.... | class ArffFile(object):
"""An ARFF File object describes a data set consisting of a number
of data points made up of attributes. The whole data set is called
a 'relation'. Supported attributes are:
- 'numeric': floating point numbers
- 'string': strings
- 'nominal': taking one of a number of po... |
chrisspen/weka | weka/arff.py | ArffFile.write_line | python | def write_line(self, d, fmt=SPARSE):
def smart_quote(s):
if isinstance(s, basestring) and ' ' in s and s[0] != '"':
s = '"%s"' % s
return s
if fmt == DENSE:
#TODO:fix
assert not isinstance(d, dict), NotImplemented
... | Converts a single data line to a string. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L447-L532 | [
"def convert_weka_to_py_date_pattern(p):\n \"\"\"\n Converts the date format pattern used by Weka to the date format pattern used by Python's datetime.strftime().\n \"\"\"\n # https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior\n # https://www.cs.waikato.ac.nz/ml/weka/arff.html... | class ArffFile(object):
"""An ARFF File object describes a data set consisting of a number
of data points made up of attributes. The whole data set is called
a 'relation'. Supported attributes are:
- 'numeric': floating point numbers
- 'string': strings
- 'nominal': taking one of a number of po... |
chrisspen/weka | weka/arff.py | ArffFile.write | python | def write(self,
fout=None,
fmt=SPARSE,
schema_only=False,
data_only=False):
assert not (schema_only and data_only), 'Make up your mind.'
assert fmt in FORMATS, 'Invalid format "%s". Should be one of: %s' % (fmt, ', '.join(FORMATS))
close = False
if fout is... | Write an arff structure to a string. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L559-L584 | [
" def write_line(self, d, fmt=SPARSE):\n \"\"\"\n Converts a single data line to a string.\n \"\"\"\n\n def smart_quote(s):\n if isinstance(s, basestring) and ' ' in s and s[0] != '\"':\n s = '\"%s\"' % s\n return s\n\n if fmt == DENSE:\n ... | class ArffFile(object):
"""An ARFF File object describes a data set consisting of a number
of data points made up of attributes. The whole data set is called
a 'relation'. Supported attributes are:
- 'numeric': floating point numbers
- 'string': strings
- 'nominal': taking one of a number of po... |
chrisspen/weka | weka/arff.py | ArffFile.define_attribute | python | def define_attribute(self, name, atype, data=None):
self.attributes.append(name)
assert atype in TYPES, "Unknown type '%s'. Must be one of: %s" % (atype, ', '.join(TYPES),)
self.attribute_types[name] = atype
self.attribute_data[name] = data | Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'.
For nominal attributes, pass the possible values as data.
For date attributes, pass the format as data. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L592-L601 | null | class ArffFile(object):
"""An ARFF File object describes a data set consisting of a number
of data points made up of attributes. The whole data set is called
a 'relation'. Supported attributes are:
- 'numeric': floating point numbers
- 'string': strings
- 'nominal': taking one of a number of po... |
chrisspen/weka | weka/arff.py | ArffFile.dump | python | def dump(self):
print("Relation " + self.relation)
print(" With attributes")
for n in self.attributes:
if self.attribute_types[n] != TYPE_NOMINAL:
print(" %s of type %s" % (n, self.attribute_types[n]))
else:
print(" " + n + " of type... | Print an overview of the ARFF file. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L722-L732 | null | class ArffFile(object):
"""An ARFF File object describes a data set consisting of a number
of data points made up of attributes. The whole data set is called
a 'relation'. Supported attributes are:
- 'numeric': floating point numbers
- 'string': strings
- 'nominal': taking one of a number of po... |
chrisspen/weka | weka/arff.py | ArffFile.alphabetize_attributes | python | def alphabetize_attributes(self):
self.attributes.sort(key=lambda name: (name == self.class_attr_name, name)) | Orders attributes names alphabetically, except for the class attribute, which is kept last. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L746-L750 | null | class ArffFile(object):
"""An ARFF File object describes a data set consisting of a number
of data points made up of attributes. The whole data set is called
a 'relation'. Supported attributes are:
- 'numeric': floating point numbers
- 'string': strings
- 'nominal': taking one of a number of po... |
chrisspen/weka | weka/classifiers.py | Classifier.load_raw | python | def load_raw(cls, model_fn, schema, *args, **kwargs):
c = cls(*args, **kwargs)
c.schema = schema.copy(schema_only=True)
c._model_data = open(model_fn, 'rb').read()
return c | Loads a trained classifier from the raw Weka model format.
Must specify the model schema and classifier name, since
these aren't currently deduced from the model format. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/classifiers.py#L270-L279 | null | class Classifier(BaseClassifier):
def __init__(self, name, ckargs=None, model_data=None):
self._model_data = model_data
self.name = name # Weka classifier class name.
self.schema = None
self.ckargs = ckargs
self.last_training_stdout = None
self.last_training_stderr ... |
chrisspen/weka | weka/classifiers.py | Classifier.train | python | def train(self, training_data, testing_data=None, verbose=False):
model_fn = None
training_fn = None
clean_training = False
testing_fn = None
clean_testing = False
try:
# Validate training data.
if isinstance(training_data, basestring)... | Updates the classifier with new data. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/classifiers.py#L312-L417 | [
"def load(cls, filename, schema_only=False):\n \"\"\"\n Load an ARFF File from a file.\n \"\"\"\n o = open(filename)\n s = o.read()\n a = cls.parse(s, schema_only=schema_only)\n if not schema_only:\n a._filename = filename\n o.close()\n return a\n",
"def _get_ckargs_str(self):\n ... | class Classifier(BaseClassifier):
def __init__(self, name, ckargs=None, model_data=None):
self._model_data = model_data
self.name = name # Weka classifier class name.
self.schema = None
self.ckargs = ckargs
self.last_training_stdout = None
self.last_training_stderr ... |
chrisspen/weka | weka/classifiers.py | Classifier.predict | python | def predict(self, query_data, verbose=False, distribution=False, cleanup=True):
model_fn = None
query_fn = None
clean_query = False
stdout = None
try:
# Validate query data.
if isinstance(query_data, basestring):
assert os.path... | Iterates over the predicted values and probability (if supported).
Each iteration yields a tuple of the form (prediction, probability).
If the file is a test file (i.e. contains no query variables),
then the tuple will be of the form (prediction, actual).
See http://wek... | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/classifiers.py#L419-L592 | [
"def load(cls, filename, schema_only=False):\n \"\"\"\n Load an ARFF File from a file.\n \"\"\"\n o = open(filename)\n s = o.read()\n a = cls.parse(s, schema_only=schema_only)\n if not schema_only:\n a._filename = filename\n o.close()\n return a\n"
] | class Classifier(BaseClassifier):
def __init__(self, name, ckargs=None, model_data=None):
self._model_data = model_data
self.name = name # Weka classifier class name.
self.schema = None
self.ckargs = ckargs
self.last_training_stdout = None
self.last_training_stderr ... |
chrisspen/weka | weka/classifiers.py | EnsembleClassifier.get_training_coverage | python | def get_training_coverage(self):
total = len(self.training_results)
i = sum(1 for data in self.training_results.values() if not isinstance(data, basestring))
return i/float(total) | Returns a ratio of classifiers that were able to be trained successfully. | train | https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/classifiers.py#L640-L646 | null | class EnsembleClassifier(BaseClassifier):
def __init__(self, classes=None):
self.best = None, None # score, cls
self.training_results = {} # {name: score}
self.trained_classifiers = {} # {name: classifier instance}
self.prediction_results = {} # {name: results}
self.classes ... |
heigeo/climata | climata/bin/acis_sites.py | load_sites | python | def load_sites(*basin_ids):
# Resolve basin ids to HUC8s if needed
basins = []
for basin in basin_ids:
if basin.isdigit() and len(basin) == 8:
basins.append(basin)
else:
from climata.huc8 import get_huc8
basins.extend(get_huc8(basin))
# Load sites wi... | Load metadata for all sites in given basin codes. | train | https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/bin/acis_sites.py#L16-L118 | [
"def get_huc8(prefix):\n \"\"\"\n Return all HUC8s matching the given prefix (e.g. 1801) or basin name\n (e.g. Klamath)\n \"\"\"\n if not prefix.isdigit():\n # Look up hucs by name\n name = prefix\n prefix = None\n for row in hucs:\n if row.basin.lower() == name... | #!/usr/bin/env python
from __future__ import print_function
import sys
from datetime import date
from climata.acis import StationMetaIO
from climata.acis.constants import (
ELEMENT_BY_NAME, ELEMENT_BY_ID, ALL_META_FIELDS
)
elems = ELEMENT_BY_NAME.copy()
# Eloement 7 (pan evap) does not have a name, copy from ID l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.