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 |
|---|---|---|---|---|---|---|---|---|---|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _get_cache_dir | python | def _get_cache_dir(candidate):
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir | Get the current cache directory. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L426-L444 | null | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _all_files_matching_ext | python | def _all_files_matching_ext(start, ext):
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files | Get all files matching :ext: from :start: directory. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L447-L454 | null | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _is_excluded(filename, exclusions):
"""Return true if filename matches any of exclusions."""
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | _is_excluded | python | def _is_excluded(filename, exclusions):
for exclusion in exclusions:
if fnmatch(filename, exclusion):
return True
return False | Return true if filename matches any of exclusions. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L457-L463 | null | # /polysquare_setuptools_lint/__init__.py
#
# Provides a setuptools command for running pyroma, prospector and
# flake8 with maximum settings on all distributed files and tests.
#
# See /LICENCE.md for Copyright information
"""Provide a setuptools command for linters."""
import errno
import multiprocessing
import os
import os.path
import platform
import re
import subprocess
import traceback
import sys # suppress(I100)
from sys import exit as sys_exit # suppress(I100)
from collections import namedtuple # suppress(I100)
from contextlib import contextmanager
from distutils.errors import DistutilsArgError # suppress(import-error)
from fnmatch import filter as fnfilter
from fnmatch import fnmatch
from jobstamps import jobstamp
import setuptools
@contextmanager
def _custom_argv(argv):
"""Overwrite argv[1:] with argv, restore on exit."""
backup_argv = sys.argv
sys.argv = backup_argv[:1] + argv
try:
yield
finally:
sys.argv = backup_argv
@contextmanager
def _patched_pep257():
"""Monkey-patch pep257 after imports to avoid info logging."""
import pep257
if getattr(pep257, "log", None):
def _dummy(*args, **kwargs):
del args
del kwargs
old_log_info = pep257.log.info
pep257.log.info = _dummy # suppress(unused-attribute)
try:
yield
finally:
if getattr(pep257, "log", None):
pep257.log.info = old_log_info
def _stamped_deps(stamp_directory, func, dependencies, *args, **kwargs):
"""Run func, assumed to have dependencies as its first argument."""
if not isinstance(dependencies, list):
jobstamps_dependencies = [dependencies]
else:
jobstamps_dependencies = dependencies
kwargs.update({
"jobstamps_cache_output_directory": stamp_directory,
"jobstamps_dependencies": jobstamps_dependencies
})
return jobstamp.run(func, dependencies, *args, **kwargs)
class _Key(namedtuple("_Key", "file line code")):
"""A sortable class representing a key to store messages in a dict."""
def __lt__(self, other):
"""Check if self should sort less than other."""
if self.file == other.file:
if self.line == other.line:
return self.code < other.code
return self.line < other.line
return self.file < other.file
def _debug_linter_status(linter, filename, show_lint_files):
"""Indicate that we are running this linter if required."""
if show_lint_files:
print("{linter}: {filename}".format(linter=linter, filename=filename))
def _run_flake8_internal(filename):
"""Run flake8."""
from flake8.engine import get_style_guide
from pep8 import BaseReport
from prospector.message import Message, Location
return_dict = dict()
cwd = os.getcwd()
class Flake8MergeReporter(BaseReport):
"""An implementation of pep8.BaseReport merging results.
This implementation merges results from the flake8 report
into the prospector report created earlier.
"""
def __init__(self, options):
"""Initialize this Flake8MergeReporter."""
super(Flake8MergeReporter, self).__init__(options)
self._current_file = ""
def init_file(self, filename, lines, expected, line_offset):
"""Start processing filename."""
relative_path = os.path.join(cwd, filename)
self._current_file = os.path.realpath(relative_path)
super(Flake8MergeReporter, self).init_file(filename,
lines,
expected,
line_offset)
def error(self, line_number, offset, text, check):
"""Record error and store in return_dict."""
code = super(Flake8MergeReporter, self).error(line_number,
offset,
text,
check) or "no-code"
key = _Key(self._current_file, line_number, code)
return_dict[key] = Message(code,
code,
Location(self._current_file,
None,
None,
line_number,
offset),
text[5:])
flake8_check_paths = [filename]
get_style_guide(reporter=Flake8MergeReporter,
jobs="1").check_files(paths=flake8_check_paths)
return return_dict
def _run_flake8(filename, stamp_file_name, show_lint_files):
"""Run flake8, cached by stamp_file_name."""
_debug_linter_status("flake8", filename, show_lint_files)
return _stamped_deps(stamp_file_name,
_run_flake8_internal,
filename)
def can_run_pylint():
"""Return true if we can run pylint.
Pylint fails on pypy3 as pypy3 doesn't implement certain attributes
on functions.
"""
return not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3)
def can_run_frosted():
"""Return true if we can run frosted.
Frosted fails on pypy3 as the installer depends on configparser. It
also fails on Windows, because it reports file names incorrectly.
"""
return (not (platform.python_implementation() == "PyPy" and
sys.version_info.major == 3) and
platform.system() != "Windows")
# suppress(too-many-locals)
def _run_prospector_on(filenames,
tools,
disabled_linters,
show_lint_files,
ignore_codes=None):
"""Run prospector on filename, using the specified tools.
This function enables us to run different tools on different
classes of files, which is necessary in the case of tests.
"""
from prospector.run import Prospector, ProspectorConfig
assert tools
tools = list(set(tools) - set(disabled_linters))
return_dict = dict()
ignore_codes = ignore_codes or list()
# Early return if all tools were filtered out
if not tools:
return return_dict
# pylint doesn't like absolute paths, so convert to relative.
all_argv = (["-F", "-D", "-M", "--no-autodetect", "-s", "veryhigh"] +
("-t " + " -t ".join(tools)).split(" "))
for filename in filenames:
_debug_linter_status("prospector", filename, show_lint_files)
with _custom_argv(all_argv + [os.path.relpath(f) for f in filenames]):
prospector = Prospector(ProspectorConfig())
prospector.execute()
messages = prospector.get_messages() or list()
for message in messages:
message.to_absolute_path(os.getcwd())
loc = message.location
code = message.code
if code in ignore_codes:
continue
key = _Key(loc.path, loc.line, code)
return_dict[key] = message
return return_dict
def _file_is_test(filename):
"""Return true if file is a test."""
is_test = re.compile(r"^.*test[^{0}]*.py$".format(re.escape(os.path.sep)))
return bool(is_test.match(filename))
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# Run prospector on tests. There are some errors we don't care about:
# - invalid-name: This is often triggered because test method names
# can be quite long. Descriptive test method names are
# good, so disable this warning.
# - super-on-old-class: unittest.TestCase is a new style class, but
# pylint detects an old style class.
# - too-many-public-methods: TestCase subclasses by definition have
# lots of methods.
test_ignore_codes = [
"invalid-name",
"super-on-old-class",
"too-many-public-methods"
]
kwargs = dict()
if _file_is_test(filename):
kwargs["ignore_codes"] = test_ignore_codes
else:
if can_run_frosted():
linter_tools += ["frosted"]
return _stamped_deps(stamp_file_name,
_run_prospector_on,
[filename],
linter_tools,
disabled_linters,
show_lint_files,
**kwargs)
def _run_pyroma(setup_file, show_lint_files):
"""Run pyroma."""
from pyroma import projectdata, ratings
from prospector.message import Message, Location
_debug_linter_status("pyroma", setup_file, show_lint_files)
return_dict = dict()
data = projectdata.get_data(os.getcwd())
all_tests = ratings.ALL_TESTS
for test in [mod() for mod in [t.__class__ for t in all_tests]]:
if test.test(data) is False:
class_name = test.__class__.__name__
key = _Key(setup_file, 0, class_name)
loc = Location(setup_file, None, None, 0, 0)
msg = test.message()
return_dict[key] = Message("pyroma",
class_name,
loc,
msg)
return return_dict
_BLOCK_REGEXPS = [
r"\bpylint:disable=[^\s]*\b",
r"\bNOLINT:[^\s]*\b",
r"\bNOQA[^\s]*\b",
r"\bsuppress\([^\s]*\)"
]
def _run_polysquare_style_linter(matched_filenames,
cache_dir,
show_lint_files):
"""Run polysquare-generic-file-linter on matched_filenames."""
from polysquarelinter import linter as lint
from prospector.message import Message, Location
return_dict = dict()
def _custom_reporter(error, file_path):
key = _Key(file_path, error[1].line, error[0])
loc = Location(file_path, None, None, error[1].line, 0)
return_dict[key] = Message("polysquare-generic-file-linter",
error[0],
loc,
error[1].description)
for filename in matched_filenames:
_debug_linter_status("style-linter", filename, show_lint_files)
# suppress(protected-access,unused-attribute)
lint._report_lint_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--log-technical-terms-to=" + os.path.join(cache_dir,
"technical-terms"),
] + matched_filenames + [
"--block-regexps"
] + _BLOCK_REGEXPS)
return return_dict
def _run_spellcheck_linter(matched_filenames, cache_dir, show_lint_files):
"""Run spellcheck-linter on matched_filenames."""
from polysquarelinter import lint_spelling_only as lint
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("spellcheck-linter", filename, show_lint_files)
return_dict = dict()
def _custom_reporter(error, file_path):
line = error.line_offset + 1
key = _Key(file_path, line, "file/spelling_error")
loc = Location(file_path, None, None, line, 0)
# suppress(protected-access)
desc = lint._SPELLCHECK_MESSAGES[error.error_type].format(error.word)
return_dict[key] = Message("spellcheck-linter",
"file/spelling_error",
loc,
desc)
# suppress(protected-access,unused-attribute)
lint._report_spelling_error = _custom_reporter
lint.main([
"--spellcheck-cache=" + os.path.join(cache_dir, "spelling"),
"--stamp-file-path=" + os.path.join(cache_dir,
"jobstamps",
"polysquarelinter"),
"--technical-terms=" + os.path.join(cache_dir, "technical-terms"),
] + matched_filenames)
return return_dict
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matched_filenames,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
lines = proc.communicate()[0].decode().splitlines()
except OSError as error:
if error.errno == errno.ENOENT:
return []
lines = [
re.match(r"([\w\-.\/\\ ]+)\:([0-9]+)\: (\w+) (.+)", l).groups(1)
for l in lines
]
return_dict = dict()
for filename, lineno, code, msg in lines:
key = _Key(filename, int(lineno), code)
loc = Location(filename, None, None, int(lineno), 0)
return_dict[key] = Message("markdownlint", code, loc, msg)
return return_dict
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",")
def _get_cache_dir(candidate):
"""Get the current cache directory."""
if candidate:
return candidate
import distutils.dist # suppress(import-error)
import distutils.command.build # suppress(import-error)
build_cmd = distutils.command.build.build(distutils.dist.Distribution())
build_cmd.finalize_options()
cache_dir = os.path.abspath(build_cmd.build_temp)
# Make sure that it is created before anyone tries to use it
try:
os.makedirs(cache_dir)
except OSError as error:
if error.errno != errno.EEXIST:
raise error
return cache_dir
def _all_files_matching_ext(start, ext):
"""Get all files matching :ext: from :start: directory."""
md_files = []
for root, _, files in os.walk(start):
md_files += fnfilter([os.path.join(root, f) for f in files],
"*." + ext)
return md_files
class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | PolysquareLintCommand._file_lines | python | def _file_lines(self, filename):
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename] | Get lines for filename, caching opened files. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L479-L490 | null | class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | PolysquareLintCommand._suppressed | python | def _suppressed(self, filename, line, code):
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass | Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L492-L522 | null | class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | PolysquareLintCommand._get_md_files | python | def _get_md_files(self):
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)]) | Get all markdown files. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L524-L532 | null | class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | PolysquareLintCommand._get_files_to_lint | python | def _get_files_to_lint(self, external_directories):
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)]) | Get files to lint. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L534-L559 | null | class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | PolysquareLintCommand._map_over_linters | python | def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error | Run mapper over passed in files, returning a list of results. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L562-L621 | null | class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | PolysquareLintCommand.run | python | def run(self): # suppress(unused-function)
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1) | Run linters. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L623-L685 | null | class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | PolysquareLintCommand.initialize_options | python | def initialize_options(self): # suppress(unused-function)
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0 | Set all options to their initial values. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L687-L695 | null | class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def finalize_options(self): # suppress(unused-function)
"""Finalize all options."""
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory)
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
polysquare/polysquare-setuptools-lint | polysquare_setuptools_lint/__init__.py | PolysquareLintCommand.finalize_options | python | def finalize_options(self): # suppress(unused-function)
for option in ["suppress-codes", "exclusions", "disable-linters"]:
attribute = option.replace("-", "_")
if isinstance(getattr(self, attribute), str):
setattr(self, attribute, getattr(self, attribute).split(","))
if not isinstance(getattr(self, attribute), list):
raise DistutilsArgError("""--{0} must be """
"""a list""".format(option))
if not isinstance(self.cache_directory, str):
raise DistutilsArgError("""--cache-directory=CACHE """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.stamp_directory, str):
raise DistutilsArgError("""--stamp-directory=STAMP """
"""must be a string""")
if not isinstance(self.show_lint_files, int):
raise DistutilsArgError("""--show-lint-files must be a int""")
self.cache_directory = _get_cache_dir(self.cache_directory) | Finalize all options. | train | https://github.com/polysquare/polysquare-setuptools-lint/blob/5df5a6401c7ad6a90b42230eeb99c82cc56952b6/polysquare_setuptools_lint/__init__.py#L697-L723 | [
"def _get_cache_dir(candidate):\n \"\"\"Get the current cache directory.\"\"\"\n if candidate:\n return candidate\n\n import distutils.dist # suppress(import-error)\n import distutils.command.build # suppress(import-error)\n build_cmd = distutils.command.build.build(distutils.dist.Distributi... | class PolysquareLintCommand(setuptools.Command): # suppress(unused-function)
"""Provide a lint command."""
def __init__(self, *args, **kwargs):
"""Initialize this class' instance variables."""
setuptools.Command.__init__(self, *args, **kwargs)
self._file_lines_cache = None
self.cache_directory = None
self.stamp_directory = None
self.suppress_codes = None
self.exclusions = None
self.initialize_options()
def _file_lines(self, filename):
"""Get lines for filename, caching opened files."""
try:
return self._file_lines_cache[filename]
except KeyError:
if os.path.isfile(filename):
with open(filename) as python_file:
self._file_lines_cache[filename] = python_file.readlines()
else:
self._file_lines_cache[filename] = ""
return self._file_lines_cache[filename]
def _suppressed(self, filename, line, code):
"""Return true if linter error code is suppressed inline.
The suppression format is suppress(CODE1,CODE2,CODE3) etc.
"""
if code in self.suppress_codes:
return True
lines = self._file_lines(filename)
# File is zero length, cannot be suppressed
if not lines:
return False
# Handle errors which appear after the end of the document.
while line > len(lines):
line = line - 1
relevant_line = lines[line - 1]
try:
suppressions_function = relevant_line.split("#")[1].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
except IndexError:
above_line = lines[max(0, line - 2)]
suppressions_function = above_line.strip()[1:].strip()
if suppressions_function.startswith("suppress("):
return code in _parse_suppressions(suppressions_function)
finally:
pass
def _get_md_files(self):
"""Get all markdown files."""
all_f = _all_files_matching_ext(os.getcwd(), "md")
exclusions = [
"*.egg/*",
"*.eggs/*",
"*build/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
def _get_files_to_lint(self, external_directories):
"""Get files to lint."""
all_f = []
for external_dir in external_directories:
all_f.extend(_all_files_matching_ext(external_dir, "py"))
packages = self.distribution.packages or list()
for package in packages:
all_f.extend(_all_files_matching_ext(package, "py"))
py_modules = self.distribution.py_modules or list()
for filename in py_modules:
all_f.append(os.path.realpath(filename + ".py"))
all_f.append(os.path.join(os.getcwd(), "setup.py"))
# Remove duplicates which may exist due to symlinks or repeated
# packages found by /setup.py
all_f = list(set([os.path.realpath(f) for f in all_f]))
exclusions = [
"*.egg/*",
"*.eggs/*"
] + self.exclusions
return sorted([f for f in all_f if not _is_excluded(f, exclusions)])
# suppress(too-many-arguments)
def _map_over_linters(self,
py_files,
non_test_files,
md_files,
stamp_directory,
mapper):
"""Run mapper over passed in files, returning a list of results."""
dispatch = [
("flake8", lambda: mapper(_run_flake8,
py_files,
stamp_directory,
self.show_lint_files)),
("pyroma", lambda: [_stamped_deps(stamp_directory,
_run_pyroma,
"setup.py",
self.show_lint_files)]),
("mdl", lambda: [_run_markdownlint(md_files,
self.show_lint_files)]),
("polysquare-generic-file-linter", lambda: [
_run_polysquare_style_linter(py_files,
self.cache_directory,
self.show_lint_files)
]),
("spellcheck-linter", lambda: [
_run_spellcheck_linter(md_files,
self.cache_directory,
self.show_lint_files)
])
]
# Prospector checks get handled on a case sub-linter by sub-linter
# basis internally, so always run the mapper over prospector.
#
# vulture should be added again once issue 180 is fixed.
prospector = (mapper(_run_prospector,
py_files,
stamp_directory,
self.disable_linters,
self.show_lint_files) +
[_stamped_deps(stamp_directory,
_run_prospector_on,
non_test_files,
["dodgy"],
self.disable_linters,
self.show_lint_files)])
for ret in prospector:
yield ret
for linter, action in dispatch:
if linter not in self.disable_linters:
try:
for ret in action():
yield ret
except Exception as error:
traceback.print_exc()
sys.stderr.write("""Encountered error '{}' whilst """
"""running {}""".format(str(error),
linter))
raise error
def run(self): # suppress(unused-function)
"""Run linters."""
import parmap
from prospector.formatters.pylint import PylintFormatter
cwd = os.getcwd()
files = self._get_files_to_lint([os.path.join(cwd, "test")])
if not files:
sys_exit(0)
return
use_multiprocessing = (not os.getenv("DISABLE_MULTIPROCESSING",
None) and
multiprocessing.cpu_count() < len(files) and
multiprocessing.cpu_count() > 2)
if use_multiprocessing:
mapper = parmap.map
else:
# suppress(E731)
mapper = lambda f, i, *a: [f(*((x, ) + a)) for x in i]
with _patched_pep257():
keyed_messages = dict()
# Certain checks, such as vulture and pyroma cannot be
# meaningfully run in parallel (vulture requires all
# files to be passed to the linter, pyroma can only be run
# on /setup.py, etc).
non_test_files = [f for f in files if not _file_is_test(f)]
if self.stamp_directory:
stamp_directory = self.stamp_directory
else:
stamp_directory = os.path.join(self.cache_directory,
"polysquare_setuptools_lint",
"jobstamps")
# This will ensure that we don't repeat messages, because
# new keys overwrite old ones.
for keyed_subset in self._map_over_linters(files,
non_test_files,
self._get_md_files(),
stamp_directory,
mapper):
keyed_messages.update(keyed_subset)
messages = []
for _, message in keyed_messages.items():
if not self._suppressed(message.location.path,
message.location.line,
message.code):
message.to_relative_path(cwd)
messages.append(message)
sys.stdout.write(PylintFormatter(dict(),
messages,
None).render(messages=True,
summary=False,
profile=False) + "\n")
if messages:
sys_exit(1)
def initialize_options(self): # suppress(unused-function)
"""Set all options to their initial values."""
self._file_lines_cache = dict()
self.suppress_codes = list()
self.exclusions = list()
self.cache_directory = ""
self.stamp_directory = ""
self.disable_linters = list()
self.show_lint_files = 0
user_options = [ # suppress(unused-variable)
("suppress-codes=", None, """Error codes to suppress"""),
("exclusions=", None, """Glob expressions of files to exclude"""),
("disable-linters=", None, """Linters to disable"""),
("cache-directory=", None, """Where to store caches"""),
("stamp-directory=",
None,
"""Where to store stamps of completed jobs"""),
("show-lint-files", None, """Show files before running lint""")
]
# suppress(unused-variable)
description = ("""run linter checks using prospector, """
"""flake8 and pyroma""")
|
GeoPyTool/GeoPyTool | geopytool/Stereo.py | Stereo.lines | python | def lines(self, Width=1, Color='k'):
'''
read the Excel, then draw the wulf net and Plot points, job done~
'''
self.axes.clear()
# self.axes.set_xlim(-90, 450)
self.axes.set_ylim(0, 90)
titles = list('NWSE')
titles = ['N', '330', '300', 'W', '240', '210', 'S', '150', '120', 'E', '60', '30']
self.n = len(titles)
self.angles = np.arange(90, 90 + 360, 360.0 / self.n)
self.angles = np.array([90., 120., 150., 180., 210., 240., 270., 300., 330.,
360., 30., 60.])
self.axes.set_thetagrids(self.angles, labels=titles, fontsize=14)
raw = self._df
Data = []
Labels = []
if (int(self.type_slider.value()) == 0):
list1 = [self.eqan(x) for x in range(15, 90, 15)]
else:
list1 = [self.eqar(x) for x in range(15, 90, 15)]
list2 = [str(x) for x in range(15, 90, 15)]
self.axes.set_rgrids(list1, list2)
for i in range(len(raw)):
Data.append([raw.at[i, 'Dip'], raw.at[i, 'Dip-Angle'], raw.at[i, 'Color'],
raw.at[i, 'Width'], raw.at[i, 'Alpha'], raw.at[i, 'Label']])
Dip = raw.at[i, 'Dip']
Dip_Angle = raw.at[i, 'Dip-Angle']
Label = raw.at[i, 'Label']
if (Label not in Labels):
Labels.append(Label)
else:
Label = ''
Width = 1
Color = 'red'
Alpha = 0.8
Marker = 'o'
Size = 50
Setting = [Width, Color, Alpha, Marker, Size]
Width = raw.at[i, 'Width']
Color = raw.at[i, 'Color']
Alpha = raw.at[i, 'Alpha']
Marker = raw.at[i, 'Marker']
Size = raw.at[i, 'Size']
if (Color not in Setting or Color != ''):
Width = raw.at[i, 'Width']
Color = raw.at[i, 'Color']
Alpha = raw.at[i, 'Alpha']
Marker = raw.at[i, 'Marker']
Size = raw.at[i, 'Size']
Setting = [Width, Color, Alpha, Marker, Size]
r = np.arange(Dip - 90, Dip + 91, 1)
BearR = [np.radians(-A + 90) for A in r]
if (int(self.type_slider.value()) == 0):
Line = (self.eqan(self.getangular(Dip_Angle, Dip, r)))
else:
Line = (self.eqar(self.getangular(Dip_Angle, Dip, r)))
self.axes.plot(BearR, Line, color=Color, linewidth=Width, alpha=Alpha, label=Label)
# self.axes.thetagrids(range(360 + 90, 0 + 90, -30), [str(x) for x in range(0, 360, 30)])
if (self.legend_cb.isChecked()):
self.axes.legend(bbox_to_anchor=(1.5, 1), loc=2, borderaxespad=0, prop=fontprop) | read the Excel, then draw the wulf net and Plot points, job done~ | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/Stereo.py#L142-L222 | null | class Stereo(AppForm):
reference = 'Zhou, J. B., Zeng, Z. X., and Yuan, J. R., 2003, THE DESIGN AND DEVELOPMENT OF THE SOFTWARE STRUCKIT FOR STRUCTURAL GEOLOGY: Journal of Changchun University of Science & Technology, v. 33, no. 3, p. 276-281.'
_df = pd.DataFrame()
_changed = False
xlabel = r''
ylabel = r''
def __init__(self, parent=None, df=pd.DataFrame()):
QMainWindow.__init__(self, parent)
self.setWindowTitle('Stereo Net Projection')
self._df = df
if (len(df) > 0):
self._changed = True
# print('DataFrame recieved to Stereo')
self.create_main_frame()
self.create_status_bar()
def create_main_frame(self):
self.resize(1000,600)
self.main_frame = QWidget()
self.dpi = 128
self.fig = Figure((8.0, 8.0), dpi=self.dpi)
self.fig.subplots_adjust(hspace=0.5, wspace=0.5, left=0.1, bottom=0.1, right=0.6, top=0.9)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.axes = self.fig.add_subplot(111, projection='polar')
# self.axes.set_xlim(-90, 450)
self.axes.set_ylim(0, 90)
# Create the navigation toolbar, tied to the canvas
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
# Other GUI controls
self.save_button = QPushButton('&Save')
self.save_button.clicked.connect(self.saveImgFile)
self.draw_button = QPushButton('&Reset')
self.draw_button.clicked.connect(self.Stereo)
self.legend_cb = QCheckBox('&Legend')
self.legend_cb.setChecked(True)
self.legend_cb.stateChanged.connect(self.Stereo) # int
self.tag_cb = QCheckBox('&Tag')
self.tag_cb.setChecked(True)
self.tag_cb.stateChanged.connect(self.Stereo) # int
self.shape_slider_left_label = QLabel('Line')
self.shape_slider_right_label = QLabel('Point')
self.shape_slider = QSlider(Qt.Horizontal)
self.shape_slider.setRange(0, 1)
self.shape_slider.setValue(0)
self.shape_slider.setTracking(True)
self.shape_slider.setTickPosition(QSlider.TicksBothSides)
self.shape_slider.valueChanged.connect(self.Stereo) # int
self.type_slider_left_label = QLabel('Wulff')
self.type_slider_right_label = QLabel('Schmidt')
self.type_slider = QSlider(Qt.Horizontal)
self.type_slider.setRange(0, 1)
self.type_slider.setValue(0)
self.type_slider.setTracking(True)
self.type_slider.setTickPosition(QSlider.TicksBothSides)
self.type_slider.valueChanged.connect(self.Stereo) # int
#
# Layout with box sizers
#
self.hbox = QHBoxLayout()
for w in [self.save_button,self.legend_cb, self.shape_slider_left_label, self.shape_slider, self.shape_slider_right_label,
self.type_slider_left_label,self.type_slider,self.type_slider_right_label]:
self.hbox.addWidget(w)
self.hbox.setAlignment(w, Qt.AlignVCenter)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.mpl_toolbar)
self.vbox.addWidget(self.canvas)
self.vbox.addLayout(self.hbox)
self.textbox = GrowingTextEdit(self)
self.textbox.setText(self.reference)
self.vbox.addWidget(self.textbox)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame)
w=self.width()
h=self.height()
self.shape_slider.setFixedWidth(w/20)
self.type_slider.setFixedWidth(w/20)
def eqar(self, A):
return (2 ** .5) * 90 * np.sin(np.pi * (90. - A) / (2. * 180.))
def eqan(self, A):
return 90 * np.tan(np.pi * (90. - A) / (2. * 180.))
def getangular(self, A, B, C):
a = np.radians(A)
b = np.radians(B)
c = np.radians(C)
result = np.arctan((np.tan(a)) * np.cos(np.abs(b - c)))
result = np.rad2deg(result)
return result
def Trans(self, S=(0, 100, 110), D=(0, 30, 40)):
a = []
b = []
for i in S:
a.append(np.radians(90 - i))
for i in D:
b.append(self.eqar(i))
return (a, b)
def points(self, Width=1, Color='k'):
'''
read the Excel, then draw the schmidt net and Plot points, job done~
'''
self.axes.clear()
# self.axes.set_xlim(-90, 450)
self.axes.set_ylim(0, 90)
titles = list('NWSE')
titles = ['N', '330', '300', 'W', '240', '210', 'S', '150', '120', 'E', '60', '30']
self.n = len(titles)
self.angles = np.arange(90, 90 + 360, 360.0 / self.n)
self.angles = np.array([90., 120., 150., 180., 210., 240., 270., 300., 330.,
360., 30., 60.])
self.axes.set_thetagrids(self.angles, labels=titles, fontsize=14)
raw = self._df
Data = []
Labels = []
if (int(self.type_slider.value()) == 0):
list1 = [self.eqan(x) for x in range(15, 90, 15)]
else:
list1 = [self.eqar(x) for x in range(15, 90, 15)]
list2 = [str(x) for x in range(15, 90, 15)]
self.axes.set_rgrids(list1, list2)
for i in range(len(raw)):
Data.append(
[raw.at[i, 'Dip'], raw.at[i, 'Dip-Angle'], raw.at[i, 'Color'],
raw.at[i, 'Width'], raw.at[i, 'Alpha'], raw.at[i, 'Marker'], raw.at[i, 'Label']])
Dip = raw.at[i, 'Dip']
Dip_Angle = raw.at[i, 'Dip-Angle']
Label = raw.at[i, 'Label']
if (Label not in Labels):
Labels.append(Label)
else:
Label = ''
Width = 1
Color = 'red'
Alpha = 0.8
Marker = 'o'
Size = 50
Setting = [Width, Color, Alpha, Marker, Size]
Width = raw.at[i, 'Width']
Color = raw.at[i, 'Color']
Alpha = raw.at[i, 'Alpha']
Marker = raw.at[i, 'Marker']
Size = raw.at[i, 'Size']
if (Color not in Setting or Color != ''):
Width = raw.at[i, 'Width']
Color = raw.at[i, 'Color']
Alpha = raw.at[i, 'Alpha']
Marker = raw.at[i, 'Marker']
Size = raw.at[i, 'Size']
Setting = [Width, Color, Alpha, Marker, Size]
if (int(self.type_slider.value()) == 0):
self.axes.scatter(np.radians(90 - Dip), self.eqan(Dip_Angle), marker=Marker, s=Size, color=Color,
alpha=Alpha,
label=Label, edgecolors='black')
else:
self.axes.scatter(np.radians(90 - Dip), self.eqar(Dip_Angle), marker=Marker, s=Size, color=Color,
alpha=Alpha,
label=Label, edgecolors='black')
# plt.plot(120, 30, color='K', linewidth=4, alpha=Alpha, marker='o')
# self.axes.thetagrids(range(360 + 90, 0 + 90, -30), [str(x) for x in range(0, 360, 30)])
if (self.legend_cb.isChecked()):
self.axes.legend(bbox_to_anchor=(1.5, 1), loc=2, borderaxespad=0, prop=fontprop)
def Stereo(self):
self.Label = [u'N', u'S', u'W', u'E']
self.LabelPosition = []
if (int(self.shape_slider.value()) == 0):
self.lines()
else:
self.points()
self.canvas.draw()
|
GeoPyTool/GeoPyTool | Experimental/Alpah_Shape_2D.py | add_edge | python | def add_edge(edges, edge_points, coords, i, j):
if (i, j) in edges or (j, i) in edges:
# already added
return( edges.add((i, j)), edge_points.append(coords[[i, j]])) | Add a line between the i-th and j-th points,
if not in the list already | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/Experimental/Alpah_Shape_2D.py#L28-L35 | null | from shapely.ops import cascaded_union, polygonize
from scipy.spatial import Delaunay
import numpy as np
import math
import pylab as pl
import fiona
import shapely.geometry as geometry
from descartes import PolygonPatch
def plot_polygon(polygon):
fig = pl.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
margin = .3
print(polygon)
x_min, y_min, x_max, y_max = polygon.bounds
ax.set_xlim([x_min - margin, x_max + margin])
ax.set_ylim([y_min - margin, y_max + margin])
patch = PolygonPatch(polygon, fc='#999999',
ec='#000000', fill=True,
zorder=-1)
ax.add_patch(patch)
return fig
def alpha_shape(points, alpha):
"""
Compute the alpha shape (concave hull) of a set
of points.
@param points: Iterable container of points.
@param alpha: alpha value to influence the
gooeyness of the border. Smaller numbers
don't fall inward as much as larger numbers.
Too large, and you lose everything!
"""
if len(points) < 4:
# When you have a triangle, there is no sense
# in computing an alpha shape.
return geometry.MultiPoint(list(points)).convex_hull
#coords = np.array([point.coords[0] for point in points])
coords = np.array(points)
print(coords)
tri = Delaunay(coords)
edges = set()
edge_points = []
# loop over triangles:
# ia, ib, ic = indices of corner points of the
# triangle
for ia, ib, ic in tri.vertices:
pa = coords[ia]
pb = coords[ib]
pc = coords[ic]
# Lengths of sides of triangle
a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
# Semiperimeter of triangle
s = (a + b + c)/2.0
# Area of triangle by Heron's formula
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
circum_r = a*b*c/(4.0*area)
# Here's the radius filter.
#print circum_r
if circum_r < 1.0/alpha:
add_edge(edges, edge_points, coords, ia, ib)
add_edge(edges, edge_points, coords, ib, ic)
add_edge(edges, edge_points, coords, ic, ia)
m = geometry.MultiLineString(edge_points)
triangles = list(polygonize(m))
return (cascaded_union(triangles), edge_points)
print (cascaded_union(triangles), edge_points)
a = np.array([ 0.46421546, 0.50670312, 0.76935034, 0.75152631, 0.41167491,
0.75871446, 0.54695894, 0.36280667, 0.08900743, 0.32331662])
b = np.array([ 0.57476821, 0.34486742, 0.41292409, 0.95925496, 0.48904496,
0.69459014, 0.92621067, 0.18750462, 0.28832875, 0.85921044])
points=[]
for i in range(len(a)):
points.append([a[i],b[i]])
point_collection = geometry.MultiPoint(list(points))
point_collection.envelope
alpha = .4
concave_hull, edge_points = alpha_shape(points,alpha=alpha)
print(concave_hull)
_ = plot_polygon(point_collection.envelope)
_ = plot_polygon(concave_hull)
_ = pl.plot(a, b, 'o', color='#f16824')
pl.show()
|
GeoPyTool/GeoPyTool | Experimental/Alpah_Shape_2D.py | alpha_shape | python | def alpha_shape(points, alpha):
if len(points) < 4:
# When you have a triangle, there is no sense
# in computing an alpha shape.
return geometry.MultiPoint(list(points)).convex_hull
#coords = np.array([point.coords[0] for point in points])
coords = np.array(points)
print(coords)
tri = Delaunay(coords)
edges = set()
edge_points = []
# loop over triangles:
# ia, ib, ic = indices of corner points of the
# triangle
for ia, ib, ic in tri.vertices:
pa = coords[ia]
pb = coords[ib]
pc = coords[ic]
# Lengths of sides of triangle
a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
# Semiperimeter of triangle
s = (a + b + c)/2.0
# Area of triangle by Heron's formula
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
circum_r = a*b*c/(4.0*area)
# Here's the radius filter.
#print circum_r
if circum_r < 1.0/alpha:
add_edge(edges, edge_points, coords, ia, ib)
add_edge(edges, edge_points, coords, ib, ic)
add_edge(edges, edge_points, coords, ic, ia)
m = geometry.MultiLineString(edge_points)
triangles = list(polygonize(m))
return (cascaded_union(triangles), edge_points)
print (cascaded_union(triangles), edge_points) | Compute the alpha shape (concave hull) of a set
of points.
@param points: Iterable container of points.
@param alpha: alpha value to influence the
gooeyness of the border. Smaller numbers
don't fall inward as much as larger numbers.
Too large, and you lose everything! | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/Experimental/Alpah_Shape_2D.py#L39-L89 | [
"def add_edge(edges, edge_points, coords, i, j):\n \"\"\"\n Add a line between the i-th and j-th points,\n if not in the list already\n \"\"\"\n if (i, j) in edges or (j, i) in edges:\n # already added\n return( edges.add((i, j)), edge_points.append(coords[[i, j]]))\n"
] | from shapely.ops import cascaded_union, polygonize
from scipy.spatial import Delaunay
import numpy as np
import math
import pylab as pl
import fiona
import shapely.geometry as geometry
from descartes import PolygonPatch
def plot_polygon(polygon):
fig = pl.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
margin = .3
print(polygon)
x_min, y_min, x_max, y_max = polygon.bounds
ax.set_xlim([x_min - margin, x_max + margin])
ax.set_ylim([y_min - margin, y_max + margin])
patch = PolygonPatch(polygon, fc='#999999',
ec='#000000', fill=True,
zorder=-1)
ax.add_patch(patch)
return fig
def add_edge(edges, edge_points, coords, i, j):
"""
Add a line between the i-th and j-th points,
if not in the list already
"""
if (i, j) in edges or (j, i) in edges:
# already added
return( edges.add((i, j)), edge_points.append(coords[[i, j]]))
a = np.array([ 0.46421546, 0.50670312, 0.76935034, 0.75152631, 0.41167491,
0.75871446, 0.54695894, 0.36280667, 0.08900743, 0.32331662])
b = np.array([ 0.57476821, 0.34486742, 0.41292409, 0.95925496, 0.48904496,
0.69459014, 0.92621067, 0.18750462, 0.28832875, 0.85921044])
points=[]
for i in range(len(a)):
points.append([a[i],b[i]])
point_collection = geometry.MultiPoint(list(points))
point_collection.envelope
alpha = .4
concave_hull, edge_points = alpha_shape(points,alpha=alpha)
print(concave_hull)
_ = plot_polygon(point_collection.envelope)
_ = plot_polygon(concave_hull)
_ = pl.plot(a, b, 'o', color='#f16824')
pl.show()
|
GeoPyTool/GeoPyTool | geopytool/MyFA - Copy.py | MyFA.Distance_Calculation | python | def Distance_Calculation(self):
print(self.whole_labels)
distance_result={}
#distance_result[self.whole_labels[i]] = []
print(distance_result)
for i in range(len(self.whole_labels)):
#print(self.whole_labels[i], self.fa_result[self.result_to_fit.index == self.whole_labels[i]][0])
print( self.whole_labels[i], len(self.fa_result[self.result_to_fit.index == self.whole_labels[i]]))
pass
'''
for i in range(len(self.whole_labels)):
for j in range(len(self.whole_labels)):
if i ==j:
pass
else:
distance_result[self.whole_labels[i] + ' to ' + self.whole_labels[j]] = []
self.fa_result[self.result_to_fit.index == self.whole_labels[i]]
self.fa_result[self.result_to_fit.index == self.whole_labels[j]]
for m in range(len(self.fa_result[self.result_to_fit.index == self.whole_labels[i]])):
for n in range(len(self.fa_result[self.result_to_fit.index == self.whole_labels[j]])):
pass
self.fa_result[self.result_to_fit.index == self.whole_labels[i]][m]
#tmp_dist= self.Hsim_Distance(self.fa_result[self.result_to_fit.index == self.whole_labels[i]][m],self.fa_result[self.result_to_fit.index == self.whole_labels[j]][n])
#print(tmp_dist)
#distance_result[self.whole_labels[i] + ' to ' + self.whole_labels[j]].append(tmp_dist)
pass
'''
#print(self.fa_result)
try:
self.fa_data_to_test[self.data_to_test_to_fit.index == self.whole_labels[0], 0]
except Exception as e:
pass | for i in range(len(self.whole_labels)):
for j in range(len(self.whole_labels)):
if i ==j:
pass
else:
distance_result[self.whole_labels[i] + ' to ' + self.whole_labels[j]] = []
self.fa_result[self.result_to_fit.index == self.whole_labels[i]]
self.fa_result[self.result_to_fit.index == self.whole_labels[j]]
for m in range(len(self.fa_result[self.result_to_fit.index == self.whole_labels[i]])):
for n in range(len(self.fa_result[self.result_to_fit.index == self.whole_labels[j]])):
pass
self.fa_result[self.result_to_fit.index == self.whole_labels[i]][m]
#tmp_dist= self.Hsim_Distance(self.fa_result[self.result_to_fit.index == self.whole_labels[i]][m],self.fa_result[self.result_to_fit.index == self.whole_labels[j]][n])
#print(tmp_dist)
#distance_result[self.whole_labels[i] + ' to ' + self.whole_labels[j]].append(tmp_dist)
pass | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/MyFA - Copy.py#L348-L395 | null | class MyFA(AppForm):
Lines = []
Tags = []
WholeData = []
settings_backup=pd.DataFrame()
description = 'PCA'
unuseful = ['Name',
'Mineral',
'Author',
'DataType',
'Label',
'Marker',
'Color',
'Size',
'Alpha',
'Style',
'Width',
'Tag']
data_to_test=pd.DataFrame()
switched = False
text_result = ''
whole_labels=[]
fa = FactorAnalysis()
n=6
def __init__(self, parent=None, df=pd.DataFrame()):
QMainWindow.__init__(self, parent)
self._df = df
if (len(df) > 0):
self._changed = True
# print('DataFrame recieved to FA')
self.settings_backup = self._df
ItemsToTest = ['Label','Number', 'Tag', 'Name', 'Author', 'DataType', 'Marker', 'Color', 'Size', 'Alpha',
'Style', 'Width']
for i in self._df.columns.values.tolist():
if i not in ItemsToTest:
self.settings_backup = self.settings_backup.drop(i, 1)
print(self.settings_backup)
self.result_to_fit= self.Slim(self._df)
try:
self.fa.fit(self.result_to_fit.values)
self.comp = (self.fa.components_)
self.n = len(self.comp)
except Exception as e:
self.ErrorEvent(text=repr(e))
self.create_main_frame()
def create_main_frame(self):
self.resize(800,800)
self.main_frame = QWidget()
self.dpi = 128
self.fig = Figure((8.0, 6.0), dpi=self.dpi)
self.setWindowTitle('Factor Analysis')
self.fig = plt.figure(figsize=(12, 6))
self.fig.subplots_adjust(hspace=0.5, wspace=0.5, left=0.1, bottom=0.1, right=0.9, top=0.9)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.legend_cb = QCheckBox('&Legend')
self.legend_cb.setChecked(True)
self.legend_cb.stateChanged.connect(self.Key_Func) # int
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
# Other GUI controls
self.save_picture_button = QPushButton('&Save Picture')
self.save_picture_button.clicked.connect(self.saveImgFile)
self.save_result_button = QPushButton('&Save FA Result')
self.save_result_button.clicked.connect(self.saveResult)
self.save_Para_button = QPushButton('&Save FA Para')
self.save_Para_button.clicked.connect(self.savePara)
self.load_data_button = QPushButton('&Load Data to Test')
self.load_data_button.clicked.connect(self.loadDataToTest)
self.switch_button = QPushButton('&Switch to 2D')
self.switch_button.clicked.connect(self.switch)
self.x_element = QSlider(Qt.Horizontal)
self.x_element.setRange(0, self.n - 1)
self.x_element.setValue(0)
self.x_element.setTracking(True)
self.x_element.setTickPosition(QSlider.TicksBothSides)
self.x_element.valueChanged.connect(self.Key_Func) # int
self.x_element_label = QLabel('component')
self.y_element = QSlider(Qt.Horizontal)
self.y_element.setRange(0, self.n - 1)
self.y_element.setValue(1)
self.y_element.setTracking(True)
self.y_element.setTickPosition(QSlider.TicksBothSides)
self.y_element.valueChanged.connect(self.Key_Func) # int
self.y_element_label = QLabel('component')
self.z_element = QSlider(Qt.Horizontal)
self.z_element.setRange(0, self.n - 1)
self.z_element.setValue(2)
self.z_element.setTracking(True)
self.z_element.setTickPosition(QSlider.TicksBothSides)
self.z_element.valueChanged.connect(self.Key_Func) # int
self.z_element_label = QLabel('component')
self.vbox = QVBoxLayout()
self.hbox = QHBoxLayout()
self.hbox0 = QHBoxLayout()
self.hbox1 = QHBoxLayout()
self.hbox2 = QHBoxLayout()
self.hbox3 = QHBoxLayout()
self.hbox4 = QHBoxLayout()
self.vbox.addWidget(self.mpl_toolbar)
self.vbox.addWidget(self.canvas)
self.hbox.addWidget(self.legend_cb)
self.hbox.addWidget(self.switch_button)
self.hbox.addWidget(self.load_data_button)
self.hbox.addWidget(self.save_picture_button)
self.hbox.addWidget(self.save_result_button)
self.hbox.addWidget(self.save_Para_button)
self.vbox.addLayout(self.hbox)
self.vbox.addLayout(self.hbox0)
self.vbox.addLayout(self.hbox2)
self.vbox.addLayout(self.hbox3)
for w in [self.x_element_label, self.x_element]:
self.hbox2.addWidget(w)
self.hbox2.setAlignment(w, Qt.AlignVCenter)
for w in [self.y_element_label, self.y_element]:
self.hbox3.addWidget(w)
self.hbox3.setAlignment(w, Qt.AlignVCenter)
for w in [self.z_element_label,self.z_element]:
self.hbox4.addWidget(w)
self.hbox4.setAlignment(w, Qt.AlignVCenter)
if ( self.switched== False):
self.switch_button.setText('&Switch to 2D')
self.axes = Axes3D(self.fig, elev=-150, azim=110)
self.vbox.addLayout(self.hbox4)
else:
self.switch_button.setText('&Switch to 3D')
self.axes = self.fig.add_subplot(111)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame)
#self.show()
def switch(self):
self.switched = not(self.switched)
self.create_main_frame()
self.Key_Func()
def Key_Func(self):
a = int(self.x_element.value())
b = int(self.y_element.value())
c = int(self.z_element.value())
self.axes.clear()
self.fa.fit(self.result_to_fit.values)
self.comp = (self.fa.components_)
#self.text_result='N Components :' + str(n)+'N Components :' + str(comp)+ '\nExplained Variance Ratio :' + str(evr)+'\nExplained Variance :' + str(ev)
title=[]
for i in range(len(self.comp)):
title.append('Components No.'+ str(i+1))
self.nvs = zip(title, self.comp)
self.compdict = dict((title, self.comp) for title, self.comp in self.nvs)
self.Para=pd.DataFrame(self.compdict)
self.fa_result = self.fa.fit_transform(self.result_to_fit.values)
self.comp = (self.fa.components_)
#self.n = (self.fa.n_components_)
self.n = len(self.comp)
all_labels=[]
all_colors=[]
all_markers=[]
all_alpha=[]
for i in range(len(self._df)):
target =self._df.at[i, 'Label']
color = self._df.at[i, 'Color']
marker = self._df.at[i, 'Marker']
alpha = self._df.at[i, 'Alpha']
if target not in all_labels:
all_labels.append(target)
all_colors.append(color)
all_markers.append(marker)
all_alpha.append(alpha)
self.whole_labels = all_labels
if(len(self.data_to_test)>0):
contained = True
missing = 'Miss setting infor:'
for i in ['Label', 'Color', 'Marker', 'Alpha']:
if i not in self.data_to_test.columns.values.tolist():
contained = False
missing = missing +'\n' + i
if contained == True:
for i in self.data_to_test.columns.values.tolist():
if i not in self._df.columns.values.tolist():
self.data_to_test=self.data_to_test.drop(columns=i)
#print(self.data_to_test)
test_labels=[]
test_colors=[]
test_markers=[]
test_alpha=[]
for i in range(len(self.data_to_test)):
target = self.data_to_test.at[i, 'Label']
color = self.data_to_test.at[i, 'Color']
marker = self.data_to_test.at[i, 'Marker']
alpha = self.data_to_test.at[i, 'Alpha']
if target not in test_labels and target not in all_labels:
test_labels.append(target)
test_colors.append(color)
test_markers.append(marker)
test_alpha.append(alpha)
self.whole_labels = self.whole_labels +test_labels
self.data_to_test_to_fit= self.Slim(self.data_to_test)
self.load_settings_backup = self.data_to_test
Load_ItemsToTest = ['Label', 'Number', 'Tag', 'Name', 'Author', 'DataType', 'Marker', 'Color', 'Size',
'Alpha','Style', 'Width']
for i in self.data_to_test.columns.values.tolist():
if i not in Load_ItemsToTest:
self.load_settings_backup = self.load_settings_backup .drop(i, 1)
#print(self.data_to_test_to_fit)
#print(self.data_to_test_to_fit.shape)
try:
self.fa_data_to_test = self.fa.transform(self.data_to_test_to_fit)
self.load_result = pd.concat([self.load_settings_backup,pd.DataFrame(self.fa_data_to_test)], axis=1)
for i in range(len(test_labels)):
if (self.switched == False):
self.axes.scatter(self.fa_data_to_test[self.data_to_test_to_fit.index == test_labels[i], a],
self.fa_data_to_test[self.data_to_test_to_fit.index == test_labels[i], b],
self.fa_data_to_test[self.data_to_test_to_fit.index == test_labels[i], c],
color=test_colors[i],
marker=test_markers[i],
label=test_labels[i],
alpha=test_alpha[i])
else:
self.axes.scatter(self.fa_data_to_test[self.data_to_test_to_fit.index == test_labels[i], a],
self.fa_data_to_test[self.data_to_test_to_fit.index == test_labels[i], b],
color=test_colors[i],
marker=test_markers[i],
label=test_labels[i],
alpha=test_alpha[i])
except Exception as e:
self.ErrorEvent(text=repr(e))
else:
self.ErrorEvent(text=missing)
self.axes.set_xlabel("component no."+str(a+1))
self.x_element_label.setText("component no."+str(a+1))
self.axes.set_ylabel("component no."+str(b+1))
self.y_element_label.setText("component no."+str(b+1))
self.begin_result = pd.concat([self.settings_backup,pd.DataFrame(self.fa_result)], axis=1)
for i in range(len(all_labels)):
if (self.switched == False):
self.axes.scatter(self.fa_result[self.result_to_fit.index == all_labels[i], a],
self.fa_result[self.result_to_fit.index == all_labels[i], b],
self.fa_result[self.result_to_fit.index == all_labels[i], c],
color=all_colors[i],
marker=all_markers[i],
label=all_labels[i],
alpha=all_alpha[i])
self.axes.set_zlabel("component no." + str(c + 1))
self.z_element_label.setText("component no." + str(c + 1))
else:
self.axes.scatter(self.fa_result[self.result_to_fit.index == all_labels[i], a],
self.fa_result[self.result_to_fit.index == all_labels[i], b],
color=all_colors[i],
marker=all_markers[i],
label=all_labels[i],
alpha=all_alpha[i])
if (self.legend_cb.isChecked()):
self.axes.legend(loc=2,prop=fontprop)
self.result = pd.concat([self.begin_result , self.load_result], axis=0).set_index('Label')
self.canvas.draw()
def Distance_Calculation(self):
print(self.whole_labels)
distance_result={}
#distance_result[self.whole_labels[i]] = []
print(distance_result)
for i in range(len(self.whole_labels)):
#print(self.whole_labels[i], self.fa_result[self.result_to_fit.index == self.whole_labels[i]][0])
print( self.whole_labels[i], len(self.fa_result[self.result_to_fit.index == self.whole_labels[i]]))
pass
'''
for i in range(len(self.whole_labels)):
for j in range(len(self.whole_labels)):
if i ==j:
pass
else:
distance_result[self.whole_labels[i] + ' to ' + self.whole_labels[j]] = []
self.fa_result[self.result_to_fit.index == self.whole_labels[i]]
self.fa_result[self.result_to_fit.index == self.whole_labels[j]]
for m in range(len(self.fa_result[self.result_to_fit.index == self.whole_labels[i]])):
for n in range(len(self.fa_result[self.result_to_fit.index == self.whole_labels[j]])):
pass
self.fa_result[self.result_to_fit.index == self.whole_labels[i]][m]
#tmp_dist= self.Hsim_Distance(self.fa_result[self.result_to_fit.index == self.whole_labels[i]][m],self.fa_result[self.result_to_fit.index == self.whole_labels[j]][n])
#print(tmp_dist)
#distance_result[self.whole_labels[i] + ' to ' + self.whole_labels[j]].append(tmp_dist)
pass
'''
#print(self.fa_result)
try:
self.fa_data_to_test[self.data_to_test_to_fit.index == self.whole_labels[0], 0]
except Exception as e:
pass
|
GeoPyTool/GeoPyTool | geopytool/GLMultiDimension.py | GLMultiDimension.create_main_frame | python | def create_main_frame(self):
self.main_frame = QWidget()
#self.main_frame.setFixedSize(self.width(), self.width())
self.dpi = 128
self.ShapeGroups =200
self.view = gl.GLViewWidget()
#self.view = pg.PlotWidget()
#self.view.setFixedSize(self.width(),self.height())
self.view.setFixedSize(self.width(), self.width())
self.view.setParent(self.main_frame)
# Other GUI controls
self.save_button = QPushButton('&Save')
self.save_button.clicked.connect(self.saveImgFile)
self.draw_button = QPushButton('&Reset')
self.draw_button.clicked.connect(self.Reset)
self.load_button = QPushButton('&Load')
#self.load_button.clicked.connect(self.Load)
self.fit_cb= QCheckBox('&PolyFit')
self.fit_cb.setChecked(False)
self.fit_cb.stateChanged.connect(self.Magic) # int
self.fit_label = QLabel('Exp')
self.fit_seter = QLineEdit(self)
self.fit_seter.textChanged[str].connect(self.FitChanged)
self.shape_cb= QCheckBox('&Shape')
self.shape_cb.setChecked(False)
self.shape_cb.stateChanged.connect(self.Magic) # int
self.Normalize_cb = QCheckBox('&Normalize')
self.Normalize_cb.setChecked(False)
self.Normalize_cb.stateChanged.connect(self.Magic) # int
self.norm_slider_label = QLabel('Standard:' + self.NameChosen)
self.norm_slider = QSlider(Qt.Horizontal)
self.norm_slider.setRange(0, 4)
self.norm_slider.setValue(0)
self.norm_slider.setTracking(True)
self.norm_slider.setTickPosition(QSlider.TicksBothSides)
self.norm_slider.valueChanged.connect(self.Magic) # int
self.x_element = QSlider(Qt.Horizontal)
self.x_element.setRange(0, len(self.items) - 1)
self.x_element.setValue(0)
self.x_element.setTracking(True)
self.x_element.setTickPosition(QSlider.TicksBothSides)
self.x_element.valueChanged.connect(self.Magic) # int
self.x_element_label = QLabel('X')
self.logx_cb = QCheckBox('&Log')
self.logx_cb.setChecked(False)
self.logx_cb.stateChanged.connect(self.Magic) # int
self.y_element = QSlider(Qt.Horizontal)
self.y_element.setRange(0, len(self.items) - 1)
self.y_element.setValue(1)
self.y_element.setTracking(True)
self.y_element.setTickPosition(QSlider.TicksBothSides)
self.y_element.valueChanged.connect(self.Magic) # int
self.y_element_label = QLabel('Y')
self.logy_cb = QCheckBox('&Log')
self.logy_cb.setChecked(False)
self.logy_cb.stateChanged.connect(self.Magic) # int
self.z_element = QSlider(Qt.Horizontal)
self.z_element.setRange(0, len(self.items) - 1)
self.z_element.setValue(2)
self.z_element.setTracking(True)
self.z_element.setTickPosition(QSlider.TicksBothSides)
self.z_element.valueChanged.connect(self.Magic) # int
self.z_element_label = QLabel('Z')
self.logz_cb = QCheckBox('&Log')
self.logz_cb.setChecked(False)
self.logz_cb.stateChanged.connect(self.Magic) # int
self.xlim_seter_left_label = QLabel('Xleft')
self.xlim_seter_left = QLineEdit(self)
self.xlim_seter_left.textChanged[str].connect(self.XleftChanged)
self.xlim_seter_right_label = QLabel('Xright')
self.xlim_seter_right = QLineEdit(self)
self.xlim_seter_right.textChanged[str].connect(self.XrightChanged)
self.ylim_seter_down_label = QLabel('Ydown')
self.ylim_seter_down = QLineEdit(self)
self.ylim_seter_down.textChanged[str].connect(self.YdownChanged)
self.ylim_seter_up_label = QLabel('Yup')
self.ylim_seter_up = QLineEdit(self)
self.ylim_seter_up.textChanged[str].connect(self.YupChanged)
self.hbox0 = QHBoxLayout()
self.hbox1 = QHBoxLayout()
self.hbox2 = QHBoxLayout()
self.hbox3 = QHBoxLayout()
self.hbox4 = QHBoxLayout()
self.hbox5 = QHBoxLayout()
self.hbox6 = QHBoxLayout()
self.hbox7 = QHBoxLayout()
'''
for w in [self.fit_cb,self.fit_label, self.fit_seter,self.xlim_seter_left_label,self.xlim_seter_left,self.xlim_seter_right_label,self.xlim_seter_right,self.ylim_seter_down_label,self.ylim_seter_down,self.ylim_seter_up_label,self.ylim_seter_up,self.shape_cb]:
self.hbox0.addWidget(w)
self.hbox0.setAlignment(w, Qt.AlignVCenter)
'''
for w in [self.view]:
self.hbox0.addWidget(w)
self.hbox0.setAlignment(w, Qt.AlignVCenter)
for w in [self.Normalize_cb, self.norm_slider_label, self.norm_slider]:
self.hbox1.addWidget(w)
self.hbox1.setAlignment(w, Qt.AlignVCenter)
for w in [self.logx_cb, self.x_element_label, self.x_element]:
self.hbox2.addWidget(w)
self.hbox2.setAlignment(w, Qt.AlignVCenter)
for w in [self.logy_cb, self.y_element_label, self.y_element]:
self.hbox3.addWidget(w)
self.hbox3.setAlignment(w, Qt.AlignVCenter)
for w in [self.logz_cb, self.z_element_label, self.z_element]:
self.hbox4.addWidget(w)
self.hbox4.setAlignment(w, Qt.AlignVCenter)
self.vbox = QVBoxLayout()
#self.vbox.addWidget(self.view)
self.vbox.addLayout(self.hbox0)
self.vbox.addLayout(self.hbox1)
self.vbox.addLayout(self.hbox2)
self.vbox.addLayout(self.hbox3)
self.vbox.addLayout(self.hbox4)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame) | for w in [self.fit_cb,self.fit_label, self.fit_seter,self.xlim_seter_left_label,self.xlim_seter_left,self.xlim_seter_right_label,self.xlim_seter_right,self.ylim_seter_down_label,self.ylim_seter_down,self.ylim_seter_up_label,self.ylim_seter_up,self.shape_cb]:
self.hbox0.addWidget(w)
self.hbox0.setAlignment(w, Qt.AlignVCenter) | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/GLMultiDimension.py#L125-L291 | null | class GLMultiDimension(AppForm):
Element = [u'Cs', u'Tl', u'Rb', u'Ba', u'W', u'Th', u'U', u'Nb', u'Ta', u'K', u'La', u'Ce', u'Pb', u'Pr', u'Mo',
u'Sr', u'P', u'Nd', u'F', u'Sm', u'Zr', u'Hf', u'Eu', u'Sn', u'Sb', u'Ti', u'Gd', u'Tb', u'Dy',
u'Li',
u'Y', u'Ho', u'Er', u'Tm', u'Yb', u'Lu']
StandardsName = ['OIB', 'EMORB', 'C1', 'PM', 'NMORB']
NameChosen = 'OIB'
Standards = {
'OIB': {'Cs': 0.387, 'Tl': 0.077, 'Rb': 31, 'Ba': 350, 'W': 0.56, 'Th': 4, 'U': 1.02, 'Nb': 48, 'Ta': 2.7,
'K': 12000, 'La': 37, 'Ce': 80, 'Pb': 3.2, 'Pr': 9.7, 'Mo': 2.4, 'Sr': 660, 'P': 2700, 'Nd': 38.5,
'F': 1150, 'Sm': 10, 'Zr': 280, 'Hf': 7.8, 'Eu': 3, 'Sn': 2.7, 'Sb': 0.03, 'Ti': 17200, 'Gd': 7.62,
'Tb': 1.05, 'Dy': 5.6, 'Li': 5.6, 'Y': 29, 'Ho': 1.06, 'Er': 2.62, 'Tm': 0.35, 'Yb': 2.16, 'Lu': 0.3},
'EMORB': {'Cs': 0.063, 'Tl': 0.013, 'Rb': 5.04, 'Ba': 57, 'W': 0.092, 'Th': 0.6, 'U': 0.18, 'Nb': 8.3,
'Ta': 0.47, 'K': 2100, 'La': 6.3, 'Ce': 15, 'Pb': 0.6, 'Pr': 2.05, 'Mo': 0.47, 'Sr': 155, 'P': 620,
'Nd': 9, 'F': 250, 'Sm': 2.6, 'Zr': 73, 'Hf': 2.03, 'Eu': 0.91, 'Sn': 0.8, 'Sb': 0.01, 'Ti': 6000,
'Gd': 2.97, 'Tb': 0.53, 'Dy': 3.55, 'Li': 3.5, 'Y': 22, 'Ho': 0.79, 'Er': 2.31, 'Tm': 0.356,
'Yb': 2.37, 'Lu': 0.354},
'C1': {'Cs': 0.188, 'Tl': 0.14, 'Rb': 2.32, 'Ba': 2.41, 'W': 0.095, 'Th': 0.029, 'U': 0.008, 'Nb': 0.246,
'Ta': 0.014, 'K': 545, 'La': 0.237, 'Ce': 0.612, 'Pb': 2.47, 'Pr': 0.095, 'Mo': 0.92, 'Sr': 7.26,
'P': 1220, 'Nd': 0.467, 'F': 60.7, 'Sm': 0.153, 'Zr': 3.87, 'Hf': 0.1066, 'Eu': 0.058, 'Sn': 1.72,
'Sb': 0.16, 'Ti': 445, 'Gd': 0.2055, 'Tb': 0.0374, 'Dy': 0.254, 'Li': 1.57, 'Y': 1.57, 'Ho': 0.0566,
'Er': 0.1655, 'Tm': 0.0255, 'Yb': 0.17, 'Lu': 0.0254},
'PM': {'Cs': 0.032, 'Tl': 0.005, 'Rb': 0.635, 'Ba': 6.989, 'W': 0.02, 'Th': 0.085, 'U': 0.021, 'Nb': 0.713,
'Ta': 0.041, 'K': 250, 'La': 0.687, 'Ce': 1.775, 'Pb': 0.185, 'Pr': 0.276, 'Mo': 0.063, 'Sr': 21.1,
'P': 95, 'Nd': 1.354, 'F': 26, 'Sm': 0.444, 'Zr': 11.2, 'Hf': 0.309, 'Eu': 0.168, 'Sn': 0.17,
'Sb': 0.005, 'Ti': 1300, 'Gd': 0.596, 'Tb': 0.108, 'Dy': 0.737, 'Li': 1.6, 'Y': 4.55, 'Ho': 0.164,
'Er': 0.48, 'Tm': 0.074, 'Yb': 0.493, 'Lu': 0.074},
'NMORB': {'Cs': 0.007, 'Tl': 0.0014, 'Rb': 0.56, 'Ba': 6.3, 'W': 0.01, 'Th': 0.12, 'U': 0.047, 'Nb': 2.33,
'Ta': 0.132, 'K': 600, 'La': 2.5, 'Ce': 7.5, 'Pb': 0.3, 'Pr': 1.32, 'Mo': 0.31, 'Sr': 90, 'P': 510,
'Nd': 7.3, 'F': 210, 'Sm': 2.63, 'Zr': 74, 'Hf': 2.05, 'Eu': 1.02, 'Sn': 1.1, 'Sb': 0.01, 'Ti': 7600,
'Gd': 3.68, 'Tb': 0.67, 'Dy': 4.55, 'Li': 4.3, 'Y': 28, 'Ho': 1.01, 'Er': 2.97, 'Tm': 0.456,
'Yb': 3.05, 'Lu': 0.455}, }
Lines = []
Tags = []
xlabel = 'x'
ylabel = 'y'
zlabel = 'z'
description = 'X-Y- diagram'
unuseful = ['Name',
'Author',
'DataType',
'Label',
'Marker',
'Color',
'Size',
'Alpha',
'Style',
'Width',
'Type',
'Tag']
width_plot = 100.0
height_plot = 100.0
depth_plot= 100.0
width_load = width_plot
height_load = height_plot
depth_load = depth_plot
polygon = []
polyline = []
line = []
strgons = []
strlines = []
strpolylines = []
extent = 0
Left = 0
Right = 0
Up = 0
Down = 0
FitLevel=3
FadeGroups=100
ShapeGroups=200
Xleft,Xright,Ydown,Yup,Ztail,Zhead=0,0,0,0,0,0
LimSet= False
def __init__(self, parent=None, df=pd.DataFrame()):
QMainWindow.__init__(self, parent)
self.setWindowTitle(self.description)
self.items = []
self._df = df
if (len(df) > 0):
self._changed = True
# print('DataFrame recieved to GLMultiDimension')
self.raw = df
self.rawitems = self.raw.columns.values.tolist()
for i in self.rawitems:
if i not in self.unuseful:
self.items.append(i)
else:
pass
self.create_main_frame()
self.create_status_bar()
self.polygon = 0
self.polyline = 0
self.flag = 0
def Read(self, inpoints):
points = []
for i in inpoints:
points.append(i.split())
result = []
for i in points:
for l in range(len(i)):
a = float((i[l].split(','))[0])
a = a * self.x_scale
b = float((i[l].split(','))[1])
b = (self.height_load - b) * self.y_scale
result.append((a, b))
return (result)
def Load(self):
fileName, filetype = QFileDialog.getOpenFileName(self,
'选取文件',
'~/',
'PNG Files (*.png);;JPG Files (*.jpg);;SVG Files (*.svg)') # 设置文件扩展名过滤,注意用双分号间隔
print(fileName, '\t', filetype)
if ('svg' in fileName):
doc = minidom.parse(fileName) # parseString also exists
polygon_points = [path.getAttribute('points') for path in doc.getElementsByTagName('polygon')]
polyline_points = [path.getAttribute('points') for path in doc.getElementsByTagName('polyline')]
svg_width = [path.getAttribute('width') for path in doc.getElementsByTagName('svg')]
svg_height = [path.getAttribute('height') for path in doc.getElementsByTagName('svg')]
# print(svg_width)
# print(svg_height)
digit = '01234567890.-'
width = svg_width[0].replace('px', '').replace('pt', '')
height = svg_height[0].replace('px', '').replace('pt', '')
self.width_load = float(width)
self.height_load = float(height)
soup = BeautifulSoup(open(fileName), 'lxml')
tmpgon = soup.find_all('polygon')
tmppolyline = soup.find_all('polyline')
tmptext = soup.find_all('text')
tmpline = soup.find_all('line')
tmppath = soup.find_all('path')
self.strgons = []
for i in tmpgon:
a = (str(i)).replace('\n', '').replace('\t', '')
m = BeautifulSoup(a, 'lxml')
k = m.polygon.attrs
self.strgons.append(k['points'].split())
self.strpolylines = []
for i in tmppolyline:
a = (str(i)).replace('\n', '').replace('\t', '')
m = BeautifulSoup(a, 'lxml')
k = m.polyline.attrs
self.strpolylines.append(k['points'].split())
self.strlines = []
for i in tmpline:
a = (str(i)).replace('\n', '').replace('\t', '')
m = BeautifulSoup(a, 'lxml')
k = m.line.attrs
a = str(k['x1']) + ',' + str(k['y1']) + ' ' + str(k['x2']) + ',' + str(k['y2'])
self.strlines.append(a.split())
self.strpath = []
for i in tmppath:
a = (str(i)).replace('\n', '').replace('\t', '')
m = BeautifulSoup(a, 'lxml')
k = m.path.attrs
self.strpath.append(k['d'].split())
# print(self.strpath)
self.polygon = []
for i in self.strgons:
m = self.Read(i)
m.append(m[0])
self.polygon.append(m)
self.polyline = []
for i in self.strpolylines:
m = self.Read(i)
# print('i: ',i,'\n m:',m)
self.polyline.append(m)
self.line = []
for i in self.strlines:
m = self.Read(i)
# print('i: ',i,'\n m:',m)
self.line.append(m)
elif ('png' in fileName or 'jpg' in fileName):
self.img = mpimg.imread(fileName)
self.flag = 1
self.Magic()
def Reset(self):
self.flag = 0
self.Magic()
def FitChanged(self, text):
w = 'Fit' + text
self.fit_label.setText(w)
self.fit_label.adjustSize()
try:
self.FitLevel = float(text)
except:
pass
self.Magic()
def XleftChanged(self,text):
if len(text)<1:
self.LimSet = False
else:
self.LimSet = True
w = 'Left ' + text
self.xlim_seter_left_label.setText(w)
self.xlim_seter_left_label.adjustSize()
try:
self.Xleft = float(text)
except:
pass
self.Magic()
def XrightChanged(self,text):
if len(text)<1:
self.LimSet = False
else:
self.LimSet = True
w = 'Right ' + text
self.xlim_seter_right_label.setText(w)
self.xlim_seter_right_label.adjustSize()
try:
self.Xright = float(text)
except:
pass
self.Magic()
def YdownChanged(self,text):
if len(text)<1:
self.LimSet = False
else:
self.LimSet = True
w = 'Down ' + text
self.ylim_seter_down_label.setText(w)
self.ylim_seter_down_label.adjustSize()
try:
self.Ydown = float(text)
except:
pass
self.Magic()
def YupChanged(self,text):
if len(text)<1:
self.LimSet = False
else:
self.LimSet =True
w = 'Up ' + text
self.ylim_seter_up_label.setText(w)
self.ylim_seter_up_label.adjustSize()
try:
self.Yup = float(text)
except:
pass
self.Magic()
def ShapeChanged(self, text):
w = 'Shape' + text
#self.shape_label.setText(w)
#self.shape_label.adjustSize()
try:
self.ShapeGroups = int(text)
except:
pass
self.Magic()
def GetASequence(self, head=0, tail= 200, count=10):
if count > 0:
result = np.arange(head, tail, (tail - head) / count)
else:
result = np.arange(head, tail, (tail - head) / 10)
return (result)
def Magic(self):
#self.view.setFixedSize(self.width(), self.width())
self.WholeData = []
self.x_scale = self.width_plot / self.width_load
self.y_scale = self.height_plot / self.height_load
self.z_scale = self.depth_plot / self.depth_load
# print(self.x_scale,' and ',self.x_scale)
raw = self._df
a = int(self.x_element.value())
b = int(self.y_element.value())
c = int(self.z_element.value())
self.x_element_label.setText(self.items[a])
self.y_element_label.setText(self.items[b])
self.z_element_label.setText(self.items[c])
if (self.Left != self.Right) and (self.Down != self.Up) and abs(self.Left) + abs(self.Right) + abs(
self.Down) + abs(self.Up) != 0:
self.extent = [self.Left, self.Right, self.Down, self.Up]
elif (self.Left == self.Right and abs(self.Left) + abs(self.Right) != 0):
reply = QMessageBox.warning(self, 'Warning', 'You set same value to Left and Right limits.')
self.extent = 0
elif (self.Down == self.Up and abs(self.Down) + abs(self.Up) != 0):
reply = QMessageBox.warning(self, 'Warning', 'You set same value to Up and Down limits.')
self.extent = 0
else:
self.extent = 0
standardnamechosen = self.StandardsName[int(self.norm_slider.value())]
standardchosen = self.Standards[standardnamechosen]
self.norm_slider_label.setText(standardnamechosen)
PointLabels = []
XtoDraw = []
YtoDraw = []
ZtoDraw = []
Colors=[]
Alphas=[]
Markers=[]
Names=[]
for i in range(len(raw)):
# raw.at[i, 'DataType'] == 'User' or raw.at[i, 'DataType'] == 'user' or raw.at[i, 'DataType'] == 'USER'
TmpLabel = ''
# self.WholeData.append(math.log(tmp, 10))
if (raw.at[i, 'Label'] in PointLabels or raw.at[i, 'Label'] == ''):
TmpLabel = ''
else:
PointLabels.append(raw.at[i, 'Label'])
TmpLabel = raw.at[i, 'Label']
x, y ,z = 0, 0, 0
xuse, yuse,zuse = 0, 0, 0
x, y,z = raw.at[i, self.items[a]], raw.at[i, self.items[b]],raw.at[i, self.items[c]]
try:
xuse = x
yuse = y
zuse = z
self.xlabel = self.items[a]
self.ylabel = self.items[b]
self.zlabel = self.items[c]
if (self.Normalize_cb.isChecked()):
self.xlabel = self.items[a] + ' Norm by ' + standardnamechosen
self.x_element_label.setText(self.xlabel)
self.ylabel = self.items[b] + ' Norm by ' + standardnamechosen
self.y_element_label.setText(self.ylabel)
self.zlabel = self.items[c] + ' Norm by ' + standardnamechosen
self.z_element_label.setText(self.zlabel)
if self.items[a] in self.Element:
xuse = xuse / standardchosen[self.items[a]]
if self.items[b] in self.Element:
yuse = yuse / standardchosen[self.items[b]]
if self.items[c] in self.Element:
zuse = zuse / standardchosen[self.items[c]]
if (self.logx_cb.isChecked()):
xuse = math.log(x, 10)
self.xlabel = '$log10$ ' + self.xlabel
if (self.logy_cb.isChecked()):
yuse = math.log(y, 10)
self.ylabel = '$log10$ ' + self.ylabel
if (self.logz_cb.isChecked()):
zuse = math.log(z, 10)
self.zlabel = '$log10$ ' + self.zlabel
XtoDraw.append(xuse)
YtoDraw.append(yuse)
ZtoDraw.append(zuse)
Colors.append(raw.at[i, 'Color'])
Alphas.append(raw.at[i, 'Alpha'])
Names.append(raw.at[i, 'Label'])
Markers.append(raw.at[i, 'Marker'])
except(ValueError):
pass
if self.LimSet==False:
self.Xleft, self.Xright, self.Ydown, self.Yup, self.Tail, self.Head = min(XtoDraw), max(XtoDraw), min(YtoDraw), max(YtoDraw), min(ZtoDraw), max(ZtoDraw)
xmin, xmax = min(XtoDraw), max(XtoDraw)
ymin, ymax = min(YtoDraw), max(YtoDraw)
zmin, zmax = min(ZtoDraw), max(ZtoDraw)
xmean = np.mean(XtoDraw)
ymean = np.mean(YtoDraw)
zmean = np.mean(ZtoDraw)
Xoriginal = np.arange(xmin, xmax, (xmax - xmin) / 10)
Yoriginal = np.arange(ymin, ymax, (ymax - ymin) / 10)
Zoriginal = np.arange(zmin, zmax, (zmax - zmin) / 10)
XonPlot = self.GetASequence(tail=self.ShapeGroups)
YonPlot = self.GetASequence(tail=self.ShapeGroups)
ZonPlot = self.GetASequence(tail=self.ShapeGroups)
XonStick = []
YonStick = []
ZonStick = []
for i in range(len(XonPlot)):
XonStick.append([XonPlot[i], Xoriginal[i]])
YonStick.append([YonPlot[i], Yoriginal[i]])
ZonStick.append([ZonPlot[i], Zoriginal[i]])
pass
#print(XtoDraw,'\n', YtoDraw,'\n', ZtoDraw)
toDf = {self.xlabel:XtoDraw,
self.ylabel:YtoDraw,
self.zlabel:ZtoDraw}
newdf = pd.DataFrame(toDf)
pos = newdf.as_matrix()
print(pos)
ThreeDimView = gl.GLScatterPlotItem(pos=pos, color=(100, 255, 255, 88), size=0.1, pxMode=False)
print(xmean,'\n', ymean,'\n', zmean,'\n')
self.view.pan(xmean, ymean, zmean)
xgrid = gl.GLGridItem(size=QtGui.QVector3D(10, 10, 1), color=1)
ygrid = gl.GLGridItem(size=QtGui.QVector3D(20, 20, 2), color=2)
zgrid = gl.GLGridItem(size=QtGui.QVector3D(30, 30, 3), color=3)
## rotate x and y grids to face the correct direction
xgrid.rotate(90, 0, 1, 0)
ygrid.rotate(90, 1, 0, 0)
xgrid.translate(xmean, ymean, zmean)
ygrid.translate(xmean, ymean, zmean)
zgrid.translate(xmean, ymean, zmean)
## scale each grid differently
'''
xgrid.scale(12.8, 12.8, 12.8)
ygrid.scale(12.8, 12.8, 12.8)
zgrid.scale(12.8, 12.8, 12.8)
'''
# xgrid.setTransform(xmean,ymean,zmean)
self.view.addItem(xgrid)
self.view.addItem(ygrid)
self.view.addItem(zgrid)
self.view.addItem(ThreeDimView)
|
GeoPyTool/GeoPyTool | geopytool/GLMultiDimension.py | GLMultiDimension.Magic | python | def Magic(self):
#self.view.setFixedSize(self.width(), self.width())
self.WholeData = []
self.x_scale = self.width_plot / self.width_load
self.y_scale = self.height_plot / self.height_load
self.z_scale = self.depth_plot / self.depth_load
# print(self.x_scale,' and ',self.x_scale)
raw = self._df
a = int(self.x_element.value())
b = int(self.y_element.value())
c = int(self.z_element.value())
self.x_element_label.setText(self.items[a])
self.y_element_label.setText(self.items[b])
self.z_element_label.setText(self.items[c])
if (self.Left != self.Right) and (self.Down != self.Up) and abs(self.Left) + abs(self.Right) + abs(
self.Down) + abs(self.Up) != 0:
self.extent = [self.Left, self.Right, self.Down, self.Up]
elif (self.Left == self.Right and abs(self.Left) + abs(self.Right) != 0):
reply = QMessageBox.warning(self, 'Warning', 'You set same value to Left and Right limits.')
self.extent = 0
elif (self.Down == self.Up and abs(self.Down) + abs(self.Up) != 0):
reply = QMessageBox.warning(self, 'Warning', 'You set same value to Up and Down limits.')
self.extent = 0
else:
self.extent = 0
standardnamechosen = self.StandardsName[int(self.norm_slider.value())]
standardchosen = self.Standards[standardnamechosen]
self.norm_slider_label.setText(standardnamechosen)
PointLabels = []
XtoDraw = []
YtoDraw = []
ZtoDraw = []
Colors=[]
Alphas=[]
Markers=[]
Names=[]
for i in range(len(raw)):
# raw.at[i, 'DataType'] == 'User' or raw.at[i, 'DataType'] == 'user' or raw.at[i, 'DataType'] == 'USER'
TmpLabel = ''
# self.WholeData.append(math.log(tmp, 10))
if (raw.at[i, 'Label'] in PointLabels or raw.at[i, 'Label'] == ''):
TmpLabel = ''
else:
PointLabels.append(raw.at[i, 'Label'])
TmpLabel = raw.at[i, 'Label']
x, y ,z = 0, 0, 0
xuse, yuse,zuse = 0, 0, 0
x, y,z = raw.at[i, self.items[a]], raw.at[i, self.items[b]],raw.at[i, self.items[c]]
try:
xuse = x
yuse = y
zuse = z
self.xlabel = self.items[a]
self.ylabel = self.items[b]
self.zlabel = self.items[c]
if (self.Normalize_cb.isChecked()):
self.xlabel = self.items[a] + ' Norm by ' + standardnamechosen
self.x_element_label.setText(self.xlabel)
self.ylabel = self.items[b] + ' Norm by ' + standardnamechosen
self.y_element_label.setText(self.ylabel)
self.zlabel = self.items[c] + ' Norm by ' + standardnamechosen
self.z_element_label.setText(self.zlabel)
if self.items[a] in self.Element:
xuse = xuse / standardchosen[self.items[a]]
if self.items[b] in self.Element:
yuse = yuse / standardchosen[self.items[b]]
if self.items[c] in self.Element:
zuse = zuse / standardchosen[self.items[c]]
if (self.logx_cb.isChecked()):
xuse = math.log(x, 10)
self.xlabel = '$log10$ ' + self.xlabel
if (self.logy_cb.isChecked()):
yuse = math.log(y, 10)
self.ylabel = '$log10$ ' + self.ylabel
if (self.logz_cb.isChecked()):
zuse = math.log(z, 10)
self.zlabel = '$log10$ ' + self.zlabel
XtoDraw.append(xuse)
YtoDraw.append(yuse)
ZtoDraw.append(zuse)
Colors.append(raw.at[i, 'Color'])
Alphas.append(raw.at[i, 'Alpha'])
Names.append(raw.at[i, 'Label'])
Markers.append(raw.at[i, 'Marker'])
except(ValueError):
pass
if self.LimSet==False:
self.Xleft, self.Xright, self.Ydown, self.Yup, self.Tail, self.Head = min(XtoDraw), max(XtoDraw), min(YtoDraw), max(YtoDraw), min(ZtoDraw), max(ZtoDraw)
xmin, xmax = min(XtoDraw), max(XtoDraw)
ymin, ymax = min(YtoDraw), max(YtoDraw)
zmin, zmax = min(ZtoDraw), max(ZtoDraw)
xmean = np.mean(XtoDraw)
ymean = np.mean(YtoDraw)
zmean = np.mean(ZtoDraw)
Xoriginal = np.arange(xmin, xmax, (xmax - xmin) / 10)
Yoriginal = np.arange(ymin, ymax, (ymax - ymin) / 10)
Zoriginal = np.arange(zmin, zmax, (zmax - zmin) / 10)
XonPlot = self.GetASequence(tail=self.ShapeGroups)
YonPlot = self.GetASequence(tail=self.ShapeGroups)
ZonPlot = self.GetASequence(tail=self.ShapeGroups)
XonStick = []
YonStick = []
ZonStick = []
for i in range(len(XonPlot)):
XonStick.append([XonPlot[i], Xoriginal[i]])
YonStick.append([YonPlot[i], Yoriginal[i]])
ZonStick.append([ZonPlot[i], Zoriginal[i]])
pass
#print(XtoDraw,'\n', YtoDraw,'\n', ZtoDraw)
toDf = {self.xlabel:XtoDraw,
self.ylabel:YtoDraw,
self.zlabel:ZtoDraw}
newdf = pd.DataFrame(toDf)
pos = newdf.as_matrix()
print(pos)
ThreeDimView = gl.GLScatterPlotItem(pos=pos, color=(100, 255, 255, 88), size=0.1, pxMode=False)
print(xmean,'\n', ymean,'\n', zmean,'\n')
self.view.pan(xmean, ymean, zmean)
xgrid = gl.GLGridItem(size=QtGui.QVector3D(10, 10, 1), color=1)
ygrid = gl.GLGridItem(size=QtGui.QVector3D(20, 20, 2), color=2)
zgrid = gl.GLGridItem(size=QtGui.QVector3D(30, 30, 3), color=3)
## rotate x and y grids to face the correct direction
xgrid.rotate(90, 0, 1, 0)
ygrid.rotate(90, 1, 0, 0)
xgrid.translate(xmean, ymean, zmean)
ygrid.translate(xmean, ymean, zmean)
zgrid.translate(xmean, ymean, zmean)
## scale each grid differently
'''
xgrid.scale(12.8, 12.8, 12.8)
ygrid.scale(12.8, 12.8, 12.8)
zgrid.scale(12.8, 12.8, 12.8)
'''
# xgrid.setTransform(xmean,ymean,zmean)
self.view.addItem(xgrid)
self.view.addItem(ygrid)
self.view.addItem(zgrid)
self.view.addItem(ThreeDimView) | xgrid.scale(12.8, 12.8, 12.8)
ygrid.scale(12.8, 12.8, 12.8)
zgrid.scale(12.8, 12.8, 12.8) | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/GLMultiDimension.py#L507-L727 | null | class GLMultiDimension(AppForm):
Element = [u'Cs', u'Tl', u'Rb', u'Ba', u'W', u'Th', u'U', u'Nb', u'Ta', u'K', u'La', u'Ce', u'Pb', u'Pr', u'Mo',
u'Sr', u'P', u'Nd', u'F', u'Sm', u'Zr', u'Hf', u'Eu', u'Sn', u'Sb', u'Ti', u'Gd', u'Tb', u'Dy',
u'Li',
u'Y', u'Ho', u'Er', u'Tm', u'Yb', u'Lu']
StandardsName = ['OIB', 'EMORB', 'C1', 'PM', 'NMORB']
NameChosen = 'OIB'
Standards = {
'OIB': {'Cs': 0.387, 'Tl': 0.077, 'Rb': 31, 'Ba': 350, 'W': 0.56, 'Th': 4, 'U': 1.02, 'Nb': 48, 'Ta': 2.7,
'K': 12000, 'La': 37, 'Ce': 80, 'Pb': 3.2, 'Pr': 9.7, 'Mo': 2.4, 'Sr': 660, 'P': 2700, 'Nd': 38.5,
'F': 1150, 'Sm': 10, 'Zr': 280, 'Hf': 7.8, 'Eu': 3, 'Sn': 2.7, 'Sb': 0.03, 'Ti': 17200, 'Gd': 7.62,
'Tb': 1.05, 'Dy': 5.6, 'Li': 5.6, 'Y': 29, 'Ho': 1.06, 'Er': 2.62, 'Tm': 0.35, 'Yb': 2.16, 'Lu': 0.3},
'EMORB': {'Cs': 0.063, 'Tl': 0.013, 'Rb': 5.04, 'Ba': 57, 'W': 0.092, 'Th': 0.6, 'U': 0.18, 'Nb': 8.3,
'Ta': 0.47, 'K': 2100, 'La': 6.3, 'Ce': 15, 'Pb': 0.6, 'Pr': 2.05, 'Mo': 0.47, 'Sr': 155, 'P': 620,
'Nd': 9, 'F': 250, 'Sm': 2.6, 'Zr': 73, 'Hf': 2.03, 'Eu': 0.91, 'Sn': 0.8, 'Sb': 0.01, 'Ti': 6000,
'Gd': 2.97, 'Tb': 0.53, 'Dy': 3.55, 'Li': 3.5, 'Y': 22, 'Ho': 0.79, 'Er': 2.31, 'Tm': 0.356,
'Yb': 2.37, 'Lu': 0.354},
'C1': {'Cs': 0.188, 'Tl': 0.14, 'Rb': 2.32, 'Ba': 2.41, 'W': 0.095, 'Th': 0.029, 'U': 0.008, 'Nb': 0.246,
'Ta': 0.014, 'K': 545, 'La': 0.237, 'Ce': 0.612, 'Pb': 2.47, 'Pr': 0.095, 'Mo': 0.92, 'Sr': 7.26,
'P': 1220, 'Nd': 0.467, 'F': 60.7, 'Sm': 0.153, 'Zr': 3.87, 'Hf': 0.1066, 'Eu': 0.058, 'Sn': 1.72,
'Sb': 0.16, 'Ti': 445, 'Gd': 0.2055, 'Tb': 0.0374, 'Dy': 0.254, 'Li': 1.57, 'Y': 1.57, 'Ho': 0.0566,
'Er': 0.1655, 'Tm': 0.0255, 'Yb': 0.17, 'Lu': 0.0254},
'PM': {'Cs': 0.032, 'Tl': 0.005, 'Rb': 0.635, 'Ba': 6.989, 'W': 0.02, 'Th': 0.085, 'U': 0.021, 'Nb': 0.713,
'Ta': 0.041, 'K': 250, 'La': 0.687, 'Ce': 1.775, 'Pb': 0.185, 'Pr': 0.276, 'Mo': 0.063, 'Sr': 21.1,
'P': 95, 'Nd': 1.354, 'F': 26, 'Sm': 0.444, 'Zr': 11.2, 'Hf': 0.309, 'Eu': 0.168, 'Sn': 0.17,
'Sb': 0.005, 'Ti': 1300, 'Gd': 0.596, 'Tb': 0.108, 'Dy': 0.737, 'Li': 1.6, 'Y': 4.55, 'Ho': 0.164,
'Er': 0.48, 'Tm': 0.074, 'Yb': 0.493, 'Lu': 0.074},
'NMORB': {'Cs': 0.007, 'Tl': 0.0014, 'Rb': 0.56, 'Ba': 6.3, 'W': 0.01, 'Th': 0.12, 'U': 0.047, 'Nb': 2.33,
'Ta': 0.132, 'K': 600, 'La': 2.5, 'Ce': 7.5, 'Pb': 0.3, 'Pr': 1.32, 'Mo': 0.31, 'Sr': 90, 'P': 510,
'Nd': 7.3, 'F': 210, 'Sm': 2.63, 'Zr': 74, 'Hf': 2.05, 'Eu': 1.02, 'Sn': 1.1, 'Sb': 0.01, 'Ti': 7600,
'Gd': 3.68, 'Tb': 0.67, 'Dy': 4.55, 'Li': 4.3, 'Y': 28, 'Ho': 1.01, 'Er': 2.97, 'Tm': 0.456,
'Yb': 3.05, 'Lu': 0.455}, }
Lines = []
Tags = []
xlabel = 'x'
ylabel = 'y'
zlabel = 'z'
description = 'X-Y- diagram'
unuseful = ['Name',
'Author',
'DataType',
'Label',
'Marker',
'Color',
'Size',
'Alpha',
'Style',
'Width',
'Type',
'Tag']
width_plot = 100.0
height_plot = 100.0
depth_plot= 100.0
width_load = width_plot
height_load = height_plot
depth_load = depth_plot
polygon = []
polyline = []
line = []
strgons = []
strlines = []
strpolylines = []
extent = 0
Left = 0
Right = 0
Up = 0
Down = 0
FitLevel=3
FadeGroups=100
ShapeGroups=200
Xleft,Xright,Ydown,Yup,Ztail,Zhead=0,0,0,0,0,0
LimSet= False
def __init__(self, parent=None, df=pd.DataFrame()):
QMainWindow.__init__(self, parent)
self.setWindowTitle(self.description)
self.items = []
self._df = df
if (len(df) > 0):
self._changed = True
# print('DataFrame recieved to GLMultiDimension')
self.raw = df
self.rawitems = self.raw.columns.values.tolist()
for i in self.rawitems:
if i not in self.unuseful:
self.items.append(i)
else:
pass
self.create_main_frame()
self.create_status_bar()
self.polygon = 0
self.polyline = 0
self.flag = 0
def create_main_frame(self):
self.main_frame = QWidget()
#self.main_frame.setFixedSize(self.width(), self.width())
self.dpi = 128
self.ShapeGroups =200
self.view = gl.GLViewWidget()
#self.view = pg.PlotWidget()
#self.view.setFixedSize(self.width(),self.height())
self.view.setFixedSize(self.width(), self.width())
self.view.setParent(self.main_frame)
# Other GUI controls
self.save_button = QPushButton('&Save')
self.save_button.clicked.connect(self.saveImgFile)
self.draw_button = QPushButton('&Reset')
self.draw_button.clicked.connect(self.Reset)
self.load_button = QPushButton('&Load')
#self.load_button.clicked.connect(self.Load)
self.fit_cb= QCheckBox('&PolyFit')
self.fit_cb.setChecked(False)
self.fit_cb.stateChanged.connect(self.Magic) # int
self.fit_label = QLabel('Exp')
self.fit_seter = QLineEdit(self)
self.fit_seter.textChanged[str].connect(self.FitChanged)
self.shape_cb= QCheckBox('&Shape')
self.shape_cb.setChecked(False)
self.shape_cb.stateChanged.connect(self.Magic) # int
self.Normalize_cb = QCheckBox('&Normalize')
self.Normalize_cb.setChecked(False)
self.Normalize_cb.stateChanged.connect(self.Magic) # int
self.norm_slider_label = QLabel('Standard:' + self.NameChosen)
self.norm_slider = QSlider(Qt.Horizontal)
self.norm_slider.setRange(0, 4)
self.norm_slider.setValue(0)
self.norm_slider.setTracking(True)
self.norm_slider.setTickPosition(QSlider.TicksBothSides)
self.norm_slider.valueChanged.connect(self.Magic) # int
self.x_element = QSlider(Qt.Horizontal)
self.x_element.setRange(0, len(self.items) - 1)
self.x_element.setValue(0)
self.x_element.setTracking(True)
self.x_element.setTickPosition(QSlider.TicksBothSides)
self.x_element.valueChanged.connect(self.Magic) # int
self.x_element_label = QLabel('X')
self.logx_cb = QCheckBox('&Log')
self.logx_cb.setChecked(False)
self.logx_cb.stateChanged.connect(self.Magic) # int
self.y_element = QSlider(Qt.Horizontal)
self.y_element.setRange(0, len(self.items) - 1)
self.y_element.setValue(1)
self.y_element.setTracking(True)
self.y_element.setTickPosition(QSlider.TicksBothSides)
self.y_element.valueChanged.connect(self.Magic) # int
self.y_element_label = QLabel('Y')
self.logy_cb = QCheckBox('&Log')
self.logy_cb.setChecked(False)
self.logy_cb.stateChanged.connect(self.Magic) # int
self.z_element = QSlider(Qt.Horizontal)
self.z_element.setRange(0, len(self.items) - 1)
self.z_element.setValue(2)
self.z_element.setTracking(True)
self.z_element.setTickPosition(QSlider.TicksBothSides)
self.z_element.valueChanged.connect(self.Magic) # int
self.z_element_label = QLabel('Z')
self.logz_cb = QCheckBox('&Log')
self.logz_cb.setChecked(False)
self.logz_cb.stateChanged.connect(self.Magic) # int
self.xlim_seter_left_label = QLabel('Xleft')
self.xlim_seter_left = QLineEdit(self)
self.xlim_seter_left.textChanged[str].connect(self.XleftChanged)
self.xlim_seter_right_label = QLabel('Xright')
self.xlim_seter_right = QLineEdit(self)
self.xlim_seter_right.textChanged[str].connect(self.XrightChanged)
self.ylim_seter_down_label = QLabel('Ydown')
self.ylim_seter_down = QLineEdit(self)
self.ylim_seter_down.textChanged[str].connect(self.YdownChanged)
self.ylim_seter_up_label = QLabel('Yup')
self.ylim_seter_up = QLineEdit(self)
self.ylim_seter_up.textChanged[str].connect(self.YupChanged)
self.hbox0 = QHBoxLayout()
self.hbox1 = QHBoxLayout()
self.hbox2 = QHBoxLayout()
self.hbox3 = QHBoxLayout()
self.hbox4 = QHBoxLayout()
self.hbox5 = QHBoxLayout()
self.hbox6 = QHBoxLayout()
self.hbox7 = QHBoxLayout()
'''
for w in [self.fit_cb,self.fit_label, self.fit_seter,self.xlim_seter_left_label,self.xlim_seter_left,self.xlim_seter_right_label,self.xlim_seter_right,self.ylim_seter_down_label,self.ylim_seter_down,self.ylim_seter_up_label,self.ylim_seter_up,self.shape_cb]:
self.hbox0.addWidget(w)
self.hbox0.setAlignment(w, Qt.AlignVCenter)
'''
for w in [self.view]:
self.hbox0.addWidget(w)
self.hbox0.setAlignment(w, Qt.AlignVCenter)
for w in [self.Normalize_cb, self.norm_slider_label, self.norm_slider]:
self.hbox1.addWidget(w)
self.hbox1.setAlignment(w, Qt.AlignVCenter)
for w in [self.logx_cb, self.x_element_label, self.x_element]:
self.hbox2.addWidget(w)
self.hbox2.setAlignment(w, Qt.AlignVCenter)
for w in [self.logy_cb, self.y_element_label, self.y_element]:
self.hbox3.addWidget(w)
self.hbox3.setAlignment(w, Qt.AlignVCenter)
for w in [self.logz_cb, self.z_element_label, self.z_element]:
self.hbox4.addWidget(w)
self.hbox4.setAlignment(w, Qt.AlignVCenter)
self.vbox = QVBoxLayout()
#self.vbox.addWidget(self.view)
self.vbox.addLayout(self.hbox0)
self.vbox.addLayout(self.hbox1)
self.vbox.addLayout(self.hbox2)
self.vbox.addLayout(self.hbox3)
self.vbox.addLayout(self.hbox4)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame)
def Read(self, inpoints):
points = []
for i in inpoints:
points.append(i.split())
result = []
for i in points:
for l in range(len(i)):
a = float((i[l].split(','))[0])
a = a * self.x_scale
b = float((i[l].split(','))[1])
b = (self.height_load - b) * self.y_scale
result.append((a, b))
return (result)
def Load(self):
fileName, filetype = QFileDialog.getOpenFileName(self,
'选取文件',
'~/',
'PNG Files (*.png);;JPG Files (*.jpg);;SVG Files (*.svg)') # 设置文件扩展名过滤,注意用双分号间隔
print(fileName, '\t', filetype)
if ('svg' in fileName):
doc = minidom.parse(fileName) # parseString also exists
polygon_points = [path.getAttribute('points') for path in doc.getElementsByTagName('polygon')]
polyline_points = [path.getAttribute('points') for path in doc.getElementsByTagName('polyline')]
svg_width = [path.getAttribute('width') for path in doc.getElementsByTagName('svg')]
svg_height = [path.getAttribute('height') for path in doc.getElementsByTagName('svg')]
# print(svg_width)
# print(svg_height)
digit = '01234567890.-'
width = svg_width[0].replace('px', '').replace('pt', '')
height = svg_height[0].replace('px', '').replace('pt', '')
self.width_load = float(width)
self.height_load = float(height)
soup = BeautifulSoup(open(fileName), 'lxml')
tmpgon = soup.find_all('polygon')
tmppolyline = soup.find_all('polyline')
tmptext = soup.find_all('text')
tmpline = soup.find_all('line')
tmppath = soup.find_all('path')
self.strgons = []
for i in tmpgon:
a = (str(i)).replace('\n', '').replace('\t', '')
m = BeautifulSoup(a, 'lxml')
k = m.polygon.attrs
self.strgons.append(k['points'].split())
self.strpolylines = []
for i in tmppolyline:
a = (str(i)).replace('\n', '').replace('\t', '')
m = BeautifulSoup(a, 'lxml')
k = m.polyline.attrs
self.strpolylines.append(k['points'].split())
self.strlines = []
for i in tmpline:
a = (str(i)).replace('\n', '').replace('\t', '')
m = BeautifulSoup(a, 'lxml')
k = m.line.attrs
a = str(k['x1']) + ',' + str(k['y1']) + ' ' + str(k['x2']) + ',' + str(k['y2'])
self.strlines.append(a.split())
self.strpath = []
for i in tmppath:
a = (str(i)).replace('\n', '').replace('\t', '')
m = BeautifulSoup(a, 'lxml')
k = m.path.attrs
self.strpath.append(k['d'].split())
# print(self.strpath)
self.polygon = []
for i in self.strgons:
m = self.Read(i)
m.append(m[0])
self.polygon.append(m)
self.polyline = []
for i in self.strpolylines:
m = self.Read(i)
# print('i: ',i,'\n m:',m)
self.polyline.append(m)
self.line = []
for i in self.strlines:
m = self.Read(i)
# print('i: ',i,'\n m:',m)
self.line.append(m)
elif ('png' in fileName or 'jpg' in fileName):
self.img = mpimg.imread(fileName)
self.flag = 1
self.Magic()
def Reset(self):
self.flag = 0
self.Magic()
def FitChanged(self, text):
w = 'Fit' + text
self.fit_label.setText(w)
self.fit_label.adjustSize()
try:
self.FitLevel = float(text)
except:
pass
self.Magic()
def XleftChanged(self,text):
if len(text)<1:
self.LimSet = False
else:
self.LimSet = True
w = 'Left ' + text
self.xlim_seter_left_label.setText(w)
self.xlim_seter_left_label.adjustSize()
try:
self.Xleft = float(text)
except:
pass
self.Magic()
def XrightChanged(self,text):
if len(text)<1:
self.LimSet = False
else:
self.LimSet = True
w = 'Right ' + text
self.xlim_seter_right_label.setText(w)
self.xlim_seter_right_label.adjustSize()
try:
self.Xright = float(text)
except:
pass
self.Magic()
def YdownChanged(self,text):
if len(text)<1:
self.LimSet = False
else:
self.LimSet = True
w = 'Down ' + text
self.ylim_seter_down_label.setText(w)
self.ylim_seter_down_label.adjustSize()
try:
self.Ydown = float(text)
except:
pass
self.Magic()
def YupChanged(self,text):
if len(text)<1:
self.LimSet = False
else:
self.LimSet =True
w = 'Up ' + text
self.ylim_seter_up_label.setText(w)
self.ylim_seter_up_label.adjustSize()
try:
self.Yup = float(text)
except:
pass
self.Magic()
def ShapeChanged(self, text):
w = 'Shape' + text
#self.shape_label.setText(w)
#self.shape_label.adjustSize()
try:
self.ShapeGroups = int(text)
except:
pass
self.Magic()
def GetASequence(self, head=0, tail= 200, count=10):
if count > 0:
result = np.arange(head, tail, (tail - head) / count)
else:
result = np.arange(head, tail, (tail - head) / 10)
return (result)
|
GeoPyTool/GeoPyTool | geopytool/XY.py | XY.create_main_frame | python | def create_main_frame(self):
self.resize(800, 800)
self.main_frame = QWidget()
self.dpi = 128
self.fig = Figure((8.0, 8.0), dpi=self.dpi)
self.fig.subplots_adjust(hspace=0.5, wspace=0.5, left=0.13, bottom=0.2, right=0.7, top=0.9)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.axes = self.fig.add_subplot(111)
# self.axes.hold(False)
# Create the navigation toolbar, tied to the canvas
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
# Other GUI controls
self.load_data_button = QPushButton('&Add Data to Compare')
self.load_data_button.clicked.connect(self.loadDataToTest)
self.save_plot_button = QPushButton('&Save IMG')
self.save_plot_button .clicked.connect(self.saveImgFile)
self.stat_button = QPushButton('&Show Stat')
self.stat_button.clicked.connect(self.Stat)
self.load_img_button = QPushButton('&Load Basemap')
self.load_img_button.clicked.connect(self.Load)
self.unload_img_button = QPushButton('&Unload Basemap')
self.unload_img_button.clicked.connect(self.Unload)
self.legend_cb = QCheckBox('&Legend')
self.legend_cb.setChecked(True)
self.legend_cb.stateChanged.connect(self.Magic) # int
self.show_load_data_cb = QCheckBox('&Show Loaded Data')
self.show_load_data_cb.setChecked(True)
self.show_load_data_cb.stateChanged.connect(self.Magic) # int
self.show_data_index_cb = QCheckBox('&Show Data Index')
self.show_data_index_cb.setChecked(False)
self.show_data_index_cb.stateChanged.connect(self.Magic) # int
self.hyperplane_cb= QCheckBox('&Hyperplane')
self.hyperplane_cb.setChecked(False)
self.hyperplane_cb.stateChanged.connect(self.Magic) # int
self.fit_cb= QCheckBox('&PolyFit')
self.fit_cb.setChecked(False)
self.fit_cb.stateChanged.connect(self.Magic) # int
self.fit_seter = QLineEdit(self)
self.fit_seter.textChanged[str].connect(self.FitChanged)
self.fit_slider_label = QLabel('y= f(x) EXP')
self.fit_slider = QSlider(Qt.Vertical)
self.fit_slider.setRange(0, 1)
self.fit_slider.setValue(0)
self.fit_slider.setTracking(True)
self.fit_slider.setTickPosition(QSlider.TicksBothSides)
self.fit_slider.valueChanged.connect(self.Magic) # int
self.shape_cb= QCheckBox('&Shape')
self.shape_cb.setChecked(False)
self.shape_cb.stateChanged.connect(self.Magic) # int
#self.shape_label = QLabel('Step')
#self.shape_seter = QLineEdit(self)
#self.shape_seter.textChanged[str].connect(self.ShapeChanged)
self.norm_cb = QCheckBox('&Norm')
self.norm_cb.setChecked(False)
self.norm_cb.stateChanged.connect(self.Magic) # int
self.standard_slider = QSlider(Qt.Horizontal)
self.standard_slider.setRange(0, len(self.StandardsName))
if len(self._given_Standard) > 0:
self.standard_slider.setValue(len(self.StandardsName))
self.right_label = QLabel("Self Defined Standard")
else:
self.standard_slider.setValue(0)
self.right_label = QLabel(self.StandardsName[int(self.standard_slider.value())])
self.standard_slider.setTracking(True)
self.standard_slider.setTickPosition(QSlider.TicksBothSides)
self.standard_slider.valueChanged.connect(self.Magic) # int
self.left_label= QLabel('Standard' )
self.x_element = QSlider(Qt.Horizontal)
self.x_element.setRange(0, len(self.items) - 1)
self.x_element.setValue(0)
self.x_element.setTracking(True)
self.x_element.setTickPosition(QSlider.TicksBothSides)
self.x_element.valueChanged.connect(self.ValueChooser) # int
self.x_seter = QLineEdit(self)
self.x_seter.textChanged[str].connect(self.LabelSeter)
#self.x_calculator = QLineEdit(self)
self.logx_cb = QCheckBox('&Log')
self.logx_cb.setChecked(False)
self.logx_cb.stateChanged.connect(self.Magic) # int
self.y_element = QSlider(Qt.Horizontal)
self.y_element.setRange(0, len(self.items) - 1)
self.y_element.setValue(1)
self.y_element.setTracking(True)
self.y_element.setTickPosition(QSlider.TicksBothSides)
self.y_element.valueChanged.connect(self.ValueChooser) # int
self.y_seter = QLineEdit(self)
self.y_seter.textChanged[str].connect(self.LabelSeter)
#self.y_calculator = QLineEdit(self)
self.logy_cb = QCheckBox('&Log')
self.logy_cb.setChecked(False)
self.logy_cb.stateChanged.connect(self.Magic) # int
self.hyperplane_cb= QCheckBox('&Hyperplane')
self.hyperplane_cb.setChecked(False)
self.hyperplane_cb.stateChanged.connect(self.Magic) # int
self.save_predict_button_selected = QPushButton('&Predict Selected')
self.save_predict_button_selected.clicked.connect(self.showPredictResultSelected)
self.save_predict_button = QPushButton('&Predict All')
self.save_predict_button.clicked.connect(self.showPredictResult)
self.load_data_button = QPushButton('&Add Data to Compare')
self.load_data_button.clicked.connect(self.loadDataToTest)
self.width_size_seter_label = QLabel('SVG Width')
self.width_size_seter = QLineEdit(self)
self.width_size_seter.textChanged[str].connect(self.WChanged)
self.height_size_seter_label = QLabel('SVG Height')
self.height_size_seter = QLineEdit(self)
self.height_size_seter.textChanged[str].connect(self.HChanged)
self.Left_size_seter_label = QLabel('PNG Left')
self.Left_size_seter = QLineEdit(self)
self.Left_size_seter.textChanged[str].connect(self.LeftChanged)
self.Right_size_seter_label = QLabel('PNG Right')
self.Right_size_seter = QLineEdit(self)
self.Right_size_seter.textChanged[str].connect(self.RightChanged)
self.Up_size_seter_label = QLabel('PNG Top')
self.Up_size_seter = QLineEdit(self)
self.Up_size_seter.textChanged[str].connect(self.UpChanged)
self.Down_size_seter_label = QLabel('PNG Bottom')
self.Down_size_seter = QLineEdit(self)
self.Down_size_seter.textChanged[str].connect(self.DownChanged)
#
# Layout with box sizers
#
self.hbox = QHBoxLayout()
self.hbox0 = QHBoxLayout()
self.hbox1 = QHBoxLayout()
self.hbox2 = QHBoxLayout()
self.hbox3 = QHBoxLayout()
self.hbox4 = QHBoxLayout()
self.hbox5 = QHBoxLayout()
w=self.width()
h=self.height()
#self.load_data_button.setFixedWidth(w/4)
self.kernel_select = QSlider(Qt.Horizontal)
self.kernel_select.setRange(0, len(self.kernel_list)-1)
self.kernel_select.setValue(0)
self.kernel_select.setTracking(True)
self.kernel_select.setTickPosition(QSlider.TicksBothSides)
self.kernel_select.valueChanged.connect(self.Magic) # int
self.kernel_select_label = QLabel('Kernel')
for w in [self.save_plot_button ,self.stat_button,self.load_data_button,self.save_predict_button,self.save_predict_button_selected]:
self.hbox.addWidget(w)
self.hbox.setAlignment(w, Qt.AlignVCenter)
for w in [self.legend_cb,self.show_load_data_cb,self.show_data_index_cb, self.norm_cb,self.shape_cb,self.hyperplane_cb,self.kernel_select_label,self.kernel_select]:
self.hbox0.addWidget(w)
self.hbox0.setAlignment(w, Qt.AlignVCenter)
for w in [self.left_label, self.standard_slider,self.right_label,self.fit_cb,self.fit_slider,self.fit_slider_label ,self.fit_seter]:
self.hbox1.addWidget(w)
self.hbox1.setAlignment(w, Qt.AlignVCenter)
for w in [self.logx_cb,self.x_seter, self.x_element]:
self.hbox2.addWidget(w)
self.hbox2.setAlignment(w, Qt.AlignVCenter)
for w in [self.logy_cb,self.y_seter, self.y_element]:
self.hbox3.addWidget(w)
self.hbox3.setAlignment(w, Qt.AlignVCenter)
for w in [self.load_img_button, self.width_size_seter_label, self.width_size_seter, self.height_size_seter_label,
self.height_size_seter]:
self.hbox4.addWidget(w)
self.hbox4.setAlignment(w, Qt.AlignLeft)
for w in [self.unload_img_button,self.Left_size_seter_label, self.Left_size_seter,
self.Right_size_seter_label, self.Right_size_seter,self.Down_size_seter_label, self.Down_size_seter,
self.Up_size_seter_label ,self.Up_size_seter]:
self.hbox5.addWidget(w)
self.hbox5.setAlignment(w, Qt.AlignLeft)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.mpl_toolbar)
self.vbox.addWidget(self.canvas)
self.vbox.addLayout(self.hbox)
self.vbox.addLayout(self.hbox0)
self.vbox.addLayout(self.hbox1)
self.vbox.addLayout(self.hbox2)
self.vbox.addLayout(self.hbox3)
self.vbox.addLayout(self.hbox4)
self.vbox.addLayout(self.hbox5)
self.textbox = GrowingTextEdit(self)
self.vbox.addWidget(self.textbox)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame)
w=self.width()
h=self.height()
self.x_seter.setFixedWidth(w/10)
self.y_seter.setFixedWidth(w/10)
'''
self.save_plot_button.setFixedWidth(w/10)
self.stat_button.setFixedWidth(w/10)
self.load_data_button.setFixedWidth(w/4)
self.save_predict_button_selected.setFixedWidth(w/4)
self.save_predict_button.setFixedWidth(w/4)
'''
self.standard_slider.setFixedWidth(w/5)
self.right_label.setFixedWidth(w/5)
self.fit_seter.setFixedWidth(w/20)
self.load_img_button.setFixedWidth(w/5)
self.unload_img_button.setFixedWidth(w/5)
self.width_size_seter_label.setFixedWidth(w/10)
self.height_size_seter_label.setFixedWidth(w/10)
self.width_size_seter.setMinimumWidth(w/20)
self.height_size_seter.setMinimumWidth(w/20)
self.Right_size_seter_label.setFixedWidth(w/10)
self.Left_size_seter_label.setFixedWidth(w/10)
self.Up_size_seter_label.setFixedWidth(w/10)
self.Down_size_seter_label.setFixedWidth(w/10)
self.Right_size_seter.setFixedWidth(w/20)
self.Left_size_seter.setFixedWidth(w/20)
self.Up_size_seter.setFixedWidth(w/20)
self.Down_size_seter.setFixedWidth(w/20) | self.save_plot_button.setFixedWidth(w/10)
self.stat_button.setFixedWidth(w/10)
self.load_data_button.setFixedWidth(w/4)
self.save_predict_button_selected.setFixedWidth(w/4)
self.save_predict_button.setFixedWidth(w/4) | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/XY.py#L176-L498 | null | class XY(AppForm):
Element = [u'Cs', u'Tl', u'Rb', u'Ba', u'W', u'Th', u'U', u'Nb', u'Ta', u'K', u'La', u'Ce', u'Pb', u'Pr', u'Mo',
u'Sr', u'P', u'Nd', u'F', u'Sm', u'Zr', u'Hf', u'Eu', u'Sn', u'Sb', u'Ti', u'Gd', u'Tb', u'Dy',
u'Li',
u'Y', u'Ho', u'Er', u'Tm', u'Yb', u'Lu']
StandardsName = ['PM', 'OIB', 'EMORB', 'C1', 'NMORB','UCC_Rudnick & Gao2003']
reference = 'Reference: Sun, S. S., and Mcdonough, W. F., 1989, UCC_Rudnick & Gao2003'
sentence =''
ContainNan = False
NameChosen = 'PM'
Standards = {
'PM': {'Cs': 0.032, 'Tl': 0.005, 'Rb': 0.635, 'Ba': 6.989, 'W': 0.02, 'Th': 0.085, 'U': 0.021, 'Nb': 0.713,
'Ta': 0.041, 'K': 250, 'La': 0.687, 'Ce': 1.775, 'Pb': 0.185, 'Pr': 0.276, 'Mo': 0.063, 'Sr': 21.1,
'P': 95, 'Nd': 1.354, 'F': 26, 'Sm': 0.444, 'Zr': 11.2, 'Hf': 0.309, 'Eu': 0.168, 'Sn': 0.17,
'Sb': 0.005, 'Ti': 1300, 'Gd': 0.596, 'Tb': 0.108, 'Dy': 0.737, 'Li': 1.6, 'Y': 4.55, 'Ho': 0.164,
'Er': 0.48, 'Tm': 0.074, 'Yb': 0.493, 'Lu': 0.074},
'OIB': {'Cs': 0.387, 'Tl': 0.077, 'Rb': 31, 'Ba': 350, 'W': 0.56, 'Th': 4, 'U': 1.02, 'Nb': 48, 'Ta': 2.7,
'K': 12000, 'La': 37, 'Ce': 80, 'Pb': 3.2, 'Pr': 9.7, 'Mo': 2.4, 'Sr': 660, 'P': 2700, 'Nd': 38.5,
'F': 1150, 'Sm': 10, 'Zr': 280, 'Hf': 7.8, 'Eu': 3, 'Sn': 2.7, 'Sb': 0.03, 'Ti': 17200, 'Gd': 7.62,
'Tb': 1.05, 'Dy': 5.6, 'Li': 5.6, 'Y': 29, 'Ho': 1.06, 'Er': 2.62, 'Tm': 0.35, 'Yb': 2.16, 'Lu': 0.3},
'EMORB': {'Cs': 0.063, 'Tl': 0.013, 'Rb': 5.04, 'Ba': 57, 'W': 0.092, 'Th': 0.6, 'U': 0.18, 'Nb': 8.3,
'Ta': 0.47, 'K': 2100, 'La': 6.3, 'Ce': 15, 'Pb': 0.6, 'Pr': 2.05, 'Mo': 0.47, 'Sr': 155, 'P': 620,
'Nd': 9, 'F': 250, 'Sm': 2.6, 'Zr': 73, 'Hf': 2.03, 'Eu': 0.91, 'Sn': 0.8, 'Sb': 0.01, 'Ti': 6000,
'Gd': 2.97, 'Tb': 0.53, 'Dy': 3.55, 'Li': 3.5, 'Y': 22, 'Ho': 0.79, 'Er': 2.31, 'Tm': 0.356,
'Yb': 2.37, 'Lu': 0.354},
'C1': {'Cs': 0.188, 'Tl': 0.14, 'Rb': 2.32, 'Ba': 2.41, 'W': 0.095, 'Th': 0.029, 'U': 0.008, 'Nb': 0.246,
'Ta': 0.014, 'K': 545, 'La': 0.237, 'Ce': 0.612, 'Pb': 2.47, 'Pr': 0.095, 'Mo': 0.92, 'Sr': 7.26,
'P': 1220, 'Nd': 0.467, 'F': 60.7, 'Sm': 0.153, 'Zr': 3.87, 'Hf': 0.1066, 'Eu': 0.058, 'Sn': 1.72,
'Sb': 0.16, 'Ti': 445, 'Gd': 0.2055, 'Tb': 0.0374, 'Dy': 0.254, 'Li': 1.57, 'Y': 1.57, 'Ho': 0.0566,
'Er': 0.1655, 'Tm': 0.0255, 'Yb': 0.17, 'Lu': 0.0254},
'NMORB': {'Cs': 0.007, 'Tl': 0.0014, 'Rb': 0.56, 'Ba': 6.3, 'W': 0.01, 'Th': 0.12, 'U': 0.047, 'Nb': 2.33,
'Ta': 0.132, 'K': 600, 'La': 2.5, 'Ce': 7.5, 'Pb': 0.3, 'Pr': 1.32, 'Mo': 0.31, 'Sr': 90, 'P': 510,
'Nd': 7.3, 'F': 210, 'Sm': 2.63, 'Zr': 74, 'Hf': 2.05, 'Eu': 1.02, 'Sn': 1.1, 'Sb': 0.01, 'Ti': 7600,
'Gd': 3.68, 'Tb': 0.67, 'Dy': 4.55, 'Li': 4.3, 'Y': 28, 'Ho': 1.01, 'Er': 2.97, 'Tm': 0.456,
'Yb': 3.05, 'Lu': 0.455},
'UCC_Rudnick & Gao2003':{'K':23244.13776,'Ti':3835.794545,'P':654.6310022,'Li':24,'Be':2.1,'B':17,'N':83,'F':557,'S':62,'Cl':370,'Sc':14,'V':97,'Cr':92,
'Co':17.3,'Ni':47,'Cu':28,'Zn':67,'Ga':17.5,'Ge':1.4,'As':4.8,'Se':0.09,
'Br':1.6,'Rb':84,'Sr':320,'Y':21,'Zr':193,'Nb':12,'Mo':1.1,'Ru':0.34,
'Pd':0.52,'Ag':53,'Cd':0.09,'In':0.056,'Sn':2.1,'Sb':0.4,'I':1.4,'Cs':4.9,
'Ba':628,'La':31,'Ce':63,'Pr':7.1,'Nd':27,'Sm':4.7,'Eu':1,'Gd':4,'Tb':0.7,
'Dy':3.9,'Ho':0.83,'Er':2.3,'Tm':0.3,'Yb':1.96,'Lu':0.31,'Hf':5.3,'Ta':0.9,
'W':1.9,'Re':0.198,'Os':0.031,'Ir':0.022,'Pt':0.5,'Au':1.5,'Hg':0.05,'Tl':0.9,
'Pb':17,'Bi':0.16,'Th':10.5,'U':2.7}}
Lines = []
Tags = []
xlabel = 'x'
ylabel = 'y'
description = 'X-Y Diagram'
unuseful = ['Name',
'Mineral',
'Author',
'DataType',
'Label',
'Marker',
'Color',
'Size',
'Alpha',
'Style',
'Width',
'Tag']
width_plot = 100.0
height_plot = 100.0
width_load = width_plot
height_load = height_plot
polygon = []
polyline = []
line = []
strgons = []
strlines = []
strpolylines = []
extent = 0
Left = 0
Right = 0
Up = 0
Down = 0
FitLevel=1
FadeGroups=100
ShapeGroups=200
LabelSetted = False
ValueChoosed = True
FlagLoaded=False
TypeLoaded=''
whole_labels=[]
def __init__(self, parent=None, df=pd.DataFrame(),Standard={}):
QMainWindow.__init__(self, parent)
self.setWindowTitle(self.description)
self.FileName_Hint='XY'
self.items = []
self.a_index= 0
self.b_index= 1
self.raw = df
self._df = df
self._df_back=df
self._given_Standard = Standard
self.All_X=[]
self.All_Y=[]
if (len(df) > 0):
self._changed = True
# print('DataFrame recieved to Magic')
self.rawitems = self.raw.columns.values.tolist()
dataframe = self._df
ItemsAvalibale = self._df.columns.values.tolist()
ItemsToTest = ['Number', 'Tag', 'Name', 'Author', 'DataType', 'Marker', 'Color', 'Size', 'Alpha',
'Style', 'Width','Label']
for i in ItemsToTest:
if i in ItemsAvalibale:
dataframe = dataframe.drop(i, 1)
dataframe_values_only = dataframe.apply(pd.to_numeric, errors='coerce')
dataframe_values_only = dataframe_values_only.dropna(axis='columns')
ItemsAvalibale = dataframe_values_only.columns.values.tolist()
data_columns= ItemsAvalibale
df= dataframe_values_only
numdf = (df.drop(data_columns, axis=1).join(df[data_columns].apply(pd.to_numeric, errors='coerce')))
numdf = numdf[numdf[data_columns].notnull().all(axis=1)]
ItemsAvalibale = numdf.columns.values.tolist()
dataframe_values_only=numdf
self.items = dataframe_values_only.columns.values.tolist()
#print(self.items)
self.dataframe_values_only=dataframe_values_only
self.create_main_frame()
self.create_status_bar()
self.polygon = 0
self.polyline = 0
self.flag = 0
def loadDataToTest(self):
TMP =self.getDataFile()
if TMP != 'Blank':
self.data_to_test=TMP[0]
self.Magic()
def Read(self, inpoints):
points = []
for i in inpoints:
points.append(i.split())
result = []
for i in points:
for l in range(len(i)):
a = float((i[l].split(','))[0])
a = a * self.x_scale
b = float((i[l].split(','))[1])
b = (self.height_load - b) * self.y_scale
result.append((a, b))
return (result)
def Load(self):
fileName, filetype = QFileDialog.getOpenFileName(self,
'选取文件',
'~/',
'PNG Files (*.png);;JPG Files (*.jpg);;SVG Files (*.svg)') # 设置文件扩展名过滤,注意用双分号间隔
#print(fileName, '\t', filetype)
if len(fileName)>0:
self.FlagLoaded= True
if ('svg' in fileName):
self.TypeLoaded='svg'
doc = minidom.parse(fileName) # parseString also exists
polygon_points = [path.getAttribute('points') for path in doc.getElementsByTagName('polygon')]
polyline_points = [path.getAttribute('points') for path in doc.getElementsByTagName('polyline')]
svg_width = [path.getAttribute('width') for path in doc.getElementsByTagName('svg')]
svg_height = [path.getAttribute('height') for path in doc.getElementsByTagName('svg')]
# print(svg_width)
# print(svg_height)
digit = '01234567890.-'
width = svg_width[0].replace('px', '').replace('pt', '')
height = svg_height[0].replace('px', '').replace('pt', '')
self.width_load = float(width)
self.height_load = float(height)
soup = BeautifulSoup(open(fileName), 'lxml')
tmpgon = soup.find_all('polygon')
tmppolyline = soup.find_all('polyline')
tmptext = soup.find_all('text')
tmpline = soup.find_all('line')
tmppath = soup.find_all('path')
self.strgons = []
for i in tmpgon:
a = (str(i)).replace('\n', '').replace('\t', '')
m = BeautifulSoup(a, 'lxml')
k = m.polygon.attrs
self.strgons.append(k['points'].split())
self.strpolylines = []
for i in tmppolyline:
a = (str(i)).replace('\n', '').replace('\t', '')
m = BeautifulSoup(a, 'lxml')
k = m.polyline.attrs
self.strpolylines.append(k['points'].split())
self.strlines = []
for i in tmpline:
a = (str(i)).replace('\n', '').replace('\t', '')
m = BeautifulSoup(a, 'lxml')
k = m.line.attrs
a = str(k['x1']) + ',' + str(k['y1']) + ' ' + str(k['x2']) + ',' + str(k['y2'])
self.strlines.append(a.split())
self.strpath = []
for i in tmppath:
a = (str(i)).replace('\n', '').replace('\t', '')
m = BeautifulSoup(a, 'lxml')
k = m.path.attrs
self.strpath.append(k['d'].split())
# print(self.strpath)
self.polygon = []
for i in self.strgons:
m = self.Read(i)
m.append(m[0])
self.polygon.append(m)
self.polyline = []
for i in self.strpolylines:
m = self.Read(i)
# print('i: ',i,'\n m:',m)
self.polyline.append(m)
self.line = []
for i in self.strlines:
m = self.Read(i)
# print('i: ',i,'\n m:',m)
self.line.append(m)
elif ('png' in fileName or 'jpg' in fileName):
self.TypeLoaded='png'
self.img = mpimg.imread(fileName)
self.flag = 1
self.Magic()
def Unload(self):
self.flag = 0
self.FlagLoaded = False
self.TypeLoaded = ''
self.Magic()
def WChanged(self, text):
try:
self.width_plot = float(text)
except Exception as e:
self.ErrorEvent(text=repr(e))
self.x_scale = self.width_plot / self.width_load
self.polygon = []
for i in self.strgons:
m = self.Read(i)
m.append(m[0])
self.polygon.append(m)
self.polyline = []
for i in self.strpolylines:
m = self.Read(i)
# print('i: ',i,'\n m:',m)
self.polyline.append(m)
self.line = []
for i in self.strlines:
m = self.Read(i)
# print('i: ',i,'\n m:',m)
self.line.append(m)
self.Magic()
def HChanged(self, text):
try:
self.height_plot = float(text)
except Exception as e:
self.ErrorEvent(text=repr(e))
self.y_scale = self.height_plot / self.height_load
self.polygon = []
for i in self.strgons:
m = self.Read(i)
m.append(m[0])
self.polygon.append(m)
self.polyline = []
for i in self.strpolylines:
m = self.Read(i)
# print('i: ',i,'\n m:',m)
self.polyline.append(m)
self.line = []
for i in self.strlines:
m = self.Read(i)
# print('i: ',i,'\n m:',m)
self.line.append(m)
self.Magic()
# text_location= [path.getAttribute('transform') for path in doc.getElementsByTagName('text')]
'''
tmppolygon_points=[]
for i in polygon_points:
tmppolygon_points.append(i.split())
polygon=[]
for i in tmppolygon_points:
for l in range(len(i)):
a=float((i[l].split(','))[0])
b=float((i[l].split(','))[1])
polygon.append([a,b])
'''
def LeftChanged(self, text):
try:
self.Left = float(text)
except Exception as e:
self.ErrorEvent(text=repr(e))
self.Magic()
def RightChanged(self, text):
try:
self.Right = float(text)
except Exception as e:
self.ErrorEvent(text=repr(e))
self.Magic()
def UpChanged(self, text):
try:
self.Up = float(text)
except Exception as e:
self.ErrorEvent(text=repr(e))
self.Magic()
def DownChanged(self, text):
try:
self.Down = float(text)
except Exception as e:
self.ErrorEvent(text=repr(e))
self.Magic()
def FitChanged(self, text):
try:
self.FitLevel = float(text)
except Exception as e:
self.ErrorEvent(text=repr(e))
self.Magic()
def ShapeChanged(self, text):
w = 'Shape' + text
self.shape_label.setText(w)
self.shape_label.adjustSize()
try:
self.ShapeGroups = int(text)
except Exception as e:
self.ErrorEvent(text=repr(e))
self.Magic()
def LabelSeter(self):
self.LabelSetted = True
self.ValueChoosed = False
self.Magic()
def ValueChooser(self):
self.LabelSetted = False
self.ValueChoosed = True
self.Magic()
def Magic(self):
k_s = int(self.kernel_select.value())
self.kernel_select_label.setText(self.kernel_list[k_s])
self.WholeData = []
self.x_scale = self.width_plot / self.width_load
self.y_scale = self.height_plot / self.height_load
# print(self.x_scale,' and ',self.x_scale)
raw = self._df
dataframe = self._df
ItemsAvalibale = self._df.columns.values.tolist()
ItemsToTest = ['Number', 'Tag', 'Name', 'Author', 'DataType', 'Marker', 'Color', 'Size', 'Alpha',
'Style', 'Width','Label']
for i in ItemsToTest:
if i in ItemsAvalibale:
dataframe = dataframe.drop(i, 1)
dataframe_values_only = dataframe.apply(pd.to_numeric, errors='coerce')
dataframe_values_only = dataframe_values_only.dropna(axis='columns')
ItemsAvalibale = dataframe_values_only.columns.values.tolist()
data_columns= ItemsAvalibale
df= dataframe_values_only
numdf = (df.drop(data_columns, axis=1).join(df[data_columns].apply(pd.to_numeric, errors='coerce')))
numdf = numdf[numdf[data_columns].notnull().all(axis=1)]
ItemsAvalibale = numdf.columns.values.tolist()
dataframe_values_only=numdf
a = int(self.x_element.value())
b = int(self.y_element.value())
if self.LabelSetted == True:
if(self.x_seter.text()!=''):
try:
a = int(self.x_seter.text())
except(ValueError):
atmp=self.x_seter.text()
try:
if atmp in ItemsAvalibale:
a= ItemsAvalibale.index(atmp)
#print(a)
except Exception as e:
self.ErrorEvent(text=repr(e))
pass
pass
self.x_element.setValue(a)
else:
a = int(self.x_element.value())
if (self.y_seter.text() != ''):
try:
b = int(self.y_seter.text())
except(ValueError):
btmp=self.y_seter.text()
try:
if btmp in ItemsAvalibale:
b= ItemsAvalibale.index(btmp)
#print(b)
except Exception as e:
self.ErrorEvent(text=repr(e))
pass
pass
self.y_element.setValue(b)
else:
b = int(self.y_element.value())
if b> len(ItemsAvalibale)-1:
b = int(self.y_element.value())
if a> len(ItemsAvalibale)-1:
a = int(self.x_element.value())
if self.ValueChoosed == True:
a = int(self.x_element.value())
b = int(self.y_element.value())
self.x_seter.setText(ItemsAvalibale[a])
self.y_seter.setText(ItemsAvalibale[b])
self.a_index= a
self.b_index= b
self.axes.clear()
if (self.Left != self.Right) and (self.Down != self.Up) and abs(self.Left) + abs(self.Right) + abs(
self.Down) + abs(self.Up) != 0:
self.extent = [self.Left, self.Right, self.Down, self.Up]
elif (self.Left == self.Right and abs(self.Left) + abs(self.Right) != 0):
reply = QMessageBox.warning(self, 'Warning', 'You set same value to Left and Right limits.')
self.extent = 0
elif (self.Down == self.Up and abs(self.Down) + abs(self.Up) != 0):
reply = QMessageBox.warning(self, 'Warning', 'You set same value to Up and Down limits.')
self.extent = 0
else:
self.extent = 0
slider_value=int(self.standard_slider.value())
if slider_value < len(self.StandardsName):
standardnamechosen = self.StandardsName[slider_value]
standardchosen = self.Standards[standardnamechosen]
right_label_text=self.StandardsName[slider_value]
elif len(self._given_Standard)<=0:
standardnamechosen = self.StandardsName[slider_value-1]
standardchosen = self.Standards[standardnamechosen]
right_label_text = self.StandardsName[slider_value-1]
else:
standardnamechosen = "Self Defined Standard"
standardchosen = self._given_Standard
right_label_text = "Self Defined Standard"
self.right_label.setText(right_label_text)
if self.flag != 0:
if self.extent != 0:
self.axes.imshow(self.img, interpolation='nearest', aspect='auto', extent=self.extent)
else:
self.axes.imshow(self.img, interpolation='nearest', aspect='auto')
self.axes.set_xlabel(ItemsAvalibale[a])
self.axes.set_ylabel(ItemsAvalibale[b])
PointLabels = []
PointColors = []
XtoFit = []
YtoFit = []
all_labels=[]
all_colors=[]
all_markers=[]
all_alpha=[]
for i in range(len(self._df)):
target = self._df.at[i, 'Label']
color = self._df.at[i, 'Color']
marker = self._df.at[i, 'Marker']
alpha = self._df.at[i, 'Alpha']
if target not in all_labels:
all_labels.append(target)
all_colors.append(color)
all_markers.append(marker)
all_alpha.append(alpha)
self.whole_labels = all_labels
df = self.CleanDataFile(self._df)
for i in range(len(df)):
TmpLabel = ''
if (df.at[i, 'Label'] in PointLabels or df.at[i, 'Label'] == ''):
TmpLabel = ''
else:
PointLabels.append(df.at[i, 'Label'])
TmpLabel = df.at[i, 'Label']
TmpColor = ''
if (df.at[i, 'Color'] in PointColors or df.at[i, 'Color'] == ''):
TmpColor = ''
else:
PointColors.append(df.at[i, 'Color'])
TmpColor = df.at[i, 'Color']
x, y = dataframe_values_only.at[i, self.items[a]], dataframe_values_only.at[i, self.items[b]]
try:
xuse = x
yuse = y
self.xlabel = self.items[a]
self.ylabel = self.items[b]
if (self.norm_cb.isChecked()):
self.sentence = self.reference
#print(self.items[a] , self.items[a] in self.Element)
item_a =self.items[a]
item_b =self.items[b]
str_to_check=['ppm','(',')','[',']','wt','\%']
for j in str_to_check:
if j in item_a:
item_a=item_a.replace(j, "")
if j in item_b:
item_b=item_b.replace(j, "")
if item_a in self.Element:
self.xlabel = self.items[a] + ' Norm by ' + standardnamechosen
xuse = xuse / standardchosen[item_a]
if item_b in self.Element:
self.ylabel = self.items[b] + ' Norm by ' + standardnamechosen
yuse = yuse / standardchosen[item_b]
if (self.logx_cb.isChecked()):
xuse = math.log(x, 10)
newxlabel = '$log10$( ' + self.xlabel + ')'
self.axes.set_xlabel(newxlabel)
else:
self.axes.set_xlabel(self.xlabel)
if (self.logy_cb.isChecked()):
yuse = math.log(y, 10)
newylabel = '$log10$( ' + self.ylabel + ')'
self.axes.set_ylabel(newylabel)
else:
self.axes.set_ylabel(self.ylabel)
self.axes.scatter(xuse, yuse, marker=raw.at[i, 'Marker'],
s=raw.at[i, 'Size'], color=raw.at[i, 'Color'], alpha=raw.at[i, 'Alpha'],
label=TmpLabel)
'''
if raw.at[i, 'Color'] == 'w' or raw.at[i, 'Color'] =='White':
self.axes.scatter(xuse, yuse, marker=raw.at[i, 'Marker'],
s=raw.at[i, 'Size'], color=raw.at[i, 'Color'], alpha=raw.at[i, 'Alpha'],
label=TmpLabel, edgecolors='black')
else:
self.axes.scatter(xuse, yuse, marker=raw.at[i, 'Marker'],
s=raw.at[i, 'Size'], color=raw.at[i, 'Color'], alpha=raw.at[i, 'Alpha'],
label=TmpLabel,
edgecolors='white')
'''
XtoFit.append(xuse)
YtoFit.append(yuse)
except Exception as e:
self.ErrorEvent(text=repr(e))
#pass
#Yline = np.linspace(min(YtoFit), max(YtoFit), 30)
ResultStr=''
BoxResultStr=''
Paralist=[]
#print(XtoFit, '\n', YtoFit)
if len(XtoFit) != len(YtoFit):
reply = QMessageBox.information(self, 'Warning','Your Data X and Y have different length!')
pass
fitstatus = True
if (int(self.fit_slider.value()) == 0):
if len(XtoFit)>0:
Xline = np.linspace(min(XtoFit), max(XtoFit), 30)
try:
np.polyfit(XtoFit, YtoFit, self.FitLevel)
except Exception as e:
self.ErrorEvent(text=repr(e))
fitstatus = False
if (fitstatus == True):
try:
opt, cov = np.polyfit(XtoFit, YtoFit, self.FitLevel, cov=True)
self.fit_slider_label.setText('y= f(x) EXP')
p = np.poly1d(opt)
Yline = p(Xline)
formular = 'y= f(x):'
sigma = np.sqrt(np.diag(cov))
N = len(XtoFit)
F = N - 2
MSWD = 1 + 2 * np.sqrt(2 / F)
MSWDerr = np.sqrt(2 / F)
for i in range(int(self.FitLevel + 1)):
Paralist.append([opt[i], sigma[i]])
if int(self.fit_slider.value()) == 0:
if (self.FitLevel - i == 0):
ResultStr = ResultStr + str(opt[i]) + '$\pm$' + str(sigma[i]) + '+'
BoxResultStr = BoxResultStr + str(opt[i]) + '±' + str(sigma[i]) + '\n'
else:
ResultStr = ResultStr + str(opt[i]) + '$\pm$' + str(sigma[i]) + '$x^' + str(
self.FitLevel - i) + '$' + '+'
BoxResultStr = BoxResultStr + str(opt[i]) + '±' + str(sigma[i]) + 'x^' + str(
self.FitLevel - i) + '+\n'
elif (int(self.fit_slider.value()) == 1):
if (self.FitLevel - i == 0):
ResultStr = ResultStr + str(opt[i]) + '$\pm$' + str(sigma[i]) + '+'
BoxResultStr = BoxResultStr + str(opt[i]) + '±' + str(sigma[i]) + '+\n'
else:
ResultStr = ResultStr + str(opt[i]) + '$\pm$' + str(sigma[i]) + '$y^' + str(
self.FitLevel - i) + '$' + '+'
BoxResultStr = BoxResultStr + str(opt[i]) + '±' + str(sigma[i]) + 'y^' + str(
self.FitLevel - i) + '+\n'
pass
pass
self.textbox.setText(formular + '\n' + BoxResultStr + '\n MSWD(±2σ)' + str(MSWD) + '±' + str(
2 * MSWDerr) + '\n' + self.sentence)
if (self.fit_cb.isChecked()):
self.axes.plot(Xline, Yline, 'b-')
except Exception as e:
self.ErrorEvent(text=repr(e))
elif (int(self.fit_slider.value()) == 1):
if len(YtoFit) > 0:
Yline = np.linspace(min(YtoFit), max(YtoFit), 30)
try:
np.polyfit(YtoFit, XtoFit, self.FitLevel, cov=True)
except(ValueError, TypeError):
fitstatus = False
pass
if (fitstatus == True):
opt, cov = np.polyfit(YtoFit, XtoFit, self.FitLevel, cov=True)
self.fit_slider_label.setText('x= f(x) EXP')
p = np.poly1d(opt)
Xline = p(Yline)
formular = 'x= f(y):'
sigma = np.sqrt(np.diag(cov))
N=len(XtoFit)
F=N-2
MSWD=1+2*np.sqrt(2/F)
MSWDerr=np.sqrt(2/F)
for i in range(int(self.FitLevel + 1)):
Paralist.append([opt[i], sigma[i]])
if int(self.fit_slider.value()) == 0:
if (self.FitLevel - i == 0):
ResultStr = ResultStr + str(opt[i]) + '$\pm$' + str(sigma[i])+'+'
BoxResultStr = BoxResultStr + str(opt[i]) + '±' + str(sigma[i]) + '\n'
else:
ResultStr = ResultStr+ str(opt[i])+'$\pm$'+str(sigma[i])+'$x^'+str(self.FitLevel-i)+'$'+'+'
BoxResultStr = BoxResultStr + str(opt[i]) + '±' + str(sigma[i]) + 'x^' + str(
self.FitLevel - i) + '+\n'
elif (int(self.fit_slider.value()) == 1):
if (self.FitLevel-i==0):
ResultStr = ResultStr + str(opt[i]) + '$\pm$' + str(sigma[i])+'+'
BoxResultStr = BoxResultStr + str(opt[i]) + '±' + str(sigma[i]) + '+\n'
else:
ResultStr = ResultStr+ str(opt[i])+'$\pm$'+str(sigma[i])+'$y^'+str(self.FitLevel-i)+'$'+'+'
BoxResultStr = BoxResultStr + str(opt[i]) + '±' + str(sigma[i]) + 'y^' + str(
self.FitLevel - i) + '+\n'
pass
pass
self.textbox.setText(formular +'\n'+ BoxResultStr+ '\n MSWD(±2σ)'+str(MSWD)+'±'+str(2*MSWDerr)+'\n' + self.sentence)
if (self.fit_cb.isChecked()):
self.axes.plot(Xline, Yline, 'b-')
XtoFit_dic = {}
YtoFit_dic = {}
for i in PointLabels:
XtoFit_dic[i] = []
YtoFit_dic[i] = []
for i in range(len(df)):
Alpha = df.at[i, 'Alpha']
Marker = df.at[i, 'Marker']
Label = df.at[i, 'Label']
xtest = self.dataframe_values_only.at[i, self.items[a]]
ytest = self.dataframe_values_only.at[i, self.items[b]]
XtoFit_dic[Label].append(xtest)
YtoFit_dic[Label].append(ytest)
if (self.shape_cb.isChecked()):
for i in PointLabels:
if XtoFit_dic[i] != YtoFit_dic[i]:
xmin, xmax = min(XtoFit_dic[i]), max(XtoFit_dic[i])
ymin, ymax = min(YtoFit_dic[i]), max(YtoFit_dic[i])
DensityColorMap = 'Greys'
DensityAlpha = 0.1
DensityLineColor = PointColors[PointLabels.index(i)]
DensityLineAlpha = 0.3
# Peform the kernel density estimate
xx, yy = np.mgrid[xmin:xmax:200j, ymin:ymax:200j]
# print(self.ShapeGroups)
# command='''xx, yy = np.mgrid[xmin:xmax:'''+str(self.ShapeGroups)+ '''j, ymin:ymax:''' +str(self.ShapeGroups)+'''j]'''
# exec(command)
# print(xx, yy)
positions = np.vstack([xx.ravel(), yy.ravel()])
values = np.vstack([XtoFit_dic[i], YtoFit_dic[i]])
kernelstatus = True
try:
st.gaussian_kde(values)
except Exception as e:
self.ErrorEvent(text=repr(e))
kernelstatus = False
if kernelstatus == True:
kernel = st.gaussian_kde(values)
f = np.reshape(kernel(positions).T, xx.shape)
# Contourf plot
cfset = self.axes.contourf(xx, yy, f, cmap=DensityColorMap, alpha=DensityAlpha)
## Or kernel density estimate plot instead of the contourf plot
# self.axes.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax])
# Contour plot
cset = self.axes.contour(xx, yy, f, colors=DensityLineColor, alpha=DensityLineAlpha)
# Label plot
#self.axes.clabel(cset, inline=1, fontsize=10)
if (len(self.data_to_test) > 0):
contained = True
missing = 'Miss setting infor:'
for i in ['Label', 'Color', 'Marker', 'Alpha']:
if i not in self.data_to_test.columns.values.tolist():
contained = False
missing = missing + '\n' + i
if contained == True:
for i in self.data_to_test.columns.values.tolist():
if i not in self._df.columns.values.tolist():
self.data_to_test = self.data_to_test.drop(columns=i)
# print(self.data_to_test)
test_labels = []
test_colors = []
test_markers = []
test_alpha = []
for i in range(len(self.data_to_test)):
# print(self.data_to_test.at[i, 'Label'])
target = self.data_to_test.at[i, 'Label']
color = self.data_to_test.at[i, 'Color']
marker = self.data_to_test.at[i, 'Marker']
alpha = self.data_to_test.at[i, 'Alpha']
if target not in test_labels and target not in all_labels:
test_labels.append(target)
test_colors.append(color)
test_markers.append(marker)
test_alpha.append(alpha)
self.whole_labels = self.whole_labels + test_labels
self.data_to_test_to_fit = self.Slim(self.data_to_test)
self.load_settings_backup = self.data_to_test
Load_ItemsToTest = ['Label', 'Number', 'Tag', 'Name', 'Author', 'DataType', 'Marker', 'Color', 'Size',
'Alpha',
'Style', 'Width']
for i in self.data_to_test.columns.values.tolist():
if i not in Load_ItemsToTest:
self.load_settings_backup = self.load_settings_backup.drop(i, 1)
print(self.load_settings_backup ,self.data_to_test)
print(self.load_settings_backup.shape ,self.data_to_test.shape)
#self.load_result = pd.concat([self.load_settings_backup, pd.DataFrame(self.data_to_test_to_fit)], axis=1)
try:
for i in range(len(self.data_to_test)):
target = self.data_to_test.at[i, 'Label']
if target not in all_labels:
all_labels.append(target)
tmp_label = self.data_to_test.at[i, 'Label']
else:
tmp_label=''
x_load_test = self.data_to_test.at[i, self.items[a]]
y_load_test = self.data_to_test.at[i, self.items[b]]
if (self.show_load_data_cb.isChecked()):
self.axes.scatter(x_load_test, y_load_test,
marker=self.data_to_test.at[i, 'Marker'],
s=self.data_to_test.at[i, 'Size'], color=self.data_to_test.at[i, 'Color'],
alpha=self.data_to_test.at[i, 'Alpha'],
label=tmp_label)
'''
if raw.at[i, 'Color'] == 'w' or raw.at[i, 'Color'] == 'White':
self.axes.scatter(x_load_test, y_load_test,
marker=self.data_to_test.at[i, 'Marker'],
s=self.data_to_test.at[i, 'Size'], color=self.data_to_test.at[i, 'Color'],
alpha=self.data_to_test.at[i, 'Alpha'],
label=tmp_label,
edgecolors='black')
else:
self.axes.scatter(x_load_test, y_load_test,
marker=self.data_to_test.at[i, 'Marker'],
s=self.data_to_test.at[i, 'Size'], color=self.data_to_test.at[i, 'Color'],
alpha=self.data_to_test.at[i, 'Alpha'],
label=tmp_label,
edgecolors='white')
'''
except Exception as e:
self.ErrorEvent(text=repr(e))
if (self.TypeLoaded=='svg'):
if self.polygon != 0 and self.polyline != 0 and self.line != 0:
# print('gon: ',self.polygon,' \n line:',self.polyline)
for i in self.polygon:
self.DrawLine(i)
for i in self.polyline:
self.DrawLine(i)
for i in self.line:
self.DrawLine(i)
# self.DrawLine(self.polygon)
# self.DrawLine(self.polyline)
self.All_X=XtoFit
self.All_Y=YtoFit
if (self.hyperplane_cb.isChecked()):
if XtoFit != YtoFit:
clf = svm.SVC(C=1.0, kernel=self.kernel_list[k_s], probability=True)
svm_x = XtoFit
svm_y = YtoFit
xx, yy = np.meshgrid(np.arange( min(svm_x), max(svm_x), np.ptp(svm_x) / 500),
np.arange( min(svm_y), max(svm_y), np.ptp(svm_y) / 500))
le = LabelEncoder()
le.fit(self._df.Label)
print(len(self._df.Label),self._df.Label)
class_label=le.transform(self._df.Label)
svm_train= pd.concat([pd.DataFrame(svm_x),pd.DataFrame(svm_y)], axis=1)
svm_train=svm_train.values
clf.fit(svm_train,class_label)
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
self.axes.contourf(xx, yy, Z, cmap='hot', alpha=0.2)
if (self.show_data_index_cb.isChecked()):
if 'Index' in self._df_back.columns.values:
for i in range(len(self._df)):
self.axes.annotate(self._df_back.at[i, 'Index'],
xy=(self.All_X[i],
self.All_Y[i]),
color=self._df.at[i, 'Color'],
alpha=self._df.at[i, 'Alpha'])
else:
for i in range(len(self._df)):
self.axes.annotate('No' + str(i+1),
xy=(self.All_X[i],
self.All_Y[i]),
color=self._df.at[i, 'Color'],
alpha=self._df.at[i, 'Alpha'])
if (self.legend_cb.isChecked()):
self.axes.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0, prop=fontprop)
self.canvas.draw()
def loadDataToTest(self):
TMP =self.getDataFile()
if TMP != 'Blank':
self.data_to_test=TMP[0]
self.Magic()
def showPredictResultSelected(self):
k_s = int(self.kernel_select.value())
try:
clf = svm.SVC(C=1.0, kernel=self.kernel_list[k_s], probability=True)
svm_x = self.All_X
svm_y = self.All_Y
le = LabelEncoder()
le.fit(self._df.Label)
class_label = le.transform(self._df.Label)
svm_train = pd.concat([pd.DataFrame(svm_x), pd.DataFrame(svm_y)], axis=1)
svm_train = svm_train.values
clf.fit(svm_train, self._df.Label)
xx = self.data_to_test_to_fit[self.items[self.a_index]]
yy = self.data_to_test_to_fit[self.items[self.b_index]]
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z2 = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])
proba_df = pd.DataFrame(Z2)
proba_df.columns = clf.classes_
proba_list = []
for i in range(len(proba_df)):
proba_list.append(round(max(proba_df.iloc[i])+ 0.001, 2))
predict_result = pd.concat(
[self.data_to_test['Label'], pd.DataFrame({'SVM Classification': Z}), pd.DataFrame({'Confidence probability': proba_list})],
axis=1).set_index('Label')
print(predict_result)
self.predictpop = TableViewer(df=predict_result, title='SVM Predict Result With '+ self.items[self.a_index]+','+self.items[self.b_index])
self.predictpop.show()
'''
DataFileOutput, ok2 = QFileDialog.getSaveFileName(self, '文件保存', 'C:/', 'Excel Files (*.xlsx);;CSV Files (*.csv)') # 数据文件保存输出
if (DataFileOutput != ''):
if ('csv' in DataFileOutput):
# DataFileOutput = DataFileOutput[0:-4]
predict_result.to_csv(DataFileOutput, sep=',', encoding='utf-8')
# self.result.to_csv(DataFileOutput + '.csv', sep=',', encoding='utf-8')
elif ('xlsx' in DataFileOutput):
# DataFileOutput = DataFileOutput[0:-5]
predict_result.to_excel(DataFileOutput, encoding='utf-8')
# self.result.to_excel(DataFileOutput + '.xlsx', encoding='utf-8')
'''
except Exception as e:
msg = 'You need to load another data to run SVM.\n '
self.ErrorEvent(text= msg +repr(e) )
def showPredictResult(self):
k_s = int(self.kernel_select.value())
try:
clf = svm.SVC(C=1.0, kernel=self.kernel_list[k_s], probability=True)
le = LabelEncoder()
le.fit(self._df.Label)
df_values = self.Slim(self._df)
clf.fit(df_values, self._df.Label)
Z = clf.predict(np.c_[self.data_to_test_to_fit])
Z2 = clf.predict_proba(np.c_[self.data_to_test_to_fit])
proba_df = pd.DataFrame(Z2)
proba_df.columns = clf.classes_
proba_list = []
for i in range(len(proba_df)):
proba_list.append(round(max(proba_df.iloc[i])+ 0.001, 2))
predict_result = pd.concat(
[self.data_to_test['Label'], pd.DataFrame({'SVM Classification': Z}), pd.DataFrame({'Confidence probability': proba_list})],
axis=1).set_index('Label')
print(predict_result)
self.predictAllpop = TableViewer(df=predict_result, title='SVM Predict Result with All Items')
self.predictAllpop.show()
except Exception as e:
msg = 'You need to load another data to run SVM.\n '
self.ErrorEvent(text= msg +repr(e) )
def relation(self,data1=np.ndarray,data2=np.ndarray):
data=array([data1,data2])
dict={'cov':cov(data,bias=1),'corrcoef':corrcoef(data)}
return(dict)
def Stat(self):
df=self._df
m = ['Width', 'Style', 'Alpha', 'Size', 'Color', 'Marker', 'Author']
for i in m:
if i in df.columns.values:
df = df.drop(i, 1)
df.set_index('Label', inplace=True)
items = df.columns.values
index = df.index.values
StatResultDict = {}
for i in items:
StatResultDict[i] = self.stateval(df[i].values)
StdSortedList = sorted(StatResultDict.keys(), key=lambda x: StatResultDict[x]['std'])
StdSortedList.reverse()
StatResultDf = pd.DataFrame.from_dict(StatResultDict, orient='index')
StatResultDf['Items']=StatResultDf.index.tolist()
self.tablepop = TableViewer(df=StatResultDf,title='Statistical Result')
self.tablepop.show()
self.Intro = StatResultDf
return(StatResultDf)
|
GeoPyTool/GeoPyTool | geopytool/QAPF.py | QAPF.create_main_frame | python | def create_main_frame(self):
self.resize(800, 1000)
self.main_frame = QWidget()
self.dpi = 128
self.fig = Figure((12, 11), dpi=self.dpi)
self.fig.subplots_adjust(hspace=0.5, wspace=0.5, left=0.1, bottom=0.2, right=0.7, top=0.9)
# 8 * np.sqrt(3)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.axes = self.fig.add_subplot(111)
self.axes.axis('off')
self.axes.set_xlim(-10, 110)
self.axes.set_ylim(-105 * np.sqrt(3) / 2, 105 * np.sqrt(3) / 2)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.axes = self.fig.add_subplot(111)
# Create the navigation toolbar, tied to the canvas
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
# Other GUI controls
self.save_button = QPushButton('&Save')
self.save_button.clicked.connect(self.saveImgFile)
#self.result_button = QPushButton('&Result')
#self.result_button.clicked.connect(self.Explain)
self.legend_cb = QCheckBox('&Legend')
self.legend_cb.setChecked(True)
self.legend_cb.stateChanged.connect(self.QAPF) # int
self.slider_left_label = QLabel('Plutonic')
self.slider_right_label = QLabel('Volcanic')
self.slider = QSlider(Qt.Horizontal)
self.slider.setRange(0, 1)
self.slider.setValue(0)
self.slider.setTracking(True)
self.slider.setTickPosition(QSlider.TicksBothSides)
self.slider.valueChanged.connect(self.QAPF) # int
'''
self.Tag_cb = QCheckBox('&Plutonic')
self.Tag_cb.setChecked(True)
self.Tag_cb.stateChanged.connect(self.QAPF) # int
if (self.Tag_cb.isChecked()):
self.Tag_cb.setText('&Plutonic')
else:
self.Tag_cb.setText('&Volcanic')
'''
self.detail_cb = QCheckBox('&Detail')
self.detail_cb.setChecked(True)
self.detail_cb.stateChanged.connect(self.QAPF) # int
#
# Layout with box sizers
#
self.hbox = QHBoxLayout()
for w in [self.save_button, self.detail_cb, self.legend_cb,self.slider_left_label,self.slider,self.slider_right_label]:
self.hbox.addWidget(w)
self.hbox.setAlignment(w, Qt.AlignVCenter)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.mpl_toolbar)
self.vbox.addWidget(self.canvas)
self.vbox.addLayout(self.hbox)
self.textbox = GrowingTextEdit(self)
self.vbox.addWidget(self.textbox)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame)
w=self.width()
h=self.height()
#setFixedWidth(w/10)
self.slider.setMinimumWidth(w/10)
self.slider_left_label.setMinimumWidth(w/10)
self.slider_right_label.setMinimumWidth(w/10) | self.Tag_cb = QCheckBox('&Plutonic')
self.Tag_cb.setChecked(True)
self.Tag_cb.stateChanged.connect(self.QAPF) # int
if (self.Tag_cb.isChecked()):
self.Tag_cb.setText('&Plutonic')
else:
self.Tag_cb.setText('&Volcanic') | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/QAPF.py#L211-L303 | null | class QAPF(AppForm, Tool):
infotext ='Q = quartz, A = alkali feldspar, P = plagioclase and F = feldspathoid.\nOnly for rocks in which the mafic mineral content, M, is greater than 90%.'
exptext='''
1a: quartzolite,
1b: quartz-rich granitoid,
2: alkali feldspar granite,
3a: (syeno granite),
3b: (monzo granite),
4: granodiorite,
5: tonalite,
6*: quartz alkali feldspar syenite,
7*: quartz syenite,
8*: quartz monzonite,
9*: quartz monzodiorite quartz monzogabbro,
10*: quartz diorite quartz gabbro quartz anorthosite,
6: alkali feldspar syenite,
7: syenite,
8: monzonite,
9: monzodiorite monzogabbro,
10: diorite gabbro anorthosite,
6\': foid-bearing alkali feldspar syenite,
7\': foid-bearing syenite,
8\': foid-bearing monzonite,
9\': foid-bearing monzodiorite foid-bearing monzogabbro,
10\': foid-bearing diorite foid-bearing gabbro foid-bearing anorthosite,
11: foid syenite,
12: foid monzosyenite,
13: foid monzodiorite foid monzogabbro,
14: foid diorite foid gabbro,
15: foidolite
'''
#infotext = infotext + exptext
reference = 'Reference: Maitre, R. W. L., Streckeisen, A., Zanettin, B., Bas, M. J. L., Bonin, B., and Bateman, P., 2004, Igneous Rocks: A Classification and Glossary of Terms: Cambridge University Press, v. -1, no. 70, p. 93–120.'
_df = pd.DataFrame()
_changed = False
xlabel = r''
ylabel = r''
Tags = []
Label = [u'Q', u'A', u'P', u'F']
LabelPosition = [(48, 50 * np.sqrt(3) + 1),
(-6, -1),
(104, -1),
(49, -50 * np.sqrt(3) - 4)]
Labels = ['quartzolite',
'quartz-rich\ngranitoid',
'granite',
'alkali\nfeldspar\ngranite',
'(syeno\ngranite)',
'(monzo\ngranite)',
'granodiorite',
'tonalite',
'quartz\nalkali\nfeldspar\nsyenite',
'quartz\nsyenite',
'quartz\nmonzonite',
'quartz\nmonzodiorite\nquartz\nmonzogabbro',
'quartz\ndiorite\nquartz gabbro\n quartz\nanorthosite',
'alkali\nfeldspar\nsyenite',
'syenite',
'monzonite',
'monzodiorite\nmonzogabbro',
'diorite\ngabbro\nanorthosite',
'foid-bearing\nalkali\nfeldspar\nsyenite',
'foid-bearing\nsyenite',
'foid-bearing\nmonzonite',
'foid-bearing\nmonzodiorite\nfoid-bearing\nmonzogabbro',
'foid-bearing\ndiorite\nfoid-bearing gabbro\nfoid-bearing\nanorthosite',
'foid\nsyenite',
'foid\nmonzosyenite',
'foid\nmonzodiorite\nfoid\nmonzogabbro',
'foid\ndiorite\nfoid\ngabbro',
'foidolite']
Locations = [(5, 5, 95),
(10, 10, 80),
(35, 15, 50),
(45, 5, 50),
(45, 25, 30),
(35, 35, 30),
(25, 45, 30),
(5, 45, 50),
(85, 5, 10),
(75, 15, 10),
(45, 45, 10),
(15, 75, 10),
(5, 85, 10),
(93, 5, 1),
(83, 15, 1),
(53, 53, 1),
(15, 83, 1),
(5, 93, 1),
(95, 3, -8),
(75, 23, -8),
(49, 49, -8),
(23, 75, -8),
(3, 95, -8),
(63, 7, -30),
(50, 20, -30),
(20, 50, -30),
(7, 63, -30),
(10, 10, -80)]
Offset = [(-30, 0),
(-30, 0),
(-20, 0),
(-70, 30),
(-50, 30),
(-30, 0),
(0, 0),
(30, 20),
(-70, 15),
(-10, 0),
(-40, 0),
(-50, -5),
(30, 15),
(-80, 5),
(0, 0),
(-40, 0),
(-50, -5),
(60, 5),
(-80, -15),
(-40, 0),
(-40, 0),
(-20, -15),
(50, -30),
(-80, 0),
(-40, 0),
(-40, 0),
(60, 0),
(-30, 0)]
def __init__(self, parent=None, df=pd.DataFrame()):
QMainWindow.__init__(self, parent)
self.FileName_Hint='QAPF'
self._df = df
if (len(df) > 0):
self._changed = True
# print('DataFrame recieved to DualTri')
self.raw = self._df
self.create_main_frame()
self.create_status_bar()
TriLine(Points=[(100, 0, 0), (0, 0, 100), (0, 100, 0), (0, 0, -100), (100, 0, 0), (35, 65, 0)], Sort='',
Width=1, Color='black', Style='-',
Alpha=0.7, Label='')
for i in range(len(self.LabelPosition)):
plt.annotate(self.Label[i], xy=(self.LabelPosition[i]), xycoords='data', xytext=(0, 0),
textcoords='offset points',
fontsize=16, )
def QAPF(self):
self.axes.clear()
self.axes.axis('off')
self.Tags = []
self.axes.set_xlim(-10, 110)
self.axes.set_ylim(-105 * np.sqrt(3) / 2, 105 * np.sqrt(3) / 2)
if (int(self.slider.value()) == 0):
s = [
TriLine(Points=[(100, 0, 0), (0, 0, 100), (0, 100, 0), (0, 0, -100), (100, 0, 0), (0, 100, 0)], Sort='',
Width=1, Color='black', Style='-',
Alpha=0.7, Label='')]
for i in s:
self.axes.plot(i.X, i.Y, color=i.Color, linewidth=i.Width, linestyle=i.Style, alpha=i.Alpha,
label=i.Label)
self.Labels = ['1a',
'1b',
'2',
'3a',
'3b',
'4',
'5',
'6*',
'7*',
'8*',
'9*',
'10*',
'6',
'7',
'8',
'9',
'10',
'6\'',
'7\'',
'8\'',
'9\'',
'10\'',
'11',
'12',
'13',
'14',
'15']
self.Locations = [(50,80),
(50,65),
(22,33),
(32,33),
(50,33),
(66,33),
(76,33),
(10, 10),
(26, 10),
(50, 10),
(74, 10),
(88, 10),
(6, 1),
(24, 1),
(50, 1),
(76, 1),
(90, 1),
(6, -5),
(24, -5),
(50, -5),
(76, -5),
(90, -5),
(18, -30),
(40, -30),
(60, -30),
(78, -30),
(50, -60)]
self.setWindowTitle('QAPF modal classification of plutonic rocks')
self.exptext='''
1a: quartzolite,
1b: quartz-rich granitoid,
2: alkali feldspar granite,
3a: (syeno granite),
3b: (monzo granite),
4: granodiorite,
5: tonalite,
6*: quartz alkali feldspar syenite,
7*: quartz syenite,
8*: quartz monzonite,
9*: quartz monzodiorite quartz monzogabbro,
10*: quartz diorite quartz gabbro quartz anorthosite,
6: alkali feldspar syenite,
7: syenite,
8: monzonite,
9: monzodiorite monzogabbro,
10: diorite gabbro anorthosite,
6\': foid-bearing alkali feldspar syenite,
7\': foid-bearing syenite,
8\': foid-bearing monzonite,
9\': foid-bearing monzodiorite foid-bearing monzogabbro,
10\': foid-bearing diorite foid-bearing gabbro foid-bearing anorthosite,
11: foid syenite,
12: foid monzosyenite,
13: foid monzodiorite foid monzogabbro,
14: foid diorite foid gabbro,
15: foidolite
'''
self.textbox.setText(self.reference + '\n' + self.infotext+ '\n' + self.exptext)
D1 = (0, 0, 100)
L1 = [(10, 0, 90), (0, 10, 90)]
L2 = [(40, 0, 60), (0, 40, 60)]
L3 = [(80, 0, 20), (0, 80, 20)]
L4 = [(95, 0, 5), (0, 95, 5)]
SL1 = [D1, (90, 10, 0)]
SL2 = [D1, (65, 35, 0)]
SL3 = [D1, (35, 65, 0)]
SL4 = [D1, (10, 90, 0)]
CL1 = self.TriCross(SL1, L2)
CL21 = self.TriCross(SL2, L2)
CL22 = self.TriCross(SL2, L3)
CL3 = self.TriCross(SL3, L2)
CL41 = self.TriCross(SL4, L2)
CL42 = self.TriCross(SL4, L3)
NSL1 = [CL1, (90, 10, 0)]
NSL21 = [CL21, CL22]
NSL22 = [CL22, (65, 35, 0)]
NSL3 = [CL3, (35, 65, 0)]
NSL4 = [CL41, (10, 90, 0)]
s = [TriLine(Points=L1, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=L2, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=L3, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=L4, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL1, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL21, Sort='', Width=1, Color='black', Style='--', Alpha=0.7,
Label=''),
TriLine(Points=NSL22, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL3, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL4, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label='')]
for i in s:
self.axes.plot(i.X, i.Y, color=i.Color, linewidth=i.Width, linestyle=i.Style, alpha=i.Alpha,
label=i.Label)
D2 = (0, 0, -100)
L2 = [(40, 0, -60), (0, 40, -60)]
L3 = [(90, 0, -10), (0, 90, -10)]
SL1 = [D2, (90, 10, 0)]
SL2 = [D2, (65, 35, 0)]
SL3 = [D2, (35, 65, 0)]
SL4 = [D2, (10, 90, 0)]
SL5 = [(20, 20, -60), (45, 45, -10)]
CL1 = self.TriCross(SL1, L2)
CL2 = self.TriCross(SL2, L3)
CL3 = self.TriCross(SL3, L3)
CL41 = self.TriCross(SL4, L2)
CL42 = self.TriCross(SL4, L3)
NSL1 = [CL1, (90, 10, 0)]
NSL2 = [CL2, (65, 35, 0)]
NSL3 = [CL3, (35, 65, 0)]
NSL4 = [CL41, (10, 90, 0)]
s = [
TriLine(Points=L2, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=L3, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=SL5, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL1, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL2, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL3, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL4, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label='')]
for i in s:
self.axes.plot(i.X, i.Y, color=i.Color, linewidth=i.Width, linestyle=i.Style, alpha=i.Alpha,
label=i.Label)
else:
s = [
TriLine(Points=[ (35, 65, 0),(100, 0, 0), (0, 0, 100), (0, 100, 0),(0, 0, -100), (100, 0, 0)], Sort='',
Width=1, Color='black', Style='-',
Alpha=0.7, Label='')]
for i in s:
self.axes.plot(i.X, i.Y, color=i.Color, linewidth=i.Width, linestyle=i.Style, alpha=i.Alpha,
label=i.Label)
self.Labels = ['1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'17',
'18',
'19',
'20']
self.Locations = [(22,33),
(42,33),
(65,33),
(10, 10),
(25, 10),
(50, 10),
(80, 10),
(6, 1),
(24, 1),
(50, 1),
(6, -5),
(24, -5),
(50, -5),
(18, -30),
(40, -30),
(60, -30),
(78, -30),
(40, -63),
(55, -63),
(48, -82)]
self.setWindowTitle('QAPF modal classification of volcanic rocks')
self.exptext='''
1:alkali feldspar rhyolite,
2:rhyolite,
3:dacite,
4:quartz alkali feldspar trachyte,
5:quartz trachyte,
6:quartz latite,
7:basalt andesite,
8:alkali feldspar trachyte,
9:trachyte,
10:latite,
11:foid-bearing alkali feldspar trachyte,
12:foid-bearing trachyte,
13:foid-bearing latite,
14:phonolite,
15:tephritic phonolite,
16:phonolitic basanite (olivine > 10%) phonolitic tephrite (olivine < 10%),
17:basanite (olivine > 10%) tephrite (olivine < 10%),
18:phonolitic foidite,
19:tephritic foidite,
20:foidoite,
'''
self.textbox.setText(self.reference + '\n' + self.infotext+ '\n' + self.exptext)
D = (0, 0, 100)
L1 = [(10, 0, 90), (0, 10, 90)]
L2 = [(40, 0, 60), (0, 40, 60)]
L3 = [(80, 0, 20), (0, 80, 20)]
L4 = [(95, 0, 5), (0, 95, 5)]
s = [TriLine(Points=L1, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=L2, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=L3, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''), ]
for i in s:
self.axes.plot(i.X, i.Y, color=i.Color, linewidth=i.Width, linestyle=i.Style, alpha=i.Alpha,
label=i.Label)
SL1 = [D, (90, 10, 0)]
SL2 = [D, (65, 35, 0)]
SL3 = [D, (35, 65, 0)]
SL4 = [D, (10, 90, 0)]
CL1 = self.TriCross(SL1, L2)
CL21 = self.TriCross(SL2, L2)
CL22 = self.TriCross(SL2, L3)
CL3 = self.TriCross(SL3, L2)
CL41 = self.TriCross(SL4, L2)
CL42 = self.TriCross(SL4, L3)
TL4 = self.TriCross(SL3, L4)
NL4 = [(95, 0, 5), TL4]
NSL1 = [CL1, (90, 10, 0)]
NSL21 = [CL21, CL22]
NSL22 = [CL22, (65, 35, 0)]
NSL3 = [CL3, (35, 65, 0)]
NSL4 = [CL41, CL42]
s = [TriLine(Points=NL4, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL1, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL21, Sort='', Width=1, Color='black', Style='--', Alpha=0.7,
Label=''),
TriLine(Points=NSL22, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL3, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL4, Sort='', Width=1, Color='black', Style='--', Alpha=0.7,
Label='')]
for i in s:
self.axes.plot(i.X, i.Y, color=i.Color, linewidth=i.Width, linestyle=i.Style, alpha=i.Alpha,
label=i.Label)
D = (0, 0, -100)
L1 = [(10, 0, -90), (0, 10, -90)]
L2 = [(40, 0, -60), (0, 40, -60)]
L3 = [(90, 0, -10), (0, 90, -10)]
SL5 = [(5, 5, -90), (45, 45, -10)]
s = [TriLine(Points=L1, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=L2, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=L3, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=SL5, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label='')]
for i in s:
self.axes.plot(i.X, i.Y, color=i.Color, linewidth=i.Width, linestyle=i.Style, alpha=i.Alpha,
label=i.Label)
SL1 = [D, (90, 10, 0)]
SL2 = [D, (65, 35, 0)]
SL3 = [D, (35, 65, 0)]
SL4 = [D, (10, 90, 0)]
CL1 = self.TriCross(SL1, L2)
CL2 = self.TriCross(SL2, L3)
CL3 = self.TriCross(SL3, L3)
CL41 = self.TriCross(SL4, L2)
CL42 = self.TriCross(SL4, L3)
NSL1 = [CL1, (90, 10, 0)]
NSL2 = [CL2, (65, 35, 0)]
NSL3 = [CL3, (35, 65, 0)]
NSL4 = [CL41, CL42]
s = [TriLine(Points=NSL1, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL2, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL3, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label=''),
TriLine(Points=NSL4, Sort='', Width=1, Color='black', Style='-', Alpha=0.7,
Label='')]
for i in s:
self.axes.plot(i.X, i.Y, color=i.Color, linewidth=i.Width, linestyle=i.Style, alpha=i.Alpha,
label=i.Label)
for i in range(len(self.LabelPosition)):
self.axes.annotate(self.Label[i], xy=(self.LabelPosition[i]), xycoords='data', xytext=(0, 0),
textcoords='offset points',
fontsize=8, )
for i in range(len(self.Labels)):
self.Tags.append(Tag(Label=self.Labels[i],
Location=(self.Locations[i][0], self.Locations[i][1]),
))
if (self.detail_cb.isChecked()):
for i in self.Tags:
self.axes.annotate(i.Label, xy=i.Location,
fontsize=6, color='grey', alpha=0.8)
#raw = self._df
raw = self.CleanDataFile(self._df)
PointLabels = []
TPoints = []
for i in range(len(raw)):
if 'A (Volume)' in raw.columns.values:
q = raw.at[i, 'Q (Volume)']
f = raw.at[i, 'F (Volume)']
a = raw.at[i, 'A (Volume)']
p = raw.at[i, 'P (Volume)']
elif 'A' in raw.columns.values:
q = raw.at[i, 'Q']
f = raw.at[i, 'F']
a = raw.at[i, 'A']
p = raw.at[i, 'P']
TmpLabel = ''
if (raw.at[i, 'Label'] in PointLabels or raw.at[i, 'Label'] == ''):
TmpLabel = ''
else:
PointLabels.append(raw.at[i, 'Label'])
TmpLabel = raw.at[i, 'Label']
if (q != 0 and q != ''):
TPoints.append(TriPoint((a, p, q), Size=raw.at[i, 'Size'],
Color=raw.at[i, 'Color'], Alpha=raw.at[i, 'Alpha'], Marker=raw.at[i, 'Marker'],
Label=TmpLabel))
else:
TPoints.append(TriPoint((a, p, 0 - f), Size=raw.at[i, 'Size'],
Color=raw.at[i, 'Color'], Alpha=raw.at[i, 'Alpha'], Marker=raw.at[i, 'Marker'],
Label=TmpLabel))
for i in TPoints:
self.axes.scatter(i.X, i.Y, marker=i.Marker, s=i.Size, color=i.Color, alpha=i.Alpha,
label=i.Label)
if (self.legend_cb.isChecked()):
self.axes.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0, prop=fontprop)
self.canvas.draw()
self.OutPutFig=self.fig |
GeoPyTool/GeoPyTool | geopytool/CustomClass.py | Tool.TriToBin | python | def TriToBin(self, x, y, z):
'''
Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:return: the corresponding a-b coord
:rtype: a tuple consist of a and b
'''
if (z >= 0):
if (x + y + z == 0):
return (0, 0)
else:
Sum = x + y + z
X = 100.0 * x / Sum
Y = 100.0 * y / Sum
Z = 100.0 * z / Sum
if (X + Y != 0):
a = Z / 2.0 + (100.0 - Z) * Y / (Y + X)
else:
a = Z / 2.0
b = Z / 2.0 * (np.sqrt(3))
return (a, b)
else:
z = abs(z)
if (x + y + z == 0):
return (0, 0)
else:
Sum = x + y + z
X = 100.0 * x / Sum
Y = 100.0 * y / Sum
Z = 100.0 * z / Sum
if (X + Y != 0):
a = Z / 2.0 + (100.0 - Z) * Y / (Y + X)
else:
a = Z / 2.0
b = Z / 2.0 * (np.sqrt(3))
return (a, -b) | Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:return: the corresponding a-b coord
:rtype: a tuple consist of a and b | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/CustomClass.py#L28-L67 | null | class Tool():
def BinToTri(self, a, b):
'''
Turn an a-b coord to an x-y-z triangular coord .
if z is negative, calc with its abs then return (a, -b).
:param a,b: the numbers of the a-b coord
:type a,b: float or double are both OK, just numbers
:return: the corresponding x-y-z triangular coord
:rtype: a tuple consist of x,y,z
'''
if (b >= 0):
y = a - b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a + b / np.sqrt(3))
return (x, y, z)
else:
y = a + b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a - b / np.sqrt(3))
return (x, y, z)
def Cross(self, A=[(0, 0), (10, 10)], B=[(0, 10), (100, 0)]):
'''
Return the crosspoint of two line A and B.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of two numbers, the x-y of the crosspoint
'''
x0, y0 = A[0]
x1, y1 = A[1]
x2, y2 = B[0]
x3, y3 = B[1]
b1 = (y1 - y0) / (x1 - x0)
b2 = (y3 - y2) / (x3 - x2)
c1 = y0 - b1 * x0
c2 = y2 - b2 * x2
x = (c2 - c1) / (b1 - b2)
y = b1 * x + c1
return ([x, y])
def TriCross(self, A=[(100, 0, 0), (0, 50, 60)], B=[(50, 50, 0), (0, 0, 100)]):
'''
Return the crosspoint of two line A and B in triangular coord.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of three numbers, the x-y-z of the triangular coord
'''
x0, y0 = self.TriToBin(A[0][0], A[0][1], A[0][2])
x1, y1 = self.TriToBin(A[1][0], A[1][1], A[1][2])
x2, y2 = self.TriToBin(B[0][0], B[0][1], B[0][2])
x3, y3 = self.TriToBin(B[1][0], B[1][1], B[1][2])
b1 = (y1 - y0) / (x1 - x0)
b2 = (y3 - y2) / (x3 - x2)
c1 = y0 - b1 * x0
c2 = y2 - b2 * x2
x = (c2 - c1) / (b1 - b2)
y = b1 * x + c1
result = self.BinToTri(x, y)
return (result)
def Fill(self, P=[(100, 0), (85, 15), (0, 3)], Color='blue', Alpha=0.3):
'''
Fill a region in planimetric rectangular coord.
:param P: the peak points of the region in planimetric rectangular coord
:type P: a list consist of at least three tuples, which are the points in planimetric rectangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
'''
a = []
b = []
for i in P:
a.append(i[0])
b.append(i[1])
return (a, b)
def TriFill(self, P=[(100, 0, 0), (85, 15, 0), (0, 3, 97)], Color='blue', Alpha=0.3):
'''
Fill a region in triangular coord.
:param P: the peak points of the region in triangular coord
:type P: a list consist of at least three tuples, which are the points in triangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
'''
a = []
b = []
for i in P:
a.append(self.TriToBin(i[0], i[1], i[2])[0])
b.append(self.TriToBin(i[0], i[1], i[2])[1])
return (a, b)
|
GeoPyTool/GeoPyTool | geopytool/CustomClass.py | Tool.BinToTri | python | def BinToTri(self, a, b):
'''
Turn an a-b coord to an x-y-z triangular coord .
if z is negative, calc with its abs then return (a, -b).
:param a,b: the numbers of the a-b coord
:type a,b: float or double are both OK, just numbers
:return: the corresponding x-y-z triangular coord
:rtype: a tuple consist of x,y,z
'''
if (b >= 0):
y = a - b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a + b / np.sqrt(3))
return (x, y, z)
else:
y = a + b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a - b / np.sqrt(3))
return (x, y, z) | Turn an a-b coord to an x-y-z triangular coord .
if z is negative, calc with its abs then return (a, -b).
:param a,b: the numbers of the a-b coord
:type a,b: float or double are both OK, just numbers
:return: the corresponding x-y-z triangular coord
:rtype: a tuple consist of x,y,z | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/CustomClass.py#L69-L89 | null | class Tool():
def TriToBin(self, x, y, z):
'''
Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:return: the corresponding a-b coord
:rtype: a tuple consist of a and b
'''
if (z >= 0):
if (x + y + z == 0):
return (0, 0)
else:
Sum = x + y + z
X = 100.0 * x / Sum
Y = 100.0 * y / Sum
Z = 100.0 * z / Sum
if (X + Y != 0):
a = Z / 2.0 + (100.0 - Z) * Y / (Y + X)
else:
a = Z / 2.0
b = Z / 2.0 * (np.sqrt(3))
return (a, b)
else:
z = abs(z)
if (x + y + z == 0):
return (0, 0)
else:
Sum = x + y + z
X = 100.0 * x / Sum
Y = 100.0 * y / Sum
Z = 100.0 * z / Sum
if (X + Y != 0):
a = Z / 2.0 + (100.0 - Z) * Y / (Y + X)
else:
a = Z / 2.0
b = Z / 2.0 * (np.sqrt(3))
return (a, -b)
def Cross(self, A=[(0, 0), (10, 10)], B=[(0, 10), (100, 0)]):
'''
Return the crosspoint of two line A and B.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of two numbers, the x-y of the crosspoint
'''
x0, y0 = A[0]
x1, y1 = A[1]
x2, y2 = B[0]
x3, y3 = B[1]
b1 = (y1 - y0) / (x1 - x0)
b2 = (y3 - y2) / (x3 - x2)
c1 = y0 - b1 * x0
c2 = y2 - b2 * x2
x = (c2 - c1) / (b1 - b2)
y = b1 * x + c1
return ([x, y])
def TriCross(self, A=[(100, 0, 0), (0, 50, 60)], B=[(50, 50, 0), (0, 0, 100)]):
'''
Return the crosspoint of two line A and B in triangular coord.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of three numbers, the x-y-z of the triangular coord
'''
x0, y0 = self.TriToBin(A[0][0], A[0][1], A[0][2])
x1, y1 = self.TriToBin(A[1][0], A[1][1], A[1][2])
x2, y2 = self.TriToBin(B[0][0], B[0][1], B[0][2])
x3, y3 = self.TriToBin(B[1][0], B[1][1], B[1][2])
b1 = (y1 - y0) / (x1 - x0)
b2 = (y3 - y2) / (x3 - x2)
c1 = y0 - b1 * x0
c2 = y2 - b2 * x2
x = (c2 - c1) / (b1 - b2)
y = b1 * x + c1
result = self.BinToTri(x, y)
return (result)
def Fill(self, P=[(100, 0), (85, 15), (0, 3)], Color='blue', Alpha=0.3):
'''
Fill a region in planimetric rectangular coord.
:param P: the peak points of the region in planimetric rectangular coord
:type P: a list consist of at least three tuples, which are the points in planimetric rectangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
'''
a = []
b = []
for i in P:
a.append(i[0])
b.append(i[1])
return (a, b)
def TriFill(self, P=[(100, 0, 0), (85, 15, 0), (0, 3, 97)], Color='blue', Alpha=0.3):
'''
Fill a region in triangular coord.
:param P: the peak points of the region in triangular coord
:type P: a list consist of at least three tuples, which are the points in triangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
'''
a = []
b = []
for i in P:
a.append(self.TriToBin(i[0], i[1], i[2])[0])
b.append(self.TriToBin(i[0], i[1], i[2])[1])
return (a, b)
|
GeoPyTool/GeoPyTool | geopytool/CustomClass.py | Tool.Cross | python | def Cross(self, A=[(0, 0), (10, 10)], B=[(0, 10), (100, 0)]):
'''
Return the crosspoint of two line A and B.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of two numbers, the x-y of the crosspoint
'''
x0, y0 = A[0]
x1, y1 = A[1]
x2, y2 = B[0]
x3, y3 = B[1]
b1 = (y1 - y0) / (x1 - x0)
b2 = (y3 - y2) / (x3 - x2)
c1 = y0 - b1 * x0
c2 = y2 - b2 * x2
x = (c2 - c1) / (b1 - b2)
y = b1 * x + c1
return ([x, y]) | Return the crosspoint of two line A and B.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of two numbers, the x-y of the crosspoint | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/CustomClass.py#L91-L116 | null | class Tool():
def TriToBin(self, x, y, z):
'''
Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:return: the corresponding a-b coord
:rtype: a tuple consist of a and b
'''
if (z >= 0):
if (x + y + z == 0):
return (0, 0)
else:
Sum = x + y + z
X = 100.0 * x / Sum
Y = 100.0 * y / Sum
Z = 100.0 * z / Sum
if (X + Y != 0):
a = Z / 2.0 + (100.0 - Z) * Y / (Y + X)
else:
a = Z / 2.0
b = Z / 2.0 * (np.sqrt(3))
return (a, b)
else:
z = abs(z)
if (x + y + z == 0):
return (0, 0)
else:
Sum = x + y + z
X = 100.0 * x / Sum
Y = 100.0 * y / Sum
Z = 100.0 * z / Sum
if (X + Y != 0):
a = Z / 2.0 + (100.0 - Z) * Y / (Y + X)
else:
a = Z / 2.0
b = Z / 2.0 * (np.sqrt(3))
return (a, -b)
def BinToTri(self, a, b):
'''
Turn an a-b coord to an x-y-z triangular coord .
if z is negative, calc with its abs then return (a, -b).
:param a,b: the numbers of the a-b coord
:type a,b: float or double are both OK, just numbers
:return: the corresponding x-y-z triangular coord
:rtype: a tuple consist of x,y,z
'''
if (b >= 0):
y = a - b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a + b / np.sqrt(3))
return (x, y, z)
else:
y = a + b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a - b / np.sqrt(3))
return (x, y, z)
def TriCross(self, A=[(100, 0, 0), (0, 50, 60)], B=[(50, 50, 0), (0, 0, 100)]):
'''
Return the crosspoint of two line A and B in triangular coord.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of three numbers, the x-y-z of the triangular coord
'''
x0, y0 = self.TriToBin(A[0][0], A[0][1], A[0][2])
x1, y1 = self.TriToBin(A[1][0], A[1][1], A[1][2])
x2, y2 = self.TriToBin(B[0][0], B[0][1], B[0][2])
x3, y3 = self.TriToBin(B[1][0], B[1][1], B[1][2])
b1 = (y1 - y0) / (x1 - x0)
b2 = (y3 - y2) / (x3 - x2)
c1 = y0 - b1 * x0
c2 = y2 - b2 * x2
x = (c2 - c1) / (b1 - b2)
y = b1 * x + c1
result = self.BinToTri(x, y)
return (result)
def Fill(self, P=[(100, 0), (85, 15), (0, 3)], Color='blue', Alpha=0.3):
'''
Fill a region in planimetric rectangular coord.
:param P: the peak points of the region in planimetric rectangular coord
:type P: a list consist of at least three tuples, which are the points in planimetric rectangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
'''
a = []
b = []
for i in P:
a.append(i[0])
b.append(i[1])
return (a, b)
def TriFill(self, P=[(100, 0, 0), (85, 15, 0), (0, 3, 97)], Color='blue', Alpha=0.3):
'''
Fill a region in triangular coord.
:param P: the peak points of the region in triangular coord
:type P: a list consist of at least three tuples, which are the points in triangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
'''
a = []
b = []
for i in P:
a.append(self.TriToBin(i[0], i[1], i[2])[0])
b.append(self.TriToBin(i[0], i[1], i[2])[1])
return (a, b)
|
GeoPyTool/GeoPyTool | geopytool/CustomClass.py | Tool.TriCross | python | def TriCross(self, A=[(100, 0, 0), (0, 50, 60)], B=[(50, 50, 0), (0, 0, 100)]):
'''
Return the crosspoint of two line A and B in triangular coord.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of three numbers, the x-y-z of the triangular coord
'''
x0, y0 = self.TriToBin(A[0][0], A[0][1], A[0][2])
x1, y1 = self.TriToBin(A[1][0], A[1][1], A[1][2])
x2, y2 = self.TriToBin(B[0][0], B[0][1], B[0][2])
x3, y3 = self.TriToBin(B[1][0], B[1][1], B[1][2])
b1 = (y1 - y0) / (x1 - x0)
b2 = (y3 - y2) / (x3 - x2)
c1 = y0 - b1 * x0
c2 = y2 - b2 * x2
x = (c2 - c1) / (b1 - b2)
y = b1 * x + c1
result = self.BinToTri(x, y)
return (result) | Return the crosspoint of two line A and B in triangular coord.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of three numbers, the x-y-z of the triangular coord | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/CustomClass.py#L118-L144 | [
"def TriToBin(self, x, y, z):\n\n '''\n Turn an x-y-z triangular coord to an a-b coord.\n if z is negative, calc with its abs then return (a, -b).\n :param x,y,z: the three numbers of the triangular coord\n :type x,y,z: float or double are both OK, just numbers\n :return: the corresponding a-b co... | class Tool():
def TriToBin(self, x, y, z):
'''
Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:return: the corresponding a-b coord
:rtype: a tuple consist of a and b
'''
if (z >= 0):
if (x + y + z == 0):
return (0, 0)
else:
Sum = x + y + z
X = 100.0 * x / Sum
Y = 100.0 * y / Sum
Z = 100.0 * z / Sum
if (X + Y != 0):
a = Z / 2.0 + (100.0 - Z) * Y / (Y + X)
else:
a = Z / 2.0
b = Z / 2.0 * (np.sqrt(3))
return (a, b)
else:
z = abs(z)
if (x + y + z == 0):
return (0, 0)
else:
Sum = x + y + z
X = 100.0 * x / Sum
Y = 100.0 * y / Sum
Z = 100.0 * z / Sum
if (X + Y != 0):
a = Z / 2.0 + (100.0 - Z) * Y / (Y + X)
else:
a = Z / 2.0
b = Z / 2.0 * (np.sqrt(3))
return (a, -b)
def BinToTri(self, a, b):
'''
Turn an a-b coord to an x-y-z triangular coord .
if z is negative, calc with its abs then return (a, -b).
:param a,b: the numbers of the a-b coord
:type a,b: float or double are both OK, just numbers
:return: the corresponding x-y-z triangular coord
:rtype: a tuple consist of x,y,z
'''
if (b >= 0):
y = a - b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a + b / np.sqrt(3))
return (x, y, z)
else:
y = a + b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a - b / np.sqrt(3))
return (x, y, z)
def Cross(self, A=[(0, 0), (10, 10)], B=[(0, 10), (100, 0)]):
'''
Return the crosspoint of two line A and B.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of two numbers, the x-y of the crosspoint
'''
x0, y0 = A[0]
x1, y1 = A[1]
x2, y2 = B[0]
x3, y3 = B[1]
b1 = (y1 - y0) / (x1 - x0)
b2 = (y3 - y2) / (x3 - x2)
c1 = y0 - b1 * x0
c2 = y2 - b2 * x2
x = (c2 - c1) / (b1 - b2)
y = b1 * x + c1
return ([x, y])
def Fill(self, P=[(100, 0), (85, 15), (0, 3)], Color='blue', Alpha=0.3):
'''
Fill a region in planimetric rectangular coord.
:param P: the peak points of the region in planimetric rectangular coord
:type P: a list consist of at least three tuples, which are the points in planimetric rectangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
'''
a = []
b = []
for i in P:
a.append(i[0])
b.append(i[1])
return (a, b)
def TriFill(self, P=[(100, 0, 0), (85, 15, 0), (0, 3, 97)], Color='blue', Alpha=0.3):
'''
Fill a region in triangular coord.
:param P: the peak points of the region in triangular coord
:type P: a list consist of at least three tuples, which are the points in triangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
'''
a = []
b = []
for i in P:
a.append(self.TriToBin(i[0], i[1], i[2])[0])
b.append(self.TriToBin(i[0], i[1], i[2])[1])
return (a, b)
|
GeoPyTool/GeoPyTool | geopytool/CustomClass.py | Tool.Fill | python | def Fill(self, P=[(100, 0), (85, 15), (0, 3)], Color='blue', Alpha=0.3):
'''
Fill a region in planimetric rectangular coord.
:param P: the peak points of the region in planimetric rectangular coord
:type P: a list consist of at least three tuples, which are the points in planimetric rectangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
'''
a = []
b = []
for i in P:
a.append(i[0])
b.append(i[1])
return (a, b) | Fill a region in planimetric rectangular coord.
:param P: the peak points of the region in planimetric rectangular coord
:type P: a list consist of at least three tuples, which are the points in planimetric rectangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/CustomClass.py#L146-L164 | null | class Tool():
def TriToBin(self, x, y, z):
'''
Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:return: the corresponding a-b coord
:rtype: a tuple consist of a and b
'''
if (z >= 0):
if (x + y + z == 0):
return (0, 0)
else:
Sum = x + y + z
X = 100.0 * x / Sum
Y = 100.0 * y / Sum
Z = 100.0 * z / Sum
if (X + Y != 0):
a = Z / 2.0 + (100.0 - Z) * Y / (Y + X)
else:
a = Z / 2.0
b = Z / 2.0 * (np.sqrt(3))
return (a, b)
else:
z = abs(z)
if (x + y + z == 0):
return (0, 0)
else:
Sum = x + y + z
X = 100.0 * x / Sum
Y = 100.0 * y / Sum
Z = 100.0 * z / Sum
if (X + Y != 0):
a = Z / 2.0 + (100.0 - Z) * Y / (Y + X)
else:
a = Z / 2.0
b = Z / 2.0 * (np.sqrt(3))
return (a, -b)
def BinToTri(self, a, b):
'''
Turn an a-b coord to an x-y-z triangular coord .
if z is negative, calc with its abs then return (a, -b).
:param a,b: the numbers of the a-b coord
:type a,b: float or double are both OK, just numbers
:return: the corresponding x-y-z triangular coord
:rtype: a tuple consist of x,y,z
'''
if (b >= 0):
y = a - b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a + b / np.sqrt(3))
return (x, y, z)
else:
y = a + b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a - b / np.sqrt(3))
return (x, y, z)
def Cross(self, A=[(0, 0), (10, 10)], B=[(0, 10), (100, 0)]):
'''
Return the crosspoint of two line A and B.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of two numbers, the x-y of the crosspoint
'''
x0, y0 = A[0]
x1, y1 = A[1]
x2, y2 = B[0]
x3, y3 = B[1]
b1 = (y1 - y0) / (x1 - x0)
b2 = (y3 - y2) / (x3 - x2)
c1 = y0 - b1 * x0
c2 = y2 - b2 * x2
x = (c2 - c1) / (b1 - b2)
y = b1 * x + c1
return ([x, y])
def TriCross(self, A=[(100, 0, 0), (0, 50, 60)], B=[(50, 50, 0), (0, 0, 100)]):
'''
Return the crosspoint of two line A and B in triangular coord.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of three numbers, the x-y-z of the triangular coord
'''
x0, y0 = self.TriToBin(A[0][0], A[0][1], A[0][2])
x1, y1 = self.TriToBin(A[1][0], A[1][1], A[1][2])
x2, y2 = self.TriToBin(B[0][0], B[0][1], B[0][2])
x3, y3 = self.TriToBin(B[1][0], B[1][1], B[1][2])
b1 = (y1 - y0) / (x1 - x0)
b2 = (y3 - y2) / (x3 - x2)
c1 = y0 - b1 * x0
c2 = y2 - b2 * x2
x = (c2 - c1) / (b1 - b2)
y = b1 * x + c1
result = self.BinToTri(x, y)
return (result)
def TriFill(self, P=[(100, 0, 0), (85, 15, 0), (0, 3, 97)], Color='blue', Alpha=0.3):
'''
Fill a region in triangular coord.
:param P: the peak points of the region in triangular coord
:type P: a list consist of at least three tuples, which are the points in triangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
'''
a = []
b = []
for i in P:
a.append(self.TriToBin(i[0], i[1], i[2])[0])
b.append(self.TriToBin(i[0], i[1], i[2])[1])
return (a, b)
|
GeoPyTool/GeoPyTool | geopytool/CustomClass.py | Tool.TriFill | python | def TriFill(self, P=[(100, 0, 0), (85, 15, 0), (0, 3, 97)], Color='blue', Alpha=0.3):
'''
Fill a region in triangular coord.
:param P: the peak points of the region in triangular coord
:type P: a list consist of at least three tuples, which are the points in triangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
'''
a = []
b = []
for i in P:
a.append(self.TriToBin(i[0], i[1], i[2])[0])
b.append(self.TriToBin(i[0], i[1], i[2])[1])
return (a, b) | Fill a region in triangular coord.
:param P: the peak points of the region in triangular coord
:type P: a list consist of at least three tuples, which are the points in triangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/CustomClass.py#L166-L185 | [
"def TriToBin(self, x, y, z):\n\n '''\n Turn an x-y-z triangular coord to an a-b coord.\n if z is negative, calc with its abs then return (a, -b).\n :param x,y,z: the three numbers of the triangular coord\n :type x,y,z: float or double are both OK, just numbers\n :return: the corresponding a-b co... | class Tool():
def TriToBin(self, x, y, z):
'''
Turn an x-y-z triangular coord to an a-b coord.
if z is negative, calc with its abs then return (a, -b).
:param x,y,z: the three numbers of the triangular coord
:type x,y,z: float or double are both OK, just numbers
:return: the corresponding a-b coord
:rtype: a tuple consist of a and b
'''
if (z >= 0):
if (x + y + z == 0):
return (0, 0)
else:
Sum = x + y + z
X = 100.0 * x / Sum
Y = 100.0 * y / Sum
Z = 100.0 * z / Sum
if (X + Y != 0):
a = Z / 2.0 + (100.0 - Z) * Y / (Y + X)
else:
a = Z / 2.0
b = Z / 2.0 * (np.sqrt(3))
return (a, b)
else:
z = abs(z)
if (x + y + z == 0):
return (0, 0)
else:
Sum = x + y + z
X = 100.0 * x / Sum
Y = 100.0 * y / Sum
Z = 100.0 * z / Sum
if (X + Y != 0):
a = Z / 2.0 + (100.0 - Z) * Y / (Y + X)
else:
a = Z / 2.0
b = Z / 2.0 * (np.sqrt(3))
return (a, -b)
def BinToTri(self, a, b):
'''
Turn an a-b coord to an x-y-z triangular coord .
if z is negative, calc with its abs then return (a, -b).
:param a,b: the numbers of the a-b coord
:type a,b: float or double are both OK, just numbers
:return: the corresponding x-y-z triangular coord
:rtype: a tuple consist of x,y,z
'''
if (b >= 0):
y = a - b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a + b / np.sqrt(3))
return (x, y, z)
else:
y = a + b / np.sqrt(3)
z = b * 2 / np.sqrt(3)
x = 100 - (a - b / np.sqrt(3))
return (x, y, z)
def Cross(self, A=[(0, 0), (10, 10)], B=[(0, 10), (100, 0)]):
'''
Return the crosspoint of two line A and B.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of two numbers, the x-y of the crosspoint
'''
x0, y0 = A[0]
x1, y1 = A[1]
x2, y2 = B[0]
x3, y3 = B[1]
b1 = (y1 - y0) / (x1 - x0)
b2 = (y3 - y2) / (x3 - x2)
c1 = y0 - b1 * x0
c2 = y2 - b2 * x2
x = (c2 - c1) / (b1 - b2)
y = b1 * x + c1
return ([x, y])
def TriCross(self, A=[(100, 0, 0), (0, 50, 60)], B=[(50, 50, 0), (0, 0, 100)]):
'''
Return the crosspoint of two line A and B in triangular coord.
:param A: first line
:type A: a list consist of two tuples, beginning and end point of the line
:param B: second line
:type B: a list consist of two tuples, beginning and end point of the line
:return: the crosspoint of A and B
:rtype: a list consist of three numbers, the x-y-z of the triangular coord
'''
x0, y0 = self.TriToBin(A[0][0], A[0][1], A[0][2])
x1, y1 = self.TriToBin(A[1][0], A[1][1], A[1][2])
x2, y2 = self.TriToBin(B[0][0], B[0][1], B[0][2])
x3, y3 = self.TriToBin(B[1][0], B[1][1], B[1][2])
b1 = (y1 - y0) / (x1 - x0)
b2 = (y3 - y2) / (x3 - x2)
c1 = y0 - b1 * x0
c2 = y2 - b2 * x2
x = (c2 - c1) / (b1 - b2)
y = b1 * x + c1
result = self.BinToTri(x, y)
return (result)
def Fill(self, P=[(100, 0), (85, 15), (0, 3)], Color='blue', Alpha=0.3):
'''
Fill a region in planimetric rectangular coord.
:param P: the peak points of the region in planimetric rectangular coord
:type P: a list consist of at least three tuples, which are the points in planimetric rectangular coord
:param Color: the color used to fill the region
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Alpha: the transparency used to fill the region
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
'''
a = []
b = []
for i in P:
a.append(i[0])
b.append(i[1])
return (a, b)
|
GeoPyTool/GeoPyTool | geopytool/CustomClass.py | Line.sequence | python | def sequence(self):
'''
sort the points in the line with given option
'''
if (len(self.Points[0]) == 2):
if (self.Sort == 'X' or self.Sort == 'x'):
self.Points.sort(key=lambda x: x[0])
self.order(self.Points)
elif (self.Sort == 'Y' or self.Sort == 'y'):
self.Points.sort(key=lambda x: x[1])
self.order(self.Points)
else:
self.order(self.Points)
if (len(self.Points[0]) == 3):
if (self.Sort == 'X' or self.Sort == 'x'):
self.Points.sort(key=lambda x: x[0])
self.order(self.Points)
elif (self.Sort == 'Y' or self.Sort == 'y'):
self.Points.sort(key=lambda x: x[1])
self.order(self.Points)
elif (self.Sort == 'Z' or self.Sort == 'Z'):
self.Points.sort(key=lambda x: x[2])
self.order(self.Points)
else:
self.order(self.Points) | sort the points in the line with given option | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/CustomClass.py#L367-L394 | [
"def order(self, TMP=[]):\n X_TMP = []\n Y_TMP = []\n for i in TMP:\n X_TMP.append(i[0])\n Y_TMP.append(i[1])\n self.X = X_TMP\n self.Y = Y_TMP\n",
"def order(self, TMP=[]):\n X_TMP = []\n Y_TMP = []\n Z_TMP = []\n for i in TMP:\n X_TMP.append(i[0])\n Y_TMP.a... | class Line():
'''
a line class
:param Begin: the Beginning point of the line
:type Begin: a Point Instance
:param End: the End point of the line
:type End: a Point Instance
:param Points: gathering all the Point Instances
:type Points: a list
:param X,Y: the gathered x and y values of the line to use in plotting
:type X,Y: two lists containing float numbers
:param Width: the width of the line
:type Width: an int number , mayby float is OK
:param Color: the color of the Line to draw on canvas
:type Color: a string; b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white
:param Style: the style used for the Line
:type Style: a string; -, --,-., : maybe there would be some other types , from matplotlib
:param Alpha: the transparency of the Point
:type Alpha: a float number from 0 to 1, higher darker, lower more transparent
:param Label: label of the Line, telling what it is and distinguish it from other lines
:type Label: a string , if leave as '' or '' such kind of blank string, the label will not show on canvas
:param Sort: the sequence used for sorting the points consisting the line
:type Sort: a string, x means sort the points with their x values, y means use y instead of x, other means use the sequence of points as these points are put to the line
'''
Begin = Point(0, 0)
End = Point(1, 1)
Points = []
X = [Begin.X, End.X]
Y = [Begin.Y, End.Y]
Width = 1
Color = 'blue'
Style = '-'
Alpha = 0.3
Label = ''
Sort = ''
def __init__(self, Points=[(0, 0), (1, 1)], Sort='', Width=1, Color='blue', Style='-', Alpha=0.3, Label=''):
'''
setup the datas
'''
super().__init__()
self.Sort = Sort
self.Width = Width
self.Color = Color
self.Style = Style
self.Alpha = Alpha
self.Label = Label
if (len(Points) == 2):
self.X = [Points[0][0], Points[1][0]]
self.Y = [Points[0][1], Points[1][1]]
self.Points = Points
elif (len(Points) > 2):
self.Points = Points
else:
# print('Cannot draw line with one point')
pass
def order(self, TMP=[]):
X_TMP = []
Y_TMP = []
for i in TMP:
X_TMP.append(i[0])
Y_TMP.append(i[1])
self.X = X_TMP
self.Y = Y_TMP
|
GeoPyTool/GeoPyTool | geopytool/CustomClass.py | TableViewer.resizeEvent | python | def resizeEvent(self, evt=None):
w = self.width()
h = self.height()
'''
if h<=360:
h=360
self.resize(w,h)
if w<=640:
w = 640
self.resize(w, h)
'''
step = (w * 94 / 100) / 5
foot = h * 3 / 48 | if h<=360:
h=360
self.resize(w,h)
if w<=640:
w = 640
self.resize(w, h) | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/CustomClass.py#L813-L827 | null | class TableViewer(QMainWindow):
addon = 'Name Author DataType Label Marker Color Size Alpha Style Width TOTAL total LOI loi'
Minerals = ['Quartz',
'Zircon',
'K2SiO3',
'Anorthite',
'Na2SiO3',
'Acmite',
'Diopside',
'Sphene',
'Hypersthene',
'Albite',
'Orthoclase',
'Wollastonite',
'Olivine',
'Perovskite',
'Nepheline',
'Leucite',
'Larnite',
'Kalsilite',
'Apatite',
'Halite',
'Fluorite',
'Anhydrite',
'Thenardite',
'Pyrite',
'Magnesiochromite',
'Chromite',
'Ilmenite',
'Calcite',
'Na2CO3',
'Corundum',
'Rutile',
'Magnetite',
'Hematite',
'Q',
'A',
'P',
'F', ]
Calced = ['Fe3+/(Total Fe) in rock',
'Mg/(Mg+Total Fe) in rock',
'Mg/(Mg+Fe2+) in rock',
'Mg/(Mg+Fe2+) in silicates',
'Ca/(Ca+Na) in rock',
'Plagioclase An content',
'Differentiation Index']
DataWeight = {}
DataVolume = {}
DataBase = {}
DataCalced = {}
raw = pd.DataFrame()
result = pd.DataFrame()
Para = pd.DataFrame()
_df = pd.DataFrame()
data_to_test = pd.DataFrame()
data_to_test_location =''
begin_result = pd.DataFrame()
load_result = pd.DataFrame()
def __init__(self, parent=None, df=pd.DataFrame(), title='Statistical Result'):
QMainWindow.__init__(self, parent)
self.setAcceptDrops(True)
self.setWindowTitle(title)
self.df = df
self.create_main_frame()
self.create_status_bar()
def Old__init__(self, parent=None, df=pd.DataFrame()):
QWidget.__init__(self, parent)
self.setWindowTitle('TAS (total alkali–silica) diagram Volcanic/Intrusive (Wilson et al. 1989)')
self._df = df
if (len(df) > 0):
self._changed = True
# print('DataFrame recieved to TabelView')
self.AllLabel = []
for i in range(len(self._df)):
tmp_label = self._df.at[i, 'Label']
if tmp_label not in self.AllLabel:
self.AllLabel.append(tmp_label)
for i in range(len(self.LocationAreas)):
tmpi = self.LocationAreas[i] + [self.LocationAreas[i][0]]
tmppath = path.Path(tmpi)
self.AreasHeadClosed.append(tmpi)
patch = patches.PathPatch(tmppath, facecolor='orange', lw=0.3, alpha=0.3)
self.SelectDic[self.ItemNames[i]] = tmppath
self.create_main_frame()
self.create_status_bar()
def create_main_frame(self):
self.resize(800, 600)
self.main_frame = QWidget()
self.save_button = QPushButton('&Save')
self.save_button.clicked.connect(self.saveResult)
self.tableView = CustomQTableView(self.main_frame)
self.tableView.setObjectName('tableView')
self.tableView.setSortingEnabled(True)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.tableView)
self.vbox.addWidget(self.save_button)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame)
self.model = PandasModel(self.df)
self.tableView.setModel(self.model)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dropEvent(self, event):
files = [(u.toLocalFile()) for u in event.mimeData().urls()]
for f in files:
print(f)
def clearLayout(self, layout):
if layout is not None:
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
else:
self.clearLayout(item.layout())
def ErrorEvent(self, text=''):
_translate = QtCore.QCoreApplication.translate
if (text == ''):
reply = QMessageBox.information(self, _translate('MainWindow', 'Warning'), _translate('MainWindow',
'Your Data mismatch this Function.\n Some Items missing?\n Or maybe there are blanks in items names?\n Or there are nonnumerical value?'))
else:
reply = QMessageBox.information(self, _translate('MainWindow', 'Warning'), _translate('MainWindow',
'Your Data mismatch this Function.\n Error infor is:') + text)
def create_main_frame(self):
self.resize(800, 600)
self.main_frame = QWidget()
self.save_button = QPushButton('&Save')
self.save_button.clicked.connect(self.saveDataFile)
self.tableView = CustomQTableView(self.main_frame)
self.tableView.setObjectName('tableView')
self.tableView.setSortingEnabled(True)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.tableView)
self.vbox.addWidget(self.save_button)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame)
self.model = PandasModel(self.df)
self.tableView.setModel(self.model)
def create_status_bar(self):
self.status_text = QLabel("Click Save button to save.")
self.statusBar().addWidget(self.status_text, 1)
def add_actions(self, target, actions):
for action in actions:
if action is None:
target.addSeparator()
else:
target.addAction(action)
def saveDataFile(self):
# if self.model._changed == True:
# print('changed')
# print(self.model._df)
DataFileOutput, ok2 = QFileDialog.getSaveFileName(self,
'文件保存',
'C:/',
'Excel Files (*.xlsx);;CSV Files (*.csv)') # 数据文件保存输出
if "Label" in self.model._df.columns.values.tolist():
self.model._df = self.model._df.set_index('Label')
if (DataFileOutput != ''):
if ('csv' in DataFileOutput):
self.model._df.to_csv(DataFileOutput, sep=',', encoding='utf-8')
elif ('xls' in DataFileOutput):
self.model._df.to_excel(DataFileOutput, encoding='utf-8')
def create_action(self, text, slot=None, shortcut=None,
icon=None, tip=None, checkable=False,
signal='triggered()'):
action = QAction(text, self)
if icon is not None:
action.setIcon(QIcon(':/%s.png' % icon))
if shortcut is not None:
action.setShortcut(shortcut)
if tip is not None:
action.setToolTip(tip)
action.setStatusTip(tip)
if slot is not None:
action.triggered.connect(slot)
if checkable:
action.setCheckable(True)
return action
|
GeoPyTool/GeoPyTool | geopytool/K2OSiO2.py | K2OSiO2.K2OSiO2 | python | def K2OSiO2(self, Left=35, Right=79, X0=30, X1=90, X_Gap=7, Base=0,
Top=19, Y0=1, Y1=19, Y_Gap=19, FontSize=12, xlabel=r'$SiO_2 wt\%$', ylabel=r'$K_2O wt\%$', width=12,
height=12, dpi=300):
self.setWindowTitle('K2OSiO2 diagram ')
self.axes.clear()
#self.axes.axis('off')
self.axes.set_xlabel(self.xlabel)
self.axes.set_ylabel(self.ylabel)
self.axes.spines['right'].set_color('none')
self.axes.spines['top'].set_color('none')
'''
self.axes.set_xticks([30,40,50,60,70,80,90])
self.axes.set_xticklabels([30,40,50,60,70,80,90])
self.axes.set_yticks([0, 5, 10, 15, 20])
self.axes.set_yticklabels([0, 5, 10, 15, 20])
self.axes.set_ylim(bottom=0)
'''
all_labels=[]
all_colors=[]
all_markers=[]
all_alpha=[]
for i in range(len(self._df)):
target = self._df.at[i, 'Label']
color = self._df.at[i, 'Color']
marker = self._df.at[i, 'Marker']
alpha = self._df.at[i, 'Alpha']
if target not in self.SVM_labels:
self.SVM_labels.append(target)
if target not in all_labels:
all_labels.append(target)
all_colors.append(color)
all_markers.append(marker)
all_alpha.append(alpha)
self.whole_labels = all_labels
PointLabels = []
PointColors = []
x = []
y = []
title = 'K2O-SiO2diagram'
self.setWindowTitle(title)
self.textbox.setText(self.reference)
k_1=(2.9-1.2)/(68-48)
y_1= 1.2+ (85-48)*k_1
y_0= 1.2+ (45-48)*k_1
self.DrawLine([(45, y_0),(48, 1.2), (68,2.9),(85,y_1)])
k_2=(1.2-0.3)/(68-48)
y_2= 0.3+ (85-48)*k_2
y_3= 0.3+ (45-48)*k_2
self.DrawLine([(45, y_3),(48, 0.3), (68, 1.2),(85,y_2)])
Labels=['High K','Medium K','Low K']
Locations=[(80,5),(80,3),(80,1)]
X_offset, Y_offset=0,0
for k in range(len(Labels)):
self.axes.annotate(Labels[k], Locations[k], xycoords='data', xytext=(X_offset, Y_offset),
textcoords='offset points',
fontsize=9, color='grey', alpha=0.8)
self.Check()
if self.OutPutCheck==True:
pass
if (self._changed):
df = self.CleanDataFile(self._df)
for i in range(len(df)):
TmpLabel = ''
if (df.at[i, 'Label'] in PointLabels or df.at[i, 'Label'] == ''):
TmpLabel = ''
else:
PointLabels.append(df.at[i, 'Label'])
TmpLabel = df.at[i, 'Label']
TmpColor = ''
if (df.at[i, 'Color'] in PointColors or df.at[i, 'Color'] == ''):
TmpColor = ''
else:
PointColors.append(df.at[i, 'Color'])
TmpColor = df.at[i, 'Color']
x.append(df.at[i, 'SiO2'])
y.append(df.at[i, 'K2O'])
Size = df.at[i, 'Size']
Color = df.at[i, 'Color']
# print(Color, df.at[i, 'SiO2'], (df.at[i, 'Na2O'] + df.at[i, 'K2O']))
Alpha = df.at[i, 'Alpha']
Marker = df.at[i, 'Marker']
Label = df.at[i, 'Label']
xtest=df.at[i, 'SiO2']
ytest=df.at[i, 'K2O']
for j in self.ItemNames:
if self.SelectDic[j].contains_point([xtest,ytest]):
self.LabelList.append(Label)
self.TypeList.append(j)
break
pass
self.axes.scatter(df.at[i, 'SiO2'], df.at[i, 'K2O'], marker=df.at[i, 'Marker'],
s=df.at[i, 'Size'], color=df.at[i, 'Color'], alpha=df.at[i, 'Alpha'], label=TmpLabel)
XtoFit = {}
YtoFit = {}
SVM_X=[]
SVM_Y=[]
for i in PointLabels:
XtoFit[i]=[]
YtoFit[i]=[]
for i in range(len(df)):
Alpha = df.at[i, 'Alpha']
Marker = df.at[i, 'Marker']
Label = df.at[i, 'Label']
xtest=df.at[i, 'SiO2']
ytest=df.at[i, 'K2O']
XtoFit[Label].append(xtest)
YtoFit[Label].append(ytest)
SVM_X.append(xtest)
SVM_Y.append(ytest)
if (self.shape_cb.isChecked()):
for i in PointLabels:
if XtoFit[i] != YtoFit[i]:
xmin, xmax = min(XtoFit[i]), max(XtoFit[i])
ymin, ymax = min(YtoFit[i]), max(YtoFit[i])
DensityColorMap = 'Greys'
DensityAlpha = 0.1
DensityLineColor = PointColors[PointLabels.index(i)]
DensityLineAlpha = 0.3
# Peform the kernel density estimate
xx, yy = np.mgrid[xmin:xmax:200j, ymin:ymax:200j]
# print(self.ShapeGroups)
# command='''xx, yy = np.mgrid[xmin:xmax:'''+str(self.ShapeGroups)+ '''j, ymin:ymax:''' +str(self.ShapeGroups)+'''j]'''
# exec(command)
# print(xx, yy)
positions = np.vstack([xx.ravel(), yy.ravel()])
values = np.vstack([XtoFit[i], YtoFit[i]])
kernelstatus = True
try:
st.gaussian_kde(values)
except Exception as e:
self.ErrorEvent(text=repr(e))
kernelstatus = False
if kernelstatus == True:
kernel = st.gaussian_kde(values)
f = np.reshape(kernel(positions).T, xx.shape)
# Contourf plot
cfset = self.axes.contourf(xx, yy, f, cmap=DensityColorMap, alpha=DensityAlpha)
## Or kernel density estimate plot instead of the contourf plot
# self.axes.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax])
# Contour plot
cset = self.axes.contour(xx, yy, f, colors=DensityLineColor, alpha=DensityLineAlpha)
# Label plot
#self.axes.clabel(cset, inline=1, fontsize=10)
if (len(self.data_to_test) > 0):
contained = True
missing = 'Miss setting infor:'
for i in ['Label', 'Color', 'Marker', 'Alpha']:
if i not in self.data_to_test.columns.values.tolist():
contained = False
missing = missing + '\n' + i
if contained == True:
for i in self.data_to_test.columns.values.tolist():
if i not in self._df.columns.values.tolist():
self.data_to_test = self.data_to_test.drop(columns=i)
# print(self.data_to_test)
test_labels = []
test_colors = []
test_markers = []
test_alpha = []
for i in range(len(self.data_to_test)):
# print(self.data_to_test.at[i, 'Label'])
target = self.data_to_test.at[i, 'Label']
color = self.data_to_test.at[i, 'Color']
marker = self.data_to_test.at[i, 'Marker']
alpha = self.data_to_test.at[i, 'Alpha']
if target not in test_labels and target not in all_labels:
test_labels.append(target)
test_colors.append(color)
test_markers.append(marker)
test_alpha.append(alpha)
self.whole_labels = self.whole_labels + test_labels
self.load_settings_backup = self.data_to_test
Load_ItemsToTest = ['Label', 'Number', 'Tag', 'Name', 'Author', 'DataType', 'Marker', 'Color',
'Size',
'Alpha',
'Style', 'Width']
for i in self.data_to_test.columns.values.tolist():
if i not in Load_ItemsToTest:
self.load_settings_backup = self.load_settings_backup.drop(i, 1)
print(self.load_settings_backup, self.data_to_test)
print(self.load_settings_backup.shape, self.data_to_test.shape)
try:
for i in range(len(self.data_to_test)):
target = self.data_to_test.at[i, 'Label']
if target not in all_labels:
all_labels.append(target)
tmp_label = self.data_to_test.at[i, 'Label']
else:
tmp_label=''
x_load_test = self.data_to_test.at[i, 'SiO2']
y_load_test = self.data_to_test.at[i, 'K2O']
for j in self.ItemNames:
if self.SelectDic[j].contains_point([x_load_test, y_load_test]):
self.LabelList.append(self.data_to_test.at[i, 'Label'])
self.TypeList.append(j)
break
pass
if (self.show_load_data_cb.isChecked()):
self.axes.scatter(self.data_to_test.at[i, 'SiO2'],self.data_to_test.at[i, 'K2O'],
marker=self.data_to_test.at[i, 'Marker'],
s=self.data_to_test.at[i, 'Size'],
color=self.data_to_test.at[i, 'Color'],
alpha=self.data_to_test.at[i, 'Alpha'],
label=tmp_label)
except Exception as e:
self.ErrorEvent(text=repr(e))
if (self.legend_cb.isChecked()):
self.axes.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0, prop=fontprop)
self.All_X=SVM_X
self.All_Y=SVM_Y
if (self.hyperplane_cb.isChecked()):
clf = svm.SVC(C=1.0, kernel='linear',probability= True)
svm_x= SVM_X
svm_y= SVM_Y
print(len(svm_x),len(svm_y),len(df.index))
xx, yy = np.meshgrid(np.arange(min(svm_x), max(svm_x), np.ptp(svm_x) / 500),
np.arange(min(svm_y), max(svm_y), np.ptp(svm_y) / 500))
le = LabelEncoder()
le.fit(self._df.Label)
class_label = le.transform(self._df.Label)
svm_train= pd.concat([pd.DataFrame(svm_x),pd.DataFrame(svm_y)], axis=1)
svm_train=svm_train.values
clf.fit(svm_train,class_label)
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
self.axes.contourf(xx, yy, Z, cmap='hot', alpha=0.2)
if (self.show_data_index_cb.isChecked()):
if 'Index' in self._df.columns.values:
for i in range(len(self._df)):
self.axes.annotate(self._df.at[i, 'Index'],
xy=(self.All_X[i],
self.All_Y[i]),
color=self._df.at[i, 'Color'],
alpha=self._df.at[i, 'Alpha'])
else:
for i in range(len(self._df)):
self.axes.annotate('No' + str(i + 1),
xy=(self.All_X[i],
self.All_Y[i]),
color=self._df.at[i, 'Color'],
alpha=self._df.at[i, 'Alpha'])
self.canvas.draw()
self.OutPutTitle='K2OSiO2'
self.OutPutData = pd.DataFrame(
{'Label': self.LabelList,
'RockType': self.TypeList
})
self.OutPutFig=self.fig | self.axes.set_xticks([30,40,50,60,70,80,90])
self.axes.set_xticklabels([30,40,50,60,70,80,90])
self.axes.set_yticks([0, 5, 10, 15, 20])
self.axes.set_yticklabels([0, 5, 10, 15, 20])
self.axes.set_ylim(bottom=0) | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/K2OSiO2.py#L122-L471 | null | class K2OSiO2(AppForm):
_df = pd.DataFrame()
_changed = False
xlabel = r'$SiO_2 wt\%$'
ylabel = r'$K_2O wt\%$'
itemstocheck = ['SiO2', 'K2O']
reference = 'Reference: Maitre, R. W. L., Streckeisen, A., Zanettin, B., Bas, M. J. L., Bonin, B., and Bateman, P., 2004, Igneous Rocks: A Classification and Glossary of Terms: Cambridge University Press, v. -1, no. 70, p. 93–120.'
AreasHeadClosed = []
SelectDic = {}
TypeList=[]
All_X = []
All_Y = []
whole_labels=[]
SVM_labels=[]
def create_main_frame(self):
self.resize(1000, 800)
self.main_frame = QWidget()
self.dpi = 128
self.fig = Figure((18.0, 12.0), dpi=self.dpi)
self.fig.subplots_adjust(hspace=0.5, wspace=0.5, left=0.1, bottom=0.2, right=0.7, top=0.9)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.axes = self.fig.add_subplot(111)
self.axes.axis('off')
# Create the navigation toolbar, tied to the canvas
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
# Other GUI controls
self.load_data_button = QPushButton('&Add Data to Compare')
self.load_data_button.clicked.connect(self.loadDataToTest)
self.save_button = QPushButton('&Save Img')
self.save_button.clicked.connect(self.saveImgFile)
self.result_button = QPushButton('&Classification Result')
self.result_button.clicked.connect(self.Explain)
self.save_predict_button_selected = QPushButton('&Predict Result')
self.save_predict_button_selected.clicked.connect(self.showPredictResultSelected)
self.legend_cb = QCheckBox('&Legend')
self.legend_cb.setChecked(True)
self.legend_cb.stateChanged.connect(self.K2OSiO2) # int
self.show_load_data_cb = QCheckBox('&Show Loaded Data')
self.show_load_data_cb.setChecked(True)
self.show_load_data_cb.stateChanged.connect(self.K2OSiO2) # int
self.show_data_index_cb = QCheckBox('&Show Data Index')
self.show_data_index_cb.setChecked(False)
self.show_data_index_cb.stateChanged.connect(self.K2OSiO2) # int
self.shape_cb= QCheckBox('&Shape')
self.shape_cb.setChecked(False)
self.shape_cb.stateChanged.connect(self.K2OSiO2) # int
self.hyperplane_cb= QCheckBox('&Hyperplane')
self.hyperplane_cb.setChecked(False)
self.hyperplane_cb.stateChanged.connect(self.K2OSiO2) # int
#
# Layout with box sizers
#
self.hbox = QHBoxLayout()
self.hbox1 = QHBoxLayout()
self.hbox2 = QHBoxLayout()
for w in [self.load_data_button,self.save_button, self.result_button, self.save_predict_button_selected]:
self.hbox1.addWidget(w)
self.hbox1.setAlignment(w, Qt.AlignVCenter)
for w in [self.legend_cb,self.show_load_data_cb,self.show_data_index_cb,self.shape_cb,self.hyperplane_cb]:
self.hbox2.addWidget(w)
self.hbox2.setAlignment(w, Qt.AlignVCenter)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.mpl_toolbar)
self.vbox.addWidget(self.canvas)
self.vbox.addLayout(self.hbox1)
self.vbox.addLayout(self.hbox2)
self.textbox = GrowingTextEdit(self)
self.textbox.setText(self.reference)
self.vbox.addWidget(self.textbox)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame)
w=self.width()
h=self.height()
def loadDataToTest(self):
TMP =self.getDataFile()
if TMP != 'Blank':
self.data_to_test=TMP[0]
self.K2OSiO2()
def K2OSiO2(self, Left=35, Right=79, X0=30, X1=90, X_Gap=7, Base=0,
Top=19, Y0=1, Y1=19, Y_Gap=19, FontSize=12, xlabel=r'$SiO_2 wt\%$', ylabel=r'$K_2O wt\%$', width=12,
height=12, dpi=300):
self.setWindowTitle('K2OSiO2 diagram ')
self.axes.clear()
#self.axes.axis('off')
self.axes.set_xlabel(self.xlabel)
self.axes.set_ylabel(self.ylabel)
self.axes.spines['right'].set_color('none')
self.axes.spines['top'].set_color('none')
'''
self.axes.set_xticks([30,40,50,60,70,80,90])
self.axes.set_xticklabels([30,40,50,60,70,80,90])
self.axes.set_yticks([0, 5, 10, 15, 20])
self.axes.set_yticklabels([0, 5, 10, 15, 20])
self.axes.set_ylim(bottom=0)
'''
all_labels=[]
all_colors=[]
all_markers=[]
all_alpha=[]
for i in range(len(self._df)):
target = self._df.at[i, 'Label']
color = self._df.at[i, 'Color']
marker = self._df.at[i, 'Marker']
alpha = self._df.at[i, 'Alpha']
if target not in self.SVM_labels:
self.SVM_labels.append(target)
if target not in all_labels:
all_labels.append(target)
all_colors.append(color)
all_markers.append(marker)
all_alpha.append(alpha)
self.whole_labels = all_labels
PointLabels = []
PointColors = []
x = []
y = []
title = 'K2O-SiO2diagram'
self.setWindowTitle(title)
self.textbox.setText(self.reference)
k_1=(2.9-1.2)/(68-48)
y_1= 1.2+ (85-48)*k_1
y_0= 1.2+ (45-48)*k_1
self.DrawLine([(45, y_0),(48, 1.2), (68,2.9),(85,y_1)])
k_2=(1.2-0.3)/(68-48)
y_2= 0.3+ (85-48)*k_2
y_3= 0.3+ (45-48)*k_2
self.DrawLine([(45, y_3),(48, 0.3), (68, 1.2),(85,y_2)])
Labels=['High K','Medium K','Low K']
Locations=[(80,5),(80,3),(80,1)]
X_offset, Y_offset=0,0
for k in range(len(Labels)):
self.axes.annotate(Labels[k], Locations[k], xycoords='data', xytext=(X_offset, Y_offset),
textcoords='offset points',
fontsize=9, color='grey', alpha=0.8)
self.Check()
if self.OutPutCheck==True:
pass
if (self._changed):
df = self.CleanDataFile(self._df)
for i in range(len(df)):
TmpLabel = ''
if (df.at[i, 'Label'] in PointLabels or df.at[i, 'Label'] == ''):
TmpLabel = ''
else:
PointLabels.append(df.at[i, 'Label'])
TmpLabel = df.at[i, 'Label']
TmpColor = ''
if (df.at[i, 'Color'] in PointColors or df.at[i, 'Color'] == ''):
TmpColor = ''
else:
PointColors.append(df.at[i, 'Color'])
TmpColor = df.at[i, 'Color']
x.append(df.at[i, 'SiO2'])
y.append(df.at[i, 'K2O'])
Size = df.at[i, 'Size']
Color = df.at[i, 'Color']
# print(Color, df.at[i, 'SiO2'], (df.at[i, 'Na2O'] + df.at[i, 'K2O']))
Alpha = df.at[i, 'Alpha']
Marker = df.at[i, 'Marker']
Label = df.at[i, 'Label']
xtest=df.at[i, 'SiO2']
ytest=df.at[i, 'K2O']
for j in self.ItemNames:
if self.SelectDic[j].contains_point([xtest,ytest]):
self.LabelList.append(Label)
self.TypeList.append(j)
break
pass
self.axes.scatter(df.at[i, 'SiO2'], df.at[i, 'K2O'], marker=df.at[i, 'Marker'],
s=df.at[i, 'Size'], color=df.at[i, 'Color'], alpha=df.at[i, 'Alpha'], label=TmpLabel)
XtoFit = {}
YtoFit = {}
SVM_X=[]
SVM_Y=[]
for i in PointLabels:
XtoFit[i]=[]
YtoFit[i]=[]
for i in range(len(df)):
Alpha = df.at[i, 'Alpha']
Marker = df.at[i, 'Marker']
Label = df.at[i, 'Label']
xtest=df.at[i, 'SiO2']
ytest=df.at[i, 'K2O']
XtoFit[Label].append(xtest)
YtoFit[Label].append(ytest)
SVM_X.append(xtest)
SVM_Y.append(ytest)
if (self.shape_cb.isChecked()):
for i in PointLabels:
if XtoFit[i] != YtoFit[i]:
xmin, xmax = min(XtoFit[i]), max(XtoFit[i])
ymin, ymax = min(YtoFit[i]), max(YtoFit[i])
DensityColorMap = 'Greys'
DensityAlpha = 0.1
DensityLineColor = PointColors[PointLabels.index(i)]
DensityLineAlpha = 0.3
# Peform the kernel density estimate
xx, yy = np.mgrid[xmin:xmax:200j, ymin:ymax:200j]
# print(self.ShapeGroups)
# command='''xx, yy = np.mgrid[xmin:xmax:'''+str(self.ShapeGroups)+ '''j, ymin:ymax:''' +str(self.ShapeGroups)+'''j]'''
# exec(command)
# print(xx, yy)
positions = np.vstack([xx.ravel(), yy.ravel()])
values = np.vstack([XtoFit[i], YtoFit[i]])
kernelstatus = True
try:
st.gaussian_kde(values)
except Exception as e:
self.ErrorEvent(text=repr(e))
kernelstatus = False
if kernelstatus == True:
kernel = st.gaussian_kde(values)
f = np.reshape(kernel(positions).T, xx.shape)
# Contourf plot
cfset = self.axes.contourf(xx, yy, f, cmap=DensityColorMap, alpha=DensityAlpha)
## Or kernel density estimate plot instead of the contourf plot
# self.axes.imshow(np.rot90(f), cmap='Blues', extent=[xmin, xmax, ymin, ymax])
# Contour plot
cset = self.axes.contour(xx, yy, f, colors=DensityLineColor, alpha=DensityLineAlpha)
# Label plot
#self.axes.clabel(cset, inline=1, fontsize=10)
if (len(self.data_to_test) > 0):
contained = True
missing = 'Miss setting infor:'
for i in ['Label', 'Color', 'Marker', 'Alpha']:
if i not in self.data_to_test.columns.values.tolist():
contained = False
missing = missing + '\n' + i
if contained == True:
for i in self.data_to_test.columns.values.tolist():
if i not in self._df.columns.values.tolist():
self.data_to_test = self.data_to_test.drop(columns=i)
# print(self.data_to_test)
test_labels = []
test_colors = []
test_markers = []
test_alpha = []
for i in range(len(self.data_to_test)):
# print(self.data_to_test.at[i, 'Label'])
target = self.data_to_test.at[i, 'Label']
color = self.data_to_test.at[i, 'Color']
marker = self.data_to_test.at[i, 'Marker']
alpha = self.data_to_test.at[i, 'Alpha']
if target not in test_labels and target not in all_labels:
test_labels.append(target)
test_colors.append(color)
test_markers.append(marker)
test_alpha.append(alpha)
self.whole_labels = self.whole_labels + test_labels
self.load_settings_backup = self.data_to_test
Load_ItemsToTest = ['Label', 'Number', 'Tag', 'Name', 'Author', 'DataType', 'Marker', 'Color',
'Size',
'Alpha',
'Style', 'Width']
for i in self.data_to_test.columns.values.tolist():
if i not in Load_ItemsToTest:
self.load_settings_backup = self.load_settings_backup.drop(i, 1)
print(self.load_settings_backup, self.data_to_test)
print(self.load_settings_backup.shape, self.data_to_test.shape)
try:
for i in range(len(self.data_to_test)):
target = self.data_to_test.at[i, 'Label']
if target not in all_labels:
all_labels.append(target)
tmp_label = self.data_to_test.at[i, 'Label']
else:
tmp_label=''
x_load_test = self.data_to_test.at[i, 'SiO2']
y_load_test = self.data_to_test.at[i, 'K2O']
for j in self.ItemNames:
if self.SelectDic[j].contains_point([x_load_test, y_load_test]):
self.LabelList.append(self.data_to_test.at[i, 'Label'])
self.TypeList.append(j)
break
pass
if (self.show_load_data_cb.isChecked()):
self.axes.scatter(self.data_to_test.at[i, 'SiO2'],self.data_to_test.at[i, 'K2O'],
marker=self.data_to_test.at[i, 'Marker'],
s=self.data_to_test.at[i, 'Size'],
color=self.data_to_test.at[i, 'Color'],
alpha=self.data_to_test.at[i, 'Alpha'],
label=tmp_label)
except Exception as e:
self.ErrorEvent(text=repr(e))
if (self.legend_cb.isChecked()):
self.axes.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0, prop=fontprop)
self.All_X=SVM_X
self.All_Y=SVM_Y
if (self.hyperplane_cb.isChecked()):
clf = svm.SVC(C=1.0, kernel='linear',probability= True)
svm_x= SVM_X
svm_y= SVM_Y
print(len(svm_x),len(svm_y),len(df.index))
xx, yy = np.meshgrid(np.arange(min(svm_x), max(svm_x), np.ptp(svm_x) / 500),
np.arange(min(svm_y), max(svm_y), np.ptp(svm_y) / 500))
le = LabelEncoder()
le.fit(self._df.Label)
class_label = le.transform(self._df.Label)
svm_train= pd.concat([pd.DataFrame(svm_x),pd.DataFrame(svm_y)], axis=1)
svm_train=svm_train.values
clf.fit(svm_train,class_label)
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
self.axes.contourf(xx, yy, Z, cmap='hot', alpha=0.2)
if (self.show_data_index_cb.isChecked()):
if 'Index' in self._df.columns.values:
for i in range(len(self._df)):
self.axes.annotate(self._df.at[i, 'Index'],
xy=(self.All_X[i],
self.All_Y[i]),
color=self._df.at[i, 'Color'],
alpha=self._df.at[i, 'Alpha'])
else:
for i in range(len(self._df)):
self.axes.annotate('No' + str(i + 1),
xy=(self.All_X[i],
self.All_Y[i]),
color=self._df.at[i, 'Color'],
alpha=self._df.at[i, 'Alpha'])
self.canvas.draw()
self.OutPutTitle='K2OSiO2'
self.OutPutData = pd.DataFrame(
{'Label': self.LabelList,
'RockType': self.TypeList
})
self.OutPutFig=self.fig
def showPredictResultSelected(self):
try:
clf = svm.SVC(C=1.0, kernel='linear',probability= True)
svm_x = self.All_X
svm_y = self.All_Y
le = LabelEncoder()
le.fit(self._df.Label)
class_label = le.transform(self._df.Label)
svm_train = pd.concat([pd.DataFrame(svm_x), pd.DataFrame(svm_y)], axis=1)
svm_train = svm_train.values
clf.fit(svm_train, self._df.Label)
xx = self.data_to_test['SiO2']
yy=[]
for k in range(len(self.data_to_test)):
tmp =self.data_to_test.at[k, 'Na2O'] + self.data_to_test.at[k,'K2O']
yy.append(tmp)
pass
Z = clf.predict(np.c_[xx.ravel(), yy])
Z2 = clf.predict_proba(np.c_[xx.ravel(), yy])
proba_df = pd.DataFrame(Z2)
proba_df.columns = self.SVM_labels
predict_result = pd.concat(
[self.load_settings_backup['Label'], pd.DataFrame({'SVM Classification': Z}), proba_df],
axis=1).set_index('Label')
print(predict_result)
self.predictpop = TableViewer(df=predict_result, title='SVM Predict Result')
self.predictpop.show()
'''
DataFileOutput, ok2 = QFileDialog.getSaveFileName(self, '文件保存', 'C:/', 'Excel Files (*.xlsx);;CSV Files (*.csv)') # 数据文件保存输出
if (DataFileOutput != ''):
if ('csv' in DataFileOutput):
# DataFileOutput = DataFileOutput[0:-4]
predict_result.to_csv(DataFileOutput, sep=',', encoding='utf-8')
# self.result.to_csv(DataFileOutput + '.csv', sep=',', encoding='utf-8')
elif ('xlsx' in DataFileOutput):
# DataFileOutput = DataFileOutput[0:-5]
predict_result.to_excel(DataFileOutput, encoding='utf-8')
# self.result.to_excel(DataFileOutput + '.xlsx', encoding='utf-8')
'''
except Exception as e:
msg = 'You need to load another data to run SVM.\n '
self.ErrorEvent(text= msg +repr(e) )
def Explain(self):
#self.OutPutData = self.OutPutData.set_index('Label')
self.tablepop = TableViewer(df=self.OutPutData,title='K2OSiO2 Result')
self.tablepop.show() |
GeoPyTool/GeoPyTool | geopytool/REE.py | REE.REE | python | def REE(self, Left=0, Right=16, X0=1, X1=15, X_Gap=15, Base=-1,
Top=6, Y0=-1,
Y1=3, Y_Gap=5, FontSize=12,
xLabel=r'$REE-Standardlized-Pattern$', yLabel='', width=12, height=12, dpi=300):
self.axes.clear()
self.axes.spines['right'].set_color('none')
self.axes.spines['top'].set_color('none')
self.WholeData = []
self.OutPutData = pd.DataFrame()
self.LabelList=[]
self.algebraDeltaEuList=[]
self.geometricDeltaEuList=[]
self.LaPrDeltaCeList=[]
self.LaNdDeltaCeList=[]
self.LaSmList=[]
self.LaYbList=[]
self.GdYbList=[]
self.LREEList=[]
self.MREEList=[]
self.HREEList=[]
self.ALLREEList=[]
self.BinHREEList=[]
self.BinLREEList=[]
self.L_HREEList=[]
self.AllAlpha=[]
self.AllWidth = []
self.AllSize = []
#raw = self._df
raw = self.CleanDataFile(self._df)
self.FontSize = FontSize
PointLabels = []
k = 0
slider_value=int(self.standard_slider.value())
item_value=int(self.item_slider.value())
if slider_value < len(self.StandardsName):
standardnamechosen = self.StandardsName[slider_value]
standardchosen = self.Standards[standardnamechosen]
self.textbox.setText(self.reference+"\nStandard Chosen: "+self.StandardsName[slider_value])
right_label_text=self.StandardsName[slider_value]
elif len(self._given_Standard)<=0:
standardnamechosen = self.StandardsName[slider_value-1]
standardchosen = self.Standards[standardnamechosen]
self.textbox.setText(self.reference+"\nStandard Chosen: "+self.StandardsName[slider_value-1])
right_label_text = self.StandardsName[slider_value-1]
else:
standardchosen = self._given_Standard
self.textbox.setText(self.reference + "\n You are using Self Defined Standard")
right_label_text = "Self Defined Standard"
for i in range(len(raw)):
# raw.at[i, 'DataType'] == 'User' or raw.at[i, 'DataType'] == 'user' or raw.at[i, 'DataType'] == 'USER'
TmpLabel = ''
LinesX = []
LinesY = []
TmpEu = raw.at[i, 'Eu'] / standardchosen['Eu']
TmpSm = raw.at[i, 'Sm'] / standardchosen['Sm']
TmpGd = raw.at[i, 'Gd'] / standardchosen['Gd']
TmpCe = raw.at[i, 'Ce'] / standardchosen['Ce']
TmpLa = raw.at[i, 'La'] / standardchosen['La']
TmpPr = raw.at[i, 'Pr'] / standardchosen['Pr']
TmpNd = raw.at[i, 'Nd'] / standardchosen['Nd']
TmpYb = raw.at[i, 'Yb'] / standardchosen['Yb']
algebraEu = 2*TmpEu/(TmpSm+TmpGd)
geometricEu = TmpEu/np.power((TmpSm*TmpGd),0.5)
firstCe=2*TmpCe/(TmpLa+TmpPr)
secondCe=3*TmpCe/(2*TmpLa+TmpNd)
LaYb=TmpLa/TmpYb
LaSm=TmpLa/TmpSm
GdYb=TmpGd/TmpYb
tmpLREEResult = 0
tmpMREEResult = 0
tmpHREEResult = 0
tmpWholeResult = 0
tmpBinLREE=0
tmpBinHREE=0
for j in self.Element:
if j in self.LREE:
tmpLREEResult += raw.at[i, j]
elif j in self.MREE:
tmpMREEResult += raw.at[i, j]
elif j in self.HREE:
tmpHREEResult += raw.at[i, j]
if j in self.BinLREE:
tmpBinLREE += raw.at[i, j]
elif j in self.BinHREE:
tmpBinHREE += raw.at[i, j]
tmpWholeResult+= raw.at[i, j]
self.LabelList.append(raw.at[i, 'Label'])
self.algebraDeltaEuList.append( algebraEu )
self.geometricDeltaEuList.append( geometricEu )
self.LaPrDeltaCeList.append(firstCe)
self.LaNdDeltaCeList.append(secondCe)
self.LaSmList.append(LaSm)
self.LaYbList.append(LaYb)
self.GdYbList.append(GdYb)
self.LREEList.append( tmpLREEResult )
self.MREEList.append( tmpMREEResult )
self.HREEList.append( tmpHREEResult )
self.ALLREEList.append( tmpWholeResult )
self.BinHREEList.append(tmpBinHREE)
self.BinLREEList.append(tmpBinLREE)
self.L_HREEList.append(tmpBinLREE/tmpBinHREE)
'''
for i in self.data_to_norm.columns.values.tolist():
if i not in self.Element:
self.data_to_norm = self.data_to_norm.drop(i, 1)
'''
Y_bottom=0
Y_top=0
for j in range(len(self.Element)):
tmp = raw.at[i, self.Element[j]] / standardchosen[self.Element[j]]
self.data_to_norm.at[i, self.Element[j]] = tmp
tmpflag = 1
a = 0
try:
a = math.log(tmp, 10)
except(ValueError):
tmpflag = 0
pass
if (tmpflag == 1):
if Y_bottom >a:Y_bottom =a
if Y_top<a:Y_top=a
self.axes.set_ylim(Y_bottom, Y_top+1)
if item_value == 0:
self.item_left_label.setText('Show All')
for j in range(len(self.Element)):
tmp = raw.at[i, self.Element[j]] / standardchosen[self.Element[j]]
self.data_to_norm.at[i, self.Element[j]] = tmp
tmpflag = 1
a = 0
try:
a = math.log(tmp, 10)
except(ValueError):
tmpflag = 0
pass
if (tmpflag == 1):
if (raw.at[i, 'Label'] in PointLabels or raw.at[i, 'Label'] == ''):
self.WholeData.append(math.log(tmp, 10))
TmpLabel = ''
else:
PointLabels.append(raw.at[i, 'Label'])
TmpLabel = raw.at[i, 'Label']
LinesY.append(a)
LinesX.append(j + 1)
self.axes.scatter(j + 1, math.log(tmp, 10), marker=raw.at[i, 'Marker'],
s=raw.at[i, 'Size'], color=raw.at[i, 'Color'], alpha=raw.at[i, 'Alpha'],
label=TmpLabel)
self.axes.plot(LinesX, LinesY, color=raw.at[i, 'Color'], linewidth=raw.at[i, 'Width'],
linestyle=raw.at[i, 'Style'], alpha=raw.at[i, 'Alpha'])
if (self.show_data_index_cb.isChecked()):
if 'Index' in self._df_back.columns.values:
self.axes.annotate(self._df_back.at[i, 'Index'],
xy=(LinesX[-1], LinesY[-1]),
color=self._df.at[i, 'Color'],
alpha=self._df.at[i, 'Alpha'])
else:
self.axes.annotate('No' + str(i + 1),
xy=(LinesX[-1],
LinesY[-1]),
color=self._df.at[i, 'Color'],
alpha=self._df.at[i, 'Alpha'])
else:
self.item_left_label.setText(self.AllLabel[item_value-1])
for j in range(len(self.Element)):
tmp = raw.at[i, self.Element[j]] / standardchosen[self.Element[j]]
self.data_to_norm.at[i, self.Element[j]] = tmp
tmpflag = 1
a = 0
try:
a = math.log(tmp, 10)
except(ValueError):
tmpflag = 0
pass
if (tmpflag == 1):
if (raw.at[i, 'Label'] in PointLabels or raw.at[i, 'Label'] == ''):
TmpLabel = ''
else:
PointLabels.append(raw.at[i, 'Label'])
TmpLabel = raw.at[i, 'Label']
alpha= raw.at[i, 'Alpha']
linewidth= raw.at[i, 'Width']
pointsize= raw.at[i, 'Size']
if raw.at[i, 'Label'] == self.AllLabel[item_value - 1]:
LinesY.append(a)
LinesX.append(j + 1)
self.WholeData.append(math.log(tmp, 10))
self.axes.scatter(j + 1, math.log(tmp, 10), marker=raw.at[i, 'Marker'],
s=pointsize, color=raw.at[i, 'Color'], alpha=alpha,
label=TmpLabel)
self.axes.plot(LinesX, LinesY, color=raw.at[i, 'Color'], linewidth=linewidth,linestyle=raw.at[i, 'Style'], alpha=alpha)
print(LinesX,LinesY)
if (self.show_data_index_cb.isChecked()):
if len(LinesX) > 0 and len(LinesY) > 0:
if 'Index' in self._df_back.columns.values:
self.axes.annotate(self._df_back.at[i, 'Index'],
xy=(LinesX[-1], LinesY[-1]),
color=self._df.at[i, 'Color'],
alpha=self._df.at[i, 'Alpha'])
else:
self.axes.annotate('No' + str(i + 1),
xy=(LinesX[-1], LinesY[-1]),
color=self._df.at[i, 'Color'],
alpha=self._df.at[i, 'Alpha'])
Tale = 0
Head = 0
if (len(self.WholeData) > 0):
Tale = min(self.WholeData)
Head = max(self.WholeData)+0.5
Location = round(Tale - (Head - Tale) / 5)
count = round((Head - Tale) / 5 * 7) + 1
if (self.legend_cb.isChecked()):
self.axes.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0, prop=fontprop)
self.standard_right_label.setText(right_label_text)
self.yticks = [Location+i for i in range(count)]
self.yticklabels = [str(np.power(10.0, (Location + i))) for i in range(count)]
self.axes.set_yticks(self.yticks)
self.axes.set_yticklabels(self.yticklabels, fontsize=6)
#self.axes.set_yscale('log')
self.axes.set_xticks(self.xticks)
self.axes.set_xticklabels(self.xticklabels, rotation=-45, fontsize=6)
self.canvas.draw()
self.OutPutTitle='REE'
#print(len(self.algebraDeltaEuList))
self.OutPutData = pd.DataFrame(
{'Label': self.LabelList,
'Eu/Eu*(algebra)': self.algebraDeltaEuList,
'Eu/Eu*(square)': self.geometricDeltaEuList,
'Ce/Ce*(LaPr)': self.LaPrDeltaCeList,
'Ce/Ce*(LaNd)': self.LaNdDeltaCeList,
'(La/Sm)N':self.LaSmList,
'(La/Yb)N':self.LaYbList,
'(Gd/Yb)N':self.GdYbList,
'trisection LREE': self.LREEList,
'trisection MREE': self.MREEList,
'trisection HREE': self.HREEList,
'bisection LREE': self.BinLREEList,
'bisection HREE': self.BinHREEList,
'LREE/HREE':self.L_HREEList,
'ALLREE': self.ALLREEList
})
#print('middle ',len(self.OutPutData['Eu/Eu*(algebra)']))
'''
self.LaPrDeltaCeList.append(firstCe)
self.LaNdDeltaCeList.append(secondCe)
'''
self.OutPutFig=self.fig | self.LaPrDeltaCeList.append(firstCe)
self.LaNdDeltaCeList.append(secondCe) | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/REE.py#L252-L584 | null | class REE(AppForm):
reference = 'Reference: Sun, S. S., and Mcdonough, W. F., 1989, UCC_Rudnick & Gao2003'
xticks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
xticklabels = ['La', 'Ce', 'Pr', 'Nd', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu']
itemstocheck = ['La', 'Ce', 'Pr', 'Nd', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu']
LREE = ['La', 'Ce', 'Pr', 'Nd']
MREE = ['Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho']
HREE = [ 'Er', 'Tm', 'Yb', 'Lu']
BinLREE=['La', 'Ce', 'Pr', 'Nd','Sm', 'Eu']
BinHREE=['Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu']
StandardsName = ['C1 Chondrite Sun and McDonough,1989', 'Chondrite Taylor and McLennan,1985',
'Chondrite Haskin et al.,1966', 'Chondrite Nakamura,1977', 'MORB Sun and McDonough,1989','UCC_Rudnick & Gao2003']
# RefName=['Sun, S. S., and Mcdonough, W. F., 1989, Chemical and isotopic systematics of oceanic basalts: implications for mantle composition and processes: Geological Society London Special Publications, v. 42, no. 1, p. 313-345.',]
NameChosen = 'C1 Chondrite Sun and McDonough,1989'
Standards = {
'C1 Chondrite Sun and McDonough,1989': {'La': 0.237, 'Ce': 0.612, 'Pr': 0.095, 'Nd': 0.467, 'Sm': 0.153,
'Eu': 0.058, 'Gd': 0.2055, 'Tb': 0.0374, 'Dy': 0.254, 'Ho': 0.0566,
'Er': 0.1655, 'Tm': 0.0255, 'Yb': 0.17, 'Lu': 0.0254},
'Chondrite Taylor and McLennan,1985': {'La': 0.367, 'Ce': 0.957, 'Pr': 0.137, 'Nd': 0.711, 'Sm': 0.231,
'Eu': 0.087, 'Gd': 0.306, 'Tb': 0.058, 'Dy': 0.381, 'Ho': 0.0851,
'Er': 0.249, 'Tm': 0.0356, 'Yb': 0.248, 'Lu': 0.0381},
'Chondrite Haskin et al.,1966': {'La': 0.32, 'Ce': 0.787, 'Pr': 0.112, 'Nd': 0.58, 'Sm': 0.185, 'Eu': 0.071,
'Gd': 0.256, 'Tb': 0.05, 'Dy': 0.343, 'Ho': 0.07, 'Er': 0.225, 'Tm': 0.03,
'Yb': 0.186, 'Lu': 0.034},
'Chondrite Nakamura,1977': {'La': 0.33, 'Ce': 0.865, 'Pr': 0.112, 'Nd': 0.63, 'Sm': 0.203, 'Eu': 0.077,
'Gd': 0.276, 'Tb': 0.047, 'Dy': 0.343, 'Ho': 0.07, 'Er': 0.225, 'Tm': 0.03,
'Yb': 0.22,
'Lu': 0.034},
'MORB Sun and McDonough,1989': {'La': 2.5, 'Ce': 7.5, 'Pr': 1.32, 'Nd': 7.3, 'Sm': 2.63, 'Eu': 1.02, 'Gd': 3.68,
'Tb': 0.67, 'Dy': 4.55, 'Ho': 1.052, 'Er': 2.97, 'Tm': 0.46, 'Yb': 3.05,
'Lu': 0.46},
'UCC_Rudnick & Gao2003':{'K':23244.13776,'Ti':3835.794545,'P':654.6310022,'Li':24,'Be':2.1,'B':17,'N':83,'F':557,'S':62,'Cl':370,'Sc':14,'V':97,'Cr':92,
'Co':17.3,'Ni':47,'Cu':28,'Zn':67,'Ga':17.5,'Ge':1.4,'As':4.8,'Se':0.09,
'Br':1.6,'Rb':84,'Sr':320,'Y':21,'Zr':193,'Nb':12,'Mo':1.1,'Ru':0.34,
'Pd':0.52,'Ag':53,'Cd':0.09,'In':0.056,'Sn':2.1,'Sb':0.4,'I':1.4,'Cs':4.9,
'Ba':628,'La':31,'Ce':63,'Pr':7.1,'Nd':27,'Sm':4.7,'Eu':1,'Gd':4,'Tb':0.7,
'Dy':3.9,'Ho':0.83,'Er':2.3,'Tm':0.3,'Yb':1.96,'Lu':0.31,'Hf':5.3,'Ta':0.9,
'W':1.9,'Re':0.198,'Os':0.031,'Ir':0.022,'Pt':0.5,'Au':1.5,'Hg':0.05,'Tl':0.9,
'Pb':17,'Bi':0.16,'Th':10.5,'U':2.7}}
LabelList=[]
algebraDeltaEuList = []
geometricDeltaEuList = []
LaPrDeltaCeList = []
LaNdDeltaCeList = []
LaYbList=[]
LaSmList=[]
GdYbList=[]
LREEList=[]
MREEList=[]
HREEList=[]
BinLREEList = []
BinHREEList = []
L_HREEList=[]
ALLREEList=[]
AllAlpha = []
AllWidth = []
AllSize = []
def __init__(self, parent=None, df=pd.DataFrame(),Standard={}):
QMainWindow.__init__(self, parent)
self.setWindowTitle('REE Standardlized Pattern Diagram')
#self._df = df
self._df_back= df
self.FileName_Hint='REE'
self.OutPutData = pd.DataFrame()
self.LabelList=[]
self.algebraDeltaEuList=[]
self.geometricDeltaEuList=[]
self.LaPrDeltaCeList=[]
self.LaNdDeltaCeList=[]
self.LaSmList=[]
self.LaYbList=[]
self.GdYbList=[]
self.LREEList=[]
self.MREEList=[]
self.HREEList=[]
self.ALLREEList=[]
self.BinHREEList=[]
self.BinLREEList=[]
self.L_HREEList=[]
self.data_to_norm = self.CleanDataFile(df)
self._df = self.CleanDataFile(df)
self.AllLabel=[]
for i in range(len(self._df)):
tmp_label = self._df.at[i, 'Label']
if tmp_label not in self.AllLabel:
self.AllLabel.append(tmp_label)
#self._given_Standard = Standard
self._given_Standard = self.Standard
if (len(df) > 0):
self._changed = True
# #print('DataFrame recieved to REE')
self.Element = ['La', 'Ce', 'Pr', 'Nd', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu']
self.WholeData = []
self.X0 = 1
self.X1 = 15
self.X_Gap = 15
self.create_main_frame()
self.create_status_bar()
def Check(self):
row = self._df.index.tolist()
col = self._df.columns.tolist()
itemstocheck = self.itemstocheck
checklist = list((set(itemstocheck).union(set(col))) ^ (set(itemstocheck) ^ set(col)))
if len(checklist) > 1 :
self.OutPutCheck = True
else:
self.OutPutCheck = False
return(self.OutPutCheck)
def create_main_frame(self):
self.resize(800, 600)
self.main_frame = QWidget()
self.dpi = 128
self.fig = Figure((18.0, 12.0), dpi=self.dpi)
self.fig.subplots_adjust(hspace=0.5, wspace=0.5, left=0.1, bottom=0.2, right=0.7, top=0.9)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.axes = self.fig.add_subplot(111)
#self.axes.axis('off')
# Create the navigation toolbar, tied to the canvas
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
# Other GUI controls
self.save_img_button = QPushButton('&Save Img')
self.save_img_button.clicked.connect(self.saveImgFile)
self.explain_button = QPushButton('&Norm Result')
self.explain_button.clicked.connect(self.Explain)
self.legend_cb = QCheckBox('&Legend')
self.legend_cb.setChecked(True)
self.legend_cb.stateChanged.connect(self.REE) # int
self.show_data_index_cb = QCheckBox('&Show Data Index')
self.show_data_index_cb.setChecked(False)
self.show_data_index_cb.stateChanged.connect(self.REE) # int
self.standard_slider = QSlider(Qt.Horizontal)
self.standard_slider.setRange(0, len(self.StandardsName))
if len(self._given_Standard) > 0:
self.standard_slider.setValue(len(self.StandardsName))
self.standard_right_label = QLabel("Self Defined Standard")
else:
self.standard_slider.setValue(0)
self.standard_right_label = QLabel(self.StandardsName[int(self.standard_slider.value())])
self.standard_slider.setTracking(True)
self.standard_slider.setTickPosition(QSlider.TicksBothSides)
self.standard_slider.valueChanged.connect(self.REE) # int
self.standard_left_label= QLabel('Standard')
self.item_left_label= QLabel('Show All' )
self.item_slider = QSlider(Qt.Horizontal)
self.item_slider.setRange(0, len(self.AllLabel))
self.item_slider.setTracking(True)
self.item_slider.setTickPosition(QSlider.TicksBothSides)
self.item_slider.valueChanged.connect(self.REE) # int
#
# Layout with box sizers
#
self.hbox1 = QHBoxLayout()
self.hbox2 = QHBoxLayout()
for w in [self.save_img_button, self.explain_button, self.legend_cb,self.show_data_index_cb,self.standard_left_label, self.standard_slider, self.standard_right_label]:
self.hbox1.addWidget(w)
self.hbox1.setAlignment(w, Qt.AlignVCenter)
for w in [ self.item_left_label,self.item_slider]:
self.hbox2.addWidget(w)
self.hbox2.setAlignment(w, Qt.AlignVCenter)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.mpl_toolbar)
self.vbox.addWidget(self.canvas)
self.vbox.addLayout(self.hbox1)
self.vbox.addLayout(self.hbox2)
self.textbox = GrowingTextEdit(self)
#self.textbox.setText(self.reference+"\nStandard Chosen: "+self.StandardsName[int(self.standard_slider.value())])
self.vbox.addWidget(self.textbox)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame)
w=self.width()
h=self.height()
#setFixedWidth(w/10)
self.standard_slider.setMinimumWidth(w/4)
self.standard_right_label.setFixedWidth(w/2)
self.item_left_label.setMinimumWidth(w/4)
#self.item_left_label.setMinimumWidth(w/5)
self.item_left_label.setFixedWidth(w/10)
def Explain(self):
self.data_to_norm
for i in self.data_to_norm.columns.values.tolist():
if i in self.Element:
self.data_to_norm = self.data_to_norm.rename(columns = {i : i+'_N'})
#elif i in ['Label','Number', 'Tag', 'Name', 'Author', 'DataType', 'Marker', 'Color', 'Size', 'Alpha','Style', 'Width']: pass
elif i in ['Number', 'Tag', 'Name', 'Author', 'DataType', 'Marker', 'Color', 'Size', 'Alpha','Style', 'Width']: pass
else:
self.data_to_norm = self.data_to_norm.drop(i, 1)
#print('last',len(self.OutPutData['Eu/Eu*(algebra)']))
df = pd.concat([self.data_to_norm,self.OutPutData], axis=1).set_index('Label')
self.tablepop = TableViewer(df=df,title='REE Norm Result')
self.tablepop.show()
|
GeoPyTool/GeoPyTool | geopytool/NewCIPW.py | CIPW.create_main_frame | python | def create_main_frame(self):
self.resize(800, 600)
self.main_frame = QWidget()
self.dpi = 128
self.save_button = QPushButton('&Save Result')
self.save_button.clicked.connect(self.saveResult)
self.qapf_button = QPushButton('&QAPF')
self.qapf_button.clicked.connect(self.QAPF)
'''
self.tableView = CustomQTableView(self.main_frame)
self.tableView.setObjectName('tableView')
self.tableView.setSortingEnabled(True)
'''
self.tableViewMole = CustomQTableView(self.main_frame)
self.tableViewMole.setObjectName('tableViewMole')
self.tableViewMole.setSortingEnabled(True)
self.tableViewWeight = CustomQTableView(self.main_frame)
self.tableViewWeight.setObjectName('tableViewWeight')
self.tableViewWeight.setSortingEnabled(True)
self.tableViewVolume = CustomQTableView(self.main_frame)
self.tableViewVolume.setObjectName('tableViewVolume')
self.tableViewVolume.setSortingEnabled(True)
self.tableViewCalced = CustomQTableView(self.main_frame)
self.tableViewCalced.setObjectName('tableViewCalced')
self.tableViewCalced.setSortingEnabled(True)
#
# Layout with box sizers
#
self.hbox = QHBoxLayout()
for w in [self.qapf_button]:
self.hbox.addWidget(w)
self.hbox.setAlignment(w, Qt.AlignVCenter)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.tableViewMole)
self.vbox.addWidget(self.tableViewWeight)
self.vbox.addWidget(self.tableViewVolume)
self.vbox.addWidget(self.tableViewCalced)
self.vbox.addWidget(self.save_button)
self.vbox.addLayout(self.hbox)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame) | self.tableView = CustomQTableView(self.main_frame)
self.tableView.setObjectName('tableView')
self.tableView.setSortingEnabled(True) | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/NewCIPW.py#L162-L221 | null | class CIPW(AppForm):
addon = 'Name Author DataType Label Marker Color Size Alpha Style Width TOTAL total LOI loi'
Minerals = ['Quartz',
'Zircon',
'K2SiO3',
'Anorthite',
'Na2SiO3',
'Acmite',
'Diopside',
'Sphene',
'Hypersthene',
'Albite',
'Orthoclase',
'Wollastonite',
'Olivine',
'Perovskite',
'Nepheline',
'Leucite',
'Larnite',
'Kalsilite',
'Apatite',
'Halite',
'Fluorite',
'Anhydrite',
'Thenardite',
'Pyrite',
'Magnesiochromite',
'Chromite',
'Ilmenite',
'Calcite',
'Na2CO3',
'Corundum',
'Rutile',
'Magnetite',
'Hematite',
'Q',
'A',
'P',
'F', ]
Calced = ['Fe3+/(Total Fe) in rock',
'Mg/(Mg+Total Fe) in rock',
'Mg/(Mg+Fe2+) in rock',
'Mg/(Mg+Fe2+) in silicates',
'Ca/(Ca+Na) in rock',
'Plagioclase An content',
'Differentiation Index']
DataBase = {'Quartz': [60.0843, 2.65],
'Zircon': [183.3031, 4.56],
'K2SiO3': [154.2803, 2.5],
'Anorthite': [278.2093, 2.76],
'Na2SiO3': [122.0632, 2.4],
'Acmite': [462.0083, 3.6],
'Diopside': [229.0691997, 3.354922069],
'Sphene': [196.0625, 3.5],
'Hypersthene': [112.9054997, 3.507622212],
'Albite': [524.446, 2.62],
'Orthoclase': [556.6631, 2.56],
'Wollastonite': [116.1637, 2.86],
'Olivine': [165.7266995, 3.68429065],
'Perovskite': [135.9782, 4],
'Nepheline': [284.1088, 2.56],
'Leucite': [436.4945, 2.49],
'Larnite': [172.2431, 3.27],
'Kalsilite': [316.3259, 2.6],
'Apatite': [493.3138, 3.2],
'Halite': [66.44245, 2.17],
'Fluorite': [94.0762, 3.18],
'Anhydrite': [136.1376, 2.96],
'Thenardite': [142.0371, 2.68],
'Pyrite': [135.9664, 4.99],
'Magnesiochromite': [192.2946, 4.43],
'Chromite': [223.8366, 5.09],
'Ilmenite': [151.7452, 4.75],
'Calcite': [100.0892, 2.71],
'Na2CO3': [105.9887, 2.53],
'Corundum': [101.9613, 3.98],
'Rutile': [79.8988, 4.2],
'Magnetite': [231.5386, 5.2],
'Hematite': [159.6922, 5.25]}
BaseMass = {'SiO2': 60.083,
'TiO2': 79.865,
'Al2O3': 101.960077,
'Fe2O3': 159.687,
'FeO': 71.844,
'MnO': 70.937044,
'MgO': 40.304,
'CaO': 56.077000000000005,
'Na2O': 61.978538560000004,
'K2O': 94.1956,
'P2O5': 141.942523996,
'CO2': 44.009,
'SO3': 80.057,
'S': 32.06,
'F': 18.998403163,
'Cl': 35.45,
'Sr': 87.62,
'Ba': 137.327,
'Ni': 58.6934,
'Cr': 51.9961,
'Zr': 91.224}
Elements = ['SiO2',
'TiO2',
'Al2O3',
'Fe2O3',
'FeO',
'MnO',
'MgO',
'CaO',
'Na2O',
'K2O',
'P2O5',
'CO2',
'SO3',
'S',
'F',
'Cl',
'Sr',
'Ba',
'Ni',
'Cr',
'Zr']
DataWeight = {}
DataVolume = {}
DataCalced = {}
ResultMole =[]
ResultWeight=[]
ResultVolume=[]
ResultCalced=[]
FinalResultMole = pd.DataFrame()
FinalResultWeight = pd.DataFrame()
FinalResultVolume = pd.DataFrame()
FinalResultCalced = pd.DataFrame()
raw = pd.DataFrame()
DictList=[]
def __init__(self, parent=None, df=pd.DataFrame()):
QMainWindow.__init__(self, parent)
self.setWindowTitle('CIPW Norm Result')
self._df = df
#self.raw = df
self.raw = self.CleanDataFile(self._df)
if (len(df) > 0):
self._changed = True
# print('DataFrame recieved')
self.create_main_frame()
self.create_status_bar()
def CIPW(self):
self.ResultMole=[]
self.ResultWeight=[]
self.ResultVolume=[]
self.ResultCalced=[]
self.DictList=[]
for i in range(len(self.raw)):
tmpDict={}
for j in self.raw.columns:
tmpDict.update({j:self.raw.at[i,j]})
TmpResult = self.singleCalc(m=tmpDict)
TmpResultMole = pd.DataFrame(TmpResult[0],index=[i])
TmpResultWeight = pd.DataFrame(TmpResult[1],index=[i])
TmpResultVolume = pd.DataFrame(TmpResult[2],index=[i])
TmpResultCalced = pd.DataFrame(TmpResult[3],index=[i])
self.ResultMole.append(TmpResultMole)
self.ResultWeight.append(TmpResultWeight)
self.ResultVolume.append(TmpResultVolume)
self.ResultCalced.append(TmpResultCalced)
self.DictList.append(tmpDict)
self.useddf = pd.concat(self.ResultVolume)
self.FinalResultMole = self.ReduceSize(pd.concat(self.ResultMole).set_index('Label'))
self.FinalResultWeight = self.ReduceSize(pd.concat(self.ResultWeight).set_index('Label'))
self.FinalResultVolume = self.ReduceSize(pd.concat(self.ResultVolume).set_index('Label'))
self.FinalResultCalced = self.ReduceSize(pd.concat(self.ResultCalced).set_index('Label'))
self.FinalResultMole = self.FinalResultMole.fillna(0)
self.FinalResultWeight = self.FinalResultWeight.fillna(0)
self.FinalResultVolume = self.FinalResultVolume.fillna(0)
self.FinalResultCalced = self.FinalResultCalced.fillna(0)
self.FinalResultMole = self.FinalResultMole.loc[:, (self.FinalResultMole != 0).any(axis=0)]
self.FinalResultWeight = self.FinalResultWeight.loc[:, (self.FinalResultWeight != 0).any(axis=0)]
self.FinalResultVolume = self.FinalResultVolume.loc[:, (self.FinalResultVolume != 0).any(axis=0)]
self.FinalResultCalced = self.FinalResultCalced.loc[:, (self.FinalResultCalced != 0).any(axis=0)]
self.newdf = self.FinalResultMole
self.newdf1 = self.FinalResultWeight
self.newdf2 = self.FinalResultVolume
self.newdf3 = self.FinalResultCalced
print(self.FinalResultVolume)
#self.WholeResult = self.WholeResult.T.groupby(level=0).first().T
#self.model = PandasModel(self.WholeResult)
#self.model = PandasModel(self.FinalResultVolume)
#self.model = PandasModel(self.useddf)
self.modelMole = PandasModel(self.FinalResultMole)
self.modelWeight= PandasModel(self.FinalResultWeight)
self.modelVolume = PandasModel(self.FinalResultVolume)
self.modelCalced = PandasModel(self.FinalResultCalced)
#self.tableView.setModel(self.model)
self.tableViewMole.setModel(self.modelMole)
self.tableViewWeight.setModel(self.modelWeight)
self.tableViewVolume.setModel(self.modelVolume)
self.tableViewCalced.setModel(self.modelCalced)
self.WholeResult = pd.concat([self.FinalResultMole,self.FinalResultWeight,self.FinalResultVolume,self.FinalResultCalced], axis=1)
self.OutPutData = self.WholeResult
def singleCalc(self,
m={'Al2O3': 13.01, 'Alpha': 0.6, 'Ba': 188.0, 'Be': 0.85, 'CaO': 8.35, 'Ce': 28.2, 'Co': 45.2,
'Cr': 117.0, 'Cs': 0.83, 'Cu': 53.5, 'Dy': 5.58, 'Er': 2.96, 'Eu': 1.79, 'Fe2O3': 14.47,
'FeO': 5.51, 'Ga': 19.4, 'Gd': 5.24, 'Hf': 3.38, 'Ho': 1.1, 'K2O': 0.72, 'LOI': 5.05,
'La': 11.4, 'Label': 'ZhangSH2016', 'Li': 15.0, 'Lu': 0.39, 'Mg#': 41.9, 'MgO': 5.26,
'MnO': 0.21, 'Na2O': 1.88, 'Nb': 12.6, 'Nd': 18.4, 'Ni': 69.4, 'P2O5': 0.23, 'Pb': 3.17,
'Pr': 3.95, 'Rb': 18.4, 'Sc': 37.4, 'SiO2': 48.17, 'Size': 10, 'Sm': 5.08, 'Sr': 357,
'Ta': 0.77, 'Tb': 0.88, 'Th': 1.85, 'TiO2': 2.56, 'Tl': 0.06, 'Tm': 0.44, 'Total': 99.91,
'U': 0.41, 'V': 368.0, 'Y': 29.7, 'Yb': 2.68, 'Zn': 100.0, 'Zr': 130.0, }):
DataResult={}
DataWeight={}
DataVolume={}
DataCalced={}
DataResult.update({'Label': m['Label']})
DataWeight.update({'Label': m['Label']})
DataVolume.update({'Label': m['Label']})
DataCalced.update({'Label': m['Label']})
DataResult.update({'Width': m['Width']})
DataWeight.update({'Width': m['Width']})
DataVolume.update({'Width': m['Width']})
DataCalced.update({'Width': m['Width']})
DataResult.update({'Style': m['Style']})
DataWeight.update({'Style': m['Style']})
DataVolume.update({'Style': m['Style']})
DataCalced.update({'Style': m['Style']})
DataResult.update({'Alpha': m['Alpha']})
DataWeight.update({'Alpha': m['Alpha']})
DataVolume.update({'Alpha': m['Alpha']})
DataCalced.update({'Alpha': m['Alpha']})
DataResult.update({'Size': m['Size']})
DataWeight.update({'Size': m['Size']})
DataVolume.update({'Size': m['Size']})
DataCalced.update({'Size': m['Size']})
DataResult.update({'Color': m['Color']})
DataWeight.update({'Color': m['Color']})
DataVolume.update({'Color': m['Color']})
DataCalced.update({'Color': m['Color']})
DataResult.update({'Marker': m['Marker']})
DataWeight.update({'Marker': m['Marker']})
DataVolume.update({'Marker': m['Marker']})
DataCalced.update({'Marker': m['Marker']})
WholeMass = 0
EachMole = {}
for j in self.Elements:
'''
Get the Whole Mole of the dataset
'''
try:
T_TMP = m[j]
except(KeyError):
T_TMP = 0
if j == 'Sr':
TMP = T_TMP / (87.62 / 103.619 * 10000)
elif j == 'Ba':
TMP = T_TMP / (137.327 / 153.326 * 10000)
elif j == 'Ni':
TMP = T_TMP / (58.6934 / 74.69239999999999 * 10000)
elif j == 'Cr':
TMP = T_TMP / ((2 * 51.9961) / 151.98919999999998 * 10000)
elif j == 'Zr':
# Zr Multi 2 here
TMP = T_TMP / ((2 * 91.224) / 123.22200000000001 * 10000)
else:
TMP = T_TMP
V = TMP
try:
WholeMass += float(V)
except ValueError:
pass
WeightCorrectionFactor = (100 / WholeMass)
for j in self.Elements:
'''
Get the Mole percentage of each element
'''
try:
T_TMP = m[j]
except(KeyError):
T_TMP = 0
if j == 'Sr':
TMP = T_TMP / (87.62 / 103.619 * 10000)
elif j == 'Ba':
TMP = T_TMP / (137.327 / 153.326 * 10000)
elif j == 'Ni':
TMP = T_TMP / (58.6934 / 74.69239999999999 * 10000)
elif j == 'Cr':
TMP = T_TMP / ((2 * 51.9961) / 151.98919999999998 * 10000)
elif j == 'Zr':
# Zr not Multiple by 2 Here
TMP = T_TMP / ((91.224) / 123.22200000000001 * 10000)
else:
TMP = T_TMP
try:
M = TMP / self.BaseMass[j] * WeightCorrectionFactor
except TypeError:
pass
# M= TMP/NewMass(j) * WeightCorrectionFactor
EachMole.update({j: M})
# self.DataMole.append(EachMole)
DataCalculating = EachMole
Fe3 = DataCalculating['Fe2O3']
Fe2 = DataCalculating['FeO']
Mg = DataCalculating['MgO']
Ca = DataCalculating['CaO']
Na = DataCalculating['Na2O']
try:
DataCalced.update({'Fe3+/(Total Fe) in rock (Mole)': 100 * Fe3 * 2 / (Fe3 * 2 + Fe2)})
except(ZeroDivisionError):
DataCalced.update({'Fe3+/(Total Fe) in rock (Mole)': 0})
pass
try:
DataCalced.update({'Mg/(Mg+Total Fe) in rock (Mole)': 100 * Mg / (Mg + Fe3 * 2 + Fe2)})
except(ZeroDivisionError):
DataCalced.update({'Mg/(Mg+Total Fe) in rock (Mole)': 0})
pass
try:
DataCalced.update({'Mg/(Mg+Fe2+) in rock (Mole)': 100 * Mg / (Mg + Fe2)})
except(ZeroDivisionError):
DataCalced.update({'Mg/(Mg+Fe2+) in rock (Mole)': 0})
pass
try:
DataCalced.update({'Ca/(Ca+Na) in rock (Mole)': 100 * Ca / (Ca + Na * 2)})
except(ZeroDivisionError):
DataCalced.update({'Ca/(Ca+Na) in rock (Mole)': 0})
pass
DataCalculating['CaO'] += DataCalculating['Sr']
DataCalculating['Sr'] = 0
DataCalculating['K2O'] += 2 * DataCalculating['Ba']
DataCalculating['Ba'] = 0
try:
if DataCalculating['CaO'] >= 10 / 3 * DataCalculating['P2O5']:
DataCalculating['CaO'] -= 10 / 3 * DataCalculating['P2O5']
else:
DataCalculating['CaO'] = 0
except(ZeroDivisionError):
pass
DataCalculating['P2O5'] = DataCalculating['P2O5'] / 1.5
Apatite = DataCalculating['P2O5']
# IF(S19>=T15,S19-T15,0)
if DataCalculating['F'] >= DataCalculating['P2O5']:
DataCalculating['F'] -= DataCalculating['P2O5']
else:
DataCalculating['F'] = 0
if DataCalculating['F'] >= DataCalculating['P2O5']:
DataCalculating['F'] -= DataCalculating['P2O5']
else:
DataCalculating['F'] = 0
if DataCalculating['Na2O'] >= DataCalculating['Cl']:
DataCalculating['Na2O'] -= DataCalculating['Cl']
else:
DataCalculating['Na2O'] = 0
Halite = DataCalculating['Cl']
# IF(U12>=(U19/2),U12-(U19/2),0)
if DataCalculating['CaO'] >= 0.5 * DataCalculating['F']:
DataCalculating['CaO'] -= 0.5 * DataCalculating['F']
else:
DataCalculating['CaO'] = 0
DataCalculating['F'] *= 0.5
Fluorite = DataCalculating['F']
# =IF(V17>0,IF(V13>=V17,'Thenardite',IF(V13>0,'Both','Anhydrite')),'None')
AorT = 0
if DataCalculating['SO3'] <= 0:
AorT = 'None'
else:
if DataCalculating['Na2O'] >= DataCalculating['SO3']:
AorT = 'Thenardite'
else:
if DataCalculating['Na2O'] > 0:
AorT = 'Both'
else:
AorT = 'Anhydrite'
# =IF(W26='Anhydrite',V17,IF(W26='Both',V12,0))
# =IF(W26='Thenardite',V17,IF(W26='Both',V17-W17,0))
if AorT == 'Anhydrite':
DataCalculating['Sr'] = 0
elif AorT == 'Thenardite':
DataCalculating['Sr'] = DataCalculating['SO3']
DataCalculating['SO3'] = 0
elif AorT == 'Both':
DataCalculating['Sr'] = DataCalculating['SO3'] - DataCalculating['CaO']
DataCalculating['SO3'] = DataCalculating['CaO']
else:
DataCalculating['SO3'] = 0
DataCalculating['Sr'] = 0
DataCalculating['CaO'] -= DataCalculating['SO3']
DataCalculating['Na2O'] -= DataCalculating['Sr']
Anhydrite = DataCalculating['SO3']
Thenardite = DataCalculating['Sr']
Pyrite = 0.5 * DataCalculating['S']
# =IF(W9>=(W18*0.5),W9-(W18*0.5),0)
if DataCalculating['FeO'] >= DataCalculating['S'] * 0.5:
DataCalculating['FeO'] -= DataCalculating['S'] * 0.5
else:
DataCalculating['FeO'] = 0
# =IF(X24>0,IF(X9>=X24,'Chromite',IF(X9>0,'Both','Magnesiochromite')),'None')
if DataCalculating['Cr'] > 0:
if DataCalculating['FeO'] >= DataCalculating['Cr']:
CorM = 'Chromite'
elif DataCalculating['FeO'] > 0:
CorM = 'Both'
else:
CorM = 'Magnesiochromite'
else:
CorM = 'None'
# =IF(Y26='Chromite',X24,IF(Y26='Both',X9,0))
# =IF(Y26='Magnesiochromite',X24,IF(Y26='Both',X24-Y24,0))
if CorM == 'Chromite':
DataCalculating['Cr'] = DataCalculating['Cr']
DataCalculating['Ni'] = 0
elif CorM == 'Magnesiochromite':
DataCalculating['Ni'] = DataCalculating['Cr']
DataCalculating['Cr'] = 0
elif CorM == 'Both':
DataCalculating['Ni'] = DataCalculating['Cr'] - DataCalculating['FeO']
DataCalculating['Cr'] = DataCalculating['FeO']
else:
DataCalculating['Cr'] = 0
DataCalculating['Ni'] = 0
DataCalculating['MgO'] -= DataCalculating['Ni']
Magnesiochromite = DataCalculating['Ni']
Chromite = DataCalculating['Cr']
# =IF(X9>=Y24,X9-Y24,0)
if DataCalculating['FeO'] >= DataCalculating['Cr']:
DataCalculating['FeO'] -= DataCalculating['Cr']
else:
DataCalculating['FeO'] = 0
# =IF(Y6>0,IF(Y9>=Y6,'Ilmenite',IF(Y9>0,'Both','Sphene')),'None')
if DataCalculating['TiO2'] < 0:
IorS = 'None'
else:
if DataCalculating['FeO'] >= DataCalculating['TiO2']:
IorS = 'Ilmenite'
else:
if DataCalculating['FeO'] > 0:
IorS = 'Both'
else:
IorS = 'Sphene'
# =IF(Z26='Ilmenite',Y6,IF(Z26='Both',Y9,0))
# =IF(Z26='Sphene',Y6,IF(Z26='Both',Y6-Z6,0))
if IorS == 'Ilmenite':
DataCalculating['TiO2'] = DataCalculating['TiO2']
DataCalculating['MnO'] = 0
elif IorS == 'Sphene':
DataCalculating['MnO'] = DataCalculating['TiO2']
DataCalculating['TiO2'] = 0
elif IorS == 'Both':
DataCalculating['MnO'] = DataCalculating['TiO2'] - DataCalculating['FeO']
DataCalculating['TiO2'] = DataCalculating['FeO']
else:
DataCalculating['TiO2'] = 0
DataCalculating['MnO'] = 0
DataCalculating['FeO'] -= DataCalculating['TiO2']
Ilmenite = DataCalculating['TiO2']
# =IF(Z16>0,IF(Z12>=Z16,'Calcite',IF(Z12>0,'Both','Na2CO3')),'None')
if DataCalculating['CO2'] <= 0:
CorN = 'None'
else:
if DataCalculating['CaO'] >= DataCalculating['CO2']:
CorN = 'Calcite'
else:
if DataCalculating['CaO'] > 0:
CorN = 'Both'
else:
CorN = 'Na2CO3'
# =IF(AA26='Calcite',Z16,IF(AA26='Both',Z12,0))
# =IF(AA26='Na2CO3',Z16,IF(AA26='Both',Z16-AA16,0))
if CorN == 'None':
DataCalculating['CO2'] = 0
DataCalculating['SO3'] = 0
elif CorN == 'Calcite':
DataCalculating['CO2'] = DataCalculating['CO2']
DataCalculating['SO3'] = 0
elif CorN == 'Na2CO3':
DataCalculating['SO3'] = DataCalculating['SO3']
DataCalculating['CO2'] = 0
elif CorN == 'Both':
DataCalculating['SO3'] = DataCalculating['CO2'] - DataCalculating['CaO']
DataCalculating['CO2'] = DataCalculating['CaO']
DataCalculating['CaO'] -= DataCalculating['CO2']
Calcite = DataCalculating['CO2']
Na2CO3 = DataCalculating['SO3']
# =IF(AA17>Z13,0,Z13-AA17)
if DataCalculating['SO3'] > DataCalculating['Na2O']:
DataCalculating['Na2O'] = 0
else:
DataCalculating['Na2O'] -= DataCalculating['SO3']
DataCalculating['SiO2'] -= DataCalculating['Zr']
Zircon = DataCalculating['Zr']
# =IF(AB14>0,IF(AB7>=AB14,'Orthoclase',IF(AB7>0,'Both','K2SiO3')),'None')
if DataCalculating['K2O'] <= 0:
OorK = 'None'
else:
if DataCalculating['Al2O3'] >= DataCalculating['K2O']:
OorK = 'Orthoclase'
else:
if DataCalculating['Al2O3'] > 0:
OorK = 'Both'
else:
OorK = 'K2SiO3'
# =IF(AC26='Orthoclase',AB14,IF(AC26='Both',AB7,0))
# =IF(AC26='K2SiO3',AB14,IF(AC26='Both',AB14-AB7,0))
if OorK == 'None':
DataCalculating['K2O'] = 0
DataCalculating['P2O5'] = 0
elif OorK == 'Orthoclase':
DataCalculating['K2O'] = DataCalculating['K2O']
DataCalculating['P2O5'] = 0
elif OorK == 'K2SiO3':
DataCalculating['P2O5'] = DataCalculating['K2O']
DataCalculating['K2O'] = 0
elif OorK == 'Both':
DataCalculating['P2O5'] = DataCalculating['K2O'] - DataCalculating['Al2O3']
DataCalculating['K2O'] = DataCalculating['Al2O3']
DataCalculating['Al2O3'] -= DataCalculating['K2O']
# =IF(AC13>0,IF(AC7>=AC13,'Albite',IF(AC7>0,'Both','Na2SiO3')),'None')
if DataCalculating['Na2O'] <= 0:
AorN = 'None'
else:
if DataCalculating['Al2O3'] >= DataCalculating['Na2O']:
AorN = 'Albite'
else:
if DataCalculating['Al2O3'] > 0:
AorN = 'Both'
else:
AorN = 'Na2SiO3'
# =IF(AND(AC7>=AC13,AC7>0),AC7-AC13,0)
if DataCalculating['Al2O3'] >= DataCalculating['Na2O'] and DataCalculating['Al2O3'] > 0:
DataCalculating['Al2O3'] -= DataCalculating['Na2O']
else:
DataCalculating['Al2O3'] = 0
# =IF(AD26='Albite',AC13,IF(AD26='Both',AC7,0))
# =IF(AD26='Na2SiO3',AC13,IF(AD26='Both',AC13-AD13,0))
if AorN == 'Albite':
DataCalculating['Cl'] = 0
elif AorN == 'Both':
DataCalculating['Cl'] = DataCalculating['Na2O'] - DataCalculating['Al2O3']
DataCalculating['Na2O'] = DataCalculating['Al2O3']
elif AorN == 'Na2SiO3':
DataCalculating['Cl'] = DataCalculating['Na2O']
DataCalculating['Na2O'] = 0
elif AorN == 'None':
DataCalculating['Na2O'] = 0
DataCalculating['Cl'] = 0
# =IF(AD7>0,IF(AD12>0,'Anorthite','None'),'None')
'''
Seem like should be =IF(AD7>0,IF(AD12>AD7,'Anorthite','Corundum'),'None')
If Al2O3 is left after alloting orthoclase and albite, then:
Anorthite = Al2O3, CaO = CaO - Al2O3, SiO2 = SiO2 - 2 Al2O3, Al2O3 = 0
If Al2O3 exceeds CaO in the preceding calculation, then:
Anorthite = CaO, Al2O3 = Al2O3 - CaO, SiO2 = SiO2 - 2 CaO
Corundum = Al2O3, CaO =0, Al2O3 = 0
if DataCalculating['Al2O3']<=0:
AorC='None'
else:
if DataCalculating['CaO']>DataCalculating['Al2O3']:
AorC= 'Anorthite'
else:
Aorc='Corundum'
'''
if DataCalculating['Al2O3'] <= 0:
AorC = 'None'
else:
if DataCalculating['CaO'] > 0:
AorC = 'Anorthite'
else:
Aorc = 'None'
# =IF(AE26='Anorthite',IF(AD12>AD7,0,AD7-AD12),AD7)
# =IF(AE26='Anorthite',IF(AD7>AD12,0,AD12-AD7),AD12)
# =IF(AE26='Anorthite',IF(AD7>AD12,AD12,AD7),0)
if AorC == 'Anorthite':
if DataCalculating['Al2O3'] >= DataCalculating['CaO']:
DataCalculating['Sr'] = DataCalculating['CaO']
DataCalculating['Al2O3'] -= DataCalculating['CaO']
DataCalculating['CaO'] = 0
else:
DataCalculating['Sr'] = DataCalculating['Al2O3']
DataCalculating['CaO'] -= DataCalculating['Al2O3']
DataCalculating['Al2O3'] = 0
else:
DataCalculating['Sr'] = 0
Corundum = DataCalculating['Al2O3']
Anorthite = DataCalculating['Sr']
# =IF(AE10>0,IF(AE12>=AE10,'Sphene',IF(AE12>0,'Both','Rutile')),'None')
if DataCalculating['MnO'] <= 0:
SorR = 'None'
else:
if DataCalculating['CaO'] >= DataCalculating['MnO']:
SorR = 'Sphene'
elif DataCalculating['CaO'] > 0:
SorR = 'Both'
else:
SorR = 'Rutile'
# =IF(AF26='Sphene',AE10,IF(AF26='Both',AE12,0))
# =IF(AF26='Rutile',AE10,IF(AF26='Both',AE10-AE12,0))
if SorR == 'Sphene':
DataCalculating['MnO'] = DataCalculating['MnO']
DataCalculating['S'] = 0
elif SorR == 'Rutile':
DataCalculating['S'] = DataCalculating['MnO']
DataCalculating['MnO'] = 0
elif SorR == 'Both':
DataCalculating['S'] = DataCalculating['MnO'] - DataCalculating['CaO']
DataCalculating['MnO'] = DataCalculating['CaO']
elif SorR == 'None':
DataCalculating['MnO'] = 0
DataCalculating['S'] = 0
DataCalculating['CaO'] -= DataCalculating['MnO']
Rutile = DataCalculating['S']
# =IF(AND(AF20>0),IF(AF8>=AF20,'Acmite',IF(AF8>0,'Both','Na2SiO3')),'None')
if DataCalculating['Cl'] <= 0:
ACorN = 'None'
else:
if DataCalculating['Fe2O3'] >= DataCalculating['Cl']:
ACorN = 'Acmite'
else:
if DataCalculating['Fe2O3'] > 0:
ACorN = 'Both'
else:
ACorN = 'Na2SiO3'
# =IF(AG26='Acmite',AF20,IF(AG26='Both',AF8,0))
# =IF(AG26='Na2SiO3',AF20,IF(AG26='Both',AF20-AG19,0))
if ACorN == 'Acmite':
DataCalculating['F'] = DataCalculating['Cl']
DataCalculating['Cl'] = 0
elif ACorN == 'Na2SiO3':
DataCalculating['Cl'] = DataCalculating['Cl']
DataCalculating['F'] = 0
elif ACorN == 'Both':
DataCalculating['F'] = DataCalculating['Fe2O3']
DataCalculating['Cl'] = DataCalculating['Cl'] - DataCalculating['F']
elif ACorN == 'None':
DataCalculating['F'] = 0
DataCalculating['Cl'] = 0
DataCalculating['Fe2O3'] -= DataCalculating['F']
Acmite = DataCalculating['F']
# =IF(AG8>0,IF(AG9>=AG8,'Magnetite',IF(AG9>0,'Both','Hematite')),'None')
if DataCalculating['Fe2O3'] <= 0:
MorH = 'None'
else:
if DataCalculating['FeO'] >= DataCalculating['Fe2O3']:
MorH = 'Magnetite'
else:
if DataCalculating['FeO'] > 0:
MorH = 'Both'
else:
MorH = 'Hematite'
# =IF(AH26='Magnetite',AG8,IF(AH26='Both',AG9,0))
# =IF(AH26='Hematite',AG8,IF(AH26='Both',AG8-AG9,0))
if MorH == 'Magnetite':
DataCalculating['Fe2O3'] = DataCalculating['Fe2O3']
DataCalculating['Ba'] = 0
elif MorH == 'Hematite':
DataCalculating['Fe2O3'] = 0
DataCalculating['Ba'] = DataCalculating['FeO']
elif MorH == 'Both':
DataCalculating['Fe2O3'] = DataCalculating['FeO']
DataCalculating['Ba'] = DataCalculating['Fe2O3'] - DataCalculating['FeO']
elif MorH == 'None':
DataCalculating['Fe2O3'] = 0
DataCalculating['Ba'] == 0
DataCalculating['FeO'] -= DataCalculating['Fe2O3']
Magnetite = DataCalculating['Fe2O3']
Hematite = DataCalculating['Ba']
# =IF(AH11>0,AH11/(AH11+AH9),0)
Fe2 = DataCalculating['FeO']
Mg = DataCalculating['MgO']
if Mg > 0:
DataCalced.update({'Mg/(Mg+Fe2+) in silicates': 100 * Mg / (Mg + Fe2)})
else:
DataCalced.update({'Mg/(Mg+Fe2+) in silicates': 0})
DataCalculating['FeO'] += DataCalculating['MgO']
DataCalculating['MgO'] = 0
# =IF(AI12>0,IF(AI9>=AI12,'Diopside',IF(AI9>0,'Both','Wollastonite')),'None')
if DataCalculating['CaO'] <= 0:
DorW = 'None'
else:
if DataCalculating['FeO'] >= DataCalculating['CaO']:
DorW = 'Diopside'
else:
if DataCalculating['FeO'] > 0:
DorW = 'Both'
else:
DorW = 'Wollastonite'
# =IF(AJ26='Diopside',AI12,IF(AJ26='Both',AI9,0))
# =IF(AJ26='Wollastonite',AI12,IF(AJ26='Both',AI12-AI9,0))
if DorW == 'Diopside':
DataCalculating['CaO'] = DataCalculating['CaO']
DataCalculating['S'] = 0
elif DorW == 'Wollastonite':
DataCalculating['S'] = DataCalculating['CaO']
DataCalculating['CaO'] = 0
elif DorW == 'Both':
DataCalculating['S'] = DataCalculating['CaO'] - DataCalculating['FeO']
DataCalculating['CaO'] = DataCalculating['FeO']
elif DorW == 'None':
DataCalculating['CaO'] = 0
DataCalculating['S'] = 0
DataCalculating['FeO'] -= DataCalculating['CaO']
Diopside = DataCalculating['CaO']
Quartz = DataCalculating['SiO2']
Zircon = DataCalculating['Zr']
K2SiO3 = DataCalculating['P2O5']
Na2SiO3 = DataCalculating['Cl']
Sphene = DataCalculating['MnO']
Hypersthene = DataCalculating['FeO']
Albite = DataCalculating['Na2O']
Orthoclase = DataCalculating['K2O']
Wollastonite = DataCalculating['S']
# =AJ5-(AL6)-(AL7)-(AL8*2)-(AL12)-(AL9)-(AL10*4)-(AL11*2)-(AL13)-(AL14*6)-(AL15*6)-(AL16)
Quartz -= (Zircon +
K2SiO3 +
Anorthite * 2 +
Na2SiO3 +
Acmite * 4 +
Diopside * 2 +
Sphene +
Hypersthene +
Albite * 6 +
Orthoclase * 6 +
Wollastonite)
# =IF(AL5>0,AL5,0)
if Quartz > 0:
Quartz = Quartz
else:
Quartz = 0
# =IF(AL13>0,IF(AL5>=0,'Hypersthene',IF(AL13+(2*AL5)>0,'Both','Olivine')),'None')
if Hypersthene <= 0:
HorO = 'None'
else:
if Quartz >= 0:
HorO = 'Hypersthene'
else:
if Hypersthene + 2 * Quartz > 0:
HorO = 'Both'
else:
HorO = 'Olivine'
# =IF(AN26='Hypersthene',AL13,IF(AN26='Both',AL13+(2*AL5),0))
# =IF(AN26='Olivine',AL13*0.5,IF(AN26='Both',ABS(AL5),0))
Old_Hypersthene = Hypersthene
if HorO == 'Hypersthene':
Hypersthene = Hypersthene
Olivine = 0
elif HorO == 'Both':
Hypersthene = Hypersthene + Quartz * 2
Olivine = abs(Quartz)
elif HorO == 'Olivine':
Olivine = Hypersthene / 2
Hypersthene = 0
elif HorO == 'None':
Hypersthene = 0
Olivine = 0
# =AL5+AL13-(AN13+AN17)
Quartz += Old_Hypersthene - (Hypersthene + Olivine)
# =IF(AL12>0,IF(AN5>=0,'Sphene',IF(AL12+AN5>0,'Both','Perovskite')),'None')
if Sphene <= 0:
SorP = 'None'
else:
if Quartz >= 0:
SorP = 'Sphene'
else:
if Sphene + Quartz > 0:
SorP = 'Both'
else:
SorP = 'Perovskite'
# =IF(AO26='Sphene',AL12,IF(AO26='Both',AL12+AN5,0))
# =IF(AO26='Perovskite',AL12,IF(AO26='Both',AL12-AO12,0))
Old_Sphene = Sphene
if SorP == 'Sphene':
Sphene = Sphene
Perovskite = 0
elif SorP == 'Perovskite':
Perovskite = Sphene
Sphene = 0
elif SorP == 'Both':
Sphene += Quartz
Perovskite = Old_Sphene - Sphene
elif SorP == 'None':
Sphene = 0
Perovskite = 0
Quartz += Old_Sphene - Sphene
# =IF(AL14>0,IF(AO5>=0,'Albite',IF(AL14+(AO5/4)>0,'Both','Nepheline')),'None')
if Albite <= 0:
AlorNe = 'None'
else:
if Quartz >= 0:
AlorNe = 'Albite'
else:
if Albite + (Quartz / 4) > 0:
AlorNe = 'Both'
else:
AlorNe = 'Nepheline'
# =AO5+(6*AL14)-(AP14*6)-(AP19*2)
# =IF(AP26='Albite',AL14,IF(AP26='Both',AL14+(AO5/4),0))
# =IF(AP26='Nepheline',AL14,IF(AP26='Both',AL14-AP14,0))
Old_Albite = Albite
if AlorNe == 'Albite':
Albite = Albite
Nepheline = 0
elif AlorNe == 'Nepheline':
Nepheline = Albite
Albite = 0
elif AlorNe == 'Both':
Albite += Quartz / 4
Nepheline = Old_Albite - Albite
elif AlorNe == 'None':
Nepheline = 0
Albite = 0
Quartz += (6 * Old_Albite) - (Albite * 6) - (Nepheline * 2)
# =IF(AL8=0,0,AL8/(AL8+(AP14*2)))
if Anorthite == 0:
DataCalced.update({'Plagioclase An content': 0})
else:
DataCalced.update({'Plagioclase An content': 100 * Anorthite / (Anorthite + 2 * Albite)})
# =IF(AL15>0,IF(AP5>=0,'Orthoclase',IF(AL15+(AP5/2)>0,'Both','Leucite')),'None')
if Orthoclase <= 0:
OorL = 'None'
else:
if Quartz >= 0:
OorL = 'Orthoclase'
else:
if Orthoclase + Quartz / 2 > 0:
OorL = 'Both'
else:
OorL = 'Leucite'
# =IF(AQ26='Orthoclase',AL15,IF(AQ26='Both',AL15+(AP5/2),0))
# =IF(AQ26='Leucite',AL15,IF(AQ26='Both',AL15-AQ15,0))
Old_Orthoclase = Orthoclase
if OorL == 'Orthoclase':
Orthoclase = Orthoclase
Leucite = 0
elif OorL == 'Leucite':
Leucite = Orthoclase
Orthoclase = 0
elif OorL == 'Both':
Orthoclase += Quartz / 2
Leucite = Old_Orthoclase - Orthoclase
elif OorL == 'None':
Orthoclase = 0
Leucite = 0
# =AP5+(AL15*6)-(AQ15*6)-(AQ20*4)
Quartz += (Old_Orthoclase * 6) - (Orthoclase * 6) - (Leucite * 4)
# =IF(AL16>0,IF(AQ5>=0,'Wollastonite',IF(AL16+(AQ5*2)>0,'Both','Larnite')),'None')
if Wollastonite <= 0:
WorB = 'None'
else:
if Quartz >= 0:
WorB = 'Wollastonite'
else:
if Wollastonite + Quartz / 2 > 0:
WorB = 'Both'
else:
WorB = 'Larnite'
# =IF(AR26='Wollastonite',AL16,IF(AR26='Both',AL16+(2*AQ5),0))
# =IF(AR26='Larnite',AL16/2,IF(AR26='Both',(AL16-AR16)/2,0))
Old_Wollastonite = Wollastonite
if WorB == 'Wollastonite':
Wollastonite = Wollastonite
Larnite = 0
elif WorB == 'Larnite':
Larnite = Wollastonite / 2
Wollastonite = 0
elif WorB == 'Both':
Wollastonite += Quartz * 2
Larnite = (Old_Wollastonite - Wollastonite) / 2
elif WorB == 'None':
Wollastonite = 0
Larnite = 0
# =AQ5+AL16-AR16-AR21
Quartz += Old_Wollastonite - Wollastonite - Larnite
# =IF(AL11>0,IF(AR5>=0,'Diopside',IF(AL11+AR5>0,'Both','LarniteOlivine')),'None')
if Diopside <= 0:
DorL = 'None'
else:
if Quartz >= 0:
DorL = 'Diopside'
else:
if Diopside + Quartz > 0:
DorL = 'Both'
else:
DorL = 'LarniteOlivine'
# =IF(AS26='Diopside',AL11,IF(AS26='Both',AL11+AR5,0))
# =(IF(AS26='LarniteOlivine',AL11/2,IF(AS26='Both',(AL11-AS11)/2,0)))+AN17
# =(IF(AS26='LarniteOlivine',AL11/2,IF(AS26='Both',(AL11-AS11)/2,0)))+AR21
Old_Diopside = Diopside
Old_Larnite = Larnite
Old_Olivine = Olivine
if DorL == 'Diopside':
Diopside = Diopside
elif DorL == 'LarniteOlivine':
Larnite += Diopside / 2
Olivine += Diopside / 2
Diopside = 0
elif DorL == 'Both':
Diopside += Quartz
Larnite += Old_Diopside - Diopside
Olivine += Old_Diopside - Diopside
elif DorL == 'None':
Diopside = 0
# =AR5+(AL11*2)+AN17+AR21-AS21-(AS11*2)-AS17
Quartz += (Old_Diopside * 2) + Old_Olivine + Old_Larnite - Larnite - (Diopside * 2) - Olivine
# =IF(AQ20>0,IF(AS5>=0,'Leucite',IF(AQ20+(AS5/2)>0,'Both','Kalsilite')),'None')
if Leucite <= 0:
LorK = 'None'
else:
if Quartz >= 0:
LorK = 'Leucite'
else:
if Leucite + Quartz / 2 > 0:
LorK = 'Both'
else:
LorK = 'Kalsilite'
# =IF(AT26='Leucite',AQ20,IF(AT26='Both',AQ20+(AS5/2),0))
# =IF(AT26='Kalsilite',AQ20,IF(AT26='Both',AQ20-AT20,0))
Old_Leucite = Leucite
if LorK == 'Leucite':
Leucite = Leucite
Kalsilite = 0
elif LorK == 'Kalsilite':
Kalsilite = Leucite
Leucite = 0
elif LorK == 'Both':
Leucite += Quartz / 2
Kalsilite = Old_Leucite - Leucite
elif LorK == 'None':
Leucite = 0
Kalsilite = 0
# =AS5+(AQ20*4)-(AT20*4)-(AT22*2)
Quartz += Old_Leucite * 4 - Leucite * 4 - Kalsilite * 2
Q = Quartz
A = Orthoclase
P = Anorthite + Albite
F = Nepheline + Leucite + Kalsilite
DataResult.update({'Quartz': Quartz})
DataResult.update({'Zircon': Zircon})
DataResult.update({'K2SiO3': K2SiO3})
DataResult.update({'Anorthite': Anorthite})
DataResult.update({'Na2SiO3': Na2SiO3})
DataResult.update({'Acmite': Acmite})
DataResult.update({'Diopside': Diopside})
DataResult.update({'Sphene': Sphene})
DataResult.update({'Hypersthene': Hypersthene})
DataResult.update({'Albite': Albite})
DataResult.update({'Orthoclase': Orthoclase})
DataResult.update({'Wollastonite': Wollastonite})
DataResult.update({'Olivine': Olivine})
DataResult.update({'Perovskite': Perovskite})
DataResult.update({'Nepheline': Nepheline})
DataResult.update({'Leucite': Leucite})
DataResult.update({'Larnite': Larnite})
DataResult.update({'Kalsilite': Kalsilite})
DataResult.update({'Apatite': Apatite})
DataResult.update({'Halite': Halite})
DataResult.update({'Fluorite': Fluorite})
DataResult.update({'Anhydrite': Anhydrite})
DataResult.update({'Thenardite': Thenardite})
DataResult.update({'Pyrite': Pyrite})
DataResult.update({'Magnesiochromite': Magnesiochromite})
DataResult.update({'Chromite': Chromite})
DataResult.update({'Ilmenite': Ilmenite})
DataResult.update({'Calcite': Calcite})
DataResult.update({'Na2CO3': Na2CO3})
DataResult.update({'Corundum': Corundum})
DataResult.update({'Rutile': Rutile})
DataResult.update({'Magnetite': Magnetite})
DataResult.update({'Hematite': Hematite})
DataResult.update({'Q Mole': Q})
DataResult.update({'A Mole': A})
DataResult.update({'P Mole': P})
DataResult.update({'F Mole': F})
DataWeight.update({'Quartz': Quartz * self.DataBase['Quartz'][0]})
DataWeight.update({'Zircon': Zircon * self.DataBase['Zircon'][0]})
DataWeight.update({'K2SiO3': K2SiO3 * self.DataBase['K2SiO3'][0]})
DataWeight.update({'Anorthite': Anorthite * self.DataBase['Anorthite'][0]})
DataWeight.update({'Na2SiO3': Na2SiO3 * self.DataBase['Na2SiO3'][0]})
DataWeight.update({'Acmite': Acmite * self.DataBase['Acmite'][0]})
DataWeight.update({'Diopside': Diopside * self.DataBase['Diopside'][0]})
DataWeight.update({'Sphene': Sphene * self.DataBase['Sphene'][0]})
DataWeight.update({'Hypersthene': Hypersthene * self.DataBase['Hypersthene'][0]})
DataWeight.update({'Albite': Albite * self.DataBase['Albite'][0]})
DataWeight.update({'Orthoclase': Orthoclase * self.DataBase['Orthoclase'][0]})
DataWeight.update({'Wollastonite': Wollastonite * self.DataBase['Wollastonite'][0]})
DataWeight.update({'Olivine': Olivine * self.DataBase['Olivine'][0]})
DataWeight.update({'Perovskite': Perovskite * self.DataBase['Perovskite'][0]})
DataWeight.update({'Nepheline': Nepheline * self.DataBase['Nepheline'][0]})
DataWeight.update({'Leucite': Leucite * self.DataBase['Leucite'][0]})
DataWeight.update({'Larnite': Larnite * self.DataBase['Larnite'][0]})
DataWeight.update({'Kalsilite': Kalsilite * self.DataBase['Kalsilite'][0]})
DataWeight.update({'Apatite': Apatite * self.DataBase['Apatite'][0]})
DataWeight.update({'Halite': Halite * self.DataBase['Halite'][0]})
DataWeight.update({'Fluorite': Fluorite * self.DataBase['Fluorite'][0]})
DataWeight.update({'Anhydrite': Anhydrite * self.DataBase['Anhydrite'][0]})
DataWeight.update({'Thenardite': Thenardite * self.DataBase['Thenardite'][0]})
DataWeight.update({'Pyrite': Pyrite * self.DataBase['Pyrite'][0]})
DataWeight.update({'Magnesiochromite': Magnesiochromite * self.DataBase['Magnesiochromite'][0]})
DataWeight.update({'Chromite': Chromite * self.DataBase['Chromite'][0]})
DataWeight.update({'Ilmenite': Ilmenite * self.DataBase['Ilmenite'][0]})
DataWeight.update({'Calcite': Calcite * self.DataBase['Calcite'][0]})
DataWeight.update({'Na2CO3': Na2CO3 * self.DataBase['Na2CO3'][0]})
DataWeight.update({'Corundum': Corundum * self.DataBase['Corundum'][0]})
DataWeight.update({'Rutile': Rutile * self.DataBase['Rutile'][0]})
DataWeight.update({'Magnetite': Magnetite * self.DataBase['Magnetite'][0]})
DataWeight.update({'Hematite': Hematite * self.DataBase['Hematite'][0]})
DataWeight.update({'Q Weight': Quartz * self.DataBase['Quartz'][0]})
DataWeight.update({'A Weight': Orthoclase * self.DataBase['Orthoclase'][0]})
DataWeight.update({'P Weight': Anorthite * self.DataBase['Anorthite'][0] + Albite * self.DataBase['Albite'][0]})
DataWeight.update({'F Weight': Nepheline * self.DataBase['Nepheline'][0] + Leucite * self.DataBase['Leucite'][0] + Kalsilite * self.DataBase['Kalsilite'][0]})
WholeVolume = 0
WholeMole = 0
tmpVolume = []
tmpVolume.append(Quartz * self.DataBase['Quartz'][0] / self.DataBase['Quartz'][1])
tmpVolume.append(Zircon * self.DataBase['Zircon'][0] / self.DataBase['Zircon'][1])
tmpVolume.append(K2SiO3 * self.DataBase['K2SiO3'][0] / self.DataBase['K2SiO3'][1])
tmpVolume.append(Anorthite * self.DataBase['Anorthite'][0] / self.DataBase['Anorthite'][1])
tmpVolume.append(Na2SiO3 * self.DataBase['Na2SiO3'][0] / self.DataBase['Na2SiO3'][1])
tmpVolume.append(Acmite * self.DataBase['Acmite'][0] / self.DataBase['Acmite'][1])
tmpVolume.append(Diopside * self.DataBase['Diopside'][0] / self.DataBase['Diopside'][1])
tmpVolume.append(Sphene * self.DataBase['Sphene'][0] / self.DataBase['Sphene'][1])
tmpVolume.append(Hypersthene * self.DataBase['Hypersthene'][0] / self.DataBase['Hypersthene'][1])
tmpVolume.append(Albite * self.DataBase['Albite'][0] / self.DataBase['Albite'][1])
tmpVolume.append(Orthoclase * self.DataBase['Orthoclase'][0] / self.DataBase['Orthoclase'][1])
tmpVolume.append(Wollastonite * self.DataBase['Wollastonite'][0] / self.DataBase['Wollastonite'][1])
tmpVolume.append(Olivine * self.DataBase['Olivine'][0] / self.DataBase['Olivine'][1])
tmpVolume.append(Perovskite * self.DataBase['Perovskite'][0] / self.DataBase['Perovskite'][1])
tmpVolume.append(Nepheline * self.DataBase['Nepheline'][0] / self.DataBase['Nepheline'][1])
tmpVolume.append(Leucite * self.DataBase['Leucite'][0] / self.DataBase['Leucite'][1])
tmpVolume.append(Larnite * self.DataBase['Larnite'][0] / self.DataBase['Larnite'][1])
tmpVolume.append(Kalsilite * self.DataBase['Kalsilite'][0] / self.DataBase['Kalsilite'][1])
tmpVolume.append(Apatite * self.DataBase['Apatite'][0] / self.DataBase['Apatite'][1])
tmpVolume.append(Halite * self.DataBase['Halite'][0] / self.DataBase['Halite'][1])
tmpVolume.append(Fluorite * self.DataBase['Fluorite'][0] / self.DataBase['Fluorite'][1])
tmpVolume.append(Anhydrite * self.DataBase['Anhydrite'][0] / self.DataBase['Anhydrite'][1])
tmpVolume.append(Thenardite * self.DataBase['Thenardite'][0] / self.DataBase['Thenardite'][1])
tmpVolume.append(Pyrite * self.DataBase['Pyrite'][0] / self.DataBase['Pyrite'][1])
tmpVolume.append(Magnesiochromite * self.DataBase['Magnesiochromite'][0] / self.DataBase['Magnesiochromite'][1])
tmpVolume.append(Chromite * self.DataBase['Chromite'][0] / self.DataBase['Chromite'][1])
tmpVolume.append(Ilmenite * self.DataBase['Ilmenite'][0] / self.DataBase['Ilmenite'][1])
tmpVolume.append(Calcite * self.DataBase['Calcite'][0] / self.DataBase['Calcite'][1])
tmpVolume.append(Na2CO3 * self.DataBase['Na2CO3'][0] / self.DataBase['Na2CO3'][1])
tmpVolume.append(Corundum * self.DataBase['Corundum'][0] / self.DataBase['Corundum'][1])
tmpVolume.append(Rutile * self.DataBase['Rutile'][0] / self.DataBase['Rutile'][1])
tmpVolume.append(Magnetite * self.DataBase['Magnetite'][0] / self.DataBase['Magnetite'][1])
tmpVolume.append(Hematite * self.DataBase['Hematite'][0] / self.DataBase['Hematite'][1])
WholeVolume = sum(tmpVolume)
DataVolume.update(
{'Quartz': (Quartz * self.DataBase['Quartz'][0] / self.DataBase['Quartz'][1]) / WholeVolume * 100})
DataVolume.update(
{'Zircon': (Zircon * self.DataBase['Zircon'][0] / self.DataBase['Zircon'][1]) / WholeVolume * 100})
DataVolume.update(
{'K2SiO3': (K2SiO3 * self.DataBase['K2SiO3'][0] / self.DataBase['K2SiO3'][1]) / WholeVolume * 100})
DataVolume.update({'Anorthite': (Anorthite * self.DataBase['Anorthite'][0] / self.DataBase['Anorthite'][
1]) / WholeVolume * 100})
DataVolume.update(
{'Na2SiO3': (Na2SiO3 * self.DataBase['Na2SiO3'][0] / self.DataBase['Na2SiO3'][1]) / WholeVolume * 100})
DataVolume.update(
{'Acmite': (Acmite * self.DataBase['Acmite'][0] / self.DataBase['Acmite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Diopside': (Diopside * self.DataBase['Diopside'][0] / self.DataBase['Diopside'][1]) / WholeVolume * 100})
DataVolume.update(
{'Sphene': (Sphene * self.DataBase['Sphene'][0] / self.DataBase['Sphene'][1]) / WholeVolume * 100})
DataVolume.update({'Hypersthene': (Hypersthene * self.DataBase['Hypersthene'][0] / self.DataBase['Hypersthene'][
1]) / WholeVolume * 100})
DataVolume.update(
{'Albite': (Albite * self.DataBase['Albite'][0] / self.DataBase['Albite'][1]) / WholeVolume * 100})
DataVolume.update({'Orthoclase': (Orthoclase * self.DataBase['Orthoclase'][0] / self.DataBase['Orthoclase'][
1]) / WholeVolume * 100})
DataVolume.update({'Wollastonite': (Wollastonite * self.DataBase['Wollastonite'][0] /
self.DataBase['Wollastonite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Olivine': (Olivine * self.DataBase['Olivine'][0] / self.DataBase['Olivine'][1]) / WholeVolume * 100})
DataVolume.update({'Perovskite': (Perovskite * self.DataBase['Perovskite'][0] / self.DataBase['Perovskite'][
1]) / WholeVolume * 100})
DataVolume.update({'Nepheline': (Nepheline * self.DataBase['Nepheline'][0] / self.DataBase['Nepheline'][
1]) / WholeVolume * 100})
DataVolume.update(
{'Leucite': (Leucite * self.DataBase['Leucite'][0] / self.DataBase['Leucite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Larnite': (Larnite * self.DataBase['Larnite'][0] / self.DataBase['Larnite'][1]) / WholeVolume * 100})
DataVolume.update({'Kalsilite': (Kalsilite * self.DataBase['Kalsilite'][0] / self.DataBase['Kalsilite'][
1]) / WholeVolume * 100})
DataVolume.update(
{'Apatite': (Apatite * self.DataBase['Apatite'][0] / self.DataBase['Apatite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Halite': (Halite * self.DataBase['Halite'][0] / self.DataBase['Halite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Fluorite': (Fluorite * self.DataBase['Fluorite'][0] / self.DataBase['Fluorite'][1]) / WholeVolume * 100})
DataVolume.update({'Anhydrite': (Anhydrite * self.DataBase['Anhydrite'][0] / self.DataBase['Anhydrite'][
1]) / WholeVolume * 100})
DataVolume.update({'Thenardite': (Thenardite * self.DataBase['Thenardite'][0] / self.DataBase['Thenardite'][
1]) / WholeVolume * 100})
DataVolume.update(
{'Pyrite': (Pyrite * self.DataBase['Pyrite'][0] / self.DataBase['Pyrite'][1]) / WholeVolume * 100})
DataVolume.update({'Magnesiochromite': (Magnesiochromite * self.DataBase['Magnesiochromite'][0] /
self.DataBase['Magnesiochromite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Chromite': (Chromite * self.DataBase['Chromite'][0] / self.DataBase['Chromite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Ilmenite': (Ilmenite * self.DataBase['Ilmenite'][0] / self.DataBase['Ilmenite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Calcite': (Calcite * self.DataBase['Calcite'][0] / self.DataBase['Calcite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Na2CO3': (Na2CO3 * self.DataBase['Na2CO3'][0] / self.DataBase['Na2CO3'][1]) / WholeVolume * 100})
DataVolume.update(
{'Corundum': (Corundum * self.DataBase['Corundum'][0] / self.DataBase['Corundum'][1]) / WholeVolume * 100})
DataVolume.update(
{'Rutile': (Rutile * self.DataBase['Rutile'][0] / self.DataBase['Rutile'][1]) / WholeVolume * 100})
DataVolume.update({'Magnetite': (Magnetite * self.DataBase['Magnetite'][0] / self.DataBase['Magnetite'][
1]) / WholeVolume * 100})
DataVolume.update(
{'Hematite': (Hematite * self.DataBase['Hematite'][0] / self.DataBase['Hematite'][1]) / WholeVolume * 100})
DataVolume.update({'Q': DataVolume['Quartz']})
DataVolume.update({'A': DataVolume['Orthoclase']})
DataVolume.update({'P': DataVolume['Anorthite'] + DataVolume['Albite']})
DataVolume.update({'F': DataVolume['Nepheline'] + DataVolume['Leucite'] + DataVolume['Kalsilite']})
DI = 0
# for i in ['Quartz', 'Anorthite', 'Albite', 'Orthoclase', 'Nepheline', 'Leucite', 'Kalsilite']:
# exec('DI+=' + i + '*self.DataBase[\'' + i + '\'][0]')
DI = Quartz + Anorthite + Albite + Orthoclase + Nepheline + Leucite + Kalsilite
DiWeight=0
DiVolume=0
DiWeight = DataWeight['Quartz']+DataWeight['Anorthite']+DataWeight['Albite']+DataWeight['Orthoclase']+DataWeight['Nepheline']+DataWeight['Leucite']+DataWeight['Kalsilite']
DiVolume = DataVolume['Quartz']+DataVolume['Anorthite']+DataVolume['Albite']+DataVolume['Orthoclase']+DataVolume['Nepheline']+DataVolume['Leucite']+DataVolume['Kalsilite']
# print('\n\n DI is\n',DI,'\n\n')
DataCalced.update({'Differentiation Index Weight': DiWeight})
DataCalced.update({'Differentiation Index Volume': DiVolume})
return (DataResult, DataWeight, DataVolume, DataCalced)
def WriteData(self, target='DataResult'):
DataToWrite = []
TMP_DataToWrite = ['Label']
TMP_DataToWrite = ['Label', 'Marker', 'Color', 'Size', 'Alpha', 'Style', 'Width']
for j in self.Minerals:
TMP_DataToWrite.append(str(j))
DataToWrite.append(TMP_DataToWrite)
for i in range(len(self.DataMole)):
TMP_DataToWrite = []
k = self.raw.at[i, 'Label']
TMP_DataToWrite = [self.raw.at[i, 'Label'], self.raw.at[i, 'Marker'], self.raw.at[i, 'Color'],
self.raw.at[i, 'Size'], self.raw.at[i, 'Alpha'], self.raw.at[i, 'Style'],
self.raw.at[i, 'Width']]
for j in self.Minerals:
command = 'TMP_DataToWrite.append((self.' + target + '[k][j]))'
exec('#print((self.' + target + '[k][j]))')
try:
exec(command)
except(KeyError):
pass
DataToWrite.append(TMP_DataToWrite)
return (DataToWrite)
def WriteCalced(self, target='DataCalced'):
DataToWrite = []
TMP_DataToWrite = ['Label']
TMP_DataToWrite = ['Label', 'Marker', 'Color', 'Size', 'Alpha', 'Style', 'Width']
for j in self.Calced:
TMP_DataToWrite.append(str(j))
DataToWrite.append(TMP_DataToWrite)
for i in range(len(self.DataMole)):
TMP_DataToWrite = []
k = self.raw.at[i, 'Label']
TMP_DataToWrite = [self.raw.at[i, 'Label'], self.raw.at[i, 'Marker'], self.raw.at[i, 'Color'],
self.raw.at[i, 'Size'], self.raw.at[i, 'Alpha'], self.raw.at[i, 'Style'],
self.raw.at[i, 'Width']]
for j in self.Calced:
command = 'TMP_DataToWrite.append((self.' + target + '[k][j]))'
try:
exec('#print((self.' + target + '[k][j]))')
exec(command)
except(KeyError):
pass
DataToWrite.append(TMP_DataToWrite)
# print('\n',DataToWrite,'\n')
return (DataToWrite)
def ReduceSize(self,df=pd.DataFrame):
m = ['Width', 'Style', 'Alpha', 'Size', 'Color', 'Marker', 'Author']
for i in m:
if i in df.columns.values:
df = df.drop(i, 1)
df = df.loc[:, (df != 0).any(axis=0)]
return(df)
def GetSym(self,df=pd.DataFrame):
m = ['Label', 'Width', 'Style', 'Alpha', 'Size', 'Color', 'Marker', 'Author']
for i in df.columns.values:
if i not in m:
df = df.drop(i, 1)
df = df.loc[:, (df != 0).any(axis=0)]
return(df)
def DropUseless(self,df= pd.DataFrame(),droplist = ['Q (Mole)', 'A (Mole)', 'P (Mole)', 'F (Mole)',
'Q (Mass)', 'A (Mass)', 'P (Mass)', 'F (Mass)']):
for t in droplist:
if t in df.columns.values:
df = df.drop(t, 1)
return(df)
def QAPF(self):
self.qapfpop = QAPF(df=self.useddf)
try:
self.qapfpop.QAPF()
except(TypeError):
pass
self.qapfpop.show()
def QAPFsilent(self):
self.qapfpop = QAPF(df=self.useddf)
try:
self.qapfpop.QAPF()
except(TypeError):
pass
self.OutPutFig = self.qapfpop.OutPutFig
def saveResult(self):
DataFileOutput, ok2 = QFileDialog.getSaveFileName(self,
'文件保存',
'C:/',
'Excel Files (*.xlsx);;CSV Files (*.csv)') # 数据文件保存输出
if (DataFileOutput != ''):
if ('csv' in DataFileOutput):
DataFileOutput=DataFileOutput[0:-4]
#self.newdf.to_csv(DataFileOutput, sep=',', encoding='utf-8')
self.newdf.to_csv(DataFileOutput + '-cipw-mole.csv', sep=',', encoding='utf-8')
self.newdf1.to_csv(DataFileOutput + '-cipw-mass.csv', sep=',', encoding='utf-8')
self.newdf2.to_csv(DataFileOutput + '-cipw-volume.csv', sep=',', encoding='utf-8')
self.newdf3.to_csv(DataFileOutput + '-cipw-index.csv', sep=',', encoding='utf-8')
elif ('xlsx' in DataFileOutput):
DataFileOutput = DataFileOutput[0:-5]
#self.newdf.to_excel(DataFileOutput, encoding='utf-8')
self.newdf.to_excel(DataFileOutput + '-cipw-mole.xlsx', encoding='utf-8')
self.newdf1.to_excel(DataFileOutput + '-cipw-mass.xlsx', encoding='utf-8')
self.newdf2.to_excel(DataFileOutput + '-cipw-volume.xlsx', encoding='utf-8')
self.newdf3.to_excel(DataFileOutput + '-cipw-index.xlsx', encoding='utf-8') |
GeoPyTool/GeoPyTool | geopytool/NewCIPW.py | CIPW.singleCalc | python | def singleCalc(self,
m={'Al2O3': 13.01, 'Alpha': 0.6, 'Ba': 188.0, 'Be': 0.85, 'CaO': 8.35, 'Ce': 28.2, 'Co': 45.2,
'Cr': 117.0, 'Cs': 0.83, 'Cu': 53.5, 'Dy': 5.58, 'Er': 2.96, 'Eu': 1.79, 'Fe2O3': 14.47,
'FeO': 5.51, 'Ga': 19.4, 'Gd': 5.24, 'Hf': 3.38, 'Ho': 1.1, 'K2O': 0.72, 'LOI': 5.05,
'La': 11.4, 'Label': 'ZhangSH2016', 'Li': 15.0, 'Lu': 0.39, 'Mg#': 41.9, 'MgO': 5.26,
'MnO': 0.21, 'Na2O': 1.88, 'Nb': 12.6, 'Nd': 18.4, 'Ni': 69.4, 'P2O5': 0.23, 'Pb': 3.17,
'Pr': 3.95, 'Rb': 18.4, 'Sc': 37.4, 'SiO2': 48.17, 'Size': 10, 'Sm': 5.08, 'Sr': 357,
'Ta': 0.77, 'Tb': 0.88, 'Th': 1.85, 'TiO2': 2.56, 'Tl': 0.06, 'Tm': 0.44, 'Total': 99.91,
'U': 0.41, 'V': 368.0, 'Y': 29.7, 'Yb': 2.68, 'Zn': 100.0, 'Zr': 130.0, }):
DataResult={}
DataWeight={}
DataVolume={}
DataCalced={}
DataResult.update({'Label': m['Label']})
DataWeight.update({'Label': m['Label']})
DataVolume.update({'Label': m['Label']})
DataCalced.update({'Label': m['Label']})
DataResult.update({'Width': m['Width']})
DataWeight.update({'Width': m['Width']})
DataVolume.update({'Width': m['Width']})
DataCalced.update({'Width': m['Width']})
DataResult.update({'Style': m['Style']})
DataWeight.update({'Style': m['Style']})
DataVolume.update({'Style': m['Style']})
DataCalced.update({'Style': m['Style']})
DataResult.update({'Alpha': m['Alpha']})
DataWeight.update({'Alpha': m['Alpha']})
DataVolume.update({'Alpha': m['Alpha']})
DataCalced.update({'Alpha': m['Alpha']})
DataResult.update({'Size': m['Size']})
DataWeight.update({'Size': m['Size']})
DataVolume.update({'Size': m['Size']})
DataCalced.update({'Size': m['Size']})
DataResult.update({'Color': m['Color']})
DataWeight.update({'Color': m['Color']})
DataVolume.update({'Color': m['Color']})
DataCalced.update({'Color': m['Color']})
DataResult.update({'Marker': m['Marker']})
DataWeight.update({'Marker': m['Marker']})
DataVolume.update({'Marker': m['Marker']})
DataCalced.update({'Marker': m['Marker']})
WholeMass = 0
EachMole = {}
for j in self.Elements:
'''
Get the Whole Mole of the dataset
'''
try:
T_TMP = m[j]
except(KeyError):
T_TMP = 0
if j == 'Sr':
TMP = T_TMP / (87.62 / 103.619 * 10000)
elif j == 'Ba':
TMP = T_TMP / (137.327 / 153.326 * 10000)
elif j == 'Ni':
TMP = T_TMP / (58.6934 / 74.69239999999999 * 10000)
elif j == 'Cr':
TMP = T_TMP / ((2 * 51.9961) / 151.98919999999998 * 10000)
elif j == 'Zr':
# Zr Multi 2 here
TMP = T_TMP / ((2 * 91.224) / 123.22200000000001 * 10000)
else:
TMP = T_TMP
V = TMP
try:
WholeMass += float(V)
except ValueError:
pass
WeightCorrectionFactor = (100 / WholeMass)
for j in self.Elements:
'''
Get the Mole percentage of each element
'''
try:
T_TMP = m[j]
except(KeyError):
T_TMP = 0
if j == 'Sr':
TMP = T_TMP / (87.62 / 103.619 * 10000)
elif j == 'Ba':
TMP = T_TMP / (137.327 / 153.326 * 10000)
elif j == 'Ni':
TMP = T_TMP / (58.6934 / 74.69239999999999 * 10000)
elif j == 'Cr':
TMP = T_TMP / ((2 * 51.9961) / 151.98919999999998 * 10000)
elif j == 'Zr':
# Zr not Multiple by 2 Here
TMP = T_TMP / ((91.224) / 123.22200000000001 * 10000)
else:
TMP = T_TMP
try:
M = TMP / self.BaseMass[j] * WeightCorrectionFactor
except TypeError:
pass
# M= TMP/NewMass(j) * WeightCorrectionFactor
EachMole.update({j: M})
# self.DataMole.append(EachMole)
DataCalculating = EachMole
Fe3 = DataCalculating['Fe2O3']
Fe2 = DataCalculating['FeO']
Mg = DataCalculating['MgO']
Ca = DataCalculating['CaO']
Na = DataCalculating['Na2O']
try:
DataCalced.update({'Fe3+/(Total Fe) in rock (Mole)': 100 * Fe3 * 2 / (Fe3 * 2 + Fe2)})
except(ZeroDivisionError):
DataCalced.update({'Fe3+/(Total Fe) in rock (Mole)': 0})
pass
try:
DataCalced.update({'Mg/(Mg+Total Fe) in rock (Mole)': 100 * Mg / (Mg + Fe3 * 2 + Fe2)})
except(ZeroDivisionError):
DataCalced.update({'Mg/(Mg+Total Fe) in rock (Mole)': 0})
pass
try:
DataCalced.update({'Mg/(Mg+Fe2+) in rock (Mole)': 100 * Mg / (Mg + Fe2)})
except(ZeroDivisionError):
DataCalced.update({'Mg/(Mg+Fe2+) in rock (Mole)': 0})
pass
try:
DataCalced.update({'Ca/(Ca+Na) in rock (Mole)': 100 * Ca / (Ca + Na * 2)})
except(ZeroDivisionError):
DataCalced.update({'Ca/(Ca+Na) in rock (Mole)': 0})
pass
DataCalculating['CaO'] += DataCalculating['Sr']
DataCalculating['Sr'] = 0
DataCalculating['K2O'] += 2 * DataCalculating['Ba']
DataCalculating['Ba'] = 0
try:
if DataCalculating['CaO'] >= 10 / 3 * DataCalculating['P2O5']:
DataCalculating['CaO'] -= 10 / 3 * DataCalculating['P2O5']
else:
DataCalculating['CaO'] = 0
except(ZeroDivisionError):
pass
DataCalculating['P2O5'] = DataCalculating['P2O5'] / 1.5
Apatite = DataCalculating['P2O5']
# IF(S19>=T15,S19-T15,0)
if DataCalculating['F'] >= DataCalculating['P2O5']:
DataCalculating['F'] -= DataCalculating['P2O5']
else:
DataCalculating['F'] = 0
if DataCalculating['F'] >= DataCalculating['P2O5']:
DataCalculating['F'] -= DataCalculating['P2O5']
else:
DataCalculating['F'] = 0
if DataCalculating['Na2O'] >= DataCalculating['Cl']:
DataCalculating['Na2O'] -= DataCalculating['Cl']
else:
DataCalculating['Na2O'] = 0
Halite = DataCalculating['Cl']
# IF(U12>=(U19/2),U12-(U19/2),0)
if DataCalculating['CaO'] >= 0.5 * DataCalculating['F']:
DataCalculating['CaO'] -= 0.5 * DataCalculating['F']
else:
DataCalculating['CaO'] = 0
DataCalculating['F'] *= 0.5
Fluorite = DataCalculating['F']
# =IF(V17>0,IF(V13>=V17,'Thenardite',IF(V13>0,'Both','Anhydrite')),'None')
AorT = 0
if DataCalculating['SO3'] <= 0:
AorT = 'None'
else:
if DataCalculating['Na2O'] >= DataCalculating['SO3']:
AorT = 'Thenardite'
else:
if DataCalculating['Na2O'] > 0:
AorT = 'Both'
else:
AorT = 'Anhydrite'
# =IF(W26='Anhydrite',V17,IF(W26='Both',V12,0))
# =IF(W26='Thenardite',V17,IF(W26='Both',V17-W17,0))
if AorT == 'Anhydrite':
DataCalculating['Sr'] = 0
elif AorT == 'Thenardite':
DataCalculating['Sr'] = DataCalculating['SO3']
DataCalculating['SO3'] = 0
elif AorT == 'Both':
DataCalculating['Sr'] = DataCalculating['SO3'] - DataCalculating['CaO']
DataCalculating['SO3'] = DataCalculating['CaO']
else:
DataCalculating['SO3'] = 0
DataCalculating['Sr'] = 0
DataCalculating['CaO'] -= DataCalculating['SO3']
DataCalculating['Na2O'] -= DataCalculating['Sr']
Anhydrite = DataCalculating['SO3']
Thenardite = DataCalculating['Sr']
Pyrite = 0.5 * DataCalculating['S']
# =IF(W9>=(W18*0.5),W9-(W18*0.5),0)
if DataCalculating['FeO'] >= DataCalculating['S'] * 0.5:
DataCalculating['FeO'] -= DataCalculating['S'] * 0.5
else:
DataCalculating['FeO'] = 0
# =IF(X24>0,IF(X9>=X24,'Chromite',IF(X9>0,'Both','Magnesiochromite')),'None')
if DataCalculating['Cr'] > 0:
if DataCalculating['FeO'] >= DataCalculating['Cr']:
CorM = 'Chromite'
elif DataCalculating['FeO'] > 0:
CorM = 'Both'
else:
CorM = 'Magnesiochromite'
else:
CorM = 'None'
# =IF(Y26='Chromite',X24,IF(Y26='Both',X9,0))
# =IF(Y26='Magnesiochromite',X24,IF(Y26='Both',X24-Y24,0))
if CorM == 'Chromite':
DataCalculating['Cr'] = DataCalculating['Cr']
DataCalculating['Ni'] = 0
elif CorM == 'Magnesiochromite':
DataCalculating['Ni'] = DataCalculating['Cr']
DataCalculating['Cr'] = 0
elif CorM == 'Both':
DataCalculating['Ni'] = DataCalculating['Cr'] - DataCalculating['FeO']
DataCalculating['Cr'] = DataCalculating['FeO']
else:
DataCalculating['Cr'] = 0
DataCalculating['Ni'] = 0
DataCalculating['MgO'] -= DataCalculating['Ni']
Magnesiochromite = DataCalculating['Ni']
Chromite = DataCalculating['Cr']
# =IF(X9>=Y24,X9-Y24,0)
if DataCalculating['FeO'] >= DataCalculating['Cr']:
DataCalculating['FeO'] -= DataCalculating['Cr']
else:
DataCalculating['FeO'] = 0
# =IF(Y6>0,IF(Y9>=Y6,'Ilmenite',IF(Y9>0,'Both','Sphene')),'None')
if DataCalculating['TiO2'] < 0:
IorS = 'None'
else:
if DataCalculating['FeO'] >= DataCalculating['TiO2']:
IorS = 'Ilmenite'
else:
if DataCalculating['FeO'] > 0:
IorS = 'Both'
else:
IorS = 'Sphene'
# =IF(Z26='Ilmenite',Y6,IF(Z26='Both',Y9,0))
# =IF(Z26='Sphene',Y6,IF(Z26='Both',Y6-Z6,0))
if IorS == 'Ilmenite':
DataCalculating['TiO2'] = DataCalculating['TiO2']
DataCalculating['MnO'] = 0
elif IorS == 'Sphene':
DataCalculating['MnO'] = DataCalculating['TiO2']
DataCalculating['TiO2'] = 0
elif IorS == 'Both':
DataCalculating['MnO'] = DataCalculating['TiO2'] - DataCalculating['FeO']
DataCalculating['TiO2'] = DataCalculating['FeO']
else:
DataCalculating['TiO2'] = 0
DataCalculating['MnO'] = 0
DataCalculating['FeO'] -= DataCalculating['TiO2']
Ilmenite = DataCalculating['TiO2']
# =IF(Z16>0,IF(Z12>=Z16,'Calcite',IF(Z12>0,'Both','Na2CO3')),'None')
if DataCalculating['CO2'] <= 0:
CorN = 'None'
else:
if DataCalculating['CaO'] >= DataCalculating['CO2']:
CorN = 'Calcite'
else:
if DataCalculating['CaO'] > 0:
CorN = 'Both'
else:
CorN = 'Na2CO3'
# =IF(AA26='Calcite',Z16,IF(AA26='Both',Z12,0))
# =IF(AA26='Na2CO3',Z16,IF(AA26='Both',Z16-AA16,0))
if CorN == 'None':
DataCalculating['CO2'] = 0
DataCalculating['SO3'] = 0
elif CorN == 'Calcite':
DataCalculating['CO2'] = DataCalculating['CO2']
DataCalculating['SO3'] = 0
elif CorN == 'Na2CO3':
DataCalculating['SO3'] = DataCalculating['SO3']
DataCalculating['CO2'] = 0
elif CorN == 'Both':
DataCalculating['SO3'] = DataCalculating['CO2'] - DataCalculating['CaO']
DataCalculating['CO2'] = DataCalculating['CaO']
DataCalculating['CaO'] -= DataCalculating['CO2']
Calcite = DataCalculating['CO2']
Na2CO3 = DataCalculating['SO3']
# =IF(AA17>Z13,0,Z13-AA17)
if DataCalculating['SO3'] > DataCalculating['Na2O']:
DataCalculating['Na2O'] = 0
else:
DataCalculating['Na2O'] -= DataCalculating['SO3']
DataCalculating['SiO2'] -= DataCalculating['Zr']
Zircon = DataCalculating['Zr']
# =IF(AB14>0,IF(AB7>=AB14,'Orthoclase',IF(AB7>0,'Both','K2SiO3')),'None')
if DataCalculating['K2O'] <= 0:
OorK = 'None'
else:
if DataCalculating['Al2O3'] >= DataCalculating['K2O']:
OorK = 'Orthoclase'
else:
if DataCalculating['Al2O3'] > 0:
OorK = 'Both'
else:
OorK = 'K2SiO3'
# =IF(AC26='Orthoclase',AB14,IF(AC26='Both',AB7,0))
# =IF(AC26='K2SiO3',AB14,IF(AC26='Both',AB14-AB7,0))
if OorK == 'None':
DataCalculating['K2O'] = 0
DataCalculating['P2O5'] = 0
elif OorK == 'Orthoclase':
DataCalculating['K2O'] = DataCalculating['K2O']
DataCalculating['P2O5'] = 0
elif OorK == 'K2SiO3':
DataCalculating['P2O5'] = DataCalculating['K2O']
DataCalculating['K2O'] = 0
elif OorK == 'Both':
DataCalculating['P2O5'] = DataCalculating['K2O'] - DataCalculating['Al2O3']
DataCalculating['K2O'] = DataCalculating['Al2O3']
DataCalculating['Al2O3'] -= DataCalculating['K2O']
# =IF(AC13>0,IF(AC7>=AC13,'Albite',IF(AC7>0,'Both','Na2SiO3')),'None')
if DataCalculating['Na2O'] <= 0:
AorN = 'None'
else:
if DataCalculating['Al2O3'] >= DataCalculating['Na2O']:
AorN = 'Albite'
else:
if DataCalculating['Al2O3'] > 0:
AorN = 'Both'
else:
AorN = 'Na2SiO3'
# =IF(AND(AC7>=AC13,AC7>0),AC7-AC13,0)
if DataCalculating['Al2O3'] >= DataCalculating['Na2O'] and DataCalculating['Al2O3'] > 0:
DataCalculating['Al2O3'] -= DataCalculating['Na2O']
else:
DataCalculating['Al2O3'] = 0
# =IF(AD26='Albite',AC13,IF(AD26='Both',AC7,0))
# =IF(AD26='Na2SiO3',AC13,IF(AD26='Both',AC13-AD13,0))
if AorN == 'Albite':
DataCalculating['Cl'] = 0
elif AorN == 'Both':
DataCalculating['Cl'] = DataCalculating['Na2O'] - DataCalculating['Al2O3']
DataCalculating['Na2O'] = DataCalculating['Al2O3']
elif AorN == 'Na2SiO3':
DataCalculating['Cl'] = DataCalculating['Na2O']
DataCalculating['Na2O'] = 0
elif AorN == 'None':
DataCalculating['Na2O'] = 0
DataCalculating['Cl'] = 0
# =IF(AD7>0,IF(AD12>0,'Anorthite','None'),'None')
'''
Seem like should be =IF(AD7>0,IF(AD12>AD7,'Anorthite','Corundum'),'None')
If Al2O3 is left after alloting orthoclase and albite, then:
Anorthite = Al2O3, CaO = CaO - Al2O3, SiO2 = SiO2 - 2 Al2O3, Al2O3 = 0
If Al2O3 exceeds CaO in the preceding calculation, then:
Anorthite = CaO, Al2O3 = Al2O3 - CaO, SiO2 = SiO2 - 2 CaO
Corundum = Al2O3, CaO =0, Al2O3 = 0
if DataCalculating['Al2O3']<=0:
AorC='None'
else:
if DataCalculating['CaO']>DataCalculating['Al2O3']:
AorC= 'Anorthite'
else:
Aorc='Corundum'
'''
if DataCalculating['Al2O3'] <= 0:
AorC = 'None'
else:
if DataCalculating['CaO'] > 0:
AorC = 'Anorthite'
else:
Aorc = 'None'
# =IF(AE26='Anorthite',IF(AD12>AD7,0,AD7-AD12),AD7)
# =IF(AE26='Anorthite',IF(AD7>AD12,0,AD12-AD7),AD12)
# =IF(AE26='Anorthite',IF(AD7>AD12,AD12,AD7),0)
if AorC == 'Anorthite':
if DataCalculating['Al2O3'] >= DataCalculating['CaO']:
DataCalculating['Sr'] = DataCalculating['CaO']
DataCalculating['Al2O3'] -= DataCalculating['CaO']
DataCalculating['CaO'] = 0
else:
DataCalculating['Sr'] = DataCalculating['Al2O3']
DataCalculating['CaO'] -= DataCalculating['Al2O3']
DataCalculating['Al2O3'] = 0
else:
DataCalculating['Sr'] = 0
Corundum = DataCalculating['Al2O3']
Anorthite = DataCalculating['Sr']
# =IF(AE10>0,IF(AE12>=AE10,'Sphene',IF(AE12>0,'Both','Rutile')),'None')
if DataCalculating['MnO'] <= 0:
SorR = 'None'
else:
if DataCalculating['CaO'] >= DataCalculating['MnO']:
SorR = 'Sphene'
elif DataCalculating['CaO'] > 0:
SorR = 'Both'
else:
SorR = 'Rutile'
# =IF(AF26='Sphene',AE10,IF(AF26='Both',AE12,0))
# =IF(AF26='Rutile',AE10,IF(AF26='Both',AE10-AE12,0))
if SorR == 'Sphene':
DataCalculating['MnO'] = DataCalculating['MnO']
DataCalculating['S'] = 0
elif SorR == 'Rutile':
DataCalculating['S'] = DataCalculating['MnO']
DataCalculating['MnO'] = 0
elif SorR == 'Both':
DataCalculating['S'] = DataCalculating['MnO'] - DataCalculating['CaO']
DataCalculating['MnO'] = DataCalculating['CaO']
elif SorR == 'None':
DataCalculating['MnO'] = 0
DataCalculating['S'] = 0
DataCalculating['CaO'] -= DataCalculating['MnO']
Rutile = DataCalculating['S']
# =IF(AND(AF20>0),IF(AF8>=AF20,'Acmite',IF(AF8>0,'Both','Na2SiO3')),'None')
if DataCalculating['Cl'] <= 0:
ACorN = 'None'
else:
if DataCalculating['Fe2O3'] >= DataCalculating['Cl']:
ACorN = 'Acmite'
else:
if DataCalculating['Fe2O3'] > 0:
ACorN = 'Both'
else:
ACorN = 'Na2SiO3'
# =IF(AG26='Acmite',AF20,IF(AG26='Both',AF8,0))
# =IF(AG26='Na2SiO3',AF20,IF(AG26='Both',AF20-AG19,0))
if ACorN == 'Acmite':
DataCalculating['F'] = DataCalculating['Cl']
DataCalculating['Cl'] = 0
elif ACorN == 'Na2SiO3':
DataCalculating['Cl'] = DataCalculating['Cl']
DataCalculating['F'] = 0
elif ACorN == 'Both':
DataCalculating['F'] = DataCalculating['Fe2O3']
DataCalculating['Cl'] = DataCalculating['Cl'] - DataCalculating['F']
elif ACorN == 'None':
DataCalculating['F'] = 0
DataCalculating['Cl'] = 0
DataCalculating['Fe2O3'] -= DataCalculating['F']
Acmite = DataCalculating['F']
# =IF(AG8>0,IF(AG9>=AG8,'Magnetite',IF(AG9>0,'Both','Hematite')),'None')
if DataCalculating['Fe2O3'] <= 0:
MorH = 'None'
else:
if DataCalculating['FeO'] >= DataCalculating['Fe2O3']:
MorH = 'Magnetite'
else:
if DataCalculating['FeO'] > 0:
MorH = 'Both'
else:
MorH = 'Hematite'
# =IF(AH26='Magnetite',AG8,IF(AH26='Both',AG9,0))
# =IF(AH26='Hematite',AG8,IF(AH26='Both',AG8-AG9,0))
if MorH == 'Magnetite':
DataCalculating['Fe2O3'] = DataCalculating['Fe2O3']
DataCalculating['Ba'] = 0
elif MorH == 'Hematite':
DataCalculating['Fe2O3'] = 0
DataCalculating['Ba'] = DataCalculating['FeO']
elif MorH == 'Both':
DataCalculating['Fe2O3'] = DataCalculating['FeO']
DataCalculating['Ba'] = DataCalculating['Fe2O3'] - DataCalculating['FeO']
elif MorH == 'None':
DataCalculating['Fe2O3'] = 0
DataCalculating['Ba'] == 0
DataCalculating['FeO'] -= DataCalculating['Fe2O3']
Magnetite = DataCalculating['Fe2O3']
Hematite = DataCalculating['Ba']
# =IF(AH11>0,AH11/(AH11+AH9),0)
Fe2 = DataCalculating['FeO']
Mg = DataCalculating['MgO']
if Mg > 0:
DataCalced.update({'Mg/(Mg+Fe2+) in silicates': 100 * Mg / (Mg + Fe2)})
else:
DataCalced.update({'Mg/(Mg+Fe2+) in silicates': 0})
DataCalculating['FeO'] += DataCalculating['MgO']
DataCalculating['MgO'] = 0
# =IF(AI12>0,IF(AI9>=AI12,'Diopside',IF(AI9>0,'Both','Wollastonite')),'None')
if DataCalculating['CaO'] <= 0:
DorW = 'None'
else:
if DataCalculating['FeO'] >= DataCalculating['CaO']:
DorW = 'Diopside'
else:
if DataCalculating['FeO'] > 0:
DorW = 'Both'
else:
DorW = 'Wollastonite'
# =IF(AJ26='Diopside',AI12,IF(AJ26='Both',AI9,0))
# =IF(AJ26='Wollastonite',AI12,IF(AJ26='Both',AI12-AI9,0))
if DorW == 'Diopside':
DataCalculating['CaO'] = DataCalculating['CaO']
DataCalculating['S'] = 0
elif DorW == 'Wollastonite':
DataCalculating['S'] = DataCalculating['CaO']
DataCalculating['CaO'] = 0
elif DorW == 'Both':
DataCalculating['S'] = DataCalculating['CaO'] - DataCalculating['FeO']
DataCalculating['CaO'] = DataCalculating['FeO']
elif DorW == 'None':
DataCalculating['CaO'] = 0
DataCalculating['S'] = 0
DataCalculating['FeO'] -= DataCalculating['CaO']
Diopside = DataCalculating['CaO']
Quartz = DataCalculating['SiO2']
Zircon = DataCalculating['Zr']
K2SiO3 = DataCalculating['P2O5']
Na2SiO3 = DataCalculating['Cl']
Sphene = DataCalculating['MnO']
Hypersthene = DataCalculating['FeO']
Albite = DataCalculating['Na2O']
Orthoclase = DataCalculating['K2O']
Wollastonite = DataCalculating['S']
# =AJ5-(AL6)-(AL7)-(AL8*2)-(AL12)-(AL9)-(AL10*4)-(AL11*2)-(AL13)-(AL14*6)-(AL15*6)-(AL16)
Quartz -= (Zircon +
K2SiO3 +
Anorthite * 2 +
Na2SiO3 +
Acmite * 4 +
Diopside * 2 +
Sphene +
Hypersthene +
Albite * 6 +
Orthoclase * 6 +
Wollastonite)
# =IF(AL5>0,AL5,0)
if Quartz > 0:
Quartz = Quartz
else:
Quartz = 0
# =IF(AL13>0,IF(AL5>=0,'Hypersthene',IF(AL13+(2*AL5)>0,'Both','Olivine')),'None')
if Hypersthene <= 0:
HorO = 'None'
else:
if Quartz >= 0:
HorO = 'Hypersthene'
else:
if Hypersthene + 2 * Quartz > 0:
HorO = 'Both'
else:
HorO = 'Olivine'
# =IF(AN26='Hypersthene',AL13,IF(AN26='Both',AL13+(2*AL5),0))
# =IF(AN26='Olivine',AL13*0.5,IF(AN26='Both',ABS(AL5),0))
Old_Hypersthene = Hypersthene
if HorO == 'Hypersthene':
Hypersthene = Hypersthene
Olivine = 0
elif HorO == 'Both':
Hypersthene = Hypersthene + Quartz * 2
Olivine = abs(Quartz)
elif HorO == 'Olivine':
Olivine = Hypersthene / 2
Hypersthene = 0
elif HorO == 'None':
Hypersthene = 0
Olivine = 0
# =AL5+AL13-(AN13+AN17)
Quartz += Old_Hypersthene - (Hypersthene + Olivine)
# =IF(AL12>0,IF(AN5>=0,'Sphene',IF(AL12+AN5>0,'Both','Perovskite')),'None')
if Sphene <= 0:
SorP = 'None'
else:
if Quartz >= 0:
SorP = 'Sphene'
else:
if Sphene + Quartz > 0:
SorP = 'Both'
else:
SorP = 'Perovskite'
# =IF(AO26='Sphene',AL12,IF(AO26='Both',AL12+AN5,0))
# =IF(AO26='Perovskite',AL12,IF(AO26='Both',AL12-AO12,0))
Old_Sphene = Sphene
if SorP == 'Sphene':
Sphene = Sphene
Perovskite = 0
elif SorP == 'Perovskite':
Perovskite = Sphene
Sphene = 0
elif SorP == 'Both':
Sphene += Quartz
Perovskite = Old_Sphene - Sphene
elif SorP == 'None':
Sphene = 0
Perovskite = 0
Quartz += Old_Sphene - Sphene
# =IF(AL14>0,IF(AO5>=0,'Albite',IF(AL14+(AO5/4)>0,'Both','Nepheline')),'None')
if Albite <= 0:
AlorNe = 'None'
else:
if Quartz >= 0:
AlorNe = 'Albite'
else:
if Albite + (Quartz / 4) > 0:
AlorNe = 'Both'
else:
AlorNe = 'Nepheline'
# =AO5+(6*AL14)-(AP14*6)-(AP19*2)
# =IF(AP26='Albite',AL14,IF(AP26='Both',AL14+(AO5/4),0))
# =IF(AP26='Nepheline',AL14,IF(AP26='Both',AL14-AP14,0))
Old_Albite = Albite
if AlorNe == 'Albite':
Albite = Albite
Nepheline = 0
elif AlorNe == 'Nepheline':
Nepheline = Albite
Albite = 0
elif AlorNe == 'Both':
Albite += Quartz / 4
Nepheline = Old_Albite - Albite
elif AlorNe == 'None':
Nepheline = 0
Albite = 0
Quartz += (6 * Old_Albite) - (Albite * 6) - (Nepheline * 2)
# =IF(AL8=0,0,AL8/(AL8+(AP14*2)))
if Anorthite == 0:
DataCalced.update({'Plagioclase An content': 0})
else:
DataCalced.update({'Plagioclase An content': 100 * Anorthite / (Anorthite + 2 * Albite)})
# =IF(AL15>0,IF(AP5>=0,'Orthoclase',IF(AL15+(AP5/2)>0,'Both','Leucite')),'None')
if Orthoclase <= 0:
OorL = 'None'
else:
if Quartz >= 0:
OorL = 'Orthoclase'
else:
if Orthoclase + Quartz / 2 > 0:
OorL = 'Both'
else:
OorL = 'Leucite'
# =IF(AQ26='Orthoclase',AL15,IF(AQ26='Both',AL15+(AP5/2),0))
# =IF(AQ26='Leucite',AL15,IF(AQ26='Both',AL15-AQ15,0))
Old_Orthoclase = Orthoclase
if OorL == 'Orthoclase':
Orthoclase = Orthoclase
Leucite = 0
elif OorL == 'Leucite':
Leucite = Orthoclase
Orthoclase = 0
elif OorL == 'Both':
Orthoclase += Quartz / 2
Leucite = Old_Orthoclase - Orthoclase
elif OorL == 'None':
Orthoclase = 0
Leucite = 0
# =AP5+(AL15*6)-(AQ15*6)-(AQ20*4)
Quartz += (Old_Orthoclase * 6) - (Orthoclase * 6) - (Leucite * 4)
# =IF(AL16>0,IF(AQ5>=0,'Wollastonite',IF(AL16+(AQ5*2)>0,'Both','Larnite')),'None')
if Wollastonite <= 0:
WorB = 'None'
else:
if Quartz >= 0:
WorB = 'Wollastonite'
else:
if Wollastonite + Quartz / 2 > 0:
WorB = 'Both'
else:
WorB = 'Larnite'
# =IF(AR26='Wollastonite',AL16,IF(AR26='Both',AL16+(2*AQ5),0))
# =IF(AR26='Larnite',AL16/2,IF(AR26='Both',(AL16-AR16)/2,0))
Old_Wollastonite = Wollastonite
if WorB == 'Wollastonite':
Wollastonite = Wollastonite
Larnite = 0
elif WorB == 'Larnite':
Larnite = Wollastonite / 2
Wollastonite = 0
elif WorB == 'Both':
Wollastonite += Quartz * 2
Larnite = (Old_Wollastonite - Wollastonite) / 2
elif WorB == 'None':
Wollastonite = 0
Larnite = 0
# =AQ5+AL16-AR16-AR21
Quartz += Old_Wollastonite - Wollastonite - Larnite
# =IF(AL11>0,IF(AR5>=0,'Diopside',IF(AL11+AR5>0,'Both','LarniteOlivine')),'None')
if Diopside <= 0:
DorL = 'None'
else:
if Quartz >= 0:
DorL = 'Diopside'
else:
if Diopside + Quartz > 0:
DorL = 'Both'
else:
DorL = 'LarniteOlivine'
# =IF(AS26='Diopside',AL11,IF(AS26='Both',AL11+AR5,0))
# =(IF(AS26='LarniteOlivine',AL11/2,IF(AS26='Both',(AL11-AS11)/2,0)))+AN17
# =(IF(AS26='LarniteOlivine',AL11/2,IF(AS26='Both',(AL11-AS11)/2,0)))+AR21
Old_Diopside = Diopside
Old_Larnite = Larnite
Old_Olivine = Olivine
if DorL == 'Diopside':
Diopside = Diopside
elif DorL == 'LarniteOlivine':
Larnite += Diopside / 2
Olivine += Diopside / 2
Diopside = 0
elif DorL == 'Both':
Diopside += Quartz
Larnite += Old_Diopside - Diopside
Olivine += Old_Diopside - Diopside
elif DorL == 'None':
Diopside = 0
# =AR5+(AL11*2)+AN17+AR21-AS21-(AS11*2)-AS17
Quartz += (Old_Diopside * 2) + Old_Olivine + Old_Larnite - Larnite - (Diopside * 2) - Olivine
# =IF(AQ20>0,IF(AS5>=0,'Leucite',IF(AQ20+(AS5/2)>0,'Both','Kalsilite')),'None')
if Leucite <= 0:
LorK = 'None'
else:
if Quartz >= 0:
LorK = 'Leucite'
else:
if Leucite + Quartz / 2 > 0:
LorK = 'Both'
else:
LorK = 'Kalsilite'
# =IF(AT26='Leucite',AQ20,IF(AT26='Both',AQ20+(AS5/2),0))
# =IF(AT26='Kalsilite',AQ20,IF(AT26='Both',AQ20-AT20,0))
Old_Leucite = Leucite
if LorK == 'Leucite':
Leucite = Leucite
Kalsilite = 0
elif LorK == 'Kalsilite':
Kalsilite = Leucite
Leucite = 0
elif LorK == 'Both':
Leucite += Quartz / 2
Kalsilite = Old_Leucite - Leucite
elif LorK == 'None':
Leucite = 0
Kalsilite = 0
# =AS5+(AQ20*4)-(AT20*4)-(AT22*2)
Quartz += Old_Leucite * 4 - Leucite * 4 - Kalsilite * 2
Q = Quartz
A = Orthoclase
P = Anorthite + Albite
F = Nepheline + Leucite + Kalsilite
DataResult.update({'Quartz': Quartz})
DataResult.update({'Zircon': Zircon})
DataResult.update({'K2SiO3': K2SiO3})
DataResult.update({'Anorthite': Anorthite})
DataResult.update({'Na2SiO3': Na2SiO3})
DataResult.update({'Acmite': Acmite})
DataResult.update({'Diopside': Diopside})
DataResult.update({'Sphene': Sphene})
DataResult.update({'Hypersthene': Hypersthene})
DataResult.update({'Albite': Albite})
DataResult.update({'Orthoclase': Orthoclase})
DataResult.update({'Wollastonite': Wollastonite})
DataResult.update({'Olivine': Olivine})
DataResult.update({'Perovskite': Perovskite})
DataResult.update({'Nepheline': Nepheline})
DataResult.update({'Leucite': Leucite})
DataResult.update({'Larnite': Larnite})
DataResult.update({'Kalsilite': Kalsilite})
DataResult.update({'Apatite': Apatite})
DataResult.update({'Halite': Halite})
DataResult.update({'Fluorite': Fluorite})
DataResult.update({'Anhydrite': Anhydrite})
DataResult.update({'Thenardite': Thenardite})
DataResult.update({'Pyrite': Pyrite})
DataResult.update({'Magnesiochromite': Magnesiochromite})
DataResult.update({'Chromite': Chromite})
DataResult.update({'Ilmenite': Ilmenite})
DataResult.update({'Calcite': Calcite})
DataResult.update({'Na2CO3': Na2CO3})
DataResult.update({'Corundum': Corundum})
DataResult.update({'Rutile': Rutile})
DataResult.update({'Magnetite': Magnetite})
DataResult.update({'Hematite': Hematite})
DataResult.update({'Q Mole': Q})
DataResult.update({'A Mole': A})
DataResult.update({'P Mole': P})
DataResult.update({'F Mole': F})
DataWeight.update({'Quartz': Quartz * self.DataBase['Quartz'][0]})
DataWeight.update({'Zircon': Zircon * self.DataBase['Zircon'][0]})
DataWeight.update({'K2SiO3': K2SiO3 * self.DataBase['K2SiO3'][0]})
DataWeight.update({'Anorthite': Anorthite * self.DataBase['Anorthite'][0]})
DataWeight.update({'Na2SiO3': Na2SiO3 * self.DataBase['Na2SiO3'][0]})
DataWeight.update({'Acmite': Acmite * self.DataBase['Acmite'][0]})
DataWeight.update({'Diopside': Diopside * self.DataBase['Diopside'][0]})
DataWeight.update({'Sphene': Sphene * self.DataBase['Sphene'][0]})
DataWeight.update({'Hypersthene': Hypersthene * self.DataBase['Hypersthene'][0]})
DataWeight.update({'Albite': Albite * self.DataBase['Albite'][0]})
DataWeight.update({'Orthoclase': Orthoclase * self.DataBase['Orthoclase'][0]})
DataWeight.update({'Wollastonite': Wollastonite * self.DataBase['Wollastonite'][0]})
DataWeight.update({'Olivine': Olivine * self.DataBase['Olivine'][0]})
DataWeight.update({'Perovskite': Perovskite * self.DataBase['Perovskite'][0]})
DataWeight.update({'Nepheline': Nepheline * self.DataBase['Nepheline'][0]})
DataWeight.update({'Leucite': Leucite * self.DataBase['Leucite'][0]})
DataWeight.update({'Larnite': Larnite * self.DataBase['Larnite'][0]})
DataWeight.update({'Kalsilite': Kalsilite * self.DataBase['Kalsilite'][0]})
DataWeight.update({'Apatite': Apatite * self.DataBase['Apatite'][0]})
DataWeight.update({'Halite': Halite * self.DataBase['Halite'][0]})
DataWeight.update({'Fluorite': Fluorite * self.DataBase['Fluorite'][0]})
DataWeight.update({'Anhydrite': Anhydrite * self.DataBase['Anhydrite'][0]})
DataWeight.update({'Thenardite': Thenardite * self.DataBase['Thenardite'][0]})
DataWeight.update({'Pyrite': Pyrite * self.DataBase['Pyrite'][0]})
DataWeight.update({'Magnesiochromite': Magnesiochromite * self.DataBase['Magnesiochromite'][0]})
DataWeight.update({'Chromite': Chromite * self.DataBase['Chromite'][0]})
DataWeight.update({'Ilmenite': Ilmenite * self.DataBase['Ilmenite'][0]})
DataWeight.update({'Calcite': Calcite * self.DataBase['Calcite'][0]})
DataWeight.update({'Na2CO3': Na2CO3 * self.DataBase['Na2CO3'][0]})
DataWeight.update({'Corundum': Corundum * self.DataBase['Corundum'][0]})
DataWeight.update({'Rutile': Rutile * self.DataBase['Rutile'][0]})
DataWeight.update({'Magnetite': Magnetite * self.DataBase['Magnetite'][0]})
DataWeight.update({'Hematite': Hematite * self.DataBase['Hematite'][0]})
DataWeight.update({'Q Weight': Quartz * self.DataBase['Quartz'][0]})
DataWeight.update({'A Weight': Orthoclase * self.DataBase['Orthoclase'][0]})
DataWeight.update({'P Weight': Anorthite * self.DataBase['Anorthite'][0] + Albite * self.DataBase['Albite'][0]})
DataWeight.update({'F Weight': Nepheline * self.DataBase['Nepheline'][0] + Leucite * self.DataBase['Leucite'][0] + Kalsilite * self.DataBase['Kalsilite'][0]})
WholeVolume = 0
WholeMole = 0
tmpVolume = []
tmpVolume.append(Quartz * self.DataBase['Quartz'][0] / self.DataBase['Quartz'][1])
tmpVolume.append(Zircon * self.DataBase['Zircon'][0] / self.DataBase['Zircon'][1])
tmpVolume.append(K2SiO3 * self.DataBase['K2SiO3'][0] / self.DataBase['K2SiO3'][1])
tmpVolume.append(Anorthite * self.DataBase['Anorthite'][0] / self.DataBase['Anorthite'][1])
tmpVolume.append(Na2SiO3 * self.DataBase['Na2SiO3'][0] / self.DataBase['Na2SiO3'][1])
tmpVolume.append(Acmite * self.DataBase['Acmite'][0] / self.DataBase['Acmite'][1])
tmpVolume.append(Diopside * self.DataBase['Diopside'][0] / self.DataBase['Diopside'][1])
tmpVolume.append(Sphene * self.DataBase['Sphene'][0] / self.DataBase['Sphene'][1])
tmpVolume.append(Hypersthene * self.DataBase['Hypersthene'][0] / self.DataBase['Hypersthene'][1])
tmpVolume.append(Albite * self.DataBase['Albite'][0] / self.DataBase['Albite'][1])
tmpVolume.append(Orthoclase * self.DataBase['Orthoclase'][0] / self.DataBase['Orthoclase'][1])
tmpVolume.append(Wollastonite * self.DataBase['Wollastonite'][0] / self.DataBase['Wollastonite'][1])
tmpVolume.append(Olivine * self.DataBase['Olivine'][0] / self.DataBase['Olivine'][1])
tmpVolume.append(Perovskite * self.DataBase['Perovskite'][0] / self.DataBase['Perovskite'][1])
tmpVolume.append(Nepheline * self.DataBase['Nepheline'][0] / self.DataBase['Nepheline'][1])
tmpVolume.append(Leucite * self.DataBase['Leucite'][0] / self.DataBase['Leucite'][1])
tmpVolume.append(Larnite * self.DataBase['Larnite'][0] / self.DataBase['Larnite'][1])
tmpVolume.append(Kalsilite * self.DataBase['Kalsilite'][0] / self.DataBase['Kalsilite'][1])
tmpVolume.append(Apatite * self.DataBase['Apatite'][0] / self.DataBase['Apatite'][1])
tmpVolume.append(Halite * self.DataBase['Halite'][0] / self.DataBase['Halite'][1])
tmpVolume.append(Fluorite * self.DataBase['Fluorite'][0] / self.DataBase['Fluorite'][1])
tmpVolume.append(Anhydrite * self.DataBase['Anhydrite'][0] / self.DataBase['Anhydrite'][1])
tmpVolume.append(Thenardite * self.DataBase['Thenardite'][0] / self.DataBase['Thenardite'][1])
tmpVolume.append(Pyrite * self.DataBase['Pyrite'][0] / self.DataBase['Pyrite'][1])
tmpVolume.append(Magnesiochromite * self.DataBase['Magnesiochromite'][0] / self.DataBase['Magnesiochromite'][1])
tmpVolume.append(Chromite * self.DataBase['Chromite'][0] / self.DataBase['Chromite'][1])
tmpVolume.append(Ilmenite * self.DataBase['Ilmenite'][0] / self.DataBase['Ilmenite'][1])
tmpVolume.append(Calcite * self.DataBase['Calcite'][0] / self.DataBase['Calcite'][1])
tmpVolume.append(Na2CO3 * self.DataBase['Na2CO3'][0] / self.DataBase['Na2CO3'][1])
tmpVolume.append(Corundum * self.DataBase['Corundum'][0] / self.DataBase['Corundum'][1])
tmpVolume.append(Rutile * self.DataBase['Rutile'][0] / self.DataBase['Rutile'][1])
tmpVolume.append(Magnetite * self.DataBase['Magnetite'][0] / self.DataBase['Magnetite'][1])
tmpVolume.append(Hematite * self.DataBase['Hematite'][0] / self.DataBase['Hematite'][1])
WholeVolume = sum(tmpVolume)
DataVolume.update(
{'Quartz': (Quartz * self.DataBase['Quartz'][0] / self.DataBase['Quartz'][1]) / WholeVolume * 100})
DataVolume.update(
{'Zircon': (Zircon * self.DataBase['Zircon'][0] / self.DataBase['Zircon'][1]) / WholeVolume * 100})
DataVolume.update(
{'K2SiO3': (K2SiO3 * self.DataBase['K2SiO3'][0] / self.DataBase['K2SiO3'][1]) / WholeVolume * 100})
DataVolume.update({'Anorthite': (Anorthite * self.DataBase['Anorthite'][0] / self.DataBase['Anorthite'][
1]) / WholeVolume * 100})
DataVolume.update(
{'Na2SiO3': (Na2SiO3 * self.DataBase['Na2SiO3'][0] / self.DataBase['Na2SiO3'][1]) / WholeVolume * 100})
DataVolume.update(
{'Acmite': (Acmite * self.DataBase['Acmite'][0] / self.DataBase['Acmite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Diopside': (Diopside * self.DataBase['Diopside'][0] / self.DataBase['Diopside'][1]) / WholeVolume * 100})
DataVolume.update(
{'Sphene': (Sphene * self.DataBase['Sphene'][0] / self.DataBase['Sphene'][1]) / WholeVolume * 100})
DataVolume.update({'Hypersthene': (Hypersthene * self.DataBase['Hypersthene'][0] / self.DataBase['Hypersthene'][
1]) / WholeVolume * 100})
DataVolume.update(
{'Albite': (Albite * self.DataBase['Albite'][0] / self.DataBase['Albite'][1]) / WholeVolume * 100})
DataVolume.update({'Orthoclase': (Orthoclase * self.DataBase['Orthoclase'][0] / self.DataBase['Orthoclase'][
1]) / WholeVolume * 100})
DataVolume.update({'Wollastonite': (Wollastonite * self.DataBase['Wollastonite'][0] /
self.DataBase['Wollastonite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Olivine': (Olivine * self.DataBase['Olivine'][0] / self.DataBase['Olivine'][1]) / WholeVolume * 100})
DataVolume.update({'Perovskite': (Perovskite * self.DataBase['Perovskite'][0] / self.DataBase['Perovskite'][
1]) / WholeVolume * 100})
DataVolume.update({'Nepheline': (Nepheline * self.DataBase['Nepheline'][0] / self.DataBase['Nepheline'][
1]) / WholeVolume * 100})
DataVolume.update(
{'Leucite': (Leucite * self.DataBase['Leucite'][0] / self.DataBase['Leucite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Larnite': (Larnite * self.DataBase['Larnite'][0] / self.DataBase['Larnite'][1]) / WholeVolume * 100})
DataVolume.update({'Kalsilite': (Kalsilite * self.DataBase['Kalsilite'][0] / self.DataBase['Kalsilite'][
1]) / WholeVolume * 100})
DataVolume.update(
{'Apatite': (Apatite * self.DataBase['Apatite'][0] / self.DataBase['Apatite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Halite': (Halite * self.DataBase['Halite'][0] / self.DataBase['Halite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Fluorite': (Fluorite * self.DataBase['Fluorite'][0] / self.DataBase['Fluorite'][1]) / WholeVolume * 100})
DataVolume.update({'Anhydrite': (Anhydrite * self.DataBase['Anhydrite'][0] / self.DataBase['Anhydrite'][
1]) / WholeVolume * 100})
DataVolume.update({'Thenardite': (Thenardite * self.DataBase['Thenardite'][0] / self.DataBase['Thenardite'][
1]) / WholeVolume * 100})
DataVolume.update(
{'Pyrite': (Pyrite * self.DataBase['Pyrite'][0] / self.DataBase['Pyrite'][1]) / WholeVolume * 100})
DataVolume.update({'Magnesiochromite': (Magnesiochromite * self.DataBase['Magnesiochromite'][0] /
self.DataBase['Magnesiochromite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Chromite': (Chromite * self.DataBase['Chromite'][0] / self.DataBase['Chromite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Ilmenite': (Ilmenite * self.DataBase['Ilmenite'][0] / self.DataBase['Ilmenite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Calcite': (Calcite * self.DataBase['Calcite'][0] / self.DataBase['Calcite'][1]) / WholeVolume * 100})
DataVolume.update(
{'Na2CO3': (Na2CO3 * self.DataBase['Na2CO3'][0] / self.DataBase['Na2CO3'][1]) / WholeVolume * 100})
DataVolume.update(
{'Corundum': (Corundum * self.DataBase['Corundum'][0] / self.DataBase['Corundum'][1]) / WholeVolume * 100})
DataVolume.update(
{'Rutile': (Rutile * self.DataBase['Rutile'][0] / self.DataBase['Rutile'][1]) / WholeVolume * 100})
DataVolume.update({'Magnetite': (Magnetite * self.DataBase['Magnetite'][0] / self.DataBase['Magnetite'][
1]) / WholeVolume * 100})
DataVolume.update(
{'Hematite': (Hematite * self.DataBase['Hematite'][0] / self.DataBase['Hematite'][1]) / WholeVolume * 100})
DataVolume.update({'Q': DataVolume['Quartz']})
DataVolume.update({'A': DataVolume['Orthoclase']})
DataVolume.update({'P': DataVolume['Anorthite'] + DataVolume['Albite']})
DataVolume.update({'F': DataVolume['Nepheline'] + DataVolume['Leucite'] + DataVolume['Kalsilite']})
DI = 0
# for i in ['Quartz', 'Anorthite', 'Albite', 'Orthoclase', 'Nepheline', 'Leucite', 'Kalsilite']:
# exec('DI+=' + i + '*self.DataBase[\'' + i + '\'][0]')
DI = Quartz + Anorthite + Albite + Orthoclase + Nepheline + Leucite + Kalsilite
DiWeight=0
DiVolume=0
DiWeight = DataWeight['Quartz']+DataWeight['Anorthite']+DataWeight['Albite']+DataWeight['Orthoclase']+DataWeight['Nepheline']+DataWeight['Leucite']+DataWeight['Kalsilite']
DiVolume = DataVolume['Quartz']+DataVolume['Anorthite']+DataVolume['Albite']+DataVolume['Orthoclase']+DataVolume['Nepheline']+DataVolume['Leucite']+DataVolume['Kalsilite']
# print('\n\n DI is\n',DI,'\n\n')
DataCalced.update({'Differentiation Index Weight': DiWeight})
DataCalced.update({'Differentiation Index Volume': DiVolume})
return (DataResult, DataWeight, DataVolume, DataCalced) | Seem like should be =IF(AD7>0,IF(AD12>AD7,'Anorthite','Corundum'),'None')
If Al2O3 is left after alloting orthoclase and albite, then:
Anorthite = Al2O3, CaO = CaO - Al2O3, SiO2 = SiO2 - 2 Al2O3, Al2O3 = 0
If Al2O3 exceeds CaO in the preceding calculation, then:
Anorthite = CaO, Al2O3 = Al2O3 - CaO, SiO2 = SiO2 - 2 CaO
Corundum = Al2O3, CaO =0, Al2O3 = 0
if DataCalculating['Al2O3']<=0:
AorC='None'
else:
if DataCalculating['CaO']>DataCalculating['Al2O3']:
AorC= 'Anorthite'
else:
Aorc='Corundum' | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/NewCIPW.py#L307-L1492 | null | class CIPW(AppForm):
addon = 'Name Author DataType Label Marker Color Size Alpha Style Width TOTAL total LOI loi'
Minerals = ['Quartz',
'Zircon',
'K2SiO3',
'Anorthite',
'Na2SiO3',
'Acmite',
'Diopside',
'Sphene',
'Hypersthene',
'Albite',
'Orthoclase',
'Wollastonite',
'Olivine',
'Perovskite',
'Nepheline',
'Leucite',
'Larnite',
'Kalsilite',
'Apatite',
'Halite',
'Fluorite',
'Anhydrite',
'Thenardite',
'Pyrite',
'Magnesiochromite',
'Chromite',
'Ilmenite',
'Calcite',
'Na2CO3',
'Corundum',
'Rutile',
'Magnetite',
'Hematite',
'Q',
'A',
'P',
'F', ]
Calced = ['Fe3+/(Total Fe) in rock',
'Mg/(Mg+Total Fe) in rock',
'Mg/(Mg+Fe2+) in rock',
'Mg/(Mg+Fe2+) in silicates',
'Ca/(Ca+Na) in rock',
'Plagioclase An content',
'Differentiation Index']
DataBase = {'Quartz': [60.0843, 2.65],
'Zircon': [183.3031, 4.56],
'K2SiO3': [154.2803, 2.5],
'Anorthite': [278.2093, 2.76],
'Na2SiO3': [122.0632, 2.4],
'Acmite': [462.0083, 3.6],
'Diopside': [229.0691997, 3.354922069],
'Sphene': [196.0625, 3.5],
'Hypersthene': [112.9054997, 3.507622212],
'Albite': [524.446, 2.62],
'Orthoclase': [556.6631, 2.56],
'Wollastonite': [116.1637, 2.86],
'Olivine': [165.7266995, 3.68429065],
'Perovskite': [135.9782, 4],
'Nepheline': [284.1088, 2.56],
'Leucite': [436.4945, 2.49],
'Larnite': [172.2431, 3.27],
'Kalsilite': [316.3259, 2.6],
'Apatite': [493.3138, 3.2],
'Halite': [66.44245, 2.17],
'Fluorite': [94.0762, 3.18],
'Anhydrite': [136.1376, 2.96],
'Thenardite': [142.0371, 2.68],
'Pyrite': [135.9664, 4.99],
'Magnesiochromite': [192.2946, 4.43],
'Chromite': [223.8366, 5.09],
'Ilmenite': [151.7452, 4.75],
'Calcite': [100.0892, 2.71],
'Na2CO3': [105.9887, 2.53],
'Corundum': [101.9613, 3.98],
'Rutile': [79.8988, 4.2],
'Magnetite': [231.5386, 5.2],
'Hematite': [159.6922, 5.25]}
BaseMass = {'SiO2': 60.083,
'TiO2': 79.865,
'Al2O3': 101.960077,
'Fe2O3': 159.687,
'FeO': 71.844,
'MnO': 70.937044,
'MgO': 40.304,
'CaO': 56.077000000000005,
'Na2O': 61.978538560000004,
'K2O': 94.1956,
'P2O5': 141.942523996,
'CO2': 44.009,
'SO3': 80.057,
'S': 32.06,
'F': 18.998403163,
'Cl': 35.45,
'Sr': 87.62,
'Ba': 137.327,
'Ni': 58.6934,
'Cr': 51.9961,
'Zr': 91.224}
Elements = ['SiO2',
'TiO2',
'Al2O3',
'Fe2O3',
'FeO',
'MnO',
'MgO',
'CaO',
'Na2O',
'K2O',
'P2O5',
'CO2',
'SO3',
'S',
'F',
'Cl',
'Sr',
'Ba',
'Ni',
'Cr',
'Zr']
DataWeight = {}
DataVolume = {}
DataCalced = {}
ResultMole =[]
ResultWeight=[]
ResultVolume=[]
ResultCalced=[]
FinalResultMole = pd.DataFrame()
FinalResultWeight = pd.DataFrame()
FinalResultVolume = pd.DataFrame()
FinalResultCalced = pd.DataFrame()
raw = pd.DataFrame()
DictList=[]
def __init__(self, parent=None, df=pd.DataFrame()):
QMainWindow.__init__(self, parent)
self.setWindowTitle('CIPW Norm Result')
self._df = df
#self.raw = df
self.raw = self.CleanDataFile(self._df)
if (len(df) > 0):
self._changed = True
# print('DataFrame recieved')
self.create_main_frame()
self.create_status_bar()
def create_main_frame(self):
self.resize(800, 600)
self.main_frame = QWidget()
self.dpi = 128
self.save_button = QPushButton('&Save Result')
self.save_button.clicked.connect(self.saveResult)
self.qapf_button = QPushButton('&QAPF')
self.qapf_button.clicked.connect(self.QAPF)
'''
self.tableView = CustomQTableView(self.main_frame)
self.tableView.setObjectName('tableView')
self.tableView.setSortingEnabled(True)
'''
self.tableViewMole = CustomQTableView(self.main_frame)
self.tableViewMole.setObjectName('tableViewMole')
self.tableViewMole.setSortingEnabled(True)
self.tableViewWeight = CustomQTableView(self.main_frame)
self.tableViewWeight.setObjectName('tableViewWeight')
self.tableViewWeight.setSortingEnabled(True)
self.tableViewVolume = CustomQTableView(self.main_frame)
self.tableViewVolume.setObjectName('tableViewVolume')
self.tableViewVolume.setSortingEnabled(True)
self.tableViewCalced = CustomQTableView(self.main_frame)
self.tableViewCalced.setObjectName('tableViewCalced')
self.tableViewCalced.setSortingEnabled(True)
#
# Layout with box sizers
#
self.hbox = QHBoxLayout()
for w in [self.qapf_button]:
self.hbox.addWidget(w)
self.hbox.setAlignment(w, Qt.AlignVCenter)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.tableViewMole)
self.vbox.addWidget(self.tableViewWeight)
self.vbox.addWidget(self.tableViewVolume)
self.vbox.addWidget(self.tableViewCalced)
self.vbox.addWidget(self.save_button)
self.vbox.addLayout(self.hbox)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame)
def CIPW(self):
self.ResultMole=[]
self.ResultWeight=[]
self.ResultVolume=[]
self.ResultCalced=[]
self.DictList=[]
for i in range(len(self.raw)):
tmpDict={}
for j in self.raw.columns:
tmpDict.update({j:self.raw.at[i,j]})
TmpResult = self.singleCalc(m=tmpDict)
TmpResultMole = pd.DataFrame(TmpResult[0],index=[i])
TmpResultWeight = pd.DataFrame(TmpResult[1],index=[i])
TmpResultVolume = pd.DataFrame(TmpResult[2],index=[i])
TmpResultCalced = pd.DataFrame(TmpResult[3],index=[i])
self.ResultMole.append(TmpResultMole)
self.ResultWeight.append(TmpResultWeight)
self.ResultVolume.append(TmpResultVolume)
self.ResultCalced.append(TmpResultCalced)
self.DictList.append(tmpDict)
self.useddf = pd.concat(self.ResultVolume)
self.FinalResultMole = self.ReduceSize(pd.concat(self.ResultMole).set_index('Label'))
self.FinalResultWeight = self.ReduceSize(pd.concat(self.ResultWeight).set_index('Label'))
self.FinalResultVolume = self.ReduceSize(pd.concat(self.ResultVolume).set_index('Label'))
self.FinalResultCalced = self.ReduceSize(pd.concat(self.ResultCalced).set_index('Label'))
self.FinalResultMole = self.FinalResultMole.fillna(0)
self.FinalResultWeight = self.FinalResultWeight.fillna(0)
self.FinalResultVolume = self.FinalResultVolume.fillna(0)
self.FinalResultCalced = self.FinalResultCalced.fillna(0)
self.FinalResultMole = self.FinalResultMole.loc[:, (self.FinalResultMole != 0).any(axis=0)]
self.FinalResultWeight = self.FinalResultWeight.loc[:, (self.FinalResultWeight != 0).any(axis=0)]
self.FinalResultVolume = self.FinalResultVolume.loc[:, (self.FinalResultVolume != 0).any(axis=0)]
self.FinalResultCalced = self.FinalResultCalced.loc[:, (self.FinalResultCalced != 0).any(axis=0)]
self.newdf = self.FinalResultMole
self.newdf1 = self.FinalResultWeight
self.newdf2 = self.FinalResultVolume
self.newdf3 = self.FinalResultCalced
print(self.FinalResultVolume)
#self.WholeResult = self.WholeResult.T.groupby(level=0).first().T
#self.model = PandasModel(self.WholeResult)
#self.model = PandasModel(self.FinalResultVolume)
#self.model = PandasModel(self.useddf)
self.modelMole = PandasModel(self.FinalResultMole)
self.modelWeight= PandasModel(self.FinalResultWeight)
self.modelVolume = PandasModel(self.FinalResultVolume)
self.modelCalced = PandasModel(self.FinalResultCalced)
#self.tableView.setModel(self.model)
self.tableViewMole.setModel(self.modelMole)
self.tableViewWeight.setModel(self.modelWeight)
self.tableViewVolume.setModel(self.modelVolume)
self.tableViewCalced.setModel(self.modelCalced)
self.WholeResult = pd.concat([self.FinalResultMole,self.FinalResultWeight,self.FinalResultVolume,self.FinalResultCalced], axis=1)
self.OutPutData = self.WholeResult
def WriteData(self, target='DataResult'):
DataToWrite = []
TMP_DataToWrite = ['Label']
TMP_DataToWrite = ['Label', 'Marker', 'Color', 'Size', 'Alpha', 'Style', 'Width']
for j in self.Minerals:
TMP_DataToWrite.append(str(j))
DataToWrite.append(TMP_DataToWrite)
for i in range(len(self.DataMole)):
TMP_DataToWrite = []
k = self.raw.at[i, 'Label']
TMP_DataToWrite = [self.raw.at[i, 'Label'], self.raw.at[i, 'Marker'], self.raw.at[i, 'Color'],
self.raw.at[i, 'Size'], self.raw.at[i, 'Alpha'], self.raw.at[i, 'Style'],
self.raw.at[i, 'Width']]
for j in self.Minerals:
command = 'TMP_DataToWrite.append((self.' + target + '[k][j]))'
exec('#print((self.' + target + '[k][j]))')
try:
exec(command)
except(KeyError):
pass
DataToWrite.append(TMP_DataToWrite)
return (DataToWrite)
def WriteCalced(self, target='DataCalced'):
DataToWrite = []
TMP_DataToWrite = ['Label']
TMP_DataToWrite = ['Label', 'Marker', 'Color', 'Size', 'Alpha', 'Style', 'Width']
for j in self.Calced:
TMP_DataToWrite.append(str(j))
DataToWrite.append(TMP_DataToWrite)
for i in range(len(self.DataMole)):
TMP_DataToWrite = []
k = self.raw.at[i, 'Label']
TMP_DataToWrite = [self.raw.at[i, 'Label'], self.raw.at[i, 'Marker'], self.raw.at[i, 'Color'],
self.raw.at[i, 'Size'], self.raw.at[i, 'Alpha'], self.raw.at[i, 'Style'],
self.raw.at[i, 'Width']]
for j in self.Calced:
command = 'TMP_DataToWrite.append((self.' + target + '[k][j]))'
try:
exec('#print((self.' + target + '[k][j]))')
exec(command)
except(KeyError):
pass
DataToWrite.append(TMP_DataToWrite)
# print('\n',DataToWrite,'\n')
return (DataToWrite)
def ReduceSize(self,df=pd.DataFrame):
m = ['Width', 'Style', 'Alpha', 'Size', 'Color', 'Marker', 'Author']
for i in m:
if i in df.columns.values:
df = df.drop(i, 1)
df = df.loc[:, (df != 0).any(axis=0)]
return(df)
def GetSym(self,df=pd.DataFrame):
m = ['Label', 'Width', 'Style', 'Alpha', 'Size', 'Color', 'Marker', 'Author']
for i in df.columns.values:
if i not in m:
df = df.drop(i, 1)
df = df.loc[:, (df != 0).any(axis=0)]
return(df)
def DropUseless(self,df= pd.DataFrame(),droplist = ['Q (Mole)', 'A (Mole)', 'P (Mole)', 'F (Mole)',
'Q (Mass)', 'A (Mass)', 'P (Mass)', 'F (Mass)']):
for t in droplist:
if t in df.columns.values:
df = df.drop(t, 1)
return(df)
def QAPF(self):
self.qapfpop = QAPF(df=self.useddf)
try:
self.qapfpop.QAPF()
except(TypeError):
pass
self.qapfpop.show()
def QAPFsilent(self):
self.qapfpop = QAPF(df=self.useddf)
try:
self.qapfpop.QAPF()
except(TypeError):
pass
self.OutPutFig = self.qapfpop.OutPutFig
def saveResult(self):
DataFileOutput, ok2 = QFileDialog.getSaveFileName(self,
'文件保存',
'C:/',
'Excel Files (*.xlsx);;CSV Files (*.csv)') # 数据文件保存输出
if (DataFileOutput != ''):
if ('csv' in DataFileOutput):
DataFileOutput=DataFileOutput[0:-4]
#self.newdf.to_csv(DataFileOutput, sep=',', encoding='utf-8')
self.newdf.to_csv(DataFileOutput + '-cipw-mole.csv', sep=',', encoding='utf-8')
self.newdf1.to_csv(DataFileOutput + '-cipw-mass.csv', sep=',', encoding='utf-8')
self.newdf2.to_csv(DataFileOutput + '-cipw-volume.csv', sep=',', encoding='utf-8')
self.newdf3.to_csv(DataFileOutput + '-cipw-index.csv', sep=',', encoding='utf-8')
elif ('xlsx' in DataFileOutput):
DataFileOutput = DataFileOutput[0:-5]
#self.newdf.to_excel(DataFileOutput, encoding='utf-8')
self.newdf.to_excel(DataFileOutput + '-cipw-mole.xlsx', encoding='utf-8')
self.newdf1.to_excel(DataFileOutput + '-cipw-mass.xlsx', encoding='utf-8')
self.newdf2.to_excel(DataFileOutput + '-cipw-volume.xlsx', encoding='utf-8')
self.newdf3.to_excel(DataFileOutput + '-cipw-index.xlsx', encoding='utf-8') |
GeoPyTool/GeoPyTool | geopytool/__init__.py | Ui_MainWindow.retranslateUi | python | def retranslateUi(self):
_translate = QtCore.QCoreApplication.translate
self.talk= _translate('MainWindow','You are using GeoPyTool ') + version +'\n'+ _translate('MainWindow','released on ') + date + '\n'
self.menuFile.setTitle(_translate('MainWindow', u'Data File'))
self.menuGeoChem.setTitle(_translate('MainWindow', u'Geochemistry'))
self.menuGeoCalc.setTitle(_translate('MainWindow',u'Calculation'))
self.menuStructure.setTitle(_translate('MainWindow', u'Structure'))
self.menuSedimentary.setTitle(_translate('MainWindow', u'Sedimentary'))
self.menuAdditional.setTitle(_translate('MainWindow', u'Additional Functions'))
self.menuHelp.setTitle(_translate('MainWindow', u'Help'))
self.menuLanguage.setTitle(_translate('MainWindow', u'Language'))
self.actionCombine.setText(_translate('MainWindow', u'Combine'))
self.actionCombine_transverse.setText(_translate('MainWindow', u'Combine_transverse'))
self.actionFlatten.setText(_translate('MainWindow',u'Flatten'))
self.actionTrans.setText(_translate('MainWindow',u'Trans'))
self.actionReFormat.setText(_translate('MainWindow',u'ReFormat'))
self.actionOpen.setText(_translate('MainWindow', u'Open Data'))
self.actionClose.setText(_translate('MainWindow', u'Close Data'))
self.actionSet.setText(_translate('MainWindow', u'Set Format'))
self.actionSave.setText(_translate('MainWindow', u'Save Data'))
self.actionQuit.setText(_translate('MainWindow', u'Quit App'))
self.actionRemoveLOI.setText('1-0 '+_translate('MainWindow',u'Remove LOI'))
self.actionAuto.setText('1-1 '+_translate('MainWindow', u'Auto'))
self.actionTAS.setText('1-2 '+ _translate('MainWindow',u'TAS'))
self.actionTrace.setText('1-3 '+_translate('MainWindow',u'Trace'))
self.actionRee.setText('1-4 '+_translate('MainWindow',u'REE'))
self.actionPearce.setText('1-5 '+_translate('MainWindow',u'Pearce'))
self.actionHarker.setText('1-6 '+_translate('MainWindow',u'Harker'))
self.actionCIPW.setText('1-7 '+_translate('MainWindow',u'CIPW'))
self.actionQAPF.setText('1-8 '+_translate('MainWindow',u'QAPF'))
self.actionSaccani.setText('1-9 '+_translate('MainWindow',u'Saccani Plot'))
self.actionK2OSiO2.setText('1-10 '+_translate('MainWindow',u'K2O-SiO2'))
self.actionRaman.setText('1-11 '+_translate('MainWindow',u'Raman Strength'))
self.actionFluidInclusion.setText('1-12 '+_translate('MainWindow',u'Fluid Inclusion'))
self.actionHarkerOld.setText('1-14 '+_translate('MainWindow',u'Harker Classical'))
self.actionTraceNew.setText('1-15 '+_translate('MainWindow',u'TraceNew'))
self.actionStereo.setText('2-1 '+_translate('MainWindow',u'Stereo'))
self.actionRose.setText('2-2 '+_translate('MainWindow',u'Rose'))
self.actionQFL.setText('3-1 '+_translate('MainWindow',u'QFL'))
self.actionQmFLt.setText('3-2 '+_translate('MainWindow',u'QmFLt'))
self.actionClastic.setText('3-3 '+_translate('MainWindow',u'Clastic'))
self.actionCIA.setText('3-4 '+ _translate('MainWindow',u'CIA and ICV'))
self.actionZirconCe.setText('4-1 '+ _translate('MainWindow',u'ZirconCe'))
self.actionZirconCeOld.setText('4-2 '+ _translate('MainWindow', u'ZirconCeOld'))
self.actionZirconTiTemp.setText('4-3 '+ _translate('MainWindow',u'ZirconTiTemp'))
self.actionRutileZrTemp.setText('4-4 '+_translate('MainWindow',u'RutileZrTemp'))
self.actionRbSrIsoTope.setText('4-5 '+_translate('MainWindow',u'Rb-Sr IsoTope'))
self.actionSmNdIsoTope.setText('4-6 '+_translate('MainWindow',u'Sm-Nd IsoTope'))
#self.actionKArIsoTope.setText(_translate('MainWindow',u'K-Ar IsoTope'))
self.actionXY.setText('5-1 '+_translate('MainWindow',u'X-Y plot'))
self.actionXYZ.setText('5-2 '+_translate('MainWindow',u'X-Y-Z plot'))
self.actionCluster.setText('5-3 '+_translate('MainWindow',u'Cluster'))
self.actionMultiDimension.setText('5-4 '+_translate('MainWindow',u'MultiDimension'))
self.actionFA.setText('5-5 '+_translate('MainWindow',u'FA'))
self.actionPCA.setText('5-6 '+_translate('MainWindow',u'PCA'))
self.actionDist.setText('5-7 '+_translate('MainWindow',u'Distance'))
self.actionStatistics.setText('5-8 '+_translate('MainWindow',u'Statistics'))
self.actionThreeD.setText('5-9 '+_translate('MainWindow',u'ThreeD'))
self.actionTwoD.setText('5-10 '+_translate('MainWindow',u'TwoD'))
self.actionTwoD_Grey.setText('5-11 '+_translate('MainWindow',u'TwoD Grey'))
self.actionMyHist.setText('5-12 '+_translate('MainWindow',u'Histogram + KDE Curve'))
self.actionVersionCheck.setText(_translate('MainWindow', u'Check Update'))
self.actionWeb.setText(_translate('MainWindow', u'English Forum'))
self.actionGoGithub.setText(_translate('MainWindow', u'Github'))
'''
self.actionCnS.setText(_translate('MainWindow',u'Simplified Chinese'))
self.actionCnT.setText(_translate('MainWindow', u'Traditional Chinese'))
self.actionEn.setText(_translate('MainWindow',u'English'))
'''
self.actionCnS.setText(u'简体中文')
self.actionCnT.setText(u'繁體中文')
self.actionEn.setText(u'English')
self.actionLoadLanguage.setText(_translate('MainWindow',u'Load Language')) | self.actionCnS.setText(_translate('MainWindow',u'Simplified Chinese'))
self.actionCnT.setText(_translate('MainWindow', u'Traditional Chinese'))
self.actionEn.setText(_translate('MainWindow',u'English')) | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/__init__.py#L580-L675 | null | class Ui_MainWindow(QtWidgets.QMainWindow):
raw = pd.DataFrame(index=[], columns=[]) # raw is initialized as a blank DataFrame
Standard = {}# Standard is initialized as a blank Dict
Language = ''
app = QtWidgets.QApplication(sys.argv)
myStyle = MyProxyStyle('Fusion') # The proxy style should be based on an existing style,
# like 'Windows', 'Motif', 'Plastique', 'Fusion', ...
app.setStyle(myStyle)
trans = QtCore.QTranslator()
talk=''
targetversion = '0'
DataLocation =''
ChemResult=pd.DataFrame()
AutoResult=pd.DataFrame()
TotalResult=[]
def __init__(self):
super(Ui_MainWindow, self).__init__()
self.setObjectName('MainWindow')
self.resize(800, 600)
self.setAcceptDrops(True)
_translate = QtCore.QCoreApplication.translate
self.setWindowTitle(_translate('MainWindow', u'GeoPyTool'))
self.setWindowIcon(QIcon(LocationOfMySelf+'/geopytool.png'))
self.talk= _translate('MainWindow','You are using GeoPyTool ') + version +'\n'+ _translate('MainWindow','released on ') + date
self.model = PandasModel(self.raw)
self.main_widget = QWidget(self)
self.tableView = CustomQTableView(self.main_widget)
self.tableView.setObjectName('tableView')
self.tableView.setSortingEnabled(True)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.tableView)
self.main_widget.setLayout(self.vbox)
self.setCentralWidget(self.main_widget)
self.menubar = QtWidgets.QMenuBar(self)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1000, 22))
self.menubar.setNativeMenuBar(False)
self.menubar.setObjectName('menubar')
self.menuFile = QtWidgets.QMenu(self.menubar)
self.menuFile.setObjectName('menuFile')
self.menuGeoChem = QtWidgets.QMenu(self.menubar)
self.menuGeoChem.setObjectName('menuGeoChem')
self.menuStructure = QtWidgets.QMenu(self.menubar)
self.menuStructure.setObjectName('menuStructure')
self.menuSedimentary = QtWidgets.QMenu(self.menubar)
self.menuSedimentary.setObjectName('menuSedimentary')
self.menuGeoCalc = QtWidgets.QMenu(self.menubar)
self.menuGeoCalc.setObjectName('menuGeoCalc')
self.menuAdditional = QtWidgets.QMenu(self.menubar)
self.menuAdditional.setObjectName('menuAdditional')
self.menuHelp = QtWidgets.QMenu(self.menubar)
self.menuHelp.setObjectName('menuHelp')
self.menuLanguage = QtWidgets.QMenu(self.menubar)
self.menuLanguage.setObjectName('menuLanguage')
self.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(self)
self.statusbar.setObjectName('statusbar')
self.setStatusBar(self.statusbar)
self.actionOpen = QtWidgets.QAction(QIcon(LocationOfMySelf+'/open.png'), u'Open',self)
self.actionOpen.setObjectName('actionOpen')
self.actionOpen.setShortcut('Ctrl+O')
self.actionClose = QtWidgets.QAction(QIcon(LocationOfMySelf+'/close.png'), u'Close',self)
self.actionClose.setObjectName('actionClose')
self.actionClose.setShortcut('Ctrl+N')
self.actionSet = QtWidgets.QAction(QIcon(LocationOfMySelf + '/set.png'), u'Set', self)
self.actionSet.setObjectName('actionSet')
self.actionSet.setShortcut('Ctrl+F')
self.actionSave = QtWidgets.QAction(QIcon(LocationOfMySelf+'/save.png'), u'Save',self)
self.actionSave.setObjectName('actionSave')
self.actionSave.setShortcut('Ctrl+S')
self.actionCombine = QtWidgets.QAction(QIcon(LocationOfMySelf+'/combine.png'),u'Combine',self)
self.actionCombine.setObjectName('actionCombine')
self.actionCombine.setShortcut('Alt+C')
self.actionCombine_transverse = QtWidgets.QAction(QIcon(LocationOfMySelf+'/combine.png'),u'Combine_transverse',self)
self.actionCombine_transverse.setObjectName('actionCombine_transverse')
self.actionCombine_transverse.setShortcut('Alt+T')
self.actionFlatten = QtWidgets.QAction(QIcon(LocationOfMySelf+'/flatten.png'),u'Flatten',self)
self.actionFlatten.setObjectName('actionFlatten')
self.actionFlatten.setShortcut('Alt+F')
self.actionTrans = QtWidgets.QAction(QIcon(LocationOfMySelf+'/trans.png'),u'Trans',self)
self.actionTrans.setObjectName('actionTrans')
self.actionTrans.setShortcut('Ctrl+T')
self.actionReFormat = QtWidgets.QAction(QIcon(LocationOfMySelf+'/trans.png'),u'ReFormat',self)
self.actionReFormat.setObjectName('actionReFormat')
self.actionReFormat.setShortcut('Alt+R')
self.actionQuit = QtWidgets.QAction(QIcon(LocationOfMySelf+'/quit.png'), u'Quit',self)
self.actionQuit.setObjectName('actionQuit')
self.actionQuit.setShortcut('Ctrl+Q')
self.actionWeb = QtWidgets.QAction(QIcon(LocationOfMySelf+'/forum.png'), u'English Forum',self)
self.actionWeb.setObjectName('actionWeb')
self.actionGoGithub = QtWidgets.QAction(QIcon(LocationOfMySelf+'/github.png'), u'GitHub',self)
self.actionGoGithub.setObjectName('actionGoGithub')
self.actionVersionCheck = QtWidgets.QAction(QIcon(LocationOfMySelf+'/update.png'), u'Version',self)
self.actionVersionCheck.setObjectName('actionVersionCheck')
self.actionCnS = QtWidgets.QAction(QIcon(LocationOfMySelf+'/cns.png'), u'Simplified Chinese',self)
self.actionCnS.setObjectName('actionCnS')
self.actionCnT = QtWidgets.QAction(QIcon(LocationOfMySelf+'/cnt.png'), u'Traditional Chinese',self)
self.actionCnT.setObjectName('actionCnT')
self.actionEn = QtWidgets.QAction(QIcon(LocationOfMySelf+'/en.png'), u'English',self)
self.actionEn.setObjectName('actionEn')
self.actionLoadLanguage = QtWidgets.QAction(QIcon(LocationOfMySelf+'/lang.png'), u'Load Language',self)
self.actionLoadLanguage.setObjectName('actionLoadLanguage')
self.actionTAS = QtWidgets.QAction(QIcon(LocationOfMySelf+'/xy.png'), u'TAS',self)
self.actionTAS.setObjectName('actionTAS')
self.actionTrace = QtWidgets.QAction(QIcon(LocationOfMySelf+'/spider2.png'), u'Trace',self)
self.actionTrace.setObjectName('actionTrace')
self.actionTraceNew = QtWidgets.QAction(QIcon(LocationOfMySelf+'/spider2.png'), u'TraceNew',self)
self.actionTraceNew.setObjectName('actionTraceNew')
self.actionRee = QtWidgets.QAction(QIcon(LocationOfMySelf+'/spider2.png'), u'Ree',self)
self.actionRee.setObjectName('actionRee')
self.actionPearce = QtWidgets.QAction(QIcon(LocationOfMySelf+'/spider.png'),u'Pearce',self)
self.actionPearce.setObjectName('actionPearce')
self.actionHarker = QtWidgets.QAction(QIcon(LocationOfMySelf+'/spider.png'),u'Harker',self)
self.actionHarker.setObjectName('actionHarker')
self.actionHarkerOld = QtWidgets.QAction(QIcon(LocationOfMySelf+'/spider.png'),u'HarkerOld',self)
self.actionHarkerOld.setObjectName('actionHarkerOld')
self.actionRemoveLOI= QtWidgets.QAction(QIcon(LocationOfMySelf+'/fire.png'),u'RemoveLOI',self)
self.actionRemoveLOI.setObjectName('actionRemoveLOI')
self.actionK2OSiO2 = QtWidgets.QAction(QIcon(LocationOfMySelf+'/xy.png'), u'K2OSiO2',self)
self.actionK2OSiO2.setObjectName('actionK2OSiO2')
self.actionStereo = QtWidgets.QAction(QIcon(LocationOfMySelf+'/structure.png'),u'Stereo',self)
self.actionStereo.setObjectName('actionStereo')
self.actionRose = QtWidgets.QAction(QIcon(LocationOfMySelf+'/rose.png'),u'Rose',self)
self.actionRose.setObjectName('actionRose')
self.actionQFL = QtWidgets.QAction(QIcon(LocationOfMySelf+'/triangular.png'),u'QFL',self)
self.actionQFL.setObjectName('actionQFL')
self.actionQmFLt = QtWidgets.QAction(QIcon(LocationOfMySelf+'/triangular.png'),u'QmFLt',self)
self.actionQmFLt.setObjectName('actionQmFLt')
self.actionCIPW = QtWidgets.QAction(QIcon(LocationOfMySelf+'/calc.png'),u'CIPW',self)
self.actionCIPW.setObjectName('actionCIPW')
self.actionZirconCe = QtWidgets.QAction(QIcon(LocationOfMySelf+'/calc.png'),u'ZirconCe',self)
self.actionZirconCe.setObjectName('actionZirconCe')
self.actionZirconCeOld = QtWidgets.QAction(QIcon(LocationOfMySelf+'/calc.png'),u'ZirconCeOld',self)
self.actionZirconCeOld.setObjectName('actionZirconCeOldOld')
self.actionZirconTiTemp = QtWidgets.QAction(QIcon(LocationOfMySelf+'/temperature.png'),u'ZirconTiTemp',self)
self.actionZirconTiTemp.setObjectName('actionZirconTiTemp')
self.actionRutileZrTemp = QtWidgets.QAction(QIcon(LocationOfMySelf+'/temperature.png'),u'RutileZrTemp',self)
self.actionRutileZrTemp.setObjectName('actionRutileZrTemp')
self.actionCluster = QtWidgets.QAction(QIcon(LocationOfMySelf+'/cluster.png'),u'Cluster',self)
self.actionCluster.setObjectName('actionCluster')
self.actionAuto = QtWidgets.QAction(QIcon(LocationOfMySelf+'/auto.png'),u'Auto',self)
self.actionAuto.setObjectName('actionAuto')
self.actionMultiDimension = QtWidgets.QAction(QIcon(LocationOfMySelf+'/multiple.png'),u'MultiDimension',self)
self.actionMultiDimension.setObjectName('actionMultiDimension')
self.actionThreeD = QtWidgets.QAction(QIcon(LocationOfMySelf+'/multiple.png'),u'ThreeD',self)
self.actionThreeD.setObjectName('actionThreeD')
self.actionTwoD = QtWidgets.QAction(QIcon(LocationOfMySelf+'/qapf.png'),u'TwoD',self)
self.actionTwoD.setObjectName('actionTwoD')
self.actionTwoD_Grey = QtWidgets.QAction(QIcon(LocationOfMySelf+'/qapf.png'),u'TwoD Grey',self)
self.actionTwoD_Grey.setObjectName('actionTwoD_Grey')
self.actionDist = QtWidgets.QAction(QIcon(LocationOfMySelf+'/dist.png'),u'Dist',self)
self.actionDist.setObjectName('actionDist')
self.actionStatistics = QtWidgets.QAction(QIcon(LocationOfMySelf+'/statistics.png'), u'Statistics',self)
self.actionStatistics.setObjectName('actionStatistics')
self.actionMyHist = QtWidgets.QAction(QIcon(LocationOfMySelf+'/h.png'), u'Histogram',self)
self.actionMyHist.setObjectName('actionMyHist')
self.actionFA = QtWidgets.QAction(QIcon(LocationOfMySelf+'/fa.png'),u'FA',self)
self.actionFA.setObjectName('actionFA')
self.actionPCA = QtWidgets.QAction(QIcon(LocationOfMySelf+'/pca.png'),u'PCA',self)
self.actionPCA.setObjectName('actionPCA')
self.actionQAPF = QtWidgets.QAction(QIcon(LocationOfMySelf+'/qapf.png'),u'QAPF',self)
self.actionQAPF.setObjectName('actionQAPF')
self.actionSaccani = QtWidgets.QAction(QIcon(LocationOfMySelf + '/s.png'), u'Saccani Plot', self)
self.actionSaccani.setObjectName('actionSaccani')
self.actionRaman = QtWidgets.QAction(QIcon(LocationOfMySelf + '/r.png'), u'Raman Strength', self)
self.actionRaman.setObjectName('actionRaman')
self.actionFluidInclusion = QtWidgets.QAction(QIcon(LocationOfMySelf + '/f.png'), u'Fluid Inclusion', self)
self.actionFluidInclusion.setObjectName('actionFluidInclusion')
self.actionClastic = QtWidgets.QAction(QIcon(LocationOfMySelf+'/mud.png'),u'Clastic',self)
self.actionClastic.setObjectName("actionClastic")
self.actionCIA = QtWidgets.QAction(QIcon(LocationOfMySelf+'/mud.png'),u'CIA and ICV',self)
self.actionCIA.setObjectName("actionCIA")
self.actionXY = QtWidgets.QAction(QIcon(LocationOfMySelf+'/xy.png'), u'X-Y',self)
self.actionXY.setObjectName('actionXY')
self.actionXYZ = QtWidgets.QAction(QIcon(LocationOfMySelf+'/triangular.png'),u'Ternary',self)
self.actionXYZ.setObjectName('actionXYZ')
self.actionRbSrIsoTope = QtWidgets.QAction(QIcon(LocationOfMySelf+'/magic.png'),u'Rb-Sr IsoTope',self)
self.actionRbSrIsoTope.setObjectName('actionRbSrIsoTope')
self.actionSmNdIsoTope = QtWidgets.QAction(QIcon(LocationOfMySelf+'/magic.png'),u'Sm-Nd IsoTope',self)
self.actionSmNdIsoTope.setObjectName('actionSmNdIsoTope')
self.actionKArIsoTope = QtWidgets.QAction(QIcon(LocationOfMySelf+'/magic.png'),u'K-Ar IsoTope',self)
self.actionKArIsoTope.setObjectName('actionKArIsoTope')
self.menuFile.addAction(self.actionOpen)
self.menuFile.addAction(self.actionClose)
self.menuFile.addAction(self.actionSet)
self.menuFile.addAction(self.actionSave)
self.menuFile.addAction(self.actionCombine)
self.menuFile.addAction(self.actionCombine_transverse)
self.menuFile.addAction(self.actionFlatten)
self.menuFile.addAction(self.actionTrans)
#self.menuFile.addAction(self.actionReFormat)
self.menuFile.addAction(self.actionQuit)
self.menuGeoChem.addAction(self.actionRemoveLOI)
self.menuGeoChem.addAction(self.actionAuto)
self.menuGeoChem.addAction(self.actionTAS)
self.menuGeoChem.addAction(self.actionTrace)
self.menuGeoChem.addAction(self.actionRee)
self.menuGeoChem.addAction(self.actionPearce)
self.menuGeoChem.addAction(self.actionHarker)
self.menuGeoChem.addAction(self.actionCIPW)
self.menuGeoChem.addAction(self.actionQAPF)
self.menuGeoChem.addAction(self.actionSaccani)
self.menuGeoChem.addAction(self.actionK2OSiO2)
self.menuGeoChem.addAction(self.actionRaman)
self.menuGeoChem.addAction(self.actionFluidInclusion)
self.menuGeoChem.addAction(self.actionHarkerOld)
self.menuGeoChem.addAction(self.actionTraceNew)
self.menuStructure.addAction(self.actionStereo)
self.menuStructure.addAction(self.actionRose)
self.menuSedimentary.addAction(self.actionQFL)
self.menuSedimentary.addAction(self.actionQmFLt)
self.menuSedimentary.addAction(self.actionClastic)
self.menuSedimentary.addAction(self.actionCIA)
self.menuGeoCalc.addAction(self.actionZirconCe)
self.menuGeoCalc.addAction(self.actionZirconCeOld)
self.menuGeoCalc.addAction(self.actionZirconTiTemp)
self.menuGeoCalc.addAction(self.actionRutileZrTemp)
self.menuGeoCalc.addAction(self.actionRbSrIsoTope)
self.menuGeoCalc.addAction(self.actionSmNdIsoTope)
#self.menuGeoCalc.addAction(self.actionKArIsoTope)
self.menuAdditional.addAction(self.actionXY)
self.menuAdditional.addAction(self.actionXYZ)
self.menuAdditional.addAction(self.actionCluster)
self.menuAdditional.addAction(self.actionMultiDimension)
self.menuAdditional.addAction(self.actionFA)
self.menuAdditional.addAction(self.actionPCA)
self.menuAdditional.addAction(self.actionDist)
self.menuAdditional.addAction(self.actionStatistics)
self.menuAdditional.addAction(self.actionThreeD)
self.menuAdditional.addAction(self.actionTwoD)
self.menuAdditional.addAction(self.actionTwoD_Grey)
self.menuAdditional.addAction(self.actionMyHist)
self.menuHelp.addAction(self.actionWeb)
self.menuHelp.addAction(self.actionGoGithub)
self.menuHelp.addAction(self.actionVersionCheck)
self.menuLanguage.addAction(self.actionCnS)
self.menuLanguage.addAction(self.actionCnT)
self.menuLanguage.addAction(self.actionEn)
self.menuLanguage.addAction(self.actionLoadLanguage)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addSeparator()
self.menubar.addAction(self.menuGeoChem.menuAction())
self.menubar.addSeparator()
self.menubar.addAction(self.menuStructure.menuAction())
self.menubar.addSeparator()
self.menubar.addAction(self.menuSedimentary.menuAction())
self.menubar.addSeparator()
self.menubar.addAction(self.menuGeoCalc.menuAction())
self.menubar.addSeparator()
self.menubar.addAction(self.menuAdditional.menuAction())
self.menubar.addSeparator()
self.menubar.addAction(self.menuHelp.menuAction())
self.menubar.addSeparator()
self.menubar.addAction(self.menuLanguage.menuAction())
self.menubar.addSeparator()
self.actionCombine.triggered.connect(self.Combine)
self.actionCombine_transverse.triggered.connect(self.Combine_transverse)
self.actionFlatten.triggered.connect(self.Flatten)
self.actionTrans.triggered.connect(self.Trans)
self.actionReFormat.triggered.connect(self.ReFormat)
self.actionTAS.triggered.connect(self.TAS)
self.actionTrace.triggered.connect(self.Trace)
self.actionTraceNew.triggered.connect(self.TraceNew)
self.actionRee.triggered.connect(self.REE)
self.actionPearce.triggered.connect(self.Pearce)
self.actionHarker.triggered.connect(self.Harker)
self.actionHarkerOld.triggered.connect(self.HarkerOld)
self.actionQAPF.triggered.connect(self.QAPF)
self.actionSaccani.triggered.connect(self.Saccani)
self.actionK2OSiO2.triggered.connect(self.K2OSiO2)
self.actionRaman.triggered.connect(self.Raman)
self.actionFluidInclusion.triggered.connect(self.FluidInclusion)
self.actionStereo.triggered.connect(self.Stereo)
self.actionRose.triggered.connect(self.Rose)
self.actionQFL.triggered.connect(self.QFL)
self.actionQmFLt.triggered.connect(self.QmFLt)
self.actionClastic.triggered.connect(self.Clastic)
self.actionCIA.triggered.connect(self.CIA)
self.actionCIPW.triggered.connect(self.CIPW)
self.actionZirconCe.triggered.connect(self.ZirconCe)
self.actionZirconCeOld.triggered.connect(self.ZirconCeOld)
self.actionZirconTiTemp.triggered.connect(self.ZirconTiTemp)
self.actionRutileZrTemp.triggered.connect(self.RutileZrTemp)
self.actionCluster.triggered.connect(self.Cluster)
self.actionAuto.triggered.connect(self.Auto)
self.actionMultiDimension.triggered.connect(self.MultiDimension)
self.actionRemoveLOI.triggered.connect(self.RemoveLOI)
self.actionFA.triggered.connect(self.FA)
self.actionPCA.triggered.connect(self.PCA)
self.actionDist.triggered.connect(self.Dist)
self.actionStatistics.triggered.connect(self.Sta)
self.actionThreeD.triggered.connect(self.ThreeD)
self.actionTwoD.triggered.connect(self.TwoD)
self.actionTwoD_Grey.triggered.connect(self.TwoD_Grey)
self.actionMyHist.triggered.connect(self.MyHist)
#self.actionICA.triggered.connect(self.ICA)
#self.actionSVM.triggered.connect(self.SVM)
self.actionOpen.triggered.connect(self.getDataFile)
self.actionClose.triggered.connect(self.clearDataFile)
self.actionSet.triggered.connect(self.SetUpDataFile)
self.actionSave.triggered.connect(self.saveDataFile)
self.actionQuit.triggered.connect(qApp.quit)
self.actionWeb.triggered.connect(self.goIssue)
self.actionGoGithub.triggered.connect(self.goGitHub)
self.actionVersionCheck.triggered.connect(self.checkVersion)
self.actionCnS.triggered.connect(self.to_ChineseS)
self.actionCnT.triggered.connect(self.to_ChineseT)
self.actionEn.triggered.connect(self.to_English)
self.actionLoadLanguage.triggered.connect(self.to_LoadLanguage)
self.actionXY.triggered.connect(self.XY)
self.actionXYZ.triggered.connect(self.XYZ)
self.actionRbSrIsoTope.triggered.connect(self.RbSrIsoTope)
self.actionSmNdIsoTope.triggered.connect(self.SmNdIsoTope)
self.actionKArIsoTope.triggered.connect(self.KArIsoTope)
self.ReadConfig()
self.trans.load(LocationOfMySelf+'/'+self.Language)
self.app.installTranslator(self.trans)
self.retranslateUi()
def goGitHub(self):
webbrowser.open('https://github.com/GeoPyTool/GeoPyTool')
def goIssue(self):
webbrowser.open('https://github.com/GeoPyTool/GeoPyTool/issues')
def checkVersion(self):
#reply = QMessageBox.information(self, 'Version', self.talk)
_translate = QtCore.QCoreApplication.translate
url = 'https://raw.githubusercontent.com/GeoPyTool/GeoPyTool/master/geopytool/CustomClass.py'
r= 0
try:
r = requests.get(url, allow_redirects=True)
r.raise_for_status()
NewVersion = 'self.target' + r.text.splitlines()[0]
except requests.exceptions.ConnectionError as err:
print(err)
r=0
buttonReply = QMessageBox.information(self, _translate('MainWindow', u'NetWork Error'),_translate('MainWindow', u'Net work unavailable.'))
NewVersion ="targetversion = '0'"
except requests.exceptions.HTTPError as err:
print(err)
r=0
buttonReply = QMessageBox.information(self, _translate('MainWindow', u'NetWork Error'),_translate('MainWindow', u'Net work unavailable.'))
NewVersion ="targetversion = '0'"
exec(NewVersion)
print('web is', self.targetversion)
print(NewVersion)
self.talk= _translate('MainWindow','Version Online is ') + self.targetversion +'\n'+_translate('MainWindow','You are using GeoPyTool ') + version +'\n'+ _translate('MainWindow','released on ') + date + '\n'
if r != 0:
print('now is',version)
if (version < self.targetversion):
buttonReply = QMessageBox.question(self, _translate('MainWindow', u'Version'),
self.talk + _translate('MainWindow',
'New version available.\n Download and update?'),
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if buttonReply == QMessageBox.Yes:
print('Yes clicked.')
#qApp.quit
#pip.main(['install', 'geopytool', '--upgrade --no-cache-dir'])
#self.UpDate
webbrowser.open('https://github.com/chinageology/GeoPyTool/blob/master/Download.md')
else:
print('No clicked.')
else:
buttonReply = QMessageBox.information(self, _translate('MainWindow', u'Version'),
self.talk + _translate('MainWindow',
'This is the latest version.'))
def Update(self):
#webbrowser.open('https://github.com/chinageology/GeoPyTool/wiki/Download')
pip.main(['install', 'geopytool','--upgrade'])
def ReadConfig(self):
if(os.path.isfile('config.ini')):
try:
with open('config.ini', 'rt') as f:
try:
data = f.read()
except:
data = 'Language = \'en\''
pass
print(data)
try:
print("self." + data)
exec("self." + data)
except:
pass
print(self.Language)
except():
pass
def WriteConfig(self,text=LocationOfMySelf+'/en'):
try:
with open('config.ini', 'wt') as f:
f.write(text)
except():
pass
def to_ChineseS(self):
self.trans.load(LocationOfMySelf+'/cns')
self.app.installTranslator(self.trans)
self.retranslateUi()
self.WriteConfig('Language = \'cns\'')
def to_ChineseT(self):
self.trans.load(LocationOfMySelf+'/cnt')
self.app.installTranslator(self.trans)
self.retranslateUi()
self.WriteConfig('Language = \'cnt\'')
def to_English(self):
self.trans.load(LocationOfMySelf+'/en')
self.app.installTranslator(self.trans)
self.retranslateUi()
self.WriteConfig('Language = \'en\'')
def to_LoadLanguage(self):
_translate = QtCore.QCoreApplication.translate
fileName, filetype = QFileDialog.getOpenFileName(self,_translate('MainWindow', u'Choose Language File'),
'~/',
'Language Files (*.qm)') # 设置文件扩展名过滤,注意用双分号间隔
print(fileName)
self.trans.load(fileName)
self.app.installTranslator(self.trans)
self.retranslateUi()
def ErrorEvent(self,text=''):
if(text==''):
reply = QMessageBox.information(self, _translate('MainWindow', 'Warning'), _translate('MainWindow',
'Your Data mismatch this Function.\n Some Items missing?\n Or maybe there are blanks in items names?\n Or there are nonnumerical value?'))
else:
reply = QMessageBox.information(self, _translate('MainWindow', 'Warning'), _translate('MainWindow',
'Your Data mismatch this Function.\n Error infor is:') + text)
def SetUpDataFile(self):
flag = 0
ItemsAvalibale = self.model._df.columns.values.tolist()
ItemsToTest = ['Label', 'Marker', 'Color', 'Size', 'Alpha', 'Style', 'Width','Index']
LabelList = []
MarkerList = []
ColorList = []
SizeList = []
AlphaList = []
StyleList = []
WidthList = []
IndexList = []
for i in range(len(self.model._df)):
LabelList.append('Group1')
MarkerList.append('o')
ColorList.append('red')
SizeList.append(10)
AlphaList.append(0.6)
StyleList.append('-')
WidthList.append(1)
IndexList.append(i+1)
data = {'Label': LabelList,
'Index': IndexList,
'Marker': MarkerList,
'Color': ColorList,
'Size': SizeList,
'Alpha': AlphaList,
'Style': StyleList,
'Width': WidthList}
for i in ItemsToTest:
if i not in ItemsAvalibale:
# print(i)
flag = flag + 1
tmpdftoadd = pd.DataFrame({i: data[i]})
self.model._df = pd.concat([tmpdftoadd, self.model._df], axis=1)
self.model = PandasModel(self.model._df)
self.tableView.setModel(self.model)
if flag == 0:
reply = QMessageBox.information(self, _translate('MainWindow','Ready'),
_translate('MainWindow','Everything fine and no need to set up.'))
else:
reply = QMessageBox.information(self, _translate('MainWindow','Ready'),
_translate('MainWindow','Items added, Modify in the Table to set up details.'))
def clearDataFile(self):
self.raw = pd.DataFrame()
self.model = PandasModel(self.raw)
self.tableView.setModel(self.model)
def getDataFiles(self,limit=6):
print('get Multiple Data Files called \n')
DataFilesInput, filetype = QFileDialog.getOpenFileNames(self, u'Choose Data File',
'~/',
'Excel Files (*.xlsx);;Excel 2003 Files (*.xls);;CSV Files (*.csv)') # 设置文件扩展名过滤,注意用双分号间隔
# print(DataFileInput,filetype)
DataFramesList = []
if len(DataFilesInput) >= 1 :
for i in range(len(DataFilesInput)):
if i < limit:
if ('csv' in DataFilesInput[i]):
DataFramesList.append(pd.read_csv(DataFilesInput[i], engine='python'))
elif ('xls' in DataFilesInput[i]):
DataFramesList.append(pd.read_excel(DataFilesInput[i]))
else:
#self.ErrorEvent(text='You can only open up to 6 Data Files at a time.')
pass
return(DataFramesList,DataFilesInput)
def getDataFile(self,CleanOrNot=True):
_translate = QtCore.QCoreApplication.translate
DataFileInput, filetype = QFileDialog.getOpenFileName(self,_translate('MainWindow', u'Choose Data File'),
'~/',
'Excel Files (*.xlsx);;Excel 2003 Files (*.xls);;CSV Files (*.csv)') # 设置文件扩展名过滤,注意用双分号间隔
# #print(DataFileInput,filetype)
self.DataLocation = DataFileInput
print(self.DataLocation )
if ('csv' in DataFileInput):
self.raw = pd.read_csv(DataFileInput, engine='python')
elif ('xls' in DataFileInput):
self.raw = pd.read_excel(DataFileInput)
# #print(self.raw)
if len(self.raw)>0:
self.model = PandasModel(self.raw)
#print(self.model._df)
self.tableView.setModel(self.model)
self.model = PandasModel(self.raw)
#print(self.model._df)
flag = 0
ItemsAvalibale = self.model._df.columns.values.tolist()
ItemsToTest = ['Label', 'Marker', 'Color', 'Size', 'Alpha', 'Style', 'Width']
for i in ItemsToTest:
if i not in ItemsAvalibale:
# print(i)
flag = flag + 1
if flag == 0:
pass
#reply = QMessageBox.information(self, _translate('MainWindow', 'Ready'), _translate('MainWindow', 'Everything fine and no need to set up.'))
else:
pass
#self.SetUpDataFile()
def getFileName(self,list=['C:/Users/Fred/Documents/GitHub/Writing/元素数据/Ag.xlsx']):
result=[]
for i in list:
result.append(i.split("/")[-1].split(".")[0])
return(result)
def saveDataFile(self):
# if self.model._changed == True:
# print('changed')
# #print(self.model._df)
DataFileOutput, ok2 = QFileDialog.getSaveFileName(self,_translate('MainWindow', u'Save Data File'),
'C:/',
'Excel Files (*.xlsx);;CSV Files (*.csv)') # 数据文件保存输出
dftosave = self.model._df
#self.model._df.reset_index(drop=True)
if "Label" in dftosave.columns.values.tolist():
dftosave = dftosave.set_index('Label')
if (DataFileOutput != ''):
dftosave.reset_index(drop=True)
if ('csv' in DataFileOutput):
dftosave.to_csv(DataFileOutput, sep=',', encoding='utf-8')
elif ('xls' in DataFileOutput):
dftosave.to_excel(DataFileOutput, encoding='utf-8')
def OldCombine(self):
print('Combine called \n')
pass
DataFilesInput, filetype = QFileDialog.getOpenFileNames(self, _translate('MainWindow', u'Choose Data File'),
'~/',
'Excel Files (*.xlsx);;Excel 2003 Files (*.xls);;CSV Files (*.csv)') # 设置文件扩展名过滤,注意用双分号间隔
# #print(DataFileInput,filetype)
DataFramesList=[]
if len(DataFilesInput)>1:
for i in DataFilesInput:
if ('csv' in i):
DataFramesList.append(pd.read_csv(i), engine='python')
elif ('xls' in i):
DataFramesList.append(pd.read_excel(i))
pass
#result = pd.concat(DataFramesList,axis=1,sort=False)
result = pd.concat(DataFramesList, ignore_index=True, sort=False)
DataFileOutput, ok2 = QFileDialog.getSaveFileName(self,_translate('MainWindow', u'Save Data File'),
'C:/',
'Excel Files (*.xlsx);;CSV Files (*.csv)') # 数据文件保存输出
dftosave = result
if (DataFileOutput != ''):
dftosave.reset_index(drop=True)
if ('csv' in DataFileOutput):
dftosave.to_csv(DataFileOutput, sep=',', encoding='utf-8')
elif ('xls' in DataFileOutput):
dftosave.to_excel(DataFileOutput, encoding='utf-8')
def Combine(self):
print('Combine called \n')
pass
DataFilesInput, filetype = QFileDialog.getOpenFileNames(self, _translate('MainWindow', u'Choose Data File'),
'~/',
'Excel Files (*.xlsx);;Excel 2003 Files (*.xls);;CSV Files (*.csv)') # 设置文件扩展名过滤,注意用双分号间隔
# #print(DataFileInput,filetype)
DataFramesList = []
if len(DataFilesInput) > 1:
for i in DataFilesInput:
if ('csv' in i):
DataFramesList.append(pd.read_csv(i, engine='python'))
elif ('xls' in i):
DataFramesList.append(pd.read_excel(i))
pass
# result = pd.concat(DataFramesList,axis=1,sort=False)
result = pd.concat(DataFramesList, ignore_index=True, sort=False)
print('self.model._df length: ', len(result))
if (len(result) > 0):
self.Combinepop = MyCombine(df=result)
self.Combinepop.Combine()
def getFileName(self,list=['C:/Users/Fred/Documents/GitHub/Writing/元素数据/Ag.xlsx']):
result=[]
for i in list:
result.append(i.split("/")[-1].split(".")[0])
#print(result)
return(result)
def Combine_transverse(self):
print('Combine called \n')
DataFilesInput, filetype = QFileDialog.getOpenFileNames(self, _translate('MainWindow', u'Choose Data File'),
'~/',
'Excel Files (*.xlsx);;Excel 2003 Files (*.xls);;CSV Files (*.csv)') # 设置文件扩展名过滤,注意用双分号间隔
DataFramesList = []
filenamelist = self.getFileName(DataFilesInput)
if len(DataFilesInput) > 1:
for i in range(len(DataFilesInput)):
tmpdf=pd.DataFrame()
if ('csv' in DataFilesInput[i]):
tmpdf=pd.read_csv(DataFilesInput[i], engine='python')
elif ('xls' in DataFilesInput[i]):
tmpdf=pd.read_excel(DataFilesInput[i])
#name_list = tmpdf.columns.values.tolist()
tmpname_dic={}
tmpname_list =[]
oldname_list=tmpdf.columns.values.tolist()
for k in oldname_list:
tmpname_list.append(filenamelist[i]+k)
tmpname_dic[k]=filenamelist[i]+' '+k
print(tmpname_dic)
tmpdf = tmpdf.rename(index=str, columns=tmpname_dic)
DataFramesList.append(tmpdf)
# result = pd.concat(DataFramesList,axis=1,sort=False)
result = pd.concat(DataFramesList,axis=1, ignore_index=False, sort=False)
print('self.model._df length: ', len(result))
if (len(result) > 0):
self.Combinepop = MyCombine(df=result)
self.Combinepop.Combine()
def Flatten(self):
print('Flatten called \n')
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
pass
if (len(self.model._df) > 0):
self.flattenpop = MyFlatten(df=self.model._df)
self.flattenpop.Flatten()
def Trans(self):
print('Trans called \n')
if (len(self.model._df)<=0):
self.getDataFile()
pass
if (len(self.model._df) > 0):
self.transpop = MyTrans(df=self.model._df)
self.transpop.Trans()
def ReFormat(self):
print('ReFormat called \n')
Datas= self.getDataFiles()
def RemoveLOI(self):
_translate = QtCore.QCoreApplication.translate
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
self.model._df_back= self.model._df
if (len(self.model._df) > 0):
loi_list = ['LOI', 'loi', 'Loi']
all_list = ['Total', 'total', 'TOTAL', 'ALL', 'All', 'all']
itemstocheck = ['Total', 'total', 'TOTAL', 'ALL', 'All', 'all','Al2O3', 'MgO', 'FeO', 'Fe2O3', 'CaO', 'Na2O', 'K2O', 'TiO2', 'P2O5', 'SiO2','TFe2O3','MnO','TFeO']
for i in range(len(self.model._df)):
Loi_flag = False
for k in all_list:
if k in self.model._df.columns.values:
de_loi = self.model._df.iloc[i][k]
for m in itemstocheck:
if m in self.model._df.columns.values:
self.model._df.at[i,m]= 100* self.model._df.at[i,m]/de_loi
Loi_flag= True
break
else:
Loi_flag = False
for j in loi_list:
if Loi_flag == False:
if j in self.model._df.columns.values:
de_loi = 100 - self.model._df.iloc[i][k]
for m in itemstocheck:
if m in self.model._df.columns.values:
self.model._df.at[i,m] = 100 * self.model._df.at[i,m] / de_loi
Loi_flag = True
break
else:
Loi_flag = False
if Loi_flag == False:
tmp_all=0
for m in itemstocheck:
if m in self.model._df.columns.values:
tmp_all = tmp_all+ self.model._df.at[i,m]
if round(tmp_all) != 100:
print(tmp_all)
for m in itemstocheck:
if m in self.model._df.columns.values:
self.model._df.at[i, m] = 100 * self.model._df.at[i, m] / tmp_all
reply = QMessageBox.information(self, _translate('MainWindow', 'Done'), _translate('MainWindow',
'LOI has been removed!:'))
def TAS(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.taspop = TAS(df=self.model._df)
self.taspop.TAS()
self.taspop.show()
try:
self.taspop.TAS()
self.taspop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def Saccani(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df) <= 0):
self.getDataFile()
if (len(self.model._df) > 0):
self.sacpop = Saccani(df=self.model._df)
try:
self.sacpop.Saccani()
self.sacpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def Raman(self):
print('self.model._df length: ',len(self.raw))
if (len(self.raw) <= 0):
self.getDataFile()
if (len(self.raw) > 0):
self.ramanpop = Raman(df=self.raw,filename= self.DataLocation)
try:
self.ramanpop.Raman()
self.ramanpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def FluidInclusion(self):
print('self.model._df length: ',len(self.raw))
if (len(self.raw) <= 0):
self.getDataFile()
if (len(self.raw) > 0):
self.FluidInclusionpop = FluidInclusion(df=self.raw,filename= self.DataLocation)
try:
self.FluidInclusionpop.FluidInclusion()
self.FluidInclusionpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def MyHist(self):
print('self.model._df length: ',len(self.raw))
if (len(self.raw) <= 0):
self.getDataFile()
if (len(self.raw) > 0):
self.MyHistpop = MyHist(df=self.raw,filename= self.DataLocation)
self.MyHistpop.MyHist()
self.MyHistpop.show()
try:
self.MyHistpop.MyHist()
self.MyHistpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def REE(self):
print('self.model._df length: ',len(self.model._df))
if len(self.Standard)>0:
print('self.Standard length: ', len(self.Standard))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.reepop = REE(df=self.model._df,Standard=self.Standard)
try:
self.reepop.REE()
self.reepop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def Trace(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.tracepop = Trace(df=self.model._df,Standard=self.Standard)
try:
self.tracepop.Trace()
self.tracepop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def TraceNew(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.TraceNewpop = TraceNew(df=self.model._df,Standard=self.Standard)
try:
self.TraceNewpop.Trace()
self.TraceNewpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def Pearce(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.pearcepop = Pearce(df=self.model._df)
try:
self.pearcepop.Pearce()
self.pearcepop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def Harker(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.harkerpop = Harker(df=self.model._df)
try:
self.harkerpop.Harker()
self.harkerpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def HarkerOld(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.harkeroldpop = HarkerOld(df=self.model._df)
try:
self.harkeroldpop.HarkerOld()
self.harkeroldpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def CIPW(self):
print('self.model._df length: ', len(self.model._df))
if (len(self.model._df) <= 0):
self.getDataFile()
if (len(self.model._df) > 0):
self.cipwpop = CIPW(df=self.model._df)
try:
self.cipwpop.CIPW()
self.cipwpop.show()
except():
self.ErrorEvent()
def ZirconTiTemp(self):
print('self.model._df length: ', len(self.model._df))
if (len(self.model._df) <= 0):
self.getDataFile()
if (len(self.model._df) > 0):
self.ztpop = ZirconTiTemp(df=self.model._df)
try:
self.ztpop.ZirconTiTemp()
self.ztpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def RutileZrTemp(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.rzpop = RutileZrTemp(df=self.model._df)
try:
self.rzpop.RutileZrTemp()
self.rzpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def Cluster(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
pass
if (len(self.model._df) > 0):
try:
self.clusterpop = Cluster(df=self.model._df)
self.clusterpop.Cluster()
except Exception as e:
self.ErrorEvent(text=repr(e))
def Stereo(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.stereopop = Stereo(df=self.model._df)
try:
self.stereopop.Stereo()
self.stereopop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def Rose(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.rosepop = Rose(df=self.model._df)
try:
self.rosepop.Rose()
self.rosepop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def QFL(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.qflpop = QFL(df=self.model._df)
self.qflpop.Tri()
self.qflpop.show()
try:
self.qflpop.Tri()
self.qflpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def QmFLt(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.qmfltpop = QmFLt(df=self.model._df)
try:
self.qmfltpop.Tri()
self.qmfltpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def Clastic(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.clusterpop = Clastic(df=self.model._df)
try:
self.clusterpop.Tri()
self.clusterpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def CIA(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.ciapop = CIA(df=self.model._df)
try:
self.ciapop.CIA()
self.ciapop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def QAPF(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
ItemsAvalibale = self.model._df.columns.values.tolist()
if 'Q' in ItemsAvalibale and 'A' in ItemsAvalibale and 'P' in ItemsAvalibale and 'F' in ItemsAvalibale:
self.qapfpop = QAPF(df=self.model._df)
try:
self.qapfpop.QAPF()
self.qapfpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
else:
reply = QMessageBox.information(self, _translate('MainWindow', 'Warning'), _translate('MainWindow',
'Your data contain no Q/A/P/F data.\n Maybe you need to run CIPW first?'))
def ZirconCe(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile(CleanOrNot=False)
# print('Opening a new popup window...')
if (len(self.model._df) > 0):
self.zirconpop = ZirconCe(df=self.model._df)
try:
self.zirconpop.MultiBallard()
self.zirconpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def ZirconCeOld(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile(CleanOrNot=False)
# print('Opening a new popup window...')
if (len(self.model._df) > 0):
self.zirconoldpop = ZirconCeOld(df=self.model._df)
try:
self.zirconoldpop.MultiBallard()
self.zirconoldpop.show()
except(KeyError,ValueError,TypeError):
self.ErrorEvent()
def RbSrIsoTope(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.rbsrisotopepop = IsoTope(df=self.model._df,description='Rb-Sr IsoTope diagram', xname='87Rb/86Sr',
yname='87Sr/86Sr', lambdaItem=1.42e-11, xlabel=r'$^{87}Rb/^{86}Sr$', ylabel=r'$^{87}Sr/^{86}Sr$')
try:
self.rbsrisotopepop.Magic()
self.rbsrisotopepop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def SmNdIsoTope(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.smndisotopepop = IsoTope(df=self.model._df,description='Sm-Nd IsoTope diagram', xname='147Sm/144Nd',
yname= '143Nd/144Nd', lambdaItem=6.54e-12, xlabel=r'$^{147}Sm/^{144}Nd$', ylabel=r'$^{143}Nd/^{144}Nd$')
try:
self.smndisotopepop.Magic()
self.smndisotopepop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def KArIsoTope(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.karisotopepop = KArIsoTope(df=self.model._df)
try:
self.karisotopepop.Magic()
self.karisotopepop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def K2OSiO2(self):
print('self.model._df length: ', len(self.model._df))
if (len(self.model._df) <= 0):
self.getDataFile()
if (len(self.model._df) > 0):
self.taspop = K2OSiO2(df=self.model._df)
try:
self.taspop.K2OSiO2()
self.taspop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def XY(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.xypop = XY(df=self.model._df,Standard=self.Standard)
try:
self.xypop.Magic()
self.xypop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def XYZ(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.xyzpop = XYZ(df=self.model._df,Standard=self.Standard)
try:
self.xyzpop.Magic()
self.xyzpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def MultiDimension(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
self.mdpop = MultiDimension(df=self.model._df)
try:
self.mdpop.Magic()
self.mdpop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def ThreeD(self):
print('ThreeD called \n')
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df) > 0):
self.ThreeDpop = MyThreeD( DataFiles = [self.model._df],DataLocation= [self.DataLocation])
self.ThreeDpop.ThreeD()
else:
DataFiles, DataLocation = self.getDataFiles()
print(len(DataFiles),len(DataLocation))
if len(DataFiles)>0:
self.ThreeDpop = MyThreeD( DataFiles = DataFiles,DataLocation= DataLocation)
self.ThreeDpop.ThreeD()
def TwoD(self):
print('TwoD called \n')
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df) > 0):
self.TwoDpop = MyTwoD( DataFiles = [self.model._df],DataLocation= [self.DataLocation])
self.TwoDpop.TwoD()
else:
DataFiles, DataLocation = self.getDataFiles()
print(len(DataFiles),len(DataLocation))
if len(DataFiles)>0:
self.TwoDpop = MyTwoD( DataFiles = DataFiles,DataLocation= DataLocation)
self.TwoDpop.TwoD()
def TwoD_Grey(self):
print('TwoD_Grey called \n')
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df) > 0):
self.TwoDpop = MyTwoD_Grey( DataFiles = [self.model._df],DataLocation= [self.DataLocation])
self.TwoDpop.TwoD()
else:
DataFiles, DataLocation = self.getDataFiles()
print(len(DataFiles),len(DataLocation))
if len(DataFiles)>0:
self.TwoDpop = MyTwoD_Grey( DataFiles = DataFiles,DataLocation= DataLocation)
self.TwoDpop.TwoD()
def Dist(self):
print('Dist called \n')
if (len(self.model._df)<=0):
self.getDataFile()
pass
if (len(self.model._df) > 0):
try:
self.Distpop = MyDist(df=self.model._df)
self.Distpop.Dist()
except Exception as e:
self.ErrorEvent(text=repr(e))
def Sta(self):
#Sta on Calculated Distance
print('Sta called \n')
pass
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
pass
if (len(self.model._df) > 0):
self.stapop = MySta(df=self.model._df)
self.stapop.Sta()
try:
self.stapop = MySta(df=self.model._df)
self.stapop.Sta()
except Exception as e:
tmp_msg='\n This is to do Sta on Calculated Distance.\n'
self.ErrorEvent(text=tmp_msg+repr(e))
def PCA(self):
print('PCA called \n')
pass
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
pass
if (len(self.model._df) > 0):
self.pcapop = MyPCA(df=self.model._df)
try:
self.pcapop.Key_Func()
self.pcapop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def FA(self):
print('FA called \n')
pass
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
pass
if (len(self.model._df) > 0):
self.fapop = MyFA(df=self.model._df)
self.fapop.Key_Func()
self.fapop.show()
try:
self.fapop.Key_Func()
self.fapop.show()
except Exception as e:
self.ErrorEvent(text=repr(e))
def Tri(self):
pass
def Auto(self):
print('self.model._df length: ',len(self.model._df))
if (len(self.model._df)<=0):
self.getDataFile()
if (len(self.model._df) > 0):
TotalResult=[]
df = self.model._df
AutoResult = 0
FileOutput, ok1 = QFileDialog.getSaveFileName(self,
'文件保存',
'C:/',
'PDF Files (*.pdf)') # 数据文件保存输出
if (FileOutput != ''):
AutoResult = pd.DataFrame()
pdf = matplotlib.backends.backend_pdf.PdfPages(FileOutput)
cipwsilent = CIPW(df=df)
cipwsilent.CIPW()
cipwsilent.QAPFsilent()
# TotalResult.append(cipwsilent.OutPutFig)
pdf.savefig(cipwsilent.OutPutFig)
# AutoResult = pd.concat([cipwsilent.OutPutData, AutoResult], axis=1)
tassilent = TAS(df=df)
tassilent.TAS()
tassilent.GetResult()
# TotalResult.append(tassilent.OutPutFig)
pdf.savefig(tassilent.OutPutFig)
AutoResult = pd.concat([tassilent.OutPutData, AutoResult], axis=1)
reesilent = REE(df=df,Standard=self.Standard)
if (reesilent.Check() == True):
reesilent.REE()
reesilent.GetResult()
# TotalResult.append(reesilent.OutPutFig)
pdf.savefig(reesilent.OutPutFig)
AutoResult = pd.concat([reesilent.OutPutData, AutoResult], axis=1)
tracesilent = Trace(df=df,Standard=self.Standard)
if (tracesilent.Check() == True):
tracesilent.Trace()
tracesilent.GetResult()
TotalResult.append(tracesilent.OutPutFig)
pdf.savefig(tracesilent.OutPutFig)
harkersilent = Harker(df=df)
harkersilent.Harker()
harkersilent.GetResult()
TotalResult.append(harkersilent.OutPutFig)
pdf.savefig(harkersilent.OutPutFig)
pearcesilent = Pearce(df=df)
pearcesilent.Pearce()
pearcesilent.GetResult()
TotalResult.append(pearcesilent.OutPutFig)
pdf.savefig(pearcesilent.OutPutFig)
AutoResult = AutoResult.T.groupby(level=0).first().T
pdf.close()
AutoResult = AutoResult.set_index('Label')
AutoResult=AutoResult.drop_duplicates()
print(AutoResult.shape, cipwsilent.newdf3.shape)
try:
AutoResult = pd.concat([cipwsilent.newdf3, AutoResult], axis=1)
except(ValueError):
pass
if ('pdf' in FileOutput):
FileOutput = FileOutput[0:-4]
AutoResult.to_csv(FileOutput + '-chemical-info.csv', sep=',', encoding='utf-8')
cipwsilent.newdf.to_csv(FileOutput + '-cipw-mole.csv', sep=',', encoding='utf-8')
cipwsilent.newdf1.to_csv(FileOutput + '-cipw-mass.csv', sep=',', encoding='utf-8')
cipwsilent.newdf2.to_csv(FileOutput + '-cipw-volume.csv', sep=',', encoding='utf-8')
cipwsilent.newdf3.to_csv(FileOutput + '-cipw-index.csv', sep=',', encoding='utf-8')
else:
pass
|
GeoPyTool/GeoPyTool | geopytool/Rose.py | Rose.singlerose | python | def singlerose(self, Width=1, Color=['red']):
'''
draw the rose map of single sample with different items~
'''
self.chooser_label.setText(self.ChooseItems[self.chooser.value() - 1])
self.MultipleRoseName = self.ChooseItems[self.chooser.value() - 1]
self.SingleRoseName = [(self.ChooseItems[self.chooser.value() - 1])]
Name = self.SingleRoseName
self.axes.clear()
# self.axes.set_xlim(-90, 450)
# self.axes.set_ylim(0, 90)
titles = list('NWSE')
titles = ['N', '330', '300', 'W', '240', '210', 'S', '150', '120', 'E', '60', '30']
self.n = len(titles)
self.angles = np.arange(90, 90 + 360, 360.0 / self.n)
self.angles = np.array([90., 120., 150., 180., 210., 240., 270., 300., 330.,
360., 30., 60.])
self.axes.set_thetagrids(self.angles, labels=titles, fontsize=14)
self.raw = self._df
real_max = []
for k in range(len(Name)):
Data = []
S = []
R = []
for i in range(len(self.raw)):
S.append(self.raw.at[i, Name[k]])
s = np.linspace(0, 360, 360 / self.Gap + 1)
t = tuple(s.tolist())
count = []
for i in range(len(t)):
tmp_count = 0
for j in S:
if i < len(t) - 1:
if t[i] < j <= t[i + 1]:
tmp_count += 1
count.append(tmp_count)
count_max = max(count)
real_max.append(count_max)
maxuse = max(real_max)
for k in range(len(Name)):
Data = []
S = []
R = []
for i in range(len(self.raw)):
S.append(self.raw.at[i, Name[k]])
s = np.linspace(0, 360, 360 / self.Gap + 1)
t = tuple(s.tolist())
count = []
for i in range(len(t)):
tmp_count = 0
for j in S:
if i < len(t) - 1:
if t[i] < j <= t[i + 1]:
tmp_count += 1
count.append(tmp_count)
s = np.linspace(0, 360, 360 / self.Gap + 1)
t = tuple(s.tolist())
R_factor = 90 / maxuse
for i in count:
TMP = 90 - i * R_factor
R.append(TMP)
m, n = self.Trans(t, R)
self.axes.plot(m, n, color=Color[k], linewidth=1, alpha=0.6, marker='')
self.axes.fill(m, n, Color=Color[k], Alpha=0.6, )
if (self.Type_cb.isChecked()):
self.Type_cb.setText('Wulf')
list1 = [self.eqan(x) for x in range(15, 90, 15)]
else:
self.Type_cb.setText('Schmidt')
list1 = [self.eqar(x) for x in range(15, 90, 15)]
list2= list1
print(maxuse + 1)
try:
list2 = [str(x) for x in range(0, int(maxuse + 1), int((maxuse + 1.0) / 7.0))]
except(ValueError):
pass
list2.reverse()
self.axes.set_rgrids(list1, list2)
#self.axes.set_thetagrids(range(360 + 90, 0 + 90, -15), [str(x) for x in range(0, 360, 15)])
if (self.legend_cb.isChecked()):
self.axes.legend(bbox_to_anchor=(1.5, 1), loc=2, borderaxespad=0, prop=fontprop) | draw the rose map of single sample with different items~ | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/Rose.py#L154-L265 | null | class Rose(AppForm):
reference = 'Zhou, J. B., Zeng, Z. X., and Yuan, J. R., 2003, THE DESIGN AND DEVELOPMENT OF THE SOFTWARE STRUCKIT FOR STRUCTURAL GEOLOGY: Journal of Changchun University of Science & Technology, v. 33, no. 3, p. 276-281.'
_df = pd.DataFrame()
_changed = False
xlabel = r''
ylabel = r''
Gap = 10
MultipleRoseName = 'Dip'
SingleRoseName = ['Dip']
def __init__(self, parent=None, df=pd.DataFrame()):
QMainWindow.__init__(self, parent)
self.setWindowTitle('Rose Map')
self._df = df
if (len(df) > 0):
self._changed = True
# print('DataFrame recieved to Rose')
self.create_main_frame()
self.create_status_bar()
def create_main_frame(self):
self.resize(1000,600)
self.main_frame = QWidget()
self.dpi = 128
self.fig = Figure((8.0, 8.0), dpi=self.dpi)
self.fig.subplots_adjust(hspace=0.5, wspace=0.5, left=0.1, bottom=0.1, right=0.6, top=0.9)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.axes = self.fig.add_subplot(111, projection='polar')
#self.axes.set_xlim(-90, 450)
#self.axes.set_ylim(0, 90)
# Create the navigation toolbar, tied to the canvas
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
# Other GUI controls
self.save_button = QPushButton('&Save')
self.save_button.clicked.connect(self.saveImgFile)
self.draw_button = QPushButton('&Reset')
self.draw_button.clicked.connect(self.Rose)
self.legend_cb = QCheckBox('&Legend')
self.legend_cb.setChecked(True)
self.legend_cb.stateChanged.connect(self.Rose) # int
self.Type_cb = QCheckBox('&Wulf')
self.Type_cb.setChecked(True)
self.Type_cb.stateChanged.connect(self.Rose) # int
if (self.Type_cb.isChecked()):
self.Type_cb.setText('Wulf')
else:
self.Type_cb.setText('Schmidt')
self.Rose_cb = QCheckBox('&Single Rose')
self.Rose_cb.setChecked(True)
self.Rose_cb.stateChanged.connect(self.Rose) # int
if (self.Rose_cb.isChecked()):
self.Rose_cb.setText('Single Rose')
else:
self.Rose_cb.setText('Multiple Rose')
slider_label = QLabel('Step:')
self.slider = QSlider(Qt.Horizontal)
self.slider.setRange(1, 30)
self.slider.setValue(5)
self.slider.setTracking(True)
self.slider.setTickPosition(QSlider.TicksBothSides)
self.slider.valueChanged.connect(self.Rose) # int
self.ChooseItems = ['Strike', 'Dip', 'Dip-Angle']
self.chooser_label = QLabel('Dip')
self.chooser = QSlider(Qt.Horizontal)
self.chooser.setRange(1, 3)
self.chooser.setValue(2)
self.chooser.setTracking(True)
self.chooser.setTickPosition(QSlider.TicksBothSides)
self.chooser.valueChanged.connect(self.Rose) # int
self.chooser_label.setText(self.ChooseItems[self.chooser.value() - 1])
self.MultipleRoseName = self.ChooseItems[self.chooser.value() - 1]
self.SingleRoseName = [(self.ChooseItems[self.chooser.value() - 1])]
#
# Layout with box sizers
#
self.hbox = QHBoxLayout()
for w in [self.save_button, self.draw_button, self.Type_cb, self.Rose_cb,
self.legend_cb, slider_label, self.slider, self.chooser, self.chooser_label]:
self.hbox.addWidget(w)
self.hbox.setAlignment(w, Qt.AlignVCenter)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.mpl_toolbar)
self.vbox.addWidget(self.canvas)
self.vbox.addLayout(self.hbox)
self.textbox = GrowingTextEdit(self)
self.textbox.setText(self.reference)
self.vbox.addWidget(self.textbox)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame)
def eqar(self, A):
return (2 ** .5) * 90 * np.sin(np.pi * (90. - A) / (2. * 180.))
def eqan(self, A):
return 90 * np.tan(np.pi * (90. - A) / (2. * 180.))
def getangular(self, A, B, C):
a = np.radians(A)
b = np.radians(B)
c = np.radians(C)
result = np.arctan((np.tan(a)) * np.cos(np.abs(b - c)))
result = np.rad2deg(result)
return result
def Trans(self, S=(0, 100, 110), D=(0, 30, 40)):
a = []
b = []
for i in S:
a.append(np.radians(90 - i))
for i in D:
if (self.Type_cb.isChecked()):
self.Type_cb.setText('Wulf')
b.append(self.eqan(i))
else:
self.Type_cb.setText('Schmidt')
b.append(self.eqar(i))
return (a, b)
def multirose(self, Width=1, Name='Dip'):
'''
draw the rose map of multiple samples~
'''
Name = self.MultipleRoseName
self.axes.clear()
# self.axes.set_xlim(-90, 450)
# self.axes.set_ylim(0, 90)
titles = list('NWSE')
titles = ['N', '330', '300', 'W', '240', '210', 'S', '150', '120', 'E', '60', '30']
self.n = len(titles)
self.angles = np.arange(90, 90 + 360, 360.0 / self.n)
self.angles = np.array([90., 120., 150., 180., 210., 240., 270., 300., 330.,
360., 30., 60.])
self.axes.set_thetagrids(self.angles, labels=titles, fontsize=14)
self.raw = self._df
real_max = []
S = []
R = []
Color = []
Label = []
Whole = {}
for i in range(len(self.raw)):
S.append(self.raw.at[i, Name])
if self.raw.at[i, 'Color'] not in Color and self.raw.at[i, 'Color'] != '':
Color.append(self.raw.at[i, 'Color'])
if self.raw.at[i, 'Label'] not in Label and self.raw.at[i, 'Label'] != '':
Label.append(self.raw.at[i, 'Label'])
Whole = ({k: [] for k in Label})
WholeCount = ({k: [] for k in Label})
for i in range(len(self.raw)):
for k in Label:
if self.raw.at[i, 'Label'] == k:
Whole[k].append(self.raw.at[i, Name])
t = tuple(np.linspace(0, 360, 360 / self.Gap + 1).tolist())
real_max = 0
for j in range(len(Label)):
for i in range(len(t)):
tmp_count = 0
for u in Whole[Label[j]]:
if i < len(t) - 1:
if t[i] < u <= t[i + 1]:
tmp_count += 1
real_max = max(real_max, tmp_count)
WholeCount[Label[j]].append(tmp_count)
maxuse = real_max
R_factor = 90 / maxuse
for j in range(len(Label)):
R = []
for i in WholeCount[Label[j]]:
TMP = 90 - i * R_factor
R.append(TMP)
m, n = self.Trans(t, R)
self.axes.plot(m, n, color=Color[j], linewidth=1, alpha=0.6, marker='', label=Label[j])
self.axes.fill(m, n, Color=Color[j], Alpha=0.6)
if (self.Type_cb.isChecked()):
self.Type_cb.setText('Wulf')
list1 = [self.eqan(x) for x in range(15, 90, 15)]
else:
self.Type_cb.setText('Schmidt')
list1 = [self.eqar(x) for x in range(15, 90, 15)]
list2= list1
try:
list2 = [str(x) for x in range(0, int(maxuse + 1), int((maxuse + 1) / 7))]
except(ValueError):
pass
list2.reverse()
self.axes.set_rgrids(list1, list2)
#self.axes.set_thetagrids(range(360 + 90, 0 + 90, -15), [str(x) for x in range(0, 360, 15)])
if (self.legend_cb.isChecked()):
self.axes.legend(bbox_to_anchor=(1.5, 1), loc=2, borderaxespad=0, prop=fontprop)
def Rose(self):
self.Gap = self.slider.value()
self.chooser_label.setText(self.ChooseItems[self.chooser.value() - 1])
self.MultipleRoseName = self.ChooseItems[self.chooser.value() - 1]
self.SingleRoseName = [(self.ChooseItems[self.chooser.value() - 1])]
if (self.Type_cb.isChecked()):
self.Type_cb.setText('Wulf')
else:
self.Type_cb.setText('Schmidt')
if (self.Rose_cb.isChecked()):
self.Rose_cb.setText('Single Rose')
self.singlerose()
else:
self.Rose_cb.setText('Multiple Rose')
self.multirose()
self.canvas.draw()
|
GeoPyTool/GeoPyTool | geopytool/Rose.py | Rose.multirose | python | def multirose(self, Width=1, Name='Dip'):
'''
draw the rose map of multiple samples~
'''
Name = self.MultipleRoseName
self.axes.clear()
# self.axes.set_xlim(-90, 450)
# self.axes.set_ylim(0, 90)
titles = list('NWSE')
titles = ['N', '330', '300', 'W', '240', '210', 'S', '150', '120', 'E', '60', '30']
self.n = len(titles)
self.angles = np.arange(90, 90 + 360, 360.0 / self.n)
self.angles = np.array([90., 120., 150., 180., 210., 240., 270., 300., 330.,
360., 30., 60.])
self.axes.set_thetagrids(self.angles, labels=titles, fontsize=14)
self.raw = self._df
real_max = []
S = []
R = []
Color = []
Label = []
Whole = {}
for i in range(len(self.raw)):
S.append(self.raw.at[i, Name])
if self.raw.at[i, 'Color'] not in Color and self.raw.at[i, 'Color'] != '':
Color.append(self.raw.at[i, 'Color'])
if self.raw.at[i, 'Label'] not in Label and self.raw.at[i, 'Label'] != '':
Label.append(self.raw.at[i, 'Label'])
Whole = ({k: [] for k in Label})
WholeCount = ({k: [] for k in Label})
for i in range(len(self.raw)):
for k in Label:
if self.raw.at[i, 'Label'] == k:
Whole[k].append(self.raw.at[i, Name])
t = tuple(np.linspace(0, 360, 360 / self.Gap + 1).tolist())
real_max = 0
for j in range(len(Label)):
for i in range(len(t)):
tmp_count = 0
for u in Whole[Label[j]]:
if i < len(t) - 1:
if t[i] < u <= t[i + 1]:
tmp_count += 1
real_max = max(real_max, tmp_count)
WholeCount[Label[j]].append(tmp_count)
maxuse = real_max
R_factor = 90 / maxuse
for j in range(len(Label)):
R = []
for i in WholeCount[Label[j]]:
TMP = 90 - i * R_factor
R.append(TMP)
m, n = self.Trans(t, R)
self.axes.plot(m, n, color=Color[j], linewidth=1, alpha=0.6, marker='', label=Label[j])
self.axes.fill(m, n, Color=Color[j], Alpha=0.6)
if (self.Type_cb.isChecked()):
self.Type_cb.setText('Wulf')
list1 = [self.eqan(x) for x in range(15, 90, 15)]
else:
self.Type_cb.setText('Schmidt')
list1 = [self.eqar(x) for x in range(15, 90, 15)]
list2= list1
try:
list2 = [str(x) for x in range(0, int(maxuse + 1), int((maxuse + 1) / 7))]
except(ValueError):
pass
list2.reverse()
self.axes.set_rgrids(list1, list2)
#self.axes.set_thetagrids(range(360 + 90, 0 + 90, -15), [str(x) for x in range(0, 360, 15)])
if (self.legend_cb.isChecked()):
self.axes.legend(bbox_to_anchor=(1.5, 1), loc=2, borderaxespad=0, prop=fontprop) | draw the rose map of multiple samples~ | train | https://github.com/GeoPyTool/GeoPyTool/blob/8c198aa42e4fbdf62fac05d40cbf4d1086328da3/geopytool/Rose.py#L267-L365 | null | class Rose(AppForm):
reference = 'Zhou, J. B., Zeng, Z. X., and Yuan, J. R., 2003, THE DESIGN AND DEVELOPMENT OF THE SOFTWARE STRUCKIT FOR STRUCTURAL GEOLOGY: Journal of Changchun University of Science & Technology, v. 33, no. 3, p. 276-281.'
_df = pd.DataFrame()
_changed = False
xlabel = r''
ylabel = r''
Gap = 10
MultipleRoseName = 'Dip'
SingleRoseName = ['Dip']
def __init__(self, parent=None, df=pd.DataFrame()):
QMainWindow.__init__(self, parent)
self.setWindowTitle('Rose Map')
self._df = df
if (len(df) > 0):
self._changed = True
# print('DataFrame recieved to Rose')
self.create_main_frame()
self.create_status_bar()
def create_main_frame(self):
self.resize(1000,600)
self.main_frame = QWidget()
self.dpi = 128
self.fig = Figure((8.0, 8.0), dpi=self.dpi)
self.fig.subplots_adjust(hspace=0.5, wspace=0.5, left=0.1, bottom=0.1, right=0.6, top=0.9)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self.main_frame)
self.axes = self.fig.add_subplot(111, projection='polar')
#self.axes.set_xlim(-90, 450)
#self.axes.set_ylim(0, 90)
# Create the navigation toolbar, tied to the canvas
self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
# Other GUI controls
self.save_button = QPushButton('&Save')
self.save_button.clicked.connect(self.saveImgFile)
self.draw_button = QPushButton('&Reset')
self.draw_button.clicked.connect(self.Rose)
self.legend_cb = QCheckBox('&Legend')
self.legend_cb.setChecked(True)
self.legend_cb.stateChanged.connect(self.Rose) # int
self.Type_cb = QCheckBox('&Wulf')
self.Type_cb.setChecked(True)
self.Type_cb.stateChanged.connect(self.Rose) # int
if (self.Type_cb.isChecked()):
self.Type_cb.setText('Wulf')
else:
self.Type_cb.setText('Schmidt')
self.Rose_cb = QCheckBox('&Single Rose')
self.Rose_cb.setChecked(True)
self.Rose_cb.stateChanged.connect(self.Rose) # int
if (self.Rose_cb.isChecked()):
self.Rose_cb.setText('Single Rose')
else:
self.Rose_cb.setText('Multiple Rose')
slider_label = QLabel('Step:')
self.slider = QSlider(Qt.Horizontal)
self.slider.setRange(1, 30)
self.slider.setValue(5)
self.slider.setTracking(True)
self.slider.setTickPosition(QSlider.TicksBothSides)
self.slider.valueChanged.connect(self.Rose) # int
self.ChooseItems = ['Strike', 'Dip', 'Dip-Angle']
self.chooser_label = QLabel('Dip')
self.chooser = QSlider(Qt.Horizontal)
self.chooser.setRange(1, 3)
self.chooser.setValue(2)
self.chooser.setTracking(True)
self.chooser.setTickPosition(QSlider.TicksBothSides)
self.chooser.valueChanged.connect(self.Rose) # int
self.chooser_label.setText(self.ChooseItems[self.chooser.value() - 1])
self.MultipleRoseName = self.ChooseItems[self.chooser.value() - 1]
self.SingleRoseName = [(self.ChooseItems[self.chooser.value() - 1])]
#
# Layout with box sizers
#
self.hbox = QHBoxLayout()
for w in [self.save_button, self.draw_button, self.Type_cb, self.Rose_cb,
self.legend_cb, slider_label, self.slider, self.chooser, self.chooser_label]:
self.hbox.addWidget(w)
self.hbox.setAlignment(w, Qt.AlignVCenter)
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.mpl_toolbar)
self.vbox.addWidget(self.canvas)
self.vbox.addLayout(self.hbox)
self.textbox = GrowingTextEdit(self)
self.textbox.setText(self.reference)
self.vbox.addWidget(self.textbox)
self.main_frame.setLayout(self.vbox)
self.setCentralWidget(self.main_frame)
def eqar(self, A):
return (2 ** .5) * 90 * np.sin(np.pi * (90. - A) / (2. * 180.))
def eqan(self, A):
return 90 * np.tan(np.pi * (90. - A) / (2. * 180.))
def getangular(self, A, B, C):
a = np.radians(A)
b = np.radians(B)
c = np.radians(C)
result = np.arctan((np.tan(a)) * np.cos(np.abs(b - c)))
result = np.rad2deg(result)
return result
def Trans(self, S=(0, 100, 110), D=(0, 30, 40)):
a = []
b = []
for i in S:
a.append(np.radians(90 - i))
for i in D:
if (self.Type_cb.isChecked()):
self.Type_cb.setText('Wulf')
b.append(self.eqan(i))
else:
self.Type_cb.setText('Schmidt')
b.append(self.eqar(i))
return (a, b)
def singlerose(self, Width=1, Color=['red']):
'''
draw the rose map of single sample with different items~
'''
self.chooser_label.setText(self.ChooseItems[self.chooser.value() - 1])
self.MultipleRoseName = self.ChooseItems[self.chooser.value() - 1]
self.SingleRoseName = [(self.ChooseItems[self.chooser.value() - 1])]
Name = self.SingleRoseName
self.axes.clear()
# self.axes.set_xlim(-90, 450)
# self.axes.set_ylim(0, 90)
titles = list('NWSE')
titles = ['N', '330', '300', 'W', '240', '210', 'S', '150', '120', 'E', '60', '30']
self.n = len(titles)
self.angles = np.arange(90, 90 + 360, 360.0 / self.n)
self.angles = np.array([90., 120., 150., 180., 210., 240., 270., 300., 330.,
360., 30., 60.])
self.axes.set_thetagrids(self.angles, labels=titles, fontsize=14)
self.raw = self._df
real_max = []
for k in range(len(Name)):
Data = []
S = []
R = []
for i in range(len(self.raw)):
S.append(self.raw.at[i, Name[k]])
s = np.linspace(0, 360, 360 / self.Gap + 1)
t = tuple(s.tolist())
count = []
for i in range(len(t)):
tmp_count = 0
for j in S:
if i < len(t) - 1:
if t[i] < j <= t[i + 1]:
tmp_count += 1
count.append(tmp_count)
count_max = max(count)
real_max.append(count_max)
maxuse = max(real_max)
for k in range(len(Name)):
Data = []
S = []
R = []
for i in range(len(self.raw)):
S.append(self.raw.at[i, Name[k]])
s = np.linspace(0, 360, 360 / self.Gap + 1)
t = tuple(s.tolist())
count = []
for i in range(len(t)):
tmp_count = 0
for j in S:
if i < len(t) - 1:
if t[i] < j <= t[i + 1]:
tmp_count += 1
count.append(tmp_count)
s = np.linspace(0, 360, 360 / self.Gap + 1)
t = tuple(s.tolist())
R_factor = 90 / maxuse
for i in count:
TMP = 90 - i * R_factor
R.append(TMP)
m, n = self.Trans(t, R)
self.axes.plot(m, n, color=Color[k], linewidth=1, alpha=0.6, marker='')
self.axes.fill(m, n, Color=Color[k], Alpha=0.6, )
if (self.Type_cb.isChecked()):
self.Type_cb.setText('Wulf')
list1 = [self.eqan(x) for x in range(15, 90, 15)]
else:
self.Type_cb.setText('Schmidt')
list1 = [self.eqar(x) for x in range(15, 90, 15)]
list2= list1
print(maxuse + 1)
try:
list2 = [str(x) for x in range(0, int(maxuse + 1), int((maxuse + 1.0) / 7.0))]
except(ValueError):
pass
list2.reverse()
self.axes.set_rgrids(list1, list2)
#self.axes.set_thetagrids(range(360 + 90, 0 + 90, -15), [str(x) for x in range(0, 360, 15)])
if (self.legend_cb.isChecked()):
self.axes.legend(bbox_to_anchor=(1.5, 1), loc=2, borderaxespad=0, prop=fontprop)
def Rose(self):
self.Gap = self.slider.value()
self.chooser_label.setText(self.ChooseItems[self.chooser.value() - 1])
self.MultipleRoseName = self.ChooseItems[self.chooser.value() - 1]
self.SingleRoseName = [(self.ChooseItems[self.chooser.value() - 1])]
if (self.Type_cb.isChecked()):
self.Type_cb.setText('Wulf')
else:
self.Type_cb.setText('Schmidt')
if (self.Rose_cb.isChecked()):
self.Rose_cb.setText('Single Rose')
self.singlerose()
else:
self.Rose_cb.setText('Multiple Rose')
self.multirose()
self.canvas.draw()
|
alertot/detectem | detectem/cli.py | get_detection_results | python | def get_detection_results(url, timeout, metadata=False, save_har=False):
plugins = load_plugins()
if not plugins:
raise NoPluginsError('No plugins found')
logger.debug('[+] Starting detection with %(n)d plugins', {'n': len(plugins)})
response = get_response(url, plugins, timeout)
# Save HAR
if save_har:
fd, path = tempfile.mkstemp(suffix='.har')
logger.info(f'Saving HAR file to {path}')
with open(fd, 'w') as f:
json.dump(response['har'], f)
det = Detector(response, plugins, url)
softwares = det.get_results(metadata=metadata)
output = {
'url': url,
'softwares': softwares,
}
return output | Return results from detector.
This function prepares the environment loading the plugins,
getting the response and passing it to the detector.
In case of errors, it raises exceptions to be handled externally. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/cli.py#L73-L106 | [
"def load_plugins():\n \"\"\" Return the list of plugin instances. \"\"\"\n loader = _PluginLoader()\n\n for pkg in PLUGIN_PACKAGES:\n loader.load_plugins(pkg)\n\n return loader.plugins\n",
"def get_response(url, plugins, timeout=SPLASH_TIMEOUT):\n \"\"\"\n Return response with HAR, inlin... | import json
import logging
import sys
import tempfile
from operator import attrgetter
import click
import click_log
from detectem.core import Detector
from detectem.exceptions import DockerStartError, NoPluginsError, SplashError
from detectem.plugin import load_plugins
from detectem.response import get_response
from detectem.settings import CMD_OUTPUT, JSON_OUTPUT, SPLASH_TIMEOUT
from detectem.utils import create_printer
DUMMY_URL = "http://domain.tld"
# Set up logging
logger = logging.getLogger('detectem')
click_log.basic_config(logger)
@click.command()
@click.option(
'--timeout',
default=SPLASH_TIMEOUT,
type=click.INT,
help='Timeout for Splash (in seconds).',
)
@click.option(
'--format',
default=CMD_OUTPUT,
type=click.Choice([CMD_OUTPUT, JSON_OUTPUT]),
help='Set the format of the results.',
)
@click.option(
'--metadata',
default=False,
is_flag=True,
help='Include this flag to return plugin metadata.',
)
@click.option(
'--list-plugins',
is_flag=True,
help='List registered plugins',
)
@click.option(
'--save-har',
is_flag=True,
help='Save har to file',
)
@click_log.simple_verbosity_option(logger, default='info')
@click.argument('url', default=DUMMY_URL, required=True)
def main(timeout, format, metadata, list_plugins, save_har, url):
if not list_plugins and url == DUMMY_URL:
click.echo(click.get_current_context().get_help())
sys.exit(1)
printer = create_printer(format)
try:
if list_plugins:
results = get_plugins(metadata)
else:
results = get_detection_results(url, timeout, metadata, save_har)
except (NoPluginsError, DockerStartError, SplashError) as e:
printer(str(e))
sys.exit(1)
printer(results)
def get_plugins(metadata):
""" Return the registered plugins.
Load and return all registered plugins.
"""
plugins = load_plugins()
if not plugins:
raise NoPluginsError('No plugins found')
results = []
for p in sorted(plugins.get_all(), key=attrgetter('name')):
if metadata:
data = {'name': p.name, 'homepage': p.homepage}
hints = getattr(p, 'hints', [])
if hints:
data['hints'] = hints
results.append(data)
else:
results.append(p.name)
return results
if __name__ == "__main__":
main()
|
alertot/detectem | detectem/cli.py | get_plugins | python | def get_plugins(metadata):
plugins = load_plugins()
if not plugins:
raise NoPluginsError('No plugins found')
results = []
for p in sorted(plugins.get_all(), key=attrgetter('name')):
if metadata:
data = {'name': p.name, 'homepage': p.homepage}
hints = getattr(p, 'hints', [])
if hints:
data['hints'] = hints
results.append(data)
else:
results.append(p.name)
return results | Return the registered plugins.
Load and return all registered plugins. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/cli.py#L109-L128 | [
"def load_plugins():\n \"\"\" Return the list of plugin instances. \"\"\"\n loader = _PluginLoader()\n\n for pkg in PLUGIN_PACKAGES:\n loader.load_plugins(pkg)\n\n return loader.plugins\n"
] | import json
import logging
import sys
import tempfile
from operator import attrgetter
import click
import click_log
from detectem.core import Detector
from detectem.exceptions import DockerStartError, NoPluginsError, SplashError
from detectem.plugin import load_plugins
from detectem.response import get_response
from detectem.settings import CMD_OUTPUT, JSON_OUTPUT, SPLASH_TIMEOUT
from detectem.utils import create_printer
DUMMY_URL = "http://domain.tld"
# Set up logging
logger = logging.getLogger('detectem')
click_log.basic_config(logger)
@click.command()
@click.option(
'--timeout',
default=SPLASH_TIMEOUT,
type=click.INT,
help='Timeout for Splash (in seconds).',
)
@click.option(
'--format',
default=CMD_OUTPUT,
type=click.Choice([CMD_OUTPUT, JSON_OUTPUT]),
help='Set the format of the results.',
)
@click.option(
'--metadata',
default=False,
is_flag=True,
help='Include this flag to return plugin metadata.',
)
@click.option(
'--list-plugins',
is_flag=True,
help='List registered plugins',
)
@click.option(
'--save-har',
is_flag=True,
help='Save har to file',
)
@click_log.simple_verbosity_option(logger, default='info')
@click.argument('url', default=DUMMY_URL, required=True)
def main(timeout, format, metadata, list_plugins, save_har, url):
if not list_plugins and url == DUMMY_URL:
click.echo(click.get_current_context().get_help())
sys.exit(1)
printer = create_printer(format)
try:
if list_plugins:
results = get_plugins(metadata)
else:
results = get_detection_results(url, timeout, metadata, save_har)
except (NoPluginsError, DockerStartError, SplashError) as e:
printer(str(e))
sys.exit(1)
printer(results)
def get_detection_results(url, timeout, metadata=False, save_har=False):
""" Return results from detector.
This function prepares the environment loading the plugins,
getting the response and passing it to the detector.
In case of errors, it raises exceptions to be handled externally.
"""
plugins = load_plugins()
if not plugins:
raise NoPluginsError('No plugins found')
logger.debug('[+] Starting detection with %(n)d plugins', {'n': len(plugins)})
response = get_response(url, plugins, timeout)
# Save HAR
if save_har:
fd, path = tempfile.mkstemp(suffix='.har')
logger.info(f'Saving HAR file to {path}')
with open(fd, 'w') as f:
json.dump(response['har'], f)
det = Detector(response, plugins, url)
softwares = det.get_results(metadata=metadata)
output = {
'url': url,
'softwares': softwares,
}
return output
if __name__ == "__main__":
main()
|
alertot/detectem | detectem/utils.py | get_most_complete_pm | python | def get_most_complete_pm(pms):
if not pms:
return None
selected_version = None
selected_presence = None
for pm in pms:
if pm.version:
if not selected_version:
selected_version = pm
else:
if len(pm.version) > len(selected_version.version):
selected_version = pm
elif pm.presence:
selected_presence = pm
return selected_version or selected_presence | Return plugin match with longer version, if not available
will return plugin match with ``presence=True`` | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/utils.py#L25-L45 | null | import hashlib
import json
import logging
import pprint
import time
from contextlib import contextmanager
import docker
import requests
from detectem.exceptions import DockerStartError
from detectem.settings import (
CMD_OUTPUT,
DOCKER_SPLASH_IMAGE,
JSON_OUTPUT,
SETUP_SPLASH,
SPLASH_MAX_TIMEOUT,
SPLASH_URL,
)
logger = logging.getLogger('detectem')
def docker_error(method):
def run_method(self=None):
try:
method(self)
except docker.errors.DockerException as e:
raise DockerStartError(f'Docker error: {e}')
return run_method
class DockerManager:
"""
Wraps requests to Docker daemon to manage Splash container.
"""
def __init__(self):
try:
self.docker_cli = docker.from_env(version='auto')
self.container_name = 'splash-detectem'
except docker.errors.DockerException:
raise DockerStartError(
"Could not connect to Docker daemon. "
"Please ensure Docker is running."
)
def _get_splash_args(self):
return f'--max-timeout {SPLASH_MAX_TIMEOUT}'
def _get_container(self):
try:
return self.docker_cli.containers.get(self.container_name)
except docker.errors.NotFound:
try:
return self.docker_cli.containers.create(
name=self.container_name,
image=DOCKER_SPLASH_IMAGE,
ports={
'5023/tcp': 5023,
'8050/tcp': 8050,
'8051/tcp': 8051,
},
command=self._get_splash_args(),
)
except docker.errors.ImageNotFound:
raise DockerStartError(
f'Docker image {DOCKER_SPLASH_IMAGE} not found.'
f'Please install it or set an image '
f'using DOCKER_SPLASH_IMAGE environment variable.'
)
@docker_error
def start_container(self):
container = self._get_container()
if container.status != 'running':
try:
container.start()
self._wait_container()
except docker.errors.APIError as e:
raise DockerStartError(
f'There was an error running Splash container: {e.explanation}'
)
def _wait_container(self):
for t in [1, 2, 4, 6, 8, 10]:
try:
requests.get(f'{SPLASH_URL}/_ping')
break
except requests.exceptions.RequestException:
time.sleep(t)
else:
raise DockerStartError(
"Could not connect to started Splash container. "
"See 'docker logs splash-detectem' for more details, "
"or remove the container to try again."
)
@contextmanager
def docker_container():
""" Start the Splash server on a Docker container.
If the container doesn't exist, it is created and named 'splash-detectem'.
"""
if SETUP_SPLASH:
dm = DockerManager()
dm.start_container()
try:
requests.post(f'{SPLASH_URL}/_gc')
except requests.exceptions.RequestException:
pass
yield
def create_printer(oformat):
if oformat == CMD_OUTPUT:
return pprint.pprint
elif oformat == JSON_OUTPUT:
def json_printer(data):
print(json.dumps(data))
return json_printer
def get_url(entry):
""" Return URL from response if it was received otherwise requested URL. """
try:
return entry['response']['url']
except KeyError:
return entry['request']['url']
def get_response_body(entry):
return entry['response']['content']['text']
def get_version_via_file_hashes(plugin, entry):
file_hashes = getattr(plugin, 'file_hashes', {})
if not file_hashes:
return
url = get_url(entry)
body = get_response_body(entry).encode('utf-8')
for file, hash_dict in file_hashes.items():
if file not in url:
continue
m = hashlib.sha256()
m.update(body)
h = m.hexdigest()
for version, version_hash in hash_dict.items():
if h == version_hash:
return version
|
alertot/detectem | detectem/utils.py | docker_container | python | def docker_container():
if SETUP_SPLASH:
dm = DockerManager()
dm.start_container()
try:
requests.post(f'{SPLASH_URL}/_gc')
except requests.exceptions.RequestException:
pass
yield | Start the Splash server on a Docker container.
If the container doesn't exist, it is created and named 'splash-detectem'. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/utils.py#L126-L140 | [
"def run_method(self=None):\n try:\n method(self)\n except docker.errors.DockerException as e:\n raise DockerStartError(f'Docker error: {e}')\n"
] | import hashlib
import json
import logging
import pprint
import time
from contextlib import contextmanager
import docker
import requests
from detectem.exceptions import DockerStartError
from detectem.settings import (
CMD_OUTPUT,
DOCKER_SPLASH_IMAGE,
JSON_OUTPUT,
SETUP_SPLASH,
SPLASH_MAX_TIMEOUT,
SPLASH_URL,
)
logger = logging.getLogger('detectem')
def get_most_complete_pm(pms):
""" Return plugin match with longer version, if not available
will return plugin match with ``presence=True``
"""
if not pms:
return None
selected_version = None
selected_presence = None
for pm in pms:
if pm.version:
if not selected_version:
selected_version = pm
else:
if len(pm.version) > len(selected_version.version):
selected_version = pm
elif pm.presence:
selected_presence = pm
return selected_version or selected_presence
def docker_error(method):
def run_method(self=None):
try:
method(self)
except docker.errors.DockerException as e:
raise DockerStartError(f'Docker error: {e}')
return run_method
class DockerManager:
"""
Wraps requests to Docker daemon to manage Splash container.
"""
def __init__(self):
try:
self.docker_cli = docker.from_env(version='auto')
self.container_name = 'splash-detectem'
except docker.errors.DockerException:
raise DockerStartError(
"Could not connect to Docker daemon. "
"Please ensure Docker is running."
)
def _get_splash_args(self):
return f'--max-timeout {SPLASH_MAX_TIMEOUT}'
def _get_container(self):
try:
return self.docker_cli.containers.get(self.container_name)
except docker.errors.NotFound:
try:
return self.docker_cli.containers.create(
name=self.container_name,
image=DOCKER_SPLASH_IMAGE,
ports={
'5023/tcp': 5023,
'8050/tcp': 8050,
'8051/tcp': 8051,
},
command=self._get_splash_args(),
)
except docker.errors.ImageNotFound:
raise DockerStartError(
f'Docker image {DOCKER_SPLASH_IMAGE} not found.'
f'Please install it or set an image '
f'using DOCKER_SPLASH_IMAGE environment variable.'
)
@docker_error
def start_container(self):
container = self._get_container()
if container.status != 'running':
try:
container.start()
self._wait_container()
except docker.errors.APIError as e:
raise DockerStartError(
f'There was an error running Splash container: {e.explanation}'
)
def _wait_container(self):
for t in [1, 2, 4, 6, 8, 10]:
try:
requests.get(f'{SPLASH_URL}/_ping')
break
except requests.exceptions.RequestException:
time.sleep(t)
else:
raise DockerStartError(
"Could not connect to started Splash container. "
"See 'docker logs splash-detectem' for more details, "
"or remove the container to try again."
)
@contextmanager
def create_printer(oformat):
if oformat == CMD_OUTPUT:
return pprint.pprint
elif oformat == JSON_OUTPUT:
def json_printer(data):
print(json.dumps(data))
return json_printer
def get_url(entry):
""" Return URL from response if it was received otherwise requested URL. """
try:
return entry['response']['url']
except KeyError:
return entry['request']['url']
def get_response_body(entry):
return entry['response']['content']['text']
def get_version_via_file_hashes(plugin, entry):
file_hashes = getattr(plugin, 'file_hashes', {})
if not file_hashes:
return
url = get_url(entry)
body = get_response_body(entry).encode('utf-8')
for file, hash_dict in file_hashes.items():
if file not in url:
continue
m = hashlib.sha256()
m.update(body)
h = m.hexdigest()
for version, version_hash in hash_dict.items():
if h == version_hash:
return version
|
alertot/detectem | detectem/response.py | is_url_allowed | python | def is_url_allowed(url):
blacklist = [
r'\.ttf', r'\.woff', r'fonts\.googleapis\.com', r'\.png', r'\.jpe?g', r'\.gif',
r'\.svg'
]
for ft in blacklist:
if re.search(ft, url):
return False
return True | Return ``True`` if ``url`` is not in ``blacklist``.
:rtype: bool | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L21-L36 | null | import base64
import json
import logging
import re
import urllib.parse
from string import Template
import pkg_resources
import requests
from detectem.exceptions import SplashError
from detectem.settings import SPLASH_TIMEOUT, SPLASH_URL
from detectem.utils import docker_container
DEFAULT_CHARSET = 'iso-8859-1'
ERROR_STATUS_CODES = [400, 504]
logger = logging.getLogger('detectem')
def is_valid_mimetype(response):
""" Return ``True`` if the mimetype is not blacklisted.
:rtype: bool
"""
blacklist = [
'image/',
]
mimetype = response.get('mimeType')
if not mimetype:
return True
for bw in blacklist:
if bw in mimetype:
return False
return True
def get_charset(response):
""" Return charset from ``response`` or default charset.
:rtype: str
"""
# Set default charset
charset = DEFAULT_CHARSET
m = re.findall(r';charset=(.*)', response.get('mimeType', ''))
if m:
charset = m[0]
return charset
def create_lua_script(plugins):
""" Return script template filled up with plugin javascript data.
:rtype: str
"""
lua_template = pkg_resources.resource_string('detectem', 'script.lua')
template = Template(lua_template.decode('utf-8'))
javascript_data = to_javascript_data(plugins)
return template.substitute(js_data=json.dumps(javascript_data))
def to_javascript_data(plugins):
"""
Return a dictionary with all JavaScript matchers. Quotes are escaped.
:rtype: dict
"""
def escape(v):
return re.sub(r'"', r'\\"', v)
def dom_matchers(p):
dom_matchers = p.get_matchers('dom')
escaped_dom_matchers = []
for dm in dom_matchers:
check_statement, version_statement = dm
escaped_dom_matchers.append({
'check_statement': escape(check_statement),
# Escape '' and not None
'version_statement': escape(version_statement or ''),
})
return escaped_dom_matchers
return [{'name': p.name, 'matchers': dom_matchers(p)}
for p in plugins.with_dom_matchers()]
def get_response(url, plugins, timeout=SPLASH_TIMEOUT):
"""
Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict
"""
lua_script = create_lua_script(plugins)
lua = urllib.parse.quote_plus(lua_script)
page_url = f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}'
try:
with docker_container():
logger.debug('[+] Sending request to Splash instance')
res = requests.get(page_url)
except requests.exceptions.ConnectionError:
raise SplashError("Could not connect to Splash server {}".format(SPLASH_URL))
logger.debug('[+] Response received')
json_data = res.json()
if res.status_code in ERROR_STATUS_CODES:
raise SplashError(get_splash_error(json_data))
softwares = json_data['softwares']
scripts = json_data['scripts'].values()
har = get_valid_har(json_data['har'])
js_error = get_evaljs_error(json_data)
if js_error:
logger.debug('[+] WARNING: failed to eval JS matchers: %(n)s', {'n': js_error})
else:
logger.debug('[+] Detected %(n)d softwares from the DOM', {'n': len(softwares)})
logger.debug('[+] Detected %(n)d scripts from the DOM', {'n': len(scripts)})
logger.debug('[+] Final HAR has %(n)d valid entries', {'n': len(har)})
return {'har': har, 'scripts': scripts, 'softwares': softwares}
def get_splash_error(json_data):
msg = json_data['description']
if 'info' in json_data and 'error' in json_data['info']:
error = json_data['info']['error']
if error.startswith('http'):
msg = 'Request to site failed with error code {0}'.format(error)
elif error.startswith('network'):
# see http://doc.qt.io/qt-5/qnetworkreply.html
qt_errors = {
'network1': 'ConnectionRefusedError',
'network2': 'RemoteHostClosedError',
'network3': 'HostNotFoundError',
'network4': 'TimeoutError',
'network5': 'OperationCanceledError',
'network6': 'SslHandshakeFailedError',
}
error = qt_errors.get(error, "error code {0}".format(error))
msg = 'Request to site failed with {0}'.format(error)
else:
msg = '{0}: {1}'.format(msg, error)
return msg
def get_evaljs_error(json_data):
error = None
if 'errors' in json_data and 'evaljs' in json_data['errors']:
res = json_data['errors']['evaljs']
if isinstance(res, str):
m = re.search(r"'message': '(.*?)'[,}]", res)
if m:
error = bytes(m.group(1), 'utf-8').decode('unicode_escape')
return error
def get_valid_har(har_data):
""" Return list of valid HAR entries.
:rtype: list
"""
new_entries = []
entries = har_data.get('log', {}).get('entries', [])
logger.debug('[+] Detected %(n)d entries in HAR', {'n': len(entries)})
for entry in entries:
url = entry['request']['url']
if not is_url_allowed(url):
continue
response = entry['response']['content']
if not is_valid_mimetype(response):
continue
if response.get('text'):
charset = get_charset(response)
response['text'] = base64.b64decode(response['text']).decode(charset)
else:
response['text'] = ''
new_entries.append(entry)
logger.debug('[+] Added URL: %(url)s ...', {'url': url[:100]})
return new_entries
|
alertot/detectem | detectem/response.py | is_valid_mimetype | python | def is_valid_mimetype(response):
blacklist = [
'image/',
]
mimetype = response.get('mimeType')
if not mimetype:
return True
for bw in blacklist:
if bw in mimetype:
return False
return True | Return ``True`` if the mimetype is not blacklisted.
:rtype: bool | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L39-L57 | null | import base64
import json
import logging
import re
import urllib.parse
from string import Template
import pkg_resources
import requests
from detectem.exceptions import SplashError
from detectem.settings import SPLASH_TIMEOUT, SPLASH_URL
from detectem.utils import docker_container
DEFAULT_CHARSET = 'iso-8859-1'
ERROR_STATUS_CODES = [400, 504]
logger = logging.getLogger('detectem')
def is_url_allowed(url):
""" Return ``True`` if ``url`` is not in ``blacklist``.
:rtype: bool
"""
blacklist = [
r'\.ttf', r'\.woff', r'fonts\.googleapis\.com', r'\.png', r'\.jpe?g', r'\.gif',
r'\.svg'
]
for ft in blacklist:
if re.search(ft, url):
return False
return True
def get_charset(response):
""" Return charset from ``response`` or default charset.
:rtype: str
"""
# Set default charset
charset = DEFAULT_CHARSET
m = re.findall(r';charset=(.*)', response.get('mimeType', ''))
if m:
charset = m[0]
return charset
def create_lua_script(plugins):
""" Return script template filled up with plugin javascript data.
:rtype: str
"""
lua_template = pkg_resources.resource_string('detectem', 'script.lua')
template = Template(lua_template.decode('utf-8'))
javascript_data = to_javascript_data(plugins)
return template.substitute(js_data=json.dumps(javascript_data))
def to_javascript_data(plugins):
"""
Return a dictionary with all JavaScript matchers. Quotes are escaped.
:rtype: dict
"""
def escape(v):
return re.sub(r'"', r'\\"', v)
def dom_matchers(p):
dom_matchers = p.get_matchers('dom')
escaped_dom_matchers = []
for dm in dom_matchers:
check_statement, version_statement = dm
escaped_dom_matchers.append({
'check_statement': escape(check_statement),
# Escape '' and not None
'version_statement': escape(version_statement or ''),
})
return escaped_dom_matchers
return [{'name': p.name, 'matchers': dom_matchers(p)}
for p in plugins.with_dom_matchers()]
def get_response(url, plugins, timeout=SPLASH_TIMEOUT):
"""
Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict
"""
lua_script = create_lua_script(plugins)
lua = urllib.parse.quote_plus(lua_script)
page_url = f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}'
try:
with docker_container():
logger.debug('[+] Sending request to Splash instance')
res = requests.get(page_url)
except requests.exceptions.ConnectionError:
raise SplashError("Could not connect to Splash server {}".format(SPLASH_URL))
logger.debug('[+] Response received')
json_data = res.json()
if res.status_code in ERROR_STATUS_CODES:
raise SplashError(get_splash_error(json_data))
softwares = json_data['softwares']
scripts = json_data['scripts'].values()
har = get_valid_har(json_data['har'])
js_error = get_evaljs_error(json_data)
if js_error:
logger.debug('[+] WARNING: failed to eval JS matchers: %(n)s', {'n': js_error})
else:
logger.debug('[+] Detected %(n)d softwares from the DOM', {'n': len(softwares)})
logger.debug('[+] Detected %(n)d scripts from the DOM', {'n': len(scripts)})
logger.debug('[+] Final HAR has %(n)d valid entries', {'n': len(har)})
return {'har': har, 'scripts': scripts, 'softwares': softwares}
def get_splash_error(json_data):
msg = json_data['description']
if 'info' in json_data and 'error' in json_data['info']:
error = json_data['info']['error']
if error.startswith('http'):
msg = 'Request to site failed with error code {0}'.format(error)
elif error.startswith('network'):
# see http://doc.qt.io/qt-5/qnetworkreply.html
qt_errors = {
'network1': 'ConnectionRefusedError',
'network2': 'RemoteHostClosedError',
'network3': 'HostNotFoundError',
'network4': 'TimeoutError',
'network5': 'OperationCanceledError',
'network6': 'SslHandshakeFailedError',
}
error = qt_errors.get(error, "error code {0}".format(error))
msg = 'Request to site failed with {0}'.format(error)
else:
msg = '{0}: {1}'.format(msg, error)
return msg
def get_evaljs_error(json_data):
error = None
if 'errors' in json_data and 'evaljs' in json_data['errors']:
res = json_data['errors']['evaljs']
if isinstance(res, str):
m = re.search(r"'message': '(.*?)'[,}]", res)
if m:
error = bytes(m.group(1), 'utf-8').decode('unicode_escape')
return error
def get_valid_har(har_data):
""" Return list of valid HAR entries.
:rtype: list
"""
new_entries = []
entries = har_data.get('log', {}).get('entries', [])
logger.debug('[+] Detected %(n)d entries in HAR', {'n': len(entries)})
for entry in entries:
url = entry['request']['url']
if not is_url_allowed(url):
continue
response = entry['response']['content']
if not is_valid_mimetype(response):
continue
if response.get('text'):
charset = get_charset(response)
response['text'] = base64.b64decode(response['text']).decode(charset)
else:
response['text'] = ''
new_entries.append(entry)
logger.debug('[+] Added URL: %(url)s ...', {'url': url[:100]})
return new_entries
|
alertot/detectem | detectem/response.py | get_charset | python | def get_charset(response):
# Set default charset
charset = DEFAULT_CHARSET
m = re.findall(r';charset=(.*)', response.get('mimeType', ''))
if m:
charset = m[0]
return charset | Return charset from ``response`` or default charset.
:rtype: str | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L60-L73 | null | import base64
import json
import logging
import re
import urllib.parse
from string import Template
import pkg_resources
import requests
from detectem.exceptions import SplashError
from detectem.settings import SPLASH_TIMEOUT, SPLASH_URL
from detectem.utils import docker_container
DEFAULT_CHARSET = 'iso-8859-1'
ERROR_STATUS_CODES = [400, 504]
logger = logging.getLogger('detectem')
def is_url_allowed(url):
""" Return ``True`` if ``url`` is not in ``blacklist``.
:rtype: bool
"""
blacklist = [
r'\.ttf', r'\.woff', r'fonts\.googleapis\.com', r'\.png', r'\.jpe?g', r'\.gif',
r'\.svg'
]
for ft in blacklist:
if re.search(ft, url):
return False
return True
def is_valid_mimetype(response):
""" Return ``True`` if the mimetype is not blacklisted.
:rtype: bool
"""
blacklist = [
'image/',
]
mimetype = response.get('mimeType')
if not mimetype:
return True
for bw in blacklist:
if bw in mimetype:
return False
return True
def create_lua_script(plugins):
""" Return script template filled up with plugin javascript data.
:rtype: str
"""
lua_template = pkg_resources.resource_string('detectem', 'script.lua')
template = Template(lua_template.decode('utf-8'))
javascript_data = to_javascript_data(plugins)
return template.substitute(js_data=json.dumps(javascript_data))
def to_javascript_data(plugins):
"""
Return a dictionary with all JavaScript matchers. Quotes are escaped.
:rtype: dict
"""
def escape(v):
return re.sub(r'"', r'\\"', v)
def dom_matchers(p):
dom_matchers = p.get_matchers('dom')
escaped_dom_matchers = []
for dm in dom_matchers:
check_statement, version_statement = dm
escaped_dom_matchers.append({
'check_statement': escape(check_statement),
# Escape '' and not None
'version_statement': escape(version_statement or ''),
})
return escaped_dom_matchers
return [{'name': p.name, 'matchers': dom_matchers(p)}
for p in plugins.with_dom_matchers()]
def get_response(url, plugins, timeout=SPLASH_TIMEOUT):
"""
Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict
"""
lua_script = create_lua_script(plugins)
lua = urllib.parse.quote_plus(lua_script)
page_url = f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}'
try:
with docker_container():
logger.debug('[+] Sending request to Splash instance')
res = requests.get(page_url)
except requests.exceptions.ConnectionError:
raise SplashError("Could not connect to Splash server {}".format(SPLASH_URL))
logger.debug('[+] Response received')
json_data = res.json()
if res.status_code in ERROR_STATUS_CODES:
raise SplashError(get_splash_error(json_data))
softwares = json_data['softwares']
scripts = json_data['scripts'].values()
har = get_valid_har(json_data['har'])
js_error = get_evaljs_error(json_data)
if js_error:
logger.debug('[+] WARNING: failed to eval JS matchers: %(n)s', {'n': js_error})
else:
logger.debug('[+] Detected %(n)d softwares from the DOM', {'n': len(softwares)})
logger.debug('[+] Detected %(n)d scripts from the DOM', {'n': len(scripts)})
logger.debug('[+] Final HAR has %(n)d valid entries', {'n': len(har)})
return {'har': har, 'scripts': scripts, 'softwares': softwares}
def get_splash_error(json_data):
msg = json_data['description']
if 'info' in json_data and 'error' in json_data['info']:
error = json_data['info']['error']
if error.startswith('http'):
msg = 'Request to site failed with error code {0}'.format(error)
elif error.startswith('network'):
# see http://doc.qt.io/qt-5/qnetworkreply.html
qt_errors = {
'network1': 'ConnectionRefusedError',
'network2': 'RemoteHostClosedError',
'network3': 'HostNotFoundError',
'network4': 'TimeoutError',
'network5': 'OperationCanceledError',
'network6': 'SslHandshakeFailedError',
}
error = qt_errors.get(error, "error code {0}".format(error))
msg = 'Request to site failed with {0}'.format(error)
else:
msg = '{0}: {1}'.format(msg, error)
return msg
def get_evaljs_error(json_data):
error = None
if 'errors' in json_data and 'evaljs' in json_data['errors']:
res = json_data['errors']['evaljs']
if isinstance(res, str):
m = re.search(r"'message': '(.*?)'[,}]", res)
if m:
error = bytes(m.group(1), 'utf-8').decode('unicode_escape')
return error
def get_valid_har(har_data):
""" Return list of valid HAR entries.
:rtype: list
"""
new_entries = []
entries = har_data.get('log', {}).get('entries', [])
logger.debug('[+] Detected %(n)d entries in HAR', {'n': len(entries)})
for entry in entries:
url = entry['request']['url']
if not is_url_allowed(url):
continue
response = entry['response']['content']
if not is_valid_mimetype(response):
continue
if response.get('text'):
charset = get_charset(response)
response['text'] = base64.b64decode(response['text']).decode(charset)
else:
response['text'] = ''
new_entries.append(entry)
logger.debug('[+] Added URL: %(url)s ...', {'url': url[:100]})
return new_entries
|
alertot/detectem | detectem/response.py | create_lua_script | python | def create_lua_script(plugins):
lua_template = pkg_resources.resource_string('detectem', 'script.lua')
template = Template(lua_template.decode('utf-8'))
javascript_data = to_javascript_data(plugins)
return template.substitute(js_data=json.dumps(javascript_data)) | Return script template filled up with plugin javascript data.
:rtype: str | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L76-L87 | [
"def to_javascript_data(plugins):\n \"\"\"\n Return a dictionary with all JavaScript matchers. Quotes are escaped.\n\n :rtype: dict\n\n \"\"\"\n\n def escape(v):\n return re.sub(r'\"', r'\\\\\"', v)\n\n def dom_matchers(p):\n dom_matchers = p.get_matchers('dom')\n escaped_dom_... | import base64
import json
import logging
import re
import urllib.parse
from string import Template
import pkg_resources
import requests
from detectem.exceptions import SplashError
from detectem.settings import SPLASH_TIMEOUT, SPLASH_URL
from detectem.utils import docker_container
DEFAULT_CHARSET = 'iso-8859-1'
ERROR_STATUS_CODES = [400, 504]
logger = logging.getLogger('detectem')
def is_url_allowed(url):
""" Return ``True`` if ``url`` is not in ``blacklist``.
:rtype: bool
"""
blacklist = [
r'\.ttf', r'\.woff', r'fonts\.googleapis\.com', r'\.png', r'\.jpe?g', r'\.gif',
r'\.svg'
]
for ft in blacklist:
if re.search(ft, url):
return False
return True
def is_valid_mimetype(response):
""" Return ``True`` if the mimetype is not blacklisted.
:rtype: bool
"""
blacklist = [
'image/',
]
mimetype = response.get('mimeType')
if not mimetype:
return True
for bw in blacklist:
if bw in mimetype:
return False
return True
def get_charset(response):
""" Return charset from ``response`` or default charset.
:rtype: str
"""
# Set default charset
charset = DEFAULT_CHARSET
m = re.findall(r';charset=(.*)', response.get('mimeType', ''))
if m:
charset = m[0]
return charset
def to_javascript_data(plugins):
"""
Return a dictionary with all JavaScript matchers. Quotes are escaped.
:rtype: dict
"""
def escape(v):
return re.sub(r'"', r'\\"', v)
def dom_matchers(p):
dom_matchers = p.get_matchers('dom')
escaped_dom_matchers = []
for dm in dom_matchers:
check_statement, version_statement = dm
escaped_dom_matchers.append({
'check_statement': escape(check_statement),
# Escape '' and not None
'version_statement': escape(version_statement or ''),
})
return escaped_dom_matchers
return [{'name': p.name, 'matchers': dom_matchers(p)}
for p in plugins.with_dom_matchers()]
def get_response(url, plugins, timeout=SPLASH_TIMEOUT):
"""
Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict
"""
lua_script = create_lua_script(plugins)
lua = urllib.parse.quote_plus(lua_script)
page_url = f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}'
try:
with docker_container():
logger.debug('[+] Sending request to Splash instance')
res = requests.get(page_url)
except requests.exceptions.ConnectionError:
raise SplashError("Could not connect to Splash server {}".format(SPLASH_URL))
logger.debug('[+] Response received')
json_data = res.json()
if res.status_code in ERROR_STATUS_CODES:
raise SplashError(get_splash_error(json_data))
softwares = json_data['softwares']
scripts = json_data['scripts'].values()
har = get_valid_har(json_data['har'])
js_error = get_evaljs_error(json_data)
if js_error:
logger.debug('[+] WARNING: failed to eval JS matchers: %(n)s', {'n': js_error})
else:
logger.debug('[+] Detected %(n)d softwares from the DOM', {'n': len(softwares)})
logger.debug('[+] Detected %(n)d scripts from the DOM', {'n': len(scripts)})
logger.debug('[+] Final HAR has %(n)d valid entries', {'n': len(har)})
return {'har': har, 'scripts': scripts, 'softwares': softwares}
def get_splash_error(json_data):
msg = json_data['description']
if 'info' in json_data and 'error' in json_data['info']:
error = json_data['info']['error']
if error.startswith('http'):
msg = 'Request to site failed with error code {0}'.format(error)
elif error.startswith('network'):
# see http://doc.qt.io/qt-5/qnetworkreply.html
qt_errors = {
'network1': 'ConnectionRefusedError',
'network2': 'RemoteHostClosedError',
'network3': 'HostNotFoundError',
'network4': 'TimeoutError',
'network5': 'OperationCanceledError',
'network6': 'SslHandshakeFailedError',
}
error = qt_errors.get(error, "error code {0}".format(error))
msg = 'Request to site failed with {0}'.format(error)
else:
msg = '{0}: {1}'.format(msg, error)
return msg
def get_evaljs_error(json_data):
error = None
if 'errors' in json_data and 'evaljs' in json_data['errors']:
res = json_data['errors']['evaljs']
if isinstance(res, str):
m = re.search(r"'message': '(.*?)'[,}]", res)
if m:
error = bytes(m.group(1), 'utf-8').decode('unicode_escape')
return error
def get_valid_har(har_data):
""" Return list of valid HAR entries.
:rtype: list
"""
new_entries = []
entries = har_data.get('log', {}).get('entries', [])
logger.debug('[+] Detected %(n)d entries in HAR', {'n': len(entries)})
for entry in entries:
url = entry['request']['url']
if not is_url_allowed(url):
continue
response = entry['response']['content']
if not is_valid_mimetype(response):
continue
if response.get('text'):
charset = get_charset(response)
response['text'] = base64.b64decode(response['text']).decode(charset)
else:
response['text'] = ''
new_entries.append(entry)
logger.debug('[+] Added URL: %(url)s ...', {'url': url[:100]})
return new_entries
|
alertot/detectem | detectem/response.py | to_javascript_data | python | def to_javascript_data(plugins):
def escape(v):
return re.sub(r'"', r'\\"', v)
def dom_matchers(p):
dom_matchers = p.get_matchers('dom')
escaped_dom_matchers = []
for dm in dom_matchers:
check_statement, version_statement = dm
escaped_dom_matchers.append({
'check_statement': escape(check_statement),
# Escape '' and not None
'version_statement': escape(version_statement or ''),
})
return escaped_dom_matchers
return [{'name': p.name, 'matchers': dom_matchers(p)}
for p in plugins.with_dom_matchers()] | Return a dictionary with all JavaScript matchers. Quotes are escaped.
:rtype: dict | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L90-L117 | null | import base64
import json
import logging
import re
import urllib.parse
from string import Template
import pkg_resources
import requests
from detectem.exceptions import SplashError
from detectem.settings import SPLASH_TIMEOUT, SPLASH_URL
from detectem.utils import docker_container
DEFAULT_CHARSET = 'iso-8859-1'
ERROR_STATUS_CODES = [400, 504]
logger = logging.getLogger('detectem')
def is_url_allowed(url):
""" Return ``True`` if ``url`` is not in ``blacklist``.
:rtype: bool
"""
blacklist = [
r'\.ttf', r'\.woff', r'fonts\.googleapis\.com', r'\.png', r'\.jpe?g', r'\.gif',
r'\.svg'
]
for ft in blacklist:
if re.search(ft, url):
return False
return True
def is_valid_mimetype(response):
""" Return ``True`` if the mimetype is not blacklisted.
:rtype: bool
"""
blacklist = [
'image/',
]
mimetype = response.get('mimeType')
if not mimetype:
return True
for bw in blacklist:
if bw in mimetype:
return False
return True
def get_charset(response):
""" Return charset from ``response`` or default charset.
:rtype: str
"""
# Set default charset
charset = DEFAULT_CHARSET
m = re.findall(r';charset=(.*)', response.get('mimeType', ''))
if m:
charset = m[0]
return charset
def create_lua_script(plugins):
""" Return script template filled up with plugin javascript data.
:rtype: str
"""
lua_template = pkg_resources.resource_string('detectem', 'script.lua')
template = Template(lua_template.decode('utf-8'))
javascript_data = to_javascript_data(plugins)
return template.substitute(js_data=json.dumps(javascript_data))
def get_response(url, plugins, timeout=SPLASH_TIMEOUT):
"""
Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict
"""
lua_script = create_lua_script(plugins)
lua = urllib.parse.quote_plus(lua_script)
page_url = f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}'
try:
with docker_container():
logger.debug('[+] Sending request to Splash instance')
res = requests.get(page_url)
except requests.exceptions.ConnectionError:
raise SplashError("Could not connect to Splash server {}".format(SPLASH_URL))
logger.debug('[+] Response received')
json_data = res.json()
if res.status_code in ERROR_STATUS_CODES:
raise SplashError(get_splash_error(json_data))
softwares = json_data['softwares']
scripts = json_data['scripts'].values()
har = get_valid_har(json_data['har'])
js_error = get_evaljs_error(json_data)
if js_error:
logger.debug('[+] WARNING: failed to eval JS matchers: %(n)s', {'n': js_error})
else:
logger.debug('[+] Detected %(n)d softwares from the DOM', {'n': len(softwares)})
logger.debug('[+] Detected %(n)d scripts from the DOM', {'n': len(scripts)})
logger.debug('[+] Final HAR has %(n)d valid entries', {'n': len(har)})
return {'har': har, 'scripts': scripts, 'softwares': softwares}
def get_splash_error(json_data):
msg = json_data['description']
if 'info' in json_data and 'error' in json_data['info']:
error = json_data['info']['error']
if error.startswith('http'):
msg = 'Request to site failed with error code {0}'.format(error)
elif error.startswith('network'):
# see http://doc.qt.io/qt-5/qnetworkreply.html
qt_errors = {
'network1': 'ConnectionRefusedError',
'network2': 'RemoteHostClosedError',
'network3': 'HostNotFoundError',
'network4': 'TimeoutError',
'network5': 'OperationCanceledError',
'network6': 'SslHandshakeFailedError',
}
error = qt_errors.get(error, "error code {0}".format(error))
msg = 'Request to site failed with {0}'.format(error)
else:
msg = '{0}: {1}'.format(msg, error)
return msg
def get_evaljs_error(json_data):
error = None
if 'errors' in json_data and 'evaljs' in json_data['errors']:
res = json_data['errors']['evaljs']
if isinstance(res, str):
m = re.search(r"'message': '(.*?)'[,}]", res)
if m:
error = bytes(m.group(1), 'utf-8').decode('unicode_escape')
return error
def get_valid_har(har_data):
""" Return list of valid HAR entries.
:rtype: list
"""
new_entries = []
entries = har_data.get('log', {}).get('entries', [])
logger.debug('[+] Detected %(n)d entries in HAR', {'n': len(entries)})
for entry in entries:
url = entry['request']['url']
if not is_url_allowed(url):
continue
response = entry['response']['content']
if not is_valid_mimetype(response):
continue
if response.get('text'):
charset = get_charset(response)
response['text'] = base64.b64decode(response['text']).decode(charset)
else:
response['text'] = ''
new_entries.append(entry)
logger.debug('[+] Added URL: %(url)s ...', {'url': url[:100]})
return new_entries
|
alertot/detectem | detectem/response.py | get_response | python | def get_response(url, plugins, timeout=SPLASH_TIMEOUT):
lua_script = create_lua_script(plugins)
lua = urllib.parse.quote_plus(lua_script)
page_url = f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}'
try:
with docker_container():
logger.debug('[+] Sending request to Splash instance')
res = requests.get(page_url)
except requests.exceptions.ConnectionError:
raise SplashError("Could not connect to Splash server {}".format(SPLASH_URL))
logger.debug('[+] Response received')
json_data = res.json()
if res.status_code in ERROR_STATUS_CODES:
raise SplashError(get_splash_error(json_data))
softwares = json_data['softwares']
scripts = json_data['scripts'].values()
har = get_valid_har(json_data['har'])
js_error = get_evaljs_error(json_data)
if js_error:
logger.debug('[+] WARNING: failed to eval JS matchers: %(n)s', {'n': js_error})
else:
logger.debug('[+] Detected %(n)d softwares from the DOM', {'n': len(softwares)})
logger.debug('[+] Detected %(n)d scripts from the DOM', {'n': len(scripts)})
logger.debug('[+] Final HAR has %(n)d valid entries', {'n': len(har)})
return {'har': har, 'scripts': scripts, 'softwares': softwares} | Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L120-L157 | [
"def create_lua_script(plugins):\n \"\"\" Return script template filled up with plugin javascript data.\n\n :rtype: str\n\n \"\"\"\n lua_template = pkg_resources.resource_string('detectem', 'script.lua')\n template = Template(lua_template.decode('utf-8'))\n\n javascript_data = to_javascript_data(p... | import base64
import json
import logging
import re
import urllib.parse
from string import Template
import pkg_resources
import requests
from detectem.exceptions import SplashError
from detectem.settings import SPLASH_TIMEOUT, SPLASH_URL
from detectem.utils import docker_container
DEFAULT_CHARSET = 'iso-8859-1'
ERROR_STATUS_CODES = [400, 504]
logger = logging.getLogger('detectem')
def is_url_allowed(url):
""" Return ``True`` if ``url`` is not in ``blacklist``.
:rtype: bool
"""
blacklist = [
r'\.ttf', r'\.woff', r'fonts\.googleapis\.com', r'\.png', r'\.jpe?g', r'\.gif',
r'\.svg'
]
for ft in blacklist:
if re.search(ft, url):
return False
return True
def is_valid_mimetype(response):
""" Return ``True`` if the mimetype is not blacklisted.
:rtype: bool
"""
blacklist = [
'image/',
]
mimetype = response.get('mimeType')
if not mimetype:
return True
for bw in blacklist:
if bw in mimetype:
return False
return True
def get_charset(response):
""" Return charset from ``response`` or default charset.
:rtype: str
"""
# Set default charset
charset = DEFAULT_CHARSET
m = re.findall(r';charset=(.*)', response.get('mimeType', ''))
if m:
charset = m[0]
return charset
def create_lua_script(plugins):
""" Return script template filled up with plugin javascript data.
:rtype: str
"""
lua_template = pkg_resources.resource_string('detectem', 'script.lua')
template = Template(lua_template.decode('utf-8'))
javascript_data = to_javascript_data(plugins)
return template.substitute(js_data=json.dumps(javascript_data))
def to_javascript_data(plugins):
"""
Return a dictionary with all JavaScript matchers. Quotes are escaped.
:rtype: dict
"""
def escape(v):
return re.sub(r'"', r'\\"', v)
def dom_matchers(p):
dom_matchers = p.get_matchers('dom')
escaped_dom_matchers = []
for dm in dom_matchers:
check_statement, version_statement = dm
escaped_dom_matchers.append({
'check_statement': escape(check_statement),
# Escape '' and not None
'version_statement': escape(version_statement or ''),
})
return escaped_dom_matchers
return [{'name': p.name, 'matchers': dom_matchers(p)}
for p in plugins.with_dom_matchers()]
def get_splash_error(json_data):
msg = json_data['description']
if 'info' in json_data and 'error' in json_data['info']:
error = json_data['info']['error']
if error.startswith('http'):
msg = 'Request to site failed with error code {0}'.format(error)
elif error.startswith('network'):
# see http://doc.qt.io/qt-5/qnetworkreply.html
qt_errors = {
'network1': 'ConnectionRefusedError',
'network2': 'RemoteHostClosedError',
'network3': 'HostNotFoundError',
'network4': 'TimeoutError',
'network5': 'OperationCanceledError',
'network6': 'SslHandshakeFailedError',
}
error = qt_errors.get(error, "error code {0}".format(error))
msg = 'Request to site failed with {0}'.format(error)
else:
msg = '{0}: {1}'.format(msg, error)
return msg
def get_evaljs_error(json_data):
error = None
if 'errors' in json_data and 'evaljs' in json_data['errors']:
res = json_data['errors']['evaljs']
if isinstance(res, str):
m = re.search(r"'message': '(.*?)'[,}]", res)
if m:
error = bytes(m.group(1), 'utf-8').decode('unicode_escape')
return error
def get_valid_har(har_data):
""" Return list of valid HAR entries.
:rtype: list
"""
new_entries = []
entries = har_data.get('log', {}).get('entries', [])
logger.debug('[+] Detected %(n)d entries in HAR', {'n': len(entries)})
for entry in entries:
url = entry['request']['url']
if not is_url_allowed(url):
continue
response = entry['response']['content']
if not is_valid_mimetype(response):
continue
if response.get('text'):
charset = get_charset(response)
response['text'] = base64.b64decode(response['text']).decode(charset)
else:
response['text'] = ''
new_entries.append(entry)
logger.debug('[+] Added URL: %(url)s ...', {'url': url[:100]})
return new_entries
|
alertot/detectem | detectem/response.py | get_valid_har | python | def get_valid_har(har_data):
new_entries = []
entries = har_data.get('log', {}).get('entries', [])
logger.debug('[+] Detected %(n)d entries in HAR', {'n': len(entries)})
for entry in entries:
url = entry['request']['url']
if not is_url_allowed(url):
continue
response = entry['response']['content']
if not is_valid_mimetype(response):
continue
if response.get('text'):
charset = get_charset(response)
response['text'] = base64.b64decode(response['text']).decode(charset)
else:
response['text'] = ''
new_entries.append(entry)
logger.debug('[+] Added URL: %(url)s ...', {'url': url[:100]})
return new_entries | Return list of valid HAR entries.
:rtype: list | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/response.py#L194-L223 | [
"def is_url_allowed(url):\n \"\"\" Return ``True`` if ``url`` is not in ``blacklist``.\n\n :rtype: bool\n\n \"\"\"\n blacklist = [\n r'\\.ttf', r'\\.woff', r'fonts\\.googleapis\\.com', r'\\.png', r'\\.jpe?g', r'\\.gif',\n r'\\.svg'\n ]\n\n for ft in blacklist:\n if re.search(f... | import base64
import json
import logging
import re
import urllib.parse
from string import Template
import pkg_resources
import requests
from detectem.exceptions import SplashError
from detectem.settings import SPLASH_TIMEOUT, SPLASH_URL
from detectem.utils import docker_container
DEFAULT_CHARSET = 'iso-8859-1'
ERROR_STATUS_CODES = [400, 504]
logger = logging.getLogger('detectem')
def is_url_allowed(url):
""" Return ``True`` if ``url`` is not in ``blacklist``.
:rtype: bool
"""
blacklist = [
r'\.ttf', r'\.woff', r'fonts\.googleapis\.com', r'\.png', r'\.jpe?g', r'\.gif',
r'\.svg'
]
for ft in blacklist:
if re.search(ft, url):
return False
return True
def is_valid_mimetype(response):
""" Return ``True`` if the mimetype is not blacklisted.
:rtype: bool
"""
blacklist = [
'image/',
]
mimetype = response.get('mimeType')
if not mimetype:
return True
for bw in blacklist:
if bw in mimetype:
return False
return True
def get_charset(response):
""" Return charset from ``response`` or default charset.
:rtype: str
"""
# Set default charset
charset = DEFAULT_CHARSET
m = re.findall(r';charset=(.*)', response.get('mimeType', ''))
if m:
charset = m[0]
return charset
def create_lua_script(plugins):
""" Return script template filled up with plugin javascript data.
:rtype: str
"""
lua_template = pkg_resources.resource_string('detectem', 'script.lua')
template = Template(lua_template.decode('utf-8'))
javascript_data = to_javascript_data(plugins)
return template.substitute(js_data=json.dumps(javascript_data))
def to_javascript_data(plugins):
"""
Return a dictionary with all JavaScript matchers. Quotes are escaped.
:rtype: dict
"""
def escape(v):
return re.sub(r'"', r'\\"', v)
def dom_matchers(p):
dom_matchers = p.get_matchers('dom')
escaped_dom_matchers = []
for dm in dom_matchers:
check_statement, version_statement = dm
escaped_dom_matchers.append({
'check_statement': escape(check_statement),
# Escape '' and not None
'version_statement': escape(version_statement or ''),
})
return escaped_dom_matchers
return [{'name': p.name, 'matchers': dom_matchers(p)}
for p in plugins.with_dom_matchers()]
def get_response(url, plugins, timeout=SPLASH_TIMEOUT):
"""
Return response with HAR, inline scritps and software detected by JS matchers.
:rtype: dict
"""
lua_script = create_lua_script(plugins)
lua = urllib.parse.quote_plus(lua_script)
page_url = f'{SPLASH_URL}/execute?url={url}&timeout={timeout}&lua_source={lua}'
try:
with docker_container():
logger.debug('[+] Sending request to Splash instance')
res = requests.get(page_url)
except requests.exceptions.ConnectionError:
raise SplashError("Could not connect to Splash server {}".format(SPLASH_URL))
logger.debug('[+] Response received')
json_data = res.json()
if res.status_code in ERROR_STATUS_CODES:
raise SplashError(get_splash_error(json_data))
softwares = json_data['softwares']
scripts = json_data['scripts'].values()
har = get_valid_har(json_data['har'])
js_error = get_evaljs_error(json_data)
if js_error:
logger.debug('[+] WARNING: failed to eval JS matchers: %(n)s', {'n': js_error})
else:
logger.debug('[+] Detected %(n)d softwares from the DOM', {'n': len(softwares)})
logger.debug('[+] Detected %(n)d scripts from the DOM', {'n': len(scripts)})
logger.debug('[+] Final HAR has %(n)d valid entries', {'n': len(har)})
return {'har': har, 'scripts': scripts, 'softwares': softwares}
def get_splash_error(json_data):
msg = json_data['description']
if 'info' in json_data and 'error' in json_data['info']:
error = json_data['info']['error']
if error.startswith('http'):
msg = 'Request to site failed with error code {0}'.format(error)
elif error.startswith('network'):
# see http://doc.qt.io/qt-5/qnetworkreply.html
qt_errors = {
'network1': 'ConnectionRefusedError',
'network2': 'RemoteHostClosedError',
'network3': 'HostNotFoundError',
'network4': 'TimeoutError',
'network5': 'OperationCanceledError',
'network6': 'SslHandshakeFailedError',
}
error = qt_errors.get(error, "error code {0}".format(error))
msg = 'Request to site failed with {0}'.format(error)
else:
msg = '{0}: {1}'.format(msg, error)
return msg
def get_evaljs_error(json_data):
error = None
if 'errors' in json_data and 'evaljs' in json_data['errors']:
res = json_data['errors']['evaljs']
if isinstance(res, str):
m = re.search(r"'message': '(.*?)'[,}]", res)
if m:
error = bytes(m.group(1), 'utf-8').decode('unicode_escape')
return error
|
alertot/detectem | scripts/get_software_hashes.py | get_files_from_github | python | def get_files_from_github(user_and_repo, filedir, regex, prefer_tags):
''' Return dictionary of version:directory and directory has extracted files. '''
github_url = f'https://api.github.com/repos/{user_and_repo}'
args = f'?per_page={N_RESULTS}'
results = []
json_data = None
# Determine the right url
if not prefer_tags:
url = f'{github_url}/releases{args}'
json_data = requests.get(url).json()
if not json_data:
url = f'{github_url}/tags{args}'
json_data = requests.get(url).json()
logger.debug(f'[+] Using {url} as base url.')
# Get all the releases/tags available
results = json_data
for n_page in range(2, 1000):
logger.debug(f'[+] Requesting page {n_page} of releases/tags ..')
json_data = requests.get(f'{url}&page={n_page}').json()
results += json_data
if len(json_data) < N_RESULTS:
break
if not results:
raise ValueError(f'No releases/tags for {user_and_repo}')
directories = {}
for result in results:
name = result['name']
m = re.match(regex, name)
if not m:
continue
name = m.groups()[0]
logger.debug(f'[+] Downloading zip file for {name} version ..')
# Download zip file and extract in temporary directory
zip_url = result['zipball_url']
zf = requests.get(zip_url, allow_redirects=True)
z = zipfile.ZipFile(io.BytesIO(zf.content))
output_dir = f'{filedir}/{z.namelist()[0]}'
z.extractall(path=filedir)
directories[name] = output_dir
return directories | Return dictionary of version:directory and directory has extracted files. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/scripts/get_software_hashes.py#L21-L72 | null | import hashlib
import io
import logging
import os
import pprint
import re
import tempfile
import zipfile
import click
import click_log
import requests
logger = logging.getLogger(__name__)
click_log.basic_config(logger)
FILE_REGEX = r'^v?(\d+\.\d+\.?\d+?)$' # avoid beta releases
N_RESULTS = 100
@click.command()
@click.option('--github', default=None, type=str, help='user/repository')
@click.option(
'--directory',
default=None,
type=str,
help='local directory containing version directories'
)
@click.option(
'--regex', default=FILE_REGEX, type=str, help='regex to select the releases'
)
@click.option('--prefer-tags', is_flag=True, help='prefer tags over releases')
@click_log.simple_verbosity_option(logger, default='error')
@click.argument('filepath', type=str)
def main(github, directory, regex, filepath, prefer_tags):
directories = []
if github:
with tempfile.TemporaryDirectory() as filedir:
logger.debug(f'[+] Using {filedir} as temporary directory.')
directories = get_files_from_github(github, filedir, regex, prefer_tags)
else:
directories = {f.name: f.path for f in os.scandir(directory) if f.is_dir()}
logger.debug('[+] Creating hashes ..')
hashes = {}
for version, path in directories.items():
target_file = os.path.join(path, filepath)
if not os.path.exists(target_file):
logger.error(f'version {version} not contains target file')
continue
with open(target_file) as f:
content = f.read().encode('utf-8')
m = hashlib.sha256()
m.update(content)
h = m.hexdigest()
hashes[version] = h
pprint.pprint({filepath: hashes})
if __name__ == '__main__':
main()
|
alertot/detectem | detectem/core.py | HarProcessor._script_to_har_entry | python | def _script_to_har_entry(cls, script, url):
''' Return entry for embed script '''
entry = {
'request': {'url': url},
'response': {'url': url, 'content': {'text': script}}
}
cls._set_entry_type(entry, INLINE_SCRIPT_ENTRY)
return entry | Return entry for embed script | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L56-L65 | [
"def _set_entry_type(entry, entry_type):\n ''' Set entry type (detectem internal metadata) '''\n entry.setdefault('detectem', {})['type'] = entry_type\n"
] | class HarProcessor:
''' This class process the HAR list returned by Splash
adding some useful markers for matcher application
'''
@staticmethod
def _set_entry_type(entry, entry_type):
''' Set entry type (detectem internal metadata) '''
entry.setdefault('detectem', {})['type'] = entry_type
@staticmethod
def _get_location(entry):
''' Return `Location` header value if it's present in ``entry`` '''
headers = entry['response'].get('headers', [])
for header in headers:
if header['name'] == 'Location':
return header['value']
return None
@classmethod
def mark_entries(self, entries):
''' Mark one entry as main entry and the rest as resource entry.
Main entry is the entry that contain response's body
of the requested URL.
'''
for entry in entries:
self._set_entry_type(entry, RESOURCE_ENTRY)
# If first entry doesn't have a redirect, set is as main entry
main_entry = entries[0]
main_location = self._get_location(main_entry)
if not main_location:
self._set_entry_type(main_entry, MAIN_ENTRY)
return
# Resolve redirected URL and see if it's in the rest of entries
main_url = urllib.parse.urljoin(get_url(main_entry), main_location)
for entry in entries[1:]:
url = get_url(entry)
if url == main_url:
self._set_entry_type(entry, MAIN_ENTRY)
break
else:
# In fail case, set the first entry
self._set_entry_type(main_entry, MAIN_ENTRY)
def prepare(self, response, url):
har = response.get('har', [])
if har:
self.mark_entries(har)
# Detect embed scripts and add them to HAR list
for script in response.get('scripts', []):
har.append(self._script_to_har_entry(script, url))
return har
|
alertot/detectem | detectem/core.py | HarProcessor.mark_entries | python | def mark_entries(self, entries):
''' Mark one entry as main entry and the rest as resource entry.
Main entry is the entry that contain response's body
of the requested URL.
'''
for entry in entries:
self._set_entry_type(entry, RESOURCE_ENTRY)
# If first entry doesn't have a redirect, set is as main entry
main_entry = entries[0]
main_location = self._get_location(main_entry)
if not main_location:
self._set_entry_type(main_entry, MAIN_ENTRY)
return
# Resolve redirected URL and see if it's in the rest of entries
main_url = urllib.parse.urljoin(get_url(main_entry), main_location)
for entry in entries[1:]:
url = get_url(entry)
if url == main_url:
self._set_entry_type(entry, MAIN_ENTRY)
break
else:
# In fail case, set the first entry
self._set_entry_type(main_entry, MAIN_ENTRY) | Mark one entry as main entry and the rest as resource entry.
Main entry is the entry that contain response's body
of the requested URL. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L67-L93 | [
"def get_url(entry):\n \"\"\" Return URL from response if it was received otherwise requested URL. \"\"\"\n try:\n return entry['response']['url']\n except KeyError:\n return entry['request']['url']\n",
"def _set_entry_type(entry, entry_type):\n ''' Set entry type (detectem internal meta... | class HarProcessor:
''' This class process the HAR list returned by Splash
adding some useful markers for matcher application
'''
@staticmethod
def _set_entry_type(entry, entry_type):
''' Set entry type (detectem internal metadata) '''
entry.setdefault('detectem', {})['type'] = entry_type
@staticmethod
def _get_location(entry):
''' Return `Location` header value if it's present in ``entry`` '''
headers = entry['response'].get('headers', [])
for header in headers:
if header['name'] == 'Location':
return header['value']
return None
@classmethod
def _script_to_har_entry(cls, script, url):
''' Return entry for embed script '''
entry = {
'request': {'url': url},
'response': {'url': url, 'content': {'text': script}}
}
cls._set_entry_type(entry, INLINE_SCRIPT_ENTRY)
return entry
def prepare(self, response, url):
har = response.get('har', [])
if har:
self.mark_entries(har)
# Detect embed scripts and add them to HAR list
for script in response.get('scripts', []):
har.append(self._script_to_har_entry(script, url))
return har
|
alertot/detectem | detectem/core.py | Detector.get_hints | python | def get_hints(self, plugin):
''' Return plugin hints from ``plugin``. '''
hints = []
for hint_name in getattr(plugin, 'hints', []):
hint_plugin = self._plugins.get(hint_name)
if hint_plugin:
hint_result = Result(
name=hint_plugin.name,
homepage=hint_plugin.homepage,
from_url=self.requested_url,
type=HINT_TYPE,
plugin=plugin.name,
)
hints.append(hint_result)
logger.debug(f'{plugin.name} & hint {hint_result.name} detected')
else:
logger.error(f'{plugin.name} hints an invalid plugin: {hint_name}')
return hints | Return plugin hints from ``plugin``. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L121-L141 | [
"def get(self, name):\n return self._plugins.get(name)\n"
] | class Detector():
def __init__(self, response, plugins, requested_url):
self.requested_url = requested_url
self.har = HarProcessor().prepare(response, requested_url)
self._softwares_from_splash = response['softwares']
self._plugins = plugins
self._results = ResultCollection()
@staticmethod
def _get_entry_type(entry):
''' Return entry type. '''
return entry['detectem']['type']
def process_from_splash(self):
''' Add softwares found in the DOM '''
for software in self._softwares_from_splash:
plugin = self._plugins.get(software['name'])
# Determine if it's a version or presence result
try:
additional_data = {'version': software['version']}
except KeyError:
additional_data = {'type': INDICATOR_TYPE}
self._results.add_result(
Result(
name=plugin.name,
homepage=plugin.homepage,
from_url=self.requested_url,
plugin=plugin.name,
**additional_data,
)
)
for hint in self.get_hints(plugin):
self._results.add_result(hint)
def _get_matchers_for_entry(self, plugin, entry):
grouped_matchers = plugin.get_grouped_matchers()
def remove_group(group):
if group in grouped_matchers:
del grouped_matchers[group]
if self._get_entry_type(entry) == MAIN_ENTRY:
remove_group('body')
remove_group('url')
else:
remove_group('header')
remove_group('xpath')
remove_group('dom')
return grouped_matchers
def apply_plugin_matchers(self, plugin, entry):
data_list = []
grouped_matchers = self._get_matchers_for_entry(plugin, entry)
for matcher_type, matchers in grouped_matchers.items():
klass = MATCHERS[matcher_type]
plugin_match = klass.get_info(entry, *matchers)
if plugin_match.name or plugin_match.version or plugin_match.presence:
data_list.append(plugin_match)
return get_most_complete_pm(data_list)
def process_har(self):
""" Detect plugins present in the page. """
hints = []
version_plugins = self._plugins.with_version_matchers()
generic_plugins = self._plugins.with_generic_matchers()
for entry in self.har:
for plugin in version_plugins:
pm = self.apply_plugin_matchers(plugin, entry)
if not pm:
continue
# Set name if matchers could detect modular name
if pm.name:
name = '{}-{}'.format(plugin.name, pm.name)
else:
name = plugin.name
if pm.version:
self._results.add_result(
Result(
name=name,
version=pm.version,
homepage=plugin.homepage,
from_url=get_url(entry),
plugin=plugin.name,
)
)
elif pm.presence:
# Try to get version through file hashes
version = get_version_via_file_hashes(plugin, entry)
if version:
self._results.add_result(
Result(
name=name,
version=version,
homepage=plugin.homepage,
from_url=get_url(entry),
plugin=plugin.name,
)
)
else:
self._results.add_result(
Result(
name=name,
homepage=plugin.homepage,
from_url=get_url(entry),
type=INDICATOR_TYPE,
plugin=plugin.name,
)
)
hints += self.get_hints(plugin)
for plugin in generic_plugins:
pm = self.apply_plugin_matchers(plugin, entry)
if not pm:
continue
plugin_data = plugin.get_information(entry)
# Only add to results if it's a valid result
if 'name' in plugin_data:
self._results.add_result(
Result(
name=plugin_data['name'],
homepage=plugin_data['homepage'],
from_url=get_url(entry),
type=GENERIC_TYPE,
plugin=plugin.name,
)
)
hints += self.get_hints(plugin)
for hint in hints:
self._results.add_result(hint)
def get_results(self, metadata=False):
""" Return results of the analysis. """
results_data = []
self.process_har()
self.process_from_splash()
for rt in sorted(self._results.get_results()):
rdict = {'name': rt.name}
if rt.version:
rdict['version'] = rt.version
if metadata:
rdict['homepage'] = rt.homepage
rdict['type'] = rt.type
rdict['from_url'] = rt.from_url
rdict['plugin'] = rt.plugin
results_data.append(rdict)
return results_data
|
alertot/detectem | detectem/core.py | Detector.process_from_splash | python | def process_from_splash(self):
''' Add softwares found in the DOM '''
for software in self._softwares_from_splash:
plugin = self._plugins.get(software['name'])
# Determine if it's a version or presence result
try:
additional_data = {'version': software['version']}
except KeyError:
additional_data = {'type': INDICATOR_TYPE}
self._results.add_result(
Result(
name=plugin.name,
homepage=plugin.homepage,
from_url=self.requested_url,
plugin=plugin.name,
**additional_data,
)
)
for hint in self.get_hints(plugin):
self._results.add_result(hint) | Add softwares found in the DOM | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L143-L165 | [
"def get_hints(self, plugin):\n ''' Return plugin hints from ``plugin``. '''\n hints = []\n\n for hint_name in getattr(plugin, 'hints', []):\n hint_plugin = self._plugins.get(hint_name)\n if hint_plugin:\n hint_result = Result(\n name=hint_plugin.name,\n ... | class Detector():
def __init__(self, response, plugins, requested_url):
self.requested_url = requested_url
self.har = HarProcessor().prepare(response, requested_url)
self._softwares_from_splash = response['softwares']
self._plugins = plugins
self._results = ResultCollection()
@staticmethod
def _get_entry_type(entry):
''' Return entry type. '''
return entry['detectem']['type']
def get_hints(self, plugin):
''' Return plugin hints from ``plugin``. '''
hints = []
for hint_name in getattr(plugin, 'hints', []):
hint_plugin = self._plugins.get(hint_name)
if hint_plugin:
hint_result = Result(
name=hint_plugin.name,
homepage=hint_plugin.homepage,
from_url=self.requested_url,
type=HINT_TYPE,
plugin=plugin.name,
)
hints.append(hint_result)
logger.debug(f'{plugin.name} & hint {hint_result.name} detected')
else:
logger.error(f'{plugin.name} hints an invalid plugin: {hint_name}')
return hints
def _get_matchers_for_entry(self, plugin, entry):
grouped_matchers = plugin.get_grouped_matchers()
def remove_group(group):
if group in grouped_matchers:
del grouped_matchers[group]
if self._get_entry_type(entry) == MAIN_ENTRY:
remove_group('body')
remove_group('url')
else:
remove_group('header')
remove_group('xpath')
remove_group('dom')
return grouped_matchers
def apply_plugin_matchers(self, plugin, entry):
data_list = []
grouped_matchers = self._get_matchers_for_entry(plugin, entry)
for matcher_type, matchers in grouped_matchers.items():
klass = MATCHERS[matcher_type]
plugin_match = klass.get_info(entry, *matchers)
if plugin_match.name or plugin_match.version or plugin_match.presence:
data_list.append(plugin_match)
return get_most_complete_pm(data_list)
def process_har(self):
""" Detect plugins present in the page. """
hints = []
version_plugins = self._plugins.with_version_matchers()
generic_plugins = self._plugins.with_generic_matchers()
for entry in self.har:
for plugin in version_plugins:
pm = self.apply_plugin_matchers(plugin, entry)
if not pm:
continue
# Set name if matchers could detect modular name
if pm.name:
name = '{}-{}'.format(plugin.name, pm.name)
else:
name = plugin.name
if pm.version:
self._results.add_result(
Result(
name=name,
version=pm.version,
homepage=plugin.homepage,
from_url=get_url(entry),
plugin=plugin.name,
)
)
elif pm.presence:
# Try to get version through file hashes
version = get_version_via_file_hashes(plugin, entry)
if version:
self._results.add_result(
Result(
name=name,
version=version,
homepage=plugin.homepage,
from_url=get_url(entry),
plugin=plugin.name,
)
)
else:
self._results.add_result(
Result(
name=name,
homepage=plugin.homepage,
from_url=get_url(entry),
type=INDICATOR_TYPE,
plugin=plugin.name,
)
)
hints += self.get_hints(plugin)
for plugin in generic_plugins:
pm = self.apply_plugin_matchers(plugin, entry)
if not pm:
continue
plugin_data = plugin.get_information(entry)
# Only add to results if it's a valid result
if 'name' in plugin_data:
self._results.add_result(
Result(
name=plugin_data['name'],
homepage=plugin_data['homepage'],
from_url=get_url(entry),
type=GENERIC_TYPE,
plugin=plugin.name,
)
)
hints += self.get_hints(plugin)
for hint in hints:
self._results.add_result(hint)
def get_results(self, metadata=False):
""" Return results of the analysis. """
results_data = []
self.process_har()
self.process_from_splash()
for rt in sorted(self._results.get_results()):
rdict = {'name': rt.name}
if rt.version:
rdict['version'] = rt.version
if metadata:
rdict['homepage'] = rt.homepage
rdict['type'] = rt.type
rdict['from_url'] = rt.from_url
rdict['plugin'] = rt.plugin
results_data.append(rdict)
return results_data
|
alertot/detectem | detectem/core.py | Detector.process_har | python | def process_har(self):
hints = []
version_plugins = self._plugins.with_version_matchers()
generic_plugins = self._plugins.with_generic_matchers()
for entry in self.har:
for plugin in version_plugins:
pm = self.apply_plugin_matchers(plugin, entry)
if not pm:
continue
# Set name if matchers could detect modular name
if pm.name:
name = '{}-{}'.format(plugin.name, pm.name)
else:
name = plugin.name
if pm.version:
self._results.add_result(
Result(
name=name,
version=pm.version,
homepage=plugin.homepage,
from_url=get_url(entry),
plugin=plugin.name,
)
)
elif pm.presence:
# Try to get version through file hashes
version = get_version_via_file_hashes(plugin, entry)
if version:
self._results.add_result(
Result(
name=name,
version=version,
homepage=plugin.homepage,
from_url=get_url(entry),
plugin=plugin.name,
)
)
else:
self._results.add_result(
Result(
name=name,
homepage=plugin.homepage,
from_url=get_url(entry),
type=INDICATOR_TYPE,
plugin=plugin.name,
)
)
hints += self.get_hints(plugin)
for plugin in generic_plugins:
pm = self.apply_plugin_matchers(plugin, entry)
if not pm:
continue
plugin_data = plugin.get_information(entry)
# Only add to results if it's a valid result
if 'name' in plugin_data:
self._results.add_result(
Result(
name=plugin_data['name'],
homepage=plugin_data['homepage'],
from_url=get_url(entry),
type=GENERIC_TYPE,
plugin=plugin.name,
)
)
hints += self.get_hints(plugin)
for hint in hints:
self._results.add_result(hint) | Detect plugins present in the page. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L197-L273 | [
"def get_url(entry):\n \"\"\" Return URL from response if it was received otherwise requested URL. \"\"\"\n try:\n return entry['response']['url']\n except KeyError:\n return entry['request']['url']\n",
"def get_version_via_file_hashes(plugin, entry):\n file_hashes = getattr(plugin, 'fil... | class Detector():
def __init__(self, response, plugins, requested_url):
self.requested_url = requested_url
self.har = HarProcessor().prepare(response, requested_url)
self._softwares_from_splash = response['softwares']
self._plugins = plugins
self._results = ResultCollection()
@staticmethod
def _get_entry_type(entry):
''' Return entry type. '''
return entry['detectem']['type']
def get_hints(self, plugin):
''' Return plugin hints from ``plugin``. '''
hints = []
for hint_name in getattr(plugin, 'hints', []):
hint_plugin = self._plugins.get(hint_name)
if hint_plugin:
hint_result = Result(
name=hint_plugin.name,
homepage=hint_plugin.homepage,
from_url=self.requested_url,
type=HINT_TYPE,
plugin=plugin.name,
)
hints.append(hint_result)
logger.debug(f'{plugin.name} & hint {hint_result.name} detected')
else:
logger.error(f'{plugin.name} hints an invalid plugin: {hint_name}')
return hints
def process_from_splash(self):
''' Add softwares found in the DOM '''
for software in self._softwares_from_splash:
plugin = self._plugins.get(software['name'])
# Determine if it's a version or presence result
try:
additional_data = {'version': software['version']}
except KeyError:
additional_data = {'type': INDICATOR_TYPE}
self._results.add_result(
Result(
name=plugin.name,
homepage=plugin.homepage,
from_url=self.requested_url,
plugin=plugin.name,
**additional_data,
)
)
for hint in self.get_hints(plugin):
self._results.add_result(hint)
def _get_matchers_for_entry(self, plugin, entry):
grouped_matchers = plugin.get_grouped_matchers()
def remove_group(group):
if group in grouped_matchers:
del grouped_matchers[group]
if self._get_entry_type(entry) == MAIN_ENTRY:
remove_group('body')
remove_group('url')
else:
remove_group('header')
remove_group('xpath')
remove_group('dom')
return grouped_matchers
def apply_plugin_matchers(self, plugin, entry):
data_list = []
grouped_matchers = self._get_matchers_for_entry(plugin, entry)
for matcher_type, matchers in grouped_matchers.items():
klass = MATCHERS[matcher_type]
plugin_match = klass.get_info(entry, *matchers)
if plugin_match.name or plugin_match.version or plugin_match.presence:
data_list.append(plugin_match)
return get_most_complete_pm(data_list)
def get_results(self, metadata=False):
""" Return results of the analysis. """
results_data = []
self.process_har()
self.process_from_splash()
for rt in sorted(self._results.get_results()):
rdict = {'name': rt.name}
if rt.version:
rdict['version'] = rt.version
if metadata:
rdict['homepage'] = rt.homepage
rdict['type'] = rt.type
rdict['from_url'] = rt.from_url
rdict['plugin'] = rt.plugin
results_data.append(rdict)
return results_data
|
alertot/detectem | detectem/core.py | Detector.get_results | python | def get_results(self, metadata=False):
results_data = []
self.process_har()
self.process_from_splash()
for rt in sorted(self._results.get_results()):
rdict = {'name': rt.name}
if rt.version:
rdict['version'] = rt.version
if metadata:
rdict['homepage'] = rt.homepage
rdict['type'] = rt.type
rdict['from_url'] = rt.from_url
rdict['plugin'] = rt.plugin
results_data.append(rdict)
return results_data | Return results of the analysis. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/core.py#L275-L295 | [
"def process_from_splash(self):\n ''' Add softwares found in the DOM '''\n for software in self._softwares_from_splash:\n plugin = self._plugins.get(software['name'])\n\n # Determine if it's a version or presence result\n try:\n additional_data = {'version': software['version']... | class Detector():
def __init__(self, response, plugins, requested_url):
self.requested_url = requested_url
self.har = HarProcessor().prepare(response, requested_url)
self._softwares_from_splash = response['softwares']
self._plugins = plugins
self._results = ResultCollection()
@staticmethod
def _get_entry_type(entry):
''' Return entry type. '''
return entry['detectem']['type']
def get_hints(self, plugin):
''' Return plugin hints from ``plugin``. '''
hints = []
for hint_name in getattr(plugin, 'hints', []):
hint_plugin = self._plugins.get(hint_name)
if hint_plugin:
hint_result = Result(
name=hint_plugin.name,
homepage=hint_plugin.homepage,
from_url=self.requested_url,
type=HINT_TYPE,
plugin=plugin.name,
)
hints.append(hint_result)
logger.debug(f'{plugin.name} & hint {hint_result.name} detected')
else:
logger.error(f'{plugin.name} hints an invalid plugin: {hint_name}')
return hints
def process_from_splash(self):
''' Add softwares found in the DOM '''
for software in self._softwares_from_splash:
plugin = self._plugins.get(software['name'])
# Determine if it's a version or presence result
try:
additional_data = {'version': software['version']}
except KeyError:
additional_data = {'type': INDICATOR_TYPE}
self._results.add_result(
Result(
name=plugin.name,
homepage=plugin.homepage,
from_url=self.requested_url,
plugin=plugin.name,
**additional_data,
)
)
for hint in self.get_hints(plugin):
self._results.add_result(hint)
def _get_matchers_for_entry(self, plugin, entry):
grouped_matchers = plugin.get_grouped_matchers()
def remove_group(group):
if group in grouped_matchers:
del grouped_matchers[group]
if self._get_entry_type(entry) == MAIN_ENTRY:
remove_group('body')
remove_group('url')
else:
remove_group('header')
remove_group('xpath')
remove_group('dom')
return grouped_matchers
def apply_plugin_matchers(self, plugin, entry):
data_list = []
grouped_matchers = self._get_matchers_for_entry(plugin, entry)
for matcher_type, matchers in grouped_matchers.items():
klass = MATCHERS[matcher_type]
plugin_match = klass.get_info(entry, *matchers)
if plugin_match.name or plugin_match.version or plugin_match.presence:
data_list.append(plugin_match)
return get_most_complete_pm(data_list)
def process_har(self):
""" Detect plugins present in the page. """
hints = []
version_plugins = self._plugins.with_version_matchers()
generic_plugins = self._plugins.with_generic_matchers()
for entry in self.har:
for plugin in version_plugins:
pm = self.apply_plugin_matchers(plugin, entry)
if not pm:
continue
# Set name if matchers could detect modular name
if pm.name:
name = '{}-{}'.format(plugin.name, pm.name)
else:
name = plugin.name
if pm.version:
self._results.add_result(
Result(
name=name,
version=pm.version,
homepage=plugin.homepage,
from_url=get_url(entry),
plugin=plugin.name,
)
)
elif pm.presence:
# Try to get version through file hashes
version = get_version_via_file_hashes(plugin, entry)
if version:
self._results.add_result(
Result(
name=name,
version=version,
homepage=plugin.homepage,
from_url=get_url(entry),
plugin=plugin.name,
)
)
else:
self._results.add_result(
Result(
name=name,
homepage=plugin.homepage,
from_url=get_url(entry),
type=INDICATOR_TYPE,
plugin=plugin.name,
)
)
hints += self.get_hints(plugin)
for plugin in generic_plugins:
pm = self.apply_plugin_matchers(plugin, entry)
if not pm:
continue
plugin_data = plugin.get_information(entry)
# Only add to results if it's a valid result
if 'name' in plugin_data:
self._results.add_result(
Result(
name=plugin_data['name'],
homepage=plugin_data['homepage'],
from_url=get_url(entry),
type=GENERIC_TYPE,
plugin=plugin.name,
)
)
hints += self.get_hints(plugin)
for hint in hints:
self._results.add_result(hint)
|
alertot/detectem | detectem/plugin.py | load_plugins | python | def load_plugins():
loader = _PluginLoader()
for pkg in PLUGIN_PACKAGES:
loader.load_plugins(pkg)
return loader.plugins | Return the list of plugin instances. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/plugin.py#L158-L165 | [
"def load_plugins(self, plugins_package):\n ''' Load plugins from `plugins_package` module. '''\n try:\n # Resolve directory in the filesystem\n plugin_dir = find_spec(plugins_package).submodule_search_locations[0]\n except ImportError:\n logger.error(\n \"Could not load plu... | import glob
import inspect
import logging
import re
from importlib.util import find_spec, module_from_spec
from zope.interface import Attribute, Interface, implementer
from zope.interface.exceptions import BrokenImplementation
from zope.interface.verify import verifyObject
from detectem.settings import PLUGIN_PACKAGES
logger = logging.getLogger('detectem')
LANGUAGE_TAGS = [
'php', 'python', 'ruby', 'perl', 'node.js', 'javascript', 'asp.net', 'java', 'go',
'ruby on rails', 'cfml'
]
FRAMEWORK_TAGS = [
'django', 'angular', 'backbone', 'react', 'symfony', 'bootstrap', 'vue', 'laravel',
'woltlab'
]
PRODUCT_TAGS = [
'wordpress', 'mysql', 'jquery', 'mootools', 'apache', 'iis', 'nginx', 'ssl',
'joomla!', 'drupal', 'underscore.js', 'marionette.js', 'moment timezone', 'moment.js',
'devtools', 'teamcity', 'google code prettyfy', 'solr', 'postgresql', 'octopress',
'k2', 'sobi 2', 'sobipro', 'virtuemart', 'tomcat', 'coldfusion', 'jekill', 'less',
'windows server', 'mysql', 'waf'
]
CATEGORY_TAGS = [
'cms', 'seo', 'blog', 'advertising networks', 'analytics', 'wiki',
'document management system', 'miscellaneous', 'message board', 'angular',
'js framework', 'web framework', 'visualization', 'graphics', 'web server', 'wiki',
'editor', 'ecommerce', 'accounting', 'database manager', 'photo gallery',
'issue tracker', 'mobile framework', 'slider', 'accounting', 'programming language',
'hosting panel', 'lms', 'js graphic', 'exhibit', 'marketing automation',
'search engine', 'documentation tool', 'database', 'template engine'
]
PLUGIN_TAGS = LANGUAGE_TAGS + FRAMEWORK_TAGS + PRODUCT_TAGS + CATEGORY_TAGS
class PluginCollection(object):
def __init__(self):
self._plugins = {}
def __len__(self):
return len(self._plugins)
def add(self, ins):
self._plugins[ins.name] = ins
def get(self, name):
return self._plugins.get(name)
def get_all(self):
return self._plugins.values()
def with_version_matchers(self):
return [p for p in self._plugins.values() if p.is_version]
def with_dom_matchers(self):
return [p for p in self._plugins.values() if p.is_dom]
def with_generic_matchers(self):
return [p for p in self._plugins.values() if p.is_generic]
class _PluginLoader:
def __init__(self):
self.plugins = PluginCollection()
def _full_class_name(self, ins):
return '{}.{}'.format(ins.__class__.__module__, ins.__class__.__name__)
def _get_plugin_module_paths(self, plugin_dir):
''' Return a list of every module in `plugin_dir`. '''
filepaths = [
fp for fp in glob.glob('{}/**/*.py'.format(plugin_dir), recursive=True)
if not fp.endswith('__init__.py')
]
rel_paths = [re.sub(plugin_dir.rstrip('/') + '/', '', fp) for fp in filepaths]
module_paths = [rp.replace('/', '.').replace('.py', '') for rp in rel_paths]
return module_paths
def _is_plugin_ok(self, instance):
''' Return `True` if:
1. Plugin meets plugin interface.
2. Is not already registered in the plugin collection.
3. Have accepted tags.
Otherwise, return `False` and log warnings.
'''
try:
verifyObject(IPlugin, instance)
except BrokenImplementation:
logger.warning(
"Plugin '%(name)s' doesn't provide the plugin interface",
{'name': self._full_class_name(instance)}
)
return False
# Check if the plugin is already registered
reg = self.plugins.get(instance.name)
if reg:
logger.warning(
"Plugin '%(name)s' by '%(instance)s' is already provided by '%(reg)s'", {
'name': instance.name, 'instance': self._full_class_name(instance),
'reg': self._full_class_name(reg)
}
)
return False
for tag in instance.tags:
if tag not in PLUGIN_TAGS:
logger.warning(
"Invalid tag '%(tag)s' in '%(instance)s'",
{'tag': tag, 'instance': self._full_class_name(instance)}
)
return False
return True
def load_plugins(self, plugins_package):
''' Load plugins from `plugins_package` module. '''
try:
# Resolve directory in the filesystem
plugin_dir = find_spec(plugins_package).submodule_search_locations[0]
except ImportError:
logger.error(
"Could not load plugins package '%(pkg)s'", {'pkg': plugins_package}
)
return
for module_path in self._get_plugin_module_paths(plugin_dir):
# Load the module dynamically
spec = find_spec('{}.{}'.format(plugins_package, module_path))
m = module_from_spec(spec)
spec.loader.exec_module(m)
# Get classes from module and extract the plugin classes
classes = inspect.getmembers(m, predicate=inspect.isclass)
for _, klass in classes:
# Avoid imports processing
if klass.__module__ != spec.name:
continue
# Avoid classes not ending in Plugin
if not klass.__name__.endswith('Plugin'):
continue
instance = klass()
if self._is_plugin_ok(instance):
self.plugins.add(instance)
class IPlugin(Interface):
name = Attribute(""" Name to identify the plugin. """)
homepage = Attribute(""" Plugin homepage. """)
tags = Attribute(""" Tags to categorize plugins """)
matchers = Attribute(""" List of matchers """)
@implementer(IPlugin)
class Plugin:
""" Class used by normal plugins.
It implements :class:`~IPlugin`.
"""
ptype = 'normal'
def get_matchers(self, matcher_type):
return [m[matcher_type] for m in self.matchers if matcher_type in m]
def get_grouped_matchers(self):
""" Return dictionary of matchers (not empty ones)
with matcher type as key and matcher list as value.
"""
data = {}
for matcher_type in ['url', 'body', 'header', 'xpath', 'dom']:
matcher_list = self.get_matchers(matcher_type)
if matcher_list:
data[matcher_type] = matcher_list
return data
@property
def is_version(self):
return self.ptype == 'normal'
@property
def is_dom(self):
return any([m for m in self.matchers if 'dom' in m])
@property
def is_generic(self):
return self.ptype == 'generic'
class GenericPlugin(Plugin):
""" Class used by generic plugins. """
ptype = 'generic'
def get_information(self, entry):
raise NotImplementedError()
|
alertot/detectem | detectem/plugin.py | _PluginLoader._get_plugin_module_paths | python | def _get_plugin_module_paths(self, plugin_dir):
''' Return a list of every module in `plugin_dir`. '''
filepaths = [
fp for fp in glob.glob('{}/**/*.py'.format(plugin_dir), recursive=True)
if not fp.endswith('__init__.py')
]
rel_paths = [re.sub(plugin_dir.rstrip('/') + '/', '', fp) for fp in filepaths]
module_paths = [rp.replace('/', '.').replace('.py', '') for rp in rel_paths]
return module_paths | Return a list of every module in `plugin_dir`. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/plugin.py#L75-L84 | null | class _PluginLoader:
def __init__(self):
self.plugins = PluginCollection()
def _full_class_name(self, ins):
return '{}.{}'.format(ins.__class__.__module__, ins.__class__.__name__)
def _is_plugin_ok(self, instance):
''' Return `True` if:
1. Plugin meets plugin interface.
2. Is not already registered in the plugin collection.
3. Have accepted tags.
Otherwise, return `False` and log warnings.
'''
try:
verifyObject(IPlugin, instance)
except BrokenImplementation:
logger.warning(
"Plugin '%(name)s' doesn't provide the plugin interface",
{'name': self._full_class_name(instance)}
)
return False
# Check if the plugin is already registered
reg = self.plugins.get(instance.name)
if reg:
logger.warning(
"Plugin '%(name)s' by '%(instance)s' is already provided by '%(reg)s'", {
'name': instance.name, 'instance': self._full_class_name(instance),
'reg': self._full_class_name(reg)
}
)
return False
for tag in instance.tags:
if tag not in PLUGIN_TAGS:
logger.warning(
"Invalid tag '%(tag)s' in '%(instance)s'",
{'tag': tag, 'instance': self._full_class_name(instance)}
)
return False
return True
def load_plugins(self, plugins_package):
''' Load plugins from `plugins_package` module. '''
try:
# Resolve directory in the filesystem
plugin_dir = find_spec(plugins_package).submodule_search_locations[0]
except ImportError:
logger.error(
"Could not load plugins package '%(pkg)s'", {'pkg': plugins_package}
)
return
for module_path in self._get_plugin_module_paths(plugin_dir):
# Load the module dynamically
spec = find_spec('{}.{}'.format(plugins_package, module_path))
m = module_from_spec(spec)
spec.loader.exec_module(m)
# Get classes from module and extract the plugin classes
classes = inspect.getmembers(m, predicate=inspect.isclass)
for _, klass in classes:
# Avoid imports processing
if klass.__module__ != spec.name:
continue
# Avoid classes not ending in Plugin
if not klass.__name__.endswith('Plugin'):
continue
instance = klass()
if self._is_plugin_ok(instance):
self.plugins.add(instance)
|
alertot/detectem | detectem/plugin.py | _PluginLoader._is_plugin_ok | python | def _is_plugin_ok(self, instance):
''' Return `True` if:
1. Plugin meets plugin interface.
2. Is not already registered in the plugin collection.
3. Have accepted tags.
Otherwise, return `False` and log warnings.
'''
try:
verifyObject(IPlugin, instance)
except BrokenImplementation:
logger.warning(
"Plugin '%(name)s' doesn't provide the plugin interface",
{'name': self._full_class_name(instance)}
)
return False
# Check if the plugin is already registered
reg = self.plugins.get(instance.name)
if reg:
logger.warning(
"Plugin '%(name)s' by '%(instance)s' is already provided by '%(reg)s'", {
'name': instance.name, 'instance': self._full_class_name(instance),
'reg': self._full_class_name(reg)
}
)
return False
for tag in instance.tags:
if tag not in PLUGIN_TAGS:
logger.warning(
"Invalid tag '%(tag)s' in '%(instance)s'",
{'tag': tag, 'instance': self._full_class_name(instance)}
)
return False
return True | Return `True` if:
1. Plugin meets plugin interface.
2. Is not already registered in the plugin collection.
3. Have accepted tags.
Otherwise, return `False` and log warnings. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/plugin.py#L86-L123 | [
"def _full_class_name(self, ins):\n return '{}.{}'.format(ins.__class__.__module__, ins.__class__.__name__)\n"
] | class _PluginLoader:
def __init__(self):
self.plugins = PluginCollection()
def _full_class_name(self, ins):
return '{}.{}'.format(ins.__class__.__module__, ins.__class__.__name__)
def _get_plugin_module_paths(self, plugin_dir):
''' Return a list of every module in `plugin_dir`. '''
filepaths = [
fp for fp in glob.glob('{}/**/*.py'.format(plugin_dir), recursive=True)
if not fp.endswith('__init__.py')
]
rel_paths = [re.sub(plugin_dir.rstrip('/') + '/', '', fp) for fp in filepaths]
module_paths = [rp.replace('/', '.').replace('.py', '') for rp in rel_paths]
return module_paths
def load_plugins(self, plugins_package):
''' Load plugins from `plugins_package` module. '''
try:
# Resolve directory in the filesystem
plugin_dir = find_spec(plugins_package).submodule_search_locations[0]
except ImportError:
logger.error(
"Could not load plugins package '%(pkg)s'", {'pkg': plugins_package}
)
return
for module_path in self._get_plugin_module_paths(plugin_dir):
# Load the module dynamically
spec = find_spec('{}.{}'.format(plugins_package, module_path))
m = module_from_spec(spec)
spec.loader.exec_module(m)
# Get classes from module and extract the plugin classes
classes = inspect.getmembers(m, predicate=inspect.isclass)
for _, klass in classes:
# Avoid imports processing
if klass.__module__ != spec.name:
continue
# Avoid classes not ending in Plugin
if not klass.__name__.endswith('Plugin'):
continue
instance = klass()
if self._is_plugin_ok(instance):
self.plugins.add(instance)
|
alertot/detectem | detectem/plugin.py | _PluginLoader.load_plugins | python | def load_plugins(self, plugins_package):
''' Load plugins from `plugins_package` module. '''
try:
# Resolve directory in the filesystem
plugin_dir = find_spec(plugins_package).submodule_search_locations[0]
except ImportError:
logger.error(
"Could not load plugins package '%(pkg)s'", {'pkg': plugins_package}
)
return
for module_path in self._get_plugin_module_paths(plugin_dir):
# Load the module dynamically
spec = find_spec('{}.{}'.format(plugins_package, module_path))
m = module_from_spec(spec)
spec.loader.exec_module(m)
# Get classes from module and extract the plugin classes
classes = inspect.getmembers(m, predicate=inspect.isclass)
for _, klass in classes:
# Avoid imports processing
if klass.__module__ != spec.name:
continue
# Avoid classes not ending in Plugin
if not klass.__name__.endswith('Plugin'):
continue
instance = klass()
if self._is_plugin_ok(instance):
self.plugins.add(instance) | Load plugins from `plugins_package` module. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/plugin.py#L125-L155 | [
"def _get_plugin_module_paths(self, plugin_dir):\n ''' Return a list of every module in `plugin_dir`. '''\n filepaths = [\n fp for fp in glob.glob('{}/**/*.py'.format(plugin_dir), recursive=True)\n if not fp.endswith('__init__.py')\n ]\n rel_paths = [re.sub(plugin_dir.rstrip('/') + '/', ''... | class _PluginLoader:
def __init__(self):
self.plugins = PluginCollection()
def _full_class_name(self, ins):
return '{}.{}'.format(ins.__class__.__module__, ins.__class__.__name__)
def _get_plugin_module_paths(self, plugin_dir):
''' Return a list of every module in `plugin_dir`. '''
filepaths = [
fp for fp in glob.glob('{}/**/*.py'.format(plugin_dir), recursive=True)
if not fp.endswith('__init__.py')
]
rel_paths = [re.sub(plugin_dir.rstrip('/') + '/', '', fp) for fp in filepaths]
module_paths = [rp.replace('/', '.').replace('.py', '') for rp in rel_paths]
return module_paths
def _is_plugin_ok(self, instance):
''' Return `True` if:
1. Plugin meets plugin interface.
2. Is not already registered in the plugin collection.
3. Have accepted tags.
Otherwise, return `False` and log warnings.
'''
try:
verifyObject(IPlugin, instance)
except BrokenImplementation:
logger.warning(
"Plugin '%(name)s' doesn't provide the plugin interface",
{'name': self._full_class_name(instance)}
)
return False
# Check if the plugin is already registered
reg = self.plugins.get(instance.name)
if reg:
logger.warning(
"Plugin '%(name)s' by '%(instance)s' is already provided by '%(reg)s'", {
'name': instance.name, 'instance': self._full_class_name(instance),
'reg': self._full_class_name(reg)
}
)
return False
for tag in instance.tags:
if tag not in PLUGIN_TAGS:
logger.warning(
"Invalid tag '%(tag)s' in '%(instance)s'",
{'tag': tag, 'instance': self._full_class_name(instance)}
)
return False
return True
|
alertot/detectem | detectem/matchers.py | extract_named_group | python | def extract_named_group(text, named_group, matchers, return_presence=False):
''' Return ``named_group`` match from ``text`` reached
by using a matcher from ``matchers``.
It also supports matching without a ``named_group`` in a matcher,
which sets ``presence=True``.
``presence`` is only returned if ``return_presence=True``.
'''
presence = False
for matcher in matchers:
if isinstance(matcher, str):
v = re.search(matcher, text, flags=re.DOTALL)
if v:
dict_result = v.groupdict()
try:
return dict_result[named_group]
except KeyError:
if dict_result:
# It's other named group matching, discard
continue
else:
# It's a matcher without named_group
# but we can't return it until every matcher pass
# because a following matcher could have a named group
presence = True
elif callable(matcher):
v = matcher(text)
if v:
return v
if return_presence and presence:
return 'presence'
return None | Return ``named_group`` match from ``text`` reached
by using a matcher from ``matchers``.
It also supports matching without a ``named_group`` in a matcher,
which sets ``presence=True``.
``presence`` is only returned if ``return_presence=True``. | train | https://github.com/alertot/detectem/blob/b1ecc3543b7c44ee76c4cac0d3896a7747bf86c1/detectem/matchers.py#L12-L48 | null | import re
from collections import namedtuple
from parsel import Selector
from detectem.utils import get_response_body
PluginMatch = namedtuple('PluginMatch', 'name,version,presence')
def extract_version(text, *matchers):
return extract_named_group(text, 'version', matchers, return_presence=True)
def extract_name(text, *matchers):
return extract_named_group(text, 'name', matchers)
class UrlMatcher:
@classmethod
def get_info(cls, entry, *matchers):
name = None
version = None
presence = False
for rtype in ['request', 'response']:
try:
url = entry[rtype]['url']
except KeyError:
# It could not contain response
continue
if not name:
name = extract_name(url, *matchers)
if not version:
version = extract_version(url, *matchers)
if version:
if version == 'presence':
presence = True
version = None
return PluginMatch(name=name, version=version, presence=presence)
class BodyMatcher:
@classmethod
def get_info(cls, entry, *matchers):
name = None
version = None
presence = False
body = get_response_body(entry)
name = extract_name(body, *matchers)
version = extract_version(body, *matchers)
if version:
if version == 'presence':
presence = True
version = None
return PluginMatch(name=name, version=version, presence=presence)
class HeaderMatcher:
@classmethod
def _get_matches(cls, headers, *matchers):
try:
for matcher_name, matcher_value in matchers:
for header in headers:
if header['name'] == matcher_name:
yield header['value'], matcher_value
except ValueError:
raise ValueError('Header matcher value must be a tuple')
@classmethod
def get_info(cls, entry, *matchers):
name = None
version = None
presence = False
headers = entry['response']['headers']
for hstring, hmatcher in cls._get_matches(headers, *matchers):
# Avoid overriding
if not name:
name = extract_name(hstring, hmatcher)
if not version:
version = extract_version(hstring, hmatcher)
if version:
if version == 'presence':
presence = True
version = None
return PluginMatch(name=name, version=version, presence=presence)
class XPathMatcher:
@classmethod
def get_info(cls, entry, *matchers):
name = None
version = None
presence = False
body = get_response_body(entry)
selector = Selector(text=body)
for matcher in matchers:
if len(matcher) == 2:
xpath, regexp = matcher
else:
xpath = matcher[0]
regexp = None
value = selector.xpath(xpath).extract_first()
if not value:
continue
if regexp:
# Avoid overriding
if not name:
name = extract_name(value, regexp)
version = extract_version(value, regexp)
if version == 'presence':
presence = True
version = None
break
else:
presence = True
return PluginMatch(name=name, version=version, presence=presence)
|
twitterdev/search-tweets-python | setup.py | parse_version | python | def parse_version(str_):
v = re.findall(r"\d+.\d+.\d+", str_)
if v:
return v[0]
else:
print("cannot parse string {}".format(str_))
raise KeyError | Parses the program's version from a python variable declaration. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/setup.py#L8-L17 | null | # -*- coding: utf-8 -*-
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
import re
from setuptools import setup, find_packages
# Our version is stored here.
with open("./searchtweets/_version.py") as f:
_version_line = [line for line in f.readlines()
if line.startswith("VERSION")][0].strip()
VERSION = parse_version(_version_line)
setup(name='searchtweets',
description="Wrapper for Twitter's Premium and Enterprise search APIs",
url='https://github.com/twitterdev/search-tweets-python',
author='Fiona Pigott, Jeff Kolb, Josh Montague, Aaron Gonzales',
long_description=open('README.rst', 'r', encoding="utf-8").read(),
author_email='agonzales@twitter.com',
license='MIT',
version=VERSION,
python_requires='>=3.3',
install_requires=["requests", "tweet_parser", "pyyaml"],
packages=find_packages(),
scripts=["tools/search_tweets.py"],
)
|
twitterdev/search-tweets-python | searchtweets/result_stream.py | make_session | python | def make_session(username=None, password=None, bearer_token=None, extra_headers_dict=None):
if password is None and bearer_token is None:
logger.error("No authentication information provided; "
"please check your object")
raise KeyError
session = requests.Session()
session.trust_env = False
headers = {'Accept-encoding': 'gzip',
'User-Agent': 'twitterdev-search-tweets-python/' + VERSION}
if bearer_token:
logger.info("using bearer token for authentication")
headers['Authorization'] = "Bearer {}".format(bearer_token)
session.headers = headers
else:
logger.info("using username and password for authentication")
session.auth = username, password
session.headers = headers
if extra_headers_dict:
headers.update(extra_headers_dict)
return session | Creates a Requests Session for use. Accepts a bearer token
for premiums users and will override username and password information if
present.
Args:
username (str): username for the session
password (str): password for the user
bearer_token (str): token for a premium API user. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L31-L61 | null | # -*- coding: utf-8 -*-
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
"""
This module contains the request handing and actual API wrapping functionality.
Its core method is the ``ResultStream`` object, which takes the API call
arguments and returns a stream of results to the user.
"""
import time
import re
import logging
import requests
try:
import ujson as json
except ImportError:
import json
from tweet_parser.tweet import Tweet
from .utils import merge_dicts
from .api_utils import infer_endpoint, change_to_count_endpoint
from ._version import VERSION
logger = logging.getLogger(__name__)
def retry(func):
"""
Decorator to handle API retries and exceptions. Defaults to three retries.
Args:
func (function): function for decoration
Returns:
decorated function
"""
def retried_func(*args, **kwargs):
max_tries = 3
tries = 0
while True:
try:
resp = func(*args, **kwargs)
except requests.exceptions.ConnectionError as exc:
exc.msg = "Connection error for session; exiting"
raise exc
except requests.exceptions.HTTPError as exc:
exc.msg = "HTTP error for session; exiting"
raise exc
if resp.status_code != 200 and tries < max_tries:
logger.warning("retrying request; current status code: {}"
.format(resp.status_code))
tries += 1
# mini exponential backoff here.
time.sleep(tries ** 2)
continue
break
if resp.status_code != 200:
error_message = resp.json()["error"]["message"]
logger.error("HTTP Error code: {}: {}".format(resp.status_code, error_message))
logger.error("Rule payload: {}".format(kwargs["rule_payload"]))
raise requests.exceptions.HTTPError
return resp
return retried_func
@retry
def request(session, url, rule_payload, **kwargs):
"""
Executes a request with the given payload and arguments.
Args:
session (requests.Session): the valid session object
url (str): Valid API endpoint
rule_payload (str or dict): rule package for the POST. If you pass a
dictionary, it will be converted into JSON.
"""
if isinstance(rule_payload, dict):
rule_payload = json.dumps(rule_payload)
logger.debug("sending request")
result = session.post(url, data=rule_payload, **kwargs)
return result
class ResultStream:
"""
Class to represent an API query that handles two major functionality
pieces: wrapping metadata around a specific API call and automatic
pagination of results.
Args:
username (str): username for enterprise customers
password (str): password for enterprise customers
bearer_token (str): bearer token for premium users
endpoint (str): API endpoint; see your console at developer.twitter.com
rule_payload (json or dict): payload for the post request
max_results (int): max number results that will be returned from this
instance. Note that this can be slightly lower than the total returned
from the API call - e.g., setting ``max_results = 10`` would return
ten results, but an API call will return at minimum 100 results.
tweetify (bool): If you are grabbing tweets and not counts, use the
tweet parser library to convert each raw tweet package to a Tweet
with lazy properties.
max_requests (int): A hard cutoff for the number of API calls this
instance will make. Good for testing in sandbox premium environments.
extra_headers_dict (dict): custom headers to add
Example:
>>> rs = ResultStream(**search_args, rule_payload=rule, max_pages=1)
>>> results = list(rs.stream())
"""
# leaving this here to have an API call counter for ALL objects in your
# session, helping with usage of the convenience functions in the library.
session_request_counter = 0
def __init__(self, endpoint, rule_payload, username=None, password=None,
bearer_token=None, extra_headers_dict=None, max_results=500,
tweetify=True, max_requests=None, **kwargs):
self.username = username
self.password = password
self.bearer_token = bearer_token
self.extra_headers_dict = extra_headers_dict
if isinstance(rule_payload, str):
rule_payload = json.loads(rule_payload)
self.rule_payload = rule_payload
self.tweetify = tweetify
# magic number of max tweets if you pass a non_int
self.max_results = (max_results if isinstance(max_results, int)
else 10 ** 15)
self.total_results = 0
self.n_requests = 0
self.session = None
self.current_tweets = None
self.next_token = None
self.stream_started = False
self._tweet_func = Tweet if tweetify else lambda x: x
# magic number of requests!
self.max_requests = (max_requests if max_requests is not None
else 10 ** 9)
self.endpoint = (change_to_count_endpoint(endpoint)
if infer_endpoint(rule_payload) == "counts"
else endpoint)
# validate_count_api(self.rule_payload, self.endpoint)
def stream(self):
"""
Main entry point for the data from the API. Will automatically paginate
through the results via the ``next`` token and return up to ``max_results``
tweets or up to ``max_requests`` API calls, whichever is lower.
Usage:
>>> result_stream = ResultStream(**kwargs)
>>> stream = result_stream.stream()
>>> results = list(stream)
>>> # or for faster usage...
>>> results = list(ResultStream(**kwargs).stream())
"""
self.init_session()
self.check_counts()
self.execute_request()
self.stream_started = True
while True:
for tweet in self.current_tweets:
if self.total_results >= self.max_results:
break
yield self._tweet_func(tweet)
self.total_results += 1
if self.next_token and self.total_results < self.max_results and self.n_requests <= self.max_requests:
self.rule_payload = merge_dicts(self.rule_payload,
{"next": self.next_token})
logger.info("paging; total requests read so far: {}"
.format(self.n_requests))
self.execute_request()
else:
break
logger.info("ending stream at {} tweets".format(self.total_results))
self.current_tweets = None
self.session.close()
def init_session(self):
"""
Defines a session object for passing requests.
"""
if self.session:
self.session.close()
self.session = make_session(self.username,
self.password,
self.bearer_token,
self.extra_headers_dict)
def check_counts(self):
"""
Disables tweet parsing if the count API is used.
"""
if "counts" in re.split("[/.]", self.endpoint):
logger.info("disabling tweet parsing due to counts API usage")
self._tweet_func = lambda x: x
def execute_request(self):
"""
Sends the request to the API and parses the json response.
Makes some assumptions about the session length and sets the presence
of a "next" token.
"""
if self.n_requests % 20 == 0 and self.n_requests > 1:
logger.info("refreshing session")
self.init_session()
resp = request(session=self.session,
url=self.endpoint,
rule_payload=self.rule_payload)
self.n_requests += 1
ResultStream.session_request_counter += 1
resp = json.loads(resp.content.decode(resp.encoding))
self.next_token = resp.get("next", None)
self.current_tweets = resp["results"]
def __repr__(self):
repr_keys = ["username", "endpoint", "rule_payload",
"tweetify", "max_results"]
str_ = json.dumps(dict([(k, self.__dict__.get(k)) for k in repr_keys]),
indent=4)
str_ = "ResultStream: \n\t" + str_
return str_
def collect_results(rule, max_results=500, result_stream_args=None):
"""
Utility function to quickly get a list of tweets from a ``ResultStream``
without keeping the object around. Requires your args to be configured
prior to using.
Args:
rule (str): valid powertrack rule for your account, preferably
generated by the `gen_rule_payload` function.
max_results (int): maximum number of tweets or counts to return from
the API / underlying ``ResultStream`` object.
result_stream_args (dict): configuration dict that has connection
information for a ``ResultStream`` object.
Returns:
list of results
Example:
>>> from searchtweets import collect_results
>>> tweets = collect_results(rule,
max_results=500,
result_stream_args=search_args)
"""
if result_stream_args is None:
logger.error("This function requires a configuration dict for the "
"inner ResultStream object.")
raise KeyError
rs = ResultStream(rule_payload=rule,
max_results=max_results,
**result_stream_args)
return list(rs.stream())
|
twitterdev/search-tweets-python | searchtweets/result_stream.py | retry | python | def retry(func):
def retried_func(*args, **kwargs):
max_tries = 3
tries = 0
while True:
try:
resp = func(*args, **kwargs)
except requests.exceptions.ConnectionError as exc:
exc.msg = "Connection error for session; exiting"
raise exc
except requests.exceptions.HTTPError as exc:
exc.msg = "HTTP error for session; exiting"
raise exc
if resp.status_code != 200 and tries < max_tries:
logger.warning("retrying request; current status code: {}"
.format(resp.status_code))
tries += 1
# mini exponential backoff here.
time.sleep(tries ** 2)
continue
break
if resp.status_code != 200:
error_message = resp.json()["error"]["message"]
logger.error("HTTP Error code: {}: {}".format(resp.status_code, error_message))
logger.error("Rule payload: {}".format(kwargs["rule_payload"]))
raise requests.exceptions.HTTPError
return resp
return retried_func | Decorator to handle API retries and exceptions. Defaults to three retries.
Args:
func (function): function for decoration
Returns:
decorated function | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L64-L108 | null | # -*- coding: utf-8 -*-
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
"""
This module contains the request handing and actual API wrapping functionality.
Its core method is the ``ResultStream`` object, which takes the API call
arguments and returns a stream of results to the user.
"""
import time
import re
import logging
import requests
try:
import ujson as json
except ImportError:
import json
from tweet_parser.tweet import Tweet
from .utils import merge_dicts
from .api_utils import infer_endpoint, change_to_count_endpoint
from ._version import VERSION
logger = logging.getLogger(__name__)
def make_session(username=None, password=None, bearer_token=None, extra_headers_dict=None):
"""Creates a Requests Session for use. Accepts a bearer token
for premiums users and will override username and password information if
present.
Args:
username (str): username for the session
password (str): password for the user
bearer_token (str): token for a premium API user.
"""
if password is None and bearer_token is None:
logger.error("No authentication information provided; "
"please check your object")
raise KeyError
session = requests.Session()
session.trust_env = False
headers = {'Accept-encoding': 'gzip',
'User-Agent': 'twitterdev-search-tweets-python/' + VERSION}
if bearer_token:
logger.info("using bearer token for authentication")
headers['Authorization'] = "Bearer {}".format(bearer_token)
session.headers = headers
else:
logger.info("using username and password for authentication")
session.auth = username, password
session.headers = headers
if extra_headers_dict:
headers.update(extra_headers_dict)
return session
@retry
def request(session, url, rule_payload, **kwargs):
"""
Executes a request with the given payload and arguments.
Args:
session (requests.Session): the valid session object
url (str): Valid API endpoint
rule_payload (str or dict): rule package for the POST. If you pass a
dictionary, it will be converted into JSON.
"""
if isinstance(rule_payload, dict):
rule_payload = json.dumps(rule_payload)
logger.debug("sending request")
result = session.post(url, data=rule_payload, **kwargs)
return result
class ResultStream:
"""
Class to represent an API query that handles two major functionality
pieces: wrapping metadata around a specific API call and automatic
pagination of results.
Args:
username (str): username for enterprise customers
password (str): password for enterprise customers
bearer_token (str): bearer token for premium users
endpoint (str): API endpoint; see your console at developer.twitter.com
rule_payload (json or dict): payload for the post request
max_results (int): max number results that will be returned from this
instance. Note that this can be slightly lower than the total returned
from the API call - e.g., setting ``max_results = 10`` would return
ten results, but an API call will return at minimum 100 results.
tweetify (bool): If you are grabbing tweets and not counts, use the
tweet parser library to convert each raw tweet package to a Tweet
with lazy properties.
max_requests (int): A hard cutoff for the number of API calls this
instance will make. Good for testing in sandbox premium environments.
extra_headers_dict (dict): custom headers to add
Example:
>>> rs = ResultStream(**search_args, rule_payload=rule, max_pages=1)
>>> results = list(rs.stream())
"""
# leaving this here to have an API call counter for ALL objects in your
# session, helping with usage of the convenience functions in the library.
session_request_counter = 0
def __init__(self, endpoint, rule_payload, username=None, password=None,
bearer_token=None, extra_headers_dict=None, max_results=500,
tweetify=True, max_requests=None, **kwargs):
self.username = username
self.password = password
self.bearer_token = bearer_token
self.extra_headers_dict = extra_headers_dict
if isinstance(rule_payload, str):
rule_payload = json.loads(rule_payload)
self.rule_payload = rule_payload
self.tweetify = tweetify
# magic number of max tweets if you pass a non_int
self.max_results = (max_results if isinstance(max_results, int)
else 10 ** 15)
self.total_results = 0
self.n_requests = 0
self.session = None
self.current_tweets = None
self.next_token = None
self.stream_started = False
self._tweet_func = Tweet if tweetify else lambda x: x
# magic number of requests!
self.max_requests = (max_requests if max_requests is not None
else 10 ** 9)
self.endpoint = (change_to_count_endpoint(endpoint)
if infer_endpoint(rule_payload) == "counts"
else endpoint)
# validate_count_api(self.rule_payload, self.endpoint)
def stream(self):
"""
Main entry point for the data from the API. Will automatically paginate
through the results via the ``next`` token and return up to ``max_results``
tweets or up to ``max_requests`` API calls, whichever is lower.
Usage:
>>> result_stream = ResultStream(**kwargs)
>>> stream = result_stream.stream()
>>> results = list(stream)
>>> # or for faster usage...
>>> results = list(ResultStream(**kwargs).stream())
"""
self.init_session()
self.check_counts()
self.execute_request()
self.stream_started = True
while True:
for tweet in self.current_tweets:
if self.total_results >= self.max_results:
break
yield self._tweet_func(tweet)
self.total_results += 1
if self.next_token and self.total_results < self.max_results and self.n_requests <= self.max_requests:
self.rule_payload = merge_dicts(self.rule_payload,
{"next": self.next_token})
logger.info("paging; total requests read so far: {}"
.format(self.n_requests))
self.execute_request()
else:
break
logger.info("ending stream at {} tweets".format(self.total_results))
self.current_tweets = None
self.session.close()
def init_session(self):
"""
Defines a session object for passing requests.
"""
if self.session:
self.session.close()
self.session = make_session(self.username,
self.password,
self.bearer_token,
self.extra_headers_dict)
def check_counts(self):
"""
Disables tweet parsing if the count API is used.
"""
if "counts" in re.split("[/.]", self.endpoint):
logger.info("disabling tweet parsing due to counts API usage")
self._tweet_func = lambda x: x
def execute_request(self):
"""
Sends the request to the API and parses the json response.
Makes some assumptions about the session length and sets the presence
of a "next" token.
"""
if self.n_requests % 20 == 0 and self.n_requests > 1:
logger.info("refreshing session")
self.init_session()
resp = request(session=self.session,
url=self.endpoint,
rule_payload=self.rule_payload)
self.n_requests += 1
ResultStream.session_request_counter += 1
resp = json.loads(resp.content.decode(resp.encoding))
self.next_token = resp.get("next", None)
self.current_tweets = resp["results"]
def __repr__(self):
repr_keys = ["username", "endpoint", "rule_payload",
"tweetify", "max_results"]
str_ = json.dumps(dict([(k, self.__dict__.get(k)) for k in repr_keys]),
indent=4)
str_ = "ResultStream: \n\t" + str_
return str_
def collect_results(rule, max_results=500, result_stream_args=None):
"""
Utility function to quickly get a list of tweets from a ``ResultStream``
without keeping the object around. Requires your args to be configured
prior to using.
Args:
rule (str): valid powertrack rule for your account, preferably
generated by the `gen_rule_payload` function.
max_results (int): maximum number of tweets or counts to return from
the API / underlying ``ResultStream`` object.
result_stream_args (dict): configuration dict that has connection
information for a ``ResultStream`` object.
Returns:
list of results
Example:
>>> from searchtweets import collect_results
>>> tweets = collect_results(rule,
max_results=500,
result_stream_args=search_args)
"""
if result_stream_args is None:
logger.error("This function requires a configuration dict for the "
"inner ResultStream object.")
raise KeyError
rs = ResultStream(rule_payload=rule,
max_results=max_results,
**result_stream_args)
return list(rs.stream())
|
twitterdev/search-tweets-python | searchtweets/result_stream.py | request | python | def request(session, url, rule_payload, **kwargs):
if isinstance(rule_payload, dict):
rule_payload = json.dumps(rule_payload)
logger.debug("sending request")
result = session.post(url, data=rule_payload, **kwargs)
return result | Executes a request with the given payload and arguments.
Args:
session (requests.Session): the valid session object
url (str): Valid API endpoint
rule_payload (str or dict): rule package for the POST. If you pass a
dictionary, it will be converted into JSON. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L112-L126 | null | # -*- coding: utf-8 -*-
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
"""
This module contains the request handing and actual API wrapping functionality.
Its core method is the ``ResultStream`` object, which takes the API call
arguments and returns a stream of results to the user.
"""
import time
import re
import logging
import requests
try:
import ujson as json
except ImportError:
import json
from tweet_parser.tweet import Tweet
from .utils import merge_dicts
from .api_utils import infer_endpoint, change_to_count_endpoint
from ._version import VERSION
logger = logging.getLogger(__name__)
def make_session(username=None, password=None, bearer_token=None, extra_headers_dict=None):
"""Creates a Requests Session for use. Accepts a bearer token
for premiums users and will override username and password information if
present.
Args:
username (str): username for the session
password (str): password for the user
bearer_token (str): token for a premium API user.
"""
if password is None and bearer_token is None:
logger.error("No authentication information provided; "
"please check your object")
raise KeyError
session = requests.Session()
session.trust_env = False
headers = {'Accept-encoding': 'gzip',
'User-Agent': 'twitterdev-search-tweets-python/' + VERSION}
if bearer_token:
logger.info("using bearer token for authentication")
headers['Authorization'] = "Bearer {}".format(bearer_token)
session.headers = headers
else:
logger.info("using username and password for authentication")
session.auth = username, password
session.headers = headers
if extra_headers_dict:
headers.update(extra_headers_dict)
return session
def retry(func):
"""
Decorator to handle API retries and exceptions. Defaults to three retries.
Args:
func (function): function for decoration
Returns:
decorated function
"""
def retried_func(*args, **kwargs):
max_tries = 3
tries = 0
while True:
try:
resp = func(*args, **kwargs)
except requests.exceptions.ConnectionError as exc:
exc.msg = "Connection error for session; exiting"
raise exc
except requests.exceptions.HTTPError as exc:
exc.msg = "HTTP error for session; exiting"
raise exc
if resp.status_code != 200 and tries < max_tries:
logger.warning("retrying request; current status code: {}"
.format(resp.status_code))
tries += 1
# mini exponential backoff here.
time.sleep(tries ** 2)
continue
break
if resp.status_code != 200:
error_message = resp.json()["error"]["message"]
logger.error("HTTP Error code: {}: {}".format(resp.status_code, error_message))
logger.error("Rule payload: {}".format(kwargs["rule_payload"]))
raise requests.exceptions.HTTPError
return resp
return retried_func
@retry
class ResultStream:
"""
Class to represent an API query that handles two major functionality
pieces: wrapping metadata around a specific API call and automatic
pagination of results.
Args:
username (str): username for enterprise customers
password (str): password for enterprise customers
bearer_token (str): bearer token for premium users
endpoint (str): API endpoint; see your console at developer.twitter.com
rule_payload (json or dict): payload for the post request
max_results (int): max number results that will be returned from this
instance. Note that this can be slightly lower than the total returned
from the API call - e.g., setting ``max_results = 10`` would return
ten results, but an API call will return at minimum 100 results.
tweetify (bool): If you are grabbing tweets and not counts, use the
tweet parser library to convert each raw tweet package to a Tweet
with lazy properties.
max_requests (int): A hard cutoff for the number of API calls this
instance will make. Good for testing in sandbox premium environments.
extra_headers_dict (dict): custom headers to add
Example:
>>> rs = ResultStream(**search_args, rule_payload=rule, max_pages=1)
>>> results = list(rs.stream())
"""
# leaving this here to have an API call counter for ALL objects in your
# session, helping with usage of the convenience functions in the library.
session_request_counter = 0
def __init__(self, endpoint, rule_payload, username=None, password=None,
bearer_token=None, extra_headers_dict=None, max_results=500,
tweetify=True, max_requests=None, **kwargs):
self.username = username
self.password = password
self.bearer_token = bearer_token
self.extra_headers_dict = extra_headers_dict
if isinstance(rule_payload, str):
rule_payload = json.loads(rule_payload)
self.rule_payload = rule_payload
self.tweetify = tweetify
# magic number of max tweets if you pass a non_int
self.max_results = (max_results if isinstance(max_results, int)
else 10 ** 15)
self.total_results = 0
self.n_requests = 0
self.session = None
self.current_tweets = None
self.next_token = None
self.stream_started = False
self._tweet_func = Tweet if tweetify else lambda x: x
# magic number of requests!
self.max_requests = (max_requests if max_requests is not None
else 10 ** 9)
self.endpoint = (change_to_count_endpoint(endpoint)
if infer_endpoint(rule_payload) == "counts"
else endpoint)
# validate_count_api(self.rule_payload, self.endpoint)
def stream(self):
"""
Main entry point for the data from the API. Will automatically paginate
through the results via the ``next`` token and return up to ``max_results``
tweets or up to ``max_requests`` API calls, whichever is lower.
Usage:
>>> result_stream = ResultStream(**kwargs)
>>> stream = result_stream.stream()
>>> results = list(stream)
>>> # or for faster usage...
>>> results = list(ResultStream(**kwargs).stream())
"""
self.init_session()
self.check_counts()
self.execute_request()
self.stream_started = True
while True:
for tweet in self.current_tweets:
if self.total_results >= self.max_results:
break
yield self._tweet_func(tweet)
self.total_results += 1
if self.next_token and self.total_results < self.max_results and self.n_requests <= self.max_requests:
self.rule_payload = merge_dicts(self.rule_payload,
{"next": self.next_token})
logger.info("paging; total requests read so far: {}"
.format(self.n_requests))
self.execute_request()
else:
break
logger.info("ending stream at {} tweets".format(self.total_results))
self.current_tweets = None
self.session.close()
def init_session(self):
"""
Defines a session object for passing requests.
"""
if self.session:
self.session.close()
self.session = make_session(self.username,
self.password,
self.bearer_token,
self.extra_headers_dict)
def check_counts(self):
"""
Disables tweet parsing if the count API is used.
"""
if "counts" in re.split("[/.]", self.endpoint):
logger.info("disabling tweet parsing due to counts API usage")
self._tweet_func = lambda x: x
def execute_request(self):
"""
Sends the request to the API and parses the json response.
Makes some assumptions about the session length and sets the presence
of a "next" token.
"""
if self.n_requests % 20 == 0 and self.n_requests > 1:
logger.info("refreshing session")
self.init_session()
resp = request(session=self.session,
url=self.endpoint,
rule_payload=self.rule_payload)
self.n_requests += 1
ResultStream.session_request_counter += 1
resp = json.loads(resp.content.decode(resp.encoding))
self.next_token = resp.get("next", None)
self.current_tweets = resp["results"]
def __repr__(self):
repr_keys = ["username", "endpoint", "rule_payload",
"tweetify", "max_results"]
str_ = json.dumps(dict([(k, self.__dict__.get(k)) for k in repr_keys]),
indent=4)
str_ = "ResultStream: \n\t" + str_
return str_
def collect_results(rule, max_results=500, result_stream_args=None):
"""
Utility function to quickly get a list of tweets from a ``ResultStream``
without keeping the object around. Requires your args to be configured
prior to using.
Args:
rule (str): valid powertrack rule for your account, preferably
generated by the `gen_rule_payload` function.
max_results (int): maximum number of tweets or counts to return from
the API / underlying ``ResultStream`` object.
result_stream_args (dict): configuration dict that has connection
information for a ``ResultStream`` object.
Returns:
list of results
Example:
>>> from searchtweets import collect_results
>>> tweets = collect_results(rule,
max_results=500,
result_stream_args=search_args)
"""
if result_stream_args is None:
logger.error("This function requires a configuration dict for the "
"inner ResultStream object.")
raise KeyError
rs = ResultStream(rule_payload=rule,
max_results=max_results,
**result_stream_args)
return list(rs.stream())
|
twitterdev/search-tweets-python | searchtweets/result_stream.py | collect_results | python | def collect_results(rule, max_results=500, result_stream_args=None):
if result_stream_args is None:
logger.error("This function requires a configuration dict for the "
"inner ResultStream object.")
raise KeyError
rs = ResultStream(rule_payload=rule,
max_results=max_results,
**result_stream_args)
return list(rs.stream()) | Utility function to quickly get a list of tweets from a ``ResultStream``
without keeping the object around. Requires your args to be configured
prior to using.
Args:
rule (str): valid powertrack rule for your account, preferably
generated by the `gen_rule_payload` function.
max_results (int): maximum number of tweets or counts to return from
the API / underlying ``ResultStream`` object.
result_stream_args (dict): configuration dict that has connection
information for a ``ResultStream`` object.
Returns:
list of results
Example:
>>> from searchtweets import collect_results
>>> tweets = collect_results(rule,
max_results=500,
result_stream_args=search_args) | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L276-L308 | [
"def stream(self):\n \"\"\"\n Main entry point for the data from the API. Will automatically paginate\n through the results via the ``next`` token and return up to ``max_results``\n tweets or up to ``max_requests`` API calls, whichever is lower.\n\n Usage:\n >>> result_stream = ResultStream(**... | # -*- coding: utf-8 -*-
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
"""
This module contains the request handing and actual API wrapping functionality.
Its core method is the ``ResultStream`` object, which takes the API call
arguments and returns a stream of results to the user.
"""
import time
import re
import logging
import requests
try:
import ujson as json
except ImportError:
import json
from tweet_parser.tweet import Tweet
from .utils import merge_dicts
from .api_utils import infer_endpoint, change_to_count_endpoint
from ._version import VERSION
logger = logging.getLogger(__name__)
def make_session(username=None, password=None, bearer_token=None, extra_headers_dict=None):
"""Creates a Requests Session for use. Accepts a bearer token
for premiums users and will override username and password information if
present.
Args:
username (str): username for the session
password (str): password for the user
bearer_token (str): token for a premium API user.
"""
if password is None and bearer_token is None:
logger.error("No authentication information provided; "
"please check your object")
raise KeyError
session = requests.Session()
session.trust_env = False
headers = {'Accept-encoding': 'gzip',
'User-Agent': 'twitterdev-search-tweets-python/' + VERSION}
if bearer_token:
logger.info("using bearer token for authentication")
headers['Authorization'] = "Bearer {}".format(bearer_token)
session.headers = headers
else:
logger.info("using username and password for authentication")
session.auth = username, password
session.headers = headers
if extra_headers_dict:
headers.update(extra_headers_dict)
return session
def retry(func):
"""
Decorator to handle API retries and exceptions. Defaults to three retries.
Args:
func (function): function for decoration
Returns:
decorated function
"""
def retried_func(*args, **kwargs):
max_tries = 3
tries = 0
while True:
try:
resp = func(*args, **kwargs)
except requests.exceptions.ConnectionError as exc:
exc.msg = "Connection error for session; exiting"
raise exc
except requests.exceptions.HTTPError as exc:
exc.msg = "HTTP error for session; exiting"
raise exc
if resp.status_code != 200 and tries < max_tries:
logger.warning("retrying request; current status code: {}"
.format(resp.status_code))
tries += 1
# mini exponential backoff here.
time.sleep(tries ** 2)
continue
break
if resp.status_code != 200:
error_message = resp.json()["error"]["message"]
logger.error("HTTP Error code: {}: {}".format(resp.status_code, error_message))
logger.error("Rule payload: {}".format(kwargs["rule_payload"]))
raise requests.exceptions.HTTPError
return resp
return retried_func
@retry
def request(session, url, rule_payload, **kwargs):
"""
Executes a request with the given payload and arguments.
Args:
session (requests.Session): the valid session object
url (str): Valid API endpoint
rule_payload (str or dict): rule package for the POST. If you pass a
dictionary, it will be converted into JSON.
"""
if isinstance(rule_payload, dict):
rule_payload = json.dumps(rule_payload)
logger.debug("sending request")
result = session.post(url, data=rule_payload, **kwargs)
return result
class ResultStream:
"""
Class to represent an API query that handles two major functionality
pieces: wrapping metadata around a specific API call and automatic
pagination of results.
Args:
username (str): username for enterprise customers
password (str): password for enterprise customers
bearer_token (str): bearer token for premium users
endpoint (str): API endpoint; see your console at developer.twitter.com
rule_payload (json or dict): payload for the post request
max_results (int): max number results that will be returned from this
instance. Note that this can be slightly lower than the total returned
from the API call - e.g., setting ``max_results = 10`` would return
ten results, but an API call will return at minimum 100 results.
tweetify (bool): If you are grabbing tweets and not counts, use the
tweet parser library to convert each raw tweet package to a Tweet
with lazy properties.
max_requests (int): A hard cutoff for the number of API calls this
instance will make. Good for testing in sandbox premium environments.
extra_headers_dict (dict): custom headers to add
Example:
>>> rs = ResultStream(**search_args, rule_payload=rule, max_pages=1)
>>> results = list(rs.stream())
"""
# leaving this here to have an API call counter for ALL objects in your
# session, helping with usage of the convenience functions in the library.
session_request_counter = 0
def __init__(self, endpoint, rule_payload, username=None, password=None,
bearer_token=None, extra_headers_dict=None, max_results=500,
tweetify=True, max_requests=None, **kwargs):
self.username = username
self.password = password
self.bearer_token = bearer_token
self.extra_headers_dict = extra_headers_dict
if isinstance(rule_payload, str):
rule_payload = json.loads(rule_payload)
self.rule_payload = rule_payload
self.tweetify = tweetify
# magic number of max tweets if you pass a non_int
self.max_results = (max_results if isinstance(max_results, int)
else 10 ** 15)
self.total_results = 0
self.n_requests = 0
self.session = None
self.current_tweets = None
self.next_token = None
self.stream_started = False
self._tweet_func = Tweet if tweetify else lambda x: x
# magic number of requests!
self.max_requests = (max_requests if max_requests is not None
else 10 ** 9)
self.endpoint = (change_to_count_endpoint(endpoint)
if infer_endpoint(rule_payload) == "counts"
else endpoint)
# validate_count_api(self.rule_payload, self.endpoint)
def stream(self):
"""
Main entry point for the data from the API. Will automatically paginate
through the results via the ``next`` token and return up to ``max_results``
tweets or up to ``max_requests`` API calls, whichever is lower.
Usage:
>>> result_stream = ResultStream(**kwargs)
>>> stream = result_stream.stream()
>>> results = list(stream)
>>> # or for faster usage...
>>> results = list(ResultStream(**kwargs).stream())
"""
self.init_session()
self.check_counts()
self.execute_request()
self.stream_started = True
while True:
for tweet in self.current_tweets:
if self.total_results >= self.max_results:
break
yield self._tweet_func(tweet)
self.total_results += 1
if self.next_token and self.total_results < self.max_results and self.n_requests <= self.max_requests:
self.rule_payload = merge_dicts(self.rule_payload,
{"next": self.next_token})
logger.info("paging; total requests read so far: {}"
.format(self.n_requests))
self.execute_request()
else:
break
logger.info("ending stream at {} tweets".format(self.total_results))
self.current_tweets = None
self.session.close()
def init_session(self):
"""
Defines a session object for passing requests.
"""
if self.session:
self.session.close()
self.session = make_session(self.username,
self.password,
self.bearer_token,
self.extra_headers_dict)
def check_counts(self):
"""
Disables tweet parsing if the count API is used.
"""
if "counts" in re.split("[/.]", self.endpoint):
logger.info("disabling tweet parsing due to counts API usage")
self._tweet_func = lambda x: x
def execute_request(self):
"""
Sends the request to the API and parses the json response.
Makes some assumptions about the session length and sets the presence
of a "next" token.
"""
if self.n_requests % 20 == 0 and self.n_requests > 1:
logger.info("refreshing session")
self.init_session()
resp = request(session=self.session,
url=self.endpoint,
rule_payload=self.rule_payload)
self.n_requests += 1
ResultStream.session_request_counter += 1
resp = json.loads(resp.content.decode(resp.encoding))
self.next_token = resp.get("next", None)
self.current_tweets = resp["results"]
def __repr__(self):
repr_keys = ["username", "endpoint", "rule_payload",
"tweetify", "max_results"]
str_ = json.dumps(dict([(k, self.__dict__.get(k)) for k in repr_keys]),
indent=4)
str_ = "ResultStream: \n\t" + str_
return str_
|
twitterdev/search-tweets-python | searchtweets/result_stream.py | ResultStream.stream | python | def stream(self):
self.init_session()
self.check_counts()
self.execute_request()
self.stream_started = True
while True:
for tweet in self.current_tweets:
if self.total_results >= self.max_results:
break
yield self._tweet_func(tweet)
self.total_results += 1
if self.next_token and self.total_results < self.max_results and self.n_requests <= self.max_requests:
self.rule_payload = merge_dicts(self.rule_payload,
{"next": self.next_token})
logger.info("paging; total requests read so far: {}"
.format(self.n_requests))
self.execute_request()
else:
break
logger.info("ending stream at {} tweets".format(self.total_results))
self.current_tweets = None
self.session.close() | Main entry point for the data from the API. Will automatically paginate
through the results via the ``next`` token and return up to ``max_results``
tweets or up to ``max_requests`` API calls, whichever is lower.
Usage:
>>> result_stream = ResultStream(**kwargs)
>>> stream = result_stream.stream()
>>> results = list(stream)
>>> # or for faster usage...
>>> results = list(ResultStream(**kwargs).stream()) | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L193-L227 | [
"def merge_dicts(*dicts):\n \"\"\"\n Helpful function to merge / combine dictionaries and return a new\n dictionary.\n\n Args:\n dicts (list or Iterable): iterable set of dictionaries for merging.\n\n Returns:\n dict: dict with all keys from the passed list. Later dictionaries in\n ... | class ResultStream:
"""
Class to represent an API query that handles two major functionality
pieces: wrapping metadata around a specific API call and automatic
pagination of results.
Args:
username (str): username for enterprise customers
password (str): password for enterprise customers
bearer_token (str): bearer token for premium users
endpoint (str): API endpoint; see your console at developer.twitter.com
rule_payload (json or dict): payload for the post request
max_results (int): max number results that will be returned from this
instance. Note that this can be slightly lower than the total returned
from the API call - e.g., setting ``max_results = 10`` would return
ten results, but an API call will return at minimum 100 results.
tweetify (bool): If you are grabbing tweets and not counts, use the
tweet parser library to convert each raw tweet package to a Tweet
with lazy properties.
max_requests (int): A hard cutoff for the number of API calls this
instance will make. Good for testing in sandbox premium environments.
extra_headers_dict (dict): custom headers to add
Example:
>>> rs = ResultStream(**search_args, rule_payload=rule, max_pages=1)
>>> results = list(rs.stream())
"""
# leaving this here to have an API call counter for ALL objects in your
# session, helping with usage of the convenience functions in the library.
session_request_counter = 0
def __init__(self, endpoint, rule_payload, username=None, password=None,
bearer_token=None, extra_headers_dict=None, max_results=500,
tweetify=True, max_requests=None, **kwargs):
self.username = username
self.password = password
self.bearer_token = bearer_token
self.extra_headers_dict = extra_headers_dict
if isinstance(rule_payload, str):
rule_payload = json.loads(rule_payload)
self.rule_payload = rule_payload
self.tweetify = tweetify
# magic number of max tweets if you pass a non_int
self.max_results = (max_results if isinstance(max_results, int)
else 10 ** 15)
self.total_results = 0
self.n_requests = 0
self.session = None
self.current_tweets = None
self.next_token = None
self.stream_started = False
self._tweet_func = Tweet if tweetify else lambda x: x
# magic number of requests!
self.max_requests = (max_requests if max_requests is not None
else 10 ** 9)
self.endpoint = (change_to_count_endpoint(endpoint)
if infer_endpoint(rule_payload) == "counts"
else endpoint)
# validate_count_api(self.rule_payload, self.endpoint)
def init_session(self):
"""
Defines a session object for passing requests.
"""
if self.session:
self.session.close()
self.session = make_session(self.username,
self.password,
self.bearer_token,
self.extra_headers_dict)
def check_counts(self):
"""
Disables tweet parsing if the count API is used.
"""
if "counts" in re.split("[/.]", self.endpoint):
logger.info("disabling tweet parsing due to counts API usage")
self._tweet_func = lambda x: x
def execute_request(self):
"""
Sends the request to the API and parses the json response.
Makes some assumptions about the session length and sets the presence
of a "next" token.
"""
if self.n_requests % 20 == 0 and self.n_requests > 1:
logger.info("refreshing session")
self.init_session()
resp = request(session=self.session,
url=self.endpoint,
rule_payload=self.rule_payload)
self.n_requests += 1
ResultStream.session_request_counter += 1
resp = json.loads(resp.content.decode(resp.encoding))
self.next_token = resp.get("next", None)
self.current_tweets = resp["results"]
def __repr__(self):
repr_keys = ["username", "endpoint", "rule_payload",
"tweetify", "max_results"]
str_ = json.dumps(dict([(k, self.__dict__.get(k)) for k in repr_keys]),
indent=4)
str_ = "ResultStream: \n\t" + str_
return str_
|
twitterdev/search-tweets-python | searchtweets/result_stream.py | ResultStream.init_session | python | def init_session(self):
if self.session:
self.session.close()
self.session = make_session(self.username,
self.password,
self.bearer_token,
self.extra_headers_dict) | Defines a session object for passing requests. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L229-L238 | [
"def make_session(username=None, password=None, bearer_token=None, extra_headers_dict=None): \n \"\"\"Creates a Requests Session for use. Accepts a bearer token\n for premiums users and will override username and password information if\n present.\n\n Args:\n username (str): username for the sess... | class ResultStream:
"""
Class to represent an API query that handles two major functionality
pieces: wrapping metadata around a specific API call and automatic
pagination of results.
Args:
username (str): username for enterprise customers
password (str): password for enterprise customers
bearer_token (str): bearer token for premium users
endpoint (str): API endpoint; see your console at developer.twitter.com
rule_payload (json or dict): payload for the post request
max_results (int): max number results that will be returned from this
instance. Note that this can be slightly lower than the total returned
from the API call - e.g., setting ``max_results = 10`` would return
ten results, but an API call will return at minimum 100 results.
tweetify (bool): If you are grabbing tweets and not counts, use the
tweet parser library to convert each raw tweet package to a Tweet
with lazy properties.
max_requests (int): A hard cutoff for the number of API calls this
instance will make. Good for testing in sandbox premium environments.
extra_headers_dict (dict): custom headers to add
Example:
>>> rs = ResultStream(**search_args, rule_payload=rule, max_pages=1)
>>> results = list(rs.stream())
"""
# leaving this here to have an API call counter for ALL objects in your
# session, helping with usage of the convenience functions in the library.
session_request_counter = 0
def __init__(self, endpoint, rule_payload, username=None, password=None,
bearer_token=None, extra_headers_dict=None, max_results=500,
tweetify=True, max_requests=None, **kwargs):
self.username = username
self.password = password
self.bearer_token = bearer_token
self.extra_headers_dict = extra_headers_dict
if isinstance(rule_payload, str):
rule_payload = json.loads(rule_payload)
self.rule_payload = rule_payload
self.tweetify = tweetify
# magic number of max tweets if you pass a non_int
self.max_results = (max_results if isinstance(max_results, int)
else 10 ** 15)
self.total_results = 0
self.n_requests = 0
self.session = None
self.current_tweets = None
self.next_token = None
self.stream_started = False
self._tweet_func = Tweet if tweetify else lambda x: x
# magic number of requests!
self.max_requests = (max_requests if max_requests is not None
else 10 ** 9)
self.endpoint = (change_to_count_endpoint(endpoint)
if infer_endpoint(rule_payload) == "counts"
else endpoint)
# validate_count_api(self.rule_payload, self.endpoint)
def stream(self):
"""
Main entry point for the data from the API. Will automatically paginate
through the results via the ``next`` token and return up to ``max_results``
tweets or up to ``max_requests`` API calls, whichever is lower.
Usage:
>>> result_stream = ResultStream(**kwargs)
>>> stream = result_stream.stream()
>>> results = list(stream)
>>> # or for faster usage...
>>> results = list(ResultStream(**kwargs).stream())
"""
self.init_session()
self.check_counts()
self.execute_request()
self.stream_started = True
while True:
for tweet in self.current_tweets:
if self.total_results >= self.max_results:
break
yield self._tweet_func(tweet)
self.total_results += 1
if self.next_token and self.total_results < self.max_results and self.n_requests <= self.max_requests:
self.rule_payload = merge_dicts(self.rule_payload,
{"next": self.next_token})
logger.info("paging; total requests read so far: {}"
.format(self.n_requests))
self.execute_request()
else:
break
logger.info("ending stream at {} tweets".format(self.total_results))
self.current_tweets = None
self.session.close()
def check_counts(self):
"""
Disables tweet parsing if the count API is used.
"""
if "counts" in re.split("[/.]", self.endpoint):
logger.info("disabling tweet parsing due to counts API usage")
self._tweet_func = lambda x: x
def execute_request(self):
"""
Sends the request to the API and parses the json response.
Makes some assumptions about the session length and sets the presence
of a "next" token.
"""
if self.n_requests % 20 == 0 and self.n_requests > 1:
logger.info("refreshing session")
self.init_session()
resp = request(session=self.session,
url=self.endpoint,
rule_payload=self.rule_payload)
self.n_requests += 1
ResultStream.session_request_counter += 1
resp = json.loads(resp.content.decode(resp.encoding))
self.next_token = resp.get("next", None)
self.current_tweets = resp["results"]
def __repr__(self):
repr_keys = ["username", "endpoint", "rule_payload",
"tweetify", "max_results"]
str_ = json.dumps(dict([(k, self.__dict__.get(k)) for k in repr_keys]),
indent=4)
str_ = "ResultStream: \n\t" + str_
return str_
|
twitterdev/search-tweets-python | searchtweets/result_stream.py | ResultStream.check_counts | python | def check_counts(self):
if "counts" in re.split("[/.]", self.endpoint):
logger.info("disabling tweet parsing due to counts API usage")
self._tweet_func = lambda x: x | Disables tweet parsing if the count API is used. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L240-L246 | null | class ResultStream:
"""
Class to represent an API query that handles two major functionality
pieces: wrapping metadata around a specific API call and automatic
pagination of results.
Args:
username (str): username for enterprise customers
password (str): password for enterprise customers
bearer_token (str): bearer token for premium users
endpoint (str): API endpoint; see your console at developer.twitter.com
rule_payload (json or dict): payload for the post request
max_results (int): max number results that will be returned from this
instance. Note that this can be slightly lower than the total returned
from the API call - e.g., setting ``max_results = 10`` would return
ten results, but an API call will return at minimum 100 results.
tweetify (bool): If you are grabbing tweets and not counts, use the
tweet parser library to convert each raw tweet package to a Tweet
with lazy properties.
max_requests (int): A hard cutoff for the number of API calls this
instance will make. Good for testing in sandbox premium environments.
extra_headers_dict (dict): custom headers to add
Example:
>>> rs = ResultStream(**search_args, rule_payload=rule, max_pages=1)
>>> results = list(rs.stream())
"""
# leaving this here to have an API call counter for ALL objects in your
# session, helping with usage of the convenience functions in the library.
session_request_counter = 0
def __init__(self, endpoint, rule_payload, username=None, password=None,
bearer_token=None, extra_headers_dict=None, max_results=500,
tweetify=True, max_requests=None, **kwargs):
self.username = username
self.password = password
self.bearer_token = bearer_token
self.extra_headers_dict = extra_headers_dict
if isinstance(rule_payload, str):
rule_payload = json.loads(rule_payload)
self.rule_payload = rule_payload
self.tweetify = tweetify
# magic number of max tweets if you pass a non_int
self.max_results = (max_results if isinstance(max_results, int)
else 10 ** 15)
self.total_results = 0
self.n_requests = 0
self.session = None
self.current_tweets = None
self.next_token = None
self.stream_started = False
self._tweet_func = Tweet if tweetify else lambda x: x
# magic number of requests!
self.max_requests = (max_requests if max_requests is not None
else 10 ** 9)
self.endpoint = (change_to_count_endpoint(endpoint)
if infer_endpoint(rule_payload) == "counts"
else endpoint)
# validate_count_api(self.rule_payload, self.endpoint)
def stream(self):
"""
Main entry point for the data from the API. Will automatically paginate
through the results via the ``next`` token and return up to ``max_results``
tweets or up to ``max_requests`` API calls, whichever is lower.
Usage:
>>> result_stream = ResultStream(**kwargs)
>>> stream = result_stream.stream()
>>> results = list(stream)
>>> # or for faster usage...
>>> results = list(ResultStream(**kwargs).stream())
"""
self.init_session()
self.check_counts()
self.execute_request()
self.stream_started = True
while True:
for tweet in self.current_tweets:
if self.total_results >= self.max_results:
break
yield self._tweet_func(tweet)
self.total_results += 1
if self.next_token and self.total_results < self.max_results and self.n_requests <= self.max_requests:
self.rule_payload = merge_dicts(self.rule_payload,
{"next": self.next_token})
logger.info("paging; total requests read so far: {}"
.format(self.n_requests))
self.execute_request()
else:
break
logger.info("ending stream at {} tweets".format(self.total_results))
self.current_tweets = None
self.session.close()
def init_session(self):
"""
Defines a session object for passing requests.
"""
if self.session:
self.session.close()
self.session = make_session(self.username,
self.password,
self.bearer_token,
self.extra_headers_dict)
def execute_request(self):
"""
Sends the request to the API and parses the json response.
Makes some assumptions about the session length and sets the presence
of a "next" token.
"""
if self.n_requests % 20 == 0 and self.n_requests > 1:
logger.info("refreshing session")
self.init_session()
resp = request(session=self.session,
url=self.endpoint,
rule_payload=self.rule_payload)
self.n_requests += 1
ResultStream.session_request_counter += 1
resp = json.loads(resp.content.decode(resp.encoding))
self.next_token = resp.get("next", None)
self.current_tweets = resp["results"]
def __repr__(self):
repr_keys = ["username", "endpoint", "rule_payload",
"tweetify", "max_results"]
str_ = json.dumps(dict([(k, self.__dict__.get(k)) for k in repr_keys]),
indent=4)
str_ = "ResultStream: \n\t" + str_
return str_
|
twitterdev/search-tweets-python | searchtweets/result_stream.py | ResultStream.execute_request | python | def execute_request(self):
if self.n_requests % 20 == 0 and self.n_requests > 1:
logger.info("refreshing session")
self.init_session()
resp = request(session=self.session,
url=self.endpoint,
rule_payload=self.rule_payload)
self.n_requests += 1
ResultStream.session_request_counter += 1
resp = json.loads(resp.content.decode(resp.encoding))
self.next_token = resp.get("next", None)
self.current_tweets = resp["results"] | Sends the request to the API and parses the json response.
Makes some assumptions about the session length and sets the presence
of a "next" token. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/result_stream.py#L248-L265 | [
"def init_session(self):\n \"\"\"\n Defines a session object for passing requests.\n \"\"\"\n if self.session:\n self.session.close()\n self.session = make_session(self.username,\n self.password,\n self.bearer_token,\n ... | class ResultStream:
"""
Class to represent an API query that handles two major functionality
pieces: wrapping metadata around a specific API call and automatic
pagination of results.
Args:
username (str): username for enterprise customers
password (str): password for enterprise customers
bearer_token (str): bearer token for premium users
endpoint (str): API endpoint; see your console at developer.twitter.com
rule_payload (json or dict): payload for the post request
max_results (int): max number results that will be returned from this
instance. Note that this can be slightly lower than the total returned
from the API call - e.g., setting ``max_results = 10`` would return
ten results, but an API call will return at minimum 100 results.
tweetify (bool): If you are grabbing tweets and not counts, use the
tweet parser library to convert each raw tweet package to a Tweet
with lazy properties.
max_requests (int): A hard cutoff for the number of API calls this
instance will make. Good for testing in sandbox premium environments.
extra_headers_dict (dict): custom headers to add
Example:
>>> rs = ResultStream(**search_args, rule_payload=rule, max_pages=1)
>>> results = list(rs.stream())
"""
# leaving this here to have an API call counter for ALL objects in your
# session, helping with usage of the convenience functions in the library.
session_request_counter = 0
def __init__(self, endpoint, rule_payload, username=None, password=None,
bearer_token=None, extra_headers_dict=None, max_results=500,
tweetify=True, max_requests=None, **kwargs):
self.username = username
self.password = password
self.bearer_token = bearer_token
self.extra_headers_dict = extra_headers_dict
if isinstance(rule_payload, str):
rule_payload = json.loads(rule_payload)
self.rule_payload = rule_payload
self.tweetify = tweetify
# magic number of max tweets if you pass a non_int
self.max_results = (max_results if isinstance(max_results, int)
else 10 ** 15)
self.total_results = 0
self.n_requests = 0
self.session = None
self.current_tweets = None
self.next_token = None
self.stream_started = False
self._tweet_func = Tweet if tweetify else lambda x: x
# magic number of requests!
self.max_requests = (max_requests if max_requests is not None
else 10 ** 9)
self.endpoint = (change_to_count_endpoint(endpoint)
if infer_endpoint(rule_payload) == "counts"
else endpoint)
# validate_count_api(self.rule_payload, self.endpoint)
def stream(self):
"""
Main entry point for the data from the API. Will automatically paginate
through the results via the ``next`` token and return up to ``max_results``
tweets or up to ``max_requests`` API calls, whichever is lower.
Usage:
>>> result_stream = ResultStream(**kwargs)
>>> stream = result_stream.stream()
>>> results = list(stream)
>>> # or for faster usage...
>>> results = list(ResultStream(**kwargs).stream())
"""
self.init_session()
self.check_counts()
self.execute_request()
self.stream_started = True
while True:
for tweet in self.current_tweets:
if self.total_results >= self.max_results:
break
yield self._tweet_func(tweet)
self.total_results += 1
if self.next_token and self.total_results < self.max_results and self.n_requests <= self.max_requests:
self.rule_payload = merge_dicts(self.rule_payload,
{"next": self.next_token})
logger.info("paging; total requests read so far: {}"
.format(self.n_requests))
self.execute_request()
else:
break
logger.info("ending stream at {} tweets".format(self.total_results))
self.current_tweets = None
self.session.close()
def init_session(self):
"""
Defines a session object for passing requests.
"""
if self.session:
self.session.close()
self.session = make_session(self.username,
self.password,
self.bearer_token,
self.extra_headers_dict)
def check_counts(self):
"""
Disables tweet parsing if the count API is used.
"""
if "counts" in re.split("[/.]", self.endpoint):
logger.info("disabling tweet parsing due to counts API usage")
self._tweet_func = lambda x: x
def __repr__(self):
repr_keys = ["username", "endpoint", "rule_payload",
"tweetify", "max_results"]
str_ = json.dumps(dict([(k, self.__dict__.get(k)) for k in repr_keys]),
indent=4)
str_ = "ResultStream: \n\t" + str_
return str_
|
twitterdev/search-tweets-python | searchtweets/api_utils.py | convert_utc_time | python | def convert_utc_time(datetime_str):
if not datetime_str:
return None
if not set(['-', ':']) & set(datetime_str):
_date = datetime.datetime.strptime(datetime_str, "%Y%m%d%H%M")
else:
try:
if "T" in datetime_str:
# command line with 'T'
datetime_str = datetime_str.replace('T', ' ')
_date = datetime.datetime.strptime(datetime_str, "%Y-%m-%d %H:%M")
except ValueError:
_date = datetime.datetime.strptime(datetime_str, "%Y-%m-%d")
return _date.strftime("%Y%m%d%H%M") | Handles datetime argument conversion to the GNIP API format, which is
`YYYYMMDDHHSS`. Flexible passing of date formats in the following types::
- YYYYmmDDHHMM
- YYYY-mm-DD
- YYYY-mm-DD HH:MM
- YYYY-mm-DDTHH:MM
Args:
datetime_str (str): valid formats are listed above.
Returns:
string of GNIP API formatted date.
Example:
>>> from searchtweets.utils import convert_utc_time
>>> convert_utc_time("201708020000")
'201708020000'
>>> convert_utc_time("2017-08-02")
'201708020000'
>>> convert_utc_time("2017-08-02 00:00")
'201708020000'
>>> convert_utc_time("2017-08-02T00:00")
'201708020000' | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/api_utils.py#L24-L63 | null | # -*- coding: utf-8 -*-
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
"""
Module containing the various functions that are used for API calls,
rule generation, and related.
"""
import re
import datetime
import logging
try:
import ujson as json
except ImportError:
import json
__all__ = ["gen_rule_payload", "gen_params_from_config",
"infer_endpoint", "convert_utc_time",
"validate_count_api", "change_to_count_endpoint"]
logger = logging.getLogger(__name__)
def change_to_count_endpoint(endpoint):
"""Utility function to change a normal endpoint to a ``count`` api
endpoint. Returns the same endpoint if it's already a valid count endpoint.
Args:
endpoint (str): your api endpoint
Returns:
str: the modified endpoint for a count endpoint.
"""
tokens = filter(lambda x: x != '', re.split("[/:]", endpoint))
filt_tokens = list(filter(lambda x: x != "https", tokens))
last = filt_tokens[-1].split('.')[0] # removes .json on the endpoint
filt_tokens[-1] = last # changes from *.json -> '' for changing input
if last == 'counts':
return endpoint
else:
return "https://" + '/'.join(filt_tokens) + '/' + "counts.json"
def gen_rule_payload(pt_rule, results_per_call=None,
from_date=None, to_date=None, count_bucket=None,
tag=None,
stringify=True):
"""
Generates the dict or json payload for a PowerTrack rule.
Args:
pt_rule (str): The string version of a powertrack rule,
e.g., "beyonce has:geo". Accepts multi-line strings
for ease of entry.
results_per_call (int): number of tweets or counts returned per API
call. This maps to the ``maxResults`` search API parameter.
Defaults to 500 to reduce API call usage.
from_date (str or None): Date format as specified by
`convert_utc_time` for the starting time of your search.
to_date (str or None): date format as specified by `convert_utc_time`
for the end time of your search.
count_bucket (str or None): If using the counts api endpoint,
will define the count bucket for which tweets are aggregated.
stringify (bool): specifies the return type, `dict`
or json-formatted `str`.
Example:
>>> from searchtweets.utils import gen_rule_payload
>>> gen_rule_payload("beyonce has:geo",
... from_date="2017-08-21",
... to_date="2017-08-22")
'{"query":"beyonce has:geo","maxResults":100,"toDate":"201708220000","fromDate":"201708210000"}'
"""
pt_rule = ' '.join(pt_rule.split()) # allows multi-line strings
payload = {"query": pt_rule}
if results_per_call is not None and isinstance(results_per_call, int) is True:
payload["maxResults"] = results_per_call
if to_date:
payload["toDate"] = convert_utc_time(to_date)
if from_date:
payload["fromDate"] = convert_utc_time(from_date)
if count_bucket:
if set(["day", "hour", "minute"]) & set([count_bucket]):
payload["bucket"] = count_bucket
del payload["maxResults"]
else:
logger.error("invalid count bucket: provided {}"
.format(count_bucket))
raise ValueError
if tag:
payload["tag"] = tag
return json.dumps(payload) if stringify else payload
def gen_params_from_config(config_dict):
"""
Generates parameters for a ResultStream from a dictionary.
"""
if config_dict.get("count_bucket"):
logger.warning("change your endpoint to the count endpoint; this is "
"default behavior when the count bucket "
"field is defined")
endpoint = change_to_count_endpoint(config_dict.get("endpoint"))
else:
endpoint = config_dict.get("endpoint")
def intify(arg):
if not isinstance(arg, int) and arg is not None:
return int(arg)
else:
return arg
# this parameter comes in as a string when it's parsed
results_per_call = intify(config_dict.get("results_per_call", None))
rule = gen_rule_payload(pt_rule=config_dict["pt_rule"],
from_date=config_dict.get("from_date", None),
to_date=config_dict.get("to_date", None),
results_per_call=results_per_call,
count_bucket=config_dict.get("count_bucket", None))
_dict = {"endpoint": endpoint,
"username": config_dict.get("username"),
"password": config_dict.get("password"),
"bearer_token": config_dict.get("bearer_token"),
"extra_headers_dict": config_dict.get("extra_headers_dict",None),
"rule_payload": rule,
"results_per_file": intify(config_dict.get("results_per_file")),
"max_results": intify(config_dict.get("max_results")),
"max_pages": intify(config_dict.get("max_pages", None))}
return _dict
def infer_endpoint(rule_payload):
"""
Infer which endpoint should be used for a given rule payload.
"""
bucket = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload)).get("bucket")
return "counts" if bucket else "search"
def validate_count_api(rule_payload, endpoint):
"""
Ensures that the counts api is set correctly in a payload.
"""
rule = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload))
bucket = rule.get('bucket')
counts = set(endpoint.split("/")) & {"counts.json"}
if len(counts) == 0:
if bucket is not None:
msg = ("""There is a count bucket present in your payload,
but you are using not using the counts API.
Please check your endpoints and try again""")
logger.error(msg)
raise ValueError
|
twitterdev/search-tweets-python | searchtweets/api_utils.py | change_to_count_endpoint | python | def change_to_count_endpoint(endpoint):
tokens = filter(lambda x: x != '', re.split("[/:]", endpoint))
filt_tokens = list(filter(lambda x: x != "https", tokens))
last = filt_tokens[-1].split('.')[0] # removes .json on the endpoint
filt_tokens[-1] = last # changes from *.json -> '' for changing input
if last == 'counts':
return endpoint
else:
return "https://" + '/'.join(filt_tokens) + '/' + "counts.json" | Utility function to change a normal endpoint to a ``count`` api
endpoint. Returns the same endpoint if it's already a valid count endpoint.
Args:
endpoint (str): your api endpoint
Returns:
str: the modified endpoint for a count endpoint. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/api_utils.py#L66-L83 | null | # -*- coding: utf-8 -*-
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
"""
Module containing the various functions that are used for API calls,
rule generation, and related.
"""
import re
import datetime
import logging
try:
import ujson as json
except ImportError:
import json
__all__ = ["gen_rule_payload", "gen_params_from_config",
"infer_endpoint", "convert_utc_time",
"validate_count_api", "change_to_count_endpoint"]
logger = logging.getLogger(__name__)
def convert_utc_time(datetime_str):
"""
Handles datetime argument conversion to the GNIP API format, which is
`YYYYMMDDHHSS`. Flexible passing of date formats in the following types::
- YYYYmmDDHHMM
- YYYY-mm-DD
- YYYY-mm-DD HH:MM
- YYYY-mm-DDTHH:MM
Args:
datetime_str (str): valid formats are listed above.
Returns:
string of GNIP API formatted date.
Example:
>>> from searchtweets.utils import convert_utc_time
>>> convert_utc_time("201708020000")
'201708020000'
>>> convert_utc_time("2017-08-02")
'201708020000'
>>> convert_utc_time("2017-08-02 00:00")
'201708020000'
>>> convert_utc_time("2017-08-02T00:00")
'201708020000'
"""
if not datetime_str:
return None
if not set(['-', ':']) & set(datetime_str):
_date = datetime.datetime.strptime(datetime_str, "%Y%m%d%H%M")
else:
try:
if "T" in datetime_str:
# command line with 'T'
datetime_str = datetime_str.replace('T', ' ')
_date = datetime.datetime.strptime(datetime_str, "%Y-%m-%d %H:%M")
except ValueError:
_date = datetime.datetime.strptime(datetime_str, "%Y-%m-%d")
return _date.strftime("%Y%m%d%H%M")
def gen_rule_payload(pt_rule, results_per_call=None,
from_date=None, to_date=None, count_bucket=None,
tag=None,
stringify=True):
"""
Generates the dict or json payload for a PowerTrack rule.
Args:
pt_rule (str): The string version of a powertrack rule,
e.g., "beyonce has:geo". Accepts multi-line strings
for ease of entry.
results_per_call (int): number of tweets or counts returned per API
call. This maps to the ``maxResults`` search API parameter.
Defaults to 500 to reduce API call usage.
from_date (str or None): Date format as specified by
`convert_utc_time` for the starting time of your search.
to_date (str or None): date format as specified by `convert_utc_time`
for the end time of your search.
count_bucket (str or None): If using the counts api endpoint,
will define the count bucket for which tweets are aggregated.
stringify (bool): specifies the return type, `dict`
or json-formatted `str`.
Example:
>>> from searchtweets.utils import gen_rule_payload
>>> gen_rule_payload("beyonce has:geo",
... from_date="2017-08-21",
... to_date="2017-08-22")
'{"query":"beyonce has:geo","maxResults":100,"toDate":"201708220000","fromDate":"201708210000"}'
"""
pt_rule = ' '.join(pt_rule.split()) # allows multi-line strings
payload = {"query": pt_rule}
if results_per_call is not None and isinstance(results_per_call, int) is True:
payload["maxResults"] = results_per_call
if to_date:
payload["toDate"] = convert_utc_time(to_date)
if from_date:
payload["fromDate"] = convert_utc_time(from_date)
if count_bucket:
if set(["day", "hour", "minute"]) & set([count_bucket]):
payload["bucket"] = count_bucket
del payload["maxResults"]
else:
logger.error("invalid count bucket: provided {}"
.format(count_bucket))
raise ValueError
if tag:
payload["tag"] = tag
return json.dumps(payload) if stringify else payload
def gen_params_from_config(config_dict):
"""
Generates parameters for a ResultStream from a dictionary.
"""
if config_dict.get("count_bucket"):
logger.warning("change your endpoint to the count endpoint; this is "
"default behavior when the count bucket "
"field is defined")
endpoint = change_to_count_endpoint(config_dict.get("endpoint"))
else:
endpoint = config_dict.get("endpoint")
def intify(arg):
if not isinstance(arg, int) and arg is not None:
return int(arg)
else:
return arg
# this parameter comes in as a string when it's parsed
results_per_call = intify(config_dict.get("results_per_call", None))
rule = gen_rule_payload(pt_rule=config_dict["pt_rule"],
from_date=config_dict.get("from_date", None),
to_date=config_dict.get("to_date", None),
results_per_call=results_per_call,
count_bucket=config_dict.get("count_bucket", None))
_dict = {"endpoint": endpoint,
"username": config_dict.get("username"),
"password": config_dict.get("password"),
"bearer_token": config_dict.get("bearer_token"),
"extra_headers_dict": config_dict.get("extra_headers_dict",None),
"rule_payload": rule,
"results_per_file": intify(config_dict.get("results_per_file")),
"max_results": intify(config_dict.get("max_results")),
"max_pages": intify(config_dict.get("max_pages", None))}
return _dict
def infer_endpoint(rule_payload):
"""
Infer which endpoint should be used for a given rule payload.
"""
bucket = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload)).get("bucket")
return "counts" if bucket else "search"
def validate_count_api(rule_payload, endpoint):
"""
Ensures that the counts api is set correctly in a payload.
"""
rule = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload))
bucket = rule.get('bucket')
counts = set(endpoint.split("/")) & {"counts.json"}
if len(counts) == 0:
if bucket is not None:
msg = ("""There is a count bucket present in your payload,
but you are using not using the counts API.
Please check your endpoints and try again""")
logger.error(msg)
raise ValueError
|
twitterdev/search-tweets-python | searchtweets/api_utils.py | gen_rule_payload | python | def gen_rule_payload(pt_rule, results_per_call=None,
from_date=None, to_date=None, count_bucket=None,
tag=None,
stringify=True):
pt_rule = ' '.join(pt_rule.split()) # allows multi-line strings
payload = {"query": pt_rule}
if results_per_call is not None and isinstance(results_per_call, int) is True:
payload["maxResults"] = results_per_call
if to_date:
payload["toDate"] = convert_utc_time(to_date)
if from_date:
payload["fromDate"] = convert_utc_time(from_date)
if count_bucket:
if set(["day", "hour", "minute"]) & set([count_bucket]):
payload["bucket"] = count_bucket
del payload["maxResults"]
else:
logger.error("invalid count bucket: provided {}"
.format(count_bucket))
raise ValueError
if tag:
payload["tag"] = tag
return json.dumps(payload) if stringify else payload | Generates the dict or json payload for a PowerTrack rule.
Args:
pt_rule (str): The string version of a powertrack rule,
e.g., "beyonce has:geo". Accepts multi-line strings
for ease of entry.
results_per_call (int): number of tweets or counts returned per API
call. This maps to the ``maxResults`` search API parameter.
Defaults to 500 to reduce API call usage.
from_date (str or None): Date format as specified by
`convert_utc_time` for the starting time of your search.
to_date (str or None): date format as specified by `convert_utc_time`
for the end time of your search.
count_bucket (str or None): If using the counts api endpoint,
will define the count bucket for which tweets are aggregated.
stringify (bool): specifies the return type, `dict`
or json-formatted `str`.
Example:
>>> from searchtweets.utils import gen_rule_payload
>>> gen_rule_payload("beyonce has:geo",
... from_date="2017-08-21",
... to_date="2017-08-22")
'{"query":"beyonce has:geo","maxResults":100,"toDate":"201708220000","fromDate":"201708210000"}' | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/api_utils.py#L86-L138 | [
"def convert_utc_time(datetime_str):\n \"\"\"\n Handles datetime argument conversion to the GNIP API format, which is\n `YYYYMMDDHHSS`. Flexible passing of date formats in the following types::\n\n - YYYYmmDDHHMM\n - YYYY-mm-DD\n - YYYY-mm-DD HH:MM\n - YYYY-mm-DDTHH:MM\n\n Ar... | # -*- coding: utf-8 -*-
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
"""
Module containing the various functions that are used for API calls,
rule generation, and related.
"""
import re
import datetime
import logging
try:
import ujson as json
except ImportError:
import json
__all__ = ["gen_rule_payload", "gen_params_from_config",
"infer_endpoint", "convert_utc_time",
"validate_count_api", "change_to_count_endpoint"]
logger = logging.getLogger(__name__)
def convert_utc_time(datetime_str):
"""
Handles datetime argument conversion to the GNIP API format, which is
`YYYYMMDDHHSS`. Flexible passing of date formats in the following types::
- YYYYmmDDHHMM
- YYYY-mm-DD
- YYYY-mm-DD HH:MM
- YYYY-mm-DDTHH:MM
Args:
datetime_str (str): valid formats are listed above.
Returns:
string of GNIP API formatted date.
Example:
>>> from searchtweets.utils import convert_utc_time
>>> convert_utc_time("201708020000")
'201708020000'
>>> convert_utc_time("2017-08-02")
'201708020000'
>>> convert_utc_time("2017-08-02 00:00")
'201708020000'
>>> convert_utc_time("2017-08-02T00:00")
'201708020000'
"""
if not datetime_str:
return None
if not set(['-', ':']) & set(datetime_str):
_date = datetime.datetime.strptime(datetime_str, "%Y%m%d%H%M")
else:
try:
if "T" in datetime_str:
# command line with 'T'
datetime_str = datetime_str.replace('T', ' ')
_date = datetime.datetime.strptime(datetime_str, "%Y-%m-%d %H:%M")
except ValueError:
_date = datetime.datetime.strptime(datetime_str, "%Y-%m-%d")
return _date.strftime("%Y%m%d%H%M")
def change_to_count_endpoint(endpoint):
"""Utility function to change a normal endpoint to a ``count`` api
endpoint. Returns the same endpoint if it's already a valid count endpoint.
Args:
endpoint (str): your api endpoint
Returns:
str: the modified endpoint for a count endpoint.
"""
tokens = filter(lambda x: x != '', re.split("[/:]", endpoint))
filt_tokens = list(filter(lambda x: x != "https", tokens))
last = filt_tokens[-1].split('.')[0] # removes .json on the endpoint
filt_tokens[-1] = last # changes from *.json -> '' for changing input
if last == 'counts':
return endpoint
else:
return "https://" + '/'.join(filt_tokens) + '/' + "counts.json"
def gen_params_from_config(config_dict):
"""
Generates parameters for a ResultStream from a dictionary.
"""
if config_dict.get("count_bucket"):
logger.warning("change your endpoint to the count endpoint; this is "
"default behavior when the count bucket "
"field is defined")
endpoint = change_to_count_endpoint(config_dict.get("endpoint"))
else:
endpoint = config_dict.get("endpoint")
def intify(arg):
if not isinstance(arg, int) and arg is not None:
return int(arg)
else:
return arg
# this parameter comes in as a string when it's parsed
results_per_call = intify(config_dict.get("results_per_call", None))
rule = gen_rule_payload(pt_rule=config_dict["pt_rule"],
from_date=config_dict.get("from_date", None),
to_date=config_dict.get("to_date", None),
results_per_call=results_per_call,
count_bucket=config_dict.get("count_bucket", None))
_dict = {"endpoint": endpoint,
"username": config_dict.get("username"),
"password": config_dict.get("password"),
"bearer_token": config_dict.get("bearer_token"),
"extra_headers_dict": config_dict.get("extra_headers_dict",None),
"rule_payload": rule,
"results_per_file": intify(config_dict.get("results_per_file")),
"max_results": intify(config_dict.get("max_results")),
"max_pages": intify(config_dict.get("max_pages", None))}
return _dict
def infer_endpoint(rule_payload):
"""
Infer which endpoint should be used for a given rule payload.
"""
bucket = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload)).get("bucket")
return "counts" if bucket else "search"
def validate_count_api(rule_payload, endpoint):
"""
Ensures that the counts api is set correctly in a payload.
"""
rule = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload))
bucket = rule.get('bucket')
counts = set(endpoint.split("/")) & {"counts.json"}
if len(counts) == 0:
if bucket is not None:
msg = ("""There is a count bucket present in your payload,
but you are using not using the counts API.
Please check your endpoints and try again""")
logger.error(msg)
raise ValueError
|
twitterdev/search-tweets-python | searchtweets/api_utils.py | gen_params_from_config | python | def gen_params_from_config(config_dict):
if config_dict.get("count_bucket"):
logger.warning("change your endpoint to the count endpoint; this is "
"default behavior when the count bucket "
"field is defined")
endpoint = change_to_count_endpoint(config_dict.get("endpoint"))
else:
endpoint = config_dict.get("endpoint")
def intify(arg):
if not isinstance(arg, int) and arg is not None:
return int(arg)
else:
return arg
# this parameter comes in as a string when it's parsed
results_per_call = intify(config_dict.get("results_per_call", None))
rule = gen_rule_payload(pt_rule=config_dict["pt_rule"],
from_date=config_dict.get("from_date", None),
to_date=config_dict.get("to_date", None),
results_per_call=results_per_call,
count_bucket=config_dict.get("count_bucket", None))
_dict = {"endpoint": endpoint,
"username": config_dict.get("username"),
"password": config_dict.get("password"),
"bearer_token": config_dict.get("bearer_token"),
"extra_headers_dict": config_dict.get("extra_headers_dict",None),
"rule_payload": rule,
"results_per_file": intify(config_dict.get("results_per_file")),
"max_results": intify(config_dict.get("max_results")),
"max_pages": intify(config_dict.get("max_pages", None))}
return _dict | Generates parameters for a ResultStream from a dictionary. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/api_utils.py#L141-L179 | [
"def gen_rule_payload(pt_rule, results_per_call=None,\n from_date=None, to_date=None, count_bucket=None,\n tag=None,\n stringify=True):\n\n \"\"\"\n Generates the dict or json payload for a PowerTrack rule.\n\n Args:\n pt_rule (str): The st... | # -*- coding: utf-8 -*-
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
"""
Module containing the various functions that are used for API calls,
rule generation, and related.
"""
import re
import datetime
import logging
try:
import ujson as json
except ImportError:
import json
__all__ = ["gen_rule_payload", "gen_params_from_config",
"infer_endpoint", "convert_utc_time",
"validate_count_api", "change_to_count_endpoint"]
logger = logging.getLogger(__name__)
def convert_utc_time(datetime_str):
"""
Handles datetime argument conversion to the GNIP API format, which is
`YYYYMMDDHHSS`. Flexible passing of date formats in the following types::
- YYYYmmDDHHMM
- YYYY-mm-DD
- YYYY-mm-DD HH:MM
- YYYY-mm-DDTHH:MM
Args:
datetime_str (str): valid formats are listed above.
Returns:
string of GNIP API formatted date.
Example:
>>> from searchtweets.utils import convert_utc_time
>>> convert_utc_time("201708020000")
'201708020000'
>>> convert_utc_time("2017-08-02")
'201708020000'
>>> convert_utc_time("2017-08-02 00:00")
'201708020000'
>>> convert_utc_time("2017-08-02T00:00")
'201708020000'
"""
if not datetime_str:
return None
if not set(['-', ':']) & set(datetime_str):
_date = datetime.datetime.strptime(datetime_str, "%Y%m%d%H%M")
else:
try:
if "T" in datetime_str:
# command line with 'T'
datetime_str = datetime_str.replace('T', ' ')
_date = datetime.datetime.strptime(datetime_str, "%Y-%m-%d %H:%M")
except ValueError:
_date = datetime.datetime.strptime(datetime_str, "%Y-%m-%d")
return _date.strftime("%Y%m%d%H%M")
def change_to_count_endpoint(endpoint):
"""Utility function to change a normal endpoint to a ``count`` api
endpoint. Returns the same endpoint if it's already a valid count endpoint.
Args:
endpoint (str): your api endpoint
Returns:
str: the modified endpoint for a count endpoint.
"""
tokens = filter(lambda x: x != '', re.split("[/:]", endpoint))
filt_tokens = list(filter(lambda x: x != "https", tokens))
last = filt_tokens[-1].split('.')[0] # removes .json on the endpoint
filt_tokens[-1] = last # changes from *.json -> '' for changing input
if last == 'counts':
return endpoint
else:
return "https://" + '/'.join(filt_tokens) + '/' + "counts.json"
def gen_rule_payload(pt_rule, results_per_call=None,
from_date=None, to_date=None, count_bucket=None,
tag=None,
stringify=True):
"""
Generates the dict or json payload for a PowerTrack rule.
Args:
pt_rule (str): The string version of a powertrack rule,
e.g., "beyonce has:geo". Accepts multi-line strings
for ease of entry.
results_per_call (int): number of tweets or counts returned per API
call. This maps to the ``maxResults`` search API parameter.
Defaults to 500 to reduce API call usage.
from_date (str or None): Date format as specified by
`convert_utc_time` for the starting time of your search.
to_date (str or None): date format as specified by `convert_utc_time`
for the end time of your search.
count_bucket (str or None): If using the counts api endpoint,
will define the count bucket for which tweets are aggregated.
stringify (bool): specifies the return type, `dict`
or json-formatted `str`.
Example:
>>> from searchtweets.utils import gen_rule_payload
>>> gen_rule_payload("beyonce has:geo",
... from_date="2017-08-21",
... to_date="2017-08-22")
'{"query":"beyonce has:geo","maxResults":100,"toDate":"201708220000","fromDate":"201708210000"}'
"""
pt_rule = ' '.join(pt_rule.split()) # allows multi-line strings
payload = {"query": pt_rule}
if results_per_call is not None and isinstance(results_per_call, int) is True:
payload["maxResults"] = results_per_call
if to_date:
payload["toDate"] = convert_utc_time(to_date)
if from_date:
payload["fromDate"] = convert_utc_time(from_date)
if count_bucket:
if set(["day", "hour", "minute"]) & set([count_bucket]):
payload["bucket"] = count_bucket
del payload["maxResults"]
else:
logger.error("invalid count bucket: provided {}"
.format(count_bucket))
raise ValueError
if tag:
payload["tag"] = tag
return json.dumps(payload) if stringify else payload
def infer_endpoint(rule_payload):
"""
Infer which endpoint should be used for a given rule payload.
"""
bucket = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload)).get("bucket")
return "counts" if bucket else "search"
def validate_count_api(rule_payload, endpoint):
"""
Ensures that the counts api is set correctly in a payload.
"""
rule = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload))
bucket = rule.get('bucket')
counts = set(endpoint.split("/")) & {"counts.json"}
if len(counts) == 0:
if bucket is not None:
msg = ("""There is a count bucket present in your payload,
but you are using not using the counts API.
Please check your endpoints and try again""")
logger.error(msg)
raise ValueError
|
twitterdev/search-tweets-python | searchtweets/api_utils.py | infer_endpoint | python | def infer_endpoint(rule_payload):
bucket = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload)).get("bucket")
return "counts" if bucket else "search" | Infer which endpoint should be used for a given rule payload. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/api_utils.py#L182-L188 | null | # -*- coding: utf-8 -*-
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
"""
Module containing the various functions that are used for API calls,
rule generation, and related.
"""
import re
import datetime
import logging
try:
import ujson as json
except ImportError:
import json
__all__ = ["gen_rule_payload", "gen_params_from_config",
"infer_endpoint", "convert_utc_time",
"validate_count_api", "change_to_count_endpoint"]
logger = logging.getLogger(__name__)
def convert_utc_time(datetime_str):
"""
Handles datetime argument conversion to the GNIP API format, which is
`YYYYMMDDHHSS`. Flexible passing of date formats in the following types::
- YYYYmmDDHHMM
- YYYY-mm-DD
- YYYY-mm-DD HH:MM
- YYYY-mm-DDTHH:MM
Args:
datetime_str (str): valid formats are listed above.
Returns:
string of GNIP API formatted date.
Example:
>>> from searchtweets.utils import convert_utc_time
>>> convert_utc_time("201708020000")
'201708020000'
>>> convert_utc_time("2017-08-02")
'201708020000'
>>> convert_utc_time("2017-08-02 00:00")
'201708020000'
>>> convert_utc_time("2017-08-02T00:00")
'201708020000'
"""
if not datetime_str:
return None
if not set(['-', ':']) & set(datetime_str):
_date = datetime.datetime.strptime(datetime_str, "%Y%m%d%H%M")
else:
try:
if "T" in datetime_str:
# command line with 'T'
datetime_str = datetime_str.replace('T', ' ')
_date = datetime.datetime.strptime(datetime_str, "%Y-%m-%d %H:%M")
except ValueError:
_date = datetime.datetime.strptime(datetime_str, "%Y-%m-%d")
return _date.strftime("%Y%m%d%H%M")
def change_to_count_endpoint(endpoint):
"""Utility function to change a normal endpoint to a ``count`` api
endpoint. Returns the same endpoint if it's already a valid count endpoint.
Args:
endpoint (str): your api endpoint
Returns:
str: the modified endpoint for a count endpoint.
"""
tokens = filter(lambda x: x != '', re.split("[/:]", endpoint))
filt_tokens = list(filter(lambda x: x != "https", tokens))
last = filt_tokens[-1].split('.')[0] # removes .json on the endpoint
filt_tokens[-1] = last # changes from *.json -> '' for changing input
if last == 'counts':
return endpoint
else:
return "https://" + '/'.join(filt_tokens) + '/' + "counts.json"
def gen_rule_payload(pt_rule, results_per_call=None,
from_date=None, to_date=None, count_bucket=None,
tag=None,
stringify=True):
"""
Generates the dict or json payload for a PowerTrack rule.
Args:
pt_rule (str): The string version of a powertrack rule,
e.g., "beyonce has:geo". Accepts multi-line strings
for ease of entry.
results_per_call (int): number of tweets or counts returned per API
call. This maps to the ``maxResults`` search API parameter.
Defaults to 500 to reduce API call usage.
from_date (str or None): Date format as specified by
`convert_utc_time` for the starting time of your search.
to_date (str or None): date format as specified by `convert_utc_time`
for the end time of your search.
count_bucket (str or None): If using the counts api endpoint,
will define the count bucket for which tweets are aggregated.
stringify (bool): specifies the return type, `dict`
or json-formatted `str`.
Example:
>>> from searchtweets.utils import gen_rule_payload
>>> gen_rule_payload("beyonce has:geo",
... from_date="2017-08-21",
... to_date="2017-08-22")
'{"query":"beyonce has:geo","maxResults":100,"toDate":"201708220000","fromDate":"201708210000"}'
"""
pt_rule = ' '.join(pt_rule.split()) # allows multi-line strings
payload = {"query": pt_rule}
if results_per_call is not None and isinstance(results_per_call, int) is True:
payload["maxResults"] = results_per_call
if to_date:
payload["toDate"] = convert_utc_time(to_date)
if from_date:
payload["fromDate"] = convert_utc_time(from_date)
if count_bucket:
if set(["day", "hour", "minute"]) & set([count_bucket]):
payload["bucket"] = count_bucket
del payload["maxResults"]
else:
logger.error("invalid count bucket: provided {}"
.format(count_bucket))
raise ValueError
if tag:
payload["tag"] = tag
return json.dumps(payload) if stringify else payload
def gen_params_from_config(config_dict):
"""
Generates parameters for a ResultStream from a dictionary.
"""
if config_dict.get("count_bucket"):
logger.warning("change your endpoint to the count endpoint; this is "
"default behavior when the count bucket "
"field is defined")
endpoint = change_to_count_endpoint(config_dict.get("endpoint"))
else:
endpoint = config_dict.get("endpoint")
def intify(arg):
if not isinstance(arg, int) and arg is not None:
return int(arg)
else:
return arg
# this parameter comes in as a string when it's parsed
results_per_call = intify(config_dict.get("results_per_call", None))
rule = gen_rule_payload(pt_rule=config_dict["pt_rule"],
from_date=config_dict.get("from_date", None),
to_date=config_dict.get("to_date", None),
results_per_call=results_per_call,
count_bucket=config_dict.get("count_bucket", None))
_dict = {"endpoint": endpoint,
"username": config_dict.get("username"),
"password": config_dict.get("password"),
"bearer_token": config_dict.get("bearer_token"),
"extra_headers_dict": config_dict.get("extra_headers_dict",None),
"rule_payload": rule,
"results_per_file": intify(config_dict.get("results_per_file")),
"max_results": intify(config_dict.get("max_results")),
"max_pages": intify(config_dict.get("max_pages", None))}
return _dict
def validate_count_api(rule_payload, endpoint):
"""
Ensures that the counts api is set correctly in a payload.
"""
rule = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload))
bucket = rule.get('bucket')
counts = set(endpoint.split("/")) & {"counts.json"}
if len(counts) == 0:
if bucket is not None:
msg = ("""There is a count bucket present in your payload,
but you are using not using the counts API.
Please check your endpoints and try again""")
logger.error(msg)
raise ValueError
|
twitterdev/search-tweets-python | searchtweets/api_utils.py | validate_count_api | python | def validate_count_api(rule_payload, endpoint):
rule = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload))
bucket = rule.get('bucket')
counts = set(endpoint.split("/")) & {"counts.json"}
if len(counts) == 0:
if bucket is not None:
msg = ("""There is a count bucket present in your payload,
but you are using not using the counts API.
Please check your endpoints and try again""")
logger.error(msg)
raise ValueError | Ensures that the counts api is set correctly in a payload. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/api_utils.py#L191-L205 | null | # -*- coding: utf-8 -*-
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
"""
Module containing the various functions that are used for API calls,
rule generation, and related.
"""
import re
import datetime
import logging
try:
import ujson as json
except ImportError:
import json
__all__ = ["gen_rule_payload", "gen_params_from_config",
"infer_endpoint", "convert_utc_time",
"validate_count_api", "change_to_count_endpoint"]
logger = logging.getLogger(__name__)
def convert_utc_time(datetime_str):
"""
Handles datetime argument conversion to the GNIP API format, which is
`YYYYMMDDHHSS`. Flexible passing of date formats in the following types::
- YYYYmmDDHHMM
- YYYY-mm-DD
- YYYY-mm-DD HH:MM
- YYYY-mm-DDTHH:MM
Args:
datetime_str (str): valid formats are listed above.
Returns:
string of GNIP API formatted date.
Example:
>>> from searchtweets.utils import convert_utc_time
>>> convert_utc_time("201708020000")
'201708020000'
>>> convert_utc_time("2017-08-02")
'201708020000'
>>> convert_utc_time("2017-08-02 00:00")
'201708020000'
>>> convert_utc_time("2017-08-02T00:00")
'201708020000'
"""
if not datetime_str:
return None
if not set(['-', ':']) & set(datetime_str):
_date = datetime.datetime.strptime(datetime_str, "%Y%m%d%H%M")
else:
try:
if "T" in datetime_str:
# command line with 'T'
datetime_str = datetime_str.replace('T', ' ')
_date = datetime.datetime.strptime(datetime_str, "%Y-%m-%d %H:%M")
except ValueError:
_date = datetime.datetime.strptime(datetime_str, "%Y-%m-%d")
return _date.strftime("%Y%m%d%H%M")
def change_to_count_endpoint(endpoint):
"""Utility function to change a normal endpoint to a ``count`` api
endpoint. Returns the same endpoint if it's already a valid count endpoint.
Args:
endpoint (str): your api endpoint
Returns:
str: the modified endpoint for a count endpoint.
"""
tokens = filter(lambda x: x != '', re.split("[/:]", endpoint))
filt_tokens = list(filter(lambda x: x != "https", tokens))
last = filt_tokens[-1].split('.')[0] # removes .json on the endpoint
filt_tokens[-1] = last # changes from *.json -> '' for changing input
if last == 'counts':
return endpoint
else:
return "https://" + '/'.join(filt_tokens) + '/' + "counts.json"
def gen_rule_payload(pt_rule, results_per_call=None,
from_date=None, to_date=None, count_bucket=None,
tag=None,
stringify=True):
"""
Generates the dict or json payload for a PowerTrack rule.
Args:
pt_rule (str): The string version of a powertrack rule,
e.g., "beyonce has:geo". Accepts multi-line strings
for ease of entry.
results_per_call (int): number of tweets or counts returned per API
call. This maps to the ``maxResults`` search API parameter.
Defaults to 500 to reduce API call usage.
from_date (str or None): Date format as specified by
`convert_utc_time` for the starting time of your search.
to_date (str or None): date format as specified by `convert_utc_time`
for the end time of your search.
count_bucket (str or None): If using the counts api endpoint,
will define the count bucket for which tweets are aggregated.
stringify (bool): specifies the return type, `dict`
or json-formatted `str`.
Example:
>>> from searchtweets.utils import gen_rule_payload
>>> gen_rule_payload("beyonce has:geo",
... from_date="2017-08-21",
... to_date="2017-08-22")
'{"query":"beyonce has:geo","maxResults":100,"toDate":"201708220000","fromDate":"201708210000"}'
"""
pt_rule = ' '.join(pt_rule.split()) # allows multi-line strings
payload = {"query": pt_rule}
if results_per_call is not None and isinstance(results_per_call, int) is True:
payload["maxResults"] = results_per_call
if to_date:
payload["toDate"] = convert_utc_time(to_date)
if from_date:
payload["fromDate"] = convert_utc_time(from_date)
if count_bucket:
if set(["day", "hour", "minute"]) & set([count_bucket]):
payload["bucket"] = count_bucket
del payload["maxResults"]
else:
logger.error("invalid count bucket: provided {}"
.format(count_bucket))
raise ValueError
if tag:
payload["tag"] = tag
return json.dumps(payload) if stringify else payload
def gen_params_from_config(config_dict):
"""
Generates parameters for a ResultStream from a dictionary.
"""
if config_dict.get("count_bucket"):
logger.warning("change your endpoint to the count endpoint; this is "
"default behavior when the count bucket "
"field is defined")
endpoint = change_to_count_endpoint(config_dict.get("endpoint"))
else:
endpoint = config_dict.get("endpoint")
def intify(arg):
if not isinstance(arg, int) and arg is not None:
return int(arg)
else:
return arg
# this parameter comes in as a string when it's parsed
results_per_call = intify(config_dict.get("results_per_call", None))
rule = gen_rule_payload(pt_rule=config_dict["pt_rule"],
from_date=config_dict.get("from_date", None),
to_date=config_dict.get("to_date", None),
results_per_call=results_per_call,
count_bucket=config_dict.get("count_bucket", None))
_dict = {"endpoint": endpoint,
"username": config_dict.get("username"),
"password": config_dict.get("password"),
"bearer_token": config_dict.get("bearer_token"),
"extra_headers_dict": config_dict.get("extra_headers_dict",None),
"rule_payload": rule,
"results_per_file": intify(config_dict.get("results_per_file")),
"max_results": intify(config_dict.get("max_results")),
"max_pages": intify(config_dict.get("max_pages", None))}
return _dict
def infer_endpoint(rule_payload):
"""
Infer which endpoint should be used for a given rule payload.
"""
bucket = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload)).get("bucket")
return "counts" if bucket else "search"
|
twitterdev/search-tweets-python | searchtweets/utils.py | partition | python | def partition(iterable, chunk_size, pad_none=False):
args = [iter(iterable)] * chunk_size
if not pad_none:
return zip(*args)
else:
return it.zip_longest(*args) | adapted from Toolz. Breaks an iterable into n iterables up to the
certain chunk size, padding with Nones if availble.
Example:
>>> from searchtweets.utils import partition
>>> iter_ = range(10)
>>> list(partition(iter_, 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(partition(iter_, 3, pad_none=True))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)] | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/utils.py#L41-L57 | null | """
Utility functions that are used in various parts of the program.
"""
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
from functools import reduce
import itertools as it
import os
import types
import codecs
import datetime
import logging
import configparser
from configparser import MissingSectionHeaderError
try:
import ujson as json
except ImportError:
import json
import yaml
logger = logging.getLogger(__name__)
__all__ = ["take", "partition", "merge_dicts", "write_result_stream",
"read_config"]
def take(n, iterable):
"""Return first n items of the iterable as a list.
Originally found in the Python itertools documentation.
Args:
n (int): number of items to return
iterable (iterable): the object to select
"""
return it.islice(iterable, n)
def merge_dicts(*dicts):
"""
Helpful function to merge / combine dictionaries and return a new
dictionary.
Args:
dicts (list or Iterable): iterable set of dictionaries for merging.
Returns:
dict: dict with all keys from the passed list. Later dictionaries in
the sequence will override duplicate keys from previous dictionaries.
Example:
>>> from searchtweets.utils import merge_dicts
>>> d1 = {"rule": "something has:geo"}
>>> d2 = {"maxResults": 1000}
>>> merge_dicts(*[d1, d2])
{"maxResults": 1000, "rule": "something has:geo"}
"""
def _merge_dicts(dict1, dict2):
merged = dict1.copy()
merged.update(dict2)
return merged
return reduce(_merge_dicts, dicts)
def write_ndjson(filename, data_iterable, append=False, **kwargs):
"""
Generator that writes newline-delimited json to a file and returns items
from an iterable.
"""
write_mode = "ab" if append else "wb"
logger.info("writing to file {}".format(filename))
with codecs.open(filename, write_mode, "utf-8") as outfile:
for item in data_iterable:
outfile.write(json.dumps(item) + "\n")
yield item
def write_result_stream(result_stream, filename_prefix=None,
results_per_file=None, **kwargs):
"""
Wraps a ``ResultStream`` object to save it to a file. This function will still
return all data from the result stream as a generator that wraps the
``write_ndjson`` method.
Args:
result_stream (ResultStream): the unstarted ResultStream object
filename_prefix (str or None): the base name for file writing
results_per_file (int or None): the maximum number of tweets to write
per file. Defaults to having no max, which means one file. Multiple
files will be named by datetime, according to
``<prefix>_YYY-mm-ddTHH_MM_SS.json``.
"""
if isinstance(result_stream, types.GeneratorType):
stream = result_stream
else:
stream = result_stream.stream()
file_time_formatter = "%Y-%m-%dT%H_%M_%S"
if filename_prefix is None:
filename_prefix = "twitter_search_results"
if results_per_file:
logger.info("chunking result stream to files with {} tweets per file"
.format(results_per_file))
chunked_stream = partition(stream, results_per_file, pad_none=True)
for chunk in chunked_stream:
chunk = filter(lambda x: x is not None, chunk)
curr_datetime = (datetime.datetime.utcnow()
.strftime(file_time_formatter))
_filename = "{}_{}.json".format(filename_prefix, curr_datetime)
yield from write_ndjson(_filename, chunk)
else:
curr_datetime = (datetime.datetime.utcnow()
.strftime(file_time_formatter))
_filename = "{}.json".format(filename_prefix)
yield from write_ndjson(_filename, stream)
def read_config(filename):
"""Reads and flattens a configuration file into a single
dictionary for ease of use. Works with both ``.config`` and
``.yaml`` files. Files should look like this::
search_rules:
from-date: 2017-06-01
to-date: 2017-09-01 01:01
pt-rule: kanye
search_params:
results-per-call: 500
max-results: 500
output_params:
save_file: True
filename_prefix: kanye
results_per_file: 10000000
or::
[search_rules]
from_date = 2017-06-01
to_date = 2017-09-01
pt_rule = beyonce has:geo
[search_params]
results_per_call = 500
max_results = 500
[output_params]
save_file = True
filename_prefix = beyonce
results_per_file = 10000000
Args:
filename (str): location of file with extension ('.config' or '.yaml')
Returns:
dict: parsed configuration dictionary.
"""
file_type = "yaml" if filename.endswith(".yaml") else "config"
config = configparser.ConfigParser()
if file_type == "yaml":
with open(os.path.expanduser(filename)) as f:
config_dict = yaml.load(f)
config_dict = merge_dicts(*[dict(config_dict[s]) for s
in config_dict.keys()])
elif file_type == "config":
with open(filename) as f:
config.read_file(f)
config_dict = merge_dicts(*[dict(config[s]) for s
in config.sections()])
else:
logger.error("Config files must be either in YAML or Config style.")
raise TypeError
# ensure args are renamed correctly:
config_dict = {k.replace('-', '_'): v for k, v in config_dict.items()}
# YAML will parse datestrings as datetimes; we'll convert them here if they
# exist
if config_dict.get("to_date") is not None:
config_dict["to_date"] = str(config_dict["to_date"])
if config_dict.get("from_date") is not None:
config_dict["from_date"] = str(config_dict["from_date"])
return config_dict
|
twitterdev/search-tweets-python | searchtweets/utils.py | merge_dicts | python | def merge_dicts(*dicts):
def _merge_dicts(dict1, dict2):
merged = dict1.copy()
merged.update(dict2)
return merged
return reduce(_merge_dicts, dicts) | Helpful function to merge / combine dictionaries and return a new
dictionary.
Args:
dicts (list or Iterable): iterable set of dictionaries for merging.
Returns:
dict: dict with all keys from the passed list. Later dictionaries in
the sequence will override duplicate keys from previous dictionaries.
Example:
>>> from searchtweets.utils import merge_dicts
>>> d1 = {"rule": "something has:geo"}
>>> d2 = {"maxResults": 1000}
>>> merge_dicts(*[d1, d2])
{"maxResults": 1000, "rule": "something has:geo"} | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/utils.py#L60-L84 | null | """
Utility functions that are used in various parts of the program.
"""
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
from functools import reduce
import itertools as it
import os
import types
import codecs
import datetime
import logging
import configparser
from configparser import MissingSectionHeaderError
try:
import ujson as json
except ImportError:
import json
import yaml
logger = logging.getLogger(__name__)
__all__ = ["take", "partition", "merge_dicts", "write_result_stream",
"read_config"]
def take(n, iterable):
"""Return first n items of the iterable as a list.
Originally found in the Python itertools documentation.
Args:
n (int): number of items to return
iterable (iterable): the object to select
"""
return it.islice(iterable, n)
def partition(iterable, chunk_size, pad_none=False):
"""adapted from Toolz. Breaks an iterable into n iterables up to the
certain chunk size, padding with Nones if availble.
Example:
>>> from searchtweets.utils import partition
>>> iter_ = range(10)
>>> list(partition(iter_, 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(partition(iter_, 3, pad_none=True))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
"""
args = [iter(iterable)] * chunk_size
if not pad_none:
return zip(*args)
else:
return it.zip_longest(*args)
def write_ndjson(filename, data_iterable, append=False, **kwargs):
"""
Generator that writes newline-delimited json to a file and returns items
from an iterable.
"""
write_mode = "ab" if append else "wb"
logger.info("writing to file {}".format(filename))
with codecs.open(filename, write_mode, "utf-8") as outfile:
for item in data_iterable:
outfile.write(json.dumps(item) + "\n")
yield item
def write_result_stream(result_stream, filename_prefix=None,
results_per_file=None, **kwargs):
"""
Wraps a ``ResultStream`` object to save it to a file. This function will still
return all data from the result stream as a generator that wraps the
``write_ndjson`` method.
Args:
result_stream (ResultStream): the unstarted ResultStream object
filename_prefix (str or None): the base name for file writing
results_per_file (int or None): the maximum number of tweets to write
per file. Defaults to having no max, which means one file. Multiple
files will be named by datetime, according to
``<prefix>_YYY-mm-ddTHH_MM_SS.json``.
"""
if isinstance(result_stream, types.GeneratorType):
stream = result_stream
else:
stream = result_stream.stream()
file_time_formatter = "%Y-%m-%dT%H_%M_%S"
if filename_prefix is None:
filename_prefix = "twitter_search_results"
if results_per_file:
logger.info("chunking result stream to files with {} tweets per file"
.format(results_per_file))
chunked_stream = partition(stream, results_per_file, pad_none=True)
for chunk in chunked_stream:
chunk = filter(lambda x: x is not None, chunk)
curr_datetime = (datetime.datetime.utcnow()
.strftime(file_time_formatter))
_filename = "{}_{}.json".format(filename_prefix, curr_datetime)
yield from write_ndjson(_filename, chunk)
else:
curr_datetime = (datetime.datetime.utcnow()
.strftime(file_time_formatter))
_filename = "{}.json".format(filename_prefix)
yield from write_ndjson(_filename, stream)
def read_config(filename):
"""Reads and flattens a configuration file into a single
dictionary for ease of use. Works with both ``.config`` and
``.yaml`` files. Files should look like this::
search_rules:
from-date: 2017-06-01
to-date: 2017-09-01 01:01
pt-rule: kanye
search_params:
results-per-call: 500
max-results: 500
output_params:
save_file: True
filename_prefix: kanye
results_per_file: 10000000
or::
[search_rules]
from_date = 2017-06-01
to_date = 2017-09-01
pt_rule = beyonce has:geo
[search_params]
results_per_call = 500
max_results = 500
[output_params]
save_file = True
filename_prefix = beyonce
results_per_file = 10000000
Args:
filename (str): location of file with extension ('.config' or '.yaml')
Returns:
dict: parsed configuration dictionary.
"""
file_type = "yaml" if filename.endswith(".yaml") else "config"
config = configparser.ConfigParser()
if file_type == "yaml":
with open(os.path.expanduser(filename)) as f:
config_dict = yaml.load(f)
config_dict = merge_dicts(*[dict(config_dict[s]) for s
in config_dict.keys()])
elif file_type == "config":
with open(filename) as f:
config.read_file(f)
config_dict = merge_dicts(*[dict(config[s]) for s
in config.sections()])
else:
logger.error("Config files must be either in YAML or Config style.")
raise TypeError
# ensure args are renamed correctly:
config_dict = {k.replace('-', '_'): v for k, v in config_dict.items()}
# YAML will parse datestrings as datetimes; we'll convert them here if they
# exist
if config_dict.get("to_date") is not None:
config_dict["to_date"] = str(config_dict["to_date"])
if config_dict.get("from_date") is not None:
config_dict["from_date"] = str(config_dict["from_date"])
return config_dict
|
twitterdev/search-tweets-python | searchtweets/utils.py | write_ndjson | python | def write_ndjson(filename, data_iterable, append=False, **kwargs):
write_mode = "ab" if append else "wb"
logger.info("writing to file {}".format(filename))
with codecs.open(filename, write_mode, "utf-8") as outfile:
for item in data_iterable:
outfile.write(json.dumps(item) + "\n")
yield item | Generator that writes newline-delimited json to a file and returns items
from an iterable. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/utils.py#L87-L97 | null | """
Utility functions that are used in various parts of the program.
"""
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
from functools import reduce
import itertools as it
import os
import types
import codecs
import datetime
import logging
import configparser
from configparser import MissingSectionHeaderError
try:
import ujson as json
except ImportError:
import json
import yaml
logger = logging.getLogger(__name__)
__all__ = ["take", "partition", "merge_dicts", "write_result_stream",
"read_config"]
def take(n, iterable):
"""Return first n items of the iterable as a list.
Originally found in the Python itertools documentation.
Args:
n (int): number of items to return
iterable (iterable): the object to select
"""
return it.islice(iterable, n)
def partition(iterable, chunk_size, pad_none=False):
"""adapted from Toolz. Breaks an iterable into n iterables up to the
certain chunk size, padding with Nones if availble.
Example:
>>> from searchtweets.utils import partition
>>> iter_ = range(10)
>>> list(partition(iter_, 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(partition(iter_, 3, pad_none=True))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
"""
args = [iter(iterable)] * chunk_size
if not pad_none:
return zip(*args)
else:
return it.zip_longest(*args)
def merge_dicts(*dicts):
"""
Helpful function to merge / combine dictionaries and return a new
dictionary.
Args:
dicts (list or Iterable): iterable set of dictionaries for merging.
Returns:
dict: dict with all keys from the passed list. Later dictionaries in
the sequence will override duplicate keys from previous dictionaries.
Example:
>>> from searchtweets.utils import merge_dicts
>>> d1 = {"rule": "something has:geo"}
>>> d2 = {"maxResults": 1000}
>>> merge_dicts(*[d1, d2])
{"maxResults": 1000, "rule": "something has:geo"}
"""
def _merge_dicts(dict1, dict2):
merged = dict1.copy()
merged.update(dict2)
return merged
return reduce(_merge_dicts, dicts)
def write_result_stream(result_stream, filename_prefix=None,
results_per_file=None, **kwargs):
"""
Wraps a ``ResultStream`` object to save it to a file. This function will still
return all data from the result stream as a generator that wraps the
``write_ndjson`` method.
Args:
result_stream (ResultStream): the unstarted ResultStream object
filename_prefix (str or None): the base name for file writing
results_per_file (int or None): the maximum number of tweets to write
per file. Defaults to having no max, which means one file. Multiple
files will be named by datetime, according to
``<prefix>_YYY-mm-ddTHH_MM_SS.json``.
"""
if isinstance(result_stream, types.GeneratorType):
stream = result_stream
else:
stream = result_stream.stream()
file_time_formatter = "%Y-%m-%dT%H_%M_%S"
if filename_prefix is None:
filename_prefix = "twitter_search_results"
if results_per_file:
logger.info("chunking result stream to files with {} tweets per file"
.format(results_per_file))
chunked_stream = partition(stream, results_per_file, pad_none=True)
for chunk in chunked_stream:
chunk = filter(lambda x: x is not None, chunk)
curr_datetime = (datetime.datetime.utcnow()
.strftime(file_time_formatter))
_filename = "{}_{}.json".format(filename_prefix, curr_datetime)
yield from write_ndjson(_filename, chunk)
else:
curr_datetime = (datetime.datetime.utcnow()
.strftime(file_time_formatter))
_filename = "{}.json".format(filename_prefix)
yield from write_ndjson(_filename, stream)
def read_config(filename):
"""Reads and flattens a configuration file into a single
dictionary for ease of use. Works with both ``.config`` and
``.yaml`` files. Files should look like this::
search_rules:
from-date: 2017-06-01
to-date: 2017-09-01 01:01
pt-rule: kanye
search_params:
results-per-call: 500
max-results: 500
output_params:
save_file: True
filename_prefix: kanye
results_per_file: 10000000
or::
[search_rules]
from_date = 2017-06-01
to_date = 2017-09-01
pt_rule = beyonce has:geo
[search_params]
results_per_call = 500
max_results = 500
[output_params]
save_file = True
filename_prefix = beyonce
results_per_file = 10000000
Args:
filename (str): location of file with extension ('.config' or '.yaml')
Returns:
dict: parsed configuration dictionary.
"""
file_type = "yaml" if filename.endswith(".yaml") else "config"
config = configparser.ConfigParser()
if file_type == "yaml":
with open(os.path.expanduser(filename)) as f:
config_dict = yaml.load(f)
config_dict = merge_dicts(*[dict(config_dict[s]) for s
in config_dict.keys()])
elif file_type == "config":
with open(filename) as f:
config.read_file(f)
config_dict = merge_dicts(*[dict(config[s]) for s
in config.sections()])
else:
logger.error("Config files must be either in YAML or Config style.")
raise TypeError
# ensure args are renamed correctly:
config_dict = {k.replace('-', '_'): v for k, v in config_dict.items()}
# YAML will parse datestrings as datetimes; we'll convert them here if they
# exist
if config_dict.get("to_date") is not None:
config_dict["to_date"] = str(config_dict["to_date"])
if config_dict.get("from_date") is not None:
config_dict["from_date"] = str(config_dict["from_date"])
return config_dict
|
twitterdev/search-tweets-python | searchtweets/utils.py | write_result_stream | python | def write_result_stream(result_stream, filename_prefix=None,
results_per_file=None, **kwargs):
if isinstance(result_stream, types.GeneratorType):
stream = result_stream
else:
stream = result_stream.stream()
file_time_formatter = "%Y-%m-%dT%H_%M_%S"
if filename_prefix is None:
filename_prefix = "twitter_search_results"
if results_per_file:
logger.info("chunking result stream to files with {} tweets per file"
.format(results_per_file))
chunked_stream = partition(stream, results_per_file, pad_none=True)
for chunk in chunked_stream:
chunk = filter(lambda x: x is not None, chunk)
curr_datetime = (datetime.datetime.utcnow()
.strftime(file_time_formatter))
_filename = "{}_{}.json".format(filename_prefix, curr_datetime)
yield from write_ndjson(_filename, chunk)
else:
curr_datetime = (datetime.datetime.utcnow()
.strftime(file_time_formatter))
_filename = "{}.json".format(filename_prefix)
yield from write_ndjson(_filename, stream) | Wraps a ``ResultStream`` object to save it to a file. This function will still
return all data from the result stream as a generator that wraps the
``write_ndjson`` method.
Args:
result_stream (ResultStream): the unstarted ResultStream object
filename_prefix (str or None): the base name for file writing
results_per_file (int or None): the maximum number of tweets to write
per file. Defaults to having no max, which means one file. Multiple
files will be named by datetime, according to
``<prefix>_YYY-mm-ddTHH_MM_SS.json``. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/utils.py#L100-L140 | [
"def partition(iterable, chunk_size, pad_none=False):\n \"\"\"adapted from Toolz. Breaks an iterable into n iterables up to the\n certain chunk size, padding with Nones if availble.\n\n Example:\n >>> from searchtweets.utils import partition\n >>> iter_ = range(10)\n >>> list(partition... | """
Utility functions that are used in various parts of the program.
"""
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
from functools import reduce
import itertools as it
import os
import types
import codecs
import datetime
import logging
import configparser
from configparser import MissingSectionHeaderError
try:
import ujson as json
except ImportError:
import json
import yaml
logger = logging.getLogger(__name__)
__all__ = ["take", "partition", "merge_dicts", "write_result_stream",
"read_config"]
def take(n, iterable):
"""Return first n items of the iterable as a list.
Originally found in the Python itertools documentation.
Args:
n (int): number of items to return
iterable (iterable): the object to select
"""
return it.islice(iterable, n)
def partition(iterable, chunk_size, pad_none=False):
"""adapted from Toolz. Breaks an iterable into n iterables up to the
certain chunk size, padding with Nones if availble.
Example:
>>> from searchtweets.utils import partition
>>> iter_ = range(10)
>>> list(partition(iter_, 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(partition(iter_, 3, pad_none=True))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
"""
args = [iter(iterable)] * chunk_size
if not pad_none:
return zip(*args)
else:
return it.zip_longest(*args)
def merge_dicts(*dicts):
"""
Helpful function to merge / combine dictionaries and return a new
dictionary.
Args:
dicts (list or Iterable): iterable set of dictionaries for merging.
Returns:
dict: dict with all keys from the passed list. Later dictionaries in
the sequence will override duplicate keys from previous dictionaries.
Example:
>>> from searchtweets.utils import merge_dicts
>>> d1 = {"rule": "something has:geo"}
>>> d2 = {"maxResults": 1000}
>>> merge_dicts(*[d1, d2])
{"maxResults": 1000, "rule": "something has:geo"}
"""
def _merge_dicts(dict1, dict2):
merged = dict1.copy()
merged.update(dict2)
return merged
return reduce(_merge_dicts, dicts)
def write_ndjson(filename, data_iterable, append=False, **kwargs):
"""
Generator that writes newline-delimited json to a file and returns items
from an iterable.
"""
write_mode = "ab" if append else "wb"
logger.info("writing to file {}".format(filename))
with codecs.open(filename, write_mode, "utf-8") as outfile:
for item in data_iterable:
outfile.write(json.dumps(item) + "\n")
yield item
def read_config(filename):
"""Reads and flattens a configuration file into a single
dictionary for ease of use. Works with both ``.config`` and
``.yaml`` files. Files should look like this::
search_rules:
from-date: 2017-06-01
to-date: 2017-09-01 01:01
pt-rule: kanye
search_params:
results-per-call: 500
max-results: 500
output_params:
save_file: True
filename_prefix: kanye
results_per_file: 10000000
or::
[search_rules]
from_date = 2017-06-01
to_date = 2017-09-01
pt_rule = beyonce has:geo
[search_params]
results_per_call = 500
max_results = 500
[output_params]
save_file = True
filename_prefix = beyonce
results_per_file = 10000000
Args:
filename (str): location of file with extension ('.config' or '.yaml')
Returns:
dict: parsed configuration dictionary.
"""
file_type = "yaml" if filename.endswith(".yaml") else "config"
config = configparser.ConfigParser()
if file_type == "yaml":
with open(os.path.expanduser(filename)) as f:
config_dict = yaml.load(f)
config_dict = merge_dicts(*[dict(config_dict[s]) for s
in config_dict.keys()])
elif file_type == "config":
with open(filename) as f:
config.read_file(f)
config_dict = merge_dicts(*[dict(config[s]) for s
in config.sections()])
else:
logger.error("Config files must be either in YAML or Config style.")
raise TypeError
# ensure args are renamed correctly:
config_dict = {k.replace('-', '_'): v for k, v in config_dict.items()}
# YAML will parse datestrings as datetimes; we'll convert them here if they
# exist
if config_dict.get("to_date") is not None:
config_dict["to_date"] = str(config_dict["to_date"])
if config_dict.get("from_date") is not None:
config_dict["from_date"] = str(config_dict["from_date"])
return config_dict
|
twitterdev/search-tweets-python | searchtweets/utils.py | read_config | python | def read_config(filename):
file_type = "yaml" if filename.endswith(".yaml") else "config"
config = configparser.ConfigParser()
if file_type == "yaml":
with open(os.path.expanduser(filename)) as f:
config_dict = yaml.load(f)
config_dict = merge_dicts(*[dict(config_dict[s]) for s
in config_dict.keys()])
elif file_type == "config":
with open(filename) as f:
config.read_file(f)
config_dict = merge_dicts(*[dict(config[s]) for s
in config.sections()])
else:
logger.error("Config files must be either in YAML or Config style.")
raise TypeError
# ensure args are renamed correctly:
config_dict = {k.replace('-', '_'): v for k, v in config_dict.items()}
# YAML will parse datestrings as datetimes; we'll convert them here if they
# exist
if config_dict.get("to_date") is not None:
config_dict["to_date"] = str(config_dict["to_date"])
if config_dict.get("from_date") is not None:
config_dict["from_date"] = str(config_dict["from_date"])
return config_dict | Reads and flattens a configuration file into a single
dictionary for ease of use. Works with both ``.config`` and
``.yaml`` files. Files should look like this::
search_rules:
from-date: 2017-06-01
to-date: 2017-09-01 01:01
pt-rule: kanye
search_params:
results-per-call: 500
max-results: 500
output_params:
save_file: True
filename_prefix: kanye
results_per_file: 10000000
or::
[search_rules]
from_date = 2017-06-01
to_date = 2017-09-01
pt_rule = beyonce has:geo
[search_params]
results_per_call = 500
max_results = 500
[output_params]
save_file = True
filename_prefix = beyonce
results_per_file = 10000000
Args:
filename (str): location of file with extension ('.config' or '.yaml')
Returns:
dict: parsed configuration dictionary. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/utils.py#L143-L212 | [
"def merge_dicts(*dicts):\n \"\"\"\n Helpful function to merge / combine dictionaries and return a new\n dictionary.\n\n Args:\n dicts (list or Iterable): iterable set of dictionaries for merging.\n\n Returns:\n dict: dict with all keys from the passed list. Later dictionaries in\n ... | """
Utility functions that are used in various parts of the program.
"""
# Copyright 2018 Twitter, Inc.
# Licensed under the MIT License
# https://opensource.org/licenses/MIT
from functools import reduce
import itertools as it
import os
import types
import codecs
import datetime
import logging
import configparser
from configparser import MissingSectionHeaderError
try:
import ujson as json
except ImportError:
import json
import yaml
logger = logging.getLogger(__name__)
__all__ = ["take", "partition", "merge_dicts", "write_result_stream",
"read_config"]
def take(n, iterable):
"""Return first n items of the iterable as a list.
Originally found in the Python itertools documentation.
Args:
n (int): number of items to return
iterable (iterable): the object to select
"""
return it.islice(iterable, n)
def partition(iterable, chunk_size, pad_none=False):
"""adapted from Toolz. Breaks an iterable into n iterables up to the
certain chunk size, padding with Nones if availble.
Example:
>>> from searchtweets.utils import partition
>>> iter_ = range(10)
>>> list(partition(iter_, 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(partition(iter_, 3, pad_none=True))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
"""
args = [iter(iterable)] * chunk_size
if not pad_none:
return zip(*args)
else:
return it.zip_longest(*args)
def merge_dicts(*dicts):
"""
Helpful function to merge / combine dictionaries and return a new
dictionary.
Args:
dicts (list or Iterable): iterable set of dictionaries for merging.
Returns:
dict: dict with all keys from the passed list. Later dictionaries in
the sequence will override duplicate keys from previous dictionaries.
Example:
>>> from searchtweets.utils import merge_dicts
>>> d1 = {"rule": "something has:geo"}
>>> d2 = {"maxResults": 1000}
>>> merge_dicts(*[d1, d2])
{"maxResults": 1000, "rule": "something has:geo"}
"""
def _merge_dicts(dict1, dict2):
merged = dict1.copy()
merged.update(dict2)
return merged
return reduce(_merge_dicts, dicts)
def write_ndjson(filename, data_iterable, append=False, **kwargs):
"""
Generator that writes newline-delimited json to a file and returns items
from an iterable.
"""
write_mode = "ab" if append else "wb"
logger.info("writing to file {}".format(filename))
with codecs.open(filename, write_mode, "utf-8") as outfile:
for item in data_iterable:
outfile.write(json.dumps(item) + "\n")
yield item
def write_result_stream(result_stream, filename_prefix=None,
results_per_file=None, **kwargs):
"""
Wraps a ``ResultStream`` object to save it to a file. This function will still
return all data from the result stream as a generator that wraps the
``write_ndjson`` method.
Args:
result_stream (ResultStream): the unstarted ResultStream object
filename_prefix (str or None): the base name for file writing
results_per_file (int or None): the maximum number of tweets to write
per file. Defaults to having no max, which means one file. Multiple
files will be named by datetime, according to
``<prefix>_YYY-mm-ddTHH_MM_SS.json``.
"""
if isinstance(result_stream, types.GeneratorType):
stream = result_stream
else:
stream = result_stream.stream()
file_time_formatter = "%Y-%m-%dT%H_%M_%S"
if filename_prefix is None:
filename_prefix = "twitter_search_results"
if results_per_file:
logger.info("chunking result stream to files with {} tweets per file"
.format(results_per_file))
chunked_stream = partition(stream, results_per_file, pad_none=True)
for chunk in chunked_stream:
chunk = filter(lambda x: x is not None, chunk)
curr_datetime = (datetime.datetime.utcnow()
.strftime(file_time_formatter))
_filename = "{}_{}.json".format(filename_prefix, curr_datetime)
yield from write_ndjson(_filename, chunk)
else:
curr_datetime = (datetime.datetime.utcnow()
.strftime(file_time_formatter))
_filename = "{}.json".format(filename_prefix)
yield from write_ndjson(_filename, stream)
|
twitterdev/search-tweets-python | searchtweets/credentials.py | _load_yaml_credentials | python | def _load_yaml_credentials(filename=None, yaml_key=None):
try:
with open(os.path.expanduser(filename)) as f:
search_creds = yaml.safe_load(f)[yaml_key]
except FileNotFoundError:
logger.error("cannot read file {}".format(filename))
search_creds = {}
except KeyError:
logger.error("{} is missing the provided key: {}"
.format(filename, yaml_key))
search_creds = {}
return search_creds | Loads and parses credentials in a YAML file. Catches common exceptions
and returns an empty dict on error, which will be handled downstream.
Returns:
dict: parsed credentials or {} | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/credentials.py#L25-L43 | null | # -*- coding: utf-8 -*-
# Copyright 2017 Twitter, Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
"""This module handles credential management and parsing for the API. As we
have multiple Search products with different authentication schemes, we try to
provide some flexibility to make this process easier. We suggest putting your
credentials in a YAML file, but the main function in this module,
``load_credentials``, will parse environment variables as well.
"""
import os
import logging
import yaml
import requests
import base64
from .utils import merge_dicts
OAUTH_ENDPOINT = 'https://api.twitter.com/oauth2/token'
__all__ = ["load_credentials"]
logger = logging.getLogger(__name__)
def _load_env_credentials():
vars_ = ["SEARCHTWEETS_ENDPOINT",
"SEARCHTWEETS_ACCOUNT",
"SEARCHTWEETS_USERNAME",
"SEARCHTWEETS_PASSWORD",
"SEARCHTWEETS_BEARER_TOKEN",
"SEARCHTWEETS_ACCOUNT_TYPE",
"SEARCHTWEETS_CONSUMER_KEY",
"SEARCHTWEETS_CONSUMER_SECRET"
]
renamed = [var.replace("SEARCHTWEETS_", '').lower() for var in vars_]
parsed = {r: os.environ.get(var) for (var, r) in zip(vars_, renamed)}
parsed = {k: v for k, v in parsed.items() if v is not None}
return parsed
def _parse_credentials(search_creds, account_type):
if account_type is None:
account_type = search_creds.get("account_type", None)
# attempt to infer account type
if account_type is None:
if search_creds.get("bearer_token") is not None:
account_type = "premium"
elif search_creds.get("password") is not None:
account_type = "enterprise"
else:
pass
if account_type not in {"premium", "enterprise"}:
msg = """Account type is not specified and cannot be inferred.
Please check your credential file, arguments, or environment variables
for issues. The account type must be 'premium' or 'enterprise'.
"""
logger.error(msg)
raise KeyError
try:
if account_type == "premium":
if "bearer_token" not in search_creds:
if "consumer_key" in search_creds \
and "consumer_secret" in search_creds:
search_creds["bearer_token"] = _generate_bearer_token(
search_creds["consumer_key"],
search_creds["consumer_secret"])
search_args = {
"bearer_token": search_creds["bearer_token"],
"endpoint": search_creds["endpoint"],
"extra_headers_dict": search_creds.get("extra_headers",None)}
if account_type == "enterprise":
search_args = {"username": search_creds["username"],
"password": search_creds["password"],
"endpoint": search_creds["endpoint"]}
except KeyError:
logger.error("Your credentials are not configured correctly and "
" you are missing a required field. Please see the "
" readme for proper configuration")
raise KeyError
return search_args
def load_credentials(filename=None, account_type=None,
yaml_key=None, env_overwrite=True):
"""
Handles credential management. Supports both YAML files and environment
variables. A YAML file is preferred for simplicity and configureability.
A YAML credential file should look something like this:
.. code:: yaml
<KEY>:
endpoint: <FULL_URL_OF_ENDPOINT>
username: <USERNAME>
password: <PW>
consumer_key: <KEY>
consumer_secret: <SECRET>
bearer_token: <TOKEN>
account_type: <enterprise OR premium>
extra_headers:
<MY_HEADER_KEY>: <MY_HEADER_VALUE>
with the appropriate fields filled out for your account. The top-level key
defaults to ``search_tweets_api`` but can be flexible.
If a YAML file is not found or is missing keys, this function will check
for this information in the environment variables that correspond to
.. code: yaml
SEARCHTWEETS_ENDPOINT
SEARCHTWEETS_USERNAME
SEARCHTWEETS_PASSWORD
SEARCHTWEETS_BEARER_TOKEN
SEARCHTWEETS_ACCOUNT_TYPE
...
Again, set the variables that correspond to your account information and
type. See the main documentation for details and more examples.
Args:
filename (str): pass a filename here if you do not want to use the
default ``~/.twitter_keys.yaml``
account_type (str): your account type, "premium" or "enterprise". We
will attempt to infer the account info if left empty.
yaml_key (str): the top-level key in the YAML file that has your
information. Defaults to ``search_tweets_api``.
env_overwrite: any found environment variables will overwrite values
found in a YAML file. Defaults to ``True``.
Returns:
dict: your access credentials.
Example:
>>> from searchtweets.api_utils import load_credentials
>>> search_args = load_credentials(account_type="premium",
env_overwrite=False)
>>> search_args.keys()
dict_keys(['bearer_token', 'endpoint'])
>>> import os
>>> os.environ["SEARCHTWEETS_ENDPOINT"] = "https://endpoint"
>>> os.environ["SEARCHTWEETS_USERNAME"] = "areallybadpassword"
>>> os.environ["SEARCHTWEETS_PASSWORD"] = "<PW>"
>>> load_credentials()
{'endpoint': 'https://endpoint',
'password': '<PW>',
'username': 'areallybadpassword'}
"""
yaml_key = yaml_key if yaml_key is not None else "search_tweets_api"
filename = "~/.twitter_keys.yaml" if filename is None else filename
yaml_vars = _load_yaml_credentials(filename=filename, yaml_key=yaml_key)
if not yaml_vars:
logger.warning("Error parsing YAML file; searching for "
"valid environment variables")
env_vars = _load_env_credentials()
merged_vars = (merge_dicts(yaml_vars, env_vars)
if env_overwrite
else merge_dicts(env_vars, yaml_vars))
parsed_vars = _parse_credentials(merged_vars, account_type=account_type)
return parsed_vars
def _generate_bearer_token(consumer_key, consumer_secret):
"""
Return the bearer token for a given pair of consumer key and secret values.
"""
data = [('grant_type', 'client_credentials')]
resp = requests.post(OAUTH_ENDPOINT,
data=data,
auth=(consumer_key, consumer_secret))
logger.warning("Grabbing bearer token from OAUTH")
if resp.status_code >= 400:
logger.error(resp.text)
resp.raise_for_status()
return resp.json()['access_token']
|
twitterdev/search-tweets-python | searchtweets/credentials.py | load_credentials | python | def load_credentials(filename=None, account_type=None,
yaml_key=None, env_overwrite=True):
yaml_key = yaml_key if yaml_key is not None else "search_tweets_api"
filename = "~/.twitter_keys.yaml" if filename is None else filename
yaml_vars = _load_yaml_credentials(filename=filename, yaml_key=yaml_key)
if not yaml_vars:
logger.warning("Error parsing YAML file; searching for "
"valid environment variables")
env_vars = _load_env_credentials()
merged_vars = (merge_dicts(yaml_vars, env_vars)
if env_overwrite
else merge_dicts(env_vars, yaml_vars))
parsed_vars = _parse_credentials(merged_vars, account_type=account_type)
return parsed_vars | Handles credential management. Supports both YAML files and environment
variables. A YAML file is preferred for simplicity and configureability.
A YAML credential file should look something like this:
.. code:: yaml
<KEY>:
endpoint: <FULL_URL_OF_ENDPOINT>
username: <USERNAME>
password: <PW>
consumer_key: <KEY>
consumer_secret: <SECRET>
bearer_token: <TOKEN>
account_type: <enterprise OR premium>
extra_headers:
<MY_HEADER_KEY>: <MY_HEADER_VALUE>
with the appropriate fields filled out for your account. The top-level key
defaults to ``search_tweets_api`` but can be flexible.
If a YAML file is not found or is missing keys, this function will check
for this information in the environment variables that correspond to
.. code: yaml
SEARCHTWEETS_ENDPOINT
SEARCHTWEETS_USERNAME
SEARCHTWEETS_PASSWORD
SEARCHTWEETS_BEARER_TOKEN
SEARCHTWEETS_ACCOUNT_TYPE
...
Again, set the variables that correspond to your account information and
type. See the main documentation for details and more examples.
Args:
filename (str): pass a filename here if you do not want to use the
default ``~/.twitter_keys.yaml``
account_type (str): your account type, "premium" or "enterprise". We
will attempt to infer the account info if left empty.
yaml_key (str): the top-level key in the YAML file that has your
information. Defaults to ``search_tweets_api``.
env_overwrite: any found environment variables will overwrite values
found in a YAML file. Defaults to ``True``.
Returns:
dict: your access credentials.
Example:
>>> from searchtweets.api_utils import load_credentials
>>> search_args = load_credentials(account_type="premium",
env_overwrite=False)
>>> search_args.keys()
dict_keys(['bearer_token', 'endpoint'])
>>> import os
>>> os.environ["SEARCHTWEETS_ENDPOINT"] = "https://endpoint"
>>> os.environ["SEARCHTWEETS_USERNAME"] = "areallybadpassword"
>>> os.environ["SEARCHTWEETS_PASSWORD"] = "<PW>"
>>> load_credentials()
{'endpoint': 'https://endpoint',
'password': '<PW>',
'username': 'areallybadpassword'} | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/credentials.py#L110-L190 | [
"def merge_dicts(*dicts):\n \"\"\"\n Helpful function to merge / combine dictionaries and return a new\n dictionary.\n\n Args:\n dicts (list or Iterable): iterable set of dictionaries for merging.\n\n Returns:\n dict: dict with all keys from the passed list. Later dictionaries in\n ... | # -*- coding: utf-8 -*-
# Copyright 2017 Twitter, Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
"""This module handles credential management and parsing for the API. As we
have multiple Search products with different authentication schemes, we try to
provide some flexibility to make this process easier. We suggest putting your
credentials in a YAML file, but the main function in this module,
``load_credentials``, will parse environment variables as well.
"""
import os
import logging
import yaml
import requests
import base64
from .utils import merge_dicts
OAUTH_ENDPOINT = 'https://api.twitter.com/oauth2/token'
__all__ = ["load_credentials"]
logger = logging.getLogger(__name__)
def _load_yaml_credentials(filename=None, yaml_key=None):
"""Loads and parses credentials in a YAML file. Catches common exceptions
and returns an empty dict on error, which will be handled downstream.
Returns:
dict: parsed credentials or {}
"""
try:
with open(os.path.expanduser(filename)) as f:
search_creds = yaml.safe_load(f)[yaml_key]
except FileNotFoundError:
logger.error("cannot read file {}".format(filename))
search_creds = {}
except KeyError:
logger.error("{} is missing the provided key: {}"
.format(filename, yaml_key))
search_creds = {}
return search_creds
def _load_env_credentials():
vars_ = ["SEARCHTWEETS_ENDPOINT",
"SEARCHTWEETS_ACCOUNT",
"SEARCHTWEETS_USERNAME",
"SEARCHTWEETS_PASSWORD",
"SEARCHTWEETS_BEARER_TOKEN",
"SEARCHTWEETS_ACCOUNT_TYPE",
"SEARCHTWEETS_CONSUMER_KEY",
"SEARCHTWEETS_CONSUMER_SECRET"
]
renamed = [var.replace("SEARCHTWEETS_", '').lower() for var in vars_]
parsed = {r: os.environ.get(var) for (var, r) in zip(vars_, renamed)}
parsed = {k: v for k, v in parsed.items() if v is not None}
return parsed
def _parse_credentials(search_creds, account_type):
if account_type is None:
account_type = search_creds.get("account_type", None)
# attempt to infer account type
if account_type is None:
if search_creds.get("bearer_token") is not None:
account_type = "premium"
elif search_creds.get("password") is not None:
account_type = "enterprise"
else:
pass
if account_type not in {"premium", "enterprise"}:
msg = """Account type is not specified and cannot be inferred.
Please check your credential file, arguments, or environment variables
for issues. The account type must be 'premium' or 'enterprise'.
"""
logger.error(msg)
raise KeyError
try:
if account_type == "premium":
if "bearer_token" not in search_creds:
if "consumer_key" in search_creds \
and "consumer_secret" in search_creds:
search_creds["bearer_token"] = _generate_bearer_token(
search_creds["consumer_key"],
search_creds["consumer_secret"])
search_args = {
"bearer_token": search_creds["bearer_token"],
"endpoint": search_creds["endpoint"],
"extra_headers_dict": search_creds.get("extra_headers",None)}
if account_type == "enterprise":
search_args = {"username": search_creds["username"],
"password": search_creds["password"],
"endpoint": search_creds["endpoint"]}
except KeyError:
logger.error("Your credentials are not configured correctly and "
" you are missing a required field. Please see the "
" readme for proper configuration")
raise KeyError
return search_args
def _generate_bearer_token(consumer_key, consumer_secret):
"""
Return the bearer token for a given pair of consumer key and secret values.
"""
data = [('grant_type', 'client_credentials')]
resp = requests.post(OAUTH_ENDPOINT,
data=data,
auth=(consumer_key, consumer_secret))
logger.warning("Grabbing bearer token from OAUTH")
if resp.status_code >= 400:
logger.error(resp.text)
resp.raise_for_status()
return resp.json()['access_token']
|
twitterdev/search-tweets-python | searchtweets/credentials.py | _generate_bearer_token | python | def _generate_bearer_token(consumer_key, consumer_secret):
data = [('grant_type', 'client_credentials')]
resp = requests.post(OAUTH_ENDPOINT,
data=data,
auth=(consumer_key, consumer_secret))
logger.warning("Grabbing bearer token from OAUTH")
if resp.status_code >= 400:
logger.error(resp.text)
resp.raise_for_status()
return resp.json()['access_token'] | Return the bearer token for a given pair of consumer key and secret values. | train | https://github.com/twitterdev/search-tweets-python/blob/7875afb4f3ee125a9fdcf2e50b5ae761da5f46b5/searchtweets/credentials.py#L193-L206 | null | # -*- coding: utf-8 -*-
# Copyright 2017 Twitter, Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
"""This module handles credential management and parsing for the API. As we
have multiple Search products with different authentication schemes, we try to
provide some flexibility to make this process easier. We suggest putting your
credentials in a YAML file, but the main function in this module,
``load_credentials``, will parse environment variables as well.
"""
import os
import logging
import yaml
import requests
import base64
from .utils import merge_dicts
OAUTH_ENDPOINT = 'https://api.twitter.com/oauth2/token'
__all__ = ["load_credentials"]
logger = logging.getLogger(__name__)
def _load_yaml_credentials(filename=None, yaml_key=None):
"""Loads and parses credentials in a YAML file. Catches common exceptions
and returns an empty dict on error, which will be handled downstream.
Returns:
dict: parsed credentials or {}
"""
try:
with open(os.path.expanduser(filename)) as f:
search_creds = yaml.safe_load(f)[yaml_key]
except FileNotFoundError:
logger.error("cannot read file {}".format(filename))
search_creds = {}
except KeyError:
logger.error("{} is missing the provided key: {}"
.format(filename, yaml_key))
search_creds = {}
return search_creds
def _load_env_credentials():
vars_ = ["SEARCHTWEETS_ENDPOINT",
"SEARCHTWEETS_ACCOUNT",
"SEARCHTWEETS_USERNAME",
"SEARCHTWEETS_PASSWORD",
"SEARCHTWEETS_BEARER_TOKEN",
"SEARCHTWEETS_ACCOUNT_TYPE",
"SEARCHTWEETS_CONSUMER_KEY",
"SEARCHTWEETS_CONSUMER_SECRET"
]
renamed = [var.replace("SEARCHTWEETS_", '').lower() for var in vars_]
parsed = {r: os.environ.get(var) for (var, r) in zip(vars_, renamed)}
parsed = {k: v for k, v in parsed.items() if v is not None}
return parsed
def _parse_credentials(search_creds, account_type):
if account_type is None:
account_type = search_creds.get("account_type", None)
# attempt to infer account type
if account_type is None:
if search_creds.get("bearer_token") is not None:
account_type = "premium"
elif search_creds.get("password") is not None:
account_type = "enterprise"
else:
pass
if account_type not in {"premium", "enterprise"}:
msg = """Account type is not specified and cannot be inferred.
Please check your credential file, arguments, or environment variables
for issues. The account type must be 'premium' or 'enterprise'.
"""
logger.error(msg)
raise KeyError
try:
if account_type == "premium":
if "bearer_token" not in search_creds:
if "consumer_key" in search_creds \
and "consumer_secret" in search_creds:
search_creds["bearer_token"] = _generate_bearer_token(
search_creds["consumer_key"],
search_creds["consumer_secret"])
search_args = {
"bearer_token": search_creds["bearer_token"],
"endpoint": search_creds["endpoint"],
"extra_headers_dict": search_creds.get("extra_headers",None)}
if account_type == "enterprise":
search_args = {"username": search_creds["username"],
"password": search_creds["password"],
"endpoint": search_creds["endpoint"]}
except KeyError:
logger.error("Your credentials are not configured correctly and "
" you are missing a required field. Please see the "
" readme for proper configuration")
raise KeyError
return search_args
def load_credentials(filename=None, account_type=None,
yaml_key=None, env_overwrite=True):
"""
Handles credential management. Supports both YAML files and environment
variables. A YAML file is preferred for simplicity and configureability.
A YAML credential file should look something like this:
.. code:: yaml
<KEY>:
endpoint: <FULL_URL_OF_ENDPOINT>
username: <USERNAME>
password: <PW>
consumer_key: <KEY>
consumer_secret: <SECRET>
bearer_token: <TOKEN>
account_type: <enterprise OR premium>
extra_headers:
<MY_HEADER_KEY>: <MY_HEADER_VALUE>
with the appropriate fields filled out for your account. The top-level key
defaults to ``search_tweets_api`` but can be flexible.
If a YAML file is not found or is missing keys, this function will check
for this information in the environment variables that correspond to
.. code: yaml
SEARCHTWEETS_ENDPOINT
SEARCHTWEETS_USERNAME
SEARCHTWEETS_PASSWORD
SEARCHTWEETS_BEARER_TOKEN
SEARCHTWEETS_ACCOUNT_TYPE
...
Again, set the variables that correspond to your account information and
type. See the main documentation for details and more examples.
Args:
filename (str): pass a filename here if you do not want to use the
default ``~/.twitter_keys.yaml``
account_type (str): your account type, "premium" or "enterprise". We
will attempt to infer the account info if left empty.
yaml_key (str): the top-level key in the YAML file that has your
information. Defaults to ``search_tweets_api``.
env_overwrite: any found environment variables will overwrite values
found in a YAML file. Defaults to ``True``.
Returns:
dict: your access credentials.
Example:
>>> from searchtweets.api_utils import load_credentials
>>> search_args = load_credentials(account_type="premium",
env_overwrite=False)
>>> search_args.keys()
dict_keys(['bearer_token', 'endpoint'])
>>> import os
>>> os.environ["SEARCHTWEETS_ENDPOINT"] = "https://endpoint"
>>> os.environ["SEARCHTWEETS_USERNAME"] = "areallybadpassword"
>>> os.environ["SEARCHTWEETS_PASSWORD"] = "<PW>"
>>> load_credentials()
{'endpoint': 'https://endpoint',
'password': '<PW>',
'username': 'areallybadpassword'}
"""
yaml_key = yaml_key if yaml_key is not None else "search_tweets_api"
filename = "~/.twitter_keys.yaml" if filename is None else filename
yaml_vars = _load_yaml_credentials(filename=filename, yaml_key=yaml_key)
if not yaml_vars:
logger.warning("Error parsing YAML file; searching for "
"valid environment variables")
env_vars = _load_env_credentials()
merged_vars = (merge_dicts(yaml_vars, env_vars)
if env_overwrite
else merge_dicts(env_vars, yaml_vars))
parsed_vars = _parse_credentials(merged_vars, account_type=account_type)
return parsed_vars
|
sdispater/cleo | cleo/parser.py | Parser.parse | python | def parse(cls, expression):
parsed = {"name": None, "arguments": [], "options": []}
if not expression.strip():
raise ValueError("Console command signature is empty.")
expression = expression.replace(os.linesep, "")
matches = re.match(r"[^\s]+", expression)
if not matches:
raise ValueError("Unable to determine command name from signature.")
name = matches.group(0)
parsed["name"] = name
tokens = re.findall(r"\{\s*(.*?)\s*\}", expression)
if tokens:
parsed.update(cls._parameters(tokens))
return parsed | Parse the given console command definition into a dict.
:param expression: The expression to parse
:type expression: str
:rtype: dict | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/parser.py#L16-L45 | [
"def _parameters(cls, tokens):\n \"\"\"\n Extract all of the parameters from the tokens.\n\n :param tokens: The tokens to extract the parameters from\n :type tokens: list\n\n :rtype: dict\n \"\"\"\n arguments = []\n options = []\n\n for token in tokens:\n if not token.startswith(\"... | class Parser(object):
@classmethod
@classmethod
def _parameters(cls, tokens):
"""
Extract all of the parameters from the tokens.
:param tokens: The tokens to extract the parameters from
:type tokens: list
:rtype: dict
"""
arguments = []
options = []
for token in tokens:
if not token.startswith("--"):
arguments.append(cls._parse_argument(token))
else:
options.append(cls._parse_option(token))
return {"arguments": arguments, "options": options}
@classmethod
def _parse_argument(cls, token):
"""
Parse an argument expression.
:param token: The argument expression
:type token: str
:rtype: InputArgument
"""
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split(" : ", 2))
token = token.strip()
description = description.strip()
# Checking validator:
matches = re.match(r"(.*)\((.*?)\)", token)
if matches:
token = matches.group(1).strip()
validator = matches.group(2).strip()
if token.endswith("?*"):
return _argument(
token.rstrip("?*"),
Argument.MULTI_VALUED | Argument.OPTIONAL,
description,
None,
)
elif token.endswith("*"):
return _argument(
token.rstrip("*"),
Argument.MULTI_VALUED | Argument.REQUIRED,
description,
None,
)
elif token.endswith("?"):
return _argument(token.rstrip("?"), Argument.OPTIONAL, description, None)
matches = re.match(r"(.+)=(.+)", token)
if matches:
return _argument(
matches.group(1), Argument.OPTIONAL, description, matches.group(2)
)
return _argument(token, Argument.REQUIRED, description, None)
@classmethod
def _parse_option(cls, token):
"""
Parse an option expression.
:param token: The option expression
:type token: str
:rtype: InputOption
"""
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split(" : ", 2))
token = token.strip()
description = description.strip()
# Checking validator:
matches = re.match(r"(.*)\((.*?)\)", token)
if matches:
token = matches.group(1).strip()
validator = matches.group(2).strip()
shortcut = None
matches = re.split(r"\s*\|\s*", token, 2)
if len(matches) > 1:
shortcut = matches[0].lstrip("-")
token = matches[1]
else:
token = token.lstrip("-")
default = None
mode = Option.NO_VALUE
if token.endswith("=*"):
mode = Option.MULTI_VALUED
token = token.rstrip("=*")
elif token.endswith("=?*"):
mode = Option.MULTI_VALUED
token = token.rstrip("=?*")
elif token.endswith("=?"):
mode = Option.OPTIONAL_VALUE
token = token.rstrip("=?")
elif token.endswith("="):
mode = Option.REQUIRED_VALUE
token = token.rstrip("=")
matches = re.match(r"(.+)(=[?*]*)(.+)", token)
if matches:
token = matches.group(1)
operator = matches.group(2)
default = matches.group(3)
if operator == "=*":
mode = Option.REQUIRED_VALUE | Option.MULTI_VALUED
elif operator == "=?*":
mode = Option.MULTI_VALUED
elif operator == "=?":
mode = Option.OPTIONAL_VALUE
elif operator == "=":
mode = Option.REQUIRED_VALUE
return _option(token, shortcut, mode, description, default)
|
sdispater/cleo | cleo/parser.py | Parser._parameters | python | def _parameters(cls, tokens):
arguments = []
options = []
for token in tokens:
if not token.startswith("--"):
arguments.append(cls._parse_argument(token))
else:
options.append(cls._parse_option(token))
return {"arguments": arguments, "options": options} | Extract all of the parameters from the tokens.
:param tokens: The tokens to extract the parameters from
:type tokens: list
:rtype: dict | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/parser.py#L48-L66 | null | class Parser(object):
@classmethod
def parse(cls, expression):
"""
Parse the given console command definition into a dict.
:param expression: The expression to parse
:type expression: str
:rtype: dict
"""
parsed = {"name": None, "arguments": [], "options": []}
if not expression.strip():
raise ValueError("Console command signature is empty.")
expression = expression.replace(os.linesep, "")
matches = re.match(r"[^\s]+", expression)
if not matches:
raise ValueError("Unable to determine command name from signature.")
name = matches.group(0)
parsed["name"] = name
tokens = re.findall(r"\{\s*(.*?)\s*\}", expression)
if tokens:
parsed.update(cls._parameters(tokens))
return parsed
@classmethod
@classmethod
def _parse_argument(cls, token):
"""
Parse an argument expression.
:param token: The argument expression
:type token: str
:rtype: InputArgument
"""
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split(" : ", 2))
token = token.strip()
description = description.strip()
# Checking validator:
matches = re.match(r"(.*)\((.*?)\)", token)
if matches:
token = matches.group(1).strip()
validator = matches.group(2).strip()
if token.endswith("?*"):
return _argument(
token.rstrip("?*"),
Argument.MULTI_VALUED | Argument.OPTIONAL,
description,
None,
)
elif token.endswith("*"):
return _argument(
token.rstrip("*"),
Argument.MULTI_VALUED | Argument.REQUIRED,
description,
None,
)
elif token.endswith("?"):
return _argument(token.rstrip("?"), Argument.OPTIONAL, description, None)
matches = re.match(r"(.+)=(.+)", token)
if matches:
return _argument(
matches.group(1), Argument.OPTIONAL, description, matches.group(2)
)
return _argument(token, Argument.REQUIRED, description, None)
@classmethod
def _parse_option(cls, token):
"""
Parse an option expression.
:param token: The option expression
:type token: str
:rtype: InputOption
"""
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split(" : ", 2))
token = token.strip()
description = description.strip()
# Checking validator:
matches = re.match(r"(.*)\((.*?)\)", token)
if matches:
token = matches.group(1).strip()
validator = matches.group(2).strip()
shortcut = None
matches = re.split(r"\s*\|\s*", token, 2)
if len(matches) > 1:
shortcut = matches[0].lstrip("-")
token = matches[1]
else:
token = token.lstrip("-")
default = None
mode = Option.NO_VALUE
if token.endswith("=*"):
mode = Option.MULTI_VALUED
token = token.rstrip("=*")
elif token.endswith("=?*"):
mode = Option.MULTI_VALUED
token = token.rstrip("=?*")
elif token.endswith("=?"):
mode = Option.OPTIONAL_VALUE
token = token.rstrip("=?")
elif token.endswith("="):
mode = Option.REQUIRED_VALUE
token = token.rstrip("=")
matches = re.match(r"(.+)(=[?*]*)(.+)", token)
if matches:
token = matches.group(1)
operator = matches.group(2)
default = matches.group(3)
if operator == "=*":
mode = Option.REQUIRED_VALUE | Option.MULTI_VALUED
elif operator == "=?*":
mode = Option.MULTI_VALUED
elif operator == "=?":
mode = Option.OPTIONAL_VALUE
elif operator == "=":
mode = Option.REQUIRED_VALUE
return _option(token, shortcut, mode, description, default)
|
sdispater/cleo | cleo/parser.py | Parser._parse_argument | python | def _parse_argument(cls, token):
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split(" : ", 2))
token = token.strip()
description = description.strip()
# Checking validator:
matches = re.match(r"(.*)\((.*?)\)", token)
if matches:
token = matches.group(1).strip()
validator = matches.group(2).strip()
if token.endswith("?*"):
return _argument(
token.rstrip("?*"),
Argument.MULTI_VALUED | Argument.OPTIONAL,
description,
None,
)
elif token.endswith("*"):
return _argument(
token.rstrip("*"),
Argument.MULTI_VALUED | Argument.REQUIRED,
description,
None,
)
elif token.endswith("?"):
return _argument(token.rstrip("?"), Argument.OPTIONAL, description, None)
matches = re.match(r"(.+)=(.+)", token)
if matches:
return _argument(
matches.group(1), Argument.OPTIONAL, description, matches.group(2)
)
return _argument(token, Argument.REQUIRED, description, None) | Parse an argument expression.
:param token: The argument expression
:type token: str
:rtype: InputArgument | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/parser.py#L69-L117 | null | class Parser(object):
@classmethod
def parse(cls, expression):
"""
Parse the given console command definition into a dict.
:param expression: The expression to parse
:type expression: str
:rtype: dict
"""
parsed = {"name": None, "arguments": [], "options": []}
if not expression.strip():
raise ValueError("Console command signature is empty.")
expression = expression.replace(os.linesep, "")
matches = re.match(r"[^\s]+", expression)
if not matches:
raise ValueError("Unable to determine command name from signature.")
name = matches.group(0)
parsed["name"] = name
tokens = re.findall(r"\{\s*(.*?)\s*\}", expression)
if tokens:
parsed.update(cls._parameters(tokens))
return parsed
@classmethod
def _parameters(cls, tokens):
"""
Extract all of the parameters from the tokens.
:param tokens: The tokens to extract the parameters from
:type tokens: list
:rtype: dict
"""
arguments = []
options = []
for token in tokens:
if not token.startswith("--"):
arguments.append(cls._parse_argument(token))
else:
options.append(cls._parse_option(token))
return {"arguments": arguments, "options": options}
@classmethod
@classmethod
def _parse_option(cls, token):
"""
Parse an option expression.
:param token: The option expression
:type token: str
:rtype: InputOption
"""
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split(" : ", 2))
token = token.strip()
description = description.strip()
# Checking validator:
matches = re.match(r"(.*)\((.*?)\)", token)
if matches:
token = matches.group(1).strip()
validator = matches.group(2).strip()
shortcut = None
matches = re.split(r"\s*\|\s*", token, 2)
if len(matches) > 1:
shortcut = matches[0].lstrip("-")
token = matches[1]
else:
token = token.lstrip("-")
default = None
mode = Option.NO_VALUE
if token.endswith("=*"):
mode = Option.MULTI_VALUED
token = token.rstrip("=*")
elif token.endswith("=?*"):
mode = Option.MULTI_VALUED
token = token.rstrip("=?*")
elif token.endswith("=?"):
mode = Option.OPTIONAL_VALUE
token = token.rstrip("=?")
elif token.endswith("="):
mode = Option.REQUIRED_VALUE
token = token.rstrip("=")
matches = re.match(r"(.+)(=[?*]*)(.+)", token)
if matches:
token = matches.group(1)
operator = matches.group(2)
default = matches.group(3)
if operator == "=*":
mode = Option.REQUIRED_VALUE | Option.MULTI_VALUED
elif operator == "=?*":
mode = Option.MULTI_VALUED
elif operator == "=?":
mode = Option.OPTIONAL_VALUE
elif operator == "=":
mode = Option.REQUIRED_VALUE
return _option(token, shortcut, mode, description, default)
|
sdispater/cleo | cleo/parser.py | Parser._parse_option | python | def _parse_option(cls, token):
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split(" : ", 2))
token = token.strip()
description = description.strip()
# Checking validator:
matches = re.match(r"(.*)\((.*?)\)", token)
if matches:
token = matches.group(1).strip()
validator = matches.group(2).strip()
shortcut = None
matches = re.split(r"\s*\|\s*", token, 2)
if len(matches) > 1:
shortcut = matches[0].lstrip("-")
token = matches[1]
else:
token = token.lstrip("-")
default = None
mode = Option.NO_VALUE
if token.endswith("=*"):
mode = Option.MULTI_VALUED
token = token.rstrip("=*")
elif token.endswith("=?*"):
mode = Option.MULTI_VALUED
token = token.rstrip("=?*")
elif token.endswith("=?"):
mode = Option.OPTIONAL_VALUE
token = token.rstrip("=?")
elif token.endswith("="):
mode = Option.REQUIRED_VALUE
token = token.rstrip("=")
matches = re.match(r"(.+)(=[?*]*)(.+)", token)
if matches:
token = matches.group(1)
operator = matches.group(2)
default = matches.group(3)
if operator == "=*":
mode = Option.REQUIRED_VALUE | Option.MULTI_VALUED
elif operator == "=?*":
mode = Option.MULTI_VALUED
elif operator == "=?":
mode = Option.OPTIONAL_VALUE
elif operator == "=":
mode = Option.REQUIRED_VALUE
return _option(token, shortcut, mode, description, default) | Parse an option expression.
:param token: The option expression
:type token: str
:rtype: InputOption | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/parser.py#L120-L186 | null | class Parser(object):
@classmethod
def parse(cls, expression):
"""
Parse the given console command definition into a dict.
:param expression: The expression to parse
:type expression: str
:rtype: dict
"""
parsed = {"name": None, "arguments": [], "options": []}
if not expression.strip():
raise ValueError("Console command signature is empty.")
expression = expression.replace(os.linesep, "")
matches = re.match(r"[^\s]+", expression)
if not matches:
raise ValueError("Unable to determine command name from signature.")
name = matches.group(0)
parsed["name"] = name
tokens = re.findall(r"\{\s*(.*?)\s*\}", expression)
if tokens:
parsed.update(cls._parameters(tokens))
return parsed
@classmethod
def _parameters(cls, tokens):
"""
Extract all of the parameters from the tokens.
:param tokens: The tokens to extract the parameters from
:type tokens: list
:rtype: dict
"""
arguments = []
options = []
for token in tokens:
if not token.startswith("--"):
arguments.append(cls._parse_argument(token))
else:
options.append(cls._parse_option(token))
return {"arguments": arguments, "options": options}
@classmethod
def _parse_argument(cls, token):
"""
Parse an argument expression.
:param token: The argument expression
:type token: str
:rtype: InputArgument
"""
description = ""
validator = None
if " : " in token:
token, description = tuple(token.split(" : ", 2))
token = token.strip()
description = description.strip()
# Checking validator:
matches = re.match(r"(.*)\((.*?)\)", token)
if matches:
token = matches.group(1).strip()
validator = matches.group(2).strip()
if token.endswith("?*"):
return _argument(
token.rstrip("?*"),
Argument.MULTI_VALUED | Argument.OPTIONAL,
description,
None,
)
elif token.endswith("*"):
return _argument(
token.rstrip("*"),
Argument.MULTI_VALUED | Argument.REQUIRED,
description,
None,
)
elif token.endswith("?"):
return _argument(token.rstrip("?"), Argument.OPTIONAL, description, None)
matches = re.match(r"(.+)=(.+)", token)
if matches:
return _argument(
matches.group(1), Argument.OPTIONAL, description, matches.group(2)
)
return _argument(token, Argument.REQUIRED, description, None)
@classmethod
|
sdispater/cleo | cleo/application.py | Application.add | python | def add(self, command): # type: (BaseCommand) -> Application
self.add_command(command.config)
command.set_application(self)
return self | Adds a command object. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/application.py#L38-L45 | null | class Application(ConsoleApplication, object):
"""
An Application is the container for a collection of commands.
This class is optimized for a standard CLI environment.
Usage:
>>> app = Application('myapp', '1.0 (stable)')
>>> app.add(HelpCommand())
>>> app.run()
"""
def __init__(
self, name=None, version=None, complete=True, config=None
): # type: (str, str, bool, Optional[ApplicationConfig]) -> None
if config is None:
config = ApplicationConfig(name, version)
super(Application, self).__init__(config)
if complete:
self.add(CompletionsCommand())
def add_commands(self, *commands): # type: (Tuple[BaseCommand]) -> None
for command in commands:
self.add(command)
def find(self, name): # type: (str) -> BaseCommand
names = name.split(" ")
command = self.get_command(names[0])
for name in names[1:]:
command = command.get_sub_command(name)
return command.config.handler
|
sdispater/cleo | cleo/commands/command.py | Command._configure_using_fluent_definition | python | def _configure_using_fluent_definition(self):
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default) | Configure the console command using a fluent definition. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L71-L83 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.call | python | def call(self, name, args=None): # type: (str, Optional[str]) -> int
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io) | Call another command. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L100-L110 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.call_silent | python | def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO()) | Call another command. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L112-L122 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.argument | python | def argument(self, key=None):
if key is None:
return self._args.arguments()
return self._args.argument(key) | Get the value of a command argument. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L124-L131 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.option | python | def option(self, key=None):
if key is None:
return self._args.options()
return self._args.option(key) | Get the value of a command option. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L133-L140 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.confirm | python | def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
return self._io.confirm(question, default, true_answer_regex) | Confirm a question with the user. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L142-L146 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.ask | python | def ask(self, question, default=None):
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default) | Prompt the user for input. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L148-L155 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.choice | python | def choice(self, question, choices, default=None, attempts=None, multiple=False):
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question) | Give the user a single choice from an list of answers. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L163-L172 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.create_question | python | def create_question(self, question, type=None, **kwargs):
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs) | Returns a Question of specified type. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L174-L185 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.table | python | def table(self, header=None, rows=None, style=None):
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table | Return a Table instance. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L187-L202 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.render_table | python | def render_table(self, headers, rows, style=None):
table = self.table(headers, rows, style)
table.render(self._io) | Format input to textual table. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L204-L210 | [
"def table(self, header=None, rows=None, style=None):\n \"\"\"\n Return a Table instance.\n \"\"\"\n if style is not None:\n style = self.TABLE_STYLES[style]\n\n table = Table(style)\n\n if header:\n table.set_header_row(header)\n\n if rows:\n table.set_rows(rows)\n\n re... | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.write | python | def write(self, text, style=None):
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled) | Writes a string without a new line.
Useful if you want to use overwrite(). | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L212-L222 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.line | python | def line(self, text, style=None, verbosity=None):
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity) | Write a string as information output. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L224-L233 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.line_error | python | def line_error(self, text, style=None, verbosity=None):
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity) | Write a string as information output to stderr. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L235-L244 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def progress_indicator(self, fmt=None, interval=100, values=None):
"""
Creates a new progress indicator.
"""
return ProgressIndicator(self.io, fmt, interval, values)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
sdispater/cleo | cleo/commands/command.py | Command.progress_indicator | python | def progress_indicator(self, fmt=None, interval=100, values=None):
return ProgressIndicator(self.io, fmt, interval, values) | Creates a new progress indicator. | train | https://github.com/sdispater/cleo/blob/cf44ac2eba2d6435516501e47e5521ee2da9115a/cleo/commands/command.py#L284-L288 | null | class Command(BaseCommand):
signature = None
validation = None
TABLE_STYLES = {
"ascii": TableStyle.ascii(),
"borderless": TableStyle.borderless(),
"solid": TableStyle.solid(),
"compact": TableStyle.compact(),
}
def __init__(self):
self._args = Args(ArgsFormat())
self._io = None
self._command = None
super(Command, self).__init__()
doc = self.__doc__ or super(self.__class__, self).__doc__
if doc:
self._parse_doc(doc)
if not self.signature:
parent = super(self.__class__, self)
if hasattr(parent, "signature"):
self.signature = parent.signature
if self.signature:
self._configure_using_fluent_definition()
self._config.set_handler_method("wrap_handle")
@property
def io(self): # type: () -> ConsoleIO
return self._io
def _parse_doc(self, doc):
doc = doc.strip().split("\n", 1)
if len(doc) > 1:
self._config.set_description(doc[0].strip())
self.signature = re.sub(r"\s{2,}", " ", doc[1].strip())
else:
self._config.set_description(doc[0].strip())
def _configure_using_fluent_definition(self):
"""
Configure the console command using a fluent definition.
"""
definition = Parser.parse(self.signature)
self._config.set_name(definition["name"])
for name, flags, description, default in definition["arguments"]:
self._config.add_argument(name, flags, description, default)
for long_name, short_name, flags, description, default in definition["options"]:
self._config.add_option(long_name, short_name, flags, description, default)
def wrap_handle(
self, args, io, command
): # type: (Args, IO, CliKitCommand) -> Optional[int]
self._args = args
self._io = io
self._command = command
return self.handle()
def handle(self): # type: () -> Optional[int]
"""
Executes the command.
"""
raise NotImplementedError()
def call(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, self.io)
def call_silent(self, name, args=None): # type: (str, Optional[str]) -> int
"""
Call another command.
"""
if args is None:
args = ""
args = StringArgs(args)
command = self.application.get_command(name)
return command.run(args, NullIO())
def argument(self, key=None):
"""
Get the value of a command argument.
"""
if key is None:
return self._args.arguments()
return self._args.argument(key)
def option(self, key=None):
"""
Get the value of a command option.
"""
if key is None:
return self._args.options()
return self._args.option(key)
def confirm(self, question, default=False, true_answer_regex="(?i)^y"):
"""
Confirm a question with the user.
"""
return self._io.confirm(question, default, true_answer_regex)
def ask(self, question, default=None):
"""
Prompt the user for input.
"""
if isinstance(question, Question):
return self._io.ask_question(question)
return self._io.ask(question, default)
def secret(self, question):
"""
Prompt the user for input but hide the answer from the console.
"""
return self._io.ask_hidden(question)
def choice(self, question, choices, default=None, attempts=None, multiple=False):
"""
Give the user a single choice from an list of answers.
"""
question = ChoiceQuestion(question, choices, default)
question.set_max_attempts(attempts)
question.set_multi_select(multiple)
return self._io.ask_question(question)
def create_question(self, question, type=None, **kwargs):
"""
Returns a Question of specified type.
"""
if not type:
return Question(question, **kwargs)
if type == "choice":
return ChoiceQuestion(question, **kwargs)
if type == "confirmation":
return ConfirmationQuestion(question, **kwargs)
def table(self, header=None, rows=None, style=None):
"""
Return a Table instance.
"""
if style is not None:
style = self.TABLE_STYLES[style]
table = Table(style)
if header:
table.set_header_row(header)
if rows:
table.set_rows(rows)
return table
def render_table(self, headers, rows, style=None):
"""
Format input to textual table.
"""
table = self.table(headers, rows, style)
table.render(self._io)
def write(self, text, style=None):
"""
Writes a string without a new line.
Useful if you want to use overwrite().
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write(styled)
def line(self, text, style=None, verbosity=None):
"""
Write a string as information output.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.write_line(styled, verbosity)
def line_error(self, text, style=None, verbosity=None):
"""
Write a string as information output to stderr.
"""
if style:
styled = "<%s>%s</>" % (style, text)
else:
styled = text
self._io.error_line(styled, verbosity)
def info(self, text):
"""
Write a string as information output.
:param text: The line to write
:type text: str
"""
self.line(text, "info")
def comment(self, text):
"""
Write a string as comment output.
:param text: The line to write
:type text: str
"""
self.line(text, "comment")
def question(self, text):
"""
Write a string as question output.
:param text: The line to write
:type text: str
"""
self.line(text, "question")
def progress_bar(self, max=0):
"""
Creates a new progress bar
:param max: The maximum number of steps
:type max: int
:rtype: ProgressBar
"""
return self._io.progress_bar(max)
def spin(self, start_message, end_message, fmt=None, interval=100, values=None):
"""
Automatically spin a progress indicator.
"""
spinner = ProgressIndicator(self.io, fmt, interval, values)
return spinner.auto(start_message, end_message)
def add_style(self, name, fg=None, bg=None, options=None):
"""
Adds a new style
"""
style = Style(name)
if fg is not None:
style.fg(fg)
if bg is not None:
style.bg(bg)
if options is not None:
if "bold" in options:
style.bold()
if "underline" in options:
style.underlined()
self._io.output.formatter.add_style(style)
self._io.error_output.formatter.add_style(style)
def overwrite(self, text, size=None):
"""
Overwrites the current line.
It will not add a new line so use line('')
if necessary.
"""
self._io.overwrite(text, size=size)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.