input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>lookmlint/lookmlint.py
from collections import Counter
import json
import os
import re
import subprocess
import attr
import yaml
@attr.s
class ExploreView(object):
data = attr.ib(repr=False)
explore = attr.ib(init=False, repr=False)
name = attr.ib(init=False, repr=True)
source_view = attr.ib(init=False, repr=False)
def __attrs_post_init__(self):
self.from_view_name = self.data.get('from')
self.view_name = self.data.get('view_name')
self.join_name = self.data.get('_join')
self.explore = self.data['_explore']
self.sql_on = self.data.get('sql_on')
self.view_label = self.data.get('view_label')
self.name = self._first_existing([self.view_name, self.join_name, self.explore])
def _first_existing(self, values):
return next(v for v in values if v is not None)
def source_view_name(self):
priority = [self.from_view_name, self.view_name, self.join_name, self.explore]
return self._first_existing(priority)
def display_label(self):
priority = [
self.view_label,
self.source_view.label,
self.name.replace('_', ' ').title(),
]
return self._first_existing(priority)
def contains_raw_sql_ref(self):
if not self.sql_on:
return False
raw_sql_words = [
w
for line in self.sql_on.split('\n')
for w in line.split()
# not a comment line
if not line.replace(' ', '').startswith('--')
# doesn't contain lookml syntax
and not '${' in w and not '}' in w
# not a custom function with newlined args
and not w.endswith('(')
# contains one period
and w.count('.') == 1
# doesn't contain noqa
and not '#noqa' in line
]
return len(raw_sql_words) > 0
@attr.s
class Explore(object):
data = attr.ib(repr=False)
label = attr.ib(init=False)
model = attr.ib(init=False)
name = attr.ib(init=False)
views = attr.ib(init=False, repr=False)
def __attrs_post_init__(self):
self.name = self.data.get('_explore')
self.label = self.data.get('label')
self.model = self.data.get('_model')
joined_views = [ExploreView(j) for j in self.data.get('joins', [])]
self.views = [ExploreView(self.data)] + joined_views
def display_label(self):
return self.label if self.label else self.name.replace('_', ' ').title()
def view_label_issues(self, acronyms=[], abbreviations=[]):
results = {}
for v in self.views:
issues = label_issues(v.display_label(), acronyms, abbreviations)
if issues == []:
continue
results[v.display_label()] = issues
return results
def duplicated_view_labels(self):
c = Counter(v.display_label() for v in self.views)
return {label: n for label, n in c.items() if n > 1}
@attr.s
class Model(object):
data = attr.ib(repr=False)
explores = attr.ib(init=False, repr=False)
included_views = attr.ib(init=False, repr=False)
name = attr.ib(init=False)
def __attrs_post_init__(self):
includes = self.data.get('include', [])
if isinstance(includes, str):
includes = [includes]
self.included_views = [i[: -len('.view')] for i in includes]
self.explores = [Explore(e) for e in self.data['explore'].values() if isinstance(e, dict)]
self.name = self.data['_model']
def explore_views(self):
return [v for e in self.explores for v in e.views]
def unused_includes(self):
# if all views in a project are imported into a model,
# don't suggest any includes are unused
if self.included_views == ['*']:
return []
explore_view_sources = [v.source_view.name for v in self.explore_views()]
return sorted(list(set(self.included_views) - set(explore_view_sources)))
def explore_label_issues(self, acronyms=[], abbreviations=[]):
results = {}
for e in self.explores:
issues = label_issues(e.display_label(), acronyms, abbreviations)
if issues == []:
continue
results[e.display_label()] = issues
return results
@attr.s
class View(object):
data = attr.ib(repr=False)
name = attr.ib(init=False)
label = attr.ib(init=False)
dimensions = attr.ib(init=False, repr=False)
dimension_groups = attr.ib(init=False, repr=False)
measures = attr.ib(init=False, repr=False)
def __attrs_post_init__(self):
self.name = self.data['_view']
self.label = self.data.get('label')
self.dimensions = [Dimension(d) for d in self.data.get('dimension', {}).values() if isinstance(d, dict)]
self.measures = [Measure(m) for m in self.data.get('measure', {}).values() if isinstance(m, dict)]
self.dimension_groups = [
DimensionGroup(dg) for dg in self.data.get('dimension_group', {}).values() if isinstance(dg, dict)
]
self.fields = self.dimensions + self.dimension_groups + self.measures
self.extends = [v.strip('*') for v in self.data.get('extends', [])]
self.sql_table_name = self.data.get('sql_table_name')
self.derived_table_sql = None
if 'derived_table' in self.data:
self.derived_table_sql = self.data['derived_table']['sql']
def field_label_issues(self, acronyms=[], abbreviations=[]):
results = {}
for f in self.fields:
if f.is_hidden:
continue
issues = label_issues(f.display_label(), acronyms, abbreviations)
if issues == []:
continue
results[f.display_label()] = issues
return results
def has_primary_key(self):
return any(d.is_primary_key for d in self.dimensions)
def has_sql_definition(self):
return self.sql_table_name is not None or self.derived_table_sql is not None
def derived_table_contains_semicolon(self):
return self.derived_table_sql is not None and ';' in self.derived_table_sql
def derived_table_contains_select_star(self):
return self.derived_table_sql is not None and len(re.findall('(?:[^/])(\*)(?:[^/])', self.derived_table_sql)) > 0 and '#noqa:select-star' not in self.derived_table_sql
@attr.s
class Dimension(object):
data = attr.ib(repr=False)
name = attr.ib(init=False, repr=True)
type = attr.ib(init=False)
label = attr.ib(init=False)
description = attr.ib(init=False, repr=False)
def __attrs_post_init__(self):
self.name = self.data['_dimension']
self.type = self.data.get('type', 'string')
self.label = self.data.get('label')
self.description = self.data.get('description')
self.sql = self.data.get('sql')
self.is_primary_key = self.data.get('primary_key') is True
self.is_hidden = self.data.get('hidden') is True
def display_label(self):
return self.label if self.label else self.name.replace('_', ' ').title()
@attr.s
class DimensionGroup(object):
data = attr.ib(repr=False)
name = attr.ib(init=False, repr=True)
type = attr.ib(init=False)
label = attr.ib(init=False)
description = attr.ib(init=False, repr=False)
timeframes = attr.ib(init=False, repr=False)
def __attrs_post_init__(self):
self.name = self.data['_dimension_group']
self.type = self.data.get('type', 'string')
self.label = self.data.get('label')
self.description = self.data.get('description')
self.sql = self.data.get('sql')
self.timeframes = self.data.get('timeframes')
self.is_hidden = self.data.get('hidden') is True
def display_label(self):
return self.label if self.label else self.name.replace('_', ' ').title()
@attr.s
class Measure(object):
data = attr.ib(repr=False)
name = attr.ib(init=False, repr=True)
type = attr.ib(init=False)
label = attr.ib(init=False)
description = attr.ib(init=False, repr=False)
def __attrs_post_init__(self):
self.name = self.data['_measure']
self.type = self.data.get('type')
self.label = self.data.get('label')
self.description = self.data.get('description')
self.sql = self.data.get('sql')
self.is_hidden = self.data.get('hidden') is True
self.drill_fields = self.data.get('drill_fields', [])
self.tags = self.data.get('tags', [])
def display_label(self):
return self.label if self.label else self.name.replace('_', ' ').title()
def has_drill_fields(self):
return len(self.drill_fields) > 0 or self.type in ["number", "percent_of_previous", "percent_of_total"] or self.is_hidden or '#noqa:drill-fields' in self.tags
@attr.s
class LookML(object):
lookml_json_filepath = attr.ib()
data = attr.ib(init=False, repr=False)
models = attr.ib(init=False, repr=False)
views = attr.ib(init=False, repr=False)
def __attrs_post_init__(self):
with open(self.lookml_json_filepath) as f:
self.data = json.load(f)
model_dicts = [self._model(mn) for mn in self._model_file_names()]
self.models = [Model(m) for m in model_dicts]
view_dicts = [self._view(vn) for vn in self._view_file_names()]
self.views = [View(v) for v in view_dicts]
# match explore views with their source views
for m in self.models:
for e in m.explores:
for ev in e.views:
source_view = next(
v for v in self.views if v.name == ev.source_view_name()
)
ev.source_view = source_view
def _view_file_names(self):
return sorted(self.data['file']['view'].keys())
def _view(self, view_file_name):
return list(self.data['file']['view'][view_file_name]['view'].values())[0]
def _model_file_names(self):
return sorted(self.data['file']['model'].keys())
def _model(self, model_file_name):
return self.data['file']['model'][model_file_name]['model'][model_file_name]
def mismatched_view_names(self):
results = {}
for vf in self._view_file_names():
v = View(self._view(vf))
if v.name != vf:
results[vf] = v.name
return results
def all_explore_views(self):
explore_views = []
for m in self.models:
explore_views += m.explore_views()
return explore_views
def unused_view_files(self):
view_names = [v.name for v in self.views]
explore_view_names = [v.source_view.name for v in self.all_explore_views()]
extended_views = [exv for v in self.views for exv in v.extends]
return sorted(
list(set(view_names) - set(explore_view_names) - set(extended_views))
)
def read_lint_config(repo_path):
# read .lintconfig.yml
full_path = os.path.expanduser(repo_path)
config_filepath = os.path.join(full_path, '.lintconfig.yml')
acronyms = []
abbreviations = []
if os.path.isfile(config_filepath):
with open(config_filepath) as f:
config = yaml.load(f)
acronyms = config.get('acronyms', acronyms)
abbreviations = config.get('abbreviations', abbreviations)
lint_config = {'acronyms': acronyms, 'abbreviations': abbreviations}
return lint_config
def parse_repo(full_path):
cmd = (
f'cd {full_path} && '
'lookml-parser --input="*.lkml" --whitespace=2 > /tmp/lookmlint.json'
)
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, error = process.communicate()
def lookml_from_repo_path(repo_path):
full_path = os.path.expanduser(repo_path)
parse_repo(full_path)
lkml = LookML('/tmp/lookmlint.json')
return lkml
def label_issues(label, acronyms=[], abbreviations=[]):
def _contains_bad_acronym_usage(label, acronym):
words = label.split(' ')
# drop plural 's' from words
if not acronym.lower().endswith('s'):
words = [w if not w.endswith('s') else w[:-1] for w in words]
return any(acronym.upper() == w.upper() and w == w.title() for w in words)
def _contains_bad_abbreviation_usage(label, abbreviation):
return any(abbreviation.lower() == k.lower() for k in label.split(' '))
acronyms_used = [
a.upper() for a in acronyms if _contains_bad_acronym_usage(label, a)
]
abbreviations_used = [
a.title() for a in abbreviations if _contains_bad_abbreviation_usage(label, a)
]
return acronyms_used + abbreviations_used
def lint_labels(lkml, acronyms, abbreviations):
# check for acronym and abbreviation issues
explore_label_issues = {}
for m in lkml.models:
issues = m.explore_label_issues(acronyms, abbreviations)
if issues != {}:
explore_label_issues[m.name] = issues
explore_view_label_issues = {}
for m in lkml.models:
for e in m.explores:
issues = e.view_label_issues(acronyms, abbreviations)
if issues != {}:
if m.name not in explore_view_label_issues:
explore_view_label_issues[m.name] = {}
explore_view_label_issues[m.name][e.name] = issues
field_label_issues = {}
for v in lkml.views:
issues = v.field_label_issues(acronyms, abbreviations)
if issues != {}:
field_label_issues[v.name] = issues
# create overall labels issues dict
label_issues = {}
if explore_label_issues != {}:
label_issues['explores'] = explore_label_issues
if explore_view_label_issues != {}:
label_issues['explore_views'] = explore_view_label_issues
if field_label_issues != {}:
label_issues['fields'] = field_label_issues
return label_issues
def lint_duplicate_view_labels(lkml):
issues = {}
for m in lkml.models:
for e in m.explores:
dupes = e.duplicated_view_labels()
if dupes == {}:
continue
if m.name not in issues:
issues[m.name] = {}
if e.name not in issues[m.name]:
issues[m.name][e.name] = dupes
return issues
def lint_sql_references(lkml):
# check for raw SQL field references
raw_sql_refs = {}
for m in lkml.models:
for e in m.explores:
for v in e.views:
if not v.contains_raw_sql_ref():
continue
if m.name not in raw_sql_refs:
raw_sql_refs[m.name] = {}
if e.name not in raw_sql_refs[m.name]:
raw_sql_refs[m.name][e.name] = {}
raw_sql_refs[m.name][e.name][v.name] = v.sql_on
return raw_sql_refs
def lint_view_primary_keys(lkml):
# check for | |
info: str = None,
min_iter: int = 2, err_tol: float = 0.01,
allow_adjust: bool = True,
no_lower=False, no_upper=False, sign_lower=1, sign_upper=1,
equal=True, no_warn=False,
zu=0.0, zl=0.0, zi=1.0):
Discrete.__init__(self, name=name, tex_name=tex_name, info=info,
min_iter=min_iter, err_tol=err_tol)
self.u = u
self.lower = dummify(lower)
self.upper = dummify(upper)
self.enable = enable
self.no_lower = no_lower
self.no_upper = no_upper
self.allow_adjust = allow_adjust
if sign_lower not in (1, -1):
raise ValueError("sign_lower must be 1 or -1, got %s" % sign_lower)
if sign_upper not in (1, -1):
raise ValueError("sign_upper must be 1 or -1, got %s" % sign_upper)
self.sign_lower = dummify(sign_lower)
self.sign_upper = dummify(sign_upper)
self.equal = equal
self.no_warn = no_warn
self.zu = np.array([zu])
self.zl = np.array([zl])
self.zi = np.array([zi])
self.mask_upper = None
self.mask_lower = None
self.has_check_var = True
self.export_flags.append('zi')
self.export_flags_tex.append('z_i')
self.input_list.extend([self.u])
self.param_list.extend([self.lower, self.upper])
if not self.no_lower:
self.export_flags.append('zl')
self.export_flags_tex.append('z_l')
self.warn_flags.append(('zl', 'lower'))
if not self.no_upper:
self.export_flags.append('zu')
self.export_flags_tex.append('z_u')
self.warn_flags.append(('zu', 'upper'))
def check_var(self,
allow_adjust=True, # allow flag from model
adjust_lower=False,
adjust_upper=False,
is_init: bool = False,
*args, **kwargs):
"""
Check the input variable and set flags.
"""
if not self.enable:
return
if not self.no_upper:
upper_v = -self.upper.v if self.sign_upper.v == -1 else self.upper.v
# FIXME: adjust will not be successful when sign is -1
if self.allow_adjust and is_init:
self.do_adjust_upper(self.u.v, upper_v, allow_adjust, adjust_upper)
if self.equal:
self.zu[:] = np.greater_equal(self.u.v, upper_v)
else:
self.zu[:] = np.greater(self.u.v, upper_v)
if not self.no_lower:
lower_v = -self.lower.v if self.sign_lower.v == -1 else self.lower.v
# FIXME: adjust will not be successful when sign is -1
if self.allow_adjust and is_init:
self.do_adjust_lower(self.u.v, lower_v, allow_adjust, adjust_lower)
if self.equal:
self.zl[:] = np.less_equal(self.u.v, lower_v)
else:
self.zl[:] = np.less(self.u.v, lower_v)
self.zi[:] = np.logical_not(np.logical_or(self.zu, self.zl))
def do_adjust_lower(self, val, lower, allow_adjust=True, adjust_lower=False):
"""
Adjust the lower limit.
Notes
-----
This method is only executed if `allow_adjust` is True
and `adjust_lower` is True.
"""
if allow_adjust:
mask = (val < lower)
if sum(mask) == 0:
return
if adjust_lower:
self._show_adjust(val, lower, mask, self.lower.name, adjusted=True)
lower[mask] = val[mask]
self.mask_lower = mask # store after adjusting
else:
self._show_adjust(val, lower, mask, self.lower.name, adjusted=False)
def _show_adjust(self, val, old_limit, mask, limit_name, adjusted=True):
"""
Helper function to show a table of the adjusted limits.
"""
idxes = np.array(self.owner.idx.v)[mask]
if isinstance(val, (int, float)):
val = np.array([val])
if isinstance(old_limit, (int, float)):
old_limit = np.array([old_limit])
adjust_or_not = 'adjusted' if adjusted else '*not adjusted*'
tab = Tab(title=f"{self.owner.class_name}.{self.name}: {adjust_or_not} limit <{limit_name}>",
header=['Idx', 'Input', 'Old Limit'],
data=[*zip(idxes, val[mask], old_limit[mask])],
)
if adjusted:
logger.info(tab.draw())
else:
logger.warning(tab.draw())
def do_adjust_upper(self, val, upper, allow_adjust=True, adjust_upper=False):
"""
Adjust the upper limit.
Notes
-----
This method is only executed if `allow_adjust` is True
and `adjust_upper` is True.
"""
if allow_adjust:
mask = (val > upper)
if sum(mask) == 0:
return
if adjust_upper:
self._show_adjust(val, upper, mask, self.upper.name, adjusted=True)
upper[mask] = val[mask]
self.mask_upper = mask
else:
self._show_adjust(val, upper, mask, self.lower.name, adjusted=False)
class SortedLimiter(Limiter):
"""
A limiter that sorts inputs based on the absolute or
relative amount of limit violations.
Parameters
----------
n_select : int
the number of violations to be flagged,
for each of over-limit and under-limit cases.
If `n_select` == 1, at most one over-limit
and one under-limit inputs will be flagged.
If `n_select` is zero, heuristics will be used.
abs_violation : bool
True to use the absolute violation.
False if the relative violation
abs(violation/limit) is used for sorting.
Since most variables are in per unit,
absolute violation is recommended.
"""
def __init__(self, u, lower, upper, n_select: int = 5,
name=None, tex_name=None, enable=True, abs_violation=True,
min_iter: int = 2, err_tol: float = 0.01,
allow_adjust: bool = True,
zu=0.0, zl=0.0, zi=1.0, ql=0.0, qu=0.0,
):
super().__init__(u, lower, upper,
enable=enable, name=name, tex_name=tex_name,
min_iter=min_iter, err_tol=err_tol,
allow_adjust=allow_adjust,
zu=zu, zl=zl, zi=zi,
)
self.n_select = int(n_select)
self.auto = True if self.n_select == 0 else False
self.abs_violation = abs_violation
self.ql = np.array([ql])
self.qu = np.array([qu])
# count of ones in `ql` and `qu`
self.nql = 0
self.nqu = 0
# smallest and largest `n_select`
self.min_sel = 2
self.max_sel = 50
# store the lower and upper limit values with zeros converted to a small number
self.lower_denom = None
self.upper_denom = None
self.export_flags.extend(['ql', 'qu'])
self.export_flags_tex.extend(['q_l', 'q_u'])
def list2array(self, n):
"""
Initialize maximum and minimum `n_select` based on input size.
"""
super().list2array(n)
if self.auto:
self.min_sel = max(2, int(n / 10))
self.max_sel = max(2, int(n / 2))
def check_var(self, *args, niter=None, err=None, **kwargs):
"""
Check for the largest and smallest `n_select` elements.
"""
if not self.enable:
return
if not self.check_iter_err(niter=niter, err=err):
return
super().check_var()
# first run - calculate the denominators if using relative violation
if not self.abs_violation:
if self.lower_denom is None:
self.lower_denom = np.array(self.lower.v)
self.lower_denom[self.lower_denom == 0] = 1e-6
if self.upper_denom is None:
self.upper_denom = np.array(self.upper.v)
self.upper_denom[self.upper_denom == 0] = 1e-6
# calculate violations - abs or relative
if self.abs_violation:
lower_vio = self.u.v - self.lower.v
upper_vio = self.upper.v - self.u.v
else:
lower_vio = np.abs((self.u.v - self.lower.v) / self.lower_denom)
upper_vio = np.abs((self.upper.v - self.u.v) / self.upper_denom)
# count the number of inputs flagged
if self.auto:
self.calc_select()
# sort in both ascending and descending orders
asc = np.argsort(lower_vio)
desc = np.argsort(upper_vio)
top_n = asc[:self.n_select]
bottom_n = desc[:self.n_select]
# `reset_out` is used to flag the
reset_out = np.zeros_like(self.u.v)
reset_out[top_n] = 1
reset_out[bottom_n] = 1
# set new flags
self.zl[:] = np.logical_or(np.logical_and(reset_out, self.zl),
self.ql)
self.zu[:] = np.logical_or(np.logical_and(reset_out, self.zu),
self.qu)
self.zi[:] = 1 - np.logical_or(self.zl, self.zu)
self.ql[:] = self.zl
self.qu[:] = self.zu
# compute the number of updated flags
ql1 = np.count_nonzero(self.ql)
qu1 = np.count_nonzero(self.qu)
dqu = qu1 - self.nqu
dql = ql1 - self.nql
if dqu > 0 or dql > 0:
logger.debug("SortedLimiter: flagged %s upper and %s lower limit violations",
dqu, dql)
self.nqu = qu1
self.nql = ql1
def calc_select(self):
"""
Set `n_select` automatically.
"""
ret = int((np.count_nonzero(self.zl) + np.count_nonzero(self.zu)) / 2) + 1
if ret > self.max_sel:
ret = self.max_sel
elif ret < self.min_sel:
ret = self.min_sel
self.n_select = ret
class HardLimiter(Limiter):
"""
Hard limiter for algebraic or differential variable. This class is an alias of `Limiter`.
"""
pass
class AntiWindup(Limiter):
"""
Anti-windup limiter.
Anti-windup limiter prevents the wind-up effect of a differential variable.
The derivative of the differential variable is reset if it continues to increase in the same direction
after exceeding the limits.
During the derivative return, the limiter will be inactive ::
if x > xmax and x dot > 0: x = xmax and x dot = 0
if x < xmin and x dot < 0: x = xmin and x dot = 0
This class takes one more optional parameter for specifying the equation.
Parameters
----------
state : State, ExtState
A State (or ExtState) whose equation value will be checked and, when condition satisfies, will be reset
by the anti-windup-limiter.
"""
def __init__(self, u, lower, upper, enable=True, no_warn=False,
no_lower=False, no_upper=False, sign_lower=1, sign_upper=1,
name=None, tex_name=None, info=None, state=None,
allow_adjust: bool = True,):
super().__init__(u, lower, upper, enable=enable, no_warn=no_warn,
no_lower=no_lower, no_upper=no_upper,
sign_lower=sign_lower, sign_upper=sign_upper,
name=name, tex_name=tex_name, info=info,
allow_adjust=allow_adjust,)
self.state = state if state else u
self.has_check_var = False
self.has_check_eq = True
self.no_warn = no_warn
def check_var(self, *args, **kwargs):
"""
This function is empty. Defers `check_var` to `check_eq`.
"""
pass
def check_eq(self,
allow_adjust=True,
adjust_lower=False,
adjust_upper=False,
is_init: bool = False,
**kwargs):
"""
Check the variables and equations and set the limiter flags.
Reset differential equation values based on limiter flags.
Notes
-----
The current implementation reallocates memory for `self.x_set` in each call.
Consider improving for speed. (TODO)
"""
if not self.no_upper:
upper_v = -self.upper.v if self.sign_upper.v == -1 else self.upper.v
if self.allow_adjust and is_init:
self.do_adjust_upper(self.u.v, upper_v,
allow_adjust=allow_adjust,
adjust_upper=adjust_upper)
self.zu[:] = np.logical_and(np.greater_equal(self.u.v, upper_v),
np.greater_equal(self.state.e, 0))
if not self.no_lower:
lower_v = -self.lower.v if self.sign_lower.v == -1 else self.lower.v
if self.allow_adjust and is_init:
self.do_adjust_lower(self.u.v, lower_v,
allow_adjust=allow_adjust,
adjust_lower=adjust_lower)
self.zl[:] = np.logical_and(np.less_equal(self.u.v, lower_v),
np.less_equal(self.state.e, 0))
self.zi[:] = np.logical_not(np.logical_or(self.zu, self.zl))
# must flush the `x_set` list at the beginning
self.x_set = list()
if not np.all(self.zi):
idx = np.where(self.zi == 0)
self.state.e[:] = self.state.e * self.zi
self.state.v[:] = self.state.v * self.zi
if not self.no_upper:
self.state.v[:] += upper_v * self.zu
if not self.no_lower:
self.state.v[:] += lower_v * self.zl
self.x_set.append((self.state.a[idx], self.state.v[idx], 0)) # (address, var. values, eqn. values)
# logger.debug(f'AntiWindup for states | |
<reponame>juliomateoslangerak/ezomero<filename>tests/test_ezomero.py
import pytest
import numpy as np
import ezomero
def test_omero_connection(conn, omero_params):
assert conn.getUser().getName() == omero_params[0]
# Test posts
############
def test_post_dataset(conn, project_structure, users_groups, timestamp):
# Orphaned dataset, with descripion
ds_test_name = 'test_post_dataset_' + timestamp
did = ezomero.post_dataset(conn, ds_test_name, description='New test')
assert conn.getObject("Dataset", did).getName() == ds_test_name
assert conn.getObject("Dataset", did).getDescription() == "New test"
# Dataset in default project, no description
ds_test_name2 = 'test_post_dataset2_' + timestamp
project_info = project_structure[0]
pid = project_info[0][1]
did2 = ezomero.post_dataset(conn, ds_test_name2, project_id=pid)
ds = conn.getObjects("Dataset", opts={'project': pid})
ds_names = [d.getName() for d in ds]
assert ds_test_name2 in ds_names
# Dataset in non-existing project ID
ds_test_name3 = 'test_post_dataset3_' + timestamp
pid = 99999999
did3 = ezomero.post_dataset(conn, ds_test_name3, project_id=pid)
assert did3 == None
# Dataset in cross-group project, valid permissions
username = users_groups[1][0][0] #test_user1
groupname = users_groups[0][0][0] #test_group_1
gid = users_groups[0][0][1]
current_conn = conn.suConn(username, groupname)
ds_test_name4 = 'test_post_dataset4_' + timestamp
project_info = project_structure[0]
pid = project_info[3][1] #proj3 (in test_group_2)
did4 = ezomero.post_dataset(current_conn, ds_test_name4, project_id=pid)
current_conn.SERVICE_OPTS.setOmeroGroup('-1')
ds = current_conn.getObjects("Dataset", opts={'project': pid})
ds_names = [d.getName() for d in ds]
current_conn.close()
assert ds_test_name4 in ds_names
# Dataset in cross-group project, invalid permissions
username = users_groups[1][2][0] #test_user3
groupname = users_groups[0][1][0] #test_group_2
current_conn = conn.suConn(username, groupname)
ds_test_name5 = 'test_post_dataset5_' + timestamp
project_info = project_structure[0]
pid = project_info[1][1] #proj1 (in test_group_1)
did5 = ezomero.post_dataset(current_conn, ds_test_name5, project_id=pid)
current_conn.close()
assert did5 == None
# Dataset in cross-group project, valid permissions, across_groups flag unset
username = users_groups[1][0][0] #test_user1
groupname = users_groups[0][0][0] #test_group_1
gid = users_groups[0][0][1]
current_conn = conn.suConn(username, groupname)
ds_test_name6 = 'test_post_dataset6_' + timestamp
project_info = project_structure[0]
pid = project_info[3][1] #proj3 (in test_group_2)
did6 = ezomero.post_dataset(current_conn, ds_test_name6, project_id=pid, across_groups=False)
current_conn.close()
assert did6 == None
conn.deleteObjects("Dataset", [did, did2, did4], deleteAnns=True,
deleteChildren=True, wait=True)
def test_post_image(conn, project_structure, users_groups, timestamp, image_fixture):
dataset_info = project_structure[1]
did = dataset_info[0][1]
# Post image in dataset
image_name = 'test_post_image_' + timestamp
im_id = ezomero.post_image(conn, image_fixture, image_name,
description='This is an image',
dataset_id=did)
assert conn.getObject("Image", im_id).getName() == image_name
# Post orphaned image
im_id2 = ezomero.post_image(conn, image_fixture, image_name)
assert conn.getObject("Image", im_id2).getName() == image_name
# Post image to non-existent dataset
did3 = 999999999
im_id3 = ezomero.post_image(conn, image_fixture, image_name,
description='This is an image',
dataset_id=did3)
assert im_id3 == None
# Post image cross-group, valid permissions
username = users_groups[1][0][0] #test_user1
groupname = users_groups[0][0][0] #test_group_1
current_conn = conn.suConn(username, groupname)
dataset_info = project_structure[1]
did4 = dataset_info[3][1] #ds2 (in test_group_2)
image_name = 'test_post_image_' + timestamp
im_id4 = ezomero.post_image(current_conn, image_fixture, image_name,
description='This is an image',
dataset_id=did4)
current_conn.SERVICE_OPTS.setOmeroGroup('-1')
assert current_conn.getObject("Image", im_id4).getName() == image_name
current_conn.close()
# Post image cross-group, ivvalid permissions
username = users_groups[1][2][0] #test_user3
groupname = users_groups[0][1][0] #test_group_2
current_conn = conn.suConn(username, groupname)
dataset_info = project_structure[1]
did5 = dataset_info[1][1] #ds1 (in test_group_1)
image_name = 'test_post_image_' + timestamp
im_id5 = ezomero.post_image(current_conn, image_fixture, image_name,
description='This is an image',
dataset_id=did5)
current_conn.close()
assert im_id5 == None
# Post image cross-group, valid permissions, across_groups unset
username = users_groups[1][0][0] #test_user1
groupname = users_groups[0][0][0] #test_group_1
current_conn = conn.suConn(username, groupname)
dataset_info = project_structure[1]
did6 = dataset_info[3][1] #ds2 (in test_group_2)
image_name = 'test_post_image_' + timestamp
im_id6 = ezomero.post_image(current_conn, image_fixture, image_name,
description='This is an image',
dataset_id=did6, across_groups=False)
current_conn.close()
assert im_id6 == None
conn.deleteObjects("Image", [im_id, im_id2, im_id4], deleteAnns=True,
deleteChildren=True, wait=True)
def test_post_get_map_annotation(conn, project_structure, users_groups):
image_info = project_structure[2]
im_id = image_info[0][1]
# This test both ezomero.post_map_annotation and ezomero.get_map_annotation
kv = {"key1": "value1",
"key2": "value2"}
ns = "jax.org/omeroutils/tests/v0"
map_ann_id = ezomero.post_map_annotation(conn, "Image", im_id, kv, ns)
kv_pairs = ezomero.get_map_annotation(conn, map_ann_id)
assert kv_pairs["key2"] == "value2"
# Test posting to non-existing object
im_id2 = 999999999
map_ann_id2 = ezomero.post_map_annotation(conn, "Image", im_id2, kv, ns)
assert map_ann_id2 == None
# Test posting cross-group
username = users_groups[1][0][0] # test_user1
groupname = users_groups[0][0][0] # test_group_1
current_conn = conn.suConn(username, groupname)
im_id3 = image_info[2][1] # im2, in test_group_2
map_ann_id3 = ezomero.post_map_annotation(current_conn, "Image", im_id3, kv, ns)
kv_pairs3 = ezomero.get_map_annotation(current_conn, map_ann_id3)
assert kv_pairs3["key2"] == "value2"
current_conn.close()
# Test posting to an invalid cross-group
username = users_groups[1][2][0] # test_user3
groupname = users_groups[0][1][0] # test_group_2
current_conn = conn.suConn(username, groupname)
im_id4 = image_info[1][1] # im1(in test_group_1)
map_ann_id4 = ezomero.post_map_annotation(current_conn, "Image", im_id4, kv, ns)
assert map_ann_id4 == None
current_conn.close()
# Test posting cross-group, across_groups unset
username = users_groups[1][0][0] #test_user1
groupname = users_groups[0][0][0] #test_group_1
current_conn = conn.suConn(username, groupname)
im_id6 = image_info[2][1] #im2, in test_group_2
map_ann_id6 = ezomero.post_map_annotation(current_conn, "Image", im_id6, kv, ns, across_groups=False)
assert map_ann_id6 == None
current_conn.close()
conn.deleteObjects("Annotation", [map_ann_id, map_ann_id3], deleteAnns=True,
deleteChildren=True, wait=True)
def test_post_roi(conn, project_structure, roi_fixture, users_groups):
image_info = project_structure[2]
im_id = image_info[0][1]
roi_id = ezomero.post_roi(conn, im_id,
shapes=roi_fixture['shapes'],
name=roi_fixture['name'],
description=roi_fixture['desc'],
fill_color=roi_fixture['fill_color'],
stroke_color=roi_fixture['stroke_color'],
stroke_width=roi_fixture['stroke_width'])
roi_in_omero = conn.getObject('Roi', roi_id)
assert roi_in_omero.getName() == roi_fixture['name']
assert roi_in_omero.getDescription() == roi_fixture['desc']
# Test posting to a non-existing image
im_id2 = 999999999
with pytest.raises(Exception): # TODO: verify which exception type
_ = ezomero.post_roi(conn, im_id2,
shapes=roi_fixture['shapes'],
name=roi_fixture['name'],
description=roi_fixture['desc'],
fill_color=roi_fixture['fill_color'],
stroke_color=roi_fixture['stroke_color'],
stroke_width=roi_fixture['stroke_width'])
# Test posting to an invalid cross-group
username = users_groups[1][2][0] # test_user3
groupname = users_groups[0][1][0] # test_group_2
current_conn = conn.suConn(username, groupname)
im_id4 = image_info[1][1] # im1(in test_group_1)
with pytest.raises(Exception): # TODO: verify which exception type
_ = ezomero.post_roi(current_conn, im_id4,
shapes=roi_fixture['shapes'],
name=roi_fixture['name'],
description=roi_fixture['desc'],
fill_color=roi_fixture['fill_color'],
stroke_color=roi_fixture['stroke_color'],
stroke_width=roi_fixture['stroke_width'])
current_conn.close()
conn.deleteObjects("Roi", [roi_id], deleteAnns=True,
deleteChildren=True, wait=True)
def test_post_project(conn, timestamp):
# No description
new_proj = "test_post_project_" + timestamp
pid = ezomero.post_project(conn, new_proj)
assert conn.getObject("Project", pid).getName() == new_proj
# With description
new_proj2 = "test_post_project2_" + timestamp
desc = "Now with a description"
pid2 = ezomero.post_project(conn, new_proj2, description=desc)
assert conn.getObject("Project", pid2).getDescription() == desc
conn.deleteObjects("Project", [pid, pid2], deleteAnns=True,
deleteChildren=True, wait=True)
def test_post_project_type(conn):
with pytest.raises(TypeError):
_ = ezomero.post_project(conn, 123)
with pytest.raises(TypeError):
_ = ezomero.post_project(conn, '123', description=1245)
# Test gets
###########
def test_get_image(conn, project_structure, users_groups):
image_info = project_structure[2]
im_id = image_info[0][1]
# test default
im, im_arr = ezomero.get_image(conn, im_id)
assert im.getId() == im_id
assert im_arr.shape == (1, 20, 201, 200, 3)
assert im.getPixelsType() == im_arr.dtype
# test non-existent id
im_id2 = 999999999
im2, im_arr2 = ezomero.get_image(conn, im_id2)
assert im2 == None
assert im_arr2 == None
# test cross-group valid
username = users_groups[1][0][0] #test_user1
groupname = users_groups[0][0][0] #test_group_1
current_conn = conn.suConn(username, groupname)
im_id3 = image_info[2][1] #im2, in test_group_2
im3, im_arr3 = ezomero.get_image(current_conn, im_id3)
assert im3.getId() == im_id3
assert im_arr3.shape == (1, 20, 201, 200, 3)
assert im3.getPixelsType() == im_arr3.dtype
current_conn.close()
# test cross-group invalid
username = users_groups[1][2][0] #test_user3
groupname = users_groups[0][1][0] #test_group_2
current_conn = conn.suConn(username, groupname)
im_id4 = image_info[1][1] #im1(in test_group_1)
im4, im_arr4 = ezomero.get_image(current_conn, im_id4)
assert im4 == None
assert im_arr4 == None
current_conn.close()
# test cross-group valid, across_groups unset
username = users_groups[1][0][0] #test_user1
groupname = users_groups[0][0][0] #test_group_1
current_conn = conn.suConn(username, groupname)
im_id5 = image_info[2][1] #im2, in test_group_2
im5, im_arr5 = ezomero.get_image(current_conn, im_id5, across_groups=False)
assert im5 == None
assert im_arr5 == None
current_conn.close()
# test xyzct
im, im_arr = ezomero.get_image(conn, im_id, xyzct=True)
assert im_arr.shape == (200, 201, 20, 3, 1)
# test no pixels
im, im_arr = ezomero.get_image(conn, im_id, no_pixels=True)
assert im_arr is None
# test that IndexError comes up when pad=False
with pytest.raises(IndexError):
im, im_arr = ezomero.get_image(conn, im_id,
start_coords=(195, 195, 18, 0, 0),
axis_lengths=(10, 10, 3, 4, 3),
pad=False)
# test crop
im, im_arr = ezomero.get_image(conn, im_id,
start_coords=(101, 101, 10, 0, 0),
axis_lengths=(10, 10, 3, 3, 1))
assert im_arr.shape == (1, 3, 10, 10, 3)
assert np.allclose(im_arr[0, 0, 0, 0, :], [0, 0, 255])
# test crop with padding
im, im_arr = ezomero.get_image(conn, im_id,
start_coords=(195, 195, 18, 0, 0),
axis_lengths=(10, 11, 3, 4, 3),
pad=True)
assert im_arr.shape == (3, 3, 11, 10, 4)
def test_get_image_ids(conn, project_structure, screen_structure, users_groups):
dataset_info = project_structure[1]
main_ds_id = dataset_info[0][1]
image_info = project_structure[2]
im_id = image_info[0][1]
# Based on dataset ID
im_ids = ezomero.get_image_ids(conn, dataset=main_ds_id)
assert im_ids[0] == im_id
assert len(im_ids) == 1
# Based on well ID
well_id = screen_structure[1]
im_id1 = screen_structure[2]
im_ids = ezomero.get_image_ids(conn, well=well_id)
assert im_ids[0] == im_id1
assert len(im_ids) == 1
# test cross-group valid
username = users_groups[1][0][0] #test_user1
groupname = users_groups[0][0][0] #test_group_1
current_conn = conn.suConn(username, groupname)
main_ds_id2 = dataset_info[4][1]
im_id2 = image_info[2][1] #im2, in test_group_2
im_ids2 = ezomero.get_image_ids(current_conn, dataset=main_ds_id2)
assert im_ids2[0] == im_id2
assert len(im_ids2) == 2
current_conn.close()
# test cross-group invalid
username = users_groups[1][2][0] #test_user3
groupname = users_groups[0][1][0] #test_group_2
current_conn = conn.suConn(username, groupname)
im_id3 = image_info[1][1] #im1(in test_group_1)
main_ds_id3 = dataset_info[1][1]
im_ids3 = ezomero.get_image_ids(current_conn, dataset=main_ds_id3)
assert len(im_ids3) == 0
# test cross-group valid, across_groups unset
| |
'ticksuffix', 'visible']
Run `<angularaxis-object>.help('attribute')` on any of the above.
'<angularaxis-object>' is the object at []
"""
_name = 'angularaxis'
class Annotation(PlotlyDict):
"""
Valid attributes for 'annotation' at path [] under parents ():
['align', 'arrowcolor', 'arrowhead', 'arrowsize', 'arrowwidth', 'ax',
'axref', 'ay', 'ayref', 'bgcolor', 'bordercolor', 'borderpad',
'borderwidth', 'captureevents', 'clicktoshow', 'font', 'height',
'hoverlabel', 'hovertext', 'opacity', 'ref', 'showarrow', 'standoff',
'text', 'textangle', 'valign', 'visible', 'width', 'x', 'xanchor',
'xclick', 'xref', 'xshift', 'y', 'yanchor', 'yclick', 'yref', 'yshift',
'z']
Run `<annotation-object>.help('attribute')` on any of the above.
'<annotation-object>' is the object at []
"""
_name = 'annotation'
class Annotations(PlotlyList):
"""
Valid items for 'annotations' at path [] under parents ():
['Annotation']
"""
_name = 'annotations'
class Area(PlotlyDict):
"""
Valid attributes for 'area' at path [] under parents ():
['customdata', 'customdatasrc', 'hoverinfo', 'hoverinfosrc',
'hoverlabel', 'ids', 'idssrc', 'legendgroup', 'marker', 'name',
'opacity', 'r', 'rsrc', 'showlegend', 'stream', 't', 'tsrc', 'type',
'uid', 'visible']
Run `<area-object>.help('attribute')` on any of the above.
'<area-object>' is the object at []
"""
_name = 'area'
class Bar(PlotlyDict):
"""
Valid attributes for 'bar' at path [] under parents ():
['bardir', 'base', 'basesrc', 'constraintext', 'customdata',
'customdatasrc', 'dx', 'dy', 'error_x', 'error_y', 'hoverinfo',
'hoverinfosrc', 'hoverlabel', 'hovertext', 'hovertextsrc', 'ids',
'idssrc', 'insidetextfont', 'legendgroup', 'marker', 'name', 'offset',
'offsetsrc', 'opacity', 'orientation', 'outsidetextfont', 'r', 'rsrc',
'showlegend', 'stream', 't', 'text', 'textfont', 'textposition',
'textpositionsrc', 'textsrc', 'tsrc', 'type', 'uid', 'visible',
'width', 'widthsrc', 'x', 'x0', 'xaxis', 'xcalendar', 'xsrc', 'y',
'y0', 'yaxis', 'ycalendar', 'ysrc']
Run `<bar-object>.help('attribute')` on any of the above.
'<bar-object>' is the object at []
"""
_name = 'bar'
class Box(PlotlyDict):
"""
Valid attributes for 'box' at path [] under parents ():
['boxmean', 'boxpoints', 'customdata', 'customdatasrc', 'fillcolor',
'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'ids', 'idssrc', 'jitter',
'legendgroup', 'line', 'marker', 'name', 'opacity', 'orientation',
'pointpos', 'showlegend', 'stream', 'type', 'uid', 'visible',
'whiskerwidth', 'x', 'x0', 'xaxis', 'xcalendar', 'xsrc', 'y', 'y0',
'yaxis', 'ycalendar', 'ysrc']
Run `<box-object>.help('attribute')` on any of the above.
'<box-object>' is the object at []
"""
_name = 'box'
class Candlestick(PlotlyDict):
"""
Valid attributes for 'candlestick' at path [] under parents ():
['close', 'closesrc', 'customdata', 'customdatasrc', 'decreasing',
'high', 'highsrc', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'ids',
'idssrc', 'increasing', 'legendgroup', 'line', 'low', 'lowsrc', 'name',
'opacity', 'open', 'opensrc', 'showlegend', 'stream', 'text',
'textsrc', 'type', 'uid', 'visible', 'whiskerwidth', 'x', 'xaxis',
'xcalendar', 'xsrc', 'yaxis']
Run `<candlestick-object>.help('attribute')` on any of the above.
'<candlestick-object>' is the object at []
"""
_name = 'candlestick'
class Carpet(PlotlyDict):
"""
Valid attributes for 'carpet' at path [] under parents ():
['a', 'a0', 'aaxis', 'asrc', 'b', 'b0', 'baxis', 'bsrc', 'carpet',
'cheaterslope', 'color', 'customdata', 'customdatasrc', 'da', 'db',
'font', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'ids', 'idssrc',
'legendgroup', 'name', 'opacity', 'showlegend', 'stream', 'type',
'uid', 'visible', 'x', 'xaxis', 'xsrc', 'y', 'yaxis', 'ysrc']
Run `<carpet-object>.help('attribute')` on any of the above.
'<carpet-object>' is the object at []
"""
_name = 'carpet'
class Choropleth(PlotlyDict):
"""
Valid attributes for 'choropleth' at path [] under parents ():
['autocolorscale', 'colorbar', 'colorscale', 'customdata',
'customdatasrc', 'geo', 'hoverinfo', 'hoverinfosrc', 'hoverlabel',
'ids', 'idssrc', 'legendgroup', 'locationmode', 'locations',
'locationssrc', 'marker', 'name', 'opacity', 'reversescale',
'showlegend', 'showscale', 'stream', 'text', 'textsrc', 'type', 'uid',
'visible', 'z', 'zauto', 'zmax', 'zmin', 'zsrc']
Run `<choropleth-object>.help('attribute')` on any of the above.
'<choropleth-object>' is the object at []
"""
_name = 'choropleth'
class ColorBar(PlotlyDict):
"""
Valid attributes for 'colorbar' at path [] under parents ():
['bgcolor', 'bordercolor', 'borderwidth', 'dtick', 'exponentformat',
'len', 'lenmode', 'nticks', 'outlinecolor', 'outlinewidth',
'separatethousands', 'showexponent', 'showticklabels',
'showtickprefix', 'showticksuffix', 'thickness', 'thicknessmode',
'tick0', 'tickangle', 'tickcolor', 'tickfont', 'tickformat', 'ticklen',
'tickmode', 'tickprefix', 'ticks', 'ticksuffix', 'ticktext',
'ticktextsrc', 'tickvals', 'tickvalssrc', 'tickwidth', 'title',
'titlefont', 'titleside', 'x', 'xanchor', 'xpad', 'y', 'yanchor',
'ypad']
Run `<colorbar-object>.help('attribute')` on any of the above.
'<colorbar-object>' is the object at []
"""
_name = 'colorbar'
class Contour(PlotlyDict):
"""
Valid attributes for 'contour' at path [] under parents ():
['autocolorscale', 'autocontour', 'colorbar', 'colorscale',
'connectgaps', 'contours', 'customdata', 'customdatasrc', 'dx', 'dy',
'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'ids', 'idssrc',
'legendgroup', 'line', 'name', 'ncontours', 'opacity', 'reversescale',
'showlegend', 'showscale', 'stream', 'text', 'textsrc', 'transpose',
'type', 'uid', 'visible', 'x', 'x0', 'xaxis', 'xcalendar', 'xsrc',
'xtype', 'y', 'y0', 'yaxis', 'ycalendar', 'ysrc', 'ytype', 'z',
'zauto', 'zmax', 'zmin', 'zsrc']
Run `<contour-object>.help('attribute')` on any of the above.
'<contour-object>' is the object at []
"""
_name = 'contour'
class Contourcarpet(PlotlyDict):
"""
Valid attributes for 'contourcarpet' at path [] under parents ():
['a', 'a0', 'asrc', 'atype', 'autocolorscale', 'autocontour', 'b',
'b0', 'bsrc', 'btype', 'carpet', 'colorbar', 'colorscale',
'connectgaps', 'contours', 'customdata', 'customdatasrc', 'da', 'db',
'fillcolor', 'hoverinfo', 'hoverinfosrc', 'hoverlabel', 'ids',
'idssrc', 'legendgroup', 'line', 'mode', 'name', 'ncontours',
'opacity', 'reversescale', 'showlegend', 'showscale', 'stream', 'text',
'textsrc', 'transpose', 'type', 'uid', 'visible', 'xaxis', 'yaxis',
'z', 'zauto', 'zmax', 'zmin', 'zsrc']
Run `<contourcarpet-object>.help('attribute')` on any of the above.
'<contourcarpet-object>' is the object at []
"""
_name = 'contourcarpet'
class Contours(PlotlyDict):
"""
Valid attributes for 'contours' at path [] under parents ():
['coloring', 'end', 'labelfont', 'labelformat', 'operation',
'showlabels', 'showlines', 'size', 'start', 'type', 'value', 'x', 'y',
'z']
Run `<contours-object>.help('attribute')` on any of the above.
'<contours-object>' is the object at []
"""
_name = 'contours'
class Data(PlotlyList):
"""
Valid items for 'data' at path [] under parents ():
['Area', 'Bar', 'Box', 'Candlestick', 'Carpet', 'Choropleth',
'Contour', 'Contourcarpet', 'Heatmap', 'Heatmapgl', 'Histogram',
'Histogram2d', 'Histogram2dcontour', 'Mesh3d', 'Ohlc', 'Parcoords',
'Pie', 'Pointcloud', 'Sankey', 'Scatter', 'Scatter3d', 'Scattercarpet',
'Scattergeo', 'Scattergl', 'Scattermapbox', 'Scatterternary',
'Surface', 'Table']
"""
_name = 'data'
def _value_to_graph_object(self, index, value, _raise=True):
if not isinstance(value, dict):
if _raise:
notes = ['Entry should subclass dict.']
path = self._get_path() + (index, )
raise exceptions.PlotlyListEntryError(self, path,
notes=notes)
else:
return
item = value.get('type', 'scatter')
if item not in graph_reference.ARRAYS['data']['items']:
if _raise:
path = self._get_path() + (0, )
raise exceptions.PlotlyDataTypeError(self, path)
return GraphObjectFactory.create(item, _raise=_raise,
_parent=self,
_parent_key=index, **value)
def get_data(self, flatten=False):
"""
Returns the JSON for the plot with non-data elements stripped.
:param (bool) flatten: {'a': {'b': ''}} --> {'a.b': ''}
:returns: (dict|list) Depending on (flat|unflat)
"""
if flatten:
data = [v.get_data(flatten=flatten) for v in self]
d = {}
taken_names = []
for i, trace in enumerate(data):
# we want to give the traces helpful names
# however, we need to be sure they're unique too...
trace_name = trace.pop('name', 'trace_{0}'.format(i))
if trace_name in taken_names:
j = 1
new_trace_name = "{0}_{1}".format(trace_name, j)
while new_trace_name in taken_names:
new_trace_name = (
"{0}_{1}".format(trace_name, j)
)
j += 1
trace_name = new_trace_name
taken_names.append(trace_name)
# finish up the dot-concatenation
for k, v in trace.items():
key = "{0}.{1}".format(trace_name, k)
d[key] = v
return d
else:
return super(Data, self).get_data(flatten=flatten)
class ErrorX(PlotlyDict):
"""
Valid attributes for 'error_x' at path [] under parents ():
['array', 'arrayminus', 'arrayminussrc', 'arraysrc', 'color',
'copy_ystyle', 'copy_zstyle', 'opacity', 'symmetric', 'thickness',
'traceref', 'tracerefminus', 'type', 'value', 'valueminus', 'visible',
'width']
Run `<error_x-object>.help('attribute')` on any of the above.
'<error_x-object>' is the object at []
"""
_name = 'error_x'
class ErrorY(PlotlyDict):
"""
Valid attributes for 'error_y' at path [] under parents ():
['array', 'arrayminus', 'arrayminussrc', 'arraysrc', 'color',
'copy_ystyle', 'copy_zstyle', 'opacity', 'symmetric', 'thickness',
'traceref', 'tracerefminus', 'type', 'value', 'valueminus', 'visible',
'width']
Run `<error_y-object>.help('attribute')` on any of the above.
'<error_y-object>' is the object at []
"""
_name = 'error_y'
class ErrorZ(PlotlyDict):
"""
Valid attributes for 'error_z' at path [] under parents ():
['array', 'arrayminus', 'arrayminussrc', 'arraysrc', 'color',
'copy_ystyle', 'copy_zstyle', 'opacity', 'symmetric', 'thickness',
'traceref', 'tracerefminus', 'type', 'value', 'valueminus', 'visible',
'width']
Run `<error_z-object>.help('attribute')` on any of the above.
'<error_z-object>' is the object at []
"""
_name = 'error_z'
class Figure(PlotlyDict):
"""
Valid attributes for 'figure' at path [] under parents ():
['data', 'frames', 'layout']
Run `<figure-object>.help('attribute')` on any of the above.
'<figure-object>' is the object at []
"""
_name = 'figure'
def __init__(self, *args, **kwargs):
super(Figure, self).__init__(*args, **kwargs)
if 'data' not in self:
self.data = Data(_parent=self, _parent_key='data')
def get_data(self, flatten=False):
"""
Returns the JSON for the plot with non-data elements stripped.
Flattening may increase the utility of the result.
:param (bool) flatten: {'a': {'b': ''}} --> {'a.b': ''}
:returns: (dict|list) Depending on (flat|unflat)
"""
return self.data.get_data(flatten=flatten)
def to_dataframe(self):
"""
Create a dataframe with trace names and keys as column names.
:return: (DataFrame)
"""
data = self.get_data(flatten=True)
from pandas import DataFrame, Series
return DataFrame(
dict([(k, Series(v)) for k, v in data.items()]))
def print_grid(self):
"""
Print a visual layout of the figure's axes arrangement.
This is only valid for | |
# coding: utf-8
"""
Copyright 2017 Square, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from pprint import pformat
from six import iteritems
import re
class V1Refund(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, type=None, reason=None, refunded_money=None, refunded_processing_fee_money=None, refunded_tax_money=None, refunded_additive_tax_money=None, refunded_additive_tax=None, refunded_inclusive_tax_money=None, refunded_inclusive_tax=None, refunded_tip_money=None, refunded_discount_money=None, refunded_surcharge_money=None, refunded_surcharges=None, created_at=None, processed_at=None, payment_id=None, merchant_id=None, is_exchange=None):
"""
V1Refund - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'type': 'str',
'reason': 'str',
'refunded_money': 'V1Money',
'refunded_processing_fee_money': 'V1Money',
'refunded_tax_money': 'V1Money',
'refunded_additive_tax_money': 'V1Money',
'refunded_additive_tax': 'list[V1PaymentTax]',
'refunded_inclusive_tax_money': 'V1Money',
'refunded_inclusive_tax': 'list[V1PaymentTax]',
'refunded_tip_money': 'V1Money',
'refunded_discount_money': 'V1Money',
'refunded_surcharge_money': 'V1Money',
'refunded_surcharges': 'list[V1PaymentSurcharge]',
'created_at': 'str',
'processed_at': 'str',
'payment_id': 'str',
'merchant_id': 'str',
'is_exchange': 'bool'
}
self.attribute_map = {
'type': 'type',
'reason': 'reason',
'refunded_money': 'refunded_money',
'refunded_processing_fee_money': 'refunded_processing_fee_money',
'refunded_tax_money': 'refunded_tax_money',
'refunded_additive_tax_money': 'refunded_additive_tax_money',
'refunded_additive_tax': 'refunded_additive_tax',
'refunded_inclusive_tax_money': 'refunded_inclusive_tax_money',
'refunded_inclusive_tax': 'refunded_inclusive_tax',
'refunded_tip_money': 'refunded_tip_money',
'refunded_discount_money': 'refunded_discount_money',
'refunded_surcharge_money': 'refunded_surcharge_money',
'refunded_surcharges': 'refunded_surcharges',
'created_at': 'created_at',
'processed_at': 'processed_at',
'payment_id': 'payment_id',
'merchant_id': 'merchant_id',
'is_exchange': 'is_exchange'
}
self._type = type
self._reason = reason
self._refunded_money = refunded_money
self._refunded_processing_fee_money = refunded_processing_fee_money
self._refunded_tax_money = refunded_tax_money
self._refunded_additive_tax_money = refunded_additive_tax_money
self._refunded_additive_tax = refunded_additive_tax
self._refunded_inclusive_tax_money = refunded_inclusive_tax_money
self._refunded_inclusive_tax = refunded_inclusive_tax
self._refunded_tip_money = refunded_tip_money
self._refunded_discount_money = refunded_discount_money
self._refunded_surcharge_money = refunded_surcharge_money
self._refunded_surcharges = refunded_surcharges
self._created_at = created_at
self._processed_at = processed_at
self._payment_id = payment_id
self._merchant_id = merchant_id
self._is_exchange = is_exchange
@property
def type(self):
"""
Gets the type of this V1Refund.
The type of refund See [V1RefundType](#type-v1refundtype) for possible values
:return: The type of this V1Refund.
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""
Sets the type of this V1Refund.
The type of refund See [V1RefundType](#type-v1refundtype) for possible values
:param type: The type of this V1Refund.
:type: str
"""
self._type = type
@property
def reason(self):
"""
Gets the reason of this V1Refund.
The merchant-specified reason for the refund.
:return: The reason of this V1Refund.
:rtype: str
"""
return self._reason
@reason.setter
def reason(self, reason):
"""
Sets the reason of this V1Refund.
The merchant-specified reason for the refund.
:param reason: The reason of this V1Refund.
:type: str
"""
self._reason = reason
@property
def refunded_money(self):
"""
Gets the refunded_money of this V1Refund.
The amount of money refunded. This amount is always negative.
:return: The refunded_money of this V1Refund.
:rtype: V1Money
"""
return self._refunded_money
@refunded_money.setter
def refunded_money(self, refunded_money):
"""
Sets the refunded_money of this V1Refund.
The amount of money refunded. This amount is always negative.
:param refunded_money: The refunded_money of this V1Refund.
:type: V1Money
"""
self._refunded_money = refunded_money
@property
def refunded_processing_fee_money(self):
"""
Gets the refunded_processing_fee_money of this V1Refund.
The amount of processing fee money refunded. This amount is always positive.
:return: The refunded_processing_fee_money of this V1Refund.
:rtype: V1Money
"""
return self._refunded_processing_fee_money
@refunded_processing_fee_money.setter
def refunded_processing_fee_money(self, refunded_processing_fee_money):
"""
Sets the refunded_processing_fee_money of this V1Refund.
The amount of processing fee money refunded. This amount is always positive.
:param refunded_processing_fee_money: The refunded_processing_fee_money of this V1Refund.
:type: V1Money
"""
self._refunded_processing_fee_money = refunded_processing_fee_money
@property
def refunded_tax_money(self):
"""
Gets the refunded_tax_money of this V1Refund.
The total amount of tax money refunded. This amount is always negative.
:return: The refunded_tax_money of this V1Refund.
:rtype: V1Money
"""
return self._refunded_tax_money
@refunded_tax_money.setter
def refunded_tax_money(self, refunded_tax_money):
"""
Sets the refunded_tax_money of this V1Refund.
The total amount of tax money refunded. This amount is always negative.
:param refunded_tax_money: The refunded_tax_money of this V1Refund.
:type: V1Money
"""
self._refunded_tax_money = refunded_tax_money
@property
def refunded_additive_tax_money(self):
"""
Gets the refunded_additive_tax_money of this V1Refund.
The amount of additive tax money refunded. This amount is always negative.
:return: The refunded_additive_tax_money of this V1Refund.
:rtype: V1Money
"""
return self._refunded_additive_tax_money
@refunded_additive_tax_money.setter
def refunded_additive_tax_money(self, refunded_additive_tax_money):
"""
Sets the refunded_additive_tax_money of this V1Refund.
The amount of additive tax money refunded. This amount is always negative.
:param refunded_additive_tax_money: The refunded_additive_tax_money of this V1Refund.
:type: V1Money
"""
self._refunded_additive_tax_money = refunded_additive_tax_money
@property
def refunded_additive_tax(self):
"""
Gets the refunded_additive_tax of this V1Refund.
All of the additive taxes associated with the refund.
:return: The refunded_additive_tax of this V1Refund.
:rtype: list[V1PaymentTax]
"""
return self._refunded_additive_tax
@refunded_additive_tax.setter
def refunded_additive_tax(self, refunded_additive_tax):
"""
Sets the refunded_additive_tax of this V1Refund.
All of the additive taxes associated with the refund.
:param refunded_additive_tax: The refunded_additive_tax of this V1Refund.
:type: list[V1PaymentTax]
"""
self._refunded_additive_tax = refunded_additive_tax
@property
def refunded_inclusive_tax_money(self):
"""
Gets the refunded_inclusive_tax_money of this V1Refund.
The amount of inclusive tax money refunded. This amount is always negative.
:return: The refunded_inclusive_tax_money of this V1Refund.
:rtype: V1Money
"""
return self._refunded_inclusive_tax_money
@refunded_inclusive_tax_money.setter
def refunded_inclusive_tax_money(self, refunded_inclusive_tax_money):
"""
Sets the refunded_inclusive_tax_money of this V1Refund.
The amount of inclusive tax money refunded. This amount is always negative.
:param refunded_inclusive_tax_money: The refunded_inclusive_tax_money of this V1Refund.
:type: V1Money
"""
self._refunded_inclusive_tax_money = refunded_inclusive_tax_money
@property
def refunded_inclusive_tax(self):
"""
Gets the refunded_inclusive_tax of this V1Refund.
All of the inclusive taxes associated with the refund.
:return: The refunded_inclusive_tax of this V1Refund.
:rtype: list[V1PaymentTax]
"""
return self._refunded_inclusive_tax
@refunded_inclusive_tax.setter
def refunded_inclusive_tax(self, refunded_inclusive_tax):
"""
Sets the refunded_inclusive_tax of this V1Refund.
All of the inclusive taxes associated with the refund.
:param refunded_inclusive_tax: The refunded_inclusive_tax of this V1Refund.
:type: list[V1PaymentTax]
"""
self._refunded_inclusive_tax = refunded_inclusive_tax
@property
def refunded_tip_money(self):
"""
Gets the refunded_tip_money of this V1Refund.
The amount of tip money refunded. This amount is always negative.
:return: The refunded_tip_money of this V1Refund.
:rtype: V1Money
"""
return self._refunded_tip_money
@refunded_tip_money.setter
def refunded_tip_money(self, refunded_tip_money):
"""
Sets the refunded_tip_money of this V1Refund.
The amount of tip money refunded. This amount is always negative.
:param refunded_tip_money: The refunded_tip_money of this V1Refund.
:type: V1Money
"""
self._refunded_tip_money = refunded_tip_money
@property
def refunded_discount_money(self):
"""
Gets the refunded_discount_money of this V1Refund.
The amount of discount money refunded. This amount is always positive.
:return: The refunded_discount_money of this V1Refund.
:rtype: V1Money
"""
return self._refunded_discount_money
@refunded_discount_money.setter
def refunded_discount_money(self, refunded_discount_money):
"""
Sets the refunded_discount_money of this V1Refund.
The amount of discount money refunded. This amount is always positive.
:param refunded_discount_money: The refunded_discount_money of this V1Refund.
:type: V1Money
"""
self._refunded_discount_money = refunded_discount_money
@property
def refunded_surcharge_money(self):
"""
Gets the refunded_surcharge_money of this V1Refund.
The amount of surcharge money refunded. This amount is always negative.
:return: The refunded_surcharge_money of this V1Refund.
:rtype: V1Money
"""
return self._refunded_surcharge_money
@refunded_surcharge_money.setter
def refunded_surcharge_money(self, refunded_surcharge_money):
"""
Sets the refunded_surcharge_money of this V1Refund.
The amount of surcharge money refunded. This amount is always negative.
:param refunded_surcharge_money: The refunded_surcharge_money of this V1Refund.
:type: V1Money
"""
self._refunded_surcharge_money = refunded_surcharge_money
@property
def refunded_surcharges(self):
"""
Gets the refunded_surcharges of this V1Refund.
A list of all surcharges associated with the refund.
:return: The refunded_surcharges of this V1Refund.
:rtype: list[V1PaymentSurcharge]
"""
return self._refunded_surcharges
@refunded_surcharges.setter
def refunded_surcharges(self, refunded_surcharges):
"""
Sets the refunded_surcharges of this V1Refund.
A list of all surcharges associated with the refund.
:param refunded_surcharges: The refunded_surcharges of this V1Refund.
:type: list[V1PaymentSurcharge]
"""
self._refunded_surcharges = refunded_surcharges
@property
def created_at(self):
"""
Gets the created_at of this V1Refund.
The time when the merchant initiated the refund for Square to process, in ISO 8601 format.
:return: The created_at of this V1Refund.
:rtype: str
"""
return self._created_at
@created_at.setter
def created_at(self, created_at):
"""
Sets the created_at of this V1Refund.
The time when the merchant initiated the refund for Square to process, in ISO 8601 format.
:param created_at: The created_at of this V1Refund.
:type: str
"""
self._created_at = created_at
@property
def processed_at(self):
"""
Gets the processed_at of this V1Refund.
The time when Square processed the refund on behalf of the merchant, in ISO 8601 format.
:return: The processed_at of this V1Refund.
:rtype: str
"""
return self._processed_at
@processed_at.setter
def processed_at(self, processed_at):
"""
Sets the processed_at of this | |
"""Test descriptors, binary ops, etc.
Made for Jython.
"""
import types
import unittest
from test import test_support
class Old:
pass
class New(object):
pass
old = Old()
new = New()
class TestDescrTestCase(unittest.TestCase):
def test_class_dict_is_copy(self):
class FooMeta(type):
def __new__(meta, name, bases, class_dict):
cls = type.__new__(meta, name, bases, class_dict)
self.assert_('foo' not in class_dict)
cls.foo = 'bar'
self.assert_('foo' not in class_dict)
return cls
class Foo(object):
__metaclass__ = FooMeta
def test_descr___get__(self):
class Foo(object):
__slots__ = 'bar'
def hello(self):
pass
def hi(self):
pass
hi = staticmethod(hi)
foo = Foo()
foo.bar = 'baz'
self.assertEqual(Foo.bar.__get__(foo), 'baz')
self.assertEqual(Foo.bar.__get__(None, Foo), Foo.bar)
bound = Foo.hello.__get__(foo)
self.assert_(isinstance(bound, types.MethodType))
self.assert_(bound.im_self is foo)
self.assertEqual(Foo.hello.__get__(None, Foo), Foo.hello)
bound = Foo.hi.__get__(foo)
self.assert_(isinstance(bound, types.MethodType))
self.assert_(bound.im_self is foo)
unbound = Foo.hi.__get__(None, foo)
self.assert_(isinstance(unbound, types.MethodType))
self.assert_(unbound.im_self is None)
def test_ints(self):
class C(int):
pass
try:
foo = int(None)
except TypeError:
pass
else:
self.assert_(False, "should have raised TypeError")
try:
foo = C(None)
except TypeError:
pass
else:
self.assert_(False, "should have raised TypeError")
def test_raising_custom_attribute_error(self):
class RaisesCustomMsg(object):
def __get__(self, instance, type):
raise AttributeError("Custom message")
class CustomAttributeError(AttributeError): pass
class RaisesCustomErr(object):
def __get__(self, instance, type):
raise CustomAttributeError
class Foo(object):
custom_msg = RaisesCustomMsg()
custom_err = RaisesCustomErr()
self.assertRaises(CustomAttributeError, lambda: Foo().custom_err)
try:
Foo().custom_msg
self.assert_(False) # Previous line should raise AttributteError
except AttributeError, e:
self.assertEquals("Custom message", str(e))
class SubclassDescrTestCase(unittest.TestCase):
def test_subclass_cmp_right_op(self):
# Case 1: subclass of int
class B(int):
def __ge__(self, other):
return "B.__ge__"
def __le__(self, other):
return "B.__le__"
self.assertEqual(B(1) >= 1, "B.__ge__")
self.assertEqual(1 >= B(1), "B.__le__")
# Case 2: subclass of object
class C(object):
def __ge__(self, other):
return "C.__ge__"
def __le__(self, other):
return "C.__le__"
self.assertEqual(C() >= 1, "C.__ge__")
self.assertEqual(1 >= C(), "C.__le__")
# Case 3: subclass of new-style class; here it gets interesting
class D(C):
def __ge__(self, other):
return "D.__ge__"
def __le__(self, other):
return "D.__le__"
self.assertEqual(D() >= C(), "D.__ge__")
self.assertEqual(C() >= D(), "D.__le__")
# Case 4: comparison is different than other binops
class E(C):
pass
self.assertEqual(E.__le__, C.__le__)
self.assertEqual(E() >= 1, "C.__ge__")
self.assertEqual(1 >= E(), "C.__le__")
self.assertEqual(E() >= C(), "C.__ge__")
self.assertEqual(C() >= E(), "C.__le__") # different
def test_subclass_binop(self):
def raises(exc, expected, callable, *args):
try:
callable(*args)
except exc, msg:
if str(msg) != expected:
self.assert_(False, "Message %r, expected %r" % (str(msg),
expected))
else:
self.assert_(False, "Expected %s" % exc)
class B(object):
pass
class C(object):
def __radd__(self, o):
return '%r + C()' % (o,)
def __rmul__(self, o):
return '%r * C()' % (o,)
# Test strs, unicode, lists and tuples
mapping = []
# + binop
mapping.append((lambda o: 'foo' + o,
TypeError, "cannot concatenate 'str' and 'B' objects",
"'foo' + C()"))
# XXX: There's probably work to be done here besides just emulating this
# message
if test_support.is_jython:
mapping.append((lambda o: u'foo' + o,
TypeError, "cannot concatenate 'unicode' and 'B' objects",
"u'foo' + C()"))
else:
mapping.append((lambda o: u'foo' + o,
TypeError,
'coercing to Unicode: need string or buffer, B found',
"u'foo' + C()"))
mapping.append((lambda o: [1, 2] + o,
TypeError, 'can only concatenate list (not "B") to list',
'[1, 2] + C()'))
mapping.append((lambda o: ('foo', 'bar') + o,
TypeError, 'can only concatenate tuple (not "B") to tuple',
"('foo', 'bar') + C()"))
# * binop
mapping.append((lambda o: 'foo' * o,
TypeError, "can't multiply sequence by non-int of type 'B'",
"'foo' * C()"))
mapping.append((lambda o: u'foo' * o,
TypeError, "can't multiply sequence by non-int of type 'B'",
"u'foo' * C()"))
mapping.append((lambda o: [1, 2] * o,
TypeError, "can't multiply sequence by non-int of type 'B'",
'[1, 2] * C()'))
mapping.append((lambda o: ('foo', 'bar') * o,
TypeError, "can't multiply sequence by non-int of type 'B'",
"('foo', 'bar') * C()"))
for func, bexc, bexc_msg, cresult in mapping:
raises(bexc, bexc_msg, lambda : func(B()))
self.assertEqual(func(C()), cresult)
def test_overriding_base_binop(self):
class MulBase(object):
def __init__(self, value):
self.value = value
def __mul__(self, other):
return self.value * other.value
def __rmul__(self, other):
return other.value * self.value
class DoublerBase(MulBase):
def __mul__(self, other):
return 2 * (self.value * other.value)
class AnotherDoubler(DoublerBase):
pass
self.assertEquals(DoublerBase(2) * AnotherDoubler(3), 12)
def test_oldstyle_binop_notimplemented(self):
class Foo:
pass
class Bar(object):
def __radd__(self, other):
return 3
self.assertEqual(Foo() + Bar(), 3)
def test_int_mul(self):
# http://bugs.jython.org/issue1332
class Foo(tuple):
def __rmul__(self, other):
return 'foo'
foo = Foo()
self.assertEqual(3.0 * foo, 'foo')
self.assertEqual(4 * foo, 'foo')
class InPlaceTestCase(unittest.TestCase):
def test_iadd(self):
class Foo(object):
def __add__(self, other):
return 1
def __radd__(self, other):
return 2
class Bar(object):
pass
class Baz(object):
def __iadd__(self, other):
return NotImplemented
foo = Foo()
foo += Bar()
self.assertEqual(foo, 1)
bar = Bar()
bar += Foo()
self.assertEqual(bar, 2)
baz = Baz()
baz += Foo()
self.assertEqual(baz, 2)
def test_imul(self):
class FooInplace(list):
def __imul__(self, other):
return [1]
class Bar(FooInplace):
def __mul__(self, other):
return [2]
foo = FooInplace()
foo *= 3
self.assertEqual(foo, [1])
foo = Bar([3])
foo *= 3
self.assertEqual(foo, [1])
class Baz(FooInplace):
def __mul__(self, other):
return [3]
baz = Baz()
baz *= 3
self.assertEqual(baz, [1])
def test_list(self):
class Foo(list):
def __mul__(self, other):
return [1]
foo = Foo([2])
foo *= 3
if test_support.is_jython:
self.assertEqual(foo, [2, 2, 2])
else:
# CPython ignores list.__imul__ on a subclass with __mul__
# (unlike Jython and PyPy)
self.assertEqual(foo, [1])
class Bar(object):
def __radd__(self, other):
return 1
def __rmul__(self, other):
return 2
l = []
l += Bar()
self.assertEqual(l, 1)
l = []
l *= Bar()
self.assertEqual(l, 2)
def test_iand(self):
# Jython's set __iand__ (as well as isub, ixor, etc) was
# previously broken
class Foo(set):
def __and__(self, other):
return set([1])
foo = Foo()
foo &= 3
self.assertEqual(foo, set([1]))
class DescrExceptionsTestCase(unittest.TestCase):
def test_hex(self):
self._test(hex)
def test_oct(self):
self._test(oct)
def test_other(self):
for op in '-', '+', '~':
try:
eval('%s(old)' % op)
except AttributeError:
pass
else:
self._assert(False, 'Expected an AttributeError, op: %s' % op)
try:
eval('%s(new)' % op)
except TypeError:
pass
else:
self._assert(False, 'Expected a TypeError, op: %s' % op)
def _test(self, func):
self.assertRaises(AttributeError, func, old)
self.assertRaises(TypeError, func, new)
def test_eq(self):
class A(object):
def __eq__(self, other):
return self.value == other.value
self.assertRaises(AttributeError, lambda: A() == A())
class GetAttrTestCase(unittest.TestCase):
def test_raising_custom_attribute_error(self):
# Very similar to
# test_descr_jy.TestDescrTestCase.test_raising_custom_attribute_error
class BarAttributeError(AttributeError): pass
class Bar(object):
def __getattr__(self, name):
raise BarAttributeError
class BarClassic:
def __getattr__(self, name):
raise BarAttributeError
class Foo(object):
def __getattr__(self, name):
raise AttributeError("Custom message")
class FooClassic:
def __getattr__(self, name):
raise AttributeError("Custom message")
self.assertRaises(BarAttributeError, lambda: Bar().x)
self.assertRaises(BarAttributeError, lambda: BarClassic().x)
try:
Foo().x
self.assert_(False) # Previous line should raise AttributteError
except AttributeError, e:
self.assertEquals("Custom message", str(e))
try:
FooClassic().x
self.assert_(False) # Previous line should raise AttributteError
except AttributeError, e:
self.assertEquals("Custom message", str(e))
class Base(object):
def __init__(self, name):
self.name = name
def lookup_where(obj, name):
mro = type(obj).__mro__
for t in mro:
if name in t.__dict__:
return t.__dict__[name], t
return None, None
def refop(x, y, opname, ropname):
# this has been validated by running the tests on top of cpython
# so for the space of possibilities that the tests touch it is known
# to behave like cpython as long as the latter doesn't change its own
# algorithm
t1 = type(x)
t2 = type(y)
op, where1 = lookup_where(x, opname)
rop, where2 = lookup_where(y, ropname)
if op is None and rop is not None:
return rop(y, x)
if rop and where1 is not where2:
if (issubclass(t2, t1) and not issubclass(where1, where2) and
not issubclass(t1, where2)):
return rop(y, x)
if op is None:
return "TypeError"
return op(x,y)
def do_test(X, Y, name, impl):
x = X('x')
y = Y('y')
opname = '__%s__' % name
ropname = '__r%s__' % name
count = [0]
fail = []
def check(z1, z2):
ref = refop(z1, z2, opname, ropname)
try:
v = impl(z1, z2)
except TypeError:
v = "TypeError"
if v != ref:
fail.append(count[0])
def override_in_hier(n=6):
if n == 0:
count[0] += 1
check(x, y)
check(y, x)
return
f = lambda self, other: (n, self.name, other.name)
if n % 2 == 0:
name = opname
else:
name = ropname
for C in Y.__mro__:
if name in C.__dict__:
continue
if C is not object:
setattr(C, name, f)
override_in_hier(n - 1)
if C is not object:
delattr(C, name)
override_in_hier()
#print count[0]
return fail
class BinopCombinationsTestCase(unittest.TestCase):
"""Try to test more exhaustively binop overriding combination
cases"""
def test_binop_combinations_mul(self):
class X(Base):
pass
class Y(X):
pass
fail = do_test(X, Y, 'mul', lambda x, y: x*y)
#print len(fail)
self.assert_(not fail)
def test_binop_combinations_sub(self):
class X(Base):
pass
class Y(X):
pass
fail = do_test(X, Y, 'sub', lambda | |
<filename>ehb_client/requests/external_record_request_handler.py
from ehb_client.requests.base import JsonRequestBase, RequestBase, IdentityBase
from ehb_client.requests.request_handler import RequestHandler
import json
from ehb_client.requests.exceptions import PageNotFound, InvalidArguments
class ExternalRecord(IdentityBase):
def __init__(self, record_id, subject_id=-1, external_system_id=-1,
path='', modified=None, created=None, id=-1, label_id=1):
self.record_id = record_id
self.subject_id = subject_id # this is the id of the ehb-service Subject record id
self.external_system_id = external_system_id
self.modified = modified
self.created = created
self.path = path
self.id = id
self.label_id = label_id
@staticmethod
def findIdentity(searchTermsDict, *identities):
id = searchTermsDict.get("id", None)
path = searchTermsDict.get('path', None)
record_id = searchTermsDict.get('record_id')
if id:
for s in identities:
if s.id == int(id):
return s
if record_id:
if path:
for s in identities:
if s.record_id == record_id and s.path == path:
return s
else:
for s in identities:
if s.record_id == record_id:
return s
return None
@staticmethod
def identity_from_json(erJsonString):
jsonObj = json.loads(erJsonString)
return ExternalRecord.identity_from_jsonObject(jsonObj)
@staticmethod
def identity_from_jsonObject(jsonObj):
es_id = int(jsonObj.get('external_system'))
s_id = int(jsonObj.get('subject'))
lm = RequestBase.dateTimeFromJsonString(jsonObj.get('modified'))
c = RequestBase.dateTimeFromJsonString(jsonObj.get('created'))
id = int(jsonObj.get('id'))
rec_id = jsonObj.get('record_id')
p = jsonObj.get('path')
lbl = jsonObj.get('label')
return ExternalRecord(
record_id=rec_id,
external_system_id=es_id,
subject_id=s_id,
path=p,
modified=lm,
created=c,
id=id,
label_id=lbl
)
@staticmethod
def json_from_identity(er):
o = {
'id': int(er.id),
'subject': int(er.subject_id),
'external_system': int(er.external_system_id),
'record_id': er.record_id,
'path': er.path,
}
if er.label_id:
o['label'] = int(er.label_id)
else:
o['label'] = 1
if er.modified:
o['modified'] = er.modified.strftime('%Y-%m-%d %H:%M:%S.%f')
if er.created:
o['created'] = er.created.strftime('%Y-%m-%d %H:%M:%S.%f')
return json.dumps(o)
identityLabel = "external_record"
class ExternalRecordRequestHandler(JsonRequestBase):
def __init__(self, host, root_path='', secure=False, api_key=None):
RequestBase.__init__(self, host, '{0}/api/externalrecord/'.format(root_path), secure, api_key)
def query(self, *params):
'''Attemps to locate a collection of external records in the ehb-service database:
Inputs:
params is variable length number of dictionaries where each dictionary includes one or more sets of
identifiers. The query can be on any combination of Subject, ExternalSystem and path.
It is not necessary to specify all 3, but at least 1 must be provided.
-The allowed ExternalSystem identifiers are:
external_system_id = integer value of the external_system id
OR
external_system_name = string value of the external_systyem name
OR
external_system_url = string value of the external_system URL
-The allowed Subject identifiers are:
subject_id = integer value of the subject id
OR
subject_org = int value of the eHB Organization record id for this subject
subject_org_id = string value of the organization_subject_id for this Subject
-The allowed path identifier is path
example query({"subject_id":1, "external_system_id":2, "path":"thepath"},{"subject_id":2, "external_system_name":"somename"})
Returns:
[dictionaries]
where each entry is of the form
{"external_system":value, "subject":"id":"value", "success":boolean, "external_record":[ExternalRecords objects]}
{"external_system":value, "subject":{"subject_org":"value", "subject_org_id":"value"}, "success":boolean, "external_record":[ExternalRecords objects]}
OR
{"external_system":value, "subject":value, "success":boolean, "errors":[error codes]}'''
body = '['
for d in params:
body += '{'
for k in list(d.keys()):
body += '"{0}": "{1}",'.format(k, str(d.get(k)))
body = body[0:body.__len__() - 1] + '},'
body = body[0:body.__len__() - 1] + ']'
path = self.root_path + 'query/'
response = self.processPost(path, body)
status = []
for o in json.loads(response):
errors = o.get("errors", None)
es = o.get('external_system', o.get('external_system_id', o.get('external_system_url', 'not_provided')))
s = o.get('subject_id', 'not_provided')
if s == 'not_provided':
s_org = o.get('subject_org', None)
s_org_id = o.get('subject_org_id', None)
if s_org and s_org_id:
s = {
'subject_org': o.get('subject_org'),
'subject_org_id': o.get('subject_org_id')
}
path = o.get('path', 'not_provided')
if errors:
status.append({
"external_system": es,
"path": path,
"subject": s,
"success": False,
"errors": errors})
else:
ers = o.get('external_record')
era = []
for er in ers:
era.append(ExternalRecord.identity_from_jsonObject(er))
status.append({
"external_system": es,
"path": path,
"subject": s,
"success": True,
ExternalRecord.identityLabel: era})
return status
def __processAfterQueryOnKwargs(self, f_found, f_notfound, **kwargs):
subject_id = kwargs.pop('subject_id', None)
subject_org = kwargs.pop('subject_org', None)
subject_org_id = kwargs.pop('subject_org_id', None)
es_id = kwargs.pop('external_system_id', None)
es_name = kwargs.pop('external_system_name', None)
es_url = kwargs.pop('external_system_url', None)
path = kwargs.pop('path', None)
label_id = kwargs.pop('label_id', None)
qdict = {}
subfound = False
esfound = False
pathFound = False
if subject_id:
qdict['subject_id'] = subject_id
subfound = True
if subject_org and subject_org_id:
qdict['subject_org'] = subject_org
qdict['subject_org_id'] = subject_org_id
subfound = True
if es_id:
qdict['external_system_id'] = es_id
esfound = True
if es_name:
qdict['external_system_name'] = es_name
esfound = True
if es_url:
qdict['external_system_url'] = es_url
esfound = True
if path:
qdict['path'] = path
pathFound = True
if label_id:
qdict['label_id'] = label_id
if esfound or subfound or pathFound:
return f_found(self.query(qdict), qdict)
else:
return f_notfound(qdict)
def get(self, **kwargs):
'''Attempts to locate the external record or its links in the ehb-service database:
Inputs:
id = integer value of the externalRecord record id in the ehb-service
links = boolean value to request the links to a record rather than the record itself.
OR any combination of Subject, ExternalSystem and path. In this case it is not possible to
guarantee a single value in the response.
It is not necessary to specify all 3, but at least 1 must be provided.
-The allowed ExternalSystem identifiers are:
external_system_id = integer value of the external_system id
OR
external_system_name = string value of the external_systyem name
OR
external_system_url = string value of external_system URL
-The allowed Subject identifiers are:
subject_id = integer value of the ehb subject id
OR
subject_org = int value of the eHB Organization record id for this subject
subject_org_id = string value of the organization_subject_id for this Subject
-The allowed path identifier is path
Output:
A list of ExternalRecord objects'''
rid = kwargs.pop('id', None)
links = kwargs.pop('links', False)
if rid:
path = self.root_path + 'id/' + str(rid) + '/'
if links:
path += 'links/'
r = self.processGet(path)
return json.loads(r)
return ExternalRecord.identity_from_json(self.processGet(path))
else:
def onProperKw(query_response, qdict):
response = query_response[0]
if response.get('success'):
return response.get(ExternalRecord.identityLabel)
else:
msg = self.root_path + ', for get by ' + str(qdict)
raise PageNotFound(msg)
def onImproperKw(qdict):
msg = 'external_system_id OR external_system_name AND subject_id OR subject_org AND subject_org_id'
raise InvalidArguments(msg)
return self.__processAfterQueryOnKwargs(onProperKw, onImproperKw, **kwargs)
def delete(self, **kwargs):
'''Attempts to delete the external record in the ehb-service database:
Inputs:
id = integer value of the externalRecord record id in the ehb-service
OR any combination of Subject, ExternalSystem and path.
It is not necessary to specify all 3, but at least 1 must be provided.
-The allowed ExternalSystem identifiers are:
external_system_id = integer value of the external_system id
OR
external_system_name = string value of the external_systyem name
OR
external_system_url = string value of external_system URL
-The allowed Subject identifiers are:
subject_id = integer value of the subject id
OR
subject_org = int value of the eHB Organization record id for this subject
subject_org_id = string value of the organization_subject_id for this Subject
-The allowed path identifier is path
**WARNING**: If multiple externalRecords are found for the specified values they will all be deleted.
If this is not the desired behavior it is recommended to only allow deleting by id'''
id = kwargs.pop('id', None)
if id:
path = self.root_path + 'id/' + str(id) + '/'
return self.processDelete(path)
else:
def onProperKw(query_response, qdict):
response = query_response[0]
if response.get('success'):
for er in response.get(ExternalRecord.identityLabel):
id = er.id
path = self.root_path + 'id/' + str(id) + '/'
self.processDelete(path)
else:
msg = self.root_path + ', for delete external_record by ' + str(qdict)
raise PageNotFound(msg)
def onImproperKw(qdict):
msg = 'external_system_id OR external_system_name AND subject_id OR subject_mrn'
raise InvalidArguments(msg)
return self.__processAfterQueryOnKwargs(onProperKw, onImproperKw, **kwargs)
def create(self, *externalRecords):
'''Given an arbitrary number of ExternalRecord objects, this method attempts to create the externalRecords
in the server database.'''
def onSuccess(er, o):
er.id = int(o.get('id'))
er.created = RequestBase.dateTimeFromJsonString(o.get('created'))
er.modified = RequestBase.dateTimeFromJsonString(o.get('modified'))
return self.standardCreate(ExternalRecord, onSuccess, *externalRecords)
def link(self, externalRecord, relatedRecord, linkType):
'''Given one ExternalRecord, link another ExternalRecord to it
'''
path = self.root_path + 'id/' + str(externalRecord.id) + '/links/'
body = {
"related_record": relatedRecord.id,
"relation_type": linkType
}
return json.loads(self.processPost(path, json.dumps(body)))
def unlink(self, externalRecord, linkId):
'''Given one ExternalRecord and its link ID, remove the link to the relatedRecord
'''
path = self.root_path + 'id/' + str(externalRecord.id) + '/links/' + str(linkId) + '/'
return json.loads(self.processDelete(path))
def update(self, *externalRecords):
'''Given an arbitrary number of ExternalRecord objects, this method attempts to update the externalrecords in the
server database. NOTE: It is NOT possible to update the ExternalRecord database id or created fields using this
method. The modified value will automatically be updated in the provided externalrecord objects'''
def onSuccess(er, o):
er.modified = RequestBase.dateTimeFromJsonString(o.get('modified'))
return self.standardUpdate(ExternalRecord, onSuccess, *externalRecords)
class ExternalRecordLabelRequestHandler(JsonRequestBase):
def __init__(self, host, root_path='', secure=False, api_key=None):
RequestBase.__init__(self, host, '{0}/api/externalrecord/'.format(root_path), secure, api_key)
self.root_path = root_path
def create(*args, **kwargs):
| |
Constraint(expr= m.b224 - m.b225 <= 0)
m.c545 = Constraint(expr= m.b226 - m.b227 <= 0)
m.c546 = Constraint(expr= m.b228 - m.b229 <= 0)
m.c547 = Constraint(expr= m.b232 - m.b233 <= 0)
m.c548 = Constraint(expr= m.b234 - m.b235 <= 0)
m.c549 = Constraint(expr= m.b236 - m.b237 <= 0)
m.c550 = Constraint(expr= - m.b239 + m.b240 <= 0)
m.c551 = Constraint(expr= - m.b238 + m.b241 <= 0)
m.c552 = Constraint(expr= - m.b239 + m.b242 <= 0)
m.c553 = Constraint(expr= - m.b238 + m.b243 <= 0)
m.c554 = Constraint(expr= - m.b239 + m.b244 <= 0)
m.c555 = Constraint(expr= - m.b238 + m.b245 <= 0)
m.c556 = Constraint(expr= - m.b247 + m.b248 <= 0)
m.c557 = Constraint(expr= - m.b246 + m.b249 <= 0)
m.c558 = Constraint(expr= - m.b247 + m.b250 <= 0)
m.c559 = Constraint(expr= - m.b246 + m.b251 <= 0)
m.c560 = Constraint(expr= - m.b247 + m.b252 <= 0)
m.c561 = Constraint(expr= - m.b246 + m.b253 <= 0)
m.c562 = Constraint(expr= - m.b255 + m.b256 <= 0)
m.c563 = Constraint(expr= - m.b254 + m.b257 <= 0)
m.c564 = Constraint(expr= - m.b255 + m.b258 <= 0)
m.c565 = Constraint(expr= - m.b254 + m.b259 <= 0)
m.c566 = Constraint(expr= - m.b255 + m.b260 <= 0)
m.c567 = Constraint(expr= - m.b254 + m.b261 <= 0)
m.c568 = Constraint(expr= - m.b263 + m.b264 <= 0)
m.c569 = Constraint(expr= - m.b262 + m.b265 <= 0)
m.c570 = Constraint(expr= - m.b263 + m.b266 <= 0)
m.c571 = Constraint(expr= - m.b262 + m.b267 <= 0)
m.c572 = Constraint(expr= - m.b263 + m.b268 <= 0)
m.c573 = Constraint(expr= - m.b262 + m.b269 <= 0)
m.c574 = Constraint(expr= - m.b271 + m.b272 <= 0)
m.c575 = Constraint(expr= - m.b270 + m.b273 <= 0)
m.c576 = Constraint(expr= - m.b271 + m.b274 <= 0)
m.c577 = Constraint(expr= - m.b270 + m.b275 <= 0)
m.c578 = Constraint(expr= - m.b271 + m.b276 <= 0)
m.c579 = Constraint(expr= - m.b270 + m.b277 <= 0)
m.c580 = Constraint(expr= - m.b279 + m.b280 <= 0)
m.c581 = Constraint(expr= - m.b278 + m.b281 <= 0)
m.c582 = Constraint(expr= - m.b279 + m.b282 <= 0)
m.c583 = Constraint(expr= - m.b278 + m.b283 <= 0)
m.c584 = Constraint(expr= - m.b279 + m.b284 <= 0)
m.c585 = Constraint(expr= - m.b278 + m.b285 <= 0)
m.c586 = Constraint(expr= - m.b287 + m.b288 <= 0)
m.c587 = Constraint(expr= - m.b286 + m.b289 <= 0)
m.c588 = Constraint(expr= - m.b287 + m.b290 <= 0)
m.c589 = Constraint(expr= - m.b286 + m.b291 <= 0)
m.c590 = Constraint(expr= - m.b287 + m.b292 <= 0)
m.c591 = Constraint(expr= - m.b286 + m.b293 <= 0)
m.c592 = Constraint(expr= - m.b295 + m.b296 <= 0)
m.c593 = Constraint(expr= - m.b294 + m.b297 <= 0)
m.c594 = Constraint(expr= - m.b295 + m.b298 <= 0)
m.c595 = Constraint(expr= - m.b294 + m.b299 <= 0)
m.c596 = Constraint(expr= - m.b295 + m.b300 <= 0)
m.c597 = Constraint(expr= - m.b294 + m.b301 <= 0)
m.c598 = Constraint(expr= m.b174 - m.b238 <= 0)
m.c599 = Constraint(expr= m.b175 - m.b239 <= 0)
m.c600 = Constraint(expr= m.b182 - m.b246 <= 0)
m.c601 = Constraint(expr= m.b183 - m.b247 <= 0)
m.c602 = Constraint(expr= m.b190 - m.b254 <= 0)
m.c603 = Constraint(expr= m.b191 - m.b255 <= 0)
m.c604 = Constraint(expr= m.b198 - m.b262 <= 0)
m.c605 = Constraint(expr= m.b199 - m.b263 <= 0)
m.c606 = Constraint(expr= m.b206 - m.b270 <= 0)
m.c607 = Constraint(expr= m.b207 - m.b271 <= 0)
m.c608 = Constraint(expr= m.b214 - m.b278 <= 0)
m.c609 = Constraint(expr= m.b215 - m.b279 <= 0)
m.c610 = Constraint(expr= m.b222 - m.b286 <= 0)
m.c611 = Constraint(expr= m.b223 - m.b287 <= 0)
m.c612 = Constraint(expr= m.b230 - m.b294 <= 0)
m.c613 = Constraint(expr= m.b231 - m.b295 <= 0)
m.c614 = Constraint(expr= m.b176 - m.b240 <= 0)
m.c615 = Constraint(expr= - m.b176 + m.b177 - m.b241 <= 0)
m.c616 = Constraint(expr= m.b178 - m.b242 <= 0)
m.c617 = Constraint(expr= - m.b178 + m.b179 - m.b243 <= 0)
m.c618 = Constraint(expr= m.b180 - m.b244 <= 0)
m.c619 = Constraint(expr= - m.b180 + m.b181 - m.b245 <= 0)
m.c620 = Constraint(expr= m.b184 - m.b248 <= 0)
m.c621 = Constraint(expr= - m.b184 + m.b185 - m.b249 <= 0)
m.c622 = Constraint(expr= m.b186 - m.b250 <= 0)
m.c623 = Constraint(expr= - m.b186 + m.b187 - m.b251 <= 0)
m.c624 = Constraint(expr= m.b188 - m.b252 <= 0)
m.c625 = Constraint(expr= - m.b188 + m.b189 - m.b253 <= 0)
m.c626 = Constraint(expr= m.b192 - m.b256 <= 0)
m.c627 = Constraint(expr= - m.b192 + m.b193 - m.b257 <= 0)
m.c628 = Constraint(expr= m.b194 - m.b258 <= 0)
m.c629 = Constraint(expr= - m.b194 + m.b195 - m.b259 <= 0)
m.c630 = Constraint(expr= m.b196 - m.b260 <= 0)
m.c631 = Constraint(expr= - m.b196 + m.b197 - m.b261 <= 0)
m.c632 = Constraint(expr= m.b200 - m.b264 <= 0)
m.c633 = Constraint(expr= - m.b200 + m.b201 - m.b265 <= 0)
m.c634 = Constraint(expr= m.b202 - m.b266 <= 0)
m.c635 = Constraint(expr= - m.b202 + m.b203 - m.b267 <= 0)
m.c636 = Constraint(expr= m.b204 - m.b268 <= 0)
m.c637 = Constraint(expr= - m.b204 + m.b205 - m.b269 <= 0)
m.c638 = Constraint(expr= m.b208 - m.b272 <= 0)
m.c639 = Constraint(expr= - m.b208 + m.b209 - m.b273 <= 0)
m.c640 = Constraint(expr= m.b210 - m.b274 <= 0)
m.c641 = Constraint(expr= - m.b210 + m.b211 - m.b275 <= 0)
m.c642 = Constraint(expr= m.b212 - m.b276 <= 0)
m.c643 = Constraint(expr= - m.b212 + m.b213 - m.b277 <= 0)
m.c644 = Constraint(expr= m.b216 - m.b280 <= 0)
m.c645 = Constraint(expr= - m.b216 + m.b217 - m.b281 <= 0)
m.c646 = Constraint(expr= m.b218 - m.b282 <= 0)
m.c647 = Constraint(expr= - m.b218 + m.b219 - m.b283 <= 0)
m.c648 = Constraint(expr= m.b220 - m.b284 <= 0)
m.c649 = Constraint(expr= - m.b220 + m.b221 - m.b285 <= 0)
m.c650 = Constraint(expr= m.b224 - m.b288 <= 0)
m.c651 = Constraint(expr= - m.b224 + m.b225 - m.b289 <= 0)
m.c652 = Constraint(expr= m.b226 - m.b290 <= 0)
m.c653 = Constraint(expr= - m.b226 + m.b227 - m.b291 <= 0)
m.c654 = Constraint(expr= m.b228 - m.b292 <= 0)
m.c655 = Constraint(expr= - m.b228 + m.b229 - m.b293 <= 0)
m.c656 = Constraint(expr= m.b232 - m.b296 <= 0)
m.c657 = Constraint(expr= - m.b232 + m.b233 - m.b297 <= 0)
m.c658 = Constraint(expr= m.b234 - m.b298 <= 0)
m.c659 = Constraint(expr= - m.b234 + m.b235 - m.b299 <= 0)
m.c660 = Constraint(expr= m.b236 - m.b300 <= 0)
m.c661 = Constraint(expr= - m.b236 + m.b237 - m.b301 <= 0)
m.c662 = Constraint(expr= m.x10 - m.x64 - m.x302 == 0)
m.c663 = Constraint(expr= m.x11 - m.x65 - m.x303 == 0)
m.c664 = Constraint(expr= m.x18 - m.x66 - m.x324 == 0)
m.c665 = Constraint(expr= m.x19 - m.x67 - m.x325 == 0)
m.c666 = Constraint(expr= m.x40 - m.x68 - m.x358 == 0)
m.c667 = Constraint(expr= m.x41 - m.x69 - m.x359 == 0)
m.c668 = Constraint(expr= m.x42 - m.x70 - m.x360 == 0)
m.c669 = Constraint(expr= m.x43 - m.x71 - m.x361 == 0)
m.c670 = Constraint(expr= m.x302 - m.x304 - m.x306 == 0)
m.c671 = Constraint(expr= m.x303 - m.x305 - m.x307 == 0)
m.c672 = Constraint(expr= - m.x308 - m.x310 + m.x312 == 0)
m.c673 = Constraint(expr= - m.x309 - m.x311 + m.x313 == 0)
m.c674 = Constraint(expr= m.x312 - m.x314 - m.x316 == 0)
m.c675 = Constraint(expr= m.x313 - m.x315 - m.x317 == 0)
m.c676 = Constraint(expr= m.x316 - m.x318 - m.x320 - m.x322 == 0)
m.c677 = Constraint(expr= m.x317 - m.x319 - m.x321 - m.x323 == 0)
m.c678 = Constraint(expr= m.x326 - m.x332 - m.x334 == 0)
m.c679 = Constraint(expr= m.x327 - m.x333 - m.x335 == 0)
m.c680 = Constraint(expr= m.x330 - m.x336 - m.x338 - m.x340 == 0)
m.c681 = Constraint(expr= m.x331 - m.x337 - m.x339 - m.x341 == 0)
m.c682 = Constraint(expr= m.x346 - m.x354 - m.x356 == 0)
m.c683 = Constraint(expr= m.x347 - m.x355 - m.x357 == 0)
m.c684 = Constraint(expr= - m.x348 - m.x360 + m.x362 == 0)
m.c685 = Constraint(expr= - m.x349 - m.x361 + m.x363 == 0)
m.c686 = Constraint(expr= m.x350 - m.x364 - m.x366 == 0)
m.c687 = Constraint(expr= m.x351 - m.x365 - m.x367 == 0)
m.c688 = Constraint(expr= m.x352 - m.x368 - m.x370 - m.x372 == 0)
m.c689 = Constraint(expr= m.x353 - m.x369 - m.x371 - m.x373 == 0)
m.c690 = Constraint(expr= m.x390 - m.x392 == 0)
m.c691 = Constraint(expr= m.x391 - m.x393 == 0)
m.c692 = Constraint(expr= m.x392 - m.x394 - m.x396 == 0)
m.c693 = Constraint(expr= m.x393 - m.x395 - m.x397 == 0)
m.c694 = Constraint(expr= - m.x398 - m.x400 + m.x402 == 0)
m.c695 = Constraint(expr= - m.x399 - m.x401 + m.x403 == 0)
m.c696 = Constraint(expr= m.x402 - m.x404 - m.x406 == 0)
m.c697 = Constraint(expr= m.x403 - m.x405 - | |
daily_record = dr
, start = '09:00'
, end = '13:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '15:30'
, end = '18:30'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '13:30'
, end = '15:30'
, work_location = '1'
, wp = '40'
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-04')
, weekend_allowed = 0
, required_overtime = 0
)
db.time_record.create \
( daily_record = dr
, start = '14:30'
, end = '16:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '07:45'
, end = '13:30'
, work_location = '1'
, wp = '16'
)
db.time_record.create \
( daily_record = dr
, start = '06:15'
, end = '07:15'
, work_location = '1'
, wp = '40'
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-05')
, weekend_allowed = 0
, required_overtime = 0
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-06')
, weekend_allowed = 0
, required_overtime = 0
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-07')
, weekend_allowed = 0
, required_overtime = 0
)
db.time_record.create \
( daily_record = dr
, start = '15:30'
, end = '17:30'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '12:30'
, end = '13:00'
, work_location = '1'
, wp = '36'
)
db.time_record.create \
( daily_record = dr
, start = '08:15'
, end = '11:00'
, work_location = '1'
, wp = '11'
)
db.time_record.create \
( daily_record = dr
, start = '11:00'
, end = '12:30'
, work_location = '1'
, wp = '40'
)
db.time_record.create \
( daily_record = dr
, start = '13:30'
, end = '14:30'
, work_location = '1'
, wp = '16'
)
db.time_record.create \
( daily_record = dr
, start = '14:30'
, end = '15:30'
, work_location = '1'
, wp = '33'
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-08')
, weekend_allowed = 0
, required_overtime = 0
)
db.time_record.create \
( daily_record = dr
, start = '13:30'
, end = '14:30'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '11:15'
, end = '13:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '08:15'
, end = '10:15'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '10:15'
, end = '11:15'
, work_location = '1'
, wp = '40'
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-09')
, weekend_allowed = 0
, required_overtime = 0
)
db.time_record.create \
( daily_record = dr
, start = '14:30'
, end = '18:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '10:00'
, end = '13:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '08:30'
, end = '09:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '09:00'
, end = '10:00'
, work_location = '1'
, wp = '30'
)
db.time_record.create \
( daily_record = dr
, start = '13:30'
, end = '14:30'
, work_location = '1'
, wp = '31'
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-10')
, weekend_allowed = 0
, required_overtime = 0
)
db.time_record.create \
( daily_record = dr
, start = '14:30'
, end = '18:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '11:45'
, end = '13:00'
, work_location = '5'
, wp = '2'
)
db.time_record.create \
( daily_record = dr
, start = '09:00'
, end = '11:45'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '13:30'
, end = '14:30'
, work_location = '1'
, wp = '40'
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-11')
, weekend_allowed = 0
, required_overtime = 0
)
db.time_record.create \
( daily_record = dr
, start = '16:00'
, end = '16:30'
, work_location = '1'
, wp = '36'
)
db.time_record.create \
( daily_record = dr
, start = '12:15'
, end = '13:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '08:15'
, end = '10:15'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '10:15'
, end = '11:15'
, work_location = '1'
, wp = '11'
)
db.time_record.create \
( daily_record = dr
, start = '13:30'
, end = '16:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '11:15'
, end = '12:15'
, work_location = '1'
, wp = '31'
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-12')
, weekend_allowed = 0
, required_overtime = 0
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-13')
, weekend_allowed = 0
, required_overtime = 0
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-14')
, weekend_allowed = 0
, required_overtime = 0
)
db.time_record.create \
( daily_record = dr
, start = '13:30'
, end = '15:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '12:00'
, end = '13:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '08:15'
, end = '10:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '10:00'
, end = '11:00'
, work_location = '1'
, wp = '5'
)
db.time_record.create \
( daily_record = dr
, start = '11:00'
, end = '12:00'
, work_location = '1'
, wp = '16'
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-15')
, weekend_allowed = 0
, required_overtime = 0
)
db.time_record.create \
( daily_record = dr
, start = '15:00'
, end = '17:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '11:00'
, end = '12:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '07:30'
, end = '09:00'
, work_location = '1'
, wp = '6'
)
db.time_record.create \
( daily_record = dr
, start = '09:00'
, end = '10:00'
, work_location = '1'
, wp = '40'
)
db.time_record.create \
( daily_record = dr
, start = '12:30'
, end = '13:30'
, work_location = '5'
, wp = '2'
)
db.time_record.create \
( daily_record = dr
, start = '10:00'
, end = '11:00'
, work_location = '1'
, wp = '5'
)
db.time_record.create \
( daily_record = dr
, start = '13:30'
, end = '15:00'
, work_location = '1'
, wp = '11'
)
dr = db.daily_record.create \
( user = user
, date = date.Date ('2014-07-16')
, weekend_allowed = 0
, required_overtime = 0
)
db.time_record.create \
( daily_record = dr
, start | |
<reponame>stachu86/dcase_util<gh_stars>100-1000
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import
import collections
import hashlib
import os
import pickle
import sys
import numpy
import yaml
from six import iteritems
from dcase_util.datasets import SoundDataset, AcousticSceneDataset, SyntheticSoundEventDataset, SoundEventDataset, AudioVisualSceneDataset
from dcase_util.containers import MetaDataContainer, MetaDataItem, OneToOneMappingContainer, \
DictContainer, ParameterContainer, AudioContainer
from dcase_util.utils import Path, FileFormat, is_jupyter
# Datasets released by Tampere University (TAU), formerly known as Tampere University of Technology (TUT).
# =====================================================
# DCASE 2021
# =====================================================
class TAUUrbanAudioVisualScenes_2021_DevelopmentSet(AudioVisualSceneDataset):
"""TAU Urban Audio-Visual Scenes 2021 Development dataset
This dataset is used in DCASE2021 - Task 1, Acoustic scene classification / Subtask B / Development
"""
def __init__(self,
storage_name='TAU-urban-audio-visual-scenes-2021-development',
data_path=None,
included_content_types=None,
**kwargs):
"""
Constructor
Parameters
----------
storage_name : str
Name to be used when storing dataset on disk
Default value 'TAU-urban-audio-visual-scenes-2021-development'
data_path : str
Root path where the dataset is stored. If None, os.path.join(tempfile.gettempdir(), 'dcase_util_datasets')
is used.
Default value None
included_content_types : list of str or str
Indicates what content type should be processed. One or multiple from ['all', 'audio', 'video', 'features',
'meta', 'code', 'documentation', 'examples']. If None given, ['all'] is used. Parameter can be also
comma separated string.
Default value None
"""
kwargs['included_content_types'] = included_content_types
kwargs['data_path'] = data_path
kwargs['storage_name'] = storage_name
kwargs['dataset_group'] = 'scene'
kwargs['dataset_meta'] = {
'authors': '<NAME>, <NAME>, and <NAME>',
'title': 'TAU Urban Audio-Visual Scenes 2021, development dataset',
'url': None,
'audio_source': 'Field recording',
'audio_type': 'Natural',
'video_source': 'Field recording',
'video_type': 'Natural',
'audio_recording_device_model': 'Zoom F8',
'video_recording_device_model': 'GoPro Hero5 Session',
'microphone_model': 'Various',
'licence': 'free non-commercial'
}
kwargs['crossvalidation_folds'] = 1
kwargs['evaluation_setup_file_extension'] = 'csv'
kwargs['meta_filename'] = 'meta.csv'
filename_base = 'TAU-urban-audio-visual-scenes-2021-development'
source_url = 'https://zenodo.org/record/4477542/files/'
kwargs['package_list'] = []
kwargs['package_list'] = [
{
'content_type': 'documentation',
'remote_file': source_url + filename_base + '.doc.zip',
'remote_bytes': 12466,
'remote_md5': '26960140f453d31bbd315ed7e35675f8',
'filename': filename_base + '.doc.zip'
},
{
'content_type': 'meta',
'remote_file': source_url + filename_base + '.meta.zip',
'remote_bytes': 235316,
'remote_md5': '76e3d7ed5291b118372e06379cb2b490',
'filename': filename_base + '.meta.zip'
},
{
'content_type': 'examples',
'remote_file': source_url + filename_base + '.examples.zip',
'remote_bytes': 128196071,
'remote_md5': '27aca1ec51f856f59604cf22e93ebf80',
'filename': filename_base + '.examples.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.1.zip',
'remote_bytes': 4349202707,
'remote_md5': '186f6273f8f69ed9dbdc18ad65ac234f',
'filename': filename_base + '.audio.1.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.2.zip',
'remote_bytes': 4490960726,
'remote_md5': '7fd6bb63127f5785874a55aba4e77aa5',
'filename': filename_base + '.audio.2.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.3.zip',
'remote_bytes': 4223486056,
'remote_md5': '61396bede29d7c8c89729a01a6f6b2e2',
'filename': filename_base + '.audio.3.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.4.zip',
'remote_bytes': 4172854493,
'remote_md5': '6ddac89717fcf9c92c451868eed77fe1',
'filename': filename_base + '.audio.4.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.5.zip',
'remote_bytes': 4185568337,
'remote_md5': 'af4820756cdf1a7d4bd6037dc034d384',
'filename': filename_base + '.audio.5.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.6.zip',
'remote_bytes': 4215402064,
'remote_md5': 'ebd11ec24411f2a17a64723bd4aa7fff',
'filename': filename_base + '.audio.6.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.7.zip',
'remote_bytes': 4407222915,
'remote_md5': '2be39a76aeed704d5929d020a2909efd',
'filename': filename_base + '.audio.7.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.8.zip',
'remote_bytes': 345864456,
'remote_md5': '972d8afe0874720fc2f28086e7cb22a9',
'filename': filename_base + '.audio.8.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.1.zip',
'remote_bytes': 4996891312,
'remote_md5': 'f89b88f6ff44b109e842bff063612bf1',
'filename': filename_base + '.video.1.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.2.zip',
'remote_bytes': 4997056221,
'remote_md5': '433053f76ae028f6c4a86094b91af69c',
'filename': filename_base + '.video.2.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.3.zip',
'remote_bytes': 4995965420,
'remote_md5': '974c8e4f3741e065e5c2775f4b9e3ffc',
'filename': filename_base + '.video.3.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.4.zip',
'remote_bytes': 4991033216,
'remote_md5': 'b558fe62fb8fd9b1864d256ead8a24d1',
'filename': filename_base + '.video.4.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.5.zip',
'remote_bytes': 4997081324,
'remote_md5': 'fb3036c31e66be1caddb48834e0ea304',
'filename': filename_base + '.video.5.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.6.zip',
'remote_bytes': 4991170406,
'remote_md5': '140f331750406eaa16756b5cfdf0a336',
'filename': filename_base + '.video.6.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.7.zip',
'remote_bytes': 4996594150,
'remote_md5': 'bac47d3da9bffb89318e662c6af68539',
'filename': filename_base + '.video.7.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.8.zip',
'remote_bytes': 4992534816,
'remote_md5': '95c231ee549c6e74ab8b57a27047ff71',
'filename': filename_base + '.video.8.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.9.zip',
'remote_bytes': 4998329385,
'remote_md5': '294daf6f7de15adcae3a97a8d176eb3a',
'filename': filename_base + '.video.9.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.10.zip',
'remote_bytes': 4993017199,
'remote_md5': 'c6778f4ddbab163394f7cd26011f1452',
'filename': filename_base + '.video.10.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.11.zip',
'remote_bytes': 4993425875,
'remote_md5': '856ecd8fb1df96adcd2cc6928441bbe6',
'filename': filename_base + '.video.11.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.12.zip',
'remote_bytes': 4994719640,
'remote_md5': '57b898b19d991fde6df595fda85eb28d',
'filename': filename_base + '.video.12.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.13.zip',
'remote_bytes': 4996976020,
'remote_md5': '920562ed29a63abeabfb11b6c0a17a2c',
'filename': filename_base + '.video.13.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.14.zip',
'remote_bytes': 4999888160,
'remote_md5': '1febab0738a622dea95926e70d2fc7c4',
'filename': filename_base + '.video.14.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.15.zip',
'remote_bytes': 4995886583,
'remote_md5': 'd6d57cc85f65b1a589a1d628ca936fc9',
'filename': filename_base + '.video.15.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.16.zip',
'remote_bytes': 2286205594,
'remote_md5': '4e1ab47f0d180b818491ef3c3f45ebc6',
'filename': filename_base + '.video.16.zip'
},
]
kwargs['audio_paths'] = [
'audio'
]
kwargs['video_paths'] = [
'video'
]
super(TAUUrbanAudioVisualScenes_2021_DevelopmentSet, self).__init__(**kwargs)
self.package_extract_parameters = DictContainer({
'omit_first_level': False
})
def process_meta_item(self, item, absolute_path=True, **kwargs):
"""Process single meta data item
Parameters
----------
item : MetaDataItem
Meta data item
absolute_path : bool
Convert file paths to be absolute
Default value True
"""
if absolute_path:
item.filename = self.relative_to_absolute_path(item.filename)
item.filename_audio = self.relative_to_absolute_path(item.filename_audio)
item.filename_video = self.relative_to_absolute_path(item.filename_video)
else:
item.filename = self.absolute_to_relative_path(item.filename)
item.filename_audio = self.absolute_to_relative_path(item.filename_audio)
item.filename_video = self.absolute_to_relative_path(item.filename_video)
if not item.identifier:
item.identifier = '-'.join(os.path.splitext(os.path.split(item.filename)[-1])[0].split('-')[1:-2])
def prepare(self):
"""Prepare dataset for the usage.
Returns
-------
self
"""
if not self.meta_container.exists():
meta_data = collections.OrderedDict()
for fold in self.folds():
# Read train files in
fold_data = MetaDataContainer(
filename=self.evaluation_setup_filename(
setup_part='train',
fold=fold
)
).load()
# Read eval files in
fold_data += MetaDataContainer(
filename=self.evaluation_setup_filename(
setup_part='evaluate',
fold=fold
)
).load()
# Process, make sure each file is included only once.
for item in fold_data:
if item.filename not in meta_data:
self.process_meta_item(
item=item,
absolute_path=False
)
meta_data[item.filename] = item
# Save meta
MetaDataContainer(list(meta_data.values())).save(
filename=self.meta_file
)
# Load meta and cross validation
self.load()
return self
class TAUUrbanAudioVisualScenes_2021_EvaluationSet(AudioVisualSceneDataset):
"""TAU Urban Audio-Visual Scenes 2021 Evaluation dataset
This dataset is used in DCASE2021 - Task 1, Acoustic scene classification / Subtask B / Evaluation
"""
def __init__(self,
storage_name='TAU-urban-audio-visual-scenes-2021-evaluation',
data_path=None,
included_content_types=None,
**kwargs):
"""
Constructor
Parameters
----------
storage_name : str
Name to be used when storing dataset on disk
Default value 'TAU-urban-audio-visual-scenes-2021-evaluation'
data_path : str
Root path where the dataset is stored. If None, os.path.join(tempfile.gettempdir(), 'dcase_util_datasets')
is used.
Default value None
included_content_types : list of str or str
Indicates what content type should be processed. One or multiple from ['all', 'audio', 'video', 'features',
'meta', 'code', 'documentation', 'examples']. If None given, ['all'] is used. Parameter can be also
comma separated string.
Default value None
"""
kwargs['included_content_types'] = included_content_types
kwargs['data_path'] = data_path
kwargs['storage_name'] = storage_name
kwargs['dataset_group'] = 'scene'
kwargs['dataset_meta'] = {
'authors': '<NAME>, <NAME>, and <NAME>',
'title': 'TAU Urban Audio-Visual Scenes 2021, evaluation dataset',
'url': None,
'audio_source': 'Field recording',
'audio_type': 'Natural',
'video_source': 'Field recording',
'video_type': 'Natural',
'audio_recording_device_model': 'Zoom F8',
'video_recording_device_model': 'GoPro Hero5 Session',
'microphone_model': 'Various',
'licence': 'free non-commercial'
}
kwargs['reference_data_present'] = False
kwargs['crossvalidation_folds'] = 1
kwargs['evaluation_setup_file_extension'] = 'csv'
kwargs['meta_filename'] = 'meta.csv'
filename_base = 'TAU-urban-audio-visual-scenes-2021-evaluation'
source_url = 'https://zenodo.org/record/4767103/files/'
kwargs['package_list'] = []
kwargs['package_list'] = [
{
'content_type': 'documentation',
'remote_file': source_url + filename_base + '.doc.zip',
'remote_bytes': 6203,
'remote_md5': 'd06aadc86e63010ae02d8b7ab8ec5ee8',
'filename': filename_base + '.doc.zip'
},
{
'content_type': 'meta',
'remote_file': source_url + filename_base + '.meta.zip',
'remote_bytes': 347743,
'remote_md5': '53b513214059d272ae1441d8fd427f10',
'filename': filename_base + '.meta.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.1.zip',
'remote_bytes': 4310710828,
'remote_md5': '6ea9c6f8e6995716cc2d453caa9e8a78',
'filename': filename_base + '.audio.1.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.2.zip',
'remote_bytes': 4312972013,
'remote_md5': 'd68fe751f772da8f1d43b47a452e1df6',
'filename': filename_base + '.audio.2.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.3.zip',
'remote_bytes': 4312718628,
'remote_md5': '9c22dfb7453412990786efac3820af31',
'filename': filename_base + '.audio.3.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.4.zip',
'remote_bytes': 4310825192,
'remote_md5': '6fc7339060dce0a6cd922199a0024bb0',
'filename': filename_base + '.audio.4.zip'
},
{
'content_type': 'audio',
'remote_file': source_url + filename_base + '.audio.5.zip',
'remote_bytes': 637362159,
'remote_md5': '69af0bf61d0001e9a17d162b89cde99b',
'filename': filename_base + '.audio.5.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.1.zip',
'remote_bytes': 4997118112,
'remote_md5': '01c5401aaba7a3d8fcf9f648ba970fde',
'filename': filename_base + '.video.1.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.2.zip',
'remote_bytes': 4996463273,
'remote_md5': '853a3d22a90d654865e35de46028b819',
'filename': filename_base + '.video.2.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.3.zip',
'remote_bytes': 4996976890,
'remote_md5': '5d50efe515eb25b5aae82b472a6bfac6',
'filename': filename_base + '.video.3.zip'
},
{
'content_type': 'video',
'remote_file': source_url + filename_base + '.video.4.zip',
'remote_bytes': 4997033752,
'remote_md5': | |
to the amount of carbon that is naturally needed in the environment for processes like photosynthesis.
As humans we must remember that trees take years to grow so if we carelessly use wood, it may not always be a resource immediately available for use. When someone in Alberta cuts down a tree to burn it for energy, it is said that one tree must be planted to replace it. Humans across Canada work to replace trees at the rate in which we use them making biomass a renewable source.
##### Biomass Fun Facts!
1) If you’ve ever been near a campfire or a fireplace, you’ve witnessed biomass energy through the burning of wood.
2) Biomass has been around since the beginning of time when man burned wood for heating and cooking.
3) Wood was the biggest energy provider in the world in the 1800’s.
4) Garbage can be burned to generate energy as well. This not only makes use of trash for energy, but reduces the amount of trash that goes into landfills. This process is called Waste-to-Energy.
## Wind Energy
Wind is a newer source of energy. The use of wind for energy production, mainly electricity, has only been developed recently. Most wind power is converted to electricity by using giant machines called wind turbines. Wind is a natural resource that will never run out making wind a renewable resource. Wind that occurs naturally moves the turbines. The turbines power a generator. A generator is a device that converts mechanical energy to electrical energy. In this case the mechanical energy is the movement of the turbines created by the wind. This mechanical energy is changed into electrical energy that can be used in a home.
Did you know that Alberta has a wind energy capacity of 1,483 megawatts. Alberta's wind farms produce enough electricity each year to power 625,000 homes, which is 8 percent of Alberta's electricity demand.
<img src="https://i.gifer.com/so8.gif" style="margin: 0 auto; width: 1000px;">
#### Source Image: #Wind, n.d. Retrieved from https://gifer.com/en/so8
## Water Energy
The correct term for water energy is hydropower. Hydro means water. The first use of water for energy dates back to around 4000 B.C. They used a water wheel during Roman times to water crop and supply drinking water to villages. Now, water creates energy in hydro-dams. A hydro-dam produces electricity when water pushes a device called a turbine. This turbine spins a generator which converts mechanical energy into electrical energy. In this case the mechanical energy that occurs is when the water pushes the turbine. Water is considered a resource that will never run out. It is plentiful and is replenished every time it rains.
<img src="http://www.wvic.com/images/stories/Hydroplants/hydroplant-animate.gif" style="margin: 0 auto; width: 1000px;">
#### Source Image: Wisconsin Valley Improvement Company, n.d. Retrieved from http://www.wvic.com/content/how_hydropower_works.cfm
## Nuclear Energy
Nuclear energy uses the power of an atom to create steam power. Atoms can create energy in two different ways: nuclear fission which is when the inside of an atom is split or nuclear fusion which is done by fusing the inside of two atoms.
The energy produced by the Sun, for example, comes from nuclear fusion reactions. Hydrogen gas in the core of the Sun is squeezed together so tightly that four hydrogen particles combine to form one helium atom. This is called nuclear fusion. When one of these two physical reactions occurs (nuclear fission or nuclear fusion) the atoms experience a slight loss of mass. The mass that is lost becomes a large amount of heat energy and light. This is why the sun is so hot and shines brightly. Did you know that <NAME> discovered his famous equation, E = mc2, with the sun and stars in mind? In his equation, Einstein invented a way to show that "Energy equals mass times the speed of light squared."
The heat generated in nuclear fusion and nuclear fission is used to heat up water and produce steam, which is then used to create electricity. The separation and joining of atoms occurs safely within the walls of a nuclear power station. Nuclear power generates nuclear waste that can be dangerous to human health and the environment.
from IPython.display import YouTubeVideo
YouTubeVideo('igf96TS3Els', width=800, height=300)
#### Source Video: Nuclear Power Station, July 2008. Retrieved from https://www.youtube.com/watch?v=igf96TS3Els
## Geothermal Energy
Geothermal energy is generated by the high temperature of earth's core heating water into steam. The term 'geo' means earth and the word 'thermal' means heat, which means geothermal is 'heat from the earth.' Geothermal energy plants convert large amounts of steam (kinetic energy) into usable electricity. Geothermal energy plants are located in prime areas. Canada does not have any commercial geothermal energy plants.
Note, there exists a device called a geothermal heat pump that can tap into geothermal energy to heat and cool buildings. A geothermal heat pump system consists of a heat pump, an air delivery system (ductwork), and a heat exchanger-a system of pipes buried in the shallow ground near the building. In the summer, the heat pump moves heat from the indoor air into the heat exchanger. In the winter, the heat pump removes heat from the heat exchanger and pumps it into the indoor air delivery system.
Why is geothermal energy a renewable resource? Because the source of geothermal energy is the unlimited amount of heat generated by the Earth's core. It is important to recognize geothermal energy systems DO NOT get their heat directly from the core. Instead, they pull heat from the crust—the rocky upper 20 miles of the planet's surface.
from IPython.display import YouTubeVideo
YouTubeVideo('y_ZGBhy48YI', width=800, height=300)
#### Source Video: Energy 101: Geothermal Heat Pumps, Jan. 2011.
## Renewable Energy Sources vs. Non-renewable
Renewable energy sources are energy sources that can be replaced at the same rate they are used. The source is plentiful and generally quite efficient. An example of a renewable energy source is wind. Wind is a renewable energy source because there is a limitless supply that is naturally produced.
Non-renewable energy sources are those that run out more quickly than they are naturally reproduced. Usually these energy sources take millions of year to produce and they have a bigger negative impact on the earth compared to alternate sources. An example of a non-renewable energy source is oil. Oil is non-renewable because humans are using it faster than it is being replaced naturally on earth.
In order to get comfortable with the two types of Energy Sources, try identifying the renewable energy sources from the non-renewable in the activity below.
%%html
<!-- Question 1 -->
<div>
<!-- Is Solar Energy a Renewable Energy Source? <p> tag below -->
<p>Is Solar Energy a Renewable Energy Source?</p>
<ul style="list-style-type: none">
<li>
<!-- Each <li> tag is a list item to represent a possible Answer
q1c1 stands for "question 1 choice 1", question 2 choice 3 would be
q2c3 for example. You can change this convention if you want its just
what I chose. Make sure all answers for a question have the same
name attribute, in this case q1. This makes it so only a single
radio button can be selected at one time-->
<input type="radio" name="q1" id="q1c1" value="right">
<label for="q1c1">Yes, it is Renewable.</label>
</li>
<li>
<input type="radio" name="q1" id="q1c2" value="wrong">
<label for="q1c2">No, it is a Non-Renewable Energy Source.</label>
</li>
</ul>
<!-- Give a unique id for the button, i chose q1Btn. Question 2 I
I would choose q2Btn and so on. This is used to tell the script
which question we are interested in. -->
<button id="q1Btn">Submit</button>
<!-- this is where the user will get feedback once answering the question,
the text that will go in here will be generated inside the script -->
<p id="q1AnswerStatus"></p>
</div>
<!-- Question 2 -->
<div>
<p>Is Oil Energy | |
CloseMenu
def CloseMenu():
_close_menu()
_get_menu = _ScriptMethod(338) # GetMenuItems
_get_menu.restype = _str
_get_menu.argtypes = [_str] # MenuCaption
def GetMenuItems(MenuCaption): # TODO: split items, return list
return _get_menu(MenuCaption)
_get_last_menu = _ScriptMethod(339) # GetLastMenuItems
_get_last_menu.restype = _str
def GetLastMenuItems(): # TODO: split items, return list
return _get_last_menu()
_wait_gump = _ScriptMethod(211) # WaitGumpInt
_wait_gump.argtypes = [_int] # Value
def WaitGump(Value):
_wait_gump(int(Value))
_wait_gump_text_entry = _ScriptMethod(212) # WaitGumpTextEntry
_wait_gump_text_entry.argtypes = [_str] # Value
def WaitTextEntry(Value):
_wait_gump_text_entry(Value)
_auto_text_entry = _ScriptMethod(213) # GumpAutoTextEntry
_auto_text_entry.argtypes = [_int, # TextEntryID
_str] # Value
def GumpAutoTextEntry(TextEntryID, Value):
_auto_text_entry(TextEntryID, Value)
_auto_radiobutton = _ScriptMethod(214) # GumpAutoRadiobutton
_auto_radiobutton.argtypes = [_int, # RadiobuttonID
_int] # Value
def GumpAutoRadiobutton(RadiobuttonID, Value):
_auto_radiobutton(RadiobuttonID, Value)
_auto_checkbox = _ScriptMethod(215) # GumpAutoCheckBox
_auto_checkbox.argtypes = [_int, # CBID
_int] # Value
def GumpAutoCheckBox(CBID, Value):
_auto_checkbox(CBID, Value)
_send_gump_button = _ScriptMethod(216) # NumGumpButton
_send_gump_button.restype = _bool
_send_gump_button.argtypes = [_ushort, # GumpIndex
_int] # Value
def NumGumpButton(GumpIndex, Value):
return _send_gump_button(GumpIndex, Value)
_send_gump_text_entry = _ScriptMethod(217) # NumGumpTextEntry
_send_gump_text_entry.restype = _bool
_send_gump_text_entry.argtypes = [_ushort, # GumpIndex
_int, # TextEntryID
_str] # Value
def NumGumpTextEntry(GumpIndex, TextEntryID, Value):
return _send_gump_text_entry(GumpIndex, TextEntryID, Value)
_send_gump_radiobutton = _ScriptMethod(218) # NumGumpRadiobutton
_send_gump_radiobutton.restype = _bool
_send_gump_radiobutton.argtypes = [_ushort, # GumpIndex
_int, # RadiobuttonID
_int] # Value
def NumGumpRadiobutton(GumpIndex, RadiobuttonID, Value):
return _send_gump_radiobutton(GumpIndex, RadiobuttonID, Value)
_send_gump_checkbox = _ScriptMethod(219) # NumGumpCheckBox
_send_gump_checkbox.restype = _bool
_send_gump_checkbox.argtypes = [_ushort, # GumpIndex
_int, # CBID
_int] # Value
def NumGumpCheckBox(GumpIndex, CBID, Value):
return _send_gump_checkbox(GumpIndex, CBID, Value)
_get_gumps_count = _ScriptMethod(220) # GetGumpsCount
_get_gumps_count.restype = _int
def GetGumpsCount():
return _get_gumps_count()
_close_gump = _ScriptMethod(221) # CloseSimpleGump
_close_gump.argtypes = [_ushort] # GumpIndex
def CloseSimpleGump(GumpIndex):
_close_gump(GumpIndex)
def IsGump():
return GetGumpsCount() > 0
_get_gump_serial = _ScriptMethod(222) # GetGumpSerial
_get_gump_serial.restype = _uint
_get_gump_serial.argtypes = [_ushort] # GumpIndex
def GetGumpSerial(GumpIndex):
return _get_gump_serial(GumpIndex)
_get_gump_type = _ScriptMethod(223) # GetGumpID
_get_gump_type.restype = _uint
_get_gump_type.argtypes = [_ushort] # GumpIndex
def GetGumpID(GumpIndex):
return _get_gump_type(GumpIndex)
_get_gump_no_close = _ScriptMethod(224) # GetGumpNoClose
_get_gump_no_close.restype = _bool
_get_gump_no_close.argtypes = [_ushort] # GumpIndex
def IsGumpCanBeClosed(GumpIndex):
return _get_gump_no_close(GumpIndex)
_get_gump_text = _ScriptMethod(225) # GetGumpTextLines
_get_gump_text.restype = _str
_get_gump_text.argtypes = [_ushort] # GumpIndex
def GetGumpTextLines(GumpIndex):
result = _get_gump_text(GumpIndex)
return result.split(_linesep)[:-1] # cause '' was in the end of list
_get_gump_full_lines = _ScriptMethod(226) # GetGumpFullLines
_get_gump_full_lines.restype = _str
_get_gump_full_lines.argtypes = [_ushort] # GumpIndex
def GetGumpFullLines(GumpIndex):
result = _get_gump_full_lines(GumpIndex)
return result.split(_linesep)[:-1] # cause '' was in the end of list
_get_gump_short_lines = _ScriptMethod(227) # GetGumpShortLines
_get_gump_short_lines.restype = _str
_get_gump_short_lines.argtypes = [_ushort] # GumpIndex
def GetGumpShortLines(GumpIndex):
result = _get_gump_short_lines(GumpIndex)
return result.split(_linesep)[:-1] # cause '' was in the end of list
_get_gump_buttons = _ScriptMethod(228) # GetGumpButtonsDescription
_get_gump_buttons.restype = _str
_get_gump_buttons.argtypes = [_ushort] # GumpIndex
def GetGumpButtonsDescription(GumpIndex):
result = _get_gump_buttons(GumpIndex)
return result.split(_linesep)[:-1] # cause '' was in the end of list
_get_gump_info = _ScriptMethod(229) # GetGumpInfo
_get_gump_info.restype = _buffer # TGumpInfo
_get_gump_info.argtypes = [_ushort] # GumpIndex
class _Group:
args = [_int] * 3
container = 'groups'
keys = 'GroupNumber', 'Page', 'ElemNum'
class _EndGroup(_Group):
container = 'EndGroups'
class _GumpButton:
args = [_int] * 9
container = 'GumpButtons'
keys = ('X', 'Y', 'ReleasedID', 'PressedID', 'Quit', 'PageID',
'ReturnValue', 'Page', 'ElemNum')
class _ButtonTileArt:
args = [_int] * 12
container = 'ButtonTileArts'
keys = ('X', 'Y', 'ReleasedID', 'PressedID', 'Quit', 'PageID',
'ReturnValue', 'ArtID', 'Hue', 'ArtX', 'ArtY', 'ElemNum')
class _CheckBox:
args = [_int] * 8
container = 'CheckBoxes'
keys = ('X', 'Y', 'ReleasedID', 'PressedID', 'Status', 'ReturnValue',
'Page', 'ElemNum')
class _ChekerTrans:
args = [_int] * 6
container = 'ChekerTrans'
keys = 'X', 'Y', 'Width', 'Height', 'Page', 'ElemNum'
class _CroppedText:
args = [_int] * 8
container = 'CroppedText'
keys = 'X', 'Y', 'Width', 'Height', 'Color', 'TextID', 'Page', 'ElemNum'
class _GumpPic:
args = [_int] * 6
container = 'GumpPics'
keys = 'X', 'Y', 'ID', 'Hue', 'Page', 'ElemNum'
class _GumpPicTiled:
fmt = '=7i'
args = [_int] * 7
container = 'GumpPicTiled'
keys = 'X', 'Y', 'Width', 'Height', 'GumpID', 'Page', 'ElemNum'
class _Radiobutton:
args = [_int] * 8
container = 'RadioButtons'
keys = ('X', 'Y', 'ReleasedID', 'PressedID', 'Status', 'ReturnValue',
'Page', 'ElemNum')
class _ResizePic:
args = [_int] * 7
container = 'ResizePics'
keys = 'X', 'Y', 'GumpID', 'Width', 'Height', 'Page', 'ElemNum'
class _GumpText:
args = [_int] * 6
container = 'GumpText'
keys = 'X', 'Y', 'Color', 'TextID', 'Page', 'ElemNum'
class _TextEntry:
args = [_int] * 7 + [_str, _int, _int]
container = 'TextEntries'
keys = ('X', 'Y', 'Width', 'Height', 'Color', 'ReturnValue',
'DefaultTextID', 'RealValue', 'Page', 'ElemNum')
class _Text:
args = [_str]
container = 'Text'
keys = None
class _TextEntryLimited:
args = [_int] * 10
container = 'TextEntriesLimited'
keys = ('X', 'Y', 'Width', 'Height', 'Color', 'ReturnValue',
'DefaultTextID', 'Limit', 'Page', 'ElemNum')
class _TilePic:
args = [_int] * 5
container = 'TilePics'
keys = 'X', 'Y', 'ID', 'Page', 'ElemNum'
class _TilePicHue:
args = [_int] * 6
container = 'TilePicHue'
keys = 'X', 'Y', 'ID', 'Color', 'Page', 'ElemNum'
class _Tooltip:
args = [_uint, _str, _int, _int]
container = 'Tooltips'
keys = 'ClilocID', 'Arguments', 'Page', 'ElemNum'
class _HtmlGump:
args = [_int] * 9
container = 'HtmlGump'
keys = ('<KEY> 'Width', 'Height', 'TextID', 'Background', 'Scrollbar',
'Page', 'ElemNum')
class _XmfHtmlGump:
args = [_int] * 4 + [_uint] + [_int] * 4
container = 'XmfHtmlGump'
keys = ('<KEY> 'Width', 'Height', 'ClilocID', 'Background', 'Scrollbar',
'Page', 'ElemNum')
class _XmfHTMLGumpColor:
args = [_int] * 4 + [_uint] + [_int] * 5
container = 'XmfHTMLGumpColor'
keys = ('X', 'Y', 'Width', 'Height', 'ClilocID', 'Background', 'Scrollbar',
'Hue', 'Page', 'ElemNum')
class _XmfHTMLTok:
args = [_int] * 7 + [_uint, _str, _int, _int]
container = 'XmfHTMLTok'
keys = ('<KEY> 'Width', 'Height', 'Background', 'Scrollbar', 'Color',
'ClilocID', 'Arguments', 'Page', 'ElemNum')
class _ItemProperty:
args = [_uint, _int]
container = 'ItemProperties'
keys = 'Prop', 'ElemNum'
class _Gump:
fmt = '=2I2hi4?'
args = [_uint, _uint, _short, _short, _int] + [_bool] * 4
keys = ('Serial', 'GumpID', 'X', 'Y', 'Pages', 'NoMove', 'NoResize',
'NoDispose', 'NoClose')
def GetGumpInfo(GumpIndex):
data = _get_gump_info(GumpIndex)
values = _struct.unpack_from(_Gump.fmt, data, 0)
result = dict(zip(_Gump.keys, values))
offset = _struct.calcsize(_Gump.fmt)
# parse elements
elements = (_Group, _EndGroup, _GumpButton, _ButtonTileArt, _CheckBox,
_ChekerTrans, _CroppedText, _GumpPic, _GumpPicTiled,
_Radiobutton, _ResizePic, _GumpText, _TextEntry, _Text,
_TextEntryLimited, _TilePic, _TilePicHue, _Tooltip,
_HtmlGump, _XmfHtmlGump, _XmfHTMLGumpColor, _XmfHTMLTok,
_ItemProperty)
for cls in elements:
result[cls.container] = []
count = _ushort.from_buffer(data, offset)
offset += count.size
for i in range(count):
values = []
for arg in cls.args:
element = arg.from_buffer(data, offset)
offset += element.size
values.append(element.value)
if cls is _Text:
result[cls.container].append(*[values]) # there is only one element
else:
element = dict(zip(cls.keys, values))
if 'ClilocID' in cls.keys and 'Arguments' in cls.keys: # need to represent clilocs
text = GetClilocByID(element['ClilocID'])
args = element.get('Arguments', '')
args = args.split('@')[1:] or []
for arg in args:
if '~' in text:
if arg.startswith('#'): # another cliloc
arg = GetClilocByID(int(arg.strip('#')))
s = text.index('~')
e = text.index('~', s + 1)
text = text.replace(text[s:e + 1], arg, 1) or arg # TODO: wtf?
element['Arguments'] = text
result[cls.container].append(element)
return result
_ignore_gump_id = _ScriptMethod(230) # AddGumpIgnoreByID
_ignore_gump_id.argtypes = [_uint] # ID
def AddGumpIgnoreByID(ID):
_ignore_gump_id(ID)
_ignore_gump_serial = _ScriptMethod(231) # AddGumpIgnoreBySerial
_ignore_gump_serial.argtypes = [_uint] # Serial
def AddGumpIgnoreBySerial(Serial):
_ignore_gump_serial(Serial)
_gumps_ignore_reset = _ScriptMethod(232) # ClearGumpsIgnore
def ClearGumpsIgnore():
_gumps_ignore_reset()
def RhandLayer():
return 0x01
def LhandLayer():
return 0x02
def ShoesLayer():
return 0x03
def PantsLayer():
return 0x04
def ShirtLayer():
return 0x05
def HatLayer():
return 0x06
def GlovesLayer():
return 0x07
def RingLayer():
return 0x08
def TalismanLayer():
return 0x09
def NeckLayer():
return 0x0A
def HairLayer():
return 0x0B
def WaistLayer():
return 0x0C
def TorsoLayer():
return 0x0D
def BraceLayer():
return 0x0E
def BeardLayer():
return 0x10
def TorsoHLayer():
return 0x11
def EarLayer():
return 0x12
def ArmsLayer():
return 0x13
def CloakLayer():
return 0x14
def BpackLayer():
return 0x15
def RobeLayer():
return 0x16
def EggsLayer():
return 0x17
def LegsLayer():
return 0x18
def HorseLayer():
return 0x19
def RstkLayer():
return 0x1A
def NRstkLayer():
return 0x1B
def SellLayer():
return 0x1C
def BankLayer():
return 0x1D
_get_obj_at_layer = _ScriptMethod(233) # ObjAtLayerEx
_get_obj_at_layer.restype = _uint
_get_obj_at_layer.argtypes = [_ubyte, # LayerType
_uint] # PlayerID
def ObjAtLayerEx(LayerType, PlayerID):
return _get_obj_at_layer(LayerType, PlayerID)
def ObjAtLayer(LayerType):
return ObjAtLayerEx(LayerType, Self())
_get_layer = _ScriptMethod(234) # GetLayer
_get_layer.restype = _ubyte
_get_layer.argtypes = [_uint] # Obj
def GetLayer(Obj):
return _get_layer(Obj)
_wear_item = _ScriptMethod(235) # WearItem
_wear_item.argtypes = [_ubyte, # Layer
_uint] # Obj
def WearItem(Layer, Obj):
if GetPickupedItem() == 0 or Layer == 0 or Self() == 0:
return False
_wear_item(Layer, Obj)
SetPickupedItem(0)
return True
def Disarm():
backpack = Backpack()
tmp = []
for layer in LhandLayer(), RhandLayer():
item = ObjAtLayer(layer)
if item:
tmp.append(MoveItem(item, 1, backpack, 0, 0, 0))
return all(tmp)
def disarm():
return Disarm()
def Equip(Layer, Obj):
if Layer and DragItem(Obj, 1):
return WearItem(Layer, Obj)
return False
def equip(Layer, Obj):
return Equip(Layer, Obj)
def Equipt(Layer, ObjType):
item = FindType(ObjType, Backpack())
if item:
return Equip(Layer, item)
return False
def equipt(Layer, ObjType):
return Equipt(Layer, ObjType)
def UnEquip(Layer):
item = ObjAtLayer(Layer)
if item:
return MoveItem(item, 1, Backpack(), 0, 0, 0)
return False
_get_dress_delay = _ScriptMethod(236) # GetDressSpeed
_get_dress_delay.restype = _ushort
def GetDressSpeed():
return _get_dress_delay()
_set_dress_delay = _ScriptMethod(237) # SetDressSpeed
_set_dress_delay.argtypes = [_ushort] # Value
def SetDressSpeed(Value):
_set_dress_delay(Value)
_get_client_version_int = _ScriptMethod(355) # SCGetClientVersionInt
_get_client_version_int.restype = _int
def GetClientVersionInt():
return _get_client_version_int()
_wearable_layers = (RhandLayer(), LhandLayer(), ShoesLayer(), PantsLayer(),
ShirtLayer(), HatLayer(), GlovesLayer(), RingLayer(),
NeckLayer(), WaistLayer(), TorsoLayer(), BraceLayer(),
TorsoHLayer(), EarLayer(), ArmsLayer(), CloakLayer(),
RobeLayer(), EggsLayer(), LegsLayer())
_unequip_itemsset_macro = _ScriptMethod(356) # SCUnequipItemsSetMacro
def | |
# https://www.dexterindustries.com/BrickPi/
# https://github.com/DexterInd/BrickPi3
#
# Copyright (c) 2016 <NAME>
# Released under the MIT license (http://choosealicense.com/licenses/mit/).
# For more information see https://github.com/DexterInd/BrickPi3/blob/master/LICENSE.md
#
# Python drivers for the BrickPi3
from __future__ import print_function
from __future__ import division
#from builtins import input
import subprocess # for executing system calls
import spidev
FIRMWARE_VERSION_REQUIRED = "1.3.x" # Make sure the top 2 of 3 numbers match
BP_SPI = spidev.SpiDev()
BP_SPI.open(0, 1)
BP_SPI.max_speed_hz = 500000 #1000000 #1300000
BP_SPI.mode = 0b00
BP_SPI.bits_per_word = 8
#BP_SPI.delay_usec = 10
class Enumeration(object):
def __init__(self, names): # or *names, with no .split()
number = 0
for line, name in enumerate(names.split('\n')):
if name.find(",") >= 0:
# strip out the spaces
while(name.find(" ") != -1):
name = name[:name.find(" ")] + name[(name.find(" ") + 1):]
# strip out the commas
while(name.find(",") != -1):
name = name[:name.find(",")] + name[(name.find(",") + 1):]
# if the value was specified
if(name.find("=") != -1):
number = int(float(name[(name.find("=") + 1):]))
name = name[:name.find("=")]
# optionally print to confirm that it's working correctly
#print "%40s has a value of %d" % (name, number)
setattr(self, name, number)
number = number + 1
class FirmwareVersionError(Exception):
"""Exception raised if the BrickPi3 firmware needs to be updated"""
class BrickPi3(object):
PORT_1 = 0
PORT_2 = 1
PORT_3 = 2
PORT_4 = 3
PORT_A = 0
PORT_B = 1
PORT_C = 2
PORT_D = 3
SensorType = [0, 0, 0, 0]
I2CInBytes = [0, 0, 0, 0]
BPSPI_MESSAGE_TYPE = Enumeration("""
NONE,
READ_MANUFACTURER,
READ_NAME,
READ_HARDWARE_VERSION,
READ_FIRMWARE_VERSION,
READ_ID,
SET_LED,
READ_VOLTAGE_3V3,
READ_VOLTAGE_5V,
READ_VOLTAGE_9V,
READ_VOLTAGE_VCC,
SET_SENSOR_TYPE = 20,
SET_SENSOR_1_TYPE = 20,
SET_SENSOR_2_TYPE,
SET_SENSOR_3_TYPE,
SET_SENSOR_4_TYPE,
READ_SENSOR = 24,
READ_SENSOR_1 = 24,
READ_SENSOR_2,
READ_SENSOR_3,
READ_SENSOR_4,
WRITE_MOTOR_SPEED = 28,
WRITE_MOTOR_A_SPEED = 28,
WRITE_MOTOR_B_SPEED,
WRITE_MOTOR_C_SPEED,
WRITE_MOTOR_D_SPEED,
WRITE_MOTOR_POSITION = 32,
WRITE_MOTOR_A_POSITION = 32,
WRITE_MOTOR_B_POSITION,
WRITE_MOTOR_C_POSITION,
WRITE_MOTOR_D_POSITION,
WRITE_MOTOR_POSITION_KP = 36,
WRITE_MOTOR_A_POSITION_KP = 36,
WRITE_MOTOR_B_POSITION_KP,
WRITE_MOTOR_C_POSITION_KP,
WRITE_MOTOR_D_POSITION_KP,
WRITE_MOTOR_POSITION_KD = 40,
WRITE_MOTOR_A_POSITION_KD = 40,
WRITE_MOTOR_B_POSITION_KD,
WRITE_MOTOR_C_POSITION_KD,
WRITE_MOTOR_D_POSITION_KD,
WRITE_MOTOR_DPS = 44,
WRITE_MOTOR_A_DPS = 44,
WRITE_MOTOR_B_DPS,
WRITE_MOTOR_C_DPS,
WRITE_MOTOR_D_DPS,
WRITE_MOTOR_DPS_KP = 48,
WRITE_MOTOR_A_DPS_KP = 48,
WRITE_MOTOR_B_DPS_KP,
WRITE_MOTOR_C_DPS_KP,
WRITE_MOTOR_D_DPS_KP,
WRITE_MOTOR_DPS_KD = 52,
WRITE_MOTOR_A_DPS_KD = 52,
WRITE_MOTOR_B_DPS_KD,
WRITE_MOTOR_C_DPS_KD,
WRITE_MOTOR_D_DPS_KD,
OFFSET_MOTOR_ENCODER = 56,
OFFSET_MOTOR_A_ENCODER = 56,
OFFSET_MOTOR_B_ENCODER,
OFFSET_MOTOR_C_ENCODER,
OFFSET_MOTOR_D_ENCODER,
READ_MOTOR_ENCODER = 60,
READ_MOTOR_A_ENCODER = 60,
READ_MOTOR_B_ENCODER,
READ_MOTOR_C_ENCODER,
READ_MOTOR_D_ENCODER,
I2C_TRANSACT = 64,
I2C_TRANSACT_1 = 64,
I2C_TRANSACT_2,
I2C_TRANSACT_3,
I2C_TRANSACT_4,
WRITE_MOTOR_LIMITS = 68,
WRITE_MOTOR_A_LIMITS = 68,
WRITE_MOTOR_B_LIMITS,
WRITE_MOTOR_C_LIMITS,
WRITE_MOTOR_D_LIMITS,
READ_MOTOR_STATUS = 72,
READ_MOTOR_A_STATUS = 72,
READ_MOTOR_B_STATUS,
READ_MOTOR_C_STATUS,
READ_MOTOR_D_STATUS,
""")
SENSOR_TYPE = Enumeration("""
NONE = 1,
I2C,
CUSTOM,
TOUCH,
NXT_TOUCH,
EV3_TOUCH,
NXT_LIGHT_ON,
NXT_LIGHT_OFF,
NXT_COLOR_RED,
NXT_COLOR_GREEN,
NXT_COLOR_BLUE,
NXT_COLOR_FULL,
NXT_COLOR_OFF,
NXT_ULTRASONIC,
EV3_GYRO_ABS,
EV3_GYRO_DPS,
EV3_GYRO_ABS_DPS,
EV3_COLOR_REFLECTED,
EV3_COLOR_AMBIENT,
EV3_COLOR_COLOR,
EV3_COLOR_RAW_REFLECTED,
EV3_COLOR_COLOR_COMPONENTS,
EV3_ULTRASONIC_CM,
EV3_ULTRASONIC_INCHES,
EV3_ULTRASONIC_LISTEN,
EV3_INFRARED_PROXIMITY,
EV3_INFRARED_SEEK,
EV3_INFRARED_REMOTE,
""")
SENSOR_STATE = Enumeration("""
VALID_DATA,
NOT_CONFIGURED,
CONFIGURING,
NO_DATA,
""")
SENSOR_CUSTOM = Enumeration("""
PIN1_9V,
PIN5_OUT,
PIN5_STATE,
PIN6_OUT,
PIN6_STATE,
PIN1_ADC,
PIN6_ADC,
""")
SENSOR_CUSTOM.PIN1_9V = 0x0002
SENSOR_CUSTOM.PIN5_OUT = 0x0010
SENSOR_CUSTOM.PIN5_STATE = 0x0020
SENSOR_CUSTOM.PIN6_OUT = 0x0100
SENSOR_CUSTOM.PIN6_STATE = 0x0200
SENSOR_CUSTOM.PIN1_ADC = 0x1000
SENSOR_CUSTOM.PIN6_ADC = 0x4000
SENSOR_I2C_SETTINGS = Enumeration("""
MID_CLOCK,
PIN1_9V,
SAME,
ALLOW_STRETCH_ACK,
ALLOW_STRETCH_ANY,
""")
SENSOR_I2C_SETTINGS.MID_CLOCK = 0x01 # Send the clock pulse between reading and writing. Required by the NXT US sensor.
SENSOR_I2C_SETTINGS.PIN1_9V = 0x02 # 9v pullup on pin 1
SENSOR_I2C_SETTINGS.SAME = 0x04 # Keep performing the same transaction e.g. keep polling a sensor
MOTOR_STATUS_FLAG = Enumeration("""
LOW_VOLTAGE_FLOAT,
""")
MOTOR_STATUS_FLAG.LOW_VOLTAGE_FLOAT = 0x01 # If the motors are floating due to low battery voltage
SUCCESS = 0
SPI_ERROR = 1
SENSOR_ERROR = 2
SENSOR_TYPE_ERROR = 3
def __init__(self, addr = 1, detect = True): # Configure for the BrickPi. Optionally set the address (default to 1).
"""
Do any necessary configuration, and optionally detect the BrickPi3
Optionally set the SPI address to something other than 1
"""
# note these two lines were a temporary work-around for older Raspbian For Robots.
subprocess.call('gpio mode 13 ALT0', shell=True) # Make sure the SPI lines are configured for mode ALT0 so that the hardware SPI controller can use them
subprocess.call('gpio mode 14 ALT0', shell=True) # ''
self.SPI_Address = addr
if detect == True:
manufacturer, merr = self.get_manufacturer()
board, berr = self.get_board()
vfw, verr = self.get_version_firmware()
if merr != self.SUCCESS or berr != self.SUCCESS or verr != self.SUCCESS or manufacturer != "Dexter Industries" or board != "BrickPi3":
raise IOError("BrickPi3 not connected")
if vfw.split('.')[0] != FIRMWARE_VERSION_REQUIRED.split('.')[0] or vfw.split('.')[1] != FIRMWARE_VERSION_REQUIRED.split('.')[1]:
raise FirmwareVersionError("BrickPi3 firmware needs to be version %s but is currently version %s" % (FIRMWARE_VERSION_REQUIRED, vfw))
def spi_transfer_array(self, data_out):
"""
Conduct a SPI transaction
Keyword arguments:
data_out -- a list of bytes to send. The length of the list will determine how many bytes are transferred.
Returns a list of the bytes read.
"""
return BP_SPI.xfer2(data_out)
# def spi_read_8(self, MessageType):
# """
# Read an 8-bit value over SPI
#
# Keyword arguments:
# MessageType -- the SPI message type
#
# Returns touple:
# value, error
# """
# outArray = [self.SPI_Address, MessageType, 0, 0, 0]
# reply = self.spi_transfer_array(outArray)
# if(reply[3] == 0xA5):
# return int((reply[4] & 0xFF)), self.SUCCESS
# return 0, self.SPI_ERROR
def spi_write_8(self, MessageType, Value):
"""
Send an 8-bit value over SPI
Keyword arguments:
MessageType -- the SPI message type
Value -- the value to be sent
"""
outArray = [self.SPI_Address, MessageType, (Value & 0xFF)]
self.spi_transfer_array(outArray)
def spi_read_16(self, MessageType):
"""
Read a 16-bit value over SPI
Keyword arguments:
MessageType -- the SPI message type
Returns touple:
value, error
"""
outArray = [self.SPI_Address, MessageType, 0, 0, 0, 0]
reply = self.spi_transfer_array(outArray)
if(reply[3] == 0xA5):
return int((reply[4] << 8) | reply[5]), self.SUCCESS
return 0, self.SPI_ERROR
def spi_write_16(self, MessageType, Value):
"""
Send a 16-bit value over SPI
Keyword arguments:
MessageType -- the SPI message type
Value -- the value to be sent
"""
outArray = [self.SPI_Address, MessageType, ((Value >> 8) & 0xFF), (Value & 0xFF)]
self.spi_transfer_array(outArray)
def spi_write_24(self, MessageType, Value):
"""
Send a 24-bit value over SPI
Keyword arguments:
MessageType -- the SPI message type
Value -- the value to be sent
"""
outArray = [self.SPI_Address, MessageType, ((Value >> 16) & 0xFF), ((Value >> 8) & 0xFF), (Value & 0xFF)]
self.spi_transfer_array(outArray)
def spi_read_32(self, MessageType):
"""
Read a 32-bit value over SPI
Keyword arguments:
MessageType -- the SPI message type
Returns touple:
value, error
"""
outArray = [self.SPI_Address, MessageType, 0, 0, 0, 0, 0, 0]
reply = self.spi_transfer_array(outArray)
if(reply[3] == 0xA5):
return int((reply[4] << 24) | (reply[5] << 16) | (reply[6] << 8) | reply[7]), self.SUCCESS
return 0, self.SPI_ERROR
def spi_write_32(self, MessageType, Value):
"""
Send a 32-bit value over SPI
Keyword arguments:
MessageType -- the SPI message type
Value -- the value to be sent
"""
outArray = [self.SPI_Address, MessageType, ((Value >> 24) & 0xFF), ((Value >> 16) & 0xFF), ((Value >> 8) & 0xFF), (Value & 0xFF)]
self.spi_transfer_array(outArray)
def get_manufacturer(self):
"""
Read the 20 charactor BrickPi3 manufacturer name
Returns touple:
BrickPi3 manufacturer name string, error
"""
outArray = [self.SPI_Address, self.BPSPI_MESSAGE_TYPE.READ_MANUFACTURER, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
reply = self.spi_transfer_array(outArray)
if(reply[3] == 0xA5):
name = ""
for c in range(4, 24):
if reply[c] != 0:
name += chr(reply[c])
else:
break
return name, self.SUCCESS
return "", self.SPI_ERROR
def get_board(self):
"""
Read the 20 charactor BrickPi3 board name
Returns touple:
BrickPi3 board name string, error
"""
outArray = [self.SPI_Address, self.BPSPI_MESSAGE_TYPE.READ_NAME, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
reply = self.spi_transfer_array(outArray)
if(reply[3] == 0xA5):
name = ""
for c in range(4, 24):
if reply[c] != 0:
name += chr(reply[c])
else:
break
return name, self.SUCCESS
return "", self.SPI_ERROR
def get_version_hardware(self):
"""
Read the hardware version
Returns touple:
hardware version, error
"""
version, error = self.spi_read_32(self.BPSPI_MESSAGE_TYPE.READ_HARDWARE_VERSION)
return ("%d.%d.%d" % ((version / 1000000), ((version / 1000) % 1000), (version % 1000))), error
def get_version_firmware(self):
"""
Read the firmware version
Returns touple:
firmware version, | |
0,
"fractionalContribution": 1,
"sumWeights": 0,
"effectiveCrossSection": 0,
},
"ttother_SL_nr": {"filter": "nAdditionalBJets < 2 && nAdditionalCJets < 2 && nGenLep == 1 && (nGenJet < 9 || GenHT < 500)",
"nEventsPositive": 0,
"nEventsNegative": 0,
"fractionalContribution": 1,
"sumWeights": 0,
"effectiveCrossSection": 0,
},
},
},
},
"tt_SL-GF":{
"era": "2017",
"isData": False,
"nEvents": 8836856,
"nEventsPositive": 8794464,
"nEventsNegative": 42392,
"sumWeights": 2653328498.476976,
"sumWeights2": 812201885978.209229,
"isSignal": False,
"doFilter": True,
"crossSection": 12.3429,
"color": leg_dict["ttbar"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/tt_SL-GF_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/tt_SL-GF_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/tt_SL-GF_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/tt_SL-GF_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/tt_SL-GF_2017_v2.root"],
"destination": "/$HIST_CLASS/$HIST/tt_SL-GF/$SYSTEMATIC",
"stitch": {"mode": "Flag",
"source": "Filtered",
"channel": "SL"
},
"splitProcess": {"ID":{"unpackGenTtbarId": True,
"nGenJet/GenHT": True,
"subera": False,
},
"processes": {"ttbb_SL_fr": {"filter": "nAdditionalBJets >= 2 && nGenLep == 1 && nGenJet >= 9 && GenHT >= 500",
"nEventsPositive": 0,
"nEventsNegative": 0,
"fractionalContribution": 1,
"sumWeights": 0,
"effectiveCrossSection": 0,
},
"ttcc_SL_fr": {"filter": "nAdditionalCJets >= 2 && nGenLep == 1 && nGenJet >= 9 && GenHT >= 500",
"nEventsPositive": 0,
"nEventsNegative": 0,
"fractionalContribution": 1,
"sumWeights": 0,
"effectiveCrossSection": 0,
},
"ttother_SL_fr": {"filter": "nAdditionalBJets < 2 && nAdditionalCJets < 2 && nGenLep == 1 && nGenJet >= 9 && GenHT >= 500",
"nEventsPositive": 0,
"nEventsNegative": 0,
"fractionalContribution": 1,
"sumWeights": 0,
"effectiveCrossSection": 0,
},
},
},
},
"ST_tW":{
"era": "2017",
"isData": False,
"nEvents": 7945242,
"nEventsPositive": 7914815,
"nEventsNegative": 30427,
"sumWeights": 277241050.840222,
"sumWeights2": 9823995766.508368,
"isSignal": False,
"crossSection": 35.8,
"color": leg_dict["singletop"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ST_tW_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/ST_tW_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/ST_tW_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/ST_tW_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ST_tW_2017_v2.root"],
"destination": "/$HIST_CLASS/$HIST/ST_tW/$SYSTEMATIC",
},
"ST_tbarW":{
"era": "2017",
"isData": False,
"nEvents": 7745276,
"nEventsPositive": 7715654,
"nEventsNegative": 30427,
"sumWeights": 270762750.172525,
"sumWeights2": 9611964941.797768,
"isSignal": False,
"crossSection": 35.8,
"color": leg_dict["singletop"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ST_tbarW_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/ST_tbarW_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/ST_tbarW_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/ST_tbarW_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ST_tbarW_2017_v2.root"],
"destination": "/$HIST_CLASS/$HIST/ST_tbarW/$SYSTEMATIC",
},
"DYJets_DL":{
"era": "2017",
"isData": False,
"nEvents": 49125561,
"nEventsPositive": 49103859,
"nEventsNegative": 21702,
"sumWeights": 49082157.000000,
"sumWeights2": 49125561.000000,
"isSignal": False,
"crossSection": 5075.6,
"color": leg_dict["DY"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/DYJets_DL-*_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/DYJets_DL-*_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/DYJets_DL-*_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/DYJets_DL-*_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/DYJets_DL-1_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/DYJets_DL-2_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/DYJets_DL-3_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/DYJets_DL-4_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/DYJets_DL-5_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/DYJets_DL-6_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/DYJets_DL-7_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/DYJets_DL/$SYSTEMATIC",
},
"ttH":{
"era": "2017",
"isData": False,
"nEvents": 8000000,
"nEventsPositive": 7916867,
"nEventsNegative": 83133,
"sumWeights": 4216319.315884,
"sumWeights2": 2317497.816608,
"isSignal": False,
"crossSection": 0.2934,
"color": leg_dict["ttH"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttH_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/ttH_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/ttH_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/ttH_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttH_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/ttH/$SYSTEMATIC",
},
"ttWJets":{
"era": "2017",
"isData": False,
"nEvents": 9425384,
"nEventsPositive": 9404856,
"nEventsNegative": 20528,
"sumWeights": 9384328.000000,
"sumWeights2": 9425384.000000,
"isSignal": False,
"crossSection": 0.611,
"color": leg_dict["ttVJets"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttWJets_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/ttWJets_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/ttWJets_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/ttWJets_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttWJets_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/ttWJets/$SYSTEMATIC",
},
"ttZJets":{
"era": "2017",
"isData": False,
"nEvents": 8536618,
"nEventsPositive": 8527846,
"nEventsNegative": 8772,
"sumWeights": 8519074.000000,
"sumWeights2": 8536618.000000,
"isSignal": False,
"crossSection": 0.783,
"color": leg_dict["ttVJets"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttZJets_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/ttZJets_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/ttZJets_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/ttZJets_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttZJets_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/ttZJets/$SYSTEMATIC",
},
"ttWH":{
"era": "2017",
"isData": False,
"nEvents": 200000,
"nEventsPositive": 199491,
"nEventsNegative": 509,
"sumWeights": 198839.680865,
"sumWeights2": 199704.039588,
"isSignal": False,
"crossSection": 0.001572,
"color": leg_dict["ttultrarare"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttWH_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/ttWH_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/ttWH_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/ttWH_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttWH_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/ttWH/$SYSTEMATIC",
},
"ttWW":{
"era": "2017",
"isData": False,
"nEvents": 962000,
"nEventsPositive": 962000,
"nEventsNegative": 0,
"sumWeights": 962000.000000,
"sumWeights2": 962000.000000,
"isSignal": False,
"crossSection": 0.007882,
"color": leg_dict["ttultrarare"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttWW_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/ttWW_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/ttWW_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/ttWW_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttWW_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/ttWW/$SYSTEMATIC",
},
"ttWZ":{
"era": "2017",
"isData": False,
"nEvents": 200000,
"nEventsPositive": 199379,
"nEventsNegative": 621,
"sumWeights": 198625.183551,
"sumWeights2": 199708.972601,
"isSignal": False,
"crossSection": 0.002974,
"color": leg_dict["ttultrarare"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttWZ_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/ttWZ_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/ttWZ_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/ttWZ_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttWZ_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/ttWZ/$SYSTEMATIC",
},
"ttZZ":{
"era": "2017",
"isData": False,
"nEvents": 200000,
"nEventsPositive": 199686,
"nEventsNegative": 314,
"sumWeights": 199286.628891,
"sumWeights2": 199816.306332,
"isSignal": False,
"crossSection": 0.001572,
"color": leg_dict["ttultrarare"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttZZ_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/ttZZ_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/ttZZ_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/ttZZ_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttZZ_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/ttZZ/$SYSTEMATIC",
},
"ttZH":{
"era": "2017",
"isData": False,
"nEvents": 200000,
"nEventsPositive": 199643,
"nEventsNegative": 357,
"sumWeights": 199192.234990,
"sumWeights2": 199794.753976,
"isSignal": False,
"crossSection": 0.01253,
"color": leg_dict["ttultrarare"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttZH_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/ttZH_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/ttZH_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/ttZH_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttZH_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/ttZH/$SYSTEMATIC",
},
"ttHH":{
"era": "2017",
"isData": False,
"nEvents": 194817,
"nEventsPositive": 194516,
"nEventsNegative": 301,
"sumWeights": 194116.909912,
"sumWeights2": 194611.090542,
"isSignal": False,
"crossSection": 0.0007408,
"color": leg_dict["ttultrarare"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttHH_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/ttHH_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/ttHH_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/ttHH_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ttHH_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/ttHH/$SYSTEMATIC",
},
"tttW":{
"era": "2017",
"isData": False,
"nEvents": 200000,
"nEventsPositive": 199852,
"nEventsNegative": 148,
"sumWeights": 199552.187377,
"sumWeights2": 199697.648421,
"isSignal": False,
"crossSection": 0.007882,
"color": leg_dict["ttultrarare"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/tttW_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/tttW_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/tttW_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/tttW_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/tttW_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/tttW/$SYSTEMATIC",
},
"tttJ":{
"era": "2017",
"isData": False,
"nEvents": 200000,
"nEventsPositive": 199273,
"nEventsNegative": 727,
"sumWeights": 198394.878491,
"sumWeights2": 199663.384954,
"isSignal": False,
"crossSection": 0.0004741,
"color": leg_dict["ttultrarare"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/tttJ_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/tttJ_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/tttJ_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/tttJ_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/tttJ_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/tttJ/$SYSTEMATIC",
},
}
bookerV2_ElMu = {
"ElMu":{
"era": "2017",
"subera": "BCDEF",
"channel": "ElMu",
"isData": True,
"nEvents": 4453465 + 15595214 + 9164365 + 19043421 + 25776363,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElMu_*_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/data_ElMu_*_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/data_ElMu_*_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/data_ElMu_*_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElMu_B_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElMu_C_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElMu_D_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElMu_E_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElMu_F_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/ElMu/NOMINAL",
},
}
bookerV2_MuMu = {
"MuMu":{
"era": "2017",
"subera": "BCDEF",
"channel": "MuMu",
"isData": True,
"nEvents": 14501767 + 49636525 + 23075733 + 51589091 + 79756560,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_MuMu_*_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/data_MuMu_*_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/data_MuMu_*_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/data_MuMu_*_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_MuMu_B_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_MuMu_C_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_MuMu_D_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_MuMu_E_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_MuMu_F_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/MuMu/NOMINAL",
},
}
bookerV2_ElEl = {
"ElEl":{
"era": "2017",
"subera": "B",
"channel": "ElEl",
"isData": True,
"nEvents": 58088760 + 65181125 + 25911432 + 56233597 + 74307066,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElEl_*_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/data_ElEl_*_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/data_ElEl_*_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/data_ElEl_*_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElEl_B_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElEl_C_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElEl_D_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElEl_E_2017_v2.root",
"root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElEl_F_2017_v2.root",],
"destination": "/$HIST_CLASS/$HIST/ElEl/NOMINAL",
},
}
cutoutV2_ToBeFixed = {
"Mu":{
"era": "2017",
"subera": "BCDEF",
"channel": "Mu",
"isData": True,
"nEvents": 136300266 + 165652756 + 70361660 + 154630534 + 242135500,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_Mu_*_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/data_Mu_*_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/data_Mu_*_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/data_Mu_*_2017_v2*.root",
},
},
"El":{
"era": "2017",
"subera": "BCDEF",
"channel": "El",
"isData": True,
"nEvents": 60537490 + 136637888 + 51526710 + 102121689 + 128467223,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_El_*_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/data_El_*_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/data_El_*_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/data_El_*_2017_v2*.root",
},
},
"QCD_HT200":{
"era": "2017",
"isData": False,
"nEvents": 59200263,
"nEventsPositive": 59166789,
"nEventsNegative": 32544,
"sumWeights": 59133315.000000,
"sumWeights2": 59200263.000000,
"isSignal": False,
"crossSection": 1712000.0,
"color": leg_dict["QCD"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT200_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/QCD_HT200_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/QCD_HT200_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/QCD_HT200_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT200_2017_v2.root",],
},
"QCD_HT300":{
"era": "2017",
"isData": False,
"nEvents": 59569132,
"nEventsPositive": 59514373,
"nEventsNegative": 54759,
"sumWeights": 59459614.000000,
"sumWeights2": 59569132.000000,
"isSignal": False,
"crossSection": 347700.0,
"color": leg_dict["QCD"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT300_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/QCD_HT300_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/QCD_HT300_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/QCD_HT300_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT300_2017_v2.root",],
},
"QCD_HT500":{
"era": "2017",
"isData": False,
"nEvents": 56207744,
"nEventsPositive": 56124381,
"nEventsNegative": 83363,
"sumWeights": 56041018.000000,
"sumWeights2": 56207744.000000,
"isSignal": False,
"crossSection": 32100.0,
"color": leg_dict["QCD"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT500_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/QCD_HT500_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/QCD_HT500_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/QCD_HT500_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT500_2017_v2.root",],
},
"QCD_HT700":{
"era": "2017",
"isData": False,
"nEvents": 46840955,
"nEventsPositive": 46739970,
"nEventsNegative": 100985,
"sumWeights": 46638985.000000,
"sumWeights2": 46840955.000000,
"isSignal": False,
"crossSection": 6831.0,
"color": leg_dict["QCD"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT700_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/QCD_HT700_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/QCD_HT700_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/QCD_HT700_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT700_2017_v2.root",],
},
"QCD_HT1000":{
"era": "2017",
"isData": False,
"nEvents": 16882838,
"nEventsPositive": 16826800,
"nEventsNegative": 56038,
"sumWeights": 16770762.000000,
"sumWeights2": 16882838.000000,
"isSignal": False,
"crossSection": 1207.0,
"color": leg_dict["QCD"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT1000_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/QCD_HT1000_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/QCD_HT1000_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/QCD_HT1000_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT1000_2017_v2.root",],
},
"QCD_HT1500":{
"era": "2017",
"isData": False,
"nEvents": 11634434,
"nEventsPositive": 11571519,
"nEventsNegative": 62915,
"sumWeights": 11508604.000000,
"sumWeights2": 11634434.000000,
"isSignal": False,
"crossSection": 119.9,
"color": leg_dict["QCD"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT1500_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/QCD_HT1500_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/QCD_HT1500_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/QCD_HT1500_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT1500_2017_v2.root",],
},
"QCD_HT2000":{
"era": "2017",
"isData": False,
"nEvents": 5941306,
"nEventsPositive": 5883436,
"nEventsNegative": 57870,
"sumWeights": 5825566.000000,
"sumWeights2": 5941306.000000,
"isSignal": False,
"crossSection": 25.24,
"color": leg_dict["QCD"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT2000_2017_v2.root",
"LJMLogic/ElMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_selection/QCD_HT2000_2017_v2*.root",
"LJMLogic/MuMu_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/MuMu_selection/QCD_HT2000_2017_v2*.root",
"LJMLogic/ElEl_selection": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElEl_selection/QCD_HT2000_2017_v2*.root",
},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/QCD_HT2000_2017_v2.root",],
},
"ElMu_B":{
"era": "2017",
"subera": "B",
"channel": "ElMu",
"isData": True,
"nEvents": 4453465,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElMu_B*_2017_v2.root",},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_B_2017.root",],
},
"ElMu_C":{
"era": "2017",
"subera": "C",
"channel": "ElMu",
"isData": True,
"nEvents": 15595214,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElMu_C*_2017_v2.root",},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_C_2017.root",],
},
"ElMu_D":{
"era": "2017",
"subera": "D",
"channel": "ElMu",
"isData": True,
"nEvents": 9164365,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElMu_D*_2017_v2.root",},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_D_2017.root",],
},
"ElMu_E":{
"era": "2017",
"subera": "E",
"channel": "ElMu",
"isData": True,
"nEvents": 19043421,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElMu_E*_2017_v2.root",},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_E_2017.root",],
},
"ElMu_F":{
"era": "2017",
"subera": "F",
"channel": "ElMu",
"isData": True,
"nEvents": 25776363,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_ElMu_F*_2017_v2.root",},
"sourceSPARK": ["root://eoshome-n.cern.ch//eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/ElMu_F_2017.root",],
},
"MuMu_B":{
"era": "2017",
"subera": "B",
"channel": "MuMu",
"isData": True,
"nEvents": 14501767,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_MuMu_B*_2017_v2.root",},
},
"MuMu_C":{
"era": "2017",
"subera": "C",
"channel": "MuMu",
"isData": True,
"nEvents": 49636525,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_MuMu_C*_2017_v2.root",},
},
"MuMu_D":{
"era": "2017",
"subera": "D",
"channel": "MuMu",
"isData": True,
"nEvents": 23075733,
"color": leg_dict["Data"],
"source": {"LJMLogic": "/eos/user/n/nmangane/SWAN_projects/LogicChainRDF/FilesV2/data_MuMu_D*_2017_v2.root",},
},
"MuMu_E":{
"era": "2017",
| |
# -*- coding: utf-8 -*-
###############################################################################
###############################################################################
## ##
## _ ___ ___ ___ ___ ___ ##
## | | | __ / \ / __| _ | __| ##
## | |__| __| ( ) | (_ | _|__ \ ##
## |____|___ \___/ \___|_| \___/ ##
## v 1.3 (Stable) ##
## ##
## Module for rotation matrices supporting ICRF-to-ITRF conversion. ##
## Uses the IAU1976 Theory of Precession and IAU1980 Theory of Nutation. ##
## ##
## References: ##
## https://gssc.esa.int/navipedia/index.php/ICRF_to_CEP ##
## https://gssc.esa.int/navipedia/index.php/CEP_to_ITRF ##
## https://gssc.esa.int/navipedia/index.php/Julian_Date ##
## ##
## Written by <NAME>. ##
## Last modified 10-Jun-2021 ##
## Website: https://github.com/sammmlow/LEOGPS ##
## Documentation: https://leogps.readthedocs.io/en/latest/ ##
## ##
###############################################################################
###############################################################################
import os
import math
import datetime
import numpy as np
from os.path import dirname, abspath, join
##############################################################################
##############################################################################
### ###
### FUNCTIONS BELOW FOR DIRECTION COSINE MATRICES ###
### ###
##############################################################################
##############################################################################
def _dcmX(t):
'''Direction cosine matrix of local X-axis, with input "t" in radians'''
dcm = np.array([[ 1.0, 0.0, 0.0 ],
[ 0.0, math.cos(t), math.sin(t) ],
[ 0.0, -1*math.sin(t), math.cos(t) ]])
return dcm
def _dcmY(t):
'''Direction cosine matrix of local Y-axis, with input "t" in radians'''
dcm = np.array([[ math.cos(t), 0.0, -1*math.sin(t) ],
[ 0.0, 1.0, 0.0 ],
[ math.sin(t), 0.0, math.cos(t) ]])
return dcm
def _dcmZ(t):
'''Direction cosine matrix of local Z-axis, with input "t" in radians'''
dcm = np.array([[ math.cos(t), math.sin(t), 0.0 ],
[ -1*math.sin(t), math.cos(t), 0.0 ],
[ 0.0, 0.0, 1.0 ]])
return dcm
##############################################################################
##############################################################################
### ###
### FUNCTIONS THAT RETURNS THE DAY-OF-WEEK AND GPS WEEK ###
### ###
##############################################################################
##############################################################################
# We define a function that returns the day-of-week and the GPS week.
def _gpsweekday(t):
# Logic below calculates the desired GPS day and week number.
wkday = (t.weekday() + 1) % 7 # Weekday from Python to GPST
GPST_epoch = datetime.date(1980,1,6) # Date of GPST epoch
user_epoch = t.date() # Get the date of the input time
GPST_epoch_Monday = GPST_epoch - datetime.timedelta(GPST_epoch.weekday())
user_epoch_Monday = user_epoch - datetime.timedelta(user_epoch.weekday())
wwww = int(((user_epoch_Monday-GPST_epoch_Monday).days/7)-1) # GPS week
# Algorithmic correction to the above logic.
if wkday == 0:
wwww += 1
return str(wkday), str(wwww)
##############################################################################
##############################################################################
### ###
### FUNCTION BELOW TO COMPUTE PRECESSION ROTATION MATRIX ###
### ###
##############################################################################
##############################################################################
def precession(t):
'''Computes the precession matrix using the IAU 1976 Precession Model,
where the matrix is applied in the direction from ICRF to the CEP.
Parameters
----------
t : datetime.datetime
Current time of observation in GPST.
Returns
-------
precession : numpy.ndarray
A 3x3 DCM that rotates the ICRF by the precession offset.
'''
# Get a degree-to-radian multiplier.
d2r = np.pi / 180.0
# Convert the current epoch in GPST to Terrestrial Time (TDT)
tt = t + datetime.timedelta(seconds=51)
# Get the J2000 reference epoch
j2000 = datetime.datetime(2000,1,1,12,0,0)
# From the IAU 1976 precession model, we have the axial rotations:
# p = (2306".2181 * T) + (1".09468 * T^2) + (0".018203 * T^3)
# q = (2004".3109 * T) − (0".42665 * T^2) − (0".041833 * T^3)
# r = (2306".2181 * T) + (0".30188 * T^2) + (0".017998 * T^3)
# Where T is the time expressed in Julian centuries (36,525 Earth days),
# between the reference epoch J2000 and the current time of observation.
pqr = np.array([[2306.2181, 1.09468, 0.018203],
[2004.3109, 0.42665, 0.041833],
[2306.2181, 0.30188, 0.017998]])
# Compute the time elapsed T in Julian centuries
T = ( ( (tt - j2000).days ) + ( (tt - j2000).seconds / 86400 ) ) / 36525
p = np.dot( pqr[0], np.array([ T, T**2, T**3 ]) ) * d2r / 3600
q = np.dot( pqr[1], np.array([ T, T**2, T**3 ]) ) * d2r / 3600
r = np.dot( pqr[2], np.array([ T, T**2, T**3 ]) ) * d2r / 3600
# Compute the final precession matrix
precession = _dcmZ( -1*p ) @ _dcmY( q ) @ _dcmZ( -1*r )
return precession
##############################################################################
##############################################################################
### ###
### FUNCTION BELOW TO COMPUTE NUTATION ROTATION MATRIX ###
### ###
##############################################################################
##############################################################################
def nutation(t):
'''Computes the nutation matrix using the IAU 1980 Nutation Model,
where the matrix is applied in the direction from ICRF to the CEP.
Parameters
----------
t : datetime.datetime
Current time of observation in GPST.
Returns
-------
nutation : numpy.ndarray
A 3x3 DCM that rotates the ICRF by the nutation offset.
'''
# Get the coefficients to the IAU 1980 Nutation Model
# Headers k1, k2, k3, k4, k5, A0 ("), A1 ("), B0 ("), B1 (")
N = [[ 0.0, 0.0, 0.0, 0.0, 1.0, -17.1996, -174.2, 9.2025, 8.9 ],
[ 0.0, 0.0, 2.0, -2.0, 2.0, -1.3187, -1.6, 0.5736, -3.1 ],
[ 0.0, 0.0, 2.0, 0.0, 2.0, -0.2274, -0.2, 0.0977, -0.5 ],
[ 0.0, 0.0, 0.0, 0.0, 2.0, 0.2062, 0.2, -0.0895, 0.5 ],
[ 0.0, -1.0, 0.0, 0.0, 0.0, -0.1426, 3.4, 0.0054, -0.1 ],
[ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0712, 0.1, -0.0007, 0.0 ],
[ 0.0, 1.0, 2.0, -2.0, 2.0, -0.0517, 1.2, 0.0224, -0.6 ],
[ 0.0, 0.0, 2.0, 0.0, 1.0, -0.0386, -0.4, 0.02, 0.0 ],
[ 1.0, 0.0, 2.0, 0.0, 2.0, -0.0301, 0.0, 0.0129, -0.1 ],
[ 0.0, -1.0, 2.0, -2.0, 2.0, 0.0217, -0.5, -0.0095, 0.3 ],
[ -1.0, 0.0, 0.0, 2.0, 0.0, 0.0158, 0.0, -0.0001, 0.0 ],
[ 0.0, 0.0, 2.0, -2.0, 1.0, 0.0129, 0.1, -0.007, 0.0 ],
[ -1.0, 0.0, 2.0, 0.0, 2.0, 0.0123, 0.0, -0.0053, 0.0 ],
[ 1.0, 0.0, 0.0, 0.0, 1.0, 0.0063, 0.1, -0.0033, 0.0 ],
[ 0.0, 0.0, 0.0, 2.0, 0.0, 0.0063, 0.0, -0.0002, 0.0 ],
[ -1.0, 0.0, 2.0, 2.0, 2.0, -0.0059, 0.0, 0.0026, 0.0 ],
[ -1.0, 0.0, 0.0, 0.0, 1.0, -0.0058, -0.1, 0.0032, 0.0 ],
[ 1.0, 0.0, 2.0, 0.0, 1.0, -0.0051, 0.0, 0.0027, 0.0 ],
[ -2.0, 0.0, 0.0, 2.0, 0.0, -0.0048, 0.0, 0.0001, 0.0 ],
[ -2.0, 0.0, 2.0, 0.0, 1.0, 0.0046, 0.0, -0.0024, 0.0 ],
[ 0.0, 0.0, 2.0, 2.0, 2.0, -0.0038, 0.0, 0.0016, 0.0 ],
[ 2.0, 0.0, 2.0, 0.0, 2.0, -0.0031, 0.0, 0.0013, 0.0 ],
[ 2.0, 0.0, 0.0, 0.0, 0.0, 0.0029, 0.0, -0.0001, 0.0 ],
[ 1.0, 0.0, 2.0, -2.0, 2.0, 0.0029, 0.0, -0.0012, 0.0 ],
[ 0.0, 0.0, 2.0, 0.0, 0.0, 0.0026, 0.0, -0.0001, 0.0 ],
[ 0.0, 0.0, 2.0, -2.0, 0.0, -0.0022, 0.0, 0.0, 0.0 ],
[ -1.0, 0.0, 2.0, 0.0, 1.0, 0.0021, 0.0, -0.001, 0.0 ],
[ 0.0, 2.0, 0.0, 0.0, 0.0, 0.0017, -0.1, 0.0, 0.0 ],
[ 0.0, 2.0, 2.0, -2.0, 2.0, -0.0016, 0.1, 0.0007, 0.0 ],
[ -1.0, 0.0, 0.0, 2.0, 1.0, 0.0016, 0.0, -0.0008, 0.0 ],
[ 0.0, 1.0, 0.0, 0.0, 1.0, -0.0015, 0.0, 0.0009, 0.0 ],
[ 1.0, 0.0, 0.0, -2.0, 1.0, -0.0013, 0.0, 0.0007, 0.0 ],
[ 0.0, -1.0, 0.0, 0.0, 1.0, -0.0012, 0.0, 0.0006, 0.0 ],
[ 2.0, 0.0, -2.0, 0.0, 0.0, 0.0011, 0.0, 0.0, 0.0 ],
[ -1.0, 0.0, 2.0, 2.0, 1.0, -0.001, 0.0, 0.0005, 0.0 ],
[ 1.0, 0.0, 2.0, 2.0, 2.0, -0.0008, 0.0, 0.0003, 0.0 ],
[ 0.0, -1.0, 2.0, 0.0, 2.0, -0.0007, 0.0, 0.0003, 0.0 ],
[ 0.0, 0.0, 2.0, 2.0, 1.0, -0.0007, 0.0, 0.0003, 0.0 ],
[ 1.0, 1.0, 0.0, -2.0, 0.0, -0.0007, 0.0, 0.0, 0.0 ],
[ 0.0, 1.0, 2.0, 0.0, 2.0, 0.0007, 0.0, -0.0003, 0.0 ],
[ -2.0, 0.0, 0.0, 2.0, 1.0, -0.0006, 0.0, 0.0003, 0.0 ],
[ 0.0, 0.0, 0.0, 2.0, 1.0, -0.0006, 0.0, 0.0003, 0.0 ],
[ 2.0, 0.0, 2.0, -2.0, 2.0, 0.0006, 0.0, -0.0003, 0.0 ],
[ 1.0, 0.0, 0.0, 2.0, 0.0, 0.0006, 0.0, 0.0, 0.0 ],
[ 1.0, 0.0, 2.0, -2.0, 1.0, 0.0006, 0.0, -0.0003, 0.0 ],
[ 0.0, 0.0, 0.0, -2.0, 1.0, -0.0005, 0.0, 0.0003, 0.0 ],
[ 0.0, -1.0, 2.0, -2.0, 1.0, -0.0005, 0.0, 0.0003, 0.0 ],
[ 2.0, 0.0, 2.0, 0.0, 1.0, -0.0005, 0.0, 0.0003, 0.0 ],
[ 1.0, -1.0, 0.0, 0.0, 0.0, 0.0005, 0.0, 0.0, 0.0 ],
[ 1.0, 0.0, 0.0, -1.0, 0.0, -0.0004, 0.0, 0.0, 0.0 ],
[ 0.0, 0.0, 0.0, 1.0, 0.0, -0.0004, 0.0, 0.0, 0.0 ],
[ 0.0, 1.0, 0.0, -2.0, 0.0, -0.0004, 0.0, 0.0, 0.0 ],
[ 1.0, 0.0, -2.0, 0.0, 0.0, 0.0004, 0.0, 0.0, 0.0 ],
| |
0.00435488,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.1049,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic': 3.29472,
'Subthreshold Leakage': 6.16288,
'Subthreshold Leakage with power gating': 2.55328},
{'Area': 32.0201,
'Execution Unit/Area': 7.68434,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 9.4469e-07,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.20269,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 2.02403e-05,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.304033,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.120359,
'Execution Unit/Instruction Scheduler/Area': 1.66526,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.275653,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.000977433,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.04181,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.185249,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0143453,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.00810519,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.00568913,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.805223,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00414562,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 1.6763,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.2988,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0625755,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0355964,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 3.82262,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.584388,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.00056608,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 1.10451,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.150824,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.00906853,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00364446,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.634873,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0859892,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.047346,
'Execution Unit/Integer ALUs/Area': 0.47087,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0265291,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.211868,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.101344,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.40222,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.150833,
'Execution Unit/Peak Dynamic': 4.2375,
'Execution Unit/Register Files/Area': 0.570804,
'Execution Unit/Register Files/Floating Point RF/Area': 0.208131,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 0.000232788,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 3.82383e-06,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00777017,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.00399698,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.00176968,
'Execution Unit/Register Files/Gate Leakage': 0.000622708,
'Execution Unit/Register Files/Integer RF/Area': 0.362673,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.00038992,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0561878,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0574652,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00614175,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.00246675,
'Execution Unit/Register Files/Peak Dynamic': 0.0561917,
'Execution Unit/Register Files/Runtime Dynamic': 0.0652353,
'Execution Unit/Register Files/Subthreshold Leakage': 0.0101387,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00423643,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0390912,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00537402,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.118372,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.317706,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.081478,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0305543,
'Execution Unit/Runtime Dynamic': 1.62588,
'Execution Unit/Subthreshold Leakage': 1.79543,
'Execution Unit/Subthreshold Leakage with power gating': 0.688821,
'Gate Leakage': 0.368936,
'Instruction Fetch Unit/Area': 5.85939,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.00215912,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.00215912,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.00194663,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 0.000789695,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000825492,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00709036,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.0183418,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0589979,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.0226323,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 6.83558e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.606827,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.0552427,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.00151885,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000701682,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 3.51391,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.176185,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 1.85799,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 1.37404,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.187629,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 5.90297,
'Instruction Fetch Unit/Runtime Dynamic': 0.444489,
'Instruction Fetch Unit/Subthreshold Leakage': 0.932286,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.40843,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.0339456,
'L2/Runtime Dynamic': 0.00921918,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.80901,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 2.72366,
'Load Store Unit/Data Cache/Runtime Dynamic': 0.727438,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0350888,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.0480932,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.0480933,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 2.95077,
'Load Store Unit/Runtime Dynamic': 1.01271,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.11859,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.23718,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.591321,
'Load Store Unit/Subthreshold Leakage with power gating': 0.283293,
'Memory Management Unit/Area': 0.4339,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.0420879,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.042374,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00808595,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.218482,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.0295455,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.446891,
'Memory Management Unit/Runtime Dynamic': 0.0719195,
'Memory Management Unit/Subthreshold Leakage': 0.0766103,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0398333,
'Peak Dynamic': 17.1615,
'Renaming Unit/Area': 0.303608,
'Renaming Unit/FP Front End RAT/Area': 0.131045,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00351123,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 2.51468,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 9.45018e-06,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0308571,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.0175885,
'Renaming Unit/Free List/Area': 0.0340654,
'Renaming Unit/Free List/Gate Leakage': 2.5481e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0306032,
'Renaming Unit/Free List/Runtime Dynamic': 0.00835804,
'Renaming Unit/Free List/Subthreshold Leakage': 0.000370144,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000201064,
'Renaming Unit/Gate Leakage': 0.00708398,
'Renaming Unit/Int Front End RAT/Area': 0.0941223,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000283242,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.731965,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0951555,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00435488,
| |
<gh_stars>1-10
"""
Created on Oct 14, 2016
@author: <NAME> -- <EMAIL>
"""
from __future__ import division, print_function, absolute_import
import sys
import os
import getopt
import h5py
import numpy as np
from mpi4py import MPI
# import matplotlib.pyplot as plt
def gen_batches(n, batch_size, start=0):
"""
Copied from scikit-learn
Generator to create slices containing batch_size elements, from 0 to n.
The last slice may contain less than batch_size elements, when batch_size
does not divide n.
Examples
--------
>>> from sklearn.utils import gen_batches
>>> list(gen_batches(7, 3))
[slice(0, 3, None), slice(3, 6, None), slice(6, 7, None)]
>>> list(gen_batches(6, 3))
[slice(0, 3, None), slice(3, 6, None)]
>>> list(gen_batches(2, 3))
[slice(0, 2, None)]
"""
stop = start+n
for _ in range(int(n // batch_size)):
end = start + batch_size
yield slice(start, end)
start = end
if start < stop:
yield slice(start, stop)
def gen_batches_mpi(n_items, n_batches):
"""
Modified version of gen_batches
Generator to create `n_batches` slices, from 0 to n_items.
Some slices may contain less more elements than others, when batch_size
does not divide evenly into n_items.
Examples
--------
>>> from sklearn.utils import gen_batches
>>> list(gen_batches(7, 3))
[slice(0, 3, None), slice(3, 6, None), slice(6, 7, None)]
>>> list(gen_batches(6, 3))
[slice(0, 3, None), slice(3, 6, None)]
>>> list(gen_batches(2, 3))
[slice(0, 2, None)]
"""
batch_size = 0
rem = n_items
while rem > n_batches:
batch_size += n_items // n_batches
rem = n_items % n_batches
start = 0
for _ in range(n_batches):
end = start + batch_size
if rem > 0:
end += 1
rem -= 1
yield(slice(start, end))
start = end
def calc_chunks(dimensions, data_size, unit_chunks=None, max_chunk_mem=10240):
"""
Calculate the chunk size for the HDF5 dataset based on the dimensions and the
maximum chunk size in memory
Parameters
----------
dimensions : array_like of int
Shape of the data to be chunked
data_size : int
Size of an entry in the data in bytes
unit_chunks : array_like of int, optional
Unit size of the chunking in each dimension. Must be the same size as
the shape of `ds_main`. Default None, `unit_chunks` is set to 1 in all
dimensions
max_chunk_mem : int, optional
Maximum size of the chunk in memory in bytes. Default 10240b or 10kb
Returns
-------
chunking : tuple of int
Calculated maximum size of a chunk in each dimension that is as close to the
requested `max_chunk_mem` as posible while having steps based on the input
`unit_chunks`.
"""
'''
Ensure that dimensions is an array
'''
dimensions = np.asarray(dimensions, dtype=np.uint)
'''
Set the unit_chunks to all ones if not given. Ensure it is an array if it is.
'''
if unit_chunks is None:
unit_chunks = np.ones_like(dimensions)
else:
unit_chunks = np.asarray(unit_chunks, dtype=np.uint)
if unit_chunks.shape != dimensions.shape:
raise ValueError('Unit chunk size must have the same shape as the input dataset.')
'''
Save the original size of unit_chunks to use for incrementing the chunk size during
loop
'''
base_chunks = unit_chunks
'''
Loop until chunk_size is greater than the maximum chunk_mem or the chunk_size is equal to
that of dimensions
'''
while np.prod(unit_chunks) * data_size <= max_chunk_mem:
'''
Check if all chunk dimensions are greater or equal to the
actual dimensions. Exit the loop if true.
'''
if np.all(unit_chunks >= dimensions):
break
'''
Find the index of the next chunk to be increased and increment it by the base_chunk
size
'''
ichunk = np.argmax(dimensions // unit_chunks)
unit_chunks[ichunk] += base_chunks[ichunk]
'''
Ensure that the size of the chunks is between one and the dimension size.
'''
unit_chunks = np.clip(unit_chunks, np.ones_like(unit_chunks), dimensions)
chunking = tuple(unit_chunks)
return chunking
def clean_and_build_components(h5_svd, comm, comp_slice=None):
"""
Rebuild the Image from the PCA results on the windows
Optionally, only use components less than n_comp.
Parameters
----------
h5_svd : hdf5 Group, optional
Group containing the results from SVD on windowed data
components: {int, iterable of int, slice} optional
Defines which components to keep
Input Types
integer : Components less than the input will be kept
length 2 iterable of integers : Integers define start and stop of component slice to retain
other iterable of integers or slice : Selection of component indices to retain
Returns
-------
h5_clean : hdf5 Dataset
dataset with the cleaned image
"""
mpi_size = comm.size
mpi_rank = comm.rank
try:
h5_S = h5_svd['S']
h5_U = h5_svd['U']
h5_V = h5_svd['V']
if mpi_rank == 0:
print('Cleaning the image by removing unwanted components.')
except:
raise
comp_slice = get_component_slice(comp_slice)
'''
Get basic windowing information from attributes of
h5_win_group
'''
h5_win_group = h5_svd.parent
h5_pos = h5_win_group['Position_Indices']
im_x = h5_win_group.attrs['image_x']
im_y = h5_win_group.attrs['image_y']
win_x = h5_win_group.attrs['win_x']
win_y = h5_win_group.attrs['win_y']
win_name = h5_win_group.name.split('/')[-1]
basename = win_name.split('-')[0]
h5_source_image = h5_win_group.parent[basename]
'''
Create slice object from the positions
'''
# Get batches of positions for each rank
n_pos = h5_pos.shape[0]
win_batches = gen_batches_mpi(n_pos, mpi_size)
# Create array of windows for each rank
if mpi_rank == 0:
print('Number of positions: {}'.format(n_pos))
# print('Window batches: {}'.format(list(win_batches)))
windows = [h5_pos[my_batch] for my_batch in win_batches]
print('Number of windows batches: {} should equal the number of ranks: {}'.format(len(windows), mpi_size))
for rank in range(mpi_size):
print('Rank {} has {} windows.'.format(rank, windows[rank].shape[0]))
# print('Shape of windows: {}'.format(windows.shape))
else:
# Only need to do this on one rank
windows = None
comm.Barrier()
# Initialize the windows for a specific rank
# my_wins = np.zeros(shape=[windows[mpi_rank].shape[0], h5_pos.shape[1]], dtype=h5_pos.dtype)
# print("Pre-Scatter \t my rank: {},\tmy_wins: {}".format(mpi_rank, my_wins))
# Send each rank it's set of windows
my_wins = comm.scatter(windows, root=0)
# print("Post-scatter \t my rank: {},\tmy_wins: {}".format(mpi_rank, my_wins))
# Turn array of starting positions into a list of slices
my_slices = [[slice(x, x + win_x), slice(y, y + win_y)] for x, y in my_wins]
comm.Barrier()
n_my_wins = len(my_wins)
'''
Create a matrix to add when counting.
h5_V is usually small so go ahead and take S.V
'''
ds_V = np.dot(np.diag(h5_S[comp_slice]), h5_V[comp_slice, :]['Image Data']).T
num_comps = len(h5_S[comp_slice])
'''
Initialize arrays to hold summed windows and counts for each position
'''
ones = np.ones([win_x, win_y, num_comps], dtype=np.uint32)
my_counts = np.zeros([im_x, im_y, num_comps], dtype=np.uint32)
my_clean_image = np.zeros([im_x, im_y, num_comps], dtype=np.float32)
counts = np.zeros([im_x, im_y, num_comps], dtype=np.uint32)
clean_image = np.zeros([im_x, im_y, num_comps], dtype=np.float32)
'''
Calculate the size of a given batch that will fit in the available memory
'''
mem_per_win = ds_V.itemsize * (ds_V.size + num_comps)
max_memory = 4 * 1024 ** 3
free_mem = max_memory - ds_V.size * ds_V.itemsize * mpi_size
my_batch_size = int(free_mem / mem_per_win / mpi_size)
my_start = 0
if mpi_size > 1:
if mpi_rank == 0:
# print('max memory', max_memory)
# print('memory used per window', mem_per_win)
# print('free memory', free_mem)
# print('batch size per rank', my_batch_size)
comm.isend(n_my_wins, dest=1)
for rank in range(1, mpi_size-1):
if mpi_rank == rank:
my_start += comm.recv(source=mpi_rank - 1)
comm.isend(n_my_wins+my_start, dest=mpi_rank + 1)
comm.Barrier()
if mpi_rank == mpi_size-1:
my_start += comm.recv(source=mpi_rank - 1)
comm.Barrier()
print("my rank: {}\tmy start: {}".format(mpi_rank, my_start))
if my_batch_size < 1:
raise MemoryError('Not enough memory to perform Image Cleaning.')
batch_slices = gen_batches(n_my_wins, my_batch_size, my_start)
batch_win_slices = gen_batches(n_my_wins, my_batch_size)
comm.Barrier()
'''
Loop over all batches. Increment counts for window positions and
add current window to total.
'''
for ibatch, (my_batch, my_win_batch) in enumerate(zip(batch_slices, batch_win_slices)):
# print("my rank: {}\tmy batch: {}\tmy win batch: {}".format(mpi_rank, my_batch, my_win_batch))
batch_wins = np.reshape(h5_U[my_batch, comp_slice][:, None, :] * ds_V[None, :, :], [-1, win_x, win_y, num_comps])
# print(mpi_rank, batch_wins.shape, len(my_slices))
for islice, this_slice in enumerate(my_slices[my_win_batch]):
iwin = ibatch * my_batch_size + islice + my_start
if iwin % np.rint(n_my_wins / 10) == 0:
per_done = np.rint(100 * iwin / n_my_wins)
print('Rank {} Reconstructing Image...{}% -- step # {} -- window {} -- slice {}'.format(mpi_rank,
per_done,
islice,
iwin,
this_slice))
# if mpi_rank == 1:
# print("my rank: {}\tislice: {}\tthis_slice: {}\t iwin: {}".format(mpi_rank, islice, this_slice, iwin))
my_counts[this_slice] += ones
# print("my rank: {}\tthis_slice: {}\tislice: {}\tmy_start: {}".format(mpi_rank,
# this_slice,
# islice,
# my_start))
# print("my image: {}\tbatch_wins: {}".format(my_clean_image.shape, batch_wins.shape))
my_clean_image[this_slice] += batch_wins[islice]
del batch_wins
comm.Barrier()
if mpi_rank == 0:
print('Finished summing chunks of windows on all ranks. Combining them with All-reduce.')
comm.Allreduce(my_counts, counts, op=MPI.SUM)
comm.Allreduce(my_clean_image, clean_image, op=MPI.SUM)
comm.Barrier()
# for rank in range(mpi_size):
# if mpi_rank == rank:
| |
and report
success if an error occurs.''')
parser.error = self._parse_error
return parser
def apply(self, code, silent, store_history, user_expressions, allow_stdin):
import tempfile
import shutil
options, remaining_code = self.get_magic_and_code(code, False)
parser = self.get_parser()
try:
args = parser.parse_args(shlex.split(options))
except SystemExit:
return
self.in_sandbox = True
try:
old_dir = os.getcwd()
if args.dir:
args.dir = os.path.expanduser(args.dir)
if not os.path.isdir(args.dir):
os.makedirs(args.dir)
env.exec_dir = os.path.abspath(args.dir)
os.chdir(args.dir)
else:
new_dir = tempfile.mkdtemp()
env.exec_dir = os.path.abspath(new_dir)
os.chdir(new_dir)
if not args.keep_dict:
old_dict = env.sos_dict
self.sos_kernel._reset_dict()
ret = self.sos_kernel._do_execute(
remaining_code, silent, store_history, user_expressions, allow_stdin)
if args.expect_error and ret['status'] == 'error':
# self.sos_kernel.warn('\nSandbox execution failed.')
return {'status': 'ok',
'payload': [], 'user_expressions': {},
'execution_count': self.sos_kernel._execution_count}
else:
return ret
finally:
if not args.keep_dict:
env.sos_dict = old_dict
os.chdir(old_dir)
if not args.dir:
shutil.rmtree(new_dir)
self.in_sandbox = False
# env.exec_dir = old_dir
class Save_Magic(SoS_Magic):
name = 'save'
def __init__(self, kernel):
super(Save_Magic, self).__init__(kernel)
def get_parser(self):
parser = argparse.ArgumentParser(prog='%save',
description='''Save the content of the cell (after the magic itself) to specified file''')
parser.add_argument('filename',
help='''Filename of saved report or script.''')
parser.add_argument('-f', '--force', action='store_true',
help='''If destination file already exists, overwrite it.''')
parser.add_argument('-a', '--append', action='store_true',
help='''If destination file already exists, append to it.''')
parser.add_argument('-x', '--set-executable', dest="setx", action='store_true',
help='''Set `executable` permission to saved script.''')
parser.error = self._parse_error
return parser
def apply(self, code, silent, store_history, user_expressions, allow_stdin):
# if sos kernel ...
options, remaining_code = self.get_magic_and_code(code, False)
try:
parser = self.get_parser()
try:
args = parser.parse_args(shlex.split(options))
except SystemExit:
return
filename = os.path.expanduser(args.filename)
if os.path.isfile(filename) and not args.force:
raise ValueError(
f'Cannot overwrite existing output file {filename}')
with open(filename, 'a' if args.append else 'w') as script:
script.write(
'\n'.join(remaining_code.splitlines()).rstrip() + '\n')
if args.setx:
import stat
os.chmod(filename, os.stat(
filename).st_mode | stat.S_IEXEC)
self.sos_kernel.send_response(self.sos_kernel.iopub_socket, 'display_data',
{'metadata': {},
'data': {
'text/plain': f'Cell content saved to {filename}\n',
'text/html': HTML(
f'<div class="sos_hint">Cell content saved to <a href="{filename}" target="_blank">{filename}</a></div>').data
}
})
return
except Exception as e:
self.sos_kernel.warn(f'Failed to save cell: {e}')
return {'status': 'error',
'ename': e.__class__.__name__,
'evalue': str(e),
'traceback': [],
'execution_count': self.sos_kernel._execution_count,
}
class SessionInfo_Magic(SoS_Magic):
name = 'sessioninfo'
def __init__(self, kernel):
super(SessionInfo_Magic, self).__init__(kernel)
def get_parser(self):
parser = argparse.ArgumentParser(prog='%sessioninfo',
description='''List the session info of all subkernels, and information
stored in variable sessioninfo''')
parser.error = self._parse_error
return parser
def handle_sessioninfo(self):
#
from sos.utils import loaded_modules
result = OrderedDict()
#
result['SoS'] = [('SoS Version', __version__)]
result['SoS'].extend(loaded_modules(env.sos_dict))
#
cur_kernel = self.sos_kernel.kernel
try:
for kernel in self.sos_kernel.kernels.keys():
kinfo = self.sos_kernel.subkernels.find(kernel)
self.sos_kernel.switch_kernel(kernel)
result[kernel] = [
('Kernel', kinfo.kernel),
('Language', kinfo.language)
]
if kernel not in self.sos_kernel.supported_languages:
continue
lan = self.sos_kernel.supported_languages[kernel]
if hasattr(lan, 'sessioninfo'):
try:
sinfo = lan(self.sos_kernel, kinfo.kernel).sessioninfo()
if isinstance(sinfo, str):
result[kernel].append([sinfo])
elif isinstance(sinfo, dict):
result[kernel].extend(list(sinfo.items()))
elif isinstance(sinfo, list):
result[kernel].extend(sinfo)
else:
self.sos_kernel.warn(f'Unrecognized session info: {sinfo}')
except Exception as e:
self.sos_kernel.warn(
f'Failed to obtain sessioninfo of kernel {kernel}: {e}')
finally:
self.sos_kernel.switch_kernel(cur_kernel)
#
if 'sessioninfo' in env.sos_dict:
result.update(env.sos_dict['sessioninfo'])
#
res = ''
for key, items in result.items():
res += f'<p class="session_section">{key}</p>\n'
res += '<table class="session_info">\n'
for item in items:
res += '<tr>\n'
if isinstance(item, str):
res += f'<td colspan="2"><pre>{item}</pre></td>\n'
elif len(item) == 1:
res += f'<td colspan="2"><pre>{item[0]}</pre></td>\n'
elif len(item) == 2:
res += f'<th>{item[0]}</th><td><pre>{item[1]}</pre></td>\n'
else:
self.sos_kernel.warn(
f'Invalid session info item of type {item.__class__.__name__}: {short_repr(item)}')
res += '</tr>\n'
res += '</table>\n'
self.sos_kernel.send_response(self.sos_kernel.iopub_socket, 'display_data',
{'metadata': {},
'data': {'text/html': HTML(res).data}})
def apply(self, code, silent, store_history, user_expressions, allow_stdin):
options, remaining_code = self.get_magic_and_code(code, False)
parser = self.get_parser()
try:
parser.parse_known_args(shlex.split(options))
except SystemExit:
return
self.handle_sessioninfo()
return self.sos_kernel._do_execute(remaining_code, silent, store_history, user_expressions, allow_stdin)
class Set_Magic(SoS_Magic):
name = 'set'
def __init__(self, kernel):
super(Set_Magic, self).__init__(kernel)
def get_parser(self):
parser = argparse.ArgumentParser(prog='%set',
description='''Set persistent command line options for SoS runs.''')
parser.error = self._parse_error
return parser
def handle_magic_set(self, options):
if options.strip():
# self.sos_kernel.send_response(self.sos_kernel.iopub_socket, 'stream',
# {'name': 'stdout', 'text': 'sos options set to "{}"\n'.format(options)})
if not options.strip().startswith('-'):
self.sos_kernel.warn(
f'Magic %set cannot set positional argument, {options} provided.\n')
else:
self.sos_kernel.options = options.strip()
self.sos_kernel.send_response(self.sos_kernel.iopub_socket, 'stream',
dict(name='stdout', text=f'Set sos options to "{self.sos_kernel.options}"\n'))
else:
if self.sos_kernel.options:
self.sos_kernel.send_response(self.sos_kernel.iopub_socket, 'stream',
dict(name='stdout', text=f'Reset sos options from "{self.sos_kernel.options}" to ""\n'))
self.sos_kernel.options = ''
else:
self.sos_kernel.send_response(self.sos_kernel.iopub_socket, 'stream',
{'name': 'stdout',
'text': 'Usage: set persistent sos command line options such as "-v 3" (debug output)\n'})
def apply(self, code, silent, store_history, user_expressions, allow_stdin):
options, remaining_code = self.get_magic_and_code(code, False)
self.handle_magic_set(options)
# self.sos_kernel.options will be set to inflence the execution of remaing_code
return self.sos_kernel._do_execute(remaining_code, silent, store_history, user_expressions, allow_stdin)
class Shutdown_Magic(SoS_Magic):
name = 'shutdown'
def __init__(self, kernel):
super(Shutdown_Magic, self).__init__(kernel)
def get_parser(self):
parser = argparse.ArgumentParser(prog='%shutdown',
description='''Shutdown or restart specified subkernel''')
parser.add_argument('kernel', nargs='?',
help='''Name of the kernel to be restarted, default to the
current running kernel.''')
parser.add_argument('-r', '--restart', action='store_true',
help='''Restart the kernel''')
parser.error = self._parse_error
return parser
def apply(self, code, silent, store_history, user_expressions, allow_stdin):
options, remaining_code = self.get_magic_and_code(code, False)
parser = self.get_parser()
try:
args = parser.parse_args(shlex.split(options))
except SystemExit:
return
self.shutdown_kernel(
args.kernel if args.kernel else self.sos_kernel, args.restart)
return self.sos_kernel._do_execute(remaining_code, silent, store_history, user_expressions, allow_stdin)
class SoSRun_Magic(SoS_Magic):
name = 'sosrun'
def __init__(self, kernel):
super(SoSRun_Magic, self).__init__(kernel)
def get_parser(self):
parser = argparse.ArgumentParser(prog='%sosrun',
description='''Execute the entire notebook with steps consisting of SoS
cells (cells with SoS kernel) with section header, with specified command
line arguments. Arguments set by magic %set will be appended at the
end of command line''')
parser.error = self._parse_error
return parser
def apply(self, code, silent, store_history, user_expressions, allow_stdin):
options, remaining_code = self.get_magic_and_code(code, False)
old_options = self.sos_kernel.options
self.sos_kernel.options = options + ' ' + self.sos_kernel.options
try:
# %run is executed in its own namespace
old_dict = env.sos_dict
self.sos_kernel._reset_dict()
self.sos_kernel._meta['workflow_mode'] = True
# self.sos_kernel.send_frontend_msg('preview-workflow', self.sos_kernel._meta['workflow'])
if not self.sos_kernel._meta['workflow']:
self.sos_kernel.warn(
'Nothing to execute (notebook workflow is empty).')
else:
self.sos_kernel._do_execute(self.sos_kernel._meta['workflow'], silent,
store_history, user_expressions, allow_stdin)
except Exception as e:
self.sos_kernel.warn(f'Failed to execute workflow: {e}')
raise
finally:
old_dict.quick_update(env.sos_dict._dict)
env.sos_dict = old_dict
self.sos_kernel._meta['workflow_mode'] = False
self.sos_kernel.options = old_options
return self.sos_kernel._do_execute(remaining_code, silent, store_history, user_expressions, allow_stdin)
class SoSSave_Magic(SoS_Magic):
name = 'sossave'
def __init__(self, kernel):
super(SoSSave_Magic, self).__init__(kernel)
def get_parser(self):
parser = argparse.ArgumentParser(prog='%sossave',
description='''Save the jupyter notebook as workflow (consisting of all sos
steps defined in cells starting with section header) or a HTML report to
specified file.''')
parser.add_argument('filename', nargs='?',
help='''Filename of saved report or script. Default to notebookname with file
extension determined by option --to.''')
parser.add_argument('-t', '--to', dest='__to__', choices=['sos', 'html'],
help='''Destination format, default to sos.''')
parser.add_argument('-c', '--commit', action='store_true',
help='''Commit the saved file to git directory using command
git commit FILE''')
parser.add_argument('-a', '--all', action='store_true',
help='''The --all option for sos convert script.ipynb script.sos, which
saves all cells and their metadata to a .sos file, that contains all input
information of the notebook but might not be executable in batch mode.''')
parser.add_argument('-m', '--message',
help='''Message for git commit. Default to "save FILENAME"''')
parser.add_argument('-p', '--push', action='store_true',
help='''Push the commit with command "git push"''')
parser.add_argument('-f', '--force', action='store_true',
help='''If destination file already exists, overwrite it.''')
parser.add_argument('-x', '--set-executable', dest="setx", action='store_true',
help='''Set `executable` permission to saved script.''')
parser.add_argument('--template', default='default-sos-template',
help='''Template to generate HTML output. The default template is a
template defined by configuration key default-sos-template, or
sos-report if such a key does not exist.''')
parser.error = self._parse_error
return parser
def apply(self, code, silent, store_history, user_expressions, allow_stdin):
# get the saved filename
options, remaining_code = self.get_magic_and_code(code, False)
try:
parser = self.get_parser()
try:
args = parser.parse_args(shlex.split(options))
except SystemExit:
return
if args.filename:
filename = args.filename
if filename.lower().endswith('.html'):
if args.__to__ is None:
ftype = 'html'
elif args.__to__ != 'html':
self.sos_kernel.warn(
f'%sossave to an .html file in {args.__to__} format')
ftype = args.__to__
else:
ftype = 'sos'
else:
ftype = args.__to__ if args.__to__ else 'sos'
filename = self.sos_kernel._meta['notebook_name'] + '.' + ftype
filename = os.path.expanduser(filename)
if os.path.isfile(filename) and not args.force:
raise ValueError(
f'Cannot overwrite existing output file {filename}')
# self.sos_kernel.send_frontend_msg('preview-workflow', self.sos_kernel._meta['workflow'])
if ftype == 'sos':
if not args.all:
with open(filename, 'w') as script:
script.write(self.sos_kernel._meta['workflow'])
else:
# convert to sos report
from .converter import notebook_to_script
arg = argparse.Namespace()
arg.execute = False
arg.all = True
notebook_to_script(
self.sos_kernel._meta['notebook_name'] + '.ipynb', filename, args=arg, unknown_args=[])
if args.setx:
import stat
os.chmod(filename, os.stat(
filename).st_mode | stat.S_IEXEC)
else:
# convert to sos report
from .converter import notebook_to_html
arg = argparse.Namespace()
if args.template == 'default-sos-template':
from sos.utils import load_config_files
cfg = load_config_files()
if 'default-sos-template' in cfg:
arg.template = cfg['default-sos-template']
else:
arg.template = 'sos-report'
else:
arg.template = args.template
arg.view = False
arg.execute = False
notebook_to_html(self.sos_kernel._meta['notebook_name'] + '.ipynb',
filename, sargs=arg, unknown_args=[])
self.sos_kernel.send_response(self.sos_kernel.iopub_socket, 'display_data',
{'metadata': {},
'data': {
'text/plain': f'Workflow saved to {filename}\n',
'text/html': HTML(
f'<div | |
255]
R = inst_targets_np[roi_pairs[:, 2], roi_pairs[:, 3]] == inst_id
pos_roi_pairs = roi_pairs[R]
roi_im_res[pos_roi_pairs[:, 3]] = [0, 0, 255] #blue
roi_im_res = roi_im_res.reshape((28, 28, 3))
roi_im = imresize(roi_im_res, (roi_im.shape[1], roi_im.shape[0]))
img_np[y1:y1 + h, x1:x1 + w, :] = roi_im
start_index += prop_num
res.append(img_np)
res.append(img_np_o)
display_images(res, cols=4)
@force_fp32(apply_to=('mask_cluster_pred_1', 'mask_cluster_pred_2', ))
def background_loss(self, pred, target, labels):
loss = self.loss_background(pred, target, torch.zeros_like(labels))
return dict(loss_background = loss)
def _resize_inst_mask(self, inst_mask, mask_size):
inst_mask = imresize(inst_mask, mask_size)
return inst_mask
def _one_mask_target_single(self, gt_masks, inst_ids, mask_size):
inst_ids_nd = inst_ids.cpu().numpy().astype(np.int32)
roi_masks = gt_masks.astype(np.float32)
valid = np.any(roi_masks.reshape((roi_masks.shape[0], -1)), axis=1)
roi_masks = roi_masks[valid]
mask_roi_inst_ids = inst_ids_nd[valid]
inst_number = inst_ids_nd.shape[0]
bg_mask = np.equal(np.any(roi_masks, axis=0), np.zeros((roi_masks.shape[1], roi_masks.shape[2]))).astype(np.float32)
bg_target = imresize(bg_mask, mask_size)
size_list = [mask_size for _ in range(valid.sum())]
mask_target = map(self._resize_inst_mask, (roi_masks).astype(np.float32) , size_list)
mask_target = list(mask_target)
#First should be zero
mask_roi_inst_ids = np.concatenate((np.zeros(1, dtype=np.uint16), mask_roi_inst_ids))
mask_target = [np.zeros([mask_size[1], mask_size[0]], dtype=np.float64)] + mask_target
mask_target = np.stack(mask_target)
score_map = np.max(mask_target, axis=0)
score_map = score_map * (1 + (inst_number/10))
su = np.sum(mask_target, axis=0)
mask_target[:, su>1.1] = 0
mask_target = np.argmax(mask_target, axis=0)
mask_target = mask_roi_inst_ids[mask_target]
mask_target = mask_target.flatten()
score_map = score_map.flatten()
bg_mask_targets = torch.from_numpy(np.stack([bg_target])).float().to(
inst_ids.device)
inst_mask_targets_tensor = torch.from_numpy(np.stack([mask_target])).float().to(
inst_ids.device)
return bg_mask_targets, inst_mask_targets_tensor
def get_one_target(self, gt_masks, inst_ids, mask_sizes):
"""Compute target of mask cluster.
M
"""
bg_mask, inst_mask = multi_apply(self._one_mask_target_single,
gt_masks, inst_ids, mask_sizes)
bg_mask_targets = torch.cat(list(bg_mask))
inst_mask_targets = inst_mask
return bg_mask_targets, inst_mask_targets
def _mask_target_single(self, pos_proposals, pos_assigned_gt_inds, gt_masks, inst_ids, cfg):
mask_size = cfg.mask_size
num_pos = pos_proposals.size(0)
bg_mask_targets = []
inst_mask_targets = []
inst_mask_scores = []
inst_roi_targets = []
inst_roi_scores = []
if num_pos > 0:
pos_proposals_nd = pos_proposals.cpu().numpy().astype(np.int32)
inst_ids_nd = inst_ids.cpu().numpy().astype(np.int32)
pos_assigned_gt_inds = pos_assigned_gt_inds.cpu().numpy()
roi_inst_ids = inst_ids_nd[pos_assigned_gt_inds]
#inst_sizes = gt_masks.reshape(gt_masks.shape[0], -1).sum(axis=1).argsort()
#gt_masks = gt_masks[inst_sizes]
#inst_ids_nd = inst_ids_nd[inst_sizes]
for i in range(num_pos):
bbox = pos_proposals_nd[i, :]
x1, y1, x2, y2 = bbox
w = np.maximum(x2 - x1 + 1, 1)
h = np.maximum(y2 - y1 + 1, 1)
# mask is uint8 both before and after resizing
roi_masks = gt_masks[:, y1:y1 + h, x1:x1 + w].astype(np.float32)
valid = np.any(roi_masks.reshape((roi_masks.shape[0], -1)), axis=1)
roi_masks = roi_masks[valid]
mask_roi_inst_ids = inst_ids_nd[valid]
inst_number = inst_ids_nd.shape[0]
bg_mask = np.equal(np.any(roi_masks, axis=0), np.zeros((roi_masks.shape[1], roi_masks.shape[2]))).astype(np.float32)
bg_target = imresize(bg_mask,
(mask_size, mask_size))
bg_mask_targets.append(bg_target)
size_list = [(mask_size, mask_size) for _ in range(valid.sum())]
mask_target = map(self._resize_inst_mask, (roi_masks).astype(np.float32) , size_list)
mask_target = list(mask_target)
#First should be zero
mask_roi_inst_ids = np.concatenate((np.zeros(1, dtype=np.uint16), mask_roi_inst_ids))
mask_target = [np.zeros([mask_size, mask_size], dtype=np.float64)] + mask_target
mask_target = np.stack(mask_target)
score_map = np.max(mask_target, axis=0)
score_map = score_map * (1 + (inst_number/10))
su = np.sum(mask_target, axis=0)
mask_target[:, su>1.1] = 0
mask_target = np.argmax(mask_target, axis=0)
mask_target = mask_roi_inst_ids[mask_target]
mask_target = mask_target.flatten()
score_map = score_map.flatten()
roi_inst_id = roi_inst_ids[i]
inst_roi_targets.append(np.array([roi_inst_id]))
inst_roi_scores.append(np.array([cfg.roi_cluster_score]))
inst_mask_targets.append(mask_target)
inst_mask_scores.append(score_map)
bg_mask_targets = torch.from_numpy(np.stack(bg_mask_targets)).float().to(
pos_proposals.device)
inst_mask_targets_tensor = torch.from_numpy(np.stack(inst_mask_targets)).float().to(
pos_proposals.device)
inst_mask_scores_tensor = torch.from_numpy(np.stack(inst_mask_scores)).float().to(
pos_proposals.device)
inst_roi_targets_tensor = torch.from_numpy(np.stack(inst_roi_targets)).float().to(
pos_proposals.device)
inst_roi_scores_tensor = torch.from_numpy(np.stack(inst_roi_scores)).float().to(
pos_proposals.device)
else:
bg_mask_targets = pos_proposals.new_zeros((0, mask_size, mask_size))
inst_mask_targets_tensor = pos_proposals.new_zeros((0, mask_size * mask_size ))
inst_mask_scores_tensor = pos_proposals.new_zeros((0, mask_size * mask_size))
inst_roi_targets_tensor = pos_proposals.new_zeros((0, 1))
inst_roi_scores_tensor = pos_proposals.new_zeros((0, 1))
return bg_mask_targets, inst_mask_targets_tensor, inst_mask_scores_tensor, inst_roi_targets_tensor, inst_roi_scores_tensor
def get_target(self, sampling_results, gt_masks, inst_ids,
rcnn_train_cfg):
"""Compute target of mask cluster.
Mask IoU target is the IoU of the predicted mask (inside a bbox) and
the gt mask of corresponding gt mask (the whole instance).
The intersection area is computed inside the bbox, and the gt mask area
is computed with two steps, firstly we compute the gt area inside the
bbox, then divide it by the area ratio of gt area inside the bbox and
the gt area of the whole instance.
Args:
sampling_results (list[:obj:`SamplingResult`]): sampling results.
gt_masks (list[ndarray]): Gt masks (the whole instance) of each
image, binary maps with the same shape of the input image.
mask_targets (Tensor): Gt mask of each positive proposal,
binary map of the shape (num_pos, h, w).
rcnn_train_cfg (dict): Training config for R-CNN part.
Returns:
Tensor: mask iou target (length == num positive).
"""
pos_proposals = [res.pos_bboxes for res in sampling_results]
pos_assigned_gt_ind_list = [res.pos_assigned_gt_inds for res in sampling_results]
cfg_list = [rcnn_train_cfg for _ in range(len(pos_proposals))]
bg_mask, inst_mask, inst_mask_scores, inst_roi, inst_roi_scores = multi_apply(self._mask_target_single,
pos_proposals, pos_assigned_gt_ind_list,
gt_masks, inst_ids, cfg_list)
bg_mask_targets = torch.cat(list(bg_mask))
inst_mask_targets = inst_mask
inst_mask_scores = inst_mask_scores
inst_roi_targets = inst_roi
inst_roi_scores = inst_roi_scores
return bg_mask_targets, inst_mask_targets, inst_mask_scores, inst_roi_targets, inst_roi_scores
def _roi_mask_target_single(self, pos_proposals, pos_assigned_gt_inds, gt_masks, inst_ids, mask_cluster_preds, cfg):
mask_size = cfg.mask_size
num_pos = pos_proposals.size(0)
inst_roi_targets = []
roi_indeces = []
cluster_indeces = []
ext_assigned_gt_inds = []
if num_pos > 0:
pos_proposals_nd = pos_proposals.cpu().numpy().astype(np.int32)
mask_cluster_preds_nd = mask_cluster_preds.detach().cpu().numpy()
inst_ids_nd = inst_ids.cpu().numpy().astype(np.int32)
pos_assigned_gt_inds = pos_assigned_gt_inds.cpu().numpy()
roi_inst_ids = inst_ids_nd[pos_assigned_gt_inds]
mask_sizes = gt_masks.sum(-1).sum(-1)
for i in range(num_pos):
roi_mask_cluster_preds = mask_cluster_preds_nd[i]
roi_inst_id = roi_inst_ids[i]
bbox = pos_proposals_nd[i, :]
x1, y1, x2, y2 = bbox
w = np.maximum(x2 - x1 + 1, 1)
h = np.maximum(y2 - y1 + 1, 1)
# mask is uint8 both before and after resizing
assigned_gt_ind = pos_assigned_gt_inds[i]
roi_masks = gt_masks[:, y1:y1 + h, x1:x1 + w].astype(np.float32)
roi_mask_sizes = roi_masks.sum(-1).sum(-1)
mask_in_roi = roi_mask_sizes / mask_sizes
other_mask_in_roi_inds = np.where(mask_in_roi>.5)[0]
other_mask_in_roi_inds = other_mask_in_roi_inds[other_mask_in_roi_inds!=assigned_gt_ind]
other_mask_in_roi_ids = inst_ids_nd[other_mask_in_roi_inds]
valid = np.any(roi_masks.reshape((roi_masks.shape[0], -1)), axis=1)
roi_masks = roi_masks[valid]
mask_roi_inst_ids = inst_ids_nd[valid]
inst_number = inst_ids_nd.shape[0]
size_list = [(mask_size, mask_size) for _ in range(valid.sum())]
mask_target = map(self._resize_inst_mask, (roi_masks).astype(np.float32) , size_list)
mask_target = list(mask_target)
#First should be zero
mask_roi_inst_ids = np.concatenate((np.zeros(1, dtype=np.uint16), mask_roi_inst_ids))
mask_target = [np.zeros([mask_size, mask_size], dtype=np.float64)] + mask_target
mask_target = np.stack(mask_target)
score_map = np.max(mask_target, axis=0)
score_map = score_map * (1 + (inst_number/10))
mask_target = np.argmax(mask_target, axis=0)
mask_target = mask_roi_inst_ids[mask_target]
for c in np.concatenate(([roi_inst_id], other_mask_in_roi_ids)):
sum_map = roi_mask_cluster_preds.transpose(1, 2, 0)[mask_target==roi_inst_id]
sums = np.sum(sum_map, axis=0)
choosen_cluster = np.argmax(sums[1:]) + 1
inst_roi_targets.append(np.array([roi_inst_id]))
roi_indeces.append(i)
cluster_indeces.append(choosen_cluster)
ext_assigned_gt_inds.append(assigned_gt_ind)
inst_roi_targets_tensor = torch.from_numpy(np.stack(inst_roi_targets)).float().to(
pos_proposals.device)
roi_indeces_tensor = torch.from_numpy(np.stack(roi_indeces)).to(
pos_proposals.device)
cluster_indeces_tensor = torch.from_numpy(np.stack(cluster_indeces)).to(
pos_proposals.device)
ext_assigned_gt_inds_tensor = torch.from_numpy(np.stack(ext_assigned_gt_inds)).to(
pos_proposals.device)
else:
inst_roi_targets_tensor = pos_proposals.new_zeros((0, 1))
roi_indeces_tensor = pos_proposals.new_zeros((0, 1))
cluster_indeces_tensor = pos_proposals.new_zeros((0, 1))
ext_assigned_gt_inds_tensor = pos_proposals.new_zeros((0, 1))
return inst_roi_targets_tensor, roi_indeces_tensor, cluster_indeces_tensor, ext_assigned_gt_inds_tensor
def get_roi_mask_target(self, sampling_results, gt_masks, inst_ids, mask_cluster_preds, rcnn_train_cfg):
pos_proposals = [res.pos_bboxes for res in sampling_results]
pos_assigned_gt_ind_list = [res.pos_assigned_gt_inds for res in sampling_results]
cfg_list = [rcnn_train_cfg for _ in range(len(pos_proposals))]
inst_roi, roi_indeces, cluster_indeces, assigned_gt_inds = multi_apply(self._roi_mask_target_single,
pos_proposals, pos_assigned_gt_ind_list,
gt_masks, inst_ids, mask_cluster_preds, cfg_list)
return inst_roi, roi_indeces, cluster_indeces, assigned_gt_inds
def _roi_target_single(self, pos_assigned_gt_inds, inst_ids):
return inst_ids[pos_assigned_gt_inds].view(-1, 1)
def get_roi_target(self, pos_assigned_gt_inds, inst_ids):
inst_roi = map(self._roi_target_single, pos_assigned_gt_inds, inst_ids)
return inst_roi
def _roi_distance(self, boxes1, boxes2, im_size, max_num_instances=100):
"""Computes distance between two sets of boxes.
boxes1, boxes2: [N, (y1, x1, y2, x2)].
"""
# 1. Tile boxes2 and repeat boxes1. This allows us to compare
# every boxes1 against every boxes2 without loops.
b1_size = boxes1.size()
b2_size = boxes2.size()
b1 = boxes1.repeat(1, b2_size[0]).view(-1, 4)
b2 = boxes2.repeat(b1_size[0], 1)
b1_y1, b1_x1, b1_y2, b1_x2 = torch.split(b1, 1, dim=-1)
b2_y1, b2_x1, b2_y2, b2_x2 = torch.split(b2, 1, dim=-1)
y1 = torch.max(b1_y1, b2_y1)
x1 = torch.max(b1_x1, b2_x1)
y2 = torch.min(b1_y2, b2_y2)
x2 = torch.min(b1_x2, b2_x2)
dy = torch.max(y1 - y2, torch.zeros_like(y1))
dx = torch.max(x1 - x2, torch.zeros_like(x1))
dqrt = dx * dx + dy * dy
dqrt = dqrt.view(b1_size[0], b2_size[0])
distances = torch.sqrt(dqrt.float())
distances = distances / im_size
bbox_rank_0 = torch.argsort(torch.argsort(distances, dim=0), dim=0)
bbox_rank_1 = torch.argsort(torch.argsort(distances, dim=1), dim=1)
xtr_dist = torch.ones_like(distances) *10
distances = torch.where(bbox_rank_0 <= (max_num_instances-1), distances, xtr_dist)
distances = torch.where(bbox_rank_1 <= (max_num_instances-1), distances, xtr_dist)
return distances
def _sample_instances(self, inst_mask_targets, num_samples, roi_cluster):
sampled_idx = np.ones((inst_mask_targets.shape[0], num_samples, 2), dtype=int) * -1
for i in range(inst_mask_targets.shape[0]):
whr_x = np.where(inst_mask_targets[i]>0)[0]
if(len(whr_x)>0):
sampled_perm = np.random.permutation(len(whr_x))
sampled_perm = sampled_perm[:num_samples]
whr_x = whr_x[sampled_perm]
sampled_idx[i, :len(whr_x), 0] = i
sampled_idx[i, :len(whr_x), 1] = whr_x
return sampled_idx
def _get_pairs_single(self, pos_assigned_gt_ind,
inst_mask_targets,
gt_bboxes,
im_size, roi_cluster):
sample = self._sample_instances(inst_mask_targets.cpu().numpy(), self.num_samples, roi_cluster)
bbox_distance = self._roi_distance(gt_bboxes, gt_bboxes, im_size, self.num_instances)
bbox_distance = bbox_distance.cpu().numpy()
pos_assigned_gt_ind = pos_assigned_gt_ind.cpu().numpy()
roi_distance = bbox_distance[pos_assigned_gt_ind, :][:, pos_assigned_gt_ind] #TODO can be swapped
roi_idx_1, roi_idx_2 = np.where(roi_distance<=self.max_distance)
mask_pair_idx = np.hstack([sample[roi_idx_1].reshape(-1, 2), sample[roi_idx_2].reshape(-1, 2)])
| |
They’ve concluded that the
assassin was—well, was named Wheeler—and they’re only concerned to
discover the first name. Forgive my plain speaking, but to save yourself
and the other two, we must be outspoken.”
“Yes, yes—pray don’t hesitate to say anything you think. I am in a
terrible position, Mr. Keefe—more terrible than you can know, and while I
am willing to make any sacrifice for my dear ones—it may be in vain——”
The two men had been alone in the den, but now were joined by Burdon and
young Allen.
“Glad to see you back, Mr. Keefe,” Burdon said; “usually we detectives
don’t hanker after outside help, but you’ve a good, keen mind, and I
notice you generally put your finger on the right spot.”
“All right, Burdon, we’ll work together. Now, Mr. Wheeler, I’m going to
ask you to leave us—for there are some details to discuss——”
<NAME> was only too glad to be excused, and with a sigh of relief he
went away to his upstairs quarters.
“Now, it’s this way,” Keefe began; “I’ve been sounding Mr. Wheeler, but I
didn’t get any real satisfaction. But here’s a point. Either he did or
didn’t kill <NAME>, but in either case, he’s in bad.”
“What do you mean?” asked Allen.
“Why, I’ve inquired about among the servants and, adding our own
testimony, I’ve figured it out that <NAME> was either the murderer
or he was over the line on the other side of the house, and in that case
has broken his parole and is subject to the law.”
“How do you prove that?” inquired Burdon, interestedly.
“By the story of <NAME>, who says her father was not in the den at
all at the time <NAME> was shot. Now, as we know, <NAME> ran
downstairs at that time, and she, too, says her husband was not in the
den. Also she says he was not in the living-room, nor in the hall. This
leaves only her own sitting-room, from which Mr. Wheeler could see the
fire and into which he was most likely to go for that purpose.”
“He wouldn’t go in that room for any purpose,” declared Allen.
“Not ordinarily, but in the excitement of a fire, men can scarcely
refrain from running to look at it, and if he was not in the places he
had a right to be, he must have been over on the forbidden ground. So, it
comes back to this: either <NAME> was the murderer, and his wife and
daughter have perjured themselves to save him, or he was in a place
which, by virtue of the conditions, cancels his pardon. This, I take it,
explains Mr. Wheeler’s present perturbed state of mind—for he is
bewildered and worried in many ways.”
“Well,” said Allen, “where does all this lead us?”
“It leads us,” Keefe returned, “to the necessity of a lot of hard work.
I’m willing to go on record as desiring to find a criminal outside of the
Wheeler family. Or to put it bluntly, I want to acquit all three of
them—even if——”
“Even if one of them is guilty?” said Burdon.
“Well, yes—just that. But, of course I don’t mean to hang an innocent
man! What I want is to get a verdict for persons unknown.”
“I’m with you,” said Allen. “It’s all wrong, I know, but—well, I can’t
believe any of the Wheelers really did it.”
“You do believe it, though!” Keefe turned on him, sharply. “And what’s
more, you believe the criminal is the one of the three whom you least
want it to be!”
Keefe’s meaning was unmistakable, and Allen’s flushed and crestfallen
face betrayed his unwilling assent. Unable to retort—even unable to
speak, he quickly left the room.
Keefe closed the door and turned to Burdon.
“That was a test,” he said; “I’m not sure whether Allen suspects Miss
Wheeler—or not——”
“He sure acts as if he does,” Burdon said, his face drawn with
perplexity. “But, I say, Mr. Keefe, haven’t you ever thought it might
have been <NAME> himself?”
“Who did the shooting?”
“Yes; he had all the motives the others had——”
“But not opportunity. Why, he was at the garage fire—where I was——”
“Yes, but he might have got away long enough for——”
“Nonsense, man, nothing of the sort! We were together, fighting the
flames. The two chauffeurs were with us—the Wheelers’ man, and Mr.
Appleby’s. We used those chemical extinguishers——”
“I know all that—but then—he might have slipped away, and in the
excitement you didn’t notice——”
“Not a chance! No, take my word for it, the three Wheelers are the
exclusive suspects—unless we can work in that bugler individual.”
“It’s too many for me,” Burdon sighed. “And Hallen, he’s at his wit’s
end. But you’re clever at such things, sir, and Mr. Appleby, he’s going
to get a big detective from the city.”
“You don’t seem to mind being discarded!”
“No, sir. If anybody’s to fasten a crime on one of those Wheelers, I
don’t want to be the one to do it.”
“Look here, Burdon, how about Wheeler’s doing it in self-defence? I know
a lot about those two men, and Appleby was just as much interested in
getting Wheeler out of his way as _vice versa_. If Appleby attacked and
Wheeler defended, we can get him off easy.”
“Maybe so, but it’s all speculation, Mr. Keefe. What we ought to get is
evidence—testimony—and that’s hard, for the only people to ask about it
are——”
“Are the criminals themselves.”
“The suspected criminals—yes, sir.”
“There are others. Have you quizzed all the servants?”
“I don’t take much stock in servants’ stories.”
“You’re wrong there, my man. That principle is a good one in ordinary
matters, but when it comes to a murder case, a servant’s testimony is as
good as his master’s.”
Burdon made no direct response to Keefe’s suggestion, but he mulled it
over in his slow-going mind, and as a result, he had a talk with Rachel,
who was ladies’ maid to both Maida and her mother.
The girl bridled a little when Burdon began to question her.
“Nobody seemed to think it worth while to ask me anything,” she said, “so
I held my tongue. But if so be you want information, you ask and I’ll
answer.”
“I doubt if she really knows anything,” Burdon thought to himself,
judging from her air of self-importance, but he said:
“Tell me anything you know of the circumstances at the time of the
murder.”
“Circumstances?” repeated Rachel, wrinkling her brow.
“Yes; for instance, where was <NAME> when you heard the shot?”
“I didn’t say I heard the shot.”
“Didn’t you?”
“Yes.”
“Go on, then; don’t be foolish, or you’ll be sorry for it!”
“Well, then, <NAME> was downstairs—she had just left her room——”
“Here, let me get this story straight. How long had she been in her room?
Were you there with her?”
“Yes; we had been there half an hour or so. Then, we heard noise and
excitement and a cry of fire. <NAME> rushed out of her room and ran
downstairs—and I followed, naturally.”
“Yes; and what did you see?”
“Nothing special—I saw a blaze of light, through the front door——”
“The north door?”
“Of course—the one toward the garage—and I saw the garage was on fire, so
I thought of nothing else—then.”
“Then? What did you think of later?”
“I remembered that I saw <NAME> in the living-room—in the north end
of it—where he never goes——”
“You know about his restrictions?”
“Oh, yes, sir. The servants all know—we have to. Well, it was natural,
poor man, that he should go to look at the fire!”
“You’re sure of this, Rachel?”
“Sure, yes; but don’t let’s tell, for it might get the master in
trouble.”
“On the contrary it may get him out of trouble. To break his parole is
not as serious a crime as murder. And if he was in the north end of the
living-room he couldn’t have been in the den shooting Mr. Appleby.”
“That’s true enough. And neither could Mrs. Wheeler have done it.”
“Why not?”
“Well—that is—she was right ahead of me——”
“Did you keep her in sight?”
“No; I was so excited myself, I ran past her and out to the garage.”
“Who was there?”
“Mr. Allen and Mr. Keefe and the two chauffeurs and the head gardener and
well, most all the servants. The men were fighting the fire, and the
women were standing back, looking on.”
“Yelling, I suppose.”
“No; they were mostly | |
longitude labels. This adjustment itself should of been set when
the class was initialized pre-scaled such that it an offset on a 1/2 degree grid scale.
"""
return self.longitude_offset_adjustment
def extend_mask_to_neighbours(self,changes_mask):
"""Extend a mask on this grid to include neighbouring points
Arguments:
changes_mask: numpy 2d array of boolean value; the mask to be extended
Return:
The extended mask as a numpy 2d array of boolean values
Extends the mask using the binary erosion method from the morophology class of
numpy's image processing module. The copies of the first and last column are
inserted into the position after the last column and before the first column
respectively to wrap the calculation around the globe. The borders at the poles
assume the mask to be true and any cross pole neighbours are ignore in this
calculation.
"""
#For an unknown reason insert only works as required if the array axis are
#swapped so axis 0 is being inserted into.
changes_mask = changes_mask.swapaxes(0,1)
changes_mask = np.insert(changes_mask,obj=(0,np.size(changes_mask,axis=0)),
values=(changes_mask[-1,:],changes_mask[0,:]),
axis=0)
changes_mask = changes_mask.swapaxes(0,1)
#binary_erosion has a keyword mask that is nothing to do with the mask we are
#manipulating; its value defaults to None but set this explicitly for clarity
return ndi.morphology.binary_erosion(changes_mask,
structure=ndi.generate_binary_structure(2,2),
iterations=1,
mask=None,
border_value=1)[:,1:-1]
def flow_direction_kernel(self,orog_section):
"""Find flow direction a single grid point
Arguements:
orog_section: a flatten 1d array-like object; a 3 by 3 square of orography centre on
the grid point under consideration flattened into a 1d array
Returns:
A flow direction (which will take an integer value) as a numpy float 64 (for technical
reasons)
Takes coordinate of the minimum of the orography section (the first minimum if several
point equal minima exist) and uses it to look up a flow direction. If this grid cell itself
is also a minima then assign the flow to it (diretion 5; min_coord=4) instead of the first
minimum found.
"""
#Only the first minimum is found by argmin. Thus it will be this that
#is assigned as minima if two points have the same height
min_coord = np.argmin(orog_section)
if orog_section[4] == np.amin(orog_section):
min_coord = 4
return self.flow_direction_labels[min_coord]
def compute_flow_directions(self,data,use_fortran_kernel=True):
"""Compute the flow direction for a given orograpy
Arguments:
data: numpy array-like object; the orography to compute the flow direction for
use_fortran_kernel: boolean: a flag to choose between using a python kernel (False)
or using a Fortran kernel (True)
Returns:
A numpy array of flow directions as integers
Inserts extra rows to ensure there is no cross pole flow; then flip the field to get the same first
minima as Stefan uses for easy comparison. Setup the kernel function to use depending on the input
flag. Then run a generic filter from the numpy image processing module that considers the 3 by 3
area around each grid cell; wrapping around the globe in the east-west direction. Return the output
as an integer after flipping it back the right way up and removing the extra rows added at the top
and bottom
"""
#insert extra rows across the top and bottom of the grid to ensure correct
#treatmen of boundaries
data = np.insert(data,obj=(0,np.size(data,axis=0)),values=self.pole_boundary_condition, axis=0)
#processing the data upside down to ensure that the handling of the case where two neighbours
#have exactly the same height matches that of Stefan's scripts
data = np.flipud(data)
if use_fortran_kernel:
f2py_mngr = f2py_mg.f2py_manager(path.join(fortran_source_path,
'mod_grid_flow_direction_kernels.f90'),
func_name='HDgrid_fdir_kernel')
flow_direction_kernel = f2py_mngr.run_current_function_or_subroutine
else:
flow_direction_kernel = self.flow_direction_kernel
flow_directions_as_float = ndi.generic_filter(data,
flow_direction_kernel,
size=(3,3),
mode = 'wrap')
flow_directions_as_float = np.flipud(flow_directions_as_float)
return flow_directions_as_float[1:-1].astype(int)
def get_number_of_masked_neighbors(self,data):
"""Compute the number of neighbors that are masked of each masked cell"""
#insert extra rows across the top and bottom of the grid to ensure correct
#treatmen of boundaries
data = np.insert(data,obj=(0,np.size(data,axis=0)),values=False, axis=0)
f2py_mngr = f2py_mg.f2py_manager(path.join(fortran_source_path,
'mod_grid_m_nbrs_kernels.f90'),
func_name='HDgrid_masked_nbrs_kernel')
nbrs_kernel = f2py_mngr.run_current_function_or_subroutine
nbrs_num = ndi.generic_filter(data.astype(np.float64),
nbrs_kernel,
size=(3,3),
mode = 'wrap')
return nbrs_num[1:-1].astype(int)
def get_grid_dimensions(self):
"""Get the dimension of the grid and return them as a tuple"""
return (self.nlat,self.nlong)
def set_grid_dimensions(self,dimensions):
self.nlat,self.nlong = dimensions
def get_sea_point_flow_direction_value(self):
"""Get the sea point flow direction value"""
return self.sea_point_flow_direction_value
def mask_insignificant_gradient_changes(self,gradient_changes,old_gradients,
gc_method=default_gc_method,**kwargs):
"""Mask insignicant gradient changes using a keyword selected method
Arguments:
gradient_changes: numpy array; a numpy array with gradient changes in 8 direction from
each grid cell plus flow to self gradient changes set to zero to make 9 elements
per grid cell in an order matching the river flow direction 1-9 compass rose keypad
labelling scheme. Thus this should be 9 by nlat by nlong sized numpy array.
old_gradients: numpy array; the gradients from the base orography in the same format as
the gradient changes
gc_method: str; a keyword specifying which method to use to mask insignificant gradient
changes
**kwargs: keyword dictionary; keyword parameter to pass to the selected gradient change
masking method
Returns: the masked gradient changes returned by the selected method
The methods selected should be from a helper class called
LatLongGridGradientChangeMaskingHelper where all such methods should be stored in order
to keep the main LatLongGrid class from becoming too cluttered. The gradient changes,
old_gradient and **kwargs (except for gc_method) will be passed onto the selected
method.
"""
return self.gc_methods[gc_method](gradient_changes,old_gradients,**kwargs)
def calculate_gradients(self,orography):
"""Calculate the (pseudo) gradients between neighbouring cells from an orography
Arguments:
orography: numpy array; an array contain the orography data to calculate gradients for
Returns:
A numpy array that consists of the gradient from each point in all 8 directions (plus
zero for the gradient to self). Thus the array has 1 more dimension than the input
orography (i.e. 2+1 = 3 dimensions); the length of this extra dimension is 9 for
a 9 by nlong by nlat array. The order of the 9 different kinds of gradient change for
each grid point matches the 1-9 keypad compass rose numbering used to denote flow
directions
First adds extra columns to the start/end of the input orography that are equal to the
last/first row respectively; thus allowing gradients that wrap in the longitudal direction
to be calculated. Then calculate arrays of the edge differences using numpy's diff method.
Calculate the corner differences by overlaying two offset version of the same orography
field. Return all these gradients array stacked up to form the final array; inserting
extra rows of zeros where no gradient exists as it would go over the pole (over the
pole gradients are set to zero) and trimming off one (or where necessary both) of the
extra columns added to facilitate wrapping. Notice the gradients calculated are actually
just the differences between neighbouring cells and don't take into account the distances
between the point at which the gradient is defined; if this point was the cell centre then
the gradients would need to calculated different for diagonal neighbours from the direct
(NESW) neighbours.
"""
#should be equal to nlat and nlong but redefining here allows for
#easy testing of this method isolation
naxis0 = np.size(orography,axis=0)
naxis1 = np.size(orography,axis=1)
#For an unknown reason insert only works as required if the array axis are
#swapped so axis 0 is being inserted into.
orography = orography.swapaxes(0,1)
orography = np.insert(orography,obj=(0,np.size(orography,axis=0)),
values=(orography[-1,:],orography[0,:]),
axis=0)
orography = orography.swapaxes(0,1)
edge_differences_zeroth_axis = np.diff(orography,n=1,axis=0)
edge_differences_first_axis = np.diff(orography,n=1,axis=1)
corner_differences_pp_mm_indices = orography[1:,1:] - orography[:-1,:-1]
corner_differences_pm_mp_indices = orography[1:,:-1] - orography[:-1,1:]
#To simplify later calculations allow two copies of each gradient thus
#allow us to associate set of gradients to each grid cell, note the
#use of naxisx-0 instead of naxis0 to add to the final row because the
#individual gradient arrays have all be reduced in size along the relevant
#axis by 1.
return np.stack([
#keypad direction 1
#extra row added to end of zeroth axis; an extra column is not
#required due to wrapping
np.insert(corner_differences_pm_mp_indices[:,:-1],obj=naxis0-1,
values=0,axis=0),
#keypad direction 2
#extra row added to end of zeroth axis
np.insert(edge_differences_zeroth_axis[:,1:-1],obj=naxis0-1,values=0,
axis=0),
#keypad direction 3
#extra row added to end of zeroth axis; an extra column is not
#required due to wrapping
np.insert(corner_differences_pp_mm_indices[:,1:],obj=naxis0-1,
values=0,axis=0),
#keypad direction 4
#extra | |
<filename>src/ElectronicTransformer/etk_callback.py
# -*- coding: utf-8 -*-
#
# copyright 2021, ANSYS Inc. Software is released under GNU license
#
# Replacement of old ETK (Electronic Transformer Kit) for Maxwell
#
# ACT Written by : <NAME> (<EMAIL>)
# Tested by: <NAME> (<EMAIL>)
# Last updated : 11.03.2021
import copy
import datetime
import json
import os
import re
import shutil
import sys
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
from webbrowser import open as webopen
# all below imports are done via appending sys path due to ACT import limitations
root_folder = os.path.abspath(os.path.dirname(__file__))
sys.path.append(root_folder)
from cores_geometry import ECore, EFDCore, EICore, EPCore, ETDCore, PCore, PQCore, UCore, UICore, RMCore
from circuit import Circuit
try:
a = ExtAPI # will work only when running from ACT
from value_checker import check_core_dimensions
from forms import WindingForm, ConnectionForm
except NameError:
pass
# object to save UI settings that are cross shared between classes
transformer_definition = OrderedDict()
def atoi(letter):
return int(letter) if letter.isdigit() else letter
def natural_keys(text):
return [atoi(c) for c in re.split(r'(\d+)', text)]
def setup_button(step, comp_name, caption, position, callback, active=True, style=None):
# Setup a button
update_btn_session = step.UserInterface.GetComponent(comp_name) # get component name from XML
update_btn_session.AddButton(comp_name, caption, position, active) # add button caption and position
update_btn_session.ButtonClicked += callback # connect to callback function
if style == "blue":
# change CSS properties of the button to change it's color
update_btn_session.AddCSSProperty("background-color", "#3383ff", "button")
update_btn_session.AddCSSProperty("color", "white", "button")
def help_button_clicked(_sender, _args):
"""when user clicks Help button HTML page will be opened in standard web browser"""
webopen(str(ExtAPI.Extension.InstallDir) + '/help/help.html')
def update_ui(step):
"""Refresh UI data """
step.UserInterface.GetComponent("Properties").UpdateData()
step.UserInterface.GetComponent("Properties").Refresh()
def add_info_message(msg):
oDesktop.AddMessage("", "", 0, "ACT:" + str(msg))
def add_warning_message(msg):
oDesktop.AddMessage("", "", 1, "ACT:" + str(msg))
def add_error_message(msg):
oDesktop.AddMessage("", "", 2, "ACT:" + str(msg))
def verify_input_data(function):
"""
Check that all input data is present in JSON file for each step
:param function: function to populate ui
:return: None
"""
def check(*args):
try:
function(*args)
except ValueError:
msg = "Please verify that integer numbers in input file have proper format eg 1 and not 1.0"
return add_error_message(msg)
except KeyError as e:
return add_error_message("Please specify parameter:{} in input file".format(e))
return check
class Step1(object):
__metaclass__ = ABCMeta
def __init__(self, step):
self.step1 = step.Wizard.Steps["step1"]
# create all objects for UI
self.segmentation_angle = self.step1.Properties["core_properties/segmentation_angle"]
self.supplier = self.step1.Properties["core_properties/supplier"]
self.core_type = self.step1.Properties["core_properties/core_type"]
self.core_model = self.step1.Properties["core_properties/core_type/core_model"]
self.core_dimensions = {
"D_1": self.step1.Properties["core_properties/core_type/D_1"],
"D_2": self.step1.Properties["core_properties/core_type/D_2"],
"D_3": self.step1.Properties["core_properties/core_type/D_3"],
"D_4": self.step1.Properties["core_properties/core_type/D_4"],
"D_5": self.step1.Properties["core_properties/core_type/D_5"],
"D_6": self.step1.Properties["core_properties/core_type/D_6"],
"D_7": self.step1.Properties["core_properties/core_type/D_7"],
"D_8": self.step1.Properties["core_properties/core_type/D_8"]
}
self.define_airgap = self.step1.Properties["core_properties/define_airgap"]
self.airgap_value = self.step1.Properties["core_properties/define_airgap/airgap_value"]
self.airgap_on_leg = self.step1.Properties["core_properties/define_airgap/airgap_on_leg"]
self.core_models = []
self.cores_database = {}
self.personal_lib_path = ""
def github(self, _sender, _args):
"""
opens GitHub page with project
"""
webopen(r"https://github.com/beliaev-maksim/ansys-electronic-transformer-act")
def open_custom_lib(self, _sender, _args):
"""
Opens folder with custom library definitions
"""
os.startfile(self.personal_lib_path)
def open_examples(self, _sender, _args):
"""
Opens read data method in folder with examples
"""
examples_folder = os.path.join(ExtAPI.Extension.InstallDir, "examples").replace("/", "\\")
self.read_data(_sender, _args, default_path=examples_folder, ext_filter="*.jpg")
def read_data(self, _sender, _args, default_path="", ext_filter=""):
"""
Function called when click button Read Settings From File. Parse json file with settings and dump them to
transformer definition object
:param default_path: path to the folder that should be opened
:param ext_filter: additional filter for file types
:param _sender: unused standard event
:param _args: unused standard event
:return: None
"""
global transformer_definition
file_filter = 'Input Files(*.json;{0})|*.json;{0}'.format(ext_filter)
path = ExtAPI.UserInterface.UIRenderer.ShowFileOpenDialog(file_filter, default_path)
if path is None:
return
if path.endswith(".jpg"):
webopen(path)
path = path.replace(".jpg", ".json")
if not os.path.isfile(path):
add_error_message("Input File does not exist: " + path)
with open(path, "r") as input_f:
try:
transformer_definition = json.load(input_f, object_pairs_hook=OrderedDict)
except ValueError as e:
match_line = re.match("Expecting object: line (.*) column", str(e))
if match_line:
add_error_message(
'Please verify that all data in file is covered by double quotes "" ' +
'(integers and floats can be both covered or uncovered)')
else:
match_line = re.match("Expecting property name: line (.*) column", str(e))
if match_line:
add_error_message("Please verify that there is no empty argument in the file. "
"Cannot be two commas in a row without argument in between")
else:
# so smth unexpected
return add_error_message(e)
return add_error_message("Please correct following line: {} in file: {}".format(
match_line.group(1), path))
self.populate_ui_data_step1()
def refresh_step1(self):
"""create buttons and HTML data for first step"""
setup_button(self.step1, "read_data_button", "Read Settings File", ButtonPositionType.Left, self.read_data)
setup_button(self.step1, "open_examples_button", "Open Examples", ButtonPositionType.Left, self.open_examples)
setup_button(self.step1, "open_library_button", "Custom Library", ButtonPositionType.Center, self.open_custom_lib)
setup_button(self.step1, "github_button", "Contribute on GitHub", ButtonPositionType.Center, self.github)
setup_button(self.step1, "help_button", "Help", ButtonPositionType.Center, help_button_clicked, style="blue")
self.personal_lib_path = os.path.join(oDesktop.GetPersonalLibDirectory(), 'ElectronicTransformer')
if not transformer_definition:
self.read_core_dimensions()
self.prefill_supplier()
else:
self.show_core_img()
validate_aedt_version()
@verify_input_data
def populate_ui_data_step1(self):
"""
Set data to UI fields from transformer_definition dictionary
"""
self.segmentation_angle.Value = int(transformer_definition["core_dimensions"]["segmentation_angle"])
self.supplier.Value = transformer_definition["core_dimensions"]["supplier"]
self.core_type.Value = transformer_definition["core_dimensions"]["core_type"]
self.prefill_core_types(only_menu=True) # populate drop down menu once we read core type
self.core_model.Value = transformer_definition["core_dimensions"]["core_model"]
for i in range(1, 9):
if "D_" + str(i) in transformer_definition["core_dimensions"].keys():
d_value = transformer_definition["core_dimensions"]["D_" + str(i)]
self.core_dimensions["D_" + str(i)].Value = float(d_value)
else:
self.core_dimensions["D_" + str(i)].Visible = False
self.define_airgap.Value = transformer_definition["core_dimensions"]["airgap"]["define_airgap"]
if self.define_airgap.Value:
self.airgap_on_leg.Value = transformer_definition["core_dimensions"]["airgap"]["airgap_on_leg"]
self.airgap_value.Value = float(transformer_definition["core_dimensions"]["airgap"]["airgap_value"])
update_ui(self.step1)
def callback_step1(self):
self.collect_ui_data_step1()
check_core_dimensions(transformer_definition)
def show_core_img(self):
"""invoked to change image and core dimensions when supplier or core type changed"""
if self.core_type.Value not in ['EP', 'ER', 'PQ', 'RM']:
width = 300
height = 200
else:
width = 275
height = 360
html_data = '<img width="{}" height="{}" src="file:///{}/images/{}Core.png"/>'.format(width, height,
ExtAPI.Extension.InstallDir,
self.core_type.Value)
report = self.step1.UserInterface.GetComponent("coreImage")
report.SetHtmlContent(html_data)
report.Refresh()
def prefill_supplier(self):
"""
Read supplier from input data
:return:
"""
self.supplier.Options.Clear()
for key in sorted(self.cores_database.keys(), key=lambda x: x.lower()):
self.supplier.Options.Add(key)
self.supplier.Value = self.supplier.Options[0]
self.prefill_core_types()
def prefill_core_types(self, only_menu=False):
"""
Read core types from input data
:return:
"""
self.core_type.Options.Clear()
for key in sorted(self.cores_database[self.supplier.Value].keys()):
self.core_type.Options.Add(key)
if not only_menu:
self.core_type.Value = self.core_type.Options[0]
self.prefill_core_models(only_menu)
def prefill_core_models(self, only_menu=False):
"""
Read core models from input data
:return:
"""
self.core_model.Options.Clear()
self.core_models = self.cores_database[self.supplier.Value][self.core_type.Value]
for model in sorted(self.core_models.keys(), key=natural_keys):
self.core_model.Options.Add(model)
self.core_model.Value = self.core_model.Options[0]
self.show_core_img()
if not only_menu:
self.prefill_core_dimensions()
update_ui(self.step1)
def prefill_core_dimensions(self):
"""
Set core dimensions from the predefined lists
:return:
"""
for j in range(1, 9):
try:
self.core_dimensions["D_" + str(j)].Value = float(self.core_models[self.core_model.Value][j - 1])
self.core_dimensions["D_" + str(j)].Visible = True
except ValueError:
self.core_dimensions["D_" + str(j)].Visible = False
def read_core_dimensions(self):
"""
Read all possible core dimensions from input file
:return:
"""
core_dims_json = os.path.join(self.personal_lib_path, "core_dimensions.json")
if not os.path.isfile(core_dims_json):
# file does not exist, copy it from root location
if not os.path.exists(self.personal_lib_path):
os.makedirs(self.personal_lib_path)
shutil.copy(os.path.join(ExtAPI.Extension.InstallDir, "core_dimensions.json"), core_dims_json)
with open(core_dims_json) as file:
self.cores_database = json.load(file)
def collect_ui_data_step1(self):
"""collect data from all steps, write this data to dictionary"""
# step1
transformer_definition["core_dimensions"] = OrderedDict([
("segmentation_angle", self.segmentation_angle.Value),
("supplier", self.supplier.Value),
("core_type", self.core_type.Value),
("core_model", self.core_model.Value)
])
for i in range(1, 9):
if self.core_dimensions["D_" + str(i)].Visible:
d_value = str(self.core_dimensions["D_" + str(i)].Value)
else:
d_value = 0 # fill with zeros for cores where no parameter
transformer_definition["core_dimensions"]["D_" + str(i)] = d_value
transformer_definition["core_dimensions"]["airgap"] = OrderedDict([
("define_airgap", bool(self.define_airgap.Value)) # need to specify boolean due to bug 324104
])
if self.define_airgap.Value:
transformer_definition["core_dimensions"]["airgap"]["airgap_on_leg"] = self.airgap_on_leg.Value
transformer_definition["core_dimensions"]["airgap"]["airgap_value"] = str(self.airgap_value.Value)
class Step2(object):
__metaclass__ = ABCMeta
def __init__(self, step):
self.step2 = step.Wizard.Steps["step2"]
self.winding_prop = self.step2.Properties["winding_properties"]
self.layer_type = self.step2.Properties["winding_properties/layer_type"]
self.number_of_layers = self.step2.Properties["winding_properties/number_of_layers"]
self.layer_spacing = self.step2.Properties["winding_properties/layer_spacing"]
self.bobbin_board_thickness = self.step2.Properties["winding_properties/bobbin_board_thickness"]
self.top_margin = self.step2.Properties["winding_properties/top_margin"]
self.side_margin = self.step2.Properties["winding_properties/side_margin"]
self.include_bobbin = self.step2.Properties["winding_properties/include_bobbin"]
self.conductor_type = self.step2.Properties["winding_properties/conductor_type"]
self.table_layers = self.conductor_type.Properties["table_layers"]
self.table_layers_circles = self.conductor_type.Properties["table_layers_circles"]
self.skip_check = self.step2.Properties["winding_properties/skip_check"]
self.materials = {}
def init_tables_step2(self):
"""initialize tables with some initial data"""
self.table_layers.AddRow()
self.table_layers.Properties["conductor_width"].Value = 0.2
self.table_layers.Properties["conductor_height"].Value = 0.2
self.table_layers.Properties["turns_number"].Value = 2
self.table_layers.Properties["insulation_thickness"].Value = 0.05
self.table_layers.Properties["layer"].Value = 'Layer_1'
self.table_layers.SaveActiveRow()
self.table_layers_circles.AddRow()
self.table_layers_circles.Properties["conductor_diameter"].Value = 0.2
self.table_layers_circles.Properties["segments_number"].Value = 8
self.table_layers_circles.Properties["turns_number"].Value = 2
self.table_layers_circles.Properties["insulation_thickness"].Value = 0.05
self.table_layers_circles.Properties["layer"].Value = 'Layer_1'
self.table_layers_circles.SaveActiveRow()
def refresh_step2(self):
"""
each time step layout is opening
:return:
"""
setup_button(self.step2, "help_button", "Help", ButtonPositionType.Right, help_button_clicked, style="blue")
if "winding_definition" in transformer_definition:
# that mean that we read settings file from user and need to populate UI
self.populate_ui_data_step2()
update_ui(self.step2)
@verify_input_data
def populate_ui_data_step2(self):
# read data for step 2
winding_def = transformer_definition["winding_definition"]
self.winding_prop.Properties["layer_type"].Value = winding_def["layer_type"]
self.winding_prop.Properties["number_of_layers"].Value = int(winding_def["number_of_layers"])
self.winding_prop.Properties["layer_spacing"].Value = float(winding_def["layer_spacing"])
self.winding_prop.Properties["bobbin_board_thickness"].Value = float(winding_def["bobbin_board_thickness"])
self.winding_prop.Properties["top_margin"].Value = float(winding_def["top_margin"])
self.winding_prop.Properties["side_margin"].Value = float(winding_def["side_margin"])
self.winding_prop.Properties["include_bobbin"].Value = winding_def["include_bobbin"]
self.winding_prop.Properties["conductor_type"].Value = winding_def["conductor_type"]
if self.conductor_type.Value == "Circular":
xml_path_to_table = 'winding_properties/conductor_type/table_layers_circles'
list_of_prop = ["conductor_diameter", "segments_number", "turns_number", "insulation_thickness"]
else:
xml_path_to_table = 'winding_properties/conductor_type/table_layers'
list_of_prop = ["conductor_width", "conductor_height", "turns_number", "insulation_thickness"]
table = self.step2.Properties[xml_path_to_table]
row_num = table.RowCount
for j in range(0, row_num):
table.DeleteRow(0)
for i in range(1, int(self.number_of_layers.Value) + 1):
try:
layer_dict = winding_def["layers_definition"]["layer_" + str(i)]
except KeyError:
return add_error_message("Number of layers does not correspond to defined parameters." +
"Please specify parameters for each layer")
table.AddRow()
for prop in list_of_prop:
if prop in ["segments_number", | |
= self.session.query(models.DiseaseComment)
q = self.get_model_queries(q, ((comment, models.DiseaseComment.comment),))
q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),))
return self._limit_and_df(q, limit, as_df)
def other_gene_name(self, type_=None, name=None, entry_name=None, limit=None, as_df=None):
"""Method to query :class:`.models.OtherGeneName` objects in database
:param type_: type(s) of gene name e.g. *synonym*
:type type_: str or tuple(str) or None
:param name: other gene name(s)
:type name: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) or None
:param limit:
- if `isinstance(limit,int)==True` -> limit
- if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page)
- if limit == None -> all results
:type limit: int or tuple(int) or None
:param bool as_df: if `True` results are returned as :class:`pandas.DataFrame`
:return:
- if `as_df == False` -> list(:class:`.models.OtherGeneName`)
- if `as_df == True` -> :class:`pandas.DataFrame`
:rtype: list(:class:`.models.OtherGeneName`) or :class:`pandas.DataFrame`
"""
q = self.session.query(models.OtherGeneName)
model_queries_config = (
(type_, models.OtherGeneName.type_),
(name, models.OtherGeneName.name),
)
q = self.get_model_queries(q, model_queries_config)
q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),))
return self._limit_and_df(q, limit, as_df)
def alternative_full_name(self, name=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.AlternativeFullName` objects in database
:param name: alternative full name(s)
:type name: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) or None
:param limit:
- if `isinstance(limit,int)==True` -> limit
- if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page)
- if limit == None -> all results
:type limit: int or tuple(int) or None
:param bool as_df: if `True` results are returned as :class:`pandas.DataFrame`
:return:
- if `as_df == False` -> list(:class:`.models.AlternativeFullName`)
- if `as_df == True` -> :class:`pandas.DataFrame`
:rtype: list(:class:`.models.AlternativeFullName`) or :class:`pandas.DataFrame`
"""
q = self.session.query(models.AlternativeFullName)
model_queries_config = (
(name, models.AlternativeFullName.name),
)
q = self.get_model_queries(q, model_queries_config)
q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),))
return self._limit_and_df(q, limit, as_df)
def alternative_short_name(self, name=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.AlternativeShortlName` objects in database
:param name: alternative short name(s)
:type name: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) or None
:param limit:
- if `isinstance(limit,int)==True` -> limit
- if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page)
- if limit == None -> all results
:type limit: int or tuple(int) or None
:param bool as_df: if `True` results are returned as :class:`pandas.DataFrame`
:return:
- if `as_df == False` -> list(:class:`.models.AlternativeShortName`)
- if `as_df == True` -> :class:`pandas.DataFrame`
:rtype: list(:class:`.models.AlternativeShortName`) or :class:`pandas.DataFrame`
"""
q = self.session.query(models.AlternativeShortName)
model_queries_config = (
(name, models.AlternativeShortName.name),
)
q = self.get_model_queries(q, model_queries_config)
q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),))
return self._limit_and_df(q, limit, as_df)
def accession(self, accession=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.Accession` objects in database
:param accession: UniProt Accession number(s)
:type accession: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) or None
:param limit:
- if `isinstance(limit,int)==True` -> limit
- if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page)
- if limit == None -> all results
:type limit: int or tuple(int) or None
:param bool as_df: if `True` results are returned as :class:`pandas.DataFrame`
:return:
- if `as_df == False` -> list(:class:`.models.Accession`)
- if `as_df == True` -> :class:`pandas.DataFrame`
:rtype: list(:class:`.models.Accession`) or :class:`pandas.DataFrame`
"""
q = self.session.query(models.Accession)
model_queries_config = (
(accession, models.Accession.accession),
)
q = self.get_model_queries(q, model_queries_config)
q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),))
return self._limit_and_df(q, limit, as_df)
def pmid(self,
pmid=None,
entry_name=None,
first=None,
last=None,
volume=None,
name=None,
date=None,
title=None,
limit=None,
as_df=False
):
"""Method to query :class:`.models.Pmid` objects in database
:param pmid: PubMed identifier(s)
:type pmid: int or tuple(int) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) or None
:param first: first page(s)
:type first: str or tuple(str) or None
:param last: last page(s)
:type last: str or tuple(str) or None
:param volume: volume(s)
:type volume: int or tuple(int) or None
:param name: name(s) of journal
:type name: str or tuple(str) or None
:param date: publication year(s)
:type date: int or tuple(int) or None
:param title: title(s) of publication
:type title: str or tuple(str) or None
:param limit:
- if `isinstance(limit,int)==True` -> limit
- if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page)
- if limit == None -> all results
:type limit: int or tuple(int) or None
:param bool as_df: if `True` results are returned as :class:`pandas.DataFrame`
:return:
- if `as_df == False` -> list(:class:`.models.Pmid`)
- if `as_df == True` -> :class:`pandas.DataFrame`
:rtype: list(:class:`.models.Pmid`) or :class:`pandas.DataFrame`
"""
q = self.session.query(models.Pmid)
model_queries_config = (
(pmid, models.Pmid.pmid),
(last, models.Pmid.last),
(first, models.Pmid.first),
(volume, models.Pmid.volume),
(name, models.Pmid.name),
(date, models.Pmid.date),
(title, models.Pmid.title)
)
q = self.get_model_queries(q, model_queries_config)
q = self.get_many_to_many_queries(q, ((entry_name, models.Pmid.entries, models.Entry.name),))
return self._limit_and_df(q, limit, as_df)
def organism_host(self, taxid=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.OrganismHost` objects in database
:param taxid: NCBI taxonomy identifier(s)
:type taxid: int or tuple(int) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) or None
:param limit:
- if `isinstance(limit,int)==True` -> limit
- if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page)
- if limit == None -> all results
:type limit: int or tuple(int) or None
:param bool as_df: if `True` results are returned as :class:`pandas.DataFrame`
:return:
- if `as_df == False` -> list(:class:`.models.OrganismHost`)
- if `as_df == True` -> :class:`pandas.DataFrame`
:rtype: list(:class:`.models.OrganismHost`) or :class:`pandas.DataFrame`
"""
q = self.session.query(models.OrganismHost)
q = self.get_model_queries(q, ((taxid, models.OrganismHost.taxid),))
q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),))
return self._limit_and_df(q, limit, as_df)
def db_reference(self, type_=None, identifier=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.DbReference` objects in database
Check list of available databases with on :py:attr:`.dbreference_types`
:param type_: type(s) (or name(s)) of database
:type type_: str or tuple(str) or None
:param identifier: unique identifier(s) in specific database (type)
:type identifier: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) or None
:param limit:
- if `isinstance(limit,int)==True` -> limit
- if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page)
- if limit == None -> all results
:type limit: int or tuple(int) or None
:param bool as_df: if `True` results are returned as :class:`pandas.DataFrame`
:return:
- if `as_df == False` -> list(:class:`.models.DbReference`)
- if `as_df == True` -> :class:`pandas.DataFrame`
:rtype: list(:class:`.models.DbReference`) or :class:`pandas.DataFrame`
**Links**
- `UniProt dbxref <http://www.uniprot.org/docs/dbxref>`_
"""
q = self.session.query(models.DbReference)
model_queries_config = (
(type_, models.DbReference.type_),
(identifier, models.DbReference.identifier)
)
q = self.get_model_queries(q, model_queries_config)
q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),))
return self._limit_and_df(q, limit, as_df)
def feature(self, type_=None, identifier=None, description=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.Feature` objects in database
Check available features types with ``pyuniprot.query().feature_types``
:param type_: type(s) of feature
:type type_: str or tuple(str) or None
:param identifier: feature identifier(s)
:type identifier: str or tuple(str) or None
:param description: description(s) of feature(s)
:type description: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) or None
:param limit:
- if `isinstance(limit,int)==True` -> limit
- if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page)
- if limit == None -> all results
:type limit: int or tuple(int) or None
:param bool as_df: if `True` results are returned as :class:`pandas.DataFrame`
:return:
- if `as_df == False` -> list(:class:`.models.Feature`)
- if `as_df == True` -> :class:`pandas.DataFrame`
:rtype: list(:class:`.models.Feature`) or :class:`pandas.DataFrame`
"""
q = self.session.query(models.Feature)
model_queries_config = (
(type_, models.Feature.type_),
(identifier, models.Feature.identifier),
(description, models.Feature.description)
)
q = self.get_model_queries(q, model_queries_config)
q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),))
return self._limit_and_df(q, limit, as_df)
def function(self, text=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.Function` objects in database
:param text: description(s) of function(s)
:type text: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) or None
:param limit:
- if `isinstance(limit,int)==True` -> limit
- if `isinstance(limit,tuple)==True` -> format:= tuple(page_number, results_per_page)
- if limit == None -> all results
:type limit: int or tuple(int) or None
:param bool as_df: if `True` results are returned as :class:`pandas.DataFrame`
:return:
- if `as_df == False` -> list(:class:`.models.Function`)
- if `as_df == True` -> :class:`pandas.DataFrame`
:rtype: list(:class:`.models.Function`) or :class:`pandas.DataFrame`
"""
q = self.session.query(models.Function)
model_queries_config = (
(text, models.Function.text),
)
q = self.get_model_queries(q, model_queries_config)
q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),))
return self._limit_and_df(q, limit, as_df)
def ec_number(self, ec_number=None, entry_name=None, limit=None, as_df=False):
"""Method to query :class:`.models.ECNumber` objects in database
:param ec_number: Enzyme Commission number(s)
:type ec_number: str or tuple(str) or None
:param entry_name: name(s) in :class:`.models.Entry`
:type entry_name: str or tuple(str) | |
-N 'LNA:47' -S 2400000 -f 858.8375e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Durham/Duke_University.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Camden_Ave():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 858.8125e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Durham/Camden_Ave.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Cole_Mill_Rd():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 859.5125e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Durham/Cole_Mill_Rd.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Brian_Center():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 774.2875e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Durham/Brian_Center.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Dodge_City():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.975e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Edgecombe/Dodge_City.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Tarboro_City():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.6875e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Edgecombe/Tarboro_City.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Fountain():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 774.04375e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Edgecombe/Fountain.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Winston_Salem_State_University():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.95e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Forsyth/Winston_Salem_State_University.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Clemmons():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 859.7875e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Forsyth/Clemmons.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Hosley_Forest():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.7125e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Franklin/Hosley_Forest.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Louisburg():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 852.1375e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Franklin/Louisburg.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Margaret():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.8375e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Franklin/Margaret.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Youngsville():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 774.83125e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Franklin/Youngsville.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Belmont():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.625e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Gaston/Belmont.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Cherryville():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.375e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Gaston/Cherryville.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Crowders_Mountain_VFD():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.875e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Gaston/Crowders_Mountain_VFD.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Stanley():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 773.30625e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Gaston/Stanley.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Gatesville_DOC():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.45e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Gates/Gatesville_DOC.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Wauchecha_Bald():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.9875e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Graham/Wauchecha_Bald.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Berea():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.75e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Granville/Berea.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Butner():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.6125e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Granville/Butner.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Bullock_WICE_FM():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.975e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Granville/Bullock_WICE_FM.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Oak_Hill():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.6375e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Granville/Oak_Hill.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Oxford_Water_Tower():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 852.975e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Granville/Oxford_Water_Tower.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Arba():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.575e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Greene/Arba.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Farmville():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.6125e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Greene/Farmville.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Greensboro_AT():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 774.74375e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Guilford/Greensboro_AT.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Riverdale_Rd():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.875e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Guilford/Riverdale_Rd.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Brinkleyville():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.85e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Halifax/Brinkleyville.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Halifax():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.625e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Halifax/Halifax.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Cokesbury():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 774.55625e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Harnett/Cokesbury.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Erwin_PE():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.9875e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Harnett/Erwin_PE.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Lillington():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 854.9875e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Harnett/Lillington.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Spout_Springs():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 854.2375e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Harnett/Spout_Springs.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Angier():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 773.08125e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Harnett/Angier.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Broadway():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 773.49375e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Harnett/Broadway.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Chambers_Mtn():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 856.1125e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Haywood/Chambers_Mtn.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Hazel_Top():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 774.55625e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Haywood/Hazel_Top.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Bearwallow():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 773.71875e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Henderson/Bearwallow.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Corbin_Mtn():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 851.5875e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Henderson/Corbin_Mtn.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Jumpoff_Mountain():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.6875e6 -o 25000 -q 1 -T ~/op25/op25/gr-op25_repeater/apps/NC_Viper/Henderson/Jumpoff_Mountain.tsv -V -2 -U 2> stderr.2 -O plughw:1,0 -l 'http:0.0.0.0:8080'&")
def CMD_Ahoskie():
os.system("pkill -f ./rx.py")
os.system("cd ~/op25/op25/gr-op25_repeater/apps; ./rx.py --args 'rtl' -N 'LNA:47' -S 2400000 -f 853.7125e6 -o 25000 -q | |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
""" P1 tests for Templates
"""
#Import Local Modules
import marvin
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import *
from marvin.cloudstackAPI import *
from marvin.integration.lib.utils import *
from marvin.integration.lib.base import *
from marvin.integration.lib.common import *
import urllib
from random import random
#Import System modules
import time
class Services:
"""Test Templates Services
"""
def __init__(self):
self.services = {
"account": {
"email": "<EMAIL>",
"firstname": "Test",
"lastname": "User",
"username": "test",
# Random characters are appended for unique
# username
"password": "password",
},
"service_offering": {
"name": "Tiny Instance",
"displaytext": "Tiny Instance",
"cpunumber": 1,
"cpuspeed": 100, # in MHz
"memory": 128, # In MBs
},
"disk_offering": {
"displaytext": "Small",
"name": "Small",
"disksize": 1
},
"virtual_machine": {
"displayname": "testVM",
"hypervisor": 'XenServer',
"protocol": 'TCP',
"ssh_port": 22,
"username": "root",
"password": "password",
"privateport": 22,
"publicport": 22,
},
"volume": {
"diskname": "Test Volume",
},
"templates": {
# Configs for different Template formats
# For Eg. raw image, zip etc
0: {
"displaytext": "Public Template",
"name": "Public template",
"ostype": 'CentOS 5.3 (64-bit)',
"url": "http://download.cloud.com/releases/2.0.0/UbuntuServer-10-04-64bit.vhd.bz2",
"hypervisor": 'XenServer',
"format": 'VHD',
"isfeatured": True,
"ispublic": True,
"isextractable": True,
},
},
"template": {
"displaytext": "Cent OS Template",
"name": "Cent OS Template",
"ostype": 'CentOS 5.3 (64-bit)',
"templatefilter": 'self',
},
"templatefilter": 'self',
"ostype": 'CentOS 5.3 (64-bit)',
"sleep": 60,
"timeout": 10,
}
class TestCreateTemplate(cloudstackTestCase):
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
#Clean up, terminate the created templates
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def setUpClass(cls):
cls.services = Services().services
cls.api_client = super(TestCreateTemplate, cls).getClsTestClient().getApiClient()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.services['mode'] = cls.zone.networktype
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
cls.services["account"] = cls.account.name
cls._cleanup = [
cls.account,
cls.service_offering
]
return
@classmethod
def tearDownClass(cls):
try:
cls.api_client = super(TestCreateTemplate, cls).getClsTestClient().getApiClient()
#Cleanup resources used
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags = ["advanced", "advancedns"])
def test_01_create_template(self):
"""Test create public & private template
"""
# Validate the following:
# 1. Upload a templates in raw img format. Create a Vm instances from
# raw img template.
# 2. Upload a templates in zip file format. Create a Vm instances from
# zip template.
# 3. Upload a templates in tar format.Create a Vm instances from tar
# template.
# 4. Upload a templates in tar gzip format.Create a Vm instances from
# tar gzip template.
# 5. Upload a templates in tar bzip format. Create a Vm instances from
# tar bzip template.
# 6. Verify VMs & Templates is up and in ready state
builtin_info = get_builtin_template_info(self.apiclient, self.zone.id)
self.services["templates"][0]["url"] = builtin_info[0]
self.services["templates"][0]["hypervisor"] = builtin_info[1]
self.services["templates"][0]["format"] = builtin_info[2]
# Register new template
template = Template.register(
self.apiclient,
self.services["templates"][0],
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
self.debug(
"Registered a template of format: %s with ID: %s" % (
self.services["templates"][0]["format"],
template.id
))
# Wait for template to download
template.download(self.apiclient)
self.cleanup.append(template)
# Wait for template status to be changed across
time.sleep(self.services["sleep"])
timeout = self.services["timeout"]
while True:
list_template_response = list_templates(
self.apiclient,
templatefilter='all',
id=template.id,
zoneid=self.zone.id,
account=self.account.name,
domainid=self.account.domainid
)
if isinstance(list_template_response, list):
break
elif timeout == 0:
raise Exception("List template failed!")
time.sleep(5)
timeout = timeout - 1
#Verify template response to check whether template added successfully
self.assertEqual(
isinstance(list_template_response, list),
True,
"Check for list template response return valid data"
)
self.assertNotEqual(
len(list_template_response),
0,
"Check template available in List Templates"
)
template_response = list_template_response[0]
self.assertEqual(
template_response.isready,
True,
"Check display text of newly created template"
)
# Deploy new virtual machine using template
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
templateid=template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
mode=self.services["mode"]
)
self.debug("creating an instance with template ID: %s" % template.id)
vm_response = list_virtual_machines(
self.apiclient,
id=virtual_machine.id,
account=self.account.name,
domainid=self.account.domainid
)
self.assertEqual(
isinstance(vm_response, list),
True,
"Check for list VMs response after VM deployment"
)
#Verify VM response to check whether VM deployment was successful
self.assertNotEqual(
len(vm_response),
0,
"Check VMs available in List VMs response"
)
vm = vm_response[0]
self.assertEqual(
vm.state,
'Running',
"Check the state of VM created from Template"
)
return
class TestTemplates(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.services = Services().services
cls.api_client = super(TestTemplates, cls).getClsTestClient().getApiClient()
# Get Zone, templates etc
cls.domain = get_domain(cls.api_client, cls.services)
cls.zone = get_zone(cls.api_client, cls.services)
cls.services['mode'] = cls.zone.networktype
#populate second zone id for iso copy
cmd = listZones.listZonesCmd()
zones = cls.api_client.listZones(cmd)
if not isinstance(zones, list):
raise Exception("Failed to find zones.")
if len(zones) >= 2:
cls.services["destzoneid"] = zones[1].id
template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
cls.services["account"] = cls.account.name
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"]
)
# create virtual machine
cls.virtual_machine = VirtualMachine.create(
cls.api_client,
cls.services["virtual_machine"],
templateid=template.id,
accountid=cls.account.name,
domainid=cls.account.domainid,
serviceofferingid=cls.service_offering.id,
)
#Stop virtual machine
cls.virtual_machine.stop(cls.api_client)
timeout = cls.services["timeout"]
#Wait before server has be successfully stopped
time.sleep(cls.services["sleep"])
while True:
list_volume = list_volumes(
cls.api_client,
virtualmachineid=cls.virtual_machine.id,
type='ROOT',
listall=True
)
if isinstance(list_volume, list):
break
elif timeout == 0:
raise Exception("List volumes failed.")
time.sleep(5)
timeout = timeout - 1
cls.volume = list_volume[0]
#Create template from volume
cls.template = Template.create(
cls.api_client,
cls.services["template"],
cls.volume.id
)
cls._cleanup = [
cls.service_offering,
cls.account,
]
@classmethod
def tearDownClass(cls):
try:
cls.api_client = super(TestTemplates, cls).getClsTestClient().getApiClient()
#Cleanup created resources such as templates and VMs
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
return
def tearDown(self):
try:
#Clean up, terminate the created templates
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@attr(tags = ["advanced", "advancedns"])
def test_01_create_template_volume(self):
"""Test Create template from volume
"""
# Validate the following:
# 1. Deploy new VM using the template created from Volume
# 2. VM should be in Up and Running state
virtual_machine = VirtualMachine.create(
self.apiclient,
self.services["virtual_machine"],
templateid=self.template.id,
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
)
self.debug("creating an instance with template ID: %s" % self.template.id)
self.cleanup.append(virtual_machine)
vm_response = list_virtual_machines(
self.apiclient,
id=virtual_machine.id,
account=self.account.name,
domainid=self.account.domainid
)
#Verify VM response to check whether VM deployment was successful
self.assertNotEqual(
len(vm_response),
0,
"Check VMs available in List VMs response"
)
vm = vm_response[0]
self.assertEqual(
vm.state,
'Running',
"Check the state of VM created from Template"
)
return
@attr(tags = ["advanced", "advancedns"])
def test_03_delete_template(self):
"""Test Delete template
"""
# Validate the following:
# 1. Create a template and verify it is shown in list templates response
# 2. Delete the created template and again verify list template response
# Verify template response for updated attributes
list_template_response = list_templates(
self.apiclient,
templatefilter=\
self.services["template"]["templatefilter"],
id=self.template.id,
zoneid=self.zone.id
)
self.assertEqual(
isinstance(list_template_response, list),
True,
"Check for list template response return valid list"
)
self.assertNotEqual(
len(list_template_response),
0,
"Check template available in List Templates"
)
template_response = list_template_response[0]
self.assertEqual(
template_response.id,
self.template.id,
"Check display text of updated template"
)
self.debug("Deleting template: %s" % self.template)
# Delete the template
self.template.delete(self.apiclient)
self.debug("Delete template: %s successful" % self.template)
list_template_response = list_templates(
self.apiclient,
templatefilter=\
self.services["template"]["templatefilter"],
id=self.template.id,
zoneid=self.zone.id
)
self.assertEqual(
list_template_response,
None,
"Check template available in List Templates"
)
return
@attr(speed = "slow")
@attr(tags = ["advanced", "advancedns"])
def test_04_template_from_snapshot(self):
"""Create Template from snapshot
"""
# Validate the following
# 2. Snapshot the Root disk
# 3. Create Template from snapshot
# 4. Deploy Virtual machine using this template
# 5. VM should be in running state
volumes = list_volumes(
self.apiclient,
virtualmachineid=self.virtual_machine.id,
type='ROOT',
listall=True
)
volume = volumes[0]
self.debug("Creating a snapshot from volume: %s" % | |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 16:31:56 2021
@author: nicolasnavarre
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
figures = 'figures/'
def extra_analysis(POM_data, Org_food, EAT_food, FAO_Crops, FAO_Crop_yield, POM_protein_feed, meat_products, final_df, Group_Area):
POM_p_balance = POM_data.loc[POM_data.Item.isin(['Milk, whole fresh cow'])]
POM_diet = POM_data
# temp_list = []
# for i in final_df["IMAGEGROUP"].unique().tolist():
# temp_ha = round(final_df.loc[final_df["IMAGEGROUP"] == i, 'Ha'].sum(),2)
# temp_org = round(final_df.loc[final_df["IMAGEGROUP"] == i, 'Org area'].sum(),2)
# temp_land = round(final_df.loc[final_df["IMAGEGROUP"] == i, 'Value'].sum(),2)
# print(i, temp_ha, temp_org, temp_land)
# temp_list.append(temp_ha)
# print(sum(temp_list))
# print("Micro Data")
# print(final_df.Population.sum()/(final_df.Population.sum()+POM_micro['Population (2016), 1000person'].sum()))
# print(final_df.Value.sum()/(final_df.Value.sum()+POM_micro['1000 Ha'].sum()))
# POM_micro['1000 Ha'].sum()
# final_df.Value.sum()
# final_df.Value.sum()+POM_micro['1000 Ha'].sum()
#Goes in the main.
# print((Feed_crops_area_sum['Feed crop Area'].sum() + Meat_Area['EAT'].sum())/Total_Area['EAT'].sum())
# print(Feed_crops_area_sum['Feed crop Area'].sum() + Meat_Area['EAT'].sum())
# print(Total_Area['EAT'].sum())
# feed_detail['prod'] = 0
# feed_detail = pd.merge(feed_detail, POM_p_balance[['Area', 'EAT POM (with waste)', 'GROUP']], left_on = 'Area', right_on = 'Area' )
# for i in feed_detail.Area.tolist():
# feed_detail.loc[feed_detail.Area == i, 'prod'] = float(POM_p_balance.loc[POM_p_balance.Area == i, 'EAT POM (with waste)'])
# feed_detail['prod'] *= feed_detail['fraction']
# #feed_detail['prod'] *= 0.141926
# #feed_detail['grass'] *= 0.18
# #feed_detail['Maize'] *= 0.100455
# #feed_detail['Soybeans'] *= 0.20333
# feed_detail['ratio'] = feed_detail['prod']/(feed_detail['grass'] + feed_detail['Maize'] + feed_detail['Soybeans'])
# feed_detail['ratio'] *= 100
# p_in = feed_detail['grass'].sum() + feed_detail['Maize'].sum() + feed_detail['Soybeans'].sum()
# print(p_in)
# print(feed_detail['prod'].sum())
# print(feed_detail['prod'].sum()/p_in)
#import Prod_Global_Figures as Gfigs
#import Prod_Regional_Figures as Rfigs
#Gfigs.GlobalFig()
#Rfigs.RegionalFig("Europe")
temp_list = []
for i in final_df["IMAGEGROUP"].unique().tolist():
temp_ha = round(final_df.loc[final_df["IMAGEGROUP"] == i, 'Ha'].sum(),2)
temp_org = round(final_df.loc[final_df["IMAGEGROUP"] == i, 'Org area'].sum(),2)
temp_land = round(final_df.loc[final_df["IMAGEGROUP"] == i, 'Value'].sum(),2)
print(i, temp_ha, temp_org, temp_land)
temp_list.append(temp_ha)
print(sum(temp_list))
POM_waste = POM_data
POM_nations = POM_data
nation_list = []
food_times_list = []
for i in POM_nations.Area.unique().tolist():
POM_temp = POM_nations.loc[POM_nations.Area == i]
if i == 'Syrian Arab Republic':
nation_list.append(i)
food_times_list.append(len(POM_temp.Area))
#df_temp = pd.DataFrame()
#df_temp['Area'] = nation_list
#df_temp['Times'] = food_times_list
gp_nat = POM_waste[['Area', 'Cal Provided']].drop_duplicates(subset=['Area'])
POM_waste['eat waste'] = POM_waste['EAT POM (with waste)']- POM_waste['EAT POM']
POM_waste['eat feed'] = POM_waste['POM EAT (with waste & feed)'] - POM_waste['EAT POM (with waste)']
POM_waste = pd.merge(POM_waste, FAO_Crop_yield[['Area', 'Item', 'Value']], on=["Area", 'Item'], how = 'left')
check_waste = POM_waste.groupby(["EAT_group"]).apply(lambda x: x["eat waste"].sum())
zcheck_feed = POM_waste['for feed EAT'].sum()/POM_waste['POM EAT (with waste & feed)'].sum()
zcheck_waste = POM_waste['eat waste'].sum()/POM_waste['POM EAT (with waste & feed)'].sum()
zcheck_food = POM_waste['POM (no waste)'].sum()/POM_waste['POM Org (with waste & feed)'].sum()
zcheck_waste_nofeed = 1 - POM_waste['EAT POM'].sum()/POM_waste['EAT POM (with waste)'].sum()
zcheck_waste_nofeed = 1 - POM_waste['POM (no waste)'].sum()/POM_waste['POM'].sum()
waste_total = POM_waste['eat waste'].sum()
waste_veg = POM_waste.loc[POM_waste['EAT_group'] == 'vegetables', 'eat waste'].sum()
print(waste_veg/waste_total)
print(POM_waste['POM (no waste)'].sum()/POM_waste['POM Org (with waste & feed)'].sum())
POM_legumes = POM_waste.loc[POM_waste['EAT_group'] == 'dairy foods', 'EAT POM'].sum()
feed_by_nation_eat = POM_waste.loc[POM_waste.Item != 'grass'].groupby(["GROUP"]).apply(lambda x: x["for feed EAT"].sum())#/x["POM EAT (with waste & feed)"].sum())
feed_by_nation_org = POM_waste.loc[POM_waste.Item != 'grass'].groupby(["GROUP"]).apply(lambda x: x["for feed Org"].sum())#/x["POM Org (with waste & feed)"].sum())
print(POM_waste['for feed Org'].sum())
feed_global_eat = POM_waste['eat feed'].sum()/POM_waste['POM EAT (with waste & feed)'].sum()
feed_global_org = POM_waste['for feed Org'].sum()/POM_waste['POM Org (with waste & feed)'].sum()
POM_meat = POM_waste[POM_waste['group_nf'].isin(meat_products)]
temp = POM_waste['EAT POM (with waste)'].sum() - POM_meat['EAT POM (with waste)'].sum()
print(temp/POM_waste['POM EAT (with waste & feed)'].sum())
meat_by_group_eat = POM_meat.groupby(["GROUP"]).apply(lambda x: x['POM EAT (with waste & feed)'].sum())
meat_by_group_org = POM_meat.groupby(["GROUP"]).apply(lambda x: x['POM Org (with waste & feed)'].sum())
meat_by_group_eat = pd.DataFrame(meat_by_group_eat)
meat_by_group_org = pd.DataFrame(meat_by_group_org)
food_eat = POM_waste.groupby(["GROUP"]).apply(lambda x: x["POM EAT (with waste & feed)"].sum())
food_org = POM_waste.groupby(["GROUP"]).apply(lambda x: x["POM Org (with waste & feed)"].sum())
food_eat = pd.DataFrame(food_eat)
food_org = pd.DataFrame(food_org)
meat_by_group_eat = pd.merge(meat_by_group_eat, food_eat, left_index=True, right_index=True)
meat_by_group_eat['share'] = meat_by_group_eat['0_x']/meat_by_group_eat['0_y']
meat_by_group_org = pd.merge(meat_by_group_org, food_org, left_index=True, right_index=True)
meat_by_group_org['share'] = meat_by_group_org['0_x']/meat_by_group_org['0_y']
temp_count = 0
temp_counteat = 0
fig, ax = plt.subplots()
for i,j in zip(meat_by_group_eat.index, meat_by_group_org.index) :
if i == 'Other':
continue
ax.plot(j, meat_by_group_org['share'][j]*100 , "rd")
ax.plot(i, meat_by_group_eat['share'][i]*100 , "gd")
temp_count += Org_food
temp_counteat += EAT_food
#ax.title.set_text("Global per Capita Food Group Production (inc. waste & feed)")
ax.grid(alpha = 0.5)
ax.tick_params(labelrotation=90)
plt.yticks(rotation = "horizontal")
plt.ylabel("Feed Share (%)")
plt.ylim(-0.2, 100)
legend_elements = [Line2D([0], [0], lw = 0, marker='d', color='r', label='Current Diet\nGlobal = '+str(round((meat_by_group_org['0_x'].sum()/meat_by_group_org['0_y'].sum())*100,1))+' % animal products',\
markerfacecolor='r'),
Line2D([0], [0], lw = 0, marker='d', color='g', label='EAT Lancet Diet\nGlobal = '+str(round((meat_by_group_eat['0_x'].sum()/meat_by_group_eat['0_y'].sum())*100,1))+' % animal products',\
markerfacecolor='g')]
lg = ax.legend(handles=legend_elements, bbox_to_anchor=(1.0, 0.42), loc="lower left")
#plt.legend(handles =[one, two])
fig.savefig(figures+"Global Meat Share.png", bbox_extra_artists=(lg,), bbox_inches='tight', dpi = 400)
plt.close()
temp_count = 0
temp_counteat = 0
group_list = []
food_list_eat = []
food_list_org = []
fig, ax = plt.subplots()
for i,j in zip(feed_by_nation_org.index, feed_by_nation_eat.index) :
if i == 'Other':
continue
ax.plot(i, feed_by_nation_org[i]* 1000 , "rd")
ax.plot(j, feed_by_nation_eat[j]* 1000 , "gd")
temp_count += Org_food
temp_counteat += EAT_food
group_list.append(i)
food_list_eat.append(feed_by_nation_eat[j]* 1000)
food_list_org.append(feed_by_nation_org[i]* 1000)
#ax.title.set_text("Global per Capita Food Group Production (inc. waste & feed)")
ax.grid(alpha = 0.5)
ax.tick_params(labelrotation=90)
plt.yticks(rotation = "horizontal")
plt.ylabel("Feed Produced (tonnes)")
#plt.ylim(-0.2, 100)
legend_elements = [Line2D([0], [0], lw = 0, marker='d', color='r', label='Current Diet\nTotal = '+str(round(POM_waste['for feed Org'].sum()*1000/10**9,1))+' 1e9 tonnes',\
markerfacecolor='r'),
Line2D([0], [0], lw = 0, marker='d', color='g', label='EAT Lancet Diet\nTotal = '+str(round(POM_waste['for feed EAT'].sum()*1000/10**9,1))+' 1e9 tonnes',\
markerfacecolor='g')]
lg = ax.legend(handles=legend_elements, bbox_to_anchor=(1.0, 0.42), loc="lower left")
#plt.legend(handles =[one, two])
fig.savefig(figures+"Global Feed Share.png", bbox_extra_artists=(lg,), bbox_inches='tight', dpi = 400)
fig, ax = plt.subplots()
diet_df = pd.DataFrame()
width = 0.35
x = np.arange(len(group_list))
diet_df['group'] = group_list
diet_df['gF EAT'] = food_list_eat
diet_df['gF Org'] = food_list_org
diet_df['dif'] = diet_df['gF Org'] - diet_df['gF EAT']
diet_df = diet_df.sort_values(by=['dif'], ascending=False)
ax.bar(x + width/2, diet_df['gF EAT'], width, label='EAT Diet', color = 'g')
ax.bar(x - width/2, diet_df['gF Org'], width, label='BAU Diet', color = 'r')
ax.set_ylabel('Prod/capita (g/person-day)')
ax.set_xticks(x)
ax.set_xticklabels(diet_df['group'])
pos_values = len(diet_df[diet_df["dif"]>0])
ax.axvspan(-0.5, pos_values-0.5, facecolor='0.2', alpha=0.25, zorder=-100)
plt.xticks(rotation = 90)
POM_leg = POM_waste.loc[POM_waste.Item != 'grass']
legend_elements = [Line2D([0], [0], lw = 0, marker='s', color='r', label='Current Diet\nTotal = '+str(round(POM_leg['for feed Org'].sum()*1000/10**9,1))+' 1e9 tonnes',\
markerfacecolor='r'),
Line2D([0], [0], lw = 0, marker='s', color='g', label='EAT Lancet Diet\nTotal = '+str(round(POM_leg['for feed EAT'].sum()*1000/10**9,1))+' 1e9 tonnes',\
markerfacecolor='g'),
Line2D([0], [0], lw = 0, marker='s', color='0.2', alpha=0.25, label='Reduction in production',\
markerfacecolor='0.2')]
lg = ax.legend(handles=legend_elements, bbox_to_anchor=(1.0, 0.42), loc="lower left")
fig.savefig(figures+j+" EAT_Group Production.png", bbox_extra_artists=(lg,), bbox_inches='tight', dpi = 400)
plt.close()
FAO_yield_glob = FAO_Crops[['Area', "Item", 'Value', 'GROUP', 'for feed EAT', 'for feed Org']]
FAO_yield_glob = FAO_yield_glob[FAO_yield_glob.Item != 'grass' ]
FAO_yield_glob['EAT Feed Area'] = FAO_yield_glob['for feed EAT']/FAO_yield_glob['Value']
FAO_yield_glob['Org Feed Area'] = FAO_yield_glob['for feed Org']/FAO_yield_glob['Value']
global_yield_feed = FAO_yield_glob.groupby(["GROUP"]).apply(lambda x: x['for feed EAT'].sum()/x['EAT Feed Area'].sum())
fig, ax = plt.subplots()
for i in global_yield_feed.index :
if i == 'Other':
continue
ax.plot(i, global_yield_feed[i]*1000, 'kd')
#ax.title.set_text("Global per Capita Food Group Production (inc. waste & feed)")
ax.grid(alpha = 0.5)
ax.tick_params(labelrotation=90)
plt.yticks(rotation = "horizontal")
plt.ylabel("Feed Crop Yields (tons/ha)")
plt.ylim(-0.2, 4)
fig, ax = plt.subplots()
group_list = []
food_list = []
for i in global_yield_feed.index :
if i == 'Other':
continue
ax.plot(i, global_yield_feed[i]*1000, 'kd')
group_list.append(i)
food_list.append(global_yield_feed[i]*1000)
diet_df = pd.DataFrame()
width = 0.35
x = np.arange(len(group_list))
diet_df['group'] = group_list
diet_df['food'] = food_list_eat
ax.bar(x, diet_df['food'], width, label='EAT Diet', color = 'k')
#ax.bar(x - width/2, diet_df['gF Org'], width, label='BAU Diet', color = 'r')
ax.set_ylabel('Prod/capita (g/person-day)')
ax.set_xticks(x)
ax.set_xticklabels(diet_df['group'])
#pos_values = len(diet_df[diet_df["dif"]>0])
#ax.axvspan(-0.5, pos_values-0.5, facecolor='0.2', alpha=0.25, zorder=-100)
plt.xticks(rotation = 90)
fig.savefig(figures+j+" yield_crop.png", dpi = 400)
legend_elements = [Line2D([0], [0], lw = 0, marker='s', color='r', label='Current Diet\nTotal = '+str(round(POM_waste['for feed Org'].sum()*1000/10**9,1))+' 1e9 tonnes',\
markerfacecolor='r'),
Line2D([0], [0], lw = 0, marker='s', color='g', label='EAT Lancet Diet\nTotal = '+str(round(POM_waste['for feed EAT'].sum()*1000/10**9,1))+' 1e9 tonnes',\
markerfacecolor='g'),
Line2D([0], [0], lw = 0, marker='s', color='0.2', alpha=0.25, label='Reduction in production',\
markerfacecolor='0.2')]
lg = ax.legend(handles=legend_elements, bbox_to_anchor=(1.0, 0.42), loc="lower left")
fig.savefig(figures+j+" EAT_Group Production.png", bbox_extra_artists=(lg,), bbox_inches='tight', dpi = 400)
#ax.title.set_text("Global per Capita Food Group Production (inc. waste & feed)")
ax.grid(alpha = 0.5)
ax.tick_params(labelrotation=90)
plt.yticks(rotation = "horizontal")
plt.ylabel("Feed Crop Yields (tons/ha)")
plt.ylim(-0.2, 5)
#lg = ax.legend(handles=legend_elements, bbox_to_anchor=(1.0, 0.42), loc="lower left")
#plt.legend(handles =[one, two])
fig.savefig(figures+"Global Feed yield.png", bbox_inches='tight', dpi = 400)
plt.close()
#print(zcheck_feed+zcheck_waste+zcheck_food)
#print(zcheck_feed)
#print(zcheck_waste)
POM_chicken = POM_data.loc[POM_data.Item == 'Eggs, hen, in shell']
POM_chicken = POM_chicken[['Area', 'POM', 'EAT POM']]
POM_chicken['Change'] = | |
first_paragraph = utils.remove_tag_from_tag(
first_paragraph, "supplementary-material"
)
if utils.node_text(first_paragraph).strip():
component["caption"] = utils.node_text(first_paragraph)
component["full_caption"] = utils.node_contents_str(first_paragraph)
if raw_parser.permissions(tag):
component["permissions"] = []
for permissions_tag in raw_parser.permissions(tag):
permissions_item = {}
if raw_parser.copyright_statement(permissions_tag):
permissions_item["copyright_statement"] = utils.node_text(
raw_parser.copyright_statement(permissions_tag)
)
if raw_parser.copyright_year(permissions_tag):
permissions_item["copyright_year"] = utils.node_text(
raw_parser.copyright_year(permissions_tag)
)
if raw_parser.copyright_holder(permissions_tag):
permissions_item["copyright_holder"] = utils.node_text(
raw_parser.copyright_holder(permissions_tag)
)
if raw_parser.licence_p(permissions_tag):
permissions_item["license"] = utils.node_text(
utils.first(raw_parser.licence_p(permissions_tag))
)
permissions_item["full_license"] = utils.node_contents_str(
utils.first(raw_parser.licence_p(permissions_tag))
)
component["permissions"].append(permissions_item)
if raw_parser.contributors(tag):
component["contributors"] = []
for contributor_tag in raw_parser.contributors(tag):
component["contributors"].append(
format_contributor(contributor_tag, soup)
)
# There are only some parent tags we care about for components
# and only check two levels of parentage
parent_nodenames = [
"sub-article",
"fig-group",
"fig",
"boxed-text",
"table-wrap",
"app",
"media",
]
parent_tag = utils.first_parent(tag, parent_nodenames)
if parent_tag:
# For fig-group we actually want the first fig of the fig-group as the parent
acting_parent_tag = utils.component_acting_parent_tag(parent_tag, tag)
# Only counts if the acting parent tag has a DOI
if (
acting_parent_tag
and extract_component_doi(acting_parent_tag, parent_nodenames)
is not None
):
component["parent_type"] = acting_parent_tag.name
component["parent_ordinal"] = utils.tag_ordinal(acting_parent_tag)
component["parent_sibling_ordinal"] = tag_details_sibling_ordinal(
acting_parent_tag
)
component["parent_asset"] = tag_details_asset(acting_parent_tag)
# Look for parent parent, if available
parent_parent_tag = utils.first_parent(parent_tag, parent_nodenames)
if parent_parent_tag:
acting_parent_tag = utils.component_acting_parent_tag(
parent_parent_tag, parent_tag
)
if (
acting_parent_tag
and extract_component_doi(acting_parent_tag, parent_nodenames)
is not None
):
component["parent_parent_type"] = acting_parent_tag.name
component["parent_parent_ordinal"] = utils.tag_ordinal(
acting_parent_tag
)
component[
"parent_parent_sibling_ordinal"
] = tag_details_sibling_ordinal(acting_parent_tag)
component["parent_parent_asset"] = tag_details_asset(
acting_parent_tag
)
content = ""
for p_tag in utils.extract_nodes(tag, "p"):
if content != "":
# Add a space before each new paragraph for now
content = content + " "
content = content + utils.node_text(p_tag)
if content != "":
component["content"] = content
# mime type
media_tag = None
if ctype == "media":
media_tag = tag
elif ctype == "supplementary-material":
media_tag = utils.first(raw_parser.media(tag))
if media_tag:
component["mimetype"] = media_tag.get("mimetype")
component["mime-subtype"] = media_tag.get("mime-subtype")
if len(component) > 0:
component["article_doi"] = article_doi
component["type"] = ctype
component["position"] = position
# Ordinal is based on all tags of the same type even if they have no DOI
component["ordinal"] = utils.tag_ordinal(tag)
component["sibling_ordinal"] = tag_details_sibling_ordinal(tag)
component["asset"] = tag_details_asset(tag)
# component['ordinal'] = position_by_type[ctype]
components.append(component)
position += 1
position_by_type[ctype] += 1
return components
def correspondence(soup):
"""
Find the corresp tags included in author-notes
for primary correspondence
"""
correspondence = []
author_notes_nodes = raw_parser.author_notes(soup)
if author_notes_nodes:
corresp_nodes = raw_parser.corresp(author_notes_nodes)
for tag in corresp_nodes:
correspondence.append(tag.text)
return correspondence
def full_correspondence(soup):
cor = {}
author_notes_nodes = raw_parser.author_notes(soup)
if author_notes_nodes:
corresp_nodes = raw_parser.corresp(author_notes_nodes)
for tag in corresp_nodes:
# check for required id attribute
if "id" not in tag.attrs:
continue
if tag["id"] not in cor:
cor[tag["id"]] = []
if raw_parser.email(tag):
# Multiple email addresses possible
for email_tag in raw_parser.email(tag):
cor[tag["id"]].append(utils.node_contents_str(email_tag))
elif raw_parser.phone(tag):
# Look for a phone number
cor[tag["id"]].append(
utils.node_contents_str(utils.first(raw_parser.phone(tag)))
)
return cor
@utils.nullify
def author_notes(soup):
"""
Find the fn tags included in author-notes
"""
author_notes = []
author_notes_section = raw_parser.author_notes(soup)
if author_notes_section:
fn_nodes = raw_parser.fn(author_notes_section)
for tag in fn_nodes:
if "fn-type" in tag.attrs:
if tag["fn-type"] != "present-address":
author_notes.append(utils.node_text(tag))
return author_notes
@utils.nullify
def full_author_notes(soup, fntype_filter=None):
"""
Find the fn tags included in author-notes
"""
notes = []
author_notes_section = raw_parser.author_notes(soup)
if author_notes_section:
fn_nodes = raw_parser.fn(author_notes_section)
notes = footnotes(fn_nodes, fntype_filter)
return notes
@utils.nullify
def competing_interests(soup, fntype_filter):
"""
Find the fn tags included in the competing interest
"""
competing_interests_section = utils.extract_nodes(
soup, "fn-group", attr="content-type", value="competing-interest"
)
if not competing_interests_section:
return None
fn_nodes = utils.extract_nodes(utils.first(competing_interests_section), "fn")
interests = footnotes(fn_nodes, fntype_filter)
return interests
@utils.nullify
def present_addresses(soup):
notes = []
fntype_filter = "present-address"
author_notes_section = raw_parser.author_notes(soup)
if author_notes_section:
fn_nodes = utils.extract_nodes(author_notes_section, "fn")
notes = footnotes(fn_nodes, fntype_filter)
return notes
@utils.nullify
def other_foot_notes(soup):
notes = []
fntype_filter = ["fn", "other"]
author_notes_section = raw_parser.author_notes(soup)
if author_notes_section:
fn_nodes = utils.extract_nodes(author_notes_section, "fn")
notes = footnotes(fn_nodes, fntype_filter)
return notes
@utils.nullify
def author_contributions(soup, fntype_filter):
"""
Find the fn tags included in the competing interest
"""
author_contributions_section = utils.extract_nodes(
soup, "fn-group", attr="content-type", value="author-contribution"
)
if not author_contributions_section:
return None
fn_nodes = utils.extract_nodes(utils.first(author_contributions_section), "fn")
cons = footnotes(fn_nodes, fntype_filter)
return cons
def footnotes(fn_nodes, fntype_filter):
notes = []
for fn_node in fn_nodes:
try:
if fntype_filter is None or fn_node["fn-type"] in fntype_filter:
notes.append(
{
"id": fn_node["id"],
"text": utils.clean_whitespace(
utils.node_contents_str(fn_node)
),
"fn-type": fn_node["fn-type"],
}
)
except KeyError:
# TODO log
pass
return notes
@utils.nullify
def full_award_groups(soup):
"""
Find the award-group items and return a list of details
"""
award_groups = []
funding_group_section = utils.extract_nodes(soup, "funding-group")
# counter for auto generated id values, if required
generated_id_counter = 1
for funding_group in funding_group_section:
award_group_tags = utils.extract_nodes(funding_group, "award-group")
for award_group_tag in award_group_tags:
if "id" in award_group_tag.attrs:
ref = award_group_tag["id"]
else:
# hack: generate and increment an id value none is available
ref = "award-group-{id}".format(id=generated_id_counter)
generated_id_counter += 1
award_group = {}
award_group_id = award_group_award_id(award_group_tag)
if award_group_id is not None:
award_group["award-id"] = utils.first(award_group_id)
funding_sources = full_award_group_funding_source(award_group_tag)
source = utils.first(funding_sources)
if source is not None:
utils.copy_attribute(source, "institution", award_group)
utils.copy_attribute(source, "institution-id", award_group, "id")
utils.copy_attribute(
source,
"institution-id-type",
award_group,
destination_key="id-type",
)
award_group_by_ref = {}
award_group_by_ref[ref] = award_group
award_groups.append(award_group_by_ref)
return award_groups
@utils.nullify
def award_groups(soup):
"""
Find the award-group items and return a list of details
"""
award_groups = []
funding_group_section = utils.extract_nodes(soup, "funding-group")
for funding_group in funding_group_section:
award_group_tags = utils.extract_nodes(funding_group, "award-group")
for award_group_tag in award_group_tags:
award_group = {}
award_group["funding_source"] = award_group_funding_source(award_group_tag)
award_group["recipient"] = award_group_principal_award_recipient(
award_group_tag
)
award_group["award_id"] = award_group_award_id(award_group_tag)
award_groups.append(award_group)
return award_groups
@utils.nullify
def award_group_funding_source(tag):
"""
Given a funding group element
Find the award group funding sources, one for each
item found in the get_funding_group section
"""
award_group_funding_source = []
funding_source_tags = utils.extract_nodes(tag, "funding-source")
for funding_source_tag in funding_source_tags:
award_group_funding_source.append(funding_source_tag.text)
return award_group_funding_source
@utils.nullify
def full_award_group_funding_source(tag):
"""
Given a funding group element
Find the award group funding sources, one for each
item found in the get_funding_group section
"""
award_group_funding_sources = []
funding_source_nodes = utils.extract_nodes(tag, "funding-source")
for funding_source_node in funding_source_nodes:
award_group_funding_source = {}
institution_nodes = utils.extract_nodes(funding_source_node, "institution")
institution_node = utils.first(institution_nodes)
if institution_node:
award_group_funding_source["institution"] = utils.node_text(
institution_node
)
if "content-type" in institution_node.attrs:
award_group_funding_source["institution-type"] = institution_node[
"content-type"
]
institution_id_nodes = utils.extract_nodes(
funding_source_node, "institution-id"
)
institution_id_node = utils.first(institution_id_nodes)
if institution_id_node:
award_group_funding_source["institution-id"] = utils.node_text(
institution_id_node
)
if "institution-id-type" in institution_id_node.attrs:
award_group_funding_source["institution-id-type"] = institution_id_node[
"institution-id-type"
]
award_group_funding_sources.append(award_group_funding_source)
return award_group_funding_sources
@utils.nullify
def award_group_award_id(tag):
"""
Find the award group award id, one for each
item found in the get_funding_group section
"""
award_group_award_id = []
award_id_tags = utils.extract_nodes(tag, "award-id")
for award_id_tag in award_id_tags:
award_group_award_id.append(award_id_tag.text)
return award_group_award_id
@utils.nullify
def award_group_principal_award_recipient(tag):
"""
Find the award group principal award recipient, one for each
item found in the get_funding_group section
"""
award_group_principal_award_recipient = []
principal_award_recipients = utils.extract_nodes(tag, "principal-award-recipient")
for recipient_tag in principal_award_recipients:
principal_award_recipient_text = ""
institution = utils.node_text(
utils.first(utils.extract_nodes(recipient_tag, "institution"))
)
surname = utils.node_text(
utils.first(utils.extract_nodes(recipient_tag, "surname"))
)
given_names = utils.node_text(
utils.first(utils.extract_nodes(recipient_tag, "given-names"))
)
string_name = utils.node_text(
utils.first(raw_parser.string_name(recipient_tag))
)
# Concatenate name and institution values if found
# while filtering out excess whitespace
if given_names:
principal_award_recipient_text += given_names
if principal_award_recipient_text != "":
principal_award_recipient_text += " "
if surname:
principal_award_recipient_text += surname
if institution:
principal_award_recipient_text += institution
if string_name:
principal_award_recipient_text += string_name
award_group_principal_award_recipient.append(principal_award_recipient_text)
return award_group_principal_award_recipient
def object_id_doi(tag, parent_tag_name=None):
"""DOI in an object-id tag found inside the tag"""
doi = None
object_id = None
object_ids = raw_parser.object_id(tag, "doi")
if object_ids:
object_id = utils.first(object_ids)
if parent_tag_name and object_id and object_id.parent.name != parent_tag_name:
object_id = None
if object_id:
doi = utils.node_contents_str(object_id)
return doi
def title_tag_inspected(
tag, parent_tag_name=None, p_parent_tag_name=None, direct_sibling_only=False
):
"""Extract the title tag and sometimes inspect its parents"""
title_tag = None
if direct_sibling_only is True:
for sibling_tag in tag:
if sibling_tag.name and sibling_tag.name == "title":
title_tag = sibling_tag
else:
title_tag = raw_parser.title(tag)
if parent_tag_name and p_parent_tag_name:
if (
title_tag
and title_tag.parent.name
and title_tag.parent.parent.name
and title_tag.parent.name == parent_tag_name
and title_tag.parent.parent.name == p_parent_tag_name
):
pass
else:
title_tag = None
return title_tag
def title_text(
tag, parent_tag_name=None, p_parent_tag_name=None, direct_sibling_only=False
):
"""Extract the text of a title tag and sometimes inspect its parents"""
title = None
title_tag = title_tag_inspected(
tag, parent_tag_name, p_parent_tag_name, direct_sibling_only
)
if title_tag:
title = utils.node_contents_str(title_tag)
return title
def caption_tag_inspected(tag, parent_tag_name=None):
caption_tag = raw_parser.caption(tag)
if parent_tag_name and caption_tag and caption_tag.parent.name != parent_tag_name:
caption_tag = None
return caption_tag
def label_tag_inspected(tag, parent_tag_name=None):
label_tag = raw_parser.label(tag)
if parent_tag_name and label_tag and label_tag.parent.name != parent_tag_name:
label_tag = None
return label_tag
def label(tag, parent_tag_name=None):
label = None
label_tag = label_tag_inspected(tag, parent_tag_name)
if label_tag:
label = utils.node_contents_str(label_tag)
return label
def full_title_json(soup):
return xml_to_html(True, full_title(soup))
def impact_statement_json(soup):
return xml_to_html(True, impact_statement(soup))
def acknowledgements_json(soup):
if raw_parser.acknowledgements(soup):
return body_block_content_render(raw_parser.acknowledgements(soup))[0].get(
"content"
)
return None
def keywords_json(soup, html_flag=True):
| |
exc:
log.error('User not found: {0}'.format(name))
log.error('nbr: {0}'.format(exc.winerror))
log.error('ctx: {0}'.format(exc.funcname))
log.error('msg: {0}'.format(exc.strerror))
return False
else:
log.error('User {0} is currently logged in.'.format(name))
return False
# Remove the User Profile directory
if purge:
try:
sid = getUserSid(name)
win32profile.DeleteProfile(sid)
except pywintypes.error as exc:
(number, context, message) = exc
if number == 2: # Profile Folder Not Found
pass
else:
log.error('Failed to remove profile for {0}'.format(name))
log.error('nbr: {0}'.format(exc.winerror))
log.error('ctx: {0}'.format(exc.funcname))
log.error('msg: {0}'.format(exc.strerror))
return False
# And finally remove the user account
try:
win32net.NetUserDel(None, name)
except win32net.error as exc:
(number, context, message) = exc
log.error('Failed to delete user {0}'.format(name))
log.error('nbr: {0}'.format(exc.winerror))
log.error('ctx: {0}'.format(exc.funcname))
log.error('msg: {0}'.format(exc.strerror))
return False
return True
def getUserSid(username):
'''
Get the Security ID for the user
Args:
username (str): The user name for which to look up the SID
Returns:
str: The user SID
CLI Example:
.. code-block:: bash
salt '*' user.getUserSid jsnuffy
'''
if six.PY2:
username = _to_unicode(username)
domain = win32api.GetComputerName()
if username.find(u'\\') != -1:
domain = username.split(u'\\')[0]
username = username.split(u'\\')[-1]
domain = domain.upper()
return win32security.ConvertSidToStringSid(
win32security.LookupAccountName(None, domain + u'\\' + username)[0])
def setpassword(name, password):
'''
Set the user's password
Args:
name (str): The user name for which to set the password
password (<PASSWORD>): <PASSWORD>
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.setpassword jsnuffy sup<PASSWORD>cr3t
'''
return update(name=name, password=password)
def addgroup(name, group):
'''
Add user to a group
Args:
name (str): The user name to add to the group
group (str): The name of the group to which to add the user
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.addgroup jsnuffy 'Power Users'
'''
if six.PY2:
name = _to_unicode(name)
group = _to_unicode(group)
name = _cmd_quote(name)
group = _cmd_quote(group).lstrip('\'').rstrip('\'')
user = info(name)
if not user:
return False
if group in user['groups']:
return True
cmd = 'net localgroup "{0}" {1} /add'.format(group, name)
ret = __salt__['cmd.run_all'](cmd, python_shell=True)
return ret['retcode'] == 0
def removegroup(name, group):
'''
Remove user from a group
Args:
name (str): The user name to remove from the group
group (str): The name of the group from which to remove the user
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.removegroup jsnuffy 'Power Users'
'''
if six.PY2:
name = _to_unicode(name)
group = _to_unicode(group)
name = _cmd_quote(name)
group = _cmd_quote(group).lstrip('\'').rstrip('\'')
user = info(name)
if not user:
return False
if group not in user['groups']:
return True
cmd = 'net localgroup "{0}" {1} /delete'.format(group, name)
ret = __salt__['cmd.run_all'](cmd, python_shell=True)
return ret['retcode'] == 0
def chhome(name, home, **kwargs):
'''
Change the home directory of the user, pass True for persist to move files
to the new home directory if the old home directory exist.
Args:
name (str): The name of the user whose home directory you wish to change
home (str): The new location of the home directory
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.chhome foo \\\\fileserver\\home\\foo True
'''
if six.PY2:
name = _to_unicode(name)
home = _to_unicode(home)
kwargs = salt.utils.clean_kwargs(**kwargs)
persist = kwargs.pop('persist', False)
if kwargs:
salt.utils.invalid_kwargs(kwargs)
if persist:
log.info('Ignoring unsupported \'persist\' argument to user.chhome')
pre_info = info(name)
if not pre_info:
return False
if home == pre_info['home']:
return True
if not update(name=name, home=home):
return False
post_info = info(name)
if post_info['home'] != pre_info['home']:
return post_info['home'] == home
return False
def chprofile(name, profile):
'''
Change the profile directory of the user
Args:
name (str): The name of the user whose profile you wish to change
profile (str): The new location of the profile
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.chprofile foo \\\\fileserver\\profiles\\foo
'''
return update(name=name, profile=profile)
def chfullname(name, fullname):
'''
Change the full name of the user
Args:
name (str): The user name for which to change the full name
fullname (str): The new value for the full name
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.chfullname user 'First Last'
'''
return update(name=name, fullname=fullname)
def chgroups(name, groups, append=True):
'''
Change the groups this user belongs to, add append=False to make the user a
member of only the specified groups
Args:
name (str): The user name for which to change groups
groups (str, list): A single group or a list of groups to assign to the
user. For multiple groups this can be a comma delimited string or a
list.
append (bool, optional): True adds the passed groups to the user's
current groups. False sets the user's groups to the passed groups
only. Default is True.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' user.chgroups jsnuffy Administrators,Users True
'''
if six.PY2:
name = _to_unicode(name)
if isinstance(groups, string_types):
groups = groups.split(',')
groups = [x.strip(' *') for x in groups]
if six.PY2:
groups = [_to_unicode(x) for x in groups]
ugrps = set(list_groups(name))
if ugrps == set(groups):
return True
name = _cmd_quote(name)
if not append:
for group in ugrps:
group = _cmd_quote(group).lstrip('\'').rstrip('\'')
if group not in groups:
cmd = 'net localgroup "{0}" {1} /delete'.format(group, name)
__salt__['cmd.run_all'](cmd, python_shell=True)
for group in groups:
if group in ugrps:
continue
group = _cmd_quote(group).lstrip('\'').rstrip('\'')
cmd = 'net localgroup "{0}" {1} /add'.format(group, name)
out = __salt__['cmd.run_all'](cmd, python_shell=True)
if out['retcode'] != 0:
log.error(out['stdout'])
return False
agrps = set(list_groups(name))
return len(ugrps - agrps) == 0
def info(name):
'''
Return user information
Args:
name (str): Username for which to display information
Returns:
dict: A dictionary containing user information
- fullname
- username
- SID
- passwd (will always return None)
- comment (same as description, left here for backwards compatibility)
- description
- active
- logonscript
- profile
- home
- homedrive
- groups
- password_changed
- successful_logon_attempts
- failed_logon_attempts
- last_logon
- account_disabled
- account_locked
- password_never_expires
- disallow_change_password
- gid
CLI Example:
.. code-block:: bash
salt '*' user.info jsnuffy
'''
if six.PY2:
name = _to_unicode(name)
ret = {}
items = {}
try:
items = win32net.NetUserGetInfo(None, name, 4)
except win32net.error:
pass
if items:
groups = []
try:
groups = win32net.NetUserGetLocalGroups(None, name)
except win32net.error:
pass
ret['fullname'] = items['full_name']
ret['name'] = items['name']
ret['uid'] = win32security.ConvertSidToStringSid(items['user_sid'])
ret['passwd'] = items['password']
ret['comment'] = items['comment']
ret['description'] = items['comment']
ret['active'] = (not bool(items['flags'] & win32netcon.UF_ACCOUNTDISABLE))
ret['logonscript'] = items['script_path']
ret['profile'] = items['profile']
ret['failed_logon_attempts'] = items['bad_pw_count']
ret['successful_logon_attempts'] = items['num_logons']
secs = time.mktime(datetime.now().timetuple()) - items['password_age']
ret['password_changed'] = datetime.fromtimestamp(secs). \
strftime('%Y-%m-%d %H:%M:%S')
if items['last_logon'] == 0:
ret['last_logon'] = 'Never'
else:
ret['last_logon'] = datetime.fromtimestamp(items['last_logon']).\
strftime('%Y-%m-%d %H:%M:%S')
ret['expiration_date'] = datetime.fromtimestamp(items['acct_expires']).\
strftime('%Y-%m-%d %H:%M:%S')
ret['expired'] = items['password_expired'] == 1
if not ret['profile']:
ret['profile'] = _get_userprofile_from_registry(name, ret['uid'])
ret['home'] = items['home_dir']
ret['homedrive'] = items['home_dir_drive']
if not ret['home']:
ret['home'] = ret['profile']
ret['groups'] = groups
if items['flags'] & win32netcon.UF_DONT_EXPIRE_PASSWD == 0:
ret['password_never_expires'] = False
else:
ret['password_never_expires'] = True
if items['flags'] & win32netcon.UF_ACCOUNTDISABLE == 0:
ret['account_disabled'] = False
else:
ret['account_disabled'] = True
if items['flags'] & win32netcon.UF_LOCKOUT == 0:
ret['account_locked'] = False
else:
ret['account_locked'] = True
if items['flags'] & win32netcon.UF_PASSWD_CANT_CHANGE == 0:
ret['disallow_change_password'] = False
else:
ret['disallow_change_password'] = True
ret['gid'] = ''
return ret
else:
return {}
def _get_userprofile_from_registry(user, sid):
'''
In case net user doesn't return the userprofile we can get it from the
registry
Args:
user (str): The user name, used in debug message
sid (str): The sid to lookup in the registry
Returns:
str: Profile directory
'''
profile_dir = __salt__['reg.read_value'](
'HKEY_LOCAL_MACHINE',
u'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\{0}'.format(sid),
'ProfileImagePath'
)['vdata']
log.debug(u'user {0} with sid={2} profile is located at "{1}"'.format(user, profile_dir, sid))
return profile_dir
def list_groups(name):
'''
Return a list of groups the named user belongs to
Args:
name (str): The user name for which to list groups
Returns:
list: A list of groups to which the user belongs
CLI Example:
.. code-block:: bash
salt '*' user.list_groups foo
'''
if six.PY2:
name = _to_unicode(name)
ugrp = set()
try:
user = info(name)['groups']
except KeyError:
return False
for group in user:
ugrp.add(group.strip(' *'))
return sorted(list(ugrp))
def getent(refresh=False):
'''
Return the list of all info for all users
Args:
refresh (bool, optional): Refresh the cached user information. Useful
when used from | |
<reponame>smolins/alquimia-dev
#!/usr/bin/env python
"""
Program to compare the results of alquimia driven and pflotran native simulations.
Alquimia Copyright (c) 2013, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of any
required approvals from the U.S. Dept. of Energy). All rights reserved.
Alquimia is available under a BSD license. See LICENSE.txt for more
information.
If you have questions about your rights to use or distribute this software,
please contact Berkeley Lab's Technology Transfer and Intellectual Property
Management at <EMAIL> referring to Alquimia (LBNL Ref. 2013-119).
NOTICE. This software was developed under funding from the U.S. Department
of Energy. As such, the U.S. Government has been granted for itself and
others acting on its behalf a paid-up, nonexclusive, irrevocable, worldwide
license in the Software to reproduce, prepare derivative works, and perform
publicly and display publicly. Beginning five (5) years after the date
permission to assert copyright is obtained from the U.S. Department of Energy,
and subject to any subsequent five (5) year renewals, the U.S. Government is
granted for itself and others acting on its behalf a paid-up, nonexclusive,
irrevocable, worldwide license in the Software to reproduce, prepare derivative
works, distribute copies to the public, perform publicly and display publicly,
and to permit others to do so.
Authors: <NAME> <<EMAIL>>
"""
from __future__ import print_function
from __future__ import division
import argparse
from collections import deque
import datetime
import math
import os
import pprint
import re
import subprocess
import sys
import textwrap
import time
import traceback
if sys.version_info[0] == 2:
import ConfigParser as config_parser
else:
import configparser as config_parser
import numpy as np
pprinter = pprint.PrettyPrinter(indent=2)
txtwrap = textwrap.TextWrapper(width=78, subsequent_indent=4*" ")
class PFloTranObservationData(object):
"""
Simple class to parse and store a pflotran observation file
"""
_time_re = re.compile("^Time[\s]+\[([\w]+)\]$")
def __init__(self):
self.filename = None
self.num_columns = None
self.time_units = None
self.column_names = []
self.columns = None
def __str__(self):
message = []
message.append("PFloTran data :")
message.append(" Filename : {0}".format(self.filename))
message.append(" Number of columns : {0}".format(self.num_columns))
message.append(" Time units : {0}".format(self.time_units))
message.append(" Column names ({0}) : {1}".format(len(self.column_names),
self.column_names))
message.append(" Number of rows : {0}".format(self.columns.shape[0]))
return "\n".join(message)
def read(self, filebase):
self.filename = filebase + "-obs-0.tec"
# manually process the header, then read the data columns with numpy
with open(self.filename, 'r') as obs_file:
header_line = obs_file.readline()
self._process_header(header_line)
self.columns = np.loadtxt(self.filename, comments='"')
#print(self.columns)
def _process_header(self, header_line):
header = header_line.split(',')
self.num_columns = len(header)
self.column_names.append("Time")
time_field = header[0].strip(' "')
match = self._time_re.match(time_field)
if match:
self.time_units = match.group(1)
else:
# default seconds or error...?
raise Exception("ERROR: Could not determine time units in file '{0}'."
"\n Time field : '{1}'".format(self.filename,
time_field))
for column_header in header[1:]:
column = column_header.strip(' "')
fields = column.split("all")
self.column_names.append(fields[0].strip())
if len(self.column_names) != self.num_columns:
raise Exception("ERROR: Could not determine all column names in "
"observation file.\n Expected {0}, found {1}.\n"
" Identified : {2}\n Header: {3}".format(
self.num_columns, len(self.column_names), self.column_names,
header_line))
class AlquimiaObservationData(object):
"""
Simple class to parse and store the data from an alquimia
batch_chem output file.
"""
_time_re = re.compile("^Time[\s]+\[([\w]+)\]$")
def __init__(self):
self.filename = None
self.num_columns = None
self.time_units = None
self.column_names = []
self.columns = None
def __str__(self):
message = []
message.append("Alquimia data :")
message.append(" Filename : {0}".format(self.filename))
message.append(" Number of columns : {0}".format(self.num_columns))
message.append(" Time units : {0}".format(self.time_units))
message.append(" Column names ({0}) : {1}".format(len(self.column_names),
self.column_names))
message.append(" Number of rows : {0}".format(self.columns.shape[0]))
return "\n".join(message)
def read(self, filebase):
self.filename = filebase + ".txt"
# manually process the header, then read the data columns with numpy
with open(self.filename, 'r') as obs_file:
header_line = obs_file.readline()
self._process_header(header_line)
self.columns = np.loadtxt(self.filename, comments='#')
#print(self.columns)
def _process_header(self, header_line):
header = header_line.strip("#")
header = header.strip()
header = header.split(',')
self.num_columns = len(header)
self.column_names.append("Time")
time_field = header[0].strip(' "')
match = self._time_re.match(time_field)
if match:
self.time_units = match.group(1)
else:
# default seconds or error...?
raise Exception("ERROR: Could not determine time units in file '{0}'."
"\n Time field : '{1}'".format(self.filename,
time_field))
for column_header in header[1:]:
column = column_header.strip(' "')
self.column_names.append(column)
if len(self.column_names) != self.num_columns:
raise Exception("ERROR: Could not determine all column names in "
"observation file.\n Expected {0}, found {1}.\n"
" Identified : {2}\n Header: {3}".format(
self.num_columns, len(self.column_names), self.column_names,
header_line))
class TestManager(object):
def __init__(self):
self._config_filename = None
self._alquimia = None
self._pflotran = None
self._test_info = None
self._log_filename = None
self._test_log = None
self.report = {}
self._setup_logfile()
def __str__(self):
message = ["Alquimia Batch Chemistry Test Manager:"]
message.append(" log file : {0}".format(self._log_filename))
message.append(" config file : {0}".format(self._config_filename))
message.append(" alquimia : {0}".format(self._alquimia))
message.append(" pflotran : {0}".format(self._pflotran))
return "\n".join(message)
def set_alquimia(self, alquimia):
self._alquimia = self._check_executable(alquimia)
def set_pflotran(self, pflotran):
self._pflotran = self._check_executable(pflotran)
def get_tests_from_config_file(self, config_filename):
"""
Read a configuration file of the form:
[test-name]
alquimia = alquimia-inputfile-prefix
pflotran = pflotran-inputfile-prefix
NOTES:
* the input filenames are prefix only. The suffix .cfg,
.in, etc will be added automatically.
"""
if config_filename == None:
raise Exception("Error, must provide a test config filename")
self._config_filename = config_filename
#print("Reading config file : {0}".format(self._config_filename))
config = config_parser.SafeConfigParser()
config.read(self._config_filename)
self._test_info = {}
for name in config.sections():
self._test_info[name] = {}
for item in config.items(name):
self._test_info[name][item[0]] = item[1]
#pprinter.pprint(self._test_info)
def run_all_tests(self, timeout):
print("Running tests :")
for t in self._test_info:
status = self.run_test(t, timeout)
if status == 0:
print(".", end='', file=sys.stdout)
else:
print("F", end='', file=sys.stdout)
sys.stdout.flush()
print("", file=sys.stdout)
def run_test(self, test_name, timeout):
status = -1
if test_name in self._test_info:
print(70*'_', file=self._test_log)
print("Running test : {0}".format(test_name), file=self._test_log)
test = self._test_info[test_name]
alquimia_status = self._run_alquimia(test["alquimia"], timeout)
pflotran_status = self._run_pflotran(test["pflotran"], timeout)
if alquimia_status == 0 and pflotran_status == 0:
status = compare_results(self._test_log,
test["alquimia"],
test["pflotran"])
else:
print("ERROR: test name is not "
"valid: '{0}'".format(options.test))
print(" Valid tests are: ")
pprinter.pprint(tests.keys())
status = 1
self.report[test_name] = status
return status
def _setup_logfile(self):
self._log_filename = "alquimia-tests-{0}.testlog".format(datetime.datetime.today().strftime("%Y-%m-%d_%H-%M-%S"))
self._test_log = open(self._log_filename, 'w')
print("Alquimia / PFloTran Batch Chemistry Test Log", file=self._test_log)
print("System Info :", file=self._test_log)
print(" platform : {0}".format(sys.platform), file=self._test_log)
def _run_job(self, name, command, timeout):
print(" {0}".format(" ".join(command)), file=self._test_log)
run_stdout = open(name + ".stdout", 'w')
start = time.time()
proc = subprocess.Popen(command,
shell=False,
stdout=run_stdout,
stderr=subprocess.STDOUT)
while proc.poll() is None:
time.sleep(0.1)
if time.time() - start > timeout:
proc.terminate()
time.sleep(0.1)
message = txtwrap.fill(
"ERROR: job '{0}' has exceeded timeout limit of "
"{1} seconds.".format(name, timeout))
print(''.join(['\n', message, '\n']), file=self._test_log)
run_stdout.close()
return abs(proc.returncode)
def _run_alquimia(self, test_name, timeout):
"""
Generate the run command, then run alquimia's batch_chem driver:
batch_chem -d -i test_name.cfg
"""
command = []
command.append(self._alquimia)
command.append("-d")
command.append("-i")
input_file_name = test_name + ".cfg"
command.append(input_file_name)
if os.path.isfile(test_name + ".txt"):
os.rename(test_name + ".txt",
test_name + ".txt.old")
if os.path.isfile(test_name + ".stdout"):
os.rename(test_name + ".stdout",
test_name + ".stdout.old")
status = self._run_job(test_name, command, timeout)
if status != 0:
message = txtwrap.fill(
"ERROR : {name} : alquimia driver return an error "
"code ({status}) indicating the simulation may have "
"failed. Please check '{name}.stdout' for error "
"messages.".format(
name=test_name, status=status))
print("".join(['\n', message, '\n']), file=self._test_log)
return status
def _run_pflotran(self, test_name, timeout):
PFLOTRAN_SUCCESS = 86
command = []
command.append(self._pflotran)
command.append("-input_prefix")
command.append(test_name)
if os.path.isfile(test_name + "-obs-0.tec"):
os.rename(test_name + "-obs-0.tec",
test_name + "-obs-0.tec.old")
if os.path.isfile(test_name + ".out"):
os.rename(test_name + ".out",
test_name + ".out.old")
if os.path.isfile(test_name + ".stdout"):
os.rename(test_name + ".stdout",
test_name + ".stdout.old")
pflotran_status = self._run_job(test_name, command, timeout)
# pflotran returns 0 on an error (e.g. can't find an input
# file), 86 on success. 59 for timeout errors?
if pflotran_status != PFLOTRAN_SUCCESS:
status = 1
message = txtwrap.fill(
"ERROR : {name} : pflotran return an error "
"code ({status}) indicating the simulation may have "
"failed. Please check '{name}.out' and '{name}.stdout' "
"for error messages.".format(
name=test_name, status=status))
print("".join(['\n', message, '\n']), file=self._test_log)
else:
status = 0
return status
def _check_executable(self, executable):
"""
Try to verify that we have something reasonable for the executable
"""
# absolute path to the executable
executable = os.path.abspath(executable)
# is it a valid file?
if not os.path.isfile(executable):
raise Exception("ERROR: executable is not a valid file: "
"'{0}'".format(executable))
return executable
def compare_columns(test_log, name,
alquimia_data, aindex,
pflotran_data, pindex):
status = 0
if not np.array_equal(pflotran_data.columns[:, pindex],
alquimia_data.columns[:, aindex]):
status = 1
different = (pflotran_data.columns[:, pindex] !=
alquimia_data.columns[:, aindex])
for i in range(len(different)):
if different[i]:
print("FAIL: observations are not equal for column '{0}': row = "
"{1} pflotran = {2} alquimia = {3}".format(name,
i, pflotran_data.columns[i, pindex],
alquimia_data.columns[i, aindex]), file=test_log)
return status
def compare_results(test_log, alquimia_name, pflotran_name):
| |
if self.paren_level > 0:
prev = self.code_list[-1]
if prev.kind == 'lt' or (prev.kind, prev.value) == ('op', ','):
self.blank()
self.add_token('op', val)
return
self.blank()
self.add_token('op', val)
self.blank()
#@+node:ekr.20200107165250.47: *5* orange.star_star_op
def star_star_op(self):
"""Put a ** operator, with a special case for **kwargs."""
val = '**'
self.clean('blank')
if self.paren_level > 0:
prev = self.code_list[-1]
if prev.kind == 'lt' or (prev.kind, prev.value) == ('op', ','):
self.blank()
self.add_token('op', val)
return
self.blank()
self.add_token('op', val)
self.blank()
#@+node:ekr.20200107165250.48: *5* orange.word & word_op
def word(self, s):
"""Add a word request to the code list."""
assert s and isinstance(s, str), repr(s)
if self.square_brackets_stack:
# A previous 'op-no-blanks' token may cancel this blank.
self.blank()
self.add_token('word', s)
elif self.in_arg_list > 0:
self.add_token('word', s)
self.blank()
else:
self.blank()
self.add_token('word', s)
self.blank()
def word_op(self, s):
"""Add a word-op request to the code list."""
assert s and isinstance(s, str), repr(s)
self.blank()
self.add_token('word-op', s)
self.blank()
#@+node:ekr.20200118120049.1: *4* orange: Split/join
#@+node:ekr.20200107165250.34: *5* orange.split_line & helpers
def split_line(self, node, token):
"""
Split token's line, if possible and enabled.
Return True if the line was broken into two or more lines.
"""
assert token.kind in ('newline', 'nl'), repr(token)
# Return if splitting is disabled:
if self.max_split_line_length <= 0: # pragma: no cover (user option)
return False
# Return if the node can't be split.
if not is_long_statement(node):
return False
# Find the *output* tokens of the previous lines.
line_tokens = self.find_prev_line()
line_s = ''.join([z.to_string() for z in line_tokens])
# Do nothing for short lines.
if len(line_s) < self.max_split_line_length:
return False
# Return if the previous line has no opening delim: (, [ or {.
if not any(z.kind == 'lt' for z in line_tokens): # pragma: no cover (defensive)
return False
prefix = self.find_line_prefix(line_tokens)
# Calculate the tail before cleaning the prefix.
tail = line_tokens[len(prefix) :]
# Cut back the token list: subtract 1 for the trailing line-end.
self.code_list = self.code_list[: len(self.code_list) - len(line_tokens) - 1]
# Append the tail, splitting it further, as needed.
self.append_tail(prefix, tail)
# Add the line-end token deleted by find_line_prefix.
self.add_token('line-end', '\n')
return True
#@+node:ekr.20200107165250.35: *6* orange.append_tail
def append_tail(self, prefix, tail):
"""Append the tail tokens, splitting the line further as necessary."""
tail_s = ''.join([z.to_string() for z in tail])
if len(tail_s) < self.max_split_line_length:
# Add the prefix.
self.code_list.extend(prefix)
# Start a new line and increase the indentation.
self.add_token('line-end', '\n')
self.add_token('line-indent', self.lws + ' ' * 4)
self.code_list.extend(tail)
return
# Still too long. Split the line at commas.
self.code_list.extend(prefix)
# Start a new line and increase the indentation.
self.add_token('line-end', '\n')
self.add_token('line-indent', self.lws + ' ' * 4)
open_delim = Token(kind='lt', value=prefix[-1].value)
value = open_delim.value.replace('(', ')').replace('[', ']').replace('{', '}')
close_delim = Token(kind='rt', value=value)
delim_count = 1
lws = self.lws + ' ' * 4
for i, t in enumerate(tail):
if t.kind == 'op' and t.value == ',':
if delim_count == 1:
# Start a new line.
self.add_token('op-no-blanks', ',')
self.add_token('line-end', '\n')
self.add_token('line-indent', lws)
# Kill a following blank.
if i + 1 < len(tail):
next_t = tail[i + 1]
if next_t.kind == 'blank':
next_t.kind = 'no-op'
next_t.value = ''
else:
self.code_list.append(t)
elif t.kind == close_delim.kind and t.value == close_delim.value:
# Done if the delims match.
delim_count -= 1
if delim_count == 0:
# Start a new line
self.add_token('op-no-blanks', ',')
self.add_token('line-end', '\n')
self.add_token('line-indent', self.lws)
self.code_list.extend(tail[i:])
return
lws = lws[:-4]
self.code_list.append(t)
elif t.kind == open_delim.kind and t.value == open_delim.value:
delim_count += 1
lws = lws + ' ' * 4
self.code_list.append(t)
else:
self.code_list.append(t)
g.trace('BAD DELIMS', delim_count)
#@+node:ekr.20200107165250.36: *6* orange.find_prev_line
def find_prev_line(self):
"""Return the previous line, as a list of tokens."""
line = []
for t in reversed(self.code_list[:-1]):
if t.kind in ('hard-newline', 'line-end'):
break
line.append(t)
return list(reversed(line))
#@+node:ekr.20200107165250.37: *6* orange.find_line_prefix
def find_line_prefix(self, token_list):
"""
Return all tokens up to and including the first lt token.
Also add all lt tokens directly following the first lt token.
"""
result = []
for i, t in enumerate(token_list):
result.append(t)
if t.kind == 'lt':
break
return result
#@+node:ekr.20200107165250.39: *5* orange.join_lines
def join_lines(self, node, token):
"""
Join preceding lines, if possible and enabled.
token is a line_end token. node is the corresponding ast node.
"""
if self.max_join_line_length <= 0: # pragma: no cover (user option)
return
assert token.kind in ('newline', 'nl'), repr(token)
if token.kind == 'nl':
return
# Scan backward in the *code* list,
# looking for 'line-end' tokens with tok.newline_kind == 'nl'
nls = 0
i = len(self.code_list) - 1
t = self.code_list[i]
assert t.kind == 'line-end', repr(t)
# Not all tokens have a newline_kind ivar.
assert t.newline_kind == 'newline' # type:ignore
i -= 1
while i >= 0:
t = self.code_list[i]
if t.kind == 'comment':
# Can't join.
return
if t.kind == 'string' and not self.allow_joined_strings:
# An EKR preference: don't join strings, no matter what black does.
# This allows "short" f-strings to be aligned.
return
if t.kind == 'line-end':
if getattr(t, 'newline_kind', None) == 'nl':
nls += 1
else:
break # pragma: no cover
i -= 1
# Retain at the file-start token.
if i <= 0:
i = 1
if nls <= 0: # pragma: no cover (rare)
return
# Retain line-end and and any following line-indent.
# Required, so that the regex below won't eat too much.
while True:
t = self.code_list[i]
if t.kind == 'line-end':
if getattr(t, 'newline_kind', None) == 'nl': # pragma: no cover (rare)
nls -= 1
i += 1
elif self.code_list[i].kind == 'line-indent':
i += 1
else:
break # pragma: no cover (defensive)
if nls <= 0: # pragma: no cover (defensive)
return
# Calculate the joined line.
tail = self.code_list[i:]
tail_s = tokens_to_string(tail)
tail_s = re.sub(r'\n\s*', ' ', tail_s)
tail_s = tail_s.replace('( ', '(').replace(' )', ')')
tail_s = tail_s.rstrip()
# Don't join the lines if they would be too long.
if len(tail_s) > self.max_join_line_length: # pragma: no cover (defensive)
return
# Cut back the code list.
self.code_list = self.code_list[:i]
# Add the new output tokens.
self.add_token('string', tail_s)
self.add_token('line-end', '\n')
#@-others
#@+node:ekr.20200107170847.1: *3* class OrangeSettings
class OrangeSettings:
pass
#@+node:ekr.20200107170126.1: *3* class ParseState
class ParseState:
"""
A class representing items in the parse state stack.
The present states:
'file-start': Ensures the stack stack is never empty.
'decorator': The last '@' was a decorator.
do_op(): push_state('decorator')
do_name(): pops the stack if state.kind == 'decorator'.
'indent': The indentation level for 'class' and 'def' names.
do_name(): push_state('indent', self.level)
do_dendent(): pops the stack once or twice if state.value == self.level.
"""
def __init__(self, kind, value):
self.kind = kind
self.value = value
def __repr__(self):
return f"State: {self.kind} {self.value!r}"
__str__ = __repr__
#@+node:ekr.20200122033203.1: ** TOT classes...
#@+node:ekr.20191222083453.1: *3* class Fstringify (TOT)
class Fstringify(TokenOrderTraverser):
"""A class to fstringify files."""
silent = True # for pytest. Defined in all entries.
line_number = 0
line = ''
#@+others
#@+node:ekr.20191222083947.1: *4* fs.fstringify
def fstringify(self, contents, filename, tokens, tree):
"""
Fstringify.fstringify:
f-stringify the sources given by (tokens, tree).
Return the resulting string.
"""
self.filename = filename
self.tokens = tokens
self.tree = tree
# Prepass: reassign tokens.
ReassignTokens().reassign(filename, tokens, tree)
# Main pass.
self.traverse(self.tree)
results = tokens_to_string(self.tokens)
return results
#@+node:ekr.20200103054101.1: *4* fs.fstringify_file (entry)
def fstringify_file(self, filename): # pragma: no cover
"""
Fstringify.fstringify_file.
The entry point for the fstringify-file command.
f-stringify the given external file with the Fstrinfify class.
Return True if the file was changed.
"""
tag = 'fstringify-file'
self.filename = filename
self.silent = False
tog = TokenOrderGenerator()
try:
contents, encoding, tokens, tree = tog.init_from_file(filename)
if not contents or not tokens or not tree:
print(f"{tag}: Can not fstringify: {filename}")
return False
results = self.fstringify(contents, filename, tokens, tree)
except Exception as e:
print(e)
return False
# Something besides newlines must change.
changed = regularize_nls(contents) != regularize_nls(results)
status = 'Wrote' if changed else 'Unchanged'
print(f"{tag}: {status:>9}: {filename}")
if changed:
write_file(filename, results, encoding=encoding)
return changed
#@+node:ekr.20200103065728.1: *4* fs.fstringify_file_diff (entry)
def fstringify_file_diff(self, filename): # pragma: no cover
"""
Fstringify.fstringify_file_diff.
The entry point for the diff-fstringify-file command.
Print the diffs that would resulf from the fstringify-file command.
Return True if the file would be changed.
"""
tag = 'diff-fstringify-file'
self.filename = filename
self.silent = | |
not_in_db = pc.productcheckentry_set.get(input_product_id="Test")
assert not_in_db.amount == 2
assert not_in_db.in_database is False
assert not_in_db.product_in_database is None
assert not_in_db.part_of_product_list == ""
assert not_in_db.migration_product is None
# change product list (the name should not appear anymore in the product check)
pl.name = "RenamedTestList"
pl.save()
pl_names = in_db.get_product_list_names()
assert len(pl_names) == 1
assert "AnotherTestList" in pl_names
# run again (should reset and recreate the results)
pc.perform_product_check()
assert pc.productcheckentry_set.count() == 2
assert ProductCheckEntry.objects.all().count() == 2
# run again with a specific migration source
pc.migration_source = pms2 # use the less preferred migration source
pc.perform_product_check()
assert pc.productcheckentry_set.count() == 2
in_db = pc.productcheckentry_set.get(input_product_id="myprod")
assert in_db.amount == 4
assert in_db.in_database is True
assert in_db.product_in_database is not None
assert in_db.part_of_product_list == pl2.hash + "\n" + pl.hash
assert in_db.migration_product.replacement_product_id == pmo2.replacement_product_id
pl_names = in_db.get_product_list_names()
assert len(pl_names) == 2
assert "AnotherTestList" in pl_names
assert "RenamedTestList" in pl_names # back after product check runs again
not_in_db = pc.productcheckentry_set.get(input_product_id="Test")
assert not_in_db.amount == 2
assert not_in_db.in_database is False
assert not_in_db.product_in_database is None
assert not_in_db.part_of_product_list == ""
assert not_in_db.migration_product is None
def test_recursive_product_check(self):
test_product_string = "myprod"
test_list = "myprod;myprod\nmyprod;myprod\n" \
"Test;Test"
p = mixer.blend(
"productdb.Product",
product_id=test_product_string,
vendor=Vendor.objects.get(id=1),
eox_update_time_stamp=_datetime.datetime.utcnow(),
eol_ext_announcement_date=_datetime.date(2016, 1, 1),
end_of_sale_date=_datetime.date(2016, 1, 1)
)
p2 = mixer.blend(
"productdb.Product",
product_id="replacement_pid",
vendor=Vendor.objects.get(id=1),
eox_update_time_stamp=_datetime.datetime.utcnow(),
eol_ext_announcement_date=_datetime.date(2016, 1, 1),
end_of_sale_date=_datetime.date(2016, 1, 1)
)
mixer.blend(
"productdb.Product",
product_id="another_replacement_pid",
vendor=Vendor.objects.get(id=1)
)
pms = mixer.blend("productdb.ProductMigrationSource", name="Preferred Migration Source", preference=60)
mixer.blend("productdb.ProductMigrationOption", product=p, migration_source=pms,
replacement_product_id="replacement_pid")
mixer.blend("productdb.ProductMigrationOption", product=p2, migration_source=pms,
replacement_product_id="another_replacement_pid")
pl = mixer.blend(
"productdb.ProductList",
name="TestList",
string_product_list="myprod"
)
pl2 = mixer.blend(
"productdb.ProductList",
name="AnotherTestList",
string_product_list="myprod"
)
pc = ProductCheck.objects.create(name="Test", input_product_ids=test_list, migration_source=pms)
pc.perform_product_check()
assert pc.productcheckentry_set.count() == 2
in_db = pc.productcheckentry_set.get(input_product_id="myprod")
assert in_db.amount == 4
assert in_db.in_database is True
assert in_db.product_in_database is not None
assert in_db.part_of_product_list == pl2.hash + "\n" + pl.hash
assert in_db.migration_product.replacement_product_id == "another_replacement_pid" # use the last element in the path
pl_names = in_db.get_product_list_names()
assert len(pl_names) == 2
assert "AnotherTestList" in pl_names
assert "TestList" in pl_names
not_in_db = pc.productcheckentry_set.get(input_product_id="Test")
assert not_in_db.amount == 2
assert not_in_db.in_database is False
assert not_in_db.product_in_database is None
assert not_in_db.part_of_product_list == ""
assert not_in_db.migration_product is None
def test_basic_product_check_with_less_preferred_migration_source(self):
"""only Product Migration sources that have a preference > 25 should be considered as preferred"""
test_product_string = "myprod"
test_list = "myprod;myprod\nmyprod;myprod\n" \
"Test;Test"
p = mixer.blend(
"productdb.Product",
product_id=test_product_string,
vendor=Vendor.objects.get(id=1)
)
pms1 = mixer.blend("productdb.ProductMigrationSource", name="Preferred Migration Source", preference=25)
pms2 = mixer.blend("productdb.ProductMigrationSource", name="Another Migration Source", preference=10)
pmo1 = mixer.blend("productdb.ProductMigrationOption", product=p, migration_source=pms1,
replacement_product_id="replacement")
pmo2 = mixer.blend("productdb.ProductMigrationOption", product=p, migration_source=pms2,
replacement_product_id="other_replacement")
pl = mixer.blend(
"productdb.ProductList",
name="TestList",
string_product_list="myprod"
)
pl2 = mixer.blend(
"productdb.ProductList",
name="AnotherTestList",
string_product_list="myprod"
)
pc = ProductCheck.objects.create(name="Test", input_product_ids=test_list)
pc.perform_product_check()
assert pc.productcheckentry_set.count() == 2
in_db = pc.productcheckentry_set.get(input_product_id="myprod")
assert in_db.amount == 4
assert in_db.migration_product is None
assert str(in_db) == "Test: myprod (4)"
pl_names = in_db.get_product_list_names()
assert len(pl_names) == 2
assert "AnotherTestList" in pl_names
assert "TestList" in pl_names
not_in_db = pc.productcheckentry_set.get(input_product_id="Test")
assert not_in_db.amount == 2
assert not_in_db.in_database is False
assert not_in_db.product_in_database is None
assert not_in_db.part_of_product_list == ""
assert not_in_db.migration_product is None
# run again with a specific migration source (should perform the product check as normal)
pc.migration_source = pms2 # use the less preferred migration source
pc.perform_product_check()
assert pc.productcheckentry_set.count() == 2
in_db = pc.productcheckentry_set.get(input_product_id="myprod")
assert in_db.amount == 4
assert in_db.in_database is True
assert in_db.product_in_database is not None
assert in_db.part_of_product_list == pl2.hash + "\n" + pl.hash
assert in_db.migration_product.replacement_product_id == pmo2.replacement_product_id
not_in_db = pc.productcheckentry_set.get(input_product_id="Test")
assert not_in_db.amount == 2
assert not_in_db.in_database is False
assert not_in_db.product_in_database is None
assert not_in_db.part_of_product_list == ""
assert not_in_db.migration_product is None
def test_recursive_product_check_with_less_preferred_migration_source(self):
"""test recursive Product Check with specific less preferred migration source"""
test_product_string = "myprod"
test_list = "myprod;myprod\nmyprod;myprod\n" \
"Test;Test"
p = mixer.blend(
"productdb.Product",
product_id=test_product_string,
vendor=Vendor.objects.get(id=1),
eox_update_time_stamp=_datetime.datetime.utcnow(),
eol_ext_announcement_date=_datetime.date(2016, 1, 1),
end_of_sale_date=_datetime.date(2016, 1, 1)
)
p2 = mixer.blend(
"productdb.Product",
product_id="replacement_pid",
vendor=Vendor.objects.get(id=1),
eox_update_time_stamp=_datetime.datetime.utcnow(),
eol_ext_announcement_date=_datetime.date(2016, 1, 1),
end_of_sale_date=_datetime.date(2016, 1, 1)
)
mixer.blend(
"productdb.Product",
product_id="another_replacement_pid",
vendor=Vendor.objects.get(id=1)
)
pms = mixer.blend("productdb.ProductMigrationSource", name="Preferred Migration Source", preference=25)
mixer.blend("productdb.ProductMigrationOption", product=p, migration_source=pms,
replacement_product_id="replacement_pid")
mixer.blend("productdb.ProductMigrationOption", product=p2, migration_source=pms,
replacement_product_id="another_replacement_pid")
pl = mixer.blend(
"productdb.ProductList",
name="TestList",
string_product_list="myprod"
)
pl2 = mixer.blend(
"productdb.ProductList",
name="AnotherTestList",
string_product_list="myprod"
)
pc = ProductCheck.objects.create(name="Test", input_product_ids=test_list, migration_source=pms)
pc.perform_product_check()
assert pc.productcheckentry_set.count() == 2
in_db = pc.productcheckentry_set.get(input_product_id="myprod")
assert in_db.amount == 4
assert in_db.in_database is True
assert in_db.product_in_database is not None
assert in_db.part_of_product_list == pl2.hash + "\n" + pl.hash
assert in_db.migration_product.replacement_product_id == "another_replacement_pid" # use the last element in the path
pl_names = in_db.get_product_list_names()
assert len(pl_names) == 2
assert "AnotherTestList" in pl_names
assert "TestList" in pl_names
not_in_db = pc.productcheckentry_set.get(input_product_id="Test")
assert not_in_db.amount == 2
assert not_in_db.in_database is False
assert not_in_db.product_in_database is None
assert not_in_db.part_of_product_list == ""
assert not_in_db.migration_product is None
@pytest.mark.usefixtures("import_default_vendors")
class TestProductMigrationOption:
def test_model(self):
test_product_id = "My Product ID"
replacement_product_id = "replaced product"
p = mixer.blend(
"productdb.Product",
product_id=test_product_id,
vendor=Vendor.objects.get(id=1)
)
repl_p = mixer.blend("productdb.Product", product_id=replacement_product_id)
promiggrp = ProductMigrationSource.objects.create(name="Test")
with pytest.raises(ValidationError) as exinfo:
ProductMigrationOption.objects.create(
migration_source=promiggrp
)
assert exinfo.match("\'product\': \[\'This field cannot be null.\'\]")
with pytest.raises(ValidationError) as exinfo:
ProductMigrationOption.objects.create(
product=p
)
assert exinfo.match("\'migration_source\': \[\'This field cannot be null.\'\]")
# test replacement_product_id with a product ID that is not in the database
pmo = ProductMigrationOption.objects.create(
product=p,
migration_source=promiggrp,
replacement_product_id="Missing Product"
)
assert pmo.is_replacement_in_db() is False
assert pmo.get_product_replacement_id() is None
assert pmo.is_valid_replacement() is True
assert pmo.get_valid_replacement_product() is None
assert str(pmo) == "replacement option for %s" % p.product_id
pmo.delete()
# test replacement_product_id with a product ID that is in the database
pmo2 = ProductMigrationOption.objects.create(
product=p,
migration_source=promiggrp,
replacement_product_id=replacement_product_id
)
assert pmo2.is_valid_replacement() is True
assert pmo2.is_replacement_in_db() is True
assert pmo2.get_product_replacement_id() == repl_p.id
assert pmo2.get_valid_replacement_product().id == repl_p.id
assert pmo2.get_valid_replacement_product().product_id == replacement_product_id
# test replacement_product_id with a product ID that is in the database but EoL announced
p = mixer.blend(
"productdb.Product",
product_id="eol_product",
vendor=Vendor.objects.get(id=1),
eox_update_time_stamp=_datetime.datetime.utcnow(),
eol_ext_announcement_date=_datetime.date(2016, 1, 1),
end_of_sale_date=_datetime.date(2016, 1, 1)
)
mixer.blend(
"productdb.Product",
product_id="replacement_eol_product",
vendor=Vendor.objects.get(id=1),
eox_update_time_stamp=_datetime.datetime.utcnow(),
eol_ext_announcement_date=_datetime.date(2016, 1, 1),
end_of_sale_date=_datetime.date(2016, 1, 1)
)
assert p.current_lifecycle_states == [Product.END_OF_SALE_STR]
pmo3 = ProductMigrationOption.objects.create(
product=p,
migration_source=promiggrp,
replacement_product_id="replacement_eol_product",
)
assert pmo3.is_valid_replacement() is False, "Should be False, because the product is EoL announced"
assert pmo3.is_replacement_in_db() is True
assert pmo3.get_valid_replacement_product() is None
def test_unique_together_constraint(self):
p = mixer.blend(
"productdb.Product",
product_id="Product",
vendor=Vendor.objects.get(id=1)
)
promiggrp = ProductMigrationSource.objects.create(name="Test")
ProductMigrationOption.objects.create(migration_source=promiggrp, product=p)
with pytest.raises(ValidationError) as exinfo:
ProductMigrationOption.objects.create(migration_source=promiggrp, product=p)
assert exinfo.match("Product Migration Option with this Product and Migration source already exists.")
def test_product_migration_group_set(self):
test_product_id = "My Product ID"
p = mixer.blend(
"productdb.Product",
product_id=test_product_id,
vendor=Vendor.objects.get(id=1)
)
assert p.get_product_migration_source_names_set() == []
promiggrp = ProductMigrationSource.objects.create(name="Test")
ProductMigrationOption.objects.create(
product=p,
migration_source=promiggrp,
replacement_product_id="Missing Product"
)
p.refresh_from_db()
assert p.get_product_migration_source_names_set() == ["Test"]
# test with additional migration group
promiggrp2 = ProductMigrationSource.objects.create(name="Test 2")
ProductMigrationOption.objects.create(
product=p,
migration_source=promiggrp2,
replacement_product_id="Additional Missing Product"
)
p.refresh_from_db()
assert p.get_product_migration_source_names_set() == ["Test", "Test 2"]
def test_no_migration_option_provided_in_product(self):
test_product_id = "My Product ID"
p = mixer.blend(
"productdb.Product",
product_id=test_product_id,
vendor=Vendor.objects.get(id=1)
)
assert p.has_migration_options() is False
assert p.get_preferred_replacement_option() is None
def test_single_valid_migration_option_provided_in_product(self):
test_product_id = "My Product ID"
p = mixer.blend(
"productdb.Product",
product_id=test_product_id,
vendor=Vendor.objects.get(id=1)
)
promiggrp = ProductMigrationSource.objects.create(name="Test")
pmo = ProductMigrationOption.objects.create(
product=p,
migration_source=promiggrp,
replacement_product_id="Missing Product"
)
p.refresh_from_db()
assert p.has_migration_options() is True
assert p.get_preferred_replacement_option() == pmo
assert pmo.is_valid_replacement() is True
def test_single_valid_migration_option_provided_in_product_without_replacement_id(self):
test_product_id = "My Product ID"
p = mixer.blend(
"productdb.Product",
product_id=test_product_id,
vendor=Vendor.objects.get(id=1)
)
promiggrp = ProductMigrationSource.objects.create(name="Test")
pmo = ProductMigrationOption.objects.create(
product=p,
migration_source=promiggrp
)
p.refresh_from_db()
assert p.has_migration_options() is True
assert p.get_preferred_replacement_option() == pmo
assert pmo.is_valid_replacement() is False
def test_multiple_migration_options_provided_in_product(self):
test_product_id = "My Product ID"
p = mixer.blend(
"productdb.Product",
product_id=test_product_id,
vendor=Vendor.objects.get(id=1)
)
promiggrp = ProductMigrationSource.objects.create(name="Test")
preferred_promiggrp = ProductMigrationSource.objects.create(name="Test2", preference=100)
pmo = ProductMigrationOption.objects.create(
product=p,
migration_source=promiggrp,
replacement_product_id="Missing Product"
)
pmo2 = ProductMigrationOption.objects.create(
product=p,
migration_source=preferred_promiggrp,
replacement_product_id="Another Missing Product"
)
p.refresh_from_db()
assert p.has_migration_options() is True
assert p.get_preferred_replacement_option() != pmo
assert p.get_preferred_replacement_option() == pmo2
assert pmo.is_valid_replacement() is True, "It is also a valid migration option, even if not the preferred one"
assert pmo2.is_valid_replacement() is True
def test_get_migration_path(self):
# create basic object structure
group1 = ProductMigrationSource.objects.create(name="Group One")
group2 = ProductMigrationSource.objects.create(name="Group Two", preference=100)
root_product = mixer.blend(
"productdb.Product",
product_id="C2960XS",
vendor=Vendor.objects.get(id=1)
)
p11 = mixer.blend(
"productdb.Product",
product_id="C2960XL",
vendor=Vendor.objects.get(id=1)
)
p12 = mixer.blend(
"productdb.Product",
product_id="C2960XT",
vendor=Vendor.objects.get(id=1)
)
p23 = mixer.blend(
"productdb.Product",
product_id="C2960XR",
vendor=Vendor.objects.get(id=1)
)
# root is replaced by 11 by Group One and by 12 by Group Two
ProductMigrationOption.objects.create(
product=root_product,
migration_source=group1,
replacement_product_id=p11.product_id
)
ProductMigrationOption.objects.create(
product=root_product,
migration_source=group2,
replacement_product_id=p12.product_id
)
# p12 is replaced by 23 by group 2
ProductMigrationOption.objects.create(
product=p12,
migration_source=group2,
replacement_product_id=p23.product_id
)
# get the preferred group for the root product
assert root_product.get_preferred_replacement_option().migration_source.name == group2.name
# get the new migration path for the preferred group
| |
<filename>ts3/filetransfer.py
#!/usr/bin/env python3
# The MIT License (MIT)
#
# Copyright (c) 2013-2018 <see AUTHORS.txt>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
This module contains an API for the TS3 file transfer interface.
"""
# Modules
# ------------------------------------------------
import socket
import time
import threading
# local
try:
from common import TS3Error
except ImportError:
from .common import TS3Error
# Data
# ------------------------------------------------
__all__ = [
"TS3FileTransferError",
"TS3UploadError",
"TS3DownloadError",
"TS3FileTransfer"]
# Exceptions
# ------------------------------------------------
class TS3FileTransferError(TS3Error):
"""
This is the base class for all exceptions in this module.
"""
class TS3UploadError(TS3FileTransferError):
"""
Is raised, when an upload fails.
"""
def __init__(self, send_size, err=None):
#: The number of sent bytes till the error occured.
self.send_size = send_size
#: If the upload failed due to a thrown exception, this attribute
#: contains it.
self.err = err
return None
def __str__(self):
tmp = "TS3 file upload failed. "
if self.err is not None:
tmp += str(self.err)
return tmp
class TS3DownloadError(TS3FileTransferError):
"""
Is raised, when a download fails.
"""
def __init__(self, read_size, err=None):
#: The number of read bytes untill the error occured.
self.read_size = read_size
#: If the download failed due to a thrown exception, this attribute
#: contains the original exception.
self.err = err
return None
def __str__(self):
tmp = "TS3 file download failed. "
if self.err is not None:
tmp += str(self.err)
return tmp
# Classes
# ------------------------------------------------
class TS3FileTransfer(object):
"""
A high-level TS3 file transfer handler.
The recommended methods to download or upload a file are:
* :meth:`init_download`
* :meth:`init_upload`
"""
# Counter for the client file transfer ids.
_FTID = 0
_FTID_LOCK = threading.Lock()
def __init__(self, ts3conn):
"""
Creates a new TS3FileTransfer object, that is associated with
the TS3Connection ts3conn. This means, that calls of
:meth:`init_download` and :meth:`init_upload` will use this
connection to authenticate the file transfer.
"""
self.ts3conn = ts3conn
return None
# Common stuff
# --------------------------------------------
@classmethod
def get_ftid(cls):
"""
:return:
Returns a unique id for a file transfer.
:rtype:
int
"""
with cls._FTID_LOCK:
tmp = cls._FTID
cls._FTID += 1
return tmp
@classmethod
def _ip_from_resp(self, ip_val):
"""
The value of the ip key in a TS3QueryResponse is a comma separated
list of ips and this method parses the list and returns the first ip.
>>> ts3ft._ip_from_resp('0.0.0.0,172.16.17.32')
'localhost'
>>> ts3ft._ip_from_resp('172.16.17.32,')
'172.16.17.32'
"""
ip_val = ip_val.split(",")
ip = ip_val[0]
if ip == "0.0.0.0":
ip = "localhost"
return ip
# Download
# --------------------------------------------
def init_download(self, output_file,
name, cid, cpw="", seekpos=0,
query_resp_hook=None, reporthook=None):
"""
This is the recommended method to download a file from a TS3 server.
**name**, **cid**, **cpw** and **seekpos** are the parameters for the
TS3 query command **ftinitdownload**. The parameter **clientftid** is
automatically created and unique for the whole runtime of the programm.
**query_resp_hook**, if provided, is called, when the response of the
ftinitdownload query has been received. Its single parameter is the
the response of the querry.
For downloading the file from the server, :meth:`download()` is called.
So take a look a this method for further information.
.. seealso::
* :meth:`~commands.TS3Commands.ftinitdownload`
* :func:`~urllib.request.urlretrieve`
"""
ftid = self.get_ftid()
resp = self.ts3conn.ftinitdownload(
clientftfid=ftid, name=name, cid=cid, cpw=cpw, seekpos=seekpos)
if query_resp_hook is not None:
query_resp_hook(resp)
return self.download_by_resp(
output_file=output_file, ftinitdownload_resp=resp,
seekpos=seekpos, reporthook=reporthook,
fallbackhost=self.ts3conn.telnet_conn.host)
@classmethod
def download_by_resp(cls, output_file, ftinitdownload_resp,
seekpos=0, reporthook=None, fallbackhost=None):
"""
This is *almost* a shortcut for:
>>> TS3FileTransfer.download(
... output_file = file,
... adr = (resp[0]["ip"], int(resp[0]["port"])),
... ftkey = resp[0]["ftkey"],
... seekpos = seekpos,
... total_size = resp[0]["size"],
... reporthook = reporthook
... )
Note, that the value of ``resp[0]["ip"]`` is a csv list and needs
to be parsed.
"""
if "ip" in ftinitdownload_resp[0]:
ip = cls._ip_from_resp(ftinitdownload_resp[0]["ip"])
elif fallbackhost:
ip = fallbackhost
else:
raise TS3DownloadError(0, "The response did not contain an ip.")
port = int(ftinitdownload_resp[0]["port"])
adr = (ip, port)
ftkey = ftinitdownload_resp[0]["ftkey"]
total_size = int(ftinitdownload_resp[0]["size"])
return cls.download(
output_file=output_file, adr=adr, ftkey=ftkey, seekpos=seekpos,
total_size=total_size, reporthook=reporthook)
@classmethod
def download(cls, output_file, adr, ftkey,
seekpos=0, total_size=0, reporthook=None):
"""
Downloads a file from a TS3 server in the file **output_file**. The
TS3 file transfer interface is specified with the address tuple **adr**
and the download with the file transfer key **ftkey**.
If **seekpos** and the total **size** are provided, the **reporthook**
function (lambda read_size, block_size, total_size: None) is called
after receiving a new block.
If you provide **seekpos** and **total_size**, this method will check,
if the download is complete and raise a :exc:`TS3DownloadError` if not.
Note, that if **total_size** is 0 or less, each download will be
considered as complete.
If no error is raised, the number of read bytes is returned.
:return:
The number of received bytes.
:rtype:
int
:raises TS3DownloadError:
If the download is incomplete or a socket error occured.
"""
# Convert the ftkey if necessairy
if isinstance(ftkey, str):
ftkey = ftkey.encode()
if seekpos < 0:
raise ValueError("Seekpos has to be >= 0!")
read_size = seekpos
block_size = 4096
try:
with socket.create_connection(adr) as sock:
sock.sendall(ftkey)
# Begin with the download.
if reporthook is not None:
reporthook(read_size, block_size, total_size)
while True:
data = sock.recv(block_size)
output_file.write(data)
read_size += len(data)
if reporthook is not None:
reporthook(read_size, block_size, total_size)
# Break, if the connection has been closed.
if not data:
break
# Catch all socket errors.
except OSError as err:
raise TS3DownloadError(read_size, err)
# Raise an error, if the download is not complete.
if read_size < total_size:
raise TS3DownloadError(read_size)
return read_size
# Upload
# --------------------------------------------
def init_upload(self, input_file,
name, cid, cpw="", overwrite=True, resume=False,
query_resp_hook=None, reporthook=None):
"""
This is the recommended method to upload a file to a TS3 server.
**name**, **cid**, **cpw**, **overwrite** and **resume** are the
parameters for the TS3 query command **ftinitdownload**.
The parameter **clientftid** is automatically created and unique for
the whole runtime of the programm and the value of **size** is
retrieved by the size of the **input_file**.
**query_resp_hook**, if provided, is called, when the response of the
ftinitupload query has been received. Its single parameter is the
the response of the querry.
For uploading the file to the server :meth:`upload` is called. So
take a look at this method for further information.
.. seealso::
* :meth:`~commands.TS3Commands.ftinitupload`
* :func:`~urllib.request.urlretrieve`
"""
overwrite = "1" if overwrite else "0"
resume = "1" if resume else "0"
input_file.seek(0, 2)
size = input_file.tell()
ftid = self.get_ftid()
resp = self.ts3conn.ftinitupload(
clientftfid=ftid, name=name, cid=cid, cpw=cpw, size=size,
overwrite=overwrite, resume=resume)
if query_resp_hook is not None:
query_resp_hook(resp)
return self.upload_by_resp(
input_file=input_file, ftinitupload_resp=resp,
reporthook=reporthook, fallbackhost=self.ts3conn.telnet_conn.host)
@classmethod
def upload_by_resp(cls, input_file, ftinitupload_resp,
reporthook=None, fallbackhost=None):
"""
This is *almost* a shortcut for:
>>> TS3FileTransfer.upload(
input_file = file,
adr = (resp[0]["ip"], int(resp[0]["port"])),
ftkey = resp[0]["ftkey"],
seekpos = resp[0]["seekpos"],
reporthook = reporthook
)
...
Note, that the value of ``resp[0]["ip"]`` is a csv list and needs
to be parsed.
For the final upload, :meth:`upload` is called.
"""
if "ip" in ftinitupload_resp[0]:
ip = cls._ip_from_resp(ftinitupload_resp[0]["ip"])
elif fallbackhost:
ip = fallbackhost
else:
raise TS3UploadError(0, "The response did not contain an ip.")
port = int(ftinitupload_resp[0]["port"])
adr = (ip, port)
ftkey = ftinitupload_resp[0]["ftkey"]
seekpos = int(ftinitupload_resp[0]["seekpos"])
return cls.upload(
input_file=input_file, adr=adr, ftkey=ftkey, seekpos=seekpos,
reporthook=reporthook)
@classmethod
def upload(cls, input_file, adr, ftkey,
seekpos=0, reporthook=None):
"""
Uploads the data in the file **input_file** to the TS3 server listening
| |
<filename>main.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
u"""
Created at 2020.01.02
A python wrapper for running the netprophet to replace snakemake
"""
import os
import sys
import json
import logging
from argparse import ArgumentParser, ArgumentError
from multiprocessing import Pool
from shutil import rmtree
from subprocess import check_call, CalledProcessError
from tqdm import tqdm
from CODE import prepare_resources
from CODE import weighted_avg_similar_dbds
from CODE import build_motif_network
from CODE import combine_networks
from CODE import convert_fire2meme
from CODE import parse_network_scores
from CODE import parse_motif_summary
from CODE import parse_quantized_bins
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(name)-12s %(levelname)-8s %(message)s")
def call(cmd):
u"""
:param cmd:
:return:
"""
with open(os.devnull, "w+") as w:
check_call(cmd, shell=True, stdout=w, stderr=w)
class SnakeMakePipe(object):
u"""
"""
def __init__(self, path: str, processes: int=1):
u"""
path to config file
:param path:
:param processes
"""
self.processes = processes
# self.__root__ = os.path.abspath(os.path.dirname(__file__))
self.__root__ = "/opt/NetProphet_2.0"
if not os.path.exists(path) or not os.path.isfile(path):
raise FileNotFoundError("Cannot find config file at %s" % path)
with open(path) as r:
self.config = json.load(r)
self.progress = os.path.join(self.config["NETPROPHET2_DIR"], "progress.json")
if self.check_progress(11):
logging.info("Please remove {} before re-run this pipeline".format(self.progress))
def check_progress(self, step):
u"""
:param step:
:return:
"""
progress = []
if os.path.exists(self.progress):
with open(self.progress) as r:
progress = json.load(r)
return step in progress
def log_progress(self, step):
progress = []
if os.path.exists(self.progress):
with open(self.progress) as r:
progress = json.load(r)
if step not in progress:
progress.append(step)
with open(self.progress, "w+") as w:
json.dump(progress, w, indent=4)
def step1(self):
u"""
STEP 1 to create output dir or files
:return:
"""
logging.info("STEP1: make_directories")
if self.check_progress(1):
logging.info("STEP1: skipped")
return
paths = [
os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
"tmp"
),
os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/"
),
os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"motif_inference/"
),
os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"motif_inference/network_scores/"
),
os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"motif_inference/network_bins/"
),
os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"motif_inference/motifs_pfm/"
),
os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"motif_inference/motifs_score/"
)
]
for i in paths:
if not os.path.exists(i):
logging.info("Create %s" % i)
os.makedirs(i)
else:
logging.info("%s exists" % i)
self.log_progress(1)
def step2(self):
u"""
:return:
"""
logging.info("STEP2: prepare_resources")
if not self.check_progress(1):
raise FileNotFoundError("Please run STEP1 before run STEP2")
else:
if not self.check_progress(2):
prepare_resources.main([
"-g", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_GENES"]
),
"-r", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_REGULATORS"]
),
"-e", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_EXPRESSION_DATA"]
),
"-c", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_SAMPLE_CONDITIONS"]
),
"-or", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
"tmp/rdata.expr"
),
"-of", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
"tmp/data.fc.tsv"
),
"-oa", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
"tmp/allowed.adj"
),
"-op1", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
"tmp/data.pert.adj"
),
"-op2", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
"tmp/data.pert.tsv"
),
])
self.log_progress(2)
def step3(self):
u"""
:return:
"""
logging.info("STEP3: map_np_network")
if not self.check_progress(2):
raise FileNotFoundError("Please run STEP2 before run STEP3")
else:
if not self.check_progress(3):
check_call(
"bash {program} -m -u {input_u} -t {input_t} -r {input_r} -a {input_a} -p {input_p} -d {input_d} -g {input_g} -f {input_f} -o {input_o} -n {output_n}".format(**{
"program": os.path.join(self.__root__, "SRC/NetProphet1/netprophet"),
"input_u": os.path.join(
self.config["NETPROPHET2_DIR"], "SRC/NetProphet1/"),
"input_t": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_EXPRESSION_DATA"]),
"input_r": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
"tmp/rdata.expr"
),
"input_a": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
"tmp/allowed.adj"
),
"input_p": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
"tmp/data.pert.adj"
),
"input_d": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_DE_ADJMTR"]
),
"input_g": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_GENES"]
),
"input_f": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_REGULATORS"]
),
"input_o": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/"
),
"output_n": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/np.adjmtr"
)
}),
shell=True
)
self.log_progress(3)
def step4(self):
u"""
data_fc_expr=${1}
pert_matrix=${2}
tf_names=${3}
output_adjmtr=${4}
use_serial=${5}
:return:
"""
logging.info("STEP4: map_bart_network")
if not self.check_progress(3):
raise FileNotFoundError("Please run STEP3 before run STEP4")
else:
if not self.check_progress(4):
check_call("Rscript --vanilla {program} fcFile={data_fc_expr} isPerturbedFile={pert_matrix} tfNameFile={tf_names} saveTo={output_adjmtr}.tsv mpiBlockSize={processes}".format(**{
"program": os.path.join(self.__root__, "CODE/build_bart_network.r"),
"data_fc_expr": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
"tmp/data.fc.tsv"
),
"pert_matrix": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
"tmp/data.pert.adj"
),
"tf_names": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_REGULATORS"]
),
"output_adjmtr": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/bn.adjmtr"
),
"processes": self.processes
}), shell=True)
# 推测,这里只是单纯的去除行名和列名
o = os.path.join(self.config["NETPROPHET2_DIR"], self.config["OUTPUT_DIR"], "networks/bn.adjmtr")
with open(o, "w+") as w:
with open(o + ".tsv") as r:
for idx, line in enumerate(r):
if idx > 0:
lines = line.split()
if len(lines) > 0:
w.write("\t".join(lines[1:]) + "\n")
self.log_progress(4)
def step5(self):
u"""
:return:
"""
logging.info("STEP5: weighted_average_np_network")
if not self.check_progress(4):
raise FileNotFoundError("Please run STEP4 before run STEP5")
else:
if not self.check_progress(5):
weighted_avg_similar_dbds.main([
"-n", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/np.adjmtr"
),
"-r", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_REGULATORS"]
),
"-a", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["DBD_PID_DIR"]
),
"-d", "50", "-t", "single_dbds",
"-o", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/npwa.adjmtr"
)
])
self.log_progress(5)
def step6(self):
u"""
:return:
"""
logging.info("STEP6: weighted_average_bart_network")
if not self.check_progress(5):
raise FileNotFoundError("Please run STEP5 before run STEP6")
else:
if not self.check_progress(6):
weighted_avg_similar_dbds.main([
"-n", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/bn.adjmtr"
),
"-r", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_REGULATORS"]
),
"-a", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["DBD_PID_DIR"]
),
"-d", "50", "-t", "single_dbds",
"-o", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/bnwa.adjmtr"
)
])
self.log_progress(6)
def step7(self):
u"""
:return:
"""
logging.info("STEP7: combine_npwa_bnwa")
if not self.check_progress(6):
raise FileNotFoundError("Please run STEP6 before run STEP7")
else:
if not self.check_progress(7):
check_call(
"Rscript {program} {input_n} {input_b} {output_o}".format(**{
"program": os.path.join(self.__root__, "CODE/quantile_combine_networks.r"),
"input_n": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/npwa.adjmtr"
),
"input_b": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/bnwa.adjmtr"
),
"output_o": os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/npwa_bnwa.adjmtr"
)
}),
shell=True
)
self.log_progress(7)
def step8(self):
u"""
## Check if all motifs are ready
bash CODE/check_inference_status.sh ${OUTPUT_DIR}/motif_inference/motif_inference.log $REGULATORS $FLAG
:return:
"""
logging.info("STEP8: infer_motifs")
if not self.check_progress(7):
raise FileNotFoundError("Please run STEP7 before run STEP8")
else:
if not self.check_progress(8):
logging.info("Binning promoters based on network scores ... ")
parse_network_scores.main([
"-a", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/npwa_bnwa.adjmtr"
),
"-r", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_REGULATORS"]
),
"-t", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_GENES"]
),
"-o", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"motif_inference/network_scores"
)
])
parse_quantized_bins.main([
"-n", "20",
"-i", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"motif_inference/network_scores"
),
"-o", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"motif_inference/network_bins"
),
])
logging.info("Done")
promoter = os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_PROMOTERS"]
)
out_dir = os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"]
)
tasks = []
with open(os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_REGULATORS"])
) as r:
for regulator in r:
regulator = regulator.strip()
tasks.append(
"perl {FIREDIR}/fire.pl --expfiles={OUTDIR} --exptype=discrete --fastafile_dna={PROMOTER} --k=7 --jn=20 --jn_t=16 --nodups=1 --dorna=0 --dodnarna=0".format(**{
"FIREDIR": os.getenv("FIREDIR"),
"OUTDIR": os.path.join(out_dir, "motif_inference/network_bins", regulator),
"PROMOTER": promoter
})
)
try:
with Pool(self.processes) as p:
list(tqdm(p.imap(call, tasks), total=len(tasks)))
except CalledProcessError as err:
logging.error(err)
exit(1)
self.log_progress(8)
def step9(self):
u"""
:return:
"""
logging.info("STEP9: score_motifs")
if not self.check_progress(8):
raise FileNotFoundError("Please run STEP8 before run STEP9")
else:
if not self.check_progress(9):
OUTPUT_DIR = os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"]
)
MOTIFS_DIR = os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"motif_inference/network_bins/"
)
REGULATORS = os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_REGULATORS"]
)
PROMOTERS = os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_PROMOTERS"]
)
MOTIFS_LIST = os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"], "motif_inference/motifs.txt"
)
logging.info("Parsing motif inference results ... ")
parse_motif_summary.main([
"-a", "True",
"-i", MOTIFS_DIR,
"-o", MOTIFS_LIST
])
convert_fire2meme.main([
"-i", MOTIFS_LIST,
"-o", os.path.join(OUTPUT_DIR, "motif_inference/motifs_pfm/")
])
logging.info("Done")
# score_motifs $ $PROMOTERS $ ${OUTPUT_DIR}/motif_inference/motif_scoring.log
FN_TF_PWM = os.path.join(OUTPUT_DIR, "motif_inference/motifs_pfm/") # directory of tf pwm
FN_PROMOTERS = PROMOTERS # promoter sequence file
OUT_FIMO = os.path.join(OUTPUT_DIR, "motif_inference/motifs_score") # directory of fimo alignment output
tasks1, tasks2, tasks3 = [], [], []
with open(REGULATORS) as r:
for regulator in r:
regulator = regulator.strip()
if not os.path.exists(os.path.join(FN_TF_PWM, regulator)):
continue
if os.path.exists(os.path.join(OUT_FIMO, regulator)):
rmtree(os.path.join(OUT_FIMO, regulator))
os.makedirs(os.path.join(OUT_FIMO, regulator))
tasks1.append("{fimo} -o {OUT_FIMO}/{regulator} --thresh 5e-3 {FN_TF_PWM}/{regulator} {FN_PROMOTERS}".format(**{
"OUT_FIMO": OUT_FIMO,
"regulator": regulator,
"FN_TF_PWM": FN_TF_PWM,
"FN_PROMOTERS": FN_PROMOTERS,
"fimo": os.path.join(self.__root__, "SRC/meme/bin/fimo")
}))
tasks2.append("sed '1d' {OUT_FIMO}/{regulator}/fimo.txt | cut -f 1,2,7 > {OUT_FIMO}/{regulator}/temp.txt".format(**{
"OUT_FIMO": OUT_FIMO,
"regulator": regulator,
}))
tasks3.append("ruby {program} -i {OUT_FIMO}/{regulator}/temp.txt > {OUT_FIMO}/{regulator}.summary".format(**{
"OUT_FIMO": OUT_FIMO,
"regulator": regulator,
"program": os.path.join(self.__root__, "CODE/estimate_affinity.rb")
}))
with Pool(self.processes) as p:
try:
list(tqdm(p.imap(call, tasks1), total=len(tasks1)))
except CalledProcessError as err:
pass
try:
list(tqdm(p.imap(call, tasks2), total=len(tasks2)))
list(tqdm(p.imap(call, tasks3), total=len(tasks3)))
except CalledProcessError as err:
logging.error(err)
exit(1)
self.log_progress(9)
def step10(self):
u"""
:return:
"""
logging.info("STEP10: build_motif_network")
if not self.check_progress(9):
raise FileNotFoundError("Please run STEP9 before run STEP10")
else:
if not self.check_progress(10):
build_motif_network.main([
"-i", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"motif_inference/motifs.txt"
),
"-r", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_REGULATORS"]
),
"-g", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_GENES"]
),
"-f", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"motif_inference/motifs_score/"
),
"-t", "robust",
"-v", str(self.config["MOTIF_THRESHOLD"]),
"-o", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/mn.adjmtr"
)
])
self.log_progress(10)
def step11(self):
u"""
:return:
"""
logging.info("STEP11: assemble_final_network")
if not self.check_progress(10):
raise FileNotFoundError("Please run STEP10 before run STEP11")
else:
if not self.check_progress(11):
combine_networks.main([
"-s", "resort",
"-n", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/npwa_bnwa.adjmtr"
),
"-b", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/mn.adjmtr"
),
"-od", os.path.join(self.config["NETPROPHET2_DIR"], self.config["OUTPUT_DIR"], "networks/"),
"-om", "npwa_bnwa_mn.adjmtr"
])
weighted_avg_similar_dbds.main([
"-n", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
"networks/", "npwa_bnwa_mn.adjmtr"
),
"-r", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["FILENAME_REGULATORS"]
),
"-a", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["RESOURCES_DIR"],
self.config["DBD_PID_DIR"]
),
"-d", "50", "-f", "single_dbds",
"-o", os.path.join(
self.config["NETPROPHET2_DIR"],
self.config["OUTPUT_DIR"],
self.config["FILENAME_NETPROPHET2_NETWORK"]
)
])
self.log_progress(11)
if __name__ == '__main__':
parser = ArgumentParser(description="NetProphet 2.0")
parser.add_argument("-c", "--config", type=str, required=True, help="Path to config file")
parser.add_argument("-p", "--processes", type=int, default=1, help="How many cpu to use")
if len(sys.argv) <= 1:
parser.print_help()
else:
try:
args = parser.parse_args(sys.argv[1:])
if not os.path.exists(args.config) or not os.path.isfile(args.config):
print("Please set the correct path to config file")
exit(1)
root_dir = os.path.abspath(os.path.dirname(__file__))
config = os.path.abspath(args.config)
if args.processes <= 0:
processes = 1
| |
<reponame>ndevenish/prime<gh_stars>1-10
# LIBTBX_SET_DISPATCHER_NAME prime.print_integration_pickle
"""
Author : Uervirojnangkoorn, M.
Created : 11/1/2015
Description : read integration pickles and view systemetic absences and beam X, Y position
"""
from __future__ import absolute_import, division, print_function
from six.moves import cPickle as pickle
from cctbx.array_family import flex
from iotbx import reflection_file_reader
import sys, math
from scitbx.matrix import sqr
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from cctbx.uctbx import unit_cell
from prime.postrefine.mod_leastsqr import good_unit_cell
from cctbx import statistics
from prime.postrefine.mod_input import read_frame, read_pickles
from six.moves import range
from six.moves import zip
def calc_wilson(observations_full, n_residues):
"""Caculate isotropic Wilson G and B-factors."""
if n_residues == 0:
return 0, 0
from prime.postrefine.mod_util import mx_handler
mxh = mx_handler()
asu_contents = mxh.get_asu_contents(n_residues)
try:
observations_as_f = observations_full.as_amplitude_array()
binner_template_asu = observations_as_f.setup_binner(auto_binning=True)
wp = statistics.wilson_plot(observations_as_f, asu_contents, e_statistics=True)
G = wp.wilson_intensity_scale_factor
B = wp.wilson_b
except Exception:
G, B = (0, 0)
return G, B
def get_miller_array_from_mtz(mtz_filename):
flag_hklisoin_found = False
miller_array_iso = None
if mtz_filename is not None:
flag_hklisoin_found = True
reflection_file_iso = reflection_file_reader.any_reflection_file(mtz_filename)
miller_arrays_iso = reflection_file_iso.as_miller_arrays()
is_found_iso_as_intensity_array = False
is_found_iso_as_amplitude_array = False
for miller_array in miller_arrays_iso:
if miller_array.is_xray_intensity_array():
miller_array_iso = miller_array.deep_copy()
is_found_iso_as_intensity_array = True
break
elif miller_array.is_xray_amplitude_array():
is_found_iso_as_amplitude_array = True
miller_array_converted_to_intensity = miller_array.as_intensity_array()
if is_found_iso_as_intensity_array == False:
if is_found_iso_as_amplitude_array:
miller_array_iso = miller_array_converted_to_intensity.deep_copy()
else:
flag_hklisoin_found = False
if miller_array_iso is not None:
perm = miller_array_iso.sort_permutation(by_value="resolution", reverse=True)
miller_array_iso = miller_array_iso.select(perm)
return flag_hklisoin_found, miller_array_iso
def read_input(args):
if len(args) == 0:
print(
"prime.print_integration_pickle: for viewing systematic absences and beam xy position from integration pickles."
)
print(
"usage: prime.print_integration_pickle data=integrated.lst pixel_size_mm=0.079346 check_sys_absent=True target_space_group=P212121"
)
exit()
data = []
hklrefin = None
pixel_size_mm = None
check_sys_absent = False
target_space_group = None
target_unit_cell = None
target_anomalous_flag = False
flag_plot = True
d_min = 0
d_max = 99
n_residues = 0
for i in range(len(args)):
pair = args[i].split("=")
if pair[0] == "data":
data.append(pair[1])
if pair[0] == "hklrefin":
hklrefin = pair[1]
if pair[0] == "pixel_size_mm":
pixel_size_mm = float(pair[1])
if pair[0] == "check_sys_absent":
check_sys_absent = bool(pair[1])
if pair[0] == "target_space_group":
target_space_group = pair[1]
if pair[0] == "target_unit_cell":
try:
tuc = pair[1].split(",")
a, b, c, alpha, beta, gamma = (
float(tuc[0]),
float(tuc[1]),
float(tuc[2]),
float(tuc[3]),
float(tuc[4]),
float(tuc[5]),
)
target_unit_cell = unit_cell((a, b, c, alpha, beta, gamma))
except Exception:
pass
if pair[0] == "target_anomalous_flag":
target_anomalous_flag = bool(pair[1])
if pair[0] == "flag_plot":
if pair[1] == "False":
flag_plot = False
if pair[0] == "d_min":
d_min = float(pair[1])
if pair[0] == "d_max":
d_max = float(pair[1])
if pair[0] == "n_residues":
n_residues = int(pair[1])
if len(data) == 0:
print("Please provide data path. (eg. data=/path/to/pickle/)")
exit()
if check_sys_absent:
if target_space_group is None:
print(
"Please provide target space group if you want to check systematic absence (eg. target_space_group=P212121)"
)
exit()
if pixel_size_mm is None:
print("Please specify pixel size (eg. pixel_size_mm=0.079346)")
exit()
return (
data,
hklrefin,
pixel_size_mm,
check_sys_absent,
target_unit_cell,
target_space_group,
target_anomalous_flag,
flag_plot,
d_min,
d_max,
n_residues,
)
if __name__ == "__main__":
cc_bin_low_thres = 0.25
beam_thres = 0.5
uc_tol = 20
# 0 .read input parameters and frames (pickle files)
data, hklrefin, pixel_size_mm, check_sys_absent_input, target_unit_cell, target_space_group, target_anomalous_flag, flag_plot, d_min, d_max, n_residues = read_input(
args=sys.argv[1:]
)
frame_files = read_pickles(data)
xbeam_set = flex.double()
ybeam_set = flex.double()
sys_abs_set = []
sys_abs_all = flex.double()
cc_bin_low_set = flex.double()
cc_bins_set = []
d_bins_set = []
oodsqr_bins_set = []
flag_good_unit_cell_set = []
print("Summary of integration pickles:")
print(
"(image file, min. res., max. res, beamx, beamy, n_refl, cciso, <cciso_bin>, a, b, c, mosaicity, residual, dd_mm, wavelength, good_cell?, G, B)"
)
uc_a = flex.double()
uc_b = flex.double()
uc_c = flex.double()
dd_mm = flex.double()
wavelength_set = flex.double()
for pickle_filename in frame_files:
check_sys_absent = check_sys_absent_input
observations_pickle = read_frame(pickle_filename)
pickle_filename_arr = pickle_filename.split("/")
pickle_filename_only = pickle_filename_arr[len(pickle_filename_arr) - 1]
flag_hklisoin_found, miller_array_iso = get_miller_array_from_mtz(hklrefin)
observations = observations_pickle["observations"][0]
swap_dict = {"test_xx1.pickle": 0, "tes_xx2.pickle": 0}
if pickle_filename_only in swap_dict:
from cctbx import sgtbx
cb_op = sgtbx.change_of_basis_op("a,c,b")
observations = observations.change_basis(cb_op)
# from cctbx import sgtbx
# cb_op = sgtbx.change_of_basis_op('c,b,a')
# observations = observations.change_basis(cb_op)
# apply constrain using the crystal system
# check systematic absent
if check_sys_absent:
try:
from cctbx.crystal import symmetry
miller_set = symmetry(
unit_cell=observations.unit_cell().parameters(),
space_group_symbol=target_space_group,
).build_miller_set(
anomalous_flag=target_anomalous_flag, d_min=observations.d_min()
)
observations = observations.customized_copy(
anomalous_flag=target_anomalous_flag,
crystal_symmetry=miller_set.crystal_symmetry(),
)
except Exception:
print(
"Cannot apply target space group: observed space group=",
observations.space_group_info(),
)
check_sys_absent = False
# check if the uc is good
flag_good_unit_cell = False
if check_sys_absent:
if target_unit_cell is None:
flag_good_unit_cell = True
else:
flag_good_unit_cell = good_unit_cell(
observations.unit_cell().parameters(),
None,
uc_tol,
target_unit_cell=target_unit_cell,
)
flag_good_unit_cell_set.append(flag_good_unit_cell)
# calculate partiality
wavelength = observations_pickle["wavelength"]
crystal_init_orientation = observations_pickle["current_orientation"][0]
detector_distance_mm = observations_pickle["distance"]
mm_predictions = pixel_size_mm * (observations_pickle["mapped_predictions"][0])
xbeam = observations_pickle["xbeam"]
ybeam = observations_pickle["ybeam"]
xbeam_set.append(xbeam)
ybeam_set.append(ybeam)
alpha_angle = flex.double(
[
math.atan(abs(pred[0] - xbeam) / abs(pred[1] - ybeam))
for pred in mm_predictions
]
)
spot_pred_x_mm = flex.double([pred[0] - xbeam for pred in mm_predictions])
spot_pred_y_mm = flex.double([pred[1] - ybeam for pred in mm_predictions])
# calculate mean unit cell
if flag_good_unit_cell:
uc_a.append(observations.unit_cell().parameters()[0])
uc_b.append(observations.unit_cell().parameters()[1])
uc_c.append(observations.unit_cell().parameters()[2])
dd_mm.append(detector_distance_mm)
wavelength_set.append(wavelength)
# resoultion filter
i_sel_res = observations.resolution_filter_selection(d_min=d_min, d_max=d_max)
observations = observations.select(i_sel_res)
alpha_angle = alpha_angle.select(i_sel_res)
spot_pred_x_mm = spot_pred_x_mm.select(i_sel_res)
spot_pred_y_mm = spot_pred_y_mm.select(i_sel_res)
# sort by resolution
perm = observations.sort_permutation(by_value="resolution", reverse=True)
observations = observations.select(perm)
alpha_angle = alpha_angle.select(perm)
spot_pred_x_mm = spot_pred_x_mm.select(perm)
spot_pred_y_mm = spot_pred_y_mm.select(perm)
from prime.postrefine.mod_partiality import partiality_handler
ph = partiality_handler()
r0 = ph.calc_spot_radius(
sqr(crystal_init_orientation.reciprocal_matrix()),
observations.indices(),
wavelength,
)
two_theta = observations.two_theta(wavelength=wavelength).data()
sin_theta_over_lambda_sq = (
observations.two_theta(wavelength=wavelength)
.sin_theta_over_lambda_sq()
.data()
)
ry, rz, re, nu, rotx, roty = (0, 0, 0.003, 0.5, 0, 0)
flag_beam_divergence = False
partiality_init, delta_xy_init, rs_init, rh_init = ph.calc_partiality_anisotropy_set(
crystal_init_orientation.unit_cell(),
rotx,
roty,
observations.indices(),
ry,
rz,
r0,
re,
nu,
two_theta,
alpha_angle,
wavelength,
crystal_init_orientation,
spot_pred_x_mm,
spot_pred_y_mm,
detector_distance_mm,
"Lorentzian",
flag_beam_divergence,
)
I_full = observations.data() / partiality_init
sigI_full = observations.sigmas() / partiality_init
observations_full = observations.customized_copy(data=I_full, sigmas=sigI_full)
wilson_G, wilson_B = calc_wilson(observations_full, n_residues)
# calculate R and cc with reference
cc_iso, cc_full_iso, cc_bin_low, cc_bin_med = (0, 0, 0, 0)
observations_asu = observations.map_to_asu()
observations_full_asu = observations_full.map_to_asu()
cc_bins = flex.double()
oodsqr_bins = flex.double()
d_bins = flex.double()
if flag_hklisoin_found:
# build observations dict
obs_dict = {}
for mi_asu, I, sigI, I_full, sigI_full in zip(
observations_asu.indices(),
observations_asu.data(),
observations_asu.sigmas(),
observations_full_asu.data(),
observations_full_asu.sigmas(),
):
obs_dict[mi_asu] = (I, sigI, I_full, sigI_full)
I_match = flex.double()
I_full_match = flex.double()
I_iso_match = flex.double()
d_match = flex.double()
oodsqr_match = flex.double()
for mi_asu, d, I_iso in zip(
miller_array_iso.indices(),
miller_array_iso.d_spacings().data(),
miller_array_iso.data(),
):
if mi_asu in obs_dict:
I, sigI, I_full, sigI_full = obs_dict[mi_asu]
I_match.append(I)
I_full_match.append(I_full)
I_iso_match.append(I_iso)
oodsqr_match.append(1 / (d ** 2))
d_match.append(d)
# calculate correlation
try:
cc_iso = np.corrcoef(I_iso_match, I_match)[0, 1]
cc_full_iso = np.corrcoef(I_iso_match, I_full_match)[0, 1]
except Exception:
pass
# scatter plot
if flag_plot and len(frame_files) == 1:
plt.subplot(211)
# plt.scatter(oodsqr_match, I_iso_match, s=10, marker='o', c='r')
plt.plot(oodsqr_match, I_iso_match)
plt.title("Reference intensity")
plt.xlabel("1/d^2")
plt.ylabel("I_ref")
plt.subplot(212)
# plt.scatter(oodsqr_match, I_match, s=10, marker='o', c='r')
plt.plot(oodsqr_match, I_match)
plt.title("Observed intensity CC=%.4g" % (cc_iso))
plt.xlabel("1/d^2")
plt.ylabel("I_obs")
plt.show()
# scatter bin plot
n_bins = 10
n_refl = int(round(len(I_match) / n_bins))
if len(I_match) > 0:
for i_bin in range(n_bins):
i_start = i_bin * n_refl
if i_bin < n_bins - 1:
i_end = (i_bin * n_refl) + n_refl
else:
i_end = -1
I_iso_bin = I_iso_match[i_start:i_end]
I_bin = I_match[i_start:i_end]
d_bin = d_match[i_start:i_end]
try:
cc_bin = np.corrcoef(I_iso_bin, I_bin)[0, 1]
except Exception:
cc_bin = 0
cc_bins.append(cc_bin)
try:
min_d_bin = np.min(d_bin)
except Exception:
min_d_bin = 1
d_bins.append(min_d_bin)
oodsqr_bins.append(1 / (min_d_bin ** 2))
if i_bin == 0:
cc_bin_low = cc_bin
if i_bin == 5:
cc_bin_med = cc_bin
if flag_plot and len(frame_files) == 1:
plt.subplot(2, 5, i_bin + 1)
plt.scatter(I_iso_bin, I_bin, s=10, marker="o", c="r")
plt.title(
"Bin %2.0f (%6.2f-%6.2f A) CC=%6.2f"
% (i_bin + 1, np.max(d_bin), np.min(d_bin), cc_bin)
)
if i_bin == 0:
plt.xlabel("I_ref")
plt.ylabel("I_obs")
if flag_plot and len(frame_files) == 1:
plt.show()
# print full detail if given a single file
if len(frame_files) == 1:
print("Crystal orientation")
print(crystal_init_orientation.crystal_rotation_matrix())
print("Direct matrix")
print(crystal_init_orientation.direct_matrix())
a, b, c, alpha, beta, gamma = observations.unit_cell().parameters()
txt_out_head = "{0:40} {1:5.2f} {2:5.2f} {3:5.2f} {4:5.2f} {5:5.0f} {6:6.2f} {7:6.2f} {8:6.2f} {9:6.2f} {10:6.2f} {11:6.2f} {12:6.2f} {13:6.2f} {14:6.2f} {15:6.2f} {16:6.2f} {20:6.4f} {17:5} {18:6.2f} {19:6.2f}".format(
pickle_filename_only
+ " ("
+ str(observations.crystal_symmetry().space_group_info())
+ ")",
observations.d_min(),
np.max(observations.d_spacings().data()),
xbeam,
ybeam,
len(observations.data()),
cc_iso,
np.mean(cc_bins),
a,
b,
c,
alpha,
beta,
gamma,
observations_pickle["mosaicity"],
observations_pickle["residual"],
detector_distance_mm,
flag_good_unit_cell,
wilson_G,
wilson_B,
wavelength,
)
print(txt_out_head)
cc_bin_low_set.append(cc_iso)
cc_bins_set.append(cc_bins)
d_bins_set.append(d_bins)
oodsqr_bins_set.append(oodsqr_bins)
sys_abs_lst = flex.double()
if check_sys_absent:
cn_refl = 0
for (
sys_absent_flag,
d_spacing,
miller_index_ori,
miller_index_asu,
I,
sigI,
) in zip(
observations.sys_absent_flags(),
observations.d_spacings().data(),
observations.indices(),
observations_asu.indices(),
observations.data(),
observations.sigmas(),
):
if sys_absent_flag[1]:
txt_out = | |
<filename>lib/circuitpython_nrf24l01/fake_ble.py<gh_stars>1-10
# The MIT License (MIT)
#
# Copyright (c) 2019 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Original research was done by <NAME> and his write-up can be found at
http://dmitry.gr/index.php?r=05.Projects&proj=11.%20Bluetooth%20LE%20fakery"""
from os import urandom
import struct
from micropython import const
from .rf24 import RF24, address_repr
def swap_bits(original):
"""This function reverses the bit order for a single byte."""
original &= 0xFF
reverse = 0
for _ in range(8):
reverse <<= 1
reverse |= original & 1
original >>= 1
return reverse
def reverse_bits(original):
"""This function reverses the bit order for an entire buffer protocol object."""
ret = bytearray(len(original))
for i, byte in enumerate(original):
ret[i] = swap_bits(byte)
return ret
def chunk(buf, data_type=0x16):
"""This function is used to pack data values into a block of data that
make up part of the BLE payload per Bluetooth Core Specifications."""
return bytearray([len(buf) + 1, data_type & 0xFF]) + buf
def whitener(buf, coef):
"""Whiten and dewhiten data according to the given coefficient."""
data = bytearray(buf)
for i, byte in enumerate(data):
res, mask = (0, 1)
for _ in range(8):
if coef & 1:
coef ^= 0x88
byte ^= mask
mask <<= 1
coef >>= 1
data[i] = byte ^ res
return data
def crc24_ble(data, deg_poly=0x65B, init_val=0x555555):
"""This function calculates a checksum of various sized buffers."""
crc = init_val
for byte in data:
crc ^= swap_bits(byte) << 16
for _ in range(8):
if crc & 0x800000:
crc = (crc << 1) ^ deg_poly
else:
crc <<= 1
crc &= 0xFFFFFF
return reverse_bits((crc).to_bytes(3, "big"))
BLE_FREQ = (2, 26, 80)
"""The BLE channel number is different from the nRF channel number."""
TEMPERATURE_UUID = const(0x1809) #: The Temperature Service UUID number
BATTERY_UUID = const(0x180F) #: The Battery Service UUID number
EDDYSTONE_UUID = const(0xFEAA) #: The Eddystone Service UUID number
class QueueElement:
"""A data structure used for storing received & decoded BLE payloads in
the :attr:`~circuitpython_nrf24l01.fake_ble.FakeBLE.rx_queue`.
:param bytes,bytearray buffer: the validated BLE payload (not including
the CRC checksum). The buffer passed here is decoded into this class's
properties.
"""
def __init__(self, buffer):
#: The transmitting BLE device's MAC address as a `bytes` object.
self.mac = bytes(buffer[2:8])
self.name = None
"""The transmitting BLE device's name. This will be a `str`, `bytes` object (if
a `UnicodeError` was caught), or `None` (if not included in the received
payload)."""
self.pa_level = None
"""The transmitting device's PA Level (if included in the received payload)
as an `int`.
.. note:: This value does not represent the received signal strength.
The nRF24L01 will receive anything over a -64 dbm threshold."""
self.data = []
"""A `list` of the transmitting device's data structures (if any).
If an element in this `list` is not an instance (or descendant) of the
`ServiceData` class, then it is likely a custom, user-defined, or unsupported
specification - in which case it will be a `bytearray` object."""
end = buffer[1] + 2
i = 8
while i < end:
size = buffer[i]
if size + i + 1 > end or i + 1 > end or not size:
# data seems malformed. just append the buffer & move on
self.data.append(buffer[i:end])
break
result = self._decode_data_struct(buffer[i + 1 : i + 1 + size])
if not result: # decoding failed
self.data.append(buffer[i : i + 1 + size])
i += 1 + size
def _decode_data_struct(self, buf):
"""Decode a data structure in a received BLE payload."""
# print("decoding", address_repr(buf, 0, " "))
if buf[0] not in (0x16, 0x0A, 0x08, 0x09):
return False # unknown/unsupported "chunk" of data
if buf[0] == 0x0A and len(buf) == 2: # if data is the device's TX-ing PA Level
self.pa_level = struct.unpack("b", buf[1:2])[0]
if buf[0] in (0x08, 0x09): # if data is a BLE device name
try:
self.name = buf[1:].decode()
except UnicodeError:
self.name = bytes(buf[1:])
if buf[0] == 0xFF: # if it is a custom/user-defined data format
self.data.append(buf) # return the raw buffer as a value
if buf[0] == 0x16: # if it is service data
service_data_uuid = struct.unpack("<H", buf[1:3])[0]
if service_data_uuid == TEMPERATURE_UUID:
service = TemperatureServiceData()
service.data = buf[3:]
self.data.append(service)
elif service_data_uuid == BATTERY_UUID:
service = BatteryServiceData()
service.data = buf[3:]
self.data.append(service)
elif service_data_uuid == EDDYSTONE_UUID:
service = UrlServiceData()
service.pa_level_at_1_meter = buf[4:5]
service.data = buf[5:]
self.data.append(service)
else:
self.data.append(buf)
return True
class FakeBLE(RF24):
"""A class to implement BLE advertisements using the nRF24L01."""
def __init__(self, spi, csn, ce_pin, spi_frequency=10000000):
super().__init__(spi, csn, ce_pin, spi_frequency=spi_frequency)
self._curr_freq = 2
self._show_dbm = False
self._ble_name = None
self._mac = urandom(6)
self._config = self._config & 3 | 0x10 # disable CRC
# disable auto_ack, dynamic payloads, all TX features, & auto-retry
self._aa, self._dyn_pl, self._features, self._retry_setup = (0,) * 4
self._addr_len = 4 # use only 4 byte address length
self._tx_address[:4] = b"\x71\x91\x7D\x6B"
with self:
super().open_rx_pipe(0, b"\x71\x91\x7D\x6B\0")
#: The internal queue of received BLE payloads' data.
self.rx_queue = []
self.rx_cache = bytearray(0)
"""The internal cache used when validating received BLE payloads."""
self.hop_channel()
def __exit__(self, *exc):
self._show_dbm = False
self._ble_name = None
return super().__exit__()
@property
def mac(self):
"""This attribute returns a 6-byte buffer that is used as the
arbitrary mac address of the BLE device being emulated."""
return self._mac
@mac.setter
def mac(self, address):
if address is None:
self._mac = urandom(6)
if isinstance(address, int):
self._mac = (address).to_bytes(6, "little")
elif isinstance(address, (bytearray, bytes)):
self._mac = address
if len(self._mac) < 6:
self._mac += urandom(6 - len(self._mac))
@property
def name(self):
"""The broadcasted BLE name of the nRF24L01."""
return self._ble_name
@name.setter
def name(self, _name):
if _name is not None:
if isinstance(_name, str):
_name = _name.encode("utf-8")
if not isinstance(_name, (bytes, bytearray)):
raise ValueError("name must be a bytearray or bytes object.")
if len(_name) > (18 - self._show_dbm * 3):
raise ValueError("name length exceeds maximum.")
self._ble_name = _name
@property
def show_pa_level(self) -> bool:
"""If this attribute is `True`, the payload will automatically include
the nRF24L01's :attr:`~circuitpython_nrf24l01.rf24.RF24.pa_level` in the
advertisement."""
return bool(self._show_dbm)
@show_pa_level.setter
def show_pa_level(self, enable: bool):
if enable and len(self.name) > 16:
raise ValueError("there is not enough room to show the pa_level.")
self._show_dbm = bool(enable)
def hop_channel(self):
"""Trigger an automatic change of BLE compliant channels."""
self._curr_freq += 1 if self._curr_freq < 2 else -2
self.channel = BLE_FREQ[self._curr_freq]
def whiten(self, data) -> bytearray:
"""Whitening the BLE packet data ensures there's no long repetition
of bits."""
coef = (self._curr_freq + 37) | 0x40
# print("buffer: 0x" + address_repr(data, 0))
# print(f"Whiten Coef: {hex(coef)} on channel {BLE_FREQ[self._curr_freq]}")
data = whitener(data, coef)
# print("whitened: 0x" + address_repr(data, 0))
return data
def _make_payload(self, payload) -> bytes:
"""Assemble the entire packet to be transmitted as a payload."""
if self.len_available(payload) < 0:
raise ValueError(
"Payload length exceeds maximum buffer size by "
"{} bytes".format(abs(self.len_available(payload)))
)
name_length = (len(self.name) + 2) if self.name is not None else 0
pl_size = 9 + len(payload) + name_length + self._show_dbm * 3
buf = bytes([0x42, pl_size]) + self.mac
buf += chunk(b"\x05", 1)
pa_level = b""
if self._show_dbm:
pa_level = chunk(struct.pack(">b", self.pa_level), 0x0A)
buf += pa_level
if name_length:
buf += chunk(self.name, 0x08)
buf += payload
# print(f"PL: {address_repr(buf, 0)} CRC: {address_repr(crc24_ble(buf), 0)}")
buf += crc24_ble(buf)
return buf
def len_available(self, hypothetical=b"") -> int:
"""This function will calculates how | |
import os
import sys
from unittest import mock
import pytest
from _pytest.config import ExitCode
from _pytest.mark import EMPTY_PARAMETERSET_OPTION
from _pytest.mark import MarkGenerator as Mark
from _pytest.nodes import Collector
from _pytest.nodes import Node
class TestMark:
@pytest.mark.parametrize("attr", ["mark", "param"])
@pytest.mark.parametrize("modulename", ["py.test", "pytest"])
def test_pytest_exists_in_namespace_all(self, attr, modulename):
module = sys.modules[modulename]
assert attr in module.__all__
def test_pytest_mark_notcallable(self):
mark = Mark()
with pytest.raises(TypeError):
mark()
def test_mark_with_param(self):
def some_function(abc):
pass
class SomeClass:
pass
assert pytest.mark.foo(some_function) is some_function
assert pytest.mark.foo.with_args(some_function) is not some_function
assert pytest.mark.foo(SomeClass) is SomeClass
assert pytest.mark.foo.with_args(SomeClass) is not SomeClass
def test_pytest_mark_name_starts_with_underscore(self):
mark = Mark()
with pytest.raises(AttributeError):
mark._some_name
def test_marked_class_run_twice(testdir):
"""Test fails file is run twice that contains marked class.
See issue#683.
"""
py_file = testdir.makepyfile(
"""
import pytest
@pytest.mark.parametrize('abc', [1, 2, 3])
class Test1(object):
def test_1(self, abc):
assert abc in [1, 2, 3]
"""
)
file_name = os.path.basename(py_file.strpath)
rec = testdir.inline_run(file_name, file_name)
rec.assertoutcome(passed=6)
def test_ini_markers(testdir):
testdir.makeini(
"""
[pytest]
markers =
a1: this is a webtest marker
a2: this is a smoke marker
"""
)
testdir.makepyfile(
"""
def test_markers(pytestconfig):
markers = pytestconfig.getini("markers")
print(markers)
assert len(markers) >= 2
assert markers[0].startswith("a1:")
assert markers[1].startswith("a2:")
"""
)
rec = testdir.inline_run()
rec.assertoutcome(passed=1)
def test_markers_option(testdir):
testdir.makeini(
"""
[pytest]
markers =
a1: this is a webtest marker
a1some: another marker
nodescription
"""
)
result = testdir.runpytest("--markers")
result.stdout.fnmatch_lines(
["*a1*this is a webtest*", "*a1some*another marker", "*nodescription*"]
)
def test_ini_markers_whitespace(testdir):
testdir.makeini(
"""
[pytest]
markers =
a1 : this is a whitespace marker
"""
)
testdir.makepyfile(
"""
import pytest
@pytest.mark.a1
def test_markers():
assert True
"""
)
rec = testdir.inline_run("--strict-markers", "-m", "a1")
rec.assertoutcome(passed=1)
def test_marker_without_description(testdir):
testdir.makefile(
".cfg",
setup="""
[tool:pytest]
markers=slow
""",
)
testdir.makeconftest(
"""
import pytest
pytest.mark.xfail('FAIL')
"""
)
ftdir = testdir.mkdir("ft1_dummy")
testdir.tmpdir.join("conftest.py").move(ftdir.join("conftest.py"))
rec = testdir.runpytest("--strict-markers")
rec.assert_outcomes()
def test_markers_option_with_plugin_in_current_dir(testdir):
testdir.makeconftest('pytest_plugins = "flip_flop"')
testdir.makepyfile(
flip_flop="""\
def pytest_configure(config):
config.addinivalue_line("markers", "flip:flop")
def pytest_generate_tests(metafunc):
try:
mark = metafunc.function.flipper
except AttributeError:
return
metafunc.parametrize("x", (10, 20))"""
)
testdir.makepyfile(
"""\
import pytest
@pytest.mark.flipper
def test_example(x):
assert x"""
)
result = testdir.runpytest("--markers")
result.stdout.fnmatch_lines(["*flip*flop*"])
def test_mark_on_pseudo_function(testdir):
testdir.makepyfile(
"""
import pytest
@pytest.mark.r(lambda x: 0/0)
def test_hello():
pass
"""
)
reprec = testdir.inline_run()
reprec.assertoutcome(passed=1)
@pytest.mark.parametrize("option_name", ["--strict-markers", "--strict"])
def test_strict_prohibits_unregistered_markers(testdir, option_name):
testdir.makepyfile(
"""
import pytest
@pytest.mark.unregisteredmark
def test_hello():
pass
"""
)
result = testdir.runpytest(option_name)
assert result.ret != 0
result.stdout.fnmatch_lines(
["'unregisteredmark' not found in `markers` configuration option"]
)
@pytest.mark.parametrize(
"spec",
[
("xyz", ("test_one",)),
("xyz and xyz2", ()),
("xyz2", ("test_two",)),
("xyz or xyz2", ("test_one", "test_two")),
],
)
def test_mark_option(spec, testdir):
testdir.makepyfile(
"""
import pytest
@pytest.mark.xyz
def test_one():
pass
@pytest.mark.xyz2
def test_two():
pass
"""
)
opt, passed_result = spec
rec = testdir.inline_run("-m", opt)
passed, skipped, fail = rec.listoutcomes()
passed = [x.nodeid.split("::")[-1] for x in passed]
assert len(passed) == len(passed_result)
assert list(passed) == list(passed_result)
@pytest.mark.parametrize(
"spec", [("interface", ("test_interface",)), ("not interface", ("test_nointer",))]
)
def test_mark_option_custom(spec, testdir):
testdir.makeconftest(
"""
import pytest
def pytest_collection_modifyitems(items):
for item in items:
if "interface" in item.nodeid:
item.add_marker(pytest.mark.interface)
"""
)
testdir.makepyfile(
"""
def test_interface():
pass
def test_nointer():
pass
"""
)
opt, passed_result = spec
rec = testdir.inline_run("-m", opt)
passed, skipped, fail = rec.listoutcomes()
passed = [x.nodeid.split("::")[-1] for x in passed]
assert len(passed) == len(passed_result)
assert list(passed) == list(passed_result)
@pytest.mark.parametrize(
"spec",
[
("interface", ("test_interface",)),
("not interface", ("test_nointer", "test_pass")),
("pass", ("test_pass",)),
("not pass", ("test_interface", "test_nointer")),
],
)
def test_keyword_option_custom(spec, testdir):
testdir.makepyfile(
"""
def test_interface():
pass
def test_nointer():
pass
def test_pass():
pass
"""
)
opt, passed_result = spec
rec = testdir.inline_run("-k", opt)
passed, skipped, fail = rec.listoutcomes()
passed = [x.nodeid.split("::")[-1] for x in passed]
assert len(passed) == len(passed_result)
assert list(passed) == list(passed_result)
def test_keyword_option_considers_mark(testdir):
testdir.copy_example("marks/marks_considered_keywords")
rec = testdir.inline_run("-k", "foo")
passed = rec.listoutcomes()[0]
assert len(passed) == 1
@pytest.mark.parametrize(
"spec",
[
("None", ("test_func[None]",)),
("1.3", ("test_func[1.3]",)),
("2-3", ("test_func[2-3]",)),
],
)
def test_keyword_option_parametrize(spec, testdir):
testdir.makepyfile(
"""
import pytest
@pytest.mark.parametrize("arg", [None, 1.3, "2-3"])
def test_func(arg):
pass
"""
)
opt, passed_result = spec
rec = testdir.inline_run("-k", opt)
passed, skipped, fail = rec.listoutcomes()
passed = [x.nodeid.split("::")[-1] for x in passed]
assert len(passed) == len(passed_result)
assert list(passed) == list(passed_result)
def test_parametrize_with_module(testdir):
testdir.makepyfile(
"""
import pytest
@pytest.mark.parametrize("arg", [pytest,])
def test_func(arg):
pass
"""
)
rec = testdir.inline_run()
passed, skipped, fail = rec.listoutcomes()
expected_id = "test_func[" + pytest.__name__ + "]"
assert passed[0].nodeid.split("::")[-1] == expected_id
@pytest.mark.parametrize(
"spec",
[
(
"foo or import",
"ERROR: Python keyword 'import' not accepted in expressions passed to '-k'",
),
("foo or", "ERROR: Wrong expression passed to '-k': foo or"),
],
)
def test_keyword_option_wrong_arguments(spec, testdir, capsys):
testdir.makepyfile(
"""
def test_func(arg):
pass
"""
)
opt, expected_result = spec
testdir.inline_run("-k", opt)
out = capsys.readouterr().err
assert expected_result in out
def test_parametrized_collected_from_command_line(testdir):
"""Parametrized test not collected if test named specified
in command line issue#649.
"""
py_file = testdir.makepyfile(
"""
import pytest
@pytest.mark.parametrize("arg", [None, 1.3, "2-3"])
def test_func(arg):
pass
"""
)
file_name = os.path.basename(py_file.strpath)
rec = testdir.inline_run(file_name + "::" + "test_func")
rec.assertoutcome(passed=3)
def test_parametrized_collect_with_wrong_args(testdir):
"""Test collect parametrized func with wrong number of args."""
py_file = testdir.makepyfile(
"""
import pytest
@pytest.mark.parametrize('foo, bar', [(1, 2, 3)])
def test_func(foo, bar):
pass
"""
)
result = testdir.runpytest(py_file)
result.stdout.fnmatch_lines(
[
'test_parametrized_collect_with_wrong_args.py::test_func: in "parametrize" the number of names (2):',
" ['foo', 'bar']",
"must be equal to the number of values (3):",
" (1, 2, 3)",
]
)
def test_parametrized_with_kwargs(testdir):
"""Test collect parametrized func with wrong number of args."""
py_file = testdir.makepyfile(
"""
import pytest
@pytest.fixture(params=[1,2])
def a(request):
return request.param
@pytest.mark.parametrize(argnames='b', argvalues=[1, 2])
def test_func(a, b):
pass
"""
)
result = testdir.runpytest(py_file)
assert result.ret == 0
def test_parametrize_iterator(testdir):
"""parametrize should work with generators (#5354)."""
py_file = testdir.makepyfile(
"""\
import pytest
def gen():
yield 1
yield 2
yield 3
@pytest.mark.parametrize('a', gen())
def test(a):
assert a >= 1
"""
)
result = testdir.runpytest(py_file)
assert result.ret == 0
# should not skip any tests
result.stdout.fnmatch_lines(["*3 passed*"])
class TestFunctional:
def test_merging_markers_deep(self, testdir):
# issue 199 - propagate markers into nested classes
p = testdir.makepyfile(
"""
import pytest
class TestA(object):
pytestmark = pytest.mark.a
def test_b(self):
assert True
class TestC(object):
# this one didn't get marked
def test_d(self):
assert True
"""
)
items, rec = testdir.inline_genitems(p)
for item in items:
print(item, item.keywords)
assert [x for x in item.iter_markers() if x.name == "a"]
def test_mark_decorator_subclass_does_not_propagate_to_base(self, testdir):
p = testdir.makepyfile(
"""
import pytest
@pytest.mark.a
class Base(object): pass
@pytest.mark.b
class Test1(Base):
def test_foo(self): pass
class Test2(Base):
def test_bar(self): pass
"""
)
items, rec = testdir.inline_genitems(p)
self.assert_markers(items, test_foo=("a", "b"), test_bar=("a",))
def test_mark_should_not_pass_to_siebling_class(self, testdir):
"""#568"""
p = testdir.makepyfile(
"""
import pytest
class TestBase(object):
def test_foo(self):
pass
@pytest.mark.b
class TestSub(TestBase):
pass
class TestOtherSub(TestBase):
pass
"""
)
items, rec = testdir.inline_genitems(p)
base_item, sub_item, sub_item_other = items
print(items, [x.nodeid for x in items])
# new api segregates
assert not list(base_item.iter_markers(name="b"))
assert not list(sub_item_other.iter_markers(name="b"))
assert list(sub_item.iter_markers(name="b"))
def test_mark_decorator_baseclasses_merged(self, testdir):
p = testdir.makepyfile(
"""
import pytest
@pytest.mark.a
class Base(object): pass
@pytest.mark.b
class Base2(Base): pass
@pytest.mark.c
class Test1(Base2):
def test_foo(self): pass
class Test2(Base2):
@pytest.mark.d
def test_bar(self): pass
"""
)
items, rec = testdir.inline_genitems(p)
self.assert_markers(items, test_foo=("a", "b", "c"), test_bar=("a", "b", "d"))
def test_mark_closest(self, testdir):
p = testdir.makepyfile(
"""
import pytest
@pytest.mark.c(location="class")
class Test:
@pytest.mark.c(location="function")
def test_has_own():
pass
def test_has_inherited():
pass
"""
)
items, rec = testdir.inline_genitems(p)
has_own, has_inherited = items
assert has_own.get_closest_marker("c").kwargs == {"location": "function"}
assert has_inherited.get_closest_marker("c").kwargs == {"location": "class"}
assert has_own.get_closest_marker("missing") is None
def test_mark_with_wrong_marker(self, testdir):
reprec = testdir.inline_runsource(
"""
import pytest
class pytestmark(object):
pass
def test_func():
pass
"""
)
values = reprec.getfailedcollections()
assert len(values) == 1
assert "TypeError" in str(values[0].longrepr)
def test_mark_dynamically_in_funcarg(self, testdir):
testdir.makeconftest(
"""
import pytest
@pytest.fixture
def arg(request):
request.applymarker(pytest.mark.hello)
def pytest_terminal_summary(terminalreporter):
values = terminalreporter.stats['passed']
terminalreporter._tw.line("keyword: %s" % values[0].keywords)
"""
)
testdir.makepyfile(
"""
def test_func(arg):
pass
"""
)
result = testdir.runpytest()
result.stdout.fnmatch_lines(["keyword: *hello*"])
def test_no_marker_match_on_unmarked_names(self, testdir):
p = testdir.makepyfile(
"""
import pytest
@pytest.mark.shouldmatch
def test_marked():
assert 1
def test_unmarked():
assert 1
"""
)
reprec = testdir.inline_run("-m", "test_unmarked", p)
passed, skipped, failed = reprec.listoutcomes()
assert len(passed) + len(skipped) + len(failed) == 0
dlist = reprec.getcalls("pytest_deselected")
deselected_tests = dlist[0].items
assert len(deselected_tests) == 2
def test_invalid_m_option(self, testdir):
testdir.makepyfile(
"""
def test_a():
pass
"""
)
result = testdir.runpytest("-m bogus/")
result.stdout.fnmatch_lines(
["INTERNALERROR> Marker expression must be valid Python!"]
)
def test_keywords_at_node_level(self, testdir):
testdir.makepyfile(
"""
import pytest
@pytest.fixture(scope="session", autouse=True)
def some(request):
request.keywords["hello"] = 42
assert "world" not in request.keywords
@pytest.fixture(scope="function", autouse=True)
def funcsetup(request):
assert "world" in request.keywords
assert "hello" in request.keywords
@pytest.mark.world
def test_function():
pass
"""
)
reprec = testdir.inline_run()
reprec.assertoutcome(passed=1)
def test_keyword_added_for_session(self, testdir):
testdir.makeconftest(
"""
import pytest
def pytest_collection_modifyitems(session):
session.add_marker("mark1")
session.add_marker(pytest.mark.mark2)
session.add_marker(pytest.mark.mark3)
pytest.raises(ValueError, lambda:
session.add_marker(10))
"""
)
testdir.makepyfile(
"""
def test_some(request):
assert "mark1" in | |
'am:DiscreteValueHistogram':
print("ExecutionNeed - value type \'am:DiscreteValueHistogram\' not supported.")
continue
elif values.attrib[xsi+'type'] == 'am:BoundedDiscreteValueDistribution':
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:DiscreteValueBoundaries':
# samplingType = parser.xml_get(values, 'samplingType')
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:DiscreteValueStatistics':
# average = float(parser.xml_get(values, 'average'))
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:DiscreteValueUniformDistribution':
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:DiscreteValueWeibullEstimatorsDistribution':
# average = float(parser.xml_get(values, 'average'))
# pRemainPromille = float(parser.xml_get(values, 'pRemainPromille'))
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:DiscreteValueBetaDistribution':
# alpha = float(parser.xml_get(values, 'alpha'))
# beta = float(parser.xml_get(values, 'beta'))
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:TruncatedDiscreteValueDistribution':
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:DiscreteValueGaussDistribution':
# mean = float(parser.xml_get(values, 'mean'))
# sd = float(parser.xml_get(values, 'sd'))
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
min += lowerBound
max += upperBound
return min, max
else:
return 0, 0
def __get_ticks(self, executableEntity, elem):
""" parsing of ActivityGraph entry of type Ticks
using param elem the function can be both used for "tasks" and "runnables"
:param executableEntity: xml entry of type Task or Runnable
:param elem: string
:rtype: int, int
"""
if amalthea_version in ['0_9_5', '0_9_6']:
path = [elem, 'callGraph', 'items']
filterArgs = ['option', 'Ticks']
elif amalthea_version in ['0_9_7', '0_9_8', '0_9_9']:
path = [elem, 'activityGraph', 'items']
filterArgs = ['option', 'Ticks']
elif amalthea_version in ['0_7_2', '0_8_0', '0_8_1', '0_8_2', '0_8_3', '0_9_0', '0_9_1', '0_9_2', '0_9_3', '0_9_4']:
print("Class Ticks not part of Amalthea version %s" %amalthea_version)
return 0, 0
multipleElements = True
ticks_xml = parser.getElement(path, root=executableEntity, multipleElements=multipleElements, filterArgs=filterArgs)
if ticks_xml is not None:
ticks_min, ticks_max = 0, 0
for ticks_entry in ticks_xml:
if amalthea_version in ['0_9_5','0_9_6', '0_9_7', '0_9_8', '0_9_9']:
# IDiscreteValueDeviation
sub_path = ['items', 'default']
filterArgs = None
multipleElements = False
values = parser.getElement(sub_path, root=ticks_entry, multipleElements=multipleElements, filterArgs=filterArgs)
if values is not None:
if values.attrib[xsi+'type'] == 'am:DiscreteValueConstant':
value = int(parser.xml_get(values, 'value'))
lowerBound = value
upperBound = value
elif values.attrib[xsi+'type'] == 'am:DiscreteValueHistogram':
print("Ticks - value type \'am:DiscreteValueHistogram\' not supported")
continue
elif values.attrib[xsi+'type'] == 'am:BoundedDiscreteValueDistribution':
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:DiscreteValueBoundaries':
# samplingType = parser.xml_get(values, 'samplingType')
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:DiscreteValueStatistics':
# average = float(parser.xml_get(values, 'average'))
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:DiscreteValueUniformDistribution':
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:DiscreteValueWeibullEstimatorsDistribution':
# average = float(parser.xml_get(values, 'average'))
# pRemainPromille = float(parser.xml_get(values, 'pRemainPromille'))
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:DiscreteValueBetaDistribution':
# alpha = float(parser.xml_get(values, 'alpha'))
# beta = float(parser.xml_get(values, 'beta'))
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:TruncatedDiscreteValueDistribution':
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
elif values.attrib[xsi+'type'] == 'am:DiscreteValueGaussDistribution':
# mean = float(parser.xml_get(values, 'mean'))
# sd = float(parser.xml_get(values, 'sd'))
lowerBound = int(parser.xml_get(values, 'lowerBound'))
upperBound = int(parser.xml_get(values, 'upperBound'))
ticks_min += lowerBound
ticks_max += upperBound
return ticks_min, ticks_max
else:
return 0, 0
def __get_labels(self, task):
""" parses all labels accessed by a given task.
also determines whether a given label access (entry) is a reading or writing access
:param task: xml element of type task
:rtype: list, list
"""
if amalthea_version in ['0_9_5', '0_9_6']:
path = ['tasks', 'callGraph', 'items']
filterArgs = ['option', 'LabelAccess']
elif amalthea_version in ['0_9_7', '0_9_8', '0_9_9']:
path = ['tasks', 'activityGraph', 'items']
filterArgs = ['option', 'LabelAccess']
elif amalthea_version in ['0_7_2', '0_8_0', '0_8_1', '0_8_2', '0_8_3', '0_9_0', '0_9_1', '0_9_2', '0_9_3', '0_9_4']:
print("Processing of LabelAccess not implemented for Amalthea version %s" %amalthea_version)
return [], []
multipleElements = True
accesses = parser.getElement(path, root=task, multipleElements=multipleElements, filterArgs=filterArgs)
read = list()
write = list()
if accesses is not None:
if amalthea_version in ['0_9_5', '0_9_6', '0_9_7', '0_9_8', '0_9_9']:
for entry in accesses:
# LabelAccessEnum will take on one of the following values: ['_undefined_', 'read', 'write']
rw = parser.xml_get(entry, 'access')
label = self.__get_accessedLabel(entry)
if rw == 'read':
read.append(label)
elif rw == 'write':
write.append(label)
return read, write
def __get_accessedLabel(self, entry):
""" parses labels accessed by LabelAccess
:param entry: xml element of type LabelAccess
"""
# LabelAccess -> Label
if amalthea_version in ['0_9_5', '0_9_6', '0_9_7', '0_9_8', '0_9_9']:
path = ['LabelAccess', 'Label']
else:
print("Processing of LabelAccess not implemented for Amalthea version %s" %amalthea_version)
lst = parser.getAssocaitedElement(path=path, rootElem=entry)
if lst is not None:
if amalthea_version in ['0_9_5', '0_9_6', '0_9_7', '0_9_8', '0_9_9']:
for label in lst:
name = parser.xml_get(label, 'name')
# only one label expected, return after first result!
return label
else:
return None
def __get_activation_pattern(self, task):
""" process stimulus pattern of a given task
:param task: xml element of type task
:rtype: pyCPA activation pattern
"""
if amalthea_version in ["0_9_3", "0_9_4", "0_9_5", "0_9_6", "0_9_7", "0_9_8", "0_9_9"]:
path = ['Task', 'Stimulus']
else:
return None
lst = parser.getAssocaitedElement(path=path, rootElem=task)
if lst is not None:
if amalthea_version in ["0_9_3", "0_9_4", "0_9_5", "0_9_6", "0_9_7", "0_9_8", "0_9_9"]:
# note: only one result expected here! return the first result
for stimulus in lst:
name = parser.xml_get(stimulus, 'name')
xmlElement = stimulus
if xmlElement.attrib[xsi+'type'] == 'am:PeriodicStimulus':
# Time recurrence
path = ['stimuli', 'recurrence']
filterArgs = None
multipleElements = False
recurrence = parser.getElement(path, root=stimulus, multipleElements=multipleElements, filterArgs=filterArgs)
# if multipleElements is True, <elem> is a list -> use for loop to iterate over all elements
if recurrence is not None:
value = int(parser.xml_get(recurrence, 'value'))
# TimeUnit will take on one of the following values: ['_undefined_', 's', 'ms', 'us', 'ns', 'ps']
unit = parser.xml_get(recurrence, 'unit')
recurrence = value #* units[unit]
else:
recurrence = None
# Time minDistance
path = ['stimuli', 'minDistance']
filterArgs = None
multipleElements = False
minDistance = parser.getElement(path, root=stimulus, multipleElements=multipleElements, filterArgs=filterArgs)
# if multipleElements is True, <elem> is a list -> use for loop to iterate over all elements
if minDistance is not None:
value = int(parser.xml_get(minDistance, 'value'))
# TimeUnit will take on one of the following values: ['_undefined_', 's', 'ms', 'us', 'ns', 'ps']
unit = parser.xml_get(minDistance, 'unit')
distance = value #* units[unit]
else:
distance = 0
# ITimeDeviation jitter
#...
jitter = 0
# subordinated element: Time offset
path = ['stimuli', 'offset']
filterArgs = None
multipleElements = False
offset = parser.getElement(path, root=stimulus, multipleElements=multipleElements, filterArgs=filterArgs)
# if multipleElements is True, <elem> is a list -> use for loop to iterate over all elements
if offset is not None:
#attributes:
value = int(parser.xml_get(offset, 'value'))
unit = parser.xml_get(offset, 'unit')
offset = value #* units[unit]
else:
offset = 0
activation_model = model.PJdEventModel(P=int(recurrence), J=jitter, dmin=distance, phi=offset)
return ['pjd', activation_model]
if xmlElement.attrib[xsi+'type'] == 'am:RelativePeriodicStimulus':
print('[__get_activation_pattern] processing of stimulus %s not implemented yet' % xmlElement.attrib[xsi+'type'])
return None
if xmlElement.attrib[xsi+'type'] == 'am:VariableRateStimulus':
print('[__get_activation_pattern] processing of stimulus %s not implemented yet' % xmlElement.attrib[xsi+'type'])
return None
if xmlElement.attrib[xsi+'type'] == 'am:PeriodicSyntheticStimulus':
print('[__get_activation_pattern] processing of stimulus %s not implemented yet' % xmlElement.attrib[xsi+'type'])
return None
if xmlElement.attrib[xsi+'type'] == 'am:SingleStimulus':
print('[__get_activation_pattern] processing of stimulus %s not implemented yet' % xmlElement.attrib[xsi+'type'])
return None
if xmlElement.attrib[xsi+'type'] == 'am:PeriodicBurstStimulus':
print('[__get_activation_pattern] processing of stimulus %s not implemented yet' % xmlElement.attrib[xsi+'type'])
return None
if xmlElement.attrib[xsi+'type'] == 'am:EventStimulus':
print('[__get_activation_pattern] processing of stimulus %s not implemented yet' % xmlElement.attrib[xsi+'type'])
return None
if xmlElement.attrib[xsi+'type'] == 'am:CustomStimulus':
print('[__get_activation_pattern] processing of stimulus %s not implemented yet' % xmlElement.attrib[xsi+'type'])
return None
if xmlElement.attrib[xsi+'type'] == 'am:InterProcessStimulus':
print('[__get_activation_pattern] processing of stimulus %s not implemented yet' % xmlElement.attrib[xsi+'type'])
return None
if xmlElement.attrib[xsi+'type'] == 'am:ArrivalCurveStimulus':
print('[__get_activation_pattern] processing of stimulus %s not implemented yet' % xmlElement.attrib[xsi+'type'])
return None
def __get_deadline(self, task):
""" retrieve task deadlines
:param task: xml element of type task
:rtype: int
"""
if amalthea_version in ["0_9_3", "0_9_4", "0_9_5", "0_9_6", "0_9_7", "0_9_8", "0_9_9"]:
path = ['Task', 'ProcessRequirement']
else:
return None
lst = parser.getAssocaitedElement(path=path, rootElem=task)
if lst is not None:
for requirement in lst:
if amalthea_version in ["0_9_3", "0_9_4", "0_9_5", "0_9_6", "0_9_7", "0_9_8", "0_9_9"]:
# RequirementLimit limit
path = ['requirements', 'limit']
filterArgs = None
multipleElements = False
limit = parser.getElement(path, root=requirement, multipleElements=multipleElements, filterArgs=filterArgs)
if limit is not None:
xmlElement = limit
if xmlElement.attrib[xsi+'type'] | |
# Copyright 2020- Robot Framework Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from typing import Any, List, Optional, Union
import grpc # type: ignore
from assertionengine import (
AssertionOperator,
bool_verify_assertion,
dict_verify_assertion,
float_str_verify_assertion,
int_dict_verify_assertion,
list_verify_assertion,
verify_assertion,
)
from ..assertion_engine import with_assertion_polling
from ..base import LibraryComponent
from ..generated.playwright_pb2 import Request
from ..utils import exec_scroll_function, keyword, logger
from ..utils.data_types import (
AreaFields,
BoundingBoxFields,
ElementStateKey,
SelectAttribute,
SizeFields,
)
class Getters(LibraryComponent):
@keyword(tags=("Getter", "Assertion", "PageContent"))
@with_assertion_polling
def get_url(
self,
assertion_operator: Optional[AssertionOperator] = None,
assertion_expected: Any = None,
message: Optional[str] = None,
) -> Any:
"""Returns the current URL.
``assertion_operator`` See `Assertions` for further details. Defaults to None.
``expected_value`` Expected value for the state
``message`` overrides the default error message for assertion.
Optionally asserts that it matches the specified assertion. See `Assertions` for further details
for the assertion arguments. By default assertion is not done.
``message`` overrides the default error message.
"""
with self.playwright.grpc_channel() as stub:
response = stub.GetUrl(Request().Empty())
logger.debug(response.log)
value = response.body
return verify_assertion(
value, assertion_operator, assertion_expected, "URL", message
)
# @keyword(tags=("Getter", "Assertion", "BrowserControl"))
# Not published as keyword due to missing of good docs.
@with_assertion_polling
def get_page_state(
self,
assertion_operator: Optional[AssertionOperator] = None,
assertion_expected: Any = None,
message: Optional[str] = None,
) -> Any:
"""Returns page model state object as a dictionary.
``assertion_operator`` See `Assertions` for further details. Defaults to None.
``expected_value`` Expected value for the state
``message`` overrides the default error message for assertion.
This must be given on the page to ``window.__SET_RFBROWSER_STATE__``
For example:
``let mystate = {'login': true, 'name': 'George', 'age': 123};``
``window.__SET_RFBROWSER_STATE__ && window.__SET_RFBROWSER_STATE__(mystate);``
"""
with self.playwright.grpc_channel() as stub:
response = stub.GetPageState(Request().Empty())
logger.debug(response.log)
value = json.loads(response.result)
return verify_assertion(
value, assertion_operator, assertion_expected, "State", message
)
@keyword(tags=("Getter", "Assertion", "PageContent"))
@with_assertion_polling
def get_page_source(
self,
assertion_operator: Optional[AssertionOperator] = None,
assertion_expected: Any = None,
message: Optional[str] = None,
) -> Any:
"""Gets pages HTML source as a string.
``assertion_operator`` See `Assertions` for further details. Defaults to None.
``expected_value`` Expected value for the state
``message`` overrides the default error message for assertion.
Optionally does a string assertion. See `Assertions` for further details for
the assertion arguments. By default assertion is not done.
"""
with self.playwright.grpc_channel() as stub:
response = stub.GetPageSource(Request().Empty())
logger.debug(response.log)
value = json.loads(response.body)
return verify_assertion(
value, assertion_operator, assertion_expected, "HTML:", message
)
@keyword(tags=("Getter", "Assertion", "PageContent"))
@with_assertion_polling
def get_title(
self,
assertion_operator: Optional[AssertionOperator] = None,
assertion_expected: Any = None,
message: Optional[str] = None,
) -> Any:
"""Returns the title of the current page.
``assertion_operator`` See `Assertions` for further details. Defaults to None.
``expected_value`` Expected value for the state
``message`` overrides the default error message for assertion.
Optionally asserts that title matches the specified assertion. See `Assertions`
for further details for the assertion arguments. By default assertion is not done.
``message`` overrides the default error message.
"""
with self.playwright.grpc_channel() as stub:
response = stub.GetTitle(Request().Empty())
logger.debug(response.log)
value = response.body
return verify_assertion(
value, assertion_operator, assertion_expected, "Title", message
)
@keyword(tags=("Getter", "Assertion", "PageContent"))
@with_assertion_polling
def get_text(
self,
selector: str,
assertion_operator: Optional[AssertionOperator] = None,
assertion_expected: Any = None,
message: Optional[str] = None,
) -> Any:
"""Returns text attribute of the element found by ``selector``.
See the `Finding elements` section for details about the selectors.
``assertion_operator`` See `Assertions` for further details. Defaults to None.
``expected_value`` Expected value for the state
``message`` overrides the default error message for assertion.
Optionally asserts that the text matches the specified assertion. See `Assertions`
for further details for the assertion arguments. By default assertion is not done.
Example:
| ${text} = `Get Text` id=important # Returns element text without assertion.
| ${text} = `Get Text` id=important == Important text # Returns element text with assertion.
"""
with self.playwright.grpc_channel() as stub:
response = stub.GetText(Request().ElementSelector(selector=selector))
logger.debug(response.log)
return verify_assertion(
response.body, assertion_operator, assertion_expected, "Text", message
)
@keyword(tags=("Getter", "Assertion", "PageContent"))
@with_assertion_polling
def get_property(
self,
selector: str,
property: str,
assertion_operator: Optional[AssertionOperator] = None,
assertion_expected: Any = None,
message: Optional[str] = None,
) -> Any:
"""Returns the ``property`` of the element found by ``selector``.
``selector`` Selector from which the info is to be retrieved.
See the `Finding elements` section for details about the selectors.
``property`` Requested property name.
``assertion_operator`` See `Assertions` for further details. Defaults to None.
``expected_value`` Expected value for the state
``message`` overrides the default error message for assertion.
Optionally asserts that the property value matches the expected value. See `Assertions`
for further details for the assertion arguments. By default assertion is not done.
If ``assertion_operator`` is set and property is not found, ``value`` is ``None``
and Keyword does not fail. See `Get Attribute` for examples.
Example:
| `Get Property` h1 innerText == Login Page
| ${property} = `Get Property` h1 innerText
"""
with self.playwright.grpc_channel() as stub:
response = stub.GetDomProperty(
Request().ElementProperty(selector=selector, property=property)
)
logger.debug(response.log)
if response.body:
value = json.loads(response.body)
elif assertion_operator is not None:
value = None
else:
raise AttributeError(f"Property '{property}' not found!")
return verify_assertion(
value,
assertion_operator,
assertion_expected,
f"Property {property}",
message,
)
@keyword(tags=("Getter", "Assertion", "PageContent"))
@with_assertion_polling
def get_attribute(
self,
selector: str,
attribute: str,
assertion_operator: Optional[AssertionOperator] = None,
assertion_expected: Any = None,
message: Optional[str] = None,
) -> Any:
"""Returns the HTML ``attribute`` of the element found by ``selector``.
``selector`` Selector from which the info is to be retrieved.
See the `Finding elements` section for details about the selectors.
``attribute`` Requested attribute name.
``assertion_operator`` See `Assertions` for further details. Defaults to None.
``expected_value`` Expected value for the state
``message`` overrides the default error message for assertion.
Optionally asserts that the attribute value matches the expected value. See
`Assertions` for further details for the assertion arguments. By default assertion
is not done.
When a attribute is selected that is not present and no assertion operator is set,
the keyword fails. If an assertion operator is set and the attribute is not present,
the returned value is ``None``. This can be used to assert check the presents or
the absents of an attribute.
``message`` overrides the default error message.
Example Element:
| <button class="login button active" id="enabled_button" something>Login</button>
Example Code:
| `Get Attribute` id=enabled_button disabled # FAIL => "Attribute 'disabled' not found!"
| `Get Attribute` id=enabled_button disabled == ${None} # PASS => returns: None
| `Get Attribute` id=enabled_button something evaluate value is not None # PASS => returns: True
| `Get Attribute` id=enabled_button disabled evaluate value is None # PASS => returns: True
"""
with self.playwright.grpc_channel() as stub:
response = stub.GetElementAttribute(
Request().ElementProperty(selector=selector, property=attribute)
)
logger.debug(response.log)
value = json.loads(response.body)
if assertion_operator is None and value is None:
raise AttributeError(f"Attribute '{attribute}' not found!")
logger.debug(f"Attribute is: {value}")
return verify_assertion(
value,
assertion_operator,
assertion_expected,
f"Attribute {selector}",
message,
)
@keyword(tags=("Getter", "Assertion", "PageContent"))
@with_assertion_polling
def get_attribute_names(
self,
selector: str,
assertion_operator: Optional[AssertionOperator] = None,
*assertion_expected,
message: Optional[str] = None,
) -> Any:
"""Returns all HTML attribute names of an element as a list.
``selector`` Selector from which the info is to be retrieved.
See the `Finding elements` section for details about the selectors.
``assertion_operator`` See `Assertions` for further details. Defaults to None.
``expected_value`` Expected value for the state
``message`` overrides the default error message for assertion.
Optionally asserts that attribute names do match to the expected value. See
`Assertions` for further details for the assertion arguments. By default assertion
is not done.
Available assertions:
- ``==`` and ``!=`` can work with multiple values
- ``contains`` / ``*=`` only accepts one single expected value
Other operators are not allowed.
``message`` overrides the default error message.
Example:
| `Get Attribute Names` [name="readonly_input"] == type name value readonly # Has exactly these attribute names.
| `Get Attribute Names` [name="readonly_input"] contains disabled # Contains at least this attribute name.
"""
| |
<gh_stars>1-10
#!/usr/bin/env python
"""
netCDF4 functions to a copy netcdf file while doing some transformations on
variables and dimensions.
This module was written by <NAME> while at Institut National de
Recherche pour l'Agriculture, l'Alimentation et l'Environnement (INRAE), Nancy,
France.
It borrows the idea of _get_variable_definition from the netcdf4 thin layer of
David Schaefer.
:copyright: Copyright 2020-2022 <NAME>, see AUTHORS.rst for details.
:license: MIT License, see LICENSE for details.
.. moduleauthor:: <NAME>
The following functions are provided
.. autosummary::
copy_dimensions
copy_file
copy_global_attributes
copy_variables
create_new_variable
create_variables
get_fill_value_for_dtype
set_output_filename
History
* Written Apr 2020 by <NAME> (mc (at) macu (dot) de)
* Added get_fill_value_for_dtype, Mar 2021, <NAME>
* Added create_new_variable, Mar 2021, <NAME>
* flake8 compatible, Mar 2021, <NAME>
* Remove keyword in copy_global_attributes, Mar 2021, <NAME>
* Add timedim in create_variables, Dec 2021, <NAME>
* Rename functions, e.g. create_dimensions -> copy_dimensions,
May 2022, <NAME>
* Add copy_variables, May 2022, <NAME>
"""
import numpy as np
import netCDF4 as nc
__all__ = ['copy_dimensions', 'copy_file', 'copy_global_attributes',
'copy_variables', 'create_new_variable', 'create_variables',
'get_fill_value_for_dtype', 'set_output_filename']
def _tolist(arg):
"""
Assure that *arg* is a list, e.g. if string or None are given.
Parameters
----------
arg :
Argument to make list
Returns
-------
list
list(arg)
Examples
--------
>>> _tolist('string')
['string']
>>> _tolist([1,2,3])
[1, 2, 3]
>>> _tolist(None)
[None]
"""
if isinstance(arg, str):
return [arg]
try:
return list(arg)
except TypeError:
return [arg]
def _get_variable_definition(ncvar):
"""
Collect information on input variable.
Parameters
----------
ncvar : netcdf4 variable
Variable of input file
Returns
-------
dict
Containing information on input variable withkey/value pairs.
The following keys are returned: 'name', 'dtype', 'dimensions',
'fill_vallue', 'chunksizes'
Examples
--------
.. code-block:: python
_get_variable_definition(fi.variables['GPP'])
"""
out = ncvar.filters() if ncvar.filters() else {}
# chunksizes
chunks = None
if "chunking" in dir(ncvar):
if ncvar.chunking() is not None:
if not isinstance(ncvar.chunking(), str):
chunks = list(ncvar.chunking())
# missing value
if "missing_value" in dir(ncvar):
ifill = ncvar.missing_value
elif "_FillValue" in dir(ncvar):
ifill = ncvar._FillValue
else:
ifill = None
# output variable
out.update({
"name": ncvar.name,
"dtype": ncvar.dtype,
"dimensions": list(ncvar.dimensions),
"fill_value": ifill,
"chunksizes": chunks,
})
return out
def copy_file(ifile, ofile, timedim='time',
removevar=[], renamevar={}, replacevar={}, replaceatt={},
noclose=False):
"""
Copy variables from input file into output file.
Parameters
----------
ifile : str
File name of netcdf input file
ofile : str
File name of netcdf output file
timedim : str, optional
Name of time dimension in input file (default: 'time').
removevar : list of str, optional
Do not copy variables given in *removevar* to output file.
renamevar : dict, optional
Copy variables from input file with different name in output file.
Variable names in input file are given as dictionary keys,
corresponding variable names of output file are give as dictionary
values.
replacevar : dict, optional
Replace existing variables with variables in dictionary.
Variable names in input file are given as dictionary keys,
dictionary values are also dictionaries where keys are the output
variable name and values are the output variable values.
replaceatt : dict, optional
Replace or set attributes of variables in dictionary keys
(case sensitive). Dictionary values are also dictionaries with
{'attribute_name': attribute_value}. Dictionary keys are the names
of the output variables after renaming and replacing.
noclose : bool, optional
Return file handle of opened output file for further manipulation
if True (default: False)
Returns
-------
nothing or file_handle
The output file will have the altered or unaltered variables
copied from the input file.
Examples
--------
.. code-block:: python
ovar = np.arange(100)
copy_variable('in.nc', 'out.nc',
renamevar={'lon': 'longitude'},
replacevar={'var1': {'arange': ovar}},
replaceatt={'arange':
{'long_name': 'A range', 'unit': '-'}})
"""
import time as ptime
fi = nc.Dataset(ifile, 'r')
if 'file_format' in dir(fi):
fo = nc.Dataset(ofile, 'w', format=fi.file_format)
else: # pragma: no cover
fo = nc.Dataset(ofile, 'w', format='NETCDF4')
# meta data
copy_global_attributes(
fi, fo, add={'history': ptime.asctime() + ': ' +
'copy_variables(' + ifile + ', ' + ofile + ')'})
# copy dimensions
copy_dimensions(fi, fo)
# create variables
# rename replace variables as well
xreplacevar = {}
for rr in replacevar:
nn = replacevar[rr].copy()
kk = nn.popitem()[0]
xreplacevar.update({rr: kk})
arenamevar = renamevar.copy()
arenamevar.update(xreplacevar)
# create static variables (independent of time)
create_variables(fi, fo, time=False, timedim=timedim, fill=True,
removevar=removevar, renamevar=arenamevar)
# create dynamic variables (time dependent)
create_variables(fi, fo, time=True, timedim=timedim, fill=True,
removevar=removevar, renamevar=arenamevar)
# set extra attributes
for rr in replaceatt:
ovar = fo.variables[rr]
att = replaceatt[rr]
for aa in att:
ovar.setncattr(aa, att[aa])
# copy variables
# do not copy replace variables
aremovevar = _tolist(removevar)
aremovevar.extend(xreplacevar.keys())
copy_variables(fi, fo, time=False, timedim=timedim,
removevar=aremovevar, renamevar=renamevar)
copy_variables(fi, fo, time=True, timedim=timedim,
removevar=aremovevar, renamevar=renamevar)
# set replace variables
for rr in replacevar:
odict = replacevar[rr].copy()
oname, oval = odict.popitem()
ovar = fo.variables[oname]
ovar[:] = oval
fi.close()
if noclose:
return fo
else:
fo.close()
return
def copy_dimensions(fi, fo, removedim=[], renamedim={}, changedim={},
adddim={}):
"""
Create dimensions in output file from dimensions in input file.
Parameters
----------
fi : file_handle
File handle of opened netcdf input file
fo : file_handle
File handle of opened netcdf output file
removedim : list of str, optional
Do not create dimensions given in *removedim* in output file.
renamedim : dict, optional
Rename dimensions in output file compared to input file.
Dimension names in input file are given as dictionary keys,
corresponding dimension names of output file are give as dictionary
values.
changedim : dict, optional
Change the size of the output dimension compared to the input file.
Dimension names are given as dictionary keys, corresponding dimension
sizes are given as dictionary values.
adddim : dict, optional
Add dimension to output file.
New dimension names are given as dictionary keys and new dimension
sizes are given as dictionary values.
Returns
-------
nothing
The output file will have the altered and unaltered dimensions
of the input file.
Examples
--------
.. code-block:: python
copy_dimensions(fi, fo, removedim=['patch'],
renamedim={'x': 'lon', 'y': 'lat'},
changedim={'mland': 1})
"""
removedim = _tolist(removedim)
for d in fi.dimensions.values():
# remove dimension if in removedim
if d.name not in removedim:
# change dimension size if in changedim
if d.name in changedim.keys():
nd = changedim[d.name]
elif d.isunlimited():
nd = None
else:
nd = len(d)
# rename dimension if in renamedim
if d.name in renamedim.keys():
oname = renamedim[d.name]
else:
oname = d.name
# create dimension
fo.createDimension(oname, nd)
# add new dimensions
for d in adddim.keys():
if d not in fo.dimensions:
fo.createDimension(d, adddim[d])
return
def copy_global_attributes(fi, fo, add={}, remove=[]):
"""
Create global output file attributes from input global file attributes.
Parameters
----------
fi : file_handle
File handle of opened netcdf input file
fo : file_handle
File handle of opened netcdf output file
add : dict, optional
dict values will be given to attributes given in dict keys.
Attributes will be created if they do not exist yet.
remove : list, optional
Do not create global attributes given in *remove* in the output file.
Returns
-------
nothing
Output will have global file attributes
Examples
--------
.. code-block:: python
copy_global_attributes(
fi, fo, add={'history': time.asctime()+': '+' '.join(sys.argv)})
"""
for k in fi.ncattrs():
if k not in remove:
iattr = fi.getncattr(k)
# add to existing global attribute
if k in add.keys():
iattr += '\n'+add[k]
fo.setncattr(k, iattr)
# add if global attribute does not exist yet
for k in add.keys():
if k not in fi.ncattrs():
fo.setncattr(k, add[k])
return
def copy_variables(fi, fo, time=None, timedim='time',
removevar=[], renamevar={}):
"""
Copy variables from input file into output file.
Parameters
----------
fi : file_handle
File handle of opened netcdf input file
fo : file_handle
File handle of opened netcdf output file
time : None or bool, optional
None: copy all variables (default).
True: copy only variables having dimension *timedim*.
False: copy only variables that do not have dimension *timedim*.
timedim : str, optional
Name of time dimension (default: 'time').
removevar : list of str, optional
Do not copy variables given in *removevar* to output file.
renamevar : dict, optional
Copy variables from input file with different name in output file.
Variable names in input file are given as dictionary keys,
corresponding variable names of output file are give as dictionary
values.
Returns
-------
nothing
The output file will have the altered or unaltered variables
copied from the | |
observation
az, el = target.azel(now + duration, antenna)
visible_after.append(el >= horizon)
if all(visible_before) and all(visible_after):
return True
always_invisible = any(~np.array(visible_before) & ~np.array(visible_after))
if always_invisible:
user_logger.warning("Target '%s' is never up during requested period (average elevation is %g degrees)" %
(target.name, np.mean(average_el)))
else:
user_logger.warning("Target '%s' will rise or set during requested period" % (target.name,))
return False
def fire_noise_diode(self, diode='coupler', on=10.0, off=10.0, period=0.0, align=True, announce=True):
"""Switch noise diode on and off.
This switches the selected noise diode on and off for all the antennas
doing the observation.
The on and off durations can be specified. Additionally, setting the
*period* allows the noise diode to be fired on a semi-regular basis. The
diode will only be fired if more than *period* seconds have elapsed since
the last firing. If *period* is 0, the diode is fired unconditionally.
On the other hand, if *period* is negative it is not fired at all.
Parameters
----------
diode : {'coupler', 'pin'}
Noise diode source to use (pin diode is situated in feed horn and
produces high-level signal, while coupler diode couples into
electronics after the feed at a much lower level)
on : float, optional
Minimum duration for which diode is switched on, in seconds
off : float, optional
Minimum duration for which diode is switched off, in seconds
period : float, optional
Minimum time between noise diode firings, in seconds. (The maximum
time is determined by the duration of individual slews and scans,
which are considered atomic and won't be interrupted.) If 0, fire
diode unconditionally. If negative, don't fire diode at all.
align : {True, False}, optional
True if noise diode transitions should be aligned with correlator
dump boundaries, or False if they should happen as soon as possible
announce : {True, False}, optional
True if start of action should be announced, with details of settings
Returns
-------
fired : {True, False}
True if noise diode fired
Notes
-----
When the function returns, data will still be recorded to the HDF5 file.
The specified *off* duration is therefore a minimum value. Remember to
run :meth:`end` to close the file and finally stop the observation
(automatically done when this object is used in a with-statement)!
"""
# XXX This needs a rethink...
return False
#
# if self.ants is None:
# raise ValueError('No antennas specified for session - please run session.standard_setup first')
# # Create references to allow easy copy-and-pasting from this function
# session, kat, ants, data, dump_period = self, self.kat, self.ants, self.data, self.dump_period
#
# # Wait for the dump period to become known, as it is needed to set a good timeout for the first dump
# if dump_period == 0.0:
# if not data.wait('k7w_spead_dump_period', lambda sensor: sensor.value > 0, timeout=1.5 * session._requested_dump_period, poll_period=0.2 * session._requested_dump_period):
# dump_period = session.dump_period = session._requested_dump_period
# user_logger.warning('SPEAD metadata header is overdue at ingest - noise diode will be out of sync')
# else:
# # Get actual dump period in seconds (as opposed to the requested period)
# dump_period = session.dump_period = data.sensor.k7w_spead_dump_period.get_value()
# # This can still go wrong if the sensor times out - again fall back to requested period
# if dump_period is None:
# dump_period = session.dump_period = session._requested_dump_period
# user_logger.warning('Could not read actual dump period - noise diode will be out of sync')
# # Wait for the first correlator dump to appear, both as a check that capturing works and to align noise diode
# last_dump = data.sensor.k7w_last_dump_timestamp.get_value()
# if last_dump == session._end_of_previous_session or last_dump is None:
# user_logger.info('waiting for correlator dump to arrive')
# # Wait for the first correlator dump to appear
# if not data.wait('k7w_last_dump_timestamp', lambda sensor: sensor.value > session._end_of_previous_session,
# timeout=2.2 * dump_period, poll_period=0.2 * dump_period):
# last_dump = time.time()
# user_logger.warning('Correlator dump is overdue at k7_capture - noise diode will be out of sync')
# else:
# last_dump = data.sensor.k7w_last_dump_timestamp.get_value()
# if last_dump is None:
# last_dump = time.time()
# user_logger.warning('Could not read last dump timestamp - noise diode will be out of sync')
# else:
# user_logger.info('correlator dump arrived')
#
# # If period is non-negative, quit if it is not yet time to fire the noise diode
# if period < 0.0 or (time.time() - session.last_nd_firing) < period:
# return False
#
# if align:
# # Round "on" duration up to the nearest integer multiple of dump period
# on = np.ceil(float(on) / dump_period) * dump_period
# # The last fully complete dump is more than 1 dump period in the past
# next_dump = last_dump + 2 * dump_period
# # The delay in setting up noise diode firing - next dump should be at least this far in future
# lead_time = 0.25
# # Find next suitable dump boundary
# now = time.time()
# while next_dump < now + lead_time:
# next_dump += dump_period
#
# if announce:
# user_logger.info("Firing '%s' noise diode (%g seconds on, %g seconds off)" % (diode, on, off))
# else:
# user_logger.info('firing noise diode')
#
# if align:
# # Schedule noise diode switch-on on all antennas at the next suitable dump boundary
# ants.req.rfe3_rfe15_noise_source_on(diode, 1, 1000 * next_dump, 0)
# # If using Data simulator, fire the simulated noise diode for desired period to toggle power levels in output
# if hasattr(data.req, 'data_fire_nd') and dump_period > 0:
# time.sleep(max(next_dump - time.time(), 0))
# data.req.data_fire_nd(np.ceil(float(on) / dump_period))
# # Wait until the noise diode is on
# time.sleep(max(next_dump + 0.5 * on - time.time(), 0))
# # Schedule noise diode switch-off on all antennas a duration of "on" seconds later
# ants.req.rfe3_rfe15_noise_source_on(diode, 0, 1000 * (next_dump + on), 0)
# time.sleep(max(next_dump + on + off - time.time(), 0))
# # Mark on -> off transition as last firing
# session.last_nd_firing = next_dump + on
# else:
# # Switch noise diode on on all antennas
# ants.req.rfe3_rfe15_noise_source_on(diode, 1, 'now', 0)
# # If using Data simulator, fire the simulated noise diode for desired period to toggle power levels in output
# if hasattr(data.req, 'data_fire_nd'):
# data.req.data_fire_nd(np.ceil(float(on) / dump_period))
# time.sleep(on)
# # Mark on -> off transition as last firing
# session.last_nd_firing = time.time()
# # Switch noise diode off on all antennas
# ants.req.rfe3_rfe15_noise_source_on(diode, 0, 'now', 0)
# time.sleep(off)
#
# user_logger.info('noise diode fired')
# return True
def set_target(self, target):
"""Set target to use for tracking or scanning.
This sets the target on all antennas involved in the session, as well as
on the CBF (where it serves as delay-tracking centre). It also moves the
test target in the Data simulator to match the requested target (if it is
a stationary 'azel' type).
Parameters
----------
target : :class:`katpoint.Target` object or string
Target as an object or description string
"""
if self.ants is None:
raise ValueError('No antennas specified for session - please run session.standard_setup first')
# Create references to allow easy copy-and-pasting from this function
ants, data = self.ants, self.data
# Convert description string to target object, or keep object as is
target = target if isinstance(target, katpoint.Target) else katpoint.Target(target)
# Set the antenna target (antennas will already move there if in mode 'POINT')
ants.req.target(target)
# Provide target to the data proxy, which will use it as delay-tracking center
# XXX No fringe stopping support in data_rts yet
# data.req.target(target)
# If using Data simulator and target is azel type, move test target here (allows changes in correlation power)
if hasattr(data.req, 'cbf_test_target') and target.body_type == 'azel':
azel = katpoint.rad2deg(np.array(target.azel()))
data.req.cbf_test_target(azel[0], azel[1], 100.)
def track(self, target, duration=20.0, announce=True):
"""Track a target.
This tracks the specified target with all antennas involved in the
session.
Parameters
----------
target : :class:`katpoint.Target` object or string
Target to track, as an object or description string
duration : float, optional
Minimum duration of track, in seconds
announce : {True, False}, optional
True if start of action should be announced, with details of settings
Returns
-------
success : {True, False}
True if track was successfully completed
Notes
-----
When the function returns, the antennas will still track the target and
data will still be recorded to the HDF5 file. The specified *duration*
is therefore a minimum value. Remember to run :meth:`end` to close the
file and finally stop the observation (automatically done when this
object is used in a with-statement)!
"""
if self.ants is None:
raise ValueError('No antennas | |
preClusteringUseChaining = cms.bool(True)
),
gemRecHitLabel = cms.InputTag("gemRecHits")
)
hbhereco = cms.EDProducer("HBHEPhase1Reconstructor",
algoConfigClass = cms.string(''),
algorithm = cms.PSet(
Class = cms.string('SimpleHBHEPhase1Algo'),
activeBXs = cms.vint32(
-3, -2, -1, 0, 1,
2, 3, 4
),
applyPedConstraint = cms.bool(True),
applyPulseJitter = cms.bool(False),
applyTimeConstraint = cms.bool(True),
applyTimeSlew = cms.bool(True),
applyTimeSlewM3 = cms.bool(True),
chiSqSwitch = cms.double(15.0),
correctForPhaseContainment = cms.bool(True),
correctionPhaseNS = cms.double(6.0),
deltaChiSqThresh = cms.double(0.001),
dynamicPed = cms.bool(False),
firstSampleShift = cms.int32(0),
fitTimes = cms.int32(1),
meanPed = cms.double(0.0),
meanTime = cms.double(0.0),
nMaxItersMin = cms.int32(500),
nMaxItersNNLS = cms.int32(500),
nnlsThresh = cms.double(1e-11),
pulseJitter = cms.double(1.0),
respCorrM3 = cms.double(1.0),
samplesToAdd = cms.int32(2),
tdcTimeShift = cms.double(0.0),
timeMax = cms.double(12.5),
timeMin = cms.double(-12.5),
timeSigmaHPD = cms.double(5.0),
timeSigmaSiPM = cms.double(2.5),
timeSlewParsType = cms.int32(3),
ts4Max = cms.vdouble(100.0, 20000.0, 30000),
ts4Min = cms.double(0.0),
ts4Thresh = cms.double(0.0),
ts4chi2 = cms.vdouble(15.0, 15.0),
useM2 = cms.bool(False),
useM3 = cms.bool(True),
useMahi = cms.bool(True)
),
digiLabelQIE11 = cms.InputTag("hcalDigis"),
digiLabelQIE8 = cms.InputTag("hcalDigis"),
dropZSmarkedPassed = cms.bool(True),
flagParametersQIE11 = cms.PSet(
),
flagParametersQIE8 = cms.PSet(
hitEnergyMinimum = cms.double(1.0),
hitMultiplicityThreshold = cms.int32(17),
nominalPedestal = cms.double(3.0),
pulseShapeParameterSets = cms.VPSet(
cms.PSet(
pulseShapeParameters = cms.vdouble(
0.0, 100.0, -50.0, 0.0, -15.0,
0.15
)
),
cms.PSet(
pulseShapeParameters = cms.vdouble(
100.0, 2000.0, -50.0, 0.0, -5.0,
0.05
)
),
cms.PSet(
pulseShapeParameters = cms.vdouble(
2000.0, 1000000.0, -50.0, 0.0, 95.0,
0.0
)
),
cms.PSet(
pulseShapeParameters = cms.vdouble(
-1000000.0, 1000000.0, 45.0, 0.1, 1000000.0,
0.0
)
)
)
),
makeRecHits = cms.bool(True),
processQIE11 = cms.bool(True),
processQIE8 = cms.bool(True),
pulseShapeParametersQIE11 = cms.PSet(
),
pulseShapeParametersQIE8 = cms.PSet(
LeftSlopeCut = cms.vdouble(5, 2.55, 2.55),
LeftSlopeThreshold = cms.vdouble(250, 500, 100000),
LinearCut = cms.vdouble(-3, -0.054, -0.054),
LinearThreshold = cms.vdouble(20, 100, 100000),
MinimumChargeThreshold = cms.double(20),
MinimumTS4TS5Threshold = cms.double(100),
R45MinusOneRange = cms.double(0.2),
R45PlusOneRange = cms.double(0.2),
RMS8MaxCut = cms.vdouble(-13.5, -11.5, -11.5),
RMS8MaxThreshold = cms.vdouble(20, 100, 100000),
RightSlopeCut = cms.vdouble(5, 4.15, 4.15),
RightSlopeSmallCut = cms.vdouble(1.08, 1.16, 1.16),
RightSlopeSmallThreshold = cms.vdouble(150, 200, 100000),
RightSlopeThreshold = cms.vdouble(250, 400, 100000),
TS3TS4ChargeThreshold = cms.double(70),
TS3TS4UpperChargeThreshold = cms.double(20),
TS4TS5ChargeThreshold = cms.double(70),
TS4TS5LowerCut = cms.vdouble(
-1, -0.7, -0.5, -0.4, -0.3,
0.1
),
TS4TS5LowerThreshold = cms.vdouble(
100, 120, 160, 200, 300,
500
),
TS4TS5UpperCut = cms.vdouble(1, 0.8, 0.75, 0.72),
TS4TS5UpperThreshold = cms.vdouble(70, 90, 100, 400),
TS5TS6ChargeThreshold = cms.double(70),
TS5TS6UpperChargeThreshold = cms.double(20),
TriangleIgnoreSlow = cms.bool(False),
TrianglePeakTS = cms.uint32(10000),
UseDualFit = cms.bool(True)
),
recoParamsFromDB = cms.bool(True),
saveDroppedInfos = cms.bool(False),
saveEffectivePedestal = cms.bool(True),
saveInfos = cms.bool(False),
setLegacyFlagsQIE11 = cms.bool(False),
setLegacyFlagsQIE8 = cms.bool(True),
setNegativeFlagsQIE11 = cms.bool(False),
setNegativeFlagsQIE8 = cms.bool(True),
setNoiseFlagsQIE11 = cms.bool(False),
setNoiseFlagsQIE8 = cms.bool(True),
setPulseShapeFlagsQIE11 = cms.bool(False),
setPulseShapeFlagsQIE8 = cms.bool(True),
sipmQNTStoSum = cms.int32(3),
sipmQTSShift = cms.int32(0),
tsFromDB = cms.bool(False),
use8ts = cms.bool(True)
)
hfprereco = cms.EDProducer("HFPreReconstructor",
digiLabel = cms.InputTag("hcalDigis"),
dropZSmarkedPassed = cms.bool(False),
forceSOI = cms.int32(-1),
soiShift = cms.int32(0),
sumAllTimeSlices = cms.bool(False),
tsFromDB = cms.bool(False)
)
hfreco = cms.EDProducer("HFPhase1Reconstructor",
PETstat = cms.PSet(
HcalAcceptSeverityLevel = cms.int32(9),
longETParams = cms.vdouble(
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0
),
longEnergyParams = cms.vdouble(
43.5, 45.7, 48.32, 51.36, 54.82,
58.7, 63.0, 67.72, 72.86, 78.42,
84.4, 90.8, 97.62
),
long_R = cms.vdouble(0.98),
long_R_29 = cms.vdouble(0.8),
shortETParams = cms.vdouble(
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0
),
shortEnergyParams = cms.vdouble(
35.1773, 35.37, 35.7933, 36.4472, 37.3317,
38.4468, 39.7925, 41.3688, 43.1757, 45.2132,
47.4813, 49.98, 52.7093
),
short_R = cms.vdouble(0.8),
short_R_29 = cms.vdouble(0.8)
),
S8S1stat = cms.PSet(
HcalAcceptSeverityLevel = cms.int32(9),
isS8S1 = cms.bool(True),
longETParams = cms.vdouble(
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0
),
longEnergyParams = cms.vdouble(
40, 100, 100, 100, 100,
100, 100, 100, 100, 100,
100, 100, 100
),
long_optimumSlope = cms.vdouble(
0.3, 0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1
),
shortETParams = cms.vdouble(
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0
),
shortEnergyParams = cms.vdouble(
40, 100, 100, 100, 100,
100, 100, 100, 100, 100,
100, 100, 100
),
short_optimumSlope = cms.vdouble(
0.3, 0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1, 0.1, 0.1,
0.1, 0.1, 0.1
)
),
S9S1stat = cms.PSet(
HcalAcceptSeverityLevel = cms.int32(9),
isS8S1 = cms.bool(False),
longETParams = cms.vdouble(
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0
),
longEnergyParams = cms.vdouble(
43.5, 45.7, 48.32, 51.36, 54.82,
58.7, 63.0, 67.72, 72.86, 78.42,
84.4, 90.8, 97.62
),
long_optimumSlope = cms.vdouble(
-99999, 0.0164905, 0.0238698, 0.0321383, 0.041296,
0.0513428, 0.0622789, 0.0741041, 0.0868186, 0.100422,
0.135313, 0.136289, 0.0589927
),
shortETParams = cms.vdouble(
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0
),
shortEnergyParams = cms.vdouble(
35.1773, 35.37, 35.7933, 36.4472, 37.3317,
38.4468, 39.7925, 41.3688, 43.1757, 45.2132,
47.4813, 49.98, 52.7093
),
short_optimumSlope = cms.vdouble(
-99999, 0.0164905, 0.0238698, 0.0321383, 0.041296,
0.0513428, 0.0622789, 0.0741041, 0.0868186, 0.100422,
0.135313, 0.136289, 0.0589927
)
),
algoConfigClass = cms.string('HFPhase1PMTParams'),
algorithm = cms.PSet(
Class = cms.string('HFFlexibleTimeCheck'),
alwaysCalculateQAsymmetry = cms.bool(False),
energyWeights = cms.vdouble(
1.0, 1.0, 1.0, 0.0, 1.0,
0.0, 2.0, 0.0, 2.0, 0.0,
2.0, 0.0, 1.0, 0.0, 0.0,
1.0, 0.0, 1.0, 0.0, 2.0,
0.0, 2.0, 0.0, 2.0, 0.0,
1.0
),
minChargeForOvershoot = cms.double(10000000000.0),
minChargeForUndershoot = cms.double(10000000000.0),
rejectAllFailures = cms.bool(True),
soiPhase = cms.uint32(1),
tfallIfNoTDC = cms.double(-101.0),
timeShift = cms.double(0.0),
tlimits = cms.vdouble(-1000.0, 1000.0, -1000.0, 1000.0),
triseIfNoTDC = cms.double(-100.0)
),
checkChannelQualityForDepth3and4 = cms.bool(True),
inputLabel = cms.InputTag("hfprereco"),
setNoiseFlags = cms.bool(True),
useChannelQualityFromDB = cms.bool(True)
)
horeco = cms.EDProducer("HcalHitReconstructor",
Subdetector = cms.string('HO'),
correctForPhaseContainment = cms.bool(True),
correctForTimeslew = cms.bool(True),
correctTiming = cms.bool(True),
correctionPhaseNS = cms.double(13.0),
dataOOTCorrectionCategory = cms.string('Data'),
dataOOTCorrectionName = cms.string(''),
digiLabel = cms.InputTag("hcalDigis"),
dropZSmarkedPassed = cms.bool(True),
firstAuxTS = cms.int32(4),
firstSample = cms.int32(4),
mcOOTCorrectionCategory = cms.string('MC'),
mcOOTCorrectionName = cms.string(''),
recoParamsFromDB = cms.bool(True),
samplesToAdd = cms.int32(4),
saturationParameters = cms.PSet(
maxADCvalue = cms.int32(127)
),
setHSCPFlags = cms.bool(True),
setNegativeFlags = cms.bool(False),
setNoiseFlags = cms.bool(True),
setPulseShapeFlags = cms.bool(False),
setSaturationFlags = cms.bool(True),
setTimingTrustFlags = cms.bool(False),
tsFromDB = cms.bool(True),
useLeakCorrection = cms.bool(False)
)
me0RecHits = cms.EDProducer("ME0RecHitProducer",
me0DigiLabel = cms.InputTag("simMuonME0PseudoReDigis"),
recAlgo = cms.string('ME0RecHitStandardAlgo'),
recAlgoConfig = cms.PSet(
)
)
me0Segments = cms.EDProducer("ME0SegmentProducer",
algo_psets = cms.VPSet(
cms.PSet(
algo_name = cms.string('ME0SegmentAlgorithm'),
algo_pset = cms.PSet(
ME0Debug = cms.untracked.bool(True),
dEtaChainBoxMax = cms.double(0.05),
dPhiChainBoxMax = cms.double(0.02),
dTimeChainBoxMax = cms.double(15.0),
dXclusBoxMax = cms.double(1.0),
dYclusBoxMax = cms.double(5.0),
maxRecHitsInCluster = cms.int32(6),
minHitsPerSegment = cms.uint32(3),
preClustering = cms.bool(True),
preClusteringUseChaining = cms.bool(True)
)
),
cms.PSet(
algo_name = cms.string('ME0SegAlgoRU'),
algo_pset = cms.PSet(
allowWideSegments = cms.bool(True),
doCollisions = cms.bool(True),
maxChi2Additional = cms.double(100.0),
maxChi2GoodSeg = cms.double(50),
maxChi2Prune = cms.double(50),
maxETASeeds = cms.double(0.1),
maxPhiAdditional = cms.double(0.001096605744),
maxPhiSeeds = cms.double(0.001096605744),
maxTOFDiff = cms.double(25),
minNumberOfHits = cms.uint32(4),
requireCentralBX = cms.bool(True)
)
)
),
algo_type = cms.int32(2),
me0RecHitLabel = cms.InputTag("me0RecHits")
)
offlineBeamSpot = cms.EDProducer("BeamSpotProducer")
particleFlowClusterHGCal = cms.EDProducer("PFClusterProducer",
energyCorrector = cms.PSet(
),
initialClusteringStep = cms.PSet(
algoName = cms.string('RealisticSimClusterMapper'),
calibMaxEta = cms.double(3.0),
calibMinEta = cms.double(1.4),
egammaCalib = cms.vdouble(
1.0, 1.0, 1.01, 1.01, 1.02,
1.03, 1.04, 1.04
),
exclusiveFraction = cms.double(0.6),
hadronCalib = cms.vdouble(
1.24, 1.24, 1.24, 1.23, 1.24,
1.25, 1.29, 1.29
),
invisibleFraction = cms.double(0.6),
maxDforTimingSquared = cms.double(4.0),
maxDistance = cms.double(10.0),
maxDistanceFilter = cms.bool(True),
minNHitsforTiming = cms.uint32(3),
simClusterSrc = cms.InputTag("mix","MergedCaloTruth"),
thresholdsByDetector = cms.VPSet(),
timeOffset = cms.double(5),
useMCFractionsForExclEnergy = cms.bool(False)
),
pfClusterBuilder = cms.PSet(
),
positionReCalc = cms.PSet(
algoName = cms.string('Cluster3DPCACalculator'),
minFractionInCalc = cms.double(1e-09),
updateTiming = cms.bool(False)
),
recHitCleaners = cms.VPSet(),
recHitsSource = cms.InputTag("particleFlowRecHitHGC"),
seedFinder = cms.PSet(
algoName = cms.string('PassThruSeedFinder'),
nNeighbours = cms.int32(8),
thresholdsByDetector = cms.VPSet()
)
)
rpcRecHits = cms.EDProducer("RPCRecHitProducer",
deadSource = cms.string('File'),
deadvecfile = cms.FileInPath('RecoLocalMuon/RPCRecHit/data/RPCDeadVec.dat'),
maskSource = cms.string('File'),
maskvecfile = cms.FileInPath('RecoLocalMuon/RPCRecHit/data/RPCMaskVec.dat'),
recAlgo = cms.string('RPCRecHitStandardAlgo'),
recAlgoConfig = cms.PSet(
),
rpcDigiLabel = cms.InputTag("simMuonRPCDigis")
)
MeasurementTrackerEvent = cms.EDProducer("MeasurementTrackerEventProducer",
Phase2TrackerCluster1DProducer = cms.string('siPhase2Clusters'),
badPixelFEDChannelCollectionLabels = cms.VInputTag("siPixelDigis"),
inactivePixelDetectorLabels = cms.VInputTag(),
inactiveStripDetectorLabels = cms.VInputTag("siStripDigis"),
measurementTracker = cms.string(''),
pixelCablingMapLabel = cms.string(''),
pixelClusterProducer = cms.string('siPixelClusters'),
skipClusters = cms.InputTag(""),
stripClusterProducer = cms.string(''),
switchOffPixelsIfEmpty = cms.bool(True)
)
ak4CaloJetsForTrk = cms.EDProducer("FastjetJetProducer",
Active_Area_Repeats = cms.int32(1),
GhostArea = cms.double(0.01),
Ghost_EtaMax = cms.double(5.0),
Rho_EtaMax = cms.double(4.4),
doAreaDiskApprox = cms.bool(False),
doAreaFastjet = cms.bool(False),
doPUOffsetCorr = cms.bool(False),
doPVCorrection = cms.bool(True),
doRhoFastjet = cms.bool(False),
inputEMin = cms.double(0.0),
inputEtMin = cms.double(0.3),
jetAlgorithm = cms.string('AntiKt'),
jetPtMin = cms.double(10.0),
jetType = cms.string('CaloJet'),
maxBadEcalCells = cms.uint32(9999999),
maxBadHcalCells = cms.uint32(9999999),
maxProblematicEcalCells = cms.uint32(9999999),
maxProblematicHcalCells = cms.uint32(9999999),
maxRecoveredEcalCells = cms.uint32(9999999),
maxRecoveredHcalCells = cms.uint32(9999999),
minSeed = cms.uint32(14327),
nSigmaPU = cms.double(1.0),
puPtMin = cms.double(10),
| |
optchords=alt_optchords)
# print(repr(unichars), repr(alt_optchords), funcs[alt_optchords])
#
# Feed Keyboard into Bottom Lines of the Screen, a la the Ex inside Vim
#
class TerminalEx:
"""Feed Keyboard into Line at Bottom of Screen of Scrolling Rows, a la Ex"""
def __init__(self, editor, vi_reply):
self.editor = editor
self.vi_reply = vi_reply
self.ex_line = None
def read_ex_line(self):
"""Take an Input Line from beneath the Scrolling Rows"""
editor = self.editor
self.ex_line = ""
keyboard = TerminalKeyboardEx(ex=self)
try:
editor.run_skin_with_keyboard(keyboard) # TerminalKeyboardEx
assert False # unreached
except SystemExit:
line = self.ex_line
editor.skin.doing_traceback = editor.skin.traceback
return line
def flush_ex_status(self):
"""Paint Status and Cursor now"""
editor = self.editor
keyboard = editor.skin.keyboard
reply = editor.skin.reply
editor.flush_editor(keyboard, reply=reply) # for 'flush_ex_status'
def format_ex_status(self, reply):
"""Keep up the Vi Reply while working the Ex Keyboard, but add the Input Line"""
_ = reply
ex_line = self.ex_line
vi_reply = self.vi_reply
ex_reply = vi_reply + ex_line
return ex_reply
def place_ex_cursor(self):
"""Place the Cursor"""
editor = self.editor
painter = editor.painter
ex_reply = self.format_ex_status(editor.skin.reply)
row = painter.status_row
column = len(ex_reply)
return TerminalPin(row, column=column)
def do_clear_chars(self): # Ex ⌃U in Vim
"""Undo all the Append Chars, if any Not undone already"""
self.ex_line = ""
def do_append_char(self):
"""Append the Chords to the Input Line"""
editor = self.editor
chars = editor.get_arg0_chars()
self.ex_line += chars
def do_undo_append_char(self):
"""Undo the last Append Char, else Quit Ex"""
ex_line = self.ex_line
if ex_line:
self.ex_line = ex_line[:-1]
else:
self.ex_line = None
sys.exit()
def do_quit_ex(self): # Ex ⌃C in Vim
"""Lose all input and quit Ex"""
self.ex_line = None
sys.exit()
def do_copy_down(self): # Ex ⌃P, ↑ Up-Arrow, in Vim
"""Recall last input line"""
editor = self.editor
ex_line = self.ex_line
editor_finding_line = editor.finding_line
if ex_line is not None:
if editor_finding_line is not None:
if editor_finding_line.startswith(ex_line):
self.ex_line = editor_finding_line
return
raise ValueError("substring not found")
class TerminalKeyboardEx(TerminalKeyboard):
"""Map Keyboard Inputs to Code, for when feeling like Ex"""
# pylint: disable=too-few-public-methods
def __init__(self, ex):
super().__init__()
self.ex = ex
self.editor = ex.editor
self.format_status_func = ex.format_ex_status
self.place_cursor_func = ex.place_ex_cursor
self._init_by_ex_chords_()
def _init_by_ex_chords_(self):
ex = self.ex
funcs = self.func_by_chords
editor = self.editor
# Define the C0_CONTROL_STDINS
for chords in C0_CONTROL_STDINS:
funcs[chords] = editor.do_raise_name_error
# Mutate the C0_CONTROL_STDINS definitions
funcs[b"\x03"] = ex.do_quit_ex # ETX, ⌃C, 3
funcs[b"\x08"] = ex.do_undo_append_char # BS, ⌃H, 8 \b
funcs[b"\x0D"] = editor.do_sys_exit # CR, ⌃M, 13 \r
funcs[b"\x10"] = ex.do_copy_down # DLE, ⌃P, 16
funcs[b"\x1A"] = editor.do_suspend_frame # SUB, ⌃Z, 26
funcs[b"\x15"] = ex.do_clear_chars # NAK, ⌃U, 21
funcs[b"\x1B[A"] = ex.do_copy_down # ↑ Up-Arrow
funcs[b"\x7F"] = ex.do_undo_append_char # DEL, ⌃?, 127
# Define the BASIC_LATIN_STDINS
for chords in BASIC_LATIN_STDINS:
funcs[chords] = ex.do_append_char
# TODO: input Search Keys containing more than BASIC_LATIN_STDINS and #
# TODO: Define Chords beyond the C0_CONTROL_STDINS and BASIC_LATIN_STDINS
# TODO: such as U00A3 PoundSign
# TODO: define Esc to replace live Regex punctuation with calmer r"."
#
# Carry an Em Py for Emacs inside this Vi Py for Vim
#
class TerminalEm:
"""Feed Keyboard into Scrolling Rows of File of Lines of Chars, a la Emacs"""
# pylint: disable=too-many-public-methods
def __init__(self, files, script, evals):
self.main_traceback = None
vi = TerminalVi(files, script=script, evals=evals)
self.vi = vi
def run_inside_terminal(self):
"""Enter Terminal Driver, then run Emacs Keyboard, then exit Terminal Driver"""
vi = self.vi
try:
vi.run_inside_terminal(em=self)
finally:
self.main_traceback = vi.main_traceback # ⌃X⌃G⌃X⌃C Egg
def take_em_inserts(self):
"""Take keyboard Input Chords to mean insert Chars"""
editor = self.vi.editor
editor.intake_beyond = "inserting" # as if many 'do_em_self_insert_command'
def do_em_prefix_chord(self, chord): # TODO: # noqa C901 too complex
"""Take ⌃U { ⌃U } [ "-" ] { "0123456789" } [ ⌃U ] as a Prefix to more Chords"""
# Emacs ⌃U Universal-Argument
editor = self.vi.editor
prefix = editor.skin.nudge.prefix
chords = editor.skin.nudge.chords
keyboard = editor.skin.keyboard
intake_chords_set = keyboard.choose_intake_chords_set()
prefix_plus = chord if (prefix is None) else (prefix + chord)
prefix_opened = b"\x15" + prefix_plus.lstrip(b"\x15")
# Don't take more Prefix Chords after the first of the Chords to Call
if chords:
return False
assert b"\x15" not in intake_chords_set
# Start with one or more ⌃U, close with ⌃U, or start over with next ⌃U
if chord == b"\x15":
if not prefix:
editor.skin.nudge.prefix = prefix_plus
elif set(prefix) == set(b"\x15"):
editor.skin.nudge.prefix = prefix_plus
elif not prefix.endswith(b"\x15"):
editor.skin.nudge.prefix = prefix_plus
else:
editor.skin.nudge.prefix = chord
return True
# Take no more Chords after closing ⌃U (except for a next ⌃U above)
if prefix:
opening = set(prefix) == set(b"\x15")
closed = prefix.endswith(b"\x15") or (prefix.lstrip(b"\x15") == b"0")
if opening or not closed:
if (chord == b"-") and opening:
editor.skin.nudge.prefix = prefix_opened
return True
if (chord == b"0") and not prefix.endswith(b"-"):
editor.skin.nudge.prefix = prefix_opened
return True
if chord in b"123456789":
editor.skin.nudge.prefix = prefix_opened
return True
# Else declare Prefix complete
return False
# Em Py takes ⌃U - 0 and ⌃U 0 0..9 as complete
# Emacs quirkily disappears 0's after ⌃U if after -, after 0, or before 1..9
def eval_em_prefix(self, prefix):
"""Take the Chords of a Signed Int Prefix before the Called Chords"""
# pylint: disable=no-self-use
evalled = None
if prefix is not None: # then drop the ⌃U's and eval the Digits
prefix_digits = prefix.decode()
prefix_digits = "".join(_ for _ in prefix_digits if _ in "-0123456789")
if prefix_digits == "-": # except take "-" alone as -1
prefix_digits = "-1"
elif prefix and not prefix_digits: # and take ⌃U's alone as powers of 4
prefix_digits = str(4 ** len(prefix)).encode()
evalled = int(prefix_digits) if prefix_digits else None
return evalled # may be negative, zero, or positive int
# Emacs quirkily takes ⌃U's alone as powers of 4, Em Py does too
def uneval_em_prefix(self, prefix):
"""Rewrite history to make the Prefix Chords more explicit"""
_ = prefix
nudge = self.vi.editor.skin.nudge
lead_chord = nudge.chords[0] if nudge.chords else b"\x07" # TODO: ugly b"\x07"
# Echo no Prefix as no Prefix
arg1 = self.vi.editor.skin.arg1
if arg1 is None:
return None
# Echo Decimal Digits before Other Chords, with or without a leading Minus Sign
prefix = b"\x15" + str(arg1).encode()
if arg1 == -1:
prefix = b"\x15" + b"-"
if (lead_chord not in b"123456789") or (arg1 == 0):
return prefix
# Close the Prefix with ⌃U to separate from a Decimal Digit Chord
prefix += b"\x15"
return prefix
# Em Py echoes the Evalled Prefix, Emacs quirkily does Not
def do_em_negative_argument(self): # Emacs ⌥-
"""Mostly work like ⌃U -"""
skin = self.vi.editor.skin
arg1 = skin.arg1
chars_ahead = "\x15" # NAK, ⌃U, 21
if arg1 is None:
chars_ahead += "-"
else:
int_arg1 = int(arg1) # unneeded, ducks PyLint invalid-unary-operand-type
chars_ahead += str(-int_arg1)
skin.chord_ints_ahead = list(chars_ahead.encode())
def do_em_digit_argument(self): # Emacs ⌥0, ⌥1, ⌥2, ⌥3, ⌥4, ⌥5, ⌥6, ⌥7, ⌥8, ⌥9
"""Mostly work like ⌃U 0, 1, 2, 3, 4, 5, 6, 7, 8, 9"""
vi = self.vi
editor = vi.editor
skin = editor.skin
arg1 = skin.arg1
chord_ints_ahead = skin.chord_ints_ahead
#
str_digit = vi.vi_get_arg0_digit()
chars_ahead = "\x15" # NAK, ⌃U, 21
if arg1 is None:
chars_ahead += str_digit
else:
chars_ahead += str(arg1) + str_digit
chord_ints_ahead[::] = chord_ints_ahead + list(chars_ahead.encode())
def do_em_quoted_insert(self): # Emacs ⌃Q
"""Take the next Input Keyboard Chord to replace or insert, not as Control"""
self.vi.do_vi_quoted_insert()
#
# Define Control Chords
#
def do_em_keyboard_quit(self): # Emacs ⌃G # Em Py Init
"""Cancel stuff, and eventually prompt to quit Em Py"""
# Start up lazily, so as to blink into XTerm Alt Screen only when needed
vi = self.vi
if not vi.editor.painter.rows:
vi.do_next_vi_file() # as if Vi Py b":n\r"
vi.vi_print() # clear the announce of First File
vi.do_resume_vi() # as if Vi Py b":em\r"
# Cancel stuff, and eventually prompt to quit Em Py
count = self.vi.editor.get_arg1_int(default=None)
if count is not None: # ⌃U 123 ⌃G Egg
self.vi.vi_print("Quit Repeat Count")
else:
held_vi_file = vi.held_vi_file
title_py = sys_argv_0_title_py() # "Vi Py", "Em Py", etc
version = module_file_version_zero()
nickname = held_vi_file.pick_file_nickname() if held_vi_file else None
vi.vi_print(
"{!r} Press ⌃X⌃C to save changes and quit {} {}".format(
nickname, title_py, version
)
)
# such as '/dev/stdout' Press ⌃X⌃C to save changes and quit Emacs Py 0.1.2
| |
import requests
import urllib.request, urllib.parse, urllib.error
import logging
import hashlib
import base64
import os
import sys
import copy
import xml.dom.minidom
import xml.etree.ElementTree
from requests import Request, Session
from urllib.parse import quote
from hashlib import md5
from .streambody import StreamBody
from .xml2dict import Xml2Dict
from dicttoxml import dicttoxml
from .cos_auth import CosS3Auth
from .cos_comm import *
from .cos_threadpool import SimpleThreadPool
from .cos_exception import CosClientError
from .cos_exception import CosServiceError
import imp
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='cos_v5.log',
filemode='w')
logger = logging.getLogger(__name__)
imp.reload(sys)
class CosConfig(object):
"""config类,保存用户相关信息"""
def __init__(self, Appid=None, Region=None, Secret_id=None, Secret_key=None, Token=None, Scheme=None, Timeout=None, Access_id=None, Access_key=None):
"""初始化,保存用户的信息
:param Appid(string): 用户APPID.
:param Region(string): 地域信息.
:param Secret_id(string): 秘钥SecretId.
:param Secret_key(string): 秘钥SecretKey.
:param Token(string): 临时秘钥使用的token.
:param Schema(string): http/https
:param Timeout(int): http超时时间.
:param Access_id(string): 秘钥AccessId(兼容).
:param Access_key(string): 秘钥AccessKey(兼容).
"""
self._appid = Appid
self._region = format_region(Region)
self._token = Token
self._timeout = Timeout
if Scheme is None:
Scheme = 'http'
if(Scheme != 'http' and Scheme != 'https'):
raise CosClientError('Scheme can be only set to http/https')
self._scheme = Scheme
# 兼容(SecretId,SecretKey)以及(AccessId,AccessKey)
if(Secret_id and Secret_key):
self._secret_id = Secret_id
self._secret_key = Secret_key
elif(Access_id and Access_key):
self._secret_id = Access_id
self._secret_key = Access_key
else:
raise CosClientError('SecretId and SecretKey is Required!')
logger.info("config parameter-> appid: {appid}, region: {region}".format(
appid=Appid,
region=Region))
def uri(self, bucket, path=None, scheme=None, region=None):
"""拼接url
:param bucket(string): 存储桶名称.
:param path(string): 请求COS的路径.
:return(string): 请求COS的URL地址.
"""
bucket = format_bucket(bucket, self._appid)
if scheme is None:
scheme = self._scheme
if region is None:
region = self._region
if path is not None:
if path == "":
raise CosClientError("Key can't be empty string")
if path[0] == '/':
path = path[1:]
url = "{scheme}://{bucket}.{region}.myqcloud.com/{path}".format(
scheme=scheme,
bucket=to_unicode(bucket),
region=region,
path=to_unicode(path)
)
else:
url = "{scheme}://{bucket}.{region}.myqcloud.com/".format(
scheme=self._scheme,
bucket=to_unicode(bucket),
region=self._region
)
return url
class CosS3Client(object):
"""cos客户端类,封装相应请求"""
def __init__(self, conf, retry=1, session=None):
"""初始化client对象
:param conf(CosConfig): 用户的配置.
:param retry(int): 失败重试的次数.
:param session(object): http session.
"""
self._conf = conf
self._retry = retry # 重试的次数,分片上传时可适当增大
if session is None:
self._session = requests.session()
else:
self._session = session
def get_auth(self, Method, Bucket, Key='', Expired=300, Headers={}, Params={}):
"""获取签名
:param Method(string): http method,如'PUT','GET'.
:param Bucket(string): 存储桶名称.
:param Key(string): 请求COS的路径.
:param Expired(int): 签名有效时间,单位为s.
:param headers(dict): 签名中的http headers.
:param params(dict): 签名中的http params.
:return (string): 计算出的V5签名.
"""
url = self._conf.uri(bucket=Bucket, path=quote(Key, '/-_.~'))
r = Request(Method, url, headers=Headers, params=Params)
auth = CosS3Auth(self._conf._secret_id, self._conf._secret_key, Key, Params, Expired)
return auth(r).headers['Authorization']
def send_request(self, method, url, timeout=30, **kwargs):
"""封装request库发起http请求"""
if self._conf._timeout is not None: # 用户自定义超时时间
timeout = self._conf._timeout
if self._conf._token is not None:
kwargs['headers']['x-cos-security-token'] = self._conf._token
kwargs['headers']['User-Agent'] = 'cos-python-sdk-v5.3.2'
try:
for j in range(self._retry):
if method == 'POST':
res = self._session.post(url, timeout=timeout, **kwargs)
elif method == 'GET':
res = self._session.get(url, timeout=timeout, **kwargs)
elif method == 'PUT':
res = self._session.put(url, timeout=timeout, **kwargs)
elif method == 'DELETE':
res = self._session.delete(url, timeout=timeout, **kwargs)
elif method == 'HEAD':
res = self._session.head(url, timeout=timeout, **kwargs)
if res.status_code < 300:
return res
except Exception as e: # 捕获requests抛出的如timeout等客户端错误,转化为客户端错误
logger.exception('url:%s, exception:%s' % (url, str(e)))
raise CosClientError(str(e))
if res.status_code >= 400: # 所有的4XX,5XX都认为是COSServiceError
if method == 'HEAD' and res.status_code == 404: # Head 需要处理
info = dict()
info['code'] = 'NoSuchResource'
info['message'] = 'The Resource You Head Not Exist'
info['resource'] = url
info['requestid'] = res.headers['x-cos-request-id']
info['traceid'] = res.headers['x-cos-trace-id']
logger.error(info)
raise CosServiceError(method, info, res.status_code)
else:
msg = res.text
if msg == '': # 服务器没有返回Error Body时 给出头部的信息
msg = res.headers
logger.error(msg)
raise CosServiceError(method, msg, res.status_code)
# s3 object interface begin
def put_object(self, Bucket, Body, Key, **kwargs):
"""单文件上传接口,适用于小文件,最大不得超过5GB
:param Bucket(string): 存储桶名称.
:param Body(file|string): 上传的文件内容,类型为文件流或字节流.
:param Key(string): COS路径.
:kwargs(dict): 设置上传的headers.
:return(dict): 上传成功返回的结果,包含ETag等信息.
"""
headers = mapped(kwargs)
if 'Metadata' in list(headers.keys()):
for i in list(headers['Metadata'].keys()):
headers[i] = headers['Metadata'][i]
headers.pop('Metadata')
url = self._conf.uri(bucket=Bucket, path=quote(Key, '/-_.~')) # 提前对key做encode
logger.info("put object, url=:{url} ,headers=:{headers}".format(
url=url,
headers=headers))
Body = deal_with_empty_file_stream(Body)
rt = self.send_request(
method='PUT',
url=url,
auth=CosS3Auth(self._conf._secret_id, self._conf._secret_key, Key),
data=Body,
headers=headers)
response = rt.headers
return response
def get_object(self, Bucket, Key, **kwargs):
"""单文件下载接口
:param Bucket(string): 存储桶名称.
:param Key(string): COS路径.
:param kwargs(dict): 设置下载的headers.
:return(dict): 下载成功返回的结果,包含Body对应的StreamBody,可以获取文件流或下载文件到本地.
"""
headers = mapped(kwargs)
params = {}
for key in list(headers.keys()):
if key.startswith("response"):
params[key] = headers[key]
headers.pop(key)
url = self._conf.uri(bucket=Bucket, path=quote(Key, '/-_.~'))
logger.info("get object, url=:{url} ,headers=:{headers}".format(
url=url,
headers=headers))
rt = self.send_request(
method='GET',
url=url,
stream=True,
auth=CosS3Auth(self._conf._secret_id, self._conf._secret_key, Key),
params=params,
headers=headers)
response = rt.headers
response['Body'] = StreamBody(rt)
return response
def get_presigned_download_url(self, Bucket, Key, Expired=300):
"""生成预签名的下载url
:param Bucket(string): 存储桶名称.
:param Key(string): COS路径.
:param Expired(int): 签名过期时间.
:return(string): 预先签名的下载URL.
"""
url = self._conf.uri(bucket=Bucket, path=quote(Key, '/-_.~'))
sign = self.get_auth(Method='GET', Bucket=Bucket, Key=Key, Expired=300)
url = url + '?sign=' + urllib.parse.quote(sign)
return url
def delete_object(self, Bucket, Key, **kwargs):
"""单文件删除接口
:param Bucket(string): 存储桶名称.
:param Key(string): COS路径.
:param kwargs(dict): 设置请求headers.
:return: None.
"""
headers = mapped(kwargs)
url = self._conf.uri(bucket=Bucket, path=quote(Key, '/-_.~'))
logger.info("delete object, url=:{url} ,headers=:{headers}".format(
url=url,
headers=headers))
rt = self.send_request(
method='DELETE',
url=url,
auth=CosS3Auth(self._conf._secret_id, self._conf._secret_key, Key),
headers=headers)
return None
def delete_objects(self, Bucket, Delete={}, **kwargs):
"""文件批量删除接口,单次最多支持1000个object
:param Bucket(string): 存储桶名称.
:param Delete(dict): 批量删除的object信息.
:param kwargs(dict): 设置请求headers.
:return(dict): 批量删除的结果.
"""
lst = ['<Object>', '</Object>'] # 类型为list的标签
xml_config = format_xml(data=Delete, root='Delete', lst=lst)
headers = mapped(kwargs)
headers['Content-MD5'] = get_md5(xml_config)
headers['Content-Type'] = 'application/xml'
url = self._conf.uri(bucket=Bucket, path="?delete")
logger.info("put bucket replication, url=:{url} ,headers=:{headers}".format(
url=url,
headers=headers))
rt = self.send_request(
method='POST',
url=url,
data=xml_config,
auth=CosS3Auth(self._conf._secret_id, self._conf._secret_key),
headers=headers)
data = xml_to_dict(rt.text)
if 'Deleted' in list(data.keys()) and not isinstance(data['Deleted'], list):
lst = []
lst.append(data['Deleted'])
data['Deleted'] = lst
if 'Error' in list(data.keys()) and not isinstance(data['Error'], list):
lst = []
lst.append(data['Error'])
data['Error'] = lst
return data
def head_object(self, Bucket, Key, **kwargs):
"""获取文件信息
:param Bucket(string): 存储桶名称.
:param Key(string): COS路径.
:param kwargs(dict): 设置请求headers.
:return(dict): 文件的metadata信息.
"""
headers = mapped(kwargs)
url = self._conf.uri(bucket=Bucket, path=quote(Key, '/-_.~'))
logger.info("head object, url=:{url} ,headers=:{headers}".format(
url=url,
headers=headers))
rt = self.send_request(
method='HEAD',
url=url,
auth=CosS3Auth(self._conf._secret_id, self._conf._secret_key, Key),
headers=headers)
return rt.headers
def copy_object(self, Bucket, Key, CopySource, CopyStatus='Copy', **kwargs):
"""文件拷贝,文件信息修改
:param Bucket(string): 存储桶名称.
:param Key(string): 上传COS路径.
:param CopySource(dict): 拷贝源,包含Appid,Bucket,Region,Key.
:param CopyStatus(string): 拷贝状态,可选值'Copy'|'Replaced'.
:param kwargs(dict): 设置请求headers.
:return(dict): 拷贝成功的结果.
"""
headers = mapped(kwargs)
if 'Metadata' in list(headers.keys()):
for i in list(headers['Metadata'].keys()):
headers[i] = headers['Metadata'][i]
headers.pop('Metadata')
headers['x-cos-copy-source'] = gen_copy_source_url(CopySource)
if CopyStatus != 'Copy' and CopyStatus != 'Replaced':
raise CosClientError('CopyStatus must be Copy or Replaced')
headers['x-cos-metadata-directive'] = CopyStatus
url = self._conf.uri(bucket=Bucket, path=quote(Key, '/-_.~'))
logger.info("copy object, url=:{url} ,headers=:{headers}".format(
url=url,
headers=headers))
rt = self.send_request(
method='PUT',
url=url,
auth=CosS3Auth(self._conf._secret_id, self._conf._secret_key, Key),
headers=headers)
data = xml_to_dict(rt.text)
return data
def upload_part_copy(self, Bucket, Key, PartNumber, UploadId, CopySource, CopySourceRange='', **kwargs):
"""拷贝指定文件至分块上传
:param Bucket(string): 存储桶名称.
:param Key(string): 上传COS路径.
:param PartNumber(int): 上传分块的编号.
:param UploadId(string): 分块上传创建的UploadId.
:param CopySource(dict): 拷贝源,包含Appid,Bucket,Region,Key.
:param CopySourceRange(string): 拷贝源的字节范围,bytes=first-last。
:param kwargs(dict): 设置请求headers.
:return(dict): 拷贝成功的结果.
"""
headers = mapped(kwargs)
headers['x-cos-copy-source'] = gen_copy_source_url(CopySource)
headers['x-cos-copy-source-range'] = CopySourceRange
url = self._conf.uri(bucket=Bucket, path=quote(Key, '/-_.~')+"?partNumber={PartNumber}&uploadId={UploadId}".format(
PartNumber=PartNumber,
UploadId=UploadId))
logger.info("upload part copy, url=:{url} ,headers=:{headers}".format(
url=url,
headers=headers))
rt = self.send_request(
method='PUT',
url=url,
headers=headers,
auth=CosS3Auth(self._conf._secret_id, self._conf._secret_key, Key))
data = xml_to_dict(rt.text)
return data
def create_multipart_upload(self, Bucket, Key, **kwargs):
"""创建分片上传,适用于大文件上传
:param Bucket(string): 存储桶名称.
:param Key(string): COS路径.
:param kwargs(dict): 设置请求headers.
:return(dict): 初始化分块上传返回的结果,包含UploadId等信息.
"""
headers = mapped(kwargs)
if 'Metadata' in list(headers.keys()):
for i in list(headers['Metadata'].keys()):
headers[i] = headers['Metadata'][i]
headers.pop('Metadata')
url = self._conf.uri(bucket=Bucket, path=quote(Key, '/-_.~')+"?uploads")
logger.info("create multipart upload, url=:{url} ,headers=:{headers}".format(
url=url,
headers=headers))
rt = self.send_request(
method='POST',
url=url,
auth=CosS3Auth(self._conf._secret_id, self._conf._secret_key, Key),
headers=headers)
data = xml_to_dict(rt.text)
return data
def upload_part(self, Bucket, Key, Body, PartNumber, UploadId, **kwargs):
"""上传分片,单个大小不得超过5GB
:param Bucket(string): 存储桶名称.
:param Key(string): COS路径.
:param Body(file|string): 上传分块的内容,可以为文件流或者字节流.
:param PartNumber(int): 上传分块的编号.
:param UploadId(string): 分块上传创建的UploadId.
:param kwargs(dict): 设置请求headers.
:return(dict): 上传成功返回的结果,包含单个分块ETag等信息.
"""
headers = mapped(kwargs)
url = self._conf.uri(bucket=Bucket, path=quote(Key, '/-_.~')+"?partNumber={PartNumber}&uploadId={UploadId}".format(
PartNumber=PartNumber,
UploadId=UploadId))
logger.info("put object, url=:{url} ,headers=:{headers}".format(
url=url,
headers=headers))
Body = deal_with_empty_file_stream(Body)
rt = self.send_request(
method='PUT',
url=url,
headers=headers,
auth=CosS3Auth(self._conf._secret_id, self._conf._secret_key, Key),
data=Body)
response = dict()
logger.debug("local md5: {key}".format(key=rt.headers['ETag'][1:-1]))
logger.debug("cos md5: {key}".format(key=md5(Body).hexdigest()))
if md5(Body).hexdigest() != rt.headers['ETag'][1:-1]:
raise CosClientError("MD5 inconsistencies")
response['ETag'] = rt.headers['ETag']
return response
def complete_multipart_upload(self, Bucket, Key, UploadId, MultipartUpload={}, **kwargs):
"""完成分片上传,除最后一块分块块大小必须大于等于1MB,否则会返回错误.
:param Bucket(string): 存储桶名称.
:param Key(string): COS路径.
:param UploadId(string): 分块上传创建的UploadId.
:param MultipartUpload(dict): 所有分块的信息,包含Etag和PartNumber.
:param kwargs(dict): 设置请求headers.
:return(dict): 上传成功返回的结果,包含整个文件的ETag等信息.
"""
headers = mapped(kwargs)
url = self._conf.uri(bucket=Bucket, path=quote(Key, '/-_.~')+"?uploadId={UploadId}".format(UploadId=UploadId))
logger.info("complete multipart upload, url=:{url} ,headers=:{headers}".format(
url=url,
headers=headers))
rt = self.send_request(
method='POST',
url=url,
auth=CosS3Auth(self._conf._secret_id, self._conf._secret_key, Key),
data=dict_to_xml(MultipartUpload),
timeout=1200, # 分片上传大文件的时间比较长,设置为20min
headers=headers)
data = xml_to_dict(rt.text)
return data
def abort_multipart_upload(self, Bucket, Key, UploadId, **kwargs):
"""放弃一个已经存在的分片上传任务,删除所有已经存在的分片.
:param Bucket(string): 存储桶名称.
:param Key(string): COS路径.
:param UploadId(string): 分块上传创建的UploadId.
:param kwargs(dict): 设置请求headers.
:return: None.
"""
headers = mapped(kwargs)
url = self._conf.uri(bucket=Bucket, path=quote(Key, '/-_.~')+"?uploadId={UploadId}".format(UploadId=UploadId))
logger.info("abort multipart upload, url=:{url} ,headers=:{headers}".format(
url=url,
headers=headers))
rt = self.send_request(
method='DELETE',
url=url,
auth=CosS3Auth(self._conf._secret_id, self._conf._secret_key, Key),
headers=headers)
return None
def list_parts(self, Bucket, Key, UploadId, EncodingType='', MaxParts=1000, PartNumberMarker=0, **kwargs):
"""列出已上传的分片.
:param Bucket(string): 存储桶名称.
:param Key(string): COS路径.
:param UploadId(string): 分块上传创建的UploadId.
| |
#!/usr/bin/env python
# Part of the psychopy_ext library
# Copyright 2010-2015 <NAME>
# The program is distributed under the terms of the GNU General Public License,
# either version 3 of the License, or (at your option) any later version.
"""
A library of simple models of vision
Simple usage::
import glob
from psychopy_ext import models
ims = glob.glob('Example_set/*.jpg') # get all jpg images
hmax = models.HMAX()
# if you want to see how similar your images are to each other
hmax.compare(ims)
# or to simply get the output and use it further
out = hmax.run(ims)
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# from __future__ import unicode_literals
import sys, os, glob, itertools, warnings, inspect, argparse, imp
import tempfile, shutil
import pickle
from collections import OrderedDict
import numpy as np
import scipy.ndimage
import pandas
import seaborn as sns
import matlab_wrapper
import sklearn.manifold
import sklearn.preprocessing, sklearn.metrics, sklearn.cluster
import skimage.feature, skimage.data
from psychopy_ext import stats, plot, report, utils
try:
imp.find_module('caffe')
HAS_CAFFE = True
except:
try:
os.environ['CAFFE']
# put Python bindings in the path
sys.path.insert(0, os.path.join(os.environ['CAFFE'], 'python'))
HAS_CAFFE = True
except:
HAS_CAFFE = False
if HAS_CAFFE:
# Suppress GLOG output for python bindings
GLOG_minloglevel = os.environ.pop('GLOG_minloglevel', None)
os.environ['GLOG_minloglevel'] = '5'
import caffe
from caffe.proto import caffe_pb2
from google.protobuf import text_format
HAS_CAFFE = True
# Turn GLOG output back on for subprocess calls
if GLOG_minloglevel is None:
del os.environ['GLOG_minloglevel']
else:
os.environ['GLOG_minloglevel'] = GLOG_minloglevel
class Model(object):
def __init__(self, model, labels=None, verbose=True, *args, **kwargs):
self.name = ALIASES[model]
self.nice_name = NICE_NAMES[model]
self.safename = self.name
self.labels = labels
self.args = args
self.kwargs = kwargs
self.verbose = verbose
def download_model(self, path=None):
"""Downloads and extracts a model
:Kwargs:
path (str, default: '')
Where model should be extracted
"""
self._setup()
if self.model.model_url is None:
print('Model {} is already available'.format(self.nice_name))
elif self.model.model_url == 'manual':
print('WARNING: Unfortunately, you need to download {} manually. '
'Follow the instructions in the documentation.'.format(self.nice_name))
else:
print('Downloading and extracting {}...'.format(self.nice_name))
if path is None:
path = os.getcwd()
text = raw_input('Where do you want the model to be extracted? '
'(default: {})\n'.format(path))
if text != '': path = text
outpath, _ = utils.extract_archive(self.model.model_url,
folder_name=self.safename, path=path)
if self.name == 'phog':
with open(os.path.join(outpath, 'anna_phog.m')) as f:
text = f.read()
with open(os.path.join(outpath, 'anna_phog.m'), 'wb') as f:
s = 'dlmwrite(s,p);'
f.write(text.replace(s, '% ' + s, 1))
print('Model {} is available here: {}'.format(self.nice_name, outpath))
print('If you want to use this model, either give this path when '
'calling the model or add it to your path '
'using {} as the environment variable.'.format(self.safename.upper()))
def _setup(self):
if not hasattr(self, 'model'):
if self.name in CAFFE_MODELS:
self.model = CAFFE_MODELS[self.name](model=self.name, *self.args, **self.kwargs)
else:
self.model = KNOWN_MODELS[self.name](*self.args, **self.kwargs)
self.model.labels = self.labels
self.isflat = self.model.isflat
self.model.verbose = self.verbose
def run(self, *args, **kwargs):
self._setup()
return self.model.run(*args, **kwargs)
def train(self, *args, **kwargs):
self._setup()
return self.model.train(*args, **kwargs)
def test(self, *args, **kwargs):
self._setup()
return self.model.test(*args, **kwargs)
def predict(self, *args, **kwargs):
self._setup()
return self.model.predict(*args, **kwargs)
def gen_report(self, *args, **kwargs):
self._setup()
return self.model.gen_report(*args, **kwargs)
class _Model(object):
def __init__(self, labels=None):
self.name = 'Model'
self.safename = 'model'
self.isflat = False
self.labels = labels
self.model_url = None
def gen_report(self, test_ims, train_ims=None, html=None):
print('input images:', test_ims)
print('processing:', end=' ')
if html is None:
html = report.Report(path=reppath)
html.open()
close_html = True
else:
close_html = False
resps = self.run(test_ims=test_ims, train_ims=train_ims)
html.writeh('Dissimilarity', h=1)
dis = dissimilarity(resps)
plot_data(dis, kind='dis')
html.writeimg('dis', caption='Dissimilarity across stimuli'
'(blue: similar, red: dissimilar)')
html.writeh('MDS', h=1)
mds_res = mds(dis)
plot_data(mds_res, kind='mds', icons=test_ims)
html.writeimg('mds', caption='Multidimensional scaling')
if self.labels is not None:
html.writeh('Linear separability', h=1)
lin = linear_clf(dis, y)
plot_data(lin, kind='linear_clf', chance=1./len(np.unique(self.labels)))
html.writeimg('lin', caption='Linear separability')
if close_html:
html.close()
def run(self, test_ims, train_ims=None, layers='output', return_dict=True):
"""
This is the main function to run the model.
:Args:
test_ims (str, list, tuple, np.ndarray)
Test images
:Kwargs:
- train_ims (str, list, tuple, np.ndarray)
Training images
- layers ('all'; 'output', 'top', None; str, int;
list of str or int; default: None)
Which layers to record and return. 'output', 'top' and None
return the output layer.
- return_dict (bool, default: True`)
Whether a dictionary should be returned. If False, only the last
layer is returned as an np.ndarray.
"""
if train_ims is not None:
self.train(train_ims)
output = self.test(test_ims, layers=layers, return_dict=return_dict)
return output
def train(self, train_ims):
"""
A placeholder for a function for training a model.
If the model is not trainable, then it will default to this function
here that does nothing.
"""
self.train_ims = im2iter(train_ims)
def test(self, test_ims, layers='output', return_dict=True):
"""
A placeholder for a function for testing a model.
:Args:
test_ims (str, list, tuple, np.ndarray)
Test images
:Kwargs:
- layers ('all'; 'output', 'top', None; str, int;
list of str or int; default: 'output')
Which layers to record and return. 'output', 'top' and None
return the output layer.
- return_dict (bool, default: True`)
Whether a dictionary should be returned. If False, only the last
layer is returned as an np.ndarray.
"""
self.layers = layers
# self.test_ims = im2iter(test_ims)
def predict(self, ims, topn=5):
"""
A placeholder for a function for predicting a label.
"""
pass
def _setup_layers(self, layers, model_keys):
if self.safename in CAFFE_MODELS:
filt_layers = self._filter_layers()
else:
filt_layers = model_keys
if layers in [None, 'top', 'output']:
self.layers = [filt_layers[-1]]
elif layers == 'all':
self.layers = filt_layers
elif isinstance(layers, (str, unicode)):
self.layers = [layers]
elif isinstance(layers, int):
self.layers = [filt_layers[layers]]
elif isinstance(layers, (list, tuple, np.ndarray)):
if isinstance(layers[0], int):
self.layers = [filt_layers[layer] for layer in layers]
elif isinstance(layers[0], (str, unicode)):
self.layers = layers
else:
raise ValueError('Layers can only be: None, "all", int or str, '
'list of int or str, got', layers)
else:
raise ValueError('Layers can only be: None, "all", int or str, '
'list of int or str, got', layers)
def _fmt_output(self, output, layers, return_dict=True):
self._setup_layers(layers, output.keys())
outputs = [output[layer] for layer in self.layers]
if not return_dict:
output = output[self.layers[-1]]
return output
def _im2iter(self, ims):
"""
Converts input into in iterable.
This is used to take arbitrary input value for images and convert them to
an iterable. If a string is passed, a list is returned with a single string
in it. If a list or an array of anything is passed, nothing is done.
Otherwise, if the input object does not have `len`, an Exception is thrown.
"""
if isinstance(ims, (str, unicode)):
out = [ims]
else:
try:
len(ims)
except:
raise ValueError('input image data type not recognized')
else:
try:
ndim = ims.ndim
except:
out = ims
else:
if ndim == 1: out = ims.tolist()
elif self.isflat:
if ndim == 2: out = [ims]
elif ndim == 3: out = ims
else:
raise ValueError('images must be 2D or 3D, got %d '
'dimensions instead' % ndim)
else:
if ndim == 3: out = [ims]
elif ndim == 4: out = ims
else:
raise ValueError('images must be 3D or 4D, got %d '
'dimensions instead' % ndim)
return out
def load_image(self, *args, **kwargs):
return utils.load_image(*args, **kwargs)
def dissimilarity(self, resps, kind='mean_euclidean', **kwargs):
return dissimilarity(resps, kind=kind, **kwargs)
def mds(self, dis, ims=None, ax=None, seed=None, kind='metric'):
return mds(dis, ims=ims, ax=ax, seed=seed, kind=kind)
def cluster(self, *args, **kwargs):
return cluster(*args, **kwargs)
def linear_clf(self, resps, y, clf=None):
return linear_clf(resps, y, clf=clf)
def plot_data(data, kind=None, **kwargs):
if kind in ['dis', 'dissimilarity']:
if isinstance(data, dict): data = data.values()[0]
g = sns.heatmap(data, **kwargs)
elif kind == 'mds':
g = plot.mdsplot(data, **kwargs)
elif kind in ['clust', 'cluster']:
g = sns.factorplot('layer', 'dissimilarity', data=df, kind='point')
elif kind in ['lin', 'linear_clf']:
g = sns.factorplot('layer', 'accuracy', data=df, kind='point')
if chance in kwargs:
ax.axhline(kwargs['chance'], ls='--', c='.2')
else:
try:
sns.factorplot(x='layers', y=data.columns[-1], data=data)
except:
raise ValueError('Plot kind "{}" not recognized.'.format(kind))
return g
def dissimilarity(resps, kind='mean_euclidean', **kwargs):
"""
Computes dissimilarity between all rows in a matrix.
:Args:
resps (numpy.array)
A NxM array of model responses. Each row contains an
output vector of length M from a model, and distances
are computed between each pair of rows.
:Kwargs:
- kind (str or callable, default: 'mean_euclidean')
Distance metric. Accepts string values or callables recognized
by :func:`~sklearn.metrics.pairwise.pairwise_distances`, and
also 'mean_euclidean' that normalizes
Euclidean distance by the number of features (that is,
divided by M), as used, e.g., by Grill-Spector et al.
(1999), Op de Beeck et al. (2001), Panis et | |
<reponame>jbrodman/SYCL-CTS<filename>tests/vector_operators/generate_vector_operators.py
#!/usr/bin/env python3
# ************************************************************************
#
# SYCL Conformance Test Suite
#
# Copyright: (c) 2018 by Codeplay Software LTD. All Rights Reserved.
#
# ************************************************************************
import sys
import argparse
from string import Template
sys.path.append('../common/')
from common_python_vec import (Data, ReverseData, wrap_with_kernel,
wrap_with_test_func, make_func_call,
write_source_file)
TEST_NAME = 'OPERATORS'
all_type_test_template = Template("""
/** Performs a test of each vector operator available to all types,
* on a given type, size, and two given values of that type
*/
auto testVec1 = cl::sycl::vec<${type}, ${size}>(static_cast<${type}>(${test_value_1}));
auto testVec1Copy = cl::sycl::vec<${type}, ${size}>(static_cast<${type}>(${test_value_1}));
auto testVec2 = cl::sycl::vec<${type}, ${size}>(static_cast<${type}>(${test_value_2}));
cl::sycl::vec<${type}, ${size}> resVec;
${type} resArr[${size}];
${type} resArr2[${size}];
// Arithmetic operators
for (int i = 0; i < ${size}; ++i) {
resArr[i] = static_cast<${type}>(${test_value_1}) + static_cast<${type}>(${test_value_2});
}
resVec = testVec1 + testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1 + testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1 + static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1.${swizzle} + testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1.${swizzle} + testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1.${swizzle} + static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = static_cast<${type}>(${test_value_1}) + testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = static_cast<${type}>(${test_value_1}) + testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
for (int i = 0; i < ${size}; ++i) {
resArr[i] = static_cast<${type}>(${test_value_1}) - static_cast<${type}>(${test_value_2});
}
resVec = testVec1 - testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1 - testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1 - static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1.${swizzle} - testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1.${swizzle} - testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1.${swizzle} - static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = static_cast<${type}>(${test_value_1}) - testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = static_cast<${type}>(${test_value_1}) - testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
for (int i = 0; i < ${size}; ++i) {
resArr[i] = static_cast<${type}>(${test_value_1}) * static_cast<${type}>(${test_value_2});
}
resVec = testVec1 * testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1 * testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1 * static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1.${swizzle} * testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1.${swizzle} * testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1.${swizzle} * static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = static_cast<${type}>(${test_value_1}) * testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = static_cast<${type}>(${test_value_1}) * testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
for (int i = 0; i < ${size}; ++i) {
resArr[i] = static_cast<${type}>(${test_value_1}) / static_cast<${type}>(${test_value_2});
}
resVec = testVec1 / testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1 / testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1 / static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1.${swizzle} / testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1.${swizzle} / testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1.${swizzle} / static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = static_cast<${type}>(${test_value_1}) / testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = static_cast<${type}>(${test_value_1}) / testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
// Post and pre increment and decrement
for (int i = 0; i < ${size}; ++i) {
resArr[i] = static_cast<${type}>(${test_value_1});
}
for (int i = 0; i < ${size}; ++i) {
resArr2[i] = static_cast<${type}>(${test_value_1}) + static_cast<${type}>(1);
}
testVec1Copy = testVec1;
resVec = testVec1Copy++;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
if (!check_vector_values(testVec1Copy, resArr2)) {
resAcc[0] = false;
}
testVec1Copy = testVec1;
resVec = testVec1Copy.${swizzle}++;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
if (!check_vector_values(testVec1Copy, resArr2)) {
resAcc[0] = false;
}
for (int i = 0; i < ${size}; ++i) {
resArr[i] = static_cast<${type}>(${test_value_1}) + static_cast<${type}>(1);
}
testVec1Copy = testVec1;
resVec = ++testVec1Copy;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
if (!check_vector_values(testVec1Copy, resArr)) {
resAcc[0] = false;
}
testVec1Copy = testVec1;
resVec = ++testVec1Copy.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
if (!check_vector_values(testVec1Copy, resArr)) {
resAcc[0] = false;
}
for (int i = 0; i < ${size}; ++i) {
resArr[i] = static_cast<${type}>(${test_value_1});
}
for (int i = 0; i < ${size}; ++i) {
resArr2[i] = static_cast<${type}>(${test_value_1}) - static_cast<${type}>(1);
}
testVec1Copy = testVec1;
resVec = testVec1Copy--;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
if (!check_vector_values(testVec1Copy, resArr2)) {
resAcc[0] = false;
}
testVec1Copy = testVec1;
resVec = testVec1Copy.${swizzle}--;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
if (!check_vector_values(testVec1Copy, resArr2)) {
resAcc[0] = false;
}
for (int i = 0; i < ${size}; ++i) {
resArr[i] = static_cast<${type}>(${test_value_1}) - static_cast<${type}>(1);
}
testVec1Copy = testVec1;
resVec = --testVec1Copy;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
if (!check_vector_values(testVec1Copy, resArr)) {
resAcc[0] = false;
}
testVec1Copy = testVec1;
resVec = --testVec1Copy.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
if (!check_vector_values(testVec1Copy, resArr)) {
resAcc[0] = false;
}
// Assignment operators
for (int i = 0; i < ${size}; ++i) {
resArr[i] = static_cast<${type}>(${test_value_1}) + static_cast<${type}>(${test_value_2});
}
resVec = testVec1;
resVec += testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec += testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec += static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec.${swizzle} += testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec.${swizzle} += testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec.${swizzle} += static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
for (int i = 0; i < ${size}; ++i) {
resArr[i] = static_cast<${type}>(${test_value_1}) - static_cast<${type}>(${test_value_2});
}
resVec = testVec1;
resVec -= testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec -= testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec -= static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec.${swizzle} -= testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec.${swizzle} -= testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec.${swizzle} -= static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
for (int i = 0; i < ${size}; ++i) {
resArr[i] = static_cast<${type}>(${test_value_1}) * static_cast<${type}>(${test_value_2});
}
resVec = testVec1;
resVec *= testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec *= testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec *= static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec.${swizzle} *= testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec.${swizzle} *= testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec.${swizzle} *= static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
for (int i = 0; i < ${size}; ++i) {
resArr[i] = static_cast<${type}>(${test_value_1}) / static_cast<${type}>(${test_value_2});
}
resVec = testVec1;
resVec /= testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec /= testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec /= static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec.${swizzle} /= testVec2;
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec.${swizzle} /= testVec2.${swizzle};
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
resVec = testVec1;
resVec.${swizzle} /= static_cast<${type}>(${test_value_2});
if (!check_vector_values(resVec, resArr)) {
resAcc[0] = false;
}
""")
specific_return_type_test_template = Template("""
/** Tests each logical and relational operator available to vector types
*/
auto testVec1 = cl::sycl::vec<${type}, ${size}>(static_cast<${type}>(${test_value_1}));
auto testVec2 = cl::sycl::vec<${type}, ${size}>(static_cast<${type}>(${test_value_2}));
cl::sycl::vec<${ret_type}, ${size}> resVec;
${ret_type} resArr[${size}];
// Logical operators
for (int i = 0; | |
<gh_stars>0
# coding: utf-8
import traceback
from .analyze import KlineAnalyze, is_bei_chi, get_ka_feature
def is_in_tolerance(base_price, latest_price, tolerance):
"""判断 latest_price 是否在 base_price 的买入容差范围(上下 tolerance)"""
if (1 - tolerance) * base_price <= latest_price <= (1 + tolerance) * base_price:
return True
else:
return False
def is_first_buy(ka, ka1, ka2=None, pf=False):
"""确定某一级别一买
注意:如果本级别上一级别的 ka 不存在,无法识别本级别一买,返回 `无操作` !!!
一买识别逻辑:
1)必须:上级别最后一个线段标记和最后一个笔标记重合且为底分型;
2)必须:上级别最后一个向下线段内部笔标记数量大于等于6,且本级别最后一个线段标记为底分型;
3)必须:本级别向下线段背驰 或 本级别向下笔背驰;
4)辅助:下级别向下线段背驰 或 下级别向下笔背驰。
:param ka: KlineAnalyze
本级别
:param ka1: KlineAnalyze
上级别
:param ka2: KlineAnalyze
下级别,默认为 None
:param pf: bool
pf 为 precision first 的缩写, 控制是否使用 `高精度优先模式` ,默认为 False ,即 `高召回优先模式`。
在 `高精度优先模式` 下,会充分利用辅助判断条件提高识别准确率。
:return: dict
"""
detail = {
"标的代码": ka.symbol,
"操作提示": "无操作",
"出现时间": None,
"基准价格": None,
"其他信息": None
}
if not isinstance(ka1, KlineAnalyze):
return detail
# 上级别最后一个线段标记和最后一个笔标记重合且为底分型;
if len(ka1.xd) >= 2 and ka1.xd[-1]['xd'] == ka1.bi[-1]['bi'] \
and ka1.xd[-1]['fx_mark'] == ka1.bi[-1]['fx_mark'] == 'd':
bi_inside = [x for x in ka1.bi if ka1.xd[-2]['dt'] <= x['dt'] <= ka1.xd[-1]['dt']]
# 上级别最后一个向下线段内部笔标记数量大于等于6,且本级别最后一个线段标记为底分型;
if len(bi_inside) >= 6 and ka.xd[-1]['fx_mark'] == 'd':
# 本级别向下线段背驰 或 本级别向下笔背驰;
if (ka.xd_bei_chi() or
(ka.bi[-1]['fx_mark'] == 'd' and ka.bi_bei_chi())):
detail['操作提示'] = "一买"
detail['出现时间'] = ka.xd[-1]['dt']
detail['基准价格'] = ka.xd[-1]['xd']
if pf and detail["操作提示"] == "一买" and isinstance(ka2, KlineAnalyze):
# 下级别线段背驰 或 下级别笔背驰
if not ((ka2.xd[-1]['fx_mark'] == 'd' and ka2.xd_bei_chi()) or
(ka2.bi[-1]['fx_mark'] == 'd' and ka2.bi_bei_chi())):
detail['操作提示'] = "无操作"
return detail
def is_first_sell(ka, ka1, ka2=None, pf=False):
"""确定某一级别一卖
注意:如果本级别上一级别的 ka 不存在,无法识别本级别一卖,返回 `无操作` !!!
一卖识别逻辑:
1)必须:上级别最后一个线段标记和最后一个笔标记重合且为顶分型;
2)必须:上级别最后一个向上线段内部笔标记数量大于等于6,且本级别最后一个线段标记为顶分型;
3)必须:本级别向上线段背驰 或 本级别向上笔背驰;
4)辅助:下级别向上线段背驰 或 下级别向上笔背驰。
:param ka: KlineAnalyze
本级别
:param ka1: KlineAnalyze
上级别
:param ka2: KlineAnalyze
下级别,默认为 None
:param pf: bool
pf 为 precision first 的缩写, 控制是否使用 `高精度优先模式` ,默认为 False ,即 `高召回优先模式`。
在 `高精度优先模式` 下,会充分利用辅助判断条件提高识别准确率。
:return: dict
"""
detail = {
"标的代码": ka.symbol,
"操作提示": "无操作",
"出现时间": None,
"基准价格": None,
"其他信息": None
}
if not isinstance(ka1, KlineAnalyze):
return detail
# 上级别最后一个线段标记和最后一个笔标记重合且为顶分型;
if len(ka1.xd) >= 2 and ka1.xd[-1]['xd'] == ka1.bi[-1]['bi'] \
and ka1.xd[-1]['fx_mark'] == ka1.bi[-1]['fx_mark'] == 'g':
bi_inside = [x for x in ka1.bi if ka1.xd[-2]['dt'] <= x['dt'] <= ka1.xd[-1]['dt']]
# 上级别最后一个向上线段内部笔标记数量大于等于6,且本级别最后一个线段标记为顶分型;
if len(bi_inside) >= 6 and ka.xd[-1]['fx_mark'] == 'g':
# 本级别向上线段背驰 或 本级别向上笔背驰
if (ka.xd_bei_chi() or
(ka.bi[-1]['fx_mark'] == 'g' and ka.bi_bei_chi())):
detail['操作提示'] = "一卖"
detail['出现时间'] = ka.xd[-1]['dt']
detail['基准价格'] = ka.xd[-1]['xd']
if pf and detail["操作提示"] == "一卖" and isinstance(ka2, KlineAnalyze):
# 下级别线段背驰 或 下级别笔背驰
if not ((ka2.xd[-1]['fx_mark'] == 'g' and ka2.xd_bei_chi()) or
(ka2.bi[-1]['fx_mark'] == 'g' and ka2.bi_bei_chi())):
detail['操作提示'] = "无操作"
return detail
def is_second_buy(ka, ka1, ka2=None, pf=False):
"""确定某一级别二买
注意:如果本级别上一级别的 ka 不存在,无法识别本级别二买,返回 `无操作` !!!
二买识别逻辑:
1)必须:上级别最后一个线段标记和最后一个笔标记都是底分型;
2)必须:上级别最后一个向下线段内部笔标记数量大于等于6,且本级别最后一个线段标记为底分型,不创新低;
3)必须:上级别最后一个线段标记后有且只有三个笔标记,且上级别向下笔不创新低;
4)辅助:下级别向下线段背驰 或 下级别向下笔背驰
:param ka: KlineAnalyze
本级别
:param ka1: KlineAnalyze
上级别
:param ka2: KlineAnalyze
下级别,默认为 None
:param pf: bool
pf 为 precision first 的缩写, 控制是否使用 `高精度优先模式` ,默认为 False ,即 `高召回优先模式`。
在 `高精度优先模式` 下,会充分利用辅助判断条件提高识别准确率。
:return: dict
"""
detail = {
"标的代码": ka.symbol,
"操作提示": "无操作",
"出现时间": None,
"基准价格": None,
"其他信息": None
}
if not isinstance(ka1, KlineAnalyze):
return detail
# 上级别最后一个线段标记和最后一个笔标记都是底分型;
if len(ka1.xd) >= 2 and ka1.xd[-1]['fx_mark'] == ka1.bi[-1]['fx_mark'] == 'd':
bi_inside = [x for x in ka1.bi if ka1.xd[-2]['dt'] <= x['dt'] <= ka1.xd[-1]['dt']]
# 上级别最后一个向上线段内部笔标记数量大于等于6,且本级别最后一个线段标记为底分型,不创新低;
if len(bi_inside) >= 6 and ka.xd[-1]['fx_mark'] == 'd' \
and ka.xd[-1]["xd"] > ka.xd[-3]['xd']:
# 上级别最后一个线段标记后有且只有三个笔标记,且上级别向下笔不创新低;
bi_next = [x for x in ka1.bi if x['dt'] >= ka1.xd[-1]['dt']]
if len(bi_next) == 3 and bi_next[-1]['fx_mark'] == 'd' \
and bi_next[-1]['bi'] > bi_next[-3]['bi']:
detail['操作提示'] = "二买"
detail['出现时间'] = ka.xd[-1]['dt']
detail['基准价格'] = ka.xd[-1]['xd']
if pf and detail["操作提示"] == "二买" and isinstance(ka2, KlineAnalyze):
# 下级别向下线段背驰 或 下级别向下笔背驰
if not ((ka2.xd[-1]['fx_mark'] == 'd' and ka2.xd_bei_chi()) or
(ka2.bi[-1]['fx_mark'] == 'd' and ka2.bi_bei_chi())):
detail['操作提示'] = "无操作"
return detail
def is_second_sell(ka, ka1, ka2=None, pf=False):
"""确定某一级别二卖,包括类二卖
注意:如果本级别上一级别的 ka 不存在,无法识别本级别一买,返回 `无操作` !!!
二卖识别逻辑:
1)必须:上级别最后一个线段标记和最后一个笔标记都是顶分型;
2)必须:上级别最后一个向上线段内部笔标记数量大于等于6,且本级别最后一个线段标记为顶分型,不创新高;
3)必须:上级别最后一个线段标记后有且只有三个笔标记,且上级别向上笔不创新低;
4)辅助:下级别向上线段背驰 或 下级别向上笔背驰
:param ka: KlineAnalyze
本级别
:param ka1: KlineAnalyze
上级别
:param ka2: KlineAnalyze
下级别,默认为 None
:param pf: bool
pf 为 precision first 的缩写, 控制是否使用 `高精度优先模式` ,默认为 False ,即 `高召回优先模式`。
在 `高精度优先模式` 下,会充分利用辅助判断条件提高识别准确率。
:return: dict
"""
detail = {
"标的代码": ka.symbol,
"操作提示": "无操作",
"出现时间": None,
"基准价格": None,
"其他信息": None
}
if not isinstance(ka1, KlineAnalyze):
return detail
# 上级别最后一个线段标记和最后一个笔标记都是顶分型
if len(ka1.xd) >= 2 and ka1.xd[-1]['fx_mark'] == ka1.bi[-1]['fx_mark'] == 'g':
bi_inside = [x for x in ka1.bi if ka1.xd[-2]['dt'] <= x['dt'] <= ka1.xd[-1]['dt']]
# 上级别最后一个向上线段内部笔标记数量大于等于6,且本级别最后一个线段标记为顶分型,不创新高
if len(bi_inside) >= 6 and ka.xd[-1]['fx_mark'] == 'g' \
and ka.xd[-1]["xd"] < ka.xd[-3]['xd']:
# 上级别最后一个线段标记后有且只有三个笔标记,且上级别向上笔不创新低
bi_next = [x for x in ka1.bi if x['dt'] >= ka1.xd[-1]['dt']]
if len(bi_next) == 3 and bi_next[-1]['fx_mark'] == 'g' \
and bi_next[-1]['bi'] < bi_next[-3]['bi']:
detail['操作提示'] = "二卖"
detail['出现时间'] = ka.xd[-1]['dt']
detail['基准价格'] = ka.xd[-1]['xd']
if pf and detail["操作提示"] == "二卖" and isinstance(ka2, KlineAnalyze):
# 下级别向上线段背驰 或 下级别向上笔背驰
if not ((ka2.xd[-1]['fx_mark'] == 'g' and ka2.xd_bei_chi()) or
(ka2.bi[-1]['fx_mark'] == 'g' and ka2.bi_bei_chi())):
detail['操作提示'] = "无操作"
return detail
def is_third_buy(ka, ka1=None, ka2=None, pf=False):
"""确定某一级别三买
第三类买点: 一个第三类买点,至少需要有5段次级别的走势,前三段构成中枢,第四段离开中枢,第5段不跌回中枢。
三买识别逻辑:
1)必须:本级别有6个以上线段标记,且最后一个线段标记为底分型;
2)必须:前三段有价格重叠部分,构成中枢;
2)必须:第4段比第2段新高无背驰,第5段不跌回中枢;
4)辅助:向上中枢数量小于等于3
:param ka: KlineAnalyze
本级别
:param ka1: KlineAnalyze
上级别
:param ka2: KlineAnalyze
下级别,默认为 None
:param pf: bool
pf 为 precision first 的缩写, 控制是否使用 `高精度优先模式` ,默认为 False ,即 `高召回优先模式`。
在 `高精度优先模式` 下,会充分利用辅助判断条件提高识别准确率。
:return: dict
"""
detail = {
"标的代码": ka.symbol,
"操作提示": "无操作",
"出现时间": None,
"基准价格": None,
"其他信息": None
}
# 本级别有6个以上线段标记,且最后一个线段标记为底分型;
if len(ka.xd) >= 6 and ka.xd[-1]['fx_mark'] == 'd':
# 前三段有价格重叠部分,构成中枢;
zs_g = min([x['xd'] for x in ka.xd[-6:-2] if x['fx_mark'] == "g"])
zs_d = max([x['xd'] for x in ka.xd[-6:-2] if x['fx_mark'] == "d"])
if zs_g > zs_d:
# 第4段比第2段有新高或新低,且无背驰,第5段不跌回中枢;
direction = 'up'
zs1 = {"start_dt": ka.xd[-3]['dt'], "end_dt": ka.xd[-2]['dt'], "direction": direction}
zs2 = {"start_dt": ka.xd[-5]['dt'], "end_dt": ka.xd[-4]['dt'], "direction": direction}
if ka.xd[-2]['xd'] > ka.xd[-4]['xd'] \
and not is_bei_chi(ka, zs1, zs2, mode='xd') \
and ka.xd[-1]['xd'] > zs_g:
detail['操作提示'] = '三买'
detail['出现时间'] = ka.xd[-1]['dt']
detail['基准价格'] = ka.xd[-1]['xd']
if pf and detail['操作提示'] == '三买':
# 向上中枢数量小于等于3
un = ka.up_zs_number()
if un > 3:
detail['操作提示'] = '无操作'
if isinstance(ka1, KlineAnalyze):
pass
if isinstance(ka2, KlineAnalyze):
pass
return detail
def is_third_sell(ka, ka1=None, ka2=None, pf=False):
"""确定某一级别三卖
第三类卖点: 一个第三类卖点,至少需要有5段次级别的走势,前三段构成中枢,第四段离开中枢,第5段不升破中枢的低点。
三卖识别逻辑:
1)必须:本级别有6个以上线段标记,且最后一个线段标记为顶分型;
2)必须:前三段有价格重叠部分,构成中枢;
2)必须:第4段比第2段新低无背驰,第5段不升回中枢;
4)辅助:向下中枢数量小于等于3
:param ka: KlineAnalyze
本级别
:param ka1: KlineAnalyze
上级别
:param ka2: KlineAnalyze
下级别,默认为 None
:param pf: bool
pf 为 precision first 的缩写, 控制是否使用 `高精度优先模式` ,默认为 False ,即 `高召回优先模式`。
在 `高精度优先模式` 下,会充分利用辅助判断条件提高识别准确率。
:return: dict
"""
detail = {
"标的代码": ka.symbol,
"操作提示": "无操作",
"出现时间": None,
"基准价格": None,
"其他信息": None
}
# 本级别有6个以上线段标记,且最后一个线段标记为顶分型;
if len(ka.xd) >= 6 and ka.xd[-1]['fx_mark'] == 'g':
# 前三段有价格重叠部分,构成中枢;
zs_g = min([x['xd'] for x in ka.xd[-6:-2] if x['fx_mark'] == "g"])
zs_d = max([x['xd'] for x in ka.xd[-6:-2] if x['fx_mark'] == "d"])
if zs_g > zs_d:
# 第4段比第2段新低无背驰,第5段不升回中枢;
direction = 'down'
zs1 = {"start_dt": ka.xd[-3]['dt'], "end_dt": ka.xd[-2]['dt'], "direction": direction}
zs2 = {"start_dt": ka.xd[-5]['dt'], "end_dt": ka.xd[-4]['dt'], "direction": direction}
if ka.xd[-2]['xd'] < ka.xd[-4]['xd'] \
and not is_bei_chi(ka, zs1, zs2, mode='xd') \
and ka.xd[-1]['xd'] > zs_g:
detail['操作提示'] = '三卖'
detail['出现时间'] = ka.xd[-1]['dt']
detail['基准价格'] = ka.xd[-1]['xd']
if pf and detail['操作提示'] == '三卖':
# 向下中枢数量小于等于3
dn = ka.down_zs_number()
if dn > 3:
detail['操作提示'] = '无操作'
if isinstance(ka1, KlineAnalyze):
pass
if isinstance(ka2, KlineAnalyze):
pass
return detail
def is_xd_buy(ka, ka1=None, ka2=None, pf=False):
"""同级别分解买点,我称之为线买,即线段买点
线买识别逻辑:
1) 必须:本级别至少有 3 个线段标记且最后一个线段标记为底分型;
2) 必须:本级别向下线段背驰 或 本级别向下线段不创新低;
3) 辅助:上级别向下笔背驰 或 上级别向下笔不创新低
4) 辅助:下级别向下笔背驰
:param ka: KlineAnalyze
本级别
:param ka1: KlineAnalyze
上级别
:param ka2: KlineAnalyze
下级别,默认为 None
:param pf: bool
pf 为 precision first 的缩写, 控制是否使用 `高精度优先模式` ,默认为 False ,即 `高召回优先模式`。
在 `高精度优先模式` 下,会充分利用辅助判断条件提高识别准确率。
:return: dict
"""
detail = {
"标的代码": ka.symbol,
"操作提示": "无操作",
"出现时间": None,
"基准价格": None,
"其他信息": None
}
# 本级别至少有 3 个线段标记且最后一个线段标记为底分型;
if len(ka.xd) > 3 and ka.xd[-1]['fx_mark'] == 'd':
# 本级别向下线段背驰 或 本级别向下线段不创新低;
if ka.xd_bei_chi() or ka.xd[-1]['xd'] > ka.xd[-3]['xd']:
detail['操作提示'] = "线买"
detail['出现时间'] = ka.xd[-1]['dt']
detail['基准价格'] = ka.xd[-1]['xd']
if pf and detail['操作提示'] == "线买":
if isinstance(ka1, KlineAnalyze):
# 上级别向下笔背驰 或 上级别向下笔不创新低
if not (ka1.bi[-1]['fx_mark'] == 'd' and
(ka1.bi[-1]['bi'] > ka1.bi[-3]['bi'] or ka1.bi_bei_chi())):
detail['操作提示'] = "无操作"
if isinstance(ka2, KlineAnalyze):
# 下级别向下笔背驰
if not (ka2.bi[-1]['fx_mark'] == 'd' and ka2.bi_bei_chi()):
detail['操作提示'] = "无操作"
return detail
def is_xd_sell(ka, ka1=None, ka2=None, pf=False):
"""同级别分解卖点,我称之为线卖,即线段卖点
线卖识别逻辑:
1) 必须:本级别至少有 3 个线段标记且最后一个线段标记为顶分型;
2) 必须:本级别向上线段背驰 或 本级别向上线段不创新高;
3) 辅助:上级别向上笔背驰 或 上级别向上笔不创新高
4) 辅助:下级别向上笔背驰
:param ka: KlineAnalyze
本级别
:param ka1: KlineAnalyze
上级别
:param ka2: KlineAnalyze
下级别,默认为 None
:param pf: bool
pf 为 precision first 的缩写, 控制是否使用 `高精度优先模式` ,默认为 False ,即 `高召回优先模式`。
在 `高精度优先模式` 下,会充分利用辅助判断条件提高识别准确率。
:return: dict
"""
detail = {
"标的代码": ka.symbol,
"操作提示": "无操作",
"出现时间": None,
"基准价格": None,
"其他信息": None
}
# 本级别至少有 3 个线段标记且最后一个线段标记为顶分型;
if len(ka.xd) > 3 and ka.xd[-1]['fx_mark'] == 'g':
| |
"""
MyView all views saved here
"""
# flake8: noqa:E501
# pylint: disable=import-error
# pylint: disable=invalid-name
# pylint: disable=protected-access
# pylint: disable=no-else-return
# pylint: disable=broad-except
# pylint: disable=using-constant-test
# pylint: disable=too-many-arguments
# pylint: disable=too-many-locals
import os
from html import escape
from typing import Optional
from tempfile import NamedTemporaryFile
from fastapi import FastAPI, Request, Depends, Response, status
from fastapi import HTTPException, File, UploadFile, Form
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from sqlalchemy.orm import Session
from jwt.jwt_utils import get_current_user_optional, create_access_token
from crud import crud
from models import models
from schemas import schemas
from media import s3_utils
from db.database import get_db, engine
from utils import utils
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:8080",
]
# static files directory for javascript and css
app.mount("/static", StaticFiles(directory="static"), name="static")
# html templates directory
templates = Jinja2Templates(directory="templates")
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
models.Base.metadata.create_all(bind=engine)
# url to get tokens from
JWT_SECRET = os.environ.get("JWT_SECRET")
JWT_ALGO = os.environ.get("JWT_ALGO")
@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
"""
Function to create a user
First check if user exists.
Args:
- user: schemas.UserCreate
- db: Session
Returns:
- db_user
Raises:
- HTTPException if email already registered
"""
db_user = crud.get_user_by_email(db, email=user.email)
# check if email already exists
if db_user:
raise HTTPException(status_code=400, detail="Email already registered")
return crud.create_user(db=db, user=user)
@app.get("/users/{user_id}", response_model=schemas.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
"""
Function to read user table.
Check if user exists.
Raise error if not found
Args:
- user_id: int
- db: Session
Returns:
- user
Raises:
- HTTPException if user not found
"""
db_user = crud.get_user(db, user_id=user_id)
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")
return db_user
@app.get("/", response_class=HTMLResponse)
async def home(
request: Request,
active_user: Optional[schemas.UserBase] = Depends(get_current_user_optional),
db: Session = Depends(get_db),
):
"""
HomePage
Args:
- request: Request
- active_user: Optional[schemas.User] = Depends(get_current_user)
Returns:
- index.html
- Optional: active_user
"""
# Get top videos
# query top videos by views
# sanitize active_user
if active_user:
active_user = utils.sanitize_active_user(active_user)
top_videos = crud.get_top_videos(db)
thumbnail_drive = os.environ.get("thumbnail_drive")
cloud_url = os.environ.get("cloud_url")
thumbnail_url = f"{cloud_url}/{thumbnail_drive}"
profile_folder = os.environ.get("profile_folder")
profile_picture_url = f"{cloud_url}/{profile_folder}"
request = utils.sanitize_request(request)
def get_profile(username):
"""
Function to get
bool of profile_picture of
User
"""
return (
db.query(models.User)
.filter(models.User.username == username)
.first()
.profile_picture
)
context = {
"request": request,
"active_user": active_user,
"videos": top_videos,
"thumbnail_url": thumbnail_url,
"profile_picture_url": profile_picture_url,
"get_profile": get_profile,
}
return templates.TemplateResponse(
"index.html",
context=context,
)
@app.get("/video/{video_link}")
def read_video(
request: Request,
video_link: str,
db: Session = Depends(get_db),
active_user: Optional[schemas.User] = Depends(get_current_user_optional),
):
"""
Serves Video link
Increments view by 1
Args:
-request: Request,
- video_link: str,
- db: Session = Depends(get_db),
- active_user: Optional[schemas.User] = Depends(get_current_user_optional),
Returns:
- video.html template with context
"""
# sanitize
if active_user:
active_user.username = escape(active_user.username)
video = crud.get_video_link(db, video_link)
cloud_url = os.environ.get("cloud_url")
folder_name = os.environ.get("folder_name")
video_url = f"{cloud_url}/{folder_name}"
crud.increase_view(db, video.video_id, active_user)
# get all comments
comments = crud.get_comments(db, video_id=video.video_id)
# get username
def get_username(user_id):
return crud.get_username(db, user_id)
# get profile picture
def get_profile(username):
"""
Function to get
bool of profile_picture of
User
"""
return (
db.query(models.User)
.filter(models.User.username == username)
.first()
.profile_picture
)
return templates.TemplateResponse(
"video.html",
context={
"request": request,
"video_url": video_url,
"active_user": active_user,
"video": video,
"video_link": video_link,
"comments": comments,
"get_profile": get_profile,
"get_username": get_username,
},
)
@app.get("/upload", response_class=HTMLResponse)
async def upload_page(
request: Request, active_user: schemas.User = Depends(get_current_user_optional)
):
"""
Upload page
"""
# if user is not logged in
if not active_user:
# url for login
url = app.url_path_for("login")
# return url
response = RedirectResponse(url=url)
# set found status code
response.status_code = status.HTTP_302_FOUND
return response
# sanitize active_user
active_user = utils.sanitize_active_user(active_user)
return templates.TemplateResponse(
"upload.html", context={"request": request, "active_user": active_user}
)
@app.post("/upload_file", dependencies=[Depends(utils.valid_content_length)])
async def upload_file(
# pylint: disable=too-many-arguments
# pylint: disable=too-many-locals
video_file: UploadFile = File(...),
videoName: str = Form(...),
videoLength: str = Form(...),
videoHeight: int = Form(...),
videoWidth: int = Form(...),
# pylint: disable=unused-argument
thumbnail: UploadFile = File(...),
db: Session = Depends(get_db),
active_user: schemas.User = Depends(get_current_user_optional),
videoDescription: Optional[str] = Form(None),
videoCategories: Optional[str] = Form(None),
):
"""
Upload file to s3
Only accepts video file types.
Limit file uploads to 100 mb
Args:
- video_file: UploadFile
Returns:
- Status 200 if success, else 304 invalid type
"""
# sanitize input
videoName = escape(videoName)
videoLength = escape(videoLength)
if videoDescription:
videoDescription = escape(videoDescription)
if videoCategories:
videoCategories = escape(videoCategories)
file_size = 10_00_00_000
real_file_size = 0
# pylint: disable="consider-using-with"
temp = NamedTemporaryFile()
# check file size
for chunk in video_file.file:
real_file_size += len(chunk)
if real_file_size > file_size:
raise HTTPException(
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, detail="Too large"
)
temp.write(chunk)
temp.close()
# pylint: disable=too-many-locals
if video_file.content_type in ["video/mp4", "video/x-m4v", "video/mpeg4"]:
# upload to s3
try:
# upload video
# bring the file reader to start position
await video_file.seek(0)
# convert to bytes
data = video_file.file
# get filename
filename = video_file.filename
file_format = video_file.content_type
# extract extension from file
bucket = os.environ.get("bucket_name")
new_video_name = utils.create_video_name(filename)
folder_name = os.environ.get("folder_name")
destination = f"{folder_name}/{new_video_name}"
s3_utils.upload_file(data, bucket, destination)
# upload thumbnail
thumbnail_drive = os.environ.get("thumbnail_drive")
thumbnail_data = thumbnail.file._file
thumbnail.filename = new_video_name
thumbnail_destination = f"{thumbnail_drive}/{thumbnail.filename}"
s3_utils.upload_file(thumbnail_data, bucket, thumbnail_destination)
except Exception as e:
print(f"Could not upload {filename}: {e}")
return {"status": 124}
# add entry to database
try:
# create instance of video schemas
# add parameters
username = active_user.username
video = schemas.Video(
video_username=username,
video_link=new_video_name,
video_name=videoName,
video_height=videoHeight,
video_width=videoWidth,
file_format=file_format,
categories=videoCategories,
description=videoDescription,
length=videoLength,
)
# pass it to crud function
crud.add_video(db, video)
except Exception as e:
print(f"Could not make entry {filename}: {e}")
return {"status": 125}
# url for homepage
url = app.url_path_for("home")
response = RedirectResponse(url=url)
# set found status code
response.status_code = status.HTTP_302_FOUND
return response
else:
return {"Invalid file type": 304}
@app.get("/login", response_class=HTMLResponse)
async def login_page(request: Request):
"""
Login Page
"""
return templates.TemplateResponse("login.html", {"request": request})
@app.post("/login")
async def login(
request: Request,
response: Response,
db: Session = Depends(get_db),
email: str = Form(...),
password: str = Form(...),
):
"""
Login Page Post
Logs user in and creates cookie
Args:
- request: Request,
- response: Response,
- db: Session = Depends(get_db),
- email: str = Form(...),
- password: str = Form(...),
Returns:
- index.html: if user credentials are valid
- login.html: if user credentials are invalid
"""
# check if user is present
user_status = crud.authenticate_user_email(db, email=email, password=password)
# if username and password matches redirect to homepage
if user_status:
# create access token
token = await create_access_token(data={"sub": email})
# url for homepage
url = app.url_path_for("home")
# return url
response = RedirectResponse(url=url)
# set found status code
response.status_code = status.HTTP_302_FOUND
response.set_cookie("session", token)
return response
# else provide error message
else:
login_context = {
"request": request,
"message": "Email or Password is incorrect",
"tag": "warning",
}
return templates.TemplateResponse("login.html", context=login_context)
@app.get("/register", response_class=HTMLResponse)
async def register_page(request: Request):
"""
Register page
"""
return templates.TemplateResponse("register.html", {"request": request})
@app.post("/register")
async def register(
request: Request,
username: str = Form(...),
password: str = Form(...),
profile_picture: UploadFile = File(None),
email: str = Form(...),
db: Session = Depends(get_db),
):
"""
Regiser Post Page
Args:
- request: Request
- username: str = Form(...)
- password: str = Form(...)
- profile_picture: UploadFile = File(None)
- email: str = Form(...)
- db: Session = Depends(get_db)
Returns:
- register.html: if name already in use
- login.html: if successly registered
"""
# sanitize input
username = escape(username)
password = escape(password)
email = escape(email)
profile_bool = False
# if profile picture is present then upload
if profile_picture and profile_picture.content_type in [
"image/jpeg",
"image/jpg",
"image/png",
]:
bucket = os.environ.get("bucket_name")
profile_folder = os.environ.get("profile_folder")
profile_pic = profile_picture.file._file
new_profile_name = username
destination = f"{profile_folder}/{new_profile_name}"
s3_utils.upload_file(profile_pic, bucket, destination)
profile_bool = True
# otherwise none
# get the details
user = schemas.UserCreate(
username=username, email=email, password=password, profile_picture=profile_bool
)
# first check if user exists
# #if user exists return error
username_check = (
db.query(models.User).filter(models.User.username == user.username).first()
)
email_check = db.query(models.User).filter(models.User.email == user.email).first()
if username_check or email_check:
error_context = {
"request": request,
"message": "Email or Username already in use",
"tag": "warning",
}
return templates.TemplateResponse("register.html", context=error_context)
# create the schema to carry it
# create user
create_user(db=db, user=user)
success_context = {
"request": request,
"message": "Successfully registered",
"tag": "success",
}
return templates.TemplateResponse("login.html", context=success_context)
@app.get("/logout")
def logout(response: Response, request: Request):
"""
Logs user out of session.
Deletes cookie
Args:
- response: Response
- request: Request
Returns:
- response - index.html and delete cookie session
"""
success_context = {
"request": request,
"message": "Successfully Logged Out",
"tag": "success",
}
response = templates.TemplateResponse("index.html", context=success_context)
response.delete_cookie("session")
return response
@app.get("/search")
def search_video(request: Request, search_query: str, db: Session = Depends(get_db)):
"""
Search Video
| |
""" Contains upsampling and resize layers """
import numpy as np
import tensorflow.compat.v1 as tf
from .layer import Layer, add_as_function
from .conv import ConvTranspose
from .core import Xip
from ..utils import get_shape, get_num_channels, get_spatial_shape
class IncreaseDim(Layer):
""" Increase dimensionality of passed tensor by desired amount.
Used for `>` letter in layout convention of :class:`~.tf.layers.ConvBlock`.
"""
def __init__(self, dim=1, insert=True, name='increase_dim', **kwargs):
self.dim, self.insert = dim, insert
self.name, self.kwargs = name, kwargs
def __call__(self, inputs):
with tf.variable_scope(self.name):
shape = get_shape(inputs)
ones = [1] * self.dim
if self.insert:
return tf.reshape(inputs, (-1, *ones, *shape))
return tf.reshape(inputs, (-1, *shape, *ones))
class Reshape(Layer):
""" Enforce desired shape of tensor.
Used for `r` letter in layout convention of :class:`~.tf.layers.ConvBlock`.
"""
def __init__(self, reshape_to=None, name='reshape', **kwargs):
self.reshape_to = reshape_to
self.name, self.kwargs = name, kwargs
def __call__(self, inputs):
with tf.variable_scope(self.name):
return tf.reshape(inputs, (-1, *self.reshape_to))
class Crop:
""" Crop input tensor to a shape of a given image.
If resize_to does not have a fully defined shape (resize_to.get_shape() has at least one None),
the returned tf.Tensor will be of unknown shape except the number of channels.
Parameters
----------
inputs : tf.Tensor
Input tensor.
resize_to : tf.Tensor
Tensor which shape the inputs should be resized to.
data_format : str {'channels_last', 'channels_first'}
Data format.
"""
def __init__(self, resize_to, data_format='channels_last', name='crop'):
self.resize_to = resize_to
self.data_format, self.name = data_format, name
def __call__(self, inputs):
with tf.variable_scope(self.name):
static_shape = get_spatial_shape(self.resize_to, self.data_format, False)
dynamic_shape = get_spatial_shape(self.resize_to, self.data_format, True)
if None in get_shape(inputs) + static_shape:
return self._dynamic_crop(inputs, static_shape, dynamic_shape, self.data_format)
return self._static_crop(inputs, static_shape, self.data_format)
def _static_crop(self, inputs, shape, data_format='channels_last'):
input_shape = np.array(get_spatial_shape(inputs, data_format))
if np.abs(input_shape - shape).sum() > 0:
begin = [0] * inputs.shape.ndims
if data_format == "channels_last":
size = [-1] + shape + [-1]
else:
size = [-1, -1] + shape
x = tf.slice(inputs, begin=begin, size=size)
else:
x = inputs
return x
def _dynamic_crop(self, inputs, static_shape, dynamic_shape, data_format='channels_last'):
input_shape = get_spatial_shape(inputs, data_format, True)
n_channels = get_num_channels(inputs, data_format)
if data_format == 'channels_last':
slice_size = [(-1,), dynamic_shape, (n_channels,)]
output_shape = [None] * (len(static_shape) + 1) + [n_channels]
else:
slice_size = [(-1, n_channels), dynamic_shape]
output_shape = [None, n_channels] + [None] * len(static_shape)
begin = [0] * len(inputs.get_shape().as_list())
size = tf.concat(slice_size, axis=0)
cond = tf.reduce_sum(tf.abs(input_shape - dynamic_shape)) > 0
x = tf.cond(cond, lambda: tf.slice(inputs, begin=begin, size=size), lambda: inputs)
x.set_shape(output_shape)
return x
def _calc_size(inputs, factor, data_format):
shape = inputs.get_shape().as_list()
channels = shape[-1] if data_format == 'channels_last' else shape[1]
if None in shape[1:]:
shape = _dynamic_calc_shape(inputs, factor, data_format)
else:
shape = _static_calc_shape(inputs, factor, data_format)
return shape, channels
def _static_calc_shape(inputs, factor, data_format):
shape = inputs.get_shape().as_list()
shape = shape[1:-1] if data_format == 'channels_last' else shape[2:]
shape = np.asarray(shape) * np.asarray(factor)
shape = list(np.ceil(shape).astype(np.int32))
return shape
def _dynamic_calc_shape(inputs, factor, data_format):
shape = tf.cast(tf.shape(inputs), dtype=tf.float32)
shape = shape[1:-1] if data_format == 'channels_last' else shape[2:]
shape = shape * np.asarray(factor)
shape = tf.cast(tf.ceil(shape), dtype=tf.int32)
return shape
class DepthToSpace(Layer):
""" 1d, 2d and 3d depth_to_space transformation.
Parameters
----------
block_size : int
An int that is >= 2. The size of the spatial block.
name : str
Scope name.
data_format : {'channels_last', 'channels_first'}
Position of the channels dimension.
See also
--------
`tf.depth_to_space <https://www.tensorflow.org/api_docs/python/tf/depth_to_space>`_
"""
def __init__(self, block_size, data_format='channels_last', **kwargs):
self.block_size, self.data_format = block_size, data_format
self.kwargs = kwargs
def __call__(self, inputs):
return depth_to_space(inputs, **self.params_dict, **self.kwargs)
def depth_to_space(inputs, block_size, data_format='channels_last', name='d2s'):
""" 1d, 2d and 3d depth_to_space transformation. """
dim = inputs.shape.ndims - 2
if dim == 2:
dafo = 'NHWC' if data_format == 'channels_last' else 'NCHW'
return tf.depth_to_space(inputs, block_size, name, data_format=dafo)
if data_format == 'channels_first':
inputs = tf.transpose(inputs, [0] + list(range(2, dim+2)) + [1])
x = _depth_to_space(inputs, block_size, name)
if data_format == 'channels_first':
x = tf.transpose(x, [0, dim+1] + list(range(1, dim+1)))
return x
def _depth_to_space(inputs, block_size, name='d2s'):
dim = inputs.shape.ndims - 2
with tf.variable_scope(name):
shape = inputs.get_shape().as_list()[1:]
channels = shape[-1]
if channels % (block_size ** dim) != 0:
raise ValueError('channels of the inputs must be divisible by block_size ** {}'.format(dim))
output_shape = tf.concat([(tf.shape(inputs)[0],), tf.shape(inputs)[1:-1]*block_size,
(tf.shape(inputs)[-1], )], axis=-1)
slices = [np.arange(0, channels // (block_size ** dim)) + i
for i in range(0, channels, channels // (block_size ** dim))]
tensors = []
for i in range(block_size ** dim):
zero_filter = np.zeros(block_size ** dim)
selective_filter = np.zeros(block_size ** dim)
selective_filter[i] = 1
zero_filter = zero_filter.reshape([block_size] * dim)
selective_filter = selective_filter.reshape([block_size] * dim)
fltr = []
for j in range(channels):
_filter = [zero_filter] * channels
_filter[j] = selective_filter
_filter = np.stack(_filter, axis=-1)
fltr.append(_filter)
fltr = np.stack(fltr, axis=-1)
fltr = np.transpose(fltr, axes=list(range(dim))+[dim, dim+1])
fltr = tf.constant(fltr, tf.float32)
x = ConvTranspose(fltr, output_shape, [1] + [block_size] * dim + [1])(inputs)
if None in shape[:-1]:
resized_shape = shape[:-1]
else:
resized_shape = list(np.array(shape[:-1]) * block_size)
x.set_shape([None] + resized_shape + [channels/(block_size ** dim)])
x = tf.gather(x, slices[i], axis=-1)
tensors.append(x)
x = tf.add_n(tensors)
return x
class UpsamplingLayer(Layer):
""" Parent for all the upsampling layers with the same parameters. """
def __init__(self, factor=2, shape=None, data_format='channels_last', name='upsampling', **kwargs):
self.factor, self.shape = factor, shape
self.data_format = data_format
self.name, self.kwargs = name, kwargs
class SubpixelConv(UpsamplingLayer):
""" Resize input tensor with subpixel convolution (depth to space operation).
Used for `X` letter in layout convention of :class:`~.tf.layers.ConvBlock`.
Parameters
----------
factor : int
Upsampling factor.
layout : str
Layers applied before depth-to-space transform.
name : str
Scope name.
data_format : {'channels_last', 'channels_first'}
Position of the channels dimension.
"""
def __call__(self, inputs):
return subpixel_conv(inputs, **self.params_dict, **self.kwargs)
def subpixel_conv(inputs, factor=2, name='subpixel', data_format='channels_last', **kwargs):
""" Resize input tensor with subpixel convolution (depth to space operation. """
dim = inputs.shape.ndims - 2
_, channels = _calc_size(inputs, factor, data_format)
layout = kwargs.pop('layout', 'cna')
kwargs['filters'] = channels*factor**dim
x = inputs
with tf.variable_scope(name):
if layout:
from .conv_block import ConvBlock # can't be imported in the file beginning due to recursive imports
x = ConvBlock(layout=layout, kernel_size=1, name='conv', data_format=data_format, **kwargs)(inputs)
x = depth_to_space(x, block_size=factor, name='d2s', data_format=data_format)
return x
class ResizeBilinearAdditive(UpsamplingLayer):
""" Resize input tensor with bilinear additive technique.
Used for `A` letter in layout convention of :class:`~.tf.layers.ConvBlock`.
Parameters
----------
factor : int
Upsampling factor.
layout : str
Layers applied between bilinear resize and xip.
name : str
Scope name.
data_format : {'channels_last', 'channels_first'}
Position of the channels dimension.
"""
def __call__(self, inputs):
return resize_bilinear_additive(inputs, **self.params_dict, **self.kwargs)
def resize_bilinear_additive(inputs, factor=2, name='bilinear_additive', data_format='channels_last', **kwargs):
""" Resize input tensor with bilinear additive technique. """
dim = inputs.shape.ndims - 2
_, channels = _calc_size(inputs, factor, data_format)
layout = kwargs.pop('layout', 'cna')
with tf.variable_scope(name):
from .conv_block import ConvBlock # can't be imported in the file beginning due to recursive imports
x = resize_bilinear(inputs, factor, name=name, data_format=data_format, **kwargs)
x = ConvBlock(layout=layout, filters=channels*factor**dim, kernel_size=1, name='conv', **kwargs)(x)
x = Xip(depth=factor**dim, reduction='sum', name='addition')(x)
return x
def resize_bilinear_1d(inputs, size, name='resize', **kwargs):
""" Resize 1D input tensor with bilinear method.
Parameters
----------
inputs : tf.Tensor
a tensor to resize.
size : tf.Tensor or list
size of the output image.
name : str
scope name.
Returns
-------
tf.Tensor
"""
x = tf.expand_dims(inputs, axis=1)
size = tf.concat([[1], size], axis=-1)
x = tf.image.resize_bilinear(x, size=size, name=name, **kwargs)
x = tf.squeeze(x, [1])
return x
def resize_bilinear_3d(tensor, size, name='resize', **kwargs):
""" Resize 3D input tensor with bilinear method.
Parameters
----------
inputs : tf.Tensor
a tensor to resize.
size : tf.Tensor or list
size of the output image.
name : str
scope name.
Returns
-------
tf.Tensor
"""
with tf.variable_scope(name):
tensor = _resize_along_axis(tensor, size, 2, **kwargs)
tensor = _resize_except_axis(tensor, size, 2, **kwargs)
return tensor
def _resize_along_axis(inputs, size, axis, **kwargs):
""" Resize 3D input tensor to size along just one axis. """
except_axis = (axis + 1) % 3
size, _ = _calc_size_after_resize(inputs, size, axis)
output = _resize_except_axis(inputs, size, except_axis, **kwargs)
return output
def _resize_except_axis(inputs, size, axis, **kwargs):
""" Resize 3D input tensor to size except just one axis. """
perm = np.arange(5)
reverse_perm = np.arange(5)
if axis == 0:
spatial_perm = [2, 3, 1]
reverse_spatial_perm = [3, 1, 2]
elif axis == 1:
spatial_perm = [1, 3, 2]
reverse_spatial_perm = [1, 3, 2]
else:
spatial_perm = [1, 2, 3]
reverse_spatial_perm = [1, 2, 3]
perm[1:4] = spatial_perm
reverse_perm[1:4] = reverse_spatial_perm
x = tf.transpose(inputs, perm)
if isinstance(size, tf.Tensor):
size = tf.unstack(size)
size = [size[i-1] for i in spatial_perm]
size = tf.stack(size)
else:
| |
<reponame>lelegan/sympy<filename>sympy/geometry/util.py
"""Utility functions for geometrical entities.
Contains
========
intersection
convex_hull
are_similar
"""
from __future__ import print_function, division
from sympy import Symbol, Function, solve
from sympy.core.compatibility import string_types, is_sequence
def idiff(eq, y, x, n=1):
"""Return ``dy/dx`` assuming that ``eq == 0``.
Parameters
==========
y : the dependent variable or a list of dependent variables (with y first)
x : the variable that the derivative is being taken with respect to
n : the order of the derivative (default is 1)
Examples
========
>>> from sympy.abc import x, y, a
>>> from sympy.geometry.util import idiff
>>> circ = x**2 + y**2 - 4
>>> idiff(circ, y, x)
-x/y
>>> idiff(circ, y, x, 2).simplify()
-(x**2 + y**2)/y**3
Here, ``a`` is assumed to be independent of ``x``:
>>> idiff(x + a + y, y, x)
-1
Now the x-dependence of ``a`` is made explicit by listing ``a`` after
``y`` in a list.
>>> idiff(x + a + y, [y, a], x)
-Derivative(a, x) - 1
See Also
========
sympy.core.function.Derivative: represents unevaluated derivatives
sympy.core.function.diff: explicitly differentiates wrt symbols
"""
if is_sequence(y):
dep = set(y)
y = y[0]
elif isinstance(y, Symbol):
dep = set([y])
else:
raise ValueError("expecting x-dependent symbol(s) but got: %s" % y)
f = dict([(s, Function(
s.name)(x)) for s in eq.atoms(Symbol) if s != x and s in dep])
dydx = Function(y.name)(x).diff(x)
eq = eq.subs(f)
derivs = {}
for i in range(n):
yp = solve(eq.diff(x), dydx)[0].subs(derivs)
if i == n - 1:
return yp.subs([(v, k) for k, v in f.items()])
derivs[dydx] = yp
eq = dydx - yp
dydx = dydx.diff(x)
def _symbol(s, matching_symbol=None):
"""Return s if s is a Symbol, else return either a new Symbol (real=True)
with the same name s or the matching_symbol if s is a string and it matches
the name of the matching_symbol.
>>> from sympy import Symbol
>>> from sympy.geometry.util import _symbol
>>> x = Symbol('x')
>>> _symbol('y')
y
>>> _.is_real
True
>>> _symbol(x)
x
>>> _.is_real is None
True
>>> arb = Symbol('foo')
>>> _symbol('arb', arb) # arb's name is foo so foo will not be returned
arb
>>> _symbol('foo', arb) # now it will
foo
NB: the symbol here may not be the same as a symbol with the same
name defined elsewhere as a result of different assumptions.
See Also
========
sympy.core.symbol.Symbol
"""
if isinstance(s, string_types):
if matching_symbol and matching_symbol.name == s:
return matching_symbol
return Symbol(s, real=True)
elif isinstance(s, Symbol):
return s
else:
raise ValueError('symbol must be string for symbol name or Symbol')
def intersection(*entities):
"""The intersection of a collection of GeometryEntity instances.
Parameters
==========
entities : sequence of GeometryEntity
Returns
=======
intersection : list of GeometryEntity
Raises
======
NotImplementedError
When unable to calculate intersection.
Notes
=====
The intersection of any geometrical entity with itself should return
a list with one item: the entity in question.
An intersection requires two or more entities. If only a single
entity is given then the function will return an empty list.
It is possible for `intersection` to miss intersections that one
knows exists because the required quantities were not fully
simplified internally.
Reals should be converted to Rationals, e.g. Rational(str(real_num))
or else failures due to floating point issues may result.
See Also
========
sympy.geometry.entity.GeometryEntity.intersection
Examples
========
>>> from sympy.geometry import Point, Line, Circle, intersection
>>> p1, p2, p3 = Point(0, 0), Point(1, 1), Point(-1, 5)
>>> l1, l2 = Line(p1, p2), Line(p3, p2)
>>> c = Circle(p2, 1)
>>> intersection(l1, p2)
[Point(1, 1)]
>>> intersection(l1, l2)
[Point(1, 1)]
>>> intersection(c, p2)
[]
>>> intersection(c, Point(1, 0))
[Point(1, 0)]
>>> intersection(c, l2)
[Point(-sqrt(5)/5 + 1, 2*sqrt(5)/5 + 1),
Point(sqrt(5)/5 + 1, -2*sqrt(5)/5 + 1)]
"""
from .entity import GeometryEntity
from .point import Point
if len(entities) <= 1:
return []
for i, e in enumerate(entities):
if not isinstance(e, GeometryEntity):
try:
entities[i] = Point(e)
except NotImplementedError:
raise ValueError('%s is not a GeometryEntity and cannot be made into Point' % str(e))
res = entities[0].intersection(entities[1])
for entity in entities[2:]:
newres = []
for x in res:
newres.extend(x.intersection(entity))
res = newres
return res
def convex_hull(*args):
"""The convex hull surrounding the Points contained in the list of entities.
Parameters
==========
args : a collection of Points, Segments and/or Polygons
Returns
=======
convex_hull : Polygon
Notes
=====
This can only be performed on a set of non-symbolic points.
References
==========
[1] http://en.wikipedia.org/wiki/Graham_scan
[2] Andrew's Monotone Chain Algorithm
(A.M. Andrew,
"Another Efficient Algorithm for Convex Hulls in Two Dimensions", 1979)
http://softsurfer.com/Archive/algorithm_0109/algorithm_0109.htm
See Also
========
sympy.geometry.point.Point, sympy.geometry.polygon.Polygon
Examples
========
>>> from sympy.geometry import Point, convex_hull
>>> points = [(1,1), (1,2), (3,1), (-5,2), (15,4)]
>>> convex_hull(*points)
Polygon(Point(-5, 2), Point(1, 1), Point(3, 1), Point(15, 4))
"""
from .entity import GeometryEntity
from .point import Point
from .line import Segment
from .polygon import Polygon
p = set()
for e in args:
if not isinstance(e, GeometryEntity):
try:
e = Point(e)
except NotImplementedError:
raise ValueError('%s is not a GeometryEntity and cannot be made into Point' % str(e))
if isinstance(e, Point):
p.add(e)
elif isinstance(e, Segment):
p.update(e.points)
elif isinstance(e, Polygon):
p.update(e.vertices)
else:
raise NotImplementedError(
'Convex hull for %s not implemented.' % type(e))
p = list(p)
if len(p) == 1:
return p[0]
elif len(p) == 2:
return Segment(p[0], p[1])
def _orientation(p, q, r):
'''Return positive if p-q-r are clockwise, neg if ccw, zero if
collinear.'''
return (q.y - p.y)*(r.x - p.x) - (q.x - p.x)*(r.y - p.y)
# scan to find upper and lower convex hulls of a set of 2d points.
U = []
L = []
p.sort(key=lambda x: x.args)
for p_i in p:
while len(U) > 1 and _orientation(U[-2], U[-1], p_i) <= 0:
U.pop()
while len(L) > 1 and _orientation(L[-2], L[-1], p_i) >= 0:
L.pop()
U.append(p_i)
L.append(p_i)
U.reverse()
convexHull = tuple(L + U[1:-1])
if len(convexHull) == 2:
return Segment(convexHull[0], convexHull[1])
return Polygon(*convexHull)
def are_similar(e1, e2):
"""Are two geometrical entities similar.
Can one geometrical entity be uniformly scaled to the other?
Parameters
==========
e1 : GeometryEntity
e2 : GeometryEntity
Returns
=======
are_similar : boolean
Raises
======
GeometryError
When `e1` and `e2` cannot be compared.
Notes
=====
If the two objects are equal then they are similar.
See Also
========
sympy.geometry.entity.GeometryEntity.is_similar
Examples
========
>>> from sympy import Point, Circle, Triangle, are_similar
>>> c1, c2 = Circle(Point(0, 0), 4), Circle(Point(1, 4), 3)
>>> t1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
>>> t2 = Triangle(Point(0, 0), Point(2, 0), Point(0, 2))
>>> t3 = Triangle(Point(0, 0), Point(3, 0), Point(0, 1))
>>> are_similar(t1, t2)
True
>>> are_similar(t1, t3)
False
"""
from .exceptions import GeometryError
if e1 == e2:
return True
try:
return e1.is_similar(e2)
except AttributeError:
try:
return e2.is_similar(e1)
except AttributeError:
n1 = e1.__class__.__name__
n2 = e2.__class__.__name__
raise GeometryError(
"Cannot test similarity between %s and %s" % (n1, n2))
def centroid(*args):
"""Find the centroid (center of mass) of the collection containing only Points,
Segments or Polygons. The centroid is the weighted average of the individual centroid
where the weights are the lengths (of segments) or areas (of polygons).
Overlapping regions will add to the weight of that region.
If there are no objects (or a mixture of objects) then None is returned.
See Also
========
sympy.geometry.point.Point, sympy.geometry.line.Segment,
sympy.geometry.polygon.Polygon
Examples
========
>>> from sympy import Point, Segment, Polygon
>>> from sympy.geometry.util import centroid
>>> p = Polygon((0, 0), (10, 0), (10, 10))
>>> q = p.translate(0, 20)
>>> p.centroid, q.centroid
(Point(20/3, 10/3), Point(20/3, 70/3))
>>> centroid(p, q)
Point(20/3, 40/3)
>>> p, q = Segment((0, 0), (2, 0)), Segment((0, 0), (2, 2))
>>> centroid(p, q)
Point(1, -sqrt(2) + 2)
>>> centroid(Point(0, 0), Point(2, 0))
Point(1, 0)
Stacking 3 polygons on top of each other effectively triples the
weight of that polygon:
>>> p = Polygon((0, 0), (1, 0), (1, 1), (0, 1))
>>> q = Polygon((1, 0), (3, 0), (3, 1), (1, 1))
>>> centroid(p, q)
Point(3/2, 1/2)
>>> centroid(p, p, p, q) # centroid x-coord shifts left
Point(11/10, 1/2)
Stacking the squares vertically above and below p has the same
effect:
>>> centroid(p, p.translate(0, 1), p.translate(0, -1), | |
m.x595 >= 0)
m.c773 = Constraint(expr= - m.b73 + m.x358 + m.x449 + m.x491 + m.x533 + m.x596 >= 0)
m.c774 = Constraint(expr= - m.b74 + m.x359 + m.x450 + m.x492 + m.x534 + m.x597 >= 0)
m.c775 = Constraint(expr= - m.b75 + m.x360 + m.x451 + m.x493 + m.x535 + m.x598 >= 0)
m.c776 = Constraint(expr= - m.b76 + m.x361 + m.x452 + m.x494 + m.x536 + m.x599 >= 0)
m.c777 = Constraint(expr= - m.b77 + m.x362 + m.x453 + m.x495 + m.x537 + m.x600 >= 0)
m.c778 = Constraint(expr= - m.b78 + m.x363 + m.x398 + m.x454 + m.x496 + m.x538 + m.x573 >= 0)
m.c779 = Constraint(expr= - m.b79 + m.x364 + m.x399 + m.x455 + m.x497 + m.x539 + m.x574 >= 0)
m.c780 = Constraint(expr= - m.b80 + m.x365 + m.x400 + m.x456 + m.x498 + m.x540 + m.x575 >= 0)
m.c781 = Constraint(expr= - m.b81 + m.x366 + m.x401 + m.x457 + m.x499 + m.x541 + m.x576 >= 0)
m.c782 = Constraint(expr= - m.b82 + m.x367 + m.x402 + m.x458 + m.x500 + m.x542 + m.x577 >= 0)
m.c783 = Constraint(expr= - m.b83 + m.x368 + m.x403 + m.x459 + m.x501 + m.x543 + m.x578 >= 0)
m.c784 = Constraint(expr= - m.b84 + m.x369 + m.x404 + m.x460 + m.x502 + m.x544 + m.x579 >= 0)
m.c785 = Constraint(expr= - m.b85 + m.x370 + m.x405 + m.x461 + m.x503 + m.x545 + m.x580 >= 0)
m.c786 = Constraint(expr= - m.b86 + m.x371 + m.x406 + m.x462 + m.x504 + m.x546 + m.x581 >= 0)
m.c787 = Constraint(expr= - m.b87 + m.x372 + m.x407 + m.x463 + m.x505 + m.x547 + m.x582 >= 0)
m.c788 = Constraint(expr= - m.b88 + m.x373 + m.x408 + m.x464 + m.x506 + m.x548 + m.x583 >= 0)
m.c789 = Constraint(expr= - m.b89 + m.x374 + m.x409 + m.x465 + m.x507 + m.x549 + m.x584 >= 0)
m.c790 = Constraint(expr= - m.b90 + m.x375 + m.x410 + m.x466 + m.x508 + m.x550 + m.x585 >= 0)
m.c791 = Constraint(expr= - m.b91 + m.x376 + m.x411 + m.x467 + m.x509 + m.x551 + m.x586 >= 0)
m.c792 = Constraint(expr= - m.b92 + m.x412 + m.x468 + m.x552 + m.x587 >= 0)
m.c793 = Constraint(expr= - m.b93 + m.x413 + m.x469 + m.x553 + m.x588 >= 0)
m.c794 = Constraint(expr= - m.b94 + m.x414 + m.x470 + m.x554 + m.x589 >= 0)
m.c795 = Constraint(expr= - m.b95 + m.x415 + m.x471 + m.x555 + m.x590 >= 0)
m.c796 = Constraint(expr= - m.b96 + m.x416 + m.x472 + m.x556 + m.x591 >= 0)
m.c797 = Constraint(expr= - m.b97 + m.x417 + m.x473 + m.x557 + m.x592 >= 0)
m.c798 = Constraint(expr= - m.b98 + m.x418 + m.x474 + m.x558 + m.x593 >= 0)
m.c799 = Constraint(expr= - 0.002*m.x335 - m.x667 + m.x668 >= 0)
m.c800 = Constraint(expr= - 0.002*m.x336 - m.x668 + m.x669 >= 0)
m.c801 = Constraint(expr= - 0.002*m.x337 - m.x669 + m.x670 >= 0)
m.c802 = Constraint(expr= - 0.002*m.x338 - m.x670 + m.x671 >= 0)
m.c803 = Constraint(expr= - 0.002*m.x339 - m.x671 + m.x672 >= 0)
m.c804 = Constraint(expr= - 0.002*m.x340 - m.x672 + m.x673 >= 0)
m.c805 = Constraint(expr= - 0.002*m.x341 - m.x673 + m.x674 >= 0)
m.c806 = Constraint(expr= - 0.002*m.x377 - m.x667 + m.x668 >= 0)
m.c807 = Constraint(expr= - 0.002*m.x378 - m.x668 + m.x669 >= 0)
m.c808 = Constraint(expr= - 0.002*m.x379 - m.x669 + m.x670 >= 0)
m.c809 = Constraint(expr= - 0.002*m.x380 - m.x670 + m.x671 >= 0)
m.c810 = Constraint(expr= - 0.002*m.x381 - m.x671 + m.x672 >= 0)
m.c811 = Constraint(expr= - 0.002*m.x382 - m.x672 + m.x673 >= 0)
m.c812 = Constraint(expr= - 0.002*m.x383 - m.x673 + m.x674 >= 0)
m.c813 = Constraint(expr= - 0.002*m.x419 - m.x667 + m.x668 >= 0)
m.c814 = Constraint(expr= - 0.002*m.x420 - m.x668 + m.x669 >= 0)
m.c815 = Constraint(expr= - 0.002*m.x421 - m.x669 + m.x670 >= 0)
m.c816 = Constraint(expr= - 0.002*m.x422 - m.x670 + m.x671 >= 0)
m.c817 = Constraint(expr= - 0.002*m.x423 - m.x671 + m.x672 >= 0)
m.c818 = Constraint(expr= - 0.002*m.x424 - m.x672 + m.x673 >= 0)
m.c819 = Constraint(expr= - 0.002*m.x425 - m.x673 + m.x674 >= 0)
m.c820 = Constraint(expr= - 0.002*m.x342 - 0.002*m.x475 - m.x667 + m.x668 >= 0)
m.c821 = Constraint(expr= - 0.002*m.x343 - 0.002*m.x476 - m.x668 + m.x669 >= 0)
m.c822 = Constraint(expr= - 0.002*m.x344 - 0.002*m.x477 - m.x669 + m.x670 >= 0)
m.c823 = Constraint(expr= - 0.002*m.x345 - 0.002*m.x478 - m.x670 + m.x671 >= 0)
m.c824 = Constraint(expr= - 0.002*m.x346 - 0.002*m.x479 - m.x671 + m.x672 >= 0)
m.c825 = Constraint(expr= - 0.002*m.x347 - 0.002*m.x480 - m.x672 + m.x673 >= 0)
m.c826 = Constraint(expr= - 0.002*m.x348 - 0.002*m.x481 - m.x673 + m.x674 >= 0)
m.c827 = Constraint(expr= - 0.002*m.x349 - 0.002*m.x482 - m.x667 + m.x668 >= 0)
m.c828 = Constraint(expr= - 0.002*m.x350 - 0.002*m.x483 - m.x668 + m.x669 >= 0)
m.c829 = Constraint(expr= - 0.002*m.x351 - 0.002*m.x484 - m.x669 + m.x670 >= 0)
m.c830 = Constraint(expr= - 0.002*m.x352 - 0.002*m.x485 - m.x670 + m.x671 >= 0)
m.c831 = Constraint(expr= - 0.002*m.x353 - 0.002*m.x486 - m.x671 + m.x672 >= 0)
m.c832 = Constraint(expr= - 0.002*m.x354 - 0.002*m.x487 - m.x672 + m.x673 >= 0)
m.c833 = Constraint(expr= - 0.002*m.x355 - 0.002*m.x488 - m.x673 + m.x674 >= 0)
m.c834 = Constraint(expr= - 0.002*m.x426 - 0.002*m.x510 - m.x667 + m.x668 >= 0)
m.c835 = Constraint(expr= - 0.002*m.x427 - 0.002*m.x511 - m.x668 + m.x669 >= 0)
m.c836 = Constraint(expr= - 0.002*m.x428 - 0.002*m.x512 - m.x669 + m.x670 >= 0)
m.c837 = Constraint(expr= - 0.002*m.x429 - 0.002*m.x513 - m.x670 + m.x671 >= 0)
m.c838 = Constraint(expr= - 0.002*m.x430 - 0.002*m.x514 - m.x671 + m.x672 >= 0)
m.c839 = Constraint(expr= - 0.002*m.x431 - 0.002*m.x515 - m.x672 + m.x673 >= 0)
m.c840 = Constraint(expr= - 0.002*m.x432 - 0.002*m.x516 - m.x673 + m.x674 >= 0)
m.c841 = Constraint(expr= - 0.002*m.x433 - 0.002*m.x517 - m.x667 + m.x668 >= 0)
m.c842 = Constraint(expr= - 0.002*m.x434 - 0.002*m.x518 - m.x668 + m.x669 >= 0)
m.c843 = Constraint(expr= - 0.002*m.x435 - 0.002*m.x519 - m.x669 + m.x670 >= 0)
m.c844 = Constraint(expr= - 0.002*m.x436 - 0.002*m.x520 - m.x670 + m.x671 >= 0)
m.c845 = Constraint(expr= - 0.002*m.x437 - 0.002*m.x521 - m.x671 + m.x672 >= 0)
m.c846 = Constraint(expr= - 0.002*m.x438 - 0.002*m.x522 - m.x672 + m.x673 >= 0)
m.c847 = Constraint(expr= - 0.002*m.x439 - 0.002*m.x523 - m.x673 + m.x674 >= 0)
m.c848 = Constraint(expr= - 0.002*m.x440 - 0.002*m.x524 - m.x667 + m.x668 >= 0)
m.c849 = Constraint(expr= - 0.002*m.x441 - 0.002*m.x525 - m.x668 + m.x669 >= 0)
m.c850 = Constraint(expr= - 0.002*m.x442 - 0.002*m.x526 - m.x669 + m.x670 >= 0)
m.c851 = Constraint(expr= - 0.002*m.x443 - 0.002*m.x527 - m.x670 + m.x671 >= 0)
m.c852 = Constraint(expr= - 0.002*m.x444 - 0.002*m.x528 - m.x671 + m.x672 >= 0)
m.c853 = Constraint(expr= - 0.002*m.x445 - 0.002*m.x529 - m.x672 + m.x673 >= 0)
m.c854 = Constraint(expr= - 0.002*m.x446 - 0.002*m.x530 - m.x673 + m.x674 >= 0)
m.c855 = Constraint(expr= - 0.002*m.x384 - 0.002*m.x559 - m.x667 + m.x668 >= 0)
m.c856 = Constraint(expr= - 0.002*m.x385 - 0.002*m.x560 - m.x668 + m.x669 >= 0)
m.c857 = Constraint(expr= - 0.002*m.x386 - 0.002*m.x561 - m.x669 + m.x670 >= 0)
m.c858 = Constraint(expr= - 0.002*m.x387 - 0.002*m.x562 - m.x670 + m.x671 >= 0)
m.c859 = Constraint(expr= - 0.002*m.x388 - 0.002*m.x563 - m.x671 + m.x672 >= 0)
m.c860 = Constraint(expr= - 0.002*m.x389 - 0.002*m.x564 - m.x672 + m.x673 >= 0)
m.c861 = Constraint(expr= - 0.002*m.x390 - 0.002*m.x565 - m.x673 + m.x674 >= 0)
m.c862 = Constraint(expr= - 0.002*m.x391 - 0.002*m.x566 - m.x667 + m.x668 >= 0)
m.c863 = Constraint(expr= - 0.002*m.x392 - 0.002*m.x567 - m.x668 + m.x669 >= 0)
m.c864 = Constraint(expr= - 0.002*m.x393 - 0.002*m.x568 - m.x669 + m.x670 >= 0)
m.c865 = Constraint(expr= - 0.002*m.x394 - 0.002*m.x569 - m.x670 + m.x671 >= 0)
m.c866 = Constraint(expr= - 0.002*m.x395 - 0.002*m.x570 - m.x671 + m.x672 >= 0)
m.c867 = Constraint(expr= - 0.002*m.x396 - 0.002*m.x571 - m.x672 + m.x673 >= 0)
m.c868 = Constraint(expr= - 0.002*m.x397 - 0.002*m.x572 - m.x673 + m.x674 >= 0)
m.c869 = Constraint(expr= - 0.002*m.x363 - 0.002*m.x370 - 0.002*m.x398 - 0.002*m.x405 - 0.002*m.x454 - 0.002*m.x461
- 0.002*m.x496 - 0.002*m.x503 - 0.002*m.x538 - 0.002*m.x545 - 0.002*m.x573 - 0.002*m.x580
- m.x667 + m.x668 >= 0)
m.c870 = Constraint(expr= - 0.002*m.x364 - 0.002*m.x371 - 0.002*m.x399 - 0.002*m.x406 - 0.002*m.x455 - 0.002*m.x462
- 0.002*m.x497 - | |
<gh_stars>10-100
# [h] hTools2.modules.unicode
from collections import OrderedDict
'''Tools to work with Unicode, convert glyph names to hex/unicode etc.'''
def clear_unicodes(font):
'''Remove unicodes from all glyphs in the font.'''
for g in font:
g.unicodes = []
font.update()
def auto_unicodes(font, custom_unicodes={}):
'''Automatically set unicode values for all glyphs in the font.'''
clear_unicodes(font)
for g in font:
if g is not None:
auto_unicode(g, custom_unicodes)
font.update()
def auto_unicode(g, custom_unicodes={}):
'''
Automatically set unicode value(s) for the specified glyph.
The method uses RoboFab's ``glyph.autoUnicodes()`` function for common glyphs, and complements it with additional values from ``unicodes_extra``.
'''
if g.name is not None:
# handle 'uni' names
if g.name[:3] == "uni" and len(g.name) in [7, 8]:
c = g.name
g.unicode = int(c.split('uni')[1], 16)
# handle extra cases
elif g.name in unicodes_extra.keys():
uString = 'uni%s' % unicodes_extra[g.name]
g.unicode = unicode_hexstr_to_int(uString)
# use auto unicode for everything else
elif custom_unicodes.get(g.name) is not None:
uString = 'uni%s' % custom_unicodes[g.name]
g.unicode = unicode_hexstr_to_int(uString)
else:
g.autoUnicodes()
g.update()
#------------------------------
# unicode-to-string conversion
#------------------------------
def unicode_int_to_hexstr(intUnicode, _0x=False, uni=False):
'''
Converts unicode integers to hexadecimal.
See also the reverse function ``unicode_hexstr_to_int``.
Note that ``glyph.unicodes`` is a list (a glyph can have many unicodes), so we need to pass the first value only.
The optional parameters ``uni`` and ``_0x`` add the respective prefixes.
'''
hexUnicode = "%X".lstrip("0x") % intUnicode
hexUnicode = "0" * (4 - len(hexUnicode)) + hexUnicode
if _0x:
return "0x%s" % hexUnicode
elif uni:
return "uni%s" % hexUnicode
return hexUnicode
def unicode_hexstr_to_int(hexUnicode, replaceUni=True):
'''
Converts a unicode hexadecimal value into an integer.
It does exactly the reverse of ``unicode_int_to_hexstr``.
'''
if replaceUni:
return int(hexUnicode.replace("uni",""), 16)
return int(hexUnicode.lstrip("x"), 16)
#-----------------------------
# additional unicode mappings
#-----------------------------
#: A dict containing additional `glyphName` to `unicode` mappings.
unicodes_extra = {
# extended latin lc
'aemacron' : '01E3',
'dotlessj' : '0237',
'schwa' : '0259',
'ymacron' : '0233',
'eszett' : '00DF',
# extended latin uc
'AEmacron' : '01E2',
'Schwa' : '018F',
'Uppercaseeszett' : '1E9E',
# ligatures
'fi' : 'FB01',
'fl' : 'FB02',
'f_f' : 'FB00',
'f_f_i' : 'FB03',
'f_f_l' : 'FB04',
# greek exceptions
'Delta' : '2206', # 0394
'Omega' : '2126', # 03A9
'mu' : '00B5', # 03BC
# superiors
'zerosuperior' : '2070',
'onesuperior' : '00B9',
'twosuperior' : '00B2',
'threesuperior' : '00B3',
'foursuperior' : '2074',
'fivesuperior' : '2075',
'sixsuperior' : '2076',
'sevensuperior' : '2077',
'eightsuperior' : '2078',
'ninesuperior' : '2079',
# inferiors
'zeroinferior' : '2080',
'oneinferior' : '2081',
'twoinferior' : '2082',
'threeinferior' : '2083',
'fourinferior' : '2084',
'fiveinferior' : '2085',
'sixinferior' : '2086',
'seveninferior' : '2087',
'eightinferior' : '2088',
'nineinferior' : '2089',
# spaces
'enspace' : '2002',
'emspace' : '2003',
'nbspace' : '00A0',
'hairspace' : '200A',
'thinspace' : '2009',
'thickspace' : '2004',
'figurespace' : '2007',
'zerowidthspace' : '200B',
# combining accents
'gravecomb' : '0300',
'acutecomb' : '0301',
'circumflexcomb' : '0302',
'tildecomb' : '0303',
'dieresiscomb' : '0308',
'dotbelowcomb' : '0323',
'cedillacomb' : '0327',
# arrows
'arrowleft' : '2190',
'arrowup' : '2191',
'arrowright' : '2192',
'arrowdown' : '2193',
'arrowleftright' : '2194',
'arrowupdown' : '2195',
'arrowupleft' : '2196',
'arrowupright' : '2197',
'arrowdownright' : '2198',
'arrowdownleft' : '2199',
# latin accented lc
'adotbelow' : '1EA1',
'aringacute' : '01FB',
'edotbelow' : '1EB9',
'etilde' : '1EBD',
'gcaron' : '01E7',
'idotbelow' : '1ECB',
'ndotbelow' : '1E47',
'nhookleft' : '0272',
'odotbelow' : '1ECD',
'oogonek' : '01EB',
'sdotbelow' : '1E63',
'udotbelow' : '1EE5',
'ymacron' : '0233',
'ytilde' : '1EF9',
# latin accented uc
'Adotbelow' : '1EA0',
'Aringacute' : '01FA',
'Edotbelow' : '1EB8',
'Etilde' : '1EBC',
'Gcaron' : '01E6',
'Idotbelow' : '1ECA',
'Ndotbelow' : '1E46',
'Nhookleft' : '019D',
'Odotbelow' : '1ECC',
'Oogonek' : '01EA',
'Sdotbelow' : '1E62',
'Udotbelow' : '1EE4',
'Ymacron' : '0232',
'Ytilde' : '1EF8',
# symbols etc
'bulletoperator' : '2219',
'florin' : '0192',
}
#-----------------------------
# unicode to psNames mappings
#-----------------------------
#: A dictionary mapping unicode values to psNames.
unicode2psnames = {
None : '.notdef',
32 : 'space',
33 : 'exclam',
34 : 'quotedbl',
35 : 'numbersign',
36 : 'dollar',
37 : 'percent',
38 : 'ampersand',
39 : 'quotesingle',
40 : 'parenleft',
41 : 'parenright',
42 : 'asterisk',
43 : 'plus',
44 : 'comma',
45 : 'hyphen',
46 : 'period',
47 : 'slash',
48 : 'zero',
49 : 'one',
50 : 'two',
51 : 'three',
52 : 'four',
53 : 'five',
54 : 'six',
55 : 'seven',
56 : 'eight',
57 : 'nine',
58 : 'colon',
59 : 'semicolon',
60 : 'less',
61 : 'equal',
62 : 'greater',
63 : 'question',
64 : 'at',
65 : 'A',
66 : 'B',
67 : 'C',
68 : 'D',
69 : 'E',
70 : 'F',
71 : 'G',
72 : 'H',
73 : 'I',
74 : 'J',
75 : 'K',
76 : 'L',
77 : 'M',
78 : 'N',
79 : 'O',
80 : 'P',
81 : 'Q',
82 : 'R',
83 : 'S',
84 : 'T',
85 : 'U',
86 : 'V',
87 : 'W',
88 : 'X',
89 : 'Y',
90 : 'Z',
91 : 'bracketleft',
92 : 'backslash',
93 : 'bracketright',
94 : 'asciicircum',
95 : 'underscore',
96 : 'grave',
97 : 'a',
98 : 'b',
99 : 'c',
100 : 'd',
101 : 'e',
102 : 'f',
103 : 'g',
104 : 'h',
105 : 'i',
106 : 'j',
107 : 'k',
108 : 'l',
109 : 'm',
110 : 'n',
111 : 'o',
112 : 'p',
113 : 'q',
114 : 'r',
115 : 's',
116 : 't',
117 : 'u',
118 : 'v',
119 : 'w',
120 : 'x',
121 : 'y',
122 : 'z',
123 : 'braceleft',
124 : 'bar',
125 : 'braceright',
126 : 'asciitilde',
161 : 'exclamdown',
162 : 'cent',
163 : 'sterling',
164 : 'currency',
165 : 'yen',
166 : 'brokenbar',
167 : 'section',
168 : 'dieresis',
169 : 'copyright',
170 : 'ordfeminine',
171 : 'guillemotleft',
172 : 'logicalnot',
174 : 'registered',
175 : 'macron',
176 : 'degree',
177 : 'plusminus',
178 : 'twosuperior',
179 : 'threesuperior',
180 : 'acute',
181 : 'mu',
182 : 'paragraph',
183 : 'periodcentered',
184 : 'cedilla',
185 : 'onesuperior',
186 : 'ordmasculine',
187 : 'guillemotright',
188 : 'onequarter',
189 : 'onehalf',
190 : 'threequarters',
191 : 'questiondown',
192 : 'Agrave',
193 : 'Aacute',
194 : 'Acircumflex',
195 : 'Atilde',
196 : 'Adieresis',
197 : 'Aring',
198 : 'AE',
199 : 'Ccedilla',
200 : 'Egrave',
201 : 'Eacute',
202 : 'Ecircumflex',
203 : 'Edieresis',
204 : 'Igrave',
205 : 'Iacute',
206 : 'Icircumflex',
207 : 'Idieresis',
208 : 'Eth',
209 : 'Ntilde',
210 : 'Ograve',
211 : 'Oacute',
212 : 'Ocircumflex',
213 : 'Otilde',
214 : 'Odieresis',
215 : 'multiply',
216 : 'Oslash',
217 : 'Ugrave',
218 : 'Uacute',
219 : 'Ucircumflex',
220 : 'Udieresis',
221 : 'Yacute',
222 : 'Thorn',
223 : 'germandbls',
224 : 'agrave',
225 : 'aacute',
226 : 'acircumflex',
227 : 'atilde',
228 : 'adieresis',
229 : 'aring',
230 : 'ae',
231 : 'ccedilla',
232 : 'egrave',
233 : 'eacute',
234 : 'ecircumflex',
235 : 'edieresis',
236 : 'igrave',
237 : 'iacute',
238 : 'icircumflex',
239 : 'idieresis',
240 : 'eth',
241 : 'ntilde',
242 : 'ograve',
243 : 'oacute',
244 : 'ocircumflex',
245 : 'otilde',
246 : 'odieresis',
247 : 'divide',
248 : 'oslash',
249 : 'ugrave',
250 : 'uacute',
251 : 'ucircumflex',
252 : 'udieresis',
253 : 'yacute',
254 : 'thorn',
255 : 'ydieresis',
256 : 'Amacron',
257 : 'amacron',
258 : 'Abreve',
259 : 'abreve',
260 : 'Aogonek',
261 : 'aogonek',
262 : 'Cacute',
263 : 'cacute',
264 : 'Ccircumflex',
265 : 'ccircumflex',
266 : 'Cdotaccent',
267 : 'cdotaccent',
268 : 'Ccaron',
269 : 'ccaron',
270 : 'Dcaron',
271 : 'dcaron',
272 : 'Dcroat',
273 : 'dcroat',
274 : 'Emacron',
275 : 'emacron',
276 : 'Ebreve',
277 : 'ebreve',
278 : 'Edotaccent',
279 : 'edotaccent',
280 : 'Eogonek',
281 : 'eogonek',
282 : 'Ecaron',
283 : 'ecaron',
284 : 'Gcircumflex',
285 : 'gcircumflex',
286 : 'Gbreve',
287 : 'gbreve',
288 : 'Gdotaccent',
289 : 'gdotaccent',
290 : 'Gcommaaccent',
291 : 'gcommaaccent',
292 : 'Hcircumflex',
293 : 'hcircumflex',
294 | |
nframeswrite = %d"%nframeswrite
for i in range(nframeswrite):
self.outfile.write(struct.pack("<Q",self.writesbfmf_framestarts[i]))
# write the location of the index
self.outfile.seek(self.writesbfmf_indexptrloc)
self.outfile.write(struct.pack("<Q",indexloc))
# write the number of frames
self.outfile.seek(self.writesbfmf_nframesloc)
self.outfile.write(struct.pack("<I",nframeswrite))
def writesbfmf_writeheader(self,bg):
"""
Writes the header for the file. Format:
Number of bytes in version string: (I = unsigned int)
Version Number (string of specified length)
Number of rows (I = unsigned int)
Number of columns (I = unsigned int)
Number of frames (I = unsigned int)
Difference mode (I = unsigned int):
0 if light flies on dark background, unsigned mode
1 if dark flies on light background, unsigned mode
2 if other, signed mode
Location of index (Q = unsigned long long)
Background image (ncols * nrows * double)
Standard deviation image (ncols * nrows * double)
"""
self.nr = self.get_height()
self.nc = self.get_width()
# write the number of columns, rows, frames, difference mode
if bg.bg_type == 'light_on_dark':
difference_mode = 0
elif bg.bg_type == 'dark_on_light':
difference_mode = 1
else:
difference_mode = 2
self.outfile.write(struct.pack("<I",len(__version__)))
self.outfile.write(__version__)
self.outfile.write(struct.pack("<2I",int(self.nr),int(self.nc)))
self.writesbfmf_nframesloc = self.outfile.tell()
self.outfile.write(struct.pack("<2I",int(self.nframescompress),int(difference_mode)))
if DEBUG_MOVIES: print "writeheader: nframescompress = " + str(self.nframescompress)
# compute the location of the standard deviation image
stdloc = self.outfile.tell() + struct.calcsize("B")*self.nr*self.nc
# compute the location of the first frame
ffloc = stdloc + struct.calcsize("d")*self.nr*self.nc
# where do we write the location of the index -- this is always the same
self.writesbfmf_indexptrloc = self.outfile.tell()
# write a placeholder for the index location
self.outfile.write(struct.pack("<Q",0))
# write the background image
self.outfile.write(bg.center)
# write the standard deviation image
self.outfile.write(bg.dev)
def writesbfmf_writeframe(self,isfore,im,stamp,currframe):
if DEBUG_MOVIES: print "writing frame %d"%currframe
tmp = isfore.copy()
tmp.shape = (self.nr*self.nc,)
i, = num.nonzero(tmp)
# values at foreground pixels
v = im[isfore]
# number of foreground pixels
n = len(i)
# store the start of this frame
j = currframe - params.start_frame
self.writesbfmf_framestarts[j] = self.outfile.tell()
if DEBUG_MOVIES: print "stored in framestarts[%d]"%j
# write number of pixels and time stamp
self.outfile.write(struct.pack("<Id",n,stamp))
i = i.astype(num.uint32)
self.outfile.write(i)
self.outfile.write(v)
def close(self):
if hasattr(self,'h_mov'):
with self.file_lock:
try:
self.h_mov.close()
except:
print "Could not close"
"""
AVI class; written by JAB and KMB, altered by <NAME>.
Don's changes:
important alterations from version I received:
- allows fccHandler = "" or all nulls
- allows width to vary to match actual frame size (suspect that avi pads to
multiples of four?) (and let get_width return actual width)
- added various derived attributes to better masquerade as an FMF file
- added an "fmf" mode; in this mode, it reshapes array to same shape as fmf
(row/column order swapped) -> was commented out, so removed JAB 8/29/11
- added a seek() method
- I want to make this width change more transparent, but I keep
running into related shape issues
- Avi class is still byte-order undefined, but at least it's read-only
"""
class Avi:
"""Read uncompressed AVI movies."""
def __init__( self, filename ):
self.issbfmf = False
# need to open in binary mode to support Windows:
self.file = open( filename, 'rb' )
self.frame_index = {} # file locations of each frame
try:
self.read_header()
self.postheader_calculations()
except Exception, details:
if DEBUG_MOVIES: print( "error reading uncompressed AVI:" )
if DEBUG_MOVIES: print( details )
raise
# added to help masquerade as FMF file:
self.filename = filename
self.chunk_start = self.data_start
# this is a mystery, but I think it's 8 for avi: seems to be offset
# from beginning of "chunk" to beginning of array data within chunk
self.timestamp_len = 8
if hasattr(self, "newwidth"):
self.bytes_per_chunk = (self.height * self.newwidth) + self.timestamp_len
else:
self.bytes_per_chunk = self.buf_size + self.timestamp_len
#self.bits_per_pixel = 8
if DEBUG_MOVIES: print "bits per pix: %d, bytes per chunk %d" % (self.bits_per_pixel, self.bytes_per_chunk)
def get_all_timestamps( self ):
"""Return a Numpy array containing all frames' timestamps."""
timestamps = num.zeros( (self.n_frames,) )
for fr in range( self.n_frames ):
timestamps[fr] = self.make_timestamp( fr )
return timestamps
def make_timestamp( self, fr ):
"""Approximate timestamp from frame rate recorded in header."""
if self.frame_delay_us != 0:
return fr * self.frame_delay_us / 1e6
elif self.time_scale != 0:
return fr * self.data_rate / float(self.time_scale)
else:
return fr / 30.
###################################################################
# read_header()
###################################################################
def read_header( self ):
# read RIFF then riffsize
RIFF, riff_size, AVI = struct.unpack( '4sI4s', self.file.read( 12 ) )
if not RIFF == 'RIFF':
print "movie header RIFF error at", RIFF, riff_size, AVI
raise TypeError("Invalid AVI file. Must be a RIFF file.")
if (not AVI == 'AVI ') and (not AVI == 'AVIX'):
print "movie header AVI error at", RIFF, riff_size, AVI
raise TypeError("Invalid AVI file. File type must be \'AVI \'.")
# read hdrl
LIST, hdrl_size, hdrl = struct.unpack( '4sI4s', self.file.read( 12 ) )
hdrlstart = self.file.tell() - 4
if not LIST == 'LIST':
print "movie header LIST 1 error at", LIST, hdrl_size, hdrl
raise TypeError("Invalid AVI file. Did not find header list.")
if hdrl == 'hdrl': # a real header
# read avih
avih, avih_size = struct.unpack( '4sI', self.file.read( 8 ) )
if not avih == 'avih':
print "movie header avih error at", avih, avih_size
raise TypeError("Invalid AVI file. Did not find avi header.")
avihchunkstart = self.file.tell()
# read microsecperframe
self.frame_delay_us, = struct.unpack('I',self.file.read(4))
# skip to nframes
self.file.seek(3*4,1)
self.n_frames, = struct.unpack('I',self.file.read(4))
# skip to width, height
self.file.seek(3*4,1)
self.width,self.height = struct.unpack('2I',self.file.read(8))
if DEBUG_MOVIES: print "width = %d, height = %d"%(self.width,self.height)
if DEBUG_MOVIES: print "n_frames = %d"%self.n_frames
# skip the rest of the aviheader
self.file.seek(avihchunkstart+avih_size,0)
LIST, stream_listsize, strl = \
struct.unpack( '4sI4s', self.file.read( 12 ) )
if (not LIST == 'LIST') or (not strl == 'strl'):
print "movie header LIST 2 error at", LIST, strl
raise TypeError("Invalid AVI file. Did not find stream list.")
strh, strh_size = struct.unpack( '4sI', self.file.read( 8 ) )
if not strh == 'strh':
print "movie header strh error at", strh, strh_size
raise TypeError("Invalid AVI file. Did not find stream header.")
strhstart = self.file.tell()
# read stream type, fcc handler
vids, fcc = struct.unpack( '4s4s', self.file.read( 8 ) )
# check for vidstream
if not vids == 'vids':
print "movie header vids error at", vids
raise TypeError("Unsupported AVI file type. First stream found is not a video stream.")
# check fcc
if fcc not in ['DIB ', '\x00\x00\x00\x00', "", "RAW ", "NONE", chr(24)+"BGR", 'Y8 ']:
if DEBUG_MOVIES: print "movie header codec error at", fcc
raise TypeError("Unsupported AVI file type %s, only uncompressed AVIs supported."%fcc)
if DEBUG_MOVIES: print "codec", fcc
# skip the rest of the stream header
self.file.seek(strhstart+strh_size,0)
strf, strf_size = struct.unpack( '4sI', self.file.read( 8 ) )
if not strf == "strf":
print "movie header strf error at", strf
raise TypeError("Invalid AVI file. Did not find strf.")
strfstart = self.file.tell()
bitmapheadersize, = struct.unpack('I',self.file.read(4))
# skip width, height, planes
self.file.seek(4*2+2,1)
# read in bits per pixel
self.bits_per_pixel, = struct.unpack('H',self.file.read(2))
if DEBUG_MOVIES: print "bits_per_pixel = %d"%self.bits_per_pixel
# is this an indexed avi?
colormapsize = (strf_size - bitmapheadersize)/4
if colormapsize > 0:
self.isindexed = True
self.file.seek(strfstart+bitmapheadersize,0)
self.colormap = num.frombuffer(self.file.read(4*colormapsize),num.uint8)
self.colormap = self.colormap.reshape((colormapsize,4))
self.colormap = self.colormap[:,:-1]
if DEBUG_MOVIES: print "file is indexed with %d colors" % len( self.colormap )
else:
self.isindexed = False
if self.bits_per_pixel == 24:
self.isindexed = False
# skip the rest of the strf
self.file.seek(hdrlstart+hdrl_size,0)
else:
# maybe this is a "second header" following an index... no hdrl
self.file.seek( -12, os.SEEK_CUR )
while True:
# find LIST chunk
LIST,movilist_size = struct.unpack( '4sI', self.file.read( 8 ) )
if LIST == 'LIST':
# find movi
movi, = struct.unpack('4s',self.file.read(4))
if DEBUG_MOVIES: print 'looking for movi, found ' + movi
if movi == 'movi':
break
else:
self.file.seek(-4,1)
# found some other chunk, seek past
self.file.seek(movilist_size,1)
if not movi == 'movi':
raise TypeError("Invalid AVI file. Did not find movi, found %s."%movi)
# read extra stuff
while True:
fourcc,chunksize, = struct.unpack('4sI',self.file.read(8))
if DEBUG_MOVIES: print 'read fourcc=%s, chunksize=%d'%(fourcc,chunksize)
if fourcc == '00db' or fourcc == '00dc':
self.file.seek(-8,1)
break
self.file.seek(chunksize,1)
self.buf_size = chunksize
if DEBUG_MOVIES: print "chunk size: ", self.buf_size
# check whether n_frames makes sense (sometimes headers lie)
approx_file_len = self.buf_size*self.n_frames
cur_pos = self.file.tell()
self.file.seek( 0, os.SEEK_END )
real_file_len = self.file.tell()
self.file.seek( cur_pos )
if real_file_len > approx_file_len*1.1:
| |
<filename>augly/image/utils/bboxes.py
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import math
from typing import List, Optional, Tuple
import augly.image.utils as imutils
import numpy as np
def crop_bboxes_helper(
bbox: Tuple, x1: float, y1: float, x2: float, y2: float, **kwargs
) -> Tuple:
"""
If part of the bbox was cropped out in the x-axis, the left/right side will now be
0/1 respectively; otherwise the fraction x1 is cut off from the left & x2 from the
right and we renormalize with the new width. Analogous for the y-axis
"""
left_factor, upper_factor, right_factor, lower_factor = bbox
new_w, new_h = x2 - x1, y2 - y1
return (
max(0, (left_factor - x1) / new_w),
max(0, (upper_factor - y1) / new_h),
min(1, 1 - (x2 - right_factor) / new_w),
min(1, 1 - (y2 - lower_factor) / new_h),
)
def hflip_bboxes_helper(bbox: Tuple, **kwargs) -> Tuple:
"""
When the src image is horizontally flipped, the bounding box also gets horizontally
flipped
"""
left_factor, upper_factor, right_factor, lower_factor = bbox
return (1 - right_factor, upper_factor, 1 - left_factor, lower_factor)
def meme_format_bboxes_helper(
bbox: Tuple, src_w: int, src_h: int, caption_height: int, **kwargs
) -> Tuple:
"""
The src image is offset vertically by caption_height pixels, so we normalize that to
get the y offset, add that to the upper & lower coordinates, & renormalize with the
new height. The x dimension is unaffected
"""
left_f, upper_f, right_f, lower_f = bbox
y_off = caption_height / src_h
new_h = 1.0 + y_off
return left_f, (upper_f + y_off) / new_h, right_f, (lower_f + y_off) / new_h
def overlay_onto_background_image_bboxes_helper(
bbox: Tuple, overlay_size: float, x_pos: float, y_pos: float, **kwargs
) -> Tuple:
"""
The src image is overlaid on the dst image offset by (`x_pos`, `y_pos`) & with a
size of `overlay_size` (all relative to the dst image dimensions). So the bounding
box is also offset by (`x_pos`, `y_pos`) & scaled by `overlay_size`. It is also
possible that some of the src image will be cut off, so we take the max with 0/min
with 1 in order to crop the bbox if needed
"""
left_factor, upper_factor, right_factor, lower_factor = bbox
return (
max(0, left_factor * overlay_size + x_pos),
max(0, upper_factor * overlay_size + y_pos),
min(1, right_factor * overlay_size + x_pos),
min(1, lower_factor * overlay_size + y_pos),
)
def overlay_image_bboxes_helper(
bbox: Tuple,
opacity: float,
overlay_size: float,
x_pos: float,
y_pos: float,
max_visible_opacity: float,
**kwargs,
) -> Tuple:
"""
We made a few decisions for this augmentation about how bboxes are defined:
1. If `opacity` < `max_visible_opacity` (default 0.75, can be specified by the user),
the bbox stays the same because it is still considered "visible" behind the
overlaid image
2. If the entire bbox is covered by the overlaid image, the bbox is no longer valid
so we return it as (0, 0, 0, 0), which will be turned to None in `check_bboxes()`
3. If the entire bottom of the bbox is covered by the overlaid image
(i.e. `x_pos < left_factor` & `x_pos + overlay_size > right_factor` &
`y_pos + overlay_size > lower_factor`), we crop out the lower part of the bbox
that is covered. The analogue is true for the top/left/right being occluded
4. If just the middle of the bbox is covered or a rectangle is sliced out of the
bbox, we consider that the bbox is unchanged, even though part of it is occluded.
This isn't ideal but otherwise it's very complicated; we could split the
remaining area into smaller visible bboxes, but then we would have to return
multiple dst bboxes corresponding to one src bbox
"""
left_factor, upper_factor, right_factor, lower_factor = bbox
if opacity >= max_visible_opacity:
occluded_left = x_pos < left_factor
occluded_upper = y_pos < upper_factor
occluded_right = x_pos + overlay_size > right_factor
occluded_lower = y_pos + overlay_size > lower_factor
if occluded_left and occluded_right:
# If the bbox is completely covered, it's no longer valid so return zeros
if occluded_upper and occluded_lower:
return (0.0, 0.0, 0.0, 0.0)
if occluded_lower:
lower_factor = y_pos
elif occluded_upper:
upper_factor = y_pos + overlay_size
elif occluded_upper and occluded_lower:
if occluded_right:
right_factor = x_pos
elif occluded_left:
left_factor = x_pos + overlay_size
return left_factor, upper_factor, right_factor, lower_factor
def overlay_onto_screenshot_bboxes_helper(
bbox: Tuple,
src_w: int,
src_h: int,
template_filepath: str,
template_bboxes_filepath: str,
resize_src_to_match_template: bool,
max_image_size_pixels: int,
crop_src_to_fit: bool,
**kwargs,
) -> Tuple:
"""
We transform the bbox by applying all the same transformations as are applied in the
`overlay_onto_screenshot` function, each of which is mentioned below in comments
"""
left_f, upper_f, right_f, lower_f = bbox
template, tbbox = imutils.get_template_and_bbox(
template_filepath, template_bboxes_filepath
)
# Either src image or template image is scaled
if resize_src_to_match_template:
tbbox_w, tbbox_h = tbbox[2] - tbbox[0], tbbox[3] - tbbox[1]
src_scale_factor = min(tbbox_w / src_w, tbbox_h / src_h)
else:
template, tbbox = imutils.scale_template_image(
src_w,
src_h,
template,
tbbox,
max_image_size_pixels,
crop_src_to_fit,
)
tbbox_w, tbbox_h = tbbox[2] - tbbox[0], tbbox[3] - tbbox[1]
src_scale_factor = 1
template_w, template_h = template.size
x_off, y_off = tbbox[:2]
# Src image is scaled (if resize_src_to_match_template)
curr_w, curr_h = src_w * src_scale_factor, src_h * src_scale_factor
left, upper, right, lower = (
left_f * curr_w,
upper_f * curr_h,
right_f * curr_w,
lower_f * curr_h,
)
# Src image is cropped to (tbbox_w, tbbox_h)
if crop_src_to_fit:
dx, dy = (curr_w - tbbox_w) // 2, (curr_h - tbbox_h) // 2
x1, y1, x2, y2 = dx, dy, dx + tbbox_w, dy + tbbox_h
left_f, upper_f, right_f, lower_f = crop_bboxes_helper(
bbox, x1 / curr_w, y1 / curr_h, x2 / curr_w, y2 / curr_h
)
left, upper, right, lower = (
left_f * tbbox_w,
upper_f * tbbox_h,
right_f * tbbox_w,
lower_f * tbbox_h,
)
# Src image is resized to (tbbox_w, tbbox_h)
else:
resize_f = min(tbbox_w / curr_w, tbbox_h / curr_h)
left, upper, right, lower = (
left * resize_f,
upper * resize_f,
right * resize_f,
lower * resize_f,
)
curr_w, curr_h = curr_w * resize_f, curr_h * resize_f
# Padding with black
padding_x = max(0, (tbbox_w - curr_w) // 2)
padding_y = max(0, (tbbox_h - curr_h) // 2)
left, upper, right, lower = (
left + padding_x,
upper + padding_y,
right + padding_x,
lower + padding_y,
)
# Src image is overlaid onto template image
left, upper, right, lower = (
left + x_off,
upper + y_off,
right + x_off,
lower + y_off,
)
return left / template_w, upper / template_h, right / template_w, lower / template_h
def pad_bboxes_helper(bbox: Tuple, w_factor: float, h_factor: float, **kwargs) -> Tuple:
"""
The src image is padded horizontally with w_factor * src_w, so the bbox gets shifted
over by w_factor and then renormalized over the new width. Vertical padding is
analogous
"""
left_factor, upper_factor, right_factor, lower_factor = bbox
new_w = 1 + 2 * w_factor
new_h = 1 + 2 * h_factor
return (
(left_factor + w_factor) / new_w,
(upper_factor + h_factor) / new_h,
(right_factor + w_factor) / new_w,
(lower_factor + h_factor) / new_h,
)
def pad_square_bboxes_helper(bbox: Tuple, src_w: int, src_h: int, **kwargs) -> Tuple:
"""
In pad_square, pad is called with w_factor & h_factor computed as follows, so we can
use the `pad_bboxes_helper` function to transform the bbox
"""
w_factor, h_factor = 0, 0
if src_w < src_h:
w_factor = (src_h - src_w) / (2 * src_w)
else:
h_factor = (src_w - src_h) / (2 * src_h)
return pad_bboxes_helper(bbox, w_factor=w_factor, h_factor=h_factor)
def perspective_transform_bboxes_helper(
bbox: Tuple,
src_w: int,
src_h: int,
sigma: float,
dx: float,
dy: float,
crop_out_black_border: bool,
seed: Optional[int],
**kwargs,
) -> Tuple:
"""
Computes the bbox that encloses the bbox in the perspective transformed image. Also
uses the `crop_bboxes_helper` function since the image is cropped if
`crop_out_black_border` is True.
"""
def transform(x: float, y: float, a: List[float]) -> Tuple:
"""
Transforms a point in the image given the perspective transform matrix; we will
use this to transform the bounding box corners. Based on PIL source code:
https://github.com/python-pillow/Pillow/blob/master/src/libImaging/Geometry.c#L399
"""
return (
(a[0] * x + a[1] * y + a[2]) / (a[6] * x + a[7] * y + a[8]),
(a[3] * x + | |
'jiè',
0x86A8: 'fú',
0x86A9: 'chī',
0x86AA: 'dǒu',
0x86AB: 'bào',
0x86AC: 'xiǎn',
0x86AD: 'ní',
0x86AE: 'dài,dé',
0x86AF: 'qiū',
0x86B0: 'yóu',
0x86B1: 'zhà',
0x86B2: 'píng',
0x86B3: 'chí',
0x86B4: 'yòu',
0x86B5: 'kē',
0x86B6: 'hān',
0x86B7: 'jù',
0x86B8: 'lì',
0x86B9: 'fù',
0x86BA: 'rán',
0x86BB: 'zhá',
0x86BC: 'gǒu,qú,xù',
0x86BD: 'pí',
0x86BE: 'pí,bǒ',
0x86BF: 'xián',
0x86C0: 'zhù',
0x86C1: 'diāo',
0x86C2: 'bié',
0x86C3: 'bīng',
0x86C4: 'gū',
0x86C5: 'zhān',
0x86C6: 'qū',
0x86C7: 'shé,yí',
0x86C8: 'tiě',
0x86C9: 'líng',
0x86CA: 'gǔ',
0x86CB: 'dàn',
0x86CC: 'tún',
0x86CD: 'yíng',
0x86CE: 'lì',
0x86CF: 'chēng',
0x86D0: 'qū',
0x86D1: 'móu',
0x86D2: 'gé,luò',
0x86D3: 'cì',
0x86D4: 'huí',
0x86D5: 'huí',
0x86D6: 'máng,bàng',
0x86D7: 'fù',
0x86D8: 'yáng',
0x86D9: 'wā',
0x86DA: 'liè',
0x86DB: 'zhū',
0x86DC: 'yī',
0x86DD: 'xián',
0x86DE: 'kuò',
0x86DF: 'jiāo',
0x86E0: 'lì',
0x86E1: 'yì,xǔ',
0x86E2: 'píng',
0x86E3: 'jié',
0x86E4: 'gé,há',
0x86E5: 'shé',
0x86E6: 'yí',
0x86E7: 'wǎng',
0x86E8: 'mò',
0x86E9: 'qióng',
0x86EA: 'qiè,ní',
0x86EB: 'guǐ',
0x86EC: 'qióng',
0x86ED: 'zhì',
0x86EE: 'mán',
0x86EF: 'lǎo',
0x86F0: 'zhé',
0x86F1: 'jiá',
0x86F2: 'náo',
0x86F3: 'sī',
0x86F4: 'qí',
0x86F5: 'xíng',
0x86F6: 'jiè',
0x86F7: 'qiú',
0x86F8: 'xiāo,shāo',
0x86F9: 'yǒng',
0x86FA: 'jiá',
0x86FB: 'tuì',
0x86FC: 'chē',
0x86FD: 'bèi',
0x86FE: 'é,yǐ',
0x86FF: 'hàn',
0x8700: 'shǔ',
0x8701: 'xuán',
0x8702: 'fēng',
0x8703: 'shèn',
0x8704: 'shèn',
0x8705: 'fǔ',
0x8706: 'xiǎn',
0x8707: 'zhé',
0x8708: 'wú',
0x8709: 'fú',
0x870A: 'lì',
0x870B: 'láng',
0x870C: 'bì',
0x870D: 'chú',
0x870E: 'yuān',
0x870F: 'yǒu',
0x8710: 'jié',
0x8711: 'dàn',
0x8712: 'yán',
0x8713: 'tíng',
0x8714: 'diàn',
0x8715: 'tuì',
0x8716: 'huí',
0x8717: 'wō',
0x8718: 'zhī',
0x8719: 'zhōng',
0x871A: 'fēi',
0x871B: 'jū',
0x871C: 'mì',
0x871D: 'qí',
0x871E: 'qí',
0x871F: 'yù',
0x8720: 'jùn',
0x8721: 'là,zhà',
0x8722: 'měng',
0x8723: 'qiāng',
0x8724: 'sī',
0x8725: 'xī',
0x8726: 'lún',
0x8727: 'lì',
0x8728: 'dié',
0x8729: 'tiáo',
0x872A: 'táo',
0x872B: 'kūn',
0x872C: 'hán',
0x872D: 'hàn',
0x872E: 'yù',
0x872F: 'bàng',
0x8730: 'féi',
0x8731: 'pí',
0x8732: 'wēi',
0x8733: 'dūn',
0x8734: 'yì',
0x8735: 'yuān',
0x8736: 'suò',
0x8737: 'quán',
0x8738: 'qiǎn',
0x8739: 'ruì',
0x873A: 'ní',
0x873B: 'qīng',
0x873C: 'wèi',
0x873D: 'liǎng',
0x873E: 'guǒ',
0x873F: 'wān',
0x8740: 'dōng',
0x8741: 'è',
0x8742: 'bǎn',
0x8743: 'dì',
0x8744: 'wǎng',
0x8745: 'cán',
0x8746: 'yǎng',
0x8747: 'yíng',
0x8748: 'guō',
0x8749: 'chán',
0x874A: 'dìng',
0x874B: 'là',
0x874C: 'kē',
0x874D: 'jí',
0x874E: 'xiē',
0x874F: 'tíng',
0x8750: 'mào',
0x8751: 'xū',
0x8752: 'mián',
0x8753: 'yú',
0x8754: 'jiē',
0x8755: 'shí',
0x8756: 'xuān',
0x8757: 'huáng',
0x8758: 'yǎn',
0x8759: 'biān',
0x875A: 'róu',
0x875B: 'wēi',
0x875C: 'fù',
0x875D: 'yuán',
0x875E: 'mèi',
0x875F: 'wèi',
0x8760: 'fú',
0x8761: 'rú,ruăn',
0x8762: 'xié',
0x8763: 'yóu',
0x8764: 'qiú,yóu',
0x8765: 'máo',
0x8766: 'xiā,hā',
0x8767: 'yīng',
0x8768: 'shī',
0x8769: 'chóng',
0x876A: 'tāng',
0x876B: 'zhū',
0x876C: 'zōng',
0x876D: 'dì',
0x876E: 'fù',
0x876F: 'yuán',
0x8770: 'kuí',
0x8771: 'méng',
0x8772: 'là',
0x8773: 'dài',
0x8774: 'hú',
0x8775: 'qiū',
0x8776: 'dié',
0x8777: 'lì',
0x8778: 'wō',
0x8779: 'yūn',
0x877A: 'qǔ',
0x877B: 'nǎn',
0x877C: 'lóu',
0x877D: 'chūn',
0x877E: 'róng',
0x877F: 'yíng',
0x8780: 'jiāng',
0x8781: 'tuì,bān',
0x8782: 'láng',
0x8783: 'páng',
0x8784: 'sī',
0x8785: 'xī',
0x8786: 'cì',
0x8787: 'xī,qī',
0x8788: 'yuán',
0x8789: 'wēng',
0x878A: 'lián',
0x878B: 'sōu',
0x878C: 'bān',
0x878D: 'róng',
0x878E: 'róng',
0x878F: 'jí',
0x8790: 'wū',
0x8791: 'xiù',
0x8792: 'hàn',
0x8793: 'qín',
0x8794: 'yí',
0x8795: 'bī,pí',
0x8796: 'huá',
0x8797: 'táng',
0x8798: 'yǐ',
0x8799: 'dù',
0x879A: 'nài,něng',
0x879B: 'hé,xiá',
0x879C: 'hú',
0x879D: 'guì,huǐ',
0x879E: 'mǎ,mā,mà',
0x879F: 'míng',
0x87A0: 'yì',
0x87A1: 'wén',
0x87A2: 'yíng',
0x87A3: 'téng',
0x87A4: 'zhōng',
0x87A5: 'cāng',
0x87A6: 'sāo',
0x87A7: 'qí',
0x87A8: 'mǎn',
0x87A9: 'dāo',
0x87AA: 'shāng',
0x87AB: 'shì,zhē',
0x87AC: 'cáo',
0x87AD: 'chī',
0x87AE: 'dì',
0x87AF: 'áo',
0x87B0: 'lù',
0x87B1: 'wèi',
0x87B2: 'dié,zhì',
0x87B3: 'táng',
0x87B4: 'chén',
0x87B5: 'piāo',
0x87B6: 'qú,jù',
0x87B7: 'pí',
0x87B8: 'yú',
0x87B9: 'chán,jiàn',
0x87BA: 'luó',
0x87BB: 'lóu',
0x87BC: 'qǐn',
0x87BD: 'zhōng',
0x87BE: 'yǐn',
0x87BF: 'jiāng',
0x87C0: 'shuài',
0x87C1: 'wén',
0x87C2: 'xiāo',
0x87C3: 'wàn',
0x87C4: 'zhé',
0x87C5: 'zhè',
0x87C6: 'má,mò',
0x87C7: 'má',
0x87C8: 'guō',
0x87C9: 'liú',
0x87CA: 'máo',
0x87CB: 'xī',
0x87CC: 'cōng',
0x87CD: 'lí',
0x87CE: 'mǎn',
0x87CF: 'xiāo',
0x87D0: 'chán',
0x87D1: 'zhāng',
0x87D2: 'mǎng,měng',
0x87D3: 'xiàng',
0x87D4: 'mò',
0x87D5: 'zuī',
0x87D6: 'sī',
0x87D7: 'qiū',
0x87D8: 'tè',
0x87D9: 'zhí',
0x87DA: 'péng',
0x87DB: 'péng',
0x87DC: 'jiǎo',
0x87DD: 'qú',
0x87DE: 'biē,bié',
0x87DF: 'liáo',
0x87E0: 'pán',
0x87E1: 'guǐ',
0x87E2: 'xǐ',
0x87E3: 'jǐ',
0x87E4: 'zhuān',
0x87E5: 'huáng',
0x87E6: 'fèi,bēn',
0x87E7: 'láo,liáo',
0x87E8: 'jué',
0x87E9: 'jué',
0x87EA: 'huì',
0x87EB: 'yín,xún',
0x87EC: 'chán',
0x87ED: 'jiāo',
0x87EE: 'shàn',
0x87EF: 'náo',
0x87F0: 'xiāo',
0x87F1: 'wú',
0x87F2: 'chóng',
0x87F3: 'xún',
0x87F4: 'sī',
0x87F5: 'chú',
0x87F6: 'chēng',
0x87F7: 'dāng',
0x87F8: 'lí',
0x87F9: 'xiè',
0x87FA: 'shàn',
0x87FB: 'yǐ',
0x87FC: 'jǐng',
0x87FD: 'dá',
0x87FE: 'chán',
0x87FF: 'qì',
0x8800: 'cī',
0x8801: 'xiǎng',
0x8802: 'shè',
0x8803: 'luǒ',
0x8804: 'qín',
0x8805: 'yíng',
0x8806: 'chài',
0x8807: 'lì',
0x8808: 'zéi',
0x8809: 'xuān',
0x880A: 'lián',
0x880B: 'zhú',
0x880C: 'zé',
0x880D: 'xiē',
0x880E: 'mǎng',
0x880F: 'xiè',
0x8810: 'qí',
0x8811: 'róng',
0x8812: 'jiǎn',
0x8813: 'měng',
0x8814: 'háo',
0x8815: 'rú',
0x8816: 'huò',
0x8817: 'zhuó',
0x8818: 'jié',
0x8819: 'pín',
0x881A: 'hē',
0x881B: 'miè',
0x881C: 'fán',
0x881D: 'lěi',
0x881E: 'jié',
0x881F: 'là',
0x8820: 'mǐn',
0x8821: 'lǐ',
0x8822: 'chǔn',
0x8823: 'lì',
0x8824: 'qiū',
0x8825: 'niè',
0x8826: 'lú',
0x8827: 'dù',
0x8828: 'xiāo',
0x8829: 'zhū',
0x882A: 'lóng',
0x882B: 'lí',
0x882C: 'lóng',
0x882D: 'fēng',
0x882E: 'yē',
0x882F: 'pí',
0x8830: 'náng',
0x8831: 'gǔ',
0x8832: 'juān',
0x8833: 'yīng',
0x8834: 'shǔ',
0x8835: 'xī',
0x8836: 'cán',
0x8837: 'qú',
0x8838: 'quán',
0x8839: 'dù',
0x883A: 'cán',
0x883B: 'mán',
0x883C: 'qú',
0x883D: 'jié',
0x883E: 'zhú',
0x883F: 'zhuó',
0x8840: 'xiě,xuè',
0x8841: 'huāng',
0x8842: 'nǜ',
0x8843: 'pēi',
0x8844: 'nǜ',
0x8845: 'xìn',
0x8846: 'zhòng',
0x8847: 'mài',
0x8848: 'ěr',
0x8849: 'kè',
0x884A: 'miè',
0x884B: 'xì',
0x884C: 'háng,xíng,héng,hàng',
0x884D: 'yǎn',
0x884E: 'kàn',
0x884F: 'yuàn',
0x8850: 'qú',
0x8851: 'líng',
0x8852: 'xuàn',
0x8853: 'shù',
0x8854: 'xián',
0x8855: 'tòng',
0x8856: 'xiàng',
0x8857: 'jiē',
0x8858: 'xián',
0x8859: 'yá',
0x885A: 'hú',
0x885B: 'wèi',
0x885C: 'dào',
0x885D: 'chōng',
0x885E: 'wèi',
0x885F: 'dào',
0x8860: 'zhūn',
0x8861: 'héng',
0x8862: 'qú',
0x8863: 'yī',
0x8864: 'yī',
0x8865: 'bǔ',
0x8866: 'gǎn',
0x8867: 'yú',
0x8868: 'biǎo',
0x8869: 'chà',
0x886A: 'yì',
0x886B: 'shān',
0x886C: 'chèn',
0x886D: 'fū',
0x886E: 'gǔn',
0x886F: 'fēn',
0x8870: 'shuāi,cuī',
0x8871: 'jié',
0x8872: 'nà',
0x8873: 'zhōng',
0x8874: 'dǎn',
0x8875: 'rì',
0x8876: 'zhòng',
0x8877: 'zhōng',
0x8878: 'jiè',
0x8879: 'zhǐ',
0x887A: 'xié',
0x887B: 'rán',
0x887C: 'zhī',
0x887D: 'rèn',
0x887E: 'qīn',
0x887F: 'jīn',
0x8880: 'jūn',
0x8881: 'yuán',
0x8882: 'mèi',
0x8883: 'chài',
0x8884: 'ǎo',
0x8885: 'niǎo',
0x8886: 'huī',
0x8887: 'rán',
0x8888: 'jiā',
0x8889: 'tuó,tuō',
0x888A: 'lǐng,líng',
0x888B: 'dài',
0x888C: 'bào,páo,pào',
0x888D: 'páo',
0x888E: 'yào',
0x888F: 'zuò',
0x8890: 'bì',
0x8891: 'shào',
0x8892: 'tǎn',
0x8893: 'jù,jiē',
0x8894: 'hè,kè',
0x8895: 'xué',
0x8896: 'xiù',
0x8897: 'zhěn',
0x8898: 'yí,yì',
0x8899: 'pà',
0x889A: 'fú',
0x889B: 'dī',
0x889C: 'wà',
0x889D: 'fù',
0x889E: 'gǔn',
0x889F: 'zhì',
0x88A0: 'zhì',
0x88A1: 'rán',
0x88A2: 'pàn',
0x88A3: 'yì',
0x88A4: 'mào',
0x88A5: 'tuō',
0x88A6: 'nà,jué',
0x88A7: 'gōu',
0x88A8: 'xuàn',
0x88A9: 'zhé',
0x88AA: 'qū',
0x88AB: 'bèi,pī',
0x88AC: 'yù',
0x88AD: 'xí',
0x88AE: 'mí',
0x88AF: 'bó',
0x88B0: 'bō',
0x88B1: 'fú',
0x88B2: 'chǐ,nuǒ',
0x88B3: 'chǐ,qǐ,duǒ,nuǒ',
0x88B4: 'kù',
0x88B5: 'rèn',
0x88B6: 'péng',
0x88B7: 'jiá,jié,qiā',
0x88B8: 'jiàn,zùn',
0x88B9: 'bó,mò',
0x88BA: 'jié',
0x88BB: 'ér',
0x88BC: 'gē',
0x88BD: 'rú',
0x88BE: 'zhū',
0x88BF: 'guī,guà',
0x88C0: 'yīn',
0x88C1: 'cái',
0x88C2: 'liè,liě',
0x88C3: 'kǎ',
0x88C4: 'háng',
0x88C5: 'zhuāng',
0x88C6: 'dāng',
0x88C7: 'xū',
0x88C8: 'kūn',
0x88C9: 'kèn',
0x88CA: 'niǎo',
0x88CB: 'shù',
0x88CC: 'jiá',
0x88CD: 'kǔn',
0x88CE: 'chéng,chěng',
0x88CF: 'lǐ',
0x88D0: 'juān',
0x88D1: 'shēn',
0x88D2: 'póu',
0x88D3: 'gé,jiē',
0x88D4: 'yì',
0x88D5: 'yù',
0x88D6: 'zhěn',
0x88D7: 'liú',
0x88D8: 'qiú',
0x88D9: 'qún',
0x88DA: 'jì',
0x88DB: 'yì',
0x88DC: 'bǔ',
0x88DD: 'zhuāng',
0x88DE: 'shuì',
0x88DF: 'shā',
0x88E0: 'qún',
0x88E1: 'lǐ',
0x88E2: 'lián',
0x88E3: 'liǎn',
0x88E4: 'kù',
0x88E5: 'jiǎn',
0x88E6: 'bāo',
0x88E7: 'chān',
0x88E8: 'bì,pí',
0x88E9: 'kūn',
0x88EA: 'táo',
0x88EB: 'yuàn',
0x88EC: 'líng',
0x88ED: 'chǐ',
0x88EE: 'chāng',
0x88EF: 'chóu,dāo',
0x88F0: 'duō',
0x88F1: 'biǎo',
0x88F2: 'liǎng',
0x88F3: 'cháng,shang',
0x88F4: 'péi',
0x88F5: 'péi',
0x88F6: 'fēi',
0x88F7: 'yuān,gǔn',
0x88F8: 'luǒ',
0x88F9: 'guǒ',
0x88FA: 'yǎn,ān',
0x88FB: 'dú',
0x88FC: 'xī,tì',
0x88FD: 'zhì',
0x88FE: 'jū',
0x88FF: 'yǐ',
0x8900: 'qí',
0x8901: 'guǒ',
0x8902: 'guà',
0x8903: 'kèn',
0x8904: 'qī',
0x8905: 'tì',
0x8906: 'tí',
0x8907: 'fù',
0x8908: 'chóng',
0x8909: 'xiè',
0x890A: 'biǎn',
0x890B: 'dié',
0x890C: 'kūn',
0x890D: 'duān',
0x890E: 'xiù,yòu',
0x890F: 'xiù',
0x8910: 'hè',
0x8911: 'yuàn',
0x8912: 'bāo',
0x8913: 'bǎo',
0x8914: 'fù,fú',
0x8915: 'yú',
0x8916: 'tuàn',
0x8917: 'yǎn',
0x8918: 'huī',
0x8919: 'bèi',
0x891A: 'zhǔ,chǔ',
0x891B: 'lǚ',
0x891C: 'páo',
0x891D: 'dān',
0x891E: 'yùn',
0x891F: 'tā',
0x8920: 'gōu',
0x8921: 'dā',
0x8922: 'huái',
0x8923: 'róng',
0x8924: 'yuán',
0x8925: 'rù',
0x8926: 'nài',
0x8927: | |
import random
import numpy as np
import itertools
import re
from collections import defaultdict
import os
def get_tags(s, open_delim='<', close_delim='/>'):
"""Iterator to spit out the xml style disfluency tags in a given string.
Keyword arguments:
s -- input string
"""
while True:
# Search for the next two delimiters in the source text
start = s.find(open_delim)
end = s.find(close_delim)
# We found a non-empty match
if -1 < start < end:
# Skip the length of the open delimiter
start += len(open_delim)
# Spit out the tag
yield open_delim + s[start:end].strip() + close_delim
# Truncate string to start from last match
s = s[end+len(close_delim):]
else:
return
def remove_uttseg_tag(tag):
tags = get_tags(tag)
final_tag = ""
for t in tags:
m = re.search(r'<[ct]*/>', t)
if m:
continue
final_tag += t
return final_tag
def convert_to_simple_label(tag, rep="disf1_uttseg"):
"""Takes the complex tag set and gives back the simple,
smaller version with ten tags:
"""
disftag = "<f/>"
if "<rm-" in tag:
disftag = "<rm-0/>"
elif "<e" in tag:
disftag = "<e/>"
if "uttseg" in rep: # if combined task with TTO
m = re.search(r'<[ct]*/>', tag)
if m:
return disftag + m.group(0)
else:
print("WARNING NO TAG", +tag)
return ""
return disftag # if not TT0
def convert_to_simple_idx(tag, rep='1_trp'):
tag = convert_to_simple_label(tag, rep)
simple_tags = """<e/><cc/>
<e/><ct/>
<e/><tc/>
<e/><tt/>
<f/><cc/>
<f/><ct/>
<f/><tc/>
<f/><tt/>
<rm-0/><cc/>
<rm-0/><ct/>""".split("\n")
simple_tag_dict = {}
for s in range(0, len(simple_tags)):
simple_tag_dict[simple_tags[s].strip()] = s
return simple_tag_dict[tag]
def convert_from_full_tag_set_to_idx(tag, rep, idx_to_label):
"""Maps from the full tag set of trp repairs to the new dictionary"""
if "simple" in rep:
tag = convert_to_simple_label(tag)
for k, v in idx_to_label.items():
if v in tag: # a substring relation
return k
def add_word_continuation_tags(tags):
"""In place, add a continutation tag to each word:
<cc/> -word continues current dialogue act and the next word will also
continue it
<ct/> -word continues current dialogue act and is the last word of it
<tc/> -word starts this dialogue act tag and the next word continues it
<tt/> -word starts and ends dialogue act (single word dialogue act)
"""
tags = list(tags)
for i in range(0, len(tags)):
if i == 0:
tags[i] = tags[i] + "<t"
else:
tags[i] = tags[i] + "<c"
if i == len(tags)-1:
tags[i] = tags[i] + "t/>"
else:
tags[i] = tags[i] + "c/>"
return tags
def verify_disfluency_tags(tags, normalize_ID=False):
"""Check that the repair tags sequence is valid.
Keyword arguments:
normalize_ID -- boolean, whether to convert the repair ID
numbers to be derivable from their unique RPS position in the utterance.
"""
id_map = dict() # map between old ID and new ID
# in first pass get old and new IDs
for i in range(0, len(tags)):
rps = re.findall("<rps id\=\"[0-9]+\"\/>", tags[i])
if rps:
id_map[rps[0][rps[0].find("=")+2:-3]] = str(i)
# key: old repair ID, value, list [reparandum,interregnum,repair]
# all True when repair is all there
repairs = defaultdict(list)
for r in id_map.keys():
repairs[r] = [None, None, None] # three valued None<False<True
# print(repairs)
# second pass verify the validity of the tags
# and (optionally) modify the IDs
for i in range(0, len(tags)): # iterate over all tag strings
new_tags = []
if tags[i] == "":
assert(all([repairs[ID][2] or
repairs[ID] == [None, None, None]
for ID in repairs.keys()])),\
"Unresolved repairs at fluent tag\n\t" + str(repairs)
for tag in get_tags(tags[i]): # iterate over all tags
# print(i)
# print(tag)
if tag == "<e/>":
new_tags.append(tag)
continue
ID = tag[tag.find("=")+2:-3]
if "<rms" in tag:
assert repairs[ID][0] == None,\
"reparandum started parsed more than once " + ID
assert repairs[ID][1] == None,\
"reparandum start again during interregnum phase " + ID
assert repairs[ID][2] == None,\
"reparandum start again during repair phase " + ID
repairs[ID][0] = False # set in progress
elif "<rm " in tag:
assert repairs[ID][0] != None,\
"mid reparandum tag before reparandum start " + ID
assert repairs[ID][2] == None,\
"mid reparandum tag in a interregnum phase or beyond " + ID
assert repairs[ID][2] == None,\
"mid reparandum tag in a repair phase or beyond " + ID
elif "<i" in tag:
assert repairs[ID][0] != None,\
"interregnum start before reparandum start " + ID
assert repairs[ID][2] == None,\
"interregnum in a repair phase " + ID
if repairs[ID][1] == None: # interregnum not reached yet
repairs[ID][0] = True # reparandum completed
repairs[ID][1] = False # interregnum in progress
elif "<rps" in tag:
assert repairs[ID][0] != None,\
"repair start before reparandum start " + ID
assert repairs[ID][1] != True,\
"interregnum over before repair start " + ID
assert repairs[ID][2] == None,\
"repair start parsed twice " + ID
repairs[ID][0] = True # reparanudm complete
repairs[ID][1] = True # interregnum complete
repairs[ID][2] = False # repair in progress
elif "<rp " in tag:
assert repairs[ID][0] == True,\
"mid repair word start before reparandum end " + ID
assert repairs[ID][1] == True,\
"mid repair word start before interregnum end " + ID
assert repairs[ID][2] == False,\
"mid repair tag before repair start tag " + ID
elif "<rpn" in tag:
# make sure the rps is order in tag string is before
assert repairs[ID][0] == True,\
"repair end before reparandum end " + ID
assert repairs[ID][1] == True,\
"repair end before interregnum end " + ID
assert repairs[ID][2] == False,\
"repair end before repair start " + ID
repairs[ID][2] = True
# do the replacement of the tag's ID after checking
new_tags.append(tag.replace(ID, id_map[ID]))
if normalize_ID:
tags[i] = "".join(new_tags)
assert all([repairs[ID][2] for ID in repairs.keys()]),\
"Unresolved repairs:\n\t" + str(repairs)
def shuffle(lol, seed):
"""Shuffle inplace each list in the same order.
lol :: list of list as input
seed :: seed the shuffling
"""
for l in lol:
random.seed(seed)
random.shuffle(l)
def minibatch(l, bs):
"""Returns a list of minibatches of indexes
which size is equal to bs
border cases are treated as follow:
eg: [0,1,2,3] and bs = 3
will output:
[[0],[0,1],[0,1,2],[1,2,3]]
l :: list of word idxs
"""
out = [l[:i] for i in xrange(1, min(bs, len(l)+1))]
out += [l[i-bs:i] for i in xrange(bs, len(l)+1)]
assert len(l) == len(out)
return out
def indices_from_length(sentence_length, bs, start_index=0):
"""Return a list of indexes pairs (start/stop) for each word
max difference between start and stop equal to bs
border cases are treated as follow:
eg: sentenceLength=4 and bs = 3
will output:
[[0,0],[0,1],[0,2],[1,3]]
"""
l = map(lambda x: start_index+x, xrange(sentence_length))
out = []
for i in xrange(0, min(bs, len(l))):
out.append([l[0], l[i]])
for i in xrange(bs+1, len(l)+1):
out.append([l[i-bs], l[i-1]])
assert len(l) == sentence_length
return out
def context_win(l, win):
"""Return a list of list of indexes corresponding
to context windows surrounding each word in the sentence
given a list of indexes composing a sentence.
win :: int corresponding to the size of the window
"""
assert (win % 2) == 1
assert win >= 1
l = list(l)
lpadded = win/2 * [-1] + l + win/2 * [-1]
out = [lpadded[i:i+win] for i in range(len(l))]
assert len(out) == len(l)
return out
def context_win_backwards(l, win):
'''Same as contextwin except only backwards context
(i.e. like an n-gram model)
'''
assert win >= 1
l = list(l)
lpadded = (win-1) * [-1] + l
out = [lpadded[i: i+win] for i in range(len(l))]
assert len(out) == len(l)
return out
def corpus_to_indexed_matrix(my_array_list, win, bs, sentence=False):
"""Returns a matrix of contextwins for a list of utterances of
dimensions win * n_words_in_corpus
(i.e. total length of all arrays in my_array_list)
and corresponding matrix of indexes (of just start/stop for each one)
so 2 * n_words_in_corpus
of where to access these, using bs (backprop distance)
as the limiting history size
"""
sentences = [] # a list (of arrays, or lists?), returned as matrix
indices = [] # a list of index pairs (arrays?), returned as matrix
totalSize = 0
if sentence:
for sent in my_array_list:
mysent = np.asarray([-1] * (bs-1) + list(sent)) # padding with eos
# get list of context windows
mywords = context_win_backwards(mysent, win)
# just one per utterance for now..
cindices = [[totalSize, totalSize+len(mywords)-1]]
cwords = []
for i in | |
<filename>code/client/client.py
import struct
import hashlib
import math
import requests
import json
import web3
import util
""" Bitcoin header constants """
HDR_LEN=80
NVERSION_LEN=4
HASHPREVBLOCK_LEN=32
HASHMERKLEROOT_LEN=32
NTIME_LEN=4
NBITS_LEN=4
NNONCE_LEN=4
assert ( NVERSION_LEN +
HASHPREVBLOCK_LEN +
HASHMERKLEROOT_LEN +
NTIME_LEN +
NBITS_LEN +
NNONCE_LEN ) == HDR_LEN
""" Coinbase transaction constants """
CB_TXHASH = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
CB_TXIDX = 0xffffffff
""" Difficulty constants """
# H(block_header) <= TARGET
# difficulty = MAX_TARGET / CURRENT_TARGET
# Therefore lowest difficulty is 1, at the largest possible target
MAX_PTARGET = 0x00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF # biggest allowed value for TARGET in Bitcoin pooled mining
MAX_BTARGET = 0x00000000FFFF0000000000000000000000000000000000000000000000000000 # biggest allowed value for TARGET in Bitcoin because of nBits decoding to reconstruct target
MAX_REGTEST_TARGET = 0x7fffff0000000000000000000000000000000000000000000000000000000000 # biggest allowed value for TARGET in Bitcoin regtest mode, nBits = b"\x20\x7f\xff\xff"
MAX_TEST_TARGET = 1<<255 # even bigger value for testing, almost every hash will be below this value
DIFFICULTY_PERIOD = 2016
# === utility methods ===
def dSHA256(v,raw=False,num=False):
""" Double SHA256 as for Bitcoin block hashses """
assert type(v) is bytes, "argument must be bytes"
h1 = hashlib.sha256()
h1.update(v)
d1 = h1.digest()
h2 = hashlib.sha256()
h2.update(d1)
if raw:
# big endian output ...
if num:
# ... as number
#return int(h2.digest().hex(),16)
return int.from_bytes(h2.digest(),"big")
else:
# ... as bytes
return h2.digest()
else:
# ... as hex string, "normal" represenation of hash in Bitcoin
#return int(h2.digest().hex(),16).to_bytes(32,"little").hex()
return dbytes_to_hexstr(h2.digest())
def dbytes_to_hexstr(h,swap=True):
""" conve rts and swaps bytes from digest to hex string representation of hash """
#return int(h.hex(),16).to_bytes(32,"little").hex() # also works
#return int.from_bytes(h,"big").to_bytes(32,"little").hex() # also works
if swap:
return endSwap(h).hex()
else:
return h.hex()
def hexstr_to_dbytes(h,swap=True):
""" converts and swaps hex string represenation of hash to bytes for generating digest """
if h[:2] == "0x":
h = h[2:]
if len(h)%2 != 0:
h = h.zfill(len(h)+1)
num_bytes = len(h)//2
if swap:
return int(h,16).to_bytes(num_bytes,"little")
else:
return int(h,16).to_bytes(num_bytes,"big")
def int_to_dbytes(h):
""" converts and swaps int representation of hash to bytes for generating digest """
return h.to_bytes(32,"little")
def dbytes_to_int(h):
""" converts bytes represenation of hash to int, without conversion """
return int.from_bytes(h,"big")
def endSwap(b):
""" change endianess of bytes """
if type(b) is bytes:
return bytes(reversed(b))
elif type(b) is bytearray:
return bytearray(reversed(b))
else:
assert False,"Type must be byte or bytearray!"
def tx_hashes_to_dbytes(tx_hashes):
""" Convert list of transaction hashes to list of swaped bytes values to feed into digest """
assert type(tx_hashes) is list,"Must be list of int or hex strings"
tx_hashes_dbytes = list()
for h in tx_hashes:
if type(h) is str:
tx_hashes_dbytes.append(hexstr_to_dbytes(h))
elif type(h) is int:
tx_hashes_dbytes.append(int_to_dbytes(h))
else:
assert False,"hashes must be int or hex string"
return tx_hashes_dbytes
def vint_to_int(vint):
""" parse bytes as var int an returns tuple of var int bytes to remove and var int value """
assert type(vint) == bytes,"vint must be bytes in little endian!"
if vint[0] < 0xFD:
return (1,vint[0]) # uint8_t
elif vint[0] == 0xFD:
return (3,struct.unpack("<H",vint[1:3])[0]) # uint16_t
elif vint[0] == 0xFE:
return (5,struct.unpack("<L",vint[1:5])[0]) # uint32_t
elif vint[0] == 0xFF:
return (9,struct.unpack("<Q",vint[1:9])[0]) # uint64_t
else:
assert False,"Invalid var_int! maybe fucked up endianess?"
def int_to_vint(integer):
""" return integer as bytes of var_int """
assert type(integer) is int,"integer must be int!"
if integer < 0xFD:
return integer.to_bytes(1,"little")
elif integer < 2**16:
return b"\xFD" + integer.to_bytes(2,"little")
elif integer < 2**32:
return b"\xFE" + integer.to_bytes(4,"little")
elif integer < 2**64:
return b"\xFF" + integer.to_bytes(8,"little")
else:
assert False,"Integer overflow, var_int to small to hold python integer!"
class NBitsDecodingExcpetion(Exception):
""" Class for custom nBits decoding excpetions """
pass
def nBits_to_Target(nBits,big_endian=True,strict=True):
"""
SetCompact handling in Bitcoin core:
https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L74
https://github.com/bitcoin/bitcoin/blob/46d6930f8c7ba7cbcd7d86dd5d0117642fcbc819/src/arith_uint256.h#L277
https://github.com/bitcoin/bitcoin/blob/46d6930f8c7ba7cbcd7d86dd5d0117642fcbc819/src/arith_uint256.cpp#L203
"""
assert type(nBits) is bytes, "Must be big-endian bytes or big_endian=False"
if not big_endian:
nBits = endSwap(nBits)
nCompact = int.from_bytes(nBits,"big")
exponent = nBits[0]
mantissa = int.from_bytes(nBits[1:],"big")
nWord = nCompact & 0x007fffff # remove exponent bits and sign bit, keep the rest as is
if (exponent <= 3):
nWord = nWord >> 8 * (3 - exponent)
else:
nWord = nWord << 8 * (exponent - 3)
T = nWord
#T = nWord % (2**256-1) # only needed if not strict
if strict and nWord != 0 and ( exponent > 34 or ( nWord > 0xff and exponent > 33 ) or ( nWord > 0xffff and exponent > 32 )):
# check if mantissa/significant is larger than what fits a 256 bit value,
# if so this indicates and error during parseing
raise NBitsDecodingExcpetion("Overflow! Recovered target > 256 bits!")
if strict and nWord != 0 and nCompact & 0x00800000 != 0:
# check if sign bit is set, if so this indicates an error during parsing
raise NBitsDecodingExcpetion("nBits is negative!")
return T
def within_difficulty_period(startBlkidx,endBlkidx):
""" Helper script to check if attack interval is between two difficulty adjustments.
i.e., no difficutly adjustments occures during attack
"""
assert startBlkidx < endBlkidx, "start not smaller than end block index"
delta = endBlkidx - startBlkidx
start = startBlkidx % DIFFICULTY_PERIOD
if start + delta < DIFFICULTY_PERIOD:
return True
else:
return False
def replace_found_bytes(old_hdr,find,replace=None):
""" Find and replace bytes, if replace is None they are zeroed out """
assert type(old_hdr) is bytes and type(find) is bytes, "Wrong input type"
assert len(old_hdr) >= len(find),"Find must be smaller or equal input bytes"
if (replace is None):
replace = b"\x00"*len(find)
else:
assert type(replace) is bytes, "Wrong input type"
assert len(find) == len(replace), "Find replace lenght not equal"
new_hdr = old_hdr.replace(find,replace)
return new_hdr
def replace_at_offset(hdr,offset,replace=None):
""" Replace bytes at offset, either with replacement bytes or given number of zero bytes """
if (type(replace) is int):
replace = b"\x00"*replace
assert type(replace) is bytes, "Wrong input type"
assert len(hdr) >= offset, "Offset to large"
new_hdr = bytearray(hdr)
for pos,octet in enumerate(replace):
new_hdr[offset + pos] = octet
return bytes(new_hdr)
# --- Merkle path generation and verification ---
def vrfy_mrkl_root(tx_hashes,hashMerkleRoot):
""" verify given Merkle tree root hash by recomputing Merkle tree
:param tx_hashes: List of tx hashes as baselayer of merkle tree
:type tx_hashes: list[bytes]
:param hashMerkleRoot: Merkle tree root hash
:type hashMerkleRoot: str
:return: True if the calculated hash matches the given one
:rtype: bool
"""
return mrkl_root(tx_hashes.copy()) == hashMerkleRoot
def mrkl_root(hashes):
""" compute Merkle tree root hash """
assert type(hashes[0]) is bytes,"tx_hashes must be little endian bytes"
if len(hashes) == 1:
#return int(hashes[0].hex(),16).to_bytes(32,"little").hex()
return dbytes_to_hexstr(hashes[0])
if len(hashes) % 2 != 0:
hashes.append(hashes[-1])
nextlevel=list()
i=0
while i < len(hashes):
nextlevel.append(dSHA256(hashes[i] + hashes[i+1],raw=True))
i+=2
return mrkl_root(nextlevel)
def vrfy_root_path(hashMerkleRoot,shash,mpath,flags):
""" Verify given tx search hash against given Merkle tree root hash """
#if flags[0] == 1:
mpath.insert(0,hexstr_to_dbytes(shash))
#elif flags[0] == 0:
# mpath.insert(1,hexstr_to_dbytes(shash))
#else:
# assert False,"Flags must be list of integers!"
flags.reverse()
while len(mpath)>1:
flag = flags.pop()
if flag == 0:
calculated_hash = dSHA256(mpath[1] + mpath[0],raw=True)
elif flag == 1:
calculated_hash = dSHA256(mpath[0] + mpath[1],raw=True)
else:
assert False,"Falgs must be list of integers!"
del mpath[0:2]
mpath.insert(0,calculated_hash)
return dbytes_to_hexstr(mpath[0]) == hashMerkleRoot
def mrkl_root_path(hashes,shash=None,mpath=None,flags=None):
""" create Merkel inclusion proof
"""
initlevel = list()
for h in hashes:
initlevel.append({"value":h,"hit":False})
#print("init level: ",initlevel)
return mrkl_path(initlevel,shash=shash,mpath=mpath,flags=flags)
def mrkl_path(level,shash=None,mpath=None,flags=None):
assert type(level[0]["value"]) is bytes,"tx_hashes must be little endian bytes"
if len(level) == 1:
return level[0]
if len(level) % 2 != 0:
level.append({"value":level[-1]["value"],"hit":False})
nextlevel=list()
i=0
while i < len(level):
nextparent = dict()
if dbytes_to_hexstr(level[i]["value"]) == shash:
mpath.append(level[i+1]["value"])
nextparent["hit"] = True
flags.append(1)
elif dbytes_to_hexstr(level[i+1]["value"]) == shash:
mpath.append(level[i]["value"])
nextparent["hit"] = True
flags.append(0)
elif level[i]["hit"] == True:
nextparent["hit"] = True
mpath.append(level[i+1]["value"])
flags.append(1)
elif level[i+1]["hit"] == True:
nextparent["hit"] = True
mpath.append(level[i]["value"])
flags.append(0)
else:
nextparent["hit"] = False
nextparent["value"] = dSHA256(level[i]["value"] + level[i+1]["value"],raw=True)
nextlevel.append(nextparent)
i+=2
return mrkl_path(nextlevel,shash=shash,mpath=mpath,flags=flags)
# --- Bitcoin style Merkle Blocks verification ---
class Node():
""" Merkle Tree node """
def __init__(self, value, left=None, right=None):
self.value = value # The node value
self.left = left # Left child
self.right = right # Right child
def gen_mrkl_block(tx_hash,tx_hashes):
# TODO create Bitcoin style Merkle Blocks
mrkl_block={"hashMerkleRoot":mrkl_root(tx_hashes),
"tx_count":len(tx_hashes),
"tx_hashes":hashes_bytes,
"flag_bytes":math.ceil(len(flags)/8),
"flags":[0,0,0,1,1,1,0,1]}
return mrkl_block
def vrfy_mrkl_block(tx_hash,mrkl_block):
""" Verfiy Bitcoin style Merkle Blocks """
depth = math.ceil(math.log(mrkl_block["tx_count"],2))
assert type(mrkl_block["tx_hashes"]) is list,"tx_hashes must be list"
assert type(mrkl_block["tx_hashes"][0]) is bytes,"tx_hashes must be list of bytes objects"
hashes = mrkl_block["tx_hashes"]
assert type(mrkl_block["flags"]) is list,"Flags must be list"
assert type(mrkl_block["flags"][0]) is int,"Flags must be list of int"
flags = mrkl_block["flags"]
height = 0
flag = flags.pop()
if depth > 0 and flag == 1:
node = Node(1)
height += 1
node.left = build_tree(height,flags,hashes,depth,tx_hash)
node.right = build_tree(height,flags,hashes,depth,tx_hash)
node.value = dSHA256(node.left.value | |
<gh_stars>0
# MINLP written by GAMS Convert at 08/20/20 01:30:51
#
# Equation counts
# Total E G L N X C B
# 281 81 10 190 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc si
# Total cont binary integer sos1 sos2 scont sint
# 231 161 70 0 0 0 0 0
# FX 0 0 0 0 0 0 0 0
#
# Nonzero counts
# Total const NL DLL
# 1006 991 15 0
#
# Reformulation has removed 1 variable and 1 equation
from pyomo.environ import *
model = m = ConcreteModel()
m.b1 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b2 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b3 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b4 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b5 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b6 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b7 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b8 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b9 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b10 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b11 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b12 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b13 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b14 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b15 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b16 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b17 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b18 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b19 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b20 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b21 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b22 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b23 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b24 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b25 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b26 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b27 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b28 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b29 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b30 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b31 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b32 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b33 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b34 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b35 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b36 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b37 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b38 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b39 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b40 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b41 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b42 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b43 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b44 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b45 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b46 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b47 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b48 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b49 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b50 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b51 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b52 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b53 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b54 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b55 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b56 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b57 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b58 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b59 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b60 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b61 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b62 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b63 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b64 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b65 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b66 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b67 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b68 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b69 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b70 = Var(within=Binary,bounds=(0,1),initialize=0)
m.x71 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x72 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x73 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x74 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x75 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x76 = Var(within=Reals,bounds=(1,14),initialize=1)
m.x77 = Var(within=Reals,bounds=(1,12),initialize=1)
m.x78 = Var(within=Reals,bounds=(1,13),initialize=1)
m.x79 = Var(within=Reals,bounds=(1,14),initialize=1)
m.x80 = Var(within=Reals,bounds=(1,13),initialize=1)
m.x81 = Var(within=Reals,bounds=(1,14),initialize=1)
m.x82 = Var(within=Reals,bounds=(1,12),initialize=1)
m.x83 = Var(within=Reals,bounds=(1,13),initialize=1)
m.x84 = Var(within=Reals,bounds=(1,13),initialize=1)
m.x85 = Var(within=Reals,bounds=(1,14),initialize=1)
m.x87 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x88 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x89 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x90 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x91 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x92 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x93 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x94 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x95 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x96 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x97 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x98 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x99 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x100 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x101 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x102 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x103 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x104 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x105 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x106 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x107 = Var(within=Reals,bounds=(0,109669.003926881),initialize=0)
m.x108 = Var(within=Reals,bounds=(0,99699.094478983),initialize=0)
m.x109 = Var(within=Reals,bounds=(0,109669.003926881),initialize=0)
m.x110 = Var(within=Reals,bounds=(0,69789.3661352881),initialize=0)
m.x111 = Var(within=Reals,bounds=(0,99699.094478983),initialize=0)
m.x112 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x113 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x114 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x115 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x116 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x117 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x118 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x119 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x120 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x121 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x122 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x123 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x124 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x125 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x126 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x127 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x128 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x129 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x130 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x131 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x132 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x133 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x134 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x135 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x136 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x137 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x138 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x139 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x140 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x141 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x142 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x143 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x144 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x145 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x146 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x147 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x148 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x149 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x150 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x151 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x152 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x153 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x154 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x155 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x156 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x157 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x158 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x159 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x160 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x161 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x162 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x163 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x164 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x165 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x166 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x167 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x168 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x169 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x170 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x171 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x172 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x173 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x174 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x175 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x176 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x177 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x178 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x179 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x180 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x181 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x182 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x183 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x184 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x185 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x186 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x187 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x188 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x189 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x190 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x191 = Var(within=Reals,bounds=(0,11),initialize=0)
m.x192 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x193 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x194 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x195 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x196 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x197 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x198 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x199 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x200 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x201 = Var(within=Reals,bounds=(0,7),initialize=0)
m.x202 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x203 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x204 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x205 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x206 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x207 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x208 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x209 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x210 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x211 = Var(within=Reals,bounds=(0,10),initialize=0)
m.x212 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x213 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x214 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x215 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x216 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x217 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x218 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x219 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x220 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x221 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x222 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x223 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x224 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x225 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x226 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x227 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x228 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x229 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x230 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x231 = Var(within=Reals,bounds=(0,None),initialize=0)
m.obj = Objective(expr=88.85300006996*sqrt(1e-8 + m.x107) + 192.23073994166*sqrt(1e-8 + m.x108) + 127.63233374696*sqrt(
1e-8 + m.x109) + 419.48235478268*sqrt(1e-8 + m.x110) + 153.22284111554*sqrt(1e-8 + m.x111) +
11812.8060023653*sqrt(1e-8 + m.x76) + 1350.11753695442*sqrt(1e-8 + m.x77) + 13367.9894872554*
sqrt(1e-8 + m.x78) + 22271.0227712868*sqrt(1e-8 + m.x79) + 3005.94387692899*sqrt(1e-8 + m.x80) +
8081.13134168897*sqrt(1e-8 + m.x81) + 2725.40259637536*sqrt(1e-8 + m.x82) + 17834.6321864598*
sqrt(1e-8 + m.x83) + 11090.3708869987*sqrt(1e-8 + m.x84) + 34135.3450147183*sqrt(1e-8 + m.x85)
+ 151717.47132*m.b16 + 158432.66708*m.b17 + 155503.75356*m.b18 + 153011.37904*m.b19
+ 152922.12117*m.b20 + 31172.917964017*m.b21 + 50366.2988612629*m.b22 + 25232.3015865842*m.b23
+ 13875.2777716691*m.b24 + 12894.0919466219*m.b25 + 104246.200740246*m.b26
+ 23030.4692996671*m.b27 + 34080.9619919892*m.b28 + 23691.1338892398*m.b29
+ 71485.9325093983*m.b30 + 20595.4230163802*m.b31 + 100964.014716159*m.b32
+ 47584.642753328*m.b33 + 8366.15399075336*m.b34 + 12512.1539989574*m.b35
+ 35986.4763418661*m.b36 + 46834.267934517*m.b37 + 35500.2352632821*m.b38
+ 24409.7766590388*m.b39 + 48282.6225705813*m.b40 + 31041.4817687302*m.b41
+ 53037.2328896265*m.b42 + 51459.7461120258*m.b43 + 22667.2580628975*m.b44
+ 25228.9882448255*m.b45 + 37408.8375498868*m.b46 + 25200.7856772603*m.b47
+ 36902.8071939517*m.b48 + 26504.6681149691*m.b49 + 49522.8366523017*m.b50
+ 9271.93442865272*m.b51 + 144904.131180845*m.b52 + 24247.3790621604*m.b53
+ 7667.40116108732*m.b54 + 22073.8762813933*m.b55 + 107488.43411253*m.b56
+ 23226.4417178111*m.b57 + 34704.48655633*m.b58 + 25058.2307095212*m.b59
+ 47407.2067673463*m.b60 + 21614.5566697948*m.b61 + 101949.658248026*m.b62
+ 25381.2261639692*m.b63 + 8426.19414871674*m.b64 + 13579.8855675766*m.b65
+ 107491.687838232*m.b66 + 43784.7477537411*m.b67 + 107221.380878763*m.b68
+ 13362.229690641*m.b69 + 25676.6925875457*m.b70 + 772.8645240165*m.x87 + 109.73384215925*m.x88
+ 332.64598234875*m.x89 + 226.514334935*m.x90 + 159.627138782*m.x91 + 621.33045502625*m.x92
+ 444.925267275*m.x93 + 198.06301532475*m.x94 + 357.5965626135*m.x95 + 80.6766666775*m.x96
+ 242.0437770305*m.x97 + 630.31461703875*m.x98 + 485.8539167745*m.x99 + 239.8308926255*m.x100
+ 408.49173769875*m.x101, sense=minimize)
m.c2 = Constraint(expr= m.b1 + m.b6 + m.b11 - m.b16 == 0)
m.c3 = Constraint(expr= m.b2 + m.b7 + m.b12 - m.b17 == 0)
m.c4 = Constraint(expr= m.b3 + m.b8 + m.b13 - m.b18 == 0)
m.c5 = Constraint(expr= m.b4 + m.b9 + m.b14 - m.b19 == 0)
m.c6 = Constraint(expr= m.b5 + m.b10 + m.b15 - m.b20 == 0)
m.c7 = Constraint(expr= - m.b16 + m.b21 <= 0)
m.c8 = Constraint(expr= - m.b16 + m.b22 <= 0)
m.c9 = Constraint(expr= - m.b16 + m.b23 <= 0)
m.c10 = Constraint(expr= - m.b16 + m.b24 <= 0)
m.c11 = Constraint(expr= - m.b16 + m.b25 <= 0)
m.c12 = Constraint(expr= - m.b16 + m.b26 <= 0)
m.c13 = Constraint(expr= - m.b16 + m.b27 <= 0)
m.c14 = Constraint(expr= - m.b16 + m.b28 <= 0)
m.c15 = Constraint(expr= - m.b16 + m.b29 <= 0)
m.c16 = Constraint(expr= - m.b16 + m.b30 <= 0)
m.c17 = Constraint(expr= - m.b17 + m.b31 <= 0)
m.c18 = Constraint(expr= - m.b17 + m.b32 <= 0)
m.c19 = Constraint(expr= - m.b17 + m.b33 <= 0)
m.c20 = Constraint(expr= - m.b17 + m.b34 <= 0)
m.c21 = Constraint(expr= - m.b17 + m.b35 <= 0)
m.c22 = Constraint(expr= - m.b17 + m.b36 <= 0)
m.c23 = Constraint(expr= - m.b17 + m.b37 <= 0)
m.c24 = Constraint(expr= - m.b17 + m.b38 <= 0)
m.c25 = Constraint(expr= - m.b17 + m.b39 <= 0)
m.c26 = Constraint(expr= - m.b17 + m.b40 <= 0)
m.c27 = Constraint(expr= - m.b18 + m.b41 <= 0)
m.c28 = Constraint(expr= - m.b18 + m.b42 <= 0)
m.c29 = Constraint(expr= - m.b18 + m.b43 <= 0)
m.c30 = Constraint(expr= - m.b18 + m.b44 <= 0)
m.c31 = Constraint(expr= - m.b18 + m.b45 <= 0)
m.c32 = Constraint(expr= - m.b18 + m.b46 <= 0)
m.c33 = Constraint(expr= - m.b18 + m.b47 <= 0)
m.c34 = Constraint(expr= - m.b18 + m.b48 <= 0)
m.c35 = Constraint(expr= - m.b18 + m.b49 <= 0)
m.c36 = Constraint(expr= - m.b18 + m.b50 <= 0)
m.c37 = Constraint(expr= - m.b19 + m.b51 <= 0)
m.c38 = Constraint(expr= - m.b19 + m.b52 <= 0)
m.c39 = Constraint(expr= - m.b19 + m.b53 <= 0)
m.c40 = Constraint(expr= - m.b19 + m.b54 <= 0)
m.c41 = Constraint(expr= - m.b19 + m.b55 <= 0)
m.c42 = Constraint(expr= - m.b19 + m.b56 <= 0)
m.c43 = Constraint(expr= - m.b19 + m.b57 <= 0)
m.c44 = Constraint(expr= - m.b19 + m.b58 <= 0)
m.c45 = Constraint(expr= - m.b19 + m.b59 <= 0)
m.c46 = Constraint(expr= - m.b19 + m.b60 <= 0)
m.c47 = Constraint(expr= - m.b20 + m.b61 <= 0)
m.c48 = Constraint(expr= - m.b20 + m.b62 <= 0)
m.c49 = Constraint(expr= - m.b20 + m.b63 <= 0)
m.c50 = Constraint(expr= - m.b20 + m.b64 <= 0)
m.c51 = Constraint(expr= - m.b20 + m.b65 <= 0)
m.c52 = Constraint(expr= - m.b20 + m.b66 <= 0)
m.c53 = Constraint(expr= - m.b20 + m.b67 <= 0)
m.c54 = Constraint(expr= - m.b20 + m.b68 <= 0)
m.c55 = Constraint(expr= - m.b20 + m.b69 <= 0)
m.c56 = Constraint(expr= - m.b20 + m.b70 <= 0)
m.c57 = Constraint(expr= m.b21 + m.b31 + m.b41 + m.b51 + m.b61 == 1)
m.c58 = Constraint(expr= m.b22 + m.b32 + m.b42 + m.b52 + m.b62 == 1)
m.c59 = Constraint(expr= m.b23 + m.b33 + m.b43 + m.b53 + m.b63 == 1)
m.c60 = Constraint(expr= m.b24 + m.b34 + m.b44 + m.b54 + m.b64 == 1)
m.c61 = Constraint(expr= m.b25 + m.b35 + m.b45 + m.b55 + m.b65 == 1)
m.c62 = Constraint(expr= m.b26 + | |
in group_names:
try:
group = session.query(model.DbGroup).filter_by(name=group_name).one()
except NoResultFound:
raise DbErrors.DbUserNotFoundError("Group '%s' not found in database" % group_name)
groups.append(group)
try:
role = session.query(model.DbRole).filter_by(name=external_user.role.name).one()
user = model.DbUser(external_user.login, external_user.full_name, external_user.email, role = role)
user_auth = model.DbUserAuth(user, auth, configuration = external_id)
for group in groups:
group.users.append(user)
session.add(user)
session.add(user_auth)
session.commit()
except Exception as e:
log.log( DatabaseGateway, log.level.Warning, "Couldn't create user: %s" % e)
log.log_exc(DatabaseGateway, log.level.Info)
raise DbErrors.DatabaseError("Couldn't create user! Contact administrator")
finally:
session.close()
# Location updater
@with_session
def reset_locations_database(self):
update_stmt = sql.update(model.DbUserUsedExperiment).values(hostname = None, city = None, most_specific_subdivision = None, country = None)
_current.session.execute(update_stmt)
_current.session.commit()
@with_session
def reset_locations_cache(self):
_current.session.query(model.DbLocationCache).delete()
_current.session.commit()
@with_session
def update_locations(self, location_func):
"""update_locations(location_func) -> number_of_updated
update_locations receives a location_func which receives an IP address and
returns the location in the following format:
{
'hostname': 'foo.fr', # or None
'city': 'Bilbao', # or None
'country': 'Spain', # or None
'most_specific_subdivision': 'Bizkaia' # or None
}
If there is an error checking the data, it will simply return None.
If the IP address is local, it will simply fill the hostname URL.
update_locations will return the number of successfully changed registries.
So if there were 10 IP addresses to be changed, and it failed in 5 of them,
it will return 5. This way, the loop calling this function can sleep only if
the number is zero.
"""
counter = 0
uses_without_location = list(_current.session.query(model.DbUserUsedExperiment).filter_by(hostname = None).limit(1024).all()) # Do it iterativelly, never process more than 1024 uses
if uses_without_location:
from_direct_ip_name = _current.session.query(model.DbUserUsedExperimentProperty).filter_by(name='from_direct_ip').first()
all_direct_ips = _current.session.query(model.DbUserUsedExperimentPropertyValue).filter(model.DbUserUsedExperimentPropertyValue.property_name_id == from_direct_ip_name.id, model.DbUserUsedExperimentPropertyValue.experiment_use_id.in_([ use.id for use in uses_without_location ])).all()
from_direct_ips = { p.experiment_use_id : p.value for p in all_direct_ips }
origins = set()
origins_string = set()
pack2ip = {
# '<ip1>::<ip2>' : (ip1, ip2)
}
for use in uses_without_location:
from_direct_ip = from_direct_ips.get(use.id)
origins.add( (use.origin, from_direct_ip) )
pack = '{}::{}'.format(use.origin, from_direct_ip)
origins_string.add(pack)
pack2ip[pack] = (use.origin, from_direct_ip)
cached_origins = {
# origin::direct: result
}
last_month = datetime.datetime.utcnow() - datetime.timedelta(days = 31)
for cached_origin in _current.session.query(model.DbLocationCache).filter(model.DbLocationCache.pack.in_(origins_string), model.DbLocationCache.lookup_time > last_month).all():
cached_origins[cached_origin.pack] = {
'city' : cached_origin.city,
'hostname': cached_origin.hostname,
'country': cached_origin.country,
'most_specific_subdivision' : cached_origin.most_specific_subdivision,
}
for use in uses_without_location:
from_direct_ip = from_direct_ips.get(use.id)
pack = '{}::{}'.format(use.origin, from_direct_ip)
if pack in cached_origins:
use.city = cached_origins[pack]['city']
use.hostname = cached_origins[pack]['hostname']
use.country = cached_origins[pack]['country']
use.most_specific_subdivision = cached_origins[pack]['most_specific_subdivision']
counter += 1
else:
try:
result = location_func(use.origin, from_direct_ip)
except Exception:
traceback.print_exc()
continue
use.city = result['city']
use.hostname = result['hostname']
use.country = result['country']
use.most_specific_subdivision = result['most_specific_subdivision']
cached_origins[pack] = result
new_cached_result = model.DbLocationCache(pack = pack, lookup_time = datetime.datetime.utcnow(), hostname = result['hostname'], city = result['city'], country = result['country'], most_specific_subdivision = result['most_specific_subdivision'])
_current.session.add(new_cached_result)
counter += 1
try:
_current.session.commit()
except Exception:
traceback.print_exc()
return counter
# Admin default
@with_session
def frontend_admin_uses_last_week(self):
now = datetime.datetime.utcnow() # Not UTC
since = now + relativedelta(days=-7)
group = (model.DbUserUsedExperiment.start_date_date,)
converter = lambda args: args[0]
date_generator = self._frontend_sequence_day_generator
return self._frontend_admin_uses_last_something(since, group, converter, date_generator)
@with_session
def frontend_admin_uses_last_year(self):
now = datetime.datetime.utcnow() # Not UTC
since = (now + relativedelta(years=-1)).replace(day=1) # day=1 is important to search by start_date_month
group = (model.DbUserUsedExperiment.start_date_year,model.DbUserUsedExperiment.start_date_month)
converter = lambda args: datetime.date(args[0], args[1], 1)
date_generator = self._frontend_sequence_month_generator
return self._frontend_admin_uses_last_something(since, group, converter, date_generator)
def _frontend_sequence_month_generator(self, since):
now = datetime.date.today() # Not UTC
cur_year = since.year
cur_month = since.month
cur_date = datetime.date(cur_year, cur_month, 1)
dates = []
while cur_date <= now:
dates.append(cur_date)
if cur_month == 12:
cur_month = 1
cur_year += 1
else:
cur_month += 1
cur_date = datetime.date(cur_year, cur_month, 1)
return dates
def _frontend_sequence_day_generator(self, since):
now = datetime.datetime.today() # Not UTC
cur_date = since
dates = []
while cur_date <= now:
dates.append(cur_date.date())
cur_date = cur_date + datetime.timedelta(days = 1)
return dates
def _frontend_admin_uses_last_something(self, since, group, converter, date_generator):
results = {
# experiment_data : {
# datetime.date() : count
# }
}
for row in _current.session.query(sqlalchemy.func.count(model.DbUserUsedExperiment.id), model.DbExperiment.name, model.DbExperimentCategory.name, *group).filter(model.DbUserUsedExperiment.start_date >= since, model.DbUserUsedExperiment.experiment_id == model.DbExperiment.id, model.DbExperiment.category_id == model.DbExperimentCategory.id).group_by(model.DbUserUsedExperiment.experiment_id, *group).all():
count = row[0]
experiment = '@'.join((row[1], row[2]))
if experiment not in results:
results[experiment] = {}
results[experiment][converter(row[3:])] = count
for date in date_generator(since):
for experiment_id in results:
results[experiment_id].setdefault(date, 0)
return results
@with_session
def frontend_admin_uses_geographical_month(self):
# This is really in the last literal month
now = datetime.datetime.utcnow()
since = now + relativedelta(months = -1)
return self.quickadmin_uses_per_country(UsesQueryParams.create(start_date=since))
@with_session
def frontend_admin_latest_uses(self):
return self.quickadmin_uses(limit = 10, query_params=UsesQueryParams.create())
# Quickadmin
def _apply_filters(self, query, query_params):
if query_params.login:
query = query.join(model.DbUserUsedExperiment.user).filter(model.DbUser.login == query_params.login)
if query_params.experiment_name:
query = query.join(model.DbUserUsedExperiment.experiment).filter(model.DbExperiment.name == query_params.experiment_name)
if query_params.category_name:
query = query.join(model.DbUserUsedExperiment.experiment).join(model.DbExperiment.category).filter(model.DbExperimentCategory.name == query_params.category_name)
if query_params.group_names is not None:
if len(query_params.group_names) == 0:
# Automatically filter that there is no
return query.filter(model.DbUser.login == None, model.DbUser.login != None)
query = query.join(model.DbUserUsedExperiment.user).filter(model.DbUser.groups.any(model.DbGroup.name.in_(query_params.group_names)))
if query_params.start_date:
query = query.filter(model.DbUserUsedExperiment.start_date >= query_params.start_date)
if query_params.end_date:
query = query.filter(model.DbUserUsedExperiment.end_date <= query_params.end_date + datetime.timedelta(days=1))
if query_params.ip:
query = query.filter(model.DbUserUsedExperiment.origin == query_params.ip)
if query_params.country:
query = query.filter(model.DbUserUsedExperiment.country == query_params.country)
return query
@with_session
def quickadmin_uses(self, limit, query_params):
db_latest_uses_query = _current.session.query(model.DbUserUsedExperiment)
db_latest_uses_query = self._apply_filters(db_latest_uses_query, query_params)
db_latest_uses = db_latest_uses_query.options(joinedload("user"), joinedload("experiment"), joinedload("experiment", "category"), joinedload("properties")).order_by(model.DbUserUsedExperiment.start_date.desc()).limit(limit).offset((query_params.page - 1) * limit)
external_user = _current.session.query(model.DbUserUsedExperimentProperty).filter_by(name = 'external_user').first()
latest_uses = []
for use in db_latest_uses:
login = use.user.login
display_name = login
for prop in use.properties:
if prop.property_name == external_user:
display_name = prop.value + u'@' + login
if use.start_date:
if use.end_date is None:
duration = datetime.datetime.utcnow() - use.start_date
else:
duration = use.end_date - use.start_date
else:
duration = datetime.timedelta(seconds = 0)
# Avoid microseconds
duration_without_microseconds = datetime.timedelta(seconds = int(duration.total_seconds()))
latest_uses.append({
'id' : use.id,
'login' : login,
'display_name' : display_name,
'full_name' : use.user.full_name,
'experiment_name' : use.experiment.name,
'category_name' : use.experiment.category.name,
'start_date' : use.start_date,
'end_date' : use.end_date,
'from' : use.origin,
'city' : use.city,
'country' : use.country,
'hostname' : use.hostname,
'duration' : duration_without_microseconds,
})
return latest_uses
@with_session
def quickadmin_uses_per_country(self, query_params):
db_latest_uses_query = _current.session.query(model.DbUserUsedExperiment.country, sqlalchemy.func.count(model.DbUserUsedExperiment.id)).filter(model.DbUserUsedExperiment.country != None)
db_latest_uses_query = self._apply_filters(db_latest_uses_query, query_params)
return dict(db_latest_uses_query.group_by(model.DbUserUsedExperiment.country).all())
def quickadmin_uses_per_country_by(self, query_params):
if query_params.date_precision == 'year':
return self.quickadmin_uses_per_country_by_year(query_params)
if query_params.date_precision == 'month':
return self.quickadmin_uses_per_country_by_month(query_params)
if query_params.date_precision == 'day':
return self.quickadmin_uses_per_country_by_day(query_params)
return {}
@with_session
def quickadmin_uses_per_country_by_day(self, query_params):
# country, count, year, month
initial_query = _current.session.query(model.DbUserUsedExperiment.country, sqlalchemy.func.count(model.DbUserUsedExperiment.id), model.DbUserUsedExperiment.start_date_date)
group_by = (model.DbUserUsedExperiment.country, model.DbUserUsedExperiment.start_date_date)
return self._quickadmin_uses_per_country_by_date(query_params, initial_query, group_by)
@with_session
def quickadmin_uses_per_country_by_month(self, query_params):
# country, count, year, month
initial_query = _current.session.query(model.DbUserUsedExperiment.country, sqlalchemy.func.count(model.DbUserUsedExperiment.id), model.DbUserUsedExperiment.start_date_year, model.DbUserUsedExperiment.start_date_month)
group_by = (model.DbUserUsedExperiment.country, model.DbUserUsedExperiment.start_date_year, model.DbUserUsedExperiment.start_date_month)
return self._quickadmin_uses_per_country_by_date(query_params, initial_query, group_by)
@with_session
def quickadmin_uses_per_country_by_year(self, query_params):
# country, count, year
initial_query = _current.session.query(model.DbUserUsedExperiment.country, sqlalchemy.func.count(model.DbUserUsedExperiment.id), model.DbUserUsedExperiment.start_date_year)
group_by = (model.DbUserUsedExperiment.country, model.DbUserUsedExperiment.start_date_year)
return self._quickadmin_uses_per_country_by_date(query_params, initial_query, group_by)
def _quickadmin_uses_per_country_by_date(self, query_params, initial_query, group_by):
db_latest_uses_query = initial_query.filter(model.DbUserUsedExperiment.country != None)
db_latest_uses_query = self._apply_filters(db_latest_uses_query, query_params)
countries = {
# country : [
# [ (year, month), count ]
# ]
}
for row in db_latest_uses_query.group_by(*group_by).all():
country = row[0]
count = row[1]
key = tuple(row[2:])
if country not in countries:
countries[country] = []
countries[country].append((key, count))
# Sort by the union of the keys
countries[country].sort(lambda x, y: cmp('-'.join([ unicode(v).zfill(8) for v in x[0]]), '-'.join([ unicode(v).zfill(8) for v in y[0]])))
return countries
@with_session
def quickadmin_uses_metadata(self, query_params):
db_metadata_query = _current.session.query(sqlalchemy.func.min(model.DbUserUsedExperiment.start_date), sqlalchemy.func.max(model.DbUserUsedExperiment.start_date), sqlalchemy.func.count(model.DbUserUsedExperiment.id))
db_metadata_query = self._apply_filters(db_metadata_query, query_params)
first_element = db_metadata_query.first()
if first_element:
min_date, max_date, count = first_element
return dict(min_date = min_date, max_date = max_date, count = count)
return dict(min_date = datetime.datetime.utcnow(), max_date = datetime.datetime.now(), count = 0)
@with_session
def quickadmin_use(self, use_id):
use = _current.session.query(model.DbUserUsedExperiment).filter_by(id = use_id).options(joinedload("user"), joinedload("experiment"), joinedload("experiment", "category"), joinedload("properties")).first()
if not use:
return {'found' : False}
def get_prop(prop_name, default):
return ([ prop.value for prop in use.properties if prop.property_name.name == prop_name ] or [ default ])[0]
experiment = use.experiment.name + u'@' + use.experiment.category.name
properties = OrderedDict()
properties['Login'] = use.user.login
properties['Name'] = use.user.full_name
properties['In the name of'] = get_prop('external_user', 'Himself')
properties['Experiment'] = experiment
properties['Date'] = use.start_date
properties['Origin'] = use.origin
properties['Device used'] = use.coord_address
properties['Server IP (if federated)'] = get_prop('from_direct_ip', use.origin)
properties['Use ID'] = use.id
properties['Reservation ID'] = use.reservation_id
properties['Mobile'] = get_prop('mobile', "Don't know")
properties['Facebook'] = get_prop('facebook', "Don't know")
properties['Referer'] = get_prop('referer', "Don't know")
properties['Web Browser'] = get_prop('user_agent', "Don't know")
properties['Route'] = get_prop('route', "Don't know")
properties['Locale'] = get_prop('locale', "Don't know")
properties['City'] = use.city or 'Unknown'
properties['Country'] = use.country or 'Unknown'
properties['Hostname'] = use.hostname or 'Unknown'
commands = []
longest_length = 0
for command in use.commands:
timestamp_after = command.timestamp_after
timestamp_before = command.timestamp_before
if timestamp_after is not None and command.timestamp_after_micro is not None:
timestamp_after = timestamp_after.replace(microsecond = command.timestamp_after_micro)
| |
<filename>Smart_Fusion/testbench.py
from ppg_dalia_data_extraction import extract_data
from edr_adr_signal_extraction import edr_adr_extraction
from rqi_extraction import rqi_extraction
from rr_extraction import rr_extraction
import scipy
import numpy as np
import argparse
from machine_learning import *
import matplotlib.pyplot as plt
import re
import pandas as pd
import os
import pickle as pkl
import datetime as dt
from plots import *
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from tqdm import tqdm
import seaborn as sns
import time
import datetime as dt
# Path for the feature .pkl file.
#path_freq = 'C:/Users/ee19s/Desktop/HR/PPG_FieldStudy/FREQ_MORPH_FEATURES.pkl'
bool_variable = True
#final_rr = []
final_error = []
if __name__ == '__main__':
#parse the data path where .pkl file is present.
parser = argparse.ArgumentParser()
parser.add_argument('--data_path', type = str, help = 'Path to data')
parser.add_argument('--input_features', default = 'freq_morph', type = str, help = "'freq', 'morph' or 'freq_morph'")
args = parser.parse_args()
retreive_features = False
# Check if features are already retreived in .pkl file or not.
for file_name in os.listdir(args.data_path):
if file_name.endswith('_FEATURES.pkl'):
retreive_features = True
path_to_pkl_file = os.path.join(args.data_path, file_name)
break
# Features are not retreived the execute the steps below or go to else case.
if not(retreive_features):
#path = 'C:/Users/ee19s/Desktop/HR/PPG_FieldStudy'
srate = 700
window_len = 32 * srate
interp_freq = 4
ecg_resp_win_length = 32*interp_freq
lags_ecg = np.arange(4,45)
lags_acc = np.arange(7,70)
#call the ppg_dalia_data_extraction function and extract the different signals
data = extract_data(args.data_path, srate, window_len)
for item in enumerate(data.keys()):
patient_id = item[1]
rpeaks = data[patient_id]['ECG']['RPEAKS']
amps = data[patient_id]['ECG']['AMPLITUDES']
acc = data[patient_id]['ACC']['ACC_DATA']
resp = data[patient_id]['RESP']['RESP_DATA']
activity_id = data[patient_id]['ACTIVITY_ID']
#import pdb;pdb.set_trace()
# Filtering only for respiration signal to calculate the reference breathing rate per minute.
flpB,flpA = scipy.signal.cheby2(5,30 , 0.7/(srate/2),btype='lowpass')
fhpB,fhpA = scipy.signal.cheby2(4,20 ,0.1/(srate/2),btype='highpass')
final_resp = []
for item_1 in resp:
lp_filt = scipy.signal.filtfilt(flpB,flpA , item_1)
final_resp.append(scipy.signal.filtfilt(fhpB,fhpA , lp_filt))
#import pdb;pdb.set_trace()
# Call the respiration signal extraction function on ecg and acc,
# for ecg only rpeaks and peak amplitudes are required.
edr_hrv , edr_rpeak , adr = edr_adr_extraction(acc, rpeaks , amps)
#Call the rr_extraction function to extract average breath duration from different respiratory signals.
rr_hrv_duration , hrv_cov , hrv_mean_ptop , hrv_true_min_true_max , hrv_cov_min = rr_extraction(edr_hrv , interp_freq)
rr_rpeak_duration , rpeak_cov , rpeak_mean_ptop , rpeak_true_min_true_max , rpeak_cov_min = rr_extraction(edr_rpeak , interp_freq)
rr_adr_duration , adr_cov , adr_mean_ptop , adr_true_min_true_max , adr_cov_min = rr_extraction(adr , (srate/10))
rr_resp_duration, _ , _ , _ , _ = rr_extraction(final_resp , srate)
# Calcualte the respiratory rate per minute using the fomula below.
rr_hrv = 60/(rr_hrv_duration/interp_freq)
rr_rpeak = 60/(rr_rpeak_duration/interp_freq)
rr_adr = 60/(rr_adr_duration/(srate/10))
rr_resp = 60/(rr_resp_duration/srate)
# Calculate the Absolute error.
abs_error_hrv = np.abs(rr_hrv - rr_resp)
abs_error_rpeak = np.abs(rr_rpeak - rr_resp)
abs_error_adr = np.abs(rr_adr - rr_resp)
# Call the RQI extraction function to calculate different values of RQI.
hrv_fft , hrv_ar , hrv_ac , hrv_hjorth , hrv_fft_extra = rqi_extraction(edr_hrv ,ecg_resp_win_length , interp_freq, lags_ecg)
rpeak_fft , rpeak_ar , rpeak_ac , rpeak_hjorth , rpeak_fft_extra = rqi_extraction(edr_rpeak , ecg_resp_win_length ,interp_freq,lags_ecg)
adr_fft , adr_ar , adr_ac , adr_hjorth , adr_fft_extra = rqi_extraction(adr , window_len , srate , lags_acc)
# Frame the frequency feature metrics.
int_part = re.findall(r'\d+', patient_id)
freq_features = np.hstack((hrv_fft.reshape(-1,1) , hrv_ar.reshape(-1,1) , hrv_ac.reshape(-1,1) ,hrv_hjorth.reshape(-1,1),
hrv_fft_extra.reshape(-1,1) ,rpeak_fft.reshape(-1,1),rpeak_ar.reshape(-1,1),rpeak_ac.reshape(-1,1),
rpeak_hjorth.reshape(-1,1) , rpeak_fft_extra.reshape(-1,1),adr_fft.reshape(-1,1),
adr_ar.reshape(-1,1),adr_ac.reshape(-1,1),adr_hjorth.reshape(-1,1),adr_fft_extra.reshape(-1,1),
np.array(activity_id).reshape(-1,1),
rr_hrv.reshape(-1,1) , rr_rpeak.reshape(-1,1),rr_adr.reshape(-1,1),rr_resp.reshape(-1,1),
abs_error_hrv.reshape(-1,1) ,abs_error_rpeak.reshape(-1,1),abs_error_adr.reshape(-1,1)
,np.array([int(int_part[0])]*len(hrv_fft)).reshape(-1,1)))
# Frame the morphological feature metrics.
morph_features = np.hstack((np.array(hrv_cov).reshape(-1,1) , np.array(hrv_mean_ptop).reshape(-1,1)
, np.array(hrv_true_min_true_max).reshape(-1,1) ,
np.array(hrv_cov_min).reshape(-1,1) ,np.array(rpeak_cov).reshape(-1,1),np.array(rpeak_mean_ptop).reshape(-1,1)
,np.array(rpeak_true_min_true_max).reshape(-1,1),np.array(rpeak_cov_min).reshape(-1,1),
np.array(adr_cov).reshape(-1,1),np.array(adr_mean_ptop).reshape(-1,1)
,np.array(adr_true_min_true_max).reshape(-1,1),np.array(adr_cov_min).reshape(-1,1),
np.array(activity_id).reshape(-1,1),
rr_hrv.reshape(-1,1),rr_rpeak.reshape(-1,1),rr_adr.reshape(-1,1),rr_resp.reshape(-1,1),
abs_error_hrv.reshape(-1,1),abs_error_rpeak.reshape(-1,1),abs_error_adr.reshape(-1,1)
,np.array([int(int_part[0])]*len(hrv_fft)).reshape(-1,1)))
mixed_features = np.hstack((hrv_fft.reshape(-1,1) , hrv_ar.reshape(-1,1) , hrv_ac.reshape(-1,1) ,np.array(hrv_cov).reshape(-1,1)
, np.array(hrv_mean_ptop).reshape(-1,1)
, np.array(hrv_true_min_true_max).reshape(-1,1) , np.array(hrv_cov_min).reshape(-1,1),
hrv_hjorth.reshape(-1,1),hrv_fft_extra.reshape(-1,1)
,rpeak_fft.reshape(-1,1),rpeak_ar.reshape(-1,1),rpeak_ac.reshape(-1,1),
np.array(rpeak_cov).reshape(-1,1),
np.array(rpeak_mean_ptop).reshape(-1,1)
,np.array(rpeak_true_min_true_max).reshape(-1,1),np.array(rpeak_cov_min).reshape(-1,1),
rpeak_hjorth.reshape(-1,1) , rpeak_fft_extra.reshape(-1,1),
adr_fft.reshape(-1,1),adr_ar.reshape(-1,1),adr_ac.reshape(-1,1),np.array(adr_cov).reshape(-1,1)
,np.array(adr_mean_ptop).reshape(-1,1)
,np.array(adr_true_min_true_max).reshape(-1,1),np.array(adr_cov_min).reshape(-1,1),adr_hjorth.reshape(-1,1),
adr_fft_extra.reshape(-1,1),np.array(activity_id).reshape(-1,1),
rr_hrv.reshape(-1,1) , rr_rpeak.reshape(-1,1),rr_adr.reshape(-1,1),rr_resp.reshape(-1,1),
abs_error_hrv.reshape(-1,1) ,abs_error_rpeak.reshape(-1,1),abs_error_adr.reshape(-1,1)
,np.array([int(int_part[0])]*len(hrv_fft)).reshape(-1,1)))
# Stack the features in array.
if item[0]==0:
freq_features_all_patients = freq_features
morph_features_all_patients = morph_features
mixed_features_all_patients = mixed_features
else:
freq_features_all_patients = np.vstack((freq_features_all_patients , freq_features))
morph_features_all_patients = np.vstack((morph_features_all_patients , morph_features))
mixed_features_all_patients = np.vstack((mixed_features_all_patients , mixed_features))
# Column names of morphological and frequency based features.
col_names_morph = ['hrv_cov' , 'hrv_mean_ptop' , 'hrv_true_max_true_min' , 'hrv_cov_min' ,
'rpeak_cov' , 'rpeak_mean_ptop' , 'rpeak_true_max_true_min' , 'rpeak_cov_min' ,
'adr_cov' , 'adr_mean_ptop' , 'adr_true_max_true_min' , 'adr_cov_min' ,'activity_id',
'rr_hrv','rr_rpeak','rr_adr','rr_resp' ,'error_hrv' ,'error_rpeak' ,'error_adr','patient_id']
col_names_freq = ['rqi_fft_hrv' , 'rqi_ar_hrv' , 'rqi_ac_hrv' , 'rqi_hjorth_hrv' , 'rqi_fft_extra_hrv' ,
'rqi_fft_rpeak' , 'rqi_ar_rpeak' , 'rqi_ac_rpeak' , 'rqi_hjorth_rpeak' , 'rqi_fft_extra_rpeak',
'rqi_fft_adr' , 'rqi_ar_adr' , 'rqi_ac_adr' , 'rqi_hjorth_adr' , 'rqi_fft_extra_adr', 'activity_id',
'rr_hrv','rr_rpeak','rr_adr','rr_resp' ,'error_hrv' ,'error_rpeak' ,'error_adr','patient_id']
col_names_mixed = ['rqi_fft_hrv' , 'rqi_ar_hrv' , 'rqi_ac_hrv' ,'hrv_cov' , 'hrv_mean_ptop' , 'hrv_true_max_true_min'
,'hrv_cov_min','rqi_hjorth_hrv' , 'rqi_fft_extra_hrv' ,
'rqi_fft_rpeak' , 'rqi_ar_rpeak' , 'rqi_ac_rpeak' ,'rpeak_cov' , 'rpeak_mean_ptop' ,
'rpeak_true_max_true_min' , 'rpeak_cov_min' , 'rqi_hjorth_rpeak' , 'rqi_fft_extra_rpeak',
'rqi_fft_adr' , 'rqi_ar_adr' , 'rqi_ac_adr' , 'adr_cov' , 'adr_mean_ptop' , 'adr_true_max_true_min' , 'adr_covn_min' ,
'rqi_hjorth_adr' , 'rqi_fft_extra_adr','activity_id',
'rr_hrv','rr_rpeak','rr_adr','rr_resp' ,'error_hrv' ,'error_rpeak' ,'error_adr','patient_id']
# Store the features in pandas dataframe.
df_freq = pd.DataFrame(freq_features_all_patients , columns = col_names_freq)
df_morph = pd.DataFrame(morph_features_all_patients , columns = col_names_morph)
df_mixed = pd.DataFrame(mixed_features_all_patients , columns = col_names_mixed)
df_freq['patient_id'] = df_freq['patient_id'].astype(int)
df_morph['patient_id'] = df_morph['patient_id'].astype(int)
df_mixed['patient_id'] = df_mixed['patient_id'].astype(int)
df_freq.to_pickle('FREQ_FEATURES.pkl')
df_morph.to_pickle('MORPH_FEATURES.pkl')
df_mixed.to_pickle('FREQ_MORPH_FEATURES.pkl')
else:
print('.............Pickle file containing rqi features exists.............')
saved_model = dt.datetime.now().strftime('%Y_%m_%d_%H_%M')
results_path = os.path.join(args.data_path, 'results')
if not(os.path.isdir(results_path)):
os.mkdir(results_path)
current_model_path = os.path.join(results_path, saved_model)
os.mkdir(current_model_path)
print('............Created path.............')
# Read the pickle files containing the features.
data = pd.read_pickle(path_to_pkl_file)
print('............Data read succesfully.............')
# form the feature metrics such that it can be used in ml model
# when given for 'freq' , 'morph', and both 'freq'+'morph'
# based features.
x_hrv_freq = data[['rqi_fft_hrv','rqi_ar_hrv','rqi_ac_hrv']]
x_rpeak_freq = data[['rqi_fft_rpeak','rqi_ar_rpeak','rqi_ac_rpeak']]
x_adr_freq = data[['rqi_fft_adr','rqi_ar_adr','rqi_ac_adr']]
x_hrv_morph = data[['hrv_cov','hrv_mean_ptop','hrv_true_max_true_min','hrv_cov_min']]
x_rpeak_morph = data[['rpeak_cov','rpeak_mean_ptop','rpeak_true_max_true_min','rpeak_cov_min']]
x_adr_morph = data[['adr_cov','adr_mean_ptop','adr_true_max_true_min','adr_covn_min']]
activity_id = data.loc[:,'activity_id']
y_data = data.loc[: , 'error_hrv':'patient_id']
# features metrics containing the relevent features to be fed into ml function. Its type is pd dataframe.
feature_metrics = pd.concat([x_hrv_freq,x_rpeak_freq,x_adr_freq,x_hrv_morph,x_rpeak_morph,x_adr_morph,activity_id,y_data]
, axis = 1)
# Index of different respiratory rate values.
index_hrv = data.columns.get_loc('rr_hrv')
index_rpeak = data.columns.get_loc('rr_rpeak')
index_adr = data.columns.get_loc('rr_adr')
index_resp = data.columns.get_loc('rr_resp')
if bool_variable == True:
data = np.array(data)
split = (data[: , -1])>=13
#eximport pdb;pdb.set_trace()
rr_hrv = data[split, index_hrv]
rr_rpeak = data[split , index_rpeak]
rr_adr = data[split , index_adr]
rr_resp = data[split , index_resp]
error_hrv = np.abs(rr_hrv - rr_resp).reshape(-1,1)
error_rpeak = np.abs(rr_rpeak - rr_resp).reshape(-1,1)
error_adr = np.abs(rr_adr - rr_resp).reshape(-1,1)
rmse_hrv = round(np.sqrt(np.mean(error_hrv**2)),3)
rmse_rpeak = round(np.sqrt(np.mean(error_rpeak**2)),3)
rmse_adr = round(np.sqrt(np.mean(error_adr**2)),3)
mae_hrv = round(np.mean(error_hrv),4)
mae_rpeak = round(np.mean(error_rpeak),4)
mae_adr = round(np.mean(error_adr),4)
activity_id = data[split , 27]
#import pdb;pdb.set_trace()
# Reshape to get two dimension.
rr_hrv = rr_hrv.reshape(len(rr_hrv) , -1)
rr_rpeak = rr_rpeak.reshape(len(rr_rpeak), -1)
rr_adr = rr_adr.reshape(len(rr_adr), -1)
rr_resp = rr_resp.reshape(len(rr_resp), -1)
# Create the machine learning object.
ml = machine_learning(feature_metrics , args.input_features, is_patient_wise_split= bool_variable, is_save = True, model_save_path = current_model_path)
# List containing objects related to different models.
print('....................Start of modelling...................')
objects_list = [ml.ridge_regression() , ml.randomforest(), ml.supportvector(), ml.lasso_regression(), ml.bayesian_ridge()]
print('....................End of modelling...................')
# call the models and get the predicted values
model_error_dict_rmse = {'Ridge':[], 'RF':[], 'SVM':[], 'Lasso':[], 'bRidge':[]}
model_error_dict_mae = {'Ridge':[], 'RF':[], 'SVM':[], 'Lasso':[], 'bRidge':[]}
model_dict_keys = ['Ridge', 'RF', 'SVM', 'Lasso', 'bRidge']
fusion_rr = []
fusion_error_rmse = []
fusion_error_mae = []
time_list = []
model_index = 1
for index, item in tqdm(enumerate(objects_list)):
#import pdb;pdb.set_trace()
#start = time.time()
hrv_pred , rpeak_pred , adr_pred = item
#end = time.time()
#time_list.append(end-start)
if hrv_pred.ndim != 2 or rpeak_pred.ndim!= 2 or adr_pred.ndim!= 2:
hrv_pred = hrv_pred.reshape(len(hrv_pred) , -1)
rpeak_pred = rpeak_pred.reshape(len(rpeak_pred) , -1)
adr_pred = adr_pred.reshape(len(adr_pred) , -1)
# sum of all predicted values.
#normal_sum = hrv_pred + rpeak_pred + adr_pred
# normalise the weights,
hrv_weights = np.exp((-1*hrv_pred)/5) #1 - (hrv_pred/normal_sum)
rpeak_weights = np.exp((-1*rpeak_pred)/5) #1-(rpeak_pred/normal_sum)
adr_weights = np.exp((-1*adr_pred)/5) #1 - (adr_pred/normal_sum)
# obtain the net rr and error and store it in list.
net_rr = (rr_hrv*hrv_weights + rr_rpeak*rpeak_weights + rr_adr*adr_weights)/(hrv_weights + rpeak_weights + adr_weights)
error_rmse = np.sqrt(np.mean((net_rr - rr_resp) ** 2))
error_mae = np.mean(np.abs(net_rr - rr_resp))
fusion_rr.append(net_rr)
#Append RMSE
fusion_error_rmse.append(round(error_rmse,4))
#Append MAE
fusion_error_mae.append(round(error_mae,4))
# Append RMSE in dictionary.
model_error_dict_rmse[model_dict_keys[index]].append(rmse_hrv)
model_error_dict_rmse[model_dict_keys[index]].append(rmse_rpeak)
model_error_dict_rmse[model_dict_keys[index]].append(rmse_adr)
model_error_dict_rmse[model_dict_keys[index]].append(round(error_rmse,4))
# Append MAE in dictionary.
model_error_dict_mae[model_dict_keys[index]].append(mae_hrv)
model_error_dict_mae[model_dict_keys[index]].append(mae_rpeak)
model_error_dict_mae[model_dict_keys[index]].append(mae_adr)
model_error_dict_mae[model_dict_keys[index]].append(round(error_mae,4))
error = np.abs(net_rr - rr_resp)
#final_rr.append(net_rr)
final_error.append(error)
#import pdb;pdb.set_trace()
# Store both rmse and mae in .csv file.
with open(os.path.join(current_model_path, 'results.txt') ,'w') as f:
f.write('----------------------- \n'.format(args.input_features)) | |
<gh_stars>10-100
# coding: utf-8
"""
Filtering functions to handle flatisfy-specific metadata.
This includes functions to guess metadata (postal codes, stations) from the
actual fetched data.
"""
from __future__ import absolute_import, print_function, unicode_literals
import logging
import re
from flatisfy import data
from flatisfy import tools
from flatisfy.constants import TimeToModes
from flatisfy.models.postal_code import PostalCode
from flatisfy.models.public_transport import PublicTransport
LOGGER = logging.getLogger(__name__)
def init(flats_list, constraint):
"""
Create a flatisfy key containing a dict of metadata fetched by flatisfy for
each flat in the list. Also perform some basic transform on flat objects to
prepare for the metadata fetching.
:param flats_list: A list of flats dict.
:param constraint: The constraint that the ``flats_list`` should satisfy.
:return: The updated list
"""
for flat in flats_list:
# Init flatisfy key
if "flatisfy" not in flat:
flat["flatisfy"] = {}
if "constraint" not in flat["flatisfy"]:
flat["flatisfy"]["constraint"] = constraint
# Move url key to urls
if "urls" not in flat:
if "url" in flat:
flat["urls"] = [flat["url"]]
else:
flat["urls"] = []
# Create merged_ids key
if "merged_ids" not in flat:
flat["merged_ids"] = [flat["id"]]
return flats_list
def fuzzy_match(query, choices, limit=3, threshold=75):
"""
Custom search for the best element in choices matching the query.
:param query: The string to match.
:param choices: The list of strings to match with.
:param limit: The maximum number of items to return. Set to ``None`` to
return all values above threshold.
:param threshold: The score threshold to use.
:return: Tuples of matching items and associated confidence.
.. note ::
This function works by removing any fancy character from the ``query``
and ``choices`` strings (replacing any non alphabetic and non numeric
characters by space), converting to lower case and normalizing them
(collapsing multiple spaces etc). It also converts any roman numerals
to decimal system. It then compares the string and look for the longest
string in ``choices`` which is a substring of ``query``. The longest
one gets a confidence of 100. The shorter ones get a confidence
proportional to their length.
.. seealso :: flatisfy.tools.normalize_string
Example::
>>> fuzzy_match("Paris 14ème", ["Ris", "ris", "Paris 14"], limit=1)
[("Paris 14", 100)
>>> fuzzy_match( \
"Saint-Jacques, Denfert-Rochereau (<NAME>), " \
"Mouton-Duvernet", \
["saint-jacques", "<NAME>", "duvernet", "toto"], \
limit=4 \
)
[('<NAME>', 100), ('saint-jacques', 76)]
"""
# TODO: Is there a better confidence measure?
normalized_query = tools.normalize_string(query).replace("saint", "st")
normalized_choices = [tools.normalize_string(choice).replace("saint", "st") for choice in choices]
# Remove duplicates in the choices list
unique_normalized_choices = tools.uniqify(normalized_choices)
# Get the matches (normalized strings)
# Keep only ``limit`` matches.
matches = sorted(
[(choice, len(choice)) for choice in tools.uniqify(unique_normalized_choices) if choice in normalized_query],
key=lambda x: x[1],
reverse=True,
)
if limit:
matches = matches[:limit]
# Update confidence
if matches:
max_confidence = max(match[1] for match in matches)
matches = [(x[0], int(x[1] / max_confidence * 100)) for x in matches]
# Convert back matches to original strings
# Also filter out matches below threshold
matches = [(choices[normalized_choices.index(x[0])], x[1]) for x in matches if x[1] >= threshold]
return matches
def guess_location_position(location, cities, constraint, must_match):
# try to find a city
# Find all fuzzy-matching cities
postal_code = None
insee_code = None
position = None
matched_cities = fuzzy_match(location, [x.name for x in cities], limit=None)
if matched_cities:
# Find associated postal codes
matched_postal_codes = []
for matched_city_name, _ in matched_cities:
postal_code_objects_for_city = [x for x in cities if x.name == matched_city_name]
insee_code = [pc.insee_code for pc in postal_code_objects_for_city][0]
matched_postal_codes.extend(pc.postal_code for pc in postal_code_objects_for_city)
# Try to match them with postal codes in config constraint
matched_postal_codes_in_config = set(matched_postal_codes) & set(constraint["postal_codes"])
if matched_postal_codes_in_config:
# If there are some matched postal codes which are also in
# config, use them preferentially. This avoid ignoring
# incorrectly some flats in cities with multiple postal
# codes, see #110.
postal_code = next(iter(matched_postal_codes_in_config))
else:
# Otherwise, simply take any matched postal code.
postal_code = matched_postal_codes[0]
# take the city position
for matched_city_name, _ in matched_cities:
postal_code_objects_for_city = [
x for x in cities if x.name == matched_city_name and x.postal_code == postal_code
]
if len(postal_code_objects_for_city):
position = {
"lat": postal_code_objects_for_city[0].lat,
"lng": postal_code_objects_for_city[0].lng,
}
LOGGER.debug(("Found position %s using city %s."), position, matched_city_name)
break
if not postal_code and must_match:
postal_code = cities[0].postal_code
position = {
"lat": cities[0].lat,
"lng": cities[0].lng,
}
insee_code = cities[0].insee_code
return (postal_code, insee_code, position)
def guess_postal_code(flats_list, constraint, config, distance_threshold=20000):
"""
Try to guess the postal code from the location of the flats.
:param flats_list: A list of flats dict.
:param constraint: The constraint that the ``flats_list`` should satisfy.
:param config: A config dict.
:param distance_threshold: Maximum distance in meters between the
constraint postal codes (from config) and the one found by this
function, to avoid bad fuzzy matching. Can be ``None`` to disable
thresholding.
:return: An updated list of flats dict with guessed postal code.
"""
opendata = {"postal_codes": data.load_data(PostalCode, constraint, config)}
for flat in flats_list:
location = flat.get("location", None)
if not location:
addr = flat.get("address", None)
if addr:
location = addr["full_address"]
if not location:
# Skip everything if empty location
LOGGER.info(
("No location field for flat %s, skipping postal code lookup. (%s)"),
flat["id"],
flat.get("address"),
)
continue
postal_code = None
insee_code = None
position = None
# Try to find a postal code directly
try:
postal_code = re.search(r"[0-9]{5}", location)
assert postal_code is not None
postal_code = postal_code.group(0)
# Check the postal code is within the db
assert postal_code in [x.postal_code for x in opendata["postal_codes"]]
LOGGER.debug(
"Found postal code directly in location field for flat %s: %s.",
flat["id"],
postal_code,
)
except AssertionError:
postal_code = None
# Then fetch position (and postal_code is couldn't be found earlier)
cities = opendata["postal_codes"]
if postal_code:
cities = [x for x in cities if x.postal_code == postal_code]
(postal_code, insee_code, position) = guess_location_position(
location, cities, constraint, postal_code is not None
)
# Check that postal code is not too far from the ones listed in config,
# limit bad fuzzy matching
if postal_code and distance_threshold:
distance = min(
tools.distance(
next((x.lat, x.lng) for x in opendata["postal_codes"] if x.postal_code == postal_code),
next((x.lat, x.lng) for x in opendata["postal_codes"] if x.postal_code == constraint_postal_code),
)
for constraint_postal_code in constraint["postal_codes"]
)
if distance > distance_threshold:
LOGGER.info(
(
"Postal code %s found for flat %s @ %s is off-constraints "
"(distance is %dm > %dm). Let's consider it is an "
"artifact match and keep the post without this postal "
"code."
),
postal_code,
flat["id"],
location,
int(distance),
int(distance_threshold),
)
postal_code = None
position = None
# Store it
if postal_code:
existing_postal_code = flat["flatisfy"].get("postal_code", None)
if existing_postal_code and existing_postal_code != postal_code:
LOGGER.warning(
"Replacing previous postal code %s by %s for flat %s.",
existing_postal_code,
postal_code,
flat["id"],
)
flat["flatisfy"]["postal_code"] = postal_code
else:
LOGGER.info("No postal code found for flat %s.", flat["id"])
if insee_code:
flat["flatisfy"]["insee_code"] = insee_code
if position:
flat["flatisfy"]["position"] = position
LOGGER.debug(
"found postal_code=%s insee_code=%s position=%s for flat %s (%s).",
postal_code,
insee_code,
position,
flat["id"],
location,
)
return flats_list
def guess_stations(flats_list, constraint, config):
"""
Try to match the station field with a list of available stations nearby.
:param flats_list: A list of flats dict.
:param constraint: The constraint that the ``flats_list`` should satisfy.
:param config: A config dict.
:return: An updated list of flats dict with guessed nearby stations.
"""
distance_threshold = config["max_distance_housing_station"]
opendata = {
"postal_codes": data.load_data(PostalCode, constraint, config),
"stations": data.load_data(PublicTransport, constraint, config),
}
for flat in flats_list:
flat_station = flat.get("station", None)
if not flat_station:
# Skip everything if empty station
LOGGER.info("No stations field for flat %s, skipping stations lookup.", flat["id"])
continue
# Woob modules can return several stations in a comma-separated list.
flat_stations = flat_station.split(",")
# But some stations containing a comma exist, so let's add the initial
# value to the list of stations to check if there was one.
if len(flat_stations) > 1:
flat_stations.append(flat_station)
matched_stations = []
for tentative_station in flat_stations:
matched_stations += fuzzy_match(
tentative_station,
[x.name for x in opendata["stations"]],
limit=10,
threshold=50,
)
# Keep only one occurrence of each station
matched_stations = list(set(matched_stations))
# Filter out the stations that are obviously too far and not well
# guessed
good_matched_stations = []
postal_code = flat["flatisfy"].get("postal_code", None)
if postal_code:
# If there is | |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 13 18:23:08 2019
This scrip is for training the experiement end2end
@author: li
"""
import tensorflow as tf
import models.AE as AE
import optimization.loss_tf as loss_tf
from data import read_frame_temporal as rft
import numpy as np
import os
import math
import cv2
import shutil
import const
def train_end2end(args, data_set, model_type, motion_method, version=0, bg_ind=None, augment_opt="none"):
model_mom_for_load_data = args.datadir
path_mom = args.expdir
if data_set == "ucsd1":
stat = [8,6,2,5]
train_ucsd1(stat, model_type, motion_method, version)
elif data_set == "ucsd2":
stat = [8,6,2,4]
train_ucsd2(stat, model_type, motion_method, version)
elif data_set == "avenue":
stat = [6,6,2,4]
train_avenue(stat, model_type, augment_opt, version)
elif data_set == "shanghaitech_allinone":
stat = [6,6,2,4]
train_shanghaitech_allinone(stat, model_type, version)
elif data_set == "shanghaitech_multiple":
stat = [6,6,2,4]
train_shanghaitech_multiple(stat, model_type, motion_method,
version, bg_ind)
# elif data_set is "moving_mnist":
# # 6, 6, 1, 4
# train_moving_mnist(model_mom_for_load_data, path_mom, stat, model_type, version)
def train_fps(model_mom_for_load_data, path_mom):
# 31,32,33,34
version = 0
interval_group = np.arange(11)[1:] * 2
learn_opt = "learn_fore"
data_set = "ucsd2"
motion_method = "conv3d"
model_type = "2d_2d_pure_unet"
time_step = 6
args.z_mse_ratio = 0.001
for single_interval in interval_group:
delta = single_interval
train_model(args.datadir, args.expdir, data_set, time_step, delta, model_type, motion_method,
single_interval, version,
None, 4, learn_opt)
def train_ucsd1_group():
stat = [8, 6, 2, 5]
model_type = "2d_2d_pure_unet"
motion_method = "convlstm"
version = [0, 1, 2, 3]
for single_version in version:
train_ucsd1(stat, model_type, motion_method, single_version)
def train_ucsd1(stat, model_type, motion_method, version):
data_set = "ucsd1"
time_step, delta, interval, num_enc_layer = stat
train_model(args.datadir, args.expdir, data_set, time_step, delta, model_type, motion_method,
interval, version,
None,
num_enc_layer, "learn_fore")
def train_ucsd2_group():
stat = [8, 6, 2, 4]
model_type = "2d_2d_pure_unet"
motion_method = "convlstm"
for single_version in [2, 3]:
train_ucsd2(stat, model_type, motion_method, single_version)
def train_ucsd2(stat, model_type, motion_method, version):
data_set = "ucsd2"
time_step, delta, interval, num_enc_layer = stat
train_model(args.datadir, args.expdir, data_set, time_step, delta, model_type, motion_method, interval,
version, None, num_enc_layer, "learn_fore")
def train_avenue_group():
data_dir = args.datadir
model_dir = args.expdir
stat = [6, 6, 2, 4]
motion_method = "conv3d"
augment_opt = "none"
for single_version in [2, 3]:
train_avenue(data_dir, model_dir, stat, "2d_2d_pure_unet", motion_method,
augment_opt, single_version)
def train_avenue(stat, model_type, motion_method, augment_opt, version):
data_set = "avenue"
args.augment_option = augment_opt
if augment_opt == "add_dark_auto":
learn_opt = "learn_full"
else:
learn_opt = "learn_fore"
time_step, delta, interval, num_enc_layer = stat
train_model(args.datadir, args.expdir, data_set, time_step, delta, model_type, motion_method,
interval, version,
None,
num_enc_layer, learn_opt)
def train_shanghaitech_allinone(stat, model_type, version):
motion_method = "conv3d"
time_step, delta, interval, num_enc_layer = stat
data_set = "shanghaitech"
train_model(args.datadir, args.expdir, data_set, time_step, delta, model_type,
motion_method, interval, version, None, num_enc_layer, "learn_fore")
def train_shanghaitech_multiple(stat, model_type, motion_method, version,
bg_ind=None):
if bg_ind[0] == 0:
bg_ind = [2, 3, 7, 9, 11]
for single_bg_ind in bg_ind:
train_shanghaitech_for_per_bg(args.datadir, args.expdir, stat, model_type, motion_method,
single_bg_ind, version)
def train_shanghaitech_for_per_bg(model_mom_for_load_data, path_mom, stat, model_type, motion_method, bg_ind, version):
time_step, delta, interval, num_enc_layer = stat
data_set = "shanghaitech"
train_model(model_mom_for_load_data, path_mom, data_set, time_step, delta, model_type,
motion_method, interval, version, None, num_enc_layer, "learn_fore",
bg_index_pool=[bg_ind])
def train_moving_mnist():
motion_method = "conv3d"
data_set = "moving_mnist"
version = 2
model_type = "2d_2d_unet_no_shortcut"
z_mse_ratio = 0.001
args.z_mse_ratio = z_mse_ratio
num_layer = [5]
stat_group = [[6, 2, 1]]
for single_layer in num_layer:
for single_stat in stat_group:
time_step, delta, interval = single_stat
num_enc_layer = single_layer
train_model(args.datadir, args.expdir, data_set, time_step, delta, model_type,
motion_method, interval, version, None, num_enc_layer, "learn_full")
def train_moving_mnist_single_digit(model_group):
"""This function train a pure autoencoder for moving mnist single digit dataset
The goal of this type of experiments is to hope the latent can show some pattern between
anomalies and normal"""
motion_method = "conv3d"
data_set = "moving_mnist_single_digit"
version = 1 # version 1 means the activation layer in the last convolutional block is changed from
# learky-relu to tanh
args.z_mse_ratio = 0.001
num_layer = [5, 4]
stat = [6, 2, 1]
for model_type in model_group:
for single_layer in num_layer:
time_step, delta, interval = stat
num_enc_layer = single_layer
train_model(args.datadir, args.expdir, data_set, time_step, delta, model_type,
motion_method, interval, version, None, num_enc_layer, "learn_full")
def train_seq2seq(version):
data_set = "ucsd2"
motion_method = "conv3d"
model_type = "many_to_one"
for time_step in [4, 6, 8]:
stat = [time_step, 2, 2, 4]
train_model(args.datadir, args.expdir, data_set, stat[0], stat[1], model_type,
motion_method, stat[2], version, None, stat[-1], "learn_fore", None)
def train_model(model_mom_for_load_data, path_mom, data_set, time_step, delta, model_type, motion_method,
single_interval, version, ckpt_dir, num_enc_layer, learn_opt, bg_index_pool=None):
print("-------------------Start to train the model------------------------------")
args.data_set = data_set
interval_input = np.array([single_interval])
bg_index = None
args.num_encoder_layer = num_enc_layer
args.num_decoder_layer = num_enc_layer
args.time_step = time_step
args.single_interval = single_interval
args.delta = delta
args.learn_opt = learn_opt
args.bg_index_pool = bg_index_pool
model_dir = path_mom + "ano_%s_motion_end2end/" % args.data_set
if not bg_index_pool:
model_dir = model_dir + "time_%d_delta_%d_gap_%d_%s_%s_%s_enc_%d_version_%d" % (time_step,
delta, single_interval, model_type, motion_method, learn_opt, num_enc_layer, version)
else:
model_dir = model_dir + "time_%d_delta_%d_gap_%d_%s_%s_%s_enc_%d_bg_%d_version_%d" % (
time_step,
delta, single_interval, model_type, motion_method,
learn_opt, num_enc_layer, bg_index_pool[0], version)
tmf = TrainMainFunc(args, model_mom_for_load_data, model_dir, ckpt_dir, time_step, interval_input, delta,
train_index=bg_index,
bg_index_pool=bg_index_pool)
tmf.build_running()
def read_data(model_mom, data_set, concat_option, time_step, interval_input, delta, bg_index_pool=None):
if data_set != "shanghaitech":
train_im, test_im, imshape, targ_shape = rft.get_video_data(model_mom, data_set).forward()
train_im_interval, in_shape, out_shape = rft.read_frame_interval_by_dataset(data_set, train_im,
time_step, concat_option,
interval_input, delta)
else:
train_im_group = []
if not bg_index_pool:
bg_index_pool = np.arange(13)[1:]
for single_bg_index in bg_index_pool:
if single_bg_index < 10:
bg_index = "bg_index_0%d" % single_bg_index
else:
bg_index = "bg_index_%d" % single_bg_index
print("--------loading data from bg %s---------------" % bg_index)
test_im, test_la, imshape, targ_shape = rft.get_video_data(model_mom, args.data_set).forward(bg_index)
test_im_interval, in_shape, out_shape = rft.read_frame_interval_by_dataset(data_set, test_im,
time_step, concat_option,
interval=interval_input,
delta=delta)
train_im_group.append(test_im_interval)
train_im_interval = np.array([v for j in train_im_group for v in j])
return train_im_interval, imshape, targ_shape, in_shape, out_shape
class TrainMainFunc(object):
def __init__(self, args, model_mom, model_dir, ckpt_dir, time_step, interval_input=np.array([1]), delta=None,
train_index=None, bg_index_pool=None):
if not os.path.exists(model_dir):
os.makedirs(model_dir)
concat_option = "conc_tr"
train_im_interval, imshape, targ_shape, in_shape, out_shape = read_data(model_mom, args.data_set,
concat_option, time_step,
interval_input, delta,
bg_index_pool=bg_index_pool)
args.output_dim = targ_shape[-1]
if concat_option == "conc_tr":
args.num_prediction = 1
else:
args.num_prediction = out_shape[0]
self.args = args
self.model_mom = model_mom
self.model_dir = model_dir
self.ckpt_dir = ckpt_dir
self.data_set = args.data_set
self.train_index = train_index
self.temp_shape = [in_shape, out_shape]
self.targ_shape = targ_shape
self.imshape = imshape
self.output_dim = args.output_dim
self.concat = "conc_tr"
self.time_step = time_step
self.delta = delta
self.interval = interval_input[0]
self.test_im = train_im_interval
self.input_option = args.input_option
self.augment_option = args.augment_option
self.darker_value = args.darker_value
self.learn_opt = args.learn_opt
self.model_type = args.model_type
self.z_mse_ratio = args.z_mse_ratio
[lrate_g_step, lrate_g], [lrate_z_step, lrate_z], [epoch, batch_size] = const.give_learning_rate_for_init_exp(self.args)
self.lrate_g_decay_step = lrate_g_step
self.lrate_g_init = lrate_g
self.lrate_z_decay_step = lrate_z_step
self.lrate_z_init = lrate_z
self.batch_size = batch_size
self.max_epoch = epoch
print(args)
def read_tensor(self):
imh, imw, ch = self.targ_shape
placeholder_shape = [None, 2, self.temp_shape[0][0]]
shuffle_option = True
if "/project/" in self.model_dir:
repeat = 20
else:
repeat = 1
images_in = tf.placeholder(tf.string, shape=placeholder_shape, name='tr_im_path')
image_queue = rft.dataset_input(self.model_mom, self.data_set, images_in, self.learn_opt,
self.temp_shape, self.imshape, self.targ_shape[:2], self.batch_size,
augment_option=self.augment_option,
darker_value=self.darker_value,
conc_option=self.concat, shuffle=shuffle_option,
train_index=None,
epoch_size=repeat)
image_init = image_queue.make_initializable_iterator()
image_batch = image_init.get_next()
x_input = image_batch[0] # [batch_size, num_input_channel, imh, imw, ch]
x_output = image_batch[1] # [batch_size, self.output_dim, imh, imw, ch]
im_background = image_batch[-1]
print("=========================================")
print("The input of the model", x_input)
print("The output of the model", x_output)
print("The background of the data", im_background)
print("=========================================")
x_input = tf.concat([x_input, x_output], axis=1) # th==already subtract the background.
if self.learn_opt == "learn_fore":
x_real_input = x_input + im_background
else:
x_real_input = x_input
self.x_real_input = tf.transpose(x_real_input, perm=(1, 0, 2, 3, 4))
x_input = tf.transpose(x_input, perm=(1, 0, 2, 3, 4)) # num_frame, batch_size, imh, imw, ch
# the last input of x_input is for prediction
im_background = tf.transpose(im_background, perm=(1, 0, 2, 3, 4)) # num_frame, batch_size, imh, imw, ch
if "crop" in self.input_option:
x_input = tf.reshape(x_input, shape=[(self.time_step + 1) * self.batch_size, imh, imw, ch])
crop_size = self.input_option.strip().split("crop_")[1]
crop_h, crop_w = crop_size.strip().split("_")
crop_h, crop_w = int(crop_h), int(crop_w)
x_input_crop, stride_size, crop_box_h_w = rft.get_crop_image(x_input, crop_h, crop_w)
x_input_crop = tf.concat([x_input_crop],
axis=0) # [num_regions, (num_time+1)*batch_size, crop_height, crop_weight,ch]
num_box = x_input_crop.get_shape().as_list()[0]
x_input_crop = tf.reshape(x_input_crop,
shape=[num_box, self.time_step + 1, self.batch_size, crop_h, crop_w, ch])
x_input_crop = tf.transpose(x_input_crop, perm=(1, 0, 2, 3, 4, 5))
x_input_crop = tf.reshape(x_input_crop,
shape=[self.time_step + 1, num_box * self.batch_size, crop_h, crop_w, ch])
x_input = x_input_crop # [time, num_box*batch, croph, cropw, ch]
x_input = tf.transpose(x_input, perm=(1, 0, 2, 3, 4)) # [batch, time, c_h, c_w, ch]
x_input = tf.random.shuffle(x_input)
if crop_h >= 128:
x_input = x_input[:4] # this is for batch size
print("The actual number of box", num_box)
x_input = tf.transpose(x_input, perm=(1, 0, 2, 3, 4)) # [time, batch, c_h, c_w, ch]
self.x_real_input = x_input
return images_in, x_input, image_init, im_background
def build_graph(self):
num_recons_output = self.time_step
image_placeholder, x_input, image_init, im_background = | |
cost[str(duel.chain - 2)]["choose"] = []
else:
if str(duel.chain - 1) not in mess:
mess[str(duel.chain - 1)] = {}
if "choose" not in mess[str(duel.chain - 1)]:
mess[str(duel.chain - 1)]["choose"] = []
tmp2 = {}
tmp2["det"] = field["det"]
tmp2["hide"] = (
field["hide"] if ("hide" in field) else False
)
tmp2["mine_or_other"] = field["mine_or_other"]
tmp2["x"] = x
tmp2["y"] = y
tmp2["deck_id"] = 0
tmp2["place_unique_id"] = field["det"][
"place_unique_id"
]
tmp2["user"] = user
tmp2["place"] = "field"
return_value.append(tmp2)
if monster_effect_val == 44:
if effect_cost_flag == 0:
if as_monster_effect[0] == "%":
if as_monster_effect not in timing_mess:
timing_mess[as_monster_effect]=[]
timing_mess[as_monster_effect].append(tmp2)
else:
if (
as_monster_effect
not in mess[str(duel.chain - 2)]
):
mess[str(duel.chain - 2)][
as_monster_effect
] = []
mess[str(duel.chain - 2)][
as_monster_effect
].append(tmp2)
else:
if (
as_monster_effect
not in cost[str(duel.chain - 2)]
):
cost[str(duel.chain - 2)][
as_monster_effect
] = []
cost[str(duel.chain - 2)][
as_monster_effect
].append(tmp2)
else:
if as_monster_effect[0] == "%":
if as_monster_effect not in timing_mess:
timing_mess[as_monster_effect]=[]
timing_mess[as_monster_effect].append(tmp2)
else:
if (
as_monster_effect
not in mess[str(duel.chain - 1)]
):
mess[str(duel.chain - 1)][
as_monster_effect
] = []
mess[str(duel.chain - 1)][
as_monster_effect
].append(tmp2)
else:
if str(duelobj.tmp_chain) not in cost:
cost[str(duelobj.tmp_chain)] = {}
if "choose" not in cost[str(duelobj.tmp_chain)]:
cost[str(duelobj.tmp_chain)]["choose"] = []
tmp2 = {}
tmp2["det"] = field["det"]
tmp2["hide"] = (
field["hide"] if ("hide" in field) else False
)
tmp2["x"] = x
tmp2["y"] = y
tmp2["deck_id"] = 0
tmp2["place_unique_id"] = field["det"][
"place_unique_id"
]
tmp2["user"] = user
tmp2["place"] = "field"
tmp2["mine_or_other"] = field["mine_or_other"]
return_value.append(tmp2)
if (
as_monster_effect
not in cost[str(duelobj.tmp_chain)]
):
cost[str(duelobj.tmp_chain)][
as_monster_effect
] = []
cost[str(duelobj.tmp_chain)][
as_monster_effect
].append(tmp2)
elif (user == 2 and chain_user == 1) or (user == 1 and chain_user == 2):
if (monster_effect_val == 4) or (
monster_effect_val == 5 and tmp_count == 2
):
monster_effect_det_monster = monster_effect_det["monster"]
for place in monster_effect_det_monster["place"]:
place_tmp = place["det"].split("_")
if place_tmp[2] == "1":
mine_or_other = user
elif place_tmp[2] == "2":
mine_or_other = other_user
else:
mine_or_other = 0
if place_tmp[0] == "field":
fields = duelobj.field
field = fields[x][y]
if field["kind"].find(place_tmp[1]) == -1:
continue
if field["mine_or_other"] != mine_or_other:
continue
if whether_monster == 0:
if field["det"] is not None:
return HttpResponse("error")
else:
if cost_flag == 0:
if monster_effect_val == 44:
if effect_cost_flag == 0:
if str(duel.chain - 2) not in mess:
mess[str(duel.chain - 2)] = {}
if (
"choose"
not in mess[str(duel.chain - 2)]
):
mess[str(duel.chain - 2)]["choose"] = []
elif effect_cost_flag == 1:
if str(duel.chain - 2) not in cost:
cost[str(duel.chain - 2)] = {}
if (
"choose"
not in cost[str(duel.chain - 2)]
):
cost[str(duel.chain - 2)]["choose"] = []
else:
if str(duel.chain - 1) not in mess:
mess[str(duel.chain - 1)] = {}
if "choose" not in mess[str(duel.chain - 1)]:
mess[str(duel.chain - 1)]["choose"] = []
tmp2 = {}
tmp2["det"] = field["det"]
tmp2["hide"] = (
field["hide"] if ("hide" in field) else False
)
tmp2["x"] = x
tmp2["y"] = y
tmp2["deck_id"] = 0
tmp2["user"] = other_user
tmp2["place"] = "field"
tmp2["mine_or_other"] = field["mine_or_other"]
return_value.append(tmp2)
if monster_effect_val == 44:
if effect_cost_flag == 0:
if as_monster_effect[0] == "%":
if as_monster_effect not in timing_mess:
timing_mess[as_monster_effect]=[]
timing_mess[as_monster_effect].append(tmp2)
else:
if (
as_monster_effect
not in mess[str(duel.chain - 2)]
):
mess[str(duel.chain - 2)][
as_monster_effect
] = []
mess[str(duel.chain - 2)][
as_monster_effect
].append(tmp2)
else:
if (
as_monster_effect
not in cost[str(duel.chain - 2)]
):
cost[str(duel.chain - 2)][
as_monster_effect
] = []
cost[str(duel.chain - 2)][
as_monster_effect
].append(tmp2)
else:
if as_monster_effect[0] == "%":
if as_monster_effect not in timing_mess:
timing_mess[as_monster_effect]=[]
timing_mess[as_monster_effect].append(tmp2)
else:
if (
as_monster_effect
not in mess[str(duel.chain - 1)]
):
mess[str(duel.chain - 1)][
as_monster_effect
] = []
mess[str(duel.chain - 1)][
as_monster_effect
].append(tmp2)
else:
if str(duelobj.tmp_chain) not in cost:
cost[str(duelobj.tmp_chain)] = {}
if "choose" not in cost[str(duelobj.tmp_chain)]:
cost[str(duelobj.tmp_chain)]["choose"] = []
tmp2 = {}
tmp2["det"] = field["det"]
tmp2["hide"] = (
field["hide"] if ("hide" in field) else False
)
tmp2["x"] = x
tmp2["y"] = y
tmp2["deck_id"] = 0
tmp2["user"] = other_user
tmp2["place"] = "field"
tmp2["mine_or_other"] = field["mine_or_other"]
return_value.append(tmp2)
if (
as_monster_effect
not in cost[str(duelobj.tmp_chain)]
):
cost[str(duelobj.tmp_chain)][
as_monster_effect
] = []
cost[str(duelobj.tmp_chain)][
as_monster_effect
].append(tmp2)
else:
if field["det"] is None:
return HttpResponse("error")
else:
tmp2 = {}
tmp2["det"] = field["det"]
tmp2["mine_or_other"] = field["mine_or_other"]
tmp2["user"] = chain_user
tmp2["place"] = "field"
tmp2["deck_id"] = 0
tmp2["x"] = x
tmp2["y"] = y
tmp2["place_unique_id"] = field["det"][
"place_unique_id"
]
return_value.append(tmp2)
if not duelobj.validate_answer(
tmp2,
monster_effect_det_monster,
exclude,
duel,
1,
cost_flag,
effect_kind,
user,
):
return HttpResponse("error")
check_array.append(field["det"])
if cost_flag == 0:
if monster_effect_val == 44:
if effect_cost_flag == 0:
if str(duel.chain - 2) not in mess:
mess[str(duel.chain - 2)] = {}
if (
"choose"
not in mess[str(duel.chain - 2)]
):
mess[str(duel.chain - 2)]["choose"] = []
else:
if str(duel.chain - 2) not in cost:
cost[str(duel.chain - 2)] = {}
if (
"choose"
not in cost[str(duel.chain - 2)]
):
cost[str(duel.chain - 2)]["choose"] = []
else:
if str(duel.chain - 1) not in mess:
mess[str(duel.chain - 1)] = {}
if "choose" not in mess[str(duel.chain - 1)]:
mess[str(duel.chain - 1)]["choose"] = []
tmp2 = {}
tmp2["det"] = field["det"]
tmp2["hide"] = (
field["hide"] if ("hide" in field) else False
)
tmp2["x"] = x
tmp2["y"] = y
tmp2["deck_id"] = 0
tmp2["place_unique_id"] = field["det"][
"place_unique_id"
]
tmp2["user"] = other_user
tmp2["place"] = "field"
tmp2["mine_or_other"] = field["mine_or_other"]
if monster_effect_val == 44:
if effect_cost_flag == 0:
if as_monster_effect[0] == "%":
if as_monster_effect not in timing_mess:
timing_mess[as_monster_effect]=[]
timing_mess[as_monster_effect].append(tmp2)
else:
if (
as_monster_effect
not in mess[str(duel.chain - 2)]
):
mess[str(duel.chain - 2)][
as_monster_effect
] = []
mess[str(duel.chain - 2)][
as_monster_effect
].append(tmp2)
else:
if (
as_monster_effect
not in cost[str(duel.chain - 2)]
):
cost[str(duel.chain - 2)][
as_monster_effect
] = []
cost[str(duel.chain - 2)][
as_monster_effect
].append(tmp2)
else:
if as_monster_effect[0] == "%":
if as_monster_effect not in timign_mess:
timing_mess[as_monster_effect]=[]
timing_mess[as_monster_effect].append(tmp2)
else:
if (
as_monster_effect
not in mess[str(duel.chain - 1)]
):
mess[str(duel.chain - 1)][
as_monster_effect
] = []
mess[str(duel.chain - 1)][
as_monster_effect
].append(tmp2)
else:
if str(duelobj.tmp_chain) not in cost:
cost[str(duelobj.tmp_chain)] = {}
if "choose" not in cost[str(duelobj.tmp_chain)]:
cost[str(duelobj.tmp_chain)]["choose"] = []
tmp2 = {}
tmp2["det"] = field["det"]
tmp2["hide"] = (
field["hide"] if ("hide" in field) else False
)
tmp2["x"] = x
tmp2["y"] = y
tmp2["deck_id"] = 0
tmp2["place_unique_id"] = field["det"][
"place_unique_id"
]
tmp2["user"] = other_user
tmp2["place"] = "field"
tmp2["mine_or_other"] = field["mine_or_other"]
return_value.append(tmp2)
if (
as_monster_effect
not in cost[str(duelobj.tmp_chain)]
):
cost[str(duelobj.tmp_chain)][
as_monster_effect
] = []
cost[str(duelobj.tmp_chain)][
as_monster_effect
].append(tmp2)
else:
for place in monster_effect_det_monster["place"]:
place_tmp = place["det"].split("_")
if place_tmp[0] == "field":
fields = duelobj.field
field = fields[x][y]
if field["kind"].find(place_tmp[1]) == -1:
continue
if int(field["mine_or_other"]) != 0:
continue
if whether_monster == 0:
if field["det"] is not None:
return HttpResponse("error")
else:
if cost_flag == 0:
if monster_effect_val == 44:
if effect_cost_flag == 0:
if str(duel.chain - 2) not in mess:
mess[str(duel.chain - 2)] = {}
if "choose" not in mess[str(duel.chain - 2)]:
mess[str(duel.chain - 2)]["choose"] = []
else:
if str(duel.chain - 2) not in cost:
cost[str(duel.chain - 2)] = {}
if "choose" not in cost[str(duel.chain - 2)]:
cost[str(duel.chain - 1)]["choose"] = []
else:
if str(duel.chain - 1) not in mess:
mess[str(duel.chain - 1)] = {}
if "choose" not in mess[str(duel.chain - 1)]:
mess[str(duel.chain - 1)]["choose"] = []
tmp2 = {}
tmp2["mine_or_other"] = field["mine_or_other"]
tmp2["det"] = field["det"]
tmp2["hide"] = (
field["hide"] if ("hide" in field) else False
)
tmp2["x"] = x
tmp2["y"] = y
tmp2["deck_id"] = 0
tmp2["user"] = user
tmp2["place"] = "field"
return_value.append(tmp2)
if monster_effect_val == 44:
if effect_cost_flag == 0:
if as_monster_effect[0] == "%":
if as_monster_effect not in timing_mess:
timing_mess[as_monster_effect]=[]
timing_mess[as_monster_effect].append(tmp2)
else:
if (
as_monster_effect
not in mess[str(duel.chain - 2)]
):
mess[str(duel.chain - 2)][
as_monster_effect
] = []
mess[str(duel.chain - 2)][
as_monster_effect
].append(tmp2)
else:
if (
as_monster_effect
not in cost[str(duel.chain - 2)]
):
cost[str(duel.chain - 2)][
as_monster_effect
] = []
cost[str(duel.chain - 2)][
as_monster_effect
].append(tmp2)
else:
if as_monster_effect[0] == "%":
if as_monster_effect not in timing_mess:
timing_mess[as_monster_effect]=[]
timing_mess[as_monster_effect].append(tmp2)
else:
if (
as_monster_effect
not in mess[str(duel.chain - 1)]
):
mess[str(duel.chain - 1)][
as_monster_effect
] = []
mess[str(duel.chain - 1)][as_monster_effect].append(
tmp2
)
else:
if str(duelobj.tmp_chain) not in cost:
cost[str(duelobj.tmp_chain)] = {}
if "choose" not in cost[str(duelobj.tmp_chain)]:
cost[str(duelobj.tmp_chain)]["choose"] = []
tmp2 = {}
tmp2["det"] = field["det"]
tmp2["hide"] = (
field["hide"] if ("hide" in field) else False
)
tmp2["x"] = x
tmp2["y"] = y
tmp2["deck_id"] = 0
| |
await self.bot.send_message(ctx.message.channel, bot_prefix + 'Password set. Do ``>avatar`` to toggle cycling avatars.')
@commands.command(pass_context=True, aliases=['pick'])
async def choose(self, ctx, *, choices: str):
"""Choose randomly from the options you give. >choose this | that"""
await self.bot.send_message(ctx.message.channel, bot_prefix + 'I choose: ``{}``'.format(random.choice(choices.split("|"))))
@commands.command(pass_context=True, aliases=['emote'])
async def emoji(self, ctx, *, msg):
"""Embed a custom emoji (from any server). Ex: >emoji :smug:"""
if msg.startswith('s '):
msg = msg[2:]
get_server = True
else:
get_server = False
msg = msg.strip(':')
if msg.startswith('<'):
msg = msg[2:].split(':', 1)[0].strip()
url = emoji = server = None
exact_match = False
for server in self.bot.servers:
for emoji in server.emojis:
if msg.strip().lower() in str(emoji):
url = emoji.url
if msg.strip() == str(emoji).split(':')[1]:
url = emoji.url
exact_match = True
break
if exact_match:
break
response = requests.get(emoji.url, stream=True)
name = emoji.url.split('/')[-1]
with open(name, 'wb') as img:
for block in response.iter_content(1024):
if not block:
break
img.write(block)
if attach_perms(ctx.message) and url:
if get_server:
await self.bot.send_message(ctx.message.channel, '**ID:** {}\n**Server:** {}'.format(emoji.id, server.name))
with open(name, 'rb') as fp:
await self.bot.send_file(ctx.message.channel, fp)
os.remove(name)
elif not embed_perms(ctx.message) and url:
await self.bot.send_message(ctx.message.channel, url)
else:
await self.bot.send_message(ctx.message.channel, bot_prefix + 'Could not find emoji.')
return await self.bot.delete_message(ctx.message)
@commands.command(pass_context=True)
async def ping(self, ctx):
"""Get response time."""
msgtime = ctx.message.timestamp.now()
await (await self.bot.ws.ping())
now = datetime.datetime.now()
ping = now - msgtime
if embed_perms(ctx.message):
pong = discord.Embed(title='Pong! Response Time:', description=str(ping.microseconds/1000.0) + ' ms', color=0x7A0000)
pong.set_thumbnail(url='http://odysseedupixel.fr/wp-content/gallery/pong/pong.jpg')
await self.bot.send_message(ctx.message.channel, content=None, embed=pong)
else:
await self.bot.send_message(ctx.message.channel, bot_prefix + '``Response Time: %s ms``' % str(ping.microseconds/1000.0))
@commands.command(pass_context=True)
async def quote(self, ctx, *, msg: str = None):
"""Quote a message. >help quote for more info.
>quote - quotes the last message sent in the channel.
>quote <words> - tries to search for a message in the server that contains the given words and quotes it.
>quote <message_id> - quotes the message with the given message id. Ex: >quote 302355374524644290(Enable developer mode to copy message ids)."""
result = channel = None
await self.bot.delete_message(ctx.message)
quote_cmd = ctx.message.content.split(' ', 1)[0]
if msg:
try:
length = len(self.bot.all_log[ctx.message.channel.id + ' ' + ctx.message.server.id])
if length < 201:
size = length
else:
size = 200
for channel in ctx.message.server.channels:
if str(channel.type) == 'text':
if channel.id + ' ' + ctx.message.server.id in self.bot.all_log:
for i in range(length - 2, length - size, -1):
try:
search = self.bot.all_log[channel.id + ' ' + ctx.message.server.id][i]
except:
continue
if (msg.lower().strip() in search[0].content.lower() and (search[0].author != ctx.message.author or not search[0].content.startswith(quote_cmd))) or ctx.message.content[6:].strip() == search[0].id:
result = search[0]
break
if result:
break
except:
pass
if not result:
for channel in ctx.message.server.channels:
try:
async for sent_message in self.bot.logs_from(channel, limit=500):
if (msg.lower().strip() in sent_message.content.lower() and (sent_message.author != ctx.message.author or not sent_message.content.startswith(quote_cmd))) or msg.strip() == sent_message.id:
result = sent_message
break
except:
pass
if result:
break
else:
channel = ctx.message.channel
search = self.bot.all_log[ctx.message.channel.id + ' ' + ctx.message.server.id][-2]
result = search[0]
if result:
if embed_perms(ctx.message) and result.content:
em = discord.Embed(description=result.content, timestamp=result.timestamp, color=0xbc0b0b)
em.set_author(name=result.author.name, icon_url=result.author.avatar_url)
if channel != ctx.message.channel:
em.set_footer(text='Sent in: {}'.format(channel.name))
await self.bot.send_message(ctx.message.channel, embed=em)
else:
await self.bot.send_message(ctx.message.channel, '%s - %s```%s```' % (result.author.name, result.timestamp, result.content))
else:
await self.bot.send_message(ctx.message.channel, bot_prefix + 'No quote found.')
@commands.command(pass_context=True)
async def poll(self, ctx, *, msg):
"""Create a strawpoll. Ex: >poll Favorite color = Blue | Red | Green"""
loop = asyncio.get_event_loop()
try:
options = [op.strip() for op in msg.split('|')]
if '=' in options[0]:
title, options[0] = options[0].split('=')
options[0] = options[0].strip()
else:
title = 'Poll by %s' % ctx.message.author.name
except:
return await self.bot.send_message(ctx.message.channel, bot_prefix + 'Invalid Syntax. Example use: ``>poll Favorite color = Blue | Red | Green | Purple``')
poll = await loop.run_in_executor(None, strawpy.create_poll, title.strip(), options)
await self.bot.send_message(ctx.message.channel, bot_prefix + poll.url)
@commands.command(pass_context=True)
async def calc(self, ctx, *, msg):
"""Simple calculator. Ex: >calc 2+2"""
equation = msg.strip().replace('^', '**')
if '=' in equation:
left = eval(equation.split('=')[0])
right = eval(equation.split('=')[1])
answer = str(left == right)
else:
answer = str(eval(equation))
if embed_perms(ctx.message):
em = discord.Embed(color=0xD3D3D3, title='Calculator')
em.add_field(name='Input:', value=msg.replace('**', '^'), inline=False)
em.add_field(name='Output:', value=answer, inline=False)
await self.bot.send_message(ctx.message.channel, content=None, embed=em)
await self.bot.delete_message(ctx.message)
else:
await self.bot.send_message(ctx.message.channel, bot_prefix + answer)
@commands.command(pass_context=True)
async def l2g(self, ctx, *, msg: str):
"""Creates a googleitfor.me link. Ex: >l2g how do i become cool."""
lmgtfy = 'http://googleitfor.me/?q='
await self.bot.send_message(ctx.message.channel, bot_prefix + lmgtfy + msg.lower().strip().replace(' ', '+'))
await self.bot.delete_message(ctx.message)
@commands.command(pass_context=True)
async def d(self, ctx, *, txt: str = None):
"""Deletes the last message sent or n messages sent. Ex: >d 5"""
# If number of seconds/messages are specified
if txt:
if txt[0] == '!':
killmsg = self.bot.self_log[ctx.message.channel.id][len(self.bot.self_log[ctx.message.channel.id]) - 2]
timer = int(txt[1:].strip())
# Animated countdown because screw rate limit amirite
destroy = await self.bot.edit_message(ctx.message, bot_prefix + 'The above message will self-destruct in:')
msg = await self.bot.send_message(ctx.message.channel, '``%s |``' % timer)
for i in range(0, timer, 4):
if timer - 1 - i == 0:
await self.bot.delete_message(destroy)
msg = await self.bot.edit_message(msg, '``0``')
break
else:
msg = await self.bot.edit_message(msg, '``%s |``' % int(timer - 1 - i))
await asyncio.sleep(1)
if timer - 1 - i != 0:
if timer - 2 - i == 0:
await self.bot.delete_message(destroy)
msg = await self.bot.edit_message(msg, '``0``')
break
else:
msg = await self.bot.edit_message(msg, '``%s /``' % int(timer - 2 - i))
await asyncio.sleep(1)
if timer - 2 - i != 0:
if timer - 3 - i == 0:
await self.bot.delete_message(destroy)
msg = await self.bot.edit_message(msg, '``0``')
break
else:
msg = await self.bot.edit_message(msg, '``%s -``' % int(timer - 3 - i))
await asyncio.sleep(1)
if timer - 3 - i != 0:
if timer - 4 - i == 0:
await self.bot.delete_message(destroy)
msg = await self.bot.edit_message(msg, '``0``')
break
else:
msg = await self.bot.edit_message(msg, '``%s \ ``' % int(timer - 4 - i))
await asyncio.sleep(1)
await self.bot.edit_message(msg, ':bomb:')
await asyncio.sleep(.5)
await self.bot.edit_message(msg, ':fire:')
await self.bot.edit_message(killmsg, ':fire:')
await asyncio.sleep(.5)
await self.bot.delete_message(msg)
await self.bot.delete_message(killmsg)
else:
await self.bot.delete_message(ctx.message)
deleted = 0
async for sent_message in self.bot.logs_from(ctx.message.channel, limit=200):
if sent_message.author == ctx.message.author:
try:
await self.bot.delete_message(sent_message)
deleted += 1
except:
pass
if deleted == int(txt):
break
# If no number specified, delete message immediately
else:
await self.bot.delete_message(self.bot.self_log[ctx.message.channel.id].pop())
await self.bot.delete_message(self.bot.self_log[ctx.message.channel.id].pop())
@commands.command(pass_context=True)
async def spoiler(self, ctx, *, msg: str):
"""Spoiler tag. Ex: >spoiler Some book | They get married."""
try:
if " | " in msg:
spoiled_work, spoiler = msg.lower().split(" | ", 1)
else:
spoiled_work, _, spoiler = msg.lower().partition(" ")
await self.bot.edit_message(ctx.message, bot_prefix + 'Spoiler for `' + spoiled_work + '`: \n`'
+ ''.join(map(lambda c: chr(ord('a') + (((ord(c) - ord('a')) + 13) % 26)) if c >= 'a' and c <= 'z' else c, spoiler))
+ '`\n' + bot_prefix + 'Use http://rot13.com to decode')
except:
await self.bot.send_message(ctx.message.channel, bot_prefix + 'Could not encrypt spoiler.')
@commands.group(pass_context=True)
async def gist(self, ctx):
"""Posts to gist"""
if ctx.invoked_subcommand is None:
pre = cmd_prefix_len()
url = PythonGists.Gist(description='Created in channel: {} in server: {}'.format(ctx.message.channel, ctx.message.server), content=ctx.message.content[4 + pre:].strip(), name='Output')
await self.bot.send_message(ctx.message.channel, bot_prefix + 'Gist output: ' + url)
await self.bot.delete_message(ctx.message)
@gist.command(pass_context=True)
async def file(self, ctx, *, msg):
"""Create gist of file"""
try:
with open(msg) as fp:
output = fp.read()
url = PythonGists.Gist(description='Created in channel: {} in server: {}'.format(ctx.message.channel, ctx.message.server), content=output, name=msg.replace('/', '.'))
await self.bot.send_message(ctx.message.channel, bot_prefix + 'Gist output: ' + url)
except:
await self.bot.send_message(ctx.message.channel, bot_prefix + 'File not found.')
finally:
await self.bot.delete_message(ctx.message)
@commands.command(pass_context=True)
async def regional(self, ctx, *, msg):
"""Replace letters with regional indicator emojis"""
await self.bot.delete_message(ctx.message)
msg = list(msg)
regional_list = [self.regionals[x.lower()] if x.isalnum() or x == '!' or x == '?' else x for x in msg]
regional_output = ' '.join(regional_list)
await self.bot.send_message(ctx.message.channel, regional_output)
@commands.command(pass_context=True)
async def space(self, ctx, *, msg):
"""Add n spaces between each letter. Ex: >space 2 thicc"""
await self.bot.delete_message(ctx.message)
if msg.split(' ', 1)[0].isdigit():
spaces = int(msg.split(' ', 1)[0]) * ' '
msg = msg.split(' ', 1)[1].strip()
else:
spaces = ' '
spaced_message = '{}'.format(spaces).join(list(msg))
await self.bot.send_message(ctx.message.channel, spaced_message)
@commands.command(pass_context=True)
async def uni(self, ctx, *, msg: str):
"""Convert to unicode emoji if possilbe. Ex: >uni :eyes:"""
await self.bot.send_message(ctx.message.channel, "`"+msg.replace("`", "")+"`")
# given String react_me, return a list of emojis that can construct the string with no duplicates (for the purpose of reacting)
# TODO make it consider reactions already applied to the message
@commands.command(pass_context=True, aliases=['r'])
| |
<gh_stars>10-100
import cv2
import numpy as np
import torchvision.datasets as datasets
class CIFAR10Noise(datasets.CIFAR10):
"""CIFAR10 Dataset with noise.
Args:
clip (bool): If True, clips a value between 0 and 1 (default: True).
seed (int): Random seed (default: 0).
This is a subclass of the `CIFAR10` Dataset.
"""
def __init__(self, clip=True, seed=0, **kwargs):
self.clip = clip
self.seed = seed
super(CIFAR10Noise, self).__init__(**kwargs)
assert (seed + 1) * len(self) - 1 <= 2**32 - 1
def __getitem__(self, index):
img, target = self.data[index], self.targets[index]
noise = self.generate_noise(index)
img = img / 255.
noise = noise / 255.
img = img + noise
img, target = self.postprocess(img, target)
return img, target
def postprocess(self, img, target):
if self.clip:
img = np.clip(img, 0., 1.)
if self.transform is not None:
img = img.astype(np.float32)
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def generate_noise(self):
raise NotImplementedError
class CIFAR10AdditiveGaussianNoise(CIFAR10Noise):
"""CIFAR10 Dataset with additive Gaussian noise.
Args:
noise_scale (float): The standard deviation of additive Gaussian noise
(default: 25.).
noise_scale_high (float): The upper bound of the standard deviation of
additive Gaussian noise (default: None, i.e., `noise_scale`).
This is a subclass of the `CIFAR10Noise` Dataset.
"""
def __init__(self, noise_scale=25., noise_scale_high=None, **kwargs):
self.noise_scale = noise_scale
self.noise_scale_high = noise_scale_high
super(CIFAR10AdditiveGaussianNoise, self).__init__(**kwargs)
def generate_noise(self, index):
rng = np.random.RandomState(self.seed * len(self) + index)
if self.noise_scale_high is None:
noise_scale = self.noise_scale
else:
noise_scale = rng.uniform(self.noise_scale, self.noise_scale_high)
return rng.randn(*self.data[index].shape) * noise_scale
class CIFAR10LocalGaussianNoise(CIFAR10Noise):
"""CIFAR10 Dataset with local Gaussian noise.
Args:
noise_scale (float): The standard deviation of additive Gaussian noise
(default: 25.).
patch_size (int): The height/width of the noise patch (default: 16.).
noise_scale_high (float): The upper bound of the standard deviation of
additive Gaussian noise (default: None, i.e., `noise_scale`).
patch_max_size (int): The maximum height/width of the noise patch
(default: None, i.e., `patch_size`).
This is a subclass of the `CIFAR10Noise` Dataset.
"""
def __init__(self,
noise_scale=25.,
patch_size=16,
noise_scale_high=None,
patch_max_size=None,
**kwargs):
self.noise_scale = noise_scale
self.patch_size = patch_size
self.noise_scale_high = noise_scale_high
self.patch_max_size = patch_max_size
super(CIFAR10LocalGaussianNoise, self).__init__(**kwargs)
def generate_noise(self, index):
rng = np.random.RandomState(self.seed * len(self) + index)
patch_shape = (self.data[index].shape[0], self.data[index].shape[1], 1)
patch = np.zeros(patch_shape, dtype=np.uint8)
if self.patch_max_size is None:
patch_width = self.patch_size
patch_height = self.patch_size
else:
patch_width = rng.randint(self.patch_size, self.patch_max_size + 1)
patch_height = rng.randint(self.patch_size,
self.patch_max_size + 1)
x = rng.randint(0, patch_shape[1] - patch_width + 1)
y = rng.randint(0, patch_shape[0] - patch_height + 1)
patch[y:y + patch_height, x:x + patch_width] = 1
if self.noise_scale_high is None:
noise_scale = self.noise_scale
else:
noise_scale = rng.uniform(self.noise_scale, self.noise_scale_high)
noise = rng.randn(*self.data[index].shape) * noise_scale
return noise * patch
class CIFAR10UniformNoise(CIFAR10Noise):
"""CIFAR10 Dataset with uniform noise.
Args:
noise_scale (float): The scale of uniform noise (default: 50.).
noise_scale_high (float): The upper bound of the scale of uniform noise
(default: None, i.e., `noise_scale`).
This is a subclass of the `CIFAR10Noise` Dataset.
"""
def __init__(self, noise_scale=50., noise_scale_high=None, **kwargs):
self.noise_scale = noise_scale
self.noise_scale_high = noise_scale_high
super(CIFAR10UniformNoise, self).__init__(**kwargs)
def generate_noise(self, index):
rng = np.random.RandomState(self.seed * len(self) + index)
if self.noise_scale_high is None:
noise_scale = self.noise_scale
else:
noise_scale = rng.uniform(self.noise_scale, self.noise_scale_high)
return rng.uniform(-1, 1, self.data[index].shape) * noise_scale
class CIFAR10MixtureNoise(CIFAR10Noise):
"""CIFAR10 Dataset with mixture noise.
Args:
noise_scale_list (float list): The values, except for the last one,
indicate the standard deviations of additive Gaussian noises. The
last value indicates the scale of uniform noise (default:
[15., 25., 50.]).
mixture_rate_list (float list): The mixture rates of the noises
(default: [0.7, 0.2, 0.1]).
This is a subclass of the `CIFAR10Noise` Dataset.
"""
def __init__(self,
noise_scale_list=[15., 25., 50.],
mixture_rate_list=[0.7, 0.2, 0.1],
**kwargs):
self.noise_scale_list = noise_scale_list
self.mixture_rate_list = mixture_rate_list
super(CIFAR10MixtureNoise, self).__init__(**kwargs)
def generate_noise(self, index):
rng = np.random.RandomState(self.seed * len(self) + index)
height, width, channel = list(self.data[index].shape)
noise = np.zeros((height * width, channel))
perm = rng.permutation(height * width)
rand = rng.rand(height * width)
cumsum = np.cumsum([0] + self.mixture_rate_list)
for i, noise_scale in enumerate(self.noise_scale_list):
inds = (rand >= cumsum[i]) * (rand < cumsum[i + 1])
if i == len(self.noise_scale_list) - 1:
noise[perm[inds], :] = rng.uniform(
-1, 1, (np.sum(inds), channel)) * noise_scale
else:
noise[perm[inds], :] = rng.randn(np.sum(inds),
channel) * noise_scale
noise = np.reshape(noise, (height, width, channel))
return noise
class CIFAR10BrownGaussianNoise(CIFAR10Noise):
"""CIFAR10 Dataset with Brown Gaussian noise.
Args:
noise_scale (float): The standard deviation of additive Gaussian noise
(default: 25.).
noise_scale_high (float): The upper bound of the standard deviation of
additive Gaussian noise (default: None, i.e., `noise_scale`).
kernel_size (int): The Gaussian kernel size (default: 5).
This is a subclass of the `CIFAR10Noise` Dataset.
"""
def __init__(self,
noise_scale=25.,
noise_scale_high=None,
kernel_size=5,
**kwargs):
self.noise_scale = noise_scale
self.noise_scale_high = noise_scale_high
self.kernel_size = kernel_size
super(CIFAR10BrownGaussianNoise, self).__init__(**kwargs)
self.kernel = (cv2.getGaussianKernel(kernel_size, 0) *
cv2.getGaussianKernel(kernel_size, 0).transpose())
def generate_noise(self, index):
rng = np.random.RandomState(self.seed * len(self) + index)
if self.noise_scale_high is None:
noise_scale = self.noise_scale
else:
noise_scale = rng.uniform(self.noise_scale, self.noise_scale_high)
noise = rng.randn(*self.data[index].shape) * noise_scale
return (cv2.GaussianBlur(noise, (self.kernel_size, self.kernel_size),
0,
borderType=cv2.BORDER_CONSTANT) /
np.sqrt(np.sum(self.kernel**2)))
class CIFAR10AdditiveBrownGaussianNoise(CIFAR10Noise):
"""CIFAR10 Dataset with additive Brown Gaussian noise.
Args:
noise_scale (float): The standard deviation of additive Gaussian noise
(default: 25.).
noise_scale_high (float): The upper bound of the standard deviation of
additive Gaussian noise (default: None, i.e., `noise_scale`).
kernel_size (int): The Gaussian kernel size (default: 5).
This is a subclass of the `CIFAR10Noise` Dataset.
"""
def __init__(self,
noise_scale=25.,
noise_scale_high=None,
kernel_size=5,
**kwargs):
self.noise_scale = noise_scale
self.noise_scale_high = noise_scale_high
self.kernel_size = kernel_size
super(CIFAR10AdditiveBrownGaussianNoise, self).__init__(**kwargs)
self.kernel = (cv2.getGaussianKernel(kernel_size, 0) *
cv2.getGaussianKernel(kernel_size, 0).transpose())
def generate_noise(self, index):
rng = np.random.RandomState(self.seed * len(self) + index)
if self.noise_scale_high is None:
noise_scale = self.noise_scale
else:
noise_scale = rng.uniform(self.noise_scale, self.noise_scale_high)
noise = rng.randn(*self.data[index].shape) * noise_scale
return noise + (cv2.GaussianBlur(noise,
(self.kernel_size, self.kernel_size),
0,
borderType=cv2.BORDER_CONSTANT) /
np.sqrt(np.sum(self.kernel**2)))
class CIFAR10MultiplicativeGaussianNoise(CIFAR10Noise):
"""CIFAR10 Dataset with multiplicative Gaussian noise.
Args:
multi_noise_scale (float): The standard deviation of multiplicative
Gaussian noise (default: 25.).
multi_noise_scale_high (float): The upper bound of the standard
deviation of multiplicative Gaussian noise (default: None, i.e.,
`multi_noise_scale`).
This is a subclass of the `CIFAR10Noise` Dataset.
"""
def __init__(self,
multi_noise_scale=25.,
multi_noise_scale_high=None,
**kwargs):
self.multi_noise_scale = multi_noise_scale
self.multi_noise_scale_high = multi_noise_scale_high
super(CIFAR10MultiplicativeGaussianNoise, self).__init__(**kwargs)
def __getitem__(self, index):
rng = np.random.RandomState(self.seed * len(self) + index)
img, target = self.data[index], self.targets[index]
img = img / 255.
if self.multi_noise_scale_high is None:
multi_noise_scale = self.multi_noise_scale
else:
multi_noise_scale = rng.uniform(self.multi_noise_scale,
self.multi_noise_scale_high)
noise = rng.randn(*img.shape) * multi_noise_scale * img / 255.
img = img + noise
img, target = self.postprocess(img, target)
return img, target
class CIFAR10AdditiveMultiplicativeGaussianNoise(CIFAR10Noise):
"""CIFAR10 Dataset with additive and multiplicative Gaussian noise.
Args:
noise_scale (float): The standard deviation of additive Gaussian noise
(default: 25.).
multi_noise_scale (float): The standard deviation of multiplicative
Gaussian noise (default: 25.).
noise_scale_high (float): The upper bound of the standard deviation of
additive Gaussian noise (default: None, i.e., `noise_scale`).
multi_noise_scale_high (float): The upper bound of the standard
deviation of multiplicative Gaussian noise (default: None, i.e.,
`multi_noise_scale`).
This is a subclass of the `CIFAR10Noise` Dataset.
"""
def __init__(self,
noise_scale=25.,
multi_noise_scale=25.,
noise_scale_high=None,
multi_noise_scale_high=None,
**kwargs):
self.noise_scale = noise_scale
self.multi_noise_scale = multi_noise_scale
self.noise_scale_high = noise_scale_high
self.multi_noise_scale_high = multi_noise_scale_high
super(CIFAR10AdditiveMultiplicativeGaussianNoise,
self).__init__(**kwargs)
def __getitem__(self, index):
rng = np.random.RandomState(self.seed * len(self) + index)
img, target = self.data[index], self.targets[index]
img = img / 255.
if self.multi_noise_scale_high is None:
multi_noise_scale = self.multi_noise_scale
else:
multi_noise_scale = rng.uniform(self.multi_noise_scale,
self.multi_noise_scale_high)
noise = rng.randn(*img.shape) * multi_noise_scale * img / 255.
if self.noise_scale_high is None:
noise_scale = self.noise_scale
else:
noise_scale = rng.uniform(self.noise_scale, self.noise_scale_high)
noise = noise + rng.randn(*img.shape) * noise_scale / 255.
img = img + noise
img, target = self.postprocess(img, target)
return img, target
class CIFAR10PoissonNoise(CIFAR10Noise):
"""CIFAR10 Dataset with Poisson noise.
Args:
noise_lam (float): The total number of events for Poisson noise
(default: 30.).
noise_lam_high (float): The maximum total number of events for Poisson
noise (default: None, i.e., `noise_lam`).
This is a subclass of the `CIFAR10Noise` Dataset.
"""
def __init__(self, noise_lam=30., noise_lam_high=None, **kwargs):
self.noise_lam = noise_lam
self.noise_lam_high = noise_lam_high
super(CIFAR10PoissonNoise, self).__init__(**kwargs)
def __getitem__(self, index):
rng = np.random.RandomState(self.seed * len(self) + index)
img, target = self.data[index], self.targets[index]
img = img / 255.
if self.noise_lam_high is None:
noise_lam = self.noise_lam
else:
noise_lam = rng.uniform(self.noise_lam, self.noise_lam_high)
img = rng.poisson(noise_lam * img) / noise_lam
img, target = self.postprocess(img, target)
return img, target
class CIFAR10PoissonGaussianNoise(CIFAR10Noise):
"""CIFAR10 Dataset with Poisson-Gaussian noise.
Args:
noise_lam (float): The total number of events for Poisson noise
(default: 30.).
| |
# and also in pairwise_distances()!
"cityblock": manhattan_distances,
"cosine": cosine_distances,
"euclidean": euclidean_distances,
"haversine": haversine_distances,
"l2": euclidean_distances,
"l1": manhattan_distances,
"manhattan": manhattan_distances,
"precomputed": None, # HACK: precomputed is always allowed, never called
"nan_euclidean": nan_euclidean_distances,
}
def distance_metrics():
"""Valid metrics for pairwise_distances.
This function simply returns the valid pairwise distance metrics.
It exists to allow for a description of the mapping for
each of the valid strings.
The valid distance metrics, and the function they map to, are:
=============== ========================================
metric Function
=============== ========================================
'cityblock' metrics.pairwise.manhattan_distances
'cosine' metrics.pairwise.cosine_distances
'euclidean' metrics.pairwise.euclidean_distances
'haversine' metrics.pairwise.haversine_distances
'l1' metrics.pairwise.manhattan_distances
'l2' metrics.pairwise.euclidean_distances
'manhattan' metrics.pairwise.manhattan_distances
'nan_euclidean' metrics.pairwise.nan_euclidean_distances
=============== ========================================
Read more in the :ref:`User Guide <metrics>`.
"""
return PAIRWISE_DISTANCE_FUNCTIONS
def _dist_wrapper(dist_func, dist_matrix, slice_, *args, **kwargs):
"""Write in-place to a slice of a distance matrix."""
dist_matrix[:, slice_] = dist_func(*args, **kwargs)
def _parallel_pairwise(X, Y, func, n_jobs, **kwds):
"""Break the pairwise matrix in n_jobs even slices
and compute them in parallel."""
if Y is None:
Y = X
X, Y, dtype = _return_float_dtype(X, Y)
if effective_n_jobs(n_jobs) == 1:
return func(X, Y, **kwds)
# enforce a threading backend to prevent data communication overhead
fd = delayed(_dist_wrapper)
ret = np.empty((X.shape[0], Y.shape[0]), dtype=dtype, order="F")
Parallel(backend="threading", n_jobs=n_jobs)(
fd(func, ret, s, X, Y[s], **kwds)
for s in gen_even_slices(_num_samples(Y), effective_n_jobs(n_jobs))
)
if (X is Y or Y is None) and func is euclidean_distances:
# zeroing diagonal for euclidean norm.
# TODO: do it also for other norms.
np.fill_diagonal(ret, 0)
return ret
def _pairwise_callable(X, Y, metric, force_all_finite=True, **kwds):
"""Handle the callable case for pairwise_{distances,kernels}."""
X, Y = check_pairwise_arrays(X, Y, force_all_finite=force_all_finite)
if X is Y:
# Only calculate metric for upper triangle
out = np.zeros((X.shape[0], Y.shape[0]), dtype="float")
iterator = itertools.combinations(range(X.shape[0]), 2)
for i, j in iterator:
out[i, j] = metric(X[i], Y[j], **kwds)
# Make symmetric
# NB: out += out.T will produce incorrect results
out = out + out.T
# Calculate diagonal
# NB: nonzero diagonals are allowed for both metrics and kernels
for i in range(X.shape[0]):
x = X[i]
out[i, i] = metric(x, x, **kwds)
else:
# Calculate all cells
out = np.empty((X.shape[0], Y.shape[0]), dtype="float")
iterator = itertools.product(range(X.shape[0]), range(Y.shape[0]))
for i, j in iterator:
out[i, j] = metric(X[i], Y[j], **kwds)
return out
_VALID_METRICS = [
"euclidean",
"l2",
"l1",
"manhattan",
"cityblock",
"braycurtis",
"canberra",
"chebyshev",
"correlation",
"cosine",
"dice",
"hamming",
"jaccard",
"kulsinski",
"mahalanobis",
"matching",
"minkowski",
"rogerstanimoto",
"russellrao",
"seuclidean",
"sokalmichener",
"sokalsneath",
"sqeuclidean",
"yule",
"wminkowski",
"nan_euclidean",
"haversine",
]
_NAN_METRICS = ["nan_euclidean"]
def _check_chunk_size(reduced, chunk_size):
"""Checks chunk is a sequence of expected size or a tuple of same."""
if reduced is None:
return
is_tuple = isinstance(reduced, tuple)
if not is_tuple:
reduced = (reduced,)
if any(isinstance(r, tuple) or not hasattr(r, "__iter__") for r in reduced):
raise TypeError(
"reduce_func returned %r. Expected sequence(s) of length %d."
% (reduced if is_tuple else reduced[0], chunk_size)
)
if any(_num_samples(r) != chunk_size for r in reduced):
actual_size = tuple(_num_samples(r) for r in reduced)
raise ValueError(
"reduce_func returned object of length %s. "
"Expected same length as input: %d."
% (actual_size if is_tuple else actual_size[0], chunk_size)
)
def _precompute_metric_params(X, Y, metric=None, **kwds):
"""Precompute data-derived metric parameters if not provided."""
if metric == "seuclidean" and "V" not in kwds:
# There is a bug in scipy < 1.5 that will cause a crash if
# X.dtype != np.double (float64). See PR #15730
dtype = np.float64 if sp_version < parse_version("1.5") else None
if X is Y:
V = np.var(X, axis=0, ddof=1, dtype=dtype)
else:
raise ValueError(
"The 'V' parameter is required for the seuclidean metric "
"when Y is passed."
)
return {"V": V}
if metric == "mahalanobis" and "VI" not in kwds:
if X is Y:
VI = np.linalg.inv(np.cov(X.T)).T
else:
raise ValueError(
"The 'VI' parameter is required for the mahalanobis metric "
"when Y is passed."
)
return {"VI": VI}
return {}
def pairwise_distances_chunked(
X,
Y=None,
*,
reduce_func=None,
metric="euclidean",
n_jobs=None,
working_memory=None,
**kwds,
):
"""Generate a distance matrix chunk by chunk with optional reduction.
In cases where not all of a pairwise distance matrix needs to be stored at
once, this is used to calculate pairwise distances in
``working_memory``-sized chunks. If ``reduce_func`` is given, it is run
on each chunk and its return values are concatenated into lists, arrays
or sparse matrices.
Parameters
----------
X : ndarray of shape (n_samples_X, n_samples_X) or \
(n_samples_X, n_features)
Array of pairwise distances between samples, or a feature array.
The shape the array should be (n_samples_X, n_samples_X) if
metric='precomputed' and (n_samples_X, n_features) otherwise.
Y : ndarray of shape (n_samples_Y, n_features), default=None
An optional second feature array. Only allowed if
metric != "precomputed".
reduce_func : callable, default=None
The function which is applied on each chunk of the distance matrix,
reducing it to needed values. ``reduce_func(D_chunk, start)``
is called repeatedly, where ``D_chunk`` is a contiguous vertical
slice of the pairwise distance matrix, starting at row ``start``.
It should return one of: None; an array, a list, or a sparse matrix
of length ``D_chunk.shape[0]``; or a tuple of such objects. Returning
None is useful for in-place operations, rather than reductions.
If None, pairwise_distances_chunked returns a generator of vertical
chunks of the distance matrix.
metric : str or callable, default='euclidean'
The metric to use when calculating distance between instances in a
feature array. If metric is a string, it must be one of the options
allowed by scipy.spatial.distance.pdist for its metric parameter, or
a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS.
If metric is "precomputed", X is assumed to be a distance matrix.
Alternatively, if metric is a callable function, it is called on each
pair of instances (rows) and the resulting value recorded. The callable
should take two arrays from X as input and return a value indicating
the distance between them.
n_jobs : int, default=None
The number of jobs to use for the computation. This works by breaking
down the pairwise matrix into n_jobs even slices and computing them in
parallel.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
working_memory : int, default=None
The sought maximum memory for temporary distance matrix chunks.
When None (default), the value of
``sklearn.get_config()['working_memory']`` is used.
`**kwds` : optional keyword parameters
Any further parameters are passed directly to the distance function.
If using a scipy.spatial.distance metric, the parameters are still
metric dependent. See the scipy docs for usage examples.
Yields
------
D_chunk : {ndarray, sparse matrix}
A contiguous slice of distance matrix, optionally processed by
``reduce_func``.
Examples
--------
Without reduce_func:
>>> import numpy as np
>>> from sklearn.metrics import pairwise_distances_chunked
>>> X = np.random.RandomState(0).rand(5, 3)
>>> D_chunk = next(pairwise_distances_chunked(X))
>>> D_chunk
array([[0. ..., 0.29..., 0.41..., 0.19..., 0.57...],
[0.29..., 0. ..., 0.57..., 0.41..., 0.76...],
[0.41..., 0.57..., 0. ..., 0.44..., 0.90...],
[0.19..., 0.41..., 0.44..., 0. ..., 0.51...],
[0.57..., 0.76..., 0.90..., 0.51..., 0. ...]])
Retrieve all neighbors and average distance within radius r:
>>> r = .2
>>> def reduce_func(D_chunk, start):
... neigh = [np.flatnonzero(d < r) for d in D_chunk]
... avg_dist = (D_chunk * (D_chunk < r)).mean(axis=1)
... return neigh, avg_dist
>>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func)
>>> neigh, avg_dist = next(gen)
>>> neigh
[array([0, 3]), array([1]), array([2]), array([0, 3]), array([4])]
>>> avg_dist
array([0.039..., 0. , 0. , 0.039..., 0. ])
Where r is defined per sample, we need to make use of ``start``:
>>> r = [.2, .4, .4, .3, .1]
>>> def reduce_func(D_chunk, start):
... neigh = [np.flatnonzero(d < r[i])
... for i, d in enumerate(D_chunk, start)]
... return neigh
>>> neigh = next(pairwise_distances_chunked(X, reduce_func=reduce_func))
>>> neigh
[array([0, 3]), array([0, 1]), array([2]), array([0, 3]), array([4])]
Force row-by-row generation by reducing ``working_memory``:
>>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func,
... working_memory=0)
>>> next(gen)
[array([0, 3])]
>>> next(gen)
[array([0, 1])]
"""
n_samples_X = _num_samples(X)
if metric == "precomputed":
slices = (slice(0, n_samples_X),)
else:
if Y is None:
Y = X
# We get as many rows as possible within our working_memory budget to
# store len(Y) distances in each row of output.
#
# Note:
# - this will get at least 1 row, even if | |
LDAP domain to use for users (eg: ou=People,dc=example,dc=org)`.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: SecretBackendArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
## Import
AD secret backend can be imported using the `backend`, e.g.
```sh
$ pulumi import vault:ad/secretBackend:SecretBackend ad ad
```
:param str resource_name: The name of the resource.
:param SecretBackendArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(SecretBackendArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
anonymous_group_search: Optional[pulumi.Input[bool]] = None,
backend: Optional[pulumi.Input[str]] = None,
binddn: Optional[pulumi.Input[str]] = None,
bindpass: Optional[pulumi.Input[str]] = None,
case_sensitive_names: Optional[pulumi.Input[bool]] = None,
certificate: Optional[pulumi.Input[str]] = None,
client_tls_cert: Optional[pulumi.Input[str]] = None,
client_tls_key: Optional[pulumi.Input[str]] = None,
default_lease_ttl_seconds: Optional[pulumi.Input[int]] = None,
deny_null_bind: Optional[pulumi.Input[bool]] = None,
description: Optional[pulumi.Input[str]] = None,
discoverdn: Optional[pulumi.Input[bool]] = None,
groupattr: Optional[pulumi.Input[str]] = None,
groupdn: Optional[pulumi.Input[str]] = None,
groupfilter: Optional[pulumi.Input[str]] = None,
insecure_tls: Optional[pulumi.Input[bool]] = None,
last_rotation_tolerance: Optional[pulumi.Input[int]] = None,
local: Optional[pulumi.Input[bool]] = None,
max_lease_ttl_seconds: Optional[pulumi.Input[int]] = None,
max_ttl: Optional[pulumi.Input[int]] = None,
password_policy: Optional[pulumi.Input[str]] = None,
request_timeout: Optional[pulumi.Input[int]] = None,
starttls: Optional[pulumi.Input[bool]] = None,
tls_max_version: Optional[pulumi.Input[str]] = None,
tls_min_version: Optional[pulumi.Input[str]] = None,
ttl: Optional[pulumi.Input[int]] = None,
upndomain: Optional[pulumi.Input[str]] = None,
url: Optional[pulumi.Input[str]] = None,
use_pre111_group_cn_behavior: Optional[pulumi.Input[bool]] = None,
use_token_groups: Optional[pulumi.Input[bool]] = None,
userattr: Optional[pulumi.Input[str]] = None,
userdn: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = SecretBackendArgs.__new__(SecretBackendArgs)
__props__.__dict__["anonymous_group_search"] = anonymous_group_search
__props__.__dict__["backend"] = backend
if binddn is None and not opts.urn:
raise TypeError("Missing required property 'binddn'")
__props__.__dict__["binddn"] = binddn
if bindpass is None and not opts.urn:
raise TypeError("Missing required property 'bindpass'")
__props__.__dict__["bindpass"] = bindpass
__props__.__dict__["case_sensitive_names"] = case_sensitive_names
__props__.__dict__["certificate"] = certificate
__props__.__dict__["client_tls_cert"] = client_tls_cert
__props__.__dict__["client_tls_key"] = client_tls_key
__props__.__dict__["default_lease_ttl_seconds"] = default_lease_ttl_seconds
__props__.__dict__["deny_null_bind"] = deny_null_bind
__props__.__dict__["description"] = description
__props__.__dict__["discoverdn"] = discoverdn
__props__.__dict__["groupattr"] = groupattr
__props__.__dict__["groupdn"] = groupdn
__props__.__dict__["groupfilter"] = groupfilter
__props__.__dict__["insecure_tls"] = insecure_tls
__props__.__dict__["last_rotation_tolerance"] = last_rotation_tolerance
__props__.__dict__["local"] = local
__props__.__dict__["max_lease_ttl_seconds"] = max_lease_ttl_seconds
__props__.__dict__["max_ttl"] = max_ttl
__props__.__dict__["password_policy"] = password_policy
__props__.__dict__["request_timeout"] = request_timeout
__props__.__dict__["starttls"] = starttls
__props__.__dict__["tls_max_version"] = tls_max_version
__props__.__dict__["tls_min_version"] = tls_min_version
__props__.__dict__["ttl"] = ttl
__props__.__dict__["upndomain"] = upndomain
__props__.__dict__["url"] = url
__props__.__dict__["use_pre111_group_cn_behavior"] = use_pre111_group_cn_behavior
__props__.__dict__["use_token_groups"] = use_token_groups
__props__.__dict__["userattr"] = userattr
__props__.__dict__["userdn"] = userdn
super(SecretBackend, __self__).__init__(
'vault:ad/secretBackend:SecretBackend',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
anonymous_group_search: Optional[pulumi.Input[bool]] = None,
backend: Optional[pulumi.Input[str]] = None,
binddn: Optional[pulumi.Input[str]] = None,
bindpass: Optional[pulumi.Input[str]] = None,
case_sensitive_names: Optional[pulumi.Input[bool]] = None,
certificate: Optional[pulumi.Input[str]] = None,
client_tls_cert: Optional[pulumi.Input[str]] = None,
client_tls_key: Optional[pulumi.Input[str]] = None,
default_lease_ttl_seconds: Optional[pulumi.Input[int]] = None,
deny_null_bind: Optional[pulumi.Input[bool]] = None,
description: Optional[pulumi.Input[str]] = None,
discoverdn: Optional[pulumi.Input[bool]] = None,
groupattr: Optional[pulumi.Input[str]] = None,
groupdn: Optional[pulumi.Input[str]] = None,
groupfilter: Optional[pulumi.Input[str]] = None,
insecure_tls: Optional[pulumi.Input[bool]] = None,
last_rotation_tolerance: Optional[pulumi.Input[int]] = None,
local: Optional[pulumi.Input[bool]] = None,
max_lease_ttl_seconds: Optional[pulumi.Input[int]] = None,
max_ttl: Optional[pulumi.Input[int]] = None,
password_policy: Optional[pulumi.Input[str]] = None,
request_timeout: Optional[pulumi.Input[int]] = None,
starttls: Optional[pulumi.Input[bool]] = None,
tls_max_version: Optional[pulumi.Input[str]] = None,
tls_min_version: Optional[pulumi.Input[str]] = None,
ttl: Optional[pulumi.Input[int]] = None,
upndomain: Optional[pulumi.Input[str]] = None,
url: Optional[pulumi.Input[str]] = None,
use_pre111_group_cn_behavior: Optional[pulumi.Input[bool]] = None,
use_token_groups: Optional[pulumi.Input[bool]] = None,
userattr: Optional[pulumi.Input[str]] = None,
userdn: Optional[pulumi.Input[str]] = None) -> 'SecretBackend':
"""
Get an existing SecretBackend resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[bool] anonymous_group_search: Use anonymous binds when performing LDAP group searches
(if true the initial credentials will still be used for the initial connection test).
:param pulumi.Input[str] backend: The unique path this backend should be mounted at. Must
not begin or end with a `/`. Defaults to `ad`.
:param pulumi.Input[str] binddn: Distinguished name of object to bind when performing user and group search.
:param pulumi.Input[str] bindpass: Password to use along with binddn when performing user search.
:param pulumi.Input[bool] case_sensitive_names: If set, user and group names assigned to policies within the
backend will be case sensitive. Otherwise, names will be normalized to lower case.
:param pulumi.Input[str] certificate: CA certificate to use when verifying LDAP server certificate, must be
x509 PEM encoded.
:param pulumi.Input[str] client_tls_cert: Client certificate to provide to the LDAP server, must be x509 PEM encoded.
:param pulumi.Input[str] client_tls_key: Client certificate key to provide to the LDAP server, must be x509 PEM encoded.
:param pulumi.Input[int] default_lease_ttl_seconds: Default lease duration for secrets in seconds.
:param pulumi.Input[bool] deny_null_bind: Denies an unauthenticated LDAP bind request if the user's password is empty;
defaults to true.
:param pulumi.Input[str] description: Human-friendly description of the mount for the Active Directory backend.
:param pulumi.Input[bool] discoverdn: Use anonymous bind to discover the bind Distinguished Name of a user.
:param pulumi.Input[str] groupattr: LDAP attribute to follow on objects returned by <groupfilter> in order to enumerate
user group membership. Examples: `cn` or `memberOf`, etc. Defaults to `cn`.
:param pulumi.Input[str] groupdn: LDAP search base to use for group membership search (eg: ou=Groups,dc=example,dc=org).
:param pulumi.Input[str] groupfilter: Go template for querying group membership of user (optional) The template can access
the following context variables: UserDN, Username. Defaults to `(|(memberUid={{.Username}})(member={{.UserDN}})(uniqueMember={{.UserDN}}))`
:param pulumi.Input[bool] insecure_tls: Skip LDAP server SSL Certificate verification. This is not recommended for production.
Defaults to `false`.
:param pulumi.Input[int] last_rotation_tolerance: The number of seconds after a Vault rotation where, if Active Directory
shows a later rotation, it should be considered out-of-band
:param pulumi.Input[bool] local: Mark the secrets engine as local-only. Local engines are not replicated or removed by
replication.Tolerance duration to use when checking the last rotation time.
:param pulumi.Input[int] max_lease_ttl_seconds: Maximum possible lease duration for secrets in seconds.
:param pulumi.Input[int] max_ttl: In seconds, the maximum password time-to-live.
:param pulumi.Input[str] password_policy: Name of the password policy to use to generate passwords.
:param pulumi.Input[int] request_timeout: Timeout, in seconds, for the connection when making requests against the server
before returning back an error.
:param pulumi.Input[bool] starttls: Issue a StartTLS command after establishing unencrypted connection.
:param pulumi.Input[str] tls_max_version: Maximum TLS version to use. Accepted values are `tls10`, `tls11`,
`tls12` or `tls13`. Defaults to `tls12`.
:param pulumi.Input[str] tls_min_version: Minimum TLS version to use. Accepted values are `tls10`, `tls11`,
`tls12` or `tls13`. Defaults to `tls12`.
:param pulumi.Input[int] ttl: In seconds, the default password time-to-live.
:param pulumi.Input[str] upndomain: Enables userPrincipalDomain login with [username]@UPNDomain.
:param pulumi.Input[str] url: LDAP URL to connect to. Multiple URLs can be specified by concatenating
them with commas; they will be tried in-order. Defaults to `ldap://127.0.0.1`.
:param pulumi.Input[bool] use_pre111_group_cn_behavior: In Vault 1.1.1 a fix for handling group CN values of
different cases unfortunately introduced a regression that could cause previously defined groups
to not be found due to a change in the resulting name. If set true, the pre-1.1.1 behavior for
matching group CNs will be used. This is only needed in some upgrade scenarios for backwards
compatibility. It is enabled by default if the config is upgraded but disabled by default on
new configurations.
:param pulumi.Input[bool] use_token_groups: If true, use the Active Directory tokenGroups constructed attribute of the
user to find the group memberships. This will find all security groups including nested ones.
:param pulumi.Input[str] userattr: Attribute used when searching users. Defaults to `cn`.
:param pulumi.Input[str] userdn: LDAP domain to use for users (eg: ou=People,dc=example,dc=org)`.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _SecretBackendState.__new__(_SecretBackendState)
__props__.__dict__["anonymous_group_search"] = anonymous_group_search
__props__.__dict__["backend"] = backend
__props__.__dict__["binddn"] = binddn
__props__.__dict__["bindpass"] = bindpass
__props__.__dict__["case_sensitive_names"] = case_sensitive_names
__props__.__dict__["certificate"] = certificate
__props__.__dict__["client_tls_cert"] = client_tls_cert
__props__.__dict__["client_tls_key"] = client_tls_key
__props__.__dict__["default_lease_ttl_seconds"] = default_lease_ttl_seconds
__props__.__dict__["deny_null_bind"] = deny_null_bind
__props__.__dict__["description"] = description
__props__.__dict__["discoverdn"] = discoverdn
__props__.__dict__["groupattr"] = groupattr
__props__.__dict__["groupdn"] = groupdn
__props__.__dict__["groupfilter"] = groupfilter
__props__.__dict__["insecure_tls"] = | |
"""
CORE DATA MODELS
================
Contains the core data structure models for sequencing files.
"""
import logging
import os
import re
from .config import CONFIG as cfg
try:
FileNotFoundError
except NameError:
FileNotFoundError = OSError
logger = logging.getLogger(__name__)
def extract_frame(name):
"""
This function by default extracts the last set of digits in the
string name and assumes it is the frame number when returning the
parts. It's a good idea to only pass basenames without extensions
so it doesn't attempt to sequence directory names or digits in the
extension.
:param str name: File basename without dir or extension.
:return: 3-pair tuple consisting of the head (all characters
preceding the last set of digits), the frame number
(last set of digits), and tail (all digits succeeding
the frame number).
"""
frame_match = re.match(cfg.frame_extract_re, name)
if frame_match:
groups = frame_match.groups()
head, tail = groups[cfg.head_group], groups[cfg.tail_group]
frame = groups[cfg.frame_group]
else:
head, frame, tail = (name, '', '')
if head is None:
head = ''
return head, frame, tail
def split_extension(filename):
"""
Splits the extension off the filename and returns a tuple of the
base filename and the extension (without the dot).
:param str filename: The base filename string to split.
:return: A tuple of the head (characters before the last '.') and
the extension (characters after the last '.').
"""
parts = filename.split('.')
if len(parts) < 2:
return parts[0], ''
ext = parts.pop(-1)
head = '.'.join(parts)
return head, ext
def frame_ranges_to_string(frames):
"""
Take a list of numbers and make a string representation of the ranges.
>>> frame_ranges_to_string([1, 2, 3, 6, 7, 8, 9, 13, 15])
'[1-3, 6-9, 13, 15]'
:param list frames: Sorted list of frame numbers.
:return: String of broken frame ranges (i.e '[10-14, 16, 20-25]').
"""
if not frames:
return '[]'
if not isinstance(frames, list):
frames = list(frames)
frames.sort()
# Make list of lists for each consecutive range
ranges = [[frames.pop(0)]]
current_range_index = 0 # index of current range
for x in frames:
if x - 1 == ranges[current_range_index][-1]:
ranges[current_range_index].append(x)
else:
current_range_index += 1
ranges.append([x])
range_strings = []
for x in ranges:
if len(x) > 1:
range_strings.append('-'.join([str(x[0]), str(x[-1])]))
else:
range_strings.append(str(x[0]))
complete_string = '[' + ', '.join(range_strings) + ']'
return complete_string
class Stat(object):
"""
This class mocks objects returned by os.stat on Unix platforms.
This is useful for instance when working with offline lists where
you want to maintain the stat information from a previously parsed
directory which the current machine does not have access to.
"""
def __init__(self, size=None, ino=None, ctime=None, mtime=None,
atime=None, mode=None, dev=None, nlink=None, uid=None,
gid=None):
"""
Refer to the docs for the the built-in os.stat module for more info.
:param int size: File size in bytes.
:param int ino: Inode number.
:param float ctime: Unix change timestamp.
:param float mtime: Unix modify timestamp.
:param float atime: Unix access timestamp.
:param int mode: Inode protection mode.
:param int dev: Device inode resides on.
:param int nlink: Number of links to the inode.
:param int uid: User id of the owner.
:param int gid: Group id of the owner.
"""
self.st_size = size
self.st_ino = ino
self.st_nlink = nlink
self.st_dev = dev
self.st_mode = mode
self.st_uid = uid
self.st_gid = gid
self.st_ctime = ctime
self.st_mtime = mtime
self.st_atime = atime
def __getattr__(self, item):
ints = ['st_size', 'st_ino', 'st_nlink', 'st_dev', 'st_mode',
'st_uid', 'st_gid']
floats = ['st_ctime', 'st_mtime', 'st_atime']
try:
if item in ints:
return int(super(Stat, self).__getattribute__(item))
elif item in floats:
return float(super(Stat, self).__getattribute__(item))
except TypeError:
return None
class File(object):
"""
The class that represents a single file and all of it's Stat
attributes if available. It contains attributes for the
various string parts of the path, base filename, frame number
and extension. All Sequences are comprised of File objects.
"""
def __init__(self, filepath, stats=None, get_stats=None):
"""
Initalize a single File instance.
:param str filepath: the absolute filepath of the file
:param stats: dict or iterable to map Stat class or
os.stat_result object.
:param bool get_stats: True to attempt to call os.stat on
the file. If file does not exist,
revert back to applying stats values
if they were supplied, else set stats
to None.
"""
if get_stats is not None and isinstance(get_stats, bool):
cfg.get_stats = get_stats
self.abspath = filepath
self.path, self.name = os.path.split(filepath)
self._base, self.ext = split_extension(self.name)
parts = extract_frame(self._base)
self.namehead, self._framenum, tail = parts
self.head = os.path.join(self.path, self.namehead)
if not self.ext:
self.tail = ''
else:
self.tail = '.'.join([tail, self.ext])
self.padding = len(self._framenum)
try:
if get_stats:
try:
stats = os.stat(filepath)
except FileNotFoundError:
if stats is None:
raise TypeError
if isinstance(stats, os.stat_result):
self.stat = stats
elif isinstance(stats, dict):
self.stat = Stat(**stats)
elif isinstance(stats, (list, tuple)):
self.stat = Stat(*stats)
else:
raise TypeError
except TypeError:
self.stat = Stat()
def __str__(self):
return self.abspath
def __repr__(self):
return "File('%s')" % self.abspath
def __lt__(self, other):
if isinstance(other, File):
return self.frame < other.frame
else:
raise TypeError('%s not File instance.' % str(other))
def __gt__(self, other):
if isinstance(other, File):
return self.frame > other.frame
else:
raise TypeError('%s not File instance.' % str(other))
def __le__(self, other):
if isinstance(other, File):
return self.frame <= other.frame
else:
raise TypeError('%s not File instance.' % str(other))
def __ge__(self, other):
if isinstance(other, File):
return self.frame >= other.frame
else:
raise TypeError('%s not File instance.' % str(other))
def __eq__(self, other):
if isinstance(other, File):
return (self.head, self.frame, self.tail) == (other.head,
other.frame,
other.tail)
else:
return False
def __ne__(self, other):
if isinstance(other, File):
return (self.head, self.frame, self.tail) != (other.head,
other.frame,
other.tail)
else:
return True
@property
def frame(self):
""" Integer frame number. """
try:
return int(self._framenum)
except ValueError:
return None
@property
def frame_as_str(self):
""" Str frame number with padding matching original filename. """
return self._framenum
@property
def size(self):
""" Same as Stat.st_size if available, otherwise None. """
if not self.stat.st_size:
try:
self.stat.st_size = os.stat(self.abspath).st_size
return self.stat.st_size
except FileNotFoundError:
return
else:
return self.stat.st_size
@property
def inode(self):
""" Same as Stat.st_ino if available, otherwise None. """
if not self.stat.st_ino:
try:
self.stat.st_ino = os.stat(self.abspath).st_ino
return self.stat.st_ino
except FileNotFoundError:
return
else:
return self.stat.st_ino
@property
def nlink(self):
""" Same as Stat.st_nlink if available, otherwise None. """
if not self.stat.st_nlink:
try:
self.stat.st_nlink = os.stat(self.abspath).st_nlink
return self.stat.st_nlink
except FileNotFoundError:
return
else:
return self.stat.st_nlink
@property
def dev(self):
""" Same as Stat.st_dev if available, otherwise None. """
if not self.stat.st_dev:
try:
self.stat.st_dev = os.stat(self.abspath).st_dev
return self.stat.st_dev
except FileNotFoundError:
return
else:
return self.stat.st_dev
@property
def mode(self):
""" Same as Stat.st_mode if available, otherwise None. """
if not self.stat.st_mode:
try:
self.stat.st_mode = os.stat(self.abspath).st_mode
return self.stat.st_mode
except FileNotFoundError:
return
else:
return self.stat.st_mode
@property
def uid(self):
""" Same as Stat.st_uid if available, otherwise None. """
if not self.stat.st_uid:
try:
self.stat.st_uid = os.stat(self.abspath).st_uid
return self.stat.st_gid
except FileNotFoundError:
return
else:
return self.stat.st_uid
@property
def gid(self):
""" Same as Stat.st_gid if available, otherwise None. """
if not self.stat.st_gid:
try:
self.stat.st_gid = os.stat(self.abspath).st_gid
return self.stat.st_gid
except FileNotFoundError:
return
else:
return self.stat.st_gid
@property
def ctime(self):
""" Same as Stat.st_ctime if available, otherwise None. """
if not self.stat.st_ctime:
try:
self.stat.st_ctime = os.stat(self.abspath).st_ctime
return self.stat.st_ctime
except FileNotFoundError:
return
else:
return self.stat.st_ctime
@property
def mtime(self):
""" Same as Stat.st_mtime if available, otherwise None. """
if not self.stat.st_mtime:
try:
self.stat.st_mtime = os.stat(self.abspath).st_mtime
return self.stat.st_mtime
except FileNotFoundError:
return
else:
return self.stat.st_mtime
@property
def atime(self):
""" Same as Stat.st_atime if available, otherwise None. """
if not self.stat.st_atime:
try:
self.stat.st_atime = os.stat(self.abspath).st_atime
return self.stat.st_atime
except FileNotFoundError:
return
else:
return self.stat.st_atime
def get_seq_key(self, ignore_padding=None):
"""
Make a sequence global name for matching frames to correct
sequences.
:param bool ignore_padding: True uses '%0#d' format, else '#'
:return: sequence key name (i.e. '/path/to/file.#.dpx')
"""
if ignore_padding is None or not isinstance(ignore_padding, bool):
ignore_padding = cfg.ignore_padding
if not self._framenum:
digits = ''
elif ignore_padding is True:
digits = '#'
elif ignore_padding is False:
digits = '%%0%dd' % self.padding
else:
raise TypeError('ignore_padding argument must be of type bool.')
return self.head + digits + self.tail
class Sequence(object):
"""
Class representing a sequence of matching file names. The frames
are stored in a dictionary with the frame numbers as keys. Sets
are used for fast operations in calculating missing frames.
This class's usage of dictionaries and sets is the core of the
speed of this program. Rather than recursively searching existing
sequences, the file key gnerated from File.get_seq_key() is used to
instantly match the sequence it belongs to.
"""
def __init__(self, frame_file=None, ignore_padding=None):
"""
Initialize an image Sequence instance.
:param File or str frame_file: File object or filename string to
initialze a File object from.
:param bool ignore_padding: True to allow inconsistent padding
as same sequence, False to treat
as separate sequences.
"""
if ignore_padding is not None and isinstance(ignore_padding, bool):
cfg.ignore_padding = ignore_padding
self._frames = {}
self.seq_name = ''
self.path = ''
self.namehead = ''
self.head = ''
self.tail = ''
self.ext = ''
self.padding = 0
self.inconsistent_padding = False
if frame_file is not None:
self.append(frame_file)
def __str__(self):
return self.format(cfg.format)
def __repr__(self):
return "Sequence('%s', frames=%d)" % (
self.format(cfg.format), self.frames)
def __len__(self):
return len(self._frames)
def __iter__(self):
return iter([self._frames[frame] for frame in self._frames])
def __getitem__(self, frames):
all_frames = list(sorted(self._frames))
if isinstance(frames, slice):
return [self._frames[f] for f in sorted(self._frames)][frames]
return self._frames[all_frames[frames]]
def __lt__(self, other):
if isinstance(other, str):
return self.seq_name < other
else:
return self.seq_name < other.seq_name
@property
def abspath(self):
""" Full sequence path name (i.e. '/path/to/file.#.dpx'). """
return self.seq_name
@property
def name(self):
""" The base sequence name without the path (i.e 'file.#.dpx'). """
return os.path.basename(self.seq_name)
@property
def start(self):
""" Int of first frame in sequence. """
return min(self._frames)
@property
def end(self):
""" Int of last frame in sequence. """
return max(self._frames)
@property
def frames(self):
""" Int of total frames in sequence. """
return len(self)
@property
def frame_numbers(self):
""" List of frame ints in sequence. """
return list(sorted(self._frames))
@property
def frame_range(self):
""" Int of expected frames in sequence. """
return self.end - self.start + 1
@property
def missing(self):
""" Int of total missing frames in sequence. """
return self.end - (self.start - 1) - self.frames
@property
def is_missing_frames(self):
""" Return True if any frames are missing from sequence. """
return self.frames != self.frame_range
@property
def size(self):
""" Sum of all filesizes (in bytes) in sequence. """
try:
return sum([file_.size for file_ in self])
except TypeError:
return
def get_frame(self, frame):
"""
Get a specific frame number's File object, works like
__getitem__ except gets exact frame number instead of index
position in list.
:param int frame: Frame number to extract from sequence.
:return: File instance.
"""
return self._frames[int(frame)]
def get_frames(self, start=None, end=None, step=1):
"""
Get a specific range of frames' File objects, works like
__getitem__ slice, but gets exact frames or frame ranges
instead of index positions in list.
:param int start: Frame number to start range.
:param int end: Frame number | |
<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import multiselectfield.db.fields
import common.forms
class Migration(migrations.Migration):
dependencies = [
('taxonomy', '__first__'),
('organization', '0004_auto_20150112_0241'),
]
operations = [
migrations.AddField(
model_name='organization',
name='client_locations',
field=models.ManyToManyField(related_name='client_locations', to='taxonomy.Country', blank=True, help_text=b'Type of product or service provided by the organization', null=True, verbose_name=b'Product/Service Type'),
preserve_default=True,
),
migrations.AlterField(
model_name='job',
name='equity_max',
field=common.forms.BetterDecimalField(null=True, max_digits=19, decimal_places=2, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='job',
name='equity_min',
field=common.forms.BetterDecimalField(null=True, max_digits=19, decimal_places=2, blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='accounts_payable',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value, at the end of the reporting period, of all outstanding debts that must be paid within a given period of time in order to avoid default.', null=True, verbose_name=b'Accounts Payable'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='accounts_receivable',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value, at the end of the reporting period, of outstanding debts from clients who received goods or services on credit.', null=True, verbose_name=b'Accounts Receivable'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='board_of_directors',
field=common.forms.BetterPositiveIntegerField(help_text=b"Number of members of organization's Board of Directors or other governing body, as of the end of the reporting period.", null=True, verbose_name=b'Board of Directors', blank=True),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='cash_and_cash_equivalents_period_end',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value of the organizations cash equivalents at the end of the reporting period.', null=True, verbose_name=b'Cash and Cash Equivalents- Period End'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='cash_and_cash_equivalents_period_start',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b"Value of the organization's cash equivalents at the beginning of the reporting period.", null=True, verbose_name=b'Cash and Cash Equivalents- Period Start'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='cash_flow_from_financing_activities',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value of cash flows during the reporting period related to financing activities by the organization. Financing activities are activities that result in changes in the size and composition of the contributed equity and borrowings of the organization.', null=True, verbose_name=b'Cash Flow from Financing Activities'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='cash_flow_from_investing_activities',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value of cash flows during the reporting period related to investing activities by the organization. Investing activities are the acquisition and disposal of long-term assets and other investments that are not considered to be cash equivalents.', null=True, verbose_name=b'Cash Flow from Investing Activities'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='cash_flow_from_operating_activities',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value of cash flows during the reporting period related to operating activities. Operating activities are the principal revenue-producing activities of the entity and other activities that are not investing or financing activities.', null=True, verbose_name=b'Cash Flow from Operating Activities'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='client_individuals',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Number of individuals or households who were clients during the reporting period.For microfinance clients, this refers to active clients.For healthcare providers, this refers to patients.Note: Organizations tracking households should report num', null=True, verbose_name=b'Client Individuals'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='community_service_donations',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value of all charitable donations made by the organization', null=True, verbose_name=b'Community Service Donations'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='contributed_revenue',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Contributed revenue during the reporting period. Includes both unrestricted and restricted operating grants and donations and in-kind contributions. Does NOT include equity grants for capital, grants that are intended for future operating periods, or gra', null=True, verbose_name=b'Contributed Revenue'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='cost_of_goods_sold',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b"Direct costs attributable to the production of the goods sold by the organization during the reporting period. The cost should include all costs of purchase, costs of conversion, and other direct costs incurred in producing and selling the organization's", null=True, verbose_name=b'Cost of Goods Sold'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='current_assets',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value, at the end of the reporting period, of all assets that are reasonably expected to be converted into cash within one year in the normal course of business. Current assets can include cash, accounts receivable, inventory, marketable securities, prepa.', null=True, verbose_name=b'Current Assets'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='current_liabilities',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value, at the end of the reporting period, of all liabilities that are expected to be settled with one year in the normal course of business. Current liabilities can include accounts payable, lines of credit, or other short term debts.', null=True, verbose_name=b'Current Liabilities'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='depreciation_and_amortization_expense',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value of expenses recorded by the organization during the reporting period for depreciation and amortization.', null=True, verbose_name=b'Depreciation and Amortization Expense'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='earned_revenue',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Revenue resulting from all business activities during the reporting period. Earned revenue is total revenues less "Contributed Revenue" (Grants and Donations).', null=True, verbose_name=b'Earned Revenue'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='ebitda',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b"Organization's earnings, excluding contributed revenues, before interest, taxes, depreciation and amortization during the reporting period.", null=True, verbose_name=b'EBITDA'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='entrepreneur_investment',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value of the equity and/or other financial contribution in the organization provided by the entrepreneur/s at the time of investment.', null=True, verbose_name=b'Entrepreneur Investment'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='equity_or_net_assets',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'The residual interest, at the end of the reporting period, in the assets of the organization after deducting all its liabilities.', null=True, verbose_name=b'Equity or Net Assets'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='female_ownership',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Percentage of the company that is female-owned as of the end of the reporting period.Calculation: number of total shares owned by females/number of total shares.Note: Where regional or local laws apply for calculating ownership by previously excluded', null=True, verbose_name=b'Female Ownership'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='financial_assets',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value, at the end of the reporting period, of all assets that represent debt, equity, and cash assets such as: stocks, bonds, mutual funds, cash, and cash management accounts. Values of assets should be based upon fair market value where efficient second.', null=True, verbose_name=b'Financial Assets'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='financial_liabilities',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b"Value, at the end of the reporting period, of an organization's financial liabilities. Financial liabilities include all borrowed funds, deposits held, or other contractual obligations to deliver cash.", null=True, verbose_name=b'Financial Liabilities'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='fixed_assets',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Value, at the end of the reporting period, of all long-term tangible assets that are not expected to be converted into cash in the current or upcoming fiscal year, e.g., buildings, real estate, production equipment, and furniture. Sometimes called PLANT.', null=True, verbose_name=b'Fixed Assets'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='fixed_costs',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Costs that do not vary based on production or sales levels.', null=True, verbose_name=b'Fixed Costs'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='gross_margin',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b"Percent of earned revenues that the organization retains after incurring the direct costs associated with producing the goods and services sold by the company.Calculation: 'Cost of Goods Sold' / 'Earned Revenue'", null=True, verbose_name=b'Gross Margin'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='gross_profit',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b"The organization's residual profit after selling a product or service and deducting the costs directly associated with its production. Gross Profit is 'Earned Revenue' less 'Cost of Goods Sold'.", null=True, verbose_name=b'Gross Profit'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='income_growth',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b"Growth in value of the organization's Net income Before Donations from one reporting period to another.Calculation: (Net Income Before Donations in reporting period 2 - Net Income Before Donations in reporting period 1) / Net Income Before Donations", null=True, verbose_name=b'Income Growth'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='interest_expense',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'Interest incurred during the reporting period on all liabilities, including any client deposit accounts held by the organization, borrowings, subordinated debt, and other liabilities.', null=True, verbose_name=b'Interest Expense'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='legal_structure',
field=models.CharField(choices=[(b'1', b'Corporation'), (b'2', b'Limited Liability Company'), (b'3', b'Non-Profit/Foundation/Association'), (b'4', b'Partnership'), (b'5', b'Sole-proprietorship'), (b'6', b'Cooperative'), (b'Other', b'Other')], max_length=255, blank=True, help_text=b'Current legal structure of the organization.', null=True, verbose_name=b'Legal Structure'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='loans_payable',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b"The remaining balance, at the end of the reporting period, on all the organization's outstanding debt obligations carried on the balance sheet.", null=True, verbose_name=b'Loans Payable'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='net_cash_flow',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b'The net cash flow of the organization during the reporting period. Net cash flow equals inflows less outflows of cash and cash equivalents.', null=True, verbose_name=b'Net Cash Flow'),
preserve_default=True,
),
migrations.AlterField(
model_name='organization',
name='net_income',
field=common.forms.BetterDecimalField(decimal_places=2, max_digits=19, blank=True, help_text=b"Net Income or change in unrestricted net assets resulting from all business activities during the reporting | |
not have an avatar (4th element)
if (time * spriteSet[object[0]]['speed'] - object[2] >= 0):
object[2] += 1
spriteListWithObject = map[object[1]]
for index in range(0, len(spriteListWithObject)):
if (debug):
print index
print len(spriteListWithObject)
print spriteListWithObject[index]
print spriteListWithObject[index].has_key(object[0]), object[0]
if (spriteListWithObject[index].has_key(object[0])):
sprite = spriteListWithObject.pop(index)
sprite[object[0]]['last-position'] = object[1]
if (spriteSet[object[0]]['orientation'] == 'up'):
object[1] = (object[1][0] - 1, object[1][1])
elif (spriteSet[object[0]]['orientation'] == 'down'):
object[1] = (object[1][0] + 1, object[1][1])
elif (spriteSet[object[0]]['orientation'] == 'left'):
object[1] = (object[1][0], object[1][1] - 1)
else:
object[1] = (object[1][0], object[1][1] + 1)
if (object[1][0] < maxMapRow and object[1][0] >= 0 and object[1][1] < maxMapCol and object[1][1] >= 0):
map[object[1]].append(sprite)
else:
objectsCount[object[0]] -= 1
movableObjects.remove(object)
break
# Function that helps to spawn objects in the game
def spawnObjects():
global spriteSet, map, movableObjects, time, objectsCount
# Get the spawn from the spawner Objects.
for spawn in spawnerObjects:
# Get the information of the spawner.
spawner = spriteSet[spawn[0]]
# Check if it meets the probability to generate a new sprite and the cooldown time
# has passed.
if (random.random() <= spawner['prob'] and int(time) % spawner['cooldown'] == 0):
# Get the sprites in the tile where the spawn is.
sprites = map[spawn[1]]
spawnNew = True
# Check if there are no generated sprites in the spawner position.
# If it find a sprite, it means that it was already generated before.
for index in range(0, len(sprites)):
if (sprites[index].has_key(spawner['generatedSprite'])):
spawnNew = False
break
# If there is no generated Sprite, then:
if (spawnNew):
# Append to that map position the generated sprite with its attributes
map[spawn[1]].append({spawner['generatedSprite'] : spriteSet[spawner['generatedSprite']]})
# Spawners generate movable objects, therefore included here too.
movableObjects.append([spawner['generatedSprite'], spawn[1], ceil(time * spriteSet[spawner['generatedSprite']]['speed'])])
objectsCount[spawner['generatedSprite']] += 1
# Method to draw all objects in map
def drawObjects():
global map, maxMapRow, maxMapCol
# Draw the white background
win.fill(globals()['color_white'])
# Loop through the map
for r in range(0, maxMapRow):
for c in range(0, maxMapCol):
# Get the sprites in map
sprites = map[(r, c)]
# If there are no sprites
if (len(sprites) == 0):
pygame.draw.rect(win, globals()['color_white'], [c * tileWidth, r * tileHeight, (c+1) * tileWidth, (r+1) * tileHeight])
# If there are sprites only draw the one that is at the top (the last one in the list)
else:
sprite = sprites[-1]
for spriteKey, spritAttrib in sprite.iteritems():
if (debug):
print [c * tileWidth, r * tileHeight, (c+1) * tileWidth, (r+1) * tileHeight]
if (spritAttrib.has_key('color')):
pygame.draw.rect(win, globals()['color_' + spritAttrib['color']], [c * tileWidth, r * tileHeight, (c+1) * tileWidth, (r+1) * tileHeight])
# After drawing, refresh screen
pygame.display.flip()
# The CORE of the VM
# It receives the quadruplet, and this method is a big swith that depending of the operation
# (quadruplet[0]) is the procces to be executed.
def doOperation(quadruplet):
global instructionCounter, functionDictionary, instructionStack, functionScope, offset, spriteSet, map, score, mapRow, mapCol, mapping, objectsCount, time, maxMapRow, maxMapCol, tileWidth, tileHeight, win, clock, avatarPos, tile, file, movableObjects, protect, spriteInTile, protectFrom, protectTile, spawnerObjects
if (debug):
print instructionCounter, quadruplet
# The first 10 operations are arithmetic or logical.
if (quadruplet[0] < 10):
elem1 = accessValueInMemory(quadruplet[1])
elem2 = accessValueInMemory(quadruplet[2])
# Plus
if (quadruplet[0] == 0):
result = elem1 + elem2
# Times
elif (quadruplet[0] == 1):
result = elem1 * elem2
# Minus
elif (quadruplet[0] == 2):
result = elem1 - elem2
# Division
elif (quadruplet[0] == 3):
result = 1.0 * elem1 / elem2
# And
elif (quadruplet[0] == 4):
result = elem1 and elem2
# Or
elif (quadruplet[0] == 5):
result = elem1 or elem2
# Lesser than
elif (quadruplet[0] == 6):
result = elem1 < elem2
# Greater than
elif (quadruplet[0] == 7):
result = elem1 > elem2
# Not equal
elif (quadruplet[0] == 8):
result = elem1 != elem2
# Equal
elif (quadruplet[0] == 9):
result = elem1 == elem2
if (debug):
print "elem1: ", elem1
print "elem2: ", elem2
print "result: ", result
# Save the result from the operation in memory
assignValueInMemory(quadruplet[3], result)
return True
# Assignation
elif (quadruplet[0] == 10):
result = accessValueInMemory(quadruplet[1])
assignValueInMemory(quadruplet[3], result)
return True
# GOTO, change the instruction counter (-1 because in the loop it will increase)
elif (quadruplet[0] == 11):
instructionCounter = quadruplet[3] - 1
return True
# GOTOF, evaluate and then
# change the instruction counter (-1 because in the loop it will increase)
elif (quadruplet[0] == 12):
result = accessValueInMemory(quadruplet[1])
if (debug):
print "GOTOF result: ", result
if (result == False):
instructionCounter = quadruplet[3] - 1
return True
# Print value to console
elif (quadruplet[0] == 13):
result = accessValueInMemory(quadruplet[3])
print "-----> AVM PRINT: ", result
if (not file.closed):
file.write("-> AVM PRINT: " + str(result) + '\n')
return True
# Get value (int or float)
elif (quadruplet[0] == 14):
scan = raw_input('-----> AVM GET_VALUE: ')
try:
if (quadruplet[3] < 15000):
result = int(scan.strip())
else:
result = float(scan.strip())
if (not file.closed):
file.write("-> AVM GET_VALUE: " + str(result) + '\n')
assignValueInMemory(quadruplet[3], result)
return True
except:
# raise ERROR
return False
# Get line (char or string)
elif (quadruplet[0] == 15):
scan = raw_input('-----> AVM GET_LINE: ')
if (not file.closed):
file.write("-> AVM GET_LINE: " + str(result) + '\n')
assignValueInMemory(quadruplet[3], scan)
return True
# Get boolean ('true or false')
elif (quadruplet[0] == 16):
scan = raw_input('-----> AVM GET_BOOLEAN: ')
result = scan.strip()
if (result == 'true' or result == 'false'):
if (not file.closed):
file.write("-> AVM GET_BOOLEAN: " + str(result) + '\n')
assignValueInMemory(quadruplet[3], result)
return True
else:
# raise ERROR
return False
# Get char (similar to get line, it only takes into account the first character)
elif (quadruplet[0] == 17):
scan = raw_input('-----> AVM GET_CHAR: ')
if (len(scan) > 0):
result = scan[0]
if (not file.closed):
file.write("-> AVM GET_CHAR: " + str(result) + '\n')
return True
else:
# raise ERROR
return False
# End Function operation. Needs to deleate ERA if it was not done before and
# set back the instruction pointer
elif (quadruplet[0] == 18):
deleteERAInMemory()
if (debug):
print "Memory after deleting ERA: ", memory
assignValueInMemory(functionDictionary[functionScope[-1]]['memory'], -1)
instructionCounter = instructionStack.pop()
functionScope.pop()
resetParametersMemoryValues()
return True
# ERA quadriplet, it creates a new dictionary in memory and sets the offset to 1
elif (quadruplet[0] == 19):
createERAInMemory()
functionScope.append(quadruplet[3])
offset = 1
if (debug):
print "Memory after creating ERA: ", memory
return True
# Gosub, it is like goto, but in this case is for a function.
# It sets offset to 0, and saves instruction pointer
elif (quadruplet[0] == 20):
function = quadruplet[3]
instructionStack.append(instructionCounter)
offset = 0
instructionCounter = functionDictionary[function]['quadruplet'] - 1
resetParametersMemoryValues()
return True
# Param operation. It uses the helper functions to manipulate two different spaces
# in memory.
elif (quadruplet[0] == 21):
value = quadruplet[1]
if (debug):
print "Function scope Name for Params: ", functionScope
paramType = functionDictionary[functionScope[-1]]['parameters'][quadruplet[3] - 1]
param = getParamMemoryValue(paramType)
assignParamInMemory(value, param)
return True
# Return operation. In this case, the function returns a value, and after that
# you need to delete the memory of the function scope and return the pointer where it
# was before the function got called.
elif (quadruplet[0] == 22):
result = accessValueInMemory(quadruplet[3])
if (debug):
print "Function Scope: ", functionScope
print "Memory direction of function = ", functionDictionary[functionScope[-1]]['memory']
assignValueInMemory(functionDictionary[functionScope[-1]]['memory'], result)
deleteERAInMemory()
if (debug):
print "Memory after deleting ERA: ", memory
instructionCounter = instructionStack.pop()
functionScope.pop()
return True
# Verify operation. This is done to handle arrays. Verifies that your assigning a value
# that is inside the limits of the array (or list).
elif (quadruplet[0] == 23):
result = accessValueInMemory(quadruplet[1])
if (result >= quadruplet[2] and result <= quadruplet[3]):
return True
else:
return False
# ================ BEGINNING OF GAME OPERATIONS ================================
# Assign operation. Different than 10 in the sense that this needs to be handled like a class.
# The attributes (color, portal, etc) are stored in the spriteSet.
elif (quadruplet[0] == 30):
if (quadruplet[1] == 301):
spriteSet[quadruplet[3]]['color'] = quadruplet[2]
elif (quadruplet[1] == 302):
spriteSet[quadruplet[3]]['portal'] = quadruplet[2]
elif (quadruplet[1] == 303):
spriteSet[quadruplet[3]]['orientation'] = quadruplet[2]
elif (quadruplet[1] == 304):
spriteSet[quadruplet[3]]['speed'] = float(quadruplet[2])
elif (quadruplet[1] == 305):
| |
import numpy as np
import scipy
from ... import operators
__all__ = ['matrix_pencil','matrix_pencil_cor','matrix_pencil_cov', 'kernel_matrix_pencil']
#-------------------------------------------------------------
def matrix_pencil(x, order, mode='full', tls_rank = None):
'''
Matrix Pencil Method (MPM)
for of the decay signals model
parameters estimation.
Parameters
--------------
* x: input 1d ndarray.
* order: int,
the model order.
* mode: string,
mode = {full, toeplitz, hankel, covar, traj},
mode for autoregression problem solving.
* tls_rank: int or None,
rank of Total Least-Square turnication of
the processied matrix, if not None,
tls_rank = min(max(order,tls_rank),N).
Returns
------------
* roots: 1d ndarray,
signal parameters in roots form.
Notes
----------------
* MPM is calculated for each component as follows:
..math::
s_p(n)=[v_N^T * λ_p]^(-1)*x(n)*λ_p^n,
where
* s_p(n) is the p-th component of decomposition;
* v^N is the Vandermonde matrix operator of degrees from 0 to N-1;
* λ_p is the p-th eigenvalue of matrix r_1^(-1)(n)*r_2(n),
where r_1(n) and r_2(n) are rows from 0 to P-1 (r_1(n))
and rows from 1 to P (r_2(n))
of the transported lags_matrix of x(n) with order P+1.
Examples
-----------
References
-----------
[1a] <NAME>, <NAME>,
<NAME>, et al.,"Coding Prony’s method in
MATLAB and applying it to biomedical signal filtering",
BMC Bioinformatics, 19, 451 (2018).
[1b] https://bmcbioinformatics.biomedcentral.com/
articles/10.1186/s12859-018-2473-y
'''
x = np.asarray(x)
N = x.shape[0]
mtx = operators.lags_matrix(x,
mode=mode,
lags = order+1)
mtx1 = mtx[:-1,:]
mtx2 = mtx[1:,:]
if tls_rank:
_tls_rank = min(max(order,tls_rank),N)
mtx1, mtx2 \
= operators.tls_turnication(mtx1, mtx2, _tls_rank)
QZ=scipy.linalg.lstsq(mtx1,mtx2)[0]
roots, _ = np.linalg.eig(QZ)
if mode in ['toeplitz']:roots = np.conj(roots)
return roots
#--------------------------------------
def matrix_pencil_cor(x, order, mode='full',cor_mode='same', tls_rank = None):
'''
Matrix Pencil Method (MPM)
for of the decay signals model
parameters estimation for
additionally taken correlation function.
Parameters
--------------
* x: input 1d ndarray.
* order: int,
the model order.
* mode: string,
mode = {full, toeplitz, hankel, covar, traj},
mode for autoregression problem solving.
* cor_mode: string,
additional correlation function,
cor_mode = {same,full,straight}.
* tls_rank: int or None,
rank of Total Least-Square turnication of
the processied matrix, if not None,
tls_rank = min(max(order,tls_rank),N).
Returns
------------
* roots: 1d ndarray,
signal parameters in roots form.
Notes
----------------
* MPM is calculated for each component as follows:
..math::
s_p(n)=[v_N^T * λ_p]^(-1)*x(n)*λ_p^n,
where
* s_p(n) is the p-th component of decomposition;
* v^N is the Vandermonde matrix operator of degrees from 0 to N-1;
* λ_p is the p-th eigenvalue of matrix r_1^(-1)(n)*r_2(n),
where r_1(n) and r_2(n) are rows from 0 to P-1 (r_1(n))
and rows from 1 to P (r_2(n))
of the transported lags_matrix of x(n) with order P+1.
Examples
-----------
References
-----------
[1a] <NAME>, <NAME>,
<NAME>, et al.,"Coding Prony’s method in
MATLAB and applying it to biomedical signal filtering",
BMC Bioinformatics, 19, 451 (2018).
[1b] https://bmcbioinformatics.biomedcentral.com/
articles/10.1186/s12859-018-2473-y
'''
x = np.asarray(x)
N = x.shape[0]
r = operators.correlation(x,
mode=cor_mode)
mtx = operators.lags_matrix(r,
mode=mode,
lags = order+1)
mtx1 = mtx[:-1,:]
mtx2 = mtx[1:,:]
if tls_rank:
_tls_rank = min(max(order,tls_rank),N)
mtx1, mtx2 \
= operators.tls_turnication(mtx1, mtx2, _tls_rank)
QZ=scipy.linalg.lstsq(mtx1,mtx2)[0]
roots, _ = np.linalg.eig(QZ)
if mode in ['toeplitz']:roots = np.conj(roots)
return roots
#-------------------------------------------------------------
def matrix_pencil_cov(x, order, mode, tls_rank = None):
'''
Matrix Pencil Method (MPM)
for of the decay signals model
parameters estimation for
the signal covariance matrix.
Parameters
--------------
* x: 1d ndarray.
* order: int,
the model order.
* mode: string,
mode = {full, toeplitz, hankel, covar, traj},
mode for autoregression problem solving.
* tls_rank: int or None,
rank of Total Least-Square turnication of
the processied matrix, if not None,
tls_rank = min(max(order,tls_rank),N).
Returns
------------
* roots: 1d ndarray,
signal parameters in roots form.
Notes
----------------
* MPM is calculated for each component as follows:
..math::
s_p(n)=[v_N^T * λ_p]^(-1)*x(n)*λ_p^n,
where
* s_p(n) is the p-th component of decomposition;
* v^N is the Vandermonde matrix operator of degrees from 0 to N-1;
* λ_p is the p-th eigenvalue of matrix r_1^(-1)(n)*r_2(n),
where r_1(n) and r_2(n) are rows from 0 to P-1 (r_1(n))
and rows from 1 to P (r_2(n))
of the transported lags_matrix of x(n) with order P+1.
Examples
-----------
References
-----------
[1a] <NAME>, <NAME>,
<NAME>, et al.,"Coding Prony’s method in
MATLAB and applying it to biomedical signal filtering",
BMC Bioinformatics, 19, 451 (2018).
[1b] https://bmcbioinformatics.biomedcentral.com/
articles/10.1186/s12859-018-2473-y
'''
x = np.asarray(x)
N = x.shape[0]
mtx = operators.covariance_matrix(x,
mode=mode,
lags = order+1)
mtx1 = mtx[:-1,:]
mtx2 = mtx[1:,:]
if tls_rank:
_tls_rank = min(max(order,tls_rank),N)
mtx1, mtx2 \
= operators.tls_turnication(mtx1, mtx2, _tls_rank)
QZ=scipy.linalg.lstsq(mtx1,mtx2)[0]
roots, _ = np.linalg.eig(QZ)
if mode in ['toeplitz']:roots = np.conj(roots)
return roots
#-----------------------------------------
def kernel_matrix_pencil(x, order, mode, kernel = 'rbf',
kpar=1, tls_rank = None):
'''
Matrix Pencil Method (MPM)
for of the decay signals model
parameters estimation for
the signal kernel matrix.
Parameters
--------------
* x: input 1d ndarray.
* order: int,
the model order.
* mode: string,
mode = {full, toeplitz, hankel, covar, traj},
mode for autoregression problem solving.
* kernel: string,
kernel = {linear,rbf,thin_plate,bump,poly,sigmoid},
kernel mode.
* kpar: float,
kernel parameter depends on the kernel type.
* tls_rank: int or None,
rank of Total Least-Square turnication of
the processied matrix, if not None,
tls_rank = min(max(order,tls_rank),N).
Returns
------------
* roots: 1d ndarray,
signal parameters in roots form.
Notes
----------------
* MPM is calculated for each component as follows:
..math::
s_p(n)=[v_N^T * λ_p]^(-1)*x(n)*λ_p^n,
where
* s_p(n) is the p-th component of decomposition;
* v^N is the Vandermonde matrix operator of degrees from 0 to N-1;
* λ_p is the p-th eigenvalue of matrix r_1^(-1)(n)*r_2(n),
where r_1(n) and r_2(n) are rows from 0 to P-1 (r_1(n))
and rows from 1 to P (r_2(n))
of the transported lags_matrix of x(n) with order P+1.
Examples
-----------
References
-----------
[1a] <NAME>, <NAME>,
<NAME>, et al.,"Coding Prony’s method in
MATLAB and applying it to biomedical signal filtering",
BMC Bioinformatics, 19, 451 (2018).
[1b] https://bmcbioinformatics.biomedcentral.com/
articles/10.1186/s12859-018-2473-y
'''
x = np.asarray(x)
N = x.shape[0]
mtx = operators.kernel_matrix(x,
mode=mode,
kernel=kernel,
kpar=kpar,
lags = order+1,)
mtx1 = mtx[:-1,:]
mtx2 = mtx[1:,:]
mtx1, mtx2 \
= operators.tls_turnication(mtx1, mtx2, order)
QZ=scipy.linalg.lstsq(mtx1,mtx2)[0]
roots, _ = np.linalg.eig(QZ)
return roots
# def matrix_pencil(x, order, mode, n_psd = None):
# '''
# Matrix Pencil Method (MPM) for decay signals model.
# Parameters
# --------------
# * x: input 1d ndarray.
# * order: the model order.
# * mode: mode for autoregression problem solving.
# * n_psd: length of reconstructed signal (x.size as defaults).
# Returns
# --------------
# * Array with dementions order x x.size - signal components.
# Notes
# ----------------
# * See prony as alternative for this function.
# * MPM is calculated for each component as follows:
# ..math::
# s_p(n)=[v_N^T * λ_p]^(-1)*x(n)*λ_p^n,
# where
# * s_p(n) is the p-th component of decomposition;
# * v^N is the Vandermonde matrix operator of degrees from 0 to N-1;
# * λ_p is the p-th eigenvalue of matrix r_1^(-1)(n)*r_2(n),
# where r_1(n) and r_2(n) are rows from 0 to P-1 (r_1(n))
# and rows from 1 to P (r_2(n))
# of the transported lags_matrix of x(n) with order P+1.
# Examples
# -----------
# References
# -----------
# [1a] <NAME>, <NAME>,
# <NAME>, et al.,"Coding Prony’s method in
# MATLAB and applying it to biomedical signal filtering",
# BMC Bioinformatics, 19, 451 (2018).
# [1b] https://bmcbioinformatics.biomedcentral.com/
# articles/10.1186/s12859-018-2473-y
# '''
# x = np.asarray(x)
# N = x.shape[0]
# if (n_psd is None): n_psd = N
# #TODO: elumenate transpose
# trj = operators.lags_matrix(x,
# mode=mode,
# lags = order+1)
# trj1 = trj[:-1,:]
# trj2 = trj[1:,:]
# QZ = np.dot(np.linalg.pinv(trj1),trj2)
# D, _ = np.linalg.eig(QZ)
# # | |
<reponame>junkyul/gmid2-public
"""
read or write uai files in pure python classes
*.uai: functions
*.id: identity for var/func
*.mi: identify for var
*.map: map variables
*.pvo: partial ordering
*.evid: evidence or conditioning
*.vo: total ordering
*.pt: pseudo tree
* ID/LIMID: uai, id, pvo
* MMAP: uai, map
* MPE: uai
* SUM: uai
* MI: uai, mi
"""
from typing import Text, List
from gmid2.global_constants import *
class FileInfo:
def __init__(self):
self.uai_file = ""
self.net_type = ""
self.nvar, self.nfunc, self.nchance, self.ndec, self.nprob, self.nutil = 0, 0, 0, 0, 0, 0
self.var_types, self.domains = [], []
self.chance_vars, self.decision_vars = [], []
self.prob_funcs, self.util_funcs = [], []
self.tables, self.scopes, self.factor_types = [], [], []
self.blocks, self.block_types, self.nblock = [], [], 0
def show_members(self):
for k, v in vars(self).items():
print("{}:{}".format(k,v))
def read_limid(file_name: Text, skip_table: bool=False) -> FileInfo:
"""
read necessary files (uai for vars/functions, id for identity, pvo for partil order) for loading limid
use the return to create graphical model object that actually creates numpy based Factors
"""
file_info = FileInfo()
assert not file_name.endswith(".uai"), "remove extension as this read *.uai, *.id, *.pvo in sequence"
read_uai(file_name + ".uai", file_info, skip_table)
read_id(file_name + ".id", file_info)
read_pvo(file_name + ".pvo", file_info)
return file_info
def read_mmap(file_name:Text, skip_table: bool=False)->FileInfo:
"""
read necessary files (uai for vars/functions, map for max variables, pvo is implicit)
"""
file_info = FileInfo()
read_uai(file_name + ".uai", file_info, skip_table)
read_map(file_name + ".map", file_info)
return file_info
def read_sum(file_name:Text, skip_table: bool=False)->FileInfo:
file_info = FileInfo()
read_uai(file_name + ".uai", file_info, skip_table)
file_info.ndec = 0
file_info.decision_vars = []
file_info.chance_vars = list(range(file_info.nvar))
file_info.nchance = file_info.nvar
file_info.var_types = [TYPE_CHANCE_VAR] * file_info.nchance
file_info.factor_types = [TYPE_PROB_FUNC] * file_info.nfunc
file_info.prob_funcs = list(range(file_info.nfunc))
file_info.nprob = file_info.nfunc
file_info.util_funcs = []
file_info.nutil = 0
file_info.nblock = 1
file_info.block_types = [TYPE_CHANCE_BLOCK]
file_info.blocks = list(file_info.chance_vars)
return file_info
def read_mpe(file_name: Text, skip_table: bool = False) -> FileInfo:
file_info = FileInfo()
read_uai(file_name + ".uai", file_info, skip_table)
file_info.nchance = 0
file_info.chance_vars = []
file_info.decision_vars = list(range(file_info.nvar))
file_info.ndec = file_info.nvar
file_info.var_types = [TYPE_DECISION_VAR] * file_info.nvar
file_info.factor_types = [TYPE_PROB_FUNC] * file_info.nfunc
file_info.prob_funcs = list(range(file_info.nfunc))
file_info.nprob = file_info.nfunc
file_info.util_funcs = []
file_info.nutil = 0
file_info.nblock = 1
file_info.block_types = [TYPE_CHANCE_BLOCK]
file_info.blocks = list(file_info.chance_vars)
return file_info
def read_mixed(file_name: Text, skip_table: bool = False) -> FileInfo:
file_info = FileInfo()
assert not file_name.endswith(".uai"), "remove extension as this read *.uai, *.mi, *.pvo in sequence"
read_uai(file_name + ".uai", file_info, skip_table)
read_mi(file_name + ".mi", file_info)
read_pvo(file_name + ".pvo", file_info)
return file_info
def read_uai(file_name: Text, file_info: FileInfo=None, skip_table: bool=False) -> FileInfo:
if file_info is None:
file_info = FileInfo()
with open(file_name) as file_iter:
token = get_token(file_iter)
file_info.uai_file = file_name.split('/')[-1]
file_info.net_type = next(token).upper() # expect to see ID, LIMID but BN, MN also works
file_info.nvar = int(next(token))
file_info.domains = [int(next(token)) for _ in range(file_info.nvar)] # domain size of variables
file_info.nfunc = int(next(token))
for _ in range(file_info.nfunc):
scope_size = int(next(token)) # num vars appear in each function
scope = [int(next(token)) for _ in range(scope_size)] # list of var_ids from 0 to nvar-1
file_info.scopes.append(scope)
if not skip_table:
for _ in range(file_info.nfunc):
nrow = int(next(token))
table = [float(next(token)) + ZERO for _ in range(nrow)]
file_info.tables.append(table)
else:
for _ in range(file_info.nfunc):
file_info.tables.append(None)
return file_info
def read_id(file_name: Text, file_info: FileInfo) -> FileInfo:
"""
Read identity of variables and functions
"""
with open(file_name) as file_iter:
token = get_token(file_iter)
nvar = int(next(token))
assert nvar == file_info.nvar, "number of variables don't match"
file_info.var_types = [next(token).upper() for _ in range(nvar)]
nfunc = int(next(token))
assert nfunc == file_info.nfunc, "number of factors don't match"
file_info.factor_types = [next(token).upper() for _ in range(nfunc)]
file_info.chance_vars = [i for i, el in enumerate(file_info.var_types) if el == TYPE_CHANCE_VAR]
file_info.nchance = len(file_info.chance_vars)
file_info.decision_vars = [i for i, el in enumerate(file_info.var_types) if el == TYPE_DECISION_VAR]
file_info.ndec = len(file_info.decision_vars)
file_info.util_funcs = [i for i, el in enumerate(file_info.factor_types) if el == TYPE_UTIL_FUNC]
file_info.nutil = len(file_info.util_funcs)
file_info.prob_funcs = [i for i, el in enumerate(file_info.factor_types) if el in [TYPE_PROB_FUNC, TYPE_CHANCE_VAR]]
file_info.nprob = len(file_info.prob_funcs)
assert file_info.nprob == file_info.nchance, "number of probability functions don't match"
assert file_info.nvar == file_info.nchance + file_info.ndec, "number of variables don't match"
assert file_info.nfunc == file_info.nprob + file_info.nutil, "number of functions don't match"
return file_info
def read_map(file_name: Text, file_info: FileInfo) -> FileInfo:
with open(file_name) as file_iter:
token = get_token(file_iter)
file_info.ndec = int(next(token))
file_info.decision_vars = [int(next(token)) for _ in range(file_info.ndec)]
dec_vars_set = set(file_info.decision_vars)
file_info.chance_vars = [i for i in range(file_info.nvar) if i not in dec_vars_set]
chance_var_set = set(file_info.chance_vars)
file_info.nchance = len(file_info.chance_vars)
file_info.var_types = []
for i in range(file_info.nvar):
if i in chance_var_set:
file_info.var_types.append(TYPE_CHANCE_VAR)
else:
file_info.var_types.append(TYPE_DECISION_VAR)
file_info.util_funcs = []
file_info.nutil = 0
file_info.prob_funcs = [i for i in range(file_info.nfunc)] # mmap all functions are considered prob.
file_info.nprob = len(file_info.prob_funcs)
assert file_info.nvar == file_info.nchance + file_info.ndec, "number of variables don't match"
file_info.factor_types = [TYPE_PROB_FUNC] * file_info.nfunc
file_info.nblock = 2
file_info.block_types = [TYPE_CHANCE_BLOCK, TYPE_DEC_BLOCK]
file_info.blocks = [ list(iter(file_info.chance_vars)), list(iter(file_info.decision_vars)) ]
return file_info
def read_mi(file_name: Text, file_info: FileInfo) -> FileInfo:
with open(file_name) as file_iter:
token = get_token(file_iter)
nvar = int(next(token))
assert nvar == file_info.nvar, "number of variables don't match"
file_info.var_types = [next(token).upper() for _ in range(nvar)]
file_info.factor_types = [TYPE_PROB_FUNC] * file_info.nfunc
file_info.chance_vars = [i for i, el in enumerate(file_info.var_types) if el == TYPE_CHANCE_VAR]
file_info.nchance = len(file_info.chance_vars)
file_info.decision_vars = [i for i, el in enumerate(file_info.var_types) if el == TYPE_DECISION_VAR]
file_info.ndec = len(file_info.decision_vars)
file_info.util_funcs = []
file_info.nutil = 0
file_info.prob_funcs = list(range(file_info.nfunc))
file_info.nprob = file_info.nfunc
return file_info
def read_pvo(file_name: Text, file_info: FileInfo) -> FileInfo:
"""
Read block structure of limids, alternating chance and decision variables
:param file_name:
:param file_info:
:return:
"""
with open(file_name) as file_iter:
block = get_block(file_iter)
nvar = int(next(block))
assert nvar == file_info.nvar, "number of variables don't match"
file_info.nblock = int(next(block))
for _ in range(file_info.nblock):
file_info.blocks.append( [int(el) for el in next(block).split()] )
for each_block in file_info.blocks:
if all(el in file_info.decision_vars for el in each_block): # all variables are decision variables
file_info.block_types.append(TYPE_DEC_BLOCK)
else:
file_info.block_types.append(TYPE_CHANCE_BLOCK)
assert nvar == sum( [len(b) for b in file_info.blocks] ), "number of variables don't match"
return file_info
def read_vo(file_name: Text, file_info: FileInfo)->FileInfo:
with open(file_name, 'r') as file_iter:
token = get_token(file_iter)
nvar = int(next(token))
vo = [int(next(token)) for _ in range(nvar)]
file_info.vo = vo
return file_info
def read_evid(file_name: Text, file_info: FileInfo):
with open(file_name, 'r') as file_iter:
token = get_token(file_iter)
nevid = int(next(token))
evid = [(int(next(token)), int(next(token))) for _ in range(nevid)]
file_info.evid = evid
return file_info
def read_pt(file_name: Text, file_info: FileInfo):
with open(file_name, 'r') as file_iter:
token = get_token(file_iter)
nvar = int(next(token))
pt = [int(next(token)) for _ in range(nvar)]
file_info.pt = pt
return file_info
def read_svo(file_name: Text, file_info: FileInfo)->FileInfo:
with open(file_name, 'r') as file_iter:
token = get_token(file_iter)
nsubmodel = int(next(token))
nvars, widths = [], []
for _ in range(nsubmodel):
nvars.append(int(next(token))) # number of elim variables in submodel
for _ in range(nsubmodel):
widths.append(int(next(token))) # induced width per submodel
svo = []
for _ in range(nsubmodel):
nvar = int(next(token))
vo = [int(next(token)) for _ in range(nvar)]
svo.append(vo)
file_info.svo = svo
file_info.widths = widths
return file_info
def write_vo(file_name: Text, elim_order:List[int], induced_width:int=None)->None:
with open(file_name, 'w') as file_iter:
file_iter.write("# iw={}\n".format(induced_width))
file_iter.write(("{}\n".format(len(elim_order))))
for vid in elim_order:
file_iter.write("{}\n".format(vid))
def write_pvo_from_partial_elim_order(file_name: Text, partial_variable_ordering: List[List[int]])->None:
with open(file_name, 'w') as pvo_file:
# partial variable ordering defines blocks of variables
pvo_list = [el for el in partial_variable_ordering if len(el) > 0] # exclude zero length sub-list
num_blocks = len(pvo_list)
num_var = max(max(el) for el in pvo_list) + 1 # total var = largest var id + 1
pvo_file.write("{};\n".format(num_var))
pvo_file.write("{};\n".format(num_blocks))
for block in pvo_list:
pvo_file.write("{};\n".format(" ".join((str(v) for v in block))))
def write_uai(file_name, file_info: FileInfo, file_type:Text)->None:
with open(file_name, 'w') as uai_file:
uai_file.write("{}\n".format(file_type)) # ID, BAYES, MARKOV, LIMID
uai_file.write("{}\n".format(file_info.nvar))
uai_file.write("{}\n".format(" ".join(str(el) for el in file_info.domains)))
uai_file.write("{}\n".format(file_info.nfunc))
for each_scope in file_info.scopes:
uai_file.write("{}\n".format(' '.join([str(len(each_scope))]+[str(el) for el in each_scope])))
uai_file.write("\n")
for each_factor in file_info.tables:
uai_file.write(("{}\n".format(len(each_factor))))
for el in each_factor:
uai_file.write("{}\n".format(el))
uai_file.write("\n")
def write_id(file_name: Text, var_types: List[Text], func_types: List[Text])->None:
with open(file_name, 'w') as id_file:
id_file.write("{}\n".format(len(var_types)))
id_file.write("{}\n".format(" ".join((el.upper() for el in var_types)))) # C, D
id_file.write("{}\n".format(len(func_types)))
id_file.write("{}\n".format(" ".join((el.upper() for el in func_types)))) # P, U
def write_mi(file_name: Text, var_types: List[Text])->None:
with open(file_name, 'w') as mi_file:
mi_file.write("{}\n".format(len(var_types)))
mi_file.write("{}\n".format(" ".join((el.upper() for el in var_types))))
def write_map_from_types(file_name: Text, var_types: List[Text])->None:
with open(file_name, 'w') as map_file:
dec_vars = [str(el) for el in range(len(var_types)) if var_types[el] == "D"]
map_file.write("{}\n".format(len(dec_vars)))
map_file.write("{}\n".format("\n".join(dec_vars)))
def write_svo(file_name:Text, svo:List[List[int]], widths:List[int])->None:
with open(file_name, 'w') as file_iter:
file_iter.write("{}\n".format(len(svo)))
file_iter.write("{}\n".format(" ".join( str(len(svo[i])) for | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2007-2010 <NAME>, European Environment Agency
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Contributor(s):
#
# Note: This script has copied a lot of text from xml.dom.minidom.
# Whatever license applies to that file also applies to this file.
#
import xml.dom
from xml.dom.minicompat import *
from .namespaces import nsdict
from . import grammar
from .attrconverters import AttrConverters
# The following code is pasted form xml.sax.saxutils
# Tt makes it possible to run the code without the xml sax package installed
# To make it possible to have <rubbish> in your text elements, it is necessary to escape the texts
def _escape(data, entities={}):
""" Escape &, <, and > in a string of data.
You can escape other strings of data by passing a dictionary as
the optional entities parameter. The keys and values must all be
strings; each key will be replaced with its corresponding value.
"""
try:
data = data.decode('utf-8')
except (TypeError, AttributeError):
## Make sure our stream is a string
## If it comes through as bytes it fails
pass
data = data.replace("&", "&")
data = data.replace("<", "<")
data = data.replace(">", ">")
for chars, entity in list(entities.items()):
data = data.replace(chars, entity)
return data
def _quoteattr(data, entities={}):
""" Escape and quote an attribute value.
Escape &, <, and > in a string of data, then quote it for use as
an attribute value. The \" character will be escaped as well, if
necessary.
You can escape other strings of data by passing a dictionary as
the optional entities parameter. The keys and values must all be
strings; each key will be replaced with its corresponding value.
"""
entities['\n']=' '
entities['\r']=''
data = _escape(data, entities)
if '"' in data:
if "'" in data:
data = '"%s"' % data.replace('"', """)
else:
data = "'%s'" % data
else:
data = '"%s"' % data
return data
def _nssplit(qualifiedName):
""" Split a qualified name into namespace part and local part. """
fields = qualifiedName.split(':', 1)
if len(fields) == 2:
return fields
else:
return (None, fields[0])
def _nsassign(namespace):
return nsdict.setdefault(namespace,"ns" + str(len(nsdict)))
# Exceptions
class IllegalChild(Exception):
""" Complains if you add an element to a parent where it is not allowed """
class IllegalText(Exception):
""" Complains if you add text or cdata to an element where it is not allowed """
class Node(xml.dom.Node):
""" super class for more specific nodes """
parentNode = None
nextSibling = None
previousSibling = None
def hasChildNodes(self):
""" Tells whether this element has any children; text nodes,
subelements, whatever.
"""
if self.childNodes:
return True
else:
return False
def _get_childNodes(self):
return self.childNodes
def _get_firstChild(self):
if self.childNodes:
return self.childNodes[0]
def _get_lastChild(self):
if self.childNodes:
return self.childNodes[-1]
def insertBefore(self, newChild, refChild):
""" Inserts the node newChild before the existing child node refChild.
If refChild is null, insert newChild at the end of the list of children.
"""
if newChild.nodeType not in self._child_node_types:
raise IllegalChild("%s cannot be child of %s" % (newChild.tagName, self.tagName))
if newChild.parentNode is not None:
newChild.parentNode.removeChild(newChild)
if refChild is None:
self.appendChild(newChild)
else:
try:
index = self.childNodes.index(refChild)
except ValueError:
raise xml.dom.NotFoundErr()
self.childNodes.insert(index, newChild)
newChild.nextSibling = refChild
refChild.previousSibling = newChild
if index:
node = self.childNodes[index-1]
node.nextSibling = newChild
newChild.previousSibling = node
else:
newChild.previousSibling = None
newChild.parentNode = self
return newChild
def appendChild(self, newChild):
""" Adds the node newChild to the end of the list of children of this node.
If the newChild is already in the tree, it is first removed.
"""
if newChild.nodeType == self.DOCUMENT_FRAGMENT_NODE:
for c in tuple(newChild.childNodes):
self.appendChild(c)
### The DOM does not clearly specify what to return in this case
return newChild
if newChild.nodeType not in self._child_node_types:
raise IllegalChild("<%s> is not allowed in %s" % ( newChild.tagName, self.tagName))
if newChild.parentNode is not None:
newChild.parentNode.removeChild(newChild)
_append_child(self, newChild)
newChild.nextSibling = None
return newChild
def removeChild(self, oldChild):
""" Removes the child node indicated by oldChild from the list of children, and returns it.
"""
#FIXME: update ownerDocument.element_dict or find other solution
try:
self.childNodes.remove(oldChild)
except ValueError:
raise xml.dom.NotFoundErr()
if oldChild.nextSibling is not None:
oldChild.nextSibling.previousSibling = oldChild.previousSibling
if oldChild.previousSibling is not None:
oldChild.previousSibling.nextSibling = oldChild.nextSibling
oldChild.nextSibling = oldChild.previousSibling = None
if self.ownerDocument:
self.ownerDocument.clear_caches()
oldChild.parentNode = None
return oldChild
def __str__(self):
val = []
for c in self.childNodes:
val.append(str(c))
return ''.join(val)
def __unicode__(self):
val = []
for c in self.childNodes:
val.append(str(c))
return ''.join(val)
defproperty(Node, "firstChild", doc="First child node, or None.")
defproperty(Node, "lastChild", doc="Last child node, or None.")
def _append_child(self, node):
# fast path with less checks; usable by DOM builders if careful
childNodes = self.childNodes
if childNodes:
last = childNodes[-1]
node.__dict__["previousSibling"] = last
last.__dict__["nextSibling"] = node
childNodes.append(node)
node.__dict__["parentNode"] = self
class Childless(object):
""" Mixin that makes childless-ness easy to implement and avoids
the complexity of the Node methods that deal with children.
"""
attributes = None
childNodes = EmptyNodeList()
firstChild = None
lastChild = None
def _get_firstChild(self):
return None
def _get_lastChild(self):
return None
def appendChild(self, node):
""" Raises an error """
raise xml.dom.HierarchyRequestErr(
self.tagName + " nodes cannot have children")
def hasChildNodes(self):
return False
def insertBefore(self, newChild, refChild):
""" Raises an error """
raise xml.dom.HierarchyRequestErr(
self.tagName + " nodes do not have children")
def removeChild(self, oldChild):
""" Raises an error """
raise xml.dom.NotFoundErr(
self.tagName + " nodes do not have children")
def replaceChild(self, newChild, oldChild):
""" Raises an error """
raise xml.dom.HierarchyRequestErr(
self.tagName + " nodes do not have children")
class Text(Childless, Node):
nodeType = Node.TEXT_NODE
tagName = "Text"
def __init__(self, data):
self.data = data
def __str__(self):
return self.data.encode()
def __unicode__(self):
return self.data
def toXml(self,level,f):
""" Write XML in UTF-8 """
if self.data:
f.write(_escape(str(self.data).encode('utf-8')))
class CDATASection(Text, Childless):
nodeType = Node.CDATA_SECTION_NODE
def toXml(self,level,f):
""" Generate XML output of the node. If the text contains "]]>", then
escape it by going out of CDATA mode (]]>), then write the string
and then go into CDATA mode again. (<![CDATA[)
"""
if self.data:
f.write('<![CDATA[%s]]>' % self.data.replace(']]>',']]>]]><![CDATA['))
class Element(Node):
""" Creates a arbitrary element and is intended to be subclassed not used on its own.
This element is the base of every element it defines a class which resembles
a xml-element. The main advantage of this kind of implementation is that you don't
have to create a toXML method for every different object. Every element
consists of an attribute, optional subelements, optional text and optional cdata.
"""
nodeType = Node.ELEMENT_NODE
namespaces = {} # Due to shallow copy this is a static variable
_child_node_types = (Node.ELEMENT_NODE,
Node.PROCESSING_INSTRUCTION_NODE,
Node.COMMENT_NODE,
Node.TEXT_NODE,
Node.CDATA_SECTION_NODE,
Node.ENTITY_REFERENCE_NODE)
def __init__(self, attributes=None, text=None, cdata=None, qname=None, qattributes=None, check_grammar=True, **args):
if qname is not None:
self.qname = qname
assert(hasattr(self, 'qname'))
self.ownerDocument = None
self.childNodes=[]
self.allowed_children = grammar.allowed_children.get(self.qname)
prefix = self.get_nsprefix(self.qname[0])
self.tagName = prefix + ":" + self.qname[1]
if text is not None:
self.addText(text)
if cdata is not None:
self.addCDATA(cdata)
allowed_attrs = self.allowed_attributes()
if allowed_attrs is not None:
allowed_args = [ a[1].lower().replace('-','') for a in allowed_attrs]
self.attributes={}
# Load the attributes from the 'attributes' argument
if attributes:
for attr, value in list(attributes.items()):
self.setAttribute(attr, value)
# Load the qualified attributes
if qattributes:
for attr, value in list(qattributes.items()):
self.setAttrNS(attr[0], attr[1], value)
if allowed_attrs is not None:
# Load the attributes from the 'args' argument
for arg in list(args.keys()):
self.setAttribute(arg, args[arg])
else:
for arg in list(args.keys()): # If any attribute is allowed
self.attributes[arg]=args[arg]
if not check_grammar:
return
# Test that all mandatory attributes have been added.
required = grammar.required_attributes.get(self.qname)
if required:
for r in required:
if self.getAttrNS(r[0],r[1]) | |
import inspect
from abc import ABCMeta, abstractmethod
from functools import update_wrapper
from fixate.core.discover import discover_sub_classes, open_visa_instrument
from fixate.core.exceptions import InstrumentFeatureUnavailable
try:
import typing
number = typing.Union[float, int]
except ImportError:
number = float
def open(restrictions=None):
"""Open is the public api for the dmm driver for discovering and opening a connection
to a valid Digital Multimeter.
At the moment opens the first dmm connected
:param restrictions:
A dictionary containing the technical specifications of the required equipment
:return:
A instantiated class connected to a valid dmm
"""
return open_visa_instrument("DSO", restrictions)
def discover():
"""Discovers the dmm classes implemented
:return:
"""
return set(discover_sub_classes(DSO))
def validate_specifications(_class, specifications):
"""Validates the implemented dmm class against the specifications provided
:return:
True if all specifications are met
False if one or more specifications are not met by the class
"""
raise NotImplementedError()
class CallableNoArgs:
def __call__(self):
return self._call()
def _call(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class CallableBool:
def __call__(self, value: bool):
return self._call(value)
def _call(self, value: bool):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class SourcesCh:
def ch1(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def ch2(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def ch3(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def ch4(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class SourcesSpecial:
def function(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def math(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class SourcesWMem:
def wmemory1(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def wmemory2(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class SourcesExt:
def external(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class SourcesDig:
def d0(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d1(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d2(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d3(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d4(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d5(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d6(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d7(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d8(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d9(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d10(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d11(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d12(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d13(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d14(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def d15(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class MeasureAllSources(SourcesCh, SourcesSpecial, SourcesWMem, SourcesDig, CallableNoArgs):
pass
class TrigSources(SourcesCh, SourcesExt, SourcesDig):
pass
class MultiMeasureSources(MeasureAllSources):
def __init__(self):
self.ch1 = MeasureAllSources()
self.ch1 = MeasureAllSources()
self.ch2 = MeasureAllSources()
self.ch3 = MeasureAllSources()
self.ch4 = MeasureAllSources()
self.function = MeasureAllSources()
self.math = MeasureAllSources()
self.wmemory1 = MeasureAllSources()
self.wmemory2 = MeasureAllSources()
self.external = MeasureAllSources()
self.d0 = MeasureAllSources()
self.d1 = MeasureAllSources()
self.d2 = MeasureAllSources()
self.d3 = MeasureAllSources()
self.d4 = MeasureAllSources()
self.d5 = MeasureAllSources()
self.d6 = MeasureAllSources()
self.d7 = MeasureAllSources()
self.d8 = MeasureAllSources()
self.d9 = MeasureAllSources()
self.d10 = MeasureAllSources()
self.d11 = MeasureAllSources()
self.d12 = MeasureAllSources()
self.d13 = MeasureAllSources()
self.d14 = MeasureAllSources()
self.d15 = MeasureAllSources()
class Coupling:
def ac(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def dc(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def lf_reject(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def tv(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class Probe:
def attenuation(self, value: number):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class VerticalUnits:
def volts(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def amps(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class ChannelBase(CallableBool):
def __init__(self, channel_name: str):
self._ch_name = channel_name
# self.waveform = Waveform()
# self.modulate = Modulate()
# self.burst = Burst()
# self.load = Load()
self.coupling = Coupling()
self.probe = Probe()
self.units = VerticalUnits()
def bandwidth(self, value: number):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def bandwidth_limit(self, value: bool):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def impedance(self, value: number):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def invert(self, value: bool):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def offset(self, value: number):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def scale(self, value: number):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class Trigger:
def __init__(self):
self.mode = TrigMode()
self.delay = None
self.eburst = None
self.coupling = Coupling()
self.sweep = TrigSweep()
def force(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def hf_reject(self, value: bool):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def hold_off(self, value: number):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def n_reject(self, value: bool):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class TrigSweep:
def auto(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def normal(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class TrigLevel:
def high(self, value: number):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def low(self, value: number):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class TrigMode:
def __init__(self):
self.edge = TrigEdge()
class TrigEdge(CallableNoArgs):
def __init__(self):
self.source = TrigSources()
self.slope = Slopes()
def level(self, value: number):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class TrigReject:
def off(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def lf(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def hf(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class Slopes:
def rising(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def falling(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def alternating(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def either(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class Acquire:
def __init__(self):
self.mode = AcquireMode()
def normal(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def peak_detect(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def averaging(self, value: number):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def high_resolution(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class AcquireMode:
def rtim(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def segm(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class Timebase:
def __init__(self):
self.mode = TimebaseMode()
def position(self, value: number):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def scale(self, value: number):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class TimebaseMode:
def main(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def window(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def xy(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def roll(self):
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class Events:
def trigger(self):
"""
Indicates if a trigger event has occurred.
Calls to this will clear the existing trigger events
:return:
"""
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class MeasureInterval:
def __init__(self):
self.cycle = MeasureAllSources()
self.display = MeasureAllSources()
class MeasureIntervalMultipleSources:
def __init__(self):
self.cycle = MultiMeasureSources()
self.display = MultiMeasureSources()
class MeasureRMS:
def __init__(self):
self.dc = MeasureInterval()
self.ac = MeasureInterval()
class Threshold:
def percent(self, upper: number, middle: number, lower: number):
"""
:param upper: Upper Threshold
:param middle: Middle Threshold
:param lower: Lower Threshold
:return:
"""
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
def absolute(self, upper: number, middle: number, lower: number):
"""
:param upper: Upper Threshold
:param middle: Middle Threshold
:param lower: Lower Threshold
:return:
"""
raise InstrumentFeatureUnavailable(
"{} not available on this device".format(inspect.currentframe().f_code.co_name))
class Define:
def __init__(self):
super().__init__()
self.threshold = Threshold()
class Delay(CallableNoArgs):
def __init__(self):
super().__init__()
self.edges = MultiSlopes()
class Measure:
def __init__(self):
self.counter = MeasureAllSources()
self.define = Define()
self.delay = Delay()
self.duty = MeasureAllSources()
self.fall_time = MeasureAllSources()
self.frequency = MeasureAllSources()
self.cnt_edge_rising = MeasureAllSources()
self.cnt_edge_falling = MeasureAllSources()
self.cnt_pulse_positive = MeasureAllSources()
self.cnt_pulse_negative = MeasureAllSources()
self.period = MeasureAllSources()
self.phase = MultiMeasureSources()
self.pulse_width = MeasureAllSources()
self.vamplitude = MeasureAllSources()
self.vaverage = MeasureInterval()
self.vbase = MeasureAllSources()
self.vmax = MeasureAllSources()
self.vmin = MeasureAllSources()
self.vpp = MeasureAllSources()
self.vratio = MeasureIntervalMultipleSources()
self.vrms = MeasureRMS()
self.xmax = MeasureAllSources()
self.xmin = MeasureAllSources()
class MultiSlopes(CallableNoArgs):
def __init__(self):
super().__init__()
self.rising = Slopes()
self.falling = Slopes()
self.alternating = Slopes()
self.either = Slopes()
class DSO(metaclass=ABCMeta):
REGEX_ID = "DSO"
def __init__(self, instrument):
self.instrument = instrument
self.samples = 1
self.api = []
self.ch1 = ChannelBase("1")
self.ch2 = ChannelBase("2")
self.ch3 = ChannelBase("3")
self.ch4 | |
WordPress! ' + y + ']'
except:
pass
def print_logo(self):
clear = "\x1b[0m"
colors = [36, 32, 34, 35, 31, 37, 30, 33, 38, 39]
x = """
_____ _____ _____ _____ _____ _ _
|_ _/ ____/ ____| | __ \ / ____| | \ | |
| || | | | ____ _| |__) |__| | __ _| \| |
| || | | | |_ \ \ /\ / / ___/ __| | / _` | . ` |
_| || |___| |__| |\ V V /| | \__ \ |___| (_| | |\ |
|_____\_____\_____| \_/\_/ |_| |___/\_____\__,_|_| \_|
Coded By VanGans <3 SadCode.org
"""
for N, line in enumerate(x.split("\n")):
sys.stdout.write("\x1b[1;%dm%s%s\n" % (random.choice(colors), line, clear))
time.sleep(0.01)
def cls(self):
linux = 'clear'
windows = 'cls'
os.system([linux, windows][os.name == 'nt'])
def UserName_Enumeration(self):
_cun = 1
Flag = True
__Check2 = requests.get('http://' + self.url + '/?author=1', timeout=10)
try:
while Flag:
GG = requests.get('http://' + self.url + '/wp-json/wp/v2/users/' + str(_cun), timeout=5)
__InFo = json.loads(GG.text)
if 'id' not in __InFo:
Flag = False
else:
Usernamez = __InFo['name']
print r + ' [' + y + '+' + r + ']' + w + ' Wordpress Username: ' + m + Usernamez
_cun = _cun + 1
except:
try:
if '/author/' not in __Check2.text:
print r + ' [' + y + '+' + r + ']' + w + ' Wordpress Username: ' + r + 'Not FOund'
else:
find = re.findall('/author/(.*)/"', __Check2.text)
username = find[0].strip()
if '/feed' in username:
find = re.findall('/author/(.*)/feed/"', __Check2.text)
username2 = find[0].strip()
print r + ' [' + y + '+' + r + ']' + w + ' Wordpress Username: ' + m + username2
else:
print r + ' [' + y + '+' + r + ']' + w + ' Wordpress Username: ' + m + username
except requests.exceptions.ReadTimeout:
self.cls()
self.print_logo()
print y + '---------------------------------------------------'
print g + ' [' + y + '+' + g + ']' + r + ' Error: ' + y + ' [ ' + w + \
' ConnectionError! Maybe server Down, Or your ip blocked! ' + y + ']'
def CpaNel_UserName_Enumeration(self):
try:
Get_page = requests.get('http://' + self.url, timeout=10)
if '/wp-content/' in Get_page.text:
Hunt_path = requests.get('http://' + self.url + '/wp-includes/ID3/module.audio.ac3.php', timeout=10)
def Hunt_Path_User():
try:
find = re.findall('/home/(.*)/public_html/wp-includes/ID3/module.audio.ac3.php', Hunt_path.text)
x = find[0].strip()
return x
except:
pass
def Hunt_Path_Host():
try:
find = re.findall("not found in <b>(.*)wp-includes/ID3/module.audio.ac3.php", Hunt_path.text)
x = find[0].strip()
return x
except:
pass
Cpanel_username = Hunt_Path_User()
Path_Host = Hunt_Path_Host()
if Cpanel_username == None:
print r + ' [' + y + '+' + r + ']' + w + ' Cpanel Username: ' + r + 'Not FOund'
else:
print r + ' [' + y + '+' + r + ']' + w + ' Cpanel Username: ' + m + Cpanel_username
if Path_Host == None:
print r + ' [' + y + '+' + r + ']' + w + ' User Path Host : ' + r + 'Not FOund'
else:
print r + ' [' + y + '+' + r + ']' + w + ' User Path Host : ' + m + Path_Host
except requests.exceptions.ReadTimeout:
self.cls()
self.print_logo()
print y + '---------------------------------------------------'
print g + ' [' + y + '+' + g + ']' + r + ' Error: ' + y + ' [ ' + w + \
' ConnectionError! Maybe server Down, Or your ip blocked! ' + y + ']'
def Plugin_NamE_Vuln_TeST(self, Plugin_NaME):
num = 1
cal = 0
Flag = True
while Flag:
if Plugin_NaME == 'revslider':
Plugin_NaME = 'Slider Revolution'
url = 'https://wpvulndb.com/searches?page=' + str(num) + '&text=' + Plugin_NaME
aa = requests.get(url, timeout=5)
if 'No results found.' in aa.text:
Flag = False
break
else:
az = re.findall('<td><a href="/vulnerabilities/(.*)">', aa.text)
bb = (len(az) / 2)
for x in range(int(bb)):
uz = 'www.wpvulndb.com/vulnerabilities/' + str(az[cal])
Get_title = requests.get('http://' + uz, timeout=5)
Title = re.findall('<title>(.*)</title>', Get_title.text.encode('utf-8'))
print r + ' [' + y + 'MayBe Vuln' + r + '] ' + w + uz + ' --- ' + r + \
Title[0].encode('utf-8').split('-')[0]
cal = cal + 2
cal = 0
num = num + 1
def Version_Wp(self):
try:
Check_oNe = requests.get('http://' + self.url + '/readme.html', timeout=10)
find = re.findall('Version (.+)', Check_oNe.text)
try:
version = find[0].strip()
if len(version) != None:
print r + ' [' + y + '+' + r + ']' + w + ' Wp Version: ' + m + version
self.Plugin_NamE_Vuln_TeST('Wordpress ' + version)
except:
print r + ' [' + y + '+' + r + ']' + w + ' Wp Version: ' + r + 'Not Found'
except requests.exceptions.ReadTimeout:
self.cls()
self.print_logo()
print y + '---------------------------------------------------'
print g + ' [' + y + '+' + g + ']' + r + ' Error: ' + y + ' [ ' + w + \
' ConnectionError! Maybe server Down, Or your ip blocked! ' + y + ']'
def GeT_PluGin_Name(self):
plugin_NamEz = {}
Dup_Remove_Plug = 'iran-cyber.net'
a = re.findall('/wp-content/plugins/(.*)', self.CheckWordpress.text)
s = 0
bb = len(a)
for x in range(int(bb)):
name = a[s].split('/')[0]
if '?ver=' in a[s]:
verz = a[s].split('?ver=')[1]
version = re.findall('([0-9].[0-9].[0-9])', verz)
if len(version) ==0:
if '-' in str(name):
g = name.replace('-', ' ')
plugin_NamEz[g] = s
elif '_' in str(name):
h = name.replace('_', ' ')
plugin_NamEz[h] = s
else:
plugin_NamEz[name] = s
else:
OK_Ver = name + ' ' + version[0]
Dup_Remove_Plug = name
if '-' in OK_Ver:
ff = OK_Ver.replace('-', ' ')
plugin_NamEz[ff] = s
elif '_' in OK_Ver:
ff = OK_Ver.replace('_', ' ')
plugin_NamEz[ff] = s
else:
plugin_NamEz[OK_Ver] = s
else:
if Dup_Remove_Plug in name:
pass
else:
if '-' in str(name):
g = name.replace('-', ' ')
plugin_NamEz[g] = s
elif '_' in str(name):
h = name.replace('_', ' ')
plugin_NamEz[h] = s
else:
plugin_NamEz[name] = s
s = s + 1
for name_plugins in plugin_NamEz:
print r + ' [' + y + '+' + r + ']' + w + ' Plugin Name: ' + m + name_plugins
self.Plugin_NamE_Vuln_TeST(name_plugins)
def GeT_Theme_Name(self):
a = re.findall('/wp-content/themes/(.*)', self.CheckWordpress.text)
Name_Theme = a[0].split('/')[0]
if '?ver=' in a[0]:
verz = a[0].split('?ver=')[1]
version = re.findall('([0-9].[0-9].[0-9])', verz)
OK_Ver = Name_Theme + ' ' + version[0]
if '-' in OK_Ver:
x2 = OK_Ver.replace('-', ' ')
print r + ' [' + y + '+' + r + ']' + w + ' Themes Name: ' + m + x2
self.Plugin_NamE_Vuln_TeST(x2)
elif '_' in OK_Ver:
x = OK_Ver.replace('_', ' ')
print r + ' [' + y + '+' + r + ']' + w + ' Themes Name: ' + m + x
self.Plugin_NamE_Vuln_TeST(x)
else:
print r + ' [' + y + '+' + r + ']' + w + ' Themes Name: ' + m + OK_Ver
self.Plugin_NamE_Vuln_TeST(OK_Ver)
else:
if '-' in Name_Theme:
x2 = Name_Theme.replace('-', ' ')
print r + ' [' + y + '+' + r + ']' + w + ' Themes Name: ' + m + x2
self.Plugin_NamE_Vuln_TeST(x2)
elif '_' in Name_Theme:
x = Name_Theme.replace('_', ' ')
print r + ' [' + y + '+' + r + ']' + w + ' Themes Name: ' + m + x
self.Plugin_NamE_Vuln_TeST(x)
else:
print r + ' [' + y + '+' + r + ']' + w + ' Themes Name: ' + m + Name_Theme
self.Plugin_NamE_Vuln_TeST(Name_Theme)
class crawlerEMail(object):
def __init__(self):
self.emailz = {}
self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:36.0) Gecko/20100101 Firefox/36.0',
'Accept': '*/*'}
color.cls()
color.print_logo()
urlz = raw_input(' Enter Website Address: ')
self.Email_crawler(urlz)
def Email_crawler(self, url):
try:
if url.startswith("http://"):
url = url.replace("http://", "")
elif url.startswith("https://"):
url = url.replace("https://", "")
else:
pass
try:
requests.get('http://' + url, timeout=5)
except requests.ConnectionError:
color.domainnotvalid()
sys.exit()
sess = requests.session()
a = sess.get(binascii.a2b_base64('aHR0cDovL3ZpZXdkbnMuaW5mby93aG9pcy8/ZG9tYWluPQ==') + url,
timeout=5, | |
# -*- coding: utf-8 -*-
# Copyright 2012-2020 CERN
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Authors:
# - <NAME> <<EMAIL>>, 2012-2015
# - <NAME> <<EMAIL>>, 2012-2018
# - <NAME> <<EMAIL>>, 2012-2020
# - <NAME> <<EMAIL>>, 2012-2019
# - <NAME> <<EMAIL>>, 2013
# - <NAME> <<EMAIL>>, 2014-2017
# - <NAME> <<EMAIL>>, 2017-2020
# - <NAME> <<EMAIL>>, 2017-2019
# - <NAME> <<EMAIL>>, 2018
# - <NAME> <<EMAIL>>, 2018-2019
# - <NAME> <<EMAIL>>, 2018
# - <NAME> <<EMAIL>>, 2018
# - <NAME> <<EMAIL>>, 2018-2020
# - <NAME> <<EMAIL>>, 2018-2019
# - <NAME> <<EMAIL>>, 2019
# - <NAME> <<EMAIL>>, 2019
# - <NAME>' <<EMAIL>>, 2019
# - <NAME> <<EMAIL>>, 2019-2020
# - <NAME> <<EMAIL>>, 2020
# - <NAME> <<EMAIL>>, 2020
# - <NAME> <<EMAIL>>, 2020
# - <NAME> <<EMAIL>>, 2020
#
# PY3K COMPATIBLE
from __future__ import print_function
import copy
import logging
import random
from time import sleep
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
from rucio.common import exception, utils, constants
from rucio.common.config import config_get_int
from rucio.common.constraints import STRING_TYPES
from rucio.common.utils import make_valid_did, GLOBALLY_SUPPORTED_CHECKSUMS
_logger = logging.getLogger(__name__)
def get_rse_info(rse=None, vo='def', rse_id=None, session=None):
"""
Returns all protocol related RSE attributes.
Call with either rse and vo, or (in server mode) rse_id
:param rse: Name of the requested RSE
:param vo: The VO for the RSE.
:param rse_id: The id of the rse (use in server mode to avoid db calls)
:param session: The eventual database session.
:returns: a dict object with the following attributes:
id ... an internal identifier
rse ... the name of the RSE as string
type ... the storage type odf the RSE e.g. DISK
volatile ... boolean indictaing if the RSE is volatile
verify_checksum ... boolean indicating whether RSE supports requests for checksums
deteministic ... boolean indicating of the nameing of the files follows the defined determinism
domain ... indictaing the domain that should be assumed for transfers. Values are 'ALL', 'LAN', or 'WAN'
protocols ... all supported protocol in form of a list of dict objects with the followig structure
- scheme ... protocol scheme e.g. http, srm, ...
- hostname ... hostname of the site
- prefix ... path to the folder where the files are stored
- port ... port used for this protocol
- impl ... naming the python class of the protocol implementation
- extended_attributes ... additional information for the protocol
- domains ... a dict naming each domain and the priority of the protocol for each operation (lower is better, zero is not upported)
:raises RSENotFound: if the provided RSE coud not be found in the database.
"""
# __request_rse_info will be assigned when the module is loaded as it depends on the rucio environment (server or client)
# __request_rse_info, rse_region are defined in /rucio/rse/__init__.py
key = '{}:{}'.format(rse, vo) if rse_id is None else str(rse_id)
key = 'rse_info_%s' % (key)
rse_info = RSE_REGION.get(key) # NOQA pylint: disable=undefined-variable
if not rse_info: # no cached entry found
rse_info = __request_rse_info(str(rse), vo=vo, rse_id=rse_id, session=session) # NOQA pylint: disable=undefined-variable
RSE_REGION.set(key, rse_info) # NOQA pylint: disable=undefined-variable
return rse_info
def _get_possible_protocols(rse_settings, operation, scheme=None, domain=None):
"""
Filter the list of available protocols or provided by the supported ones.
:param rse_settings: The rse settings.
:param operation: The operation (write, read).
:param scheme: Optional filter if no specific protocol is defined in
rse_setting for the provided operation.
:param domain: Optional domain (lan/wan), if not specified, both will be returned
:returns: The list of possible protocols.
"""
operation = operation.lower()
candidates = rse_settings['protocols']
# convert scheme to list, if given as string
if scheme and not isinstance(scheme, list):
scheme = scheme.split(',')
tbr = []
for protocol in candidates:
# Check if scheme given and filter if so
if scheme and protocol['scheme'] not in scheme:
tbr.append(protocol)
continue
filtered = True
if not domain:
for d in list(protocol['domains'].keys()):
if protocol['domains'][d][operation] != 0:
filtered = False
else:
if protocol['domains'].get(domain, {operation: 0}).get(operation) != 0:
filtered = False
if filtered:
tbr.append(protocol)
if len(candidates) <= len(tbr):
raise exception.RSEProtocolNotSupported('No protocol for provided settings'
' found : %s.' % str(rse_settings))
return [c for c in candidates if c not in tbr]
def get_protocols_ordered(rse_settings, operation, scheme=None, domain='wan'):
if operation not in utils.rse_supported_protocol_operations():
raise exception.RSEOperationNotSupported('Operation %s is not supported' % operation)
if domain and domain not in utils.rse_supported_protocol_domains():
raise exception.RSEProtocolDomainNotSupported('Domain %s not supported' % domain)
candidates = _get_possible_protocols(rse_settings, operation, scheme, domain)
candidates.sort(key=lambda k: k['domains'][domain][operation])
return candidates
def select_protocol(rse_settings, operation, scheme=None, domain='wan'):
if operation not in utils.rse_supported_protocol_operations():
raise exception.RSEOperationNotSupported('Operation %s is not supported' % operation)
if domain and domain not in utils.rse_supported_protocol_domains():
raise exception.RSEProtocolDomainNotSupported('Domain %s not supported' % domain)
candidates = _get_possible_protocols(rse_settings, operation, scheme, domain)
# Shuffle candidates to load-balance over equal sources
random.shuffle(candidates)
return min(candidates, key=lambda k: k['domains'][domain][operation])
def create_protocol(rse_settings, operation, scheme=None, domain='wan', auth_token=None, logger=_logger):
"""
Instanciates the protocol defined for the given operation.
:param rse_settings: RSE attributes
:param operation: Intended operation for this protocol
:param scheme: Optional filter if no specific protocol is defined in rse_setting for the provided operation
:param domain: Optional specification of the domain
:param auth_token: Optionally passing JSON Web Token (OIDC) string for authentication
:returns: An instance of the requested protocol
"""
# Verify feasibility of Protocol
operation = operation.lower()
if operation not in utils.rse_supported_protocol_operations():
raise exception.RSEOperationNotSupported('Operation %s is not supported' % operation)
if domain and domain not in utils.rse_supported_protocol_domains():
raise exception.RSEProtocolDomainNotSupported('Domain %s not supported' % domain)
protocol_attr = select_protocol(rse_settings, operation, scheme, domain)
# Instantiate protocol
comp = protocol_attr['impl'].split('.')
mod = __import__('.'.join(comp[:-1]))
for n in comp[1:]:
try:
mod = getattr(mod, n)
except AttributeError as e:
logger.debug('Protocol implementations not supported.')
raise exception.RucioException(str(e)) # TODO: provide proper rucio exception
protocol_attr['auth_token'] = auth_token
protocol = mod(protocol_attr, rse_settings, logger=logger)
return protocol
def lfns2pfns(rse_settings, lfns, operation='write', scheme=None, domain='wan', auth_token=None):
"""
Convert the lfn to a pfn
:rse_settings: RSE attributes
:param lfns: logical file names as a dict containing 'scope' and 'name' as keys. For bulk a list of dicts can be provided
:param operation: Intended operation for this protocol
:param scheme: Optional filter if no specific protocol is defined in rse_setting for the provided operation
:param domain: Optional specification of the domain
:param auth_token: Optionally passing JSON Web Token (OIDC) string for authentication
:returns: a dict with scope:name as key and the PFN as value
"""
return create_protocol(rse_settings, operation, scheme, domain, auth_token=auth_token).lfns2pfns(lfns)
def parse_pfns(rse_settings, pfns, operation='read', domain='wan', auth_token=None):
"""
Checks if a PFN is feasible for a given RSE. If so it splits the pfn in its various components.
:rse_settings: RSE attributes
:param pfns: list of PFNs
:param operation: Intended operation for this protocol
:param domain: Optional specification of the domain
:param auth_token: Optionally passing JSON Web Token (OIDC) string for authentication
:returns: A dict with the parts known by the selected protocol e.g. scheme, hostname, prefix, path, name
:raises RSEFileNameNotSupported: if provided PFN is not supported by the RSE/protocol
:raises RSENotFound: if the referred storage is not found i the repository (rse_id)
:raises InvalidObject: If the properties parameter doesn't include scheme, hostname, and port as keys
:raises RSEOperationNotSupported: If no matching protocol was found for the requested operation
"""
if len(set([urlparse(pfn).scheme for pfn in pfns])) != 1:
raise ValueError('All PFNs must provide the same protocol scheme')
return create_protocol(rse_settings, operation, urlparse(pfns[0]).scheme, domain, auth_token=auth_token).parse_pfns(pfns)
def exists(rse_settings, files, domain='wan', auth_token=None, logger=_logger):
"""
Checks if a file is present at the connected storage.
Providing a list indicates the bulk mode.
:rse_settings: RSE attributes
:param files: a single dict or a list with dicts containing 'scope' and 'name'
if LFNs are used and only 'name' if PFNs are used.
E.g. {'name': '2_rse_remote_get.raw', 'scope': 'user.jdoe'}, {'name': 'user/jdoe/5a/98/3_rse_remote_get.raw'}
:param domain: The network domain, either 'wan' (default) or 'lan'
:param auth_token: Optionally passing JSON Web Token (OIDC) string for authentication
:param | |
:example:
Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/streaming/create_stream.py.html>`__ to see an example of how to use create_stream API.
"""
resource_path = "/streams"
method = "POST"
operation_name = "create_stream"
api_reference_link = "https://docs.oracle.com/iaas/api/#/en/streaming/20180418/Stream/CreateStream"
# Don't accept unknown kwargs
expected_kwargs = [
"allow_control_chars",
"retry_strategy",
"opc_request_id"
]
extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs]
if extra_kwargs:
raise ValueError(
"create_stream got unknown kwargs: {!r}".format(extra_kwargs))
header_params = {
"accept": "application/json",
"content-type": "application/json",
"opc-request-id": kwargs.get("opc_request_id", missing)
}
header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None}
retry_strategy = self.base_client.get_preferred_retry_strategy(
operation_retry_strategy=kwargs.get('retry_strategy'),
client_retry_strategy=self.retry_strategy
)
if retry_strategy is None:
retry_strategy = retry.DEFAULT_RETRY_STRATEGY
if retry_strategy:
if not isinstance(retry_strategy, retry.NoneRetryStrategy):
self.base_client.add_opc_client_retries_header(header_params)
retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback)
return retry_strategy.make_retrying_call(
self.base_client.call_api,
resource_path=resource_path,
method=method,
header_params=header_params,
body=create_stream_details,
response_type="Stream",
allow_control_chars=kwargs.get('allow_control_chars'),
operation_name=operation_name,
api_reference_link=api_reference_link)
else:
return self.base_client.call_api(
resource_path=resource_path,
method=method,
header_params=header_params,
body=create_stream_details,
response_type="Stream",
allow_control_chars=kwargs.get('allow_control_chars'),
operation_name=operation_name,
api_reference_link=api_reference_link)
def create_stream_pool(self, create_stream_pool_details, **kwargs):
"""
Starts the provisioning of a new stream pool.
To track the progress of the provisioning, you can periodically call GetStreamPool.
In the response, the `lifecycleState` parameter of the object tells you its current state.
:param oci.streaming.models.CreateStreamPoolDetails create_stream_pool_details: (required)
The stream pool to create.
:param str opc_request_id: (optional)
The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a
particular request, please provide the request ID.
:param str opc_retry_token: (optional)
A token that uniquely identifies a request so it can be retried in case of a timeout or server error without risk of executing that same action again. Retry tokens expire after 24 hours, but can be invalidated before then due to conflicting operations (for example, if a resource has been deleted and purged from the system, then a retry of the original creation request may be rejected).
:param obj retry_strategy: (optional)
A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level.
This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation uses :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` as default if no retry strategy is provided.
The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`.
:param bool allow_control_chars: (optional)
allow_control_chars is a boolean to indicate whether or not this request should allow control characters in the response object.
By default, the response will not allow control characters in strings
:return: A :class:`~oci.response.Response` object with data of type :class:`~oci.streaming.models.StreamPool`
:rtype: :class:`~oci.response.Response`
:example:
Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/streaming/create_stream_pool.py.html>`__ to see an example of how to use create_stream_pool API.
"""
resource_path = "/streampools"
method = "POST"
operation_name = "create_stream_pool"
api_reference_link = "https://docs.oracle.com/iaas/api/#/en/streaming/20180418/StreamPool/CreateStreamPool"
# Don't accept unknown kwargs
expected_kwargs = [
"allow_control_chars",
"retry_strategy",
"opc_request_id",
"opc_retry_token"
]
extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs]
if extra_kwargs:
raise ValueError(
"create_stream_pool got unknown kwargs: {!r}".format(extra_kwargs))
header_params = {
"accept": "application/json",
"content-type": "application/json",
"opc-request-id": kwargs.get("opc_request_id", missing),
"opc-retry-token": kwargs.get("opc_retry_token", missing)
}
header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None}
retry_strategy = self.base_client.get_preferred_retry_strategy(
operation_retry_strategy=kwargs.get('retry_strategy'),
client_retry_strategy=self.retry_strategy
)
if retry_strategy is None:
retry_strategy = retry.DEFAULT_RETRY_STRATEGY
if retry_strategy:
if not isinstance(retry_strategy, retry.NoneRetryStrategy):
self.base_client.add_opc_retry_token_if_needed(header_params)
self.base_client.add_opc_client_retries_header(header_params)
retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback)
return retry_strategy.make_retrying_call(
self.base_client.call_api,
resource_path=resource_path,
method=method,
header_params=header_params,
body=create_stream_pool_details,
response_type="StreamPool",
allow_control_chars=kwargs.get('allow_control_chars'),
operation_name=operation_name,
api_reference_link=api_reference_link)
else:
return self.base_client.call_api(
resource_path=resource_path,
method=method,
header_params=header_params,
body=create_stream_pool_details,
response_type="StreamPool",
allow_control_chars=kwargs.get('allow_control_chars'),
operation_name=operation_name,
api_reference_link=api_reference_link)
def delete_connect_harness(self, connect_harness_id, **kwargs):
"""
Deletes a connect harness and its content. Connect harness contents are deleted immediately. The service retains records of the connect harness itself for 90 days after deletion.
The `lifecycleState` parameter of the `ConnectHarness` object changes to `DELETING` and the connect harness becomes inaccessible for read or write operations.
To verify that a connect harness has been deleted, make a :func:`get_connect_harness` request. If the call returns the connect harness's
lifecycle state as `DELETED`, then the connect harness has been deleted. If the call returns a \"404 Not Found\" error, that means all records of the
connect harness have been deleted.
:param str connect_harness_id: (required)
The OCID of the connect harness.
:param str opc_request_id: (optional)
The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a
particular request, please provide the request ID.
:param str if_match: (optional)
For optimistic concurrency control. In the PUT or DELETE call for a resource, set the if-match parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.
:param obj retry_strategy: (optional)
A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level.
This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation uses :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` as default if no retry strategy is provided.
The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`.
:param bool allow_control_chars: (optional)
allow_control_chars is a boolean to indicate whether or not this request should allow control characters in the response object.
By default, the response will not allow control characters in strings
:return: A :class:`~oci.response.Response` object with data of type None
:rtype: :class:`~oci.response.Response`
:example:
Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/streaming/delete_connect_harness.py.html>`__ to see an example of how to use delete_connect_harness API.
"""
resource_path = "/connectharnesses/{connectHarnessId}"
method = "DELETE"
operation_name = "delete_connect_harness"
api_reference_link = "https://docs.oracle.com/iaas/api/#/en/streaming/20180418/ConnectHarness/DeleteConnectHarness"
# Don't accept unknown kwargs
expected_kwargs = [
"allow_control_chars",
"retry_strategy",
"opc_request_id",
"if_match"
]
extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs]
if extra_kwargs:
raise ValueError(
"delete_connect_harness got unknown kwargs: {!r}".format(extra_kwargs))
path_params = {
"connectHarnessId": connect_harness_id
}
path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing}
for (k, v) in six.iteritems(path_params):
if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0):
raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k))
header_params = {
"accept": "application/json",
"content-type": "application/json",
"opc-request-id": kwargs.get("opc_request_id", missing),
"if-match": kwargs.get("if_match", missing)
}
header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None}
retry_strategy = self.base_client.get_preferred_retry_strategy(
operation_retry_strategy=kwargs.get('retry_strategy'),
client_retry_strategy=self.retry_strategy
)
if retry_strategy is None:
retry_strategy = retry.DEFAULT_RETRY_STRATEGY
if retry_strategy:
if not isinstance(retry_strategy, retry.NoneRetryStrategy):
self.base_client.add_opc_client_retries_header(header_params)
retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback)
return retry_strategy.make_retrying_call(
self.base_client.call_api,
resource_path=resource_path,
method=method,
path_params=path_params,
header_params=header_params,
allow_control_chars=kwargs.get('allow_control_chars'),
operation_name=operation_name,
api_reference_link=api_reference_link)
else:
return self.base_client.call_api(
resource_path=resource_path,
method=method,
path_params=path_params,
header_params=header_params,
allow_control_chars=kwargs.get('allow_control_chars'),
operation_name=operation_name,
api_reference_link=api_reference_link)
def delete_stream(self, stream_id, **kwargs):
"""
Deletes a stream and its content. Stream contents are deleted immediately. The service retains records of the stream itself for 90 days after deletion.
The `lifecycleState` parameter of the `Stream` object changes to `DELETING` and the stream becomes inaccessible for read or write operations.
To verify that a stream has been deleted, make a :func:`get_stream` request. If the call returns the stream's
lifecycle state as `DELETED`, then the stream has been deleted. If the call returns a \"404 Not Found\" error, that means all records of the
stream have been deleted.
:param str stream_id: (required)
The OCID of the stream.
:param str opc_request_id: (optional)
The unique Oracle-assigned identifier for the request. If you need to contact Oracle about a
particular request, please provide the request ID.
:param str if_match: (optional)
For optimistic concurrency control. In the PUT or DELETE call for a resource, set the if-match parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value.
:param obj retry_strategy: (optional)
A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level.
This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation uses :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` as default if no retry strategy is provided.
The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__.
To have this operation explicitly not perform | |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the software owners: The Regents of the University of California, through
# Lawrence Berkeley National Laboratory, National Technology & Engineering
# Solutions of Sandia, LLC, Carnegie Mellon University, West Virginia University
# Research Corporation, et al. All rights reserved.
#
# Please see the files COPYRIGHT.md and LICENSE.md for full copyright and
# license information.
#################################################################################
"""
Tests for ControlVolumeBlockData, and for initializing the moving bed module
Author: <NAME>
"""
import pytest
from pyomo.environ import (
ConcreteModel,
check_optimal_termination,
SolverStatus,
value,
Var,
Constraint,
)
from pyomo.util.check_units import assert_units_consistent
from pyomo.common.config import ConfigBlock
from pyomo.util.calc_var_value import calculate_variable_from_constraint
from idaes.core import (
FlowsheetBlock,
MaterialBalanceType,
EnergyBalanceType,
MomentumBalanceType,
)
from idaes.core.util.model_statistics import (
degrees_of_freedom,
number_variables,
number_total_constraints,
number_unused_variables,
unused_variables_set,
)
from idaes.core.util.testing import initialization_tester
from idaes.core.util import scaling as iscale
from idaes.core.solvers import get_solver
from idaes.core.util.exceptions import InitializationError
# Import MBR unit model
from idaes.models_extra.gas_solid_contactors.unit_models.moving_bed import MBR
# Import property packages
from idaes.models_extra.gas_solid_contactors.properties.methane_iron_OC_reduction.gas_phase_thermo import (
GasPhaseParameterBlock,
)
from idaes.models_extra.gas_solid_contactors.properties.methane_iron_OC_reduction.solid_phase_thermo import (
SolidPhaseParameterBlock,
)
from idaes.models_extra.gas_solid_contactors.properties.methane_iron_OC_reduction.hetero_reactions import (
HeteroReactionParameterBlock,
)
# -----------------------------------------------------------------------------
# Get default solver for testing
solver = get_solver()
# -----------------------------------------------------------------------------
@pytest.mark.unit
def test_config():
m = ConcreteModel()
m.fs = FlowsheetBlock(default={"dynamic": False})
# Set up thermo props and reaction props
m.fs.gas_properties = GasPhaseParameterBlock()
m.fs.solid_properties = SolidPhaseParameterBlock()
m.fs.hetero_reactions = HeteroReactionParameterBlock(
default={
"solid_property_package": m.fs.solid_properties,
"gas_property_package": m.fs.gas_properties,
}
)
m.fs.unit = MBR(
default={
"gas_phase_config": {"property_package": m.fs.gas_properties},
"solid_phase_config": {
"property_package": m.fs.solid_properties,
"reaction_package": m.fs.hetero_reactions,
},
}
)
# Check unit config arguments
assert len(m.fs.unit.config) == 15
assert isinstance(m.fs.unit.config.gas_phase_config, ConfigBlock)
assert isinstance(m.fs.unit.config.solid_phase_config, ConfigBlock)
assert m.fs.unit.config.finite_elements == 10
assert m.fs.unit.config.length_domain_set == [0.0, 1.0]
assert m.fs.unit.config.transformation_method == "dae.finite_difference"
assert m.fs.unit.config.transformation_scheme == "BACKWARD"
assert m.fs.unit.config.collocation_points == 3
assert m.fs.unit.config.flow_type == "counter_current"
assert m.fs.unit.config.material_balance_type == MaterialBalanceType.componentTotal
assert m.fs.unit.config.energy_balance_type == EnergyBalanceType.enthalpyTotal
assert m.fs.unit.config.momentum_balance_type == MomentumBalanceType.pressureTotal
assert m.fs.unit.config.has_pressure_change is True
# Check gas phase config arguments
assert len(m.fs.unit.config.gas_phase_config) == 7
assert m.fs.unit.config.gas_phase_config.has_equilibrium_reactions is False
assert m.fs.unit.config.gas_phase_config.property_package is m.fs.gas_properties
assert m.fs.unit.config.gas_phase_config.reaction_package is None
# Check solid phase config arguments
assert len(m.fs.unit.config.solid_phase_config) == 7
assert m.fs.unit.config.solid_phase_config.has_equilibrium_reactions is False
assert m.fs.unit.config.solid_phase_config.property_package is m.fs.solid_properties
assert m.fs.unit.config.solid_phase_config.reaction_package is m.fs.hetero_reactions
# -----------------------------------------------------------------------------
class TestIronOC(object):
@pytest.fixture(scope="class")
def iron_oc(self):
m = ConcreteModel()
m.fs = FlowsheetBlock(default={"dynamic": False})
# Set up thermo props and reaction props
m.fs.gas_properties = GasPhaseParameterBlock()
m.fs.solid_properties = SolidPhaseParameterBlock()
m.fs.hetero_reactions = HeteroReactionParameterBlock(
default={
"solid_property_package": m.fs.solid_properties,
"gas_property_package": m.fs.gas_properties,
}
)
m.fs.unit = MBR(
default={
"gas_phase_config": {"property_package": m.fs.gas_properties},
"solid_phase_config": {
"property_package": m.fs.solid_properties,
"reaction_package": m.fs.hetero_reactions,
},
}
)
# Fix geometry variables
m.fs.unit.bed_diameter.fix(6.5) # m
m.fs.unit.bed_height.fix(5) # m
# Fix inlet port variables for gas and solid
m.fs.unit.gas_inlet.flow_mol[0].fix(128.20513) # mol/s
m.fs.unit.gas_inlet.temperature[0].fix(298.15) # K
m.fs.unit.gas_inlet.pressure[0].fix(2.00e5) # Pa = 1E5 bar
m.fs.unit.gas_inlet.mole_frac_comp[0, "CO2"].fix(0.02499)
m.fs.unit.gas_inlet.mole_frac_comp[0, "H2O"].fix(0.00001)
m.fs.unit.gas_inlet.mole_frac_comp[0, "CH4"].fix(0.975)
m.fs.unit.solid_inlet.flow_mass[0].fix(591.4) # kg/s
m.fs.unit.solid_inlet.particle_porosity[0].fix(0.27) # (-)
m.fs.unit.solid_inlet.temperature[0].fix(1183.15) # K
m.fs.unit.solid_inlet.mass_frac_comp[0, "Fe2O3"].fix(0.45)
m.fs.unit.solid_inlet.mass_frac_comp[0, "Fe3O4"].fix(1e-9)
m.fs.unit.solid_inlet.mass_frac_comp[0, "Al2O3"].fix(0.55)
return m
@pytest.mark.build
@pytest.mark.unit
def test_build(self, iron_oc):
assert hasattr(iron_oc.fs.unit, "gas_inlet")
assert len(iron_oc.fs.unit.gas_inlet.vars) == 4
assert isinstance(iron_oc.fs.unit.gas_inlet.flow_mol, Var)
assert isinstance(iron_oc.fs.unit.gas_inlet.mole_frac_comp, Var)
assert isinstance(iron_oc.fs.unit.gas_inlet.temperature, Var)
assert isinstance(iron_oc.fs.unit.gas_inlet.pressure, Var)
assert hasattr(iron_oc.fs.unit, "solid_inlet")
assert len(iron_oc.fs.unit.solid_inlet.vars) == 4
assert isinstance(iron_oc.fs.unit.solid_inlet.flow_mass, Var)
assert isinstance(iron_oc.fs.unit.solid_inlet.particle_porosity, Var)
assert isinstance(iron_oc.fs.unit.solid_inlet.mass_frac_comp, Var)
assert isinstance(iron_oc.fs.unit.solid_inlet.temperature, Var)
assert hasattr(iron_oc.fs.unit, "gas_outlet")
assert len(iron_oc.fs.unit.gas_outlet.vars) == 4
assert isinstance(iron_oc.fs.unit.gas_outlet.flow_mol, Var)
assert isinstance(iron_oc.fs.unit.gas_outlet.mole_frac_comp, Var)
assert isinstance(iron_oc.fs.unit.gas_outlet.temperature, Var)
assert isinstance(iron_oc.fs.unit.gas_outlet.pressure, Var)
assert hasattr(iron_oc.fs.unit, "solid_outlet")
assert len(iron_oc.fs.unit.solid_outlet.vars) == 4
assert isinstance(iron_oc.fs.unit.solid_outlet.flow_mass, Var)
assert isinstance(iron_oc.fs.unit.solid_outlet.particle_porosity, Var)
assert isinstance(iron_oc.fs.unit.solid_outlet.mass_frac_comp, Var)
assert isinstance(iron_oc.fs.unit.solid_outlet.temperature, Var)
assert isinstance(iron_oc.fs.unit.bed_area_eqn, Constraint)
assert isinstance(iron_oc.fs.unit.gas_phase_area, Constraint)
assert isinstance(iron_oc.fs.unit.solid_phase_area, Constraint)
assert isinstance(iron_oc.fs.unit.gas_super_vel, Constraint)
assert isinstance(iron_oc.fs.unit.solid_super_vel, Constraint)
assert isinstance(iron_oc.fs.unit.gas_phase_config_pressure_drop, Constraint)
assert isinstance(iron_oc.fs.unit.gas_solid_htc_eqn, Constraint)
assert isinstance(iron_oc.fs.unit.gas_phase_heat_transfer, Constraint)
assert isinstance(iron_oc.fs.unit.solid_phase_config_rxn_ext, Constraint)
assert isinstance(iron_oc.fs.unit.gas_comp_hetero_rxn, Constraint)
assert number_variables(iron_oc) == 819
assert number_total_constraints(iron_oc) == 781
assert number_unused_variables(iron_oc) == 16
@pytest.mark.unit
def test_dof(self, iron_oc):
assert degrees_of_freedom(iron_oc) == 0
@pytest.fixture(scope="class")
def iron_oc_unscaled(self):
m = ConcreteModel()
m.fs = FlowsheetBlock(default={"dynamic": False})
# Set up thermo props and reaction props
m.fs.gas_properties = GasPhaseParameterBlock()
m.fs.solid_properties = SolidPhaseParameterBlock()
m.fs.hetero_reactions = HeteroReactionParameterBlock(
default={
"solid_property_package": m.fs.solid_properties,
"gas_property_package": m.fs.gas_properties,
}
)
m.fs.unit = MBR(
default={
"gas_phase_config": {"property_package": m.fs.gas_properties},
"solid_phase_config": {
"property_package": m.fs.solid_properties,
"reaction_package": m.fs.hetero_reactions,
},
}
)
# Fix geometry variables
m.fs.unit.bed_diameter.fix(6.5) # m
m.fs.unit.bed_height.fix(5) # m
# Fix inlet port variables for gas and solid
m.fs.unit.gas_inlet.flow_mol[0].fix(128.20513) # mol/s
m.fs.unit.gas_inlet.temperature[0].fix(298.15) # K
m.fs.unit.gas_inlet.pressure[0].fix(2.00e5) # Pa = 1E5 bar
m.fs.unit.gas_inlet.mole_frac_comp[0, "CO2"].fix(0.02499)
m.fs.unit.gas_inlet.mole_frac_comp[0, "H2O"].fix(0.00001)
m.fs.unit.gas_inlet.mole_frac_comp[0, "CH4"].fix(0.975)
m.fs.unit.solid_inlet.flow_mass[0].fix(591.4) # kg/s
m.fs.unit.solid_inlet.particle_porosity[0].fix(0.27) # (-)
m.fs.unit.solid_inlet.temperature[0].fix(1183.15) # K
m.fs.unit.solid_inlet.mass_frac_comp[0, "Fe2O3"].fix(0.45)
m.fs.unit.solid_inlet.mass_frac_comp[0, "Fe3O4"].fix(1e-9)
m.fs.unit.solid_inlet.mass_frac_comp[0, "Al2O3"].fix(0.55)
return m
@pytest.mark.solver
@pytest.mark.skipif(solver is None, reason="Solver not available")
@pytest.mark.component
def test_initialize_unscaled(self, iron_oc_unscaled):
initialization_tester(
iron_oc_unscaled,
optarg={"tol": 1e-6},
gas_phase_state_args={
"flow_mol": 128.20513,
"temperature": 1183.15,
"pressure": 2.00e5,
},
solid_phase_state_args={"flow_mass": 591.4, "temperature": 1183.15},
)
@pytest.mark.solver
@pytest.mark.skipif(solver is None, reason="Solver not available")
@pytest.mark.component
def test_solve_unscaled(self, iron_oc_unscaled):
results = solver.solve(iron_oc_unscaled)
# Check for optimal solution
assert check_optimal_termination(results)
assert results.solver.status == SolverStatus.ok
@pytest.mark.component
def test_scaling(self, iron_oc):
# Set scaling gas phase for state variables
iron_oc.fs.gas_properties.set_default_scaling("flow_mol", 1e-3)
iron_oc.fs.gas_properties.set_default_scaling("pressure", 1e-5)
iron_oc.fs.gas_properties.set_default_scaling("temperature", 1e-2)
for comp in iron_oc.fs.gas_properties.component_list:
iron_oc.fs.gas_properties.set_default_scaling(
"mole_frac_comp", 1e1, index=comp
)
# Set scaling for gas phase thermophysical and transport properties
iron_oc.fs.gas_properties.set_default_scaling("enth_mol", 1e-6)
iron_oc.fs.gas_properties.set_default_scaling("enth_mol_comp", 1e-6)
iron_oc.fs.gas_properties.set_default_scaling("cp_mol", 1e-6)
iron_oc.fs.gas_properties.set_default_scaling("cp_mol_comp", 1e-6)
iron_oc.fs.gas_properties.set_default_scaling("cp_mass", 1e-6)
iron_oc.fs.gas_properties.set_default_scaling("entr_mol", 1e-2)
iron_oc.fs.gas_properties.set_default_scaling("entr_mol_phase", 1e-2)
iron_oc.fs.gas_properties.set_default_scaling("dens_mol", 1)
iron_oc.fs.gas_properties.set_default_scaling("dens_mol_comp", 1)
iron_oc.fs.gas_properties.set_default_scaling("dens_mass", 1e2)
iron_oc.fs.gas_properties.set_default_scaling("visc_d_comp", 1e4)
iron_oc.fs.gas_properties.set_default_scaling("diffusion_comp", 1e5)
iron_oc.fs.gas_properties.set_default_scaling("therm_cond_comp", 1e2)
iron_oc.fs.gas_properties.set_default_scaling("visc_d", 1e5)
iron_oc.fs.gas_properties.set_default_scaling("therm_cond", 1e0)
iron_oc.fs.gas_properties.set_default_scaling("mw", 1e2)
# Set scaling for solid phase state variables
iron_oc.fs.solid_properties.set_default_scaling("flow_mass", 1e-3)
iron_oc.fs.solid_properties.set_default_scaling("particle_porosity", 1e2)
iron_oc.fs.solid_properties.set_default_scaling("temperature", 1e-2)
for comp in iron_oc.fs.solid_properties.component_list:
iron_oc.fs.solid_properties.set_default_scaling(
"mass_frac_comp", 1e1, index=comp
)
# Set scaling for solid phase thermophysical and transport properties
iron_oc.fs.solid_properties.set_default_scaling("enth_mass", 1e-6)
iron_oc.fs.solid_properties.set_default_scaling("enth_mol_comp", 1e-6)
iron_oc.fs.solid_properties.set_default_scaling("cp_mol_comp", 1e-6)
iron_oc.fs.solid_properties.set_default_scaling("cp_mass", 1e-6)
iron_oc.fs.solid_properties.set_default_scaling("dens_mass_particle", 1e-2)
iron_oc.fs.solid_properties.set_default_scaling("dens_mass_skeletal", 1e-2)
MB = iron_oc.fs.unit # alias to keep test lines short
# Calculate scaling factors
iscale.calculate_scaling_factors(MB)
assert pytest.approx(0.01538, abs=1e-2) == iscale.get_scaling_factor(
MB.bed_diameter
)
assert pytest.approx(0.003014, abs=1e-2) == iscale.get_scaling_factor(
MB.bed_area
)
assert pytest.approx(0.003014, abs=1e-2) == iscale.get_scaling_factor(
MB.gas_phase.area
)
assert pytest.approx(0.003014, abs=1e-2) == iscale.get_scaling_factor(
MB.solid_phase.area
)
assert pytest.approx(0.068, abs=1e-2) == iscale.get_scaling_factor(
MB.gas_solid_htc[0, 0]
)
assert pytest.approx(6666.67, abs=1e-2) == iscale.get_scaling_factor(
MB.Re_particle[0, 0]
)
assert pytest.approx(0.099, abs=1e-2) == iscale.get_scaling_factor(
MB.Pr_particle[0, 0]
)
assert pytest.approx(0.06858, abs=1e-2) == iscale.get_scaling_factor(
MB.Nu_particle[0, 0]
)
for (t, x), v in MB.gas_phase.heat.items():
assert pytest.approx(0.001, abs=1e-2) == iscale.get_scaling_factor(v)
for (t, x), v in MB.solid_phase.heat.items():
assert pytest.approx(0.001, abs=1e-2) == iscale.get_scaling_factor(v)
for c in MB.bed_area_eqn.values():
assert pytest.approx(
0.0030, abs=1e-2
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x), c in MB.gas_phase_area.items():
assert pytest.approx(
0.0030, abs=1e-2
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x), c in MB.solid_phase_area.items():
assert pytest.approx(
0.0030, abs=1e-2
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x), c in MB.gas_super_vel.items():
assert pytest.approx(
0.001, abs=1e-2
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x), c in MB.solid_super_vel.items():
assert pytest.approx(
0.0001, abs=1e-2
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x), c in MB.gas_phase_config_pressure_drop.items():
assert pytest.approx(
0.0001, abs=1e-2
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x, r), c in MB.solid_phase_config_rxn_ext.items():
assert pytest.approx(
3.0135e-5, abs=1e-4
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x, p, j), c in MB.gas_comp_hetero_rxn.items():
assert pytest.approx(
0.01, abs=1e-2
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x), c in MB.solid_phase_heat_transfer.items():
assert pytest.approx(
1e-9, abs=1e-8
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x), c in MB.reynolds_number_particle.items():
assert pytest.approx(
6666, abs=100
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x), c in MB.prandtl_number.items():
assert pytest.approx(
0.1, abs=1e-2
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x), c in MB.nusselt_number_particle.items():
assert pytest.approx(
0.07, abs=1e-2
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x), c in MB.gas_solid_htc_eqn.items():
assert pytest.approx(
0.07, abs=1e-2
) == iscale.get_constraint_transform_applied_scaling_factor(c)
for (t, x), c in MB.gas_phase_heat_transfer.items():
assert pytest.approx(
1e-9, abs=1e-8
) == iscale.get_constraint_transform_applied_scaling_factor(c)
@pytest.mark.solver
@pytest.mark.skipif(solver is None, reason="Solver not available")
@pytest.mark.component
def test_initialize(self, iron_oc):
initialization_tester(
iron_oc,
optarg={"tol": 1e-6},
gas_phase_state_args={
"flow_mol": 128.20513,
"temperature": 1183.15,
"pressure": 2.00e5,
},
solid_phase_state_args={"flow_mass": 591.4, "temperature": 1183.15},
)
@pytest.mark.solver
@pytest.mark.skipif(solver is None, reason="Solver not available")
@pytest.mark.component
def test_solve(self, iron_oc):
results = solver.solve(iron_oc)
# Check for optimal solution
assert check_optimal_termination(results)
assert results.solver.status == SolverStatus.ok
@pytest.mark.solver
@pytest.mark.skipif(solver is None, reason="Solver not available")
@pytest.mark.component
def test_solution(self, iron_oc):
assert (
pytest.approx(0.0479, abs=1e-2)
== iron_oc.fs.unit.velocity_superficial_gas[0, 0].value
)
assert (
pytest.approx(0.5675, abs=1e-2)
== iron_oc.fs.unit.velocity_superficial_gas[0, 1].value
)
assert (
pytest.approx(0.0039, abs=1e-2)
== iron_oc.fs.unit.velocity_superficial_solid[0].value
)
# Check the pressure drop that occurs across the bed
assert (
pytest.approx(198217.7068, abs=1e-2)
== iron_oc.fs.unit.gas_outlet.pressure[0].value
)
assert (
pytest.approx(1782.2932, abs=1e-2)
== iron_oc.fs.unit.gas_inlet.pressure[0].value
- iron_oc.fs.unit.gas_outlet.pressure[0].value
)
@pytest.mark.component
def test_units_consistent(self, iron_oc):
assert_units_consistent(iron_oc)
@pytest.mark.solver
@pytest.mark.skipif(solver is None, reason="Solver not available")
@pytest.mark.component
def test_conservation(self, iron_oc):
# Conservation of material check
calculate_variable_from_constraint(
iron_oc.fs.unit.gas_phase.properties[0, 0].mw,
iron_oc.fs.unit.gas_phase.properties[0, 0].mw_eqn,
)
calculate_variable_from_constraint(
iron_oc.fs.unit.gas_phase.properties[0, 1].mw,
iron_oc.fs.unit.gas_phase.properties[0, 1].mw_eqn,
)
mbal_gas = value(
(
iron_oc.fs.unit.gas_inlet.flow_mol[0]
* iron_oc.fs.unit.gas_phase.properties[0, 0].mw
)
- (
iron_oc.fs.unit.gas_outlet.flow_mol[0]
* iron_oc.fs.unit.gas_phase.properties[0, 1].mw
)
)
mbal_solid = value(
iron_oc.fs.unit.solid_inlet.flow_mass[0]
- iron_oc.fs.unit.solid_outlet.flow_mass[0]
)
mbal_tol | |
def db_add_id(self, id):
self._db_id = id
def db_change_id(self, id):
self._db_id = id
def db_delete_id(self, id):
self._db_id = None
def __get_db_ports(self):
return self._db_ports
def __set_db_ports(self, ports):
self._db_ports = ports
self.is_dirty = True
db_ports = property(__get_db_ports, __set_db_ports)
def db_get_ports(self):
return self._db_ports
def db_add_port(self, port):
self.is_dirty = True
self._db_ports.append(port)
self.db_ports_id_index[port.db_id] = port
self.db_ports_type_index[port.db_type] = port
def db_change_port(self, port):
self.is_dirty = True
found = False
for i in xrange(len(self._db_ports)):
if self._db_ports[i].db_id == port.db_id:
self._db_ports[i] = port
found = True
break
if not found:
self._db_ports.append(port)
self.db_ports_id_index[port.db_id] = port
self.db_ports_type_index[port.db_type] = port
def db_delete_port(self, port):
self.is_dirty = True
for i in xrange(len(self._db_ports)):
if self._db_ports[i].db_id == port.db_id:
if not self._db_ports[i].is_new:
self.db_deleted_ports.append(self._db_ports[i])
del self._db_ports[i]
break
del self.db_ports_id_index[port.db_id]
del self.db_ports_type_index[port.db_type]
def db_get_port(self, key):
for i in xrange(len(self._db_ports)):
if self._db_ports[i].db_id == key:
return self._db_ports[i]
return None
def db_get_port_by_id(self, key):
return self.db_ports_id_index[key]
def db_has_port_with_id(self, key):
return key in self.db_ports_id_index
def db_get_port_by_type(self, key):
return self.db_ports_type_index[key]
def db_has_port_with_type(self, key):
return key in self.db_ports_type_index
def getPrimaryKey(self):
return self._db_id
class DBAction(object):
vtType = 'action'
def __init__(self, operations=None, id=None, prevId=None, date=None, session=None, user=None, prune=None, annotations=None):
self.db_deleted_operations = []
self.db_operations_id_index = {}
if operations is None:
self._db_operations = []
else:
self._db_operations = operations
for v in self._db_operations:
self.db_operations_id_index[v.db_id] = v
self._db_id = id
self._db_prevId = prevId
self._db_date = date
self._db_session = session
self._db_user = user
self._db_prune = prune
self.db_deleted_annotations = []
self.db_annotations_id_index = {}
self.db_annotations_key_index = {}
if annotations is None:
self._db_annotations = []
else:
self._db_annotations = annotations
for v in self._db_annotations:
self.db_annotations_id_index[v.db_id] = v
self.db_annotations_key_index[v.db_key] = v
self.is_dirty = True
self.is_new = True
def __copy__(self):
return DBAction.do_copy(self)
def do_copy(self, new_ids=False, id_scope=None, id_remap=None):
cp = DBAction(id=self._db_id,
prevId=self._db_prevId,
date=self._db_date,
session=self._db_session,
user=self._db_user,
prune=self._db_prune)
if self._db_operations is None:
cp._db_operations = []
else:
cp._db_operations = [v.do_copy(new_ids, id_scope, id_remap) for v in self._db_operations]
if self._db_annotations is None:
cp._db_annotations = []
else:
cp._db_annotations = [v.do_copy(new_ids, id_scope, id_remap) for v in self._db_annotations]
# set new ids
if new_ids:
new_id = id_scope.getNewId(self.vtType)
if self.vtType in id_scope.remap:
id_remap[(id_scope.remap[self.vtType], self.db_id)] = new_id
else:
id_remap[(self.vtType, self.db_id)] = new_id
cp.db_id = new_id
if hasattr(self, 'db_prevId') and ('action', self._db_prevId) in id_remap:
cp._db_prevId = id_remap[('action', self._db_prevId)]
# recreate indices and set flags
cp.db_operations_id_index = dict((v.db_id, v) for v in cp._db_operations)
cp.db_annotations_id_index = dict((v.db_id, v) for v in cp._db_annotations)
cp.db_annotations_key_index = dict((v.db_key, v) for v in cp._db_annotations)
if not new_ids:
cp.is_dirty = self.is_dirty
cp.is_new = self.is_new
return cp
@staticmethod
def update_version(old_obj, trans_dict, new_obj=None):
if new_obj is None:
new_obj = DBAction()
class_dict = {}
if new_obj.__class__.__name__ in trans_dict:
class_dict = trans_dict[new_obj.__class__.__name__]
if 'operations' in class_dict:
res = class_dict['operations'](old_obj, trans_dict)
for obj in res:
new_obj.db_add_operation(obj)
elif hasattr(old_obj, 'db_operations') and old_obj.db_operations is not None:
for obj in old_obj.db_operations:
if obj.vtType == 'add':
new_obj.db_add_operation(DBAdd.update_version(obj, trans_dict))
elif obj.vtType == 'delete':
new_obj.db_add_operation(DBDelete.update_version(obj, trans_dict))
elif obj.vtType == 'change':
new_obj.db_add_operation(DBChange.update_version(obj, trans_dict))
if hasattr(old_obj, 'db_deleted_operations') and hasattr(new_obj, 'db_deleted_operations'):
for obj in old_obj.db_deleted_operations:
if obj.vtType == 'add':
n_obj = DBAdd.update_version(obj, trans_dict)
new_obj.db_deleted_operations.append(n_obj)
elif obj.vtType == 'delete':
n_obj = DBDelete.update_version(obj, trans_dict)
new_obj.db_deleted_operations.append(n_obj)
elif obj.vtType == 'change':
n_obj = DBChange.update_version(obj, trans_dict)
new_obj.db_deleted_operations.append(n_obj)
if 'id' in class_dict:
res = class_dict['id'](old_obj, trans_dict)
new_obj.db_id = res
elif hasattr(old_obj, 'db_id') and old_obj.db_id is not None:
new_obj.db_id = old_obj.db_id
if 'prevId' in class_dict:
res = class_dict['prevId'](old_obj, trans_dict)
new_obj.db_prevId = res
elif hasattr(old_obj, 'db_prevId') and old_obj.db_prevId is not None:
new_obj.db_prevId = old_obj.db_prevId
if 'date' in class_dict:
res = class_dict['date'](old_obj, trans_dict)
new_obj.db_date = res
elif hasattr(old_obj, 'db_date') and old_obj.db_date is not None:
new_obj.db_date = old_obj.db_date
if 'session' in class_dict:
res = class_dict['session'](old_obj, trans_dict)
new_obj.db_session = res
elif hasattr(old_obj, 'db_session') and old_obj.db_session is not None:
new_obj.db_session = old_obj.db_session
if 'user' in class_dict:
res = class_dict['user'](old_obj, trans_dict)
new_obj.db_user = res
elif hasattr(old_obj, 'db_user') and old_obj.db_user is not None:
new_obj.db_user = old_obj.db_user
if 'prune' in class_dict:
res = class_dict['prune'](old_obj, trans_dict)
new_obj.db_prune = res
elif hasattr(old_obj, 'db_prune') and old_obj.db_prune is not None:
new_obj.db_prune = old_obj.db_prune
if 'annotations' in class_dict:
res = class_dict['annotations'](old_obj, trans_dict)
for obj in res:
new_obj.db_add_annotation(obj)
elif hasattr(old_obj, 'db_annotations') and old_obj.db_annotations is not None:
for obj in old_obj.db_annotations:
new_obj.db_add_annotation(DBAnnotation.update_version(obj, trans_dict))
if hasattr(old_obj, 'db_deleted_annotations') and hasattr(new_obj, 'db_deleted_annotations'):
for obj in old_obj.db_deleted_annotations:
n_obj = DBAnnotation.update_version(obj, trans_dict)
new_obj.db_deleted_annotations.append(n_obj)
new_obj.is_new = old_obj.is_new
new_obj.is_dirty = old_obj.is_dirty
return new_obj
def db_children(self, parent=(None,None), orphan=False):
children = []
to_del = []
for child in self.db_annotations:
children.extend(child.db_children((self.vtType, self.db_id), orphan))
if orphan:
to_del.append(child)
for child in to_del:
self.db_delete_annotation(child)
to_del = []
for child in self.db_operations:
children.extend(child.db_children((self.vtType, self.db_id), orphan))
if orphan:
to_del.append(child)
for child in to_del:
self.db_delete_operation(child)
children.append((self, parent[0], parent[1]))
return children
def db_deleted_children(self, remove=False):
children = []
children.extend(self.db_deleted_annotations)
children.extend(self.db_deleted_operations)
if remove:
self.db_deleted_annotations = []
self.db_deleted_operations = []
return children
def has_changes(self):
if self.is_dirty:
return True
for child in self._db_annotations:
if child.has_changes():
return True
for child in self._db_operations:
if child.has_changes():
return True
return False
def __get_db_operations(self):
return self._db_operations
def __set_db_operations(self, operations):
self._db_operations = operations
self.is_dirty = True
db_operations = property(__get_db_operations, __set_db_operations)
def db_get_operations(self):
return self._db_operations
def db_add_operation(self, operation):
self.is_dirty = True
self._db_operations.append(operation)
self.db_operations_id_index[operation.db_id] = operation
def db_change_operation(self, operation):
self.is_dirty = True
found = False
for i in xrange(len(self._db_operations)):
if self._db_operations[i].db_id == operation.db_id:
self._db_operations[i] = operation
found = True
break
if not found:
self._db_operations.append(operation)
self.db_operations_id_index[operation.db_id] = operation
def db_delete_operation(self, operation):
self.is_dirty = True
for i in xrange(len(self._db_operations)):
if self._db_operations[i].db_id == operation.db_id:
if not self._db_operations[i].is_new:
self.db_deleted_operations.append(self._db_operations[i])
del self._db_operations[i]
break
del self.db_operations_id_index[operation.db_id]
def db_get_operation(self, key):
for i in xrange(len(self._db_operations)):
if self._db_operations[i].db_id == key:
return self._db_operations[i]
return None
def db_get_operation_by_id(self, key):
return self.db_operations_id_index[key]
def db_has_operation_with_id(self, key):
return key in self.db_operations_id_index
def __get_db_id(self):
return self._db_id
def __set_db_id(self, id):
self._db_id = id
self.is_dirty = True
db_id = property(__get_db_id, __set_db_id)
def db_add_id(self, id):
self._db_id = id
def db_change_id(self, id):
self._db_id = id
def db_delete_id(self, id):
self._db_id = None
def __get_db_prevId(self):
return self._db_prevId
def __set_db_prevId(self, prevId):
self._db_prevId = prevId
self.is_dirty = True
db_prevId = property(__get_db_prevId, __set_db_prevId)
def db_add_prevId(self, prevId):
self._db_prevId = prevId
def db_change_prevId(self, prevId):
self._db_prevId = prevId
def db_delete_prevId(self, prevId):
self._db_prevId = None
def __get_db_date(self):
return self._db_date
def __set_db_date(self, date):
self._db_date = date
self.is_dirty = True
db_date = property(__get_db_date, __set_db_date)
def db_add_date(self, date):
self._db_date = date
def db_change_date(self, date):
self._db_date = date
def db_delete_date(self, date):
self._db_date = None
def __get_db_session(self):
return self._db_session
def __set_db_session(self, session):
self._db_session = session
self.is_dirty = True
db_session = property(__get_db_session, __set_db_session)
def db_add_session(self, session):
self._db_session = session
def db_change_session(self, session):
self._db_session = session
def db_delete_session(self, session):
self._db_session = None
def __get_db_user(self):
return self._db_user
def __set_db_user(self, user):
self._db_user = user
self.is_dirty = True
db_user = property(__get_db_user, __set_db_user)
def db_add_user(self, user):
self._db_user = user
def db_change_user(self, user):
self._db_user = user
def db_delete_user(self, user):
self._db_user = None
def __get_db_prune(self):
return self._db_prune
def __set_db_prune(self, prune):
self._db_prune = prune
self.is_dirty = True
db_prune = property(__get_db_prune, __set_db_prune)
def db_add_prune(self, prune):
self._db_prune = prune
def db_change_prune(self, prune):
self._db_prune = prune
def db_delete_prune(self, prune):
self._db_prune = None
def __get_db_annotations(self):
return self._db_annotations
def __set_db_annotations(self, annotations):
self._db_annotations = annotations
self.is_dirty = True
db_annotations = property(__get_db_annotations, __set_db_annotations)
def db_get_annotations(self):
return self._db_annotations
def db_add_annotation(self, annotation):
self.is_dirty = True
self._db_annotations.append(annotation)
self.db_annotations_id_index[annotation.db_id] = annotation
self.db_annotations_key_index[annotation.db_key] = annotation
def db_change_annotation(self, annotation):
self.is_dirty = True
found = False
for i in xrange(len(self._db_annotations)):
if self._db_annotations[i].db_id == annotation.db_id:
self._db_annotations[i] = annotation
found = True
break
if not found:
self._db_annotations.append(annotation)
self.db_annotations_id_index[annotation.db_id] = annotation
self.db_annotations_key_index[annotation.db_key] = annotation
def db_delete_annotation(self, annotation):
self.is_dirty = True
for i in xrange(len(self._db_annotations)):
if self._db_annotations[i].db_id == annotation.db_id:
if not self._db_annotations[i].is_new:
self.db_deleted_annotations.append(self._db_annotations[i])
del self._db_annotations[i]
break
del self.db_annotations_id_index[annotation.db_id]
del self.db_annotations_key_index[annotation.db_key]
def db_get_annotation(self, key):
for i in xrange(len(self._db_annotations)):
if self._db_annotations[i].db_id == key:
return self._db_annotations[i]
return None
def db_get_annotation_by_id(self, key):
return self.db_annotations_id_index[key]
def db_has_annotation_with_id(self, key):
return key in self.db_annotations_id_index
def db_get_annotation_by_key(self, key):
return self.db_annotations_key_index[key]
def db_has_annotation_with_key(self, key):
return key in self.db_annotations_key_index
def getPrimaryKey(self):
return self._db_id
class DBDelete(object):
vtType = 'delete'
def __init__(self, id=None, what=None, objectId=None, parentObjId=None, parentObjType=None):
self._db_id = id
self._db_what = what
self._db_objectId = objectId
self._db_parentObjId = parentObjId
self._db_parentObjType = parentObjType
self.is_dirty = True
self.is_new = True
def __copy__(self):
return DBDelete.do_copy(self)
def do_copy(self, new_ids=False, id_scope=None, id_remap=None):
cp = DBDelete(id=self._db_id,
what=self._db_what,
objectId=self._db_objectId,
parentObjId=self._db_parentObjId,
parentObjType=self._db_parentObjType)
# set new ids
if new_ids:
new_id = id_scope.getNewId(self.vtType)
if | |
pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for State_ in self.State:
namespaceprefix_ = self.State_nsprefix_ + ':' if (UseCapturedNS_ and self.State_nsprefix_) else ''
State_.export(outfile, level, namespaceprefix_, namespacedef_='', name_='State', pretty_print=pretty_print)
def build(self, node, gds_collector_=None):
self.gds_collector_ = gds_collector_
if SaveElementTreeNode:
self.gds_elementtree_node_ = node
already_processed = set()
self.ns_prefix_ = node.prefix
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
return self
def buildAttributes(self, node, attrs, already_processed):
pass
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
if nodeName_ == 'State':
obj_ = State.factory(parent_object_=self)
obj_.build(child_, gds_collector_=gds_collector_)
self.State.append(obj_)
obj_.original_tagname_ = 'State'
# end class ArrayOfState
class State(GeneratedsSuper):
__hash__ = GeneratedsSuper.__hash__
subclass = None
superclass = None
def __init__(self, Code=None, Name=None, gds_collector_=None, **kwargs_):
self.gds_collector_ = gds_collector_
self.gds_elementtree_node_ = None
self.original_tagname_ = None
self.parent_object_ = kwargs_.get('parent_object_')
self.ns_prefix_ = None
self.Code = Code
self.Code_nsprefix_ = None
self.Name = Name
self.Name_nsprefix_ = None
def factory(*args_, **kwargs_):
if CurrentSubclassModule_ is not None:
subclass = getSubclassFromModule_(
CurrentSubclassModule_, State)
if subclass is not None:
return subclass(*args_, **kwargs_)
if State.subclass:
return State.subclass(*args_, **kwargs_)
else:
return State(*args_, **kwargs_)
factory = staticmethod(factory)
def get_ns_prefix_(self):
return self.ns_prefix_
def set_ns_prefix_(self, ns_prefix):
self.ns_prefix_ = ns_prefix
def get_Code(self):
return self.Code
def set_Code(self, Code):
self.Code = Code
def get_Name(self):
return self.Name
def set_Name(self, Name):
self.Name = Name
def hasContent_(self):
if (
self.Code is not None or
self.Name is not None
):
return True
else:
return False
def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='State', pretty_print=True):
imported_ns_def_ = GenerateDSNamespaceDefs_.get('State')
if imported_ns_def_ is not None:
namespacedef_ = imported_ns_def_
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.original_tagname_ is not None and name_ == 'State':
name_ = self.original_tagname_
if UseCapturedNS_ and self.ns_prefix_:
namespaceprefix_ = self.ns_prefix_ + ':'
showIndent(outfile, level, pretty_print)
outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='State')
if self.hasContent_():
outfile.write('>%s' % (eol_, ))
self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='State', pretty_print=pretty_print)
showIndent(outfile, level, pretty_print)
outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
else:
outfile.write('/>%s' % (eol_, ))
def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='State'):
pass
def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='State', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Code is not None:
namespaceprefix_ = self.Code_nsprefix_ + ':' if (UseCapturedNS_ and self.Code_nsprefix_) else ''
showIndent(outfile, level, pretty_print)
outfile.write('<%sCode>%s</%sCode>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Code), input_name='Code')), namespaceprefix_ , eol_))
if self.Name is not None:
namespaceprefix_ = self.Name_nsprefix_ + ':' if (UseCapturedNS_ and self.Name_nsprefix_) else ''
showIndent(outfile, level, pretty_print)
outfile.write('<%sName>%s</%sName>%s' % (namespaceprefix_ , self.gds_encode(self.gds_format_string(quote_xml(self.Name), input_name='Name')), namespaceprefix_ , eol_))
def build(self, node, gds_collector_=None):
self.gds_collector_ = gds_collector_
if SaveElementTreeNode:
self.gds_elementtree_node_ = node
already_processed = set()
self.ns_prefix_ = node.prefix
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
return self
def buildAttributes(self, node, attrs, already_processed):
pass
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
if nodeName_ == 'Code':
value_ = child_.text
value_ = self.gds_parse_string(value_, node, 'Code')
value_ = self.gds_validate_string(value_, node, 'Code')
self.Code = value_
self.Code_nsprefix_ = child_.prefix
elif nodeName_ == 'Name':
value_ = child_.text
value_ = self.gds_parse_string(value_, node, 'Name')
value_ = self.gds_validate_string(value_, node, 'Name')
self.Name = value_
self.Name_nsprefix_ = child_.prefix
# end class State
class AddressServiceabilityRequest(GeneratedsSuper):
__hash__ = GeneratedsSuper.__hash__
subclass = None
superclass = None
def __init__(self, ClientInfo=None, Transaction=None, Address=None, ServiceDetails=None, gds_collector_=None, **kwargs_):
self.gds_collector_ = gds_collector_
self.gds_elementtree_node_ = None
self.original_tagname_ = None
self.parent_object_ = kwargs_.get('parent_object_')
self.ns_prefix_ = None
self.ClientInfo = ClientInfo
self.ClientInfo_nsprefix_ = None
self.Transaction = Transaction
self.Transaction_nsprefix_ = None
self.Address = Address
self.Address_nsprefix_ = None
self.ServiceDetails = ServiceDetails
self.ServiceDetails_nsprefix_ = None
def factory(*args_, **kwargs_):
if CurrentSubclassModule_ is not None:
subclass = getSubclassFromModule_(
CurrentSubclassModule_, AddressServiceabilityRequest)
if subclass is not None:
return subclass(*args_, **kwargs_)
if AddressServiceabilityRequest.subclass:
return AddressServiceabilityRequest.subclass(*args_, **kwargs_)
else:
return AddressServiceabilityRequest(*args_, **kwargs_)
factory = staticmethod(factory)
def get_ns_prefix_(self):
return self.ns_prefix_
def set_ns_prefix_(self, ns_prefix):
self.ns_prefix_ = ns_prefix
def get_ClientInfo(self):
return self.ClientInfo
def set_ClientInfo(self, ClientInfo):
self.ClientInfo = ClientInfo
def get_Transaction(self):
return self.Transaction
def set_Transaction(self, Transaction):
self.Transaction = Transaction
def get_Address(self):
return self.Address
def set_Address(self, Address):
self.Address = Address
def get_ServiceDetails(self):
return self.ServiceDetails
def set_ServiceDetails(self, ServiceDetails):
self.ServiceDetails = ServiceDetails
def hasContent_(self):
if (
self.ClientInfo is not None or
self.Transaction is not None or
self.Address is not None or
self.ServiceDetails is not None
):
return True
else:
return False
def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressServiceabilityRequest', pretty_print=True):
imported_ns_def_ = GenerateDSNamespaceDefs_.get('AddressServiceabilityRequest')
if imported_ns_def_ is not None:
namespacedef_ = imported_ns_def_
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.original_tagname_ is not None and name_ == 'AddressServiceabilityRequest':
name_ = self.original_tagname_
if UseCapturedNS_ and self.ns_prefix_:
namespaceprefix_ = self.ns_prefix_ + ':'
showIndent(outfile, level, pretty_print)
outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='AddressServiceabilityRequest')
if self.hasContent_():
outfile.write('>%s' % (eol_, ))
self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='AddressServiceabilityRequest', pretty_print=pretty_print)
showIndent(outfile, level, pretty_print)
outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
else:
outfile.write('/>%s' % (eol_, ))
def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='AddressServiceabilityRequest'):
pass
def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressServiceabilityRequest', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.ClientInfo is not None:
namespaceprefix_ = self.ClientInfo_nsprefix_ + ':' if (UseCapturedNS_ and self.ClientInfo_nsprefix_) else ''
self.ClientInfo.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ClientInfo', pretty_print=pretty_print)
if self.Transaction is not None:
namespaceprefix_ = self.Transaction_nsprefix_ + ':' if (UseCapturedNS_ and self.Transaction_nsprefix_) else ''
self.Transaction.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Transaction', pretty_print=pretty_print)
if self.Address is not None:
namespaceprefix_ = self.Address_nsprefix_ + ':' if (UseCapturedNS_ and self.Address_nsprefix_) else ''
self.Address.export(outfile, level, namespaceprefix_, namespacedef_='', name_='Address', pretty_print=pretty_print)
if self.ServiceDetails is not None:
namespaceprefix_ = self.ServiceDetails_nsprefix_ + ':' if (UseCapturedNS_ and self.ServiceDetails_nsprefix_) else ''
self.ServiceDetails.export(outfile, level, namespaceprefix_, namespacedef_='', name_='ServiceDetails', pretty_print=pretty_print)
def build(self, node, gds_collector_=None):
self.gds_collector_ = gds_collector_
if SaveElementTreeNode:
self.gds_elementtree_node_ = node
already_processed = set()
self.ns_prefix_ = node.prefix
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
self.buildChildren(child, node, nodeName_, gds_collector_=gds_collector_)
return self
def buildAttributes(self, node, attrs, already_processed):
pass
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False, gds_collector_=None):
if nodeName_ == 'ClientInfo':
obj_ = ClientInfo.factory(parent_object_=self)
obj_.build(child_, gds_collector_=gds_collector_)
self.ClientInfo = obj_
obj_.original_tagname_ = 'ClientInfo'
elif nodeName_ == 'Transaction':
obj_ = Transaction.factory(parent_object_=self)
obj_.build(child_, gds_collector_=gds_collector_)
self.Transaction = obj_
obj_.original_tagname_ = 'Transaction'
elif nodeName_ == 'Address':
obj_ = Address.factory(parent_object_=self)
obj_.build(child_, gds_collector_=gds_collector_)
self.Address = obj_
obj_.original_tagname_ = 'Address'
elif nodeName_ == 'ServiceDetails':
obj_ = AddressServiceDetails.factory(parent_object_=self)
obj_.build(child_, gds_collector_=gds_collector_)
self.ServiceDetails = obj_
obj_.original_tagname_ = 'ServiceDetails'
# end class AddressServiceabilityRequest
class AddressServiceDetails(GeneratedsSuper):
__hash__ = GeneratedsSuper.__hash__
subclass = None
superclass = None
def __init__(self, ProductGroup=None, ProductType=None, ServiceMode=None, gds_collector_=None, **kwargs_):
self.gds_collector_ = gds_collector_
self.gds_elementtree_node_ = None
self.original_tagname_ = None
self.parent_object_ = kwargs_.get('parent_object_')
self.ns_prefix_ = None
self.ProductGroup = ProductGroup
self.ProductGroup_nsprefix_ = None
self.ProductType = ProductType
self.ProductType_nsprefix_ = None
self.ServiceMode = ServiceMode
self.ServiceMode_nsprefix_ = None
def factory(*args_, **kwargs_):
if CurrentSubclassModule_ is not None:
subclass = getSubclassFromModule_(
CurrentSubclassModule_, AddressServiceDetails)
if subclass is not None:
return subclass(*args_, **kwargs_)
if AddressServiceDetails.subclass:
return AddressServiceDetails.subclass(*args_, **kwargs_)
else:
return AddressServiceDetails(*args_, **kwargs_)
factory = staticmethod(factory)
def get_ns_prefix_(self):
return self.ns_prefix_
def set_ns_prefix_(self, ns_prefix):
self.ns_prefix_ = ns_prefix
def get_ProductGroup(self):
return self.ProductGroup
def set_ProductGroup(self, ProductGroup):
self.ProductGroup = ProductGroup
def get_ProductType(self):
return self.ProductType
def set_ProductType(self, ProductType):
self.ProductType = ProductType
def get_ServiceMode(self):
return self.ServiceMode
def set_ServiceMode(self, ServiceMode):
self.ServiceMode = ServiceMode
def hasContent_(self):
if (
self.ProductGroup is not None or
self.ProductType is not None or
self.ServiceMode is not None
):
return True
else:
return False
def export(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressServiceDetails', pretty_print=True):
imported_ns_def_ = GenerateDSNamespaceDefs_.get('AddressServiceDetails')
if imported_ns_def_ is not None:
namespacedef_ = imported_ns_def_
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.original_tagname_ is not None and name_ == 'AddressServiceDetails':
name_ = self.original_tagname_
if UseCapturedNS_ and self.ns_prefix_:
namespaceprefix_ = self.ns_prefix_ + ':'
showIndent(outfile, level, pretty_print)
outfile.write('<%s%s%s' % (namespaceprefix_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
self.exportAttributes(outfile, level, already_processed, namespaceprefix_, name_='AddressServiceDetails')
if self.hasContent_():
outfile.write('>%s' % (eol_, ))
self.exportChildren(outfile, level + 1, namespaceprefix_, namespacedef_, name_='AddressServiceDetails', pretty_print=pretty_print)
showIndent(outfile, level, pretty_print)
outfile.write('</%s%s>%s' % (namespaceprefix_, name_, eol_))
else:
outfile.write('/>%s' % (eol_, ))
def exportAttributes(self, outfile, level, already_processed, namespaceprefix_='', name_='AddressServiceDetails'):
pass
def exportChildren(self, outfile, level, namespaceprefix_='', namespacedef_='', name_='AddressServiceDetails', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.ProductGroup is not None:
namespaceprefix_ = self.ProductGroup_nsprefix_ + ':' if (UseCapturedNS_ and self.ProductGroup_nsprefix_) else ''
showIndent(outfile, | |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Positioning_Assistant_GUI.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Mouse_Positioning_Interface(object):
def setupUi(self, Mouse_Positioning_Interface):
Mouse_Positioning_Interface.setObjectName("Mouse_Positioning_Interface")
Mouse_Positioning_Interface.setEnabled(True)
Mouse_Positioning_Interface.resize(1708, 916)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Mouse_Positioning_Interface.sizePolicy().hasHeightForWidth())
Mouse_Positioning_Interface.setSizePolicy(sizePolicy)
Mouse_Positioning_Interface.setMinimumSize(QtCore.QSize(1708, 916))
Mouse_Positioning_Interface.setMaximumSize(QtCore.QSize(16777215, 16777215))
Mouse_Positioning_Interface.setAutoFillBackground(False)
Mouse_Positioning_Interface.setStyleSheet("")
self.centralwidget = QtWidgets.QWidget(Mouse_Positioning_Interface)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_50 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_50.setObjectName("gridLayout_50")
self.splitter_4 = QtWidgets.QSplitter(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.splitter_4.sizePolicy().hasHeightForWidth())
self.splitter_4.setSizePolicy(sizePolicy)
self.splitter_4.setOrientation(QtCore.Qt.Vertical)
self.splitter_4.setObjectName("splitter_4")
self.Logo = QtWidgets.QLabel(self.splitter_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.MinimumExpanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Logo.sizePolicy().hasHeightForWidth())
self.Logo.setSizePolicy(sizePolicy)
self.Logo.setMaximumSize(QtCore.QSize(16777215, 300))
self.Logo.setText("")
self.Logo.setPixmap(QtGui.QPixmap(":/Imgs/Icons/Pic.jpg"))
self.Logo.setScaledContents(True)
self.Logo.setObjectName("Logo")
self.groupBox = QtWidgets.QGroupBox(self.splitter_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.MinimumExpanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setMinimumSize(QtCore.QSize(200, 300))
self.groupBox.setObjectName("groupBox")
self.gridLayout_14 = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout_14.setObjectName("gridLayout_14")
self.LogBox = QtWidgets.QVBoxLayout()
self.LogBox.setObjectName("LogBox")
self.gridLayout_14.addLayout(self.LogBox, 0, 0, 1, 1)
self.gridLayout_50.addWidget(self.splitter_4, 0, 1, 2, 1)
self.GroupCoordinates = QtWidgets.QGroupBox(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.GroupCoordinates.sizePolicy().hasHeightForWidth())
self.GroupCoordinates.setSizePolicy(sizePolicy)
self.GroupCoordinates.setMinimumSize(QtCore.QSize(0, 100))
self.GroupCoordinates.setMaximumSize(QtCore.QSize(16777215, 200))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.GroupCoordinates.setFont(font)
self.GroupCoordinates.setObjectName("GroupCoordinates")
self.horizontalLayout = QtWidgets.QHBoxLayout(self.GroupCoordinates)
self.horizontalLayout.setObjectName("horizontalLayout")
self.SS_IsoCenter = QtWidgets.QFrame(self.GroupCoordinates)
self.SS_IsoCenter.setMinimumSize(QtCore.QSize(0, 20))
self.SS_IsoCenter.setAutoFillBackground(False)
self.SS_IsoCenter.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.SS_IsoCenter.setFrameShadow(QtWidgets.QFrame.Sunken)
self.SS_IsoCenter.setObjectName("SS_IsoCenter")
self.gridLayout_43 = QtWidgets.QGridLayout(self.SS_IsoCenter)
self.gridLayout_43.setObjectName("gridLayout_43")
self.SS_IC_Label = QtWidgets.QLabel(self.SS_IsoCenter)
self.SS_IC_Label.setAlignment(QtCore.Qt.AlignCenter)
self.SS_IC_Label.setObjectName("SS_IC_Label")
self.gridLayout_43.addWidget(self.SS_IC_Label, 0, 0, 1, 1)
self.horizontalLayout.addWidget(self.SS_IsoCenter)
self.label_7 = QtWidgets.QLabel(self.GroupCoordinates)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_7.sizePolicy().hasHeightForWidth())
self.label_7.setSizePolicy(sizePolicy)
self.label_7.setText("")
self.label_7.setPixmap(QtGui.QPixmap(":/Arrows/Icons/move_right.png"))
self.label_7.setScaledContents(True)
self.label_7.setObjectName("label_7")
self.horizontalLayout.addWidget(self.label_7)
self.SS_PlanImage = QtWidgets.QFrame(self.GroupCoordinates)
self.SS_PlanImage.setMinimumSize(QtCore.QSize(0, 20))
self.SS_PlanImage.setAutoFillBackground(False)
self.SS_PlanImage.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.SS_PlanImage.setFrameShadow(QtWidgets.QFrame.Sunken)
self.SS_PlanImage.setObjectName("SS_PlanImage")
self.gridLayout_44 = QtWidgets.QGridLayout(self.SS_PlanImage)
self.gridLayout_44.setObjectName("gridLayout_44")
self.SS_Plan_Box_2 = QtWidgets.QLabel(self.SS_PlanImage)
self.SS_Plan_Box_2.setAlignment(QtCore.Qt.AlignCenter)
self.SS_Plan_Box_2.setObjectName("SS_Plan_Box_2")
self.gridLayout_44.addWidget(self.SS_Plan_Box_2, 0, 0, 1, 1)
self.horizontalLayout.addWidget(self.SS_PlanImage)
self.label_8 = QtWidgets.QLabel(self.GroupCoordinates)
self.label_8.setText("")
self.label_8.setPixmap(QtGui.QPixmap(":/Arrows/Icons/move_right.png"))
self.label_8.setScaledContents(True)
self.label_8.setObjectName("label_8")
self.horizontalLayout.addWidget(self.label_8)
self.SS_TreatImage = QtWidgets.QFrame(self.GroupCoordinates)
self.SS_TreatImage.setMinimumSize(QtCore.QSize(0, 20))
self.SS_TreatImage.setAutoFillBackground(False)
self.SS_TreatImage.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.SS_TreatImage.setFrameShadow(QtWidgets.QFrame.Sunken)
self.SS_TreatImage.setObjectName("SS_TreatImage")
self.gridLayout_47 = QtWidgets.QGridLayout(self.SS_TreatImage)
self.gridLayout_47.setObjectName("gridLayout_47")
self.LabelCOM_4 = QtWidgets.QLabel(self.SS_TreatImage)
self.LabelCOM_4.setAlignment(QtCore.Qt.AlignCenter)
self.LabelCOM_4.setObjectName("LabelCOM_4")
self.gridLayout_47.addWidget(self.LabelCOM_4, 0, 0, 1, 1)
self.horizontalLayout.addWidget(self.SS_TreatImage)
self.label_11 = QtWidgets.QLabel(self.GroupCoordinates)
self.label_11.setText("")
self.label_11.setPixmap(QtGui.QPixmap(":/Arrows/Icons/move_right.png"))
self.label_11.setScaledContents(True)
self.label_11.setObjectName("label_11")
self.horizontalLayout.addWidget(self.label_11)
self.SS_RegApproved = QtWidgets.QFrame(self.GroupCoordinates)
self.SS_RegApproved.setMinimumSize(QtCore.QSize(0, 20))
self.SS_RegApproved.setAutoFillBackground(False)
self.SS_RegApproved.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.SS_RegApproved.setFrameShadow(QtWidgets.QFrame.Sunken)
self.SS_RegApproved.setObjectName("SS_RegApproved")
self.gridLayout_49 = QtWidgets.QGridLayout(self.SS_RegApproved)
self.gridLayout_49.setObjectName("gridLayout_49")
self.LabelCOM_5 = QtWidgets.QLabel(self.SS_RegApproved)
self.LabelCOM_5.setAlignment(QtCore.Qt.AlignCenter)
self.LabelCOM_5.setObjectName("LabelCOM_5")
self.gridLayout_49.addWidget(self.LabelCOM_5, 0, 0, 1, 1)
self.horizontalLayout.addWidget(self.SS_RegApproved)
self.label_12 = QtWidgets.QLabel(self.GroupCoordinates)
self.label_12.setText("")
self.label_12.setPixmap(QtGui.QPixmap(":/Arrows/Icons/move_right.png"))
self.label_12.setScaledContents(True)
self.label_12.setObjectName("label_12")
self.horizontalLayout.addWidget(self.label_12)
self.SS_StageSet = QtWidgets.QFrame(self.GroupCoordinates)
self.SS_StageSet.setMinimumSize(QtCore.QSize(0, 20))
self.SS_StageSet.setAutoFillBackground(False)
self.SS_StageSet.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.SS_StageSet.setFrameShadow(QtWidgets.QFrame.Sunken)
self.SS_StageSet.setObjectName("SS_StageSet")
self.gridLayout_52 = QtWidgets.QGridLayout(self.SS_StageSet)
self.gridLayout_52.setObjectName("gridLayout_52")
self.LabelCOM_6 = QtWidgets.QLabel(self.SS_StageSet)
self.LabelCOM_6.setAlignment(QtCore.Qt.AlignCenter)
self.LabelCOM_6.setObjectName("LabelCOM_6")
self.gridLayout_52.addWidget(self.LabelCOM_6, 0, 0, 1, 1)
self.horizontalLayout.addWidget(self.SS_StageSet)
self.label_16 = QtWidgets.QLabel(self.GroupCoordinates)
self.label_16.setText("")
self.label_16.setPixmap(QtGui.QPixmap(":/Arrows/Icons/move_right.png"))
self.label_16.setScaledContents(True)
self.label_16.setObjectName("label_16")
self.horizontalLayout.addWidget(self.label_16)
self.Button_create_report = QtWidgets.QPushButton(self.GroupCoordinates)
self.Button_create_report.setMaximumSize(QtCore.QSize(16777215, 500))
self.Button_create_report.setObjectName("Button_create_report")
self.horizontalLayout.addWidget(self.Button_create_report)
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.gridLayout_50.addWidget(self.GroupCoordinates, 1, 0, 1, 1)
self.Registration = QtWidgets.QTabWidget(self.centralwidget)
self.Registration.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Registration.sizePolicy().hasHeightForWidth())
self.Registration.setSizePolicy(sizePolicy)
self.Registration.setObjectName("Registration")
self.TabRadiography = QtWidgets.QWidget()
self.TabRadiography.setObjectName("TabRadiography")
self.gridLayout_15 = QtWidgets.QGridLayout(self.TabRadiography)
self.gridLayout_15.setObjectName("gridLayout_15")
self.Group_IsoCenter = QtWidgets.QGroupBox(self.TabRadiography)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Group_IsoCenter.sizePolicy().hasHeightForWidth())
self.Group_IsoCenter.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.Group_IsoCenter.setFont(font)
self.Group_IsoCenter.setObjectName("Group_IsoCenter")
self.gridLayout_5 = QtWidgets.QGridLayout(self.Group_IsoCenter)
self.gridLayout_5.setObjectName("gridLayout_5")
self.label_5 = QtWidgets.QLabel(self.Group_IsoCenter)
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label_5.setFont(font)
self.label_5.setObjectName("label_5")
self.gridLayout_5.addWidget(self.label_5, 2, 0, 1, 1)
self.Button_Radiograph_toggleIso = QtWidgets.QPushButton(self.Group_IsoCenter)
font = QtGui.QFont()
font.setPointSize(10)
self.Button_Radiograph_toggleIso.setFont(font)
self.Button_Radiograph_toggleIso.setObjectName("Button_Radiograph_toggleIso")
self.gridLayout_5.addWidget(self.Button_Radiograph_toggleIso, 0, 2, 1, 2)
self.Text_RG_Filename_IsoCenter = QtWidgets.QTextEdit(self.Group_IsoCenter)
self.Text_RG_Filename_IsoCenter.setMaximumSize(QtCore.QSize(16777215, 60))
font = QtGui.QFont()
font.setPointSize(8)
font.setBold(False)
font.setWeight(50)
self.Text_RG_Filename_IsoCenter.setFont(font)
self.Text_RG_Filename_IsoCenter.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
self.Text_RG_Filename_IsoCenter.setObjectName("Text_RG_Filename_IsoCenter")
self.gridLayout_5.addWidget(self.Text_RG_Filename_IsoCenter, 1, 0, 1, 4)
self.label_6 = QtWidgets.QLabel(self.Group_IsoCenter)
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label_6.setFont(font)
self.label_6.setObjectName("label_6")
self.gridLayout_5.addWidget(self.label_6, 2, 2, 1, 1)
self.Button_RG_defineIsoCenter = QtWidgets.QPushButton(self.Group_IsoCenter)
font = QtGui.QFont()
font.setPointSize(10)
self.Button_RG_defineIsoCenter.setFont(font)
self.Button_RG_defineIsoCenter.setObjectName("Button_RG_defineIsoCenter")
self.gridLayout_5.addWidget(self.Button_RG_defineIsoCenter, 0, 0, 1, 2)
self.SpotTxt_x = QtWidgets.QLineEdit(self.Group_IsoCenter)
self.SpotTxt_x.setEnabled(False)
font = QtGui.QFont()
font.setPointSize(10)
self.SpotTxt_x.setFont(font)
self.SpotTxt_x.setReadOnly(True)
self.SpotTxt_x.setObjectName("SpotTxt_x")
self.gridLayout_5.addWidget(self.SpotTxt_x, 2, 1, 1, 1)
self.SpotTxt_y = QtWidgets.QLineEdit(self.Group_IsoCenter)
self.SpotTxt_y.setEnabled(False)
font = QtGui.QFont()
font.setPointSize(10)
self.SpotTxt_y.setFont(font)
self.SpotTxt_y.setReadOnly(True)
self.SpotTxt_y.setObjectName("SpotTxt_y")
self.gridLayout_5.addWidget(self.SpotTxt_y, 2, 3, 1, 1)
self.gridLayout_15.addWidget(self.Group_IsoCenter, 1, 0, 1, 1)
self.Display_Radiography = matplotlibWidget(self.TabRadiography)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Display_Radiography.sizePolicy().hasHeightForWidth())
self.Display_Radiography.setSizePolicy(sizePolicy)
self.Display_Radiography.setMinimumSize(QtCore.QSize(200, 200))
self.Display_Radiography.setObjectName("Display_Radiography")
self.gridLayout_15.addWidget(self.Display_Radiography, 0, 1, 1, 1)
self.Display_Isocenter = matplotlibWidget(self.TabRadiography)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Display_Isocenter.sizePolicy().hasHeightForWidth())
self.Display_Isocenter.setSizePolicy(sizePolicy)
self.Display_Isocenter.setMinimumSize(QtCore.QSize(200, 200))
self.Display_Isocenter.setObjectName("Display_Isocenter")
self.gridLayout_15.addWidget(self.Display_Isocenter, 0, 0, 1, 1)
self.groupBox_3 = QtWidgets.QGroupBox(self.TabRadiography)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().hasHeightForWidth())
self.groupBox_3.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.groupBox_3.setFont(font)
self.groupBox_3.setObjectName("groupBox_3")
self.gridLayout_3 = QtWidgets.QGridLayout(self.groupBox_3)
self.gridLayout_3.setObjectName("gridLayout_3")
self.Button_RadiographyLM = QtWidgets.QPushButton(self.groupBox_3)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Button_RadiographyLM.sizePolicy().hasHeightForWidth())
self.Button_RadiographyLM.setSizePolicy(sizePolicy)
self.Button_RadiographyLM.setMinimumSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(9)
self.Button_RadiographyLM.setFont(font)
self.Button_RadiographyLM.setAutoFillBackground(False)
self.Button_RadiographyLM.setDefault(True)
self.Button_RadiographyLM.setObjectName("Button_RadiographyLM")
self.gridLayout_3.addWidget(self.Button_RadiographyLM, 0, 0, 1, 2)
self.Button_toggleLandmarksRG = QtWidgets.QPushButton(self.groupBox_3)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Button_toggleLandmarksRG.sizePolicy().hasHeightForWidth())
self.Button_toggleLandmarksRG.setSizePolicy(sizePolicy)
self.Button_toggleLandmarksRG.setMinimumSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setPointSize(9)
self.Button_toggleLandmarksRG.setFont(font)
self.Button_toggleLandmarksRG.setAutoFillBackground(False)
self.Button_toggleLandmarksRG.setDefault(True)
self.Button_toggleLandmarksRG.setObjectName("Button_toggleLandmarksRG")
self.gridLayout_3.addWidget(self.Button_toggleLandmarksRG, 0, 3, 1, 1)
self.Text_RG_Filename_Landmark = QtWidgets.QTextEdit(self.groupBox_3)
self.Text_RG_Filename_Landmark.setMaximumSize(QtCore.QSize(16777215, 60))
font = QtGui.QFont()
font.setPointSize(8)
font.setBold(False)
font.setWeight(50)
self.Text_RG_Filename_Landmark.setFont(font)
self.Text_RG_Filename_Landmark.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
self.Text_RG_Filename_Landmark.setObjectName("Text_RG_Filename_Landmark")
self.gridLayout_3.addWidget(self.Text_RG_Filename_Landmark, 1, 0, 1, 4)
self.label_24 = QtWidgets.QLabel(self.groupBox_3)
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label_24.setFont(font)
self.label_24.setObjectName("label_24")
self.gridLayout_3.addWidget(self.label_24, 2, 0, 1, 1)
self.TxtRGPinX = QtWidgets.QLineEdit(self.groupBox_3)
self.TxtRGPinX.setEnabled(False)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.TxtRGPinX.sizePolicy().hasHeightForWidth())
self.TxtRGPinX.setSizePolicy(sizePolicy)
self.TxtRGPinX.setMinimumSize(QtCore.QSize(50, 0))
font = QtGui.QFont()
font.setPointSize(10)
self.TxtRGPinX.setFont(font)
self.TxtRGPinX.setText("")
self.TxtRGPinX.setObjectName("TxtRGPinX")
self.gridLayout_3.addWidget(self.TxtRGPinX, 2, 1, 1, 1)
self.label_23 = QtWidgets.QLabel(self.groupBox_3)
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label_23.setFont(font)
self.label_23.setObjectName("label_23")
self.gridLayout_3.addWidget(self.label_23, 2, 2, 1, 1)
self.TxtRGPinY = QtWidgets.QLineEdit(self.groupBox_3)
self.TxtRGPinY.setEnabled(False)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.TxtRGPinY.sizePolicy().hasHeightForWidth())
self.TxtRGPinY.setSizePolicy(sizePolicy)
self.TxtRGPinY.setMinimumSize(QtCore.QSize(50, 0))
font = QtGui.QFont()
font.setPointSize(10)
self.TxtRGPinY.setFont(font)
self.TxtRGPinY.setText("")
self.TxtRGPinY.setObjectName("TxtRGPinY")
self.gridLayout_3.addWidget(self.TxtRGPinY, 2, 3, 1, 1)
self.gridLayout_15.addWidget(self.groupBox_3, 1, 1, 1, 1)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.gridLayout_15.addItem(spacerItem1, 0, 2, 1, 1)
self.Registration.addTab(self.TabRadiography, "")
self.tab = QtWidgets.QWidget()
self.tab.setObjectName("tab")
self.gridLayout_11 = QtWidgets.QGridLayout(self.tab)
self.gridLayout_11.setObjectName("gridLayout_11")
self.groupBox_20 = QtWidgets.QGroupBox(self.tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_20.sizePolicy().hasHeightForWidth())
self.groupBox_20.setSizePolicy(sizePolicy)
self.groupBox_20.setObjectName("groupBox_20")
self.gridLayout_10 = QtWidgets.QGridLayout(self.groupBox_20)
self.gridLayout_10.setObjectName("gridLayout_10")
self.Button_RunReg = QtWidgets.QPushButton(self.groupBox_20)
self.Button_RunReg.setObjectName("Button_RunReg")
self.gridLayout_10.addWidget(self.Button_RunReg, 2, 0, 1, 1)
self.Slider_RegOverlay = QtWidgets.QSlider(self.groupBox_20)
self.Slider_RegOverlay.setMaximum(100)
self.Slider_RegOverlay.setSingleStep(0)
self.Slider_RegOverlay.setProperty("value", 50)
self.Slider_RegOverlay.setOrientation(QtCore.Qt.Horizontal)
self.Slider_RegOverlay.setObjectName("Slider_RegOverlay")
self.gridLayout_10.addWidget(self.Slider_RegOverlay, 1, 0, 1, 2)
self.Button_AccReg = QtWidgets.QPushButton(self.groupBox_20)
self.Button_AccReg.setObjectName("Button_AccReg")
self.gridLayout_10.addWidget(self.Button_AccReg, 2, 1, 1, 1)
self.Display_Fusion = matplotlibWidget(self.groupBox_20)
self.Display_Fusion.setEnabled(True)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Display_Fusion.sizePolicy().hasHeightForWidth())
self.Display_Fusion.setSizePolicy(sizePolicy)
self.Display_Fusion.setMinimumSize(QtCore.QSize(300, 300))
self.Display_Fusion.setMaximumSize(QtCore.QSize(1000000, 1000000))
self.Display_Fusion.setObjectName("Display_Fusion")
self.gridLayout_10.addWidget(self.Display_Fusion, 0, 0, 1, 2)
self.gridLayout_11.addWidget(self.groupBox_20, 0, 2, 1, 1)
self.frame_4 = QtWidgets.QFrame(self.tab)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.frame_4.sizePolicy().hasHeightForWidth())
self.frame_4.setSizePolicy(sizePolicy)
self.frame_4.setMinimumSize(QtCore.QSize(0, 200))
self.frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame_4.setObjectName("frame_4")
self.gridLayout_4 = QtWidgets.QGridLayout(self.frame_4)
self.gridLayout_4.setObjectName("gridLayout_4")
self.groupBox_21 = QtWidgets.QGroupBox(self.frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_21.sizePolicy().hasHeightForWidth())
self.groupBox_21.setSizePolicy(sizePolicy)
self.groupBox_21.setMinimumSize(QtCore.QSize(250, 170))
self.groupBox_21.setObjectName("groupBox_21")
self.gridLayout = QtWidgets.QGridLayout(self.groupBox_21)
self.gridLayout.setObjectName("gridLayout")
self.Button_default_moving = QtWidgets.QPushButton(self.groupBox_21)
self.Button_default_moving.setObjectName("Button_default_moving")
self.gridLayout.addWidget(self.Button_default_moving, 1, 0, 2, 2)
self.CoordsTable = QtWidgets.QTableWidget(self.groupBox_21)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.CoordsTable.sizePolicy().hasHeightForWidth())
self.CoordsTable.setSizePolicy(sizePolicy)
self.CoordsTable.setMinimumSize(QtCore.QSize(0, 20))
self.CoordsTable.setMaximumSize(QtCore.QSize(500, 150))
font = QtGui.QFont()
font.setPointSize(7)
self.CoordsTable.setFont(font)
self.CoordsTable.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
self.CoordsTable.setDragDropOverwriteMode(False)
self.CoordsTable.setObjectName("CoordsTable")
self.CoordsTable.setColumnCount(2)
self.CoordsTable.setRowCount(5)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setVerticalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setVerticalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setVerticalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setVerticalHeaderItem(3, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setVerticalHeaderItem(4, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setItem(0, 0, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setItem(0, 1, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setItem(1, 0, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setItem(1, 1, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setItem(2, 0, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setItem(2, 1, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setItem(3, 0, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setItem(3, 1, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setItem(4, 0, item)
item = QtWidgets.QTableWidgetItem()
self.CoordsTable.setItem(4, 1, item)
self.CoordsTable.horizontalHeader().setDefaultSectionSize(60)
self.CoordsTable.verticalHeader().setDefaultSectionSize(22)
self.gridLayout.addWidget(self.CoordsTable, 0, 0, 1, 2)
self.Button_default_fixed = QtWidgets.QPushButton(self.groupBox_21)
self.Button_default_fixed.setObjectName("Button_default_fixed")
self.gridLayout.addWidget(self.Button_default_fixed, 3, 0, 1, 2)
self.gridLayout_4.addWidget(self.groupBox_21, 0, 0, 3, 1)
self.groupBox_2 = QtWidgets.QGroupBox(self.frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().hasHeightForWidth())
self.groupBox_2.setSizePolicy(sizePolicy)
self.groupBox_2.setMinimumSize(QtCore.QSize(0, 100))
self.groupBox_2.setObjectName("groupBox_2")
self.gridLayout_6 = QtWidgets.QGridLayout(self.groupBox_2)
self.gridLayout_6.setObjectName("gridLayout_6")
self.Slider_MarkerSize_Moving = QtWidgets.QSlider(self.groupBox_2)
self.Slider_MarkerSize_Moving.setOrientation(QtCore.Qt.Horizontal)
self.Slider_MarkerSize_Moving.setObjectName("Slider_MarkerSize_Moving")
self.gridLayout_6.addWidget(self.Slider_MarkerSize_Moving, 0, 1, 1, 1)
self.Slider_MarkerSize_Fixed = QtWidgets.QSlider(self.groupBox_2)
self.Slider_MarkerSize_Fixed.setOrientation(QtCore.Qt.Horizontal)
self.Slider_MarkerSize_Fixed.setObjectName("Slider_MarkerSize_Fixed")
self.gridLayout_6.addWidget(self.Slider_MarkerSize_Fixed, 1, 1, 1, 1)
self.label = QtWidgets.QLabel(self.groupBox_2)
self.label.setObjectName("label")
self.gridLayout_6.addWidget(self.label, 0, 0, 1, 1)
self.label_3 = QtWidgets.QLabel(self.groupBox_2)
self.label_3.setObjectName("label_3")
self.gridLayout_6.addWidget(self.label_3, 1, 0, 1, 1)
self.gridLayout_4.addWidget(self.groupBox_2, 0, 2, 1, 1)
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.groupBox_10 = QtWidgets.QGroupBox(self.frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_10.sizePolicy().hasHeightForWidth())
self.groupBox_10.setSizePolicy(sizePolicy)
self.groupBox_10.setMinimumSize(QtCore.QSize(100, 0))
self.groupBox_10.setMaximumSize(QtCore.QSize(400, 16777215))
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.groupBox_10.setFont(font)
self.groupBox_10.setAutoFillBackground(False)
self.groupBox_10.setObjectName("groupBox_10")
self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox_10)
self.gridLayout_2.setObjectName("gridLayout_2")
self.TableTxt_y = QtWidgets.QLineEdit(self.groupBox_10)
self.TableTxt_y.setEnabled(False)
self.TableTxt_y.setMinimumSize(QtCore.QSize(40, 0))
font = QtGui.QFont()
font.setPointSize(10)
self.TableTxt_y.setFont(font)
self.TableTxt_y.setObjectName("TableTxt_y")
self.gridLayout_2.addWidget(self.TableTxt_y, 1, 1, 1, 1)
self.label_13 = QtWidgets.QLabel(self.groupBox_10)
font = QtGui.QFont()
font.setPointSize(10)
self.label_13.setFont(font)
self.label_13.setObjectName("label_13")
self.gridLayout_2.addWidget(self.label_13, 0, 0, 1, 1)
self.label_57 = QtWidgets.QLabel(self.groupBox_10)
font = QtGui.QFont()
font.setPointSize(10)
self.label_57.setFont(font)
self.label_57.setObjectName("label_57")
self.gridLayout_2.addWidget(self.label_57, 0, 2, 1, 1)
self.label_14 = QtWidgets.QLabel(self.groupBox_10)
font = QtGui.QFont()
font.setPointSize(10)
self.label_14.setFont(font)
self.label_14.setObjectName("label_14")
self.gridLayout_2.addWidget(self.label_14, 1, 0, 1, 1)
self.TableTxt_x = QtWidgets.QLineEdit(self.groupBox_10)
self.TableTxt_x.setEnabled(False)
self.TableTxt_x.setMinimumSize(QtCore.QSize(40, 0))
font = QtGui.QFont()
font.setPointSize(10)
self.TableTxt_x.setFont(font)
self.TableTxt_x.setObjectName("TableTxt_x")
self.gridLayout_2.addWidget(self.TableTxt_x, 0, 1, 1, 1)
self.label_58 = QtWidgets.QLabel(self.groupBox_10)
font = QtGui.QFont()
font.setPointSize(10)
self.label_58.setFont(font)
self.label_58.setObjectName("label_58")
self.gridLayout_2.addWidget(self.label_58, 1, 2, 1, 1)
self.verticalLayout_2.addWidget(self.groupBox_10)
self.Group_Result = QtWidgets.QGroupBox(self.frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.Group_Result.sizePolicy().hasHeightForWidth())
self.Group_Result.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.Group_Result.setFont(font)
self.Group_Result.setObjectName("Group_Result")
self.gridLayout_8 = QtWidgets.QGridLayout(self.Group_Result)
self.gridLayout_8.setObjectName("gridLayout_8")
self.TableTxt_yCorr = QtWidgets.QLineEdit(self.Group_Result)
self.TableTxt_yCorr.setEnabled(False)
self.TableTxt_yCorr.setMinimumSize(QtCore.QSize(40, 0))
font = QtGui.QFont()
font.setPointSize(10)
self.TableTxt_yCorr.setFont(font)
self.TableTxt_yCorr.setObjectName("TableTxt_yCorr")
self.gridLayout_8.addWidget(self.TableTxt_yCorr, 1, 1, 1, 1)
self.label_9 = QtWidgets.QLabel(self.Group_Result)
font = QtGui.QFont()
font.setPointSize(10)
self.label_9.setFont(font)
self.label_9.setObjectName("label_9")
self.gridLayout_8.addWidget(self.label_9, 0, 0, 1, 1)
self.TableTxt_xCorr = QtWidgets.QLineEdit(self.Group_Result)
self.TableTxt_xCorr.setEnabled(False)
self.TableTxt_xCorr.setMinimumSize(QtCore.QSize(40, 0))
font = QtGui.QFont()
font.setPointSize(10)
self.TableTxt_xCorr.setFont(font)
self.TableTxt_xCorr.setObjectName("TableTxt_xCorr")
self.gridLayout_8.addWidget(self.TableTxt_xCorr, 0, 1, 1, 1)
self.label_59 = QtWidgets.QLabel(self.Group_Result)
font = QtGui.QFont()
font.setPointSize(10)
self.label_59.setFont(font)
self.label_59.setObjectName("label_59")
self.gridLayout_8.addWidget(self.label_59, 0, 2, 1, 1)
self.label_60 = QtWidgets.QLabel(self.Group_Result)
font = | |
<filename>dianhua/worker/crawler/china_mobile/shandong/base_sd_crawler.py<gh_stars>1-10
# -*- coding: utf-8 -*-
import base64
import datetime,time
import traceback
import re
import json
import lxml.html
import sys
reload(sys)
sys.setdefaultencoding("utf8")
try:
from worker.crawler.china_mobile.SD.base_request_param import *
except:
from base_request_param import *
# URL for Login
MAIN_LOGON_URL = "https://sd.ac.10086.cn/portal/mainLogon.do"
PORTAL_SERVLET_URL = "https://sd.ac.10086.cn/portal/servlet/CookieServlet"
LOGIN_IMAGE_URL = "https://sd.ac.10086.cn/portal/login/briefValidateCode.jsp"
LOGIN_URL = "https://sd.ac.10086.cn/portal/servlet/LoginServlet"
SSO_LOGIN_URL = "http://www.sd.10086.cn/eMobile/loginSSO.action"
# URL for Second Validate
SECOND_VALIDATE_IMAGE_URL = "http://www.sd.10086.cn/eMobile/RandomCodeImage"
SECOND_VALIDATE_SMS_URL = "http://www.sd.10086.cn/eMobile/sendSms.action"
CHECK_SECOND_VALIDATE_URL = "http://www.sd.10086.cn/eMobile/checkSmsPass_commit.action"
# URL for Personal Info
PERSONAL_INFO_URL = "http://www.sd.10086.cn/eMobile/qryCustInfo_result.action"
# URL for Detail Info
DETAIL_BILL_URL = "http://www.sd.10086.cn/eMobile/queryBillDetail_detailBillAjax.action"
# Login Functions
def get_login_cookie(self):
"""
Set cookies for login process
:param request_session: Requests session
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
"""
try:
code, key, resp = self.post(MAIN_LOGON_URL, data=get_main_logon_do_form())
if code != 0:
return code, key
headers = {
"Accept": "*/*",
"Referer": "https://sd.ac.10086.cn/portal/mainLogon.do"
}
code, key, resp = self.get(PORTAL_SERVLET_URL, params=get_login_cookie_param(5), headers=headers)
if code != 0:
return code, key
code, key, resp = self.get(PORTAL_SERVLET_URL, params=get_login_cookie_param(1))
if code != 0:
return code, key
return 0, 'success'
except:
error = traceback.format_exc()
self.log('crawler', 'unknown_error:{}'.format(error), resp)
return 9, 'unknown_error'
def get_login_validate_image(self):
"""
Get validate image for login
:param request_session: Requests session
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
image_str: str, Raw byte of Captcha in base64 format, return "" if fail
"""
headers = {
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Referer": "https://sd.ac.10086.cn/portal/mainLogon.do"
}
code, key, resp = self.get(LOGIN_IMAGE_URL, params=get_login_image_param(), headers=headers)
if code != 0:
return code, key, ''
return code, key, base64.b64encode(resp.content)
def get_login_result(self, tel_num, user_password, image_validate_code):
"""
Process login
:param request_session: Requests session
:param tel_num: Tel number
:param user_password: <PASSWORD>
:param image_validate_code: validate code from image
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
"""
code, key, resp = self.post(LOGIN_URL, data=get_login_result_form(tel_num, user_password, image_validate_code))
if code != 0:
return code, key
if resp.text != "0":
if '登录过程中输入参数不合法' in resp.text:
self.log('website', 'website_busy_error', resp)
return 9, "website_busy_error"
elif '密码认证不正确,请重新进行验证' in resp.text:
self.log('user', 'pin_pwd_error', resp)
return 1, 'pin_pwd_error'
self.log('crawler', 'request_error', resp)
return 9, 'request_error'
return 0, 'success'
def get_prior_cookie(self):
"""
Set cookies after login process
:param request_session: Requests session
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
"""
return self.get('http://www.sd.10086.cn/eMobile/jsp/common/prior.jsp')
def get_attribute_id(self):
"""
Get attribute id for SSO Login
:param request_session: Requests session
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
result: str, response from PORTAL_SERVLET_URL
"""
return self.get(PORTAL_SERVLET_URL, params=get_login_cookie_param(2))
def extract_attribute_id_from_code(code_string):
"""
Extract attribute ID from get_attribute_id
:param code_string: Code in string format
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
value_body: str, attribute ID
"""
try:
if code_string is None:
return 9, 'request_error', "request_error", ""
if "onNoLoging" in code_string:
return 9, 'request_error', "request_error", ""
fetch_value_re = re.compile(u'var a.*?=.*?\'(.*?)\';')
value_body = fetch_value_re.search(code_string).group(1)
return 0, 'success', 'Get login result', value_body
except :
error = traceback.format_exc()
return 9, 'unknown_error', 'unknown_error:{} '.format(error), ""
def get_sso_login_cookie(self, attribute_id):
"""
SSO login and set cookie with Attribute ID
:param request_session: Request Session
:param attribute_id: Attribute ID from get_attribute_id
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
result: str, Result from SSO LOGIN
"""
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Referer": "http://www.sd.10086.cn/eMobile/jsp/common/prior.jsp"
}
return self.get(SSO_LOGIN_URL, params=get_sso_login_param(attribute_id), headers=headers)
def extract_person_info_table_border_from_html(xhtml_string):
"""
Check if the response request is an html with error message, and try to extract the keyword
:param xhtml_string: String that might be an html
:return: The error message. '0' if not a html or no error message
"""
if u'您要办理的业务需要通过短信随机码认证之后才能访问' in xhtml_string:
return u'您要办理的业务需要通过短信随机码认证之后才能访问'
root = lxml.html.document_fromstring(xhtml_string)
try:
error_message = root.xpath('//div[@class="personInfo_tableBorder"]/text()')[0].replace("\r", "")
error_message = error_message.replace("\n", "").replace("\t", "")
if error_message == "":
return "0"
return error_message
except:
return "0"
def extract_sso_login_result_from_html(xhtml_string):
"""
Extract the SSO login result from get_sso_login_cookie
:param xhtml_string: html string from get_sso_login_cookie
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
"""
try:
error_message = extract_person_info_table_border_from_html(xhtml_string)
if error_message != '0':
if '登录过程中输入参数不合法' in error_message:
return "website_busy_error", 9, '官网异常{}'.format(xhtml_string)
return 'request_error', 9, "sso login{}".format(error_message)
return 'success', 0, "Get sso login"
except Exception as e:
return 'unknown_error', 9, "extract_sso_login_result failed %s" % e
# Second Validate Functions
def send_second_validate_sms(self):
"""
Send SMS for second validate
:param request_session: Request Session
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
"""
return self.post(SECOND_VALIDATE_SMS_URL, params=send_second_validate_sms_param())
def extract_send_second_validate_sms_result_from_dict(self,resp ):
"""
Extract SMS sending result from get_second_validate_sms
:param dict_string: Dict in string format. EX: u'{"returnArr":[["error","您的短信随机码已经发送,请注意查收!"]]}'
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Request result
"""
try:
second_validate_result_dict = json.loads(resp.text)
except:
error = traceback.format_exc()
self.log('crawler','json_error:{}'.format(error), resp)
return 9, 'json_error'
if 'returnArr' not in second_validate_result_dict:
self.log('crawler', 'expected_key_error', resp)
return 9, 'expected_key_error'
if second_validate_result_dict['returnArr'][0][1] == u"您的短信随机码已经发送,请注意查收!":
return 0, 'success'
elif second_validate_result_dict['returnArr'][0][1] == u"对不起,获取验证码失败,请重新获得!":
self.log('crawler', 'send_sms_error', resp)
return 9, 'send_sms_error'
else:
self.log('crawler', 'request_error', resp)
return 9, 'request_error'
def get_second_validate_image(self):
"""
Get validate image for second validate
:param request_session: Requests session
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
image_str: str, Raw byte of Captcha in base64 format, return "" if fail
"""
headers = {
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Referer": "http://www.sd.10086.cn/eMobile/checkPassword.action?menuid=billdetails"
}
code, key, resp = self.get(SECOND_VALIDATE_IMAGE_URL, params=get_second_validate_image_param(), headers=headers)
if code != 0:
return code, key, ''
return code, key, base64.b64encode(resp.content)
def get_second_validate_result(self, captcha_code, sms_code):
"""
Process second validate
:param request_session: Request session
:param captcha_code: Validate code from image
:param sms_code: Validate code from SMS
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
"""
return self.post(CHECK_SECOND_VALIDATE_URL, params=get_second_validate_result_param(captcha_code, sms_code))
def extract_second_validate_result_from_html(self, resp):
"""
Extract second validate result from get_second_validate_result
:param html_string: html in string format
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
"""
try:
html_string = resp.text
if 'errorMessage' not in html_string:
return 0, 'success'
root = lxml.html.document_fromstring(html_string)
error_message = root.xpath('//ul[@class="errorMessage"]/li/span/text()')[0]
self.log('user', 'verify_error', resp)
return 2, 'verify_error'
except :
error = traceback.format_exc()
self.log('crawler', 'unknown_error:{}'.format(error), resp)
return 9, 'unknown_error'
# Personal Info Functions
def get_personal_info(self):
"""
Get personal info
:param request_session: Request session
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
result: unicode, The request result
"""
return self.post(PERSONAL_INFO_URL, params=get_personal_info_param())
def extract_personal_info_from_dict(self, resp):
"""
Extract needed personal info data from get_personal_info, and form a dict
:param dict_string: dict in string format
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
personal_info_dict: dict, The personal info in dict format
"""
try:
dict_string = resp.text
# Convert string to dict
info_result_dict = json.loads(dict_string)
except :
error = traceback.format_exc()
error_message = extract_person_info_table_border_from_html(dict_string)
if error_message != '0':
self.log('crawler', "outdated_sid:{}".format(error), resp)
return 9, "outdated_sid", {}
self.log('crawler', "json_error:{}".format(error), resp)
return 9, 'json_error', {}
# Check keyword
if 'returnArr' not in info_result_dict:
self.log('crawler', "request_error", resp)
return 9, 'request_error', {}
if not isinstance(info_result_dict['returnArr'], list):
self.log('crawler', "request_error", resp)
return 9, 'request_error', {}
try:
# Extract needed personal info
full_name = info_result_dict['returnArr'][0][1]
id_card = info_result_dict['returnArr'][1][3]
is_realname_register = info_result_dict['returnArr'][1][2]
if is_realname_register != "":
is_realname_register = True
else:
is_realname_register = False
open_date = info_result_dict['returnArr'][2][3]
address = info_result_dict['returnArr'][2][1]
return 0, 'success', {'full_name': full_name, 'id_card': id_card,
'is_realname_register': is_realname_register,
'open_date': time_transform(open_date, str_format='Ym'),
'address': address
}
except:
error = traceback.format_exc()
self.log('crawler', "unknown_error:{}".format(error), resp)
return 9, 'unknown_error', {}
# Detail Bill Functions
def get_detail_bill_result(self, start_date, end_date):
"""
Get detail bill
:param request_session: Request session
:param start_date: start day of detail bill
:param end_date: end day of detail bill (start day and end day must within the same month)
:return:
status_key: str, The key of status code
level: int, Error level
message: unicode, Error Message
result: unicode, The request result
"""
headers = {
"X-Requested-With": "XMLHttpRequest"
}
return self.post(DETAIL_BILL_URL, params=get_detail_bill_param(start_date, end_date), headers=headers)
def time_transform(time_str,bm='utf-8',str_format="%Y-%m-%d %H:%M:%S"):
if str_format == "Ym":
time_str = time_str.encode(bm)
xx = re.match(r'(.*年)?(.*月)?(.*日)?',time_str)
time_str_list = []
if xx.group(1):
yy = re.findall('\d+', xx.group(1))[0]
time_str_list.append(yy)
if xx.group(2):
mm = re.findall('\d+', xx.group(2))[0]
time_str_list.append(mm)
if xx.group(3):
dd = re.findall('\d+', xx.group(3))[0]
time_str_list.append(mm)
else:
# 没有日 取月中15号
time_str_list.append('15')
time_str = reduce(lambda x,y: x+"-"+y, time_str_list) + " 12:00:00"
str_format="%Y-%m-%d %H:%M:%S"
time_type = time.strptime(time_str.encode(bm), str_format)
return str(int(time.mktime(time_type)))
def time_format(time_str,**kwargs):
exec_type=1
time_str | |
node_data['namespace'][ns_name]
if 'set' not in ns.keys():
ns['set'] = {}
ns['set'][setname] = copy.deepcopy(val)
del node_data['set']
def _restructure_sindex_section(self, stats):
# Due to new server feature namespace add/remove with rolling restart,
# there is possibility that different nodes will have different namespaces and
# old sindex info available for node which does not have namespace for that sindex.
for node, node_data in stats.iteritems():
if 'sindex' not in node_data.keys():
continue
for key, val in node_data['sindex'].iteritems():
key_list = key.split()
ns_name = key_list[0]
sindex_name = key_list[2]
if ns_name not in node_data['namespace']:
continue
ns = node_data['namespace'][ns_name]
if 'sindex' not in ns.keys():
ns['sindex'] = {}
ns['sindex'][sindex_name] = copy.deepcopy(val)
del node_data['sindex']
def _restructure_bin_section(self, stats):
for node, node_data in stats.iteritems():
if 'bin' not in node_data.keys():
continue
for ns_name, val in node_data['bin'].iteritems():
if ns_name not in node_data['namespace']:
continue
ns = node_data['namespace'][ns_name]
ns['bin'] = copy.deepcopy(val)
del node_data['bin']
def _init_stat_ns_subsection(self, data):
for node, node_data in data.iteritems():
if 'namespace' not in node_data.keys():
continue
ns_map = node_data['namespace']
for ns, data in ns_map.iteritems():
ns_map[ns]['set'] = {}
ns_map[ns]['bin'] = {}
ns_map[ns]['sindex'] = {}
def _restructure_ns_section(self, data):
for node, node_data in data.iteritems():
if 'namespace' not in node_data.keys():
continue
ns_map = node_data['namespace']
for ns, data in ns_map.iteritems():
stat = {}
stat[ns] = {}
stat[ns]['service'] = data
ns_map[ns] = stat[ns]
def _remove_exception_from_section_output(self, data):
for section in data:
for node in data[section]:
if isinstance(data[section][node], Exception):
data[section][node] = {}
def _get_as_data_json(self):
as_map = {}
getter = GetStatisticsController(self.cluster)
stats = getter.get_all(nodes=self.nodes)
getter = GetConfigController(self.cluster)
config = getter.get_all(nodes=self.nodes)
# All these section have have nodeid in inner level
# flip keys to get nodeid in upper level.
# {'namespace': 'test': {'ip1': {}, 'ip2': {}}} -->
# {'namespace': {'ip1': {'test': {}}, 'ip2': {'test': {}}}}
stats['namespace'] = util.flip_keys(stats['namespace'])
stats['set'] = util.flip_keys(stats['set'])
stats['bin'] = util.flip_keys(stats['bin'])
stats['dc'] = util.flip_keys(stats['dc'])
stats['sindex'] = util.flip_keys(stats['sindex'])
config['namespace'] = util.flip_keys(config['namespace'])
config['dc'] = util.flip_keys(config['dc'])
self._remove_exception_from_section_output(stats)
self._remove_exception_from_section_output(config)
# flip key to get node ids in upper level and sections inside them.
# {'namespace': {'ip1': {'test': {}}, 'ip2': {'test': {}}}} -->
# {'ip1':{'namespace': {'test': {}}}, 'ip2': {'namespace': {'test': {}}}}
new_stats = util.flip_keys(stats)
new_config = util.flip_keys(config)
# Create a new service level for all ns stats.
# {'namespace': 'test': {<stats>}} -->
# {'namespace': 'test': {'service': {<stats>}}}
self._restructure_ns_section(new_stats)
# ns stats would have set and bin data too, service level will
# consolidate its service stats and put sets, sindex, bin stats
# in namespace section
self._init_stat_ns_subsection(new_stats)
self._restructure_set_section(new_stats)
self._restructure_sindex_section(new_stats)
self._restructure_bin_section(new_stats)
# No config for set, sindex, bin
self._restructure_ns_section(new_config)
# check this 'XDR': {'STATISTICS': {'192.168.112.194:3000':
# Type_error('expected str
as_map['statistics'] = new_stats
as_map['config'] = new_config
new_as_map = util.flip_keys(as_map)
return new_as_map
def _get_meta_for_sec(self, metasec, sec_name, nodeid, metamap):
if nodeid in metasec:
if not isinstance(metasec[nodeid], Exception):
metamap[nodeid][sec_name] = metasec[nodeid]
else:
metamap[nodeid][sec_name] = ''
def _get_as_metadata(self):
metamap = {}
builds = util.Future(self.cluster.info, 'build', nodes=self.nodes).start()
editions = util.Future(self.cluster.info, 'version', nodes=self.nodes).start()
xdr_builds = util.Future(self.cluster.info_XDR_build_version, nodes=self.nodes).start()
node_ids = util.Future(self.cluster.info_node, nodes=self.nodes).start()
ips = util.Future(self.cluster.info_ip_port, nodes=self.nodes).start()
udf_data = util.Future(self.cluster.info_udf_list, nodes=self.nodes).start()
builds = builds.result()
editions = editions.result()
xdr_builds = xdr_builds.result()
node_ids = node_ids.result()
ips = ips.result()
udf_data = udf_data.result()
for nodeid in builds:
metamap[nodeid] = {}
self._get_meta_for_sec(builds, 'asd_build', nodeid, metamap)
self._get_meta_for_sec(editions, 'edition', nodeid, metamap)
self._get_meta_for_sec(xdr_builds, 'xdr_build', nodeid, metamap)
self._get_meta_for_sec(node_ids, 'node_id', nodeid, metamap)
self._get_meta_for_sec(ips, 'ip', nodeid, metamap)
self._get_meta_for_sec(udf_data, 'udf', nodeid, metamap)
return metamap
def _get_as_histograms(self):
histogram_map = {}
hist_list = ['ttl', 'objsz']
hist_dumps = [util.Future(self.cluster.info_histogram, hist,
raw_output=True,
nodes=self.nodes).start()
for hist in hist_list]
for hist, hist_dump in zip(hist_list, hist_dumps):
hist_dump = hist_dump.result()
for node in hist_dump:
if node not in histogram_map:
histogram_map[node] = {}
if not hist_dump[node] or isinstance(hist_dump[node], Exception):
continue
histogram_map[node][hist] = hist_dump[node]
return histogram_map
def _get_as_latency(self):
latency_map = {}
latency_data = util.Future(self.cluster.info_latency,
nodes=self.nodes).start()
latency_data = latency_data.result()
for node in latency_data:
if node not in latency_map:
latency_map[node] = {}
if not latency_data[node] or isinstance(latency_data[node], Exception):
continue
latency_map[node] = latency_data[node]
return latency_map
def _get_as_pmap(self):
getter = GetPmapController(self.cluster)
return getter.get_pmap(nodes=self.nodes)
def _dump_in_json_file(self, as_logfile_prefix, dump):
self.logger.info("Dumping collectinfo in JSON format.")
self.aslogfile = as_logfile_prefix + 'ascinfo.json'
try:
with open(self.aslogfile, "w") as f:
f.write(json.dumps(dump, indent=4, separators=(',', ':')))
except Exception as e:
self.logger.error("Failed to write JSON file: " + str(e))
def _get_collectinfo_data_json(self, default_user, default_pwd, default_ssh_port,
default_ssh_key, credential_file, enable_ssh):
dump_map = {}
meta_map = self._get_as_metadata()
histogram_map = self._get_as_histograms()
# ToDO: Fix format for latency map
# latency_map = self._get_as_latency()
pmap_map = self._get_as_pmap()
sys_map = self.cluster.info_system_statistics(default_user=default_user, default_pwd=<PASSWORD>, default_ssh_key=default_ssh_key,
default_ssh_port=default_ssh_port, credential_file=credential_file, nodes=self.nodes,
collect_remote_data=enable_ssh)
cluster_names = util.Future(
self.cluster.info, 'cluster-name').start()
as_map = self._get_as_data_json()
for node in as_map:
dump_map[node] = {}
dump_map[node]['as_stat'] = as_map[node]
if node in sys_map:
dump_map[node]['sys_stat'] = sys_map[node]
if node in meta_map:
dump_map[node]['as_stat']['meta_data'] = meta_map[node]
if node in histogram_map:
dump_map[node]['as_stat']['histogram'] = histogram_map[node]
# if node in latency_map:
# dump_map[node]['as_stat']['latency'] = latency_map[node]
if node in pmap_map:
dump_map[node]['as_stat']['pmap'] = pmap_map[node]
# Get the cluster name and add one more level in map
cluster_name = 'null'
cluster_names = cluster_names.result()
# Cluster name.
for node in cluster_names:
if not isinstance(cluster_names[node], Exception) and cluster_names[node] not in ["null"]:
cluster_name = cluster_names[node]
break
snp_map = {}
snp_map[cluster_name] = dump_map
return snp_map
def _dump_collectinfo_json(self, timestamp, as_logfile_prefix, default_user, default_pwd, default_ssh_port,
default_ssh_key, credential_file, enable_ssh, snp_count, wait_time):
snpshots = {}
for i in range(snp_count):
snp_timestamp = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime())
self.logger.info("Data collection for Snapshot: " + str(i + 1) + " in progress..")
snpshots[snp_timestamp] = self._get_collectinfo_data_json(
default_user, default_pwd, default_ssh_port, default_ssh_key, credential_file, enable_ssh)
time.sleep(wait_time)
self._dump_in_json_file(as_logfile_prefix, snpshots)
def _dump_collectinfo_pretty_print(self, timestamp, as_logfile_prefix,
show_all=False, verbose=False):
# getting service port to use in ss/netstat command
port = 3000
try:
host, port, tls = list(self.cluster._original_seed_nodes)[0]
except Exception:
port = 3000
collect_output = time.strftime("%Y-%m-%d %H:%M:%S UTC\n", timestamp)
dignostic_info_params = [
'network', 'namespace', 'set', 'xdr', 'dc', 'sindex']
dignostic_features_params = ['features']
dignostic_show_params = ['config', 'config xdr', 'config dc', 'config cluster', 'distribution', 'distribution eviction',
'distribution object_size -b', 'latency', 'statistics', 'statistics xdr', 'statistics dc', 'statistics sindex', 'pmap']
dignostic_aerospike_cluster_params = ['service', 'services']
dignostic_aerospike_cluster_params_additional = [
'partition-info',
'dump-msgs:',
'dump-wr:'
]
dignostic_aerospike_cluster_params_additional_verbose = [
'dump-fabric:',
'dump-hb:',
'dump-migrates:',
'dump-paxos:',
'dump-smd:'
]
summary_params = ['summary']
summary_info_params = ['network', 'namespace', 'set', 'xdr', 'dc', 'sindex']
health_params = ['health -v']
hist_list = ['ttl', 'objsz']
hist_dump_info_str = "hist-dump:ns=%s;hist=%s"
my_ips = (util.shell_command(["hostname -I"])[0]).split(' ')
_ip = my_ips[0].strip()
as_version = None
# Need to find correct IP as per the configuration
for ip in my_ips:
try:
as_version = self.cluster.call_node_method(
[ip.strip()], "info", "build").popitem()[1]
if not as_version or isinstance(as_version, Exception):
continue
_ip = ip.strip()
break
except Exception:
pass
try:
namespaces = self._parse_namespace(self.cluster.info("namespaces"))
except Exception:
namespaces = []
for ns in namespaces:
for hist in hist_list:
dignostic_aerospike_cluster_params.append(
hist_dump_info_str % (ns, hist))
if show_all:
for ns in namespaces:
# dump-wb dumps debug information about Write Bocks, it needs
# namespace, device-id and write-block-id as a parameter
# dignostic_cluster_params_additional.append('dump-wb:ns=' + ns)
dignostic_aerospike_cluster_params_additional.append(
'dump-wb-summary:ns=' + ns)
if verbose:
for index, param in enumerate(dignostic_aerospike_cluster_params_additional_verbose):
if param.startswith("dump"):
if not param.endswith(":"):
param = param + ";"
param = param + "verbose=true"
dignostic_aerospike_cluster_params_additional_verbose[
index] = param
dignostic_aerospike_cluster_params = dignostic_aerospike_cluster_params + \
dignostic_aerospike_cluster_params_additional + \
dignostic_aerospike_cluster_params_additional_verbose
if 'ubuntu' == (platform.linux_distribution()[0]).lower():
cmd_dmesg = 'cat /var/log/syslog'
else:
cmd_dmesg = 'cat /var/log/messages'
####### Dignostic info ########
self.aslogfile = as_logfile_prefix + 'ascollectinfo.log'
util.write_to_file(self.aslogfile, collect_output)
try:
self._collectinfo_content(self._write_version)
except Exception as e:
util.write_to_file(self.aslogfile, str(e))
sys.stdout = sys.__stdout__
try:
info_controller = InfoController()
for info_param in dignostic_info_params:
self._collectinfo_content(info_controller, [info_param])
except Exception as e:
util.write_to_file(self.aslogfile, str(e))
sys.stdout = sys.__stdout__
try:
show_controller = ShowController()
for show_param in dignostic_show_params:
self._collectinfo_content(show_controller, show_param.split())
except Exception as e:
util.write_to_file(self.aslogfile, str(e))
sys.stdout = sys.__stdout__
try:
features_controller = FeaturesController()
for cmd in dignostic_features_params:
self._collectinfo_content(features_controller, [cmd])
except Exception as e:
util.write_to_file(self.aslogfile, str(e))
sys.stdout = sys.__stdout__
try:
for cmd in dignostic_aerospike_cluster_params:
self._collectinfo_content('cluster', cmd)
except Exception as e:
util.write_to_file(self.aslogfile, str(e))
sys.stdout = sys.__stdout__
####### Summary ########
collectinfo_root_controller = CollectinfoRootController(asadm_version=self.asadm_version, clinfo_path=self.aslogdir)
self.aslogfile = as_logfile_prefix + 'summary.log'
util.write_to_file(self.aslogfile, collect_output)
try:
self._collectinfo_content(self._write_version)
except Exception as e:
util.write_to_file(self.aslogfile, str(e))
sys.stdout = sys.__stdout__
try:
for summary_param in summary_params:
self._collectinfo_content(collectinfo_root_controller.execute, [summary_param])
except Exception as e:
util.write_to_file(self.aslogfile, str(e))
sys.stdout = sys.__stdout__
try:
info_controller = InfoController()
for info_param in summary_info_params:
self._collectinfo_content(info_controller, [info_param])
except Exception as e:
util.write_to_file(self.aslogfile, str(e))
sys.stdout = sys.__stdout__
####### Health ########
self.aslogfile = as_logfile_prefix + 'health.log'
util.write_to_file(self.aslogfile, collect_output)
try:
for health_param in health_params:
self._collectinfo_content(collectinfo_root_controller.execute, health_param.split())
except Exception as e:
util.write_to_file(self.aslogfile, str(e))
sys.stdout = sys.__stdout__
####### System info | |
<reponame>yocheah/dac-man
from pathlib import Path
from collections import defaultdict
import numpy as np
try:
import pandas as pd
except ImportError:
from dacman.core.utils import dispatch_import_error
dispatch_import_error(module_name='pandas', plugin_name='CSV')
from dacman.compare import base
try:
from IPython.display import display # for debugging
except ImportError:
display = print
class ChangeStatus:
added = 'ADDED'
deleted = 'DELETED'
modified = 'MODIFIED'
unchanged = 'UNCHANGED'
unset = 'UNSET'
@classmethod
def iter(cls):
yield from (cls.added, cls.deleted, cls.modified, cls.unchanged)
_S = ChangeStatus
class _InternalFields:
"""
Utility class to access commonly used table/dict fields as constants rather than bare strings.
"""
LOC_ORIG_ROW = '_loc_orig_row'
LOC_ORIG_COL = '_loc_orig_col'
ORIG = 'orig'
CALC = 'calc'
_F = _InternalFields
class ChangeMetricsBase:
"""
Convenience class to access properties from items being compared and calculate comparison metrics from them.
"""
def __init__(self, key, a=None, b=None):
self.key = key
self.a = a
self.b = b
self._comparison_data = {
'status': _S.unset,
'metadata': {
'common': {},
'changes': {},
},
}
def __setitem__(self, key, val):
self._comparison_data[key] = val
def __getitem__(self, key):
return self._comparison_data[key]
def keys(self):
# TODO maybe enforce some order?
return self._comparison_data.keys()
def add(self, other_data):
self._comparison_data.update(other_data)
@property
def properties(self):
# only interested in common fields, since we have to compare them directly
# return self.a.keys() & self.b.keys()
# use a dict with dummy values as an ordered set to preserve the order
dict_for_ordered_set = {key: None for key in self.a.keys() if key in self.b.keys()}
return dict_for_ordered_set.keys()
@property
def is_missing_a(self):
return len(self.a) == 0
@property
def is_missing_b(self):
return len(self.b) == 0
def change_in(self, prop):
if prop not in self.properties:
return False
try:
return self.a[prop] != self.b[prop]
except Exception as e:
print(e)
return False
def get_value_common(self, prop):
if prop in self.properties and not self.change_in(prop):
return self.a[prop]
# maybe use a sentinel value other than None here?
return None
def get_value_single(self, prop):
if self.is_missing_a:
return self.b[prop]
if self.is_missing_b:
return self.a[prop]
return self.get_value_common(prop)
def get_values(self, prop, orient=dict, convert=None, as_type=None, fallback=None):
if convert is None and as_type is not None:
convert = as_type
convert = convert or (lambda x: x)
val_a = convert(self.a.get(prop, fallback))
val_b = convert(self.b.get(prop, fallback))
if orient in {tuple, list}:
return val_a, val_b
if orient in {dict}:
return {'a': val_a, 'b': val_b}
@property
def is_modified(self):
# TODO change if we use multiple modified states
return self['status'] in {_S.modified}
@is_modified.setter
def is_modified(self, val):
if bool(val) is True:
# TODO manage other types as extra "modified" characterizers
# e.g. if `val` is a list, append to self['modified_labels']
self['status'] = _S.modified
def store_common_value_or_values(self, prop):
# TODO there could be some redundant logic in general in this class
if self.change_in(prop):
self['metadata']['changes'][prop] = self.get_values(prop, orient=dict)
self.is_modified = True
else:
self['metadata']['common'][prop] = self.get_value_single(prop)
def calculate(self, exclude=None):
exclude = exclude or set()
if self.is_missing_a:
self['status'] = _S.added
elif self.is_missing_b:
self['status'] = _S.deleted
for prop in self.properties:
if prop not in exclude:
self.store_common_value_or_values(prop)
if self['status'] == _S.unset:
self['status'] = _S.unchanged
class TableColumnChangeMetrics(ChangeMetricsBase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def calculate(self):
super().calculate(exclude='values_frame')
if self['status'] == _S.unset:
self['status'] = _S.unchanged
def calculate_from_value_metrics(self, value_metrics_table):
col_metrics_from_value_metrics = self.get_column_metrics_from_values(value_metrics_table)
if col_metrics_from_value_metrics['frac_changed'] > 0.:
self.is_modified = True
self['values'] = col_metrics_from_value_metrics
def get_column_metrics_from_values(self, metrics_table):
m = {}
df = metrics_table
n_total = len(df)
m['n_unchanged'] = (df['status'] == _S.unchanged).sum()
m['n_added'] = (df['status'] == _S.added).sum()
m['n_deleted'] = (df['status'] == _S.deleted).sum()
m['n_modified'] = (df['status'] == _S.modified).sum()
m['n_changed'] = (m['n_added'] + m['n_deleted'] + m['n_modified'])
m['frac_changed'] = m['n_changed'] / n_total
if not (df['delta'].isnull().all()):
m['delta_mean'] = df['delta'].mean()
m['delta_std'] = df['delta'].std()
return m
def get_stats(self):
stats = {'name': self.key}
stats.update(self['values'])
stats['status'] = self['status']
return stats
class _BaseRecord:
@staticmethod
def default_key_getter(item):
raise NotImplementedError
def __init__(self, key_getter=None, **kwargs):
super().__init__(**kwargs)
self.key_getter = key_getter or type(self).default_key_getter
self._mapping = self.get_mapping()
def get_mapping(self):
return {}
def keys(self):
return self._mapping.keys()
def __getitem__(self, key):
return self._mapping[key]
def get_empty(self):
return dict()
def get(self, key):
# TODO should we customize the default return type at the level of the class or of the instance?
return self._mapping.get(key, self.get_empty())
class TableColumnsRecord(_BaseRecord):
# TODO this class should probably also deal with the field renames,
# i.e. should receive a mapping with the field renames
def __init__(self, loader, **kwargs):
self.loader = loader
super().__init__(**kwargs)
@property
def dataframe(self):
return self.loader.to_table_dtype()
def get_metadata(self, series, name):
md = {}
md['name'] = name
md['series'] = series
md['dtype'] = series.dtype
md['n_notnull'] = series.notnull().sum()
md['n_null'] = series.isna().sum()
return md
def default_key_getter(self, col_metadata):
return col_metadata['name']
def get_mapping(self):
df = self.dataframe
mapping = {}
for colname in df:
# TODO in general the metadata collecting can also be done directly in the Record,
# since here we don't have several types of items at the same level like in the HDF5 plug-in
col_md = self.get_metadata(series=df[colname], name=colname)
# we don't need a specific record for table fields, since these are collected as metadata of the columns
mapping[self.key_getter(col_md)] = col_md
return mapping
def get_lines_frame(path, comment_char=None):
"""Read lines and associated metadata from a file"""
with Path(path).open() as f:
lines = pd.DataFrame({'content': list(f)})
lines['lineno'] = lines.index + 1
def is_comment(s):
if comment_char is None:
# get a series where all values are False
return s == np.nan
return (s
.astype(str)
.str.startswith(comment_char)
)
lines['is_comment'] = is_comment(lines['content'])
return lines
def infer_dtypes(data, converters=None):
# the order here is relevant: strings representing floats can be read (erroneously) as datetimes,
# but the reverse is not true, so pd.to_numeric should come first
converters = converters or [pd.to_numeric, pd.to_datetime]
if data.dtype == 'object':
for conv in converters:
try:
data = conv(data)
except (TypeError, ValueError):
pass
else:
break
return data
class ColumnnProcessor:
"""
Utility class to perform per-column processing and hold data in various formats
as needed to create the column-level metadata.
"""
def __init__(self, data_orig, name=None):
self.data_orig = data_orig
self.data_calc = None
self.name = name
self.header = {}
def process_header(self, data, pos_mapper=None, pos='rel', **kwargs):
# pos: relative or absolute
# relative: count from start of subrange
# absolute: use _loc_orig_row
indexer = data.iloc
if pos.startswith('abs'):
indexer = data.loc
pos_mapper = pos_mapper or kwargs
to_drop = []
for key, pos in pos_mapper.items():
val = indexer[pos]
self.header[key] = val
to_drop.append(pos)
return data.drop(indexer[to_drop].index)
def process_rename(self, data, mapper):
self.name = self.header.get('name', self.name)
self.name = mapper.get(self.name, self.name)
if self.name:
data.name = self.name
return data
def process_dtype(self, data, dtype):
if dtype is True:
data = infer_dtypes(data)
else:
if dtype is None:
dtype = {}
data.astype(dtype.get(self.name, data.dtype))
return data
def get_values_frame(self, data_orig, data_calc, index=None):
df = pd.DataFrame({_F.ORIG: data_orig, _F.CALC: data_calc}, index=data_calc.index)
# print(f'{self.name}: dtypes={df.dtypes}')
# so here there are three cases for the index:
# - a data column
# - orig
# - none (reset)
# - In this case, we don't particularly need to give it a name
# we can probably manage to express this by resetting the index in all three cases,
# and then setting the index appropriately
if isinstance(index, str) and index == 'orig':
df = df.reset_index().set_index(df.index.name, drop=False)
elif index is not None:
df = pd.merge(index, df, how='left', left_index=True, right_index=True).reset_index().set_index(index.name)
else:
# we need to be sure that we have the loc_orig_row as a column of this table
df = df.reset_index()
return df
class CSVTableColumnsRecord(_BaseRecord):
"""
Convert a CSV file into a table, and expose a record as Column in the usual way
"""
def __init__(self,
src,
comment_char=None,
drop_empty_cols=True,
table_range=None,
header=None,
column_renames=None,
index=None,
dtype=None,
):
self.src = src
self.comment_char = comment_char
self.drop_empty_cols = drop_empty_cols
self.table_range = table_range or {}
self.header = header or {}
self.column_renames = column_renames or {}
self.dtype = dtype
self.index = index
self._mapping = {}
@staticmethod
def get_lines_frame(path, comment_char=None):
"""Read lines and associated metadata from a file"""
with Path(path).open() as f:
lines = pd.DataFrame({'content': list(f)})
lines['lineno'] = lines.index + 1
def is_comment(s):
if comment_char is None:
# get a series with the same index where all values are False
return s == np.nan
return (s
.astype(str)
.str.startswith(comment_char)
)
lines['is_comment'] = is_comment(lines['content'])
return lines
def get_lineno_loadable(self):
"""
Return a sequence containing the line numbers (1-based) of lines in the source
that are loadable by the CSV parser.
This is used to associate table index/rows with their position in the source.
"""
def is_skipped_by_csv_parser(s):
# TODO redo this with | |
1, 2]]
# Scale all features (except yaws) with global scaler
x_t[:, [0, 1, 2, 3, 4, 7, 8, 9]] /= self.global_scale
else:
# Center node positions
x_t[:, [0, 1, 2]] -= batch.loc[batch.batch][:, [0, 1, 2]]
# Scale all features (except yaws) with global scaler
x_t[:, [0, 1, 2, 3, 4, 7, 8, 9]] /= self.global_scale
# Scale edge attributes
edge_attr /= self.global_scale
# Obtain predicted delta dynamics
delta_x = self.model(
x=x_t, edge_index=edge_index, edge_attr=edge_attr, batch=batch.batch
)
# Transform yaw
bbox_yaw = torch.atan2(
torch.tanh(delta_x[:, 5]), torch.tanh(delta_x[:, 6])
).unsqueeze(1)
vel_yaw = torch.atan2(
torch.tanh(delta_x[:, 7]), torch.tanh(delta_x[:, 8])
).unsqueeze(1)
tmp = torch.cat([delta_x[:, 0:5], bbox_yaw, vel_yaw], dim=1)
delta_x = tmp
# Add deltas to input graph
predicted_graph = torch.cat(
[
predicted_graph[:, : self.out_features] + delta_x,
predicted_graph[:, self.out_features :],
],
dim=1,
)
predicted_graph = predicted_graph.type_as(batch.x)
# Process yaw values to ensure [-pi, pi] interval
yaws = predicted_graph[:, [5, 6]]
yaws[yaws > 0] = (
torch.fmod(yaws[yaws > 0] + math.pi, torch.tensor(2 * math.pi))
- math.pi
)
yaws[yaws < 0] = (
torch.fmod(yaws[yaws < 0] - math.pi, torch.tensor(2 * math.pi))
+ math.pi
)
predicted_graph[:, [5, 6]] = yaws
# Save prediction alongside true value (next time step state)
y_hat[t - 10, :, :] = predicted_graph[:, : self.out_features]
y_target[t - 10, :, :] = batch.x[:, t + 1, : self.out_features]
fde_mask = mask[:, -1]
val_mask = mask[:, 11:].permute(1, 0)
# Compute and log loss
fde_loss = self.val_fde_loss(
y_hat[-1, fde_mask, :3], y_target[-1, fde_mask, :3]
)
ade_loss = self.val_ade_loss(
y_hat[:, :, 0:3][val_mask], y_target[:, :, 0:3][val_mask]
)
vel_loss = self.val_vel_loss(
y_hat[:, :, 3:5][val_mask], y_target[:, :, 3:5][val_mask]
)
yaw_loss = self.val_yaw_loss(
y_hat[:, :, 5:7][val_mask], y_target[:, :, 5:7][val_mask]
)
# Compute losses on "tracks_to_predict"
fde_ttp_mask = torch.logical_and(fde_mask, batch.tracks_to_predict)
fde_ttp_loss = self.val_fde_ttp_loss(
y_hat[-1, fde_ttp_mask, :3], y_target[-1, fde_ttp_mask, :3]
)
ade_ttp_mask = torch.logical_and(
val_mask, batch.tracks_to_predict.expand((80, mask.size(0)))
)
ade_ttp_loss = self.val_ade_loss(
y_hat[:, :, 0:3][ade_ttp_mask], y_target[:, :, 0:3][ade_ttp_mask]
)
######################
# Logging #
######################
self.log("val_ade_loss", ade_loss)
self.log("val_fde_loss", fde_loss)
self.log("val_vel_loss", vel_loss)
self.log("val_yaw_loss", yaw_loss)
self.log("val_total_loss", (ade_loss + vel_loss + yaw_loss) / 3)
self.log("val_fde_ttp_loss", fde_ttp_loss)
self.log("val_ade_ttp_loss", ade_ttp_loss)
return (ade_loss + vel_loss + yaw_loss) / 3
def predict_step(self, batch, batch_idx=None):
######################
# Initialisation #
######################
# Determine valid initialisations at t=11
mask = batch.x[:, :, -1]
valid_mask = mask[:, 10] > 0
# Discard non-valid nodes as no initial trajectories will be known
batch.x = batch.x[valid_mask]
batch.batch = batch.batch[valid_mask]
batch.tracks_to_predict = batch.tracks_to_predict[valid_mask]
batch.type = batch.type[valid_mask]
# CARS
type_mask = batch.type[:, 1] == 1
batch.x = batch.x[type_mask]
batch.batch = batch.batch[type_mask]
batch.tracks_to_predict = batch.tracks_to_predict[type_mask]
batch.type = batch.type[type_mask]
# Update mask
mask = batch.x[:, :, -1].bool()
# Allocate target/prediction tensors
n_nodes = batch.num_nodes
y_hat = torch.zeros((90, n_nodes, self.node_features))
y_target = torch.zeros((90, n_nodes, self.node_features))
# Ensure device placement
y_hat = y_hat.type_as(batch.x)
y_target = y_target.type_as(batch.x)
batch.x = batch.x[:, :, :-1]
# static_features = torch.cat(
# [batch.x[:, 10, self.out_features :], batch.type], dim=1
# )
static_features = torch.cat([batch.x[:, 10, self.out_features :]], dim=1)
edge_attr = None
######################
# History #
######################
for t in range(11):
######################
# Graph construction #
######################
mask_t = mask[:, t]
# x_t = torch.cat([batch.x[mask_t, t, :], batch.type[mask_t]], dim=1)
x_t = batch.x[mask_t, t, :].clone()
batch_t = batch.batch[mask_t]
# Construct edges
if self.edge_type == "knn":
# Neighbour-based graph
edge_index = torch_geometric.nn.knn_graph(
x=x_t[:, :2],
k=self.n_neighbours,
batch=batch_t,
loop=self.self_loop,
)
else:
# Distance-based graph
edge_index = torch_geometric.nn.radius_graph(
x=x_t[:, :2],
r=self.min_dist,
batch=batch_t,
loop=self.self_loop,
max_num_neighbors=self.n_neighbours,
flow="source_to_target",
)
if self.undirected:
edge_index, edge_attr = torch_geometric.utils.to_undirected(edge_index)
# Remove duplicates and sort
edge_index = torch_geometric.utils.coalesce(edge_index)
# Create edge_attr if specified
if self.edge_weight:
# Encode distance between nodes as edge_attr
row, col = edge_index
edge_attr = (x_t[row, :2] - x_t[col, :2]).norm(dim=-1).unsqueeze(1)
edge_attr = edge_attr.type_as(batch.x)
######################
# Prediction 1/2 #
######################
# Normalise input graph
if self.normalise:
if edge_attr is None:
# Center node positions
x_t[:, [0, 1, 2]] -= batch.loc[batch.batch][mask_t][:, [0, 1, 2]]
# Scale all features (except yaws) with global scaler
x_t[:, [0, 1, 2, 3, 4, 7, 8, 9]] /= self.global_scale
else:
# Center node positions
x_t[:, [0, 1, 2]] -= batch.loc[batch.batch][mask_t][:, [0, 1, 2]]
# Scale all features (except yaws) with global scaler
x_t[:, [0, 1, 2, 3, 4, 7, 8, 9]] /= self.global_scale
# Scale edge attributes
edge_attr /= self.global_scale
# Obtain predicted delta dynamics
delta_x = self.model(
x=x_t, edge_index=edge_index, edge_attr=edge_attr, batch=batch_t
)
# Transform yaw
bbox_yaw = torch.atan2(
torch.tanh(delta_x[:, 5]), torch.tanh(delta_x[:, 6])
).unsqueeze(1)
vel_yaw = torch.atan2(
torch.tanh(delta_x[:, 7]), torch.tanh(delta_x[:, 8])
).unsqueeze(1)
tmp = torch.cat([delta_x[:, 0:5], bbox_yaw, vel_yaw], dim=1)
delta_x = tmp
# Add deltas to input graph
predicted_graph = torch.cat(
(
batch.x[mask_t, t, : self.out_features] + delta_x,
static_features[mask_t],
),
dim=-1,
)
predicted_graph = predicted_graph.type_as(batch.x)
# Process yaw values to ensure [-pi, pi] interval
yaws = predicted_graph[:, [5, 6]]
yaws[yaws > 0] = (
torch.fmod(yaws[yaws > 0] + math.pi, torch.tensor(2 * math.pi))
- math.pi
)
yaws[yaws < 0] = (
torch.fmod(yaws[yaws < 0] - math.pi, torch.tensor(2 * math.pi))
+ math.pi
)
predicted_graph[:, [5, 6]] = yaws
# Save first prediction and target
y_hat[t, mask_t, :] = predicted_graph
# y_target[t, mask_t, :] = torch.cat(
# [batch.x[mask_t, t + 1, :], batch.type[mask_t]], dim=-1
# )
y_target[t, mask_t, :] = batch.x[mask_t, t + 1, :].clone()
######################
# Future #
######################
for t in range(11, 90):
######################
# Graph construction #
######################
# Latest prediction as input
x_t = predicted_graph.clone()
# Construct edges
if self.edge_type == "knn":
# Neighbour-based graph
edge_index = torch_geometric.nn.knn_graph(
x=x_t[:, :2],
k=self.n_neighbours,
batch=batch.batch,
loop=self.self_loop,
)
else:
# Distance-based graph
edge_index = torch_geometric.nn.radius_graph(
x=x_t[:, :2],
r=self.min_dist,
batch=batch.batch,
loop=self.self_loop,
max_num_neighbors=self.n_neighbours,
flow="source_to_target",
)
if self.undirected:
edge_index, edge_attr = torch_geometric.utils.to_undirected(edge_index)
# Remove duplicates and sort
edge_index = torch_geometric.utils.coalesce(edge_index)
# Create edge_attr if specified
if self.edge_weight:
# Encode distance between nodes as edge_attr
row, col = edge_index
edge_attr = (x_t[row, :2] - x_t[col, :2]).norm(dim=-1).unsqueeze(1)
edge_attr = edge_attr.type_as(batch.x)
######################
# Prediction 2/2 #
######################
# Normalise input graph
if self.normalise:
if edge_attr is None:
# Center node positions
x_t[:, [0, 1, 2]] -= batch.loc[batch.batch][:, [0, 1, 2]]
# Scale all features (except yaws) with global scaler
x_t[:, [0, 1, 2, 3, 4, 7, 8, 9]] /= self.global_scale
else:
# Center node positions
x_t[:, [0, 1, 2]] -= batch.loc[batch.batch][:, [0, 1, 2]]
# Scale all features (except yaws) with global scaler
x_t[:, [0, 1, 2, 3, 4, 7, 8, 9]] /= self.global_scale
# Scale edge attributes
edge_attr /= self.global_scale
# Obtain predicted delta dynamics
delta_x = self.model(
x=x_t, edge_index=edge_index, edge_attr=edge_attr, batch=batch.batch
)
# Transform yaw
bbox_yaw = torch.atan2(
torch.tanh(delta_x[:, 5]), torch.tanh(delta_x[:, 6])
).unsqueeze(1)
vel_yaw = torch.atan2(
torch.tanh(delta_x[:, 7]), torch.tanh(delta_x[:, 8])
).unsqueeze(1)
tmp = torch.cat([delta_x[:, 0:5], bbox_yaw, vel_yaw], dim=1)
delta_x = tmp
# Add deltas to input graph
predicted_graph = torch.cat(
[
predicted_graph[:, : self.out_features] + delta_x,
predicted_graph[:, self.out_features :],
],
dim=1,
)
predicted_graph = predicted_graph.type_as(batch.x)
# Process yaw values to ensure [-pi, pi] interval
yaws = predicted_graph[:, [5, 6]]
yaws[yaws > 0] = (
torch.fmod(yaws[yaws > 0] + math.pi, torch.tensor(2 * math.pi))
- math.pi
)
yaws[yaws < 0] = (
torch.fmod(yaws[yaws < 0] - math.pi, torch.tensor(2 * math.pi))
+ math.pi
)
predicted_graph[:, [5, 6]] = yaws
# Save prediction alongside true value (next time step state)
y_hat[t, :, :] = predicted_graph
# y_target[t, :, :] = torch.cat([batch.x[:, t + 1], batch.type], dim=-1)
y_target[t, :, :] = batch.x[:, t + 1].clone()
return y_hat, y_target, mask
def configure_optimizers(self):
return torch.optim.Adam(
self.parameters(), lr=self.lr, weight_decay=self.weight_decay
)
class SequentialModule(pl.LightningModule):
def __init__(
self,
model_type: Union[None, str],
model_dict: Union[None, dict],
lr: float = 1e-4,
weight_decay: float = 0.0,
noise: Union[None, float] = None,
teacher_forcing: bool = False,
teacher_forcing_ratio: float = 0.3,
min_dist: int = 0,
n_neighbours: int = 30,
fully_connected: bool = True,
edge_weight: bool = False,
edge_type: str = "knn",
self_loop: bool = True,
undirected: bool = False,
out_features: int = 6,
node_features: int = 9,
edge_features: int = 1,
normalise: bool = True,
training_horizon: int = 90,
):
super().__init__()
# Verify inputs
assert edge_type in ["knn", "distance"]
if edge_type == "distance":
assert min_dist > 0.0
assert out_features == 9
assert node_features == 12
# Set up | |
'''functions to work with contrasts for multiple tests
contrast matrices for comparing all pairs, all levels to reference level, ...
extension to 2-way groups in progress
TwoWay: class for bringing two-way analysis together and try out
various helper functions
Idea for second part
- get all transformation matrices to move in between different full rank
parameterizations
- standardize to one parameterization to get all interesting effects.
- multivariate normal distribution
- exploit or expand what we have in LikelihoodResults, cov_params, f_test,
t_test, example: resols_dropf_full.cov_params(C2)
- connect to new multiple comparison for contrast matrices, based on
multivariate normal or t distribution (Hothorn, Bretz, Westfall)
'''
from numpy.testing import assert_equal
import numpy as np
#next 3 functions copied from multicomp.py
def contrast_allpairs(nm):
'''contrast or restriction matrix for all pairs of nm variables
Parameters
----------
nm : int
Returns
-------
contr : ndarray, 2d, (nm*(nm-1)/2, nm)
contrast matrix for all pairwise comparisons
'''
contr = []
for i in range(nm):
for j in range(i+1, nm):
contr_row = np.zeros(nm)
contr_row[i] = 1
contr_row[j] = -1
contr.append(contr_row)
return np.array(contr)
def contrast_all_one(nm):
'''contrast or restriction matrix for all against first comparison
Parameters
----------
nm : int
Returns
-------
contr : ndarray, 2d, (nm-1, nm)
contrast matrix for all against first comparisons
'''
contr = np.column_stack((np.ones(nm-1), -np.eye(nm-1)))
return contr
def contrast_diff_mean(nm):
'''contrast or restriction matrix for all against mean comparison
Parameters
----------
nm : int
Returns
-------
contr : ndarray, 2d, (nm-1, nm)
contrast matrix for all against mean comparisons
'''
return np.eye(nm) - np.ones((nm,nm))/nm
def signstr(x, noplus=False):
if x in [-1,0,1]:
if not noplus:
return '+' if np.sign(x)>=0 else '-'
else:
return '' if np.sign(x)>=0 else '-'
else:
return str(x)
def contrast_labels(contrasts, names, reverse=False):
if reverse:
sl = slice(None, None, -1)
else:
sl = slice(None)
labels = [''.join(['%s%s' % (signstr(c, noplus=True),v)
for c,v in zip(row, names)[sl] if c != 0])
for row in contrasts]
return labels
def contrast_product(names1, names2, intgroup1=None, intgroup2=None, pairs=False):
'''build contrast matrices for products of two categorical variables
this is an experimental script and should be converted to a class
Parameters
----------
names1, names2 : lists of strings
contains the list of level labels for each categorical variable
intgroup1, intgroup2 : ndarrays TODO: this part not tested, finished yet
categorical variable
Notes
-----
This creates a full rank matrix. It does not do all pairwise comparisons,
parameterization is using contrast_all_one to get differences with first
level.
? does contrast_all_pairs work as a plugin to get all pairs ?
'''
n1 = len(names1)
n2 = len(names2)
names_prod = ['%s_%s' % (i,j) for i in names1 for j in names2]
ee1 = np.zeros((1,n1))
ee1[0,0] = 1
if not pairs:
dd = np.r_[ee1, -contrast_all_one(n1)]
else:
dd = np.r_[ee1, -contrast_allpairs(n1)]
contrast_prod = np.kron(dd[1:], np.eye(n2))
names_contrast_prod0 = contrast_labels(contrast_prod, names_prod, reverse=True)
names_contrast_prod = [''.join(['%s%s' % (signstr(c, noplus=True),v)
for c,v in zip(row, names_prod)[::-1] if c != 0])
for row in contrast_prod]
ee2 = np.zeros((1,n2))
ee2[0,0] = 1
#dd2 = np.r_[ee2, -contrast_all_one(n2)]
if not pairs:
dd2 = np.r_[ee2, -contrast_all_one(n2)]
else:
dd2 = np.r_[ee2, -contrast_allpairs(n2)]
contrast_prod2 = np.kron(np.eye(n1), dd2[1:])
names_contrast_prod2 = [''.join(['%s%s' % (signstr(c, noplus=True),v)
for c,v in zip(row, names_prod)[::-1] if c != 0])
for row in contrast_prod2]
if (intgroup1 is not None) and (intgroup1 is not None):
d1, _ = dummy_1d(intgroup1)
d2, _ = dummy_1d(intgroup2)
dummy = dummy_product(d1, d2)
else:
dummy = None
return (names_prod, contrast_prod, names_contrast_prod,
contrast_prod2, names_contrast_prod2, dummy)
def dummy_1d(x, varname=None):
'''dummy variable for id integer groups
Parameters
----------
x : ndarray, 1d
categorical variable, requires integers if varname is None
varname : string
name of the variable used in labels for category levels
Returns
-------
dummy : ndarray, 2d
array of dummy variables, one column for each level of the
category (full set)
labels : list of strings
labels for the columns, i.e. levels of each category
Notes
-----
use tools.categorical instead for more more options
See Also
--------
statsmodels.tools.categorical
Examples
--------
>>> x = np.array(['F', 'F', 'M', 'M', 'F', 'F', 'M', 'M', 'F', 'F', 'M', 'M'],
dtype='|S1')
>>> dummy_1d(x, varname='gender')
(array([[1, 0],
[1, 0],
[0, 1],
[0, 1],
[1, 0],
[1, 0],
[0, 1],
[0, 1],
[1, 0],
[1, 0],
[0, 1],
[0, 1]]), ['gender_F', 'gender_M'])
'''
if varname is None: #assumes integer
labels = ['level_%d' % i for i in range(x.max() + 1)]
return (x[:,None]==np.arange(x.max()+1)).astype(int), labels
else:
grouplabels = np.unique(x)
labels = [varname + '_%s' % str(i) for i in grouplabels]
return (x[:,None]==grouplabels).astype(int), labels
def dummy_product(d1, d2, method='full'):
'''dummy variable from product of two dummy variables
Parameters
----------
d1, d2 : ndarray
two dummy variables, assumes full set for methods 'drop-last'
and 'drop-first'
method : {'full', 'drop-last', 'drop-first'}
'full' returns the full product, encoding of intersection of
categories.
The drop methods provide a difference dummy encoding:
(constant, main effects, interaction effects). The first or last columns
of the dummy variable (i.e. levels) are dropped to get full rank
dummy matrix.
Returns
-------
dummy : ndarray
dummy variable for product, see method
'''
if method == 'full':
dd = (d1[:,:,None]*d2[:,None,:]).reshape(d1.shape[0],-1)
elif method == 'drop-last': #same as SAS transreg
d12rl = dummy_product(d1[:,:-1], d2[:,:-1])
dd = np.column_stack((np.ones(d1.shape[0], int), d1[:,:-1], d2[:,:-1],d12rl))
#Note: dtype int should preserve dtype of d1 and d2
elif method == 'drop-first':
d12r = dummy_product(d1[:,1:], d2[:,1:])
dd = np.column_stack((np.ones(d1.shape[0], int), d1[:,1:], d2[:,1:],d12r))
else:
raise ValueError('method not recognized')
return dd
def dummy_limits(d):
'''start and endpoints of groups in a sorted dummy variable array
helper function for nested categories
Examples
--------
>>> d1 = np.array([[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[1, 0, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1]])
>>> dummy_limits(d1)
(array([0, 4, 8]), array([ 4, 8, 12]))
get group slices from an array
>>> [np.arange(d1.shape[0])[b:e] for b,e in zip(*dummy_limits(d1))]
[array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([ 8, 9, 10, 11])]
>>> [np.arange(d1.shape[0])[b:e] for b,e in zip(*dummy_limits(d1))]
[array([0, 1, 2, 3]), array([4, 5, 6, 7]), array([ 8, 9, 10, 11])]
'''
nobs, nvars = d.shape
start1, col1 = np.nonzero(np.diff(d,axis=0)==1)
end1, col1_ = np.nonzero(np.diff(d,axis=0)==-1)
cc = np.arange(nvars)
#print(cc, np.r_[[0], col1], np.r_[col1_, [nvars-1]]
if ((not (np.r_[[0], col1] == cc).all())
or (not (np.r_[col1_, [nvars-1]] == cc).all())):
raise ValueError('dummy variable is not sorted')
start = np.r_[[0], start1+1]
end = np.r_[end1+1, [nobs]]
return start, end
def dummy_nested(d1, d2, method='full'):
'''unfinished and incomplete mainly copy past dummy_product
dummy variable from product of two dummy variables
Parameters
----------
d1, d2 : ndarray
two dummy variables, d2 is assumed to be nested in d1
Assumes full set for methods 'drop-last' and 'drop-first'.
method : {'full', 'drop-last', 'drop-first'}
'full' returns the full product, which in this case is d2.
The drop methods provide an effects encoding:
(constant, main effects, subgroup effects). The first or last columns
of the dummy variable (i.e. levels) are dropped to get full rank
encoding.
Returns
-------
dummy : ndarray
dummy variable for product, see method
'''
if method == 'full':
return d2
start1, end1 = dummy_limits(d1)
start2, end2 = dummy_limits(d2)
first = np.in1d(start2, start1)
last = np.in1d(end2, end1)
equal = (first == last)
col_dropf = ~first*~equal
col_dropl = ~last*~equal
if method == 'drop-last':
d12rl = dummy_product(d1[:,:-1], d2[:,:-1])
dd = np.column_stack((np.ones(d1.shape[0], int), d1[:,:-1], d2[:,col_dropl]))
#Note: dtype int should preserve dtype of d1 and d2
elif method == 'drop-first':
d12r = dummy_product(d1[:,1:], d2[:,1:])
dd = np.column_stack((np.ones(d1.shape[0], int), d1[:,1:], d2[:,col_dropf]))
else:
raise ValueError('method not recognized')
return dd, col_dropf, col_dropl
class DummyTransform(object):
'''Conversion between full rank dummy encodings
y = X b + u
b = C a
a = C^{-1} b
y = X C a + u
define Z = X C, then
y = Z a + u
contrasts:
R_b b = r
R_a a = R_b C a = r
where R_a = R_b C
Here C is the transform matrix, with dot_left and dot_right as the main
methods, and the same for the inverse transform matrix, C^{-1}
Note:
- The class was mainly written to keep left and right straight.
- No | |
Network Storage",
"005014": "CISCO SYSTEMS, INC.",
"005015": "BRIGHT STAR ENGINEERING",
"005016": "SST/WOODHEAD INDUSTRIES",
"005017": "RSR S.R.L.",
"005018": "AMIT, Inc.",
"005019": "SPRING TIDE NETWORKS, INC.",
"00501A": "IQinVision",
"00501B": "ABL CANADA, INC.",
"00501C": "JATOM SYSTEMS, INC.",
"00501E": "Miranda Technologies, Inc.",
"00501F": "MRG SYSTEMS, LTD.",
"005020": "MEDIASTAR CO., LTD.",
"005021": "EIS INTERNATIONAL, INC.",
"005022": "ZONET TECHNOLOGY, INC.",
"005023": "PG DESIGN ELECTRONICS, INC.",
"005024": "NAVIC SYSTEMS, INC.",
"005026": "COSYSTEMS, INC.",
"005027": "GENICOM CORPORATION",
"005028": "AVAL COMMUNICATIONS",
"005029": "1394 PRINTER WORKING GROUP",
"00502A": "CISCO SYSTEMS, INC.",
"00502B": "GENRAD LTD.",
"00502C": "SOYO COMPUTER, INC.",
"00502D": "ACCEL, INC.",
"00502E": "CAMBEX CORPORATION",
"00502F": "TollBridge Technologies, Inc.",
"005030": "FUTURE PLUS SYSTEMS",
"005031": "AEROFLEX LABORATORIES, INC.",
"005032": "PICAZO COMMUNICATIONS, INC.",
"005033": "MAYAN NETWORKS",
"005036": "NETCAM, LTD.",
"005037": "KOGA ELECTRONICS CO.",
"005038": "DAIN TELECOM CO., LTD.",
"005039": "MARINER NETWORKS",
"00503A": "DATONG ELECTRONICS LTD.",
"00503B": "MEDIAFIRE CORPORATION",
"00503C": "TSINGHUA NOVEL ELECTRONICS",
"00503E": "CISCO SYSTEMS, INC.",
"00503F": "ANCHOR GAMES",
"005040": "Panasonic Electric Works Co., Ltd.",
"005041": "Coretronic Corporation",
"005042": "SCI MANUFACTURING SINGAPORE PTE, LTD.",
"005043": "MARVELL SEMICONDUCTOR, INC.",
"005044": "ASACA CORPORATION",
"005045": "RIOWORKS SOLUTIONS, INC.",
"005046": "MENICX INTERNATIONAL CO., LTD.",
"005047": "PRIVATE",
"005048": "INFOLIBRIA",
"005049": "Arbor Networks Inc",
"00504A": "ELTECO A.S.",
"00504B": "BARCONET N.V.",
"00504C": "Galil Motion Control",
"00504D": "Tokyo Electron Device Limited",
"00504E": "SIERRA MONITOR CORP.",
"00504F": "OLENCOM ELECTRONICS",
"005050": "CISCO SYSTEMS, INC.",
"005051": "IWATSU ELECTRIC CO., LTD.",
"005052": "TIARA NETWORKS, INC.",
"005053": "CISCO SYSTEMS, INC.",
"005054": "CISCO SYSTEMS, INC.",
"005055": "DOMS A/S",
"005056": "VMware, Inc.",
"005057": "BROADBAND ACCESS SYSTEMS",
"005058": "VegaStream Group Limted",
"005059": "iBAHN",
"00505A": "NETWORK ALCHEMY, INC.",
"00505B": "KAWASAKI LSI U.S.A., INC.",
"00505C": "TUNDO CORPORATION",
"00505E": "DIGITEK MICROLOGIC S.A.",
"00505F": "BRAND INNOVATORS",
"005060": "TANDBERG TELECOM AS",
"005062": "KOUWELL ELECTRONICS CORP. **",
"005063": "OY COMSEL SYSTEM AB",
"005064": "CAE ELECTRONICS",
"005065": "TDK-Lambda Corporation",
"005066": "AtecoM GmbH advanced telecomunication modules",
"005067": "AEROCOMM, INC.",
"005068": "ELECTRONIC INDUSTRIES ASSOCIATION",
"005069": "PixStream Incorporated",
"00506A": "EDEVA, INC.",
"00506B": "SPX-ATEG",
"00506C": "Beijer Electronics Products AB",
"00506D": "VIDEOJET SYSTEMS",
"00506E": "CORDER ENGINEERING CORPORATION",
"00506F": "G-CONNECT",
"005070": "CHAINTECH COMPUTER CO., LTD.",
"005071": "AIWA CO., LTD.",
"005072": "CORVIS CORPORATION",
"005073": "CISCO SYSTEMS, INC.",
"005074": "ADVANCED HI-TECH CORP.",
"005075": "KESTREL SOLUTIONS",
"005076": "IBM Corp",
"005077": "PROLIFIC TECHNOLOGY, INC.",
"005078": "MEGATON HOUSE, LTD.",
"005079": "PRIVATE",
"00507A": "XPEED, INC.",
"00507B": "MERLOT COMMUNICATIONS",
"00507C": "VIDEOCON AG",
"00507D": "IFP",
"00507E": "NEWER TECHNOLOGY",
"00507F": "DrayTek Corp.",
"005080": "CISCO SYSTEMS, INC.",
"005081": "MURATA MACHINERY, LTD.",
"005082": "FORESSON CORPORATION",
"005083": "GILBARCO, INC.",
"005084": "ATL PRODUCTS",
"005086": "TELKOM SA, LTD.",
"005087": "TERASAKI ELECTRIC CO., LTD.",
"005088": "AMANO CORPORATION",
"005089": "SAFETY MANAGEMENT SYSTEMS",
"00508B": "Hewlett-Packard Company",
"00508C": "RSI SYSTEMS",
"00508D": "ABIT COMPUTER CORPORATION",
"00508E": "OPTIMATION, INC.",
"00508F": "ASITA TECHNOLOGIES INT'L LTD.",
"005090": "DCTRI",
"005091": "NETACCESS, INC.",
"005092": "RIGAKU INDUSTRIAL CORPORATION",
"005093": "BOEING",
"005094": "PACE plc",
"005095": "PERACOM NETWORKS",
"005096": "SALIX TECHNOLOGIES, INC.",
"005097": "MMC-EMBEDDED COMPUTERTECHNIK GmbH",
"005098": "GLOBALOOP, LTD.",
"005099": "3COM EUROPE, LTD.",
"00509A": "TAG ELECTRONIC SYSTEMS",
"00509B": "SWITCHCORE AB",
"00509C": "BETA RESEARCH",
"00509D": "THE INDUSTREE B.V.",
"00509E": "Les Technologies SoftAcoustik Inc.",
"00509F": "HORIZON COMPUTER",
"0050A0": "DELTA COMPUTER SYSTEMS, INC.",
"0050A1": "<NAME>, INC.",
"0050A2": "CISCO SYSTEMS, INC.",
"0050A3": "TransMedia Communications, Inc.",
"0050A4": "IO TECH, INC.",
"0050A5": "CAPITOL BUSINESS SYSTEMS, LTD.",
"0050A6": "OPTRONICS",
"0050A7": "CISCO SYSTEMS, INC.",
"0050A8": "OpenCon Systems, Inc.",
"0050A9": "MOLDAT WIRELESS TECHNOLGIES",
"0050AA": "K<NAME> HOLDINGS, INC.",
"0050AB": "NALTEC, Inc.",
"0050AC": "MAPLE COMPUTER CORPORATION",
"0050AD": "CommUnique Wireless Corp.",
"0050AE": "FDK Co., Ltd",
"0050AF": "INTERGON, INC.",
"0050B0": "TECHNOLOGY ATLANTA CORPORATION",
"0050B1": "GIDDINGS & LEWIS",
"0050B2": "BRODEL GmbH",
"0050B3": "VOICEBOARD CORPORATION",
"0050B4": "SATCHWELL CONTROL SYSTEMS, LTD",
"0050B5": "FICHET-BAUCHE",
"0050B6": "GOOD WAY IND. CO., LTD.",
"0050B7": "BOSER TECHNOLOGY CO., LTD.",
"0050B8": "INOVA COMPUTERS GMBH & CO. KG",
"0050B9": "XITRON TECHNOLOGIES, INC.",
"0050BA": "D-LINK",
"0050BB": "CMS TECHNOLOGIES",
"0050BC": "HAMMER STORAGE SOLUTIONS",
"0050BD": "CISCO SYSTEMS, INC.",
"0050BE": "FAST MULTIMEDIA AG",
"0050BF": "Metalligence Technology Corp.",
"0050C0": "GATAN, INC.",
"0050C1": "GEMFLEX NETWORKS, LTD.",
"0050C2": "IEEE REGISTRATION AUTHORITY - Please see IAB public listing for more information.",
"0050C4": "IMD",
"0050C5": "ADS Technologies, Inc",
"0050C6": "LOOP TELECOMMUNICATION INTERNATIONAL, INC.",
"0050C8": "Addonics Technologies, Inc.",
"0050C9": "MASPRO DENKOH CORP.",
"0050CA": "NET TO NET TECHNOLOGIES",
"0050CB": "JETTER",
"0050CC": "XYRATEX",
"0050CD": "DIGIANSWER A/S",
"0050CE": "LG INTERNATIONAL CORP.",
"0050CF": "VANLINK COMMUNICATION TECHNOLOGY RESEARCH INSTITUTE",
"0050D0": "MINERVA SYSTEMS",
"0050D1": "CISCO SYSTEMS, INC.",
"0050D2": "CMC Electronics Inc",
"0050D3": "DIGITAL AUDIO PROCESSING PTY. LTD.",
"0050D4": "JOOHONG INFORMATION &",
"0050D5": "AD SYSTEMS CORP.",
"0050D6": "ATLAS COPCO TOOLS AB",
"0050D7": "TELSTRAT",
"0050D8": "UNICORN COMPUTER CORP.",
"0050D9": "ENGETRON-ENGENHARIA ELETRONICA IND. e COM. LTDA",
"0050DA": "3COM CORPORATION",
"0050DB": "CONTEMPORARY CONTROL",
"0050DC": "TAS TELEFONBAU A. SCHWABE GMBH & CO. KG",
"0050DD": "SERRA SOLDADURA, S.A.",
"0050DE": "SIGNUM SYSTEMS CORP.",
"0050DF": "AirFiber, Inc.",
"0050E1": "NS TECH ELECTRONICS SDN BHD",
"0050E2": "CISCO SYSTEMS, INC.",
"0050E3": "ARRIS Group, Inc.",
"0050E4": "Apple",
"0050E6": "HAKUSAN CORPORATION",
"0050E7": "PARADISE INNOVATIONS (ASIA)",
"0050E8": "NOMADIX INC.",
"0050EA": "XEL COMMUNICATIONS, INC.",
"0050EB": "ALPHA-TOP CORPORATION",
"0050EC": "OLICOM A/S",
"0050ED": "ANDA NETWORKS",
"0050EE": "TEK DIGITEL CORPORATION",
"0050EF": "SPE Systemhaus GmbH",
"0050F0": "CISCO SYSTEMS, INC.",
"0050F1": "Intel Corporation",
"0050F2": "MICROSOFT CORP.",
"0050F3": "GLOBAL NET INFORMATION CO., Ltd.",
"0050F4": "SIGMATEK GMBH & CO. KG",
"0050F6": "PAN-INTERNATIONAL INDUSTRIAL CORP.",
"0050F7": "VENTURE MANUFACTURING (SINGAPORE) LTD.",
"0050F8": "ENTREGA TECHNOLOGIES, INC.",
"0050F9": "SENSORMATIC ACD",
"0050FA": "OXTEL, LTD.",
"0050FB": "VSK ELECTRONICS",
"0050FC": "EDIMAX TECHNOLOGY CO., LTD.",
"0050FD": "VISIONCOMM CO., LTD.",
"0050FE": "PCTVnet ASA",
"0050FF": "HAKKO ELECTRONICS CO., LTD.",
"005218": "Wuxi Keboda Electron Co.Ltd",
"0054AF": "Continental Automotive Systems Inc.",
"005907": "LenovoEMC Products USA, LLC",
"005CB1": "Gospell DIGITAL TECHNOLOGY CO., LTD",
"005D03": "Xilinx, Inc",
"006000": "XYCOM INC.",
"006001": "InnoSys, Inc.",
"006002": "SCREEN SUBTITLING SYSTEMS, LTD",
"006003": "TERAOKA WEIGH SYSTEM PTE, LTD.",
"006004": "COMPUTADORES MODULARES SA",
"006005": "FEEDBACK DATA LTD.",
"006006": "SOTEC CO., LTD",
"006007": "ACRES GAMING, INC.",
"006008": "3COM CORPORATION",
"006009": "CISCO SYSTEMS, INC.",
"00600A": "SORD COMPUTER CORPORATION",
"00600B": "LOGWARE GmbH",
"00600C": "Eurotech Inc.",
"00600D": "Digital Logic GmbH",
"00600E": "WAVENET INTERNATIONAL, INC.",
"00600F": "WESTELL, INC.",
"006010": "NETWORK MACHINES, INC.",
"006011": "CRYSTAL SEMICONDUCTOR CORP.",
"006012": "POWER COMPUTING CORPORATION",
"006013": "NETSTAL MASCHINEN AG",
"006014": "EDEC CO., LTD.",
"006015": "NET2NET CORPORATION",
"006016": "CLARIION",
"006017": "TOKIMEC INC.",
"006018": "STELLAR ONE CORPORATION",
"006019": "Roche Diagnostics",
"00601A": "KEITHLEY INSTRUMENTS",
"00601B": "MESA ELECTRONICS",
"00601C": "TELXON CORPORATION",
"00601D": "LUCENT TECHNOLOGIES",
"00601E": "SOFTLAB, INC.",
"00601F": "STALLION TECHNOLOGIES",
"006020": "PIVOTAL NETWORKING, INC.",
"006021": "DSC CORPORATION",
"006022": "VICOM SYSTEMS, INC.",
"006023": "PERICOM SEMICONDUCTOR CORP.",
"006024": "GRADIENT TECHNOLOGIES, INC.",
"006025": "ACTIVE IMAGING PLC",
"006026": "VIKING Modular Solutions",
"006027": "Superior Modular Products",
"006028": "MACROVISION CORPORATION",
"006029": | |
in ds_rows:
del row.values[col_index]
del row.caveats[col_index]
self.add_delta(id=VIZUAL_DELETE_COLUMN, column=col_index)
def get_column(self, name: Any) -> Optional[DatasetColumn]:
"""Get the fist column in the dataset schema that matches the given
name. If no column matches the given name None is returned.
"""
for col in self.columns:
if col.name == name:
return col
return None
def insert_column(self,
name: str,
data_type: str = DATATYPE_VARCHAR,
position: Optional[int] = None
) -> DatasetColumn:
"""Add a new column to the dataset schema.
"""
if len(self.columns) > 0:
idx = max(column.identifier for column in self.columns) + 1
else:
idx = 0
column = DatasetColumn(name=name, data_type=data_type, identifier=idx)
self.columns = list(self.columns)
if position is not None:
self.columns.insert(position, column)
# Add a null value to each row for the new column
for row in self.rows:
row.values.insert(position, None)
row.caveats.insert(position, False)
else:
self.columns.append(column)
# Add a null value to each row for the new column
for row in self.rows:
row.values.append(None)
row.caveats.append(False)
self.add_delta(
id=VIZUAL_INSERT_COLUMN,
name=name,
position=position,
dataType=data_type,
)
return column
def insert_row(self,
values: Optional[List[Any]] = None,
position: Optional[int] = None
) -> MutableDatasetRow:
"""Add a new row to the dataset. Expects a list of string values, one
for each of the columns.
Raises ValueError if the length of the values list does not match the
number of columns in the dataset.
"""
# Ensure that there is exactly one value for each column in the dataset
if values is not None:
if len(values) != len(self.columns):
raise ValueError('invalid number of values for dataset schema')
for v, col in zip(values, self.columns):
assert_type(v, col.data_type, col.name)
row = MutableDatasetRow(
values=[v for v in values],
dataset=self
)
else:
# All values in the new row are set to the empty string by default.
row = MutableDatasetRow(
values=[None] * len(self.columns),
dataset=self
)
if position is not None:
self.rows.insert(position, row)
else:
self.rows.append(row)
encoded_values: Optional[List[Any]] = None
if values is not None:
encoded_values = [
export_from_native_type(value, col.data_type)
for value, col in zip(values, self.columns)
]
self.add_delta(
id=VIZUAL_INSERT_ROW,
position=position,
values=encoded_values
)
return row
def get_cell(self, column: Any, row: int) -> Any:
"""Get dataset value for specified cell.
Raises ValueError if [column, row] does not reference an existing cell.
"""
if row < 0 or row > len(self.rows):
raise ValueError('unknown row \'' + str(row) + '\'')
return self.rows[row].get_value(column)
def move_column(self, name: str, position: int) -> None:
"""Move a column within a given dataset.
Raises ValueError if no dataset with given identifier exists or if the
specified column is unknown or the target position invalid.
"""
# Get dataset. Raise exception if dataset is unknown
# Make sure that position is a valid column index in the new dataset
if position < 0 or position > len(self.columns):
raise ValueError('invalid target position \'' + str(position) + '\'')
# Get index position of column that is being moved
source_idx = self.column_index(name)
# No need to do anything if source position equals target position
if source_idx != position:
self.columns.insert(position, self.columns.pop(source_idx))
for row in self.rows:
row.values.insert(position, row.values.pop(source_idx))
row.caveats.insert(position, row.caveats.pop(source_idx))
self.add_delta(
id=VIZUAL_MOVE_COLUMN,
column=source_idx,
position=position
)
@property
def rows(self):
"""Fetch rows on demand.
"""
return self._rows
def to_bokeh(self, columns: Optional[List[str]] = None):
"""Convert the dataset to a bokeh ColumnDataSource
"""
if columns is None:
columns = [
col.name if col.name is not None else "column_{}".format(col.identifier)
for col in self.columns
]
return ColumnDataSource({
column.name:
[row.get_value(
column.identifier if column.identifier >= 0 else column.name
) for row in self.rows
]
for column in self.columns
})
def show_map(self,
lat_col: Any,
lon_col: Any,
label_col: Optional[Any] = None,
center_lat: Optional[float] = None,
center_lon: Optional[float] = None,
zoom: int = 8,
height: str = "500",
map_provider: str = 'OSM'
) -> None:
import numpy as np # type: ignore[import]
width = "100%"
addrpts: List[Any] = list()
lats = []
lons = []
for row in self.rows:
lon, lat = float(row.get_value(lon_col)), float(row.get_value(lat_col))
lats.append(lat)
lons.append(lon)
if map_provider == 'Google':
addrpts.append({"lat": str(lat), "lng": str(lon)})
elif map_provider == 'OSM':
label = ''
if label_col is not None:
label = str(row.get_value(label_col))
rowstr = '[' + str(lat) + ', ' + \
str(lon) + ', \'' + \
label + '\']'
addrpts.append(rowstr)
if center_lat is None:
center_lat = cast(float, np.mean(lats))
if center_lon is None:
center_lon = cast(float, np.mean(lons))
if map_provider == 'Google':
import json
from pycell.wrappers import GoogleMapClusterWrapper
html = GoogleMapClusterWrapper().do_output(json.dumps(addrpts), center_lat, center_lon, zoom, width, height)
self.client.show_html(html)
elif map_provider == 'OSM':
from pycell.wrappers import LeafletClusterWrapper
html = LeafletClusterWrapper().do_output(addrpts, center_lat, center_lon, zoom, width, height)
self.client.show_html(html)
else:
print("Unknown map provider: please specify: OSM or Google")
def show_d3_plot(self, chart_type, keys=list(), labels=list(), labels_inner=list(), value_cols=list(), key_col='KEY', width=600, height=400, title='', subtitle='', legend_title='Legend', x_cols=list(), y_cols=list(), date_cols=list(), open_cols=list(), high_cols=list(), low_cols=list(), close_cols=list(), volume_cols=list(), key=None):
from pycell.wrappers import D3ChartWrapper
charttypes = ["table", "bar", "bar_stacked", "bar_horizontal", "bar_circular", "bar_cluster", "donut",
"polar", "heat_rad", "heat_table", "punch", "bubble", "candle", "line", "radar", "rose"]
if chart_type not in charttypes:
print(("Please specify a valid chart type: one of: " + str(charttypes)))
return
if not labels:
labels = keys
if not labels_inner:
labels_inner = value_cols
data = []
for key_idx, label in enumerate(labels):
entry = {}
entry['key'] = label
entry['values'] = []
for idx, label_inner in enumerate(labels_inner):
inner_entry = {}
inner_entry['key'] = label_inner
for row in self.rows:
if len(keys) == 0 or (len(keys) >= key_idx and row.get_value(key_col) == keys[key_idx]):
if value_cols and len(value_cols) >= idx:
inner_entry['value'] = row.get_value(value_cols[idx])
if x_cols and len(x_cols) >= idx:
inner_entry['x'] = row.get_value(x_cols[idx])
if y_cols and len(y_cols) >= idx:
inner_entry['y'] = row.get_value(y_cols[idx])
if date_cols and len(date_cols) >= idx:
inner_entry['date'] = row.get_value(date_cols[idx])
if open_cols and len(open_cols) >= idx:
inner_entry['open'] = row.get_value(open_cols[idx])
if high_cols and len(high_cols) >= idx:
inner_entry['high'] = row.get_value(high_cols[idx])
if low_cols and len(low_cols) >= idx:
inner_entry['low'] = row.get_value(low_cols[idx])
if close_cols and len(close_cols) >= idx:
inner_entry['close'] = row.get_value(close_cols[idx])
if volume_cols and len(volume_cols) >= idx:
inner_entry['volume'] = row.get_value(volume_cols[idx])
entry['values'].append(inner_entry)
data.append(entry)
if key is not None:
data = data[data.index(key)]
html = D3ChartWrapper().do_output(data=data, charttype=chart_type, width=str(width), height=str(height),
title=title, subtitle=subtitle, legendtitle=legend_title)
self.client.show_html(html)
def show(self):
self.client.show(self)
def to_json(self, limit: Optional[int] = None):
rows = self._rows
if limit is not None:
rows = rows[:limit]
return {
"schema": [
{
"name": col.name,
"type": col.data_type
} for col in self.columns
],
"data": [
[
export_from_native_type(v, c.data_type, c.name)
for (v, c) in zip(row.values, self.columns)
]
for row in rows
],
"prov": [row.identifier for row in rows],
"colTaint": [row.caveats if hasattr(row, 'caveats') else [] for row in rows],
"rowTaint": [row.row_caveat for row in rows],
"properties": self._properties
}
def collabel_2_index(label):
"""Convert a column label into a column index (based at 0), e.g., 'A'-> 1,
'B' -> 2, ..., 'AA' -> 27, etc.
Returns -1 if the given labe is not composed only of upper case letters
A-Z.
"""
# The following code is adopted from
# https://stackoverflow.com/questions/7261936/convert-an-excel-or-spreadsheet-column-letter-to-its-number-in-pythonic-fashion
num = 0
for c in label:
if ord('A') <= ord(c) <= ord('Z'):
num = num * 26 + (ord(c) - ord('A')) + 1
else:
return -1
return num
def import_to_native_type(value: Any, data_type: str) -> Any:
if value is None:
return None
elif data_type == DATATYPE_GEOMETRY:
from shapely import wkt # type: ignore[import]
return wkt.loads(value)
elif data_type == DATATYPE_DATETIME:
from datetime import datetime
return datetime.fromisoformat(value)
elif data_type == DATATYPE_DATE:
from datetime import date
return date.fromisoformat(value)
else:
return value
def export_from_native_type(value: Any, data_type: str, context = "the value") -> Any:
assert_type(value, data_type, context)
if value is None:
return None
elif data_type == DATATYPE_GEOMETRY:
from shapely.geometry import asShape
return asShape(value).wkt
elif data_type == DATATYPE_DATETIME or data_type == DATATYPE_DATE:
return value.isoformat()
else:
return value
def assert_type(value: Any, data_type: str, context = "the value") -> Any:
if value is None:
return value
elif data_type == DATATYPE_DATE:
import datetime
if not isinstance(value, datetime.date):
raise ValueError(f"{context} ({value}) is a {type(value)} but should be a date")
return value
elif data_type == DATATYPE_DATETIME:
import datetime
if not isinstance(value, datetime.datetime):
raise ValueError(f"{context} ({value}) is a {type(value)} but should be a datetime")
return value
elif data_type == DATATYPE_INT or data_type == DATATYPE_SHORT or data_type == DATATYPE_LONG:
if not isinstance(value, int):
raise ValueError(f"{context} ({value}) is a {type(value)} but should be an int")
return value
elif data_type == DATATYPE_REAL:
if not isinstance(value, | |
if a string column happens to be an ID column #######
#### DO NOT Add this to ID_VARS yet. It will be done later.. Dont change it easily...
#### Category DTYPE vars are very special = they can be left as is and not disturbed in Python. ###
var_df['dcat'] = var_df.apply(lambda x: 1 if str(x['type_of_column'])=='category' else 0,
axis=1)
factor_vars = list(var_df[(var_df['dcat'] ==1)]['index'])
sum_all_cols['factor_vars'] = factor_vars
########################################################################
date_or_id = var_df.apply(lambda x: 1 if x['type_of_column'] in [np.uint8,
np.uint16, np.uint32, np.uint64,
'int8','int16',
'int32','int64'] and x[
'index'] not in string_bool_vars+num_bool_vars+discrete_string_vars+nlp_vars+date_vars else 0,
axis=1)
######### This is where we figure out whether a numeric col is date or id variable ###
var_df['int'] = 0
### if a particular column is date-time type, now set it as a date time variable ##
var_df['date_time'] = var_df.apply(lambda x: 1 if x['type_of_column'] in ['<M8[ns]','datetime64[ns]'] and x[
'index'] not in string_bool_vars+num_bool_vars+discrete_string_vars+nlp_vars else 1 if x['date_time']==1 else 0,
axis=1)
### this is where we save them as date time variables ###
if len(var_df.loc[date_or_id==1]) != 0:
for col in var_df.loc[date_or_id==1]['index'].values.tolist():
if len(train[col].value_counts()) == len(train):
if train[col].min() < 1900 or train[col].max() > 2050:
var_df.loc[var_df['index']==col,'id_col'] = 1
else:
try:
pd.to_datetime(train[col],infer_datetime_format=True)
var_df.loc[var_df['index']==col,'date_time'] = 1
except:
var_df.loc[var_df['index']==col,'id_col'] = 1
else:
if train[col].min() < 1900 or train[col].max() > 2050:
if col not in num_bool_vars:
var_df.loc[var_df['index']==col,'int'] = 1
else:
try:
pd.to_datetime(train[col],infer_datetime_format=True)
var_df.loc[var_df['index']==col,'date_time'] = 1
except:
if col not in num_bool_vars:
var_df.loc[var_df['index']==col,'int'] = 1
else:
pass
int_vars = list(var_df[(var_df['int'] ==1)]['index'])
date_vars = list(var_df[(var_df['date_time'] == 1)]['index'])
id_vars = list(var_df[(var_df['id_col'] == 1)]['index'])
sum_all_cols['int_vars'] = int_vars
copy_date_vars = copy.deepcopy(date_vars)
###### In Tensorflow there is no need to create age variables from year-dates. Hence removing them!
for date_var in copy_date_vars:
if train[date_var].dtype in ['int16','int32','int64']:
if train[date_var].min() >= 1900 or train[date_var].max() <= 2050:
### if it is between these numbers, its probably a year so avoid adding it
date_items = train[date_var].dropna(axis=0).apply(str).apply(len).values
if all(date_items[0] == item for item in date_items):
if date_items[0] == 4:
print(' Changing %s from date-var to int-var' %date_var)
int_vars.append(date_var)
date_vars.remove(date_var)
continue
else:
date_items = train[date_var].dropna(axis=0).apply(str).apply(len).values
#### In some extreme cases, 4 digit date variables are not useful
if all(date_items[0] == item for item in date_items):
if date_items[0] == 4:
print(' Changing %s from date-var to discrete-string-var' %date_var)
discrete_string_vars.append(date_var)
date_vars.remove(date_var)
continue
#### This test is to make sure sure date vars are actually date vars
try:
pd.to_datetime(train[date_var],infer_datetime_format=True)
except:
##### if not a date var, then just add it to delete it from processing
cols_delete.append(date_var)
date_vars.remove(date_var)
sum_all_cols['date_vars'] = date_vars
sum_all_cols['id_vars'] = id_vars
sum_all_cols['cols_delete'] = cols_delete
## This is an EXTREMELY complicated logic for cat vars. Don't change it unless you test it many times!
var_df['numeric'] = 0
float_or_cat = var_df.apply(lambda x: 1 if x['type_of_column'] in ['float16',
'float32','float64'] else 0,
axis=1)
if len(var_df.loc[float_or_cat == 1]) > 0:
for col in var_df.loc[float_or_cat == 1]['index'].values.tolist():
if len(train[col].value_counts()) > 2 and len(train[col].value_counts()
) <= float_limit and len(train[col].value_counts()) <= len(train):
var_df.loc[var_df['index']==col,'cat'] = 1
else:
if col not in num_bool_vars:
var_df.loc[var_df['index']==col,'numeric'] = 1
cat_vars = list(var_df[(var_df['cat'] ==1)]['index'])
continuous_vars = list(var_df[(var_df['numeric'] ==1)]['index'])
######## V E R Y I M P O R T A N T ###################################################
##### There are a couple of extra tests you need to do to remove abberations in cat_vars ###
cat_vars_copy = copy.deepcopy(cat_vars)
for cat in cat_vars_copy:
if df_preds[cat].dtype==float:
continuous_vars.append(cat)
cat_vars.remove(cat)
var_df.loc[var_df['index']==cat,'cat'] = 0
var_df.loc[var_df['index']==cat,'numeric'] = 1
elif len(df_preds[cat].value_counts()) == df_preds.shape[0]:
id_vars.append(cat)
cat_vars.remove(cat)
var_df.loc[var_df['index']==cat,'cat'] = 0
var_df.loc[var_df['index']==cat,'id_col'] = 1
sum_all_cols['cat_vars'] = cat_vars
sum_all_cols['continuous_vars'] = continuous_vars
sum_all_cols['id_vars'] = id_vars
cols_delete = find_remove_duplicates(cols_delete+id_vars)
sum_all_cols['cols_delete'] = cols_delete
###### This is where you consoldate the numbers ###########
var_dict_sum = dict(zip(var_df.values[:,0], var_df.values[:,2:].sum(1)))
for col, sumval in var_dict_sum.items():
if sumval == 0:
print('%s of type=%s is not classified' %(col,train[col].dtype))
elif sumval > 1:
print('%s of type=%s is classified into more then one type' %(col,train[col].dtype))
else:
pass
############### This is where you print all the types of variables ##############
####### Returns 8 vars in the following order: continuous_vars,int_vars,cat_vars,
### string_bool_vars,discrete_string_vars,nlp_vars,date_or_id_vars,cols_delete
cat_vars_copy = copy.deepcopy(cat_vars)
for each_cat in cat_vars_copy:
if len(train[each_cat].value_counts()) > cat_limit:
discrete_string_vars.append(each_cat)
cat_vars.remove(each_cat)
sum_all_cols['cat_vars'] = cat_vars
sum_all_cols['discrete_string_vars'] = discrete_string_vars
######### The variables can now be printed ##############
if verbose == 1:
print(" Number of Numeric Columns = ", len(continuous_vars))
print(" Number of Integer-Categorical Columns = ", len(int_vars))
print(" Number of String-Categorical Columns = ", len(cat_vars))
print(" Number of Factor-Categorical Columns = ", len(factor_vars))
print(" Number of String-Boolean Columns = ", len(string_bool_vars))
print(" Number of Numeric-Boolean Columns = ", len(num_bool_vars))
print(" Number of Discrete String Columns = ", len(discrete_string_vars))
print(" Number of NLP String Columns = ", len(nlp_vars))
print(" Number of Date Time Columns = ", len(date_vars))
print(" Number of ID Columns = ", len(id_vars))
print(" Number of Columns to Delete = ", len(cols_delete))
if verbose == 2:
marthas_columns(df_preds,verbose=1)
if verbose >=1 and orig_cols_total > max_cols_to_print:
print(" Numeric Columns: %s" %continuous_vars[:max_cols_to_print])
print(" Integer-Categorical Columns: %s" %int_vars[:max_cols_to_print])
print(" String-Categorical Columns: %s" %cat_vars[:max_cols_to_print])
print(" Factor-Categorical Columns: %s" %factor_vars[:max_cols_to_print])
print(" String-Boolean Columns: %s" %string_bool_vars[:max_cols_to_print])
print(" Numeric-Boolean Columns: %s" %num_bool_vars[:max_cols_to_print])
print(" Discrete String Columns: %s" %discrete_string_vars[:max_cols_to_print])
print(" NLP text Columns: %s" %nlp_vars[:max_cols_to_print])
print(" Date Time Columns: %s" %date_vars[:max_cols_to_print])
print(" ID Columns: %s" %id_vars[:max_cols_to_print])
print(" Columns that will not be considered in modeling: %s" %cols_delete[:max_cols_to_print])
##### now collect all the column types and column names into a single dictionary to return!
#### Since cols_delete and id_vars have the same columns, you need to subtract id_vars from this!
len_sum_all_cols = reduce(add,[len(v) for v in sum_all_cols.values()]) - len(id_vars)
if len_sum_all_cols == orig_cols_total:
print(' %d Predictors classified...' %orig_cols_total)
#print(' This does not include the Target column(s)')
else:
print('Number columns classified %d does not match %d total cols. Continuing...' %(
len_sum_all_cols, orig_cols_total))
ls = sum_all_cols.values()
flat_list = [item for sublist in ls for item in sublist]
if len(left_subtract(list(train),flat_list)) == 0:
print(' Missing columns = None')
else:
print(' Missing columns = %s' %left_subtract(list(train),flat_list))
return sum_all_cols
#################################################################################
from collections import defaultdict
def nested_dictionary():
return defaultdict(nested_dictionary)
############################################################################################
def check_model_options(model_options, name, default):
try:
if model_options[name]:
value = model_options[name]
else:
value = default
except:
value = default
return value
#####################################################################################
def classify_features_using_pandas(data_sample, target, model_options={}, verbose=0):
"""
If you send in a small pandas dataframe with the name of target variable(s), you will get back
all the features classified by type such as dates, cats, ints, floats and nlps. This is all done using pandas.
"""
###### This is where you get the cat_vocab_dict is created in the form of feats_max_min #####
feats_max_min = nested_dictionary()
print_features = False
nlps = []
bools = []
### if a variable has more than this many chars, it will be treated like a NLP variable
nlp_char_limit = check_model_options(model_options, "nlp_char_limit", 30)
### if a variable has more than this limit, it will not be treated like a cat variable #
cat_limit = check_model_options(model_options, "variable_cat_limit", 30)
### Classify features using the previously define function #############
var_df1 = classify_features(data_sample, target, model_options, verbose=verbose)
dates = var_df1['date_vars']
cats = var_df1['categorical_vars']
discrete_strings = var_df1['discrete_string_vars']
lats = var_df1['lat_vars']
lons = var_df1['lon_vars']
ignore_variables = var_df1['cols_delete']
all_ints = var_df1['int_vars']
if isinstance(target, list):
preds = [x for x in list(data_sample) if x not in target+ignore_variables]
feats_max_min['predictors_in_train'] = [x for x in list(data_sample) if x not in target]
else:
preds = [x for x in list(data_sample) if x not in [target]+ignore_variables]
feats_max_min['predictors_in_train'] = [x for x in list(data_sample) if x not in [target]]
#### Take(1) always displays only one batch only if num_epochs is set to 1 or a number. Otherwise No print! ########
#### If you execute the below code without take, then it will go into an infinite loop if num_epochs was set to None.
if verbose >= 1 and target:
print(f"printing first five values of {target}: {data_sample[target].values[:5]}")
if len(preds) <= 30:
print_features = True
if print_features and verbose > 1:
print("printing features and their max, min, datatypes in one batch ")
###### Now we do the creation of cat_vocab_dict though it is called feats_max_min here #####
floats = []
for key in preds:
if data_sample[key].dtype in ['object'] or str(data_sample[key].dtype) == 'category':
feats_max_min[key]["dtype"] = "string"
elif | |
<reponame>petrpavlu/storepass
# Copyright (C) 2019-2020 <NAME> <<EMAIL>>
# SPDX-License-Identifier: MIT
"""StorePass command-line interface."""
import argparse
import getpass
import logging
import os
import sys
import storepass.exc
import storepass.model
import storepass.storage
import storepass.utils
from storepass.cli import view
_logger = logging.getLogger(__name__)
_NAME_TO_ENTRY_TYPE_MAP = {
cls.entry_type_name: cls
for cls in storepass.model.ENTRY_TYPES
}
class _EntryGenerator:
"""Generator to create a new entry."""
def __init__(self, name):
"""Initialize an entry generator."""
self.type_cls = None
self.name = name
self.description = None
self.updated = None
self.notes = None
self.properties = {}
def _normalize_argument(self, value):
"""Normalize an argument value to None if it is an empty string."""
return storepass.utils.normalize_empty_to_none(value)
def _update_property(self, field, value):
"""Update the value of a specified property."""
if value is not None:
self.properties[field] = value
elif field in self.properties:
del self.properties[field]
def set_from_entry(self, entry):
"""Update properties from an existing entry."""
self.type_cls = type(entry)
self.description = entry.description
self.updated = entry.updated
self.notes = entry.notes
for field in entry.entry_fields:
self._update_property(field, entry.properties[field])
def set_from_args(self, args):
"""Update properties from command-line arguments."""
if args.type is not None:
self.type_cls = _NAME_TO_ENTRY_TYPE_MAP[args.type]
# Process options valid for all entries.
if args.description is not None:
self.description = self._normalize_argument(args.description)
if args.notes is not None:
self.notes = self._normalize_argument(args.notes)
# Process entry-specific options.
for field, value in args.properties.items():
if field.is_protected:
value = getpass.getpass(f"Entry {field.name}: ")
self._update_property(field, self._normalize_argument(value))
# Finally, set the updated timestamp.
self.updated = storepass.utils.get_current_datetime()
def get_entry(self):
"""Obtain a new entry based on the set properties."""
# Filter out any fields that are invalid for the type of a new entry.
properties = {
field: value
for field, value in self.properties.items()
if field in self.type_cls.entry_fields
}
return self.type_cls.from_proxy(self.name, self.description,
self.updated, self.notes, properties)
def _check_entry_name(args):
"""Validate an entry name specified on the command line."""
# Reject an empty entry name.
if args.entry == '':
print("Specified entry name is empty", file=sys.stderr)
return 1
return 0
def _validate_show_command(args):
"""Pre-validate command-line options for the show command."""
return _check_entry_name(args)
def _validate_add_command(args):
"""Pre-validate command-line options for the add command."""
res = _check_entry_name(args)
if res != 0:
return res
return _check_property_arguments(args, args.type)
def _validate_delete_command(args):
"""Pre-validate command-line options for the delete command."""
return _check_entry_name(args)
def _validate_edit_command(args):
"""Pre-validate command-line options for the edit command."""
res = _check_entry_name(args)
if res != 0:
return res
# If no new type is specified on the command line then leave validation of
# property arguments to _process_edit_command() when a type of the existing
# entry is determined.
if args.type is None:
return 0
return _check_property_arguments(args, args.type)
def _process_init_command(args, _model):
"""Handle the init command: create an empty password database."""
assert args.command == 'init'
# Keep the model empty and let the main() function write out the database.
return 0
def _process_list_command(args, model):
"""Handle the list command: print short information about all entries."""
assert args.command == 'list'
plain_view = view.ListView()
model.visit_all(plain_view)
return 0
def _process_show_command(args, model):
"""Handle the show command: print detailed information about one entry."""
assert args.command == 'show'
# Find the entry specified on the command line.
try:
path_spec = storepass.model.path_string_to_spec(args.entry)
entry = model.get_entry(path_spec)
except storepass.exc.ModelException as e:
print(f"{e}", file=sys.stderr)
return 1
detail_view = view.DetailView()
entry.accept(detail_view, single=True)
return 0
def _process_add_command(args, model):
"""Handle the add command: insert a new password entry."""
assert args.command == 'add'
# Create the entry specified on the command line.
try:
path_spec = storepass.model.path_string_to_spec(args.entry)
except storepass.exc.ModelException as e:
print(f"{e}", file=sys.stderr)
return 1
generator = _EntryGenerator(path_spec[-1])
generator.set_from_args(args)
new_entry = generator.get_entry()
# Insert the new entry in the model.
try:
parent_entry = model.get_entry(path_spec[:-1])
model.add_entry(new_entry, parent_entry)
except storepass.exc.ModelException as e:
print(f"{e}", file=sys.stderr)
return 1
return 0
def _process_edit_command(args, model):
"""Handle the edit command: modify an existing password entry."""
assert args.command == 'edit'
# Find the entry specified on the command line.
try:
path_spec = storepass.model.path_string_to_spec(args.entry)
old_entry = model.get_entry(path_spec)
except storepass.exc.ModelException as e:
print(f"{e}", file=sys.stderr)
return 1
# If no new type is specified then validate that property arguments are
# valid for the existing type.
if args.type is None:
res = _check_property_arguments(args, type(old_entry))
if res != 0:
return res
# Create a replacement entry.
generator = _EntryGenerator(path_spec[-1])
generator.set_from_entry(old_entry)
generator.set_from_args(args)
new_entry = generator.get_entry()
# Update the entry in the model.
try:
model.replace_entry(old_entry, new_entry)
except storepass.exc.ModelException as e:
print(f"{e}", file=sys.stderr)
return 1
return 0
def _process_delete_command(args, model):
"""Handle the delete command: remove a single password entry."""
assert args.command == 'delete'
# Delete the entry specified on the command line.
try:
path_spec = storepass.model.path_string_to_spec(args.entry)
entry = model.get_entry(path_spec)
model.remove_entry(entry)
except storepass.exc.ModelException as e:
print(f"{e}", file=sys.stderr)
return 1
return 0
def _process_dump_command(args, storage):
"""Handle the dump command: print the raw XML content of a database."""
assert args.command == 'dump'
# Load the database content.
try:
plain_data = storage.read_plain()
except storepass.exc.StorageReadException as e:
print(f"Failed to load password database '{args.file}': {e}",
file=sys.stderr)
return 1
# Print the content.
end = "" if len(plain_data) > 0 and plain_data[-1] == "\n" else "\n"
print(plain_data, end=end)
return 0
def _check_property_arguments(args, type_):
"""
Check validity of specified property arguments for a given entry type.
Check that all type-related options specified on the command line are valid
for a given entry type. An error is logged if some option is not available.
Returns 0 if the check was successful, or 1 on failure.
"""
assert args.command in ('add', 'edit')
# Determine the entry class. It can be either specified via its name or
# directly.
if isinstance(type_, str):
entry_cls = _NAME_TO_ENTRY_TYPE_MAP[type_]
else:
assert issubclass(type_, storepass.model.Entry)
entry_cls = type_
res = 0
for field in storepass.model.ENTRY_FIELDS:
if field in args.properties and field not in entry_cls.entry_fields:
print(
f"Property '{field.name}' is not valid for entry type "
f"'{entry_cls.entry_type_name}'",
file=sys.stderr)
res = 1
return res
class _ArgumentParser(argparse.ArgumentParser):
"""Command-line argument parser."""
def error(self, message):
"""Report a specified error message and exit the program."""
self.exit(2, f"Input error: {message}\n")
class _PropertyAction(argparse.Action):
"""Command-line property action."""
def __init__(self, option_strings, dest, field, **kwargs):
super().__init__(option_strings, dest, **kwargs)
self._field = field
def __call__(self, parser, namespace, values, option_string=None):
namespace.properties[self._field] = values
def _build_parser():
"""Create and initialize a command-line parser."""
parser = _ArgumentParser()
parser.add_argument(
'-f',
'--file',
metavar='PASSDB',
default=os.path.join(os.path.expanduser('~'), '.storepass.db'),
help="password database file (the default is ~/.storepass.db)")
parser.add_argument('-v',
'--verbose',
action='count',
help="increase verbosity level")
# Add sub-commands.
subparsers = parser.add_subparsers(dest='command')
_init_parser = subparsers.add_parser(
'init', description="create a new empty database")
_list_parser = subparsers.add_parser('list',
description="list password entries")
show_parser = subparsers.add_parser(
'show', description="display details of a password entry")
argument_validity = [(name, [field.name for field in cls.entry_fields])
for name, cls in _NAME_TO_ENTRY_TYPE_MAP.items()]
add_edit_epilog = "property validity for entry types:\n" + "\n".join([
f" {name + ':':22}{', '.join(args) if len(args) > 0 else '--'}"
for name, args in argument_validity
])
add_parser = subparsers.add_parser(
'add',
description="add a new password entry",
epilog=add_edit_epilog,
formatter_class=argparse.RawDescriptionHelpFormatter)
edit_parser = subparsers.add_parser(
'edit',
description="edit an existing password entry",
epilog=add_edit_epilog,
formatter_class=argparse.RawDescriptionHelpFormatter)
delete_parser = subparsers.add_parser(
'delete', description="delete a password entry")
_dump_parser = subparsers.add_parser(
'dump', description="dump raw database content")
add_parser.add_argument('--type',
choices=_NAME_TO_ENTRY_TYPE_MAP.keys(),
default='generic',
help="entry type (the default is generic)")
edit_parser.add_argument('--type',
choices=_NAME_TO_ENTRY_TYPE_MAP.keys(),
help="entry type")
# Add command-line arguments to set entry properties.
for sub_parser in (add_parser, edit_parser):
common_group = sub_parser.add_argument_group(
"optional arguments valid for all entry types")
common_group.add_argument(
'--description',
metavar='DESC',
help="set the entry description to the specified value")
common_group.add_argument(
'--notes', help="set the entry notes to the specified value")
account_group = sub_parser.add_argument_group(
"optional arguments valid for specific entry types")
sub_parser.set_defaults(properties={})
for field in storepass.model.ENTRY_FIELDS:
if field.is_protected:
nargs = 0
help_ = f"prompt for a value of the {field.name} property"
else:
nargs = None
help_ = f"set the {field.name} property to the specified value"
account_group.add_argument(
'--' + field.name,
metavar="VALUE",
action=_PropertyAction,
field=field,
nargs=nargs,
#default=argparse.SUPPRESS,
help=help_)
for sub_parser in (show_parser, add_parser, delete_parser, edit_parser):
sub_parser.add_argument('entry',
metavar='ENTRY',
help="password entry")
return parser
def main():
"""
Run the CLI interface.
Run the StorePass command-line interface. Returns 0 if the execution was
successful and a non-zero value otherwise.
"""
# Parse the command-line arguments.
parser = _build_parser()
try:
args = parser.parse_args()
except SystemExit as e:
return e.code
# Do further command-specific checks of the command-line options.
if args.command == 'show':
res = _validate_show_command(args)
elif args.command == 'add':
res = _validate_add_command(args)
elif args.command == 'delete':
res = _validate_delete_command(args)
elif args.command == 'edit':
res = _validate_edit_command(args)
else:
# No extra checks needed.
res = 0
# Bail out if any check failed.
if res != 0:
return res
# Set desired log verbosity.
| |
from typing import Any, Union
from prefect import Task
from prefect.engine.signals import FAIL
from prefect.utilities.tasks import defaults_from_attrs
class CreateContainer(Task):
"""
Task for creating a Docker container and optionally running a command.
Note that all initialization arguments can optionally be provided or overwritten at runtime.
Args:
- image_name (str, optional): Name of the image to run
- command (Union[list, str], optional): A single command or a list of commands to run
- detach (bool, optional): Run container in the background
- entrypoint (Union[str, list]): The entrypoint for the container
- environment (Union[dict, list]): Environment variables to set inside the container,
as a dictionary or a list of strings in the format ["SOMEVARIABLE=xxx"].
- docker_server_url (str, optional): URL for the Docker server. Defaults to
`unix:///var/run/docker.sock` however other hosts such as `tcp://0.0.0.0:2375`
can be provided
- **kwargs (dict, optional): additional keyword arguments to pass to the Task
constructor
"""
def __init__(
self,
image_name: str = None,
command: Union[list, str] = None,
detach: bool = False,
entrypoint: Union[list, str] = None,
environment: Union[list, dict] = None,
docker_server_url: str = "unix:///var/run/docker.sock",
**kwargs: Any
):
self.image_name = image_name
self.command = command
self.detach = detach
self.entrypoint = entrypoint
self.environment = environment
self.docker_server_url = docker_server_url
super().__init__(**kwargs)
@defaults_from_attrs(
"image_name",
"command",
"detach",
"entrypoint",
"environment",
"docker_server_url",
)
def run(
self,
image_name: str = None,
command: Union[list, str] = None,
detach: bool = False,
entrypoint: Union[list, str] = None,
environment: Union[list, dict] = None,
docker_server_url: str = "unix:///var/run/docker.sock",
) -> str:
"""
Task run method.
Args:
- image_name (str, optional): Name of the image to run
- command (Union[list, str], optional): A single command or a list of commands to run
- detach (bool, optional): Run container in the background
- entrypoint (Union[str, list]): The entrypoint for the container
- environment (Union[dict, list]): Environment variables to set inside the container,
as a dictionary or a list of strings in the format ["SOMEVARIABLE=xxx"].
- docker_server_url (str, optional): URL for the Docker server. Defaults to
`unix:///var/run/docker.sock` however other hosts such as `tcp://0.0.0.0:2375`
can be provided
Returns:
- str: A string representing the container id
Raises:
- ValueError: if `image_name` is `None`
"""
if not image_name:
raise ValueError("An image name must be provided.")
# 'import docker' is expensive time-wise, we should do this just-in-time to keep
# the 'import prefect' time low
import docker
client = docker.APIClient(base_url=docker_server_url, version="auto")
self.logger.debug(
"Starting to create container {} with command {}".format(
image_name, command
)
)
container = client.create_container(
image=image_name,
command=command,
detach=detach,
entrypoint=entrypoint,
environment=environment,
)
self.logger.debug(
"Completed created container {} with command {}".format(image_name, command)
)
return container.get("Id")
class GetContainerLogs(Task):
"""
Task for getting the logs of a Docker container. *Note:* This does not stream logs.
Note that all initialization arguments can optionally be provided or overwritten at runtime.
Args:
- container_id (str, optional): The id of a container to retrieve logs from
- docker_server_url (str, optional): URL for the Docker server. Defaults to
`unix:///var/run/docker.sock` however other hosts such as `tcp://0.0.0.0:2375`
can be provided
- **kwargs (dict, optional): additional keyword arguments to pass to the Task
constructor
"""
def __init__(
self,
container_id: str = None,
docker_server_url: str = "unix:///var/run/docker.sock",
**kwargs: Any
):
self.container_id = container_id
self.docker_server_url = docker_server_url
super().__init__(**kwargs)
@defaults_from_attrs("container_id", "docker_server_url")
def run(
self,
container_id: str = None,
docker_server_url: str = "unix:///var/run/docker.sock",
) -> str:
"""
Task run method.
Args:
- container_id (str, optional): The id of a container to retrieve logs from
- docker_server_url (str, optional): URL for the Docker server. Defaults to
`unix:///var/run/docker.sock` however other hosts such as `tcp://0.0.0.0:2375`
can be provided
Returns:
- str: A string representation of the logs from the container
Raises:
- ValueError: if `container_id` is `None`
"""
if not container_id:
raise ValueError("A container id must be provided.")
# 'import docker' is expensive time-wise, we should do this just-in-time to keep
# the 'import prefect' time low
import docker
self.logger.debug(
"Starting fetching container logs from container with id {}".format(
container_id
)
)
client = docker.APIClient(base_url=docker_server_url, version="auto")
api_result = client.logs(container=container_id).decode()
self.logger.debug(
"Completed fetching all container logs from container with id {}".format(
container_id
)
)
return api_result
class ListContainers(Task):
"""
Task for listing Docker containers.
Note that all initialization arguments can optionally be provided or overwritten at runtime.
Args:
- all_containers (bool, optional): Show all containers. Only running containers are shown by default
- docker_server_url (str, optional): URL for the Docker server. Defaults to
`unix:///var/run/docker.sock` however other hosts such as `tcp://0.0.0.0:2375`
can be provided
- **kwargs (dict, optional): additional keyword arguments to pass to the Task
constructor
"""
def __init__(
self,
all_containers: bool = False,
docker_server_url: str = "unix:///var/run/docker.sock",
**kwargs: Any
):
self.all_containers = all_containers
self.docker_server_url = docker_server_url
super().__init__(**kwargs)
@defaults_from_attrs("all_containers", "docker_server_url")
def run(
self,
all_containers: bool = False,
docker_server_url: str = "unix:///var/run/docker.sock",
) -> list:
"""
Task run method.
Args:
- all_containers (bool, optional): Show all containers. Only running containers are shown by default
- docker_server_url (str, optional): URL for the Docker server. Defaults to
`unix:///var/run/docker.sock` however other hosts such as `tcp://0.0.0.0:2375`
can be provided
Returns:
- list: A list of dicts, one per container
"""
# 'import docker' is expensive time-wise, we should do this just-in-time to keep
# the 'import prefect' time low
import docker
self.logger.debug("Starting to list containers")
client = docker.APIClient(base_url=docker_server_url, version="auto")
api_result = client.containers(all=all_containers)
self.logger.debug("Completed listing containers")
return api_result
class StartContainer(Task):
"""
Task for starting a Docker container that runs the (optional) command it was created with.
Note that all initialization arguments can optionally be provided or overwritten at runtime.
Args:
- container_id (str, optional): The id of a container to start
- docker_server_url (str, optional): URL for the Docker server. Defaults to
`unix:///var/run/docker.sock` however other hosts such as `tcp://0.0.0.0:2375`
can be provided
- **kwargs (dict, optional): additional keyword arguments to pass to the Task
constructor
"""
def __init__(
self,
container_id: str = None,
docker_server_url: str = "unix:///var/run/docker.sock",
**kwargs: Any
):
self.container_id = container_id
self.docker_server_url = docker_server_url
super().__init__(**kwargs)
@defaults_from_attrs("container_id", "docker_server_url")
def run(
self,
container_id: str = None,
docker_server_url: str = "unix:///var/run/docker.sock",
) -> None:
"""
Task run method.
Args:
- container_id (str, optional): The id of a container to start
- docker_server_url (str, optional): URL for the Docker server. Defaults to
`unix:///var/run/docker.sock` however other hosts such as `tcp://0.0.0.0:2375`
can be provided
Raises:
- ValueError: if `container_id` is `None`
"""
if not container_id:
raise ValueError("A container id must be provided.")
# 'import docker' is expensive time-wise, we should do this just-in-time to keep
# the 'import prefect' time low
import docker
self.logger.debug("Starting container with id {}".format(container_id))
client = docker.APIClient(base_url=docker_server_url, version="auto")
client.start(container=container_id)
self.logger.debug(
"Completed starting container with id {}".format(container_id)
)
class StopContainer(Task):
"""
Task for stopping a Docker container.
Note that all initialization arguments can optionally be provided or overwritten at runtime.
Args:
- container_id (str, optional): The id of a container to stop
- docker_server_url (str, optional): URL for the Docker server. Defaults to
`unix:///var/run/docker.sock` however other hosts such as `tcp://0.0.0.0:2375`
can be provided
- **kwargs (dict, optional): additional keyword arguments to pass to the Task
constructor
"""
def __init__(
self,
container_id: str = None,
docker_server_url: str = "unix:///var/run/docker.sock",
**kwargs: Any
):
self.container_id = container_id
self.docker_server_url = docker_server_url
super().__init__(**kwargs)
@defaults_from_attrs("container_id", "docker_server_url")
def run(
self,
container_id: str = None,
docker_server_url: str = "unix:///var/run/docker.sock",
) -> None:
"""
Task run method.
Args:
- container_id (str, optional): The id of a container to stop
- docker_server_url (str, optional): URL for the Docker server. Defaults to
`unix:///var/run/docker.sock` however other hosts such as `tcp://0.0.0.0:2375`
can be provided
Raises:
- ValueError: if `container_id` is `None`
"""
if not container_id:
raise ValueError("A container id must be provided.")
# 'import docker' is expensive time-wise, we should do this just-in-time to keep
# the 'import prefect' time low
import docker
self.logger.debug("Starting to stop container with id {}".format(container_id))
client = docker.APIClient(base_url=docker_server_url, version="auto")
client.stop(container=container_id)
self.logger.debug(
"Completed stopping container with id {}".format(container_id)
)
class WaitOnContainer(Task):
"""
Task for waiting on an already started Docker container.
Note that all initialization arguments can optionally be provided or | |
<filename>flopy/modflow/mf.py
"""
mf module. Contains the ModflowGlobal, ModflowList, and Modflow classes.
"""
import os
import flopy
from inspect import getfullargspec
from ..mbase import BaseModel
from ..pakbase import Package
from ..utils import mfreadnam
from ..discretization.structuredgrid import StructuredGrid
from ..discretization.grid import Grid
from flopy.discretization.modeltime import ModelTime
from .mfpar import ModflowPar
class ModflowGlobal(Package):
"""
ModflowGlobal Package class
"""
def __init__(self, model, extension="glo"):
Package.__init__(self, model, extension, "GLOBAL", 1)
return
def __repr__(self):
return "Global Package class"
def write_file(self):
# Not implemented for global class
return
class ModflowList(Package):
"""
ModflowList Package class
"""
def __init__(self, model, extension="list", unitnumber=2):
Package.__init__(self, model, extension, "LIST", unitnumber)
return
def __repr__(self):
return "List Package class"
def write_file(self):
# Not implemented for list class
return
class Modflow(BaseModel):
"""
MODFLOW Model Class.
Parameters
----------
modelname : string, optional
Name of model. This string will be used to name the MODFLOW input
that are created with write_model. (the default is 'modflowtest')
namefile_ext : string, optional
Extension for the namefile (the default is 'nam')
version : string, optional
Version of MODFLOW to use (the default is 'mf2005').
exe_name : string, optional
The name of the executable to use (the default is
'mf2005').
listunit : integer, optional
Unit number for the list file (the default is 2).
model_ws : string, optional
model workspace. Directory name to create model data sets.
(default is the present working directory).
external_path : string
Location for external files (default is None).
verbose : boolean, optional
Print additional information to the screen (default is False).
load : boolean, optional
(default is True).
silent : integer
(default is 0)
Attributes
----------
Methods
-------
See Also
--------
Notes
-----
Examples
--------
>>> import flopy
>>> m = flopy.modflow.Modflow()
"""
def __init__(
self,
modelname="modflowtest",
namefile_ext="nam",
version="mf2005",
exe_name="mf2005.exe",
structured=True,
listunit=2,
model_ws=".",
external_path=None,
verbose=False,
**kwargs
):
BaseModel.__init__(
self,
modelname,
namefile_ext,
exe_name,
model_ws,
structured=structured,
verbose=verbose,
**kwargs
)
self.version_types = {
"mf2k": "MODFLOW-2000",
"mf2005": "MODFLOW-2005",
"mfnwt": "MODFLOW-NWT",
"mfusg": "MODFLOW-USG",
}
self.set_version(version)
if self.version == "mf2k":
self.glo = ModflowGlobal(self)
self.lst = ModflowList(self, unitnumber=listunit)
# -- check if unstructured is specified for something
# other than mfusg is specified
if not self.structured:
assert (
"mfusg" in self.version
), "structured=False can only be specified for mfusg models"
# external option stuff
self.array_free_format = True
self.array_format = "modflow"
# self.external_fnames = []
# self.external_units = []
# self.external_binflag = []
self.load_fail = False
# the starting external data unit number
self._next_ext_unit = 1000
if external_path is not None:
if os.path.exists(os.path.join(model_ws, external_path)):
print(
"Note: external_path "
+ str(external_path)
+ " already exists"
)
else:
os.makedirs(os.path.join(model_ws, external_path))
self.external_path = external_path
self.verbose = verbose
self.mfpar = ModflowPar()
# output file info
self.hext = "hds"
self.dext = "ddn"
self.cext = "cbc"
self.hpth = None
self.dpath = None
self.cpath = None
# Create a dictionary to map package with package object.
# This is used for loading models.
self.mfnam_packages = {
"zone": flopy.modflow.ModflowZon,
"mult": flopy.modflow.ModflowMlt,
"ag": flopy.modflow.ModflowAg,
"pval": flopy.modflow.ModflowPval,
"bas6": flopy.modflow.ModflowBas,
"dis": flopy.modflow.ModflowDis,
"disu": flopy.modflow.ModflowDisU,
"bcf6": flopy.modflow.ModflowBcf,
"lpf": flopy.modflow.ModflowLpf,
"hfb6": flopy.modflow.ModflowHfb,
"chd": flopy.modflow.ModflowChd,
"fhb": flopy.modflow.ModflowFhb,
"wel": flopy.modflow.ModflowWel,
"mnw1": flopy.modflow.ModflowMnw1,
"mnw2": flopy.modflow.ModflowMnw2,
"mnwi": flopy.modflow.ModflowMnwi,
"drn": flopy.modflow.ModflowDrn,
"drt": flopy.modflow.ModflowDrt,
"rch": flopy.modflow.ModflowRch,
"evt": flopy.modflow.ModflowEvt,
"ghb": flopy.modflow.ModflowGhb,
"gmg": flopy.modflow.ModflowGmg,
"lmt6": flopy.modflow.ModflowLmt,
"lmt7": flopy.modflow.ModflowLmt,
"riv": flopy.modflow.ModflowRiv,
"str": flopy.modflow.ModflowStr,
"swi2": flopy.modflow.ModflowSwi2,
"pcg": flopy.modflow.ModflowPcg,
"pcgn": flopy.modflow.ModflowPcgn,
"nwt": flopy.modflow.ModflowNwt,
"pks": flopy.modflow.ModflowPks,
"sms": flopy.modflow.ModflowSms,
"sfr": flopy.modflow.ModflowSfr2,
"lak": flopy.modflow.ModflowLak,
"gage": flopy.modflow.ModflowGage,
"sip": flopy.modflow.ModflowSip,
"sor": flopy.modflow.ModflowSor,
"de4": flopy.modflow.ModflowDe4,
"oc": flopy.modflow.ModflowOc,
"uzf": flopy.modflow.ModflowUzf1,
"upw": flopy.modflow.ModflowUpw,
"sub": flopy.modflow.ModflowSub,
"swt": flopy.modflow.ModflowSwt,
"hyd": flopy.modflow.ModflowHyd,
"hob": flopy.modflow.ModflowHob,
"chob": flopy.modflow.ModflowFlwob,
"gbob": flopy.modflow.ModflowFlwob,
"drob": flopy.modflow.ModflowFlwob,
"rvob": flopy.modflow.ModflowFlwob,
"vdf": flopy.seawat.SeawatVdf,
"vsc": flopy.seawat.SeawatVsc,
}
return
def __repr__(self):
nrow, ncol, nlay, nper = self.get_nrow_ncol_nlay_nper()
if nrow is not None:
# structured case
s = (
"MODFLOW {} layer(s) {} row(s) {} column(s) "
"{} stress period(s)".format(nlay, nrow, ncol, nper)
)
else:
# unstructured case
nodes = ncol.sum()
nodelay = " ".join(str(i) for i in ncol)
print(nodelay, nlay, nper)
s = (
"MODFLOW unstructured\n"
" nodes = {}\n"
" layers = {}\n"
" periods = {}\n"
" nodelay = {}\n".format(nodes, nlay, nper, ncol)
)
return s
#
# def next_ext_unit(self):
# """
# Function to encapsulate next_ext_unit attribute
#
# """
# next_unit = self.__next_ext_unit + 1
# self.__next_ext_unit += 1
# return next_unit
@property
def modeltime(self):
# build model time
data_frame = {
"perlen": self.dis.perlen.array,
"nstp": self.dis.nstp.array,
"tsmult": self.dis.tsmult.array,
}
self._model_time = ModelTime(
data_frame,
self.dis.itmuni_dict[self.dis.itmuni],
self.dis.start_datetime,
self.dis.steady.array,
)
return self._model_time
@property
def modelgrid(self):
if not self._mg_resync:
return self._modelgrid
if self.has_package("bas6"):
ibound = self.bas6.ibound.array
else:
ibound = None
if self.get_package("disu") is not None:
self._modelgrid = Grid(
grid_type="USG-Unstructured",
top=self.disu.top,
botm=self.disu.bot,
idomain=ibound,
proj4=self._modelgrid.proj4,
epsg=self._modelgrid.epsg,
xoff=self._modelgrid.xoffset,
yoff=self._modelgrid.yoffset,
angrot=self._modelgrid.angrot,
)
print(
"WARNING: Model grid functionality limited for unstructured "
"grid."
)
else:
# build structured grid
self._modelgrid = StructuredGrid(
self.dis.delc.array,
self.dis.delr.array,
self.dis.top.array,
self.dis.botm.array,
ibound,
self.dis.lenuni,
proj4=self._modelgrid.proj4,
epsg=self._modelgrid.epsg,
xoff=self._modelgrid.xoffset,
yoff=self._modelgrid.yoffset,
angrot=self._modelgrid.angrot,
nlay=self.dis.nlay,
laycbd=self.dis.laycbd,
)
# resolve offsets
xoff = self._modelgrid.xoffset
if xoff is None:
if self._xul is not None:
xoff = self._modelgrid._xul_to_xll(self._xul)
else:
xoff = 0.0
yoff = self._modelgrid.yoffset
if yoff is None:
if self._yul is not None:
yoff = self._modelgrid._yul_to_yll(self._yul)
else:
yoff = 0.0
self._modelgrid.set_coord_info(
xoff,
yoff,
self._modelgrid.angrot,
self._modelgrid.epsg,
self._modelgrid.proj4,
)
self._mg_resync = not self._modelgrid.is_complete
return self._modelgrid
@modelgrid.setter
def modelgrid(self, value):
self._mg_resync = False
self._modelgrid = value
@property
def solver_tols(self):
if self.pcg is not None:
return self.pcg.hclose, self.pcg.rclose
elif self.nwt is not None:
return self.nwt.headtol, self.nwt.fluxtol
elif self.sip is not None:
return self.sip.hclose, -999
elif self.gmg is not None:
return self.gmg.hclose, self.gmg.rclose
return None
@property
def nlay(self):
if self.dis:
return self.dis.nlay
elif self.disu:
return self.disu.nlay
else:
return 0
@property
def nrow(self):
if self.dis:
return self.dis.nrow
else:
return 0
@property
def ncol(self):
if self.dis:
return self.dis.ncol
else:
return 0
@property
def nper(self):
if self.dis:
return self.dis.nper
elif self.disu:
return self.disu.nper
else:
return 0
@property
def ncpl(self):
if self.dis:
return self.dis.nrow * self.dis.ncol
elif self.disu:
return self.disu.ncpl
else:
return 0
@property
def nrow_ncol_nlay_nper(self):
# structured dis
dis = self.get_package("DIS")
if dis:
return dis.nrow, dis.ncol, dis.nlay, dis.nper
# unstructured dis
dis = self.get_package("DISU")
if dis:
return None, dis.nodelay.array[:], dis.nlay, dis.nper
# no dis
return 0, 0, 0, 0
def get_nrow_ncol_nlay_nper(self):
return self.nrow_ncol_nlay_nper
def get_ifrefm(self):
bas = self.get_package("BAS6")
if bas:
return bas.ifrefm
else:
return False
def set_ifrefm(self, value=True):
if not isinstance(value, bool):
print("Error: set_ifrefm passed value must be a boolean")
return False
self.array_free_format = value
bas = self.get_package("BAS6")
if bas:
bas.ifrefm = value
else:
return False
def _set_name(self, value):
# Overrides BaseModel's setter for name property
BaseModel._set_name(self, value)
if self.version == "mf2k":
for i in range(len(self.glo.extension)):
self.glo.file_name[i] = self.name + "." + self.glo.extension[i]
for i in range(len(self.lst.extension)):
self.lst.file_name[i] = self.name + "." + self.lst.extension[i]
def write_name_file(self):
"""
Write the model name file.
"""
fn_path = os.path.join(self.model_ws, self.namefile)
f_nam = open(fn_path, "w")
f_nam.write("{}\n".format(self.heading))
if self.structured:
f_nam.write("#" + str(self.modelgrid))
f_nam.write("; start_datetime:{0}\n".format(self.start_datetime))
if self.version == "mf2k":
if self.glo.unit_number[0] > 0:
f_nam.write(
"{:14s} {:5d} {}\n".format(
self.glo.name[0],
self.glo.unit_number[0],
self.glo.file_name[0],
)
)
f_nam.write(
"{:14s} {:5d} {}\n".format(
self.lst.name[0],
self.lst.unit_number[0],
self.lst.file_name[0],
)
)
f_nam.write("{}".format(self.get_name_file_entries()))
# write the external files
for u, f, b, o in zip(
self.external_units,
self.external_fnames,
self.external_binflag,
self.external_output,
):
if u == 0:
continue
replace_text = ""
if o:
replace_text = "REPLACE"
if b:
line = (
"DATA(BINARY) {0:5d} ".format(u)
+ f
+ replace_text
+ "\n"
)
f_nam.write(line)
else:
f_nam.write("DATA {0:5d} ".format(u) + f + "\n")
# write the output files
for u, f, b in zip(
self.output_units, self.output_fnames, self.output_binflag
):
if u == 0:
continue
if b:
f_nam.write(
"DATA(BINARY) {0:5d} ".format(u) + f + " REPLACE\n"
)
else:
f_nam.write("DATA {0:5d} ".format(u) + f + "\n")
# close the name file
f_nam.close()
return
def set_model_units(self, iunit0=None):
"""
Write the model name file.
"""
if iunit0 is None:
iunit0 = 1001
# initialize starting unit number
self.next_unit(iunit0)
if self.version == "mf2k":
# update global file unit number
if self.glo.unit_number[0] > 0:
self.glo.unit_number[0] = self.next_unit()
# update lst file unit number
self.lst.unit_number[0] = self.next_unit()
# update package unit numbers
for p in self.packagelist:
p.unit_number[0] = self.next_unit()
# update external unit numbers
for i, iu in enumerate(self.external_units):
if iu == 0:
continue
self.external_units[i] = self.next_unit()
# update output files unit numbers
oc = | |
**kwargs):
pass
def MDGContext_swigregister(*args, **kwargs):
pass
def MFnNurbsSurface_numNonZeroSpansInV(*args, **kwargs):
pass
def MFnNurbsCurve_findParamFromLength(*args, **kwargs):
pass
def MItSubdVertex_className(*args, **kwargs):
pass
def MFnMesh_swigregister(*args, **kwargs):
pass
def MFnMesh_extrudeEdges(*args, **kwargs):
pass
def MAngle_asAngMinutes(*args, **kwargs):
pass
def new_MMessage(*args, **kwargs):
pass
def MDataHandle_swiginit(*args, **kwargs):
pass
def delete_MBoundingBox(*args, **kwargs):
pass
def MItSubdVertex_setLevel(*args, **kwargs):
pass
def new_MItDependencyGraph(*args, **kwargs):
pass
def MProfiler_getCategoryName(*args, **kwargs):
pass
def new_MFloatPoint(*args, **kwargs):
pass
def MNodeClass_attribute(*args, **kwargs):
pass
def new_MFnVectorArrayData(*args, **kwargs):
pass
def MFnNumericData_setData2Int(*args, **kwargs):
pass
def MFnGeometryData_hasObjectGroup(*args, **kwargs):
pass
def MArgList_asInt(*args, **kwargs):
pass
def MQuaternion_assign(*args, **kwargs):
pass
def MDataHandle_numericType(*args, **kwargs):
pass
def MFnCompoundAttribute_addChild(*args, **kwargs):
pass
def MDGModifier_className(*args, **kwargs):
pass
def delete_MAttributePattern(*args, **kwargs):
pass
def MModelMessage_addAfterDuplicateCallback(*args, **kwargs):
pass
def MStreamUtils_stdOutStream(*args, **kwargs):
pass
def MFnSubd_edgeAdjacentPolygon(*args, **kwargs):
pass
def MFnCamera_zoom(*args, **kwargs):
pass
def MFnReflectShader_reflectivity(*args, **kwargs):
pass
def MFnCamera_setUsePivotAsLocalSpace(*args, **kwargs):
pass
def delete_MFnReference(*args, **kwargs):
pass
def MProfiler_removeCategory(*args, **kwargs):
pass
def MFnPointArrayData_swigregister(*args, **kwargs):
pass
def MFnGeometryData_addObjectGroup(*args, **kwargs):
pass
def MFnNonExtendedLight_depthMapResolution(*args, **kwargs):
pass
def MDistance_internalUnit(*args, **kwargs):
pass
def MFnAttribute_setChannelBox(*args, **kwargs):
pass
def MNodeClass_pluginName(*args, **kwargs):
pass
def MFnNurbsSurface_numRegions(*args, **kwargs):
pass
def new_MFnTransform(*args, **kwargs):
pass
def MColor_r_set(*args, **kwargs):
pass
def MTimeArray_setLength(*args, **kwargs):
pass
def MPlug_setAttribute(*args, **kwargs):
pass
def MTimerMessage_setSleepCallback(*args, **kwargs):
pass
def MFnMesh_stringBlindDataComponentId(*args, **kwargs):
pass
def MDGMessage_addDelayedTimeChangeRunupCallback(*args, **kwargs):
pass
def MConnectDisconnectAttrEdit_isConnection(*args, **kwargs):
pass
def MItEdits_isReverse(*args, **kwargs):
pass
def MFnMesh_currentUVSetName(*args, **kwargs):
pass
def MFnStringArrayData_create(*args, **kwargs):
pass
def MFnContainerNode_className(*args, **kwargs):
pass
def MSelectionList_getSelectionStrings(*args, **kwargs):
pass
def MProfilingScope_swiginit(*args, **kwargs):
pass
def MFloatVector_x_get(*args, **kwargs):
pass
def MGlobal_getRichSelection(*args, **kwargs):
pass
def MFnNurbsSurface_getCV(*args, **kwargs):
pass
def MFnNonExtendedLight_setShadowRadius(*args, **kwargs):
pass
def delete_MItSurfaceCV(*args, **kwargs):
pass
def delete_MFnMesh(*args, **kwargs):
pass
def MAngle_setValue(*args, **kwargs):
pass
def MDataHandle_asGenericInt(*args, **kwargs):
pass
def MItMeshPolygon_getUVSetNames(*args, **kwargs):
pass
def MItSubdEdge_isDone(*args, **kwargs):
pass
def MFileObject_pathCount(*args, **kwargs):
pass
def MItDependencyGraph_currentTraversal(*args, **kwargs):
pass
def MFloatPointArray_assign(*args, **kwargs):
pass
def MFnVectorArrayData_swiginit(*args, **kwargs):
pass
def MFnSet_getUnion(*args, **kwargs):
pass
def MFnGenericAttribute_addDataAccept(*args, **kwargs):
pass
def MFnSubdNames_levelOneFaceAsLong(*args, **kwargs):
pass
def MColorArray_setLength(*args, **kwargs):
pass
def MUintArray___iadd__(*args, **kwargs):
pass
def MInt64Array_append(*args, **kwargs):
pass
def MScriptUtil_setFloat4ArrayItem(*args, **kwargs):
pass
def MEulerRotation_swigregister(*args, **kwargs):
pass
def MFnSingleIndexedComponent_setCompleteData(*args, **kwargs):
pass
def MDGModifier_newPlugValueChar(*args, **kwargs):
pass
def MAttributePattern_addRootAttr(*args, **kwargs):
pass
def delete_MMatrixArray(*args, **kwargs):
pass
def delete_MUuid(*args, **kwargs):
pass
def MSyntax_swiginit(*args, **kwargs):
pass
def MFnCamera_setHorizontalShake(*args, **kwargs):
pass
def MFnLambertShader_translucenceCoeff(*args, **kwargs):
pass
def MTime_value(*args, **kwargs):
pass
def MURI_addQueryItem(*args, **kwargs):
pass
def MMeshSmoothOptions_divisions(*args, **kwargs):
pass
def new_MFnPluginData(*args, **kwargs):
pass
def MFnNonAmbientLight_decayRate(*args, **kwargs):
pass
def MDistance_unit(*args, **kwargs):
pass
def MFnAttribute_isWorldSpace(*args, **kwargs):
pass
def MUuid_assign(*args, **kwargs):
pass
def MFnNurbsSurface_removeOneKnotInU(*args, **kwargs):
pass
def MFnAssembly_setRepName(*args, **kwargs):
pass
def intPtr_value(*args, **kwargs):
pass
def MFnMesh_getVertexNormals(*args, **kwargs):
pass
def delete_MEdit(*args, **kwargs):
pass
def MFnCameraSet_getLayerSceneData(*args, **kwargs):
pass
def delete_MDagPath(*args, **kwargs):
pass
def MFnMesh_setEdgeSmoothing(*args, **kwargs):
pass
def MFnLight_setColor(*args, **kwargs):
pass
def MFnTransform_setRotationOrder(*args, **kwargs):
pass
def array4dInt_get(*args, **kwargs):
pass
def MFnNonExtendedLight_setUseDepthMapShadows(*args, **kwargs):
pass
def MFnDirectionalLight_shadowAngle(*args, **kwargs):
pass
def MFloatVector___neg__(*args, **kwargs):
pass
def MQuaternion_get(*args, **kwargs):
pass
def new_MFnNurbsSurfaceData(*args, **kwargs):
pass
def MItSurfaceCV_getIndex(*args, **kwargs):
pass
def MFnDoubleIndexedComponent_getCompleteData(*args, **kwargs):
pass
def MFnMatrixData_className(*args, **kwargs):
pass
def MFnSet_addMember(*args, **kwargs):
pass
def MItMeshFaceVertex_swigregister(*args, **kwargs):
pass
def MItSelectionList_getPlug(*args, **kwargs):
pass
def new_MFileObject(*args, **kwargs):
pass
def MItMeshPolygon_swigregister(*args, **kwargs):
pass
def MFnVolumeLight_setEmitAmbient(*args, **kwargs):
pass
def MFnCamera_setMotionBlur(*args, **kwargs):
pass
def delete_MFnFloatArrayData(*args, **kwargs):
pass
def MRampAttribute_isColorRamp(*args, **kwargs):
pass
def MAttributeIndex___ne__(*args, **kwargs):
pass
def MUintArray_append(*args, **kwargs):
pass
def MInt64Array_copy(*args, **kwargs):
pass
def MScriptUtil_setInt2ArrayItem(*args, **kwargs):
pass
def MEulerRotation_alternateSolution(*args, **kwargs):
pass
def MFnSet_hasRestrictions(*args, **kwargs):
pass
def delete_MDGModifier(*args, **kwargs):
pass
def MMatrixArray_swigregister(*args, **kwargs):
pass
def MStreamUtils_writeDouble(*args, **kwargs):
pass
def MFnCamera_setVerticalFilmAperture(*args, **kwargs):
pass
def MProfiler_eventEnd(*args, **kwargs):
pass
def MPlane_normal(*args, **kwargs):
pass
def MTimeArray_length(*args, **kwargs):
pass
def MFnSubdNames_swigregister(*args, **kwargs):
pass
def delete_array3dDouble(*args, **kwargs):
pass
def uIntPtr_frompointer(*args, **kwargs):
pass
def MMeshIntersector_className(*args, **kwargs):
pass
def MFnPhongEShader_setHighlightSize(*args, **kwargs):
pass
def MFnAnisotropyShader_correlationY(*args, **kwargs):
pass
def MNurbsIntersector_swiginit(*args, **kwargs):
pass
def MFnDependencyNode_addExternalContentForFileAttr(*args, **kwargs):
pass
def MFnAssembly_createRepresentation(*args, **kwargs):
pass
def MQuaternion_setToYAxis(*args, **kwargs):
pass
def MFnMesh_isBlindDataTypeUsed(*args, **kwargs):
pass
def new_MPlug(*args, **kwargs):
pass
def MFnMesh_getPolygonVertices(*args, **kwargs):
pass
def MAddRemoveAttrEdit_node(*args, **kwargs):
pass
def MDAGDrawOverrideInfo_fDisplayType_get(*args, **kwargs):
pass
def MFnMesh_lockVertexNormals(*args, **kwargs):
pass
def MScriptUtil_asUint3Ptr(*args, **kwargs):
pass
def MFloatMatrix_inverse(*args, **kwargs):
pass
def delete_MSelectionList(*args, **kwargs):
pass
MFn_kBevel = 48
MFn_kFractal = 494
MNodeMessage_kOtherPlugSet = 16384
MFn_kRenderedImageSource = 782
MFn_kDynFieldsManip = 714
MFn_kLightLink = 760
MFn_kTripleShadingSwitch = 612
MFn_kAlignManip = 902
MFn_kNoise = 870
MFn_kUnknownDag = 316
MFn_kDistanceManip = 630
MFn_kAnimLayerClipRotation = 1093
MFn_kPolyCollapseF = 400
MFn_kCurveFromSubdivFace = 833
MFn_kAnimBlend = 786
MFn_kCacheFile = 977
MFn_kPfxGeometry = 935
MDagMessage_kRotateOrder = 134217728
MFn_kPolyCylinder = 432
MFn_kCompoundAttribute = 568
MFn_kSnapUVManip2D = 1081
MFn_kMesh = 296
MFn_kSfRevolveManip = 832
MFn_kDeltaMush = 349
MFn_kCurveCurveIntersect = 633
MFn_kHikEffector = 951
MFn_kJointCluster = 348
MFn_kStyleCurve = 891
MFn_kContourProjectionManip = 1100
MFn_kSelectionListOperator = 675
MFn_kPolyBevel3 = 1090
MNodeMessage_kAttributeKeyable = 512
MDagMessage_kRotateOrientX = 16777216
MFn_kMandelbrot = 1072
MFn_kPluginFieldNode = 722
MFn_kCreateBezierManip = 1041
MDagMessage_kAll = 268435455
MFn_kGenericAttribute = 569
MFn_kDeformSquashManip = 625
MFn_kDeformWave = 622
MFn_kUVManip2D = 697
MFn_kBendLattice = 335
MDagMessage_kScalePivotZ = 16384
MFn_kFluidEmitter = 910
MFn_kBlendNodeFloat = 1015
MFn_kSkinBinding = 1050
MFn_kBlendColors = 31
MFn_kFacade = 964
MFn_kIkSystem = 364
MFn_kCTE = 1094
MFn_kHikFloorContactMarker = 973
MFn_kClipScheduler = 771
MFn_kSamplerInfo = 471
MFn_kPolyMoveUV = 414
MFn_kTexture2d = 489
MFn_kParticleColorMapper = 446
MFn_kDirectionalLight = 308
MFn_kDeformFunc = 616
MFn_kHairTubeShader = 937
MFn_kPropModManip = 178
MNodeMessage_kAttributeArrayAdded = 4096
MFn_kNObjectData = 1003
MFn_kSCsolver = 361
MFn_kSubdBoolean = 818
MFn_kRenderPass = 775
MFn_kSurfaceRangeComponent = 540
MFn_kLeastSquares = 373
MFn_kPairBlend = 917
MFn_kPluginIkSolver = 753
MFn_kImageAdd = 651
MFn_kRemapColor = 928
MFn_kHyperGraphInfo = 355
MFn_kAnimBlendInOut = 787
MFn_kPlace2dTexture = 450
MFn_kClosestPointOnMesh = 979
MFn_kSnapshot = 475
MFn_kFloatArrayData = 1025
MFn_kPolyPrism = 958
MFn_kDynAttenuationManip = 720
MFn_kBezierCurveData = 1043
MFn_kBulge = 490
MFn_kDoubleIndexedComponent = 706
MFn_kImageRender = 650
MFn_kAir = 257
MFn_kFloatLinearAttribute = 563
MFn_kObjectRenderFilter = 673
MFn_kColorMgtGlobals = 1089
MFn_kShaderList = 469
MFn_kPolySphere = 434
MFn_kOceanShader = 889
MFn_kGuide = 353
MFn_kCommCornerManip = 605
MFn_kSurfaceInfo = 103
MFn_kImageLoad = 646
MFn_kImplicitSphere = 886
MFn_kAsset = 1006
MFn_kPolyNormal = 417
MFn_kGroupId = 351
MFn_kKeyframeDeltaAddRemove = 942
MFn_kAttribute2Float = 740
MFn_kUntrim = 106
MFn_kCharacterOffset = 681
MFn_kUnused4 = 837
MFn_kParticle = 311
MFn_kSubdSplitFace = 860
MFn_kSetGroupComponent = 552
MFn_kPolyExtrudeEdge = 785
MFn_kSubdMappingManip = 876
MFn_kRoundConstantRadius = 637
MFn_kFfdDualBase = 339
MFn_kBlendTwoAttr = 28
MFn_kPfxHair = 936
MFn_kSubdModifyEdge = 819
MFn_kFluid = 904
MNodeMessage_kAttributeUnkeyable = 1024
MFn_kImageNetSrc = 648
MFn_kSurfaceCVComponent = 535
MFn_kPolySmoothProxy = 934
MFn_kDeformFlare = 620
MFn_kMatrixFloatData = 664
MFn_kObjectFilter = 668
MFn_kCurveCVComponent = 529
MFn_kProjectionUVManip = 175
MFn_kBlindData = 748
MFn_kCurveFromSubdivEdge = 827
MFn_kPolyMoveFacetUV = 413
MFn_kPluginEmitterNode = 723
MFn_kAdskMaterial = 1055
MFn_kMatrixHold = 388
MFn_kRock = 507
MDagMessage_kRotateOrient = 117440512
MFn_kClipToGhostData = 1071
MFn_kNurbsCurveGeom = 268
MFn_kModifyEdgeManip = 821
MFn_kNurbsCurveToBezier = 1044
MFn_kDynBaseFieldManip = 715
MFn_kCreateUVSet = 800
MFn_kAssembly = 1069
MFn_kCacheTrack = 989
MFn_kImageSource = 783
MFn_kNonExtendedLight = 307
MFn_kCone = 96
MFn_kMeshFrEdgeComponent = 546
MFn_kSketchPlane = 289
MFn_kImageBlur = 657
MFn_kKeyframeDeltaWeighted = 946
MFn_kCharacter = 680
MFn_kAttribute3Long = 746
MFn_kSkin = 100
MFn_kRevolve = 94
MFn_kSoftModFilter = 347
MFn_kUnknown = 525
MFn_kNCloth = 995
MDagMessage_kScaleTransX = 262144
MFn_kPolyCut = 892
MFn_kMergeVertsToolManip = 1027
MFn_kPolyMirror = 948
MFn_kIkSolver = 358
MFn_kFloatMatrixAttribute = 572
MFn_kDeleteComponent = 318
MFn_kReverseCurve = 92
MFn_kTurbulence = 262
MFn_kClip = 801
MFn_kSurfaceEdManip = 769
MFn_kDoubleArrayData = 577
MFn_kBlinn = 368
MFn_kLast = 1107
MFn_kDropOffFunction = 817
MDagMessage_kTranslateY = 1024
MFn_kPivotComponent = 534
MFn_kRadius = 274
MFn_kNurbsCurve = 267
MFn_kIsoparmComponent = 533
MNodeMessage_kLast = 32768
MFn_kPolyPlanProj = 418
MFn_kMeshVertComponent = 547
MFn_kBlendNodeTime = 1040
MFn_kConstraint = 922
MFn_kMeshComponent = 543
MFn_kSubdivFaceComponent = 696
MFn_kEditsManager = 1085
MFn_kLightFogMaterial = 374
MFn_kHyperView = 357
MFn_kMultilisterLight = 440
MFn_kComponent = 528
MFnData_kLast = 25
MFn_kBevelPlus = 890
MFn_kRoundConstantRadiusManip = 640
MFn_kPolyAutoProj = 842
MFn_kHairSystem = 926
MFn_kSubdLayoutUV = 864
MFn_kStringShadingSwitch = 908
MFn_kPrimitive = 86
MFn_kRoundRadiusCrvManip = 639
MFn_kPolyProj = 419
MFn_kOffsetCurveManip = 172
MFn_kEditMetadata = 1077
MFn_kSectionManip = 809
MFn_kPolySmoothFacet = 691
MFn_kPolyTweak = 395
MFn_kFollicle = 925
MFn_kSubdAutoProj = 868
MFn_kViewManip = 919
MFn_kAnimLayer = 1008
MFn_kPolyMoveVertexUV = 416
MFn_kSubVertexComponent = 550
MFn_kMultDoubleLinear = 766
MFn_kAreaLight = 305
MFn_kDynGlobals = 761
MFn_kCrossSectionEditManip = 816
MFn_kCurveNormalizerLinear = 992
MFn_kEnvFogMaterial = 375
MFn_kPluginParticleAttributeMapperNode = 998
MFn_kTowPointOnSurfaceManip = 768
MFn_kSubdiv = 676
MFn_kDoubleShadingSwitch = 611
MFn_kNObject = 1004
MFn_kRadial = 261
MFn_kRenderCone = 97
kMFnNurbsEpsilon = 0.001
MFn_kShaderGlow = 468
MFn_kSubdivReverseFaces = 807
MFn_kArcLength = 273
MFn_kDeformWaveManip = 628
MFn_kNewton = 260
MFn_kReverse = 461
MFn_kMatrixData = 580
MFn_kTextureDeformerHandle = 343
MFn_kWriteToFrameBuffer = 1031
MFn_kAnisotropy = 614
MFn_kParticleCloud = 445
MFn_kPolyCutManip = 896
MFn_kSubdMoveEdge = 847
MFn_kEnvFogShape = 278
MFn_kVortex = 264
MFn_kHardwareRenderingGlobals = 1059
MFn_kBlindDataTemplate = 749
MFn_kBezierCurveToNurbs = 1045
MFn_kSquareSrfManip = 710
MFn_kBoxData = 857
MFn_kGammaCorrect = 333
MFn_kWood = 512
MFn_kCreateCVManip = 157
MDagMessage_kScaleTransY = 524288
MFn_kPolyCube = 431
MFn_kSet = 464
MFn_kPfxToon = 961
MFn_kRenderPassSet = 776
MFn_kProxyManager = 956
MFileIO_kVersion2011 = 156
MFn_kUnused1 = 834
MFn_kAnnotation = 271
MFn_kImageColorCorrect = 656
MDagMessage_kTranslateX = 512
MFn_kDagPose = 682
MFn_kScaleUVManip2D = 700
MFn_kSuper = 478
MFn_kForceUpdateManip = 687
MFn_kSubdivToPoly = 711
MFn_kObjectAttrFilter = 672
MFn_kLightDataAttribute = 570
MFn_kRigidConstraint = 313
MFn_kPluginManipContainer = 688
MFn_kPluginLocatorNode = 453
MFn_kDynamicConstraint = 981
MFn_kHeightField = 911
MFn_kGuideLine = 301
MFn_kSubdivToNurbs = 811
MFn_kPolyMoveFacet = 412
MFn_kGeometryData = 704
MFn_kPolyBoolOp = 609
MFn_kBlendNodeEnum = 1014
MFn_kUniform = 263
MFn_kPolyCylProj = 401
MFn_kParticleAgeMapper = 444
MFn_kSubdMergeVert = 856
MFn_kDeformSine = 621
MFn_kPluginObjectSet = 914
MFn_kHikSolver = 954
MFn_kLocator = 281
MFn_kGlobalCacheControls = 853
MVector_kTol = 1e-10
MFn_kPluginCameraSet = 1000
kQuaternionEpsilon = 1e-10
MPoint_kTol = 1e-10
MFn_kSnapshotShape = 850
kMFnSubdPointTolerance = 1e-10
kMFnSubdTolerance = 0.001
MFn_kAnimLayerClip = 1091
kMFnMeshPointTolerance = 1e-10
MFn_kSphereData = 596
MFn_kPolyRemesh = 1098
MFloatVector_kTol = 1e-05
MFloatMatrix_kTol = 1e-05
MFn_kVolumeNoise = 867
kEulerRotationEpsilon = 1e-10
MFn_kNurbsCurveData = 583
MFn_kKeyframeDeltaBlockAddRemove = 943
MFn_kCameraSet = 999
MFn_kPolyContourProj = 1099
MFn_kParticleTransparencyMapper = 448
MFn_kLattice = 279
MFn_kExplodeNurbsShell = 684
MFn_kAttribute2Double = 739
MFn_kMeshMapComponent = 808
MFn_kGreasePlane = 1074
MFn_kPluginHardwareShader = 881
MFn_kGroupParts = 352
MFn_kLight = 302
MFn_kCreaseSet = 1078
MFn_kSpring = 315
MFn_kAISEnvFacade = 967
MFn_kNId = 1024
MFn_kKeyframeDeltaTangent = 945
MFn_kCopyUVSet = 799
MFn_kPolyMergeFacet = 410
MFn_kHistorySwitch = 978
MFn_kTime = 513
MFn_kImageData = 645
MFn_kDynEmitterManip = 713
MFn_kCrater = 503
MFn_kSubdBlindData = 794
MFn_kPolyCone = 430
MFn_kMeshVtxFaceComponent = 737
MFn_kOffsetSurfaceManip = 644
MFn_kAttribute = 558
MFn_kLayeredShader = 371
MFn_kPolyDelVertex = 404
MFn_kSubdModifier = 845
MFn_kNodeGraphEditorInfo = 1101
MDagMessage_kRotateTransX = 2097152
MFn_kNodeGraphEditorBookmarks = 1102
MFn_kPolyTransfer = 840
MFn_kMaterialInfo = 386
MFn_kUvChooser = 789
MFn_kPolyMergeVert = 690
MFn_kIkSplineManip = 166
MFn_kSetRange = 467
MFn_kLightInfo = 372
MFn_kToonLineAttributes = 962
MFn_kPolyTweakUV = 701
MFn_kPhongMaterial = 384
MFn_kMoveUVShellManip2D = 702
MFn_kSubdMoveVertex = 846
MFn_kPolySoftEdge = 422
MFn_kPolyHoleFace = 1047
MFn_kPolyArrow = 969
MFn_kCommEdgeOperManip = 603
MFn_kPolyPrimitive = 429
MFn_kSubdTweakUV = 862
MFnData_kSphere = 18
MFn_kBlendNodeAdditiveScale = 1020
MFn_kGreasePencilSequence = 1076
MFn_kNurbsSquare = 613
MFn_kPartition = 449
MFn_kDeformBend = 617
MFn_kShadingEngine = 320
MFn_kQuadShadingSwitch = 915
MFn_kPolyFlipUV = 879
MFn_kCacheableNode = 984
MFn_kRenderGlobals = 516
MFn_kCopyColorSet = 730
MFn_kEditCurve = 812
MFn_kPluginTransformNode = 903
MFn_kVertexBakeSet = 466
MFn_kObjectBinFilter = 933
MFn_kControl = 479
MFn_kFourByFourMatrix = 767
MFn_kRebuildSurface = 91
MDagMessage_kRotatePivotX = 32768
MFn_kLambertMaterial = 382
MFn_kMarble = 506
MFn_kSelectionItem = 554
MFn_kWriteToLabelBuffer = 1035
MFn_kSubdivCollapse = 797
MFn_kCylindricalProjectionManip = 131
MFn_kSubdPlanProj = 873
MFn_kBlendNodeBoolean = 1010
MFn_kVertexWeightSet = 1052
MFn_kConcentricProjectionManip = 129
MFn_kEditCurveManip = 813
MFn_kPluginBlendShape = 1106
MFn_kEnumAttribute = 565
MFn_kParticleSamplerInfo = 798
MFn_kRigidSolver = 463
MFn_kSubdMapSewMove = 865
MNodeMessage_kIncomingDirection = 2048
MFn_kSubdivGeom = 804
MFn_kSnapshotPath = 913
MFn_kStencil = 498
MFn_kSkinClusterFilter = 678
MFn_kPolyChipOff = 397
MFn_kDoubleLinearAttribute = 562
MFn_kDoubleAngleAttribute = 560
MFn_kBlendNodeFloatLinear = 1017
MFn_kThreePointArcManip = 641
MFn_kPolyDelEdge = 402
MFn_kCurveFromMeshCoM = 924
MFn_kKeyframeRegionManip = 990
MFn_kPolyCreaseEdge = 949
MFn_kPolySplit = 424
MDagMessage_kRotatePivot = 229376
MFn_kWrapFilter = 736
MFn_kPluginDependNode = 452
MFn_kDropoffManip = 163
MFn_kFloatVectorArrayData = 1002
MFn_kDispatchCompute = 319
MFn_kDagContainer = 1057
MFn_kFluidData = 906
MFn_kSurfaceLuminance = 480
MFn_kPolyBridgeEdge = 983
MFn_kSplineSolver = 363
MFn_kWire = | |
type %s when expected time" % t_value)
elif value_type == "datetime":
if isinstance(value, datetime.datetime):
return value
else:
raise DataTableException("Wrong type %s when expected datetime" %
t_value)
# If we got here, it means the given value_type was not one of the
# supported types.
raise DataTableException("Unsupported type %s" % value_type)
@staticmethod
def EscapeForJSCode(encoder, value):
if value is None:
return "null"
elif isinstance(value, datetime.datetime):
if value.microsecond == 0:
# If it's not ms-resolution, leave that out to save space.
return "new Date(%d,%d,%d,%d,%d,%d)" % (value.year,
value.month - 1, # To match JS
value.day,
value.hour,
value.minute,
value.second)
else:
return "new Date(%d,%d,%d,%d,%d,%d,%d)" % (value.year,
value.month - 1, # match JS
value.day,
value.hour,
value.minute,
value.second,
value.microsecond / 1000)
elif isinstance(value, datetime.date):
return "new Date(%d,%d,%d)" % (value.year, value.month - 1, value.day)
else:
return encoder.encode(value)
@staticmethod
def ToString(value):
if value is None:
return "(empty)"
elif isinstance(value, (datetime.datetime,
datetime.date,
datetime.time)):
return str(value)
elif isinstance(value, str):
return value
elif isinstance(value, bool):
return str(value).lower()
else:
return str(value).decode("utf-8")
@staticmethod
def ColumnTypeParser(description):
"""Parses a single column description. Internal helper method.
Args:
description: a column description in the possible formats:
'id'
('id',)
('id', 'type')
('id', 'type', 'label')
('id', 'type', 'label', {'custom_prop1': 'custom_val1'})
Returns:
Dictionary with the following keys: id, label, type, and
custom_properties where:
- If label not given, it equals the id.
- If type not given, string is used by default.
- If custom properties are not given, an empty dictionary is used by
default.
Raises:
DataTableException: The column description did not match the RE, or
unsupported type was passed.
"""
if not description:
raise DataTableException("Description error: empty description given")
if not isinstance(description, (str, tuple)):
raise DataTableException("Description error: expected either string or "
"tuple, got %s." % type(description))
if isinstance(description, str):
description = (description,)
# According to the tuple's length, we fill the keys
# We verify everything is of type string
for elem in description[:3]:
if not isinstance(elem, str):
raise DataTableException("Description error: expected tuple of "
"strings, current element of type %s." %
type(elem))
desc_dict = {"id": description[0],
"label": description[0],
"type": "string",
"custom_properties": {}}
if len(description) > 1:
desc_dict["type"] = description[1].lower()
if len(description) > 2:
desc_dict["label"] = description[2]
if len(description) > 3:
if not isinstance(description[3], dict):
raise DataTableException("Description error: expected custom "
"properties of type dict, current element "
"of type %s." % type(description[3]))
desc_dict["custom_properties"] = description[3]
if len(description) > 4:
raise DataTableException("Description error: tuple of length > 4")
if desc_dict["type"] not in ["string", "number", "boolean",
"date", "datetime", "timeofday"]:
raise DataTableException(
"Description error: unsupported type '%s'" % desc_dict["type"])
return desc_dict
@staticmethod
def TableDescriptionParser(table_description, depth=0):
"""Parses the table_description object for internal use.
Parses the user-submitted table description into an internal format used
by the Python DataTable class. Returns the flat list of parsed columns.
Args:
table_description: A description of the table which should comply
with one of the formats described below.
depth: Optional. The depth of the first level in the current description.
Used by recursive calls to this function.
Returns:
List of columns, where each column represented by a dictionary with the
keys: id, label, type, depth, container which means the following:
- id: the id of the column
- name: The name of the column
- type: The datatype of the elements in this column. Allowed types are
described in ColumnTypeParser().
- depth: The depth of this column in the table description
- container: 'dict', 'iter' or 'scalar' for parsing the format easily.
- custom_properties: The custom properties for this column.
The returned description is flattened regardless of how it was given.
Raises:
DataTableException: Error in a column description or in the description
structure.
Examples:
A column description can be of the following forms:
'id'
('id',)
('id', 'type')
('id', 'type', 'label')
('id', 'type', 'label', {'custom_prop1': 'custom_val1'})
or as a dictionary:
'id': 'type'
'id': ('type',)
'id': ('type', 'label')
'id': ('type', 'label', {'custom_prop1': 'custom_val1'})
If the type is not specified, we treat it as string.
If no specific label is given, the label is simply the id.
If no custom properties are given, we use an empty dictionary.
input: [('a', 'date'), ('b', 'timeofday', 'b', {'foo': 'bar'})]
output: [{'id': 'a', 'label': 'a', 'type': 'date',
'depth': 0, 'container': 'iter', 'custom_properties': {}},
{'id': 'b', 'label': 'b', 'type': 'timeofday',
'depth': 0, 'container': 'iter',
'custom_properties': {'foo': 'bar'}}]
input: {'a': [('b', 'number'), ('c', 'string', 'column c')]}
output: [{'id': 'a', 'label': 'a', 'type': 'string',
'depth': 0, 'container': 'dict', 'custom_properties': {}},
{'id': 'b', 'label': 'b', 'type': 'number',
'depth': 1, 'container': 'iter', 'custom_properties': {}},
{'id': 'c', 'label': 'column c', 'type': 'string',
'depth': 1, 'container': 'iter', 'custom_properties': {}}]
input: {('a', 'number', 'column a'): { 'b': 'number', 'c': 'string'}}
output: [{'id': 'a', 'label': 'column a', 'type': 'number',
'depth': 0, 'container': 'dict', 'custom_properties': {}},
{'id': 'b', 'label': 'b', 'type': 'number',
'depth': 1, 'container': 'dict', 'custom_properties': {}},
{'id': 'c', 'label': 'c', 'type': 'string',
'depth': 1, 'container': 'dict', 'custom_properties': {}}]
input: { ('w', 'string', 'word'): ('c', 'number', 'count') }
output: [{'id': 'w', 'label': 'word', 'type': 'string',
'depth': 0, 'container': 'dict', 'custom_properties': {}},
{'id': 'c', 'label': 'count', 'type': 'number',
'depth': 1, 'container': 'scalar', 'custom_properties': {}}]
input: {'a': ('number', 'column a'), 'b': ('string', 'column b')}
output: [{'id': 'a', 'label': 'column a', 'type': 'number', 'depth': 0,
'container': 'dict', 'custom_properties': {}},
{'id': 'b', 'label': 'column b', 'type': 'string', 'depth': 0,
'container': 'dict', 'custom_properties': {}}
NOTE: there might be ambiguity in the case of a dictionary representation
of a single column. For example, the following description can be parsed
in 2 different ways: {'a': ('b', 'c')} can be thought of a single column
with the id 'a', of type 'b' and the label 'c', or as 2 columns: one named
'a', and the other named 'b' of type 'c'. We choose the first option by
default, and in case the second option is the right one, it is possible to
make the key into a tuple (i.e. {('a',): ('b', 'c')}) or add more info
into the tuple, thus making it look like this: {'a': ('b', 'c', 'b', {})}
-- second 'b' is the label, and {} is the custom properties field.
"""
# For the recursion step, we check for a scalar object (string or tuple)
if isinstance(table_description, (str, tuple)):
parsed_col = DataTable.ColumnTypeParser(table_description)
parsed_col["depth"] = depth
parsed_col["container"] = "scalar"
return [parsed_col]
# Since it is not scalar, table_description must be iterable.
if not hasattr(table_description, "__iter__"):
raise DataTableException("Expected an iterable object, got %s" %
type(table_description))
if not isinstance(table_description, dict):
# We expects a non-dictionary iterable item.
columns = []
for desc in table_description:
parsed_col = DataTable.ColumnTypeParser(desc)
parsed_col["depth"] = depth
parsed_col["container"] = "iter"
columns.append(parsed_col)
if not columns:
raise DataTableException("Description iterable objects should not"
" be empty.")
return columns
# The other case is a dictionary
if not table_description:
raise DataTableException("Empty dictionaries are not allowed inside"
" description")
# To differentiate between the two cases of more levels below or this is
# the most inner dictionary, we consider the number of keys (more then one
# key is indication for most inner dictionary) and the type of the key and
# value in case of only 1 key (if the type of key is string and the type of
# the value is a tuple of 0-3 items, we assume this is the most inner
# dictionary).
# NOTE: this way of differentiating might create ambiguity. See docs.
if (len(table_description) != 1 or
(isinstance(table_description.keys()[0], str) and
isinstance(table_description.values()[0], tuple) and
len(table_description.values()[0]) < 4)):
# This is the most inner dictionary. Parsing types.
columns = []
# We sort the items, equivalent to sort the keys since they are unique
for key, value in sorted(table_description.items()):
# We parse the column type as (key, type) or (key, type, label) using
# ColumnTypeParser.
if isinstance(value, tuple):
parsed_col = DataTable.ColumnTypeParser((key,) + value)
else:
parsed_col = DataTable.ColumnTypeParser((key, value))
parsed_col["depth"] = depth
parsed_col["container"] = "dict"
columns.append(parsed_col)
return columns
# This is an outer dictionary, must have at most one | |
"fields": [
{
"ctype": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"name": "a",
},
{
"ctype": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "char",
"signed": True,
},
"name": "b",
},
{
"ctype": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"name": "c",
},
{
"bitfield": "15",
"ctype": {
"Klass": "CtypesBitfield",
"base": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"bitfield": {
"Klass": "ConstantExpressionNode",
"errors": [],
"is_literal": False,
"value": 15,
},
"errors": [],
},
"name": "d",
},
{
"bitfield": "17",
"ctype": {
"Klass": "CtypesBitfield",
"base": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"bitfield": {
"Klass": "ConstantExpressionNode",
"errors": [],
"is_literal": False,
"value": 17,
},
"errors": [],
},
"name": None,
},
],
"name": "foo3",
"type": "struct",
},
{
"ctype": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"name": "Int",
"type": "typedef",
},
{
"attrib": {},
"fields": [
{
"ctype": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"name": "Int",
}
],
"name": "anon_4",
"type": "struct",
},
{
"ctype": {
"Klass": "CtypesStruct",
"anonymous": True,
"errors": [],
"members": [
[
"Int",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
]
],
"opaque": False,
"attrib": {},
"src": ["/some-path/temp.h", 77],
"tag": "anon_4",
"variety": "struct",
},
"name": "id_struct_t",
"type": "typedef",
},
{
"attrib": {},
"fields": [
{
"ctype": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"name": "a",
},
{
"ctype": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "char",
"signed": True,
},
"name": "b",
},
],
"name": "anon_5",
"type": "struct",
},
{
"ctype": {
"Klass": "CtypesStruct",
"anonymous": True,
"attrib": {},
"errors": [],
"members": [
[
"a",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
],
[
"b",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "char",
"signed": True,
},
],
],
"opaque": False,
"src": ["/some-path/temp.h", 81],
"tag": "anon_5",
"variety": "struct",
},
"name": "BAR0",
"type": "typedef",
},
{
"ctype": {
"Klass": "CtypesPointer",
"destination": {
"Klass": "CtypesStruct",
"anonymous": True,
"attrib": {},
"errors": [],
"members": [
[
"a",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
],
[
"b",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "char",
"signed": True,
},
],
],
"opaque": False,
"src": ["/some-path/temp.h", 81],
"tag": "anon_5",
"variety": "struct",
},
"errors": [],
"qualifiers": [],
},
"name": "PBAR0",
"type": "typedef",
},
{
"ctype": {
"Klass": "CtypesStruct",
"anonymous": False,
"errors": [],
"members": [
[
"a",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
],
[
"b",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "char",
"signed": True,
},
],
[
"c",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
],
[
"d",
{
"Klass": "CtypesBitfield",
"base": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"bitfield": {
"Klass": "ConstantExpressionNode",
"errors": [],
"is_literal": False,
"value": 15,
},
"errors": [],
},
],
[
None,
{
"Klass": "CtypesBitfield",
"base": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"bitfield": {
"Klass": "ConstantExpressionNode",
"errors": [],
"is_literal": False,
"value": 17,
},
"errors": [],
},
],
],
"opaque": False,
"attrib": {},
"src": ["/some-path/temp.h", 3],
"tag": "foo",
"variety": "struct",
},
"name": "foo",
"type": "typedef",
},
{
"ctype": {
"Klass": "CtypesStruct",
"anonymous": False,
"errors": [],
"members": [
[
"a",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
],
[
"b",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "char",
"signed": True,
},
],
[
"c",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
],
[
"d",
{
"Klass": "CtypesBitfield",
"base": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"bitfield": {
"Klass": "ConstantExpressionNode",
"errors": [],
"is_literal": False,
"value": 15,
},
"errors": [],
},
],
[
None,
{
"Klass": "CtypesBitfield",
"base": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"bitfield": {
"Klass": "ConstantExpressionNode",
"errors": [],
"is_literal": False,
"value": 17,
},
"errors": [],
},
],
],
"opaque": False,
"attrib": {"packed": True},
"src": ["/some-path/temp.h", 12],
"tag": "packed_foo",
"variety": "struct",
},
"name": "packed_foo",
"type": "typedef",
},
{
"ctype": {
"Klass": "CtypesStruct",
"anonymous": False,
"attrib": {"aligned": [2], "packed": True},
"errors": [],
"members": [
[
"a",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
],
[
"b",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "char",
"signed": True,
},
],
[
"c",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
],
[
"d",
{
"Klass": "CtypesBitfield",
"base": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"bitfield": {
"Klass": "ConstantExpressionNode",
"errors": [],
"is_literal": False,
"value": 15,
},
"errors": [],
},
],
[
None,
{
"Klass": "CtypesBitfield",
"base": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"bitfield": {
"Klass": "ConstantExpressionNode",
"errors": [],
"is_literal": False,
"value": 17,
},
"errors": [],
},
],
],
"opaque": False,
"src": ["/some-path/temp.h", 56],
"tag": "pragma_packed_foo2",
"variety": "struct",
},
"name": "pragma_packed_foo2",
"type": "typedef",
},
{
"ctype": {
"Klass": "CtypesStruct",
"anonymous": False,
"attrib": {},
"errors": [],
"members": [
[
"a",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
],
[
"b",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "char",
"signed": True,
},
],
[
"c",
{
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
],
[
"d",
{
"Klass": "CtypesBitfield",
"base": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"bitfield": {
"Klass": "ConstantExpressionNode",
"errors": [],
"is_literal": False,
"value": 15,
},
"errors": [],
},
],
[
None,
{
"Klass": "CtypesBitfield",
"base": {
"Klass": "CtypesSimple",
"errors": [],
"longs": 0,
"name": "int",
"signed": True,
},
"bitfield": {
"Klass": "ConstantExpressionNode",
"errors": [],
"is_literal": False,
"value": 17,
},
"errors": [],
},
],
],
"opaque": False,
"src": ["/some-path/temp.h", 66],
"tag": "foo3",
"variety": "struct",
},
"name": "foo3",
"type": "typedef",
},
]
compare_json(self, StructuresTest.json, json_ans, True)
def test_fields(self):
"""Test whether fields are built correctly."""
struct_foo = StructuresTest.module.struct_foo
self.assertEqual(
struct_foo._fields_,
[
("a", ctypes.c_int),
("b", ctypes.c_char),
("c", ctypes.c_int),
("d", ctypes.c_int, 15),
("unnamed_1", ctypes.c_int, 17),
],
)
def test_pack(self):
"""Test whether gcc __attribute__((packed)) is interpreted correctly."""
module = StructuresTest.module
unpacked_size = compute_packed(4, [ctypes.c_int] * 3 + [ctypes.c_char])
packed_size = compute_packed(1, [ctypes.c_int] * 3 + [ctypes.c_char])
struct_foo = module.struct_foo
struct_packed_foo = module.struct_packed_foo
foo_t = module.foo_t
packed_foo_t = module.packed_foo_t
self.assertEqual(getattr(struct_foo, "_pack_", 0), 0)
self.assertEqual(getattr(struct_packed_foo, "_pack_", 0), 1)
self.assertEqual(getattr(foo_t, "_pack_", 0), 0)
self.assertEqual(getattr(packed_foo_t, "_pack_", -1), 1)
self.assertEqual(ctypes.sizeof(struct_foo), unpacked_size)
self.assertEqual(ctypes.sizeof(foo_t), unpacked_size)
self.assertEqual(ctypes.sizeof(struct_packed_foo), packed_size)
self.assertEqual(ctypes.sizeof(packed_foo_t), packed_size)
def test_pragma_pack(self):
"""Test whether #pragma pack(...) is interpreted correctly."""
module = StructuresTest.module
packed4_size = compute_packed(4, [ctypes.c_int] * 3 + [ctypes.c_char])
packed2_size = compute_packed(2, [ctypes.c_int] * 3 + [ctypes.c_char])
unpacked_size = compute_packed(4, [ctypes.c_int] * 3 + [ctypes.c_char])
pragma_packed_foo_t = module.pragma_packed_foo_t
struct_pragma_packed_foo2 = module.struct_pragma_packed_foo2
struct_foo3 = module.struct_foo3
self.assertEqual(getattr(pragma_packed_foo_t, "_pack_", 0), 4)
self.assertEqual(getattr(struct_pragma_packed_foo2, "_pack_", 0), 2)
self.assertEqual(getattr(struct_foo3, "_pack_", 0), 0)
self.assertEqual(ctypes.sizeof(pragma_packed_foo_t), packed4_size)
self.assertEqual(ctypes.sizeof(struct_pragma_packed_foo2), packed2_size)
self.assertEqual(ctypes.sizeof(struct_foo3), unpacked_size)
def test_typedef_vs_field_id(self):
"""Test whether local field identifier names can override external
typedef names.
"""
module = StructuresTest.module
Int = module.Int
id_struct_t = module.id_struct_t
self.assertEqual(Int, ctypes.c_int)
self.assertEqual(id_struct_t._fields_, [("Int", ctypes.c_int)])
def test_anonymous_tag_uniformity(self):
"""Test whether anonymous structs with multiple declarations all resolve
to the same type.
"""
module = StructuresTest.module
BAR0 = module.BAR0
PBAR0 = module.PBAR0
self.assertEqual(PBAR0._type_, BAR0)
class MathTest(unittest.TestCase):
"""Based on math_functions.py"""
@classmethod
def setUpClass(cls):
header_str = """
#include <math.h>
#define sin_plus_y(x,y) (sin(x) + (y))
"""
if sys.platform == "win32":
# pick something from %windir%\system32\msvc*dll that include stdlib
libraries = ["msvcrt.dll"]
libraries = ["msvcrt"]
elif sys.platform.startswith("linux"):
libraries = ["libm.so.6"]
else:
libraries = ["libc"]
cls.module, _ = generate(header_str, libraries=libraries, all_headers=True)
@classmethod
def tearDownClass(cls):
del cls.module
cleanup()
def test_sin(self):
"""Based on math_functions.py"""
module = MathTest.module
self.assertEqual(module.sin(2), math.sin(2))
def test_sqrt(self):
"""Based on math_functions.py"""
module = MathTest.module
self.assertEqual(module.sqrt(4), 2)
def local_test():
module.sin("foobar")
self.assertRaises(ctypes.ArgumentError, local_test)
def test_bad_args_string_not_number(self):
"""Based on math_functions.py"""
module = MathTest.module
def local_test():
module.sin("foobar")
self.assertRaises(ctypes.ArgumentError, local_test)
def test_subcall_sin(self):
"""Test math with sin(x) in a macro"""
module = MathTest.module
self.assertEqual(module.sin_plus_y(2, | |
not in local_var_params or # noqa: E501
local_var_params['username'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `username` when calling `remove_project_member`") # noqa: E501
# verify the required parameter 'id' is set
if self.api_client.client_side_validation and ('id' not in local_var_params or # noqa: E501
local_var_params['id'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `id` when calling `remove_project_member`") # noqa: E501
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id'] # noqa: E501
query_params = []
if 'username' in local_var_params and local_var_params['username'] is not None: # noqa: E501
query_params.append(('username', local_var_params['username'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['APIKeyHeader', 'Username'] # noqa: E501
return self.api_client.call_api(
'/api/projects/{id}/members', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='bool', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def remove_role_from_project_member(self, id, username, role, **kwargs): # noqa: E501
"""Unassign Role from Member # noqa: E501
Removes the provided Role from the specified member of the Project. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_role_from_project_member(id, username, role, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str id: ID of project (required)
:param str username: Username of project member (required)
:param str role: Project role to remove (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: bool
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.remove_role_from_project_member_with_http_info(id, username, role, **kwargs) # noqa: E501
def remove_role_from_project_member_with_http_info(self, id, username, role, **kwargs): # noqa: E501
"""Unassign Role from Member # noqa: E501
Removes the provided Role from the specified member of the Project. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_role_from_project_member_with_http_info(id, username, role, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str id: ID of project (required)
:param str username: Username of project member (required)
:param str role: Project role to remove (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(bool, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ['id', 'username', 'role'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method remove_role_from_project_member" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'id' is set
if self.api_client.client_side_validation and ('id' not in local_var_params or # noqa: E501
local_var_params['id'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `id` when calling `remove_role_from_project_member`") # noqa: E501
# verify the required parameter 'username' is set
if self.api_client.client_side_validation and ('username' not in local_var_params or # noqa: E501
local_var_params['username'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `username` when calling `remove_role_from_project_member`") # noqa: E501
# verify the required parameter 'role' is set
if self.api_client.client_side_validation and ('role' not in local_var_params or # noqa: E501
local_var_params['role'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `role` when calling `remove_role_from_project_member`") # noqa: E501
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id'] # noqa: E501
query_params = []
if 'username' in local_var_params and local_var_params['username'] is not None: # noqa: E501
query_params.append(('username', local_var_params['username'])) # noqa: E501
if 'role' in local_var_params and local_var_params['role'] is not None: # noqa: E501
query_params.append(('role', local_var_params['role'])) # noqa: E501
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['APIKeyHeader', 'Username'] # noqa: E501
return self.api_client.call_api(
'/api/projects/{id}/members/roles', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='bool', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def remove_submission_service_from_project(self, id, submission_service_id, **kwargs): # noqa: E501
"""Remove Submission Service # noqa: E501
Removes the provided Submission Service from the list of available Services for the specified Project. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_submission_service_from_project(id, submission_service_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str id: ID of project (required)
:param str submission_service_id: ID of submission service (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: bool
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
return self.remove_submission_service_from_project_with_http_info(id, submission_service_id, **kwargs) # noqa: E501
def remove_submission_service_from_project_with_http_info(self, id, submission_service_id, **kwargs): # noqa: E501
"""Remove Submission Service # noqa: E501
Removes the provided Submission Service from the list of available Services for the specified Project. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.remove_submission_service_from_project_with_http_info(id, submission_service_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str id: ID of project (required)
:param str submission_service_id: ID of submission service (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(bool, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ['id', 'submission_service_id'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
for key, val in six.iteritems(local_var_params['kwargs']):
if key not in all_params:
raise ApiTypeError(
"Got an unexpected keyword argument '%s'"
" to method remove_submission_service_from_project" % key
)
local_var_params[key] = val
del local_var_params['kwargs']
# verify the required parameter 'id' is set
if self.api_client.client_side_validation and ('id' not in local_var_params or # noqa: E501
local_var_params['id'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `id` when calling `remove_submission_service_from_project`") # noqa: E501
# verify the required parameter 'submission_service_id' is set
if self.api_client.client_side_validation and ('submission_service_id' not in local_var_params or # noqa: E501
local_var_params['submission_service_id'] is None): # noqa: E501
raise ApiValueError("Missing the required parameter `submission_service_id` when calling `remove_submission_service_from_project`") # noqa: E501
collection_formats = {}
path_params = {}
if 'id' in local_var_params:
path_params['id'] = local_var_params['id'] # noqa: E501
if 'submission_service_id' in local_var_params:
path_params['submission_service_id'] = local_var_params['submission_service_id'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# Authentication setting
auth_settings = ['APIKeyHeader', 'Username'] # noqa: E501
return self.api_client.call_api(
'/api/projects/{id}/submission/{submission_service_id}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='bool', # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get('async_req'),
_return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501
_preload_content=local_var_params.get('_preload_content', True),
_request_timeout=local_var_params.get('_request_timeout'),
collection_formats=collection_formats)
def remove_trusted_project1(self, id, trustedid, **kwargs): # noqa: E501
"""Unassign Trusted Project from Project # noqa: E501
Removes the target Project from the specified Project's list of Trusted Partners. # noqa: E501
This method makes a synchronous HTTP request by default. | |
: array_like
Frequency values to evaluate at.
reuse_spline : bool, optional
Does nothing for analytic beams. Here for compatibility with UVBeam.
Returns
-------
interp_data : array_like
Array of beam values, shape (Naxes_vec, Nspws, Nfeeds or Npols,
Nfreqs or freq_array.size if freq_array is passed,
Npixels/(Naxis1, Naxis2) or az_array.size if az/za_arrays are passed)
interp_basis_vector : array_like
Array of interpolated basis vectors (or self.basis_vector_array
if az/za_arrays are not passed), shape: (Naxes_vec, Ncomponents_vec,
Npixels/(Naxis1, Naxis2) or az_array.size if az/za_arrays are passed)
"""
# Check that coordinates have same length
if az_array.size != za_array.size:
raise ValueError(
"Azimuth and zenith angle coordinate arrays must have same length."
)
# Empty data array
interp_data = np.zeros(
(2, 1, 2, freq_array.size, az_array.size), dtype=np.complex128
)
# Frequency scaling
fscale = (freq_array / self.ref_freq) ** self.spectral_index
# Transformed zenith angle, also scaled with frequency
x = 2.0 * np.sin(za_array[np.newaxis, ...] / fscale[:, np.newaxis]) - 1.0
# Primary beam values from Chebyshev polynomial
beam_values = chebval(x, self.beam_coeffs)
central_val = chebval(-1.0, self.beam_coeffs)
beam_values /= central_val # ensure normalized to 1 at za=0
# Set beam Jones matrix values (see Eq. 5 of Kohn+ arXiv:1802.04151)
# Axes: [phi, theta] (az and za) / Feeds: [n, e]
# interp_data shape: (Naxes_vec, Nspws, Nfeeds or Npols, Nfreqs, Naz)
if self.polarized:
interp_data = modulate_with_dipole(
az_array, za_array, freq_array, self.ref_freq, beam_values, fscale
)
else:
interp_data[1, 0, 0, :, :] = beam_values # (theta, n)
interp_data[0, 0, 1, :, :] = beam_values # (phi, e)
interp_basis_vector = None
if self.beam_type == "power":
# Cross-multiplying feeds, adding vector components
pairs = [(i, j) for i in range(2) for j in range(2)]
power_data = np.zeros((1, 1, 4) + beam_values.shape, dtype=np.float)
for pol_i, pair in enumerate(pairs):
power_data[:, :, pol_i] = (
interp_data[0, :, pair[0]] * np.conj(interp_data[0, :, pair[1]])
) + (interp_data[1, :, pair[0]] * np.conj(interp_data[1, :, pair[1]]))
interp_data = power_data
return interp_data, interp_basis_vector
def __eq__(self, other):
"""Evaluate equality with another object."""
if not isinstance(other, self.__class__):
return False
return self.beam_coeffs == other.beam_coeffs
class PerturbedPolyBeam(PolyBeam):
"""A :class:`PolyBeam` in which the shape of the beam has been modified.
The perturbations can be applied to the mainlobe, sidelobes, or
the entire beam. While the underlying :class:`PolyBeam` depends on
frequency via the `spectral_index` kwarg, the perturbations themselves do
not have a frequency dependence unless explicitly stated.
Mainlobe: A Gaussian of width FWHM is subtracted and then a new
Gaussian with width `mainlobe_width` is added back in. This perturbs
the width of the primary beam mainlobe, but leaves the sidelobes mostly
unchanged.
Sidelobes: The baseline primary beam model, PB, is moduled by a (sine)
Fourier series at angles beyond some zenith angle. There is an angle-
only modulation (set by `perturb_coeffs` and `perturb_scale`), and a
frequency-only modulation (set by `freq_perturb_coeffs` and
`freq_perturb_scale`).
Entire beam: May be sheared, stretched, and rotated.
Parameters
----------
beam_coeffs : array_like
Co-efficients of the baseline Chebyshev polynomial.
perturb_coeffs : array_like, optional
Array of floats with the coefficients of a (sine-only) Fourier
series that will be used to modulate the base Chebyshev primary
beam model.
perturb_scale : float, optional
Overall scale of the primary beam modulation. Must be less than 1,
otherwise the primary beam can go negative.
mainlobe_width : float
Width of the mainlobe, in radians. This determines the width of the
Gaussian mainlobe model that is subtracted, as well as the location
of the transition between the mainlobe and sidelobe regimes.
mainlobe_scale : float, optional
Factor to apply to the FHWM of the Gaussian that is used to rescale
the mainlobe.
transition_width : float, optional
Width of the smooth transition between the range of angles
considered to be in the mainlobe vs in the sidelobes, in radians.
xstretch, ystretch : float, optional
Stretching factors to apply to the beam in the x and y directions,
which introduces beam ellipticity, as well as an overall
stretching/shrinking. Default: 1.0 (no ellipticity or stretching).
rotation : float, optional
Rotation of the beam in the x-y plane, in degrees. Only has an
effect if xstretch != ystretch.
freq_perturb_coeffs : array_like, optional
Array of floats with the coefficients of a sine and cosine Fourier
series that will be used to modulate the base Chebyshev primary
beam model in the frequency direction. Default: None.
freq_perturb_scale : float, optional
Overall scale of the primary beam modulation in the frequency
direction. Must be less than 1, otherwise the primary beam can go
negative. Default: 0.
perturb_zeropoint : float, optional
If specified, override the automatical zero-point calculation for
the angle-dependent sidelobe perturbation. Default: None (use the
automatically-calculated zero-point).
spectral_index : float, optional
Spectral index of the frequency-dependent power law scaling to
apply to the width of the beam.
ref_freq : float, optional
Reference frequency for the beam width scaling power law, in Hz.
**kwargs
Any other parameters are used to initialize superclass :class:`PolyBeam`.
"""
def __init__(
self,
beam_coeffs=None,
perturb_coeffs=None,
perturb_scale=0.1,
mainlobe_width=0.3,
mainlobe_scale=1.0,
transition_width=0.05,
xstretch=1.0,
ystretch=1.0,
rotation=0.0,
freq_perturb_coeffs=None,
freq_perturb_scale=0.0,
perturb_zeropoint=None,
**kwargs
):
# Initialize base class
super().__init__(beam_coeffs=beam_coeffs, **kwargs)
# Check for valid input parameters
if mainlobe_width is None:
raise ValueError("Must specify a value for 'mainlobe_width' kwarg")
# Set sidelobe perturbation parameters
if perturb_coeffs is None:
perturb_coeffs = []
if freq_perturb_coeffs is None:
freq_perturb_coeffs = []
self.perturb_coeffs = np.array(perturb_coeffs)
self.freq_perturb_coeffs = np.array(freq_perturb_coeffs)
# Set all other parameters
self.perturb_scale = perturb_scale
self.freq_perturb_scale = freq_perturb_scale
self.mainlobe_width = mainlobe_width
self.mainlobe_scale = mainlobe_scale
self.transition_width = transition_width
self.xstretch, self.ystretch = xstretch, ystretch
self.rotation = rotation
# Calculate normalization of sidelobe perturbation functions on
# fixed grid (ensures rescaling is deterministic/independent of input
# to the interp() method)
za = np.linspace(0.0, np.pi / 2.0, 1000) # rad
freqs = np.linspace(100.0, 200.0, 1000) * 1e6 # Hz
p_za = self._sidelobe_modulation_za(za, scale=1.0, zeropoint=0.0)
p_freq = self._sidelobe_modulation_freq(freqs, scale=1.0, zeropoint=0.0)
# Rescale p_za to the range [-0.5, +0.5]
self._scale_pza, self._zeropoint_pza = 0.0, 0.0
if self.perturb_coeffs.size > 0:
self._scale_pza = 2.0 / (np.max(p_za) - np.min(p_za))
self._zeropoint_pza = -0.5 - 2.0 * np.min(p_za) / (
np.max(p_za) - np.min(p_za)
)
# Override calculated zeropoint with user-specified value
if perturb_zeropoint is not None:
self._zeropoint_pza = perturb_zeropoint
# Rescale p_freq to the range [-0.5, +0.5]
self._scale_pfreq, self._zeropoint_pfreq = 0.0, 0.0
if self.freq_perturb_coeffs.size > 0:
self._scale_pfreq = 2.0 / (np.max(p_freq) - np.min(p_freq))
self._zeropoint_pfreq = -0.5 - 2.0 * np.min(p_freq) / (
np.max(p_freq) - np.min(p_freq)
)
# Sanity checks
if self.perturb_scale >= 1.0:
raise ValueError(
"'perturb_scale' must be less than 1; otherwise "
"the beam can go negative."
)
if self.freq_perturb_scale >= 1.0:
raise ValueError(
"'freq_perturb_scale' must be less than 1; "
"otherwise the beam can go negative."
)
def _sidelobe_modulation_za(self, za_array, scale=1.0, zeropoint=0.0):
"""Calculate sidelobe modulation factor for a set of zenith angle values.
Parameters
----------
za_array : array_like
Array of zenith angles, in radians.
scale : float, optional
Multiplicative rescaling factor to be applied to the modulation
function. Default: 1.
zeropoint : float, optional
Zero-point correction to be applied to the modulation function.
Default: 0.
"""
# Construct sidelobe perturbations (angle-dependent)
p_za = 0
if self.perturb_coeffs.size > 0:
# Build Fourier (sine) series
f_fac = 2.0 * np.pi / (np.pi / 2.0) # Fourier series with period pi/2
for n in range(self.perturb_coeffs.size):
p_za += self.perturb_coeffs[n] * np.sin(f_fac * n * za_array)
return p_za * scale + zeropoint
def _sidelobe_modulation_freq(self, freq_array, scale=1.0, zeropoint=0.0):
"""Calculate sidelobe modulation factor for a set of frequency values.
Parameters
----------
freq_array : array_like
Array of frequencies, in Hz.
scale : float, optional
Multiplicative rescaling factor to be applied to the modulation
function. Default: 1.
zeropoint : float, optional
Zero-point correction to be applied to the modulation function.
Default: 0.
"""
# Construct sidelobe perturbations (frequency-dependent)
p_freq = 0
if self.freq_perturb_coeffs.size > 0:
# Build Fourier series (sine + cosine)
f_fac = 2.0 * np.pi / (100.0e6) # Fourier series with period 100 MHz
for n in range(self.freq_perturb_coeffs.size):
if n == 0:
fn = 1.0 + 0.0 * freq_array
elif n % 2 == 0:
fn = | |
1.0,Opti_all = 1,Surf_margin = 0)
# setting quadratic overdose
qod = self.modify_qod_551(Dose = int(item[2]+1.5),RMS = 0.25,Shrink_margin = 0,Opti_all = 0)
# combine them together
target = target + part2 + tar_pen[:-1] + qod[:-1]
target.append('!END\n')
else: ## external target
part2[1] = ' name=' + item[0] +'\n'
# setting target penalty
tar_pen_ext = self.modify_qp_551(Vol = item[1],Dose = item[2],Weight = 1.0,Opti_all = 1,Surf_margin = 0)
target = target + part2 + tar_pen_ext[:-1]
# first quadratic overdose to contrain inner target reigon to prevent hot dose release to low dose region
qod1 = self.modify_qod_551(Dose = tar[i-1][-1],RMS = 0.25,Shrink_margin = 0,Opti_all = 0)
target = target + qod1[:-1]
# second quadratic overdose to constarin 110% percent of external target dose region
qod2 = self.modify_qod_551(Dose = int(item[2]*1.1),RMS = 0.5,Shrink_margin = grid*2, Opti_all= 0)
target = target + qod2[:-1]
# third quadratic overdose to constrain 102% percent of external target dose region
qod3 = self.modify_qod_551(Dose = int(item[2]*1.02),RMS = 0.75,Shrink_margin = grid*3, Opti_all = 0)
target = target + qod3[:-1]
target.append('!END\n')
# OARs part
for item in OARs_nam:
'''
D_x_cc < y Gy => if x < 10, then two cost functions were added:
1. serial (k = 12, Isoconstraint(EUD) = 0.75*y)
2. maximum dose (isoconstraint = y)
D_x_% < y Gy
1. if 40% < x < 60%, then one cost function was added:
serial (k = 1, isocostraint = y)
2. if 20% < x < 40%, then one cost function was added:
serial (k = 8, isoconstraint = 0.95*y)
3. if 10% < x < 20%, then one cost function was added:
serial (k = 12, isoconstaraint = 0.85*y)
4. if 0% < x < 10%, then one cost function was added:
serial (k = 15, isoconstraint = 0.75*y)
'''
if item == 'Brain Stem':
part2[1] = ' name=' + item +'\n'
# select the maximum value from protocol request and 0.8*prescription dose
max_dose = max(float(self.protocol_dict[item][0][1].split('Gy')[0]),
0.8*tar[0][-1])
# select CF: maximum
cf = self.modify_mxd_551(Dose=int(max_dose),Weight=0.01,Opti_all=1,Shrink_margin=0)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
elif item == 'Spinal Cord':
part2[1] = ' name=' + item +'\n'
# select the maximum value from protocol request and 0.75*prescription dose
max_dose = max(float(self.protocol_dict[item][0][1].split('Gy')[0]),
0.75*tar[0][-1])
# select CF:maximum
cf = self.modify_mxd_551(Dose=int(max_dose),Weight=0.01,Opti_all=1,Shrink_margin=0)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
elif item == 'Optical Chiasm' or item == 'Optical Nerve L' or item == 'Optical Nerve R':
part2[1] = ' name=' + item +'\n'
# select the maximum value from protocol request and 0.75*prescription dose
max_dose = max(float(self.protocol_dict[item][0][1].split('Gy')[0]),
0.75*tar[0][-1])
# select CF:maximum
cf = self.modify_mxd_551(Dose=int(max_dose),Weight=0.01,Opti_all=1,Shrink_margin=0)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
elif item == 'Lens R' or item == 'Lens L':
part2[1] = ' name=' + item +'\n'
# select the maximum value from protocol request
max_dose = float(self.protocol_dict[item][0][1].split('Gy')[0])
# select CF:maximum
cf = self.modify_mxd_551(Dose=int(max_dose),Weight=0.01,Opti_all=1,Shrink_margin=0)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
elif item == 'Eye R' or item == 'Eye L':
part2[1] = ' name=' + item +'\n'
if '%' in self.protocol_dict[item][0][0]:
percent = float(self.protocol_dict[item][0][0].split('D')[1].split('%')[0])
if percent < 10:
# select CF: maximum
max_dose = float(self.protocol_dict[item][0][1].split('Gy')[0])
cf = self.modify_mxd_551(Dose=int(max_dose),Weight=0.01,Opti_all=1,Shrink_margin=0)
elif percent < 35:
# select CF: serial
eud_dose = 0.75*tar[0][-1]
cf = self.modify_se_551(Dose=int(eud_dose),Weight=0.01,Shrink_margin=0,Opti_all=0,Powe_Law=12)
elif 'cc' in self.protocol_dict[item][0][0]:
vol = float(self.protocol_dict[item][0][0].split('D')[1].split('cc')[0])
if vol < 10:
# select CF: maximum
max_dose = float(self.protocol_dict[item][0][1].split('Gy')[0])
cf = self.modify_mxd_551(Dose=int(max_dose),Weight=0.01,Opti_all=1,Shrink_margin=0)
elif vol < 35:
# select CF: serial
eud_dose = 0.75*tar[0][-1]
cf = self.modify_se_551(Dose=int(eud_dose),Weight=0.01,Shrink_margin=0,Opti_all=0,Powe_Law=12)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
elif item == 'Parotid R' or item == 'Parotid L':
part2[1] = ' name=' + item +'\n'
# select CF1: serial (constrain high dose region)
eud_dose1 = 0.5*tar[0][-1]
cf1 = self.modify_se_551(Dose= eud_dose1,Weight=0.01,Shrink_margin=grid,Opti_all=0,Powe_Law=12)
OARs = OARs + part2 + cf1[:-1]
# select CF2: serial (constrain mean dose)
eud_dose2 = float(self.protocol_dict[item][0][1].split('Gy')[0])
cf2 = self.modify_se_551(Dose= eud_dose2,Weight=0.01,Shrink_margin=0,Opti_all=1,Powe_Law=1)
OARs = OARs + cf2[:-1]
OARs.append('!END\n')
elif item == 'Oral Cavity':
part2[1] = ' name=' + item +'\n'
# select CF1: serial (constrain high dose region)
eud_dose = 0.65*tar[0][-1]
cf1 = self.modify_se_551(Dose= int(eud_dose),Weight=0.01,Shrink_margin=grid,Opti_all=0,Powe_Law=12)
OARs = OARs + part2 + cf1[:-1]
# select CF2: serial (constrain mean dose, eud = pro_dose+2Gy)
eud_dose = float(self.protocol_dict[item][0][1].split('Gy')[0])
cf2 = self.modify_se_551(Dose= int(eud_dose),Weight=0.01,Shrink_margin=0,Opti_all=0,Powe_Law=1)
OARs = OARs + cf2[:-1]
OARs.append('!END\n')
elif item == 'Larynx':
part2[1] = ' name=' + item +'\n'
# select CF1: serial (constrain high dose region)
eud_dose = 0.65*tar[0][-1]
cf1 = self.modify_se_551(Dose= int(eud_dose),Weight=0.01,Shrink_margin=grid,Opti_all=0,Powe_Law=12)
OARs = OARs + part2 + cf1[:-1]
# select CF2: parallel (constrain mean dose, eud = pro_dose+2Gy)
max_dose = float(self.protocol_dict[item][0][1].split('Gy')[0])
cf2 = self.modify_pa_551(Ref_dose= int(max_dose),Volume = 50, Weight=0.01,Powe_Law=4,Opti_all=1,Shrink_margin=0)
OARs = OARs + cf2[:-1]
OARs.append('!END\n')
elif item == 'Pitutary' or item == 'Pituitary':
part2[1] = ' name=' + item +'\n'
# select CF: Parallel (constrain D50% and optimize all)
max_dose = float(self.protocol_dict[item][0][1].split('Gy')[0])
cf = self.modify_pa_551(Ref_dose= int(max_dose),Volume = 50, Weight=0.01,Powe_Law=4,Opti_all=1,Shrink_margin=0)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
elif item == 'T.Lobe R' or item == 'T.Lobe L':
part2[1] = ' name=' + item +'\n'
# select CF: Serial (constrain high dose region)
eud_dose = float(self.protocol_dict[item][0][1].split('Gy')[0])
cf1 = self.modify_se_551(Dose= int(eud_dose),Weight=0.01,Shrink_margin=grid,Opti_all=0,Powe_Law=12)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
elif item == 'Brain':
part2[1] = ' name=' + item +'\n'
# select CF: Maximum (Constrain D5%)
max_dose = float(self.protocol_dict[item][0][1].split('Gy')[0])
cf = self.modify_mxd_551(Dose= int(max_dose)+5,Weight=0.01,Opti_all=1,Shrink_margin=0)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
elif item == 'Mandible':
part2[1] = ' name=' + item +'\n'
# select CF1: Quadratic Overdose(Constrain D2cc/Max Dose)
max_dose = tar[0][-1]
cf1 = self.modify_qod_551(Dose= int(max_dose),RMS = 0.25,Shrink_margin = 0, Opti_all = 0)
# cf1 = self.modify_mxd(Dose=max_dose,Weight=0.01,Opti_all=1,Shrink_margin=0)
# cf1 = self.modify_se(Dose= max_dose*0.75,Weight=0.01,Shrink_margin=0.25,Opti_all=0,Powe_Law=12)
OARs + part2 + cf1[:-1]
# select CF1: Serial (Constrain D50% dose )
eud_dose = tar[0][-1]*0.6
cf2 = self.modify_se_551(Dose= int(eud_dose),Weight=0.01,Shrink_margin=0,Opti_all=0,Powe_Law=1)
OARs = OARs + cf2[:-1]
OARs.append('!END\n')
elif item == 'A.D L' or item == 'A.D R' or item == 'T.Joint R' or item == 'T.Joint L':
part2[1] = ' name=' + item +'\n'
# select CF: Parallel (Constrain D50% dose )
max_dose = float(self.protocol_dict[item][0][1].split('Gy')[0])
cf = self.modify_pa_551(Ref_dose= int(max_dose),Volume = 50, Weight=0.01,Powe_Law=4,Opti_all=0,Shrink_margin=0)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
elif item == 'Lung':
part2[1] = ' name=' + item +'\n'
# select CF: Serial (Constrain high dose )
eud_dose = tar[0][-1]*0.6
cf = self.modify_se_551(Dose= int(eud_dose),Weight=0.01,Shrink_margin=grid,Opti_all=0,Powe_Law=12)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
# assistance structure like SPPRV,BSPRV,R6,R7
elif item == 'SPPRV':
part2[1] = ' name=' + item +'\n'
# select CF: Maximum (Constrain high dose )
max_dose = tar[-1][-1]*0.6
cf = self.modify_mxd_551(Dose= int(max_dose), Weight=0.01, Opti_all=1, Shrink_margin=0)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
elif item == 'BSPRV':
part2[1] = ' name=' + item +'\n'
# select CF: Maximum (Constrain high dose )
max_dose = tar[-1][-1]*0.7
cf = self.modify_mxd_551(Dose= int(max_dose), Weight=0.01, Opti_all=1, Shrink_margin=0)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
elif item == 'R6' or item == 'R7':
part2[1] = ' name=' + item +'\n'
# select CF: Maximum (Constrain high dose )
max_dose = tar[-1][-1]*0.7
cf = self.modify_mxd_551(Dose= int(max_dose), Weight=0.01, Opti_all=1, Shrink_margin=0)
OARs = OARs + part2 + cf[:-1]
OARs.append('!END\n')
elif item == 'BODY' or item == 'Patient' or item == 'Body': ## patient
part2[1] = ' name=' + item +'\n'
| |
'
'<button type="submit" name="restexplorerop" '
'value="delete" formaction="{0}">delete'
'</button>').format(self.href, self.rel, extension)
else:
return '<a href="{0}{1}" rel="{0}">{0}{1}</a>'.format(self.href,
extension)
# TODO(jjohnson2): enhance the following to support expressions:
# InputNetworkConfiguration
# InputMCI
# InputDomainName
# InputNTPServer
def get_input_message(path, operation, inputdata, nodes=None, multinode=False,
configmanager=None):
if path[0] == 'power' and path[1] == 'state' and operation != 'retrieve':
return InputPowerMessage(path, nodes, inputdata)
elif (path in (['power', 'reseat'], ['_enclosure', 'reseat_bay']) and
operation != 'retrieve'):
return InputReseatMessage(path, nodes, inputdata)
elif path == ['attributes', 'expression']:
return InputExpression(path, inputdata, nodes)
elif path == ['attributes', 'rename']:
return InputConfigChangeSet(path, inputdata, nodes, configmanager)
elif path[0] in ('attributes', 'users', 'usergroups') and operation != 'retrieve':
return InputAttributes(path, inputdata, nodes)
elif path == ['boot', 'nextdevice'] and operation != 'retrieve':
return InputBootDevice(path, nodes, inputdata)
elif (len(path) == 5 and
path[:4] == ['configuration', 'management_controller', 'alerts',
'destinations'] and operation != 'retrieve'):
return InputAlertDestination(path, nodes, inputdata, multinode)
elif path == ['identify'] and operation != 'retrieve':
return InputIdentifyMessage(path, nodes, inputdata)
elif path == ['events', 'hardware', 'decode']:
return InputAlertData(path, inputdata, nodes)
elif (path[:3] == ['configuration', 'management_controller', 'users'] and
operation not in ('retrieve', 'delete') and path[-1] != 'all'):
return InputCredential(path, inputdata, nodes)
elif (path[:3] == ['configuration', 'management_controller', 'reset']
and operation != 'retrieve'):
return InputBMCReset(path, nodes, inputdata)
elif (path[:3] == ['configuration', 'management_controller', 'identifier']
and operation != 'retrieve'):
return InputMCI(path, nodes, inputdata)
elif (path[:3] == ['configuration', 'management_controller', 'hostname']
and operation != 'retrieve'):
return InputHostname(path, nodes, inputdata, configmanager)
elif (path[:4] == ['configuration', 'management_controller',
'net_interfaces', 'management'] and operation != 'retrieve'):
return InputNetworkConfiguration(path, nodes, inputdata,
configmanager)
elif (path[:3] == ['configuration', 'management_controller', 'domain_name']
and operation != 'retrieve'):
return InputDomainName(path, nodes, inputdata)
elif (path[:4] == ['configuration', 'management_controller', 'ntp',
'enabled'] and operation != 'retrieve'):
return InputNTPEnabled(path, nodes, inputdata)
elif (path[:4] == ['configuration', 'management_controller', 'ntp',
'servers'] and operation != 'retrieve' and len(path) == 5):
return InputNTPServer(path, nodes, inputdata)
elif (path[:3] in (['configuration', 'system', 'all'],
['configuration', 'management_controller', 'extended']) and
operation != 'retrieve'):
return InputConfigChangeSet(path, inputdata, nodes, configmanager)
elif (path[0] == 'configuration' and path[2] == 'clear' and
operation != 'retrieve'):
return InputConfigClear(path, inputdata, nodes, configmanager)
elif (path[:3] == ['configuration', 'storage', 'disks'] and
operation != 'retrieve'):
return InputDisk(path, nodes, inputdata)
elif (path[:3] == ['configuration', 'storage', 'volumes'] and
operation in ('update', 'create')):
return InputVolumes(path, nodes, inputdata)
elif 'inventory/firmware/updates/active' in '/'.join(path) and inputdata:
return InputFirmwareUpdate(path, nodes, inputdata, configmanager)
elif '/'.join(path).startswith('media/detach'):
return DetachMedia(path, nodes, inputdata)
elif '/'.join(path).startswith('media/') and inputdata:
return InputMedia(path, nodes, inputdata, configmanager)
elif '/'.join(path).startswith('support/servicedata') and inputdata:
return InputMedia(path, nodes, inputdata, configmanager)
elif '/'.join(path).startswith('configuration/management_controller/save_licenses') and inputdata:
return InputMedia(path, nodes, inputdata, configmanager)
elif '/'.join(path).startswith(
'configuration/management_controller/licenses') and inputdata:
return InputLicense(path, nodes, inputdata, configmanager)
elif inputdata:
raise exc.InvalidArgumentException(
'No known input handler for request')
class InputFirmwareUpdate(ConfluentMessage):
def __init__(self, path, nodes, inputdata, configmanager):
self._filename = inputdata.get('filename', inputdata.get('url', inputdata.get('dirname', None)))
self.bank = inputdata.get('bank', None)
self.nodes = nodes
self.filebynode = {}
self._complexname = False
for expanded in configmanager.expand_attrib_expression(
nodes, self._filename):
node, value = expanded
if value != self._filename:
self._complexname = True
self.filebynode[node] = value
@property
def filename(self):
if self._complexname:
raise Exception('User requested substitutions, but code is '
'written against old api, code must be fixed or '
'skip {} expansion')
if self.filebynode[node].startswith('/etc/confluent'):
raise Exception(
'File transfer with /etc/confluent is not supported')
if self.filebynode[node].startswith('/var/log/confluent'):
raise Exception(
'File transfer with /var/log/confluent is not supported')
return self._filename
def nodefile(self, node):
if self.filebynode[node].startswith('/etc/confluent'):
raise Exception(
'File transfer with /etc/confluent is not supported')
if self.filebynode[node].startswith('/var/log/confluent'):
raise Exception(
'File transfer with /var/log/confluent is not supported')
return self.filebynode[node]
class InputMedia(InputFirmwareUpdate):
# Use InputFirmwareUpdate
pass
class InputLicense(InputFirmwareUpdate):
pass
class DetachMedia(ConfluentMessage):
def __init__(self, path, nodes, inputdata):
if 'detachall' not in inputdata:
raise exc.InvalidArgumentException('Currently only supporting'
'{"detachall": 1}')
class Media(ConfluentMessage):
def __init__(self, node, media=None, rawmedia=None):
if media:
rawmedia = {'name': media.name, 'url': media.url}
self.myargs = (node, None, rawmedia)
self.kvpairs = {node: rawmedia}
class SavedFile(ConfluentMessage):
def __init__(self, node, file):
self.myargs = (node, file)
self.kvpairs = {node: {'filename': file}}
class InputAlertData(ConfluentMessage):
def __init__(self, path, inputdata, nodes=None):
self.alertparams = inputdata
# first migrate snmpv1 input to snmpv2 format
if 'specifictrap' in self.alertparams:
# If we have a 'specifictrap', convert to SNMPv2 per RFC 2576
# This way
enterprise = self.alertparams['enterprise']
specifictrap = self.alertparams['specifictrap']
self.alertparams['.1.3.6.1.6.3.1.1.4.1.0'] = enterprise + '.0.' + \
str(specifictrap)
if '1.3.6.1.6.3.1.1.4.1.0' in self.alertparams:
self.alertparams['.1.3.6.1.6.3.1.1.4.1.0'] = \
self.alertparams['1.3.6.1.6.3.1.1.4.1.0']
if '.1.3.6.1.6.3.1.1.4.1.0' not in self.alertparams:
raise exc.InvalidArgumentException('Missing SNMP Trap OID')
def get_alert(self, node=None):
return self.alertparams
class InputExpression(ConfluentMessage):
# This is specifically designed to suppress the expansion of an expression
# so that it can make it intact to the pertinent configmanager function
def __init__(self, path, inputdata, nodes=None):
self.nodeattribs = {}
if not inputdata:
raise exc.InvalidArgumentException('no request data provided')
if nodes is None:
self.attribs = inputdata
return
for node in nodes:
self.nodeattribs[node] = inputdata
def get_attributes(self, node):
if node not in self.nodeattribs:
return {}
nodeattr = deepcopy(self.nodeattribs[node])
return nodeattr
class InputConfigClear(ConfluentMessage):
def __init__(self, path, inputdata, nodes=None, configmanager=None):
if not inputdata:
raise exc.InvalidArgumentException('no request data provided')
if 'clear' not in inputdata or not inputdata['clear']:
raise exc.InvalidArgumentException('Input must be {"clear":true}')
class InputConfigChangeSet(InputExpression):
def __init__(self, path, inputdata, nodes=None, configmanager=None):
self.cfm = configmanager
super(InputConfigChangeSet, self).__init__(path, inputdata, nodes)
def get_attributes(self, node):
attrs = super(InputConfigChangeSet, self).get_attributes(node)
endattrs = {}
for attr in attrs:
origval = attrs[attr]
if isinstance(origval, bytes) or isinstance(origval, unicode):
origval = {'expression': origval}
if 'expression' not in origval:
endattrs[attr] = attrs[attr]
else:
endattrs[attr] = list(self.cfm.expand_attrib_expression(
[node], attrs[attr]))[0][1]
return endattrs
class InputAttributes(ConfluentMessage):
# This is particularly designed for attributes, where a simple string
# should become either a string value or a dict with {'expression':} to
# preserve the client provided expression for posterity, rather than
# immediate consumption.
# for things like node configuration or similar, a different class is
# appropriate since it needs to immediately expand an expression.
# with that class, the 'InputExpression' and calling code in attributes.py
# might be deprecated in favor of the generic expression expander
# and a small function in attributes.py to reflect the expansion back
# to the client
def __init__(self, path, inputdata, nodes=None):
self.nodeattribs = {}
if not inputdata:
raise exc.InvalidArgumentException('no request data provided')
if nodes is None:
self.attribs = inputdata
for attrib in self.attribs:
if not cfm.attrib_supports_expression(attrib):
continue
if type(self.attribs[attrib]) in (bytes, unicode):
try:
# ok, try to use format against the string
# store back result to the attribute to
# handle things like '{{' and '}}'
# if any weird sort of error should
# happen, it means the string has something
# that formatter is looking to fulfill, but
# is unable to do so, meaning it is an expression
tv = self.attribs[attrib].format()
self.attribs[attrib] = tv
except (KeyError, IndexError):
# this means format() actually thought there was work
# that suggested parameters, push it in as an
# expression
self.attribs[attrib] = {
'expression': self.attribs[attrib]}
return
for node in nodes:
self.nodeattribs[node] = inputdata
def get_attributes(self, node, validattrs=None):
if node not in self.nodeattribs:
return {}
nodeattr = deepcopy(self.nodeattribs[node])
for attr in nodeattr:
if type(nodeattr[attr]) in (bytes, unicode) and cfm.attrib_supports_expression(attr):
try:
# as above, use format() to see if string follows
# expression, store value back in case of escapes
tv = nodeattr[attr].format()
nodeattr[attr] = str(tv)
except (KeyError, IndexError):
# an expression string will error if format() done
# use that as cue to put it into config as an expr
nodeattr[attr] = {'expression': nodeattr[attr]}
if validattrs and 'validvalues' in validattrs.get(attr, []):
if (nodeattr[attr] and
nodeattr[attr] not in validattrs[attr]['validvalues']):
raise exc.InvalidArgumentException(
'Attribute {0} does not accept value {1} (valid values would be {2})'.format(
attr, nodeattr[attr], ','.join(validattrs[attr]['validvalues'])))
elif validattrs and 'validlist' in validattrs.get(attr, []) and nodeattr[attr]:
req = nodeattr[attr].split(',')
for v in req:
if v and v not in validattrs[attr]['validlist']:
raise exc.InvalidArgumentException(
'Attribute {0} does not accept list member '
'{1} (valid values would be {2})'.format(
attr, v, ','.join(
validattrs[attr]['validlist'])))
elif validattrs and 'validlistkeys' in validattrs.get(attr, []) and nodeattr[attr]:
req = nodeattr[attr].split(',')
for v in req:
if '=' not in v:
raise exc.InvalidArgumentException(
'Passed key {0} requires a parameter'.format(v))
v = v.split('=', 1)[0]
if v and v not in validattrs[attr]['validlistkeys']:
raise exc.InvalidArgumentException(
'Attribute {0} does not accept key {1} (valid values would be {2})'.format(
attr, v, ','.join(
validattrs[attr]['validlistkeys'])
)
)
return nodeattr
def checkPassword(password, username):
lowercase = set('abcdefghijklmnopqrstuvwxyz')
uppercase = | |
<reponame>raalesir/private_swedish_mind<gh_stars>1-10
"""
The main file for the package
==============================
"""
import geopandas as gpd
import pandas as pd
from shapely.geometry import Point
from geovoronoi import voronoi_regions_from_coords, points_to_coords
import matplotlib.pyplot as plt
import numpy as np
import os
import logging
import collections
try:
from private_swedish_mind.utils import make_hist_mpn_geoms, get_rings_around_cell,make_group_col,get_vcs_used_area,\
get_splits, make_group_load_col
from private_swedish_mind.consts import *
import private_swedish_mind.plots
except ModuleNotFoundError:
from utils import make_hist_mpn_geoms, get_rings_around_cell, make_group_col, get_vcs_used_area,\
get_splits, make_group_load_col
from consts import *
import plots
# import logging.handlers
# SOURCE_EPSG = 4326
# WGS84_EPSG = 3857
# SWEREF_EPSG = 3006
G3_ANTENNAS_PATH = "antennas/UMTS.CSV.gz"
G4_ANTENNAS_PATH = "antennas/LTE.CSV.gz"
SWEREF_EPSG_uppsala = (647742, 6638924)
# pd.set_option('display.max_colwidth', None)
SVERIGE_CONTOUR = 'sverige_contour/sverige.shp'
ALLA_KOMMUNER = 'alla_kommuner/alla_kommuner.shp'
# column names of the DF
geometry_gps_csv = 'geometry_gps_csv'
geometry_mpn_csv = 'geometry_mpn_csv'
vc_index_gps = 'vc_index_gps'
vc_index_mpn = 'vc_index_mpn'
vc_gps_rings = 'vc_gps_rings'
hist = 'hist'
timestamp = 'timestamp'
# columns in antennas files
lat = 'llat'
long = 'llong'
SE_SHAPEFILES = 'se_shapefiles/se_1km.shp'
DATA_DIR = 'data'
ANTENNAS_LOAD_DIR = 'data/antennas_load'
class AnalyseBasicJoinedData:
"""
Class handles input files with the schema: `['timestamp', 'geometry_gps_csv', 'geometry_mpn_csv']`,
where `timestamp` is a timestamp, `geometry_gps_csv` is string representation of a list of length one, which element is a position in a
`WGS84_EPSG` projection. The `geometry_mpn_csv` is a string representation of a list which element is a position in a
`WGS84_EPSG` projection.
"""
def __init__(self, point, n_layers):
"""
creates object
:param point: tuple like (647742, 6638924) describing a point within Lan, in SWEREF_EPSG
:param n_layers: number of layers of Voronoi cells to build
"""
logger.info("reading data")
self.df = self.read_data()
logger.info("reading antennas")
self.antennas_data = self.read_antennas()
logger.info('making bounding area')
self.contour = self._get_bounding_area(point=point)
self.vcs = None
self.n_layers = n_layers
self.most_used_antennas = None
logger.info("reading antennas load files")
self.antennas_load = self.read_antennas_load()
@staticmethod
def read_data():
"""
reading data from the folder `DATA_DIR` which start with `result`.
Returns Pandas DF, as a concatenation of all files
:return: Pandas DF with `['timestamp', 'geometry_gps_csv', 'geometry_mpn_csv']` columns
"""
paths = sorted(
[os.path.join(DATA_DIR, f) for f in os.listdir(DATA_DIR) if f.startswith('result')]
)
dfs = []
for path in paths:
try:
tmp = pd.read_csv(path, parse_dates=[timestamp])[
[timestamp, geometry_gps_csv, geometry_mpn_csv]]
logger.info("number of lines: %s, location %s " %(tmp.shape[0], path))
# tmp = tmp.drop_duplicates(subset=['geometry_gps_csv'])
# print(tmp.shape[0], path)
dfs.append(tmp)
except IOError:
logger.error('path %s is wrong. check it.' % path)
pass
except KeyError:
logger.warning("some keys are missing... check it at: %s" % path)
pass
return pd.concat(dfs, axis=0, ignore_index=True)
@staticmethod
def read_antennas_load():
"""
reading data for given dates
"""
paths = sorted([os.path.join(ANTENNAS_LOAD_DIR, f) for f in os.listdir(ANTENNAS_LOAD_DIR)])
dfs = []
for path in paths:
try:
tmp = pd.read_csv(path)
logger.info("number of lines: %s, location %s " %(tmp.shape[0], path))
dfs.append(tmp)
except IOError:
logger.error('path %s is wrong. check it.' % path)
pass
except KeyError:
logger.warning("some keys are missing... check it at: %s" % path)
pass
return pd.concat(dfs, axis=0, ignore_index=True)
def transform_df(self, ):
"""
transforms string representation of a list to a Shapely point, and
groups the data for each timestamp.
:return: GeoPandas DF with `timestamp`, Point(), [Point(), Point(), ... Point()] schema
"""
df = self.df
self.df[geometry_gps_csv] = self.df[geometry_gps_csv].apply(
lambda lst: Point(float(lst[1:-1].split(',')[0]),
float(lst[1:-1].split(',')[1]))
)
self.df[geometry_mpn_csv] = self.df[geometry_mpn_csv].apply(
lambda lst: Point(float(lst[1:-1].split(',')[0]),
float(lst[1:-1].split(',')[1]))
)
self.df = self.df.groupby(timestamp).agg({geometry_gps_csv: "first", geometry_mpn_csv: list})
self.df = gpd.GeoDataFrame(self.df, geometry=geometry_gps_csv, crs=WGS84_EPSG) # .to_crs(SWEREF_EPSG)
# return df
def remove_too_often_antennas(self):
"""
:return:
"""
most_common_antennas = collections.Counter(self.df[geometry_mpn_csv]).most_common(50)
# antennas[0].__str__()
# print(most_common_antennas)
most_common_antennas_name = [p[0] for p in most_common_antennas]
self.most_used_antennas = most_common_antennas
self.df = self.df[
~self.df[geometry_mpn_csv].isin(most_common_antennas_name[:6])
]
def process_position_data(self):
"""
:return:
"""
logger.info("before removing too often used antennas: %s" %str(self.df.shape))
self.remove_too_often_antennas()
logger.info("after removing too often used antennas: %s" %str(self.df.shape))
logger.info("antennas before filtering %s" %str(self.antennas_data.shape))
logger.info('filtering antennas data to be inside contour')
self.antennas_data = self.get_objects_within_area(self.antennas_data)
logger.info("antennas after filtering: %s " % str(self.antennas_data.shape))
logger.info('making voronoi polygons')
self.vcs = self.create_voronoi_polygons().to_crs(WGS84_EPSG)
logger.info("processing data")
self.transform_df()
logger.info("processed data shape: %s" % str(self.df.shape))
logger.info('filtering data to be inside contour')
logger.info("data before filtering: %s" %str(self.df.shape))
self.df = self.get_objects_within_area(self.df.to_crs(SWEREF_EPSG), geom=geometry_gps_csv).to_crs(WGS84_EPSG)
logger.info("data after filtering: %s" %str(self.df.shape))
logger.info('adding add_vcs_indexes')
self.add_vcs_indexes()
logger.info('adding rings column')
self.add_rings_column()
logger.info("adding hist column")
self.add_hist_column()
logger.info("adding hist groups...")
self.add_hist_groups_column()
logger.info("adding distance column")
self.add_distance_column()
logger.info("processing antennas load")
self.antennas_load = self.process_antennas_load()
logger.info('done')
logger.info("adding loads columns")
self.add_hist_load_group_columns()
return self.df
def process_antennas_load(self, coarse_grain_factor=100):
"""
processing coords and summing up load for each position
"""
self.antennas_load['X'] = coarse_grain_factor * ((self.antennas_load['avg_X'] / coarse_grain_factor).astype('int'))
self.antennas_load['Y'] = coarse_grain_factor * ((self.antennas_load['avg_Y'] / coarse_grain_factor).astype('int'))
self.antennas_load = self.antennas_load.groupby(['X', 'Y']).agg({'num_ids_list': 'sum', 'num_ids_set': 'sum'}) \
.reset_index()
self.antennas_data['X'] = self.antennas_data['geometry'].apply(
lambda val: coarse_grain_factor * int(val.x / coarse_grain_factor))
self.antennas_data['Y'] = self.antennas_data['geometry'].apply(
lambda val: coarse_grain_factor * int(val.y / coarse_grain_factor))
antennas_within_loads = pd.merge(self.antennas_load, self.antennas_data, how='right', left_on=['X', 'Y'],
right_on=['X', 'Y'])
return antennas_within_loads
@staticmethod
def read_antennas():
"""
reads and prepares antennas for whole Sweden.
Returns a GeoPandas df with the antennas.
"""
try:
g3 = pd.read_csv(G3_ANTENNAS_PATH, sep=';')[[lat, long]]
g4 = pd.read_csv(G4_ANTENNAS_PATH, sep=';')[[lat, long]]
antennas = pd.concat([g3, g4]).round(3).drop_duplicates()
antennas_gdp = gpd.GeoDataFrame(antennas, geometry=gpd.points_from_xy(antennas.llong, antennas.llat),
crs=SOURCE_EPSG)[['geometry']] \
.to_crs(SWEREF_EPSG)
return antennas_gdp
except IOError:
logger.error("something is wrong with the antennas files: %s, %s"%(G3_ANTENNAS_PATH, G4_ANTENNAS_PATH))
return None
def _get_bounding_area(self, point=None):
"""
returns bounding area.
It could be either the whole Sweden, or it's Lan. In the last case one need to provide a point within that lan in
Sweref99 format.
"""
if point:
contour = self._find_area(point)
else:
try:
contour = gpd.read_file(SVERIGE_CONTOUR)
contour.crs = WGS84_EPSG
contour.to_crs(SWEREF_EPSG, inplace=True)
except IOError:
logger.error('error reading contour file: %s ' %SVERIGE_CONTOUR)
return contour
def _find_area(self, point):
"""
given a point within the area find that area in the table.
Returns geoPandas DF with the geometry
:param point: tuple representing point within Sverige Lan
:return: GeoPandas DF with the Lan for the Point
"""
sweden = None
try:
sweden = gpd.read_file(ALLA_KOMMUNER)
sweden.crs = SWEREF_EPSG
except IOError:
logger.error('failed to read %s' % ALLA_KOMMUNER)
uppsala = Point(point)
uppsala_lan = None
for index, row in sweden.iterrows():
if uppsala.within(sweden.iloc[index].geometry):
uppsala_lan = sweden.iloc[index:index + 1].reset_index()
if not uppsala_lan.empty:
return uppsala_lan
else:
logger.error('failed to find point %s in %s' % (point, ALLA_KOMMUNER))
# def get_vcs_for_bounding_area(self):
# """
# returns Voronoi cells and their centers
# """
# if self.contour.crs == self.antennas_data.crs:
# self.get_objects_within_area()
# voronoi_polygons = self.create_voronoi_polygons()
#
# return antennas_within, voronoi_polygons
# else:
# print("objects have differrent CRSs....")
# return None, None
def get_objects_within_area(self, objects, geom='geometry'):
"""
given objects and bounding geometry find which objects are within the geometry
Returns a GeoPandas DF
"""
if objects.crs == self.contour.crs:
objects_within = []
for i, row in objects.iterrows():
if row[geom].within(self.contour.geometry[0]):
objects_within.append(row)
if objects_within:
return gpd.GeoDataFrame(objects_within, geometry=geom, crs=objects.crs).reset_index(drop=False)
else:
logger.error("no objects found within area! ")
else:
logger.error('Objects have different CRSs: %s and %s ' % (objects.crs, self.contour.crs))
# return None
def create_voronoi_polygons(self):
"""
creates Voronoi polygons with `self.antennas_data` as centers, bounded by `self.contour`
:return: GeoPandas DF with VCs
"""
if self.antennas_data.crs == self.contour.crs:
coords = points_to_coords(self.antennas_data.geometry)
poly_shapes, pts = voronoi_regions_from_coords(coords, self.contour.geometry[0])
voronoi_polygons = gpd.GeoDataFrame({'geometry': poly_shapes}, crs=SWEREF_EPSG)
return voronoi_polygons
else:
logger.error('Objects have different CRSs: %s and %s ' % (self.antennas_data.crs, self.contour.crs))
def add_vcs_indexes(self):
"""
Adding indexes of Voronoi cell from `vcs` for GPS and MPN points for given `df`
"""
if self.df.crs == self.vcs.crs:
vc_gps_points = []
vc_mpn_points = []
temp = self.vcs.geometry
for point in self.df.geometry_gps_csv:
for i, vc in enumerate(temp):
if point.within(vc): vc_gps_points.append(i)
for points in self.df.geometry_mpn_csv:
t = []
for point in points:
for i, vc in enumerate(temp):
if point.within(vc): t.append(i)
vc_mpn_points.append(t)
# print(self.df.shape, len(vc_gps_points))
self.df[vc_index_gps] = vc_gps_points
self.df[vc_index_mpn] = vc_mpn_points
# return df
else:
logger.error('Objects have different CRSs: %s and %s '%(self.df.crs, self.vcs.crs))
# return None
def add_rings_column(self):
"""
constructing rings column `vc_gps_rings` centered around `vc_index_gps`.
The number of layers is given by `self.n_layers`.
:return: `vc_gps_rings` column to `self.df`
"""
tmp = self.vcs.to_crs(WGS84_EPSG)
# vc_used, area = get_vcs_used_area(tmp, self.df[[vc_index_gps, vc_index_mpn]], area_max=200)
self.df[vc_gps_rings] = self.df.apply(lambda row: get_rings_around_cell(row[vc_index_gps], tmp, self.n_layers), axis=1)
def add_hist_column(self):
"""
adding histogram by looping through mnp-indexes and vc-indexes
:return: column `hist` to `self.df`
"""
self.df[hist] = self.df.apply(lambda row: make_hist_mpn_geoms(row[vc_index_mpn], row[vc_gps_rings]),
axis=1)
def add_hist_groups_column(self):
"""
adding histograms for different groups of VC sizes
:return:
"""
tmp = self.vcs.to_crs(WGS84_EPSG)
vc_used, area = get_vcs_used_area(tmp, self.df[[vc_index_gps, vc_index_mpn]], area_max=200)
size_borders = get_splits(area, 3, make_int=False)
for key, size_ in enumerate(size_borders):
self.df['group' + str(key)] = self.df.apply(lambda row:
make_group_col(row[vc_index_mpn], tmp, size_),
axis=1)
self.df[hist + str(key)] = self.df[[hist, 'group' + str(key)]].apply(
lambda row: [el[0] for el in zip(row[hist], row['group' + str(key)]) if el[1] == True],
axis=1)
def add_hist_load_group_columns(self):
"""
adding columns for different load groups
:return:
"""
tmp = gpd.GeoDataFrame(self.antennas_load, crs=SWEREF_EPSG).to_crs(WGS84_EPSG)
| |
str is required"
)
if not isinstance(value, str):
raise TypeError(
f"{node} has {type(value).__name__} in env value for {key} when str is required"
)
res = {
"edges": [],
"nodes": [],
"images": self.repo.images,
"token": self.token,
"autorun": self._autorun,
"sleep_when_done": self._sleep_when_done,
}
queue = collections.deque([self])
while queue:
node = queue.popleft()
validate_env(node)
node._pull()
res["nodes"].append(
{k: v for k, v in node.describe().items() if v is not None}
)
for name, child in node.children.items():
queue.append(child)
res["edges"].append([node, child, name])
class NodeEncoder(json.JSONEncoder):
def default(self, o):
try:
return o._id
except AttributeError:
return o
if pretty:
import pprint
return pprint.pformat(res)
output = json.dumps(res, cls=NodeEncoder)
return base64.b64encode(
gzip.compress(output.encode(), compresslevel=3)
).decode()
@staticmethod
def deserialize(string):
string = gzip.decompress(base64.b64decode(string))
data = json.loads(string)
nodes = {i["id"]: load_node(**i) for i in data["nodes"]}
for i in data["nodes"]:
for event, cb_literal in i.get("callbacks", []):
cb, cb_args = cb_literal
kwargs = {
k: nodes[cb_args[k]] for k in cb_args.get("__node_args__", [])
}
cb = callback.base(cb, **kwargs)
nodes[i["id"]]._callbacks.append((event, cb))
for parent, child, name in data["edges"]:
nodes[parent][name] = nodes[child]
root = nodes[data["nodes"][0]["id"]]
root.token = data.get("token")
root._autorun = data.get("autorun", False)
root._sleep_when_done = data.get("sleep_when_done", False)
return root
# returns a stream in topological order
def stream(self, reverse=False):
"""
Iterate through the nodes
"""
def _fwd():
stack = [self]
while stack:
yld = stack.pop()
yield yld
stack.extend(list(yld.children.values())[::-1])
def _bwd():
stack = [[self, True]]
while stack:
while stack[-1][1]:
stack[-1][1] = False
for i in stack[-1][0].children.values():
stack.append([i, True])
yield stack.pop()[0]
if reverse:
return _bwd()
else:
return _fwd()
def get_inherited_attribute(self, attr):
node = self
while node is not None:
v = node.user_set[attr]
if v is not None:
return v
else:
node = node.parent
return None
def launch_local(
self,
use_shell=True,
retention=7,
run=False,
sleep_when_done=False,
prebuild_images=False,
):
"""
Launch directly from python.
:param use_shell: If True (default) it will connect to the running
pipeline using the shell UI. Otherwise just launch the pipeline and
then exit.
:param retention: Once the pipeline is put to sleep, its logs and
:ref:`data` will be deleted after `retention` days of inactivity.
Until then it can be woken up and interacted with.
:param run: If True the pipeline will run immediately upon launching.
Otherwise (default) it will stay Pending until the user starts it.
:param sleep_when_done: If True the pipeline will sleep -- manager
exits with recoverable state -- when the root node successfully
gets to the Done state.
:param prebuild_images: If True build the images before launching the pipeline.
"""
# TODO: Do we want these params? They seem sensible and they were documented at one point.
# :param tags: If specified, should be a list of strings. The app lets you filter programs based on these tags.
# :param title: Title to show in the program list in the app. If unspecified, the title will be based on the command line.
self._build(
build_mode=constants.BuildMode.LOCAL,
use_shell=use_shell,
retention=retention,
run=run,
sleep_when_done=sleep_when_done,
prebuild_images=prebuild_images,
)
def _build(
self,
build_mode=constants.BuildMode.LOCAL,
use_shell=False,
use_app=False,
prebuild_images=False,
retention=7,
run=False,
sleep_when_done=False,
is_public=False,
):
if self.image is None:
self.image = image_mod.Image(name="conducto-default")
self.check_images()
if build_mode != constants.BuildMode.LOCAL or prebuild_images:
image_mod.make_all(
self, push_to_cloud=build_mode != constants.BuildMode.LOCAL
)
self._autorun = run
self._sleep_when_done = sleep_when_done
from conducto.internal import build
return build.build(
self,
build_mode,
use_shell=use_shell,
use_app=use_app,
retention=retention,
is_public=is_public,
)
def check_images(self):
for node in self.stream():
if isinstance(node, Exec):
node.expanded_command()
def pretty(self, strict=True):
buf = []
self._pretty("", "", "", buf, strict)
return "\n".join(buf)
def _pretty(self, node_prefix, child_prefix, index_str, buf, strict):
"""
Draw pretty representation of the node pipeline, using ASCII box-drawing
characters.
For example:
/
├─1 First
│ ├─ Parallel1 "echo 'I run first"
│ └─ Parallel2 "echo 'I also run first"
└─2 Second "echo 'I run last.'"
"""
if isinstance(self, Exec):
node_str = f"{log.format(self.name, color='cyan')} {self.expanded_command(strict)}"
node_str = node_str.strip().replace("\n", "\\n")
else:
node_str = log.format(self.name, color="blue")
buf.append(f"{node_prefix}{index_str}{node_str}")
length_of_length = len(str(len(self.children) - 1))
for i, node in enumerate(self.children.values()):
if isinstance(self, Parallel):
new_index_str = " "
else:
new_index_str = f"{str(i).zfill(length_of_length)} "
if i == len(self.children) - 1:
this_node_prefix = f"{child_prefix}└─"
this_child_prefix = f"{child_prefix} "
else:
this_node_prefix = f"{child_prefix}├─"
this_child_prefix = f"{child_prefix}│ "
node._pretty(
this_node_prefix, this_child_prefix, new_index_str, buf, strict
)
@staticmethod
def sanitize_tags(val):
if val is None:
return val
elif isinstance(val, (bytes, str)):
return [val]
elif isinstance(val, (list, tuple, set)):
for v in val:
if not isinstance(v, (bytes, str)):
raise TypeError(f"Expected list of strings, got: {repr(v)}")
return val
else:
raise TypeError(f"Cannot convert {repr(val)} to list of strings.")
@staticmethod
def _get_file_and_line():
if Node._NUM_FILE_AND_LINE_CALLS > Node._MAX_FILE_AND_LINE_CALLS:
return None, None
Node._NUM_FILE_AND_LINE_CALLS += 1
for frame, lineno in traceback.walk_stack(None):
filename = frame.f_code.co_filename
if not filename.startswith(_conducto_dir):
if not _isabs(filename):
filename = _abspath(filename)
return filename, lineno
return None, None
@staticmethod
def force_debug_info(val):
if val:
Node._MAX_FILE_AND_LINE_CALLS = 10 ** 30
else:
Node._MAX_FILE_AND_LINE_CALLS = 10 ** 4
class Exec(Node):
"""
A node that contains an executable command
:param command: A shell command to execute or a python callable
If a Python callable is specified for the command the `args` and `kwargs`
are serialized and a `conducto` command line is constructed to launch the
function for that node in the pipeline.
"""
__slots__ = ("command",)
def __init__(self, command, *args, **kwargs):
if callable(command):
self._validate_args(command, *args, **kwargs)
from .glue import method
wrapper = method.Wrapper(command)
command = wrapper.to_command(*args, **kwargs)
kwargs = wrapper.get_exec_params(*args, **kwargs)
args = []
if args:
raise ValueError(
f"Only allowed arg is command. Got:\n command={repr(command)}\n args={args}\n kwargs={kwargs}"
)
super().__init__(**kwargs)
# Instance variables
self.command = command
# Validate arguments for the given function without calling it. This is useful for
# raising early errors on `co.Lazy()` or `co.Exec(func, *args, **kwargs).
@staticmethod
def _validate_args(func, *args, **kwargs):
params = inspect.signature(func).parameters
hints = typing.get_type_hints(func)
if isinstance(func, staticmethod):
function = func.__func__
else:
function = func
# TODO: can target function have a `*args` or `**kwargs` in the signature? If
# so, handle it.
invalid_params = [
(name, str(param.kind))
for name, param in params.items()
if param.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD
]
if invalid_params:
raise TypeError(
f"Unsupported parameter types of "
f"{function.__name__}: {invalid_params} - "
f"Only {str(inspect.Parameter.POSITIONAL_OR_KEYWORD)} is allowed."
)
# this will also validate against too-many or too-few arguments
call_args = inspect.getcallargs(function, *args, **kwargs)
for name, arg_value in call_args.items():
if name in hints:
# If there is a type hint, use the output of `typing.get_type_hints`. It
# infers typing.Optional when default is None, and it handles forward
# references.
param_type = hints[name]
else:
# If
param_type = params[name].annotation
if not t.is_instance(arg_value, param_type):
raise TypeError(
f"Argument {name}={arg_value} {type(arg_value)} for "
f"function {function.__name__} is not compatible "
f"with expected type: {param_type}"
)
def delete_child(self, node):
raise NotImplementedError("Exec nodes have no children")
def append_child(self, node):
raise NotImplementedError("Exec nodes have no children")
def expanded_command(self, strict=True):
if "__conducto_path:" in self.command:
img = self.image
if img is None:
if strict:
raise ValueError(
"Node references code inside a container but no image is specified\n"
f" Node: {self}"
)
else:
return self.command
COPY_DIR = image_mod.dockerfile_mod.COPY_DIR
def repl(match):
path = match.group(1)
path_map = dict(img.path_map)
# If a gitroot was detected, it was marked in the command with a "//".
# If copy_url was set then we can determine what the external portion
# of the path was. Together with COPY_DIR we can update path_map
if "//" in path and img.copy_url:
external = path.split("//", 1)[0]
path_map[external] = COPY_DIR
# Normalize path to get rid of the //.
path = os.path.normpath(path)
# temporary windows translations -- these are translated for
# real just-in-time during the final serialization, but we
# convert them here to faciliate this validation.
if hostdet.is_windows():
wdp = hostdet.windows_docker_path
path_map = {wdp(k): v for k, v in path_map.items()}
for external, internal in path_map.items():
# For each element of path_map, see if the external path matches
external = os.path.normpath(external.rstrip("/"))
if not path.startswith(external):
continue
# If so, calculate the corresponding internal path
internal = os.path.normpath(internal.rstrip("/"))
relative = os.path.relpath(path, external)
new_path = os.path.join(internal, relative)
# As a convenience, if we `docker_auto_workdir` then we know the workdir and
# we can shorten the path
if img.docker_auto_workdir and new_path.startswith(COPY_DIR):
return os.path.relpath(new_path, COPY_DIR)
else:
# Otherwise just return an absolute path.
return new_path
raise ValueError(
f"Node references local code but the |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.