max_stars_repo_path
stringlengths 3
269
| max_stars_repo_name
stringlengths 4
119
| max_stars_count
int64 0
191k
| id
stringlengths 1
7
| content
stringlengths 6
1.05M
| score
float64 0.23
5.13
| int_score
int64 0
5
|
---|---|---|---|---|---|---|
pymutual/__init__.py | kimballh/pymutual | 0 | 2200 | from .session import Session, MutualAPI | 1.101563 | 1 |
forms.py | Joshua-Barawa/pitches-IP | 0 | 2201 | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, Email, ValidationError
from models import User
class RegistrationForm(FlaskForm):
email = StringField('Your Email Address', validators=[InputRequired(), Email()])
username = StringField('Enter your username', validators=[InputRequired()])
password = PasswordField('Password', validators=[InputRequired()])
submit = SubmitField('Sign Up')
def validate_username(self, username):
existing_username = User.query.filter_by(username=username.data).first()
if existing_username:
raise ValidationError("The username already exists")
class LoginForm(FlaskForm):
username = StringField("Your email address", validators=[InputRequired()])
password = PasswordField("<PASSWORD>:", validators=[InputRequired()])
submit = SubmitField("Sign In")
| 3.3125 | 3 |
plugins/barracuda_waf/komand_barracuda_waf/actions/create_security_policy/schema.py | lukaszlaszuk/insightconnect-plugins | 46 | 2202 | # GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Component:
DESCRIPTION = "Creates a security policy with the default values"
class Input:
NAME = "name"
class Output:
ID = "id"
class CreateSecurityPolicyInput(komand.Input):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"name": {
"type": "string",
"title": "Name",
"description": "The name of the security policy that needs to be created",
"order": 1
}
},
"required": [
"name"
]
}
""")
def __init__(self):
super(self.__class__, self).__init__(self.schema)
class CreateSecurityPolicyOutput(komand.Output):
schema = json.loads("""
{
"type": "object",
"title": "Variables",
"properties": {
"id": {
"type": "string",
"title": "ID",
"description": "ID of the new policy",
"order": 1
}
},
"required": [
"id"
]
}
""")
def __init__(self):
super(self.__class__, self).__init__(self.schema)
| 2.5625 | 3 |
examples/dhc/rule_example.py | fruttasecca/hay_checker | 2 | 2203 | <reponame>fruttasecca/hay_checker<filename>examples/dhc/rule_example.py<gh_stars>1-10
#!/usr/bin/python3
from pyspark.sql import SparkSession
from haychecker.dhc.metrics import rule
spark = SparkSession.builder.appName("rule_example").getOrCreate()
df = spark.read.format("csv").option("header", "true").load("examples/resources/employees.csv")
df.show()
condition1 = {"column": "salary", "operator": "gt", "value": 2100}
conditions = [condition1]
r1 = rule(conditions, df)[0]
print("Rule salary>2100: {}".format(r1))
condition1 = {"column": "salary", "operator": "lt", "value": 2100}
condition2 = {"column": "title", "operator": "eq", "value": "Sales Representative"}
conditions = [condition1, condition2]
task1 = rule(conditions)
condition1 = {"column": "salary", "operator": "lt", "value": 2100}
condition2 = {"column": "city", "operator": "eq", "value": "London"}
conditions = [condition1, condition2]
task2 = rule(conditions)
task3 = task1.add(task2)
result = task3.run(df)
r1 = result[0]["scores"][0]
r2 = result[1]["scores"][0]
print("Rule salary<2100 and title=\"Sales Representative\": {},"
" rule salary<2100 and city=\"London\": {}".format(r1, r2)) | 2.765625 | 3 |
secure_message/common/utilities.py | uk-gov-mirror/ONSdigital.ras-secure-message | 0 | 2204 | import collections
import logging
import urllib.parse
from structlog import wrap_logger
from secure_message.constants import MESSAGE_BY_ID_ENDPOINT, MESSAGE_LIST_ENDPOINT, MESSAGE_QUERY_LIMIT
from secure_message.services.service_toggles import party, internal_user_service
logger = wrap_logger(logging.getLogger(__name__))
MessageArgs = collections.namedtuple(
'MessageArgs',
'page limit business_id surveys cc label desc ce is_closed my_conversations new_respondent_conversations all_conversation_types unread_conversations')
def get_options(args): # NOQA pylint:disable=too-complex
"""extract options from request , allow label to be set by caller
:param args: contains search arguments. Not all end points support all args
:returns: MessageArgs named tuple containing the args for the search
business_id If set , restricts search to conversations regarding this specific party id
surveys If set allows the count to be restricted by a list of survey_ids
cc If set , allows the count to be restricted by a particular case
ce If set, alows the count to be restricted by a particular collection exercise
is_closed If set to 'true' only counts closed conversations, else only open conversations
my_conversations If set to 'true only counts my conversations.
I.e conversations where the current user id is the to actor id
new_respondent_conversations If set to 'true'only counts conversations where the to actor is set to 'GROUP'
all_conversation_types If set 'true', overrides is_closed, my_conversations and new_respondent_conversations
and returns 4 counts 1 for each of , open , closed, my_conversations and new_respondent_conversations
page If set requests the specific page of information to return
limit If set it sets the maximum number of results to return
desc If present, requests the information in descending order
"""
fields = {'page': 1, 'limit': MESSAGE_QUERY_LIMIT, 'business_id': None, 'surveys': None,
'desc': True, 'cc': None, 'label': None, 'ce': None, 'is_closed': False,
'my_conversations': False, 'new_respondent_conversations': False, 'all_conversation_types': False,
'unread_conversations': False}
for field in ['cc', 'ce', 'business_id', 'label']:
if args.get(field):
fields[field] = str(args.get(field))
fields['surveys'] = args.getlist('survey')
for field in ['limit', 'page']:
if args.get(field):
fields[field] = int(args.get(field))
if args.get('desc') == 'false':
fields['desc'] = False
if args.get('is_closed') == 'true':
fields['is_closed'] = True
if args.get('my_conversations') == 'true':
fields['my_conversations'] = True
if args.get('new_respondent_conversations') == 'true':
fields['new_respondent_conversations'] = True
if args.get('all_conversation_types') == 'true':
fields['all_conversation_types'] = True
if args.get('unread_conversations') == 'true':
fields['unread_conversations'] = True
return MessageArgs(page=fields['page'], limit=fields['limit'], business_id=fields['business_id'],
surveys=fields['surveys'], cc=fields['cc'], label=fields['label'],
desc=fields['desc'], ce=fields['ce'], is_closed=fields['is_closed'],
my_conversations=fields['my_conversations'],
new_respondent_conversations=fields['new_respondent_conversations'],
all_conversation_types=fields['all_conversation_types'],
unread_conversations=fields['unread_conversations'])
def set_conversation_type_args(existing_args, is_closed=False, my_conversations=False, new_conversations=False,
all_types=False, unread_conversations=False):
"""Returns a new set of args based on the existing args which are a named tuple,
but allow the conversation type only to be changed"""
return MessageArgs(page=existing_args.page,
limit=existing_args.limit,
business_id=existing_args.business_id,
surveys=existing_args.surveys,
cc=existing_args.cc,
label=existing_args.label,
desc=existing_args.desc,
ce=existing_args.ce,
is_closed=is_closed,
my_conversations=my_conversations,
new_respondent_conversations=new_conversations,
all_conversation_types=all_types,
unread_conversations=unread_conversations)
def generate_string_query_args(args):
params = {}
for field in args._fields:
if field in ['page']:
continue
value = getattr(args, field)
if value:
params[field] = value
return urllib.parse.urlencode(params)
def process_paginated_list(paginated_list, host_url, user, message_args, endpoint=MESSAGE_LIST_ENDPOINT, body_summary=True):
"""used to change a pagination object to json format with links"""
messages = []
string_query_args = generate_string_query_args(message_args)
for message in paginated_list.items:
msg = message.serialize(user, body_summary=body_summary)
msg['_links'] = {"self": {"href": f"{host_url}{MESSAGE_BY_ID_ENDPOINT}/{msg['msg_id']}"}}
messages.append(msg)
links = {'first': {"href": f"{host_url}{endpoint}"},
'self': {"href": f"{host_url}{endpoint}?{string_query_args}&page={message_args.page}"}}
if paginated_list.has_next:
links['next'] = {
"href": f"{host_url}{endpoint}?{string_query_args}&page={message_args.page + 1}"}
if paginated_list.has_prev:
links['prev'] = {
"href": f"{host_url}{endpoint}?{string_query_args}&page={message_args.page - 1}"}
return messages, links
def add_to_details(messages):
"""Adds a @msg_to key to every message in a list of messages.
Every msg_to uuid is resolved to include details of the user.
If the call for the internal user id fails, an exception will be thrown.
If the external user id cannot be found in the list that we got from the party service. There
won't be a @msg_to value returned in the payload. The API documentation notes that these elements
aren't guaranteed to be provided so we're not breaking the contract by doing this.
Note: Several of these lines of code could be combined into a more succinct view, spreading them out
is deliberate so that log stack traces are better able to identify the cause of log errors
"""
external_user_details = {}
for user in party.get_users_details(get_external_user_uuid_list(messages)):
external_user_details[user['id']] = user
for message in messages:
try:
msg_to = message["msg_to"][0]
from_internal = message["from_internal"]
if not from_internal:
msg_to_details = internal_user_service.get_user_details(msg_to)
message.update({"@msg_to": [msg_to_details]})
else:
msg_to_details = external_user_details.get(msg_to)
if msg_to_details:
message.update({'@msg_to': [msg_to_details]})
else:
logger.info("No details found for the message recipient", msg_to=msg_to)
except IndexError:
logger.exception("Exception adding to details", msg_to=msg_to, from_internal=from_internal)
raise
return messages
def add_from_details(messages):
"""Adds a @msg_from key to every message in a list of messages.
Every msg_to uuid is resolved to include details of the user.
If the call for the internal user id fails, an exception will be thrown.
If the external user id cannot be found in the list that we got from the party service. There
won't be a @msg_from value returned in the payload. The API documentation notes that these elements
aren't guaranteed to be provided so we're not breaking the contract by doing this.
"""
external_user_details = {}
for user in party.get_users_details(get_external_user_uuid_list(messages)):
external_user_details[user['id']] = user
for message in messages:
try:
msg_from = message["msg_from"]
from_internal = message["from_internal"]
if from_internal:
message.update({"@msg_from": internal_user_service.get_user_details(msg_from)})
else:
if external_user_details.get(message['msg_from']):
message.update({'@msg_from': external_user_details.get(msg_from)})
except IndexError:
logger.exception("Exception adding from details message", msg_from=msg_from, from_internal=from_internal)
raise
return messages
def get_external_user_uuid_list(messages):
"""Compiles a list of all unique the external user (respondent) uuids from a list of messages"""
external_user_uuids = set()
external_msgs = [message for message in messages if message['from_internal'] is False]
for message in external_msgs:
external_user_uuids.add(message["msg_from"])
internal_messages = [message for message in messages if message['from_internal'] is True]
for uuid in internal_messages:
external_user_uuids.add(uuid["msg_to"][0])
return external_user_uuids
def add_business_details(messages):
"""Adds a @business_details key to every message in a list of messages."""
business_ids = set()
for message in messages:
business_ids.add(message['business_id'])
business_details = party.get_business_details(business_ids)
for message in messages:
message['@business_details'] = next((business for business in business_details if business["id"] == message['business_id']), None)
return messages
def add_users_and_business_details(messages):
"""Add both user and business details to messages based on data from party service"""
if not messages:
raise ValueError('messages is a required parameter and must not be empty')
messages = add_to_details(messages)
messages = add_from_details(messages)
logger.info("Successfully added to and from details")
messages = add_business_details(messages)
logger.info("Successfully added business details")
return messages
| 2.4375 | 2 |
notegame/games/nonogram/core/renderer.py | notechats/notegame | 0 | 2205 | <reponame>notechats/notegame
# -*- coding: utf-8 -*-
"""
Defines various renderers for the game of nonogram
"""
from abc import ABC
from sys import stdout
from notetool.tool.log import logger
from six import integer_types, itervalues, text_type
from ..utils.iter import max_safe, pad
from ..utils.other import two_powers
from .common import BOX, SPACE, UNKNOWN, BlottedBlock, is_list_like
class Cell(object):
"""Represent basic rendered cell"""
DEFAULT_ICON = ' '
def __init__(self, icon=None):
self.icon = icon or self.DEFAULT_ICON
def ascii_icon(self):
"""How the cell can be printed as a text"""
return self.DEFAULT_ICON
def __repr__(self):
return '{}()'.format(self.__class__.__name__)
class ThumbnailCell(Cell):
"""
Represent upper-left cell
(where the thumbnail of the puzzle usually drawn).
"""
DEFAULT_ICON = '#'
class ClueCell(Cell):
"""
Represent cell that is part of description (clue).
They are usually drawn on the top and on the left.
"""
BLOTTED_SYMBOL = '?'
def __init__(self, value):
super(ClueCell, self).__init__()
if is_list_like(value):
self.value, self.color = value
else:
self.value, self.color = value, None
def ascii_icon(self):
"""
Gets a symbolic representation of a cell given its state
and predefined table `icons`
"""
if isinstance(self.value, integer_types):
return text_type(self.value)
if self.value == BlottedBlock:
return self.BLOTTED_SYMBOL
return self.DEFAULT_ICON
def __repr__(self):
return '{}(({}, {}))'.format(
self.__class__.__name__,
self.value, self.color)
class GridCell(Cell):
"""Represent the main area cell"""
def __init__(self, value, renderer, colored=False):
super(GridCell, self).__init__()
self.renderer = renderer
self.colored = colored
if self.colored:
self.value = tuple(two_powers(value))
else:
self.value = value
def ascii_icon(self):
value = self.value
icons = self.renderer.icons
if not self.colored:
return icons[self.value]
if len(value) == 1:
value = value[0]
else:
# multiple colors
value = UNKNOWN
symbol = self.renderer.board.symbol_for_color_id(value)
if symbol is not None:
return symbol
return icons.get(value, self.DEFAULT_ICON)
def __repr__(self):
return '{}({})'.format(
self.__class__.__name__, self.value)
class _DummyBoard(object):
"""
Stub for renderer initialization
when it created before the corresponding board
"""
rows_descriptions = columns_descriptions = ()
width = height = 0
class Renderer(object):
"""Defines the abstract renderer for a nonogram board"""
def __init__(self, board=None):
self.cells = None
self.board = None
self.board_init(board)
def board_init(self, board=None):
"""Initialize renderer's properties dependent on board it draws"""
if board:
logger.info('Init %r renderer with board %r',
self.__class__.__name__, board)
else:
if self.board:
return # already initialized, do nothing
board = _DummyBoard()
self.board = board
@property
def full_height(self):
"""The full visual height of a board"""
return self.header_height + self.board.height
@property
def full_width(self):
"""The full visual width of a board"""
return self.side_width + self.board.width
@property
def header_height(self):
"""The size of the header block with columns descriptions"""
return max_safe(map(len, self.board.columns_descriptions), default=0)
@property
def side_width(self):
"""The width of the side block with rows descriptions"""
return max_safe(map(len, self.board.rows_descriptions), default=0)
def render(self):
"""Actually print out the board"""
raise NotImplementedError()
def draw(self, cells=None):
"""Calculate all the cells and draw an image of the board"""
self.draw_header()
self.draw_side()
self.draw_grid(cells=cells)
self.render()
def draw_header(self):
"""
Changes the internal state to be able to draw columns descriptions
"""
raise NotImplementedError()
def draw_side(self):
"""
Changes the internal state to be able to draw rows descriptions
"""
raise NotImplementedError()
def draw_grid(self, cells=None):
"""
Changes the internal state to be able to draw a main grid
"""
raise NotImplementedError()
@property
def is_colored(self):
"""Whether the linked board is colored board"""
return self.board.is_colored
class StreamRenderer(Renderer, ABC):
"""
Simplify textual rendering of a board to a stream (stdout by default)
"""
DEFAULT_ICONS = {
UNKNOWN: '_',
BOX: 'X',
SPACE: '.',
}
def __init__(self, board=None, stream=stdout, icons=None):
self.stream = stream
if icons is None:
icons = dict(self.DEFAULT_ICONS)
self.icons = icons
super(StreamRenderer, self).__init__(board)
def _print(self, *args):
return print(*args, file=self.stream)
class BaseAsciiRenderer(StreamRenderer):
"""
Renders a board as a simple text table (without grid)
"""
__rend_name__ = 'text'
def board_init(self, board=None):
super(BaseAsciiRenderer, self).board_init(board)
logger.info('init cells: %sx%s', self.full_width, self.full_width)
self.cells = [[Cell()] * self.full_width
for _ in range(self.full_height)]
def cell_icon(self, cell):
"""
Get a symbolic representation of a cell given its state
and predefined table `icons`
"""
return cell.ascii_icon()
def render(self):
for row in self.cells:
res = []
for index, cell in enumerate(row):
ico = self.cell_icon(cell)
# do not pad the last symbol in a line
if len(ico) == 1:
if index < len(row) - 1:
ico += ' '
res.append(ico)
self._print(''.join(res))
def draw_header(self):
for i in range(self.header_height):
for j in range(self.side_width):
self.cells[i][j] = ThumbnailCell()
for j, col in enumerate(self.board.columns_descriptions):
rend_j = j + self.side_width
if not col:
col = [0]
rend_column = [ClueCell(val) for val in col]
rend_column = pad(rend_column, self.header_height, Cell())
# self.cells[:self.header_height, rend_j] = rend_column
for i, cell in enumerate(rend_column):
self.cells[i][rend_j] = cell
def draw_side(self):
for i, row in enumerate(self.board.rows_descriptions):
rend_i = i + self.header_height
# row = list(row)
if not row:
row = [0]
rend_row = [ClueCell(val) for val in row]
rend_row = pad(rend_row, self.side_width, Cell())
self.cells[rend_i][:self.side_width] = rend_row
def draw_grid(self, cells=None):
if cells is None:
cells = self.board.cells
is_colored = self.is_colored
for i, row in enumerate(cells):
rend_i = i + self.header_height
for j, val in enumerate(row):
rend_j = j + self.side_width
self.cells[rend_i][rend_j] = GridCell(
val, self, colored=is_colored)
def _register_renderers():
res = dict()
for obj in itervalues(globals()):
if isinstance(obj, type):
if issubclass(obj, StreamRenderer) and hasattr(obj, '__rend_name__'):
res[obj.__rend_name__] = obj
return res
RENDERERS = _register_renderers()
| 3.0625 | 3 |
sympy/printing/lambdarepr.py | Carreau/sympy | 4 | 2206 | <filename>sympy/printing/lambdarepr.py
from __future__ import print_function, division
from .str import StrPrinter
from sympy.utilities import default_sort_key
class LambdaPrinter(StrPrinter):
"""
This printer converts expressions into strings that can be used by
lambdify.
"""
def _print_MatrixBase(self, expr):
return "%s(%s)" % (expr.__class__.__name__,
self._print((expr.tolist())))
_print_SparseMatrix = \
_print_MutableSparseMatrix = \
_print_ImmutableSparseMatrix = \
_print_Matrix = \
_print_DenseMatrix = \
_print_MutableDenseMatrix = \
_print_ImmutableMatrix = \
_print_ImmutableDenseMatrix = \
_print_MatrixBase
def _print_Piecewise(self, expr):
result = []
i = 0
for arg in expr.args:
e = arg.expr
c = arg.cond
result.append('((')
result.append(self._print(e))
result.append(') if (')
result.append(self._print(c))
result.append(') else (')
i += 1
result = result[:-1]
result.append(') else None)')
result.append(')'*(2*i - 2))
return ''.join(result)
def _print_Sum(self, expr):
loops = (
'for {i} in range({a}, {b}+1)'.format(
i=self._print(i),
a=self._print(a),
b=self._print(b))
for i, a, b in expr.limits)
return '(builtins.sum({function} {loops}))'.format(
function=self._print(expr.function),
loops=' '.join(loops))
def _print_And(self, expr):
result = ['(']
for arg in sorted(expr.args, key=default_sort_key):
result.extend(['(', self._print(arg), ')'])
result.append(' and ')
result = result[:-1]
result.append(')')
return ''.join(result)
def _print_Or(self, expr):
result = ['(']
for arg in sorted(expr.args, key=default_sort_key):
result.extend(['(', self._print(arg), ')'])
result.append(' or ')
result = result[:-1]
result.append(')')
return ''.join(result)
def _print_Not(self, expr):
result = ['(', 'not (', self._print(expr.args[0]), '))']
return ''.join(result)
def _print_BooleanTrue(self, expr):
return "True"
def _print_BooleanFalse(self, expr):
return "False"
def _print_ITE(self, expr):
result = [
'((', self._print(expr.args[1]),
') if (', self._print(expr.args[0]),
') else (', self._print(expr.args[2]), '))'
]
return ''.join(result)
class NumPyPrinter(LambdaPrinter):
"""
Numpy printer which handles vectorized piecewise functions,
logical operators, etc.
"""
_default_settings = {
"order": "none",
"full_prec": "auto",
}
def _print_seq(self, seq, delimiter=', '):
"General sequence printer: converts to tuple"
# Print tuples here instead of lists because numba supports
# tuples in nopython mode.
return '({},)'.format(delimiter.join(self._print(item) for item in seq))
def _print_MatMul(self, expr):
"Matrix multiplication printer"
return '({0})'.format(').dot('.join(self._print(i) for i in expr.args))
def _print_DotProduct(self, expr):
# DotProduct allows any shape order, but numpy.dot does matrix
# multiplication, so we have to make sure it gets 1 x n by n x 1.
arg1, arg2 = expr.args
if arg1.shape[0] != 1:
arg1 = arg1.T
if arg2.shape[1] != 1:
arg2 = arg2.T
return "dot(%s, %s)" % (self._print(arg1), self._print(arg2))
def _print_Piecewise(self, expr):
"Piecewise function printer"
exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg in expr.args))
conds = '[{0}]'.format(','.join(self._print(arg.cond) for arg in expr.args))
# If [default_value, True] is a (expr, cond) sequence in a Piecewise object
# it will behave the same as passing the 'default' kwarg to select()
# *as long as* it is the last element in expr.args.
# If this is not the case, it may be triggered prematurely.
return 'select({0}, {1}, default=nan)'.format(conds, exprs)
def _print_Relational(self, expr):
"Relational printer for Equality and Unequality"
op = {
'==' :'equal',
'!=' :'not_equal',
'<' :'less',
'<=' :'less_equal',
'>' :'greater',
'>=' :'greater_equal',
}
if expr.rel_op in op:
lhs = self._print(expr.lhs)
rhs = self._print(expr.rhs)
return '{op}({lhs}, {rhs})'.format(op=op[expr.rel_op],
lhs=lhs,
rhs=rhs)
return super(NumPyPrinter, self)._print_Relational(expr)
def _print_And(self, expr):
"Logical And printer"
# We have to override LambdaPrinter because it uses Python 'and' keyword.
# If LambdaPrinter didn't define it, we could use StrPrinter's
# version of the function and add 'logical_and' to NUMPY_TRANSLATIONS.
return '{0}({1})'.format('logical_and', ','.join(self._print(i) for i in expr.args))
def _print_Or(self, expr):
"Logical Or printer"
# We have to override LambdaPrinter because it uses Python 'or' keyword.
# If LambdaPrinter didn't define it, we could use StrPrinter's
# version of the function and add 'logical_or' to NUMPY_TRANSLATIONS.
return '{0}({1})'.format('logical_or', ','.join(self._print(i) for i in expr.args))
def _print_Not(self, expr):
"Logical Not printer"
# We have to override LambdaPrinter because it uses Python 'not' keyword.
# If LambdaPrinter didn't define it, we would still have to define our
# own because StrPrinter doesn't define it.
return '{0}({1})'.format('logical_not', ','.join(self._print(i) for i in expr.args))
def _print_Min(self, expr):
return '{0}(({1}))'.format('amin', ','.join(self._print(i) for i in expr.args))
def _print_Max(self, expr):
return '{0}(({1}))'.format('amax', ','.join(self._print(i) for i in expr.args))
# numexpr works by altering the string passed to numexpr.evaluate
# rather than by populating a namespace. Thus a special printer...
class NumExprPrinter(LambdaPrinter):
# key, value pairs correspond to sympy name and numexpr name
# functions not appearing in this dict will raise a TypeError
_numexpr_functions = {
'sin' : 'sin',
'cos' : 'cos',
'tan' : 'tan',
'asin': 'arcsin',
'acos': 'arccos',
'atan': 'arctan',
'atan2' : 'arctan2',
'sinh' : 'sinh',
'cosh' : 'cosh',
'tanh' : 'tanh',
'asinh': 'arcsinh',
'acosh': 'arccosh',
'atanh': 'arctanh',
'ln' : 'log',
'log': 'log',
'exp': 'exp',
'sqrt' : 'sqrt',
'Abs' : 'abs',
'conjugate' : 'conj',
'im' : 'imag',
're' : 'real',
'where' : 'where',
'complex' : 'complex',
'contains' : 'contains',
}
def _print_ImaginaryUnit(self, expr):
return '1j'
def _print_seq(self, seq, delimiter=', '):
# simplified _print_seq taken from pretty.py
s = [self._print(item) for item in seq]
if s:
return delimiter.join(s)
else:
return ""
def _print_Function(self, e):
func_name = e.func.__name__
nstr = self._numexpr_functions.get(func_name, None)
if nstr is None:
# check for implemented_function
if hasattr(e, '_imp_'):
return "(%s)" % self._print(e._imp_(*e.args))
else:
raise TypeError("numexpr does not support function '%s'" %
func_name)
return "%s(%s)" % (nstr, self._print_seq(e.args))
def blacklisted(self, expr):
raise TypeError("numexpr cannot be used with %s" %
expr.__class__.__name__)
# blacklist all Matrix printing
_print_SparseMatrix = \
_print_MutableSparseMatrix = \
_print_ImmutableSparseMatrix = \
_print_Matrix = \
_print_DenseMatrix = \
_print_MutableDenseMatrix = \
_print_ImmutableMatrix = \
_print_ImmutableDenseMatrix = \
blacklisted
# blacklist some python expressions
_print_list = \
_print_tuple = \
_print_Tuple = \
_print_dict = \
_print_Dict = \
blacklisted
def doprint(self, expr):
lstr = super(NumExprPrinter, self).doprint(expr)
return "evaluate('%s', truediv=True)" % lstr
def lambdarepr(expr, **settings):
"""
Returns a string usable for lambdifying.
"""
return LambdaPrinter(settings).doprint(expr)
| 2.84375 | 3 |
python/fill_na_v2.py | fredmell/CS229Project | 0 | 2207 | <filename>python/fill_na_v2.py
"""
Fill na with most common of the whole column
"""
import numpy as np
import pandas as pd
import time
import matplotlib.pyplot as plt
from datetime import datetime
import re
from collections import Counter
from statistics import median
from tqdm import tqdm
def find_most_common_value(element_list):
for element in element_list:
if not pd.isna(element):
break
if pd.isna(element):
return np.nan
elif isinstance(element, np.double):
array = np.array(element_list)
array = array[~np.isnan(array)]
if len(array) == 0:
return np.nan
else:
array = array.astype(np.int)
return np.double(np.bincount(array).argmax())
elif isinstance(element, str):
count = Counter(df[col])
try:
del count[np.nan]
except ValueError:
pass
if count == dict():
return np.nan
else:
return count.most_common(1)[0][0]
file = '/home/nicolasbievre/yelp_data.pkl'
file_na = '/home/nicolasbievre/yelp_data_no_na.pkl'
df = pd.read_pickle(file)
categories = list(set(df['categories'].values))
n = len(categories)
for i in tqdm(range(len(df.columns))):
col = df.columns[i]
if not col in {'review_id': 0, 'business_id': 0, 'user_id': 0, 'postal_code': 0}:
df_col = df[col].values
na = sum(pd.isna(df_col))
if na > 0:
most_commom_term = find_most_common_value(df_col)
if not pd.isna(most_commom_term):
df.loc[(pd.isna(df_col)), col] = most_commom_term
if i % 35 == 0 and i > 0:
df.to_pickle(file_na)
df.to_pickle(file_na)
| 3.09375 | 3 |
GUI Applications/calc.py | jaiswalIT02/pythonprograms | 0 | 2208 | <filename>GUI Applications/calc.py
from tkinter import Tk
from tkinter import Entry
from tkinter import Button
from tkinter import StringVar
t=Tk()
t.title("<NAME>")
t.geometry("425x300")
t.resizable(0,0)
t.configure(background="black")#back ground color
a=StringVar()
def show(c):
a.set(a.get()+c)
def equal():
x=a.get()
a.set(eval(x))
def clear():
a.set("")
e1=Entry(font=("",30),justify="right",textvariable=a)
e1.place(x=0,y=0,width=425,height=50)
b1=Button(text="7",font=("",25),bg="gray",fg="white",activebackground="yellow",command=show)
b1.place(x=5,y=55,width=100,height=50)
b1.configure(command=lambda:show("7"))
b2=Button(text="8",font=("",25),bg="gray",fg="white",activebackground="yellow")
b2.place(x=110,y=55,width=100,height=50)
b2.configure(command=lambda:show("8"))
b3=Button(text="9",font=("",25),bg="gray",fg="white",activebackground="yellow")
b3.place(x=215,y=55,width=100,height=50)
b3.configure(command=lambda:show("9"))
b4=Button(text="+",font=("",25),bg="gray",fg="white",activebackground="yellow")
b4.place(x=320,y=55,width=100,height=50)
b4.configure(command=lambda:show("+"))
b5=Button(text="4",font=("",25),bg="gray",fg="white",activebackground="yellow")
b5.place(x=5,y=110,width=100,height=50)
b5.configure(command=lambda:show("4"))
b6=Button(text="5",font=("",25),bg="gray",fg="white",activebackground="yellow")
b6.place(x=110,y=110,width=100,height=50)
b6.configure(command=lambda:show("5"))
b7=Button(text="6",font=("",25),bg="gray",fg="white",activebackground="yellow")
b7.place(x=215,y=110,width=100,height=50)
b7.configure(command=lambda:show("6"))
b8=Button(text="-",font=("",25),bg="gray",fg="white",activebackground="yellow")
b8.place(x=320,y=110,width=100,height=50)
b8.configure(command=lambda:show("-"))
b9=Button(text="1",font=("",25),bg="gray",fg="white",activebackground="yellow")
b9.place(x=5,y=165,width=100,height=50)
b9.configure(command=lambda:show("1"))
b10=Button(text="2",font=("",25),bg="gray",fg="white",activebackground="yellow")
b10.place(x=110,y=165,width=100,height=50)
b10.configure(command=lambda:show("2"))
b11=Button(text="3",font=("",25),bg="gray",fg="white",activebackground="yellow")
b11.place(x=215,y=165,width=100,height=50)
b11.configure(command=lambda:show("3"))
b12=Button(text="*",font=("",25),bg="gray",fg="white",activebackground="yellow")
b12.place(x=320,y=165,width=100,height=50)
b12.configure(command=lambda:show("*"))
b13=Button(text="C",font=("",25),bg="gray",fg="white",activebackground="yellow")
b13.place(x=5,y=220,width=100,height=50)
b13.configure(command=clear)
b14=Button(text="0",font=("",25),bg="gray",fg="white",activebackground="yellow")
b14.place(x=110,y=220,width=100,height=50)
b14.configure(command=lambda:show("0"))
b15=Button(text="=",font=("",25),bg="gray",fg="white",activebackground="yellow",command=equal)
b15.place(x=215,y=220,width=100,height=50)
b15.configure(command=equal)
b16=Button(text="/",font=("",25),bg="gray",fg="white",activebackground="yellow")
b16.place(x=320,y=220,width=100,height=50)
b16.configure(command=lambda:show("/"))
t.mainloop() | 3.484375 | 3 |
core/models.py | uktrade/great-cms | 10 | 2209 | import hashlib
import mimetypes
from urllib.parse import unquote
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.http import HttpResponseRedirect
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.functional import cached_property
from django.utils.safestring import mark_safe
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField
from great_components.mixins import GA360Mixin
from modelcluster.contrib.taggit import ClusterTaggableManager
from modelcluster.models import ClusterableModel, ParentalKey
from taggit.managers import TaggableManager
from taggit.models import ItemBase, TagBase, TaggedItemBase
from wagtail.admin.edit_handlers import (
FieldPanel,
InlinePanel,
MultiFieldPanel,
ObjectList,
PageChooserPanel,
StreamFieldPanel,
TabbedInterface,
)
from wagtail.contrib.redirects.models import Redirect
from wagtail.contrib.settings.models import BaseSetting, register_setting
from wagtail.core import blocks
from wagtail.core.blocks.stream_block import StreamBlockValidationError
from wagtail.core.fields import RichTextField, StreamField
from wagtail.core.models import Orderable, Page
from wagtail.images import get_image_model_string
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.images.models import AbstractImage, AbstractRendition, Image
from wagtail.snippets.models import register_snippet
from wagtail.utils.decorators import cached_classmethod
from wagtailmedia.models import Media
from core import blocks as core_blocks, mixins
from core.case_study_index import delete_cs_index, update_cs_index
from core.constants import BACKLINK_QUERYSTRING_NAME, RICHTEXT_FEATURES__MINIMAL
from core.context import get_context_provider
from core.utils import PageTopicHelper, get_first_lesson
from exportplan.core.data import (
SECTION_SLUGS as EXPORTPLAN_SLUGS,
SECTIONS as EXPORTPLAN_URL_MAP,
)
# If we make a Redirect appear as a Snippet, we can sync it via Wagtail-Transfer
register_snippet(Redirect)
class GreatMedia(Media):
transcript = models.TextField(
verbose_name=_('Transcript'), blank=False, null=True # left null because was an existing field
)
subtitles_en = models.TextField(
verbose_name=_('English subtitles'),
null=True,
blank=True,
help_text='English-language subtitles for this video, in VTT format',
)
admin_form_fields = Media.admin_form_fields + (
'transcript',
'subtitles_en',
)
@property
def sources(self):
return [
{
'src': self.url,
'type': mimetypes.guess_type(self.filename)[0] or 'application/octet-stream',
'transcript': self.transcript,
}
]
@property
def subtitles(self):
output = []
# TO COME: support for more than just English
if self.subtitles_en:
output.append(
{
'srclang': 'en',
'label': 'English',
'url': reverse('core:subtitles-serve', args=[self.id, 'en']),
'default': False,
},
)
return output
class AbstractObjectHash(models.Model):
class Meta:
abstract = True
content_hash = models.CharField(max_length=1000)
@staticmethod
def generate_content_hash(field_file):
filehash = hashlib.md5()
field_file.open()
filehash.update(field_file.read())
field_file.close()
return filehash.hexdigest()
class DocumentHash(AbstractObjectHash):
document = models.ForeignKey(
'wagtaildocs.Document', null=True, blank=True, on_delete=models.CASCADE, related_name='+'
)
class ImageHash(AbstractObjectHash):
image = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.CASCADE, related_name='+')
class AltTextImage(AbstractImage):
alt_text = models.CharField(max_length=255, blank=True)
admin_form_fields = Image.admin_form_fields + ('alt_text',)
class Rendition(AbstractRendition):
image = models.ForeignKey(AltTextImage, on_delete=models.CASCADE, related_name='renditions')
class Meta:
unique_together = ('image', 'filter_spec', 'focal_point_key')
@property
def alt(self):
return self.image.alt_text
@register_snippet
class Tour(ClusterableModel):
page = models.OneToOneField('wagtailcore.Page', on_delete=models.CASCADE, related_name='tour')
title = models.CharField(max_length=255)
body = models.CharField(max_length=255)
button_text = models.CharField(max_length=255)
panels = [
PageChooserPanel('page'),
FieldPanel('title'),
FieldPanel('body'),
FieldPanel('button_text'),
MultiFieldPanel([InlinePanel('steps')], heading='Steps'),
]
def __str__(self):
return self.page.title
class TourStep(Orderable):
title = models.CharField(max_length=255)
body = models.CharField(max_length=255)
position = models.CharField(max_length=255)
selector = models.CharField(max_length=255)
tour = ParentalKey(Tour, on_delete=models.CASCADE, related_name='steps')
panels = [
FieldPanel('title'),
FieldPanel('body'),
FieldPanel('position'),
FieldPanel('selector'),
]
@register_snippet
class Product(models.Model):
name = models.CharField(max_length=255)
panels = [
FieldPanel('name'),
]
def __str__(self):
return self.name
@register_snippet
class Region(models.Model):
name = models.CharField(max_length=100, unique=True)
panels = [FieldPanel('name')]
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
@register_snippet
class Country(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=100, unique=True)
region = models.ForeignKey(Region, null=True, blank=True, on_delete=models.SET_NULL)
panels = [
FieldPanel('name'),
FieldPanel('region'),
]
class Meta:
verbose_name_plural = 'Countries'
ordering = ('name',)
def save(self, *args, **kwargs):
# Automatically set slug on save, if not already set
if not self.slug:
self.slug = slugify(self.name)
super().save(*args, **kwargs)
def __str__(self):
return self.name
@register_snippet
class Tag(models.Model):
name = models.CharField(max_length=100, unique=True)
panels = [FieldPanel('name')]
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
@register_snippet
class IndustryTag(models.Model):
name = models.CharField(max_length=100, unique=True)
icon = models.ForeignKey(
AltTextImage,
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+',
)
panels = [FieldPanel('name'), ImageChooserPanel('icon')]
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
class TimeStampedModel(models.Model):
"""Modified version of django_extensions.db.models.TimeStampedModel
Unfortunately, because null=True needed to be added to create and
modified fields, inheritance causes issues with field clash.
"""
created = CreationDateTimeField('created', null=True)
modified = ModificationDateTimeField('modified', null=True)
def save(self, **kwargs):
self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True))
super().save(**kwargs)
class Meta:
get_latest_by = 'modified'
ordering = (
'-modified',
'-created',
)
abstract = True
# Content models
class CMSGenericPage(
mixins.EnableTourMixin,
mixins.AuthenticatedUserRequired,
mixins.WagtailGA360Mixin,
GA360Mixin,
Page,
):
"""
Generic page, freely inspired by Codered page
"""
class Meta:
abstract = True
# Do not allow this page type to be created in wagtail admin
is_creatable = False
template_choices = []
###############
# Layout fields
###############
template = models.CharField(
max_length=255,
choices=None,
)
#########
# Panels
##########
layout_panels = [FieldPanel('template')]
settings_panels = [FieldPanel('slug')] + Page.settings_panels
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
field = self._meta.get_field('template')
field.choices = self.template_choices
field.required = True
@cached_classmethod
def get_edit_handler(cls): # NOQA N805
panels = [
ObjectList(cls.content_panels, heading='Content'),
ObjectList(cls.layout_panels, heading='Layout'),
ObjectList(cls.settings_panels, heading='Settings', classname='settings'),
]
return TabbedInterface(panels).bind_to(model=cls)
def get_template(self, request, *args, **kwargs):
return self.template
def get_context(self, request, *args, **kwargs):
context = super().get_context(request)
self.set_ga360_payload(
page_id=self.id,
business_unit=settings.GA360_BUSINESS_UNIT,
site_section=str(self.url or '/').split('/')[1],
)
self.add_ga360_data_to_payload(request)
context['ga360'] = self.ga360_payload
provider = get_context_provider(request=request, page=self)
if provider:
context.update(provider.get_context_data(request=request, page=self))
return context
class LandingPage(CMSGenericPage):
parent_page_types = [
'domestic.DomesticHomePage', # TODO: once we've restructured, remove this permission
'domestic.GreatDomesticHomePage',
]
subpage_types = [
'core.ListPage',
'core.InterstitialPage',
'domestic.DomesticDashboard',
]
template_choices = (
('learn/landing_page.html', 'Learn'),
('core/generic_page.html', 'Generic'),
)
################
# Content fields
################
description = RichTextField()
button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True)
image = models.ForeignKey(
get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+'
)
body = StreamField(
[
('section', core_blocks.SectionBlock()),
('title', core_blocks.TitleBlock()),
('text', blocks.RichTextBlock(icon='openquote', helptext='Add a textblock')),
('image', core_blocks.ImageBlock()),
],
null=True,
blank=True,
)
components = StreamField(
[
('route', core_blocks.RouteSectionBlock()),
],
null=True,
blank=True,
)
#########
# Panels
#########
content_panels = CMSGenericPage.content_panels + [
FieldPanel('description'),
StreamFieldPanel('button'),
ImageChooserPanel('image'),
StreamFieldPanel('components'),
StreamFieldPanel('body'),
]
class InterstitialPage(CMSGenericPage):
parent_page_types = ['core.LandingPage']
template_choices = (('learn/interstitial.html', 'Learn'),)
################
# Content fields
################
button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True)
#########
# Panels
#########
content_panels = CMSGenericPage.content_panels + [
StreamFieldPanel('button'),
]
class ListPage(CMSGenericPage):
parent_page_types = ['core.LandingPage']
subpage_types = ['core.CuratedListPage']
template_choices = (('learn/automated_list_page.html', 'Learn'),)
record_read_progress = models.BooleanField(
default=False,
help_text='Should we record when a user views a page in this collection?',
)
class Meta:
verbose_name = 'Automated list page'
verbose_name_plural = 'Automated list pages'
def get_context(self, request, *args, **kwargs):
from core.helpers import get_high_level_completion_progress
from domestic.helpers import get_lesson_completion_status
context = super().get_context(request)
if request.user.is_authenticated:
completion_status = get_lesson_completion_status(request.user)
context['high_level_completion_progress'] = get_high_level_completion_progress(
completion_status=completion_status,
)
return context
################
# Content fields
################
description = RichTextField()
button_label = models.CharField(max_length=100)
#########
# Panels
#########
settings_panels = CMSGenericPage.settings_panels + [FieldPanel('record_read_progress')]
content_panels = CMSGenericPage.content_panels + [FieldPanel('description'), FieldPanel('button_label')]
class CuratedListPage(CMSGenericPage):
parent_page_types = ['core.ListPage']
subpage_types = [
'core.TopicPage',
]
template_choices = (('learn/curated_list_page.html', 'Learn'),)
################
# Content fields
################
heading = RichTextField()
image = models.ForeignKey(
get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+'
)
########
# Panels
########
content_panels = CMSGenericPage.content_panels + [
FieldPanel('heading'),
ImageChooserPanel('image'),
]
def get_topics(self, live=True) -> models.QuerySet:
qs = TopicPage.objects.live().specific().descendant_of(self)
if live:
qs = qs.live()
return qs
@cached_property
def count_topics(self):
return self.get_topics().count()
@cached_property
def count_detail_pages(self):
count = 0
for topic in self.get_topics():
count += DetailPage.objects.live().descendant_of(topic).count()
return count
def get_context(self, request, *args, **kwargs):
from core.helpers import (
get_high_level_completion_progress,
get_module_completion_progress,
)
from domestic.helpers import get_lesson_completion_status
context = super().get_context(request)
# Give the template a simple way to link back to the parent
# learning module (ListPage)
context['parent_page_url'] = self.get_parent().url
if request.user.is_authenticated:
# get this once, so we don't waste the network call to get the data twice
completion_status = get_lesson_completion_status(request.user)
context['module_completion_progress'] = get_module_completion_progress(
completion_status=completion_status,
module_page=self,
)
context['high_level_completion_progress'] = get_high_level_completion_progress(
completion_status=completion_status,
)
return context
def hero_singular_validation(value):
if value and len(value) > 1:
raise StreamBlockValidationError(
non_block_errors=ValidationError('Only one image or video allowed in Hero section', code='invalid'),
)
class TopicPage(mixins.AuthenticatedUserRequired, Page):
"""Structural page to allow for cleaner mapping of lessons (`DetailPage`s)
to modules (`CuratedListPage`s).
Not intented to be viewed by end users, so will redirect to the parent
module if accessed.
Also, for the above reason, mixins.WagtailGA360Mixin and GA360Mixin
are not used."""
parent_page_types = ['core.CuratedListPage']
subpage_types = [
'core.DetailPage',
'core.LessonPlaceholderPage',
]
# `title` comes from Page superclass and that's all we need here
def _redirect_to_parent_module(self):
return HttpResponseRedirect(self.get_parent().url)
def serve_preview(self, request, mode_name='dummy'):
# It doesn't matter what is passed as mode_name - we always redirect
return self._redirect_to_parent_module()
def serve(self, request):
return self._redirect_to_parent_module()
class LessonPlaceholderPage(mixins.AuthenticatedUserRequired, Page):
"""Structural page to allow for configuring and representing very simple
to modules (`CuratedListPage`s).
Not intented to be viewed by end users, so will redirect to the parent
module if accessed.
Also, for the above reason, mixins.WagtailGA360Mixin and GA360Mixin
are not used."""
parent_page_types = ['core.TopicPage']
subpage_types = [] # No child pages allowed for placeholders
# `title` comes from Page superclass and that's all we need here
def _redirect_to_parent_module(self):
dest = CuratedListPage.objects.ancestor_of(self).first().url
return HttpResponseRedirect(dest)
def serve_preview(self, request, mode_name='dummy'):
# It doesn't matter what is passed as mode_name - we always redirect
return self._redirect_to_parent_module()
def serve(self, request):
return self._redirect_to_parent_module()
class DetailPage(CMSGenericPage):
estimated_read_duration = models.DurationField(null=True, blank=True)
parent_page_types = [
'core.CuratedListPage', # TEMPORARY: remove after topics refactor migration has run
'core.TopicPage',
]
template_choices = (('learn/detail_page.html', 'Learn'),)
class Meta:
verbose_name = 'Detail page'
verbose_name_plural = 'Detail pages'
################
# Content fields
################
hero = StreamField(
[
('Image', core_blocks.ImageBlock(template='core/includes/_hero_image.html')),
('Video', core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')),
],
null=True,
blank=True,
validators=[hero_singular_validation],
)
objective = StreamField(
[
(
'paragraph',
blocks.RichTextBlock(options={'class': 'objectives'}),
),
('ListItem', core_blocks.Item()),
]
)
body = StreamField(
[
(
'paragraph',
blocks.StructBlock(
[('paragraph', blocks.RichTextBlock())],
template='core/struct_paragraph_block.html',
icon='fa-font',
),
),
(
'video',
blocks.StructBlock(
[('video', core_blocks.VideoBlock())],
template='core/struct_video_block.html',
icon='fa-play',
),
),
('case_study', core_blocks.CaseStudyStaticBlock(icon='fa-book')),
(
'Step',
core_blocks.StepByStepBlock(icon='cog'),
),
(
'fictional_example',
blocks.StructBlock(
[('fiction_body', blocks.RichTextBlock(icon='openquote'))],
template='learn/fictional_company_example.html',
icon='fa-commenting-o',
),
),
(
'ITA_Quote',
core_blocks.ITAQuoteBlock(icon='fa-quote-left'),
),
(
'pros_cons',
blocks.StructBlock(
[
(
'pros',
blocks.StreamBlock(
[
(
'item',
core_blocks.Item(icon='fa-arrow-right'),
)
]
),
),
(
'cons',
blocks.StreamBlock(
[
(
'item',
core_blocks.Item(icon='fa-arrow-right'),
)
]
),
),
],
template='learn/pros_and_cons.html',
icon='fa-arrow-right',
),
),
('choose_do_not_choose', core_blocks.ChooseDoNotChooseBlock()),
(
'image',
core_blocks.ImageBlock(
template='core/includes/_image_full_width.html',
help_text='Image displayed within a full-page-width block',
),
),
(
'video',
core_blocks.SimpleVideoBlock(
template='core/includes/_video_full_width.html',
help_text='Video displayed within a full-page-width block',
),
),
]
)
recap = StreamField(
[
(
'recap_item',
blocks.StructBlock(
[
('title', blocks.CharBlock(icon='fa-header')),
(
'item',
blocks.StreamBlock(
[
(
'item',
core_blocks.Item(),
)
]
),
),
],
template='learn/recap.html',
icon='fa-commenting-o',
),
)
]
)
#########
# Panels
##########
content_panels = Page.content_panels + [
StreamFieldPanel('hero'),
StreamFieldPanel('objective'),
StreamFieldPanel('body'),
StreamFieldPanel('recap'),
]
def handle_page_view(self, request):
if request.user.is_authenticated:
# checking if the page should record read progress
# checking if the page is already marked as read
list_page = (
ListPage.objects.ancestor_of(self)
.filter(record_read_progress=True)
.exclude(page_views_list__sso_id=request.user.pk, page_views_list__page=self)
.first()
)
if list_page:
PageView.objects.get_or_create(
page=self,
list_page=list_page,
sso_id=request.user.pk,
)
def serve(self, request, *args, **kwargs):
self.handle_page_view(request)
return super().serve(request, **kwargs)
@cached_property
def topic_title(self):
return self.get_parent().title
@cached_property
def module(self):
"""Gets the learning module this lesson belongs to"""
return CuratedListPage.objects.live().specific().ancestor_of(self).first()
@cached_property
def _export_plan_url_map(self):
"""Return a lookup dictionary of URL Slugs->title for all the
Export Plan sections we have."""
return {url: values['title'] for url, values in EXPORTPLAN_URL_MAP.items()}
def _get_backlink(self, request):
"""Try to extract a backlink (used for a link to the export plan) from the
querystring on the request that brought us to this view.
Only accepts backlinks that we KNOW are for the export plan, else ignore it."""
backlink_path = request.GET.get(BACKLINK_QUERYSTRING_NAME, '')
if backlink_path is not None:
backlink_path = unquote(backlink_path)
if len(backlink_path.split('/')) > 2 and (
backlink_path.split('/')[3] in EXPORTPLAN_SLUGS and '://' not in backlink_path
):
# The check for '://' will stop us accepting a backlink which
# features a full URL as its OWN querystring param (eg a crafted attack
# URL), but that's an acceptable limitation here and is very unlikely
# to happen.
return backlink_path
return None # safe default
def _get_backlink_title(self, backlink_path):
"""For a given backlink, see if we can get a title that goes with it.
For now, this is limited only to Export Plan pages/links.
"""
# We have to re-arrange EXPORT_PLAN_SECTION_TITLES_URLS after import
# because it features lazily-evaluated URLs that aren't ready when
# models are imported
if backlink_path and len(backlink_path.split('/')) > 3:
_path = backlink_path.split('/')[3]
return self._export_plan_url_map.get(_path)
def get_context(self, request, *args, **kwargs):
context = super().get_context(request)
context['refresh_on_market_change'] = True
# Prepare backlink to the export plan if we detect one and can validate it
_backlink = self._get_backlink(request)
if _backlink:
context['backlink'] = _backlink
context['backlink_title'] = self._get_backlink_title(_backlink)
if isinstance(self.get_parent().specific, TopicPage):
# In a conditional because a DetailPage currently MAY be used as
# a child of another page type...
page_topic_helper = PageTopicHelper(self)
next_lesson = page_topic_helper.get_next_lesson()
context['current_lesson'] = self
context['current_module'] = page_topic_helper.module
if page_topic_helper:
topic_page = page_topic_helper.get_page_topic()
if topic_page:
context['current_topic'] = topic_page
context['page_topic'] = topic_page.title
if next_lesson:
context['next_lesson'] = next_lesson
else:
next_module = self.module.get_next_sibling()
if not next_module:
return context
context['next_module'] = next_module.specific
context['next_lesson'] = get_first_lesson(next_module)
return context
class PageView(TimeStampedModel):
page = models.ForeignKey(DetailPage, on_delete=models.CASCADE, related_name='page_views')
list_page = models.ForeignKey(ListPage, on_delete=models.CASCADE, related_name='page_views_list')
sso_id = models.TextField()
class Meta:
ordering = ['page__pk']
unique_together = ['page', 'sso_id']
# TODO: deprecate and remove
class ContentModuleTag(TaggedItemBase):
content_object = ParentalKey('core.ContentModule', on_delete=models.CASCADE, related_name='tagged_items')
# TODO: deprecate and remove
@register_snippet
class ContentModule(ClusterableModel):
title = models.CharField(max_length=255)
content = RichTextField()
tags = TaggableManager(through=ContentModuleTag, blank=True)
panels = [
FieldPanel('title'),
FieldPanel('content'),
FieldPanel('tags'),
]
def __str__(self):
return self.title
class PersonalisationHSCodeTag(TagBase):
"""Custom tag for personalisation.
Tag value will be a HS6, HS4 or HS2 code"""
# free_tagging = False # DISABLED until tag data only comes via data migration
class Meta:
verbose_name = 'HS Code tag for personalisation'
verbose_name_plural = 'HS Code tags for personalisation'
class PersonalisationCountryTag(TagBase):
"""Custom tag for personalisation.
Tag value will be an ISO-2 Country code ('DE')
"""
free_tagging = False
class Meta:
verbose_name = 'Country tag for personalisation'
verbose_name_plural = 'Country tags for personalisation'
class PersonalisationRegionTag(TagBase):
"""Custom tag for personalisation.
Tag value will be a geographical string ('Europe')
"""
free_tagging = False
class Meta:
verbose_name = 'Region tag for personalisation'
verbose_name_plural = 'Region tags for personalisation'
class PersonalisationTradingBlocTag(TagBase):
"""Custom tag for personalisation.
Tag value will be an Trading blocs
"""
free_tagging = False
class Meta:
verbose_name = 'Trading bloc tag for personalisation'
verbose_name_plural = 'Trading bloc tags for personalisation'
# If you're wondering what's going on here:
# https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models
class HSCodeTaggedCaseStudy(ItemBase):
tag = models.ForeignKey(
PersonalisationHSCodeTag, related_name='hscode_tagged_case_studies', on_delete=models.CASCADE
)
content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='hs_code_tagged_items')
class CountryTaggedCaseStudy(ItemBase):
tag = models.ForeignKey(
PersonalisationCountryTag, related_name='country_tagged_case_studies', on_delete=models.CASCADE
)
content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='country_tagged_items')
class RegionTaggedCaseStudy(ItemBase):
tag = models.ForeignKey(
PersonalisationRegionTag, related_name='region_tagged_case_studies', on_delete=models.CASCADE
)
content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='region_tagged_items')
class TradingBlocTaggedCaseStudy(ItemBase):
tag = models.ForeignKey(
PersonalisationTradingBlocTag, related_name='trading_bloc_tagged_case_studies', on_delete=models.CASCADE
)
content_object = ParentalKey(
to='core.CaseStudy', on_delete=models.CASCADE, related_name='trading_bloc_tagged_items'
)
def _high_level_validation(value, error_messages):
TEXT_BLOCK = 'text' # noqa N806
MEDIA_BLOCK = 'media' # noqa N806
QUOTE_BLOCK = 'quote' # noqa N806
# we need to be strict about presence and ordering of these nodes
if [node.block_type for node in value if node.block_type != QUOTE_BLOCK] != [MEDIA_BLOCK, TEXT_BLOCK]:
error_messages.append(
(
'This block must contain one Media section (with one or '
'two items in it) and/or a Quote section, then one Text section following it.'
)
)
return error_messages
def _low_level_validation(value, error_messages):
# Check content of media node, which should be present here
MEDIA_BLOCK = 'media' # noqa N806
VIDEO_BLOCK = 'video' # noqa N806
for node in value:
if node.block_type == MEDIA_BLOCK:
subnode_block_types = [subnode.block_type for subnode in node.value]
if len(subnode_block_types) == 2:
if set(subnode_block_types) == {VIDEO_BLOCK}:
# Two videos: not allowed
error_messages.append('Only one video may be used in a case study.')
elif subnode_block_types[1] == VIDEO_BLOCK:
# implicitly, [0] must be an image
# video after image: not allowed
error_messages.append('The video must come before a still image.')
return error_messages
def case_study_body_validation(value):
"""Ensure the case study has exactly both a media node and a text node
and that the media node has the following content:
* One image, only
* One video, only
* One video + One image
* (video must comes first so that it is displayed first)
* Two images
"""
error_messages = []
if value:
error_messages = _high_level_validation(value, error_messages)
error_messages = _low_level_validation(value, error_messages)
if error_messages:
raise StreamBlockValidationError(
non_block_errors=ValidationError('; '.join(error_messages), code='invalid'),
)
class MagnaPageChooserPanel(PageChooserPanel):
show_label = False
field_template = 'admin/wagtailadmin/edit_handlers/field_panel_field.html'
def render_as_field(self):
instance_obj = self.get_chosen_item()
context = {
'field': self.bound_field,
self.object_type_name: instance_obj,
'is_chosen': bool(instance_obj), # DEPRECATED - passed to templates for backwards compatibility only
# Added obj_type on base class method render_as_field
'obj_type': instance_obj.specific.__class__.__name__ if instance_obj else None,
}
return mark_safe(render_to_string(self.field_template, context))
class CaseStudyRelatedPages(Orderable):
case_study = ParentalKey(
'core.CaseStudy',
related_name='related_pages',
on_delete=models.SET_NULL,
null=True,
blank=True,
)
page = models.ForeignKey(
'wagtailcore.Page',
on_delete=models.CASCADE,
related_name='+',
)
panels = [
MagnaPageChooserPanel('page', [DetailPage, CuratedListPage, TopicPage]),
]
class Meta:
unique_together = ['case_study', 'page']
@register_snippet
class CaseStudy(ClusterableModel):
"""Dedicated snippet for use as a case study. Supports personalised
selection via its tags.
The decision about the appropriate Case Study block to show will happen
when the page attempts to render the relevant CaseStudyBlock.
Note that this is rendered via Wagtail's ModelAdmin, so appears in the sidebar,
but we have to keep it registered as a Snippet to be able to transfer it
with Wagtail-Transfer
"""
title = models.CharField(
max_length=255,
blank=False,
verbose_name='Internal case study title',
)
# old name company_name
summary_context = models.CharField(max_length=255, blank=False, default='How we did it')
# old name summary
lead_title = models.TextField(blank=False) # Deliberately not rich-text / no formatting
body = StreamField(
[
(
'media',
blocks.StreamBlock(
[
('video', core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')),
('image', core_blocks.ImageBlock()),
],
min_num=1,
max_num=2,
),
),
(
'text',
blocks.RichTextBlock(
features=RICHTEXT_FEATURES__MINIMAL,
),
),
(
'quote',
core_blocks.CaseStudyQuoteBlock(),
),
],
validators=[case_study_body_validation],
help_text=(
'This block must contain one Media section (with one or two items in it) '
'and/or Quote sections, then one Text section.'
),
)
# We are keeping the personalisation-relevant tags in separate
# fields to aid lookup and make the UX easier for editors
hs_code_tags = ClusterTaggableManager(through='core.HSCodeTaggedCaseStudy', blank=True, verbose_name='HS-code tags')
country_code_tags = ClusterTaggableManager(
through='core.CountryTaggedCaseStudy', blank=True, verbose_name='Country tags'
)
region_code_tags = ClusterTaggableManager(
through='core.RegionTaggedCaseStudy', blank=True, verbose_name='Region tags'
)
trading_bloc_code_tags = ClusterTaggableManager(
through='core.TradingBlocTaggedCaseStudy', blank=True, verbose_name='Trading bloc tags'
)
created = CreationDateTimeField('created', null=True)
modified = ModificationDateTimeField('modified', null=True)
panels = [
MultiFieldPanel(
[
FieldPanel('title'),
FieldPanel('lead_title'),
FieldPanel('summary_context'),
StreamFieldPanel('body'),
],
heading='Case Study content',
),
MultiFieldPanel(
[
FieldPanel('hs_code_tags'),
FieldPanel('country_code_tags'),
FieldPanel('region_code_tags'),
FieldPanel('trading_bloc_code_tags'),
],
heading='Case Study tags for Personalisation',
),
MultiFieldPanel(
[
InlinePanel('related_pages', label='Related pages'),
],
heading='Related Lesson, Topic & Module, also used for Personalisation',
),
]
def __str__(self):
display_name = self.title if self.title else self.summary_context
return f'{display_name}'
def save(self, **kwargs):
# When we create a new CS need to call create to obtain an ID for indexing
self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True))
super().save(**kwargs)
update_cs_index(self)
def delete(self, **kwargs):
delete_cs_index(self.id)
super().delete(**kwargs)
def get_cms_standalone_view_url(self):
return reverse('cms_extras:case-study-view', args=[self.id])
class Meta:
verbose_name_plural = 'Case studies'
get_latest_by = 'modified'
ordering = (
'-modified',
'-created',
)
@register_setting
class CaseStudyScoringSettings(BaseSetting):
threshold = models.DecimalField(
help_text='This is the minimum score which a case study needs to have to be '
'considered before being presented to users. ',
default=10,
decimal_places=3,
max_digits=5,
)
lesson = models.DecimalField(
help_text="Score given when user's lesson is tagged in the case study.",
default=8,
decimal_places=3,
max_digits=5,
)
topic = models.DecimalField(
help_text="Score given when user's lesson's topic is tagged in the case study "
'unless there is also lesson match.',
default=4,
decimal_places=3,
max_digits=5,
)
module = models.DecimalField(
help_text="Score given when the user's lesson's module is tagged in the case study "
'unless there is also lesson or topic match.',
default=2,
decimal_places=3,
max_digits=5,
)
product_hs6 = models.DecimalField(
help_text='Score given when any case study HS6 tag matches the complete HS6 code of '
"any of the user's products",
default=8,
decimal_places=3,
max_digits=5,
)
product_hs4 = models.DecimalField(
help_text="Score given when any case study HS4 tag matches the first 4 digits of any of the user's products "
'unless there is an HS6 match.',
default=4,
decimal_places=3,
max_digits=5,
)
product_hs2 = models.DecimalField(
help_text="Score given when any case study HS2 tag matches the first 2 digits of any of the user's products "
'unless there is an HS6 or HS4 match.',
default=2,
decimal_places=3,
max_digits=5,
)
country_exact = models.DecimalField(
help_text="Score given when any case study country tag exactly matches one of the user's export markets.",
default=4,
decimal_places=3,
max_digits=5,
)
country_region = models.DecimalField(
help_text="Score given when any case study region tag matches the region of any of the user's export markets "
'unless there is an exact country match.',
default=2,
decimal_places=3,
max_digits=5,
)
trading_blocs = models.DecimalField(
help_text='Score given when any case study trading bloc tag matches the any trading bloc that any of '
"the user's export markets falls into unless there is an exact country or region match.",
default=2,
decimal_places=3,
max_digits=5,
)
product_tab = [MultiFieldPanel([FieldPanel('product_hs6'), FieldPanel('product_hs4'), FieldPanel('product_hs2')])]
market_tab = [
MultiFieldPanel([FieldPanel('country_exact'), FieldPanel('country_region'), FieldPanel('trading_blocs')])
]
lesson_tab = [MultiFieldPanel([FieldPanel('lesson'), FieldPanel('topic'), FieldPanel('module')])]
threshold_tab = [
MultiFieldPanel(
[
FieldPanel('threshold'),
]
)
]
edit_handler = TabbedInterface(
[
ObjectList(product_tab, heading='Product'),
ObjectList(market_tab, heading='Market'),
ObjectList(lesson_tab, heading='Lesson'),
ObjectList(threshold_tab, heading='Threshold'),
]
)
class Meta:
verbose_name = 'Case Study Scoring'
| 1.359375 | 1 |
CV/Effective Transformer-based Solution for RSNA Intracranial Hemorrhage Detection/easymia/transforms/transforms.py | dumpmemory/Research | 0 | 2210 | # -*-coding utf-8 -*-
##########################################################################
#
# Copyright (c) 2022 Baidu.com, Inc. 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.
#
##########################################################################
"""
数据变换器
"""
import numpy as np
import numbers
import collections
import random
import math
import cv2
from . import functional as F
from easymia.core.abstract_transforms import AbstractTransform
from easymia.libs import manager
@manager.TRANSFORMS.add_component
class Compose(AbstractTransform):
"""
Do transformation on input data with corresponding pre-processing and augmentation operations.
The shape of input data to all operations is [height, width, channels].
Args:
transforms (list): A list contains data pre-processing or augmentation. Empty list means only reading images, no transformation.
to_rgb (bool, optional): If converting image to RGB color space. Default: True.
Raises:
TypeError: When 'transforms' is not a list.
ValueError: when the length of 'transforms' is less than 1.
"""
def __init__(self, mode, transforms):
if not isinstance(transforms, list):
raise TypeError('The transforms must be a list!')
self.transforms = transforms
super().__init__(mode)
def __clas__(self, im):
"""
Args:
im (np.ndarray): It is either image path or image object.
Returns:
(np.array). Image after transformation.
"""
for op in self.transforms:
im = op(im)
return im
@manager.TRANSFORMS.add_component
class RandomHorizontalFlip(AbstractTransform):
"""Horizontally flip the given PIL Image randomly with a given probability.
Args:
p (float): probability of the image being flipped. Default value is 0.5
"""
def __init__(self, mode, prob=0.5):
"""
init
"""
self.prob = prob
super().__init__(mode)
def __clas__(self, img):
"""
Args:
img (numpy ndarray): Image to be flipped.
Returns:
numpy ndarray: Randomly flipped image.
"""
if random.random() < self.prob:
return F.hflip(img)
return img
@manager.TRANSFORMS.add_component
class RandomVerticalFlip(AbstractTransform):
"""Vertically flip the given PIL Image randomly with a given probability.
Args:
p (float): probability of the image being flipped. Default value is 0.5
"""
def __init__(self, mode, prob=0.5):
"""
init
"""
self.prob = prob
super().__init__(mode)
def __clas__(self, img):
"""
Args:
img (numpy ndarray): Image to be flipped.
Returns:
numpy ndarray: Randomly flipped image.
"""
if random.random() < self.prob:
return F.vflip(img)
return img
@manager.TRANSFORMS.add_component
class RandomResizedCrop(AbstractTransform):
"""Crop the given numpy ndarray to random size and aspect ratio.
A crop of random size (default: of 0.08 to 1.0) of the original size and a random
aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop
is finally resized to given size.
This is popularly used to train the Inception networks.
Args:
size: expected output size of each edge
scale: range of size of the origin size cropped
ratio: range of aspect ratio of the origin aspect ratio cropped
interpolation: Default: cv2.INTER_CUBIC
"""
def __init__(self, mode, size, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.), interpolation=cv2.INTER_CUBIC):
"""
init
"""
self.size = (size, size)
self.interpolation = interpolation
self.scale = scale
self.ratio = ratio
super().__init__(mode)
def get_params(self, img, scale, ratio):
"""Get parameters for ``crop`` for a random sized crop.
Args:
img (numpy ndarray): Image to be cropped.
scale (tuple): range of size of the origin size cropped
ratio (tuple): range of aspect ratio of the origin aspect ratio cropped
Returns:
tuple: params (i, j, h, w) to be passed to ``crop`` for a random
sized crop.
"""
params_ret = collections.namedtuple('params_ret', ['i', 'j', 'h', 'w'])
for attempt in range(10):
area = img.shape[0] * img.shape[1]
target_area = random.uniform(*scale) * area
aspect_ratio = random.uniform(*ratio)
w = int(round(math.sqrt(target_area * aspect_ratio)))
h = int(round(math.sqrt(target_area / aspect_ratio)))
if random.random() < 0.5:
w, h = h, w
if w <= img.shape[1] and h <= img.shape[0]:
i = random.randint(0, img.shape[0] - h)
j = random.randint(0, img.shape[1] - w)
return params_ret(i, j, h, w)
# Fallback
w = min(img.shape[0], img.shape[1])
i = (img.shape[0] - w) // 2
j = (img.shape[1] - w) // 2
return params_ret(i, j, w, w)
def __clas__(self, img):
"""
Args:
img (numpy ndarray): Image to be cropped and resized.
Returns:
numpy ndarray: Randomly cropped and resized image.
"""
i, j, h, w = self.get_params(img, self.scale, self.ratio)
return F.resized_crop(img, i, j, h, w, self.size, self.interpolation)
@manager.TRANSFORMS.add_component
class RandomRotation(AbstractTransform):
"""Rotate the image by angle.
Args:
degrees (sequence or float or int): Range of degrees to select from.
If degrees is a number instead of sequence like (min, max), the range of degrees
will be (-degrees, +degrees).
resample ({cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4}, optional):
An optional resampling filter. See `filters`_ for more information.
If omitted, or if the image has mode "1" or "P", it is set to PIL.Image.NEAREST.
expand (bool, optional): Optional expansion flag.
If true, expands the output to make it large enough to hold the entire rotated image.
If false or omitted, make the output image the same size as the input image.
Note that the expand flag assumes rotation around the center and no translation.
center (2-tuple, optional): Optional center of rotation.
Origin is the upper left corner.
Default is the center of the image.
"""
def __init__(self, mode, degrees, center=None):
"""
init
"""
if isinstance(degrees, numbers.Number):
if degrees < 0:
raise ValueError(
"If degrees is a single number, it must be positive.")
self.degrees = (-degrees, degrees)
else:
if len(degrees) != 2:
raise ValueError(
"If degrees is a sequence, it must be of len 2.")
self.degrees = degrees
self.center = center
super().__init__(mode)
@staticmethod
def get_params(degrees):
"""Get parameters for ``rotate`` for a random rotation.
Returns:
sequence: params to be passed to ``rotate`` for random rotation.
"""
angle = random.uniform(degrees[0], degrees[1])
return angle
def __clas__(self, img):
"""
img (numpy ndarray): Image to be rotated.
Returns:
numpy ndarray: Rotated image.
"""
angle = self.get_params(self.degrees)
return F.rotate(img, angle, self.center)
@manager.TRANSFORMS.add_component
class Resize(AbstractTransform):
"""Resize the input numpy ndarray to the given size.
Args:
size (sequence or int): Desired output size. If size is a sequence like
(h, w), output size will be matched to this. If size is an int,
smaller edge of the image will be matched to this number.
i.e, if height > width, then image will be rescaled to
(size * height / width, size)
interpolation (int, optional): Desired interpolation. Default is
``cv2.INTER_CUBIC``, bicubic interpolation
"""
def __init__(self, mode, size, interpolation=cv2.INTER_LINEAR):
"""
resize
"""
# assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)
if isinstance(size, int):
self.size = (size, size)
elif isinstance(size, collections.abc.Iterable) and len(size) == 2:
if type(size) == list:
size = tuple(size)
self.size = size
else:
raise ValueError('Unknown inputs for size: {}'.format(size))
self.interpolation = interpolation
super().__init__(mode)
def __clas__(self, img):
"""
Args:
img (numpy ndarray): Image to be scaled.
Returns:
numpy ndarray: Rescaled image.
"""
return F.resize(img, self.size, self.interpolation) | 2.140625 | 2 |
tests/ui/terms/test_views.py | galterlibrary/InvenioRDM-at-NU | 6 | 2211 | # -*- coding: utf-8 -*-
#
# This file is part of menRva.
# Copyright (C) 2018-present NU,FSM,GHSL.
#
# menRva is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Test terms views.py"""
from cd2h_repo_project.modules.terms.views import serialize_terms_for_edit_ui
def test_serialize_terms_for_edit_ui(create_record):
deposit = create_record(
{
'terms': [
{'source': 'MeSH', 'value': 'Cognitive Neuroscience'},
{'source': 'FAST', 'value': 'Border terrier'}
]
},
published=False
)
serialized_deposit = serialize_terms_for_edit_ui(deposit)
assert 'terms' not in serialized_deposit
assert serialized_deposit['mesh_terms'] == [
{
'data': {'source': 'MeSH', 'value': 'Cognitive Neuroscience'}
}
]
assert serialized_deposit['fast_terms'] == [
{
'data': {'source': 'FAST', 'value': 'Border terrier'}
}
]
def test_serialize_terms_for_edit_ui_no_terms(create_record):
deposit = create_record(published=False)
serialized_deposit = serialize_terms_for_edit_ui(deposit)
assert 'terms' not in serialized_deposit
assert serialized_deposit['mesh_terms'] == []
assert serialized_deposit['fast_terms'] == []
| 2.203125 | 2 |
main.py | alamin3637k/Searcher | 1 | 2212 | <gh_stars>1-10
import webbrowser
import wikipedia
import requests
def yt_search(search: str):
webbrowser.open_new_tab(f"https://www.youtube.com/results?search_query={search}")
def google_search(search: str):
webbrowser.open_new_tab(f"https://www.google.com/search?q={search}")
def bing_search(search: str):
webbrowser.open_new_tab(f"https://www.bing.com/search?q={search}")
def duck_search(search: str):
webbrowser.open_new_tab(f"https://duckduckgo.com/?q={search}")
def yahoo_search(search: str):
webbrowser.open_new_tab(f"https://search.yahoo.com/search?p={search}")
def ask_search(search: str):
webbrowser.open_new_tab(f"https://www.ask.com/web?q={search}")
def yandex_search(search: str):
webbrowser.open_new_tab(f"https://yandex.com/search/?text={search}")
def ecosia_search(search: str):
webbrowser.open_new_tab(f"https://www.ecosia.org/search?q={search}")
def fb_search(search: str):
webbrowser.open_new_tab(f"https://www.facebook.com/search/top/?q={search}")
def wiki_terminal_search(search: str, lang='en', sentence=1):
try:
wikipedia.set_lang(lang)
print(wikipedia.summary(search, sentences=sentence))
except Exception as error:
print(error)
return error
def mail_search(search: str):
webbrowser.open_new_tab(f"https://mail.google.com/mail/u/0/#search/{search}")
def wiki_web_search(search: str):
webbrowser.open_new_tab(f"https://en.wikipedia.org/wiki/{search}")
def test_site(search: str):
"""please enter site name with http information"""
try:
r = requests.get(search)
except Exception as error:
print(error)
return "site not working"
if r.status_code == 200:
print("site working")
return "site working"
| 3.265625 | 3 |
hw1.py | ptsurko/coursera_crypt | 0 | 2213 | <reponame>ptsurko/coursera_crypt<filename>hw1.py
import string
from timeit import itertools
s1 = '<KEY>'
s2 = '<KEY>'
s3 = '32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb'
s4 = '32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa'
s5 = '3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070'
s6 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4'
s7 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce'
s8 = '315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3'
s9 = '271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027'
s10 = '466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83'
s11 = '32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904'
def strxor(a, b): # xor two strings of different lengths
# a = a.decode('hex')
# b = b.decode('hex')
if len(a) > len(b):
return ("".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])) #.encode('hex')
else:
return ("".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])) #.encode('hex')
def random(size=16):
return open("/dev/urandom").read(size)
def encrypt(key, msg):
c = strxor(key, msg)
print
print c #.encode('hex')
return c
MSGS = (s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11)
MSGS_DECODED = [s.decode('hex') for s in MSGS]
def combinations(iterable, r):
indices = range(r)
n = len(iterable)
while True:
yield tuple(i for i in indices) + (tuple(iterable[i] for i in indices),)
for i in reversed(range(r)):
if indices[i] < n - (r - i):
indices[i] = indices[i] + 1
for j in range(i + 1, r):
indices[j] = indices[j - 1] + 1
break
else:
return
# def main():
# for c in combinations('ABCD', 2):
# print c
def output_combinations_table():
comb = [(i1, i2, strxor(s1.decode('hex'), s2.decode('hex'))) for i1, i2, (s1,s2) in combinations(MSGS, 2)]
html = '<html><body>'
html += '<table style="white-space:nowrap" border="1">'
html += '<thead>'
html += '<tr>'
# WTF???
# max_len = max(combinations, key=lambda x: len(x))
max_len = 0
for i1, i2, c in comb:
if len(c) > max_len:
max_len = len(c)
# print max_len
html += '<th></th>'
for i in xrange(max_len):
html += '<th>' + str(i) + '</th>'
html += '</tr>'
html += '</thead>'
for i1, i2, c in comb:
html += '<tr>'
html += '<td>(%s, %s)</td>' % (i1 + 1, i2 + 1)
for ch in c:
html += '<td>'
html += '%02d' % ord(ch)
if ch in string.printable:
html += '<br />'
html += '&#%d;' % ord(ch)
html += '</td>'
html += '</tr>'
html += '<tr>'
html += '<th></th>'
for i in xrange(max_len):
html += '<th>' + str(i) + '</th>'
html += '</tr>'
html += '</table>'
html += '</body>'
html += '</html>'
with open('combinations.html', 'w') as f:
f.write(html)
def key_by_space(ct_index, ch_index):
return key_by_guess(ct_index, ch_index)
def key_by_guess(ct_index, ch_index, guess=' '):
return strxor(MSGS_DECODED[ct_index][ch_index], guess)
def main():
output_combinations_table()
key = [
lambda : key_by_space(9, 0),
lambda : key_by_space(8, 1),
lambda : key_by_space(0, 2),
lambda : key_by_space(4, 3),
lambda : key_by_space(9, 4),
lambda : key_by_space(6, 5),
lambda : key_by_space(7, 6),
lambda : key_by_guess(4, 7, '\''), #???
lambda : key_by_space(2, 8),
lambda : key_by_space(6, 9),
lambda : key_by_space(10, 10),
lambda : key_by_space(1, 11),
lambda : key_by_space(9, 12),
lambda : key_by_space(6, 13),
lambda : key_by_space(4, 14),
lambda : key_by_space(8, 15),
lambda : key_by_space(8, 16),
lambda : key_by_space(4, 17),
lambda : key_by_space(10, 18),
lambda : key_by_space(6, 19),
lambda : key_by_space(7, 20),
lambda : key_by_space(4, 21),
lambda : key_by_space(6, 22),
lambda : key_by_space(4, 23),
lambda : key_by_space(0, 24),
lambda : key_by_guess(1, 25, 'y'),
lambda : key_by_space(7, 26),
lambda : key_by_space(10, 27),
lambda : key_by_space(3, 28),
lambda : key_by_space(9, 29),
lambda : key_by_space(7, 30),
lambda : key_by_space(1, 31),
lambda : key_by_space(0, 32),
lambda : key_by_space(10, 33),
lambda : key_by_space(8, 34),
lambda : key_by_space(10, 35),
lambda : key_by_space(9, 36),
lambda : key_by_space(5, 37),
lambda : key_by_space(7, 38),
lambda : key_by_space(1, 39),
lambda : key_by_space(0, 40),
lambda : key_by_space(8, 41),
lambda : key_by_space(5, 42),
lambda : key_by_guess(3, 43, 'n'),
lambda : key_by_space(4, 44),
lambda : key_by_guess(7, 45, 'y'),
lambda : key_by_space(7, 46),
lambda : key_by_guess(10, 47, 'e'),
lambda : key_by_guess(10, 48, 'r'),
lambda : key_by_space(7, 49),
lambda : key_by_guess(3, 50, 'i'),
lambda : key_by_guess(3, 51, 't'),
lambda : key_by_guess(3, 52, 'h'),
lambda : key_by_guess(3, 53, 'm'),
lambda : key_by_space(4, 54),
lambda : key_by_space(1, 55),
lambda : key_by_space(10, 56),
lambda : key_by_space(1, 57),
lambda : key_by_space(0, 58),
lambda : key_by_space(9, 59),
lambda : key_by_space(3, 60),
lambda : key_by_space(7, 61),
lambda : key_by_guess(0, 62, 'o'),
lambda : key_by_space(0, 63),
lambda : key_by_space(10, 64),
lambda : key_by_guess(6, 65, 't'),
lambda : key_by_space(5, 66),
lambda : key_by_guess(10, 67, 'y'),
lambda : key_by_space(10, 68),
lambda : key_by_space(7, 69),
lambda : key_by_space(1, 70),
lambda : key_by_space(3, 71),
lambda : key_by_space(2, 72),
lambda : key_by_space(1, 73),
lambda : key_by_space(0, 74),
lambda : key_by_guess(10, 75, 'h'),
lambda : key_by_guess(10, 76, 'a'),
lambda : key_by_guess(10, 77, 'n'),
lambda : key_by_space(10, 78),
lambda : key_by_guess(3, 79, 'e'),
lambda : key_by_guess(3, 80, 'x'),
lambda : key_by_guess(3, 81, 't'),
lambda : key_by_guess(10, 82, 'e'),
lambda : key_by_guess(6, 83, 'c'),
lambda : key_by_guess(6, 84, 'e'),
# lambda : key_by_guess(6, 68, 't'),
]
for i, s in enumerate(MSGS):
print '%2d: %s' % (i + 1, ''.join([strxor(k(), ch) for k, ch in itertools.izip(key, s.decode('hex'))]))
if __name__ == "__main__":
main() | 3.421875 | 3 |
moe/bandit/ucb/ucb_interface.py | dstoeckel/MOE | 966 | 2214 | # -*- coding: utf-8 -*-
"""Classes (Python) to compute the Bandit UCB (Upper Confidence Bound) arm allocation and choosing the arm to pull next.
See :mod:`moe.bandit.bandit_interface` for further details on bandit.
"""
import copy
from abc import abstractmethod
from moe.bandit.bandit_interface import BanditInterface
from moe.bandit.utils import get_winning_arm_names_from_payoff_arm_name_list, get_equal_arm_allocations
class UCBInterface(BanditInterface):
r"""Implementation of the constructor of UCB (Upper Confidence Bound) and method allocate_arms. The method get_ucb_payoff is implemented in subclass.
A class to encapsulate the computation of bandit UCB.
The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf
To inherit this class, a subclass needs to implement get_ucb_payoff
(see :func:`moe.bandit.ucb.ucb1.UCB1.get_ucb_payoff` for an example), everything else is already implemented.
See :mod:`moe.bandit.bandit_interface` docs for further details.
"""
def __init__(
self,
historical_info,
subtype=None,
):
"""Construct a UCB object.
:param historical_info: a dictionary of arms sampled
:type historical_info: dictionary of (str, SampleArm()) pairs (see :class:`moe.bandit.data_containers.SampleArm` for more details)
:param subtype: subtype of the UCB bandit algorithm (default: None)
:type subtype: str
"""
self._historical_info = copy.deepcopy(historical_info)
self._subtype = subtype
@staticmethod
def get_unsampled_arm_names(arms_sampled):
r"""Compute the set of unsampled arm names based on the given ``arms_sampled``..
Throws an exception when arms_sampled is empty.
:param arms_sampled: a dictionary of arm name to :class:`moe.bandit.data_containers.SampleArm`
:type arms_sampled: dictionary of (str, SampleArm()) pairs
:return: set of names of the unsampled arms
:rtype: frozenset(str)
:raise: ValueError when ``arms_sampled`` are empty.
"""
if not arms_sampled:
raise ValueError('arms_sampled is empty!')
unsampled_arm_name_list = [name for name, sampled_arm in arms_sampled.iteritems() if sampled_arm.total == 0]
return frozenset(unsampled_arm_name_list)
@abstractmethod
def get_ucb_payoff(self, sampled_arm, number_sampled):
r"""Compute the expected upper confidence bound payoff using the UCB subtype formula.
See definition in subclasses for details.
:param sampled_arm: a sampled arm
:type sampled_arm: :class:`moe.bandit.data_containers.SampleArm`
:param number_sampled: the overall number of pulls so far
:type number_sampled: int
:return: ucb payoff
:rtype: float64
:raise: ValueError when ``sampled_arm`` is empty.
"""
pass
def allocate_arms(self):
r"""Compute the allocation to each arm given ``historical_info``, running bandit ``subtype`` endpoint.
Computes the allocation to each arm based on the given subtype, and, historical info.
Works with k-armed bandits (k >= 1).
The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf
If there is at least one unsampled arm, this method will choose to pull the unsampled arm
(randomly choose an unsampled arm if there are multiple unsampled arms).
If all arms are pulled at least once, this method will pull the optimal arm
(best expected upper confidence bound payoff).
See :func:`moe.bandit.ucb.ucb_interface.UCBInterface.get_ucb_payoff` for details on how to compute the expected upper confidence bound payoff (expected UCB payoff)
In case of a tie, the method will split the allocation among the optimal arms.
For example, if we have three arms (arm1, arm2, and arm3) with expected UCB payoff 0.5, 0.5, and 0.1 respectively.
We split the allocation between the optimal arms arm1 and arm2.
``{arm1: 0.5, arm2: 0.5, arm3: 0.0}``
:return: the dictionary of (arm, allocation) key-value pairs
:rtype: a dictionary of (str, float64) pairs
:raise: ValueError when ``sample_arms`` are empty.
"""
arms_sampled = self._historical_info.arms_sampled
if not arms_sampled:
raise ValueError('sample_arms are empty!')
return get_equal_arm_allocations(arms_sampled, self.get_winning_arm_names(arms_sampled))
def get_winning_arm_names(self, arms_sampled):
r"""Compute the set of winning arm names based on the given ``arms_sampled``..
Throws an exception when arms_sampled is empty.
:param arms_sampled: a dictionary of arm name to :class:`moe.bandit.data_containers.SampleArm`
:type arms_sampled: dictionary of (str, SampleArm()) pairs
:return: set of names of the winning arms
:rtype: frozenset(str)
:raise: ValueError when ``arms_sampled`` are empty.
"""
if not arms_sampled:
raise ValueError('arms_sampled is empty!')
# If there exists an unsampled arm, return the names of the unsampled arms
unsampled_arm_names = self.get_unsampled_arm_names(arms_sampled)
if unsampled_arm_names:
return unsampled_arm_names
number_sampled = sum([sampled_arm.total for sampled_arm in arms_sampled.itervalues()])
ucb_payoff_arm_name_list = [(self.get_ucb_payoff(sampled_arm, number_sampled), arm_name) for arm_name, sampled_arm in arms_sampled.iteritems()]
return get_winning_arm_names_from_payoff_arm_name_list(ucb_payoff_arm_name_list)
| 3.515625 | 4 |
Hedge/Shell.py | RonaldoAPSD/Hedge | 2 | 2215 | <reponame>RonaldoAPSD/Hedge
import Hedge
while True:
text = input('Hedge > ')
if text.strip() == "":
continue
result, error = Hedge.run('<stdin>', text)
if (error):
print(error.asString())
elif result:
if len(result.elements) == 1:
print(repr(result.elements[0]))
else:
print(repr(result)) | 3.125 | 3 |
yt/frontends/enzo/io.py | Xarthisius/yt | 1 | 2216 | import numpy as np
from yt.geometry.selection_routines import GridSelector
from yt.utilities.io_handler import BaseIOHandler
from yt.utilities.logger import ytLogger as mylog
from yt.utilities.on_demand_imports import _h5py as h5py
_convert_mass = ("particle_mass", "mass")
_particle_position_names = {}
class IOHandlerPackedHDF5(BaseIOHandler):
_dataset_type = "enzo_packed_3d"
_base = slice(None)
_field_dtype = "float64"
def _read_field_names(self, grid):
if grid.filename is None:
return []
f = h5py.File(grid.filename, mode="r")
try:
group = f["/Grid%08i" % grid.id]
except KeyError:
group = f
fields = []
dtypes = set()
add_io = "io" in grid.ds.particle_types
add_dm = "DarkMatter" in grid.ds.particle_types
for name, v in group.items():
# NOTE: This won't work with 1D datasets or references.
# For all versions of Enzo I know about, we can assume all floats
# are of the same size. So, let's grab one.
if not hasattr(v, "shape") or v.dtype == "O":
continue
elif len(v.dims) == 1:
if grid.ds.dimensionality == 1:
fields.append(("enzo", str(name)))
elif add_io:
fields.append(("io", str(name)))
elif add_dm:
fields.append(("DarkMatter", str(name)))
else:
fields.append(("enzo", str(name)))
dtypes.add(v.dtype)
if len(dtypes) == 1:
# Now, if everything we saw was the same dtype, we can go ahead and
# set it here. We do this because it is a HUGE savings for 32 bit
# floats, since our numpy copying/casting is way faster than
# h5py's, for some reason I don't understand. This does *not* need
# to be correct -- it will get fixed later -- it just needs to be
# okay for now.
self._field_dtype = list(dtypes)[0]
f.close()
return fields
@property
def _read_exception(self):
return (KeyError,)
def _read_particle_coords(self, chunks, ptf):
yield from self._read_particle_fields(chunks, ptf, None)
def _read_particle_fields(self, chunks, ptf, selector):
chunks = list(chunks)
for chunk in chunks: # These should be organized by grid filename
f = None
for g in chunk.objs:
if g.filename is None:
continue
if f is None:
# print("Opening (read) %s" % g.filename)
f = h5py.File(g.filename, mode="r")
nap = sum(g.NumberOfActiveParticles.values())
if g.NumberOfParticles == 0 and nap == 0:
continue
ds = f.get("/Grid%08i" % g.id)
for ptype, field_list in sorted(ptf.items()):
if ptype == "io":
if g.NumberOfParticles == 0:
continue
pds = ds
elif ptype == "DarkMatter":
if g.NumberOfActiveParticles[ptype] == 0:
continue
pds = ds
elif not g.NumberOfActiveParticles[ptype]:
continue
else:
for pname in ["Active Particles", "Particles"]:
pds = ds.get(f"{pname}/{ptype}")
if pds is not None:
break
else:
raise RuntimeError(
"Could not find active particle group in data."
)
pn = _particle_position_names.get(ptype, r"particle_position_%s")
x, y, z = (
np.asarray(pds.get(pn % ax)[()], dtype="=f8") for ax in "xyz"
)
if selector is None:
# This only ever happens if the call is made from
# _read_particle_coords.
yield ptype, (x, y, z)
continue
mask = selector.select_points(x, y, z, 0.0)
if mask is None:
continue
for field in field_list:
data = np.asarray(pds.get(field)[()], "=f8")
if field in _convert_mass:
data *= g.dds.prod(dtype="f8")
yield (ptype, field), data[mask]
if f:
f.close()
def io_iter(self, chunks, fields):
h5_dtype = self._field_dtype
for chunk in chunks:
fid = None
filename = -1
for obj in chunk.objs:
if obj.filename is None:
continue
if obj.filename != filename:
# Note one really important thing here: even if we do
# implement LRU caching in the _read_obj_field function,
# we'll still be doing file opening and whatnot. This is a
# problem, but one we can return to.
if fid is not None:
fid.close()
fid = h5py.h5f.open(
obj.filename.encode("latin-1"), h5py.h5f.ACC_RDONLY
)
filename = obj.filename
for field in fields:
nodal_flag = self.ds.field_info[field].nodal_flag
dims = obj.ActiveDimensions[::-1] + nodal_flag[::-1]
data = np.empty(dims, dtype=h5_dtype)
yield field, obj, self._read_obj_field(obj, field, (fid, data))
if fid is not None:
fid.close()
def _read_obj_field(self, obj, field, fid_data):
if fid_data is None:
fid_data = (None, None)
fid, data = fid_data
if fid is None:
close = True
fid = h5py.h5f.open(obj.filename.encode("latin-1"), h5py.h5f.ACC_RDONLY)
else:
close = False
if data is None:
data = np.empty(obj.ActiveDimensions[::-1], dtype=self._field_dtype)
ftype, fname = field
try:
node = "/Grid%08i/%s" % (obj.id, fname)
dg = h5py.h5d.open(fid, node.encode("latin-1"))
except KeyError:
if fname == "Dark_Matter_Density":
data[:] = 0
return data.T
raise
dg.read(h5py.h5s.ALL, h5py.h5s.ALL, data)
# I don't know why, but on some installations of h5py this works, but
# on others, nope. Doesn't seem to be a version thing.
# dg.close()
if close:
fid.close()
return data.T
class IOHandlerPackedHDF5GhostZones(IOHandlerPackedHDF5):
_dataset_type = "enzo_packed_3d_gz"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
NGZ = self.ds.parameters.get("NumberOfGhostZones", 3)
self._base = (slice(NGZ, -NGZ), slice(NGZ, -NGZ), slice(NGZ, -NGZ))
def _read_obj_field(self, *args, **kwargs):
return super()._read_obj_field(*args, **kwargs)[self._base]
class IOHandlerInMemory(BaseIOHandler):
_dataset_type = "enzo_inline"
def __init__(self, ds, ghost_zones=3):
self.ds = ds
import enzo
self.enzo = enzo
self.grids_in_memory = enzo.grid_data
self.old_grids_in_memory = enzo.old_grid_data
self.my_slice = (
slice(ghost_zones, -ghost_zones),
slice(ghost_zones, -ghost_zones),
slice(ghost_zones, -ghost_zones),
)
BaseIOHandler.__init__(self, ds)
def _read_field_names(self, grid):
fields = []
add_io = "io" in grid.ds.particle_types
for name, v in self.grids_in_memory[grid.id].items():
# NOTE: This won't work with 1D datasets or references.
if not hasattr(v, "shape") or v.dtype == "O":
continue
elif v.ndim == 1:
if grid.ds.dimensionality == 1:
fields.append(("enzo", str(name)))
elif add_io:
fields.append(("io", str(name)))
else:
fields.append(("enzo", str(name)))
return fields
def _read_fluid_selection(self, chunks, selector, fields, size):
rv = {}
# Now we have to do something unpleasant
chunks = list(chunks)
if isinstance(selector, GridSelector):
if not (len(chunks) == len(chunks[0].objs) == 1):
raise RuntimeError
g = chunks[0].objs[0]
for ftype, fname in fields:
rv[(ftype, fname)] = self.grids_in_memory[g.id][fname].swapaxes(0, 2)
return rv
if size is None:
size = sum(g.count(selector) for chunk in chunks for g in chunk.objs)
for field in fields:
ftype, fname = field
fsize = size
rv[field] = np.empty(fsize, dtype="float64")
ng = sum(len(c.objs) for c in chunks)
mylog.debug(
"Reading %s cells of %s fields in %s grids",
size,
[f2 for f1, f2 in fields],
ng,
)
ind = 0
for chunk in chunks:
for g in chunk.objs:
# We want a *hard error* here.
# if g.id not in self.grids_in_memory: continue
for field in fields:
ftype, fname = field
data_view = self.grids_in_memory[g.id][fname][
self.my_slice
].swapaxes(0, 2)
nd = g.select(selector, data_view, rv[field], ind)
ind += nd
assert ind == fsize
return rv
def _read_particle_coords(self, chunks, ptf):
chunks = list(chunks)
for chunk in chunks: # These should be organized by grid filename
for g in chunk.objs:
if g.id not in self.grids_in_memory:
continue
nap = sum(g.NumberOfActiveParticles.values())
if g.NumberOfParticles == 0 and nap == 0:
continue
for ptype in sorted(ptf):
x, y, z = (
self.grids_in_memory[g.id]["particle_position_x"],
self.grids_in_memory[g.id]["particle_position_y"],
self.grids_in_memory[g.id]["particle_position_z"],
)
yield ptype, (x, y, z)
def _read_particle_fields(self, chunks, ptf, selector):
chunks = list(chunks)
for chunk in chunks: # These should be organized by grid filename
for g in chunk.objs:
if g.id not in self.grids_in_memory:
continue
nap = sum(g.NumberOfActiveParticles.values())
if g.NumberOfParticles == 0 and nap == 0:
continue
for ptype, field_list in sorted(ptf.items()):
x, y, z = (
self.grids_in_memory[g.id]["particle_position_x"],
self.grids_in_memory[g.id]["particle_position_y"],
self.grids_in_memory[g.id]["particle_position_z"],
)
mask = selector.select_points(x, y, z, 0.0)
if mask is None:
continue
for field in field_list:
data = self.grids_in_memory[g.id][field]
if field in _convert_mass:
data = data * g.dds.prod(dtype="f8")
yield (ptype, field), data[mask]
class IOHandlerPacked2D(IOHandlerPackedHDF5):
_dataset_type = "enzo_packed_2d"
_particle_reader = False
def _read_data_set(self, grid, field):
f = h5py.File(grid.filename, mode="r")
ds = f["/Grid%08i/%s" % (grid.id, field)][:]
f.close()
return ds.transpose()[:, :, None]
def _read_fluid_selection(self, chunks, selector, fields, size):
rv = {}
# Now we have to do something unpleasant
chunks = list(chunks)
if isinstance(selector, GridSelector):
if not (len(chunks) == len(chunks[0].objs) == 1):
raise RuntimeError
g = chunks[0].objs[0]
f = h5py.File(g.filename, mode="r")
gds = f.get("/Grid%08i" % g.id)
for ftype, fname in fields:
rv[(ftype, fname)] = np.atleast_3d(gds.get(fname)[()].transpose())
f.close()
return rv
if size is None:
size = sum(g.count(selector) for chunk in chunks for g in chunk.objs)
for field in fields:
ftype, fname = field
fsize = size
rv[field] = np.empty(fsize, dtype="float64")
ng = sum(len(c.objs) for c in chunks)
mylog.debug(
"Reading %s cells of %s fields in %s grids",
size,
[f2 for f1, f2 in fields],
ng,
)
ind = 0
for chunk in chunks:
f = None
for g in chunk.objs:
if f is None:
# print("Opening (count) %s" % g.filename)
f = h5py.File(g.filename, mode="r")
gds = f.get("/Grid%08i" % g.id)
if gds is None:
gds = f
for field in fields:
ftype, fname = field
ds = np.atleast_3d(gds.get(fname)[()].transpose())
nd = g.select(selector, ds, rv[field], ind) # caches
ind += nd
f.close()
return rv
class IOHandlerPacked1D(IOHandlerPackedHDF5):
_dataset_type = "enzo_packed_1d"
_particle_reader = False
def _read_data_set(self, grid, field):
f = h5py.File(grid.filename, mode="r")
ds = f["/Grid%08i/%s" % (grid.id, field)][:]
f.close()
return ds.transpose()[:, None, None]
| 2.125 | 2 |
cidr_enum.py | arisada/cidr_enum | 0 | 2217 | <gh_stars>0
#!/usr/bin/env python3
"""
cidr_enum.py is a very simple tool to help enumerate IP ranges when being used with other tools
"""
import argparse
import netaddr
def enum_ranges(ranges, do_sort):
cidrs=[]
for r in ranges:
try:
cidrs.append(netaddr.IPNetwork(r))
except Exception as e:
print("Error:", e)
return
if(do_sort):
cidrs = sorted(cidrs)
#print(cidrs)
for cidr in cidrs:
for ip in cidr:
print(ip)
def main():
parser = argparse.ArgumentParser(description='Enumarate CIDR ranges')
parser.add_argument('ranges', metavar='range', type=str, nargs='*',
help='List of CIDR ranges to enumerate')
parser.add_argument('-f', '--files', metavar='file', type=str, nargs='*',
help='List of files to retrieve CIDR ranges to enumerate')
parser.add_argument('-s', '--sort', action='store_true', help='Sort CIDR ranges')
args = parser.parse_args()
if args.files:
files = list(args.files)
else:
files = []
ranges = list(args.ranges)
if not (files or ranges):
print ("Please give a list or ranges or input files")
parser.print_help()
return
for f in files:
with open(f, "r") as fd:
for l in fd.readlines():
ranges.append(l.strip())
enum_ranges(ranges, do_sort=args.sort)
if __name__ == '__main__':
main()
| 3.390625 | 3 |
configs/k400-fixmatch-tg-alignment-videos-ptv-simclr/8gpu/r3d_r18_8x8x1_45e_k400_rgb_offlinetg_1percent_align0123_1clip_no_contrast_precisebn_ptv.py | lambert-x/video_semisup | 0 | 2218 | # model settings
model = dict(
type='Semi_AppSup_TempSup_SimCLR_Crossclip_PTV_Recognizer3D',
backbone=dict(
type='ResNet3d',
depth=18,
pretrained=None,
pretrained2d=False,
norm_eval=False,
conv_cfg=dict(type='Conv3d'),
norm_cfg=dict(type='SyncBN', requires_grad=True, eps=1e-3),
act_cfg=dict(type='ReLU'),
conv1_kernel=(3, 7, 7),
conv1_stride_t=1,
pool1_stride_t=1,
inflate=(1, 1, 1, 1),
spatial_strides=(1, 2, 2, 2),
temporal_strides=(1, 2, 2, 2),
zero_init_residual=False),
cls_head=dict(
type='I3DHead',
num_classes=400,
in_channels=512,
spatial_type='avg',
dropout_ratio=0.5,
init_std=0.01),
cls_head_temp=None,
temp_backbone='same',
temp_sup_head='same',
train_cfg=dict(
warmup_epoch=10,
fixmatch_threshold=0.3,
temp_align_indices=(0, 1, 2, 3),
align_loss_func='Cosine',
pseudo_label_metric='avg',
crossclip_contrast_loss=[],
crossclip_contrast_range=[],
),
test_cfg=dict(average_clips='score'))
# dataset settings
dataset_type = 'VideoDataset'
dataset_type_labeled = 'VideoDataset_Contrastive'
dataset_type_unlabeled = 'UnlabeledVideoDataset_MultiView_Contrastive'
# dataset_type_appearance = 'RawframeDataset_withAPP'
data_root = 'data/kinetics400/videos_train'
data_root_val = 'data/kinetics400/videos_val'
labeled_percentage = 1
ann_file_train_labeled = f'data/kinetics400/videossl_splits/kinetics400_train_{labeled_percentage}_percent_labeled_videos.txt'
ann_file_train_unlabeled = 'data/kinetics400/kinetics400_train_list_videos.txt'
ann_file_val = 'data/kinetics400/kinetics400_val_list_videos.txt'
ann_file_test = 'data/kinetics400/kinetics400_val_list_videos.txt'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False)
train_pipeline = [
dict(type='DecordInit'),
dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1,
total_frames_offset=-1),
dict(type='DecordDecode_Custom',
extra_modalities=['tempgrad']),
dict(type='Resize', scale=(-1, 256), lazy=True),
dict(type='RandomResizedCrop', lazy=True),
dict(type='Resize', scale=(224, 224), keep_ratio=False, lazy=True),
dict(type='Flip', flip_ratio=0.5, lazy=True),
dict(type='Fuse_WithDiff'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='FormatShape_Diff', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label', 'imgs_diff'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff'])
]
# Get the frame and resize, shared by both weak and strong
train_pipeline_weak = [
dict(type='DecordInit'),
dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1,
total_frames_offset=-1),
dict(type='DecordDecode_Custom',
extra_modalities=['tempgrad']),
dict(type='Resize', scale=(-1, 256), lazy=True),
dict(type='RandomResizedCrop', lazy=True),
dict(type='Resize', scale=(224, 224), keep_ratio=False, lazy=True),
dict(type='Flip', flip_ratio=0.5, lazy=True),
dict(type='Fuse_WithDiff'),
]
# Only used for strong augmentation
train_pipeline_strong = [
dict(type='Imgaug', transforms='default'),
dict(type='Imgaug_Custom', transforms='default', modality='imgs_diff')
]
# Formating the input tensors, shared by both weak and strong
train_pipeline_format = [
dict(type='Normalize', **img_norm_cfg),
dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='FormatShape_Diff', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label', 'imgs_diff'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff'])
]
val_pipeline = [
dict(type='DecordInit'),
dict(
type='SampleFrames',
clip_len=8,
frame_interval=8,
num_clips=1,
test_mode=True),
dict(type='DecordDecode'),
dict(type='Resize', scale=(-1, 256), lazy=True),
dict(type='CenterCrop', crop_size=224, lazy=True),
dict(type='Flip', flip_ratio=0, lazy=True),
dict(type='Fuse'),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
test_pipeline = [
dict(type='DecordInit'),
dict(
type='SampleFrames',
clip_len=8,
frame_interval=8,
num_clips=10,
test_mode=True),
dict(type='DecordDecode'),
dict(type='Resize', scale=(-1, 256)),
dict(type='ThreeCrop', crop_size=256),
dict(type='Flip', flip_ratio=0),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
data = dict(
videos_per_gpu=8, # NOTE: Need to reduce batch size. 16 -> 5
workers_per_gpu=4, # Default: 4
train_dataloader=dict(drop_last=True, pin_memory=True),
train_labeled=dict(
type=dataset_type_labeled,
ann_file=ann_file_train_labeled,
data_prefix=data_root,
pipeline=train_pipeline,
contrast_clip_num=1
),
train_unlabeled=dict(
type=dataset_type_unlabeled,
ann_file=ann_file_train_unlabeled,
data_prefix=data_root,
pipeline_weak=train_pipeline_weak,
pipeline_strong=train_pipeline_strong,
pipeline_format=train_pipeline_format,
contrast_clip_num=1
),
val=dict(
type=dataset_type,
ann_file=ann_file_val,
data_prefix=data_root_val,
pipeline=val_pipeline,
test_mode=True),
test=dict(
type=dataset_type,
ann_file=ann_file_val,
data_prefix=data_root_val,
pipeline=test_pipeline,
test_mode=True),
precise_bn=dict(
type=dataset_type,
ann_file=ann_file_train_unlabeled,
data_prefix=data_root,
pipeline=val_pipeline),
videos_per_gpu_precise_bn=5
)
# optimizer
optimizer = dict(
type='SGD', lr=0.2, momentum=0.9,
weight_decay=0.0001) # this lr 0.2 is used for 8 gpus
optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2))
# learning policy
lr_config = dict(policy='CosineAnnealing',
min_lr=0,
warmup='linear',
warmup_ratio=0.1,
warmup_by_epoch=True,
warmup_iters=10)
total_epochs = 45 # Might need to increase this number for different splits. Default: 180
checkpoint_config = dict(interval=5, max_keep_ckpts=3)
evaluation = dict(
interval=5, metrics=['top_k_accuracy', 'mean_class_accuracy'], topk=(1, 5)) # Default: 5
log_config = dict(
interval=20, # Default: 20
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook'),
])
precise_bn = dict(num_iters=200, interval=5,
bn_range=['backbone', 'cls_head'])
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = None
load_from = None
resume_from = None
workflow = [('train', 1)]
find_unused_parameters = False
| 1.71875 | 2 |
experiments/rpi/gertboard/dtoa.py | willingc/pingo | 0 | 2219 | <gh_stars>0
#!/usr/bin/python2.7
# Python 2.7 version by <NAME> of http://RasPi.TV
# functionally equivalent to the Gertboard dtoa test by <NAME> & <NAME>
# Use at your own risk - I'm pretty sure the code is harmless, but check it yourself.
# This will not work unless you have installed py-spidev as in the README.txt file
# spi must also be enabled on your system
import spidev
import sys
from time import sleep
board_type = sys.argv[-1]
# reload spi drivers to prevent spi failures
import subprocess
unload_spi = subprocess.Popen('sudo rmmod spi_bcm2708', shell=True, stdout=subprocess.PIPE)
start_spi = subprocess.Popen('sudo modprobe spi_bcm2708', shell=True, stdout=subprocess.PIPE)
sleep(3)
def which_channel():
channel = raw_input("Which channel do you want to test? Type 0 or 1.\n") # User inputs channel number
while not channel.isdigit(): # Check valid user input
channel = raw_input("Try again - just numbers 0 or 1 please!\n") # Make them do it again if wrong
return channel
spi = spidev.SpiDev()
spi.open(0,1) # The Gertboard DAC is on SPI channel 1 (CE1 - aka GPIO7)
channel = 3 # set initial value to force user selection
common = [0,0,0,160,240] # 2nd byte common to both channels
voltages = [0.0,0.5,1.02,1.36,2.04] # voltages for display
while not (channel == 1 or channel == 0): # channel is set by user input
channel = int(which_channel()) # continue asking until answer 0 or 1 given
if channel == 1: # once proper answer given, carry on
num_list = [176,180,184,186,191] # set correct channel-dependent list for byte 1
else:
num_list = [48,52,56,58,63]
print "These are the connections for the digital to analogue test:"
if board_type == "m":
print "jumper connecting GPIO 7 to CSB"
print "Multimeter connections (set your meter to read V DC):"
print " connect black probe to GND"
print " connect red probe to DA%d on D/A header" % channel
else:
print "jumper connecting GP11 to SCLK"
print "jumper connecting GP10 to MOSI"
print "jumper connecting GP9 to MISO"
print "jumper connecting GP7 to CSnB"
print "Multimeter connections (set your meter to read V DC):"
print " connect black probe to GND"
print " connect red probe to DA%d on J29" % channel
raw_input("When ready hit enter.\n")
for i in range(5):
r = spi.xfer2([num_list[i],common[i]]) #write the two bytes to the DAC
print "Your meter should read about %.2fV" % voltages[i]
raw_input("When ready hit enter.\n")
r = spi.xfer2([16,0]) # switch off channel A = 00010000 00000000 [16,0]
r = spi.xfer2([144,0]) # switch off channel B = 10010000 00000000 [144,0]
# The DAC is controlled by writing 2 bytes (16 bits) to it.
# So we need to write a 16 bit word to DAC
# bit 15 = channel, bit 14 = ignored, bit 13 =gain, bit 12 = shutdown, bits 11-4 data, bits 3-0 ignored
# You feed spidev a decimal number and it converts it to 8 bit binary
# each argument is a byte (8 bits), so we need two arguments, which together make 16 bits.
# that's what spidev sends to the DAC. If you need to delve further, have a look at the datasheet. :)
| 2.984375 | 3 |
modules/statusbar.py | themilkman/GitGutter | 0 | 2220 | <gh_stars>0
# -*- coding: utf-8 -*-
import sublime
from . import blame
from . import templates
class SimpleStatusBarTemplate(object):
"""A simple template class with the same interface as jinja2's one."""
# a list of variables used by this template
variables = frozenset([
'repo', 'branch', 'compare', 'inserted', 'deleted', 'modified',
'line_author', 'line_author_age'
])
@staticmethod
def render(repo=None, branch=None, compare=None, inserted=0, deleted=0,
modified=0, line_author=None, line_author_age=None, **kwargs):
"""Format the status bar text using a static set of rules.
Arguments:
repo (string): The repository name
branch (string): The branch name.
compare (string): The compared branch/tag/commit
inserted (int): The amount of inserted lines
deleted (int): The amount of deleted lines
modified (int): The amount of modified lines
line_author (string): The author of the active line
line_author_age (string): The age of the active line's change
Returns:
string: The formatted message to display in the status bar.
"""
if not repo or not branch:
return ''
parts = ['{repo}/{branch}']
# Compare against
if compare not in ('HEAD', branch, None):
parts.append('Comparing against {compare}')
# File statistics
if inserted:
parts.append('{inserted}+')
if deleted:
parts.append('{deleted}-')
if modified:
parts.append(u'{modified}≠')
# blame message
if line_author and line_author_age:
parts.append(u'⟢ {line_author} ({line_author_age})')
# join template and fill with locals
return ', '.join(parts).format(**locals())
class GitGutterStatusBar(object):
"""The class manages status bar text rendering.
It stores all information, which might get displayed in the status bar
and provides functions to partially update them.
"""
def __init__(self, view, settings):
"""Initialize object."""
# the sublime.View the status bar is attached to
self.view = view
# the settings.ViewSettings object which stores GitGutter' settings
self.settings = settings
# initialize the jinja2 template
self.template = None
# the variables to use to render the status bar
self.vars = {
# sublime text git integration enabled
'st_git_status': view.settings().get('show_git_status', False),
# the repository name
'repo': None,
# the active branch name
'branch': None,
# the branch we compare against
'compare': None,
# the upstream branch name
'remote': None,
# the commits the local is ahead of upstream
'ahead': 0,
# the commits the local is behind of upstream
'behind': 0,
# repository statistics
'added_files': 0,
'deleted_files': 0,
'modified_files': 0,
'staged_files': 0,
# file statistics
'state': None,
'deleted': 0,
'inserted': 0,
'modified': 0,
}
# declare all blame variables
for var in blame.BLAME_VARIABLES:
self.vars[var] = None
def is_enabled(self):
"""Return whether status bar text is enabled in settings or not."""
enabled = self.settings.get('show_status_bar_text', False)
if self.template and not enabled:
self.template = None
self.vars['repo'] = None
self.erase()
return enabled
def has(self, variables):
"""Check if a set of variables is used by the user defined template.
Arguments:
variables (iter):
An iterateable object with all the variables to check for
existence within the active template.
Returns:
bool:
True - if at least one variable is used by the template.
False - if no variable is used by the template.
"""
try:
return any(var in self.template.variables for var in variables)
except:
return False
def erase(self):
"""Erase status bar text."""
self.view.erase_status('00_git_gutter')
def update(self, **kwargs):
"""Update a set of variables and redraw the status bar text.
Arguments:
kwargs (dict):
The dictionary of possibly changed variables to update the
status bar text with.
Raises:
KeyError, if `kwargs` contains unknown variables.
"""
want_update = False
for key, value in kwargs.items():
if self.vars[key] != value:
self.vars[key] = value
want_update = True
if want_update:
if not self.template:
self.template = templates.create(
self.settings, 'status_bar_text', SimpleStatusBarTemplate)
self.view.set_status(
'00_git_gutter', self.template.render(**self.vars))
| 2.796875 | 3 |
polls/tests.py | bunya017/Django-Polls-App | 0 | 2221 | <reponame>bunya017/Django-Polls-App<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
class RandomTestCase(TestCase):
def test_one_plus_one1(self):
self.assertEqual(1+1, 2)
| 1.78125 | 2 |
test.py | LeonHodgesAustin/video_stream_processor | 0 | 2222 | <gh_stars>0
# import logging
# import hercules.lib.util.hercules_logging as l
# from hercules.lib.util import sso as sso
import opencv2 as cv2
import urllib
import numpy as np
# log = l.setup_logging(__name__)
def main(args=None):
# username, passowrd = sso.get_login_credentials("WATCHER")
# Open a sample video available in sample-videos
vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4')
#if not vcap.isOpened():
# print "File Cannot be Opened"
while(True):
# Capture frame-by-frame
ret, frame = vcap.read()
#print cap.isOpened(), ret
if frame is not None:
# Display the resulting frame
cv2.imshow('frame',frame)
# Press q to close the video windows before it ends if you want
if cv2.waitKey(22) & 0xFF == ord('q'):
break
else:
print("Frame is None")
break
# When everything done, release the capture
vcap.release()
cv2.destroyAllWindows()
print("Video stop")
if __name__ == "__main__":
main()
| 2.734375 | 3 |
ribbon/exceptions.py | cloutiertyler/RibbonGraph | 2 | 2223 | <filename>ribbon/exceptions.py
from rest_framework.exceptions import APIException
from rest_framework import status
class GraphAPIError(APIException):
"""Base class for exceptions in this module."""
pass
class NodeNotFoundError(GraphAPIError):
status_code = status.HTTP_404_NOT_FOUND
def __init__(self, id):
self.id = id
super(NodeNotFoundError, self).__init__("Node with id '{}' does not exist.".format(id))
class NodeTypeNotFoundError(GraphAPIError):
status_code = status.HTTP_404_NOT_FOUND
def __init__(self, node_type):
self.node_type = node_type
super(NodeTypeNotFoundError, self).__init__("Node type '{}' does not exist.".format(node_type))
class MissingNodeTypeError(GraphAPIError):
""" Creating a node requires a type. """
status_code = status.HTTP_400_BAD_REQUEST
class MalformedUpdateDictionaryError(GraphAPIError):
status_code = status.HTTP_400_BAD_REQUEST
class InvalidPropertyError(GraphAPIError):
status_code = status.HTTP_400_BAD_REQUEST
class InvalidValueError(GraphAPIError):
status_code = status.HTTP_400_BAD_REQUEST
class PermissionDenied(GraphAPIError):
status_code = status.HTTP_403_FORBIDDEN
default_detail = 'Insufficient permissions for the request.'
| 2.75 | 3 |
kobe-trading-bot/app.py | LeonardoM011/kobe-trading-bot | 0 | 2224 | #!/usr/bin/env python3
# Crypto trading bot using binance api
# Author: LeonardoM011<<EMAIL>>
# Created on 2021-02-05 21:56
# Set constants here:
DELTA_TIME = 300 # How long can we check for setting up new trade (in seconds)
# ----------------------
# Imports:
import os
import sys
import time as t
import datetime
# Adding python-binance to path and importing python-binance
sys.path.insert(1, "../deps/binance")
from binance.client import Client
from fun import *
import candles as can
# Globals:
client = None
# Main program loop
def start():
hour_repeated = -1
try:
while True:
time = datetime.datetime.now()
hour = time.hour
minute = time.minute
open_trade = client.futures_get_open_orders()
if minute < 10:
if not open_trade and hour_repeated != hour:
candles = client.futures_klines(symbol="BTCUSDT", interval=Client.KLINE_INTERVAL_1HOUR, contractType="PERPETUAL")
info = can.get_candle_info(candles[:-1])
candle_side = can.get_side(info)
if candle_side:
output.print_info('Initiating trade...')
#current_price = client.futures_mark_price(symbol="BTCUSDT", contractType="PERPETUAL")['markPrice']
close_price = candles
client.futures_create_order(symbol="BTCUSDT", side=candle_side, type=Client.ORDER_TYPE_MARKET, quantity=0.001)
client.futures_create_order(symbol="BTCUSDT", side=can.flip_side(candle_side), type=Client.ORDER_TYPE_STOP_LOSS_LIMIT, quantity=0.001, price=57975.0, stopPrice=57976.0, workingType="MARK_PRICE")
hour_repeated = hour
t.sleep(300)
except KeyboardInterrupt:
print('Program canceled...')
def connect():
while True:
api_key = get_api_key("BINANCE_API_KEY")
api_secret = get_api_key("BINANCE_API_SECRET_KEY")
output.print_info('Connecting to binance...')
global client
client = Client(api_key, api_secret)
if check_connectivity(client):
output.print_ok('Successfully connected to binance.')
if check_account_status(client):
output.print_ok('Successfully connected using api keys.')
return
output.print_failed('Cannot connect to binance with api keys.')
def main():
output.print_ok('Starting kobe trading bot...')
connect()
start()
#try:
# client.get_all_orders()
#except BinanceAPIException as e:
# print e.status_code
# print e.message
# datetime.datetime.now().year
#btcusdt_price = requests.get("https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT")
#if (btcusdt_price.status_code != 200):
# print("Error connecting to api server to get price")
# return
#print("Successfully connected and got price")
#while(True):
# btcusdt_price = requests.get("https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT")
# print("BTC/USDT: {}".format(btcusdt_price.json()['price']))
# time.sleep(1.0)
#btcusdtindex = find_index_of('symbol', 'BTCUSDT', client.get_all_tickers())
#while (True):
# print(client.get_all_tickers()[btcusdtindex])
# time.sleep(5.0)
# client.futures_create_order(symbol="BTCUSDT", side="SELL", type="STOP", quantity=0.001, price=57975.0, stopPrice=57976.0, workingType="MARK_PRICE")
# client.futures_create_order(symbol="BTCUSDT", side="BUY", type="MARKET", quantity=0.001)
if __name__ == "__main__":
main() | 3 | 3 |
imported_files/plotting_edh01.py | SoumyaShreeram/Locating_AGN_in_DM_halos | 0 | 2225 | <filename>imported_files/plotting_edh01.py
# -*- coding: utf-8 -*-
"""Plotting.py for notebook 01_Exploring_DM_Halos
This python file contains all the functions used for plotting graphs and maps in the 1st notebook (.ipynb) of the repository: 01. Exploring parameters in DM halos and sub-halos
Script written by: <NAME>
Project supervised by <NAME>
Date created: 23rd February 2021
Last updated on 30th March 2021
"""
# astropy modules
import astropy.units as u
import astropy.io.fits as fits
from astropy.table import Table, Column
from astropy.coordinates import SkyCoord
from astropy.cosmology import FlatLambdaCDM, z_at_value
import numpy as np
# scipy modules
from scipy.spatial import KDTree
from scipy.interpolate import interp1d
import os
import importlib
# plotting imports
import matplotlib
from mpl_toolkits import axes_grid1
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib import cm
from matplotlib.collections import PatchCollection
from matplotlib.patches import Rectangle
import Exploring_DM_Haloes as edh
def setLabel(ax, xlabel, ylabel, title, xlim, ylim, legend=True):
"""
Function defining plot properties
@param ax :: axes to be held
@param xlabel, ylabel :: labels of the x-y axis
@param title :: title of the plot
@param xlim, ylim :: x-y limits for the axis
"""
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if xlim != 'default':
ax.set_xlim(xlim)
if ylim != 'default':
ax.set_ylim(ylim)
if legend:
l = ax.legend(loc='best', fontsize=14)
for legend_handle in l.legendHandles:
legend_handle._legmarker.set_markersize(12)
ax.grid(False)
ax.set_title(title, fontsize=18)
return
def plotAgnClusterDistribution(pos_z_clu, pos_z_AGN, pos_z_halo, cluster_params):
"""
Function to plot the AGN cluster distribution
@pos_z_clu :: postion and redshifts of all the selected 'clusters'
@pos_z_AGN :: postion and redshifts of all the selected AGNs
@pos_z_gal :: postion and redshifts of all the selected galaxies
"""
halo_m_500c = cluster_params[0]
fig, ax = plt.subplots(1,1,figsize=(9,8))
# plotting halos
halos = ax.plot(pos_z_halo[0], pos_z_halo[1], '.', color='#fcd16d', markersize=0.2, label=r'All DM Halos', alpha=0.2)
# plotting clusters
cluster = ax.plot(pos_z_clu[0], pos_z_clu[1], 'o', color= '#03a351', markersize=3, label=r'Clusters $M_{500c}> 10^{%.1f} M_\odot$ '%(np.log10(halo_m_500c)))
# plotting AGNs
agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='k', markersize=3.5, label=r'AGN', alpha=0.7)
# labeling axes and defining limits
xlim = [np.min(pos_z_halo[0]), np.max(pos_z_halo[0])]
ylim = [np.min(pos_z_halo[1]), np.max(pos_z_halo[1])]
setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '', xlim, ylim, legend=True)
print('Redshift z<%.2f'%(np.max(pos_z_clu[2])))
return
def plotHostSubHalos(pos_z_cen_halo, pos_z_sat_halo, pos_z_AGN):
"""
Function to plot the host and satellite halo distribution
@hd_halo :: table with all relevant info on halos, clusters, and galaxies within them
--> divided into 3 because each hd_halo holds info on 1000 halos alone
@pos_z_AGN :: postion and redshifts of all the selected AGNs
"""
ra_cen, dec_cen = pos_z_cen_halo[0], pos_z_cen_halo[1]
ra_sat, dec_sat = pos_z_sat_halo[0], pos_z_sat_halo[1]
fig, ax = plt.subplots(1,1,figsize=(9,8))
# plotting host halos
host_halos = ax.plot(ra_cen, dec_cen, '.', color= 'k', markersize=0.06, label=r'Host-halos $P_{id}=-1$', alpha=0.4)
# plotting sat halos
sat_halos = ax.plot(ra_sat, dec_sat, 'o', color='#07d9f5', markersize=0.07, label=r'Satellite halos $P_{id} \neq -1$', alpha=0.7)
# plotting AGNs
agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='#fff717', markersize=6.5, label=r'AGN', markeredgecolor='w', markeredgewidth=0.4)
# labeling axes and defining limits
xlim = [np.min(pos_z_AGN[0]), np.max(pos_z_AGN[0])]
ylim = [np.min(pos_z_AGN[1]), np.max(pos_z_AGN[1])]
setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '', xlim, ylim, legend=True)
print('AGNs: %d, Host (central) halos: %.2e, Sattelite halos: %.2e'%(len(pos_z_AGN[0]), len(ra_cen), len(ra_sat)))
return
def plotAGNfraction(pos_z_AGN, pos_z_gal, redshift_limit_agn, bin_size):
"""
Function to plot the agn fraction in the given pixel
@pos_z_AGN :: postion and redshifts of all the selected AGNs
@pos_z_gal :: postion and redshifts of all the selected galaxies
@redshift_limit_agn :: upper limit on redshift based on the clusters found
"""
fig, ax = plt.subplots(1,2,figsize=(19,7))
# getting the useful histogram properties
counts_agn, redshift_bins_agn = np.histogram(pos_z_AGN[2], bins = bin_size)
counts_gal, redshift_bins_gal = np.histogram(pos_z_gal[2], bins = bin_size)
# plotting the galaxy and agn distribution as a function of redshift
ax[0].plot(redshift_bins_gal[1:], counts_gal, 'ks', ms=4, label=r'DM Halos')
ax[0].plot(redshift_bins_agn[1:], counts_agn, 'bs', ms=4, label=r'AGNs')
# axis properties - 0
xlim = [np.min(redshift_bins_agn[1:]), np.max(redshift_bins_agn[1:])]
setLabel(ax[0], r'Redshift$_R$', 'Counts','', xlim, 'default', legend=True)
ax[0].set_yscale("log")
# agn fraction as a function of redshift
f_agn, idx = [], []
for c, c_gal in enumerate(counts_gal):
if c_gal != 0:
f_agn.append(((counts_agn[c]*100)/c_gal))
idx.append(c)
z_bin_modified = redshift_bins_gal[1:][np.array(idx)]
# plot agn fraction
ax[1].plot(z_bin_modified, f_agn, 's', color='#6b0385', ms=4)
# axis properties - 1
xlim = [np.min(redshift_bins_agn[1:])-0.02, np.max(redshift_bins_agn[1:])]
setLabel(ax[1], r'Redshift$_R$', r'$f_{AGN}$ (%s)'%"%", '', xlim, 'default', legend=False)
ax[1].set_yscale("log")
plt.savefig('figures/agn_frac.pdf', facecolor='w', edgecolor='w')
print( 'Reddhift z<%.2f'%redshift_limit_agn )
return redshift_bins_gal[1:]
def plotRedshiftComovingDistance(cosmo, redshift_limit, resolution = 0.0001):
"""Function to plot the relation between redshift and the comoving distance
@cosmo :: cosmology package loaded
@redshift_limit :: upper limit in redshift --> end point for interpolation
@resolution :: resolution of time steps (set to e-4 based of simulation resolution)
@Returns :: plot showing the dependence of redshift on comoving distance
"""
fig, ax = plt.subplots(1,1,figsize=(7,6))
distance_Mpc = cosmo.comoving_distance(np.arange(0,redshift_limit, resolution))
redshifts = np.arange(0,redshift_limit, resolution)
ax.plot(redshifts, distance_Mpc, 'k.', ms=1)
setLabel(ax, 'Redshift (z)', 'Comoving distance (Mpc)', '', 'default', 'default', legend=False)
print('Redshift-Comoving distance relationship')
return
def plotMergerDistribution(merger_val_gal, counts_gal, merger_val_agn, counts_agn, cosmo, redshift_limit):
"""
Function to plot the distribution (counts) of the merger scale factor/redshift
"""
fig, ax = plt.subplots(1,1,figsize=(7,6))
ax1 = plt.gca()
ax2 = ax1.twiny()
# plot the merger distribution for galaxies and agns
ax1.plot(merger_val_gal, counts_gal, 'kx', label='DM Halos')
ax1.plot(merger_val_agn, counts_agn, 'bx', label='AGNs')
setLabel(ax1, r'Scale, $a(t)$, of last Major Merger', 'Counts', '', 'default', 'default', legend=True)
ax.set_yscale("log")
# setting the x-label on top (converting a to redshift)
a_min, a_max = np.min(merger_val_gal), np.max(merger_val_gal)
scale_factor_arr = [a_max, a_min*4, a_min*2, a_min]
ax2.set_xticks([(1/a) -1 for a in scale_factor_arr])
ax2.invert_xaxis()
ax2.set_xlabel('Redshift (z)')
ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))
print("Objects with merger redshifts z < %.2f"%z_at_value(cosmo.scale_factor, a_min))
plt.savefig('figures/merger_distribution_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w')
return
def plotCentralSatelliteScaleMergers(cen_sat_AGN, cen_sat_halo, redshift_limit):
"""
Function to plot the central and sattelite scale factors for mergers
"""
fig, ax = plt.subplots(1,1,figsize=(7,6))
labels = [r'central AGNs', r'satellite AGNs', 'central DM halos', 'satellite DM halos']
c, m, ms = ['b', '#38cee8', 'k', 'grey'], ['^', '*', '^', '*'], [9, 15, 5, 9]
mec, mew = ['w', 'k', 'k', '#abaeb3'], [0.7, 0.4, 1, 0.7]
for i in [0, 1]:
s_m_agn, c_agn = np.unique(cen_sat_AGN[i]['HALO_scale_of_last_MM'], return_counts=True)
s_m_gal, c_gal = np.unique(cen_sat_halo[i]['HALO_scale_of_last_MM'], return_counts=True)
# agns
ax.plot(s_m_agn, c_agn, color=c[i], marker=m[i], ls='', ms=ms[i], label=labels[i], markeredgecolor=mec[i], markeredgewidth=mew[i])
# DM halos
j = i + 2
ax.plot(s_m_gal, c_gal, color=c[j], marker=m[j], ls='', ms=ms[j], label=labels[j], markeredgecolor=mec[j], markeredgewidth=mew[j])
# set label
setLabel(ax, r'Scale, $a(t)$, of last Major Merger', 'Counts', '', 'default', 'default', legend=True)
ax.set_yscale("log")
plt.savefig('figures/merger_dist_cenAndsat_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w')
print('Objects below z: ', redshift_limit)
return [labels, c, m, ms, mec, mew]
def plotTimeSinceMergerDist(scale_merger_AGN, scale_merger_gal, z_AGN, z_gal, cosmo, bin_size, redshift_limit):
"""
Plot the distribution of halos with respective galaxies & agns given the time since merger
"""
# get the time difference since merger events in the halos
t_merger_agn = edh.getMergerTimeDifference(scale_merger_AGN, z_AGN, cosmo)
t_merger_gal = edh.getMergerTimeDifference(scale_merger_gal, z_gal, cosmo)
# get the t since merger bins and counts
if bin_size[0]:
c_t_agn, merger_bins_agn = np.histogram(np.array(t_merger_agn), bins = bin_size[1])
c_t_gal, merger_bins_gal = np.histogram(np.array(t_merger_gal), bins = bin_size[1])
merger_bins_agn = merger_bins_agn[:-1]
merger_bins_gal = merger_bins_gal[:-1]
else:
merger_bins_agn, c_t_agn = np.unique(t_merger_agn, return_counts=True)
merger_bins_gal, c_t_gal = np.unique(t_merger_gal, return_counts=True)
fig, ax = plt.subplots(1,1,figsize=(7,6))
# plot the time since merger distribution for galaxies and agns
ax.plot(merger_bins_gal, np.cumsum(c_t_gal), 'k^', label='DM Halos', ms=4)
ax.plot(merger_bins_agn, np.cumsum(c_t_agn), 'b^', label='AGNs', ms=4)
# set labels/legends
setLabel(ax, r'$\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', 'Cumulative counts', '', 'default', 'default', legend=False)
ax.legend(loc='lower left', fontsize=14)
ax.set_yscale("log")
ax.set_xscale("log")
return ax, fig, t_merger_agn, t_merger_gal
def mergerRedshiftPlot(cen_sat_AGN, cen_sat_halo, dt_m, plot_params, redshift_limit):
"""
Function to plot the time since merger as a function of the redshift
@cen_sat_AGN(gal) :: handels to access the central and satellite AGNs(galaxies)
@dt_m :: time difference after merger for cen/sat AGNs(galaxies)
@plot_params :: to keep consistency between plots, array containing [labels, c, m, ms]
"""
fig, ax = plt.subplots(1,1,figsize=(7,6))
# change marker size for central DM halos
plot_params[3][1] = 9
z_R = [cen_sat_AGN[0]['redshift_R'], cen_sat_AGN[1]['redshift_R'], cen_sat_halo[0]['redshift_R'], cen_sat_halo[1]['redshift_R']]
# plot central, satellite merger distributions as per visual preference
for i in [2, 3, 0, 1]:
ax.plot(dt_m[i], z_R[i], plot_params[2][i], color=plot_params[1][i], ms=plot_params[3][i], label=plot_params[0][i], markeredgecolor=plot_params[4][i], markeredgewidth=plot_params[5][i])
# set labels/legends
setLabel(ax, r'$\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', r'Redshift$_R$', '', 'default', 'default', legend=True)
ax.set_xscale("log")
plt.savefig('figures/t_since_merger_z_plot_%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w')
return ax
def plotMergerTimeCuts(ax, t_merger_cut_arr, l):
"""
Function to plot the defined cuts in merger times within the concerned plot
@t_merger_cut_arr :: array that defines the cuts in the merger times
@l :: array that defines the linestyles used to denote these cuts (refer to the initial codeblock in the notebook)
"""
for i, t_m_cut in enumerate(t_merger_cut_arr):
ax.axvline(x=t_m_cut, color='r', linestyle= l[i], label='%.1f Gyr'%t_m_cut)
ax.legend(fontsize=14, loc='lower left')
return | 2.421875 | 2 |
asv_bench/benchmarks/omnisci/io.py | Rubtsowa/modin | 0 | 2226 | <gh_stars>0
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team 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.
"""IO Modin on OmniSci storage format benchmarks."""
import modin.pandas as pd
from ..utils import (
generate_dataframe,
RAND_LOW,
RAND_HIGH,
ASV_USE_IMPL,
IMPL,
get_shape_id,
trigger_import,
get_benchmark_shapes,
)
from ..io.csv import TimeReadCsvTrueFalseValues # noqa: F401
class TimeReadCsvNames:
shapes = get_benchmark_shapes("omnisci.TimeReadCsvNames")
param_names = ["shape"]
params = [shapes]
def setup_cache(self, test_filename="io_test_file_csv_names"):
# filenames with a metadata of saved dataframes
cache = {}
for shape in self.shapes:
df = generate_dataframe("pandas", "int", *shape, RAND_LOW, RAND_HIGH)
file_id = get_shape_id(shape)
cache[file_id] = (
f"{test_filename}_{file_id}.csv",
df.columns.to_list(),
df.dtypes.to_dict(),
)
df.to_csv(cache[file_id][0], index=False)
return cache
def setup(self, cache, shape):
# ray init
if ASV_USE_IMPL == "modin":
pd.DataFrame([])
file_id = get_shape_id(shape)
self.filename, self.names, self.dtype = cache[file_id]
def time_read_csv_names(self, cache, shape):
df = IMPL[ASV_USE_IMPL].read_csv(
self.filename,
names=self.names,
header=0,
dtype=self.dtype,
)
trigger_import(df)
| 1.882813 | 2 |
benchmarks/rotation/rotated_cifar.py | ypeng22/ProgLearn | 1 | 2227 | import matplotlib.pyplot as plt
import random
import pickle
from skimage.transform import rotate
from scipy import ndimage
from skimage.util import img_as_ubyte
from joblib import Parallel, delayed
from sklearn.ensemble.forest import _generate_unsampled_indices
from sklearn.ensemble.forest import _generate_sample_indices
import numpy as np
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier
from itertools import product
import keras
from keras import layers
from joblib import Parallel, delayed
from multiprocessing import Pool
import tensorflow as tf
from numba import cuda
import sys
sys.path.append("../../proglearn/")
from progressive_learner import ProgressiveLearner
from deciders import SimpleArgmaxAverage
from transformers import TreeClassificationTransformer, NeuralClassificationTransformer
from voters import TreeClassificationVoter, KNNClassificationVoter
def cross_val_data(data_x, data_y, total_cls=10):
x = data_x.copy()
y = data_y.copy()
idx = [np.where(data_y == u)[0] for u in np.unique(data_y)]
for i in range(total_cls):
indx = idx[i]#np.roll(idx[i],(cv-1)*100)
random.shuffle(indx)
if i==0:
train_x1 = x[indx[0:250],:]
train_x2 = x[indx[250:500],:]
train_y1 = y[indx[0:250]]
train_y2 = y[indx[250:500]]
test_x = x[indx[500:600],:]
test_y = y[indx[500:600]]
else:
train_x1 = np.concatenate((train_x1, x[indx[0:250],:]), axis=0)
train_x2 = np.concatenate((train_x2, x[indx[250:500],:]), axis=0)
train_y1 = np.concatenate((train_y1, y[indx[0:250]]), axis=0)
train_y2 = np.concatenate((train_y2, y[indx[250:500]]), axis=0)
test_x = np.concatenate((test_x, x[indx[500:600],:]), axis=0)
test_y = np.concatenate((test_y, y[indx[500:600]]), axis=0)
return train_x1, train_y1, train_x2, train_y2, test_x, test_y
def LF_experiment(data_x, data_y, angle, model, granularity, reps=1, ntrees=29, acorn=None):
if acorn is not None:
np.random.seed(acorn)
errors = np.zeros(2)
for rep in range(reps):
print("Starting Rep {} of Angle {}".format(rep, angle))
train_x1, train_y1, train_x2, train_y2, test_x, test_y = cross_val_data(data_x, data_y, total_cls=10)
#change data angle for second task
tmp_data = train_x2.copy()
_tmp_ = np.zeros((32,32,3), dtype=int)
total_data = tmp_data.shape[0]
for i in range(total_data):
tmp_ = image_aug(tmp_data[i],angle)
tmp_data[i] = tmp_
if model == "uf":
train_x1 = train_x1.reshape((train_x1.shape[0], train_x1.shape[1] * train_x1.shape[2] * train_x1.shape[3]))
tmp_data = tmp_data.reshape((tmp_data.shape[0], tmp_data.shape[1] * tmp_data.shape[2] * tmp_data.shape[3]))
test_x = test_x.reshape((test_x.shape[0], test_x.shape[1] * test_x.shape[2] * test_x.shape[3]))
with tf.device('/gpu:'+str(int(angle // granularity) % 4)):
default_transformer_class = NeuralClassificationTransformer
network = keras.Sequential()
network.add(layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=np.shape(train_x1)[1:]))
network.add(layers.BatchNormalization())
network.add(layers.Conv2D(filters=32, kernel_size=(3, 3), strides = 2, padding = "same", activation='relu'))
network.add(layers.BatchNormalization())
network.add(layers.Conv2D(filters=64, kernel_size=(3, 3), strides = 2, padding = "same", activation='relu'))
network.add(layers.BatchNormalization())
network.add(layers.Conv2D(filters=128, kernel_size=(3, 3), strides = 2, padding = "same", activation='relu'))
network.add(layers.BatchNormalization())
network.add(layers.Conv2D(filters=254, kernel_size=(3, 3), strides = 2, padding = "same", activation='relu'))
network.add(layers.Flatten())
network.add(layers.BatchNormalization())
network.add(layers.Dense(2000, activation='relu'))
network.add(layers.BatchNormalization())
network.add(layers.Dense(2000, activation='relu'))
network.add(layers.BatchNormalization())
network.add(layers.Dense(units=10, activation = 'softmax'))
default_transformer_kwargs = {"network" : network,
"euclidean_layer_idx" : -2,
"num_classes" : 10,
"optimizer" : keras.optimizers.Adam(3e-4)
}
default_voter_class = KNNClassificationVoter
default_voter_kwargs = {"k" : int(np.log2(len(train_x1)))}
default_decider_class = SimpleArgmaxAverage
progressive_learner = ProgressiveLearner(default_transformer_class = default_transformer_class,
default_transformer_kwargs = default_transformer_kwargs,
default_voter_class = default_voter_class,
default_voter_kwargs = default_voter_kwargs,
default_decider_class = default_decider_class)
progressive_learner.add_task(
X = train_x1,
y = train_y1,
transformer_voter_decider_split = [0.67, 0.33, 0],
decider_kwargs = {"classes" : np.unique(train_y1)}
)
progressive_learner.add_transformer(
X = tmp_data,
y = train_y2,
transformer_data_proportion = 1,
backward_task_ids = [0]
)
llf_task1=progressive_learner.predict(test_x, task_id=0)
llf_single_task=progressive_learner.predict(test_x, task_id=0, transformer_ids=[0])
errors[1] = errors[1]+(1 - np.mean(llf_task1 == test_y))
errors[0] = errors[0]+(1 - np.mean(llf_single_task == test_y))
errors = errors/reps
print("Errors For Angle {}: {}".format(angle, errors))
with open('rotation_results/angle_'+str(angle)+'_'+model+'.pickle', 'wb') as f:
pickle.dump(errors, f, protocol = 2)
def image_aug(pic, angle, centroid_x=23, centroid_y=23, win=16, scale=1.45):
im_sz = int(np.floor(pic.shape[0]*scale))
pic_ = np.uint8(np.zeros((im_sz,im_sz,3),dtype=int))
pic_[:,:,0] = ndimage.zoom(pic[:,:,0],scale)
pic_[:,:,1] = ndimage.zoom(pic[:,:,1],scale)
pic_[:,:,2] = ndimage.zoom(pic[:,:,2],scale)
image_aug = rotate(pic_, angle, resize=False)
#print(image_aug.shape)
image_aug_ = image_aug[centroid_x-win:centroid_x+win,centroid_y-win:centroid_y+win,:]
return img_as_ubyte(image_aug_)
### MAIN HYPERPARAMS ###
model = "dnn"
granularity = 2
reps = 4
########################
(X_train, y_train), (X_test, y_test) = keras.datasets.cifar100.load_data()
data_x = np.concatenate([X_train, X_test])
data_y = np.concatenate([y_train, y_test])
data_y = data_y[:, 0]
def perform_angle(angle):
LF_experiment(data_x, data_y, angle, model, granularity, reps=reps, ntrees=16, acorn=1)
if model == "dnn":
for angle_adder in range(30, 180, granularity * 4):
angles = angle_adder + np.arange(0, granularity * 4, granularity)
with Pool(4) as p:
p.map(perform_angle, angles)
elif model == "uf":
angles = np.arange(30,180,2)
Parallel(n_jobs=-1)(delayed(LF_experiment)(data_x, data_y, angle, model, granularity, reps=20, ntrees=16, acorn=1) for angle in angles)
| 1.929688 | 2 |
sklearn_pandas/transformers/monitor.py | toddbenanzer/sklearn_pandas | 0 | 2228 | import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin, clone
from sklearn_pandas.util import validate_dataframe
class MonitorMixin(object):
def print_message(self, message):
if self.logfile:
with open(self.logfile, "a") as fout:
fout.write(message)
else:
print(message)
class ValidateTypes(BaseEstimator, TransformerMixin, MonitorMixin):
def __init__(self, logfile=None, to_screen=True):
self.logfile = logfile
self.to_screen = to_screen
def fit(self, X, y=None, **fitparams):
X = validate_dataframe(X)
self.types = {}
for col in X.columns:
self.types[col] = X[col].dtype.name
return self
def transform(self, X, **transformparams):
X = validate_dataframe(X)
new_col_list = []
for col in X.columns:
var_type = X[col].dtype.name
if var_type != self.types[col]:
self.print_message(
'Data Type Mismatch for column {col}: Expected {expected} Received {received}'.format(
col=col, expected=self.types[col], received=var_type)
)
return X
class ValidateRange(BaseEstimator, TransformerMixin, MonitorMixin):
def __init__(self, logfile=None, to_screen=True, max_nunique=20):
self.logfile = logfile
self.to_screen = to_screen
self.max_nunique = max_nunique
def fit(self, X, y=None, **fitparams):
X = validate_dataframe(X)
self.types = {}
self.unique_vals = {}
self.minmax = {}
for col in X.columns:
self.types[col] = X[col].dtype.name
if self.types[col] in ('object', 'bool', 'category'):
unique_values = X[col].unique()
if len(unique_values) <= self.max_nunique:
self.unique_vals[col] = unique_values
else:
self.unique_vals[col] = None
elif self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'):
self.minmax[col] = (X[col].min(), X[col].max())
return self
def transform(self, X, **transformparams):
X = validate_dataframe(X)
new_col_list = []
for col in X.columns:
var_type = X[col].dtype.name
if self.types[col] in ('object', 'bool', 'category'):
if self.unique_vals[col] is not None:
not_in_list = ~X[col].isin(self.unique_vals[col])
if sum(not_in_list) > 0:
new_values = str(X[col][not_in_list].unique().tolist())
self.print_message(
'New Categories specified for column {col}: Received {received}'.format(
col=col, received=new_values)
)
elif self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'):
minX = X[col].min()
maxX = X[col].max()
if minX < self.minmax[col][0]:
self.print_message(
'Low Value warning for column {col}: Lowest Training value {lowtrain}, Lowest Scoring value {lowscore}'.format(
col=col, lowtrain=self.minmax[col][0], lowscore=minX)
)
if maxX > self.minmax[col][1]:
self.print_message(
'High Value warning for column {col}: Largest Training value {hightrain}, Largest Scoring value {highscore}'.format(
col=col, hightrain=self.minmax[col][1], highscore=maxX)
)
return X
| 2.765625 | 3 |
Packs/ProofpointThreatResponse/Integrations/ProofpointThreatResponse/ProofpointThreatResponse_test.py | cbrake1/content | 1 | 2229 | import pytest
from CommonServerPython import *
from ProofpointThreatResponse import create_incident_field_context, get_emails_context, pass_sources_list_filter, \
pass_abuse_disposition_filter, filter_incidents, prepare_ingest_alert_request_body, \
get_incidents_batch_by_time_request, get_new_incidents, get_time_delta
MOCK_INCIDENT = {
"id": 1,
"type": "Malware",
"summary": "Unsolicited Bulk Email",
"description": "EvilScheme test message",
"score": 4200,
"state": "Open",
"created_at": "2018-05-26T21:07:17Z",
"event_count": 3,
"event_sources": [
"Proofpoint TAP"
],
"users": [
""
],
"assignee": "Unassigned",
"team": "Unassigned",
"hosts": {
"attacker": [
""
],
"forensics": [
"",
]
},
"incident_field_values": [
{
"name": "Attack Vector",
"value": "Email"
},
{
"name": "Classification",
"value": "Spam"
},
{
"name": "Severity",
"value": "Critical"
},
{
"name": "Abuse Disposition",
"value": "Unknown"
}
],
"events": [
{
"id": 3,
"category": "malware",
"severity": "Info",
"source": "Proofpoint TAP",
"threatname": "",
"state": "Linked",
"description": "",
"attackDirection": "inbound",
"received": "2018-05-26T21:07:17Z",
"malwareName": "",
"emails": [
{
"sender": {
"email": "test"
},
"recipient": {
"email": "test"
},
"subject": "test",
"messageId": "test",
"messageDeliveryTime": {
"chronology": {
"zone": {
"id": "UTC"
}
},
"millis": 1544640072000,
},
"abuseCopy": "false",
"body": "test",
'bodyType': "test",
'headers': "test",
'urls': "test"
}
],
}
],
"quarantine_results": [],
"successful_quarantines": 0,
"failed_quarantines": 0,
"pending_quarantines": 0
}
INCIDENT_FIELD_CONTEXT = {
"Attack_Vector": "Email",
"Classification": "Spam",
"Severity": "Critical",
"Abuse_Disposition": "Unknown"
}
INCIDENT_FIELD_INPUT = [
(MOCK_INCIDENT, INCIDENT_FIELD_CONTEXT)
]
def get_fetch_data():
with open('./test_data/raw_response.json', 'r') as f:
file = json.loads(f.read())
return file.get('result')
FETCH_RESPONSE = get_fetch_data()
@pytest.mark.parametrize('incident, answer', INCIDENT_FIELD_INPUT)
def test_get_incident_field_context(incident, answer):
incident_field_values = create_incident_field_context(incident)
assert incident_field_values == answer
EMAIL_RESULT = [
{
'sender': "test",
'recipient': "test",
'subject': "test",
'message_id': "test",
'message_delivery_time': 1544640072000,
'body': "test",
'body_type': "test",
'headers': "test",
'urls': "test"
}
]
EMAILS_CONTEXT_INPUT = [
(MOCK_INCIDENT['events'][0], EMAIL_RESULT)
]
@pytest.mark.parametrize('event, answer', EMAILS_CONTEXT_INPUT)
def test_get_emails_context(event, answer):
emails_context = get_emails_context(event)
assert emails_context == answer
SOURCE_LIST_INPUT = [
(["Proofpoint TAP"], True),
([], True),
(["No such source"], False),
(["No such source", "Proofpoint TAP"], True)
]
@pytest.mark.parametrize('sources_list, expected_answer', SOURCE_LIST_INPUT)
def test_pass_sources_list_filter(sources_list, expected_answer):
result = pass_sources_list_filter(MOCK_INCIDENT, sources_list)
assert result == expected_answer
ABUSE_DISPOSITION_INPUT = [
(["Unknown"], True),
([], True),
(["No such value"], False),
(["No such value", "Unknown"], True)
]
@pytest.mark.parametrize('abuse_dispotion_values, expected_answer', ABUSE_DISPOSITION_INPUT)
def test_pass_abuse_disposition_filter(abuse_dispotion_values, expected_answer):
result = pass_abuse_disposition_filter(MOCK_INCIDENT, abuse_dispotion_values)
assert result == expected_answer
DEMISTO_PARAMS = [({'event_sources': "No such source, Proofpoint TAP", 'abuse_disposition': "No such value, Unknown"},
[MOCK_INCIDENT]), ({'event_sources': "", 'abuse_disposition': ""}, [MOCK_INCIDENT]),
({'event_sources': "No such source", 'abuse_disposition': "No such value, Unknown"}, []),
({'event_sources': "No such source, Proofpoint TAP", 'abuse_disposition': "No such value"}, []),
({'event_sources': "No such source", 'abuse_disposition': "No such value"}, [])]
@pytest.mark.parametrize('demisto_params, expected_answer', DEMISTO_PARAMS)
def test_filter_incidents(mocker, demisto_params, expected_answer):
mocker.patch.object(demisto, 'params', return_value=demisto_params)
filtered_incidents = filter_incidents([MOCK_INCIDENT])
assert filtered_incidents == expected_answer
INGEST_ALERT_ARGS = {
"attacker": "{\"attacker\":{\"key\":\"value\"}}",
"cnc_host": "{\"cnc_host\":{\"key\":\"value\"}}",
"detector": "{\"detector\":{\"key\":\"value\"}}",
"email": "{\"email\":{\"key\":\"value\"}}",
"forensics_hosts": "{\"forensics_hosts\":{\"key\":\"value\"}}",
"target": "{\"target\":{\"key\":\"value\"}}",
"threat_info": "{\"threat_info\":{\"key\":\"value\"}}",
"custom_fields": "{\"custom_fields\":{\"key\":\"value\"}}",
"post_url_id": "value",
"json_version": "value",
"summary": "value"
}
EXPECTED_RESULT = {
"attacker": {"key": "value"},
"cnc_host": {"key": "value"},
"detector": {"key": "value"},
"email": {"key": "value"},
"forensics_hosts": {"key": "value"},
"target": {"key": "value"},
"threat_info": {"key": "value"},
"custom_fields": {"key": "value"},
"post_url_id": "value",
"json_version": "value",
"summary": "value"
}
def test_prepare_ingest_alert_request_body():
prepared_body = prepare_ingest_alert_request_body(INGEST_ALERT_ARGS)
assert prepared_body == EXPECTED_RESULT
def test_fetch_incidents_limit_exceed(mocker):
"""
Given
- a dict of params given to the function which is gathered originally from demisto.params()
The dict includes the relevant params for the fetch e.g. fetch_delta, fetch_limit, created_after, state.
- response of the api
When
- a single iteration of the fetch is activated with a fetch limit set to 5
Then
- validate that the number or incidents that is returned is equal to the limit when the api returned more.
"""
params = {
'fetch_delta': '6 hours',
'fetch_limit': ' 5',
'created_after': '2021-03-30T11:44:24Z',
'state': 'closed'
}
mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE)
incidents_list = get_incidents_batch_by_time_request(params)
assert len(incidents_list) == 5
def test_fetch_incidents_with_same_created_time(mocker):
"""
Given
- a dict of params given to the function which is gathered originally from demisto.params()
The dict includes the relevant params for the fetch e.g. fetch_delta, fetch_limit, created_after, state and
last_fetched_id.
- response of the api
When
- when a fetch occurs and the last fetched incident has exactly the same time of the next incident.
Then
- validate that only one of the incidents appear as to the fetch limit.
- validate that the next incident whose time is exactly the same is brought in the next fetch loop.
( e.g. 3057 and 3058)
"""
expected_ids_to_fetch_first = [3055, 3056, 3057]
expected_ids_to_fetch_second = [3058, 3059, 3060]
params = {
'fetch_delta': '2 hours',
'fetch_limit': '3',
'created_after': '2021-03-30T10:44:24Z',
'state': 'closed'
}
mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE)
new_fetched_first = get_incidents_batch_by_time_request(params)
for incident in new_fetched_first:
assert incident.get('id') in expected_ids_to_fetch_first
params = {
'fetch_delta': '2 hour',
'fetch_limit': '3',
'created_after': '2021-03-30T11:21:24Z',
'last_fetched_id': '3057',
'state': 'closed'
}
new_fetched_second = get_incidents_batch_by_time_request(params)
for incident in new_fetched_second:
assert incident.get('id') in expected_ids_to_fetch_second
def test_get_new_incidents(mocker):
"""
Given
- a dict of request_params to the api.
- The last fetched incident id.
When
- Get new incidents is called during the fetch process.
Then
- validate that the number of expected incidents return.
- validate that all of the returned incident have a bigger id then the last fetched incident.
"""
last_incident_fetched = 3057
request_params = {
'state': 'closed',
'created_after': '2021-03-30T10:21:24Z',
'created_before': '2021-03-31T11:21:24Z',
}
mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE)
new_incidnets = get_new_incidents(request_params, last_incident_fetched)
assert len(new_incidnets) == 14
for incident in new_incidnets:
assert incident.get('id') > 3057
def test_get_time_delta():
"""
Given
- input to the get_time_delta function which is valid and invalid
When
- run the get_time_delta function.
Then
- validate that on invalid input such as days or no units relevant errors are raised.
- validate that on valid inputs the return value is as expected.
"""
time_delta = get_time_delta('1 minute')
assert str(time_delta) == '0:01:00'
time_delta = get_time_delta('2 hours')
assert str(time_delta) == '2:00:00'
try:
get_time_delta('2')
except Exception as ex:
assert 'The fetch_delta is invalid. Please make sure to insert both the number and the unit of the fetch delta.' in str(
ex)
try:
get_time_delta('2 days')
except Exception as ex:
assert 'The unit of fetch_delta is invalid. Possible values are "minutes" or "hours' in str(ex)
| 1.992188 | 2 |
macholib/macho_methname.py | l1haoyuan/macholib | 0 | 2230 | import sys
import os
import json
from enum import Enum
from .mach_o import LC_SYMTAB
from macholib import MachO
from macholib import mach_o
from shutil import copy2
from shutil import SameFileError
class ReplaceType(Enum):
objc_methname = 1
symbol_table = 2
def replace_in_bytes(method_bytes, name_dict, type):
is_prefix = False
empty_byte = b'\x00'
if not method_bytes.startswith(empty_byte):
is_prefix = True
method_bytes = empty_byte + method_bytes
for key, value in name_dict.items():
if len(key) != len(value):
raise("replace method name with different length may break the mach-o file, ori: " +
key + ", dst: " + value)
if type == ReplaceType.objc_methname:
method_bytes = method_bytes.replace(
empty_byte + key.encode('utf-8') + empty_byte, empty_byte + value.encode('utf-8') + empty_byte)
elif type == ReplaceType.symbol_table:
method_bytes = method_bytes.replace(
b' ' + key.encode('utf-8') + b']', b' ' + value.encode('utf-8') + b']')
if is_prefix:
method_bytes = method_bytes.replace(empty_byte, b'', 1)
return method_bytes
def ch_methname_sect(header, name_dict):
commands = header.commands
lc = None
sect = None
for _, command_tuple in enumerate(commands):
seg = command_tuple[1]
data = command_tuple[2]
if hasattr(seg, 'segname') and seg.segname.rstrip(b'\x00') == b'__TEXT':
for tmp_sect in data:
if tmp_sect.sectname.rstrip(b'\x00') == b'__objc_methname':
lc = command_tuple[0]
sect = tmp_sect
if sect is None:
raise("Can't find __objc_methname section")
sect.section_data = replace_in_bytes(
sect.section_data, name_dict, ReplaceType.objc_methname)
header.mod_dict[lc] = [sect]
def ch_symtab(header, name_dict):
commands = header.commands
for idx, command_tuple in enumerate(commands):
lc = command_tuple[0]
cmd = command_tuple[1]
data = command_tuple[2]
if lc.cmd == LC_SYMTAB:
data = replace_in_bytes(data, name_dict, ReplaceType.symbol_table)
header.mod_dict[lc] = [data]
commands[idx] = (lc, cmd, data)
return
raise("Can't find LC_SYMTAB")
def replace_methname(macho_file, methname_json, output_dir):
"""
Map method names in Mach-O file with the JSON file
"""
if not os.path.isfile(macho_file):
raise("passing not exist file " + macho_file)
if not os.path.isfile(methname_json):
raise("passing not exist file " + methname_json)
if output_dir is not None and not os.path.isdir(output_dir):
raise("passing not exist dir " + output_dir)
macho = MachO.MachO(macho_file)
name_dict = None
with open(methname_json) as json_file:
name_dict = json.load(json_file)
for header in macho.headers:
ch_methname_sect(header, name_dict)
ch_symtab(header, name_dict)
ori_dir, filename = os.path.split(macho_file)
if output_dir is None:
output_dir = ori_dir
output = os.path.join(output_dir, filename)
try:
copy2(macho_file, output_dir)
except SameFileError:
pass
with open(output, 'r+b') as fp:
macho.write(fp)
os.chmod(output, 0o755)
def main():
replace_methname(sys.argv[0], sys.argv[1], sys.argv[2])
if __name__ == '__main__':
main()
| 2.40625 | 2 |
archive/data-processing/archive/features/sd1.py | FloFincke/affective-chat | 0 | 2231 | <gh_stars>0
#!/usr/bin/env python
import math
import numpy as np
def sd1(rr):
sdnn = np.std(rr)
return math.sqrt(0.5 * sdnn * sdnn) | 2.28125 | 2 |
forms/snippets/delete_watch.py | soheilv/python-samples | 255 | 2232 | # Copyright 2021 Google 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
#
# https://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.
# [START forms_delete_watch]
from __future__ import print_function
from apiclient import discovery
from httplib2 import Http
from oauth2client import client, file, tools
SCOPES = "https://www.googleapis.com/auth/drive"
API_KEY = "<YOUR_API_KEY>"
DISCOVERY_DOC = f"https://forms.googleapis.com/$discovery/rest?version=v1beta&key={API_KEY}&labels=FORMS_BETA_TESTERS"
store = file.Storage('credentials.json')
creds = None
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
service = discovery.build('forms', 'v1beta', http=creds.authorize(
Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False)
form_id = '<YOUR_FORM_ID>'
watch_id = '<YOUR_WATCH_ID>'
# Print JSON response after deleting a form watch
result = service.forms().watches().delete(formId=form_id, watchId=watch_id).execute()
print(result)
# [END forms_delete_watch]
| 2.25 | 2 |
data_structures/disjoint_set/disjoint_set.py | egagraha/python-algorithm | 0 | 2233 | <gh_stars>0
"""
Disjoint set.
Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure
"""
class Node:
def __init__(self, data: int) -> None:
self.data = data
self.rank: int
self.parent: Node
def make_set(x: Node) -> None:
"""
Make x as a set.
"""
# rank is the distance from x to its' parent
# root's rank is 0
x.rank = 0
x.parent = x
def union_set(x: Node, y: Node) -> None:
"""
Union of two sets.
set with bigger rank should be parent, so that the
disjoint set tree will be more flat.
"""
x, y = find_set(x), find_set(y)
if x == y:
return
elif x.rank > y.rank:
y.parent = x
else:
x.parent = y
if x.rank == y.rank:
y.rank += 1
def find_set(x: Node) -> Node:
"""
Return the parent of x
"""
if x != x.parent:
x.parent = find_set(x.parent)
return x.parent
def find_python_set(node: Node) -> set:
"""
Return a Python Standard Library set that contains i.
"""
sets = ({0, 1, 2}, {3, 4, 5})
for s in sets:
if node.data in s:
return s
raise ValueError(f"{node.data} is not in {sets}")
def test_disjoint_set() -> None:
"""
>>> test_disjoint_set()
"""
vertex = [Node(i) for i in range(6)]
for v in vertex:
make_set(v)
union_set(vertex[0], vertex[1])
union_set(vertex[1], vertex[2])
union_set(vertex[3], vertex[4])
union_set(vertex[3], vertex[5])
for node0 in vertex:
for node1 in vertex:
if find_python_set(node0).isdisjoint(find_python_set(node1)):
assert find_set(node0) != find_set(node1)
else:
assert find_set(node0) == find_set(node1)
if __name__ == "__main__":
test_disjoint_set()
| 3.953125 | 4 |
cw_EPR.py | tkeller12/spin_physics | 0 | 2234 | # <NAME>
# S = 1/2, I = 1/2
# Spin 1/2 electron coupled to spin 1/2 nuclei
import numpy as np
from scipy.linalg import expm
from matplotlib.pylab import *
from matplotlib import cm
sigma_x = 0.5*np.r_[[[0, 1],[1, 0]]]
sigma_y = 0.5*np.r_[[[0,-1j],[1j, 0]]]
sigma_z = 0.5*np.r_[[[1, 0],[0, -1]]]
Identity = np.eye(2)
Sx = np.kron(sigma_x, Identity)
Sy = np.kron(sigma_y, Identity)
Sz = np.kron(sigma_z, Identity)
Ix = np.kron(Identity, sigma_x)
Iy = np.kron(Identity, sigma_y)
Iz = np.kron(Identity, sigma_z)
SxIx = np.kron(sigma_x,sigma_z)
SxIx2 = np.dot(Sx,Iz)
print(SxIx)
print(SxIx2)
print(np.allclose(SxIx,SxIx2))
omega_S = 1.76e11 # rad / (s * T)
omega_I = 267.522e6 # rad / (s * T)
Aiso = 2*np.pi * 50.e6 # Isotropic Hyperfine coupling rad / s
B0 = 0.35# T
H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso * np.dot(Sz,Iz)
#H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso * (np.dot(Sx,Ix) + np.dot(Sy,Iy) + np.dot(Sz,Iz))
print('Hamiltonian:')
print(H)
out = np.linalg.eig(H)
E = out[0]
print(E)
E12 = E[0] - E[1]
E34 = E[2] - E[3]
E13 = E[0] - E[2]
E24 = E[1] - E[3]
print(E12)
print(E34)
print(E13)
print(E24)
print('Nuclear')
print('%0.05f MHz'%(E12 / 1e6))
print('%0.05f MHz'%(E34 / 1e6))
print('Electron')
print('%0.05f GHz'%(E13 / 1e9))
print('%0.05f GHz'%(E24 / 1e9))
matshow(abs(H), cmap = cm.jet)
title('Hamiltonian')
show()
| 2.171875 | 2 |
V2RaycSpider0825/MiddleKey/VMes_IO.py | TOMJERRY23333/V2RayCloudSpider | 1 | 2235 | from spiderNest.preIntro import *
path_ = os.path.dirname(os.path.dirname(__file__)) + '/dataBase/log_information.csv'
def save_login_info(VMess, class_):
"""
VMess入库
class_: ssr or v2ray
"""
now = str(datetime.now()).split('.')[0]
with open(path_, 'a', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
# 入库时间,Vmess,初始化状态:0
writer.writerow(['{}'.format(now), '{}'.format(VMess), class_, '0'])
def vmess_IO(class_):
"""
获取可用订阅链接并刷新存储池
class_: ssr ; v2ray
"""
def refresh_log(dataFlow):
with open(path_, 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerows(dataFlow)
try:
with open(path_, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
vm_q = [vm for vm in reader]
new_q = vm_q
for i, value in enumerate(reversed(vm_q)):
if value[-1] == '0' and value[-2] == class_:
vm = value[1]
new_q[-(i + 1)][-1] = '1'
break
refresh_log(new_q)
return vm
except UnboundLocalError:
return '无可用订阅连接'
def avi_num():
from datetime import datetime, timedelta
with open(path_, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
vm_list = [i for i in reader]
# ['2020-08-06 04:27:59', 'link','class_', '1']
vm_q = [vm for vm in vm_list if vm[-1] == '0']
tag_items = ''
for vm in vm_list:
if vm[-1] == '0':
bei_ing_time = datetime.fromisoformat(vm[0]) + timedelta(hours=12)
tag_items += '\n【√可选】【{}】#{}'.format(bei_ing_time, vm[-2])
# return vm_q.__len__()
return tag_items
| 2.546875 | 3 |
paddlespeech/s2t/frontend/audio.py | AK391/PaddleSpeech | 0 | 2236 | <reponame>AK391/PaddleSpeech
# Copyright (c) 2021 PaddlePaddle 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.
"""Contains the audio segment class."""
import copy
import io
import random
import re
import struct
import numpy as np
import resampy
import soundfile
from scipy import signal
from .utility import convert_samples_from_float32
from .utility import convert_samples_to_float32
from .utility import subfile_from_tar
class AudioSegment():
"""Monaural audio segment abstraction.
:param samples: Audio samples [num_samples x num_channels].
:type samples: ndarray.float32
:param sample_rate: Audio sample rate.
:type sample_rate: int
:raises TypeError: If the sample data type is not float or int.
"""
def __init__(self, samples, sample_rate):
"""Create audio segment from samples.
Samples are convert float32 internally, with int scaled to [-1, 1].
"""
self._samples = self._convert_samples_to_float32(samples)
self._sample_rate = sample_rate
if self._samples.ndim >= 2:
self._samples = np.mean(self._samples, 1)
def __eq__(self, other):
"""Return whether two objects are equal."""
if type(other) is not type(self):
return False
if self._sample_rate != other._sample_rate:
return False
if self._samples.shape != other._samples.shape:
return False
if np.any(self.samples != other._samples):
return False
return True
def __ne__(self, other):
"""Return whether two objects are unequal."""
return not self.__eq__(other)
def __str__(self):
"""Return human-readable representation of segment."""
return ("%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, "
"rms=%.2fdB" % (type(self), self.num_samples, self.sample_rate,
self.duration, self.rms_db))
@classmethod
def from_file(cls, file, infos=None):
"""Create audio segment from audio file.
Args:
filepath (str|file): Filepath or file object to audio file.
infos (TarLocalData, optional): tar2obj and tar2infos. Defaults to None.
Returns:
AudioSegment: Audio segment instance.
"""
if isinstance(file, str) and re.findall(r".seqbin_\d+$", file):
return cls.from_sequence_file(file)
elif isinstance(file, str) and file.startswith('tar:'):
return cls.from_file(subfile_from_tar(file, infos))
else:
samples, sample_rate = soundfile.read(file, dtype='float32')
return cls(samples, sample_rate)
@classmethod
def slice_from_file(cls, file, start=None, end=None):
"""Loads a small section of an audio without having to load
the entire file into the memory which can be incredibly wasteful.
:param file: Input audio filepath or file object.
:type file: str|file
:param start: Start time in seconds. If start is negative, it wraps
around from the end. If not provided, this function
reads from the very beginning.
:type start: float
:param end: End time in seconds. If end is negative, it wraps around
from the end. If not provided, the default behvaior is
to read to the end of the file.
:type end: float
:return: AudioSegment instance of the specified slice of the input
audio file.
:rtype: AudioSegment
:raise ValueError: If start or end is incorrectly set, e.g. out of
bounds in time.
"""
sndfile = soundfile.SoundFile(file)
sample_rate = sndfile.samplerate
duration = float(len(sndfile)) / sample_rate
start = 0. if start is None else start
end = duration if end is None else end
if start < 0.0:
start += duration
if end < 0.0:
end += duration
if start < 0.0:
raise ValueError("The slice start position (%f s) is out of "
"bounds." % start)
if end < 0.0:
raise ValueError("The slice end position (%f s) is out of bounds." %
end)
if start > end:
raise ValueError("The slice start position (%f s) is later than "
"the slice end position (%f s)." % (start, end))
if end > duration:
raise ValueError("The slice end position (%f s) is out of bounds "
"(> %f s)" % (end, duration))
start_frame = int(start * sample_rate)
end_frame = int(end * sample_rate)
sndfile.seek(start_frame)
data = sndfile.read(frames=end_frame - start_frame, dtype='float32')
return cls(data, sample_rate)
@classmethod
def from_sequence_file(cls, filepath):
"""Create audio segment from sequence file. Sequence file is a binary
file containing a collection of multiple audio files, with several
header bytes in the head indicating the offsets of each audio byte data
chunk.
The format is:
4 bytes (int, version),
4 bytes (int, num of utterance),
4 bytes (int, bytes per header),
[bytes_per_header*(num_utterance+1)] bytes (offsets for each audio),
audio_bytes_data_of_1st_utterance,
audio_bytes_data_of_2nd_utterance,
......
Sequence file name must end with ".seqbin". And the filename of the 5th
utterance's audio file in sequence file "xxx.seqbin" must be
"xxx.seqbin_5", with "5" indicating the utterance index within this
sequence file (starting from 1).
:param filepath: Filepath of sequence file.
:type filepath: str
:return: Audio segment instance.
:rtype: AudioSegment
"""
# parse filepath
matches = re.match(r"(.+\.seqbin)_(\d+)", filepath)
if matches is None:
raise IOError("File type of %s is not supported" % filepath)
filename = matches.group(1)
fileno = int(matches.group(2))
# read headers
f = io.open(filename, mode='rb', encoding='utf8')
version = f.read(4)
num_utterances = struct.unpack("i", f.read(4))[0]
bytes_per_header = struct.unpack("i", f.read(4))[0]
header_bytes = f.read(bytes_per_header * (num_utterances + 1))
header = [
struct.unpack("i", header_bytes[bytes_per_header * i:
bytes_per_header * (i + 1)])[0]
for i in range(num_utterances + 1)
]
# read audio bytes
f.seek(header[fileno - 1])
audio_bytes = f.read(header[fileno] - header[fileno - 1])
f.close()
# create audio segment
try:
return cls.from_bytes(audio_bytes)
except Exception as e:
samples = np.frombuffer(audio_bytes, dtype='int16')
return cls(samples=samples, sample_rate=8000)
@classmethod
def from_bytes(cls, bytes):
"""Create audio segment from a byte string containing audio samples.
:param bytes: Byte string containing audio samples.
:type bytes: str
:return: Audio segment instance.
:rtype: AudioSegment
"""
samples, sample_rate = soundfile.read(
io.BytesIO(bytes), dtype='float32')
return cls(samples, sample_rate)
@classmethod
def concatenate(cls, *segments):
"""Concatenate an arbitrary number of audio segments together.
:param *segments: Input audio segments to be concatenated.
:type *segments: tuple of AudioSegment
:return: Audio segment instance as concatenating results.
:rtype: AudioSegment
:raises ValueError: If the number of segments is zero, or if the
sample_rate of any segments does not match.
:raises TypeError: If any segment is not AudioSegment instance.
"""
# Perform basic sanity-checks.
if len(segments) == 0:
raise ValueError("No audio segments are given to concatenate.")
sample_rate = segments[0]._sample_rate
for seg in segments:
if sample_rate != seg._sample_rate:
raise ValueError("Can't concatenate segments with "
"different sample rates")
if type(seg) is not cls:
raise TypeError("Only audio segments of the same type "
"can be concatenated.")
samples = np.concatenate([seg.samples for seg in segments])
return cls(samples, sample_rate)
@classmethod
def make_silence(cls, duration, sample_rate):
"""Creates a silent audio segment of the given duration and sample rate.
:param duration: Length of silence in seconds.
:type duration: float
:param sample_rate: Sample rate.
:type sample_rate: float
:return: Silent AudioSegment instance of the given duration.
:rtype: AudioSegment
"""
samples = np.zeros(int(duration * sample_rate))
return cls(samples, sample_rate)
def to_wav_file(self, filepath, dtype='float32'):
"""Save audio segment to disk as wav file.
:param filepath: WAV filepath or file object to save the
audio segment.
:type filepath: str|file
:param dtype: Subtype for audio file. Options: 'int16', 'int32',
'float32', 'float64'. Default is 'float32'.
:type dtype: str
:raises TypeError: If dtype is not supported.
"""
samples = self._convert_samples_from_float32(self._samples, dtype)
subtype_map = {
'int16': 'PCM_16',
'int32': 'PCM_32',
'float32': 'FLOAT',
'float64': 'DOUBLE'
}
soundfile.write(
filepath,
samples,
self._sample_rate,
format='WAV',
subtype=subtype_map[dtype])
def superimpose(self, other):
"""Add samples from another segment to those of this segment
(sample-wise addition, not segment concatenation).
Note that this is an in-place transformation.
:param other: Segment containing samples to be added in.
:type other: AudioSegments
:raise TypeError: If type of two segments don't match.
:raise ValueError: If the sample rates of the two segments are not
equal, or if the lengths of segments don't match.
"""
if isinstance(other, type(self)):
raise TypeError("Cannot add segments of different types: %s "
"and %s." % (type(self), type(other)))
if self._sample_rate != other._sample_rate:
raise ValueError("Sample rates must match to add segments.")
if len(self._samples) != len(other._samples):
raise ValueError("Segment lengths must match to add segments.")
self._samples += other._samples
def to_bytes(self, dtype='float32'):
"""Create a byte string containing the audio content.
:param dtype: Data type for export samples. Options: 'int16', 'int32',
'float32', 'float64'. Default is 'float32'.
:type dtype: str
:return: Byte string containing audio content.
:rtype: str
"""
samples = self._convert_samples_from_float32(self._samples, dtype)
return samples.tostring()
def to(self, dtype='int16'):
"""Create a `dtype` audio content.
:param dtype: Data type for export samples. Options: 'int16', 'int32',
'float32', 'float64'. Default is 'float32'.
:type dtype: str
:return: np.ndarray containing `dtype` audio content.
:rtype: str
"""
samples = self._convert_samples_from_float32(self._samples, dtype)
return samples
def gain_db(self, gain):
"""Apply gain in decibels to samples.
Note that this is an in-place transformation.
:param gain: Gain in decibels to apply to samples.
:type gain: float|1darray
"""
self._samples *= 10.**(gain / 20.)
def change_speed(self, speed_rate):
"""Change the audio speed by linear interpolation.
Note that this is an in-place transformation.
:param speed_rate: Rate of speed change:
speed_rate > 1.0, speed up the audio;
speed_rate = 1.0, unchanged;
speed_rate < 1.0, slow down the audio;
speed_rate <= 0.0, not allowed, raise ValueError.
:type speed_rate: float
:raises ValueError: If speed_rate <= 0.0.
"""
if speed_rate == 1.0:
return
if speed_rate <= 0:
raise ValueError("speed_rate should be greater than zero.")
# numpy
# old_length = self._samples.shape[0]
# new_length = int(old_length / speed_rate)
# old_indices = np.arange(old_length)
# new_indices = np.linspace(start=0, stop=old_length, num=new_length)
# self._samples = np.interp(new_indices, old_indices, self._samples)
# sox, slow
try:
import soxbindings as sox
except:
try:
from paddlespeech.s2t.utils import dynamic_pip_install
package = "sox"
dynamic_pip_install.install(package)
package = "soxbindings"
dynamic_pip_install.install(package)
import soxbindings as sox
except:
raise RuntimeError("Can not install soxbindings on your system." )
tfm = sox.Transformer()
tfm.set_globals(multithread=False)
tfm.speed(speed_rate)
self._samples = tfm.build_array(
input_array=self._samples,
sample_rate_in=self._sample_rate).squeeze(-1).astype(
np.float32).copy()
def normalize(self, target_db=-20, max_gain_db=300.0):
"""Normalize audio to be of the desired RMS value in decibels.
Note that this is an in-place transformation.
:param target_db: Target RMS value in decibels. This value should be
less than 0.0 as 0.0 is full-scale audio.
:type target_db: float
:param max_gain_db: Max amount of gain in dB that can be applied for
normalization. This is to prevent nans when
attempting to normalize a signal consisting of
all zeros.
:type max_gain_db: float
:raises ValueError: If the required gain to normalize the segment to
the target_db value exceeds max_gain_db.
"""
gain = target_db - self.rms_db
if gain > max_gain_db:
raise ValueError(
"Unable to normalize segment to %f dB because the "
"the probable gain have exceeds max_gain_db (%f dB)" %
(target_db, max_gain_db))
self.gain_db(min(max_gain_db, target_db - self.rms_db))
def normalize_online_bayesian(self,
target_db,
prior_db,
prior_samples,
startup_delay=0.0):
"""Normalize audio using a production-compatible online/causal
algorithm. This uses an exponential likelihood and gamma prior to
make online estimates of the RMS even when there are very few samples.
Note that this is an in-place transformation.
:param target_db: Target RMS value in decibels.
:type target_bd: float
:param prior_db: Prior RMS estimate in decibels.
:type prior_db: float
:param prior_samples: Prior strength in number of samples.
:type prior_samples: float
:param startup_delay: Default 0.0s. If provided, this function will
accrue statistics for the first startup_delay
seconds before applying online normalization.
:type startup_delay: float
"""
# Estimate total RMS online.
startup_sample_idx = min(self.num_samples - 1,
int(self.sample_rate * startup_delay))
prior_mean_squared = 10.**(prior_db / 10.)
prior_sum_of_squares = prior_mean_squared * prior_samples
cumsum_of_squares = np.cumsum(self.samples**2)
sample_count = np.arange(self.num_samples) + 1
if startup_sample_idx > 0:
cumsum_of_squares[:startup_sample_idx] = \
cumsum_of_squares[startup_sample_idx]
sample_count[:startup_sample_idx] = \
sample_count[startup_sample_idx]
mean_squared_estimate = ((cumsum_of_squares + prior_sum_of_squares) /
(sample_count + prior_samples))
rms_estimate_db = 10 * np.log10(mean_squared_estimate)
# Compute required time-varying gain.
gain_db = target_db - rms_estimate_db
self.gain_db(gain_db)
def resample(self, target_sample_rate, filter='kaiser_best'):
"""Resample the audio to a target sample rate.
Note that this is an in-place transformation.
:param target_sample_rate: Target sample rate.
:type target_sample_rate: int
:param filter: The resampling filter to use one of {'kaiser_best',
'kaiser_fast'}.
:type filter: str
"""
self._samples = resampy.resample(
self.samples, self.sample_rate, target_sample_rate, filter=filter)
self._sample_rate = target_sample_rate
def pad_silence(self, duration, sides='both'):
"""Pad this audio sample with a period of silence.
Note that this is an in-place transformation.
:param duration: Length of silence in seconds to pad.
:type duration: float
:param sides: Position for padding:
'beginning' - adds silence in the beginning;
'end' - adds silence in the end;
'both' - adds silence in both the beginning and the end.
:type sides: str
:raises ValueError: If sides is not supported.
"""
if duration == 0.0:
return self
cls = type(self)
silence = self.make_silence(duration, self._sample_rate)
if sides == "beginning":
padded = cls.concatenate(silence, self)
elif sides == "end":
padded = cls.concatenate(self, silence)
elif sides == "both":
padded = cls.concatenate(silence, self, silence)
else:
raise ValueError("Unknown value for the sides %s" % sides)
self._samples = padded._samples
def shift(self, shift_ms):
"""Shift the audio in time. If `shift_ms` is positive, shift with time
advance; if negative, shift with time delay. Silence are padded to
keep the duration unchanged.
Note that this is an in-place transformation.
:param shift_ms: Shift time in millseconds. If positive, shift with
time advance; if negative; shift with time delay.
:type shift_ms: float
:raises ValueError: If shift_ms is longer than audio duration.
"""
if abs(shift_ms) / 1000.0 > self.duration:
raise ValueError("Absolute value of shift_ms should be smaller "
"than audio duration.")
shift_samples = int(shift_ms * self._sample_rate / 1000)
if shift_samples > 0:
# time advance
self._samples[:-shift_samples] = self._samples[shift_samples:]
self._samples[-shift_samples:] = 0
elif shift_samples < 0:
# time delay
self._samples[-shift_samples:] = self._samples[:shift_samples]
self._samples[:-shift_samples] = 0
def subsegment(self, start_sec=None, end_sec=None):
"""Cut the AudioSegment between given boundaries.
Note that this is an in-place transformation.
:param start_sec: Beginning of subsegment in seconds.
:type start_sec: float
:param end_sec: End of subsegment in seconds.
:type end_sec: float
:raise ValueError: If start_sec or end_sec is incorrectly set, e.g. out
of bounds in time.
"""
start_sec = 0.0 if start_sec is None else start_sec
end_sec = self.duration if end_sec is None else end_sec
if start_sec < 0.0:
start_sec = self.duration + start_sec
if end_sec < 0.0:
end_sec = self.duration + end_sec
if start_sec < 0.0:
raise ValueError("The slice start position (%f s) is out of "
"bounds." % start_sec)
if end_sec < 0.0:
raise ValueError("The slice end position (%f s) is out of bounds." %
end_sec)
if start_sec > end_sec:
raise ValueError("The slice start position (%f s) is later than "
"the end position (%f s)." % (start_sec, end_sec))
if end_sec > self.duration:
raise ValueError("The slice end position (%f s) is out of bounds "
"(> %f s)" % (end_sec, self.duration))
start_sample = int(round(start_sec * self._sample_rate))
end_sample = int(round(end_sec * self._sample_rate))
self._samples = self._samples[start_sample:end_sample]
def random_subsegment(self, subsegment_length, rng=None):
"""Cut the specified length of the audiosegment randomly.
Note that this is an in-place transformation.
:param subsegment_length: Subsegment length in seconds.
:type subsegment_length: float
:param rng: Random number generator state.
:type rng: random.Random
:raises ValueError: If the length of subsegment is greater than
the origineal segemnt.
"""
rng = random.Random() if rng is None else rng
if subsegment_length > self.duration:
raise ValueError("Length of subsegment must not be greater "
"than original segment.")
start_time = rng.uniform(0.0, self.duration - subsegment_length)
self.subsegment(start_time, start_time + subsegment_length)
def convolve(self, impulse_segment, allow_resample=False):
"""Convolve this audio segment with the given impulse segment.
Note that this is an in-place transformation.
:param impulse_segment: Impulse response segments.
:type impulse_segment: AudioSegment
:param allow_resample: Indicates whether resampling is allowed when
the impulse_segment has a different sample
rate from this signal.
:type allow_resample: bool
:raises ValueError: If the sample rate is not match between two
audio segments when resample is not allowed.
"""
if allow_resample and self.sample_rate != impulse_segment.sample_rate:
impulse_segment.resample(self.sample_rate)
if self.sample_rate != impulse_segment.sample_rate:
raise ValueError("Impulse segment's sample rate (%d Hz) is not "
"equal to base signal sample rate (%d Hz)." %
(impulse_segment.sample_rate, self.sample_rate))
samples = signal.fftconvolve(self.samples, impulse_segment.samples,
"full")
self._samples = samples
def convolve_and_normalize(self, impulse_segment, allow_resample=False):
"""Convolve and normalize the resulting audio segment so that it
has the same average power as the input signal.
Note that this is an in-place transformation.
:param impulse_segment: Impulse response segments.
:type impulse_segment: AudioSegment
:param allow_resample: Indicates whether resampling is allowed when
the impulse_segment has a different sample
rate from this signal.
:type allow_resample: bool
"""
target_db = self.rms_db
self.convolve(impulse_segment, allow_resample=allow_resample)
self.normalize(target_db)
def add_noise(self,
noise,
snr_dB,
allow_downsampling=False,
max_gain_db=300.0,
rng=None):
"""Add the given noise segment at a specific signal-to-noise ratio.
If the noise segment is longer than this segment, a random subsegment
of matching length is sampled from it and used instead.
Note that this is an in-place transformation.
:param noise: Noise signal to add.
:type noise: AudioSegment
:param snr_dB: Signal-to-Noise Ratio, in decibels.
:type snr_dB: float
:param allow_downsampling: Whether to allow the noise signal to be
downsampled to match the base signal sample
rate.
:type allow_downsampling: bool
:param max_gain_db: Maximum amount of gain to apply to noise signal
before adding it in. This is to prevent attempting
to apply infinite gain to a zero signal.
:type max_gain_db: float
:param rng: Random number generator state.
:type rng: None|random.Random
:raises ValueError: If the sample rate does not match between the two
audio segments when downsampling is not allowed, or
if the duration of noise segments is shorter than
original audio segments.
"""
rng = random.Random() if rng is None else rng
if allow_downsampling and noise.sample_rate > self.sample_rate:
noise = noise.resample(self.sample_rate)
if noise.sample_rate != self.sample_rate:
raise ValueError("Noise sample rate (%d Hz) is not equal to base "
"signal sample rate (%d Hz)." % (noise.sample_rate,
self.sample_rate))
if noise.duration < self.duration:
raise ValueError("Noise signal (%f sec) must be at least as long as"
" base signal (%f sec)." %
(noise.duration, self.duration))
noise_gain_db = min(self.rms_db - noise.rms_db - snr_dB, max_gain_db)
noise_new = copy.deepcopy(noise)
noise_new.random_subsegment(self.duration, rng=rng)
noise_new.gain_db(noise_gain_db)
self.superimpose(noise_new)
@property
def samples(self):
"""Return audio samples.
:return: Audio samples.
:rtype: ndarray
"""
return self._samples.copy()
@property
def sample_rate(self):
"""Return audio sample rate.
:return: Audio sample rate.
:rtype: int
"""
return self._sample_rate
@property
def num_samples(self):
"""Return number of samples.
:return: Number of samples.
:rtype: int
"""
return self._samples.shape[0]
@property
def duration(self):
"""Return audio duration.
:return: Audio duration in seconds.
:rtype: float
"""
return self._samples.shape[0] / float(self._sample_rate)
@property
def rms_db(self):
"""Return root mean square energy of the audio in decibels.
:return: Root mean square energy in decibels.
:rtype: float
"""
# square root => multiply by 10 instead of 20 for dBs
mean_square = np.mean(self._samples**2)
return 10 * np.log10(mean_square)
def _convert_samples_to_float32(self, samples):
"""Convert sample type to float32.
Audio sample type is usually integer or float-point.
Integers will be scaled to [-1, 1] in float32.
"""
return convert_samples_to_float32(samples)
def _convert_samples_from_float32(self, samples, dtype):
"""Convert sample type from float32 to dtype.
Audio sample type is usually integer or float-point. For integer
type, float32 will be rescaled from [-1, 1] to the maximum range
supported by the integer type.
This is for writing a audio file.
"""
return convert_samples_from_float32(samples, dtype)
| 2.359375 | 2 |
tornado_debugger/debug.py | bhch/tornado-debugger | 1 | 2237 | import os.path
import re
import sys
import traceback
from pprint import pformat
import tornado
from tornado import template
SENSITIVE_SETTINGS_RE = re.compile(
'api|key|pass|salt|secret|signature|token',
flags=re.IGNORECASE
)
class ExceptionReporter:
def __init__(self, exc_info, handler):
self.exc_type = exc_info[0]
self.exc_value = exc_info[1]
self.exc_tb = exc_info[2]
self.handler = handler
def get_response(self):
loader = template.Loader(os.path.dirname(os.path.abspath(__file__)))
t = loader.load('debug.html')
return t.generate(
traceback=traceback,
pprint=pprint,
handler=self.handler,
app_settings=self.get_app_settings(),
exc_type=self.exc_type,
exc_value=self.exc_value,
exc_tb=self.exc_tb,
frames=self.get_traceback_frames(),
tornado_version=tornado.version,
sys_version='%d.%d.%d' % sys.version_info[0:3],
sys_executable=sys.executable,
sys_path=sys.path,
)
def get_app_settings(self):
settings = {}
for arg, value in self.handler.application.settings.items():
if SENSITIVE_SETTINGS_RE.search(arg):
value = '*' * 15
settings[arg] = value
return settings
def get_source_lines(self, tb):
filename = tb.tb_frame.f_code.co_filename
lineno = tb.tb_lineno
lines = []
try:
with open(filename, 'rb') as f:
_lines = f.read().splitlines()
for _lineno in range(
max(lineno - 5, 0),
min(lineno + 5, len(_lines))
):
lines.append((_lineno + 1, _lines[_lineno]))
except Exception as e:
# could not open file
pass
return lines
def get_traceback_frames(self):
frames = []
tb = self.exc_tb
while tb:
frames.append({
'lineno': tb.tb_lineno,
'filename': tb.tb_frame.f_code.co_filename,
'function': tb.tb_frame.f_code.co_name,
'module_name': tb.tb_frame.f_globals.get('__name__') or '',
'vars': tb.tb_frame.f_locals,
'lines': self.get_source_lines(tb),
})
tb = tb.tb_next
frames.reverse()
return frames
exceptions = []
exc_value = self.exc_value
while exc_value:
exceptions.append(exc_value)
exc_value = self._get_explicit_or_implicit_cause(exc_value)
if exc_value in exceptions:
warnings.warn(
"Cycle in the exception chain detected: exception '%s' "
"encountered again." % exc_value,
ExceptionCycleWarning,
)
# Avoid infinite loop if there's a cyclic reference (#29393).
break
frames = []
# No exceptions were supplied to ExceptionReporter
if not exceptions:
return frames
# In case there's just one exception, take the traceback from self.tb
exc_value = exceptions.pop()
tb = self.tb if not exceptions else exc_value.__traceback__
while True:
frames.extend(self.get_exception_traceback_frames(exc_value, tb))
try:
exc_value = exceptions.pop()
except IndexError:
break
tb = exc_value.__traceback__
return frames
def _get_explicit_or_implicit_cause(self, exc_value):
explicit = getattr(exc_value, '__cause__', None)
suppress_context = getattr(exc_value, '__suppress_context__', None)
implicit = getattr(exc_value, '__context__', None)
return explicit or (None if suppress_context else implicit)
def pprint(value):
try:
return pformat(value, width=1)
except Exception as e:
return 'Error in formatting: %s: %s' % (e.__class__.__name__, e)
| 2.1875 | 2 |
base/pylib/seq_iter.py | jpolitz/lambda-py-paper | 1 | 2238 | class SeqIter:
def __init__(self,l):
self.l = l
self.i = 0
self.stop = False
def __len__(self):
return len(self.l)
def __list__(self):
l = []
while True:
try:
l.append(self.__next__())
except StopIteration:
break
return l
def __iter__(self):
return self
def __next__(self):
has_length = True
found = False
try:
self.l.__len__()
except AttributeError:
has_length = False
try:
if self.stop:
raise StopIteration()
if has_length and self.i >= self.l.__len__():
self.stop = True
raise StopIteration()
ret = self.l[self.i]
found = True
except IndexError:
raise StopIteration()
except StopIteration:
raise StopIteration()
self.i += 1
if found:
return ret
else:
return None
___assign("%SeqIter", SeqIter)
def iter(l, *args):
callable = ___id("%callable")
if args.__len__() == 1:
if callable(l):
stopwhen = args[0]
return FuncIter(l, stopwhen)
else:
TypeError("iter(v, w): v must be callable")
elif args.__len__() == 0:
try:
return l.__iter__()
except:
try:
if callable(l.__getitem__):
return SeqIter(l)
except:
raise TypeError("object is not iterable")
else:
raise TypeError("iter expect at most 2 arguments")
___assign("%iter", iter)
def next(it, *arg):
if len(arg) == 0:
return it.__next__()
else:
return it.__next__(arg[0])
___assign("%next", next)
class FuncIter:
def __init__(self, func, stopwhen):
self.func = func
self.stopwhen = stopwhen
self.stopped = False
def __list__(self):
l = []
while not self.stopped:
try:
l.append(self.__next__())
except StopIteration:
break
return l
def __next__(self):
f = self.func
v = f()
if v == self.stopwhen:
self.stopped = True
raise StopIteration()
else:
return v
___assign("%FuncIter", FuncIter)
| 3.28125 | 3 |
caseworker/open_general_licences/enums.py | code-review-doctor/lite-frontend-1 | 0 | 2239 | <reponame>code-review-doctor/lite-frontend-1
from lite_content.lite_internal_frontend.open_general_licences import (
OGEL_DESCRIPTION,
OGTCL_DESCRIPTION,
OGTL_DESCRIPTION,
)
from lite_forms.components import Option
class OpenGeneralExportLicences:
class OpenGeneralLicence:
def __init__(self, id, name, description, acronym):
self.id = id
self.name = name
self.description = description
self.acronym = acronym
open_general_export_licence = OpenGeneralLicence(
"00000000-0000-0000-0000-000000000002",
"Open General Export Licence",
OGEL_DESCRIPTION,
"OGEL",
)
open_general_trade_control_licence = OpenGeneralLicence(
"00000000-0000-0000-0000-000000000013",
"Open General Trade Control Licence",
OGTCL_DESCRIPTION,
"OGTCL",
)
open_general_transhipment_licence = OpenGeneralLicence(
"00000000-0000-0000-0000-000000000014",
"Open General Transhipment Licence",
OGTL_DESCRIPTION,
"OGTL",
)
@classmethod
def all(cls):
return [
cls.open_general_export_licence,
cls.open_general_trade_control_licence,
cls.open_general_transhipment_licence,
]
@classmethod
def as_options(cls):
return [
Option(key=ogl.id, value=f"{ogl.name} ({ogl.acronym})", description=ogl.description) for ogl in cls.all()
]
@classmethod
def get_by_id(cls, id):
return next(ogl for ogl in cls.all() if ogl.id == id)
| 2.015625 | 2 |
Matrix/Python/rotatematrix.py | pratika1505/DSA-Path-And-Important-Questions | 26 | 2240 | # -*- coding: utf-8 -*-
"""RotateMatrix.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1LX-dZFuQCyBXDNVosTp0MHaZZxoc5T4I
"""
#Function to rotate matrix by 90 degree
def rotate(mat):
# `N × N` matrix
N = len(mat)
# Transpose the matrix
for i in range(N):
for j in range(i):
temp = mat[i][j]
mat[i][j] = mat[j][i]
mat[j][i] = temp
# swap columns
for i in range(N):
for j in range(N // 2):
temp = mat[i][j]
mat[i][j] = mat[i][N - j - 1]
mat[i][N - j - 1] = temp
if __name__ == '__main__':
#Declaring matrix
mat = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
rotate(mat)
#printing matrix
for i in mat:
print(i)
| 4.09375 | 4 |
sort.py | EYH0602/FP_Workshop | 1 | 2241 | <gh_stars>1-10
def quicksort(xs):
if len(xs) == 0:
return []
pivot = xs[0]
xs = xs[1:]
left = [x for x in xs if x <= pivot]
right = [x for x in xs if x > pivot]
res = quicksort(left)
res.append(pivot)
res += quicksort(right)
return res
xs = [1, 3, 2, 4, 5, 2]
sorted_xs = quicksort(xs)
| 3.75 | 4 |
bddtests/steps/bdd_test_util.py | TarantulaTechnology/fabric5 | 4 | 2242 | <reponame>TarantulaTechnology/fabric5
# Copyright IBM Corp. 2016 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.
#
import os
import re
import subprocess
import devops_pb2
import fabric_pb2
import chaincode_pb2
from grpc.beta import implementations
def cli_call(context, arg_list, expect_success=True):
"""Executes a CLI command in a subprocess and return the results.
@param context: the behave context
@param arg_list: a list command arguments
@param expect_success: use False to return even if an error occurred when executing the command
@return: (string, string, int) output message, error message, return code
"""
#arg_list[0] = "update-" + arg_list[0]
# We need to run the cli command by actually calling the python command
# the update-cli.py script has a #!/bin/python as the first line
# which calls the system python, not the virtual env python we
# setup for running the update-cli
p = subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = p.communicate()
if p.returncode != 0:
if output is not None:
print("Output:\n" + output)
if error is not None:
print("Error Message:\n" + error)
if expect_success:
raise subprocess.CalledProcessError(p.returncode, arg_list, output)
return output, error, p.returncode
class UserRegistration:
def __init__(self, secretMsg, composeService):
self.secretMsg = secretMsg
self.composeService = composeService
self.tags = {}
self.lastResult = None
def getUserName(self):
return self.secretMsg['enrollId']
def getSecret(self):
return devops_pb2.Secret(enrollId=self.secretMsg['enrollId'],enrollSecret=self.secretMsg['enrollSecret'])
# Registerses a user on a specific composeService
def registerUser(context, secretMsg, composeService):
userName = secretMsg['enrollId']
if 'users' in context:
pass
else:
context.users = {}
if userName in context.users:
raise Exception("User already registered: {0}".format(userName))
context.users[userName] = UserRegistration(secretMsg, composeService)
# Registerses a user on a specific composeService
def getUserRegistration(context, enrollId):
userRegistration = None
if 'users' in context:
pass
else:
context.users = {}
if enrollId in context.users:
userRegistration = context.users[enrollId]
else:
raise Exception("User has not been registered: {0}".format(enrollId))
return userRegistration
def ipFromContainerNamePart(namePart, containerDataList):
"""Returns the IPAddress based upon a name part of the full container name"""
ip = None
containerNamePrefix = os.path.basename(os.getcwd()) + "_"
for containerData in containerDataList:
if containerData.containerName.startswith(containerNamePrefix + namePart):
ip = containerData.ipAddress
if ip == None:
raise Exception("Could not find container with namePart = {0}".format(namePart))
return ip
def getTxResult(context, enrollId):
'''Returns the TransactionResult using the enrollId supplied'''
assert 'users' in context, "users not found in context. Did you register a user?"
assert 'compose_containers' in context, "compose_containers not found in context"
(channel, userRegistration) = getGRPCChannelAndUser(context, enrollId)
stub = devops_pb2.beta_create_Devops_stub(channel)
txRequest = devops_pb2.TransactionRequest(transactionUuid = context.transactionID)
response = stub.GetTransactionResult(txRequest, 2)
assert response.status == fabric_pb2.Response.SUCCESS, 'Failure getting Transaction Result from {0}, for user "{1}": {2}'.format(userRegistration.composeService,enrollId, response.msg)
# Now grab the TransactionResult from the Msg bytes
txResult = fabric_pb2.TransactionResult()
txResult.ParseFromString(response.msg)
return txResult
def getGRPCChannel(ipAddress):
channel = implementations.insecure_channel(ipAddress, 30303)
print("Returning GRPC for address: {0}".format(ipAddress))
return channel
def getGRPCChannelAndUser(context, enrollId):
'''Returns a tuple of GRPC channel and UserRegistration instance. The channel is open to the composeService that the user registered with.'''
userRegistration = getUserRegistration(context, enrollId)
# Get the IP address of the server that the user registered on
ipAddress = ipFromContainerNamePart(userRegistration.composeService, context.compose_containers)
channel = getGRPCChannel(ipAddress)
return (channel, userRegistration)
def getDeployment(context, ccAlias):
'''Return a deployment with chaincode alias from prior deployment, or None if not found'''
deployment = None
if 'deployments' in context:
pass
else:
context.deployments = {}
if ccAlias in context.deployments:
deployment = context.deployments[ccAlias]
# else:
# raise Exception("Deployment alias not found: '{0}'. Are you sure you have deployed a chaincode with this alias?".format(ccAlias))
return deployment
def deployChaincode(context, enrollId, chaincodePath, ccAlias, ctor):
'''Deploy a chaincode with the specified alias for the specfied enrollId'''
(channel, userRegistration) = getGRPCChannelAndUser(context, enrollId)
stub = devops_pb2.beta_create_Devops_stub(channel)
# Make sure deployment alias does NOT already exist
assert getDeployment(context, ccAlias) == None, "Deployment alias already exists: '{0}'.".format(ccAlias)
args = getArgsFromContextForUser(context, enrollId)
ccSpec = chaincode_pb2.ChaincodeSpec(type = chaincode_pb2.ChaincodeSpec.GOLANG,
chaincodeID = chaincode_pb2.ChaincodeID(name="",path=chaincodePath),
ctorMsg = chaincode_pb2.ChaincodeInput(function = ctor, args = args))
ccSpec.secureContext = userRegistration.getUserName()
if 'metadata' in context:
ccSpec.metadata = context.metadata
try:
ccDeploymentSpec = stub.Deploy(ccSpec, 60)
ccSpec.chaincodeID.name = ccDeploymentSpec.chaincodeSpec.chaincodeID.name
context.grpcChaincodeSpec = ccSpec
context.deployments[ccAlias] = ccSpec
except:
del stub
raise
def invokeChaincode(context, enrollId, ccAlias, functionName):
# Get the deployment for the supplied chaincode alias
deployedCcSpec = getDeployment(context, ccAlias)
assert deployedCcSpec != None, "Deployment NOT found for chaincode alias '{0}'".format(ccAlias)
# Create a new ChaincodeSpec by copying the deployed one
newChaincodeSpec = chaincode_pb2.ChaincodeSpec()
newChaincodeSpec.CopyFrom(deployedCcSpec)
# Update hte chaincodeSpec ctorMsg for invoke
args = getArgsFromContextForUser(context, enrollId)
chaincodeInput = chaincode_pb2.ChaincodeInput(function = functionName, args = args )
newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput)
ccInvocationSpec = chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec = newChaincodeSpec)
(channel, userRegistration) = getGRPCChannelAndUser(context, enrollId)
stub = devops_pb2.beta_create_Devops_stub(channel)
response = stub.Invoke(ccInvocationSpec,2)
return response
def getArgsFromContextForUser(context, enrollId):
# Update the chaincodeSpec ctorMsg for invoke
args = []
if 'table' in context:
# There are function arguments
userRegistration = getUserRegistration(context, enrollId)
# Allow the user to specify expressions referencing tags in the args list
pattern = re.compile('\{(.*)\}$')
for arg in context.table[0].cells:
m = pattern.match(arg)
if m:
# tagName reference found in args list
tagName = m.groups()[0]
# make sure the tagName is found in the users tags
assert tagName in userRegistration.tags, "TagName '{0}' not found for user '{1}'".format(tagName, userRegistration.getUserName())
args.append(userRegistration.tags[tagName])
else:
#No tag referenced, pass the arg
args.append(arg)
return args
def getContainerDataValuesFromContext(context, aliases, callback):
"""Returns the IPAddress based upon a name part of the full container name"""
assert 'compose_containers' in context, "compose_containers not found in context"
values = []
containerNamePrefix = os.path.basename(os.getcwd()) + "_"
for namePart in aliases:
for containerData in context.compose_containers:
if containerData.containerName.startswith(containerNamePrefix + namePart):
values.append(callback(containerData))
break
return values
| 2.046875 | 2 |
1.0.0/hp/dict.py | cefect/SOFDA0 | 0 | 2243 | '''
Created on Mar 6, 2018
@author: cef
hp functions for workign with dictionaries
'''
import logging, os, sys, math, copy, inspect
from collections import OrderedDict
from weakref import WeakValueDictionary as wdict
import numpy as np
import hp.basic
mod_logger = logging.getLogger(__name__) #creates a child logger of the root
def dict_2_logr(dict, logger= mod_logger): #log each value of the dictionary to fille
logger = logger.getChild('dict_2_logr')
msg = '\n'
for key, value in dict.iteritems():
msg = msg + ' key: %s\n value: %s \n'%(key, value)
logger.debug(msg)
def key_list(d, #return the intersection of the dict.keys() and the key_list
key_list, logger = mod_logger):
logger = logger.getChild('key_list')
#===========================================================================
# pre check
#===========================================================================
bool_list = hp.basic.bool_list_in_list(d.keys(), key_list)
if not bool_list.any(): raise IOError #check if any are not found
#===========================================================================
# build the found values
#===========================================================================
values_fnd_list = []
for key, value in d.iteritems():
if key in key_list: values_fnd_list.append(value)
return values_fnd_list
def build_nones_dict(key_list, logger=mod_logger): #add 'None' values to the passed keys
val_list = np.full((1, len(key_list)), None)
dict = dict(zip(key_list, val_list))
return dict
def merge_two_dicts(x, y):
if x is None: return y
if y is None: return x
z = x.copy() # start with x's keys and values
z.update(y) # modifies z with y's keys and values & returns None
return z
def value_by_ksearch(ksearch_str, d, #get the entry that matches the search str
logger=mod_logger, *search_args):
#===========================================================================
# take a shot at a perfect match
#===========================================================================
try:
return d[ksearch_str]
except:
#find a match for this key
k_fnd = hp.basic.list_search(d.keys(), ksearch_str, *search_args)
if k_fnd is None:
logger = logger.getChild('value_by_ksearch')
logger.debug('could not find \'%s\' in %i dict keys. returning None'%(ksearch_str, len(d)))
return None
else:
return d[k_fnd]
def merge(dl, dr, #intelligent dictionary merging
set_type = 'intersect',
method = 'exact',
container = dict(),
logger = mod_logger, *search_args):
if set_type == 'union':
if method == 'exact':
d_merge = merge_two_dicts(dl, dr, logger=logger)
else:
raise IOError #todo
elif set_type == 'intersect':
d_merge = subset(dl, dr.keys(), set_type = set_type,
method=method, container=container, logger=logger, *search_args)
else: raise IOError
logger.debug('got d_merge %i'%len(d_merge))
return container(d_merge)
def subset_pfx(d_big, prefix, logger=mod_logger):
#===========================================================================
# shortcuts
#===========================================================================
if len(d_big) == 0: return dict()
#===========================================================================
# defaults
#===========================================================================
logger = logger.getChild('subset_pfx')
d = copy.copy(d_big)
fnd_d = dict()
for k, v in d.iteritems():
if k.startswith(prefix):
fnd_d[k] = v
logger.debug('found %i entries with prefix \'%s\' \n'%(len(fnd_d), prefix))
return fnd_d
def subset(d_big, l, #get a dictionary subset using standard user inputs
#ordered = False, using containers instead
set_type = 'sub',
method = 'exact',
container = dict,
logger = mod_logger,
*search_args):
"""
#===========================================================================
# INPUTS
#===========================================================================
l: list of keys (within d_big) on which to erturn the sutset
set_type: how to treat the set
intersect: returna dictionary with only the common keys
sub: raise a flag if not every item in 'l' is found in d_big.keys()
method: what type of key search to perform (re.function)
search: look for a key in the dictionary that contains the list entry.
returned d is keyed by the list
"""
logger = logger.getChild('subset')
#===========================================================================
# setup[]
#==========================================================================
d = container()
"""
#dictionary setup
if ordered: d = OrderedDict()
else: d = dict()"""
#input list setup
if isinstance(l, list): pass
elif isinstance(l, basestring): l = [l]
elif l is None: return d
else: raise IOError
nofnd_l = []
#===========================================================================
# determine subset by kwarg
#===========================================================================
for k in l:
try: #attempt teh direct match
d[k] = d_big[k]
except:
#===================================================================
# try again using search functions
#===================================================================
try:
if method == 'search':
#search and return this value
v = value_by_ksearch(k, d_big, logger=logger, *search_args)
if not v is None:
d[k] = v
continue #not sure this is needed
else: raise ValueError
else: raise ValueError
#===================================================================
# nothing found. proceed based on set_type
#===================================================================
except:
logger.debug('unable to find \'%s\' in the dict with method \'%s\''%(k, method))
if set_type == 'sub':
boolar = hp.basic.bool_list_in_list(d_big.keys(), l)
if not np.all(boolar):
logger.error('%i entries in list not found in big_d'%(len(l) - boolar.sum()))
raise IOError
elif set_type == 'intersect': nofnd_l.append(k)
else: raise IOError
#===========================================================================
# wrap up
#===========================================================================
if len(nofnd_l) >0:
logger.debug('%i of %i list entries DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l))
if set_type == 'sub': raise IOError
#===========================================================================
# check
#===========================================================================
if len(d) == 0:
logger.warning('0 common values between d(%i) and l(%i)'%(len(d), len(l)))
logger.debug('returning d with %i entries: %s \n'%(len(d), d.keys()))
return container(d)
#===============================================================================
# def subset(d_big, l, #get a dictionary subset using standard user inputs
# ordered = False, set_type = 'sub', search = 'search',
# logger = mod_logger):
# """
# #===========================================================================
# # INPUTS
# #===========================================================================
# l: list of keys (within d_big) on which to erturn the sutset
#
# set_type: how to treat the set
# intersect: returna dictionary with only the common keys
# sub: raise a flag if not every item in 'l' is found in d_big.keys()
#
# search: what type of key search to perform (re.function)
# """
# logger = logger.getChild('subset')
#
# #===========================================================================
# # setup[]
# #==========================================================================
# #dictionary setup
# if ordered: d = OrderedDict()
# else: d = dict()
#
# #input list setup
# if isinstance(l, list): pass
# elif isinstance(l, basestring): l = [l]
# elif l is None: return None
# else: raise IOError
#
# #===========================================================================
# # determine subset by kwarg
# #===========================================================================
# if set_type == 'sub':
# try:
# for k in l:
# d[k] = d_big[k]
#
# except:
# boolar = hp.basic.bool_list_in_list(d_big.keys(), l)
#
# if not np.all(boolar):
# logger.error('%i entries in list not found in big_d'%(len(l) - boolar.sum()))
#
# raise IOError
#
# if len(d) == 0: raise IOError
#
# elif set_type == 'intersect':
# nofnd_l = []
# for k in l:
# try:
# d[k] = d_big[k]
# except:
# nofnd_l.append(k)
#
# if len(nofnd_l) >0:
# logger.debug('%i of %i list entries DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l))
#
# #===========================================================================
# # check
# #===========================================================================
# if len(d) == 0: logger.warning('0 common values between d(%i) and l(%i)'%
# (len(d), len(l)))
#
# return d
#===============================================================================
class deepcopier():
tries = 0 #keep track of the loop
def __init__(self,obj, logger=mod_logger):
self.logger = logger.getChild('deepcopier')
self.copy_o = obj
def tryit(self, obj=None): #make as deep a copy as possible
if obj is None: obj = self.copy_o
#===========================================================================
# simple try
#===========================================================================
try:
copy_o = copy.deepcopy(obj)
return copy_o
except:
self.logger.debug('failed first attempt')
self.tries += 1
#=======================================================================
# sophisiticated try
#=======================================================================
self.logger.debug('copy attempt %i'%self.tries)
if self.tries > 10: return self.copy_o
#try for each element of the dict
if isinstance(obj, dict):
new_d = dict()
for key, value in obj.iteritems():
try:
new_d[key] = self.tryit(obj = value)
except:
new_d[key] = copy.copy(obj)
self.logger.debug('returning new_d with %i entries: %s'%(len(new_d), new_d.keys()))
else: raise IOError
return new_d
from collections import OrderedDict
class MyOrderedDict(OrderedDict):
"""
as there is no builtin method to add to the head of an ordered dict,
here we add a method
https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python
"""
def prepend(self, key, value, dict_setitem=dict.__setitem__):
"""add entry to the front of myself"""
root = self._OrderedDict__root
first = root[1]
if key in self:
link = self._OrderedDict__map[key]
link_prev, link_next, _ = link
link_prev[1] = link_next
link_next[0] = link_prev
link[0] = root
link[1] = first
root[1] = first[0] = link
else:
root[1] = first[0] = self._OrderedDict__map[key] = [root, first, key]
dict_setitem(self, key, value)
| 2.71875 | 3 |
Core/pre.py | Cyber-Dioxide/CyberPhish | 9 | 2244 | <reponame>Cyber-Dioxide/CyberPhish<filename>Core/pre.py
import os
import random
try:
from colorama import Fore, Style
except ModuleNotFoundError:
os.system("pip install colorama")
from urllib.request import urlopen
from Core.helper.color import green, white, blue, red, start, alert
Version = "2.2"
yellow = ("\033[1;33;40m")
def connected(host='http://duckduckgo.com'):
try:
urlopen(host)
return True
except:
return False
all_col = [Style.BRIGHT + Fore.RED, Style.BRIGHT + Fore.CYAN, Style.BRIGHT + Fore.LIGHTCYAN_EX,
Style.BRIGHT + Fore.LIGHTBLUE_EX, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTMAGENTA_EX,
Style.BRIGHT + Fore.LIGHTYELLOW_EX]
ran = random.choice(all_col)
def banner():
print(Style.BRIGHT + Fore.LIGHTCYAN_EX, "\n", "- " * 4, " [+] Follow me on Instagram @cyber_dioxide ", "- " * 4)
print(Style.BRIGHT + Fore.LIGHTYELLOW_EX, "\n", "- " * 4, " [+] Coding Instagram @cyber_dioxide_ ", "- " * 4)
print(Style.BRIGHT + Fore.LIGHTRED_EX, "\n", "- " * 4, "[+] Github: https://github.com/Cyber-Dioxide/ ", "- " * 3)
banner()
def menu():
print(blue + " ██████╗██╗ ██╗██████╗ ███████╗██████╗" + white )
print(white +"██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗")
print(blue + "██║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝")
print(green + "██║ ╚██╔╝ ██╔══██╗██╔══╝ ██╔══██╗" + white+ blue + white)
print(green + "╚██████╗ ██║ ██████╔╝███████╗██║ ██║")
print(red + "██████╗ ██╗ ██╗██╗███████╗██╗ ██╗" )
print(white+ "██╔══██╗██║ ██║██║██╔════╝██║ ██║" + green)
print(yellow+"██████╔╝███████║██║███████╗███████║" + blue)
print(yellow+"██╔═══╝ ██╔══██║██║╚════██║██╔══██║" + green)
print(yellow+"██║ ██║ ██║██║███████║██║ ██║")
print(red+ "╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝ ╚═╝ ")
banner()
print(alert + " More Versions Will Come Soon Stay Updated, Follow My Github\n")
print(white + "options:")
print(green + "[" + white + "1" + green + "]" + white + " Instagram" + green + " [" + white + "12" + green + "]" + white + " Paypal")
print(green + "[" + white + "2" + green + "]" + white + " Facebook" + green + " [" + white + "13" + green + "]" + white + " Discord")
print(green + "[" + white + "3" + green + "]" + white + " Gmail" + green + " [" + white + "14" + green + "]" + white + " Spotify")
print(green + "[" + white + "4" + green + "]" + white + " Gmail (simple)" + green + " [" + white + "15" + green + "]" + white + " Blockchain")
print(green + "[" + white + "5" + green + "]" + white + " Twitter" + green + " [" + white + "16" + green + "]" + white + " RiotGames")
print(green + "[" + white + "6" + green + "]" + white + " Snapchat" + green + " [" + white + "17" + green + "]" + white + " Rockstar")
print(green + "[" + white + "7" + green + "]" + white + " Snapchat (simple)" + green + " [" + white + "18" + green + "]" + white + " AskFM")
print(green + "[" + white + "8" + green + "]" + white + " Steam" + green + " [" + white + "19" + green + "]" + white + " 000Webhost")
print(green + "[" + white + "9" + green + "]" + white + " Dropbox" + green)
print(green + "[" + white + "10" + green + "]" + white + " Linkedin" + green + " [" + white + "21" + green + "]" + white + " Gamehag")
print(green + "[" + white + "11" + green + "]" + white + " Playstation" + green + " [" + white + "22" + green + "]" + white + " Mega")
print(green + "-----------------------------------------------------------------------")
print(green + "[" + white + "00" + green + "]" + red + " EXIT")
def Welcome():
os.system("clear")
| 2.328125 | 2 |
automatoes/authorize.py | candango/automatoes | 13 | 2245 | <filename>automatoes/authorize.py
#!/usr/bin/env python
#
# Copyright 2019-2020 <NAME>
# Copyright 2016-2017 <NAME> under MIT License
#
# 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.
"""
The domain authorization command.
"""
from . import get_version
from .acme import AcmeV2
from .crypto import generate_jwk_thumbprint
from .errors import AutomatoesError
from .model import Order
from cartola import fs, sysexits
import hashlib
import os
import sys
def create_order(acme, domains, method, order_file):
order = acme.new_order(domains, method)
update_order(order, order_file)
return order
def update_order(order, order_file):
fs.write(order_file, order.serialize().decode())
def clean_http_challenges(files):
# Clean up created files
for path in files:
try:
os.remove(path)
except:
print("Couldn't delete http challenge file {}".format(path))
def clean_challenge_file(challenge_file):
try:
os.remove(challenge_file)
except:
print("Couldn't delete challenge file {}".format(challenge_file))
def authorize(server, paths, account, domains, method, verbose=False):
print("Candango Automatoes {}. Manuale replacement.\n\n".format(
get_version()))
current_path = paths['current']
orders_path = paths['orders']
domains_hash = hashlib.sha256(
"_".join(domains).encode('ascii')).hexdigest()
order_path = os.path.join(orders_path, domains_hash)
order_file = os.path.join(order_path, "order.json".format(domains_hash))
if not os.path.exists(orders_path):
if verbose:
print("Orders path not found creating it at {}."
"".format(orders_path))
os.mkdir(orders_path)
os.chmod(orders_path, 0o770)
else:
if verbose:
print("Orders path found at {}.".format(orders_path))
if not os.path.exists(order_path):
if verbose:
print("Current order {} path not found creating it at orders "
"path.\n".format(domains_hash))
os.mkdir(order_path)
os.chmod(order_path, 0o770)
else:
if verbose:
print("Current order {} path found at orders path.\n".format(
domains_hash))
method = method
acme = AcmeV2(server, account)
try:
print("Authorizing {}.\n".format(", ".join(domains)))
# Creating orders for domains if not existent
if not os.path.exists(order_file):
if verbose:
print(" Order file not found creating it.")
order = create_order(acme, domains, method, order_file)
else:
if verbose:
print(" Found order file. Querying ACME server for current "
"status.")
order = Order.deserialize(fs.read(order_file))
try:
server_order = acme.query_order(order)
order.contents = server_order.contents
except:
print(" WARNING: Old order. Setting it as expired.\n")
order.contents['status'] = "expired"
update_order(order, order_file)
if not order.expired and not order.invalid:
if order.contents['status'] == 'valid':
print(" Order is valid and expires at {}. Please run "
"the issue "
"command.\n".format(order.contents['expires']))
print(" {} domain(s) authorized. Let's Encrypt!".format(
len(domains)))
sys.exit(sysexits.EX_OK)
else:
if verbose:
print(" Order still pending and expires "
"at {}.\n".format(order.contents['expires']))
else:
if order.invalid:
print(" WARNING: Invalid order, renewing it.\n Just "
"continue with the authorization when all "
"verifications are in place.\n")
else:
print(" WARNING: Expired order. Renewing order.\n")
os.remove(order_file)
order = create_order(acme, domains, method, order_file)
update_order(order, order_file)
pending_challenges = []
for challenge in acme.get_order_challenges(order):
print(" Requesting challenge for {}.".format(challenge.domain))
if challenge.status == 'valid':
print(" {} is already authorized until {}.".format(
challenge.domain, challenge.expires))
continue
else:
challenge_file = os.path.join(order_path, challenge.file_name)
if verbose:
print(" Creating challenge file {}.\n".format(
challenge.file_name))
fs.write(challenge_file, challenge.serialize().decode())
pending_challenges.append(challenge)
# Quit if nothing to authorize
if not pending_challenges:
print("\nAll domains are already authorized, exiting.")
sys.exit(sysexits.EX_OK)
files = set()
if method == 'dns':
print("\n DNS verification required. Make sure these TXT records"
" are in place:\n")
for challenge in pending_challenges:
print(" _acme-challenge.{}. IN TXT "
"\"{}\"".format(challenge.domain, challenge.key))
elif method == 'http':
print("\n HTTP verification required. Make sure these files are "
"in place:\n")
for challenge in pending_challenges:
token = challenge.contents['token']
# path sanity check
assert (token and os.path.sep not in token and '.' not in
token)
files.add(token)
fs.write(
os.path.join(current_path, token),
"%s.%s" % (token,
generate_jwk_thumbprint(account.key))
)
print(" http://{}/.well-known/acme-challenge/{}".format(
challenge.domain, token))
print("\n The necessary files have been written to the current "
"directory.\n")
# Wait for the user to complete the challenges
input("\nPress Enter to continue.\n")
# Validate challenges
done, failed, pending = set(), set(), set()
for challenge in pending_challenges:
print(" {}: waiting for verification. Checking in 5 "
"seconds.".format(challenge.domain))
response = acme.verify_order_challenge(challenge, 5, 1)
if response['status'] == "valid":
print(" {}: OK! Authorization lasts until {}.".format(
challenge.domain, challenge.expires))
done.add(challenge.domain)
elif response['status'] == 'invalid':
print(" {}: {} ({})".format(
challenge.domain,
response['error']['detail'],
response['error']['type'])
)
failed.add(challenge.domain)
break
else:
print("{}: Pending!".format(challenge.domain))
pending.add(challenge.domain)
break
challenge_file = os.path.join(order_path, challenge.file_name)
# Print results
if failed:
print(" {} domain(s) authorized, {} failed.".format(
len(done),
len(failed),
))
print(" Authorized: {}".format(' '.join(done) or "N/A"))
print(" Failed: {}".format(' '.join(failed)))
print(" WARNING: The current order will be invalidated. "
"Try again.")
if verbose:
print(" Deleting invalid challenge file {}.\n".format(
challenge.file_name))
clean_challenge_file(challenge_file)
os.remove(order_file)
os.rmdir(order_path)
if method == 'http':
print(files)
clean_http_challenges(files)
sys.exit(sysexits.EX_FATAL_ERROR)
else:
if pending:
print(" {} domain(s) authorized, {} pending.".format(
len(done),
len(pending)))
print(" Authorized: {}".format(' '.join(done) or "N/A"))
print(" Pending: {}".format(' '.join(pending)))
print(" Try again.")
sys.exit(sysexits.EX_CANNOT_EXECUTE)
else:
if verbose:
print(" Deleting valid challenge file {}.".format(
challenge.file_name))
clean_challenge_file(challenge_file)
if verbose:
print(" Querying ACME server for current status.\n")
server_order = acme.query_order(order)
order.contents = server_order.contents
update_order(order, order_file)
print(" {} domain(s) authorized. Let's Encrypt!".format(
len(done)))
if method == 'http':
clean_http_challenges(files)
sys.exit(sysexits.EX_OK)
except IOError as e:
print("A connection or service error occurred. Aborting.")
raise AutomatoesError(e)
| 2.359375 | 2 |
rllib/agents/dqn/simple_q_torch_policy.py | jamesliu/ray | 3 | 2246 | <gh_stars>1-10
"""PyTorch policy class used for Simple Q-Learning"""
import logging
from typing import Dict, Tuple
import gym
import ray
from ray.rllib.agents.dqn.simple_q_tf_policy import (
build_q_models, compute_q_values, get_distribution_inputs_and_class)
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.torch.torch_action_dist import TorchCategorical, \
TorchDistributionWrapper
from ray.rllib.policy import Policy
from ray.rllib.policy.policy_template import build_policy_class
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.policy.torch_policy import TorchPolicy
from ray.rllib.utils.annotations import override
from ray.rllib.utils.framework import try_import_torch
from ray.rllib.utils.torch_utils import concat_multi_gpu_td_errors, huber_loss
from ray.rllib.utils.typing import TensorType, TrainerConfigDict
torch, nn = try_import_torch()
F = None
if nn:
F = nn.functional
logger = logging.getLogger(__name__)
class TargetNetworkMixin:
"""Assign the `update_target` method to the SimpleQTorchPolicy
The function is called every `target_network_update_freq` steps by the
master learner.
"""
def __init__(self):
# Hard initial update from Q-net(s) to target Q-net(s).
self.update_target()
def update_target(self):
# Update_target_fn will be called periodically to copy Q network to
# target Q networks.
state_dict = self.model.state_dict()
for target in self.target_models.values():
target.load_state_dict(state_dict)
@override(TorchPolicy)
def set_weights(self, weights):
# Makes sure that whenever we restore weights for this policy's
# model, we sync the target network (from the main model)
# at the same time.
TorchPolicy.set_weights(self, weights)
self.update_target()
def build_q_model_and_distribution(
policy: Policy, obs_space: gym.spaces.Space,
action_space: gym.spaces.Space,
config: TrainerConfigDict) -> Tuple[ModelV2, TorchDistributionWrapper]:
return build_q_models(policy, obs_space, action_space, config), \
TorchCategorical
def build_q_losses(policy: Policy, model, dist_class,
train_batch: SampleBatch) -> TensorType:
"""Constructs the loss for SimpleQTorchPolicy.
Args:
policy (Policy): The Policy to calculate the loss for.
model (ModelV2): The Model to calculate the loss for.
dist_class (Type[ActionDistribution]): The action distribution class.
train_batch (SampleBatch): The training data.
Returns:
TensorType: A single loss tensor.
"""
target_model = policy.target_models[model]
# q network evaluation
q_t = compute_q_values(
policy,
model,
train_batch[SampleBatch.CUR_OBS],
explore=False,
is_training=True)
# target q network evalution
q_tp1 = compute_q_values(
policy,
target_model,
train_batch[SampleBatch.NEXT_OBS],
explore=False,
is_training=True)
# q scores for actions which we know were selected in the given state.
one_hot_selection = F.one_hot(train_batch[SampleBatch.ACTIONS].long(),
policy.action_space.n)
q_t_selected = torch.sum(q_t * one_hot_selection, 1)
# compute estimate of best possible value starting from state at t + 1
dones = train_batch[SampleBatch.DONES].float()
q_tp1_best_one_hot_selection = F.one_hot(
torch.argmax(q_tp1, 1), policy.action_space.n)
q_tp1_best = torch.sum(q_tp1 * q_tp1_best_one_hot_selection, 1)
q_tp1_best_masked = (1.0 - dones) * q_tp1_best
# compute RHS of bellman equation
q_t_selected_target = (train_batch[SampleBatch.REWARDS] +
policy.config["gamma"] * q_tp1_best_masked)
# Compute the error (Square/Huber).
td_error = q_t_selected - q_t_selected_target.detach()
loss = torch.mean(huber_loss(td_error))
# Store values for stats function in model (tower), such that for
# multi-GPU, we do not override them during the parallel loss phase.
model.tower_stats["loss"] = loss
# TD-error tensor in final stats
# will be concatenated and retrieved for each individual batch item.
model.tower_stats["td_error"] = td_error
return loss
def stats_fn(policy: Policy, batch: SampleBatch) -> Dict[str, TensorType]:
return {"loss": torch.mean(torch.stack(policy.get_tower_stats("loss")))}
def extra_action_out_fn(policy: Policy, input_dict, state_batches, model,
action_dist) -> Dict[str, TensorType]:
"""Adds q-values to the action out dict."""
return {"q_values": policy.q_values}
def setup_late_mixins(policy: Policy, obs_space: gym.spaces.Space,
action_space: gym.spaces.Space,
config: TrainerConfigDict) -> None:
"""Call all mixin classes' constructors before SimpleQTorchPolicy
initialization.
Args:
policy (Policy): The Policy object.
obs_space (gym.spaces.Space): The Policy's observation space.
action_space (gym.spaces.Space): The Policy's action space.
config (TrainerConfigDict): The Policy's config.
"""
TargetNetworkMixin.__init__(policy)
SimpleQTorchPolicy = build_policy_class(
name="SimpleQPolicy",
framework="torch",
loss_fn=build_q_losses,
get_default_config=lambda: ray.rllib.agents.dqn.simple_q.DEFAULT_CONFIG,
stats_fn=stats_fn,
extra_action_out_fn=extra_action_out_fn,
after_init=setup_late_mixins,
make_model_and_action_dist=build_q_model_and_distribution,
mixins=[TargetNetworkMixin],
action_distribution_fn=get_distribution_inputs_and_class,
extra_learn_fetches_fn=concat_multi_gpu_td_errors,
)
| 1.992188 | 2 |
viphoneme/T2IPA.py | NoahDrisort/ViSV2TTS | 1 | 2247 | #Grapheme
Rime_tone=[ "a","ă","â","e","ê","i","o","ô","ơ","u","ư","y","iê","oa","oă","oe","oo","uâ","uê","uô","uơ","uy","ươ","uyê","yê", #blank
"á","ắ","ấ","é","ế","í","ó","ố","ớ","ú","ứ","ý","iế","óa","oắ","óe","oó","uấ","uế","uố","ướ","úy","ướ","uyế","yế", #grave
"oá", "oé","óo", "uý",
"à","ằ","ầ","è","ề","ì","ò","ồ","ờ","ù","ừ","ỳ","iề","òa","oằ","òe","oò","uầ","uề","uồ","ườ","ùy","ườ","uyề","yề", #acute
"oà", "oè","òo", "uỳ",
"ả","ẳ","ẩ","ẻ","ể","ỉ","ỏ","ổ","ở","ủ","ử","ỷ","iể","ỏa","oẳ","ỏe","oỏ","uẩ","uể","uổ","ưở","ủy","ưở","uyể","yể", #hook
"oả", "oẻ","ỏo", "uỷ",
"ã","ẵ","ẫ","ẽ","ễ","ĩ","õ","ỗ","ỡ","ũ","ữ","ỹ","iễ","õa","oẵ","õe","oõ","uẫ","uễ","uỗ","ưỡ","ũy","ưỡ","uyễ","yễ", #tilde
"oã", "oẽ","õo", "uỹ",
"ạ","ặ","ậ","ẹ","ệ","ị","ọ","ộ","ợ","ụ","ự","ỵ","iệ","ọa","oặ","ọe","oọ","uậ","uệ","uệ","ượ","ụy","ượ","uyệ","yệ", #dot
"oạ", "oẹ","ọo", "uỵ"]
Onset=["b","d","h","l","m","n","p","r","s","t","v","x","đ","p",
"tr", "th", "ch", "ph","nh","kh","gi","qu",
"ngh","ng","gh","g","k","c"]
#coding: utf-8
#Custom phoneme follow the https://vi.wikipedia.org/wiki/%C3%82m_v%E1%BB%8B_h%E1%BB%8Dc_ti%E1%BA%BFng_Vi%E1%BB%87t
#Improve pronoune between N C S
Cus_onsets = { u'b' : u'b', u't' : u't', u'th' : u'tʰ', u'đ' : u'd', u'ch' : u'c',
u'kh' : u'x', u'g' : u'ɣ', u'l' : u'l', u'm' : u'm', u'n': u'n',
u'ngh': u'ŋ', u'nh' : u'ɲ', u'ng' : u'ŋ', u'ph' : u'f', u'v' : u'v',
u'x' : u's', u'd' : u'z', u'h' : u'h', u'p' : u'p', u'qu' : u'kw',
u'gi' : u'j', u'tr' : u'ʈ', u'k' : u'k', u'c' : u'k', u'gh' : u'ɣ',
u'r' : u'ʐ', u's' : u'ʂ', u'gi': u'j'}
Cus_nuclei = { u'a' : u'a', u'á' : u'a', u'à' : u'a', u'ả' : u'a', u'ã' : u'a', u'ạ' : u'a',
u'â' : u'ɤ̆', u'ấ' : u'ɤ̆', u'ầ' : u'ɤ̆', u'ẩ' : u'ɤ̆', u'ẫ' : u'ɤ̆', u'ậ' : u'ɤ̆',
u'ă' : u'ă', u'ắ' : u'ă', u'ằ' : u'ă', u'ẳ' : u'ă', u'ẵ' : u'ă', u'ặ' : u'ă',
u'e' : u'ɛ', u'é' : u'ɛ', u'è' : u'ɛ', u'ẻ' : u'ɛ', u'ẽ' : u'ɛ', u'ẹ' : u'ɛ',
u'ê' : u'e', u'ế' : u'e', u'ề' : u'e', u'ể' : u'e', u'ễ' : u'e', u'ệ' : u'e',
u'i' : u'i', u'í' : u'i', u'ì' : u'i', u'ỉ' : u'i', u'ĩ' : u'i', u'ị' : u'i',
u'o' : u'ɔ', u'ó' : u'ɔ', u'ò' : u'ɔ', u'ỏ' : u'ɔ', u'õ' : u'ɔ', u'ọ' : u'ɔ',
u'ô' : u'o', u'ố' : u'o', u'ồ' : u'o', u'ổ' : u'o', u'ỗ' : u'o', u'ộ' : u'o',
u'ơ' : u'ɤ', u'ớ' : u'ɤ', u'ờ' : u'ɤ', u'ở' : u'ɤ', u'ỡ' : u'ɤ', u'ợ' : u'ɤ',
u'u' : u'u', u'ú' : u'u', u'ù' : u'u', u'ủ' : u'u', u'ũ' : u'u', u'ụ' : u'u',
u'ư' : u'ɯ', u'ứ' : u'ɯ', u'ừ' : u'ɯ', u'ử' : u'ɯ', u'ữ' : u'ɯ', u'ự' : u'ɯ',
u'y' : u'i', u'ý' : u'i', u'ỳ' : u'i', u'ỷ' : u'i', u'ỹ' : u'i', u'ỵ' : u'i',
u'eo' : u'eo', u'éo' : u'eo', u'èo' : u'eo', u'ẻo' : u'eo', u'ẽo': u'eo', u'ẹo' : u'eo',
u'êu' : u'ɛu', u'ếu' : u'ɛu', u'ều' : u'ɛu', u'ểu' : u'ɛu', u'ễu': u'ɛu', u'ệu' : u'ɛu',
u'ia' : u'iə', u'ía' : u'iə', u'ìa' : u'iə', u'ỉa' : u'iə', u'ĩa' : u'iə', u'ịa' : u'iə',
u'ia' : u'iə', u'iá' : u'iə', u'ià' : u'iə', u'iả' : u'iə', u'iã' : u'iə', u'iạ' : u'iə',
u'iê' : u'iə', u'iế' : u'iə', u'iề' : u'iə', u'iể' : u'iə', u'iễ' : u'iə', u'iệ' : u'iə',
u'oo' : u'ɔ', u'óo' : u'ɔ', u'òo' : u'ɔ', u'ỏo' : u'ɔ', u'õo' : u'ɔ', u'ọo' : u'ɔ',
u'oo' : u'ɔ', u'oó' : u'ɔ', u'oò' : u'ɔ', u'oỏ' : u'ɔ', u'oõ' : u'ɔ', u'oọ' : u'ɔ',
u'ôô' : u'o', u'ốô' : u'o', u'ồô' : u'o', u'ổô' : u'o', u'ỗô' : u'o', u'ộô' : u'o',
u'ôô' : u'o', u'ôố' : u'o', u'ôồ' : u'o', u'ôổ' : u'o', u'ôỗ' : u'o', u'ôộ' : u'o',
u'ua' : u'uə', u'úa' : u'uə', u'ùa' : u'uə', u'ủa' : u'uə', u'ũa' : u'uə', u'ụa' : u'uə',
u'uô' : u'uə', u'uố' : u'uə', u'uồ' : u'uə', u'uổ' : u'uə', u'uỗ' : u'uə', u'uộ' : u'uə',
u'ưa' : u'ɯə', u'ứa' : u'ɯə', u'ừa' : u'ɯə', u'ửa' : u'ɯə', u'ữa' : u'ɯə', u'ựa' : u'ɯə',
u'ươ' : u'ɯə', u'ướ' : u'ɯə', u'ườ' : u'ɯə', u'ưở' : u'ɯə', u'ưỡ' : u'ɯə', u'ượ' : u'ɯə',
u'yê' : u'iɛ', u'yế' : u'iɛ', u'yề' : u'iɛ', u'yể' : u'iɛ', u'yễ' : u'iɛ', u'yệ' : u'iɛ',
u'uơ' : u'uə', u'uở' : u'uə', u'uờ': u'uə', u'uở' : u'uə', u'uỡ' : u'uə', u'uợ' : u'uə',
}
Cus_offglides = { u'ai' : u'aj', u'ái' : u'aj', u'ài' : u'aj', u'ải' : u'aj', u'ãi' : u'aj', u'ại' : u'aj',
u'ay' : u'ăj', u'áy' : u'ăj', u'ày' : u'ăj', u'ảy' : u'ăj', u'ãy' : u'ăj', u'ạy' : u'ăj',
u'ao' : u'aw', u'áo' : u'aw', u'ào' : u'aw', u'ảo' : u'aw', u'ão' : u'aw', u'ạo' : u'aw',
u'au' : u'ăw', u'áu' : u'ăw', u'àu' : u'ăw', u'ảu' : u'ăw', u'ãu' : u'ăw', u'ạu' : u'ăw',
u'ây' : u'ɤ̆j', u'ấy' : u'ɤ̆j', u'ầy' : u'ɤ̆j', u'ẩy' : u'ɤ̆j', u'ẫy' : u'ɤ̆j', u'ậy' : u'ɤ̆j',
u'âu' : u'ɤ̆w', u'ấu' : u'ɤ̆w', u'ầu': u'ɤ̆w', u'ẩu' : u'ɤ̆w', u'ẫu' : u'ɤ̆w', u'ậu' : u'ɤ̆w',
u'eo' : u'ew', u'éo' : u'ew', u'èo' : u'ew', u'ẻo' : u'ew', u'ẽo' : u'ew', u'ẹo' : u'ew',
u'iu' : u'iw', u'íu' : u'iw', u'ìu' : u'iw', u'ỉu' : u'iw', u'ĩu' : u'iw', u'ịu' : u'iw',
u'oi' : u'ɔj', u'ói' : u'ɔj', u'òi' : u'ɔj', u'ỏi' : u'ɔj', u'õi' : u'ɔj', u'ọi' : u'ɔj',
u'ôi' : u'oj', u'ối' : u'oj', u'ồi' : u'oj', u'ổi' : u'oj', u'ỗi' : u'oj', u'ội' : u'oj',
u'ui' : u'uj', u'úi' : u'uj', u'ùi' : u'uj', u'ủi' : u'uj', u'ũi' : u'uj', u'ụi' : u'uj',
#u'uy' : u'uj', u'úy' : u'uj', u'ùy' : u'uj', u'ủy' : u'uj', u'ũy' : u'uj', u'ụy' : u'uj',
u'uy' : u'ʷi', u'úy' : u'uj', u'ùy' : u'uj', u'ủy' : u'uj', u'ũy' : u'uj', u'ụy' : u'uj',
#thay để hạn chế trùng âm
u'uy' : u'ʷi', u'uý' : u'ʷi', u'uỳ' : u'ʷi', u'uỷ' : u'ʷi', u'uỹ' : u'ʷi', u'uỵ' : u'ʷi',
u'ơi' : u'ɤj', u'ới' : u'ɤj', u'ời' : u'ɤj', u'ởi' : u'ɤj', u'ỡi' : u'ɤj', u'ợi' : u'ɤj',
u'ưi' : u'ɯj', u'ứi' : u'ɯj', u'ừi' : u'ɯj', u'ửi' : u'ɯj', u'ữi' : u'ɯj', u'ựi' : u'ɯj',
u'ưu' : u'ɯw', u'ứu' : u'ɯw', u'ừu' : u'ɯw', u'ửu' : u'ɯw', u'ữu' : u'ɯw', u'ựu' : u'ɯw',
u'iêu' : u'iəw', u'iếu' : u'iəw', u'iều' : u'iəw', u'iểu' : u'iəw', u'iễu' : u'iəw', u'iệu' : u'iəw',
u'yêu' : u'iəw', u'yếu' : u'iəw', u'yều' : u'iəw', u'yểu' : u'iəw', u'yễu' : u'iəw', u'yệu' : u'iəw',
u'uôi' : u'uəj', u'uối' : u'uəj', u'uồi' : u'uəj', u'uổi' : u'uəj', u'uỗi' : u'uəj', u'uội' : u'uəj',
u'ươi' : u'ɯəj', u'ưới' : u'ɯəj', u'ười' : u'ɯəj', u'ưởi' : u'ɯəj', u'ưỡi' : u'ɯəj', u'ượi' : u'ɯəj',
u'ươu' : u'ɯəw', u'ướu' : u'ɯəw', u'ườu' : u'ɯəw', u'ưởu' : u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw'
}
#Các âm vòng ở đây i chang không vòm: không có w ở trước => Try to add ʷ
Cus_onglides = { u'oa' : u'ʷa', u'oá' : u'ʷa', u'oà' : u'ʷa', u'oả' : u'ʷa', u'oã' : u'ʷa', u'oạ' : u'ʷa',
u'óa' : u'ʷa', u'òa' : u'ʷa', u'ỏa' : u'ʷa', u'õa' : u'ʷa', u'ọa' : u'ʷa',
u'oă' : u'ʷă', u'oắ' : u'ʷă', u'oằ' : u'ʷă', u'oẳ' : u'ʷă', u'oẵ' : u'ʷă', u'oặ' : u'ʷă',
u'oe' : u'ʷɛ', u'oé' : u'ʷɛ', u'oè' : u'ʷɛ', u'oẻ' : u'ʷɛ', u'oẽ' : u'ʷɛ', u'oẹ' : u'ʷɛ',
u'oe' : u'ʷɛ', u'óe' : u'ʷɛ', u'òe' : u'ʷɛ', u'ỏe' : u'ʷɛ', u'õe' : u'ʷɛ', u'ọe' : u'ʷɛ',
u'ua' : u'ʷa', u'uá' : u'ʷa', u'uà' : u'ʷa', u'uả' : u'ʷa', u'uã' : u'ʷa', u'uạ' : u'ʷa',
u'uă' : u'ʷă', u'uắ' : u'ʷă', u'uằ' : u'ʷă', u'uẳ' : u'ʷă', u'uẵ' : u'ʷă', u'uặ' : u'ʷă',
u'uâ' : u'ʷɤ̆', u'uấ' : u'ʷɤ̆', u'uầ' : u'ʷɤ̆', u'uẩ' : u'ʷɤ̆', u'uẫ' : u'ʷɤ̆', u'uậ' : u'ʷɤ̆',
u'ue' : u'ʷɛ', u'ué' : u'ʷɛ', u'uè' : u'ʷɛ', u'uẻ' : u'ʷɛ', u'uẽ' : u'ʷɛ', u'uẹ' : u'ʷɛ',
u'uê' : u'ʷe', u'uế' : u'ʷe', u'uề' : u'ʷe', u'uể' : u'ʷe', u'uễ' : u'ʷe', u'uệ' : u'ʷe',
u'uơ' : u'ʷɤ', u'uớ' : u'ʷɤ', u'uờ' : u'ʷɤ', u'uở' : u'ʷɤ', u'uỡ' : u'ʷɤ', u'uợ' : u'ʷɤ',
u'uy' : u'ʷi', u'uý' : u'ʷi', u'uỳ' : u'ʷi', u'uỷ' : u'ʷi', u'uỹ' : u'ʷi', u'uỵ' : u'ʷi',
u'uya' : u'ʷiə', u'uyá' : u'ʷiə', u'uyà' : u'ʷiə', u'uyả' : u'ʷiə', u'uyã' : u'ʷiə', u'uyạ' : u'ʷiə',
u'uyê' : u'ʷiə', u'uyế' : u'ʷiə', u'uyề' : u'ʷiə', u'uyể' : u'ʷiə', u'uyễ' : u'ʷiə', u'uyệ' : u'ʷiə',
u'uyu' : u'ʷiu', u'uyú' : u'ʷiu', u'uyù' : u'ʷiu', u'uyủ' : u'ʷiu', u'uyũ' : u'ʷiu', u'uyụ' : u'ʷiu',
u'uyu' : u'ʷiu', u'uýu' : u'ʷiu', u'uỳu' : u'ʷiu', u'uỷu' : u'ʷiu', u'uỹu' : u'ʷiu', u'uỵu' : u'ʷiu',
u'oen' : u'ʷen', u'oén' : u'ʷen', u'oèn' : u'ʷen', u'oẻn' : u'ʷen', u'oẽn' : u'ʷen', u'oẹn' : u'ʷen',
u'oet' : u'ʷet', u'oét' : u'ʷet', u'oèt' : u'ʷet', u'oẻt' : u'ʷet', u'oẽt' : u'ʷet', u'oẹt' : u'ʷet'
}
Cus_onoffglides = { u'oe' : u'ɛj', u'oé' : u'ɛj', u'oè' : u'ɛj', u'oẻ' : u'ɛj', u'oẽ' : u'ɛj', u'oẹ' : u'ɛj',
u'oai' : u'aj', u'oái' : u'aj', u'oài' : u'aj', u'oải' : u'aj', u'oãi' : u'aj', u'oại' : u'aj',
u'oay' : u'ăj', u'oáy' : u'ăj', u'oày' : u'ăj', u'oảy' : u'ăj', u'oãy' : u'ăj', u'oạy' : u'ăj',
u'oao' : u'aw', u'oáo' : u'aw', u'oào' : u'aw', u'oảo' : u'aw', u'oão' : u'aw', u'oạo' : u'aw',
u'oeo' : u'ew', u'oéo' : u'ew', u'oèo' : u'ew', u'oẻo' : u'ew', u'oẽo' : u'ew', u'oẹo' : u'ew',
u'oeo' : u'ew', u'óeo' : u'ew', u'òeo' : u'ew', u'ỏeo' : u'ew', u'õeo' : u'ew', u'ọeo' : u'ew',
u'ueo' : u'ew', u'uéo' : u'ew', u'uèo' : u'ew', u'uẻo' : u'ew', u'uẽo' : u'ew', u'uẹo' : u'ew',
u'uai' : u'aj', u'uái' : u'aj', u'uài' : u'aj', u'uải' : u'aj', u'uãi' : u'aj', u'uại' : u'aj',
u'uay' : u'ăj', u'uáy' : u'ăj', u'uày' : u'ăj', u'uảy' : u'ăj', u'uãy' : u'ăj', u'uạy' : u'ăj',
u'uây' : u'ɤ̆j', u'uấy' : u'ɤ̆j', u'uầy' : u'ɤ̆j', u'uẩy' : u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j'
}
Cus_codas = { u'p' : u'p', u't' : u't', u'c' : u'k', u'm' : u'm', u'n' : u'n', u'ng' : u'ŋ', u'nh' : u'ɲ', u'ch' : u'tʃ' }
Cus_tones_p = { u'á' : 5, u'à' : 2, u'ả' : 4, u'ã' : 3, u'ạ' : 6,
u'ấ' : 5, u'ầ' : 2, u'ẩ' : 4, u'ẫ' : 3, u'ậ' : 6,
u'ắ' : 5, u'ằ' : 2, u'ẳ' : 4, u'ẵ' : 3, u'ặ' : 6,
u'é' : 5, u'è' : 2, u'ẻ' : 4, u'ẽ' : 3, u'ẹ' : 6,
u'ế' : 5, u'ề' : 2, u'ể' : 4, u'ễ' : 3, u'ệ' : 6,
u'í' : 5, u'ì' : 2, u'ỉ' : 4, u'ĩ' : 3, u'ị' : 6,
u'ó' : 5, u'ò' : 2, u'ỏ' : 4, u'õ' : 3, u'ọ' : 6,
u'ố' : 5, u'ồ' : 2, u'ổ' : 4, u'ỗ' : 3, u'ộ' : 6,
u'ớ' : 5, u'ờ' : 2, u'ở' : 4, u'ỡ' : 3, u'ợ' : 6,
u'ú' : 5, u'ù' : 2, u'ủ' : 4, u'ũ' : 3, u'ụ' : 6,
u'ứ' : 5, u'ừ' : 2, u'ử' : 4, u'ữ' : 3, u'ự' : 6,
u'ý' : 5, u'ỳ' : 2, u'ỷ' : 4, u'ỹ' : 3, u'ỵ' : 6,
}
Cus_gi = { u'gi' : u'zi', u'gí': u'zi', u'gì' : u'zi', u'gì' : u'zi', u'gĩ' : u'zi', u'gị' : u'zi'}
Cus_qu = {u'quy' : u'kwi', u'qúy' : u'kwi', u'qùy' : u'kwi', u'qủy' : u'kwi', u'qũy' : u'kwi', u'qụy' : u'kwi'}
#######################################################
# North
# #coding: utf-8
N_onsets = { u'b' : u'b', u't' : u't', u'th' : u'tʰ', u'đ' : u'd', u'ch' : u'c',
u'kh' : u'x', u'g' : u'ɣ', u'l' : u'l', u'm' : u'm', u'n': u'n',
u'ngh': u'ŋ', u'nh' : u'ɲ', u'ng' : u'ŋ', u'ph' : u'f', u'v' : u'v',
u'x' : u's', u'd' : u'z', u'h' : u'h', u'p' : u'p', u'qu' : u'kw',
u'gi' : u'z', u'tr' : u'c', u'k' : u'k', u'c' : u'k', u'gh' : u'ɣ',
u'r' : u'z', u's' : u's', u'gi': u'z'}
N_nuclei = { u'a' : u'a', u'á' : u'a', u'à' : u'a', u'ả' : u'a', u'ã' : u'a', u'ạ' : u'a',
u'â' : u'ɤ̆', u'ấ' : u'ɤ̆', u'ầ' : u'ɤ̆', u'ẩ' : u'ɤ̆', u'ẫ' : u'ɤ̆', u'ậ' : u'ɤ̆',
u'ă' : u'ă', u'ắ' : u'ă', u'ằ' : u'ă', u'ẳ' : u'ă', u'ẵ' : u'ă', u'ặ' : u'ă',
u'e' : u'ɛ', u'é' : u'ɛ', u'è' : u'ɛ', u'ẻ' : u'ɛ', u'ẽ' : u'ɛ', u'ẹ' : u'ɛ',
u'ê' : u'e', u'ế' : u'e', u'ề' : u'e', u'ể' : u'e', u'ễ' : u'e', u'ệ' : u'e',
u'i' : u'i', u'í' : u'i', u'ì' : u'i', u'ỉ' : u'i', u'ĩ' : u'i', u'ị' : u'i',
u'o' : u'ɔ', u'ó' : u'ɔ', u'ò' : u'ɔ', u'ỏ' : u'ɔ', u'õ' : u'ɔ', u'ọ' : u'ɔ',
u'ô' : u'o', u'ố' : u'o', u'ồ' : u'o', u'ổ' : u'o', u'ỗ' : u'o', u'ộ' : u'o',
u'ơ' : u'ɤ', u'ớ' : u'ɤ', u'ờ' : u'ɤ', u'ở' : u'ɤ', u'ỡ' : u'ɤ', u'ợ' : u'ɤ',
u'u' : u'u', u'ú' : u'u', u'ù' : u'u', u'ủ' : u'u', u'ũ' : u'u', u'ụ' : u'u',
u'ư' : u'ɯ', u'ứ' : u'ɯ', u'ừ' : u'ɯ', u'ử' : u'ɯ', u'ữ' : u'ɯ', u'ự' : u'ɯ',
u'y' : u'i', u'ý' : u'i', u'ỳ' : u'i', u'ỷ' : u'i', u'ỹ' : u'i', u'ỵ' : u'i',
u'eo' : u'eo', u'éo' : u'eo', u'èo' : u'eo', u'ẻo' : u'eo', u'ẽo': u'eo', u'ẹo' : u'eo',
u'êu' : u'ɛu', u'ếu' : u'ɛu', u'ều' : u'ɛu', u'ểu' : u'ɛu', u'ễu': u'ɛu', u'ệu' : u'ɛu',
u'ia' : u'iə', u'ía' : u'iə', u'ìa' : u'iə', u'ỉa' : u'iə', u'ĩa' : u'iə', u'ịa' : u'iə',
u'ia' : u'iə', u'iá' : u'iə', u'ià' : u'iə', u'iả' : u'iə', u'iã' : u'iə', u'iạ' : u'iə',
u'iê' : u'iə', u'iế' : u'iə', u'iề' : u'iə', u'iể' : u'iə', u'iễ' : u'iə', u'iệ' : u'iə',
u'oo' : u'ɔ', u'óo' : u'ɔ', u'òo' : u'ɔ', u'ỏo' : u'ɔ', u'õo' : u'ɔ', u'ọo' : u'ɔ',
u'oo' : u'ɔ', u'oó' : u'ɔ', u'oò' : u'ɔ', u'oỏ' : u'ɔ', u'oõ' : u'ɔ', u'oọ' : u'ɔ',
u'ôô' : u'o', u'ốô' : u'o', u'ồô' : u'o', u'ổô' : u'o', u'ỗô' : u'o', u'ộô' : u'o',
u'ôô' : u'o', u'ôố' : u'o', u'ôồ' : u'o', u'ôổ' : u'o', u'ôỗ' : u'o', u'ôộ' : u'o',
u'ua' : u'uə', u'úa' : u'uə', u'ùa' : u'uə', u'ủa' : u'uə', u'ũa' : u'uə', u'ụa' : u'uə',
u'uô' : u'uə', u'uố' : u'uə', u'uồ' : u'uə', u'uổ' : u'uə', u'uỗ' : u'uə', u'uộ' : u'uə',
u'ưa' : u'ɯə', u'ứa' : u'ɯə', u'ừa' : u'ɯə', u'ửa' : u'ɯə', u'ữa' : u'ɯə', u'ựa' : u'ɯə',
u'ươ' : u'ɯə', u'ướ' : u'ɯə', u'ườ' : u'ɯə', u'ưở' : u'ɯə', u'ưỡ' : u'ɯə', u'ượ' : u'ɯə',
u'yê' : u'iɛ', u'yế' : u'iɛ', u'yề' : u'iɛ', u'yể' : u'iɛ', u'yễ' : u'iɛ', u'yệ' : u'iɛ',
u'uơ' : u'uə', u'uở' : u'uə', u'uờ': u'uə', u'uở' : u'uə', u'uỡ' : u'uə', u'uợ' : u'uə',
}
N_offglides = { u'ai' : u'aj', u'ái' : u'aj', u'ài' : u'aj', u'ải' : u'aj', u'ãi' : u'aj', u'ại' : u'aj',
u'ay' : u'ăj', u'áy' : u'ăj', u'ày' : u'ăj', u'ảy' : u'ăj', u'ãy' : u'ăj', u'ạy' : u'ăj',
u'ao' : u'aw', u'áo' : u'aw', u'ào' : u'aw', u'ảo' : u'aw', u'ão' : u'aw', u'ạo' : u'aw',
u'au' : u'ăw', u'áu' : u'ăw', u'àu' : u'ăw', u'ảu' : u'ăw', u'ãu' : u'ăw', u'ạu' : u'ăw',
u'ây' : u'ɤ̆j', u'ấy' : u'ɤ̆j', u'ầy' : u'ɤ̆j', u'ẩy' : u'ɤ̆j', u'ẫy' : u'ɤ̆j', u'ậy' : u'ɤ̆j',
u'âu' : u'ɤ̆w', u'ấu' : u'ɤ̆w', u'ầu': u'ɤ̆w', u'ẩu' : u'ɤ̆w', u'ẫu' : u'ɤ̆w', u'ậu' : u'ɤ̆w',
u'eo' : u'ew', u'éo' : u'ew', u'èo' : u'ew', u'ẻo' : u'ew', u'ẽo' : u'ew', u'ẹo' : u'ew',
u'iu' : u'iw', u'íu' : u'iw', u'ìu' : u'iw', u'ỉu' : u'iw', u'ĩu' : u'iw', u'ịu' : u'iw',
u'oi' : u'ɔj', u'ói' : u'ɔj', u'òi' : u'ɔj', u'ỏi' : u'ɔj', u'õi' : u'ɔj', u'ọi' : u'ɔj',
u'ôi' : u'oj', u'ối' : u'oj', u'ồi' : u'oj', u'ổi' : u'oj', u'ỗi' : u'oj', u'ội' : u'oj',
u'ui' : u'uj', u'úi' : u'uj', u'ùi' : u'uj', u'ủi' : u'uj', u'ũi' : u'uj', u'ụi' : u'uj',
u'uy' : u'uj', u'úy' : u'uj', u'ùy' : u'uj', u'ủy' : u'uj', u'ũy' : u'uj', u'ụy' : u'uj',
u'ơi' : u'ɤj', u'ới' : u'ɤj', u'ời' : u'ɤj', u'ởi' : u'ɤj', u'ỡi' : u'ɤj', u'ợi' : u'ɤj',
u'ưi' : u'ɯj', u'ứi' : u'ɯj', u'ừi' : u'ɯj', u'ửi' : u'ɯj', u'ữi' : u'ɯj', u'ựi' : u'ɯj',
u'ưu' : u'ɯw', u'ứu' : u'ɯw', u'ừu' : u'ɯw', u'ửu' : u'ɯw', u'ữu' : u'ɯw', u'ựu' : u'ɯw',
u'iêu' : u'iəw', u'iếu' : u'iəw', u'iều' : u'iəw', u'iểu' : u'iəw', u'iễu' : u'iəw', u'iệu' : u'iəw',
u'yêu' : u'iəw', u'yếu' : u'iəw', u'yều' : u'iəw', u'yểu' : u'iəw', u'yễu' : u'iəw', u'yệu' : u'iəw',
u'uôi' : u'uəj', u'uối' : u'uəj', u'uồi' : u'uəj', u'uổi' : u'uəj', u'uỗi' : u'uəj', u'uội' : u'uəj',
u'ươi' : u'ɯəj', u'ưới' : u'ɯəj', u'ười' : u'ɯəj', u'ưởi' : u'ɯəj', u'ưỡi' : u'ɯəj', u'ượi' : u'ɯəj',
u'ươu' : u'ɯəw', u'ướu' : u'ɯəw', u'ườu' : u'ɯəw', u'ưởu' : u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw'
}
N_onglides = { u'oa' : u'a', u'oá' : u'a', u'oà' : u'a', u'oả' : u'a', u'oã' : u'a', u'oạ' : u'a',
u'óa' : u'a', u'òa' : u'a', u'ỏa' : u'a', u'õa' : u'a', u'ọa' : u'a',
u'oă' : u'ă', u'oắ' : u'ă', u'oằ' : u'ă', u'oẳ' : u'ă', u'oẵ' : u'ă', u'oặ' : u'ă',
u'oe' : u'e', u'oé' : u'e', u'oè' : u'e', u'oẻ' : u'e', u'oẽ' : u'e', u'oẹ' : u'e',
u'oe' : u'e', u'óe' : u'e', u'òe' : u'e', u'ỏe' : u'e', u'õe' : u'e', u'ọe' : u'e',
u'ua' : u'a', u'uá' : u'a', u'uà' : u'a', u'uả' : u'a', u'uã' : u'a', u'uạ' : u'a',
u'uă' : u'ă', u'uắ' : u'ă', u'uằ' : u'ă', u'uẳ' : u'ă', u'uẵ' : u'ă', u'uặ' : u'ă',
u'uâ' : u'ɤ̆', u'uấ' : u'ɤ̆', u'uầ' : u'ɤ̆', u'uẩ' : u'ɤ̆', u'uẫ' : u'ɤ̆', u'uậ' : u'ɤ̆',
u'ue' : u'ɛ', u'ué' : u'ɛ', u'uè' : u'ɛ', u'uẻ' : u'ɛ', u'uẽ' : u'ɛ', u'uẹ' : u'ɛ',
u'uê' : u'e', u'uế' : u'e', u'uề' : u'e', u'uể' : u'e', u'uễ' : u'e', u'uệ' : u'e',
u'uơ' : u'ɤ', u'uớ' : u'ɤ', u'uờ' : u'ɤ', u'uở' : u'ɤ', u'uỡ' : u'ɤ', u'uợ' : u'ɤ',
u'uy' : u'i', u'uý' : u'i', u'uỳ' : u'i', u'uỷ' : u'i', u'uỹ' : u'i', u'uỵ' : u'i',
u'uya' : u'iə', u'uyá' : u'iə', u'uyà' : u'iə', u'uyả' : u'iə', u'uyã' : u'iə', u'uyạ' : u'iə',
u'uyê' : u'iə', u'uyế' : u'iə', u'uyề' : u'iə', u'uyể' : u'iə', u'uyễ' : u'iə', u'uyệ' : u'iə',
u'uyu' : u'iu', u'uyú' : u'iu', u'uyù' : u'iu', u'uyủ' : u'iu', u'uyũ' : u'iu', u'uyụ' : u'iu',
u'uyu' : u'iu', u'uýu' : u'iu', u'uỳu' : u'iu', u'uỷu' : u'iu', u'uỹu' : u'iu', u'uỵu' : u'iu',
u'oen' : u'en', u'oén' : u'en', u'oèn' : u'en', u'oẻn' : u'en', u'oẽn' : u'en', u'oẹn' : u'en',
u'oet' : u'et', u'oét' : u'et', u'oèt' : u'et', u'oẻt' : u'et', u'oẽt' : u'et', u'oẹt' : u'et'
}
N_onoffglides = { u'oe' : u'ej', u'oé' : u'ej', u'oè' : u'ej', u'oẻ' : u'ej', u'oẽ' : u'ej', u'oẹ' : u'ej',
u'oai' : u'aj', u'oái' : u'aj', u'oài' : u'aj', u'oải' : u'aj', u'oãi' : u'aj', u'oại' : u'aj',
u'oay' : u'ăj', u'oáy' : u'ăj', u'oày' : u'ăj', u'oảy' : u'ăj', u'oãy' : u'ăj', u'oạy' : u'ăj',
u'oao' : u'aw', u'oáo' : u'aw', u'oào' : u'aw', u'oảo' : u'aw', u'oão' : u'aw', u'oạo' : u'aw',
u'oeo' : u'ew', u'oéo' : u'ew', u'oèo' : u'ew', u'oẻo' : u'ew', u'oẽo' : u'ew', u'oẹo' : u'ew',
u'oeo' : u'ew', u'óeo' : u'ew', u'òeo' : u'ew', u'ỏeo' : u'ew', u'õeo' : u'ew', u'ọeo' : u'ew',
u'ueo' : u'ew', u'uéo' : u'ew', u'uèo' : u'ew', u'uẻo' : u'ew', u'uẽo' : u'ew', u'uẹo' : u'ew',
u'uai' : u'aj', u'uái' : u'aj', u'uài' : u'aj', u'uải' : u'aj', u'uãi' : u'aj', u'uại' : u'aj',
u'uay' : u'ăj', u'uáy' : u'ăj', u'uày' : u'ăj', u'uảy' : u'ăj', u'uãy' : u'ăj', u'uạy' : u'ăj',
u'uây' : u'ɤ̆j', u'uấy' : u'ɤ̆j', u'uầy' : u'ɤ̆j', u'uẩy' : u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j'
}
N_codas = { u'p' : u'p', u't' : u't', u'c' : u'k', u'm' : u'm', u'n' : u'n', u'ng' : u'ŋ', u'nh' : u'ɲ', u'ch' : u'k' }
#tones = { u'a' : 33, u'á' : 24, u'à' : 32, u'ả' : 312, u'ã' : u'35g', u'ạ' : u'21g',
# u'â' : 33, u'ấ' : 24, u'ầ' : 32, u'ẩ' : 312, u'ẫ' : u'35g', u'ậ' : u'21g',
# u'ă' : 33, u'ắ' : 24, u'ằ' : 32, u'ẳ' : 312, u'ẵ' : u'35g', u'ặ' : u'21g',
# u'e' : 33, u'é' : 24, u'è' : 32, u'ẻ' : 312, u'ẽ' : u'35g', u'ẹ' : u'21g',
# u'ê' : 33, u'ế' : 24, u'ề' : 32, u'ể' : 312, u'ễ' : u'35g', u'ệ' : u'21g',
# u'i' : 33, u'í' : 24, u'ì' : 32, u'ỉ' : 312, u'ĩ' : u'35g', u'ị' : u'21g',
# u'o' : 33, u'ó' : 24, u'ò' : 32, u'ỏ' : 312, u'õ' : u'35g', u'ọ' : u'21g',
# u'ô' : 33, u'ố' : 24, u'ồ' : 32, u'ổ' : 312, u'ỗ' : u'35g', u'ộ' : u'21g',
# u'ơ' : 33, u'ớ' : 24, u'ờ' : 32, u'ở' : 312, u'ỡ' : u'35g', u'ợ' : u'21g',
# u'u' : 33, u'ú' : 24, u'ù' : 32, u'ủ' : 312, u'ũ' : u'35g', u'ụ' : u'21g',
# u'ư' : 33, u'ứ' : 24, u'ừ' : 32, u'ử' : 312, u'ữ' : u'35g', u'ự' : u'21g',
# u'y' : 33, u'ý' : 24, u'ỳ' : 32, u'ỷ' : 312, u'ỹ' : u'35g', u'ỵ' : u'21g',
# }
N_tones = { u'á' : 24, u'à' : 32, u'ả' : 312, u'ã' : u'35g', u'ạ' : u'21g',
u'ấ' : 24, u'ầ' : 32, u'ẩ' : 312, u'ẫ' : u'35g', u'ậ' : u'21g',
u'ắ' : 24, u'ằ' : 32, u'ẳ' : 312, u'ẵ' : u'35g', u'ặ' : u'21g',
u'é' : 24, u'è' : 32, u'ẻ' : 312, u'ẽ' : u'35g', u'ẹ' : u'21g',
u'ế' : 24, u'ề' : 32, u'ể' : 312, u'ễ' : u'35g', u'ệ' : u'21g',
u'í' : 24, u'ì' : 32, u'ỉ' : 312, u'ĩ' : u'35g', u'ị' : u'21g',
u'ó' : 24, u'ò' : 32, u'ỏ' : 312, u'õ' : u'35g', u'ọ' : u'21g',
u'ố' : 24, u'ồ' : 32, u'ổ' : 312, u'ỗ' : u'35g', u'ộ' : u'21g',
u'ớ' : 24, u'ờ' : 32, u'ở' : 312, u'ỡ' : u'35g', u'ợ' : u'21g',
u'ú' : 24, u'ù' : 32, u'ủ' : 312, u'ũ' : u'35g', u'ụ' : u'21g',
u'ứ' : 24, u'ừ' : 32, u'ử' : 312, u'ữ' : u'35g', u'ự' : u'21g',
u'ý' : 24, u'ỳ' : 32, u'ỷ' : 312, u'ỹ' : u'35g', u'ỵ' : u'21g',
}
# used to use \u02C0 for the unicode raised glottal character
N_tones_p = { u'á' : 5, u'à' : 2, u'ả' : 4, u'ã' : 3, u'ạ' : 6,
u'ấ' : 5, u'ầ' : 2, u'ẩ' : 4, u'ẫ' : 3, u'ậ' : 6,
u'ắ' : 5, u'ằ' : 2, u'ẳ' : 4, u'ẵ' : 3, u'ặ' : 6,
u'é' : 5, u'è' : 2, u'ẻ' : 4, u'ẽ' : 3, u'ẹ' : 6,
u'ế' : 5, u'ề' : 2, u'ể' : 4, u'ễ' : 3, u'ệ' : 6,
u'í' : 5, u'ì' : 2, u'ỉ' : 4, u'ĩ' : 3, u'ị' : 6,
u'ó' : 5, u'ò' : 2, u'ỏ' : 4, u'õ' : 3, u'ọ' : 6,
u'ố' : 5, u'ồ' : 2, u'ổ' : 4, u'ỗ' : 3, u'ộ' : 6,
u'ớ' : 5, u'ờ' : 2, u'ở' : 4, u'ỡ' : 3, u'ợ' : 6,
u'ú' : 5, u'ù' : 2, u'ủ' : 4, u'ũ' : 3, u'ụ' : 6,
u'ứ' : 5, u'ừ' : 2, u'ử' : 4, u'ữ' : 3, u'ự' : 6,
u'ý' : 5, u'ỳ' : 2, u'ỷ' : 4, u'ỹ' : 3, u'ỵ' : 6,
}
N_gi = { u'gi' : u'zi', u'gí': u'zi', u'gì' : u'zi', u'gì' : u'zi', u'gĩ' : u'zi', u'gị' : u'zi'}
N_qu = {u'quy' : u'kwi', u'qúy' : u'kwi', u'qùy' : u'kwi', u'qủy' : u'kwi', u'qũy' : u'kwi', u'qụy' : u'kwi'}
#######################################################
#central.py
#coding: utf-8
C_onsets = { u'b' : u'b', u't' : u't', u'th' : u'tʰ', u'đ' : u'd', u'ch' : u'c',
u'kh' : u'x', u'g' : u'ɣ', u'l' : u'l', u'm' : u'm', u'n': u'n',
u'ngh': u'ŋ', u'nh' : u'ɲ', u'ng' : u'ŋ', u'ph' : u'f', u'v' : u'j',
u'x' : u's', u'd' : u'j', u'h' : u'h', u'p' : u'p', u'qu' : u'w',
u'gi' : u'j', u'tr' : u'ʈ', u'k' : u'k', u'c' : u'k', u'gh' : u'ɣ',
u'r' : u'ʐ', u's' : u'ʂ', u'gi' : u'j'
}
C_nuclei = { u'a' : u'a', u'á' : u'a', u'à' : u'a', u'ả' : u'a', u'ã' : u'a', u'ạ' : u'a',
u'â' : u'ɤ̆', u'ấ' : u'ɤ̆', u'ầ' : u'ɤ̆', u'ẩ' : u'ɤ̆', u'ẫ' : u'ɤ̆', u'ậ' : u'ɤ̆',
u'ă' : u'ă', u'ắ' : u'ă', u'ằ' : u'ă', u'ẳ' : u'ă', u'ẵ' : u'ă', u'ặ' : u'ă',
u'e' : u'ɛ', u'é' : u'ɛ', u'è' : u'ɛ', u'ẻ' : u'ɛ', u'ẽ' : u'ɛ', u'ẹ' : u'ɛ',
u'ê' : u'e', u'ế' : u'e', u'ề' : u'e', u'ể' : u'e', u'ễ' : u'e', u'ệ' : u'e',
u'i' : u'i', u'í' : u'i', u'ì' : u'i', u'ỉ' : u'i', u'ĩ' : u'i', u'ị' : u'i',
u'o' : u'ɔ', u'ó' : u'ɔ', u'ò' : u'ɔ', u'ỏ' : u'ɔ', u'õ' : u'ɔ', u'ọ' : u'ɔ',
u'ô' : u'o', u'ố' : u'o', u'ồ' : u'o', u'ổ' : u'o', u'ỗ' : u'o', u'ộ' : u'o',
u'ơ' : u'ɤ', u'ớ' : u'ɤ', u'ờ' : u'ɤ', u'ở' : u'ɤ', u'ỡ' : u'ɤ', u'ợ' : u'ɤ',
u'u' : u'u', u'ú' : u'u', u'ù' : u'u', u'ủ' : u'u', u'ũ' : u'u', u'ụ' : u'u',
u'ư' : u'ɯ', u'ứ' : u'ɯ', u'ừ' : u'ɯ', u'ử' : u'ɯ', u'ữ' : u'ɯ', u'ự' : u'ɯ',
u'y' : u'i', u'ý' : u'i', u'ỳ' : u'i', u'ỷ' : u'i', u'ỹ' : u'i', u'ỵ' : u'i',
u'eo' : u'eo', u'éo' : u'eo', u'èo' : u'eo', u'ẻo' : u'eo', u'ẽo': u'eo', u'ẹo' : u'eo',
u'êu' : u'ɛu', u'ếu' : u'ɛu', u'ều' : u'ɛu', u'ểu' : u'ɛu', u'ễu': u'ɛu', u'ệu' : u'ɛu',
u'ia' : u'iə', u'ía' : u'iə', u'ìa' : u'iə', u'ỉa' : u'iə', u'ĩa' : u'iə', u'ịa' : u'iə',
u'ia' : u'iə', u'iá' : u'iə', u'ià' : u'iə', u'iả' : u'iə', u'iã' : u'iə', u'iạ' : u'iə',
u'iê' : u'iə', u'iế' : u'iə', u'iề' : u'iə', u'iể' : u'iə', u'iễ' : u'iə', u'iệ' : u'iə',
u'oo' : u'ɔ', u'óo' : u'ɔ', u'òo' : u'ɔ', u'ỏo' : u'ɔ', u'õo' : u'ɔ', u'ọo' : u'ɔ',
u'oo' : u'ɔ', u'oó' : u'ɔ', u'oò' : u'ɔ', u'oỏ' : u'ɔ', u'oõ' : u'ɔ', u'oọ' : u'ɔ',
u'ôô' : u'o', u'ốô' : u'o', u'ồô' : u'o', u'ổô' : u'o', u'ỗô' : u'o', u'ộô' : u'o',
u'ôô' : u'o', u'ôố' : u'o', u'ôồ' : u'o', u'ôổ' : u'o', u'ôỗ' : u'o', u'ôộ' : u'o',
u'ua' : u'uə', u'úa' : u'uə', u'ùa' : u'uə', u'ủa' : u'uə', u'ũa' : u'uə', u'ụa' : u'uə',
u'uô' : u'uə', u'uố' : u'uə', u'uồ' : u'uə', u'uổ' : u'uə', u'uỗ' : u'uə', u'uộ' : u'uə',
u'ưa' : u'ɯə', u'ứa' : u'ɯə', u'ừa' : u'ɯə', u'ửa' : u'ɯə', u'ữa' : u'ɯə', u'ựa' : u'ɯə',
u'ươ' : u'ɯə', u'ướ' : u'ɯə', u'ườ' : u'ɯə', u'ưở' : u'ɯə', u'ưỡ' : u'ɯə', u'ượ' : u'ɯə',
u'yê' : u'iɛ', u'yế' : u'iɛ', u'yề' : u'iɛ', u'yể' : u'iɛ', u'yễ' : u'iɛ', u'yệ' : u'iɛ',
u'uơ' : u'uə', u'uở' : u'uə', u'uờ': u'uə', u'uở' : u'uə', u'uỡ' : u'uə', u'uợ' : u'uə',
}
C_offglides = { u'ai' : u'aj', u'ái' : u'aj', u'ài' : u'aj', u'ải' : u'aj', u'ãi' : u'aj', u'ại' : u'aj',
u'ay' : u'ăj', u'áy' : u'ăj', u'ày' : u'ăj', u'ảy' : u'ăj', u'ãy' : u'ăj', u'ạy' : u'ăj',
u'ao' : u'aw', u'áo' : u'aw', u'ào' : u'aw', u'ảo' : u'aw', u'ão' : u'aw', u'ạo' : u'aw',
u'au' : u'ăw', u'áu' : u'ăw', u'àu' : u'ăw', u'ảu' : u'ăw', u'ãu' : u'ăw', u'ạu' : u'ăw',
u'ây' : u'ɤ̆j', u'ấy' : u'ɤ̆j', u'ầy' : u'ɤ̆j', u'ẩy' : u'ɤ̆j', u'ẫy' : u'ɤ̆j', u'ậy' : u'ɤ̆j',
u'âu' : u'ɤ̆w', u'ấu' : u'ɤ̆w', u'ầu': u'ɤ̆w', u'ẩu' : u'ɤ̆w', u'ẫu' : u'ɤ̆w', u'ậu' : u'ɤ̆w',
u'eo' : u'ew', u'éo' : u'ew', u'èo' : u'ew', u'ẻo' : u'ew', u'ẽo' : u'ew', u'ẹo' : u'ew',
u'iu' : u'iw', u'íu' : u'iw', u'ìu' : u'iw', u'ỉu' : u'iw', u'ĩu' : u'iw', u'ịu' : u'iw',
u'oi' : u'ɔj', u'ói' : u'ɔj', u'òi' : u'ɔj', u'ỏi' : u'ɔj', u'õi' : u'ɔj', u'ọi' : u'ɔj',
u'ôi' : u'oj', u'ối' : u'oj', u'ồi' : u'oj', u'ổi' : u'oj', u'ỗi' : u'oj', u'ội' : u'oj',
u'ui' : u'uj', u'úi' : u'uj', u'ùi' : u'uj', u'ủi' : u'uj', u'ũi' : u'uj', u'ụi' : u'uj',
u'uy' : u'uj', u'úy' : u'uj', u'ùy' : u'uj', u'ủy' : u'uj', u'ũy' : u'uj', u'ụy' : u'uj',
u'ơi' : u'ɤj', u'ới' : u'ɤj', u'ời' : u'ɤj', u'ởi' : u'ɤj', u'ỡi' : u'ɤj', u'ợi' : u'ɤj',
u'ưi' : u'ɯj', u'ứi' : u'ɯj', u'ừi' : u'ɯj', u'ửi' : u'ɯj', u'ữi' : u'ɯj', u'ựi' : u'ɯj',
u'ưu' : u'ɯw', u'ứu' : u'ɯw', u'ừu' : u'ɯw', u'ửu' : u'ɯw', u'ữu' : u'ɯw', u'ựu' : u'ɯw',
u'iêu' : u'iəw', u'iếu' : u'iəw', u'iều' : u'iəw', u'iểu' : u'iəw', u'iễu' : u'iəw', u'iệu' : u'iəw',
u'yêu' : u'iəw', u'yếu' : u'iəw', u'yều' : u'iəw', u'yểu' : u'iəw', u'yễu' : u'iəw', u'yệu' : u'iəw',
u'uôi' : u'uəj', u'uối' : u'uəj', u'uồi' : u'uəj', u'uổi' : u'uəj', u'uỗi' : u'uəj', u'uội' : u'uəj',
u'ươi' : u'ɯəj', u'ưới' : u'ɯəj', u'ười' : u'ɯəj', u'ưởi' : u'ɯəj', u'ưỡi' : u'ɯəj', u'ượi' : u'ɯəj',
u'ươu' : u'ɯəw', u'ướu' : u'ɯəw', u'ườu' : u'ɯəw', u'ưởu' : u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw'
}
C_onglides = { u'oa' : u'a', u'oá' : u'a', u'oà' : u'a', u'oả' : u'a', u'oã' : u'a', u'oạ' : u'a',
u'óa' : u'a', u'òa' : u'a', u'ỏa' : u'a', u'õa' : u'a', u'ọa' : u'a',
u'oă' : u'ă', u'oắ' : u'ă', u'oằ' : u'ă', u'oẳ' : u'ă', u'oẵ' : u'ă', u'oặ' : u'ă',
u'oe' : u'e', u'oé' : u'e', u'oè' : u'e', u'oẻ' : u'e', u'oẽ' : u'e', u'oẹ' : u'e',
u'oe' : u'e', u'óe' : u'e', u'òe' : u'e', u'ỏe' : u'e', u'õe' : u'e', u'ọe' : u'e',
u'ua' : u'a', u'uá' : u'a', u'uà' : u'a', u'uả' : u'a', u'uã' : u'a', u'uạ' : u'a',
u'uă' : u'ă', u'uắ' : u'ă', u'uằ' : u'ă', u'uẳ' : u'ă', u'uẵ' : u'ă', u'uặ' : u'ă',
u'uâ' : u'ɤ̆', u'uấ' : u'ɤ̆', u'uầ' : u'ɤ̆', u'uẩ' : u'ɤ̆', u'uẫ' : u'ɤ̆', u'uậ' : u'ɤ̆',
u'ue' : u'ɛ', u'ué' : u'ɛ', u'uè' : u'ɛ', u'uẻ' : u'ɛ', u'uẽ' : u'ɛ', u'uẹ' : u'ɛ',
u'uê' : u'e', u'uế' : u'e', u'uề' : u'e', u'uể' : u'e', u'uễ' : u'e', u'uệ' : u'e',
u'uơ' : u'ɤ', u'uớ' : u'ɤ', u'uờ' : u'ɤ', u'uở' : u'ɤ', u'uỡ' : u'ɤ', u'uợ' : u'ɤ',
u'uy' : u'i', u'uý' : u'i', u'uỳ' : u'i', u'uỷ' : u'i', u'uỹ' : u'i', u'uỵ' : u'i',
u'uya' : u'iə', u'uyá' : u'iə', u'uyà' : u'iə', u'uyả' : u'iə', u'uyã' : u'iə', u'uyạ' : u'iə',
u'uyê' : u'iə', u'uyế' : u'iə', u'uyề' : u'iə', u'uyể' : u'iə', u'uyễ' : u'iə', u'uyệ' : u'iə',
u'uyu' : u'iu', u'uyú' : u'iu', u'uyù' : u'iu', u'uyủ' : u'iu', u'uyũ' : u'iu', u'uyụ' : u'iu',
u'uyu' : u'iu', u'uýu' : u'iu', u'uỳu' : u'iu', u'uỷu' : u'iu', u'uỹu' : u'iu', u'uỵu' : u'iu',
u'oen' : u'en', u'oén' : u'en', u'oèn' : u'en', u'oẻn' : u'en', u'oẽn' : u'en', u'oẹn' : u'en',
u'oet' : u'et', u'oét' : u'et', u'oèt' : u'et', u'oẻt' : u'et', u'oẽt' : u'et', u'oẹt' : u'et'
}
C_onoffglides = { u'oe' : u'ej', u'oé' : u'ej', u'oè' : u'ej', u'oẻ' : u'ej', u'oẽ' : u'ej', u'oẹ' : u'ej',
u'oai' : u'aj', u'oái' : u'aj', u'oài' : u'aj', u'oải' : u'aj', u'oãi' : u'aj', u'oại' : u'aj',
u'oay' : u'ăj', u'oáy' : u'ăj', u'oày' : u'ăj', u'oảy' : u'ăj', u'oãy' : u'ăj', u'oạy' : u'ăj',
u'oao' : u'aw', u'oáo' : u'aw', u'oào' : u'aw', u'oảo' : u'aw', u'oão' : u'aw', u'oạo' : u'aw',
u'oeo' : u'ew', u'oéo' : u'ew', u'oèo' : u'ew', u'oẻo' : u'ew', u'oẽo' : u'ew', u'oẹo' : u'ew',
u'oeo' : u'ew', u'óeo' : u'ew', u'òeo' : u'ew', u'ỏeo' : u'ew', u'õeo' : u'ew', u'ọeo' : u'ew',
u'ueo' : u'ew', u'uéo' : u'ew', u'uèo' : u'ew', u'uẻo' : u'ew', u'uẽo' : u'ew', u'uẹo' : u'ew',
u'uai' : u'aj', u'uái' : u'aj', u'uài' : u'aj', u'uải' : u'aj', u'uãi' : u'aj', u'uại' : u'aj',
u'uay' : u'ăj', u'uáy' : u'ăj', u'uày' : u'ăj', u'uảy' : u'ăj', u'uãy' : u'ăj', u'uạy' : u'ăj',
u'uây' : u'ɤ̆j', u'uấy' : u'ɤ̆j', u'uầy' : u'ɤ̆j', u'uẩy' : u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j'
}
C_codas = { u'p' : u'p', u't' : u'k', u'c' : u'k', u'm' : u'm', u'n' : u'ŋ', u'ng' : u'ŋ', u'nh' : u'n', u'ch' : u'k' }
# See Alves 2007 (SEALS XII), Vũ 1982
C_tones = { u'á' : 13, u'à' : 42, u'ả' : 312, u'ã' : 312, u'ạ' : u'21g',
u'ấ' : 13, u'ầ' : 42, u'ẩ' : 312, u'ẫ' : 312, u'ậ' : u'21g',
u'ắ' : 13, u'ằ' : 42, u'ẳ' : 312, u'ẵ' : 312, u'ặ' : u'21g',
u'é' : 13, u'è' : 42, u'ẻ' : 312, u'ẽ' : 312, u'ẹ' : u'21g',
u'ế' : 13, u'ề' : 42, u'ể' : 312, u'ễ' : 312, u'ệ' : u'21g',
u'í' : 13, u'ì' : 42, u'ỉ' : 312, u'ĩ' : 312, u'ị' : u'21g',
u'ó' : 13, u'ò' : 42, u'ỏ' : 312, u'õ' : 312, u'ọ' : u'21g',
u'ố' : 13, u'ồ' : 42, u'ổ' : 312, u'ỗ' : 312, u'ộ' : u'21g',
u'ớ' : 13, u'ờ' : 42, u'ở' : 312, u'ỡ' : 312, u'ợ' : u'21g',
u'ú' : 13, u'ù' : 42, u'ủ' : 312, u'ũ' : 312, u'ụ' : u'21g',
u'ứ' : 13, u'ừ' : 42, u'ử' : 312, u'ữ' : 312, u'ự' : u'21g',
u'ý' : 13, u'ỳ' : 42, u'ỷ' : 312, u'ỹ' : 312, u'ỵ' : u'21g',
}
# used to use \u02C0 for raised glottal instead of g
C_tones_p = { u'á' : 5, u'à' : 2, u'ả' : 4, u'ã' : 4, u'ạ' : 6,
u'ấ' : 5, u'ầ' : 2, u'ẩ' : 4, u'ẫ' : 4, u'ậ' : 6,
u'ắ' : 5, u'ằ' : 2, u'ẳ' : 4, u'ẵ' : 4, u'ặ' : 6,
u'é' : 5, u'è' : 2, u'ẻ' : 4, u'ẽ' : 4, u'ẹ' : 6,
u'ế' : 5, u'ề' : 2, u'ể' : 4, u'ễ' : 4, u'ệ' : 6,
u'í' : 5, u'ì' : 2, u'ỉ' : 4, u'ĩ' : 4, u'ị' : 6,
u'ó' : 5, u'ò' : 2, u'ỏ' : 4, u'õ' : 4, u'ọ' : 6,
u'ố' : 5, u'ồ' : 2, u'ổ' : 4, u'ỗ' : 4, u'ộ' : 6,
u'ớ' : 5, u'ờ' : 2, u'ở' : 4, u'ỡ' : 4, u'ợ' : 6,
u'ú' : 5, u'ù' : 2, u'ủ' : 4, u'ũ' : 4, u'ụ' : 6,
u'ứ' : 5, u'ừ' : 2, u'ử' : 4, u'ữ' : 4, u'ự' : 6,
u'ý' : 5, u'ỳ' : 2, u'ỷ' : 4, u'ỹ' : 4, u'ỵ' : 6,
}
C_gi = { u'gi' : u'ji', u'gí': u'ji', u'gì' : u'ji', u'gì' : u'ji', u'gĩ' : u'ji', u'gị' : u'ji' }
C_qu = {u'quy' : u'wi', u'qúy' : u'wi', u'qùy' : u'wi', u'qủy' : u'wi', u'qũy' : u'wi', u'qụy' : u'wi'}
############################################
#south.py
#coding: utf-8
S_onsets = { u'b' : u'b', u't' : u't', u'th' : u'tʰ', u'đ' : u'd', u'ch' : u'c',
u'kh' : u'x', u'g' : u'ɣ', u'l' : u'l', u'm' : u'm', u'n': u'n',
u'ngh': u'ŋ', u'nh' : u'ɲ', u'ng' : u'ŋ', u'ph' : u'f', u'v' : u'j',
u'x' : u's', u'd' : u'j', u'h' : u'h', u'p' : u'p', u'qu' : u'w',
u'gi' : u'j', u'tr' : u'ʈ', u'k' : u'k', u'c' : u'k', u'gh' : u'ɣ',
u'r' : u'ʐ', u's' : u'ʂ', u'gi' : u'j'
}
S_nuclei = { u'a' : u'a', u'á' : u'a', u'à' : u'a', u'ả' : u'a', u'ã' : u'a', u'ạ' : u'a',
u'â' : u'ɤ̆', u'ấ' : u'ɤ̆', u'ầ' : u'ɤ̆', u'ẩ' : u'ɤ̆', u'ẫ' : u'ɤ̆', u'ậ' : u'ɤ̆',
u'ă' : u'ă', u'ắ' : u'ă', u'ằ' : u'ă', u'ẳ' : u'ă', u'ẵ' : u'ă', u'ặ' : u'ă',
u'e' : u'ɛ', u'é' : u'ɛ', u'è' : u'ɛ', u'ẻ' : u'ɛ', u'ẽ' : u'ɛ', u'ẹ' : u'ɛ',
u'ê' : u'e', u'ế' : u'e', u'ề' : u'e', u'ể' : u'e', u'ễ' : u'e', u'ệ' : u'e',
u'i' : u'i', u'í' : u'i', u'ì' : u'i', u'ỉ' : u'i', u'ĩ' : u'i', u'ị' : u'i',
u'o' : u'ɔ', u'ó' : u'ɔ', u'ò' : u'ɔ', u'ỏ' : u'ɔ', u'õ' : u'ɔ', u'ọ' : u'ɔ',
u'ô' : u'o', u'ố' : u'o', u'ồ' : u'o', u'ổ' : u'o', u'ỗ' : u'o', u'ộ' : u'o',
u'ơ' : u'ɤ', u'ớ' : u'ɤ', u'ờ' : u'ɤ', u'ở' : u'ɤ', u'ỡ' : u'ɤ', u'ợ' : u'ɤ',
u'u' : u'u', u'ú' : u'u', u'ù' : u'u', u'ủ' : u'u', u'ũ' : u'u', u'ụ' : u'u',
u'ư' : u'ɯ', u'ứ' : u'ɯ', u'ừ' : u'ɯ', u'ử' : u'ɯ', u'ữ' : u'ɯ', u'ự' : u'ɯ',
u'y' : u'i', u'ý' : u'i', u'ỳ' : u'i', u'ỷ' : u'i', u'ỹ' : u'i', u'ỵ' : u'i',
u'eo' : u'eo', u'éo' : u'eo', u'èo' : u'eo', u'ẻo' : u'eo', u'ẽo': u'eo', u'ẹo' : u'eo',
u'êu' : u'ɛu', u'ếu' : u'ɛu', u'ều' : u'ɛu', u'ểu' : u'ɛu', u'ễu': u'ɛu', u'ệu' : u'ɛu',
u'ia' : u'iə', u'ía' : u'iə', u'ìa' : u'iə', u'ỉa' : u'iə', u'ĩa' : u'iə', u'ịa' : u'iə',
u'ia' : u'iə', u'iá' : u'iə', u'ià' : u'iə', u'iả' : u'iə', u'iã' : u'iə', u'iạ' : u'iə',
u'iê' : u'iə', u'iế' : u'iə', u'iề' : u'iə', u'iể' : u'iə', u'iễ' : u'iə', u'iệ' : u'iə',
u'oo' : u'ɔ', u'óo' : u'ɔ', u'òo' : u'ɔ', u'ỏo' : u'ɔ', u'õo' : u'ɔ', u'ọo' : u'ɔ',
u'oo' : u'ɔ', u'oó' : u'ɔ', u'oò' : u'ɔ', u'oỏ' : u'ɔ', u'oõ' : u'ɔ', u'oọ' : u'ɔ',
u'ôô' : u'o', u'ốô' : u'o', u'ồô' : u'o', u'ổô' : u'o', u'ỗô' : u'o', u'ộô' : u'o', u'ôô' : u'o', u'ôố' : u'o', u'ôồ' : u'o', u'ôổ' : u'o', u'ôỗ' : u'o', u'ôộ' : u'o', u'ua' : u'uə', u'úa' : u'uə', u'ùa' : u'uə', u'ủa' : u'uə', u'ũa' : u'uə', u'ụa' : u'uə',
u'uô' : u'uə', u'uố' : u'uə', u'uồ' : u'uə', u'uổ' : u'uə', u'uỗ' : u'uə', u'uộ' : u'uə',
u'ưa' : u'ɯə', u'ứa' : u'ɯə', u'ừa' : u'ɯə', u'ửa' : u'ɯə', u'ữa' : u'ɯə', u'ựa' : u'ɯə',
u'ươ' : u'ɯə', u'ướ' : u'ɯə', u'ườ' : u'ɯə', u'ưở' : u'ɯə', u'ưỡ' : u'ɯə', u'ượ' : u'ɯə',
u'yê' : u'iɛ', u'yế' : u'iɛ', u'yề' : u'iɛ', u'yể' : u'iɛ', u'yễ' : u'iɛ', u'yệ' : u'iɛ',
u'uơ' : u'uə', u'uở' : u'uə', u'uờ': u'uə', u'uở' : u'uə', u'uỡ' : u'uə', u'uợ' : u'uə',
}
S_offglides = { u'ai' : u'aj', u'ái' : u'aj', u'ài' : u'aj', u'ải' : u'aj', u'ãi' : u'aj', u'ại' : u'aj',
u'ay' : u'ăj', u'áy' : u'ăj', u'ày' : u'ăj', u'ảy' : u'ăj', u'ãy' : u'ăj', u'ạy' : u'ăj',
u'ao' : u'aw', u'áo' : u'aw', u'ào' : u'aw', u'ảo' : u'aw', u'ão' : u'aw', u'ạo' : u'aw',
u'au' : u'ăw', u'áu' : u'ăw', u'àu' : u'ăw', u'ảu' : u'ăw', u'ãu' : u'ăw', u'ạu' : u'ăw',
u'ây' : u'ɤ̆j', u'ấy' : u'ɤ̆j', u'ầy' : u'ɤ̆j', u'ẩy' : u'ɤ̆j', u'ẫy' : u'ɤ̆j', u'ậy' : u'ɤ̆j',
u'âu' : u'ɤ̆w', u'ấu' : u'ɤ̆w', u'ầu': u'ɤ̆w', u'ẩu' : u'ɤ̆w', u'ẫu' : u'ɤ̆w', u'ậu' : u'ɤ̆w',
u'eo' : u'ew', u'éo' : u'ew', u'èo' : u'ew', u'ẻo' : u'ew', u'ẽo' : u'ew', u'ẹo' : u'ew',
u'iu' : u'iw', u'íu' : u'iw', u'ìu' : u'iw', u'ỉu' : u'iw', u'ĩu' : u'iw', u'ịu' : u'iw',
u'oi' : u'ɔj', u'ói' : u'ɔj', u'òi' : u'ɔj', u'ỏi' : u'ɔj', u'õi' : u'ɔj', u'ọi' : u'ɔj',
u'ôi' : u'oj', u'ối' : u'oj', u'ồi' : u'oj', u'ổi' : u'oj', u'ỗi' : u'oj', u'ội' : u'oj',
u'ui' : u'uj', u'úi' : u'uj', u'ùi' : u'uj', u'ủi' : u'uj', u'ũi' : u'uj', u'ụi' : u'uj',
u'uy' : u'uj', u'úy' : u'uj', u'ùy' : u'uj', u'ủy' : u'uj', u'ũy' : u'uj', u'ụy' : u'uj',
u'ơi' : u'ɤj', u'ới' : u'ɤj', u'ời' : u'ɤj', u'ởi' : u'ɤj', u'ỡi' : u'ɤj', u'ợi' : u'ɤj',
u'ưi' : u'ɯj', u'ứi' : u'ɯj', u'ừi' : u'ɯj', u'ửi' : u'ɯj', u'ữi' : u'ɯj', u'ựi' : u'ɯj',
u'ưu' : u'ɯw', u'ứu' : u'ɯw', u'ừu' : u'ɯw', u'ửu' : u'ɯw', u'ữu' : u'ɯw', u'ựu' : u'ɯw',
u'iêu' : u'iəw', u'iếu' : u'iəw', u'iều' : u'iəw', u'iểu' : u'iəw', u'iễu' : u'iəw', u'iệu' : u'iəw',
u'yêu' : u'iəw', u'yếu' : u'iəw', u'yều' : u'iəw', u'yểu' : u'iəw', u'yễu' : u'iəw', u'yệu' : u'iəw',
u'uôi' : u'uəj', u'uối' : u'uəj', u'uồi' : u'uəj', u'uổi' : u'uəj', u'uỗi' : u'uəj', u'uội' : u'uəj',
u'ươi' : u'ɯəj', u'ưới' : u'ɯəj', u'ười' : u'ɯəj', u'ưởi' : u'ɯəj', u'ưỡi' : u'ɯəj', u'ượi' : u'ɯəj',
u'ươu' : u'ɯəw', u'ướu' : u'ɯəw', u'ườu' : u'ɯəw', u'ưởu' : u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw'
}
S_onglides = { u'oa' : u'a', u'oá' : u'a', u'oà' : u'a', u'oả' : u'a', u'oã' : u'a', u'oạ' : u'a',
u'óa' : u'a', u'òa' : u'a', u'ỏa' : u'a', u'õa' : u'a', u'ọa' : u'a',
u'oă' : u'ă', u'oắ' : u'ă', u'oằ' : u'ă', u'oẳ' : u'ă', u'oẵ' : u'ă', u'oặ' : u'ă',
u'oe' : u'e', u'oé' : u'e', u'oè' : u'e', u'oẻ' : u'e', u'oẽ' : u'e', u'oẹ' : u'e',
u'oe' : u'e', u'óe' : u'e', u'òe' : u'e', u'ỏe' : u'e', u'õe' : u'e', u'ọe' : u'e',
u'ua' : u'a', u'uá' : u'a', u'uà' : u'a', u'uả' : u'a', u'uã' : u'a', u'uạ' : u'a',
u'uă' : u'ă', u'uắ' : u'ă', u'uằ' : u'ă', u'uẳ' : u'ă', u'uẵ' : u'ă', u'uặ' : u'ă',
u'uâ' : u'ɤ̆', u'uấ' : u'ɤ̆', u'uầ' : u'ɤ̆', u'uẩ' : u'ɤ̆', u'uẫ' : u'ɤ̆', u'uậ' : u'ɤ̆',
u'ue' : u'ɛ', u'ué' : u'ɛ', u'uè' : u'ɛ', u'uẻ' : u'ɛ', u'uẽ' : u'ɛ', u'uẹ' : u'ɛ',
u'uê' : u'e', u'uế' : u'e', u'uề' : u'e', u'uể' : u'e', u'uễ' : u'e', u'uệ' : u'e',
u'uơ' : u'ɤ', u'uớ' : u'ɤ', u'uờ' : u'ɤ', u'uở' : u'ɤ', u'uỡ' : u'ɤ', u'uợ' : u'ɤ',
u'uy' : u'i', u'uý' : u'i', u'uỳ' : u'i', u'uỷ' : u'i', u'uỹ' : u'i', u'uỵ' : u'i',
u'uya' : u'iə', u'uyá' : u'iə', u'uyà' : u'iə', u'uyả' : u'iə', u'uyã' : u'iə', u'uyạ' : u'iə',
u'uyê' : u'iə', u'uyế' : u'iə', u'uyề' : u'iə', u'uyể' : u'iə', u'uyễ' : u'iə', u'uyệ' : u'iə',
u'uyu' : u'iu', u'uyú' : u'iu', u'uyù' : u'iu', u'uyủ' : u'iu', u'uyũ' : u'iu', u'uyụ' : u'iu',
u'uyu' : u'iu', u'uýu' : u'iu', u'uỳu' : u'iu', u'uỷu' : u'iu', u'uỹu' : u'iu', u'uỵu' : u'iu',
u'oen' : u'en', u'oén' : u'en', u'oèn' : u'en', u'oẻn' : u'en', u'oẽn' : u'en', u'oẹn' : u'en',
u'oet' : u'et', u'oét' : u'et', u'oèt' : u'et', u'oẻt' : u'et', u'oẽt' : u'et', u'oẹt' : u'et'
}
S_onoffglides = { u'oe' : u'ej', u'oé' : u'ej', u'oè' : u'ej', u'oẻ' : u'ej', u'oẽ' : u'ej', u'oẹ' : u'ej',
u'oai' : u'aj', u'oái' : u'aj', u'oài' : u'aj', u'oải' : u'aj', u'oãi' : u'aj', u'oại' : u'aj',
u'oay' : u'ăj', u'oáy' : u'ăj', u'oày' : u'ăj', u'oảy' : u'ăj', u'oãy' : u'ăj', u'oạy' : u'ăj',
u'oao' : u'aw', u'oáo' : u'aw', u'oào' : u'aw', u'oảo' : u'aw', u'oão' : u'aw', u'oạo' : u'aw',
u'oeo' : u'ew', u'oéo' : u'ew', u'oèo' : u'ew', u'oẻo' : u'ew', u'oẽo' : u'ew', u'oẹo' : u'ew',
u'oeo' : u'ew', u'óeo' : u'ew', u'òeo' : u'ew', u'ỏeo' : u'ew', u'õeo' : u'ew', u'ọeo' : u'ew',
u'ueo' : u'ew', u'uéo' : u'ew', u'uèo' : u'ew', u'uẻo' : u'ew', u'uẽo' : u'ew', u'uẹo' : u'ew',
u'uai' : u'aj', u'uái' : u'aj', u'uài' : u'aj', u'uải' : u'aj', u'uãi' : u'aj', u'uại' : u'aj',
u'uay' : u'ăj', u'uáy' : u'ăj', u'uày' : u'ăj', u'uảy' : u'ăj', u'uãy' : u'ăj', u'uạy' : u'ăj',
u'uây' : u'ɤ̆j', u'uấy' : u'ɤ̆j', u'uầy' : u'ɤ̆j', u'uẩy' : u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j'
}
S_codas = { u'p' : u'p', u't' : u't', u'c' : u'k', u'm' : u'm', u'n' : u'ŋ', u'ng' : u'ŋ', u'nh' : u'n', u'ch' : u't' }
S_tones = { u'á' : 45, u'à' : 32, u'ả' : 214, u'ã' : 214, u'ạ' : 212,
u'ấ' : 45, u'ầ' : 32, u'ẩ' : 214, u'ẫ' : 214, u'ậ' : 212,
u'ắ' : 45, u'ằ' : 32, u'ẳ' : 214, u'ẵ' : 214, u'ặ' : 212,
u'é' : 45, u'è' : 32, u'ẻ' : 214, u'ẽ' : 214, u'ẹ' : 212,
u'ế' : 45, u'ề' : 32, u'ể' : 214, u'ễ' : 214, u'ệ' : 212,
u'í' : 45, u'ì' : 32, u'ỉ' : 214, u'ĩ' : 214, u'ị' : 212,
u'ó' : 45, u'ò' : 32, u'ỏ' : 214, u'õ' : 214, u'ọ' : 212,
u'ố' : 45, u'ồ' : 32, u'ổ' : 214, u'ỗ' : 214, u'ộ' : 212,
u'ớ' : 45, u'ờ' : 32, u'ở' : 214, u'ỡ' : 214, u'ợ' : 212,
u'ú' : 45, u'ù' : 32, u'ủ' : 214, u'ũ' : 214, u'ụ' : 212,
u'ứ' : 45, u'ừ' : 32, u'ử' : 214, u'ữ' : 214, u'ự' : 212,
u'ý' : 45, u'ỳ' : 32, u'ỷ' : 214, u'ỹ' : 214, u'ỵ' : 212,
}
S_tones_p = { u'á' : 5, u'à' : 2, u'ả' : 4, u'ã' : 4, u'ạ' : 6,
u'ấ' : 5, u'ầ' : 2, u'ẩ' : 4, u'ẫ' : 4, u'ậ' : 6,
u'ắ' : 5, u'ằ' : 2, u'ẳ' : 4, u'ẵ' : 4, u'ặ' : 6,
u'é' : 5, u'è' : 2, u'ẻ' : 4, u'ẽ' : 4, u'ẹ' : 6,
u'ế' : 5, u'ề' : 2, u'ể' : 4, u'ễ' : 4, u'ệ' : 6,
u'í' : 5, u'ì' : 2, u'ỉ' : 4, u'ĩ' : 4, u'ị' : 6,
u'ó' : 5, u'ò' : 2, u'ỏ' : 4, u'õ' : 4, u'ọ' : 6,
u'ố' : 5, u'ồ' : 2, u'ổ' : 4, u'ỗ' : 4, u'ộ' : 6,
u'ớ' : 5, u'ờ' : 2, u'ở' : 4, u'ỡ' : 4, u'ợ' : 6,
u'ú' : 5, u'ù' : 2, u'ủ' : 4, u'ũ' : 4, u'ụ' : 6,
u'ứ' : 5, u'ừ' : 2, u'ử' : 4, u'ữ' : 4, u'ự' : 6,
u'ý' : 5, u'ỳ' : 2, u'ỷ' : 4, u'ỹ' : 4, u'ỵ' : 6,
}
S_gi = { u'gi' : u'ji', u'gí': u'ji', u'gì' : u'ji', u'gì' : u'ji', u'gĩ' : u'ji', u'gị' : u'ji' }
S_qu = {u'quy' : u'wi', u'qúy' : u'wi', u'qùy' : u'wi', u'qủy' : u'wi', u'qũy' : u'wi', u'qụy' : u'wi'}
################################################3
import sys, codecs, re
from io import StringIO
from optparse import OptionParser
from string import punctuation
def trans(word, dialect, glottal, pham, cao, palatals):
# This looks ugly, but newer versions of python complain about "from x import *" syntax
if dialect == 'n':
onsets, nuclei, codas, tones, onglides, offglides, onoffglides, qu, gi = N_onsets, N_nuclei, N_codas, N_tones, N_onglides, N_offglides, N_onoffglides, N_qu, N_gi
elif dialect == 'c':
onsets, nuclei, codas, tones, onglides, offglides, onoffglides, qu, gi = C_onsets, C_nuclei, C_codas, C_tones, C_onglides, C_offglides, C_onoffglides, C_qu, C_gi
elif dialect == 's':
onsets, nuclei, codas, tones, onglides, offglides, onoffglides, qu, gi = S_onsets, S_nuclei, S_codas, S_tones, S_onglides, S_offglides, S_onoffglides, S_qu, S_gi
#Custom
onsets, nuclei, codas, onglides, offglides, onoffglides, qu, gi = Cus_onsets, Cus_nuclei, Cus_codas, Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi
if pham or cao:
if dialect == 'n': tones_p = N_tones_p
if dialect == 'c': tones_p = C_tones_p
if dialect == 's': tones_p = S_tones_p
#Custom
tones_p = Cus_tones_p
tones = tones_p
ons = ''
nuc = ''
cod = ''
ton = 0
oOffset = 0
cOffset = 0
l = len(word)
if l > 0:
if word[0:3] in onsets: # if onset is 'ngh'
ons = onsets[word[0:3]]
oOffset = 3
elif word[0:2] in onsets: # if onset is 'nh', 'gh', 'kʷ' etc
ons = onsets[word[0:2]]
oOffset = 2
elif word[0] in onsets: # if single onset
ons = onsets[word[0]]
oOffset = 1
if word[l-2:l] in codas: # if two-character coda
cod = codas[word[l-2:l]]
cOffset = 2
elif word[l-1] in codas: # if one-character coda
cod = codas[word[l-1]]
cOffset = 1
#if word[0:2] == u'gi' and cod and len(word) == 3: # if you just have 'gi' and a coda...
if word[0:2] in gi and cod and len(word) == 3: # if you just have 'gi' and a coda...
nucl = u'i'
ons = u'z'
else:
nucl = word[oOffset:l-cOffset]
if nucl in nuclei:
if oOffset == 0:
if glottal == 1:
if word[0] not in onsets: # if there isn't an onset....
ons = u'ʔ'+nuclei[nucl] # add a glottal stop
else: # otherwise...
nuc = nuclei[nucl] # there's your nucleus
else:
nuc = nuclei[nucl] # there's your nucleus
else: # otherwise...
nuc = nuclei[nucl] # there's your nucleus
elif nucl in onglides and ons != u'kw': # if there is an onglide...
nuc = onglides[nucl] # modify the nuc accordingly
if ons: # if there is an onset...
ons = ons+u'w' # labialize it, but...
else: # if there is no onset...
ons = u'w' # add a labiovelar onset
elif nucl in onglides and ons == u'kw':
nuc = onglides[nucl]
elif nucl in onoffglides:
cod = onoffglides[nucl][-1]
nuc = onoffglides[nucl][0:-1]
if ons != u'kw':
if ons:
ons = ons+u'w'
else:
ons = u'w'
elif nucl in offglides:
cod = offglides[nucl][-1]
nuc = offglides[nucl][:-1]
elif word in gi: # if word == 'gi', 'gì',...
ons = gi[word][0]
nuc = gi[word][1]
elif word in qu: # if word == 'quy', 'qúy',...
ons = qu[word][:-1]
nuc = qu[word][-1]
else:
# Something is non-Viet
return (None, None, None, None)
# Velar Fronting (Northern dialect)
if dialect == 'n':
if nuc == u'a':
if cod == u'k' and cOffset == 2: nuc = u'ɛ'
if cod == u'ɲ' and nuc == u'a': nuc = u'ɛ'
# Final palatals (Northern dialect)
if nuc not in [u'i', u'e', u'ɛ']:
if cod == u'ɲ':
cod = u'ɲ' # u'ŋ'
elif palatals != 1 and nuc in [u'i', u'e', u'ɛ']:
if cod == u'ɲ':
cod = u'ɲ'#u'ŋ'
if palatals == 1:
if cod == u'k' and nuc in [u'i', u'e', u'ɛ']:
cod = u'c'
# Velar Fronting (Southern and Central dialects)
else:
if nuc in [u'i', u'e']:
if cod == u'k': cod = u't'
if cod == u'ŋ': cod = u'n'
# There is also this reverse fronting, see Thompson 1965:94 ff.
elif nuc in [u'iə', u'ɯə', u'uə', u'u', u'ɯ', u'ɤ', u'o', u'ɔ', u'ă', u'ɤ̆']:
if cod == u't':
cod = u'k'
if cod == u'n': cod = u'ŋ'
# Monophthongization (Southern dialects: Thompson 1965: 86; Hoàng 1985: 181)
if dialect == 's':
if cod in [u'm', u'p']:
if nuc == u'iə': nuc = u'i'
if nuc == u'uə': nuc = u'u'
if nuc == u'ɯə': nuc = u'ɯ'
# Tones
# Modified 20 Sep 2008 to fix aberrant 33 error
tonelist = [tones[word[i]] for i in range(0,l) if word[i] in tones]
if tonelist:
ton = str(tonelist[len(tonelist)-1])
else:
if not (pham or cao):
if dialect == 'c':
ton = str('35')
else:
ton = str('33')
else:
ton = str('1')
# Modifications for closed syllables
if cOffset !=0:
# Obstruent-final nang tones are modal voice
if (dialect == 'n' or dialect == 's') and ton == u'21g' and cod in ['p', 't', 'k']:
#if ton == u'21\u02C0' and cod in ['p', 't', 'k']: # fixed 8 Nov 2016
ton = u'21'
# Modification for sắc in closed syllables (Northern and Central only)
if ((dialect == 'n' and ton == u'24') or (dialect == 'c' and ton == u'13')) and cod in ['p', 't', 'k']:
ton = u'45'
# Modification for 8-tone system
if cao == 1:
if ton == u'5' and cod in ['p', 't', 'k']:
ton = u'5b'
if ton == u'6' and cod in ['p', 't', 'k']:
ton = u'6b'
# labialized allophony (added 17.09.08)
if nuc in [u'u', u'o', u'ɔ']:
if cod == u'ŋ':
cod = u'ŋ͡m'
if cod == u'k':
cod = u'k͡p'
return (ons, nuc, cod, ton)
def convert(word, dialect, glottal, pham, cao, palatals, delimit):
"""Convert a single orthographic string to IPA."""
ons = ''
nuc = ''
cod = ''
ton = 0
seq = ''
try:
(ons, nuc, cod, ton) = trans(word, dialect, glottal, pham, cao, palatals)
if None in (ons, nuc, cod, ton):
seq = u'['+word+u']'
else:
seq = delimit+delimit.join(filter(None, (ons, nuc, cod, ton)))+delimit
except (TypeError):
pass
return seq
########################333
from vinorm import *
from underthesea import word_tokenize
import eng_to_ipa
SET=[S_onsets, S_nuclei, S_codas#, S_tones
, S_onglides, S_offglides, S_onoffglides, S_qu, S_gi, C_onsets, C_nuclei, C_codas#, C_tones
, C_onglides, C_offglides, C_onoffglides, C_qu, C_gi, N_onsets, N_nuclei, N_codas#, N_tones
, N_onglides, N_offglides, N_onoffglides, N_qu, N_gi, Cus_onsets, Cus_nuclei, Cus_codas#, N_tones
, Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi]
DICT={}
#144 in total
syms=['ɯəj', 'ɤ̆j', 'ʷiə', 'ɤ̆w', 'ɯəw', 'ʷet', 'iəw', 'uəj', 'ʷen', 'tʰw', 'ʷɤ̆', 'ʷiu', 'kwi', 'ŋ͡m', 'k͡p', 'cw', 'jw', 'uə', 'eə', 'bw', 'oj', 'ʷi', 'vw', 'ăw', 'ʈw', 'ʂw', 'aʊ', 'fw', 'ɛu', 'tʰ', 'tʃ', 'ɔɪ', 'xw', 'ʷɤ', 'ɤ̆', 'ŋw', 'ʊə', 'zi', 'ʷă', 'dw', 'eɪ', 'aɪ', 'ew', 'iə', 'ɣw', 'zw', 'ɯj', 'ʷɛ', 'ɯw', 'ɤj', 'ɔ:', 'əʊ', 'ʷa', 'mw', 'ɑ:', 'hw', 'ɔj', 'uj', 'lw', 'ɪə', 'ăj', 'u:', 'aw', 'ɛj', 'iw', 'aj', 'ɜ:', 'kw', 'nw', 't∫', 'ɲw', 'eo', 'sw', 'tw', 'ʐw', 'iɛ', 'ʷe', 'i:', 'ɯə', 'dʒ', 'ɲ', 'θ', 'ʌ', 'l', 'w', '1', 'ɪ', 'ɯ', 'd', '∫', 'p', 'ə', 'u', 'o', '3', 'ɣ', '!', 'ð', 'ʧ', '6', 'ʒ', 'ʐ', 'z', 'v', 'g', 'ă', '_', 'æ', 'ɤ', '2', 'ʤ', 'i', '.', 'ɒ', 'b', 'h', 'n', 'ʂ', 'ɔ', 'ɛ', 'k', 'm', '5', ' ', 'c', 'j', 'x', 'ʈ', ',', '4', 'ʊ', 's', 'ŋ', 'a', 'ʃ', '?', 'r', ':', 'η', 'f', ';', 'e', 't', "'"]
def Parsing(listParse, text, delimit):
undefine_symbol = "'"
if listParse == "default":
listParse=['ʷiə', 'uəj', 'iəw', 'k͡p', 'ʷɤ̆', 'ɤ̆j', 'ŋ͡m', 'kwi', 'ɤ̆w', 'ɯəj', 'ʷen', 'ʷiu', 'ʷet', 'ɯəw', 'ʷɛ', 'ʷɤ', 'ɯj', 'oj', 'ăw', 'zi', 'kw', 'aɪ', 'iɛ', 'ɤ̆', 'ɔ:', 'ăj', 'ʷa', 'eə', 'u:', 'uj', 'aʊ', 'uə', 'aj', 'iə', 'iw', 'əʊ', 'ɑ:', 'tʃ', 'ʷe', 'ɛu', 'ɔɪ', 'ʷi', 'eɪ', 'ɤj', 'ɯw', 'ɛj', 'ɔj', 'i:', 't∫', 'ɪə', 'ʷă', 'ɜ:', 'tʰ', 'dʒ', 'ew', 'ʊə', 'ɯə', 'aw', '3', 'θ', 'v', 'ʊ', 'ʤ', 'ɔ', '1', 'ʧ', 'ʈ', ' ', 'd', 'i', 'ɣ', 'ɲ', 'ɤ', '?', 'ɪ', 'l', '.', 'j', ':', 't', 'ʒ', 'ə', 'ʌ', 'm', '!', '∫', 'ð', 'u', 'e', 'w', 'p', 'ʃ', 'æ', "'", 'h', 'o', 'k', '5', 'g', '4', 'n', ';', 'r', 'b', 'ɯ', 'a', 's', 'ʐ', 'η', 'ŋ', 'ɒ', 'ʂ', '_', 'f', ',', 'ɛ', 'z', '6', '2', 'x', 'ă']
listParse.sort(reverse = True,key=len)
output=""
skip=0
for ic,char in enumerate(text):
#print(char,skip)
check = 0
if skip>0:
skip=skip-1
continue
for l in listParse:
if len(l) <= len(text[ic:]) and l == text[ic:ic+len(l)]:
output+=delimit+l
check =1
skip=len(l)-1
break
if check == 0:
#Case symbol not in list
if str(char) in ["ˈ","ˌ","*"]:
continue
print("this is not in symbol :"+ char+":")
output+=delimit+undefine_symbol
return output.rstrip()+delimit
#print("Parsing",Parsing("default","iu iu","|"))
def getSymbol():
for s in SET:
DICT.update(s)
list_phoneme=DICT.values()
list_phoneme=list(list_phoneme)
English_phoneme=["p","b","t","d","t∫","dʒ","k","g","f","v","ð","θ","s","z","∫","ʒ","m","n","η","l","r","w","j","ɪ","i:","ʊ","u:","e","ə","ɜ:","ɒ","ɔ:","æ","ʌ","ɑ:","ɪə","ʊə","eə","eɪ","ɔɪ","aɪ","əʊ","aʊ",'ʃ',"ʤ","ʧ"]
Special=['jw', 'ŋw', 'bw', 'vw', 'dw', 'eo', 'ʈw', 'mw', 'zw', 'fw', 'tw', 'tʰw', 'ɲw', 'cw', 'ʂw', 'ɣw', 'ʐw', 'xw', 'lw', 'hw', 'nw', 'sw', 'c']
word_pad = ["_"]
space = [" "]
tone=["1","2","3","4","5","6"]
punctuation = [".",",","!",":","?",";","'"] #" ' ( ) Have been removed due to none sound
modifi = ["k͡p","ŋ͡m"]
symbols = list_phoneme + space+word_pad + English_phoneme + punctuation + tone + modifi + Special
symbols = list(set(symbols))
symbols.sort(reverse = True,key=len)
return symbols
def vi2IPA_pitrain(text):
epi = epitran.Epitran('vie-Latn')
r=epi.transliterate(text)
return r
def T2IPA_split(text,delimit):
sys.path.append('./Rules') # make sure we can find the Rules files
#Setup option
glottal = 0
pham = 0
cao = 0
palatals = 0
tokenize = 0
dialect='n' #"c""s"
tone_type=0
if tone_type==0:
pham=1
else:
cao=1
#Input text
line = text
if line =='\n':
return ""
else:
compound = u''
ortho = u''
words = line.split()
## toss len==0 junk
words = [word for word in words if len(word)>0]
## hack to get rid of single hyphens or underscores
words = [word for word in words if word!=u'-']
words = [word for word in words if word!=u'_']
for i in range(0,len(words)):
word = words[i].strip()
ortho += word
word = word.strip(punctuation).lower()
## 29.03.16: check if tokenize is true
## if true, call this routine for each substring
## and re-concatenate
if (tokenize and '-' in word) or (tokenize and '_' in word):
substrings = re.split(r'(_|-)', word)
values = substrings[::2]
delimiters = substrings[1::2] + ['']
ipa = [convert(x, dialect, glottal, pham, cao, palatals, delimit).strip() for x in values]
seq = ''.join(v+d for v,d in zip(ipa, delimiters))
else:
seq = convert(word, dialect, glottal, pham, cao, palatals, delimit).strip()
# concatenate
if len(words) >= 2:
ortho += ' '
if i < len(words)-1:
seq = seq+u' '
compound = compound + seq
return compound
def T2IPA(text):
sys.path.append('./Rules') # make sure we can find the Rules files
#Setup option
glottal = 0
pham = 0
cao = 0
palatals = 0
tokenize = 0
delimit = ''
dialect='n' #"c""s"
tone_type=0
if tone_type==0:
pham=1
else:
cao=1
#Input text
line = text
if line =='\n':
return ""
else:
compound = u''
ortho = u''
words = line.split()
## toss len==0 junk
words = [word for word in words if len(word)>0]
## hack to get rid of single hyphens or underscores
words = [word for word in words if word!=u'-']
words = [word for word in words if word!=u'_']
for i in range(0,len(words)):
word = words[i].strip()
ortho += word
word = word.strip(punctuation).lower()
## 29.03.16: check if tokenize is true
## if true, call this routine for each substring
## and re-concatenate
if (tokenize and '-' in word) or (tokenize and '_' in word):
substrings = re.split(r'(_|-)', word)
values = substrings[::2]
delimiters = substrings[1::2] + ['']
ipa = [convert(x, dialect, glottal, pham, cao, palatals, delimit).strip() for x in values]
seq = ''.join(v+d for v,d in zip(ipa, delimiters))
else:
seq = convert(word, dialect, glottal, pham, cao, palatals, delimit).strip()
# concatenate
if len(words) >= 2:
ortho += ' '
if i < len(words)-1:
seq = seq+u' '
compound = compound + seq
return compound
EN={"a":"ây","ă":"á","â":"ớ","b":"bi","c":"si","d":"đi","đ":"đê","e":"i","ê":"ê","f":"ép","g":"giy","h":"ếch","i":"ai","j":"giây","k":"cây","l":"eo","m":"em","n":"en","o":"âu","ô":"ô","ơ":"ơ","p":"pi","q":"kiu","r":"a","s":"ét","t":"ti","u":"diu","ư":"ư","v":"vi","w":"đắp liu","x":"ít","y":"quai","z":"giét"}
import re
def vi2IPA_split(texts,delimit):
content=[]
with open("Popular.txt",encoding="utf-8") as f:
content=f.read().splitlines()
tess = texts.split(".")
Results =""
for text in tess:
print("------------------------------------------------------")
TN= TTSnorm(text)
print("------------------------------------------------------")
print("Text normalize: ",TN)
TK= word_tokenize(TN)
print("Vietnamese Tokenize: ",TK)
for iuv,under_valid in enumerate(TK):
token_under=under_valid.split(" ")
checkinvalid=0
print(token_under)
if len(token_under) >1:
for tok in token_under:
if tok not in content or "[" in T2IPA(tok):
checkinvalid=1
if checkinvalid==1:
TK = TK[:iuv] + TK[iuv+1 :]
for tok in reversed(token_under):
TK.insert(iuv, tok)
IPA=""
for tk in TK:
ipa = T2IPA_split(tk,delimit).replace(" ","_")
if ipa =="":
IPA+=delimit+tk+delimit+" "
elif ipa[0]=="[" and ipa[-1]=="]":
eng = eng_to_ipa.convert(tk)
if eng[-1] == "*":
if tk.lower().upper() == tk:
#print("ENGLISH",tk)
#Đọc tiếng anh từng chữ
letter2sound=""
for char in tk:
CHAR = str(char).lower()
if CHAR in list(EN.keys()):
letter2sound+=EN[CHAR]+" "
else:
letter2sound+=char+" "
IPA+=T2IPA_split(letter2sound,delimit)+" "
else:
#Giữ nguyên
IPA+=Parsing("default",tk.lower(),delimit)+" "
else:
IPA+=Parsing("default",eng,delimit)+" "
#Check tu dien tieng anh Etrain bưc
#Neu co Mapping
#Neu khong, check co nguyen am
#Neu co de nguyen
#Neu khong danh van
print(" ..................Out of domain word: " ,ipa)
else:
IPA+=ipa+" "
IPA=re.sub(delimit+'+', delimit, IPA)
IPA=re.sub(' +', ' ', IPA)
print("IPA Vietnamese: ",IPA)
print("------------------------------------------------------")
Results+= IPA.rstrip()+" "+delimit+"."+delimit+" "
#For checking: need much memory
'''
check_sym="ɯəjɤ̆jʷiəɤ̆wɯəwʷetiəwuəjʷentʰwʷɤ̆ʷiukwiŋ͡mk͡pcwjwuəeəbwojʷivwăwʈwʂwaʊfwɛutʰtʃɔɪxwʷɤɤ̆ŋwʊəziʷădweɪaɪewiəɣwzwɯjʷɛɯwɤjɔ:əʊʷamwɑ:hwɔjujlwɪəăju:awɛjiwajɜ:kwnwt∫ɲweoswtwʐwiɛʷei:ɯədʒɲθʌlw1ɪɯd∫pəuo3ɣ!ðʧ6ʒʐzvgă_æɤ2ʤi.ɒbhnʂɔɛkm5cjxʈ,4ʊsŋaʃ?r:ηf;et'"
for ine,res in enumerate(Results):
if res not in check_sym:
Results[ine]="'"
'''
return Results.rstrip()
def vi2IPA(text):
print("------------------------------------------------------")
TN= TTSnorm(text)
print("------------------------------------------------------")
print("Text normalize: ",TN)
TK= word_tokenize(TN)
print("Vietnamese Tokenize: ",TK)
IPA=""
for tk in TK:
ipa = T2IPA(tk).replace(" ","_")
if ipa =="":
IPA+=tk+" "
elif ipa[0]=="[" and ipa[-1]=="]":
eng = eng_to_ipa.convert(tk)
if eng[-1] == "*":
if tk.lower().upper() == tk:
#Đọc tiếng anh từng chữ
letter2sound=""
for char in tk:
CHAR = str(char).lower()
if CHAR in list(EN.keys()):
letter2sound+=EN[CHAR]+" "
else:
letter2sound+=char+" "
IPA+=T2IPA_split(letter2sound,"")+" "
else:
#Giữ nguyên
IPA+=Parsing("default",tk,"")+" "
else:
IPA+=eng+" "
#Check tu dien tieng anh Etrain bưc
#Neu co Mapping
#Neu khong, check co nguyen am
#Neu co de nguyen
#Neu khong danh van
print(" ..................Out of domain word: " ,ipa)
else:
IPA+=ipa+" "
IPA=re.sub(' +', ' ', IPA)
print("IPA Vietnamese: ",IPA)
print("------------------------------------------------------")
return IPA
def checkDict():
cout=0
trung=0
List_token=[]
List_pair = []
with open("Popular.txt", encoding="utf-8") as f:
content=f.read().splitlines()
for line in content:
#nor_tr = vi2IPA_pitrain(line)
#nor = vi2IPA(line)
nor = T2IPA(line)
if nor in List_token:
print(line + " -> "+nor)
trung +=1
List_pair.append(line)
List_token.append(nor)
if nor=="":
cout+=1
print(line)
print("Number of token can not convert: ",cout)
print("Number of token in the same mapping:",trung)
List_token = list(set(List_token))
#print(List_token)
print(len(List_token))
################################
#Looking for pair
Pair = {}
for lt in List_pair:
Pair[T2IPA(lt)] = lt
cout_same=0
with open("Popular.txt", encoding="utf-8") as f:
content=f.read().splitlines()
for line in content:
if T2IPA(line) in Pair:
lin2 =Pair[T2IPA(line)]
if line != lin2:
if (lin2[0]=="k" and line[0]=="c") or (lin2[-1] in ['i','í','ì','ĩ','ỉ','ị'] and line[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ']) or (lin2[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ'] and line[-1] in ['i','í','ì','ĩ','ỉ','ị']):
continue
cout_same+=1
print(line+ " <-> " + lin2 +"\t\t:\t\t"+T2IPA(line))
print("Same pair:" , cout_same)
#Các trường hợp dẫn đến trùng âm là:
# Phương ngữ khác nhau đã thống nhất ở list custom
# Các trường hợp có cách bỏ dấu khác nhau đều gộp chung làm một
#Disable convert from 'ɲ' to 'ɲ'' in north
#Các âm vòng ở đây i chang không vòm: không có w ở trước như: "oa,ua,a" đều như một > must consider (nhưng nếu thêm vào ảnh hưởng chữ qu cũng ra w)
#Try to add ʷ to all start o and u as in wiki
# *** Problem with ủy onglide and off-glide is a big problem
#Same positive
#k <-> c
#g <-> gh
#i <-> y
#Same negative / need to fix
#oe <-> uê -> fix oe from e to ɛ
#âm cuối: ch : k theo bắc : t theo nam -> custom k vì nó giảm trùng nhiều hơn 241->153 case
#Tuy nhiên cuối cùng "ch" "c" "t" không phân âm được => ý tưởng mượn "tʃ" trong teach and watch để thay thế => k for c , t for t, tʃ for ch
#Thay offglide: úy -> wi để phân biệt với úi
#Remain
'''
di <-> gi : zi1
dìm <-> gìm : zim2
din <-> gin : zin1
díp <-> gíp : zip5
gen <-> ghen : ɣɛn1
ghì <-> gì : ɣi2
ghích <-> gích : ɣitʃ5
ia <-> iê : iə1
iêu <-> yêu : iəw1
khoắng <-> khuắng : xwʷăŋ5
khỏe <-> khoẻ : xwʷɛ4
khua <-> khuơ : xuə1
lóe <-> loé : lwʷɛ5
ngét <-> nghét : ŋɛt5
ngễu <-> nghễu : ŋɛu3
nghía <-> ngía : ŋiə5
nghịu <-> ngịu : ŋiw6
nghoèo <-> ngoèo : ŋwew2
quít <-> quýt : kwit5
thủa <-> thuở : tʰuə4
tòe <-> toè : twʷɛ2
ua <-> uơ : uə1
ưa <-> ươ : ɯə1
xõa <-> xoã : swʷa3
'''
#Ở đây tiết kiệm chi phí chạy máy không normal phoneme về cường độ âm sắc chỉ dừng từ 1->6
#học ác cho kết quả "c" khác nhau
###################################################
checkDict()
#print(vi2IPA_split("!Singapo english? đại học là IUYE gì khôngtontaij NIYE BoOK","'"))
#check các ipa của tiếng anh
#print(vi2IPA_split("Another table was prepared to show available onsets. Onsets are splitted into 3 types. Type 1 are onsets which has one letter ","/"))
#Lọc bỏ dấu nhấn của tiếng anh "'"
#print(vi2IPA_split("speech? Secondly, we paper, we investigate work! One is that e language to another by","/").replace("/",""))
#Case need to be deal:
# NIYE BoOK
#print(len(getSymbol()))
#print(getSymbol())
'''
test="t"
if test in syms:
print(test)
else:
print("none")
'''
###################################################
#Step
#Vinorm
#Underthesea
#For each Convert to phoneme
#Nếu không được check phoneme tiếng anh
#Nếu không có trong từ tiếng anh -> đọc từng kí tự
#Now
#+Thêm kí tự IPA của tiếng ANH
#+Thêm xử lí case không có cũng như case Tiếng anh: => dùng etrain cho tiếng anh
#+Deal case thống nhất âm vực phoneme -> ok
#+Get lại bộ symbol | 1.398438 | 1 |
taskengine/sessions.py | retmas-dv/deftcore | 0 | 2248 | <filename>taskengine/sessions.py
__author__ = '<NAME>'
from django.contrib.sessions.base_session import AbstractBaseSession
from django.contrib.sessions.backends.db import SessionStore as DBStore
class CustomSession(AbstractBaseSession):
@classmethod
def get_session_store_class(cls):
return SessionStore
class Meta:
db_name = 'deft_adcr'
db_table = '"ATLAS_DEFT"."DJANGO_SESSION"'
class SessionStore(DBStore):
@classmethod
def get_model_class(cls):
return CustomSession
| 2.046875 | 2 |
tests/assignments/test_assign7.py | acc-cosc-1336/cosc-1336-spring-2018-vcruz350 | 0 | 2249 | import unittest
#write the import for function for assignment7 sum_list_values
from src.assignments.assignment7 import sum_list_values
class Test_Assign7(unittest.TestCase):
def sample_test(self):
self.assertEqual(1,1)
#create a test for the sum_list_values function with list elements:
# bill 23 16 19 22
def test_sum_w_23_16_19_22(self):
test_list = ['bill', 23, 16, 19, 22]
self.assertEqual(80, sum_list_values(test_list))
#unittest.main(verbosity=2)
| 3.453125 | 3 |
setec/__init__.py | kgriffs/setec | 0 | 2250 | <filename>setec/__init__.py<gh_stars>0
# Copyright 2018 by <NAME>
#
# 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 base64 import b64decode, b64encode
import msgpack
import nacl.encoding
import nacl.secret
import nacl.signing
import nacl.utils
from .version import __version__ # NOQA
class Signer:
"""Message signer based on Ed25519 and nacl.signing.
Arguments:
key (str): Base64-encoded key obtained from keygen()
"""
__slots__ = ('_signing_key',)
def __init__(self, skey):
self._signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder)
@staticmethod
def keygen():
signing_key = nacl.signing.SigningKey.generate()
return (
signing_key.encode(nacl.encoding.Base64Encoder).decode(),
signing_key.verify_key.encode(nacl.encoding.Base64Encoder).decode(),
)
@staticmethod
def vkey(skey):
signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder)
return signing_key.verify_key.encode(nacl.encoding.Base64Encoder)
def signb(self, message):
"""Sign a binary message with its signature attached.
Arguments:
message(bytes): Data to sign.
Returns:
bytes: Signed message
"""
return self._signing_key.sign(message)
def pack(self, doc):
return b64encode(self.packb(doc)).decode()
def packb(self, doc):
packed = msgpack.packb(doc, encoding='utf-8', use_bin_type=True)
return self.signb(packed)
class Verifier:
"""Signature verifier based on Ed25519 and nacl.signing.
Arguments:
key (str): Base64-encoded verify key
"""
__slots__ = ('_verify_key',)
def __init__(self, vkey):
self._verify_key = nacl.signing.VerifyKey(vkey, nacl.encoding.Base64Encoder)
def verifyb(self, message):
"""Verify a signed binary message.
Arguments:
message(bytes): Data to verify.
Returns:
bytes: The orignal message, sans signature.
"""
return self._verify_key.verify(message)
def unpack(self, packed):
return self.unpackb(b64decode(packed))
def unpackb(self, packed):
packed = self.verifyb(packed)
return msgpack.unpackb(packed, raw=False, encoding='utf-8')
class BlackBox:
"""Encryption engine based on PyNaCl's SecretBox (Salsa20/Poly1305).
Warning per the SecretBox docs:
Once you’ve decrypted the message you’ve demonstrated the ability to
create arbitrary valid messages, so messages you send are repudiable.
For non-repudiable messages, sign them after encryption.
(See also: https://pynacl.readthedocs.io/en/stable/signing)
Arguments:
key (str): Base64-encoded key obtained from keygen()
"""
__slots__ = ('_box',)
def __init__(self, key):
self._box = nacl.secret.SecretBox(b64decode(key))
@staticmethod
def keygen():
return b64encode(nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)).decode()
def encrypt(self, doc, signer=None):
"""Serialize and encrypt a document to Base64-encoded ciphertext.
Arguments:
doc: The string, dict, array, or other JSON-compatible
object to serialize and encrypt.
Keyword Arguments:
signer: An instance of Signer to use in signing the result. If
not provided, the ciphertext is not signed.
Returns:
str: Ciphertext
"""
data = msgpack.packb(doc, encoding='utf-8', use_bin_type=True)
ciphertext = self._box.encrypt(data)
if signer:
ciphertext = signer.signb(ciphertext)
return b64encode(ciphertext).decode()
def decrypt(self, ciphertext, verifier=None):
"""Unpack Base64-encoded ciphertext.
Arguments:
ciphertext (bytes): Ciphertext to decrypt and deserialize.
Keyword Arguments:
verifier: An instance of Verifier to use in verifying the
signed ciphertext. If not provided, the ciphertext is
assumed to be unsigned.
Returns:
doc: Deserialized JSON-compatible object.
"""
ciphertext = b64decode(ciphertext)
if verifier:
ciphertext = verifier.verifyb(ciphertext)
data = self._box.decrypt(ciphertext)
return msgpack.unpackb(data, raw=False, encoding='utf-8')
| 2.0625 | 2 |
blender/arm/logicnode/native/LN_detect_mobile_browser.py | niacdoial/armory | 0 | 2251 | from arm.logicnode.arm_nodes import *
class DetectMobileBrowserNode(ArmLogicTreeNode):
"""Determines the mobile browser or not (works only for web browsers)."""
bl_idname = 'LNDetectMobileBrowserNode'
bl_label = 'Detect Mobile Browser'
arm_version = 1
def init(self, context):
super(DetectMobileBrowserNode, self).init(context)
self.add_output('NodeSocketBool', 'Mobile') | 2.390625 | 2 |
corehq/apps/dump_reload/tests/test_sql_dump_load.py | andyasne/commcare-hq | 471 | 2252 | <gh_stars>100-1000
import inspect
import json
import uuid
from collections import Counter
from datetime import datetime
from io import StringIO
import mock
from django.contrib.admin.utils import NestedObjects
from django.db import transaction, IntegrityError
from django.db.models.signals import post_delete, post_save
from django.test import SimpleTestCase, TestCase
from nose.tools import nottest
from casexml.apps.case.mock import CaseFactory, CaseIndex, CaseStructure
from corehq.apps.commtrack.helpers import make_product
from corehq.apps.commtrack.tests.util import get_single_balance_block
from corehq.apps.domain.models import Domain
from corehq.apps.dump_reload.sql import SqlDataDumper, SqlDataLoader
from corehq.apps.dump_reload.sql.dump import (
get_model_iterator_builders_to_dump,
get_objects_to_dump,
)
from corehq.apps.dump_reload.sql.load import (
DefaultDictWithKey,
constraint_checks_deferred,
)
from corehq.apps.hqcase.utils import submit_case_blocks
from corehq.apps.products.models import SQLProduct
from corehq.apps.zapier.consts import EventTypes
from corehq.apps.zapier.models import ZapierSubscription
from corehq.apps.zapier.signals.receivers import (
zapier_subscription_post_delete,
)
from corehq.blobs.models import BlobMeta
from corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL
from corehq.form_processor.interfaces.dbaccessors import (
CaseAccessors,
FormAccessors,
)
from corehq.form_processor.models import (
CaseTransaction,
CommCareCaseIndexSQL,
CommCareCaseSQL,
LedgerTransaction,
LedgerValue,
XFormInstanceSQL,
)
from corehq.form_processor.tests.utils import (
FormProcessorTestUtils,
create_form_for_test,
sharded,
)
from corehq.messaging.scheduling.scheduling_partitioned.models import (
AlertScheduleInstance,
)
class BaseDumpLoadTest(TestCase):
@classmethod
def setUpClass(cls):
post_delete.disconnect(zapier_subscription_post_delete, sender=ZapierSubscription)
super(BaseDumpLoadTest, cls).setUpClass()
cls.domain_name = uuid.uuid4().hex
cls.domain = Domain(name=cls.domain_name)
cls.domain.save()
cls.default_objects_counts = Counter({})
@classmethod
def tearDownClass(cls):
cls.domain.delete()
super(BaseDumpLoadTest, cls).tearDownClass()
post_delete.connect(zapier_subscription_post_delete, sender=ZapierSubscription)
def delete_sql_data(self):
delete_domain_sql_data_for_dump_load_test(self.domain_name)
def tearDown(self):
self.delete_sql_data()
super(BaseDumpLoadTest, self).tearDown()
def _dump_and_load(self, expected_dump_counts, load_filter=None, expected_load_counts=None, dumper_fn=None):
expected_load_counts = expected_load_counts or expected_dump_counts
expected_dump_counts.update(self.default_objects_counts)
models = list(expected_dump_counts)
self._check_signals_handle_raw(models)
output_stream = StringIO()
if dumper_fn:
dumper_fn(output_stream)
else:
SqlDataDumper(self.domain_name, [], []).dump(output_stream)
self.delete_sql_data()
# make sure that there's no data left in the DB
objects_remaining = list(get_objects_to_dump(self.domain_name, [], []))
object_classes = [obj.__class__.__name__ for obj in objects_remaining]
counts = Counter(object_classes)
self.assertEqual([], objects_remaining, 'Not all data deleted: {}'.format(counts))
# Dump
actual_model_counts, dump_lines = self._parse_dump_output(output_stream)
expected_model_counts = _normalize_object_counter(expected_dump_counts)
self.assertDictEqual(dict(expected_model_counts), dict(actual_model_counts))
# Load
loader = SqlDataLoader(object_filter=load_filter)
loaded_model_counts = loader.load_objects(dump_lines)
normalized_expected_loaded_counts = _normalize_object_counter(expected_load_counts, for_loaded=True)
self.assertDictEqual(dict(normalized_expected_loaded_counts), dict(loaded_model_counts))
self.assertEqual(sum(expected_load_counts.values()), sum(loaded_model_counts.values()))
return dump_lines
def _parse_dump_output(self, output_stream):
dump_output = output_stream.getvalue().split('\n')
dump_lines = [line.strip() for line in dump_output if line.strip()]
actual_model_counts = Counter([json.loads(line)['model'] for line in dump_lines])
return actual_model_counts, dump_lines
def _check_signals_handle_raw(self, models):
"""Ensure that any post_save signal handlers have been updated
to handle 'raw' calls."""
whitelist_receivers = [
'django_digest.models._post_save_persist_partial_digests'
]
for model in models:
for receiver in post_save._live_receivers(model):
receiver_path = receiver.__module__ + '.' + receiver.__name__
if receiver_path in whitelist_receivers:
continue
args = inspect.getargspec(receiver).args
message = 'Signal handler "{}" for model "{}" missing raw arg'.format(
receiver, model
)
self.assertIn('raw', args, message)
@nottest
def delete_domain_sql_data_for_dump_load_test(domain_name):
for model_class, builder in get_model_iterator_builders_to_dump(domain_name, [], []):
for iterator in builder.querysets():
with transaction.atomic(using=iterator.db), \
constraint_checks_deferred(iterator.db):
collector = NestedObjects(using=iterator.db)
collector.collect(iterator)
collector.delete()
assert [] == list(get_objects_to_dump(domain_name, [], [])), "Not all SQL objects deleted"
@sharded
class TestSQLDumpLoadShardedModels(BaseDumpLoadTest):
maxDiff = None
@classmethod
def setUpClass(cls):
super(TestSQLDumpLoadShardedModels, cls).setUpClass()
cls.factory = CaseFactory(domain=cls.domain_name)
cls.form_accessors = FormAccessors(cls.domain_name)
cls.case_accessors = CaseAccessors(cls.domain_name)
cls.product = make_product(cls.domain_name, 'A Product', 'prodcode_a')
cls.default_objects_counts.update({SQLProduct: 1})
@classmethod
def tearDownClass(cls):
FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain_name)
super(TestSQLDumpLoadShardedModels, cls).tearDownClass()
def test_dump_load_form(self):
expected_object_counts = Counter({
XFormInstanceSQL: 2,
BlobMeta: 2
})
pre_forms = [
create_form_for_test(self.domain_name),
create_form_for_test(self.domain_name)
]
self._dump_and_load(expected_object_counts)
form_ids = self.form_accessors.get_all_form_ids_in_domain('XFormInstance')
self.assertEqual(set(form_ids), set(form.form_id for form in pre_forms))
for pre_form in pre_forms:
post_form = self.form_accessors.get_form(pre_form.form_id)
self.assertDictEqual(pre_form.to_json(), post_form.to_json())
def test_sql_dump_load_case(self):
expected_object_counts = Counter({
XFormInstanceSQL: 2,
BlobMeta: 2,
CommCareCaseSQL: 2,
CaseTransaction: 3,
CommCareCaseIndexSQL: 1
})
pre_cases = self.factory.create_or_update_case(
CaseStructure(
attrs={'case_name': 'child', 'update': {'age': 3, 'diabetic': False}, 'create': True},
indices=[
CaseIndex(CaseStructure(attrs={'case_name': 'parent', 'update': {'age': 42}, 'create': True})),
]
)
)
pre_cases[0] = self.factory.create_or_update_case(CaseStructure(
case_id=pre_cases[0].case_id,
attrs={'external_id': 'billie jean', 'update': {'name': '<NAME>'}}
))[0]
self._dump_and_load(expected_object_counts)
case_ids = self.case_accessors.get_case_ids_in_domain()
self.assertEqual(set(case_ids), set(case.case_id for case in pre_cases))
for pre_case in pre_cases:
post_case = self.case_accessors.get_case(pre_case.case_id)
self.assertDictEqual(pre_case.to_json(), post_case.to_json())
def test_ledgers(self):
expected_object_counts = Counter({
XFormInstanceSQL: 3,
BlobMeta: 3,
CommCareCaseSQL: 1,
CaseTransaction: 3,
LedgerValue: 1,
LedgerTransaction: 2
})
case = self.factory.create_case()
submit_case_blocks([
get_single_balance_block(case.case_id, self.product._id, 10)
], self.domain_name)
submit_case_blocks([
get_single_balance_block(case.case_id, self.product._id, 5)
], self.domain_name)
pre_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id)
pre_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id)
self.assertEqual(1, len(pre_ledger_values))
self.assertEqual(2, len(pre_ledger_transactions))
self._dump_and_load(expected_object_counts)
post_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id)
post_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id)
self.assertEqual(1, len(post_ledger_values))
self.assertEqual(2, len(post_ledger_transactions))
self.assertEqual(pre_ledger_values[0].ledger_reference, post_ledger_values[0].ledger_reference)
self.assertDictEqual(pre_ledger_values[0].to_json(), post_ledger_values[0].to_json())
pre_ledger_transactions = sorted(pre_ledger_transactions, key=lambda t: t.pk)
post_ledger_transactions = sorted(post_ledger_transactions, key=lambda t: t.pk)
for pre, post in zip(pre_ledger_transactions, post_ledger_transactions):
self.assertEqual(str(pre), str(post))
class TestSQLDumpLoad(BaseDumpLoadTest):
def test_case_search_config(self):
from corehq.apps.case_search.models import CaseSearchConfig, FuzzyProperties
expected_object_counts = Counter({
CaseSearchConfig: 1,
FuzzyProperties: 2,
})
pre_config, created = CaseSearchConfig.objects.get_or_create(pk=self.domain_name)
pre_config.enabled = True
pre_fuzzies = [
FuzzyProperties(domain=self.domain, case_type='dog', properties=['breed', 'color']),
FuzzyProperties(domain=self.domain, case_type='owner', properties=['name']),
]
for fuzzy in pre_fuzzies:
fuzzy.save()
pre_config.fuzzy_properties.set(pre_fuzzies)
pre_config.save()
self._dump_and_load(expected_object_counts)
post_config = CaseSearchConfig.objects.get(domain=self.domain_name)
self.assertTrue(post_config.enabled)
self.assertEqual(pre_config.fuzzy_properties, post_config.fuzzy_properties)
post_fuzzies = FuzzyProperties.objects.filter(domain=self.domain_name)
self.assertEqual(set(f.case_type for f in post_fuzzies), {'dog', 'owner'})
def test_users(self):
from corehq.apps.users.models import CommCareUser
from corehq.apps.users.models import WebUser
from django.contrib.auth.models import User
expected_object_counts = Counter({User: 3})
ccuser_1 = CommCareUser.create(
domain=self.domain_name,
username='user_1',
password='<PASSWORD>',
created_by=None,
created_via=None,
email='<EMAIL>',
)
ccuser_2 = CommCareUser.create(
domain=self.domain_name,
username='user_2',
password='<PASSWORD>',
created_by=None,
created_via=None,
email='<EMAIL>',
)
web_user = WebUser.create(
domain=self.domain_name,
username='webuser_t1',
password='<PASSWORD>',
created_by=None,
created_via=None,
email='<EMAIL>',
)
self.addCleanup(ccuser_1.delete, self.domain_name, deleted_by=None)
self.addCleanup(ccuser_2.delete, self.domain_name, deleted_by=None)
self.addCleanup(web_user.delete, self.domain_name, deleted_by=None)
self._dump_and_load(expected_object_counts)
def test_dump_roles(self):
from corehq.apps.users.models import UserRole, Permissions, RoleAssignableBy, RolePermission
expected_object_counts = Counter({
UserRole: 2,
RolePermission: 11,
RoleAssignableBy: 1
})
role1 = UserRole.create(self.domain_name, 'role1')
role2 = UserRole.create(
self.domain_name, 'role1',
permissions=Permissions(edit_web_users=True),
assignable_by=[role1.id]
)
self.addCleanup(role1.delete)
self.addCleanup(role2.delete)
self._dump_and_load(expected_object_counts)
role1_loaded = UserRole.objects.get(id=role1.id)
role2_loaded = UserRole.objects.get(id=role2.id)
self.assertEqual(role1_loaded.permissions.to_list(), Permissions().to_list())
self.assertEqual(role1_loaded.assignable_by, [])
self.assertEqual(role2_loaded.permissions.to_list(), Permissions(edit_web_users=True).to_list())
self.assertEqual(role2_loaded.assignable_by, [role1_loaded.get_id])
def test_device_logs(self):
from corehq.apps.receiverwrapper.util import submit_form_locally
from phonelog.models import DeviceReportEntry, ForceCloseEntry, UserEntry, UserErrorEntry
from corehq.apps.users.models import CommCareUser
from django.contrib.auth.models import User
expected_object_counts = Counter({
User: 1,
DeviceReportEntry: 7,
UserEntry: 1,
UserErrorEntry: 2,
ForceCloseEntry: 1
})
user = CommCareUser.create(
domain=self.domain_name,
username='user_1',
password='<PASSWORD>',
created_by=None,
created_via=None,
email='<EMAIL>',
uuid='428d454aa9abc74e1964e16d3565d6b6' # match ID in devicelog.xml
)
self.addCleanup(user.delete, self.domain_name, deleted_by=None)
with open('corehq/ex-submodules/couchforms/tests/data/devicelogs/devicelog.xml', 'rb') as f:
xml = f.read()
submit_form_locally(xml, self.domain_name)
self._dump_and_load(expected_object_counts)
def test_demo_user_restore(self):
from corehq.apps.users.models import CommCareUser
from corehq.apps.ota.models import DemoUserRestore
from django.contrib.auth.models import User
expected_object_counts = Counter({
User: 1,
DemoUserRestore: 1
})
user_id = uuid.uuid4().hex
user = CommCareUser.create(
domain=self.domain_name,
username='user_1',
password='<PASSWORD>',
created_by=None,
created_via=None,
email='<EMAIL>',
uuid=user_id
)
self.addCleanup(user.delete, self.domain_name, deleted_by=None)
DemoUserRestore(
demo_user_id=user_id,
restore_blob_id=uuid.uuid4().hex,
content_length=1027,
restore_comment="Test migrate demo user restore"
).save()
self._dump_and_load(expected_object_counts)
def test_products(self):
from corehq.apps.products.models import SQLProduct
expected_object_counts = Counter({SQLProduct: 3})
p1 = SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1')
p2 = SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2')
parchived = SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3', is_archived=True)
self._dump_and_load(expected_object_counts)
self.assertEqual(2, SQLProduct.active_objects.filter(domain=self.domain_name).count())
all_active = SQLProduct.active_objects.filter(domain=self.domain_name).all()
self.assertTrue(p1 in all_active)
self.assertTrue(p2 in all_active)
self.assertTrue(parchived not in all_active)
def test_location_type(self):
from corehq.apps.locations.models import LocationType
from corehq.apps.locations.tests.test_location_types import make_loc_type
expected_object_counts = Counter({LocationType: 7})
state = make_loc_type('state', domain=self.domain_name)
district = make_loc_type('district', state, domain=self.domain_name)
section = make_loc_type('section', district, domain=self.domain_name)
block = make_loc_type('block', district, domain=self.domain_name)
center = make_loc_type('center', block, domain=self.domain_name)
county = make_loc_type('county', state, domain=self.domain_name)
city = make_loc_type('city', county, domain=self.domain_name)
self._dump_and_load(expected_object_counts)
hierarchy = LocationType.objects.full_hierarchy(self.domain_name)
desired_hierarchy = {
state.id: (
state,
{
district.id: (
district,
{
section.id: (section, {}),
block.id: (block, {
center.id: (center, {}),
}),
},
),
county.id: (
county,
{city.id: (city, {})},
),
},
),
}
self.assertEqual(hierarchy, desired_hierarchy)
def test_location(self):
from corehq.apps.locations.models import LocationType, SQLLocation
from corehq.apps.locations.tests.util import setup_locations_and_types
expected_object_counts = Counter({LocationType: 3, SQLLocation: 11})
location_type_names = ['province', 'district', 'city']
location_structure = [
('Western Cape', [
('Cape Winelands', [
('Stellenbosch', []),
('Paarl', []),
]),
('Cape Town', [
('Cape Town City', []),
])
]),
('Gauteng', [
('Ekurhuleni ', [
('Alberton', []),
('Benoni', []),
('Springs', []),
]),
]),
]
location_types, locations = setup_locations_and_types(
self.domain_name,
location_type_names,
[],
location_structure,
)
self._dump_and_load(expected_object_counts)
names = ['Cape Winelands', 'Paarl', 'Cape Town']
location_ids = [locations[name].location_id for name in names]
result = SQLLocation.objects.get_locations_and_children(location_ids)
self.assertItemsEqual(
[loc.name for loc in result],
['Cape Winelands', 'Stellenbosch', 'Paarl', 'Cape Town', 'Cape Town City']
)
result = SQLLocation.objects.get_locations_and_children([locations['Gauteng'].location_id])
self.assertItemsEqual(
[loc.name for loc in result],
['Gauteng', 'Ekurhuleni ', 'Alberton', 'Benoni', 'Springs']
)
def test_sms(self):
from corehq.apps.sms.models import PhoneNumber, MessagingEvent, MessagingSubEvent
expected_object_counts = Counter({PhoneNumber: 1, MessagingEvent: 1, MessagingSubEvent: 1})
phone_number = PhoneNumber(
domain=self.domain_name,
owner_doc_type='CommCareCase',
owner_id='fake-owner-id1',
phone_number='99912341234',
backend_id=None,
ivr_backend_id=None,
verified=True,
is_two_way=True,
pending_verification=False,
contact_last_modified=datetime.utcnow()
)
phone_number.save()
event = MessagingEvent.objects.create(
domain=self.domain_name,
date=datetime.utcnow(),
source=MessagingEvent.SOURCE_REMINDER,
content_type=MessagingEvent.CONTENT_SMS,
status=MessagingEvent.STATUS_COMPLETED
)
MessagingSubEvent.objects.create(
parent=event,
date=datetime.utcnow(),
recipient_type=MessagingEvent.RECIPIENT_CASE,
content_type=MessagingEvent.CONTENT_SMS,
status=MessagingEvent.STATUS_COMPLETED
)
self._dump_and_load(expected_object_counts)
def test_message_scheduling(self):
AlertScheduleInstance(
schedule_instance_id=uuid.uuid4(),
domain=self.domain_name,
recipient_type='CommCareUser',
recipient_id=uuid.uuid4().hex,
current_event_num=0,
schedule_iteration_num=1,
next_event_due=datetime(2017, 3, 1),
active=True,
alert_schedule_id=uuid.uuid4(),
).save()
self._dump_and_load({AlertScheduleInstance: 1})
def test_mobile_backend(self):
from corehq.apps.sms.models import (
SQLMobileBackend,
SQLMobileBackendMapping,
)
domain_backend = SQLMobileBackend.objects.create(
domain=self.domain_name,
name='test-domain-mobile-backend',
display_name='Test Domain Mobile Backend',
hq_api_id='TDMB',
inbound_api_key='test-domain-mobile-backend-inbound-api-key',
supported_countries=["*"],
backend_type=SQLMobileBackend.SMS,
is_global=False,
)
SQLMobileBackendMapping.objects.create(
domain=self.domain_name,
backend=domain_backend,
backend_type=SQLMobileBackend.SMS,
prefix='123',
)
global_backend = SQLMobileBackend.objects.create(
domain=None,
name='test-global-mobile-backend',
display_name='Test Global Mobile Backend',
hq_api_id='TGMB',
inbound_api_key='test-global-mobile-backend-inbound-api-key',
supported_countries=["*"],
backend_type=SQLMobileBackend.SMS,
is_global=True,
)
SQLMobileBackendMapping.objects.create(
domain=self.domain_name,
backend=global_backend,
backend_type=SQLMobileBackend.SMS,
prefix='*',
)
self._dump_and_load({
SQLMobileBackendMapping: 1,
SQLMobileBackend: 1,
})
self.assertEqual(SQLMobileBackend.objects.first().domain,
self.domain_name)
self.assertEqual(SQLMobileBackendMapping.objects.first().domain,
self.domain_name)
def test_case_importer(self):
from corehq.apps.case_importer.tracking.models import (
CaseUploadFileMeta,
CaseUploadFormRecord,
CaseUploadRecord,
)
upload_file_meta = CaseUploadFileMeta.objects.create(
identifier=uuid.uuid4().hex,
filename='picture.jpg',
length=1024,
)
case_upload_record = CaseUploadRecord.objects.create(
domain=self.domain_name,
upload_id=uuid.uuid4(),
task_id=uuid.uuid4(),
couch_user_id=uuid.uuid4().hex,
case_type='person',
upload_file_meta=upload_file_meta,
)
CaseUploadFormRecord.objects.create(
case_upload_record=case_upload_record,
form_id=uuid.uuid4().hex,
)
self._dump_and_load(Counter({
CaseUploadFileMeta: 1,
CaseUploadRecord: 1,
CaseUploadFormRecord: 1,
}))
def test_transifex(self):
from corehq.apps.translations.models import TransifexProject, TransifexOrganization
org = TransifexOrganization.objects.create(slug='test', name='demo', api_token='<PASSWORD>')
TransifexProject.objects.create(
organization=org, slug='testp', name='demop', domain=self.domain_name
)
TransifexProject.objects.create(
organization=org, slug='testp1', name='demop1', domain=self.domain_name
)
self._dump_and_load(Counter({TransifexOrganization: 1, TransifexProject: 2}))
def test_filtered_dump_load(self):
from corehq.apps.locations.tests.test_location_types import make_loc_type
from corehq.apps.products.models import SQLProduct
from corehq.apps.locations.models import LocationType
make_loc_type('state', domain=self.domain_name)
SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1')
expected_object_counts = Counter({LocationType: 1, SQLProduct: 1})
self._dump_and_load(expected_object_counts, load_filter='sqlproduct', expected_load_counts=Counter({SQLProduct: 1}))
self.assertEqual(0, LocationType.objects.count())
def test_sms_content(self):
from corehq.messaging.scheduling.models import AlertSchedule, SMSContent, AlertEvent
from corehq.messaging.scheduling.scheduling_partitioned.dbaccessors import \
delete_alert_schedule_instances_for_schedule
schedule = AlertSchedule.create_simple_alert(self.domain, SMSContent())
schedule.set_custom_alert(
[
(AlertEvent(minutes_to_wait=5), SMSContent()),
(AlertEvent(minutes_to_wait=15), SMSContent()),
]
)
self.addCleanup(lambda: delete_alert_schedule_instances_for_schedule(AlertScheduleInstance, schedule.schedule_id))
self._dump_and_load(Counter({AlertSchedule: 1, AlertEvent: 2, SMSContent: 2}))
def test_zapier_subscription(self):
ZapierSubscription.objects.create(
domain=self.domain_name,
case_type='case_type',
event_name=EventTypes.NEW_CASE,
url='example.com',
user_id='user_id',
)
self._dump_and_load(Counter({ZapierSubscription: 1}))
@mock.patch("corehq.apps.dump_reload.sql.load.ENQUEUE_TIMEOUT", 1)
class TestSqlLoadWithError(BaseDumpLoadTest):
def setUp(self):
self.products = [
SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1'),
SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2'),
SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3'),
]
def test_load_error_queue_full(self):
"""Blocks when sending 'test3'"""
self._load_with_errors(chunk_size=1)
def test_load_error_queue_full_on_terminate(self):
"""Blocks when sending ``None`` into the queue to 'terminate' it."""
self._load_with_errors(chunk_size=2)
def _load_with_errors(self, chunk_size):
output_stream = StringIO()
SqlDataDumper(self.domain_name, [], []).dump(output_stream)
self.delete_sql_data()
# resave the product to force an error
self.products[0].save()
actual_model_counts, dump_lines = self._parse_dump_output(output_stream)
self.assertEqual(actual_model_counts['products.sqlproduct'], 3)
loader = SqlDataLoader()
with self.assertRaises(IntegrityError),\
mock.patch("corehq.apps.dump_reload.sql.load.CHUNK_SIZE", chunk_size):
# patch the chunk size so that the queue blocks
loader.load_objects(dump_lines)
class DefaultDictWithKeyTests(SimpleTestCase):
def test_intended_use_case(self):
def enlist(item):
return [item]
greasy_spoon = DefaultDictWithKey(enlist)
self.assertEqual(greasy_spoon['spam'], ['spam'])
greasy_spoon['spam'].append('spam')
self.assertEqual(greasy_spoon['spam'], ['spam', 'spam'])
def test_not_enough_params(self):
def empty_list():
return []
greasy_spoon = DefaultDictWithKey(empty_list)
with self.assertRaisesRegex(
TypeError,
r'empty_list\(\) takes 0 positional arguments but 1 was given'
):
greasy_spoon['spam']
def test_too_many_params(self):
def appender(item1, item2):
return [item1, item2]
greasy_spoon = DefaultDictWithKey(appender)
with self.assertRaisesRegex(
TypeError,
r"appender\(\) missing 1 required positional argument: 'item2'"
):
greasy_spoon['spam']
def test_no_factory(self):
greasy_spoon = DefaultDictWithKey()
with self.assertRaisesRegex(
TypeError,
"'NoneType' object is not callable"
):
greasy_spoon['spam']
def _normalize_object_counter(counter, for_loaded=False):
"""Converts a <Model Class> keyed counter to an model label keyed counter"""
def _model_class_to_label(model_class):
label = '{}.{}'.format(model_class._meta.app_label, model_class.__name__)
return label if for_loaded else label.lower()
return Counter({
_model_class_to_label(model_class): count
for model_class, count in counter.items()
})
| 1.367188 | 1 |
tests/keras/test_activations.py | the-moliver/keras | 150 | 2253 | import pytest
import numpy as np
from numpy.testing import assert_allclose
from keras import backend as K
from keras import activations
def get_standard_values():
'''
These are just a set of floats used for testing the activation
functions, and are useful in multiple tests.
'''
return np.array([[0, 0.1, 0.5, 0.9, 1.0]], dtype=K.floatx())
def test_softmax():
'''
Test using a reference implementation of softmax
'''
def softmax(values):
m = np.max(values)
e = np.exp(values - m)
return e / np.sum(e)
x = K.placeholder(ndim=2)
f = K.function([x], [activations.softmax(x)])
test_values = get_standard_values()
result = f([test_values])[0]
expected = softmax(test_values)
assert_allclose(result, expected, rtol=1e-05)
def test_time_distributed_softmax():
x = K.placeholder(shape=(1, 1, 5))
f = K.function([x], [activations.softmax(x)])
test_values = get_standard_values()
test_values = np.reshape(test_values, (1, 1, np.size(test_values)))
f([test_values])[0]
def test_softplus():
'''
Test using a reference softplus implementation
'''
def softplus(x):
return np.log(np.ones_like(x) + np.exp(x))
x = K.placeholder(ndim=2)
f = K.function([x], [activations.softplus(x)])
test_values = get_standard_values()
result = f([test_values])[0]
expected = softplus(test_values)
assert_allclose(result, expected, rtol=1e-05)
def test_softsign():
'''
Test using a reference softsign implementation
'''
def softsign(x):
return np.divide(x, np.ones_like(x) + np.absolute(x))
x = K.placeholder(ndim=2)
f = K.function([x], [activations.softsign(x)])
test_values = get_standard_values()
result = f([test_values])[0]
expected = softsign(test_values)
assert_allclose(result, expected, rtol=1e-05)
def test_sigmoid():
'''
Test using a numerically stable reference sigmoid implementation
'''
def ref_sigmoid(x):
if x >= 0:
return 1 / (1 + np.exp(-x))
else:
z = np.exp(x)
return z / (1 + z)
sigmoid = np.vectorize(ref_sigmoid)
x = K.placeholder(ndim=2)
f = K.function([x], [activations.sigmoid(x)])
test_values = get_standard_values()
result = f([test_values])[0]
expected = sigmoid(test_values)
assert_allclose(result, expected, rtol=1e-05)
def test_hard_sigmoid():
'''
Test using a reference hard sigmoid implementation
'''
def ref_hard_sigmoid(x):
'''
Reference hard sigmoid with slope and shift values from theano, see
https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/sigm.py
'''
x = (x * 0.2) + 0.5
z = 0.0 if x <= 0 else (1.0 if x >= 1 else x)
return z
hard_sigmoid = np.vectorize(ref_hard_sigmoid)
x = K.placeholder(ndim=2)
f = K.function([x], [activations.hard_sigmoid(x)])
test_values = get_standard_values()
result = f([test_values])[0]
expected = hard_sigmoid(test_values)
assert_allclose(result, expected, rtol=1e-05)
def test_relu():
'''
Relu implementation doesn't depend on the value being
a theano variable. Testing ints, floats and theano tensors.
'''
x = K.placeholder(ndim=2)
f = K.function([x], [activations.relu(x)])
test_values = get_standard_values()
result = f([test_values])[0]
# because no negatives in test values
assert_allclose(result, test_values, rtol=1e-05)
def test_elu():
x = K.placeholder(ndim=2)
f = K.function([x], [activations.elu(x, 0.5)])
test_values = get_standard_values()
result = f([test_values])[0]
# because no negatives in test values
assert_allclose(result, test_values, rtol=1e-05)
negative_values = np.array([[-1, -2]], dtype=K.floatx())
result = f([negative_values])[0]
true_result = (np.exp(negative_values) - 1) / 2
assert_allclose(result, true_result)
def test_tanh():
test_values = get_standard_values()
x = K.placeholder(ndim=2)
exp = activations.tanh(x)
f = K.function([x], [exp])
result = f([test_values])[0]
expected = np.tanh(test_values)
assert_allclose(result, expected, rtol=1e-05)
def test_linear():
'''
This function does no input validation, it just returns the thing
that was passed in.
'''
xs = [1, 5, True, None, 'foo']
for x in xs:
assert(x == activations.linear(x))
if __name__ == '__main__':
pytest.main([__file__])
| 2.875 | 3 |
scripts/H5toXMF.py | robertsawko/proteus | 0 | 2254 |
#import numpy
#import os
#from xml.etree.ElementTree import *
import tables
#from Xdmf import *
def H5toXMF(basename,size,start,finaltime,stride):
# Open XMF files
for step in range(start,finaltime+1,stride):
XMFfile = open(basename+"."+str(step)+".xmf","w")
XMFfile.write(r"""<?xml version="1.0" ?>
<!DOCTYPE Xdmf SYSTEM "Xdmf.dtd" []>
<Xdmf Version="2.0" xmlns:xi="http://www.w3.org/2001/XInclude">
<Domain>"""+"\n")
XMFfile.write(r' <Grid GridType="Collection" CollectionType="Spatial">'+"\n")
for proc in range(0,size):
filename="solution.p"+str(proc)+"."+str(step)+".h5"
print filename
f1 = tables.openFile(filename)
XMFfile.write (r'<Grid GridType="Uniform">'+"\n")
XMFfile.write(r' <Time Value="'+str(step)+'" />'+"\n")
for tmp in f1.root:
if tmp.name == "elements":
XMFfile.write (r'<Topology NumberOfElements="' +str(len(tmp[:]))+ '" Type="Tetrahedron">'+"\n")
XMFfile.write (r' <DataItem DataType="Int" Dimensions="' +str(len(tmp[:]))+ ' 4" Format="HDF">' + filename + ':/elements</DataItem>'+"\n")
XMFfile.write (r'</Topology>'+"\n")
if tmp.name == "nodes":
XMFfile.write (r'<Geometry Type="XYZ">'+"\n")
XMFfile.write (r' <DataItem DataType="Float" Dimensions="' +str(len(tmp[:]))+ ' 3" Format="HDF" Precision="8">' + filename + ':/nodes</DataItem>'+"\n")
XMFfile.write (r'</Geometry>'+"\n")
if tmp.name == "u":
XMFfile.write (r'<Attribute AttributeType="Scalar" Center="Node" Name="u">'+"\n")
XMFfile.write (r' <DataItem DataType="Float" Dimensions="' +str(len(tmp[:]))+ '" Format="HDF" Precision="8">' + filename + ':/u</DataItem>'+"\n")
XMFfile.write (r'</Attribute>'+"\n")
if tmp.name == "v":
XMFfile.write (r'<Attribute AttributeType="Scalar" Center="Node" Name="v">'+"\n")
XMFfile.write (r' <DataItem DataType="Float" Dimensions="' +str(len(tmp[:]))+ '" Format="HDF" Precision="8">' + filename + ':/v</DataItem>'+"\n")
XMFfile.write (r'</Attribute>'+"\n")
if tmp.name == "w":
XMFfile.write (r'<Attribute AttributeType="Scalar" Center="Node" Name="w">'+"\n")
XMFfile.write (r' <DataItem DataType="Float" Dimensions="' +str(len(tmp[:]))+ '" Format="HDF" Precision="8">' + filename + ':/w</DataItem>'+"\n")
XMFfile.write (r'</Attribute>'+"\n")
if tmp.name == "p":
XMFfile.write (r'<Attribute AttributeType="Scalar" Center="Node" Name="p">'+"\n")
XMFfile.write (r' <DataItem DataType="Float" Dimensions="' +str(len(tmp[:]))+ '" Format="HDF" Precision="8">' + filename + ':/p</DataItem>'+"\n")
XMFfile.write (r'</Attribute>'+"\n")
if tmp.name == "phid":
XMFfile.write (r'<Attribute AttributeType="Scalar" Center="Node" Name="phid">'+"\n")
XMFfile.write (r' <DataItem DataType="Float" Dimensions="' +str(len(tmp[:]))+ '" Format="HDF" Precision="8">' + filename + ':/phid</DataItem>'+"\n")
XMFfile.write (r'</Attribute>'+"\n")
f1.close()
XMFfile.write(' </Grid>'+"\n")
XMFfile.write(' </Grid>'+"\n")
XMFfile.write(' </Domain>'+"\n")
XMFfile.write(' </Xdmf>'+"\n")
XMFfile.close()
if __name__ == '__main__':
from optparse import OptionParser
usage = ""
parser = OptionParser(usage=usage)
parser.add_option("-n","--size",
help="number of processors for run",
action="store",
type="int",
dest="size",
default=1)
parser.add_option("-s","--stride",
help="stride for solution output",
action="store",
type="int",
dest="stride",
default=0)
parser.add_option("-t","--finaltime",
help="finaltime",
action="store",
type="int",
dest="finaltime",
default=1000)
parser.add_option("-f","--filebase_flow",
help="base name for storage files",
action="store",
type="string",
dest="filebase",
default="solution")
(opts,args) = parser.parse_args()
start = 0
if opts.stride == 0 :
start = opts.finaltime
opts.stride = 1
H5toXMF(opts.filebase,opts.size,start,opts.finaltime,opts.stride)
| 2.40625 | 2 |
tests/test_cli/test_generate/test_generate.py | lrahmani/agents-aea | 0 | 2255 | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI 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.
#
# ------------------------------------------------------------------------------
"""This test module contains the tests for the aea.cli.generate sub-module."""
from unittest import TestCase, mock
from aea.cli.generate import _generate_item
from tests.test_cli.tools_for_testing import ContextMock
def _raise_file_exists(self, *args, **kwargs):
raise FileExistsError()
@mock.patch("builtins.open", mock.mock_open())
@mock.patch("aea.cli.generate.ConfigLoader")
@mock.patch("aea.cli.generate.os.path.join", return_value="joined-path")
@mock.patch("aea.cli.generate.ProtocolGenerator.generate", _raise_file_exists)
class GenerateItemTestCase(TestCase):
"""Test case for fetch_agent_locally method."""
def test__generate_item_file_exists(self, *mocks):
"""Test for fetch_agent_locally method positive result."""
ctx_mock = ContextMock()
with self.assertRaises(SystemExit):
_generate_item(ctx_mock, "protocol", "path")
| 1.960938 | 2 |
sphinx/ext/napoleon/__init__.py | PeerHerholz/smobsc | 3 | 2256 | """
sphinx.ext.napoleon
~~~~~~~~~~~~~~~~~~~
Support for NumPy and Google style docstrings.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from sphinx import __display_version__ as __version__
from sphinx.application import Sphinx
from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring
if False:
# For type annotation
from typing import Any, Dict, List # NOQA
class Config:
"""Sphinx napoleon extension settings in `conf.py`.
Listed below are all the settings used by napoleon and their default
values. These settings can be changed in the Sphinx `conf.py` file. Make
sure that "sphinx.ext.napoleon" is enabled in `conf.py`::
# conf.py
# Add any Sphinx extension module names here, as strings
extensions = ['sphinx.ext.napoleon']
# Napoleon settings
napoleon_google_docstring = True
napoleon_numpy_docstring = True
napoleon_include_init_with_doc = False
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = False
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False
napoleon_use_ivar = False
napoleon_use_param = True
napoleon_use_rtype = True
napoleon_use_keyword = True
napoleon_custom_sections = None
.. _Google style:
https://google.github.io/styleguide/pyguide.html
.. _NumPy style:
https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
Attributes
----------
napoleon_google_docstring : :obj:`bool` (Defaults to True)
True to parse `Google style`_ docstrings. False to disable support
for Google style docstrings.
napoleon_numpy_docstring : :obj:`bool` (Defaults to True)
True to parse `NumPy style`_ docstrings. False to disable support
for NumPy style docstrings.
napoleon_include_init_with_doc : :obj:`bool` (Defaults to False)
True to list ``__init___`` docstrings separately from the class
docstring. False to fall back to Sphinx's default behavior, which
considers the ``__init___`` docstring as part of the class
documentation.
**If True**::
def __init__(self):
\"\"\"
This will be included in the docs because it has a docstring
\"\"\"
def __init__(self):
# This will NOT be included in the docs
napoleon_include_private_with_doc : :obj:`bool` (Defaults to False)
True to include private members (like ``_membername``) with docstrings
in the documentation. False to fall back to Sphinx's default behavior.
**If True**::
def _included(self):
\"\"\"
This will be included in the docs because it has a docstring
\"\"\"
pass
def _skipped(self):
# This will NOT be included in the docs
pass
napoleon_include_special_with_doc : :obj:`bool` (Defaults to False)
True to include special members (like ``__membername__``) with
docstrings in the documentation. False to fall back to Sphinx's
default behavior.
**If True**::
def __str__(self):
\"\"\"
This will be included in the docs because it has a docstring
\"\"\"
return unicode(self).encode('utf-8')
def __unicode__(self):
# This will NOT be included in the docs
return unicode(self.__class__.__name__)
napoleon_use_admonition_for_examples : :obj:`bool` (Defaults to False)
True to use the ``.. admonition::`` directive for the **Example** and
**Examples** sections. False to use the ``.. rubric::`` directive
instead. One may look better than the other depending on what HTML
theme is used.
This `NumPy style`_ snippet will be converted as follows::
Example
-------
This is just a quick example
**If True**::
.. admonition:: Example
This is just a quick example
**If False**::
.. rubric:: Example
This is just a quick example
napoleon_use_admonition_for_notes : :obj:`bool` (Defaults to False)
True to use the ``.. admonition::`` directive for **Notes** sections.
False to use the ``.. rubric::`` directive instead.
Note
----
The singular **Note** section will always be converted to a
``.. note::`` directive.
See Also
--------
:attr:`napoleon_use_admonition_for_examples`
napoleon_use_admonition_for_references : :obj:`bool` (Defaults to False)
True to use the ``.. admonition::`` directive for **References**
sections. False to use the ``.. rubric::`` directive instead.
See Also
--------
:attr:`napoleon_use_admonition_for_examples`
napoleon_use_ivar : :obj:`bool` (Defaults to False)
True to use the ``:ivar:`` role for instance variables. False to use
the ``.. attribute::`` directive instead.
This `NumPy style`_ snippet will be converted as follows::
Attributes
----------
attr1 : int
Description of `attr1`
**If True**::
:ivar attr1: Description of `attr1`
:vartype attr1: int
**If False**::
.. attribute:: attr1
Description of `attr1`
:type: int
napoleon_use_param : :obj:`bool` (Defaults to True)
True to use a ``:param:`` role for each function parameter. False to
use a single ``:parameters:`` role for all the parameters.
This `NumPy style`_ snippet will be converted as follows::
Parameters
----------
arg1 : str
Description of `arg1`
arg2 : int, optional
Description of `arg2`, defaults to 0
**If True**::
:param arg1: Description of `arg1`
:type arg1: str
:param arg2: Description of `arg2`, defaults to 0
:type arg2: int, optional
**If False**::
:parameters: * **arg1** (*str*) --
Description of `arg1`
* **arg2** (*int, optional*) --
Description of `arg2`, defaults to 0
napoleon_use_keyword : :obj:`bool` (Defaults to True)
True to use a ``:keyword:`` role for each function keyword argument.
False to use a single ``:keyword arguments:`` role for all the
keywords.
This behaves similarly to :attr:`napoleon_use_param`. Note unlike
docutils, ``:keyword:`` and ``:param:`` will not be treated the same
way - there will be a separate "Keyword Arguments" section, rendered
in the same fashion as "Parameters" section (type links created if
possible)
See Also
--------
:attr:`napoleon_use_param`
napoleon_use_rtype : :obj:`bool` (Defaults to True)
True to use the ``:rtype:`` role for the return type. False to output
the return type inline with the description.
This `NumPy style`_ snippet will be converted as follows::
Returns
-------
bool
True if successful, False otherwise
**If True**::
:returns: True if successful, False otherwise
:rtype: bool
**If False**::
:returns: *bool* -- True if successful, False otherwise
napoleon_custom_sections : :obj:`list` (Defaults to None)
Add a list of custom sections to include, expanding the list of parsed sections.
The entries can either be strings or tuples, depending on the intention:
* To create a custom "generic" section, just pass a string.
* To create an alias for an existing section, pass a tuple containing the
alias name and the original, in that order.
If an entry is just a string, it is interpreted as a header for a generic
section. If the entry is a tuple/list/indexed container, the first entry
is the name of the section, the second is the section key to emulate.
"""
_config_values = {
'napoleon_google_docstring': (True, 'env'),
'napoleon_numpy_docstring': (True, 'env'),
'napoleon_include_init_with_doc': (False, 'env'),
'napoleon_include_private_with_doc': (False, 'env'),
'napoleon_include_special_with_doc': (False, 'env'),
'napoleon_use_admonition_for_examples': (False, 'env'),
'napoleon_use_admonition_for_notes': (False, 'env'),
'napoleon_use_admonition_for_references': (False, 'env'),
'napoleon_use_ivar': (False, 'env'),
'napoleon_use_param': (True, 'env'),
'napoleon_use_rtype': (True, 'env'),
'napoleon_use_keyword': (True, 'env'),
'napoleon_custom_sections': (None, 'env')
}
def __init__(self, **settings):
# type: (Any) -> None
for name, (default, rebuild) in self._config_values.items():
setattr(self, name, default)
for name, value in settings.items():
setattr(self, name, value)
def setup(app):
# type: (Sphinx) -> Dict[str, Any]
"""Sphinx extension setup function.
When the extension is loaded, Sphinx imports this module and executes
the ``setup()`` function, which in turn notifies Sphinx of everything
the extension offers.
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process
See Also
--------
`The Sphinx documentation on Extensions
<http://sphinx-doc.org/extensions.html>`_
`The Extension Tutorial <http://sphinx-doc.org/extdev/tutorial.html>`_
`The Extension API <http://sphinx-doc.org/extdev/appapi.html>`_
"""
if not isinstance(app, Sphinx):
# probably called by tests
return {'version': __version__, 'parallel_read_safe': True}
_patch_python_domain()
app.setup_extension('sphinx.ext.autodoc')
app.connect('autodoc-process-docstring', _process_docstring)
app.connect('autodoc-skip-member', _skip_member)
for name, (default, rebuild) in Config._config_values.items():
app.add_config_value(name, default, rebuild)
return {'version': __version__, 'parallel_read_safe': True}
def _patch_python_domain():
# type: () -> None
try:
from sphinx.domains.python import PyTypedField
except ImportError:
pass
else:
import sphinx.domains.python
from sphinx.locale import _
for doc_field in sphinx.domains.python.PyObject.doc_field_types:
if doc_field.name == 'parameter':
doc_field.names = ('param', 'parameter', 'arg', 'argument')
break
sphinx.domains.python.PyObject.doc_field_types.append(
PyTypedField('keyword', label=_('Keyword Arguments'),
names=('keyword', 'kwarg', 'kwparam'),
typerolename='obj', typenames=('paramtype', 'kwtype'),
can_collapse=True))
def _process_docstring(app, what, name, obj, options, lines):
# type: (Sphinx, str, str, Any, Any, List[str]) -> None
"""Process the docstring for a given python object.
Called when autodoc has read and processed a docstring. `lines` is a list
of docstring lines that `_process_docstring` modifies in place to change
what Sphinx outputs.
The following settings in conf.py control what styles of docstrings will
be parsed:
* ``napoleon_google_docstring`` -- parse Google style docstrings
* ``napoleon_numpy_docstring`` -- parse NumPy style docstrings
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process.
what : str
A string specifying the type of the object to which the docstring
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : str
The fully qualified name of the object.
obj : module, class, exception, function, method, or attribute
The object to which the docstring belongs.
options : sphinx.ext.autodoc.Options
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and noindex that
are True if the flag option of same name was given to the auto
directive.
lines : list of str
The lines of the docstring, see above.
.. note:: `lines` is modified *in place*
"""
result_lines = lines
docstring = None # type: GoogleDocstring
if app.config.napoleon_numpy_docstring:
docstring = NumpyDocstring(result_lines, app.config, app, what, name,
obj, options)
result_lines = docstring.lines()
if app.config.napoleon_google_docstring:
docstring = GoogleDocstring(result_lines, app.config, app, what, name,
obj, options)
result_lines = docstring.lines()
lines[:] = result_lines[:]
def _skip_member(app, what, name, obj, skip, options):
# type: (Sphinx, str, str, Any, bool, Any) -> bool
"""Determine if private and special class members are included in docs.
The following settings in conf.py determine if private and special class
members or init methods are included in the generated documentation:
* ``napoleon_include_init_with_doc`` --
include init methods if they have docstrings
* ``napoleon_include_private_with_doc`` --
include private members if they have docstrings
* ``napoleon_include_special_with_doc`` --
include special members if they have docstrings
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process
what : str
A string specifying the type of the object to which the member
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : str
The name of the member.
obj : module, class, exception, function, method, or attribute.
For example, if the member is the __init__ method of class A, then
`obj` will be `A.__init__`.
skip : bool
A boolean indicating if autodoc will skip this member if `_skip_member`
does not override the decision
options : sphinx.ext.autodoc.Options
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and noindex that
are True if the flag option of same name was given to the auto
directive.
Returns
-------
bool
True if the member should be skipped during creation of the docs,
False if it should be included in the docs.
"""
has_doc = getattr(obj, '__doc__', False)
is_member = (what == 'class' or what == 'exception' or what == 'module')
if name != '__weakref__' and has_doc and is_member:
cls_is_owner = False
if what == 'class' or what == 'exception':
qualname = getattr(obj, '__qualname__', '')
cls_path, _, _ = qualname.rpartition('.')
if cls_path:
try:
if '.' in cls_path:
import importlib
import functools
mod = importlib.import_module(obj.__module__)
mod_path = cls_path.split('.')
cls = functools.reduce(getattr, mod_path, mod)
else:
cls = obj.__globals__[cls_path]
except Exception:
cls_is_owner = False
else:
cls_is_owner = (cls and hasattr(cls, name) and # type: ignore
name in cls.__dict__)
else:
cls_is_owner = False
if what == 'module' or cls_is_owner:
is_init = (name == '__init__')
is_special = (not is_init and name.startswith('__') and
name.endswith('__'))
is_private = (not is_init and not is_special and
name.startswith('_'))
inc_init = app.config.napoleon_include_init_with_doc
inc_special = app.config.napoleon_include_special_with_doc
inc_private = app.config.napoleon_include_private_with_doc
if ((is_special and inc_special) or
(is_private and inc_private) or
(is_init and inc_init)):
return False
return None
| 1.734375 | 2 |
plugins/similarity/rdkit/tanimoto/lbvs-entry.py | skodapetr/viset | 1 | 2257 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from rdkit import DataStructs
import plugin_api
__license__ = "X11"
class LbvsEntry(plugin_api.PluginInterface):
"""
Compute Tanimoto similarity.
"""
def __init__(self):
self.stream = None
self.counter = 0
self.first_entry = False
def execute(self, files):
query = LbvsEntry._load_file(files["query_file"])
database = LbvsEntry._load_file(files["database_file"])
with open(files["output_file"], "w") as stream:
self.stream = stream
self.write_output_header()
self.compute_and_write_similarities_for_items(query, database)
self.write_output_footer()
def write_output_header(self):
self.stream.write('{"data":[')
def write_output_footer(self):
self.stream.write(']}')
def compute_and_write_similarities_for_items(self, query, database):
self.first_entry = True
for query_item in query:
for database_item in database:
self._write_separator_if_needed()
self.first_entry = False
self._compute_and_write_similarity(query_item, database_item)
def _write_separator_if_needed(self):
if not self.first_entry:
self.stream.write(",")
def _compute_and_write_similarity(self, query, item):
similarity = LbvsEntry._compute_similarity(
query["value"], item["value"])
json.dump({
"query": query["id"],
"id": item["id"],
"value": similarity
}, self.stream)
@staticmethod
def _load_file(path):
with open(path) as stream:
return [{
"id": item["id"],
"value": LbvsEntry._as_sparse_vector(item["value"])
} for item in json.load(stream)["data"]]
@staticmethod
def _as_sparse_vector(data):
# Use max integer value as a size.
vector = DataStructs.cDataStructs.IntSparseIntVect(8388608)
for key in data:
vector[(int)(key)] = (int)(data[key])
return vector
@staticmethod
def _compute_similarity(left, right):
return DataStructs.TanimotoSimilarity(left, right)
def get_metadata(self) -> object:
return {
"id": "rdkit/tanimoto"
}
| 2.453125 | 2 |
mall_spider/spiders/actions/proxy_service.py | 524243642/taobao_spider | 12 | 2258 | <gh_stars>10-100
# coding: utf-8
import time
from config.config_loader import global_config
from mall_spider.spiders.actions.context import Context
from mall_spider.spiders.actions.direct_proxy_action import DirectProxyAction
__proxy_service = None
class ProxyService(object):
proxies_set = set()
proxies_list = ['https://' + item['ip'] + ':' + item['port'] for item in global_config.s_proxy]
LOW_WATER_MARK = 5
proxy_fetch_url = "http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&qty=1&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson="
def __init__(self) -> None:
super().__init__()
self._counter = 0
def get_s_proxy(self, username):
proxy = global_config.s_proxy_dict[username]
url = 'https://' + proxy['ip'] + ':' + proxy['port']
return {
'https': url
}
def get_origin_s_proxy(self, username):
return global_config.s_proxy_dict[username]
def get_static_proxy(self, username):
if not global_config.static_proxy:
return None
proxy = global_config.static_proxy_dict[username]
if proxy['username'] and proxy['password']:
url = 'https://' + proxy['username'] + ':' + proxy['password'] + '@' + proxy['ip'] + ':' + proxy['port']
else:
url = 'https://' + proxy['ip'] + ':' + proxy['port']
return {
'https': url
}
def get_origin_static_proxy(self, username):
if not global_config.static_proxy:
return None
return global_config.static_proxy_dict[username]
def get_proxy(self):
if len(self.proxies_list) < self.LOW_WATER_MARK:
for i in range(0, int(self.LOW_WATER_MARK * 1) - len(self.proxies_list)):
self.fetch_proxy()
time.sleep(2)
proxy = self.proxies_list[self._counter % len(self.proxies_list)]
self._counter += 1
return {
'https': proxy
}
def fetch_proxy(self):
context = Context()
action = DirectProxyAction()
action.execute(context=context)
result = context.get(Context.KEY_PROXY_RESULT, [])
if result:
for item in result:
ip = item['IP']
port = str(item['Port'])
url = 'https://' + ip + ':' + port
if url not in self.proxies_set:
self.proxies_set.add(url)
self.proxies_list.append(url)
def remove_proxy(self, url, force=False):
if force:
self.proxies_set.remove(url)
self.proxies_list.remove(url)
def get_proxy_service():
global __proxy_service
if not __proxy_service:
__proxy_service = ProxyService()
return __proxy_service
| 2.0625 | 2 |
app/weather_tests.py | joedanz/flask-weather | 1 | 2259 | import os
import weather
import datetime
import unittest
import tempfile
class WeatherTestCase(unittest.TestCase):
def setUp(self):
self.db_fd, weather.app.config['DATABASE'] = tempfile.mkstemp()
weather.app.config['TESTING'] = True
self.app = weather.app.test_client()
weather.init_db()
def tearDown(self):
os.close(self.db_fd)
os.unlink(weather.app.config['DATABASE'])
def test_empty_db(self):
"""Test empty database with no entries."""
rv = self.app.get('/')
assert 'Nothing logged yet.' in rv.data
def test_report(self):
"""Test reporting weather"""
rv = self.app.get('/report/11210/63/23', follow_redirects=True)
assert b'11210' in rv.data
def test_full_db(self):
"""Test reporting weather"""
rv = self.app.get('/', follow_redirects=True)
assert b'11210' in rv.data
if __name__ == '__main__':
unittest.main()
| 2.78125 | 3 |
modules/sensors/Activator.py | memristor/mep2 | 5 | 2260 | import asyncio
class Activator:
def __init__(self, name, packet_stream=None):
self.ps = None
self.name = name
self.future = None
self.data = 0
self.state = ''
if packet_stream:
self.set_packet_stream(packet_stream)
@_core.module_cmd
def wait_activator(self):
pass
@_core.module_cmd
def check_activator(self):
print('checking act')
if self.data:
self.future.set_result(1)
else:
self.state = 'check_chinch'
print('checking for chinch')
def export_cmds(self):
_core.export_cmd('wait_activator', self.wait_activator)
_core.export_cmd('check_activator', self.check_activator)
def on_recv(self, pkt):
if self.state == 'check_chinch' and self.future and pkt[0] == 1:
self.future.set_result(1)
self.state = 'chinch_ready'
print('waiting for activator')
if self.state == 'chinch_ready' and self.future and pkt[0] == 0:
self.future.set_result(1)
def set_packet_stream(self, ps):
ps.recv = self.on_recv
self.ps = ps
| 2.5625 | 3 |
examples/retrieval/evaluation/sparse/evaluate_deepct.py | ArthurCamara/beir | 24 | 2261 | <gh_stars>10-100
"""
This example shows how to evaluate DeepCT (using Anserini) in BEIR.
For more details on DeepCT, refer here: https://arxiv.org/abs/1910.10687
The original DeepCT repository is not modularised and only works with Tensorflow 1.x (1.15).
We modified the DeepCT repository to work with Tensorflow latest (2.x).
We do not change the core-prediction code, only few input/output file format and structure to adapt to BEIR formats.
For more details on changes, check: https://github.com/NThakur20/DeepCT and compare it with original repo!
Please follow the steps below to install DeepCT:
1. git clone https://github.com/NThakur20/DeepCT.git
Since Anserini uses Java-11, we would advise you to use docker for running Pyserini.
To be able to run the code below you must have docker locally installed in your machine.
To install docker on your local machine, please refer here: https://docs.docker.com/get-docker/
After docker installation, please follow the steps below to get docker container up and running:
1. docker pull docker pull beir/pyserini-fastapi
2. docker build -t pyserini-fastapi .
3. docker run -p 8000:8000 -it --rm pyserini-fastapi
Usage: python evaluate_deepct.py
"""
from DeepCT.deepct import run_deepct # git clone https://github.com/NThakur20/DeepCT.git
from beir import util, LoggingHandler
from beir.datasets.data_loader import GenericDataLoader
from beir.retrieval.evaluation import EvaluateRetrieval
from beir.generation.models import QGenModel
from tqdm.autonotebook import trange
import pathlib, os, json
import logging
import requests
import random
#### Just some code to print debug information to stdout
logging.basicConfig(format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO,
handlers=[LoggingHandler()])
#### /print debug information to stdout
#### Download scifact.zip dataset and unzip the dataset
dataset = "scifact"
url = "https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip".format(dataset)
out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "datasets")
data_path = util.download_and_unzip(url, out_dir)
corpus, queries, qrels = GenericDataLoader(data_path).load(split="test")
#### 1. Download Google BERT-BASE, Uncased model ####
# Ref: https://github.com/google-research/bert
base_model_url = "https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip"
out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "models")
bert_base_dir = util.download_and_unzip(base_model_url, out_dir)
#### 2. Download DeepCT MSMARCO Trained BERT checkpoint ####
# Credits to DeepCT authors: <NAME>, <NAME>, (https://github.com/AdeDZY/DeepCT)
model_url = "http://boston.lti.cs.cmu.edu/appendices/arXiv2019-DeepCT-Zhuyun-Dai/outputs/marco.zip"
out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "models")
checkpoint_dir = util.download_and_unzip(model_url, out_dir)
##################################################
#### 3. Configure Params for DeepCT inference ####
##################################################
# We cannot use the original Repo (https://github.com/AdeDZY/DeepCT) as it only runs with TF 1.15.
# We reformatted the code (https://github.com/NThakur20/DeepCT) and made it working with latest TF 2.X!
if not os.path.isfile(os.path.join(data_path, "deepct.jsonl")):
################################
#### Command-Line Arugments ####
################################
run_deepct.FLAGS.task_name = "beir" # Defined a seperate BEIR task in DeepCT. Check out run_deepct.
run_deepct.FLAGS.do_train = False # We only want to use the code for inference.
run_deepct.FLAGS.do_eval = False # No evaluation.
run_deepct.FLAGS.do_predict = True # True, as we would use DeepCT model for only prediction.
run_deepct.FLAGS.data_dir = os.path.join(data_path, "corpus.jsonl") # Provide original path to corpus data, follow beir format.
run_deepct.FLAGS.vocab_file = os.path.join(bert_base_dir, "vocab.txt") # Provide bert-base-uncased model vocabulary.
run_deepct.FLAGS.bert_config_file = os.path.join(bert_base_dir, "bert_config.json") # Provide bert-base-uncased config.json file.
run_deepct.FLAGS.init_checkpoint = os.path.join(checkpoint_dir, "model.ckpt-65816") # Provide DeepCT MSMARCO model (bert-base-uncased) checkpoint file.
run_deepct.FLAGS.max_seq_length = 350 # Provide Max Sequence Length used for consideration. (Max: 512)
run_deepct.FLAGS.train_batch_size = 128 # Inference batch size, Larger more Memory but faster!
run_deepct.FLAGS.output_dir = data_path # Output directory, this will contain two files: deepct.jsonl (output-file) and predict.tf_record
run_deepct.FLAGS.output_file = "deepct.jsonl" # Output file for storing final DeepCT produced corpus.
run_deepct.FLAGS.m = 100 # Scaling parameter for DeepCT weights: scaling parameter > 0, recommend 100
run_deepct.FLAGS.smoothing = "sqrt" # Use sqrt to smooth weights. DeepCT Paper uses None.
run_deepct.FLAGS.keep_all_terms = True # Do not allow DeepCT to delete terms.
# Runs DeepCT model on the corpus.jsonl
run_deepct.main()
#### Download Docker Image beir/pyserini-fastapi ####
#### Locally run the docker Image + FastAPI ####
docker_beir_pyserini = "http://127.0.0.1:8000"
#### Upload Multipart-encoded files ####
with open(os.path.join(data_path, "deepct.jsonl"), "rb") as fIn:
r = requests.post(docker_beir_pyserini + "/upload/", files={"file": fIn}, verify=False)
#### Index documents to Pyserini #####
index_name = "beir/you-index-name" # beir/scifact
r = requests.get(docker_beir_pyserini + "/index/", params={"index_name": index_name})
######################################
#### 2. Pyserini-Retrieval (BM25) ####
######################################
#### Retrieve documents from Pyserini #####
retriever = EvaluateRetrieval()
qids = list(queries)
query_texts = [queries[qid] for qid in qids]
payload = {"queries": query_texts, "qids": qids, "k": max(retriever.k_values),
"fields": {"contents": 1.0}, "bm25": {"k1": 18, "b": 0.7}}
#### Retrieve pyserini results (format of results is identical to qrels)
results = json.loads(requests.post(docker_beir_pyserini + "/lexical/batch_search/", json=payload).text)["results"]
#### Retrieve RM3 expanded pyserini results (format of results is identical to qrels)
# results = json.loads(requests.post(docker_beir_pyserini + "/lexical/rm3/batch_search/", json=payload).text)["results"]
#### Evaluate your retrieval using NDCG@k, MAP@K ...
logging.info("Retriever evaluation for k in: {}".format(retriever.k_values))
ndcg, _map, recall, precision = retriever.evaluate(qrels, results, retriever.k_values)
#### Retrieval Example ####
query_id, scores_dict = random.choice(list(results.items()))
logging.info("Query : %s\n" % queries[query_id])
scores = sorted(scores_dict.items(), key=lambda item: item[1], reverse=True)
for rank in range(10):
doc_id = scores[rank][0]
logging.info("Doc %d: %s [%s] - %s\n" % (rank+1, doc_id, corpus[doc_id].get("title"), corpus[doc_id].get("text")))
| 2.171875 | 2 |
Examples/Space Truss - Nodal Load.py | AmirHosseinNamadchi/PyNite | 2 | 2262 | <filename>Examples/Space Truss - Nodal Load.py
# Engineering Mechanics: Statics, 4th Edition
# <NAME>
# Problem 6.64
# Units for this model are meters and kilonewtons
# Import 'FEModel3D' and 'Visualization' from 'PyNite'
from PyNite import FEModel3D
from PyNite import Visualization
# Create a new model
truss = FEModel3D()
# Define the nodes
truss.AddNode('A', 1.1, -0.4, 0)
truss.AddNode('B', 1, 0, 0)
truss.AddNode('C', 0, 0, 0.6)
truss.AddNode('D', 0, 0, -0.4)
truss.AddNode('E', 0, 0.8, 0)
# Define the supports
truss.DefineSupport('C', True, True, True, True, True, True)
truss.DefineSupport('D', True, True, True, True, True, True)
truss.DefineSupport('E', True, True, True, True, True, True)
# Create members
# Member properties were not given for this problem, so assumed values will be used
# To make all the members act rigid, the modulus of elasticity will be set to a very large value
E = 99999999
truss.AddMember('AB', 'A', 'B', E, 100, 100, 100, 100, 100)
truss.AddMember('AC', 'A', 'C', E, 100, 100, 100, 100, 100)
truss.AddMember('AD', 'A', 'D', E, 100, 100, 100, 100, 100)
truss.AddMember('BC', 'B', 'C', E, 100, 100, 100, 100, 100)
truss.AddMember('BD', 'B', 'D', E, 100, 100, 100, 100, 100)
truss.AddMember('BE', 'B', 'E', E, 100, 100, 100, 100, 100)
# Release the moments at the ends of the members to make truss members
truss.DefineReleases('AC', False, False, False, False, True, True, \
False, False, False, False, True, True)
truss.DefineReleases('AD', False, False, False, False, True, True, \
False, False, False, False, True, True)
truss.DefineReleases('BC', False, False, False, False, True, True, \
False, False, False, False, True, True)
truss.DefineReleases('BD', False, False, False, False, True, True, \
False, False, False, False, True, True)
truss.DefineReleases('BE', False, False, False, False, True, True, \
False, False, False, False, True, True)
# Add nodal loads
truss.AddNodeLoad('A', 'FX', 10)
truss.AddNodeLoad('A', 'FY', 60)
truss.AddNodeLoad('A', 'FZ', 20)
# Analyze the model
truss.Analyze()
# Print results
print('Member BC calculated axial force: ' + str(truss.GetMember('BC').MaxAxial()))
print('Member BC expected axial force: 32.7 Tension')
print('Member BD calculated axial force: ' + str(truss.GetMember('BD').MaxAxial()))
print('Member BD expected axial force: 45.2 Tension')
print('Member BE calculated axial force: ' + str(truss.GetMember('BE').MaxAxial()))
print('Member BE expected axial force: 112.1 Compression')
# Render the model for viewing. The text height will be set to 50 mm.
# Because the members in this example are nearly rigid, there will be virtually no deformation. The deformed shape won't be rendered.
# The program has created a default load case 'Case 1' and a default load combo 'Combo 1' since we didn't specify any. We'll display 'Case 1'.
Visualization.RenderModel(truss, text_height=0.05, render_loads=True, case='Case 1')
| 2.703125 | 3 |
Using Yagmail to make sending emails easier.py | CodeMaster7000/Sending-Emails-in-Python | 1 | 2263 | import yagmail
receiver = "<EMAIL>" #Receiver's gmail address
body = "Hello there from Yagmail"
filename = "document.pdf"
yag = yagmail.SMTP("<EMAIL>")#Your gmail address
yag.send(
to=receiver,
subject="Yagmail test (attachment included",
contents=body,
attachments=filename,
)
| 2.296875 | 2 |
pycad/py_src/transformations.py | markendr/esys-escript.github.io | 0 | 2264 |
##############################################################################
#
# Copyright (c) 2003-2020 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Development until 2012 by Earth Systems Science Computational Center (ESSCC)
# Development 2012-2013 by School of Earth Sciences
# Development from 2014 by Centre for Geoscience Computing (GeoComp)
# Development from 2019 by School of Earth and Environmental Sciences
#
##############################################################################
from __future__ import print_function, division
__copyright__="""Copyright (c) 2003-2020 by The University of Queensland
http://www.uq.edu.au
Primary Business: Queensland, Australia"""
__license__="""Licensed under the Apache License, version 2.0
http://www.apache.org/licenses/LICENSE-2.0"""
__url__="https://launchpad.net/escript-finley"
"""
transformations
:var __author__: name of author
:var __copyright__: copyrights
:var __license__: licence agreement
:var __url__: url entry point on documentation
:var __version__: version
:var __date__: date of the version
:var DEG: unit of degree
:var RAD: unit of radiant
"""
__author__="<NAME>, <EMAIL>"
import numpy
import math
_TYPE=numpy.float64
DEG=math.pi/180.
RAD=1.
class Transformation(object):
"""
General class to define an affine transformation *x->Ax+b*.
"""
def __init__(self):
"""
Creates a linear transformation.
"""
pass
def __call__(self,x=numpy.zeros((3,))):
"""
Applies transformation to ``x``.
"""
raise NotImplementeError()
class Translation(Transformation):
"""
Defines a translation *x->x+b*.
"""
def __init__(self,b=numpy.zeros((3,),dtype=_TYPE)):
"""
Creates the linear transformation *x->x+b*.
"""
super(Translation, self).__init__()
self.__b=numpy.array(b,_TYPE)
def __call__(self,x=numpy.zeros((3,))):
"""
Applies translation to ``x``.
"""
return numpy.array(x,_TYPE)+self.__b
class Rotatation(Transformation):
"""
Defines a rotation.
"""
def __init__(self,axis=numpy.ones((3,),dtype=_TYPE),point=numpy.zeros((3,),dtype=_TYPE),angle=0.*RAD):
"""
Creates a rotation using an axis and a point on the axis.
"""
self.__axis=numpy.array(axis,dtype=_TYPE)
self.__point=numpy.array(point,dtype=_TYPE)
lax=numpy.dot(self.__axis,self.__axis)
if not lax>0:
raise ValueError("points must be distinct.")
self.__axis/=math.sqrt(lax)
self.__angle=float(angle)
def __call__(self,x=numpy.zeros((3,))):
"""
Applies the rotation to ``x``.
"""
x=numpy.array(x,_TYPE)
z=x-self.__point
z0=numpy.dot(z,self.__axis)
z_per=z-z0*self.__axis
lz_per=numpy.dot(z_per,z_per)
if lz_per>0:
axis1=z_per/math.sqrt(lz_per)
axis2=_cross(axis1,self.__axis)
lax2=numpy.dot(axis2,axis2)
if lax2>0:
axis2/=math.sqrt(lax2)
return z0*self.__axis+math.sqrt(lz_per)*(math.cos(self.__angle)*axis1-math.sin(self.__angle)*axis2)+self.__point
else:
return x
else:
return x
def _cross(x, y):
"""
Returns the cross product of ``x`` and ``y``.
"""
return numpy.array([x[1] * y[2] - x[2] * y[1], x[2] * y[0] - x[0] * y[2], x[0] * y[1] - x[1] * y[0]], _TYPE)
class Dilation(Transformation):
"""
Defines a dilation.
"""
def __init__(self,factor=1.,center=numpy.zeros((3,),dtype=_TYPE)):
"""
Creates a dilation with a center and a given expansion/contraction
factor.
"""
if not abs(factor)>0:
raise ValueError("factor must be non-zero.")
self.__factor=factor
self.__center=numpy.array(center,dtype=_TYPE)
def __call__(self,x=numpy.zeros((3,))):
"""
Applies dilation to ``x``.
"""
x=numpy.array(x,_TYPE)
return self.__factor*(x-self.__center)+self.__center
class Reflection(Transformation):
"""
Defines a reflection on a plane.
"""
def __init__(self,normal=numpy.ones((3,),dtype=_TYPE),offset=0.):
"""
Defines a reflection on a plane defined in normal form.
"""
self.__normal=numpy.array(normal,dtype=_TYPE)
ln=math.sqrt(numpy.dot(self.__normal,self.__normal))
if not ln>0.:
raise ValueError("normal must have positive length.")
self.__normal/=ln
if isinstance(offset,float) or isinstance(offset,int):
self.__offset=offset/ln
else:
self.__offset=numpy.dot(numpy.array(offset,dtype=_TYPE),self.__normal)
def __call__(self,x=numpy.zeros((3,))):
"""
Applies reflection to ``x``.
"""
x=numpy.array(x,_TYPE)
return x - 2*(numpy.dot(x,self.__normal)-self.__offset)*self.__normal
| 1.75 | 2 |
example/complex_scalar_star_solver.py | ThomasHelfer/BosonStar | 2 | 2265 | <gh_stars>1-10
from bosonstar.ComplexBosonStar import Complex_Boson_Star
# =====================
# All imporntnat definitions
# =====================
# Physics defintions
phi0 = 0.40 # centeral phi
D = 5.0 # Dimension (total not only spacial)
Lambda = -0.2 # Cosmological constant
# Solver definitions
Rstart = 3
Rend = 50.00
deltaR = 1
N = 100000
e_pow_minus_delta_guess = 0.4999
verbose = 2
eps = 1e-10 # Small epsilon to avoid r \neq 0
# ====================================
# Main routine
# ====================================
pewpew = Complex_Boson_Star(e_pow_minus_delta_guess, phi0, D, Lambda, verbose)
pewpew.print_parameters()
alpha0 = pewpew.radial_walker(Rstart, Rend, deltaR, N, eps)
# =====================================
# Output and plotting
# =====================================
soldict = pewpew.get_solution()
# Makes sure that lapse goes asymptotically to 1
# (Not an essential step, but recommended)
pewpew.normalise_edelta()
pewpew.check_Einstein_equation()
# ===============================
path = pewpew.get_path()
pewpew.plot_solution()
pewpew.print_solution()
| 2.59375 | 3 |
setup.py | ouyhlan/fastNLP | 2,693 | 2266 | #!/usr/bin/env python
# coding=utf-8
from setuptools import setup, find_packages
with open('README.md', encoding='utf-8') as f:
readme = f.read()
with open('LICENSE', encoding='utf-8') as f:
license = f.read()
with open('requirements.txt', encoding='utf-8') as f:
reqs = f.read()
pkgs = [p for p in find_packages() if p.startswith('fastNLP')]
print(pkgs)
setup(
name='FastNLP',
version='0.7.0',
url='https://gitee.com/fastnlp/fastNLP',
description='fastNLP: Deep Learning Toolkit for NLP, developed by Fudan FastNLP Team',
long_description=readme,
long_description_content_type='text/markdown',
license='Apache License',
author='<NAME>',
python_requires='>=3.6',
packages=pkgs,
install_requires=reqs.strip().split('\n'),
)
| 1.609375 | 2 |
clients/client/python/ory_client/__init__.py | ory/sdk-generator | 0 | 2267 | <filename>clients/client/python/ory_client/__init__.py
# flake8: noqa
"""
Ory APIs
Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. # noqa: E501
The version of the OpenAPI document: v0.0.1-alpha.187
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
__version__ = "v0.0.1-alpha.187"
# import ApiClient
from ory_client.api_client import ApiClient
# import Configuration
from ory_client.configuration import Configuration
# import exceptions
from ory_client.exceptions import OpenApiException
from ory_client.exceptions import ApiAttributeError
from ory_client.exceptions import ApiTypeError
from ory_client.exceptions import ApiValueError
from ory_client.exceptions import ApiKeyError
from ory_client.exceptions import ApiException
| 1.585938 | 2 |
atmosphere/custom_activity/base_class.py | ambiata/atmosphere-python-sdk | 0 | 2268 | <filename>atmosphere/custom_activity/base_class.py<gh_stars>0
from abc import ABC, abstractmethod
from typing import Tuple
from requests import Response
from .pydantic_models import (AppliedExclusionConditionsResponse,
BiasAttributeConfigListResponse,
ComputeRewardResponse, DefaultPredictionResponse,
ExclusionRuleConditionListResponse,
PredictionResponsePayloadFormatListResponse)
class BaseActivityCustomCode(ABC):
"""
The main class of this repository: the one to be implemented
"""
is_for_mocker: bool
def __init__(self, is_for_mocker: bool = False):
self.is_for_mocker = is_for_mocker
@abstractmethod
def validate_prediction_request(self, prediction_request: dict) -> None:
"""Raise a ValidationError if the received prediction request is not valid"""
@abstractmethod
def validate_outcome_request(self, outcome_request: dict) -> None:
"""Raise a ValidationError if the received outcome request is not valid"""
@abstractmethod
def compute_reward(self, outcome_request: dict) -> ComputeRewardResponse:
"""From an outcome, compute the reward"""
@abstractmethod
def get_module_version(self) -> str:
"""Return the version of the module."""
@abstractmethod
def send_mock_prediction_request(
self, url_prediction_endpoint: str
) -> Tuple[Response, dict]:
"""
Send a mock request to the provided url and returns the corresponding response
with extra information if required for computing the prediction.
The response and dictionary will be provided to
the `send_mock_outcome_request`.
"""
@abstractmethod
def send_mock_outcome_request(
self,
url_outcome_endpoint: str,
prediction_response: Response,
info_from_prediction: dict,
) -> Response:
"""
Send a mock request to the provided url and returns the corresponding response.
Provide the prediction response and extra information created while
creating the prediction request from `send_mock_prediction_request`.
"""
def get_prediction_response_payload_formats(
self,
) -> PredictionResponsePayloadFormatListResponse:
"""
Return the list of available format of the prediction payload.
Every format should have a name and a description
The name of the format should be unique.
"""
return {"prediction_response_payload_formats": []}
def format_prediction_payload_response(
self,
default_prediction_response: DefaultPredictionResponse,
payload_format: str, # noqa pylint: disable=unused-argument
) -> dict:
"""
You can format the prediction the way you want based
on the information returned by default
"""
return default_prediction_response
def get_exclusion_rule_conditions(self) -> ExclusionRuleConditionListResponse:
"""
Define the exclusion rules for the activity
"""
return ExclusionRuleConditionListResponse(exclusion_rule_conditions=[])
def get_applied_exclusion_conditions(
self, prediction_request: dict # noqa pylint: disable=unused-argument
) -> AppliedExclusionConditionsResponse:
"""
Define the exclusion rules for the activity
"""
return AppliedExclusionConditionsResponse(applied_exclusion_conditions=[])
def get_bias_attribute_configs(self) -> BiasAttributeConfigListResponse:
"""
Define the bias attribute configs, these decide which attributes may be
used by atmospherex as bias attributes
"""
return BiasAttributeConfigListResponse(bias_attribute_configs=[])
| 2.734375 | 3 |
Module1/file3.py | modulo16/PfNE | 0 | 2269 | <reponame>modulo16/PfNE
from __future__ import print_function, unicode_literals
#Ensures Unicode is used for all strings.
my_str = 'whatever'
#Shows the String type, which should be unicode
type(my_str)
#declare string:
ip_addr = '192.168.1.1'
#check it with boolean:(True)
ip_addr == '192.168.1.1'
#(false)
ip_addr == '10.1.1.1'
#is this substring in this variable?
'192.168' in ip_addr
'1.1' in ip_addr
'15.1' not in ip_addr
#Strings also have indices starting at '0'
#in the case below we get '1' which is the first character
ip_addr[0]
#we can also get the last using negative notation. The follow gets the last:
ip_addr[-1]
#second to last:
ip_addr[-2]
#show length of string:
len(ip_addr)
#Example string concatenation
my_str = 'Hello'
my_str + ' something'
| 3.265625 | 3 |
pp_io_plugins/pp_kbddriver_plus.py | arcticmatter/pipresents-beep | 0 | 2270 | #enhanced keyboard driver
import copy
import os
import configparser
from pp_displaymanager import DisplayManager
class pp_kbddriver_plus(object):
# control list items
NAME=0 # symbolic name for input and output
DIRECTION = 1 # in/out
MATCH = 2 # for input the character/string to match (no EOL)
MODE= 3 # for input the match mode any-char,char,any-line,line
TEMPLATE=['','','','']
# CLASS VARIABLES (pp_kbddriver_plus.)
driver_active=False
title='' # usd for error reporting and logging
tick_interval='' # mS between polls of the serial input
match_mode='' # char or line, whether input characters are matched for each character or a complete line
inputs={}
# executed by main program and by each object using the driver
def __init__(self):
self.dm=DisplayManager()
# executed once from main program
def init(self,filename,filepath,widget,pp_dir,pp_home,pp_profile,event_callback=None):
# instantiate arguments
self.widget=widget
self.filename=filename
self.filepath=filepath
self.event_callback=event_callback
pp_kbddriver_plus.driver_active = False
# read pp_kbddriver_plus.cfg file.
reason,message=self._read(self.filename,self.filepath)
if reason =='error':
return 'error',message
if self.config.has_section('DRIVER') is False:
return 'error','No DRIVER section in '+self.filepath
# all the below are used by another instance of pp_kbddriver_plus so must reference class variables
# read information from DRIVER section
pp_kbddriver_plus.title=self.config.get('DRIVER','title')
pp_kbddriver_plus.bind_printing = self.config.get('DRIVER','bind-printing')
# construct the control list from the config file
pp_kbddriver_plus.in_names=[]
pp_kbddriver_plus.out_names=[]
for section in self.config.sections():
if section == 'DRIVER':
continue
entry=copy.deepcopy(pp_kbddriver_plus.TEMPLATE)
entry[pp_kbddriver_plus.NAME]=self.config.get(section,'name')
entry[pp_kbddriver_plus.DIRECTION]=self.config.get(section,'direction')
if entry[pp_kbddriver_plus.DIRECTION] == 'none':
continue
elif entry[pp_kbddriver_plus.DIRECTION] == 'in':
entry[pp_kbddriver_plus.MODE]=self.config.get(section,'mode')
if entry[pp_kbddriver_plus.MODE] in ('specific-character','specific-line'):
entry[pp_kbddriver_plus.MATCH]=self.config.get(section,'match')
pp_kbddriver_plus.in_names.append(copy.deepcopy(entry))
else:
return 'error',pp_kbddriver_plus.title + ' direction not in or out'
# print pp_kbddriver_plus.in_names
# bind the keys
self._bind_keys(widget,self._key_received)
# all ok so indicate the driver is active
pp_kbddriver_plus.driver_active=True
# init must return two arguments
return 'normal',pp_kbddriver_plus.title + ' active'
# sets up tkinter keyboard events such that any key press
# does a callback to _key_received() with the event object
def _bind_keys(self,widget,callback):
for display_name in DisplayManager.display_map:
status,message,display_id,canvas=self.dm.id_of_canvas(display_name)
if status !='normal':
continue
# bind all the normal keys that return a printing character such that x produces pp-key-x (but fileterd in _key_received)
canvas.bind("<Key>", lambda event,match='<Key>',name='': self._key_received(event,match,name))
# print 'bind printing'
# Bind <Return> so that eol detection works, <Return> cannot be used to trigger an input event
# if you wnt that use keys.cfg
canvas.bind("<Return>", lambda event,match='<Return>',name='': self._key_received(event,match,name))
# print 'bind Return to make eol work'
# go through entries and bind all specific-character matches to _key_received
for entry in pp_kbddriver_plus.in_names:
if entry[pp_kbddriver_plus.MODE] == 'specific-character':
match = entry[pp_kbddriver_plus.MATCH]
name = entry[pp_kbddriver_plus.NAME]
canvas.bind(match, lambda event, match=match,name=name: self._key_received(event,match,name))
# print 'bind specific-char', match,name
# start method must be defined. If not using inputs just pass
def start(self):
pp_kbddriver_plus.inputs['current-character']=''
pp_kbddriver_plus.inputs['current-line']=''
pp_kbddriver_plus.inputs['previous-line']=''
def _key_received(self,event,match,name):
# generate the events with symbolic names if driver is active
if pp_kbddriver_plus.driver_active is True:
char=event.char
# print 'received ',char,match,name
# if char is eol then match the line and start a new line
if match =='<Return>':
# do match of line
# print 'do match line',pp_kbddriver_plus.inputs['current-line']
self.match_line(pp_kbddriver_plus.inputs['current-line'])
# shuffle and empty the buffer
pp_kbddriver_plus.inputs['previous-line'] = pp_kbddriver_plus.inputs['current-line']
pp_kbddriver_plus.inputs['current-line']=''
pp_kbddriver_plus.inputs['current-character']=''
if name !='':
# print 'bound <Return> key'
if self.event_callback is not None:
self.event_callback(name,pp_kbddriver_plus.title)
else:
# process a character
if char == '' and match == '<Key>':
# unbound special key
# print 'unbound special key ', match
pass
else:
# a character has been received
pp_kbddriver_plus.inputs['current-character']=char
pp_kbddriver_plus.inputs['current-line']+=char
# print pp_kbddriver_plus.inputs['current-character'],pp_kbddriver_plus.inputs['current-line']
if match == '<Key>' and char != '' and self.bind_printing =='yes':
# print 'printable key, bind-printing is yes',char,match
# printable character without overiding section
if self.event_callback is not None:
self.event_callback('pp-key-'+ char,pp_kbddriver_plus.title)
else:
if name != '':
# print 'bound non-printable character',char,name
if self.event_callback is not None:
self.event_callback(name,pp_kbddriver_plus.title)
# look through entries for any-character
for entry in pp_kbddriver_plus.in_names:
if entry[pp_kbddriver_plus.MODE] == 'any-character':
# print 'match any character', char, 'current line is ',pp_kbddriver_plus.inputs['current-line']
if self.event_callback is not None:
self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title)
def match_line(self,line):
for entry in pp_kbddriver_plus.in_names:
if entry[pp_kbddriver_plus.MODE] == 'any-line':
# print 'match any line',line
if self.event_callback is not None:
self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title)
if entry[pp_kbddriver_plus.MODE] == 'specific-line' and line == entry[pp_kbddriver_plus.MATCH]:
# print 'match specific line', line
if self.event_callback is not None:
self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title)
# allow track plugins (or anything else) to access analog input values
def get_input(self,key):
if key in pp_kbddriver_plus.inputs:
return True, pp_kbddriver_plus.inputs[key]
else:
return False, None
# allow querying of driver state
def is_active(self):
return pp_kbddriver_plus.driver_active
# called by main program only. Called when PP is closed down
def terminate(self):
pp_kbddriver_plus.driver_active = False
# ************************************************
# output interface method
# this can be called from many objects so needs to operate on class variables
# ************************************************
# execute an output event
def handle_output_event(self,name,param_type,param_values,req_time):
return 'normal','no output methods'
# ***********************************
# reading .cfg file
# ************************************
def _read(self,filename,filepath):
if os.path.exists(filepath):
self.config = configparser.ConfigParser(inline_comment_prefixes = (';',))
self.config.read(filepath)
return 'normal',filename+' read'
else:
return 'error',filename+' not found at: '+filepath
if __name__ == '__main__':
from tkinter import *
def key_callback(symbol,source):
print('callback',symbol,source,'\n')
if symbol=='pp-stop':
idd.terminate()
exit()
pass
root = Tk()
w = Label(root, text="pp_kbddriver_plus.py test harness")
w.pack()
idd=pp_kbddriver_plus()
reason,message=idd.init('pp_kbddriver_plus.cfg','/home/pi/pipresents/pp_io_config/keys_plus.cfg',root,key_callback)
print(reason,message)
if reason != 'error':
idd.start()
root.mainloop()
| 2.5 | 2 |
grocery/migrations/0003_alter_item_comments.py | akshay-kapase/shopping | 0 | 2271 | <filename>grocery/migrations/0003_alter_item_comments.py
# Generated by Django 3.2.6 on 2021-09-03 15:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('grocery', '0002_alter_item_comments'),
]
operations = [
migrations.AlterField(
model_name='item',
name='comments',
field=models.CharField(blank=True, default='null', max_length=200),
preserve_default=False,
),
]
| 1.5 | 2 |
projects/objects/buildings/protos/textures/colored_textures/textures_generator.py | yjf18340/webots | 1 | 2272 | #!/usr/bin/env python
# Copyright 1996-2019 Cyberbotics 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.
"""Generate textures prepared for OSM, based on image templates."""
import glob
import os
from PIL import Image
# change directory to this script directory in order to allow this script to be called from another directory.
os.chdir(os.path.dirname(os.path.realpath(__file__)))
# get all the template files in put them in a list of tuples
templates = []
for f in glob.glob("*_diffuse_template.jpg"):
templates.append((f, f.replace('_diffuse_', '_color_mask_')))
# target colors
# ref: http://wiki.openstreetmap.org/wiki/Key:colour
# TODO: is it sufficient?
colors = {
'000000': (0.0, 0.0, 0.0),
'FFFFFF': (0.84, 0.84, 0.84),
'808080': (0.4, 0.4, 0.4),
'C0C0C0': (0.65, 0.65, 0.65),
'800000': (0.4, 0.15, 0.15),
'FF0000': (0.45, 0.0, 0.0),
'808000': (0.4, 0.4, 0.2),
'FFFF00': (0.7, 0.6, 0.15),
'008000': (0.15, 0.3, 0.15),
'00FF00': (0.55, 0.69, 0.52),
'008080': (0.15, 0.3, 0.3),
'00FFFF': (0.6, 0.7, 0.7),
'000080': (0.2, 0.2, 0.3),
'0000FF': (0.4, 0.4, 0.75),
'800080': (0.5, 0.4, 0.5),
'FF00FF': (0.9, 0.75, 0.85),
'F5DEB3': (0.83, 0.78, 0.65),
'8B4513': (0.3, 0.1, 0.05)
}
effectFactor = 0.5 # power of the effect, found empirically
# foreach template
for template in templates:
# load the templates
diffuse = Image.open(template[0])
mask = Image.open(template[1])
assert diffuse.size == mask.size
width, height = diffuse.size
# create an image per color
for colorString, color in colors.iteritems():
image = Image.new('RGB', diffuse.size)
pixels = image.load()
for x in range(height):
for y in range(width):
dR, dG, dB = diffuse.getpixel((x, y))
mR, mG, mB = mask.getpixel((x, y))
r = dR + int(255.0 * (mR / 255.0) * (color[0] * 2.0 - 1.0) * effectFactor)
g = dG + int(255.0 * (mG / 255.0) * (color[1] * 2.0 - 1.0) * effectFactor)
b = dB + int(255.0 * (mB / 255.0) * (color[2] * 2.0 - 1.0) * effectFactor)
pixels[x, y] = (r, g, b)
image.save(template[0].replace('_diffuse_template', '_' + colorString))
| 2.1875 | 2 |
tutorial/test_env.py | viz4biz/PyDataNYC2015 | 11 | 2273 | """
test local env
"""
import os
for k, v in os.environ.iteritems():
print k, '=', v
| 2.015625 | 2 |
project2/marriage.py | filipefborba/MarriageNSFG | 0 | 2274 | <gh_stars>0
"""This file contains code for use with "Think Stats",
by <NAME>, available from greenteapress.com
Copyright 2014 <NAME>
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function, division
import bisect
import numpy as np
import pandas as pd
import scipy.stats
import gzip
import matplotlib.pyplot as plt
from collections import defaultdict
from collections import OrderedDict
from collections import Counter
import thinkstats2
import thinkplot
import survival
def ResampleResps(resps, remove_missing=False, jitter=0):
"""Resamples each dataframe and then concats them.
resps: list of DataFrame
returns: DataFrame
"""
# we have to resample the data from each cycle separately
samples = [ResampleRowsWeighted(resp) for resp in resps]
# then join the cycles into one big sample
sample = pd.concat(samples, ignore_index=True, sort=False)
# remove married people with unknown marriage dates
if remove_missing:
sample = sample[~sample.missing]
# jittering the ages reflects the idea that the resampled people
# are not identical to the actual respondents
if jitter:
Jitter(sample, 'age', jitter=jitter)
Jitter(sample, 'agemarry', jitter=jitter)
DigitizeResp(resp)
return sample
def ResampleRowsWeighted(df, column='finalwgt'):
"""Resamples the rows in df in accordance with a weight column.
df: DataFrame
returns: DataFrame
"""
weights = df['finalwgt'].copy()
weights /= sum(weights)
indices = np.random.choice(df.index, len(df), replace=True, p=weights)
return df.loc[indices]
def Jitter(df, column, jitter=1):
"""Adds random noise to a column.
df: DataFrame
column: string column name
jitter: standard deviation of noise
"""
df[column] += np.random.uniform(-jitter, jitter, size=len(df))
def EstimateSurvival(resp, cutoff=None):
"""Estimates the survival curve.
resp: DataFrame of respondents
cutoff: where to truncate the estimated functions
returns: pair of HazardFunction, SurvivalFunction
"""
complete = resp.loc[resp.complete, 'complete_var'].dropna()
ongoing = resp.loc[~resp.complete, 'ongoing_var'].dropna()
hf = survival.EstimateHazardFunction(complete, ongoing)
if cutoff:
hf.Truncate(cutoff)
sf = hf.MakeSurvival()
return hf, sf
def PropensityMatch(target, group, colname='agemarry'):
"""Choose a random subset of `group` to matches propensity with `target`.
target: DataFrame
group: DataFrame
colname: string name of column with propensity scores
returns: DataFrame with sample of rows from `group`
"""
rv = scipy.stats.norm(scale=1)
values = group[colname].fillna(100)
def ChooseIndex(value):
weights = rv.pdf(values-value)
weights /= sum(weights)
return np.random.choice(group.index, 1, p=weights)[0]
indices = [ChooseIndex(value) for value in target[colname]]
return group.loc[indices]
def EstimateSurvivalByCohort(resps, iters=101,
cutoffs=None, predict_flag=False,
prop_match=None, error_rate=0):
"""Makes survival curves for resampled data.
resps: list of DataFrames
iters: number of resamples to plot
predict_flag: whether to also plot predictions
cutoffs: map from cohort to the first unreliable age_index
returns: map from group name to list of survival functions
"""
if cutoffs == None:
cutoffs = {}
sf_map = defaultdict(list)
# iters is the number of resampling runs to make
for i in range(iters):
sample = ResampleResps(resps)
# group by decade
grouped = sample.groupby('birth_index')
if prop_match:
last = grouped.get_group(prop_match)
# and estimate (hf, sf) for each group
hf_map = OrderedDict()
for name, group in iter(grouped):
if prop_match:
group = PropensityMatch(last, group)
if error_rate:
AddErrors(group, 'complete_missing', error_rate)
AddErrors(group, 'ongoing_missing', error_rate)
# the amount of missing data is small; I think it is better
# to drop it than to fill with random data
#FillMissingColumn(group, 'complete_var', 'complete_missing')
#FillMissingColumn(group, 'ongoing_var', 'ongoing_missing')
cutoff = cutoffs.get(name, 100)
hf_map[name] = EstimateSurvival(group, cutoff)
# make predictions if desired
if predict_flag:
MakePredictions(hf_map)
# extract the sf from each pair and accumulate the results
for name, (hf, sf) in hf_map.items():
sf_map[name].append(sf)
return sf_map
def AddErrors(group, colname, error_rate):
"""
NOTE: This will not work if there are actual missing values!
"""
group[colname] = np.random.random(len(group)) < error_rate
def FillMissingColumn(group, colname, missing_colname):
"""Fills missing values of the given column.
group: DataFrame
colname: string
"""
null = group[group[missing_colname]]
if len(null) == 0:
return
# print(len(null), len(group))
valid = group[colname].dropna()
fill = valid.sample(len(null), replace=True)
fill.index = null.index
group[colname].fillna(fill, inplace=True)
def PlotSurvivalFunctions(sf_map, predict_flag=False, colormap=None):
"""Plot estimated survival functions.
sf_map: map from group name to sequence of survival functions
predict_flag: whether the lines are predicted or actual
colormap: map from group name to color
"""
for name, sf_seq in sorted(sf_map.items(), reverse=True):
if len(sf_seq) == 0:
continue
sf = sf_seq[0]
if len(sf) == 0:
continue
ts, rows = MakeSurvivalCI(sf_seq, [10, 50, 90])
thinkplot.FillBetween(ts, rows[0], rows[2], color='gray', alpha=0.2)
if not predict_flag:
if colormap:
color = colormap[name]
thinkplot.Plot(ts, rows[1], label='%ds'%name, color=color)
else:
thinkplot.Plot(ts, rows[1], label='%ds'%name)
def MakePredictions(hf_map):
"""Extends a set of hazard functions and recomputes survival functions.
For each group in hf_map, we extend hf and recompute sf.
hf_map: map from group name to (HazardFunction, SurvivalFunction)
"""
names = list(hf_map.keys())
names.sort()
hfs = [hf_map[name][0] for name in names]
# extend each hazard function using data from the previous cohort,
# and update the survival function
for i, name in enumerate(names):
hf, sf = hf_map[name]
if i > 0:
hf.Extend(hfs[i-1])
sf = hf.MakeSurvival()
hf_map[name] = hf, sf
def MakeSurvivalCI(sf_seq, percents):
"""Makes confidence intervals from a list of survival functions.
sf_seq: list of SurvivalFunction
percents: list of percentiles to select, like [5, 95]
returns: (ts, rows) where ts is a sequence of times and
rows contains one row of values for each percent
"""
# find the union of all ts where the sfs are evaluated
ts = set()
for sf in sf_seq:
ts |= set(sf.ts)
ts = list(ts)
ts.sort()
# evaluate each sf at all times
ss_seq = [sf.Probs(ts) for sf in sf_seq if len(sf) > 0]
# return the requested percentiles from each column
rows = thinkstats2.PercentileRows(ss_seq, percents)
return ts, rows
def ReadFemResp1982():
"""Reads respondent data from NSFG Cycle 3.
returns: DataFrame
"""
dat_file = '1982NSFGData.dat.gz'
names = ['finalwgt', 'ageint', 'mar2p', 'cmmarrhx', 'fmarital',
'cmintvw', 'cmbirth', 'f18m1', 'cmdivorcx', 'cmstphsbx', 'fmarno']
colspecs = [(976-1, 982),
(1001-1, 1002),
(1268-1, 1271),
(1037-1, 1040),
(1041-1, 1041),
(841-1, 844),
(12-1, 15),
(606-1, 606),
(619-1, 622),
(625-1, 628),
(1142-1, 1143),
]
df = pd.read_fwf(dat_file,
colspecs=colspecs,
names=names,
header=None,
nrows=7969,
compression='gzip')
df.cmintvw.replace([9797, 9898, 9999], np.nan, inplace=True)
df.cmbirth.replace([9797, 9898, 9999], np.nan, inplace=True)
df.cmmarrhx.replace([9797, 9898, 9999], np.nan, inplace=True)
df.cmdivorcx.replace([9797, 9898, 9999], np.nan, inplace=True)
df.cmstphsbx.replace([9797, 9898, 9999], np.nan, inplace=True)
df.f18m1.replace([7, 8, 9], np.nan, inplace=True)
# CM values above 9000 indicate month unknown
df.loc[df.cmintvw>9000, 'cmintvw'] -= 9000
df.loc[df.cmbirth>9000, 'cmbirth'] -= 9000
df.loc[df.cmmarrhx>9000, 'cmmarrhx'] -= 9000
df.loc[df.cmdivorcx>9000, 'cmdivorcx'] -= 9000
df.loc[df.cmstphsbx>9000, 'cmstphsbx'] -= 9000
df['evrmarry'] = (df.fmarno > 0)
df['divorced'] = (df.f18m1 == 4)
df['separated'] = (df.f18m1 == 5)
df['widowed'] = (df.f18m1 == 3)
df['stillma'] = (df.fmarno==1) & (df.fmarital==1)
df['cycle'] = 3
CleanResp(df)
return df
def ReadFemResp1988():
"""Reads respondent data from NSFG Cycle 4.
Read as if were a standard ascii file
returns: DataFrame
"""
filename = '1988FemRespDataLines.dat.gz'
names = ['finalwgt', 'ageint', 'currentcm',
'firstcm', 'cmintvw', 'cmbirth',
'f23m1', 'cmdivorcx', 'cmstphsbx', 'fmarno']
colspecs = [(2568-1, 2574),
(36-1, 37),
(1521-1, 1525),
(1538-1, 1542),
(12-1, 16),
(26-1, 30),
(1554-1, 1554),
(1565-1, 1569),
(1570-1, 1574),
(2441-1, 2442),
]
df = pd.read_fwf(filename,
colspecs=colspecs,
names=names,
header=None,
compression='gzip')
df.cmintvw.replace([0, 99999], np.nan, inplace=True)
df.cmbirth.replace([0, 99999], np.nan, inplace=True)
df.firstcm.replace([0, 99999], np.nan, inplace=True)
df.currentcm.replace([0, 99999], np.nan, inplace=True)
df.cmdivorcx.replace([0, 99999], np.nan, inplace=True)
df.cmstphsbx.replace([0, 99999], np.nan, inplace=True)
# CM values above 9000 indicate month unknown
df.loc[df.cmintvw>90000, 'cmintvw'] -= 90000
df.loc[df.cmbirth>90000, 'cmbirth'] -= 90000
df.loc[df.firstcm>90000, 'firstcm'] -= 90000
df.loc[df.currentcm>90000, 'currentcm'] -= 90000
df.loc[df.cmdivorcx>90000, 'cmdivorcx'] -= 90000
df.loc[df.cmstphsbx>90000, 'cmstphsbx'] -= 90000
# combine current and first marriage
df['cmmarrhx'] = df.firstcm
df.cmmarrhx.fillna(df.currentcm, inplace=True)
# define evrmarry if either currentcm or firstcm is non-zero
df['evrmarry'] = (df.fmarno > 0)
df['divorced'] = (df.f23m1==2)
df['separated'] = (df.f23m1==3)
df['widowed'] = (df.f23m1==1)
df['stillma'] = (df.fmarno==1) & (df.f23m1.isnull())
df['cycle'] = 4
CleanResp(df)
return df
def ReadFemResp1995():
"""Reads respondent data from NSFG Cycle 5.
returns: DataFrame
"""
dat_file = '1995FemRespData.dat.gz'
names = ['cmintvw', 'timesmar', 'cmmarrhx', 'cmbirth', 'finalwgt',
'marend01', 'cmdivorcx', 'cmstphsbx', 'marstat']
colspecs = [(12360-1, 12363),
(4637-1, 4638),
(11759-1, 11762),
(14-1, 16),
(12350-1, 12359),
(4713-1, 4713),
(4718-1, 4721),
(4722-1, 4725),
(17-1, 17)]
df = pd.read_fwf(dat_file,
compression='gzip',
colspecs=colspecs,
names=names)
invalid = [9997, 9998, 9999]
df.cmintvw.replace(invalid, np.nan, inplace=True)
df.cmbirth.replace(invalid, np.nan, inplace=True)
df.cmmarrhx.replace(invalid, np.nan, inplace=True)
df.cmdivorcx.replace(invalid, np.nan, inplace=True)
df.cmstphsbx.replace(invalid, np.nan, inplace=True)
df.timesmar.replace([98, 99], np.nan, inplace=True)
df['evrmarry'] = (df.timesmar > 0)
df['divorced'] = (df.marend01==1)
df['separated'] = (df.marend01==2)
df['widowed'] = (df.marend01==3)
df['stillma'] = (df.timesmar==1) & (df.marend01.isnull())
df['cycle'] = 5
CleanResp(df)
return df
def ReadFemResp2002():
"""Reads respondent data from NSFG Cycle 6.
returns: DataFrame
"""
usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw',
'evrmarry', 'parity', 'finalwgt',
'mardat01', 'marend01', 'mardis01', 'rmarital',
'fmarno', 'mar1diss']
df = ReadResp('2002FemResp.dct', '2002FemResp.dat.gz', usecols=usecols)
invalid = [9997, 9998, 9999]
df.cmintvw.replace(invalid, np.nan, inplace=True)
df.cmbirth.replace(invalid, np.nan, inplace=True)
df.cmmarrhx.replace(invalid, np.nan, inplace=True)
df['evrmarry'] = (df.evrmarry==1)
df['divorced'] = (df.marend01==1)
df['separated'] = (df.marend01==2)
df['widowed'] = (df.marend01==3)
df['stillma'] = (df.fmarno == 1) & (df.rmarital==1)
df['cycle'] = 6
CleanResp(df)
return df
def ReadFemResp2010():
"""Reads respondent data from NSFG Cycle 7.
returns: DataFrame
"""
usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw',
'evrmarry', 'parity', 'wgtq1q16',
'mardat01', 'marend01', 'mardis01', 'rmarital',
'fmarno', 'mar1diss']
df = ReadResp('2006_2010_FemRespSetup.dct',
'2006_2010_FemResp.dat.gz',
usecols=usecols)
invalid = [9997, 9998, 9999]
df.cmintvw.replace(invalid, np.nan, inplace=True)
df.cmbirth.replace(invalid, np.nan, inplace=True)
df.cmmarrhx.replace(invalid, np.nan, inplace=True)
df['evrmarry'] = (df.evrmarry==1)
df['divorced'] = (df.marend01==1)
df['separated'] = (df.marend01==2)
df['widowed'] = (df.marend01==3)
df['stillma'] = (df.fmarno == 1) & (df.rmarital==1)
df['finalwgt'] = df.wgtq1q16
df['cycle'] = 7
CleanResp(df)
return df
def ReadFemResp2013():
"""Reads respondent data from NSFG Cycle 8.
returns: DataFrame
"""
usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw',
'evrmarry', 'parity', 'wgt2011_2013',
'mardat01', 'marend01', 'mardis01', 'rmarital',
'fmarno', 'mar1diss']
df = ReadResp('2011_2013_FemRespSetup.dct',
'2011_2013_FemRespData.dat.gz',
usecols=usecols)
invalid = [9997, 9998, 9999]
df.cmintvw.replace(invalid, np.nan, inplace=True)
df.cmbirth.replace(invalid, np.nan, inplace=True)
df.cmmarrhx.replace(invalid, np.nan, inplace=True)
df['evrmarry'] = (df.evrmarry==1)
df['divorced'] = (df.marend01==1)
df['separated'] = (df.marend01==2)
df['widowed'] = (df.marend01==3)
df['stillma'] = (df.fmarno == 1) & (df.rmarital==1)
df['finalwgt'] = df.wgt2011_2013
df['cycle'] = 8
CleanResp(df)
return df
def ReadFemResp2015():
"""Reads respondent data from NSFG Cycle 9.
returns: DataFrame
"""
usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw',
'evrmarry', 'parity', 'wgt2013_2015',
'mardat01', 'marend01', 'mardis01', 'rmarital',
'fmarno', 'mar1diss']
df = ReadResp('2013_2015_FemRespSetup.dct',
'2013_2015_FemRespData.dat.gz',
usecols=usecols)
invalid = [9997, 9998, 9999]
df.cmintvw.replace(invalid, np.nan, inplace=True)
df.cmbirth.replace(invalid, np.nan, inplace=True)
df.cmmarrhx.replace(invalid, np.nan, inplace=True)
df['evrmarry'] = (df.evrmarry==1)
df['divorced'] = (df.marend01==1)
df['separated'] = (df.marend01==2)
df['widowed'] = (df.marend01==3)
df['stillma'] = (df.fmarno == 1) & (df.rmarital==1)
df['finalwgt'] = df.wgt2013_2015
df['cycle'] = 9
CleanResp(df)
return df
def ReadFemResp2017():
"""Reads respondent data from NSFG Cycle 10.
returns: DataFrame
"""
# removed 'cmmarrhx', 'cmdivorcx', 'cmbirth',
usecols = ['caseid', 'cmintvw', 'ager',
'evrmarry', 'parity', 'wgt2015_2017',
'mardat01', 'marend01', 'mardis01', 'rmarital',
'fmarno', 'mar1diss']
df = ReadResp('2015_2017_FemRespSetup.dct',
'2015_2017_FemRespData.dat.gz',
usecols=usecols)
invalid = [9997, 9998, 9999]
df.cmintvw.replace(invalid, np.nan, inplace=True)
#df.cmbirth.replace(invalid, np.nan, inplace=True)
#df.cmmarrhx.replace(invalid, np.nan, inplace=True)
# since cmbirth and cmmarrhx are no longer included,
# we have to compute them based on other variables;
# the result can be off by up to 12 months
df['cmbirth'] = df.cmintvw - df.ager*12
df['cmmarrhx'] = (df.mardat01-1900) * 12
df['evrmarry'] = (df.evrmarry==1)
df['divorced'] = (df.marend01==1)
df['separated'] = (df.marend01==2)
df['widowed'] = (df.marend01==3)
df['stillma'] = (df.fmarno == 1) & (df.rmarital==1)
df['finalwgt'] = df.wgt2015_2017
df['cycle'] = 10
# Instead of calling CleanResp, we have to customize
#CleanResp(df)
df['agemarry'] = (df.cmmarrhx - df.cmbirth) / 12.0
df['age'] = (df.cmintvw - df.cmbirth) / 12.0
# if married, we need agemarry; if not married, we need age
df['missing'] = np.where(df.evrmarry,
df.agemarry.isnull(),
df.age.isnull())
month0 = pd.to_datetime('1899-12-15')
dates = [month0 + pd.DateOffset(months=cm)
for cm in df.cmbirth]
df['year'] = (pd.DatetimeIndex(dates).year - 1900)
DigitizeResp(df)
return df
def ReadResp(dct_file, dat_file, **options):
"""Reads the NSFG respondent data.
dct_file: string file name
dat_file: string file name
returns: DataFrame
"""
dct = thinkstats2.ReadStataDct(dct_file, encoding='iso-8859-1')
df = dct.ReadFixedWidth(dat_file, compression='gzip', **options)
return df
def CleanResp(resp):
"""Cleans a respondent DataFrame.
resp: DataFrame of respondents
Adds columns: agemarry, age, decade, fives
"""
resp['agemarry'] = (resp.cmmarrhx - resp.cmbirth) / 12.0
resp['age'] = (resp.cmintvw - resp.cmbirth) / 12.0
# if married, we need agemarry; if not married, we need age
resp['missing'] = np.where(resp.evrmarry,
resp.agemarry.isnull(),
resp.age.isnull())
month0 = pd.to_datetime('1899-12-15')
dates = [month0 + pd.DateOffset(months=cm)
for cm in resp.cmbirth]
resp['year'] = (pd.DatetimeIndex(dates).year - 1900)
#resp['decade'] = resp.year // 10
#resp['fives'] = resp.year // 5
DigitizeResp(resp)
def DigitizeResp(df):
"""Computes indices for age, agemarry, and birth year.
Groups each of these variables into bins and then assigns
an index to each bin.
For example, anyone between 30 and 30.99 year old is
assigned age_index 30. Anyone born in the 80s is given
the year_index 80.
This function allows me to run the analysis with different
levels of granularity.
df: DataFrame
"""
age_min = 10
age_max = 55
age_step = 1
age_bins = np.arange(age_min, age_max, age_step)
year_min = 0
year_max = 120
year_step = 10
year_bins = np.arange(year_min, year_max, year_step)
df['age_index'] = np.digitize(df.age, age_bins) * age_step
df.age_index += age_min - age_step
df.loc[df.age.isnull(), 'age_index'] = np.nan
df['agemarry_index'] = np.digitize(df.agemarry, age_bins) * age_step
df.agemarry_index += age_min - age_step
df.loc[df.agemarry.isnull(), 'agemarry_index'] = np.nan
df['birth_index'] = np.digitize(df.year, year_bins) * year_step
df.birth_index += year_min - year_step
def ReadCanadaCycle5():
"""
"""
#age at first marriage: CC232
#age of respondent at interview: C3
#final weight: C1
#marital status: C5
#Respondent every married: CC227
pass
def ReadCanadaCycle6():
"""
"""
#age at first marriage: CC232
#age of respondent at interview: C3
#final weight: C1
#marital status: C5
#Respondent every married: CC227
pass
def ReadMaleResp2002():
"""Reads respondent data from NSFG Cycle 6.
returns: DataFrame
"""
usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw',
'evrmarry', 'finalwgt', 'fmarit', 'timesmar', 'marrend4',
#'marrend', 'marrend2', 'marrend3', marrend5', 'marrend6',
]
df = ReadResp('2002Male.dct', '2002Male.dat.gz', usecols=usecols)
#df.marrend.replace([8,9], np.nan, inplace=True)
#df.marrend2.replace([8,9], np.nan, inplace=True)
#df.marrend3.replace([8,9], np.nan, inplace=True)
df.marrend4.replace([8,9], np.nan, inplace=True)
#df.marrend5.replace([8,9], np.nan, inplace=True)
#df.marrend6.replace([8,9], np.nan, inplace=True)
df.timesmar.replace([98,99], np.nan, inplace=True)
# the way marriage ends are recorded is really confusing,
# but it looks like marrend4 is the end of the first marriage.
df['marend01'] = df.marrend4
df['cmmarrhx'] = df.mardat01
df['evrmarry'] = (df.timesmar > 0)
df['divorced'] = (df.marend01==2) | (df.marend01==3)
df['separated'] = (df.marend01==4)
df['widowed'] = (df.marend01==1)
df['stillma'] = (df.timesmar== 1) & (df.fmarit==1)
df['cycle'] = 6
CleanResp(df)
return df
def ReadMaleResp2010():
"""Reads respondent data from NSFG Cycle 7.
returns: DataFrame
"""
usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw',
'evrmarry', 'wgtq1q16',
'marend01', 'rmarital', 'fmarno', 'mar1diss']
df = ReadResp('2006_2010_MaleSetup.dct',
'2006_2010_Male.dat.gz',
usecols=usecols)
df['cmmarrhx'] = df.mardat01
df['evrmarry'] = (df.evrmarry==1)
df['divorced'] = (df.marend01==1)
df['separated'] = (df.marend01==2)
df['widowed'] = (df.marend01==3)
df['stillma'] = (df.fmarno == 1) & (df.rmarital==1)
df['finalwgt'] = df.wgtq1q16
df['cycle'] = 7
CleanResp(df)
return df
def ReadMaleResp2013():
"""Reads respondent data from NSFG Cycle 8.
returns: DataFrame
"""
usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw',
'evrmarry', 'wgt2011_2013',
'marend01', 'rmarital', 'fmarno', 'mar1diss']
df = ReadResp('2011_2013_MaleSetup.dct',
'2011_2013_MaleData.dat.gz',
usecols=usecols)
df['cmmarrhx'] = df.mardat01
df['evrmarry'] = (df.evrmarry==1)
df['divorced'] = (df.marend01==1)
df['separated'] = (df.marend01==2)
df['widowed'] = (df.marend01==3)
df['stillma'] = (df.fmarno == 1) & (df.rmarital==1)
df['finalwgt'] = df.wgt2011_2013
df['cycle'] = 8
CleanResp(df)
return df
def ReadMaleResp2015():
"""Reads respondent data from NSFG Cycle 9.
returns: DataFrame
"""
usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw',
'evrmarry', 'wgt2013_2015',
'marend01', 'rmarital', 'fmarno', 'mar1diss']
df = ReadResp('2013_2015_MaleSetup.dct',
'2013_2015_MaleData.dat.gz',
usecols=usecols)
df['cmmarrhx'] = df.mardat01
df['evrmarry'] = (df.evrmarry==1)
df['divorced'] = (df.marend01==1)
df['separated'] = (df.marend01==2)
df['widowed'] = (df.marend01==3)
df['stillma'] = (df.fmarno == 1) & (df.rmarital==1)
df['finalwgt'] = df.wgt2013_2015
df['cycle'] = 9
CleanResp(df)
return df
def ReadMaleResp2017():
"""Reads respondent data from NSFG Cycle 10.
returns: DataFrame
"""
usecols = ['caseid', 'mardat01', 'cmintvw', 'ager',
'evrmarry', 'wgt2015_2017',
'marend01', 'rmarital', 'fmarno', 'mar1diss']
df = ReadResp('2015_2017_MaleSetup.dct',
'2015_2017_MaleData.dat.gz',
usecols=usecols)
# since cmbirth and cmmarrhx are no longer included,
# we have to compute them based on other variables;
# the result can be off by up to 12 months
df['cmbirth'] = df.cmintvw - df.ager*12
df['cmmarrhx'] = (df.mardat01-1900) * 12
df['evrmarry'] = (df.evrmarry==1)
df['divorced'] = (df.marend01==1)
df['separated'] = (df.marend01==2)
df['widowed'] = (df.marend01==3)
df['stillma'] = (df.fmarno == 1) & (df.rmarital==1)
df['finalwgt'] = df.wgt2015_2017
df['cycle'] = 10
# Instead of calling CleanResp, we have to customize
#CleanResp(df)
df['agemarry'] = (df.cmmarrhx - df.cmbirth) / 12.0
df['age'] = (df.cmintvw - df.cmbirth) / 12.0
# if married, we need agemarry; if not married, we need age
df['missing'] = np.where(df.evrmarry,
df.agemarry.isnull(),
df.age.isnull())
month0 = pd.to_datetime('1899-12-15')
dates = [month0 + pd.DateOffset(months=cm)
for cm in df.cmbirth]
df['year'] = (pd.DatetimeIndex(dates).year - 1900)
DigitizeResp(df)
return df
def Validate1982(df):
assert(len(df) == 7969)
assert(len(df[df.evrmarry]) == 4651)
assert(df.agemarry.value_counts().max() == 71)
def Validate1988(df):
assert(len(df) == 8450)
assert(len(df[df.evrmarry]) == 5290)
assert(df.agemarry.value_counts().max() == 73)
def Validate1995(df):
assert(len(df) == 10847)
assert(len(df[df.evrmarry]) == 6841)
assert(df.agemarry.value_counts().max() == 79)
def Validate2002(df):
assert(len(df) == 7643)
assert(sum(df.evrmarry) == 4126)
assert(df.agemarry.value_counts().max() == 45)
def Validate2010(df):
assert(len(df) == 12279)
assert(sum(df.evrmarry) == 5534)
assert(df.agemarry.value_counts().max() == 64)
def Validate2013(df):
assert(len(df) == 5601)
assert(sum(df.evrmarry) == 2452)
assert(df.agemarry.value_counts().max() == 33)
def Validate2015(df):
assert(len(df) == 5699)
assert(sum(df.evrmarry) == 2401)
assert(df.agemarry.value_counts().max() == 25)
def Validate2017(df):
assert(len(df) == 5554)
assert(sum(df.evrmarry) == 2582)
assert(df.agemarry.value_counts().max() == 29)
def main():
print('Cycle 10')
resp10 = ReadFemResp2017()
Validate2017(resp10)
print('Cycle 9')
resp9 = ReadFemResp2015()
Validate2015(resp9)
print('Cycle 8')
resp8 = ReadFemResp2013()
Validate2013(resp8)
print('Cycle 7')
resp7 = ReadFemResp2010()
Validate2010(resp7)
print('Cycle 6')
resp6 = ReadFemResp2002()
Validate2002(resp6)
print('Cycle 5')
resp5 = ReadFemResp1995()
Validate1995(resp5)
print('Cycle 4')
resp4 = ReadFemResp1988()
Validate1988(resp4)
print('Cycle 3')
resp3 = ReadFemResp1982()
Validate1982(resp3)
if __name__ == '__main__':
main()
| 2.953125 | 3 |
xfel/merging/application/reflection_table_utils.py | ErwinP/cctbx_project | 0 | 2275 | <gh_stars>0
from __future__ import absolute_import, division, print_function
from six.moves import range
from dials.array_family import flex
import math
class reflection_table_utils(object):
@staticmethod
def get_next_hkl_reflection_table(reflections):
'''Generate asu hkl slices from an asu hkl-sorted reflection table'''
if reflections.size() == 0:
yield reflections
i_begin = 0
hkl_ref = reflections[0].get('miller_index_asymmetric')
for i in range(reflections.size()):
hkl = reflections[i].get('miller_index_asymmetric')
if hkl == hkl_ref:
continue
else:
yield reflections[i_begin:i]
i_begin = i
hkl_ref = hkl
yield reflections[i_begin:i+1]
@staticmethod
def select_odd_experiment_reflections(reflections):
'Select reflections from experiments with odd ids. An experiment id must be a string representing a hexadecimal number'
sel = flex.bool()
for refl in reflections:
sel.append(int(refl['exp_id'], 16)%2 != 0)
return reflections.select(sel)
@staticmethod
def select_even_experiment_reflections(reflections):
'Select reflections from experiments with even ids. An experiment id must be a string representing a hexadecimal number'
sel = flex.bool()
for refl in reflections:
sel.append(int(refl['exp_id'], 16)%2 == 0)
return reflections.select(sel)
@staticmethod
def merged_reflection_table():
'''Create a reflection table for storing merged HKLs'''
table = flex.reflection_table()
table['miller_index'] = flex.miller_index()
table['intensity'] = flex.double()
table['sigma'] = flex.double()
table['multiplicity'] = flex.int()
return table
@staticmethod
def merge_reflections(reflections, min_multiplicity):
'''Merge intensities of multiply-measured symmetry-reduced HKLs'''
merged_reflections = reflection_table_utils.merged_reflection_table()
for refls in reflection_table_utils.get_next_hkl_reflection_table(reflections=reflections):
if refls.size() == 0:
break # unless the input "reflections" list is empty, generated "refls" lists cannot be empty
hkl = refls[0]['miller_index_asymmetric']
# This assert is timeconsuming when using a small number of cores
#assert not (hkl in merged_reflections['miller_index']) # i.e. assert that the input reflection table came in sorted
refls = refls.select(refls['intensity.sum.variance'] > 0.0)
if refls.size() >= min_multiplicity:
weighted_intensity_array = refls['intensity.sum.value'] / refls['intensity.sum.variance']
weights_array = flex.double(refls.size(), 1.0) / refls['intensity.sum.variance']
weighted_mean_intensity = flex.sum(weighted_intensity_array) / flex.sum(weights_array)
standard_error_of_weighted_mean_intensity = 1.0/math.sqrt(flex.sum(weights_array))
merged_reflections.append(
{'miller_index' : hkl,
'intensity' : weighted_mean_intensity,
'sigma' : standard_error_of_weighted_mean_intensity,
'multiplicity' : refls.size()})
return merged_reflections
@staticmethod
def prune_reflection_table_keys(reflections, keys_to_delete=None, keys_to_keep=None):
'''Remove reflection table keys: either inclusive or exclusive'''
if len(reflections) != 0:
all_keys = list()
for key in reflections[0]:
all_keys.append(key)
if keys_to_delete != None:
for key in keys_to_delete:
if key in all_keys:
del reflections[key]
elif keys_to_keep != None:
for key in all_keys:
#if not key in ['intensity.sum.value', 'intensity.sum.variance', 'miller_index', 'miller_index_asymmetric', 'exp_id', 'odd_frame', 's1']:
if not key in keys_to_keep:
del reflections[key]
return reflections
| 2.21875 | 2 |
rpython/memory/test/test_transformed_gc.py | jptomo/pypy-lang-scheme | 1 | 2276 | <reponame>jptomo/pypy-lang-scheme
import py
import inspect
from rpython.rlib.objectmodel import compute_hash, compute_identity_hash
from rpython.translator.c import gc
from rpython.annotator import model as annmodel
from rpython.rtyper.llannotation import SomePtr
from rpython.rtyper.lltypesystem import lltype, llmemory, rffi, llgroup
from rpython.memory.gctransform import framework, shadowstack
from rpython.rtyper.lltypesystem.lloperation import llop, void
from rpython.rlib.objectmodel import compute_unique_id, we_are_translated
from rpython.rlib.debug import ll_assert
from rpython.rlib import rgc
from rpython.conftest import option
from rpython.rlib.rstring import StringBuilder
from rpython.rlib.rarithmetic import LONG_BIT
WORD = LONG_BIT // 8
def rtype(func, inputtypes, specialize=True, gcname='ref',
backendopt=False, **extraconfigopts):
from rpython.translator.translator import TranslationContext
t = TranslationContext()
# XXX XXX XXX mess
t.config.translation.gc = gcname
t.config.translation.gcremovetypeptr = True
t.config.set(**extraconfigopts)
ann = t.buildannotator()
ann.build_types(func, inputtypes)
if specialize:
t.buildrtyper().specialize()
if backendopt:
from rpython.translator.backendopt.all import backend_optimizations
backend_optimizations(t)
if option.view:
t.viewcg()
return t
ARGS = lltype.FixedSizeArray(lltype.Signed, 3)
class GCTest(object):
gcpolicy = None
GC_CAN_MOVE = False
taggedpointers = False
def setup_class(cls):
cls.marker = lltype.malloc(rffi.CArray(lltype.Signed), 1,
flavor='raw', zero=True)
funcs0 = []
funcs2 = []
cleanups = []
name_to_func = {}
mixlevelstuff = []
for fullname in dir(cls):
if not fullname.startswith('define'):
continue
definefunc = getattr(cls, fullname)
_, name = fullname.split('_', 1)
func_fixup = definefunc.im_func(cls)
cleanup = None
if isinstance(func_fixup, tuple):
func, cleanup, fixup = func_fixup
mixlevelstuff.append(fixup)
else:
func = func_fixup
func.func_name = "f_%s" % name
if cleanup:
cleanup.func_name = "clean_%s" % name
nargs = len(inspect.getargspec(func)[0])
name_to_func[name] = len(funcs0)
if nargs == 2:
funcs2.append(func)
funcs0.append(None)
elif nargs == 0:
funcs0.append(func)
funcs2.append(None)
else:
raise NotImplementedError(
"defined test functions should have 0/2 arguments")
# used to let test cleanup static root pointing to runtime
# allocated stuff
cleanups.append(cleanup)
def entrypoint(args):
num = args[0]
func = funcs0[num]
if func:
res = func()
else:
func = funcs2[num]
res = func(args[1], args[2])
cleanup = cleanups[num]
if cleanup:
cleanup()
return res
from rpython.translator.c.genc import CStandaloneBuilder
s_args = SomePtr(lltype.Ptr(ARGS))
t = rtype(entrypoint, [s_args], gcname=cls.gcname,
taggedpointers=cls.taggedpointers)
for fixup in mixlevelstuff:
if fixup:
fixup(t)
cbuild = CStandaloneBuilder(t, entrypoint, config=t.config,
gcpolicy=cls.gcpolicy)
db = cbuild.generate_graphs_for_llinterp()
entrypointptr = cbuild.getentrypointptr()
entrygraph = entrypointptr._obj.graph
if option.view:
t.viewcg()
cls.name_to_func = name_to_func
cls.entrygraph = entrygraph
cls.rtyper = t.rtyper
cls.db = db
def runner(self, name, transformer=False):
db = self.db
name_to_func = self.name_to_func
entrygraph = self.entrygraph
from rpython.rtyper.llinterp import LLInterpreter
llinterp = LLInterpreter(self.rtyper)
gct = db.gctransformer
if self.__class__.__dict__.get('_used', False):
teardowngraph = gct.frameworkgc__teardown_ptr.value._obj.graph
llinterp.eval_graph(teardowngraph, [])
self.__class__._used = True
# FIIIIISH
setupgraph = gct.frameworkgc_setup_ptr.value._obj.graph
# setup => resets the gc
llinterp.eval_graph(setupgraph, [])
def run(args):
ll_args = lltype.malloc(ARGS, immortal=True)
ll_args[0] = name_to_func[name]
for i in range(len(args)):
ll_args[1+i] = args[i]
res = llinterp.eval_graph(entrygraph, [ll_args])
return res
if transformer:
return run, gct
else:
return run
class GenericGCTests(GCTest):
GC_CAN_SHRINK_ARRAY = False
def define_instances(cls):
class A(object):
pass
class B(A):
def __init__(self, something):
self.something = something
def malloc_a_lot():
i = 0
first = None
while i < 10:
i += 1
a = somea = A()
a.last = first
first = a
j = 0
while j < 30:
b = B(somea)
b.last = first
j += 1
return 0
return malloc_a_lot
def test_instances(self):
run = self.runner("instances")
run([])
def define_llinterp_lists(cls):
def malloc_a_lot():
i = 0
while i < 10:
i += 1
a = [1] * 10
j = 0
while j < 30:
j += 1
a.append(j)
return 0
return malloc_a_lot
def test_llinterp_lists(self):
run = self.runner("llinterp_lists")
run([])
def define_llinterp_tuples(cls):
def malloc_a_lot():
i = 0
while i < 10:
i += 1
a = (1, 2, i)
b = [a] * 10
j = 0
while j < 20:
j += 1
b.append((1, j, i))
return 0
return malloc_a_lot
def test_llinterp_tuples(self):
run = self.runner("llinterp_tuples")
run([])
def define_llinterp_dict(self):
class A(object):
pass
def malloc_a_lot():
i = 0
while i < 10:
i += 1
a = (1, 2, i)
b = {a: A()}
j = 0
while j < 20:
j += 1
b[1, j, i] = A()
return 0
return malloc_a_lot
def test_llinterp_dict(self):
run = self.runner("llinterp_dict")
run([])
def skipdefine_global_list(cls):
gl = []
class Box:
def __init__(self):
self.lst = gl
box = Box()
def append_to_list(i, j):
box.lst.append([i] * 50)
llop.gc__collect(lltype.Void)
return box.lst[j][0]
return append_to_list, None, None
def test_global_list(self):
py.test.skip("doesn't fit in the model, tested elsewhere too")
run = self.runner("global_list")
res = run([0, 0])
assert res == 0
for i in range(1, 5):
res = run([i, i - 1])
assert res == i - 1 # crashes if constants are not considered roots
def define_string_concatenation(cls):
def concat(j, dummy):
lst = []
for i in range(j):
lst.append(str(i))
return len("".join(lst))
return concat
def test_string_concatenation(self):
run = self.runner("string_concatenation")
res = run([100, 0])
assert res == len(''.join([str(x) for x in range(100)]))
def define_nongc_static_root(cls):
T1 = lltype.GcStruct("C", ('x', lltype.Signed))
T2 = lltype.Struct("C", ('p', lltype.Ptr(T1)))
static = lltype.malloc(T2, immortal=True)
def f():
t1 = lltype.malloc(T1)
t1.x = 42
static.p = t1
llop.gc__collect(lltype.Void)
return static.p.x
def cleanup():
static.p = lltype.nullptr(T1)
return f, cleanup, None
def test_nongc_static_root(self):
run = self.runner("nongc_static_root")
res = run([])
assert res == 42
def define_finalizer(cls):
class B(object):
pass
b = B()
b.nextid = 0
b.num_deleted = 0
class A(object):
def __init__(self):
self.id = b.nextid
b.nextid += 1
def __del__(self):
b.num_deleted += 1
def f(x, y):
a = A()
i = 0
while i < x:
i += 1
a = A()
llop.gc__collect(lltype.Void)
llop.gc__collect(lltype.Void)
return b.num_deleted
return f
def test_finalizer(self):
run = self.runner("finalizer")
res = run([5, 42]) #XXX pure lazyness here too
assert res == 6
def define_finalizer_calls_malloc(cls):
class B(object):
pass
b = B()
b.nextid = 0
b.num_deleted = 0
class AAA(object):
def __init__(self):
self.id = b.nextid
b.nextid += 1
def __del__(self):
b.num_deleted += 1
C()
class C(AAA):
def __del__(self):
b.num_deleted += 1
def f(x, y):
a = AAA()
i = 0
while i < x:
i += 1
a = AAA()
llop.gc__collect(lltype.Void)
llop.gc__collect(lltype.Void)
return b.num_deleted
return f
def test_finalizer_calls_malloc(self):
run = self.runner("finalizer_calls_malloc")
res = run([5, 42]) #XXX pure lazyness here too
assert res == 12
def define_finalizer_resurrects(cls):
class B(object):
pass
b = B()
b.nextid = 0
b.num_deleted = 0
class A(object):
def __init__(self):
self.id = b.nextid
b.nextid += 1
def __del__(self):
b.num_deleted += 1
b.a = self
def f(x, y):
a = A()
i = 0
while i < x:
i += 1
a = A()
llop.gc__collect(lltype.Void)
llop.gc__collect(lltype.Void)
aid = b.a.id
b.a = None
# check that __del__ is not called again
llop.gc__collect(lltype.Void)
llop.gc__collect(lltype.Void)
return b.num_deleted * 10 + aid + 100 * (b.a is None)
return f
def test_finalizer_resurrects(self):
run = self.runner("finalizer_resurrects")
res = run([5, 42]) #XXX pure lazyness here too
assert 160 <= res <= 165
def define_custom_trace(cls):
#
S = lltype.GcStruct('S', ('x', llmemory.Address))
T = lltype.GcStruct('T', ('z', lltype.Signed))
offset_of_x = llmemory.offsetof(S, 'x')
def customtrace(gc, obj, callback, arg):
gc._trace_callback(callback, arg, obj + offset_of_x)
lambda_customtrace = lambda: customtrace
#
def setup():
rgc.register_custom_trace_hook(S, lambda_customtrace)
tx = lltype.malloc(T)
tx.z = 4243
s1 = lltype.malloc(S)
s1.x = llmemory.cast_ptr_to_adr(tx)
return s1
def f():
s1 = setup()
llop.gc__collect(lltype.Void)
return llmemory.cast_adr_to_ptr(s1.x, lltype.Ptr(T)).z
return f
def test_custom_trace(self):
run = self.runner("custom_trace")
res = run([])
assert res == 4243
def define_weakref(cls):
import weakref, gc
class A(object):
pass
def g():
a = A()
return weakref.ref(a)
def f():
a = A()
ref = weakref.ref(a)
result = ref() is a
ref = g()
llop.gc__collect(lltype.Void)
result = result and (ref() is None)
# check that a further collection is fine
llop.gc__collect(lltype.Void)
result = result and (ref() is None)
return result
return f
def test_weakref(self):
run = self.runner("weakref")
res = run([])
assert res
def define_weakref_to_object_with_finalizer(cls):
import weakref, gc
class A(object):
count = 0
a = A()
class B(object):
def __del__(self):
a.count += 1
def g():
b = B()
return weakref.ref(b)
def f():
ref = g()
llop.gc__collect(lltype.Void)
llop.gc__collect(lltype.Void)
result = a.count == 1 and (ref() is None)
return result
return f
def test_weakref_to_object_with_finalizer(self):
run = self.runner("weakref_to_object_with_finalizer")
res = run([])
assert res
def define_collect_during_collect(cls):
class B(object):
pass
b = B()
b.nextid = 1
b.num_deleted = 0
b.num_deleted_c = 0
class A(object):
def __init__(self):
self.id = b.nextid
b.nextid += 1
def __del__(self):
llop.gc__collect(lltype.Void)
b.num_deleted += 1
C()
C()
class C(A):
def __del__(self):
b.num_deleted += 1
b.num_deleted_c += 1
def f(x, y):
persistent_a1 = A()
persistent_a2 = A()
i = 0
while i < x:
i += 1
a = A()
persistent_a3 = A()
persistent_a4 = A()
llop.gc__collect(lltype.Void)
llop.gc__collect(lltype.Void)
b.bla = persistent_a1.id + persistent_a2.id + persistent_a3.id + persistent_a4.id
# NB print would create a static root!
llop.debug_print(lltype.Void, b.num_deleted_c)
return b.num_deleted
return f
def test_collect_during_collect(self):
run = self.runner("collect_during_collect")
# runs collect recursively 4 times
res = run([4, 42]) #XXX pure lazyness here too
assert res == 12
def define_collect_0(cls):
def concat(j, dummy):
lst = []
for i in range(j):
lst.append(str(i))
result = len("".join(lst))
if we_are_translated():
llop.gc__collect(lltype.Void, 0)
return result
return concat
def test_collect_0(self):
run = self.runner("collect_0")
res = run([100, 0])
assert res == len(''.join([str(x) for x in range(100)]))
def define_interior_ptrs(cls):
from rpython.rtyper.lltypesystem.lltype import Struct, GcStruct, GcArray
from rpython.rtyper.lltypesystem.lltype import Array, Signed, malloc
S1 = Struct("S1", ('x', Signed))
T1 = GcStruct("T1", ('s', S1))
def f1():
t = malloc(T1)
t.s.x = 1
return t.s.x
S2 = Struct("S2", ('x', Signed))
T2 = GcArray(S2)
def f2():
t = malloc(T2, 1)
t[0].x = 1
return t[0].x
S3 = Struct("S3", ('x', Signed))
T3 = GcStruct("T3", ('items', Array(S3)))
def f3():
t = malloc(T3, 1)
t.items[0].x = 1
return t.items[0].x
S4 = Struct("S4", ('x', Signed))
T4 = Struct("T4", ('s', S4))
U4 = GcArray(T4)
def f4():
u = malloc(U4, 1)
u[0].s.x = 1
return u[0].s.x
S5 = Struct("S5", ('x', Signed))
T5 = GcStruct("T5", ('items', Array(S5)))
def f5():
t = malloc(T5, 1)
return len(t.items)
T6 = GcStruct("T6", ('s', Array(Signed)))
def f6():
t = malloc(T6, 1)
t.s[0] = 1
return t.s[0]
def func():
return (f1() * 100000 +
f2() * 10000 +
f3() * 1000 +
f4() * 100 +
f5() * 10 +
f6())
assert func() == 111111
return func
def test_interior_ptrs(self):
run = self.runner("interior_ptrs")
res = run([])
assert res == 111111
def define_id(cls):
class A(object):
pass
a1 = A()
def func():
a2 = A()
a3 = A()
id1 = compute_unique_id(a1)
id2 = compute_unique_id(a2)
id3 = compute_unique_id(a3)
llop.gc__collect(lltype.Void)
error = 0
if id1 != compute_unique_id(a1): error += 1
if id2 != compute_unique_id(a2): error += 2
if id3 != compute_unique_id(a3): error += 4
return error
return func
def test_id(self):
run = self.runner("id")
res = run([])
assert res == 0
def define_can_move(cls):
TP = lltype.GcArray(lltype.Float)
def func():
return rgc.can_move(lltype.malloc(TP, 1))
return func
def test_can_move(self):
run = self.runner("can_move")
res = run([])
assert res == self.GC_CAN_MOVE
def define_shrink_array(cls):
from rpython.rtyper.lltypesystem.rstr import STR
def f():
ptr = lltype.malloc(STR, 3)
ptr.hash = 0x62
ptr.chars[0] = '0'
ptr.chars[1] = 'B'
ptr.chars[2] = 'C'
ptr2 = rgc.ll_shrink_array(ptr, 2)
return ((ptr == ptr2) +
ord(ptr2.chars[0]) +
(ord(ptr2.chars[1]) << 8) +
(len(ptr2.chars) << 16) +
(ptr2.hash << 24))
return f
def test_shrink_array(self):
run = self.runner("shrink_array")
if self.GC_CAN_SHRINK_ARRAY:
expected = 0x62024231
else:
expected = 0x62024230
assert run([]) == expected
def define_string_builder_over_allocation(cls):
import gc
def fn():
s = StringBuilder(4)
s.append("abcd")
s.append("defg")
s.append("rty")
s.append_multiple_char('y', 1000)
gc.collect()
s.append_multiple_char('y', 1000)
res = s.build()[1000]
gc.collect()
return ord(res)
return fn
def test_string_builder_over_allocation(self):
fn = self.runner("string_builder_over_allocation")
res = fn([])
assert res == ord('y')
class GenericMovingGCTests(GenericGCTests):
GC_CAN_MOVE = True
GC_CAN_TEST_ID = False
def define_many_ids(cls):
class A(object):
pass
def f():
from rpython.rtyper.lltypesystem import rffi
alist = [A() for i in range(50)]
idarray = lltype.malloc(rffi.SIGNEDP.TO, len(alist), flavor='raw')
# Compute the id of all the elements of the list. The goal is
# to not allocate memory, so that if the GC needs memory to
# remember the ids, it will trigger some collections itself
i = 0
while i < len(alist):
idarray[i] = compute_unique_id(alist[i])
i += 1
j = 0
while j < 2:
if j == 1: # allocate some stuff between the two iterations
[A() for i in range(20)]
i = 0
while i < len(alist):
assert idarray[i] == compute_unique_id(alist[i])
i += 1
j += 1
lltype.free(idarray, flavor='raw')
return 0
return f
def test_many_ids(self):
if not self.GC_CAN_TEST_ID:
py.test.skip("fails for bad reasons in lltype.py :-(")
run = self.runner("many_ids")
run([])
@classmethod
def ensure_layoutbuilder(cls, translator):
jit2gc = getattr(translator, '_jit2gc', None)
if jit2gc:
assert 'invoke_after_minor_collection' in jit2gc
return jit2gc['layoutbuilder']
marker = cls.marker
GCClass = cls.gcpolicy.transformerclass.GCClass
layoutbuilder = framework.TransformerLayoutBuilder(translator, GCClass)
layoutbuilder.delay_encoding()
def seeme():
marker[0] += 1
translator._jit2gc = {
'layoutbuilder': layoutbuilder,
'invoke_after_minor_collection': seeme,
}
return layoutbuilder
def define_do_malloc_operations(cls):
P = lltype.GcStruct('P', ('x', lltype.Signed))
def g():
r = lltype.malloc(P)
r.x = 1
p = llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder
p = lltype.cast_opaque_ptr(lltype.Ptr(P), p)
p.x = r.x
return p.x
def f():
i = 0
while i < 40:
g()
i += 1
return 0
if cls.gcname == 'incminimark':
marker = cls.marker
def cleanup():
assert marker[0] > 0
marker[0] = 0
else:
cleanup = None
def fix_graph_of_g(translator):
from rpython.translator.translator import graphof
from rpython.flowspace.model import Constant
from rpython.rtyper.lltypesystem import rffi
layoutbuilder = cls.ensure_layoutbuilder(translator)
type_id = layoutbuilder.get_type_id(P)
#
# now fix the do_malloc_fixedsize in the graph of g
graph = graphof(translator, g)
for op in graph.startblock.operations:
if op.opname == 'do_malloc_fixedsize':
op.args = [Constant(type_id, llgroup.HALFWORD),
Constant(llmemory.sizeof(P), lltype.Signed),
Constant(False, lltype.Bool), # has_finalizer
Constant(False, lltype.Bool), # is_finalizer_light
Constant(False, lltype.Bool)] # contains_weakptr
break
else:
assert 0, "oups, not found"
return f, cleanup, fix_graph_of_g
def test_do_malloc_operations(self):
run = self.runner("do_malloc_operations")
run([])
def define_do_malloc_operations_in_call(cls):
P = lltype.GcStruct('P', ('x', lltype.Signed))
def g():
llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder
def f():
q = lltype.malloc(P)
q.x = 1
i = 0
while i < 40:
g()
i += q.x
return 0
def fix_graph_of_g(translator):
from rpython.translator.translator import graphof
from rpython.flowspace.model import Constant
from rpython.rtyper.lltypesystem import rffi
layoutbuilder = cls.ensure_layoutbuilder(translator)
type_id = layoutbuilder.get_type_id(P)
#
# now fix the do_malloc_fixedsize in the graph of g
graph = graphof(translator, g)
for op in graph.startblock.operations:
if op.opname == 'do_malloc_fixedsize':
op.args = [Constant(type_id, llgroup.HALFWORD),
Constant(llmemory.sizeof(P), lltype.Signed),
Constant(False, lltype.Bool), # has_finalizer
Constant(False, lltype.Bool), # is_finalizer_light
Constant(False, lltype.Bool)] # contains_weakptr
break
else:
assert 0, "oups, not found"
return f, None, fix_graph_of_g
def test_do_malloc_operations_in_call(self):
run = self.runner("do_malloc_operations_in_call")
run([])
def define_gc_heap_stats(cls):
S = lltype.GcStruct('S', ('x', lltype.Signed))
l1 = []
l2 = []
l3 = []
l4 = []
def f():
for i in range(10):
s = lltype.malloc(S)
l1.append(s)
l2.append(s)
if i < 3:
l3.append(s)
l4.append(s)
# We cheat here and only read the table which we later on
# process ourselves, otherwise this test takes ages
llop.gc__collect(lltype.Void)
tb = rgc._heap_stats()
a = 0
nr = 0
b = 0
c = 0
d = 0
e = 0
for i in range(len(tb)):
if tb[i].count == 10:
a += 1
nr = i
if tb[i].count > 50:
d += 1
for i in range(len(tb)):
if tb[i].count == 4:
b += 1
c += tb[i].links[nr]
e += tb[i].size
return d * 1000 + c * 100 + b * 10 + a
return f
def test_gc_heap_stats(self):
py.test.skip("this test makes the following test crash. Investigate.")
run = self.runner("gc_heap_stats")
res = run([])
assert res % 10000 == 2611
totsize = (res / 10000)
size_of_int = rffi.sizeof(lltype.Signed)
assert (totsize - 26 * size_of_int) % 4 == 0
# ^^^ a crude assumption that totsize - varsize would be dividable by 4
# (and give fixedsize)
def define_writebarrier_before_copy(cls):
S = lltype.GcStruct('S', ('x', lltype.Char))
TP = lltype.GcArray(lltype.Ptr(S))
def fn():
l = lltype.malloc(TP, 100)
l2 = lltype.malloc(TP, 100)
for i in range(100):
l[i] = lltype.malloc(S)
rgc.ll_arraycopy(l, l2, 50, 0, 50)
# force nursery collect
x = []
for i in range(20):
x.append((1, lltype.malloc(S)))
for i in range(50):
assert l2[i] == l[50 + i]
return 0
return fn
def test_writebarrier_before_copy(self):
run = self.runner("writebarrier_before_copy")
run([])
# ________________________________________________________________
class TestSemiSpaceGC(GenericMovingGCTests):
gcname = "semispace"
GC_CAN_SHRINK_ARRAY = True
class gcpolicy(gc.BasicFrameworkGcPolicy):
class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):
from rpython.memory.gc.semispace import SemiSpaceGC as GCClass
GC_PARAMS = {'space_size': 512*WORD,
'translated_to_c': False}
root_stack_depth = 200
class TestGenerationGC(GenericMovingGCTests):
gcname = "generation"
GC_CAN_SHRINK_ARRAY = True
class gcpolicy(gc.BasicFrameworkGcPolicy):
class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):
from rpython.memory.gc.generation import GenerationGC as \
GCClass
GC_PARAMS = {'space_size': 512*WORD,
'nursery_size': 32*WORD,
'translated_to_c': False}
root_stack_depth = 200
def define_weakref_across_minor_collection(cls):
import weakref
class A:
pass
def f():
x = 20 # for GenerationGC, enough for a minor collection
a = A()
a.foo = x
ref = weakref.ref(a)
all = [None] * x
i = 0
while i < x:
all[i] = [i] * i
i += 1
assert ref() is a
llop.gc__collect(lltype.Void)
assert ref() is a
return a.foo + len(all)
return f
def test_weakref_across_minor_collection(self):
run = self.runner("weakref_across_minor_collection")
res = run([])
assert res == 20 + 20
def define_nongc_static_root_minor_collect(cls):
T1 = lltype.GcStruct("C", ('x', lltype.Signed))
T2 = lltype.Struct("C", ('p', lltype.Ptr(T1)))
static = lltype.malloc(T2, immortal=True)
def f():
t1 = lltype.malloc(T1)
t1.x = 42
static.p = t1
x = 20
all = [None] * x
i = 0
while i < x: # enough to cause a minor collect
all[i] = [i] * i
i += 1
i = static.p.x
llop.gc__collect(lltype.Void)
return static.p.x + i
def cleanup():
static.p = lltype.nullptr(T1)
return f, cleanup, None
def test_nongc_static_root_minor_collect(self):
run = self.runner("nongc_static_root_minor_collect")
res = run([])
assert res == 84
def define_static_root_minor_collect(cls):
class A:
pass
class B:
pass
static = A()
static.p = None
def f():
t1 = B()
t1.x = 42
static.p = t1
x = 20
all = [None] * x
i = 0
while i < x: # enough to cause a minor collect
all[i] = [i] * i
i += 1
i = static.p.x
llop.gc__collect(lltype.Void)
return static.p.x + i
def cleanup():
static.p = None
return f, cleanup, None
def test_static_root_minor_collect(self):
run = self.runner("static_root_minor_collect")
res = run([])
assert res == 84
def define_many_weakrefs(cls):
# test for the case where allocating the weakref itself triggers
# a collection
import weakref
class A:
pass
def f():
a = A()
i = 0
while i < 17:
ref = weakref.ref(a)
assert ref() is a
i += 1
return 0
return f
def test_many_weakrefs(self):
run = self.runner("many_weakrefs")
run([])
def define_immutable_to_old_promotion(cls):
T_CHILD = lltype.Ptr(lltype.GcStruct('Child', ('field', lltype.Signed)))
T_PARENT = lltype.Ptr(lltype.GcStruct('Parent', ('sub', T_CHILD)))
child = lltype.malloc(T_CHILD.TO)
child2 = lltype.malloc(T_CHILD.TO)
parent = lltype.malloc(T_PARENT.TO)
parent2 = lltype.malloc(T_PARENT.TO)
parent.sub = child
child.field = 3
parent2.sub = child2
child2.field = 8
T_ALL = lltype.Ptr(lltype.GcArray(T_PARENT))
all = lltype.malloc(T_ALL.TO, 2)
all[0] = parent
all[1] = parent2
def f(x, y):
res = all[x]
#all[x] = lltype.nullptr(T_PARENT.TO)
return res.sub.field
return f
def test_immutable_to_old_promotion(self):
run, transformer = self.runner("immutable_to_old_promotion", transformer=True)
run([1, 4])
if not transformer.GCClass.prebuilt_gc_objects_are_static_roots:
assert len(transformer.layoutbuilder.addresses_of_static_ptrs) == 0
else:
assert len(transformer.layoutbuilder.addresses_of_static_ptrs) >= 4
# NB. Remember that the number above does not count
# the number of prebuilt GC objects, but the number of locations
# within prebuilt GC objects that are of type Ptr(Gc).
# At the moment we get additional_roots_sources == 6:
# * all[0]
# * all[1]
# * parent.sub
# * parent2.sub
# * the GcArray pointer from gc.wr_to_objects_with_id
# * the GcArray pointer from gc.object_id_dict.
def define_adr_of_nursery(cls):
class A(object):
pass
def f():
# we need at least 1 obj to allocate a nursery
a = A()
nf_a = llop.gc_adr_of_nursery_free(llmemory.Address)
nt_a = llop.gc_adr_of_nursery_top(llmemory.Address)
nf0 = nf_a.address[0]
nt0 = nt_a.address[0]
a0 = A()
a1 = A()
nf1 = nf_a.address[0]
nt1 = nt_a.address[0]
assert nf1 > nf0
assert nt1 > nf1
assert nt1 == nt0
return 0
return f
def test_adr_of_nursery(self):
run = self.runner("adr_of_nursery")
res = run([])
class TestGenerationalNoFullCollectGC(GCTest):
# test that nursery is doing its job and that no full collection
# is needed when most allocated objects die quickly
gcname = "generation"
class gcpolicy(gc.BasicFrameworkGcPolicy):
class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):
from rpython.memory.gc.generation import GenerationGC
class GCClass(GenerationGC):
__ready = False
def setup(self):
from rpython.memory.gc.generation import GenerationGC
GenerationGC.setup(self)
self.__ready = True
def semispace_collect(self, size_changing=False):
ll_assert(not self.__ready,
"no full collect should occur in this test")
def _teardown(self):
self.__ready = False # collecting here is expected
GenerationGC._teardown(self)
GC_PARAMS = {'space_size': 512*WORD,
'nursery_size': 128*WORD,
'translated_to_c': False}
root_stack_depth = 200
def define_working_nursery(cls):
def f():
total = 0
i = 0
while i < 40:
lst = []
j = 0
while j < 5:
lst.append(i*j)
j += 1
total += len(lst)
i += 1
return total
return f
def test_working_nursery(self):
run = self.runner("working_nursery")
res = run([])
assert res == 40 * 5
class TestHybridGC(TestGenerationGC):
gcname = "hybrid"
class gcpolicy(gc.BasicFrameworkGcPolicy):
class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):
from rpython.memory.gc.hybrid import HybridGC as GCClass
GC_PARAMS = {'space_size': 512*WORD,
'nursery_size': 32*WORD,
'large_object': 8*WORD,
'translated_to_c': False}
root_stack_depth = 200
def define_ref_from_rawmalloced_to_regular(cls):
import gc
S = lltype.GcStruct('S', ('x', lltype.Signed))
A = lltype.GcStruct('A', ('p', lltype.Ptr(S)),
('a', lltype.Array(lltype.Char)))
def setup(j):
p = lltype.malloc(S)
p.x = j*2
lst = lltype.malloc(A, j)
# the following line generates a write_barrier call at the moment,
# which is important because the 'lst' can be allocated directly
# in generation 2. This can only occur with varsized mallocs.
lst.p = p
return lst
def f(i, j):
lst = setup(j)
gc.collect()
return lst.p.x
return f
def test_ref_from_rawmalloced_to_regular(self):
run = self.runner("ref_from_rawmalloced_to_regular")
res = run([100, 100])
assert res == 200
def define_write_barrier_direct(cls):
from rpython.rlib import rgc
S = lltype.GcForwardReference()
S.become(lltype.GcStruct('S',
('x', lltype.Signed),
('prev', lltype.Ptr(S)),
('next', lltype.Ptr(S))))
s0 = lltype.malloc(S, immortal=True)
def f():
s = lltype.malloc(S)
s.x = 42
llop.bare_setfield(lltype.Void, s0, void('next'), s)
llop.gc_writebarrier(lltype.Void, llmemory.cast_ptr_to_adr(s0))
rgc.collect(0)
return s0.next.x
def cleanup():
s0.next = lltype.nullptr(S)
return f, cleanup, None
def test_write_barrier_direct(self):
run = self.runner("write_barrier_direct")
res = run([])
assert res == 42
class TestMiniMarkGC(TestHybridGC):
gcname = "minimark"
GC_CAN_TEST_ID = True
class gcpolicy(gc.BasicFrameworkGcPolicy):
class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):
from rpython.memory.gc.minimark import MiniMarkGC as GCClass
GC_PARAMS = {'nursery_size': 32*WORD,
'page_size': 16*WORD,
'arena_size': 64*WORD,
'small_request_threshold': 5*WORD,
'large_object': 8*WORD,
'card_page_indices': 4,
'translated_to_c': False,
}
root_stack_depth = 200
def define_no_clean_setarrayitems(cls):
# The optimization find_clean_setarrayitems() in
# gctransformer/framework.py does not work with card marking.
# Check that it is turned off.
S = lltype.GcStruct('S', ('x', lltype.Signed))
A = lltype.GcArray(lltype.Ptr(S))
def sub(lst):
lst[15] = lltype.malloc(S) # 'lst' is set the single mark "12-15"
lst[15].x = 123
lst[0] = lst[15] # that would be a "clean_setarrayitem"
def f():
lst = lltype.malloc(A, 16) # 16 > 10
rgc.collect()
sub(lst)
null = lltype.nullptr(S)
lst[15] = null # clear, so that A() is only visible via lst[0]
rgc.collect() # -> crash
return lst[0].x
return f
def test_no_clean_setarrayitems(self):
run = self.runner("no_clean_setarrayitems")
res = run([])
assert res == 123
def define_nursery_hash_base(cls):
class A:
pass
def fn():
objects = []
hashes = []
for i in range(200):
rgc.collect(0) # nursery-only collection, if possible
obj = A()
objects.append(obj)
hashes.append(compute_identity_hash(obj))
unique = {}
for i in range(len(objects)):
assert compute_identity_hash(objects[i]) == hashes[i]
unique[hashes[i]] = None
return len(unique)
return fn
def test_nursery_hash_base(self):
res = self.runner('nursery_hash_base')
assert res([]) >= 195
def define_instantiate_nonmovable(cls):
from rpython.rlib import objectmodel
from rpython.rtyper import annlowlevel
class A:
pass
def fn():
a1 = A()
a = objectmodel.instantiate(A, nonmovable=True)
a.next = a1 # 'a' is known young here, so no write barrier emitted
res = rgc.can_move(annlowlevel.cast_instance_to_base_ptr(a))
rgc.collect()
objectmodel.keepalive_until_here(a)
return res
return fn
def test_instantiate_nonmovable(self):
res = self.runner('instantiate_nonmovable')
assert res([]) == 0
class TestIncrementalMiniMarkGC(TestMiniMarkGC):
gcname = "incminimark"
class gcpolicy(gc.BasicFrameworkGcPolicy):
class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):
from rpython.memory.gc.incminimark import IncrementalMiniMarkGC \
as GCClass
GC_PARAMS = {'nursery_size': 32*WORD,
'page_size': 16*WORD,
'arena_size': 64*WORD,
'small_request_threshold': 5*WORD,
'large_object': 8*WORD,
'card_page_indices': 4,
'translated_to_c': False,
}
root_stack_depth = 200
def define_malloc_array_of_gcptr(self):
S = lltype.GcStruct('S', ('x', lltype.Signed))
A = lltype.GcArray(lltype.Ptr(S))
def f():
lst = lltype.malloc(A, 5)
return (lst[0] == lltype.nullptr(S)
and lst[1] == lltype.nullptr(S)
and lst[2] == lltype.nullptr(S)
and lst[3] == lltype.nullptr(S)
and lst[4] == lltype.nullptr(S))
return f
def test_malloc_array_of_gcptr(self):
run = self.runner('malloc_array_of_gcptr')
res = run([])
assert res
def define_malloc_struct_of_gcptr(cls):
S1 = lltype.GcStruct('S', ('x', lltype.Signed))
S = lltype.GcStruct('S',
('x', lltype.Signed),
('filed1', lltype.Ptr(S1)),
('filed2', lltype.Ptr(S1)))
s0 = lltype.malloc(S)
def f():
return (s0.filed1 == lltype.nullptr(S1) and s0.filed2 == lltype.nullptr(S1))
return f
def test_malloc_struct_of_gcptr(self):
run = self.runner("malloc_struct_of_gcptr")
res = run([])
assert res
# ________________________________________________________________
# tagged pointers
class TaggedPointerGCTests(GCTest):
taggedpointers = True
def define_tagged_simple(cls):
class Unrelated(object):
pass
u = Unrelated()
u.x = UnboxedObject(47)
def fn(n):
rgc.collect() # check that a prebuilt tagged pointer doesn't explode
if n > 0:
x = BoxedObject(n)
else:
x = UnboxedObject(n)
u.x = x # invoke write barrier
rgc.collect()
return x.meth(100)
def func():
return fn(1000) + fn(-1000)
assert func() == 205
return func
def test_tagged_simple(self):
func = self.runner("tagged_simple")
res = func([])
assert res == 205
def define_tagged_prebuilt(cls):
class F:
pass
f = F()
f.l = [UnboxedObject(10)]
def fn(n):
if n > 0:
x = BoxedObject(n)
else:
x = UnboxedObject(n)
f.l.append(x)
rgc.collect()
return f.l[-1].meth(100)
def func():
return fn(1000) ^ fn(-1000)
assert func() == -1999
return func
def test_tagged_prebuilt(self):
func = self.runner("tagged_prebuilt")
res = func([])
assert res == -1999
def define_gettypeid(cls):
class A(object):
pass
def fn():
a = A()
return rgc.get_typeid(a)
return fn
def test_gettypeid(self):
func = self.runner("gettypeid")
res = func([])
print res
from rpython.rlib.objectmodel import UnboxedValue
class TaggedBase(object):
__slots__ = ()
def meth(self, x):
raise NotImplementedError
class BoxedObject(TaggedBase):
attrvalue = 66
def __init__(self, normalint):
self.normalint = normalint
def meth(self, x):
return self.normalint + x + 2
class UnboxedObject(TaggedBase, UnboxedValue):
__slots__ = 'smallint'
def meth(self, x):
return self.smallint + x + 3
class TestHybridTaggedPointerGC(TaggedPointerGCTests):
gcname = "hybrid"
class gcpolicy(gc.BasicFrameworkGcPolicy):
class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):
from rpython.memory.gc.generation import GenerationGC as \
GCClass
GC_PARAMS = {'space_size': 512*WORD,
'nursery_size': 32*WORD,
'translated_to_c': False}
root_stack_depth = 200
def test_gettypeid(self):
py.test.skip("fails for obscure reasons")
| 1.8125 | 2 |
build/lib/rigidregistration/__init__.py | kem-group/rigidRegistration | 3 | 2277 | from . import utils
from . import display
from . import save
from . import FFTW
from . import stackregistration
__version__="0.2.1" | 1.085938 | 1 |
torchmetrics/retrieval/retrieval_fallout.py | rudaoshi/metrics | 0 | 2278 | # Copyright The PyTorch Lightning team.
#
# 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 typing import Any, Callable, Optional
import pangu.core.backend as B
from pangu.core.backend import Tensor, tensor
from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out
from torchmetrics.retrieval.retrieval_metric import RetrievalMetric
from torchmetrics.utilities.data import get_group_indexes
class RetrievalFallOut(RetrievalMetric):
"""Computes `Fall-out`_.
Works with binary target data. Accepts float predictions from a model output.
Forward accepts:
- ``preds`` (float tensor): ``(N, ...)``
- ``target`` (long or bool tensor): ``(N, ...)``
- ``indexes`` (long tensor): ``(N, ...)``
``indexes``, ``preds`` and ``target`` must have the same dimension.
``indexes`` indicate to which query a prediction belongs.
Predictions will be first grouped by ``indexes`` and then `Fall-out` will be computed as the mean
of the `Fall-out` over each query.
Args:
empty_target_action:
Specify what to do with queries that do not have at least a negative ``target``. Choose from:
- ``'neg'``: those queries count as ``0.0`` (default)
- ``'pos'``: those queries count as ``1.0``
- ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned
- ``'error'``: raise a ``ValueError``
k: consider only the top k elements for each query (default: None, which considers them all)
compute_on_step:
Forward only calls ``update()`` and return None if this is set to False. default: True
dist_sync_on_step:
Synchronize metric state across processes at each ``forward()``
before returning the value at the step. default: False
process_group:
Specify the process group on which synchronization is called. default: None (which selects
the entire world)
dist_sync_fn:
Callback that performs the allgather operation on the metric state. When `None`, DDP
will be used to perform the allgather. default: None
Raises:
ValueError:
If ``k`` parameter is not `None` or an integer larger than 0
Example:
>>> from torchmetrics import RetrievalFallOut
>>> indexes = tensor([0, 0, 0, 1, 1, 1, 1])
>>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2])
>>> target = tensor([False, False, True, False, True, False, True])
>>> fo = RetrievalFallOut(k=2)
>>> fo(preds, target, indexes=indexes)
tensor(0.5000)
"""
higher_is_better = False
def __init__(
self,
empty_target_action: str = "pos",
k: int = None,
compute_on_step: bool = True,
dist_sync_on_step: bool = False,
process_group: Optional[Any] = None,
dist_sync_fn: Callable = None,
) -> None:
super().__init__(
empty_target_action=empty_target_action,
compute_on_step=compute_on_step,
dist_sync_on_step=dist_sync_on_step,
process_group=process_group,
dist_sync_fn=dist_sync_fn,
)
if (k is not None) and not (isinstance(k, int) and k > 0):
raise ValueError("`k` has to be a positive integer or None")
self.k = k
def compute(self) -> Tensor:
"""First concat state `indexes`, `preds` and `target` since they were stored as lists.
After that, compute list of groups that will help in keeping together predictions about the same query. Finally,
for each group compute the `_metric` if the number of negative targets is at least 1, otherwise behave as
specified by `self.empty_target_action`.
"""
indexes = B.cat(self.indexes, dim=0)
preds = B.cat(self.preds, dim=0)
target = B.cat(self.target, dim=0)
res = []
groups = get_group_indexes(indexes)
for group in groups:
mini_preds = preds[group]
mini_target = target[group]
if not (1 - mini_target).sum():
if self.empty_target_action == "error":
raise ValueError("`compute` method was provided with a query with no negative target.")
if self.empty_target_action == "pos":
res.append(tensor(1.0))
elif self.empty_target_action == "neg":
res.append(tensor(0.0))
else:
# ensure list containt only float tensors
res.append(self._metric(mini_preds, mini_target))
return B.stack([x.to(preds) for x in res]).mean() if res else tensor(0.0).to(preds)
def _metric(self, preds: Tensor, target: Tensor) -> Tensor:
return retrieval_fall_out(preds, target, k=self.k)
| 2.015625 | 2 |
pydlm/tests/base/testKalmanFilter.py | onnheimm/pydlm | 423 | 2279 | <gh_stars>100-1000
import numpy as np
import unittest
from pydlm.modeler.trends import trend
from pydlm.modeler.seasonality import seasonality
from pydlm.modeler.builder import builder
from pydlm.base.kalmanFilter import kalmanFilter
class testKalmanFilter(unittest.TestCase):
def setUp(self):
self.kf1 = kalmanFilter(discount=[1])
self.kf0 = kalmanFilter(discount=[1e-10])
self.kf11 = kalmanFilter(discount=[1, 1])
self.trend0 = trend(degree=0, discount=1, w=1.0)
self.trend0_90 = trend(degree=0, discount=0.9, w=1.0)
self.trend0_98 = trend(degree=0, discount=0.98, w=1.0, name='a')
self.trend1 = trend(degree=1, discount=1, w=1.0)
def testForwardFilter(self):
dlm = builder()
dlm.add(self.trend0)
dlm.initialize()
self.kf1.predict(dlm.model)
self.assertAlmostEqual(dlm.model.prediction.obs, 0)
# the prior on the mean is zero, but observe 1, with
# discount = 1, one should expect the filterd mean to be 0.5
self.kf1.forwardFilter(dlm.model, 1)
self.assertAlmostEqual(dlm.model.obs, 0.5)
self.assertAlmostEqual(dlm.model.prediction.obs, 0)
self.assertAlmostEqual(dlm.model.sysVar, 0.375)
self.kf1.predict(dlm.model)
self.assertAlmostEqual(dlm.model.obs, 0.5)
self.assertAlmostEqual(dlm.model.prediction.obs, 0.5)
dlm.initialize()
self.kf0.predict(dlm.model)
self.assertAlmostEqual(dlm.model.prediction.obs, 0)
# the prior on the mean is zero, but observe 1, with discount = 0
# one should expect the filtered mean close to 1
self.kf0.forwardFilter(dlm.model, 1)
self.assertAlmostEqual(dlm.model.obs[0, 0], 1)
self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 0)
self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.5)
self.kf0.predict(dlm.model)
self.assertAlmostEqual(dlm.model.obs[0, 0], 1)
self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 1)
def testForwardFilterMultiDim(self):
dlm = builder()
dlm.add(seasonality(period=2, discount=1, w=1.0))
dlm.initialize()
self.kf11.forwardFilter(dlm.model, 1)
self.assertAlmostEqual(dlm.model.state[0][0, 0], 0.33333333333)
self.assertAlmostEqual(dlm.model.state[1][0, 0], -0.33333333333)
self.kf11.forwardFilter(dlm.model, -1)
self.assertAlmostEqual(dlm.model.state[0][0, 0], -0.5)
self.assertAlmostEqual(dlm.model.state[1][0, 0], 0.5)
def testBackwardSmoother(self):
dlm = builder()
dlm.add(self.trend0)
dlm.initialize()
# with mean being 0 and observe 1 and 0 consectively, one shall
# expect the smoothed mean at 1 will be 1/3, for discount = 1
self.kf1.forwardFilter(dlm.model, 1)
self.kf1.forwardFilter(dlm.model, 0)
self.kf1.backwardSmoother(dlm.model, \
np.matrix([[0.5]]), \
np.matrix([[0.375]]))
self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0/3)
self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.18518519)
# second order trend with discount = 1. The smoothed result should be
# equal to a direct fit on the three data points, 0, 1, -1. Thus, the
# smoothed observation should be 0.0
def testBackwardSmootherMultiDim(self):
dlm = builder()
dlm.add(self.trend1)
dlm.initialize()
self.kf11.forwardFilter(dlm.model, 1)
state1 = dlm.model.state
cov1 = dlm.model.sysVar
self.kf11.forwardFilter(dlm.model, -1)
self.kf11.backwardSmoother(dlm.model, \
rawState = state1, \
rawSysVar = cov1)
self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0)
def testMissingData(self):
dlm = builder()
dlm.add(self.trend0)
dlm.initialize()
self.kf0.forwardFilter(dlm.model, 1)
self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0)
self.assertAlmostEqual(dlm.model.obsVar[0, 0], 1.0)
self.kf0.forwardFilter(dlm.model, None)
self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0)
self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5)
self.kf0.forwardFilter(dlm.model, None)
self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0)
self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5)
self.kf0.forwardFilter(dlm.model, 0)
self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0)
def testMissingEvaluation(self):
dlm = builder()
dlm.add(self.trend0)
dlm.initialize()
dlm.model.evaluation = np.matrix([[None]])
self.kf1.forwardFilter(dlm.model, 1.0, dealWithMissingEvaluation = True)
self.assertAlmostEqual(dlm.model.obs, 0.0)
self.assertAlmostEqual(dlm.model.transition, 1.0)
def testEvolveMode(self):
dlm = builder()
dlm.add(self.trend0_90)
dlm.add(self.trend0_98)
dlm.initialize()
kf2 = kalmanFilter(discount=[0.9, 0.98],
updateInnovation='component',
index=dlm.componentIndex)
kf2.forwardFilter(dlm.model, 1.0)
self.assertAlmostEqual(dlm.model.innovation[0, 1], 0.0)
self.assertAlmostEqual(dlm.model.innovation[1, 0], 0.0)
if __name__ == '__main__':
unittest.main()
| 2.53125 | 3 |
change_threshold_migration.py | arcapix/gpfsapi-examples | 10 | 2280 | from arcapix.fs.gpfs.policy import PlacementPolicy
from arcapix.fs.gpfs.rule import MigrateRule
# load placement policy for mmfs1
policy = PlacementPolicy('mmfs1')
# create a new migrate rule for 'sata1'
r = MigrateRule(source='sata1', threshold=(90, 50))
# add rule to start of the policy
policy.rules.insert(r, 0)
# save changes
policy.save()
| 1.484375 | 1 |
1/puzzle1.py | tjol/advent-of-code-2021 | 1 | 2281 | <reponame>tjol/advent-of-code-2021<gh_stars>1-10
#!/usr/bin/env python3
import sys
depths = list(map(int, sys.stdin))
increased = [a > b for (a, b) in zip(depths[1:], depths[:-1])]
print(sum(increased))
| 3.0625 | 3 |
project/app/paste/controllers.py | An0nYm0u5101/Pastebin | 1 | 2282 | from flask import Blueprint, request, render_template, \
flash, g, session, redirect, url_for, jsonify
from app import db, requires_auth
from flask_cors import CORS
from .models import Paste
import uuid
from datetime import datetime
from app.user.models import User
from pygments import highlight
from pygments.lexers import get_lexer_by_name, guess_lexer
from pygments.formatters import HtmlFormatter
from functools import wraps
from datetime import datetime
from dateutil import parser
def requires_admin(f):
@wraps(f)
def decorated(*args, **kwargs):
if 'user_id' not in session:
return jsonify(message="Unauthorized", success=False), 401
user_id = session['user_id']
user = User.query.filter(User.id == user_id).first()
if(user.user_type != 2):
return jsonify(message="Unauthorized", success=False), 401
return f(*args, **kwargs)
return decorated
mod_paste = Blueprint('paste', __name__)
CORS(mod_paste)
def is_active(paste):
return parser.parse(paste.expire_time) > datetime.now()
@mod_paste.route('/create_paste', methods=['GET'])
@requires_auth
def create_form():
curr_id = session['user_id']
user = User.query.filter(User.id == curr_id).first()
return render_template('user.html', username=user.username)
@mod_paste.route('/create_paste', methods=['POST'])
def create_paste():
title = request.form['title']
text = request.form['text']
paste_type = request.form['type']
if 'user_id' in session:
user_id = session['user_id']
else:
user = User.query.filter(User.username == 'Guest').first()
user_id = user.id
lang = request.form['lang']
time_form = request.form['time']
expire_time = str(time_form)
add_time = str(datetime.now())
url = str(uuid.uuid4())
report_count = 0
try:
paste = Paste(title, text, lang, add_time,
expire_time, user_id, url, report_count, paste_type)
user = User.query.filter(User.id == user_id).first()
x = user.paste_count
user.paste_count = x + 1
db.session.add(paste)
db.session.commit()
# jsonify(success=True, paste=paste.to_dict())
return jsonify({'url': url}), 200
except:
return jsonify({'error': 'Error while creating Paste, Please check if all fields are filled'}), 400
@mod_paste.route('/paste', methods=['GET'])
@requires_auth
def get_all_pastes():
# user_id = session['user_id']
# pastes = paste.query.filter(paste.user_id == user_id).all()
if 'user_id' in session:
curr_id = session['user_id']
user = User.query.filter(curr_id == User.id).first()
if user.user_type == 2:
return render_template('admin_mypaste.html')
return render_template("mypaste.html")
else:
return jsonify({'error': 'Please Login to Continue'}), 400
# return jsonify(success=True, pastes=[paste.to_dict() for paste in
# pastes])
@mod_paste.route('/api/paste', methods=['POST'])
@requires_auth
def get_all_pastes_object():
user_id = session['user_id']
user = User.query.filter(user_id == User.id).first()
pastes = Paste.query.filter(Paste.user_id == user_id).all()
active = []
for paste in pastes:
if is_active(paste):
active.append(paste.to_dict())
else:
userid_to_red = paste.user_id
user_to_red = User.query.filter(userid_to_red == User.id)
user_to_red.paste_count = user_to_red.paste_count - 1
db.session.delete(paste)
db.session.commit()
return jsonify({'paste_list': active, 'username': user.username}), 200
@mod_paste.route('/<url>/embed', methods=['GET'])
def embed_code_form(url):
paste = Paste.query.filter(Paste.url == url).first()
if is_active(paste):
return render_template('embed.html', paste_text=paste.text, paste_link="http://127.0.0.1:8080/" + url)
else:
userid_to_red = paste.user_id
user_to_red = User.query.filter(User.id == userid_to_red).first()
user_to_red.paste_count = user_to_red.paste_count - 1
db.session.delete(paste)
db.session.commit()
return render_template("index.html"), 404
# @mod_paste.route('/<url>/embed', methods=['POST'])
# def embed_code(url):
# paste = Paste.query.filter(Paste.url == url).first()
# return jsonify(paste_text = paste.text,paste_link = url)
@mod_paste.route('/<url>/embed/output', methods=['GET'])
def embed_code_disp(url):
paste = Paste.query.filter(Paste.url == url).first()
if is_active(paste):
return render_template('embed_output.html')
else:
userid_to_red = paste.user_id
user_to_red = User.query.filter(User.id == userid_to_red).first()
user_to_red.paste_count = user_to_red.paste_count - 1
db.session.delete(paste)
db.session.commit()
return render_template("index.html"), 404
# @mod_paste.route('/paste', methods=['GET'])
# @requires_auth
# def get_all_pastes():
# # user_id = session['user_id']
# # pastes = paste.query.filter(paste.user_id == user_id).all()
# curr_id = session['user_id']
# user = User.query.filter(User.id == curr_id).first()
# paste_list = Paste.query.filter(curr_id == Paste.user_id).all()
# url_pre = "/"
# for paste in paste_list:
# paste.url = url_pre + paste.url
# if user.user_type == 1:
# return render_template('mypaste.html', paste_list=paste_list)
# return render_template('admin_mypaste.html',paste_list = paste_list)
# # return jsonify(success=True, pastes=[paste.to_dict() for paste in
# # pastes])
#
#
# @mod_paste.route('/api/paste', methods=['POST'])
# @requires_auth
# def get_all_pastes_object():
# user_id = session['user_id']
# user = User.query.filter(user_id == User.id).first()
# pastes = Paste.query.filter(Paste.user_id == user_id).all()
# active = []
# for paste in pastes:
# temp_paste = {}
# if paste.is_active():
# temp_paste['title'] = paste.title
# temp_paste['add_time']=paste.add_time
# temp_paste['expire_time']=paste.expire_time
# temp_paste['lang']=paste.lang
# temp_paste['url']=paste.url
# active.append(temp_paste)
#
# return jsonify({'paste_list':active,'username':user.username}),200
# @mod_paste.route('/paste/<id>', methods=['GET'])
# @requires_auth
# def get_paste(id):
# user_id = session['user_id']
# paste = paste.query.filter(
# Paste.id == id, Paste.user_id == user_id).first()
# if paste is None:
# return render_template("index.html"),4044
# else:
# return jsonify(success=True, paste=paste.to_dict())
# @mod_paste.route('/paste/<id>', methods=['POST'])
# @requires_auth
# def edit_paste(id):
# user_id = session['user_id']
# paste = Paste.query.filter(
# Paste.id == id, Paste.user_id == user_id).first()
# if paste is None:
# return render_template("index.html"),4044
# else:
# paste.title = request.form['title']
# paste.text = request.form['text']
# paste.color = request.form['color']
# paste.lang = request.form['lang']
# db.session.commit()
# return jsonify(success=True)
@mod_paste.route('/<url>/delete', methods=['POST'])
@requires_auth
def delete_paste(url):
user_id = session['user_id']
# print(user_id)
paste = Paste.query.filter(Paste.url == url).first()
user = User.query.filter(User.id == user_id).first()
if paste is None:
return render_template("index.html"), 404
if is_active(paste):
if paste.user_id == user_id or user.user_type == 2:
userid_to_red = paste.user_id
user_to_red = User.query.filter(User.id == userid_to_red).first()
user_to_red.paste_count = user_to_red.paste_count - 1
db.session.delete(paste)
db.session.commit()
return jsonify(success=True, user_type=user.user_type), 200
else:
return jsonify(success=False), 400
else:
userid_to_red = paste.user_id
user_to_red = User.query.filter(User.id == userid_to_red).first()
user_to_red.paste_count = user_to_red.paste_count - 1
db.session.delete(paste)
db.session.commit()
return render_template("index.html"), 404
# @mod_paste.route('/<url>', methods=['GET'])
# def display_paste(url):
# paste = Paste.query.filter(Paste.url == url).first()
# style = HtmlFormatter().get_style_defs('.highlight')
# lexer = get_lexer_by_name(paste.lang)
# formatter = HtmlFormatter(linenos=True, cssclass="highlight")
# result = highlight(paste.text, lexer, formatter)
# return render_template("view_paste.html", paste_title=paste.title,
# paste_lang=paste.lang, highlight_style=style,
@mod_paste.route('/<url>', methods=['GET'])
# paste_text=result,paste_rawdata = paste.text)
def display_paste(url):
paste = Paste.query.filter(Paste.url == url).first()
if Paste.query.filter(Paste.url == url).first() != None:
if is_active(paste):
if 'user_id' in session:
if(paste.paste_type == "1" and session['user_id'] != paste.user_id):
return render_template("index.html"), 200
user_id = session['user_id']
user = User.query.filter(User.id == user_id).first()
if user.user_type == 1:
return render_template('view_paste.html')
if user.user_type == 2:
return render_template('view_paste_admin.html')
return render_template("view_paste_guest.html")
else:
userid_to_red = paste.user_id
user_to_red = User.query.filter(User.id == userid_to_red).first()
user_to_red.paste_count = user_to_red.paste_count - 1
db.session.delete(paste)
db.session.commit()
return render_template("index.html"), 404
else:
return render_template("index.html"), 404
@mod_paste.route('/api/<url>', methods=['POST'])
def ret_paste(url):
paste = Paste.query.filter(Paste.url == url).first()
user = User.query.filter(paste.user_id == User.id).first()
if is_active(paste):
return jsonify({'paste_owner': user.username, 'paste_text': paste.text, 'paste_title': paste.title, 'paste_lang': paste.lang, 'paste_add': paste.add_time, 'paste_expire': paste.expire_time}), 200
else:
userid_to_red = paste.user_id
user_to_red = User.query.filter(User.id == userid_to_red).first()
user_to_red.paste_count = user_to_red.paste_count - 1
db.session.delete(paste)
db.session.commit()
return render_template("index.html"), 404
# @mod_paste.route('/<url>/add_report', methods=['POST'])
# @requires_auth
# def to_delete(url):
# paste_to_delete = Paste.query.filter(Paste.url == url).first()
# if paste_to_delete.report_count > 5:
# db.session.delete(paste_to_delete)
# else:
# paste_to_delete.report_count = paste_to_delete.report_count + 1
# db.session.commit()
# curr_id = session['user_id']
# paste_list = Paste.query.filter(Paste.user_id == curr_id).all()
# url_pre = "/"
# for paste in paste_list:
# paste.url = url_pre + paste.url
# return render_template('mypaste.html', paste_list=paste_list)
@mod_paste.route('/<url>/edit', methods=['GET'])
@requires_auth
def edit_form(url):
if 'user_id' in session:
user_id = session['user_id']
paste = Paste.query.filter(Paste.url == url).first()
if is_active(paste):
if paste.user_id == user_id:
return render_template('editpaste.html')
return jsonify(success=False, reply="Not Authorized"), 400
else:
userid_to_red = paste.user_id
user_to_red = User.query.filter(User.id == userid_to_red).first()
user_to_red.paste_count = user_to_red.paste_count - 1
db.session.delete(paste)
db.session.commit()
return render_template("index.html"), 404
return jsonify(success=False, reply="Please Login"), 400
@mod_paste.route('/<url>/edit', methods=['POST'])
@requires_auth
def edit_paste(url):
if 'user_id' in session:
user_id = session['user_id']
paste = Paste.query.filter(Paste.url == url).first()
if not is_active(paste):
userid_to_red = paste.user_id
user_to_red = User.query.filter(User.id == userid_to_red).first()
user_to_red.paste_count = user_to_red.paste_count - 1
db.session.delete(paste)
db.session.commit()
return render_template('index.html'), 404
if paste.user_id != user_id:
return jsonify(success=False, reply="Not Authorized"), 400
title = request.form['title']
text = request.form['text']
lang = request.form['lang']
time_form = request.form['time']
paste_type = request.form['type']
expire_time = str(time_form)
paste.title = title
paste.text = text
paste.lang = lang
paste.expire_time = expire_time
paste.paste_type = paste_type
db.session.commit()
return jsonify(success=True, url=url)
return jsonify(success=False, reply="Please Login")
@mod_paste.route('/admin/pastes', methods=['GET'])
@requires_admin
def all_pastes():
paste_list = db.session.all()
url_pre = "/"
for paste in paste_list:
if is_active(paste):
paste.url = url_pre + paste.url
else:
userid_to_red = paste.user_id
user_to_red = User.query.filter(User.id == userid_to_red).first()
user_to_red.paste_count = user_to_red.paste_count - 1
db.session.delete(paste)
db.session.commit()
return render_template('allpaste.html', paste_list=paste_list)
@mod_paste.route('/<username>/paste', methods=['GET'])
@requires_admin
def get_user_pastes(username):
# user_id = session['user_id']
# pastes = paste.query.filter(paste.user_id == user_id).all()
if 'user_id' in session:
return render_template('user_paste.html')
else:
return jsonify({'error': 'Please Login to Continue'}), 400
# return jsonify(success=True, pastes=[paste.to_dict() for paste in
# pastes])
@mod_paste.route('/<username>/api/paste', methods=['POST'])
#@requires_admin
def get_user_pastes_object(username):
# admin_id = session['user_id']
# admin = User.query.filter(admin_id == User.id).first()
user = User.query.filter(User.username == username).first()
pastes = Paste.query.filter(Paste.user_id == user.id).all()
active = []
for paste in pastes:
if is_active(paste):
active.append(paste.to_dict())
else:
userid_to_red = paste.user_id
user_to_red = User.query.filter(User.id == userid_to_red).first()
user_to_red.paste_count = user_to_red.paste_count - 1
db.session.delete(paste)
db.session.commit()
return jsonify({'paste_list': active, 'username': user.username}), 200
| 2.1875 | 2 |
control_drone/run_model_on_cam.py | Apiquet/DeepLearningFrameworkFromScratch | 1 | 2283 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This script run neural network model on a camera live stream
"""
import argparse
import cv2
import numpy as np
import os
import time
import sys
COMMANDS = {0: "move_forward", 1: "go_down", 2: "rot_10_deg",
3: "go_up", 4: "take_off", 5: "land", 6: "idle"}
def send_command(anafi, command_id):
"""
Function to send commands to an Anafi drone in function of the command id
"""
if command_id not in COMMANDS:
raise f"Command id not in COMMANDS choices: {command_id}"
print("The following command will be sent: ", COMMANDS[command_id])
if COMMANDS[command_id] == "move_forward":
anafi.move_relative(dx=1, dy=0, dz=0, dradians=0)
if COMMANDS[command_id] == "go_down":
anafi.move_relative(dx=0, dy=0, dz=-0.5, dradians=0)
if COMMANDS[command_id] == "rot_10_deg":
anafi.move_relative(dx=0, dy=0, dz=0, dradians=0.785)
if COMMANDS[command_id] == "go_up":
anafi.move_relative(dx=0, dy=0, dz=0.5, dradians=0)
if COMMANDS[command_id] == "take_off":
anafi.safe_takeoff(5)
if COMMANDS[command_id] == "land":
anafi.safe_land(5)
return
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"-p",
"--weight_path",
required=True,
type=str,
help="Path to load weights for the model."
)
parser.add_argument(
"-a",
"--pyparrot_path",
required=True,
type=str,
help="Path to pyparrot module downloaded from amymcgovern on github."
)
parser.add_argument(
"-w",
"--img_width",
required=False,
default=28,
type=int,
help="Image width."
)
parser.add_argument(
"-n",
"--num_classes",
required=False,
default=7,
type=int,
help="Number of classes."
)
parser.add_argument(
"-c",
"--crop",
required=False,
default=None,
type=str,
help="Crop image, format: MinWidth,MaxWidth,MinHeight,MaxHeight.\
Set -1 for the unchanged ones"
)
parser.add_argument(
"-r",
"--resize",
required=False,
default=None,
type=str,
help="Resize shape, format: height,width"
)
parser.add_argument(
"-b",
"--binarize",
required=False,
default=None,
type=str,
help="To binarize images, format for thresholding: min,max"
)
parser.add_argument(
"-g",
"--gray",
required=False,
action="store_true",
help="To save 1-channel images"
)
parser.add_argument(
"-e",
"--erode",
required=False,
default=None,
type=str,
help="Erode option, format: kernel_size,iteration"
)
parser.add_argument(
"-d",
"--dilate",
required=False,
default=None,
type=str,
help="Dilate option, format: kernel_size,iteration"
)
parser.add_argument(
"-m",
"--camid",
required=False,
default=0,
type=int,
help="Camera ID, default is 0"
)
parser.add_argument(
"-t",
"--tensorflow",
required=False,
action="store_true",
help="To specify if Tensorflow model is used."
)
parser.add_argument(
"-z",
"--number_of_confimation",
required=False,
default=3,
type=int,
help="Minimum number of identical commands before sending to drone."
)
args = parser.parse_args()
"""
Drone connection
"""
sys.path.append(args.pyparrot_path)
from pyparrot.Anafi import Anafi
print("Connecting to drone...")
anafi = Anafi(drone_type="Anafi", ip_address="192.168.42.1")
success = anafi.connect(10)
print(success)
print("Sleeping few seconds...")
anafi.smart_sleep(3)
"""
Load model
"""
print("Loading model...")
input_size = args.img_width**2
num_class = args.num_classes
hidden_size = 128
if args.tensorflow:
import tensorflow as tf
model = tf.keras.models.load_model(args.weight_path)
else:
script_path = os.path.realpath(__file__)
sys.path.append(os.path.dirname(script_path) + "/../")
from homemade_framework import framework as NN
model = NN.Sequential([NN.Linear(input_size, hidden_size),
NN.LeakyReLU(), NN.BatchNorm(),
NN.Linear(hidden_size, hidden_size),
NN.LeakyReLU(), NN.BatchNorm(),
NN.Linear(hidden_size, num_class),
NN.Softmax()], NN.LossMSE())
model.load(args.weight_path)
"""
Webcam process
"""
print("Start webcam...")
cam = cv2.VideoCapture(args.camid)
ret, frame = cam.read()
min_height, max_height = 0, frame.shape[0]
min_width, max_width = 0, frame.shape[1]
print("Cam resolution: {}x{}".format(max_width, max_height))
if args.crop is not None:
res = [int(x) for x in args.crop.split(',')]
if res[0] != -1:
min_width = res[0]
if res[1] != -1:
max_width = res[1]
if res[2] != -1:
min_height = res[2]
if res[3] != -1:
max_height = res[3]
print("Image cropped to minWidth:maxWidth, minHeight:maxHeight: {}:{}\
, {},{}".format(min_width, max_width, min_height, max_height))
pause = False
imgs = []
while True:
ret, frame = cam.read()
if not ret:
print("failed to grab frame")
break
if args.crop is not None:
frame = frame[min_height:max_height, min_width:max_width]
cv2.imshow("Original image", frame)
k = cv2.waitKey(1)
if k % 256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
elif k % 256 == ord('p'):
# p pressed
if pause:
pause = False
else:
pause = True
if not pause:
if args.gray:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if args.binarize:
frame = cv2.medianBlur(frame, 5)
min_thresh, max_thresh = [int(x) for x in
args.binarize.split(',')]
ret, frame = cv2.threshold(frame, min_thresh, max_thresh,
cv2.THRESH_BINARY)
if args.erode is not None:
k_size, iteration = [int(x) for x in args.erode.split(',')]
kernel = np.ones((k_size, k_size), np.uint8)
frame = cv2.erode(frame, kernel, iterations=int(iteration))
if args.dilate is not None:
k_size, iteration = [int(x) for x in args.dilate.split(',')]
kernel = np.ones((k_size, k_size), np.uint8)
frame = cv2.dilate(frame, kernel, iterations=int(iteration))
if args.resize:
height, width = [int(size) for size in args.resize.split(',')]
frame = cv2.resize(frame, (height, width),
interpolation=cv2.INTER_AREA)
image = np.asarray(frame)/255.
cv2.imshow("Input image for the model", frame)
image = image.reshape([np.prod(image.shape)])
if len(imgs) < args.number_of_confimation:
imgs.append(image)
else:
if args.tensorflow:
results = np.argmax(model(np.asarray(imgs)), axis=1)
else:
results = NN.get_inferences(model, np.asarray(imgs))
print("Model's output on buffer: ", results)
if np.unique(results).size == 1 and\
COMMANDS[results[0]] != "idle":
send_command(anafi, results[0])
imgs = []
imgs = imgs[1:]
imgs.append(image)
time.sleep(0.3)
cam.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
| 2.765625 | 3 |
classify_images.py | rmsare/cs231a-project | 2 | 2284 | <filename>classify_images.py<gh_stars>1-10
"""
Classification of pixels in images using color and other features.
General pipeline usage:
1. Load and segment images (img_utils.py)
2. Prepare training data (label_image.py)
3. Train classifier or cluster data (sklearn KMeans, MeanShift, SVC, etc.)
4. Predict labels on new image or directory (classify_directory())
5. Apply classification to 3D points and estimate ground plane orientation (process_pointcloud.py)
Project uses the following directory structure:
images/ - contains binary files of numpy arrays corresponding to survey images and segmentations
labelled/ - contains labelled ground truth images or training data
results/ - contains results of classification
I store randomly split training and testing images in test/ and train/ directories.
Author: <NAME>
E-mail: <EMAIL>
Date: 8 June 2017
"""
import numpy as np
import matplotlib.pyplot as plt
import skimage.color, skimage.io
from skimage.segmentation import mark_boundaries
from sklearn.svm import SVC
from sklearn.cluster import KMeans, MeanShift
from sklearn.metrics import confusion_matrix
from sklearn.utils import shuffle
import os, fnmatch
def classify_directory(classifier, test_dir, train_dir='train/'):
"""
Classify all images in a directory using an arbitrary sklearn classifier.
Saves results to results/ directory.
"""
# XXX: This is here if the classifier needs to be trained from scratch
#print("Preparing training data...")
#n_samples = 1000
#train_data, train_labels = load_training_images(train_dir, n_samples)
#
#print("Training classifier...")
#classifier = ImageSVC()
#classifier.fit(train_data, train_labels)
files = os.listdir(test_dir)
for f in files:
image = skimage.io.imread(f)
height, width, depth = image.shape
print("Predicting labels for " + f.strip('.JPG') + ".jpg")
features = compute_colorxy_features(image)
features /= features.max(axis=0)
pred_labels = classifier.predict(features)
print("Saving predictions for " + f.strip('.JPG') + ".jpg")
plt.figure()
plt.imshow(image)
plt.imshow(pred_labels.reshape((height, width)), alpha=0.5, vmin=0, vmax=2)
plt.show(block=False)
plt.savefig('results/' + f.strip('.JPG') + '_svm_pred.png')
plt.close()
np.save('results/' + f.strip('.JPG') + 'svm.npy', pred_labels.reshape((height,width)))
def compute_colorxy_features(image):
"""
Extract and normalize color and pixel location features from image data
"""
height, width, depth = image.shape
colors = skimage.color.rgb2lab(image.reshape((height*width, depth))
X, Y = np.meshgrid(np.arange(height), np.arange(width))
xy = np.hstack([X.reshape((height*width, 1)), Y.reshape((height*width, 1))])
colorxy = np.hstack([xy, colors])
colorxy /= colorxy.max(axis=0)
return colorxy
def load_ground_truth(filename):
"""
Load ground truth or training image array and redefine labelling for nice
default colors
"""
truth = np.load(filename)
# Change labels for nice default colorscale when plotted
truth = truth - 1
truth[truth == -1] = 0
truth[truth == 0] = 5
truth[truth == 2] = 0
truth[truth == 5] = 2
return truth
def load_image_labels(name):
"""
Load image and labels from previous labelling session
"""
fname = 'images/' + name + '_image.npy'
image = np.load(fname)
fname = 'labelled/' + name + '_labels.npy'
labels = np.load(fname)
return image, labels
def plot_class_image(image, segments, labels):
"""
Display image with segments and class label overlay
"""
plt.figure()
plt.subplot(1,2,1)
plt.imshow(mark_boundaries(image, segments, color=(1,0,0), mode='thick'))
plt.title('segmented image')
plt.subplot(1,2,2)
plt.imshow(image)
plt.imshow(labels, alpha=0.75)
cb = plt.colorbar(orientation='horizontal', shrink=0.5)
plt.title('predicted class labels')
plt.show(block=False)
def load_training_images(train_dir, n_samples=1000, n_features=3):
"""
Load training images from directory and subsample for training or validation
"""
train_data = np.empty((0, n_features))
train_labels = np.empty(0)
files = os.listdir(train_dir)
for f in files:
name = parse_filename(f)
image, labels = load_image_labels(name)
ht, wid, depth = image.shape
train_data = np.append(train_data,
compute_color_features(image), axis=0)
train_labels = np.append(train_labels,
labels.reshape(wid*ht, 1).ravel())
train_data, train_labels = shuffle(train_data, train_labels,
random_state=0, n_samples=n_samples)
return train_data, train_labels
def save_prediction(name, pred_labels):
"""
Save predicted class labels
"""
np.save('results/' + name + '_pred', pred_labels)
if __name__ == "__main__":
# Load training data
train_dir = 'train/'
test_dir = 'test/'
train_data, train_labels = load_training_data(train_dir)
# Train classifier
clf = SVC()
clf.fit(train_data, train_labels)
# Predict labels for test images
classify_directory(clf, test_dir)
| 3.390625 | 3 |
quick_start/my_text_classifier/predictors/sentence_classifier_predictor.py | ramild/allennlp-guide | 71 | 2285 | from allennlp.common import JsonDict
from allennlp.data import DatasetReader, Instance
from allennlp.models import Model
from allennlp.predictors import Predictor
from overrides import overrides
@Predictor.register("sentence_classifier")
class SentenceClassifierPredictor(Predictor):
def predict(self, sentence: str) -> JsonDict:
return self.predict_json({"sentence": sentence})
@overrides
def _json_to_instance(self, json_dict: JsonDict) -> Instance:
sentence = json_dict["sentence"]
return self._dataset_reader.text_to_instance(sentence)
| 2.453125 | 2 |
ciphers/SKINNY-TK2/SKINNY-TK2/skinnytk2.py | j-danner/autoguess | 7 | 2286 | # Created on Sep 7, 2020
# author: <NAME>
# contact: <EMAIL>
import os
output_dir = os.path.curdir
def skinnytk2(R=1):
"""
This function generates the relations of Skinny-n-n for R rounds.
tk ================================================> TWEAKEY_P(tk) ===> ---
SB AC | P MC SB AC |
x_0 ===> x_0 ===> x_0 ===> + ===> y_0 ===> P(y_0) ===> x_1 ===> x_1 ===> x_1 ===> + ===> y_1 ===> ---
"""
cipher_name = 'skinnytk2'
P = [0, 1, 2, 3, 7, 4, 5, 6, 10, 11, 8, 9, 13, 14, 15, 12]
TKP = [9, 15, 8, 13, 10, 14, 12, 11, 0, 1, 2, 3, 4, 5, 6, 7]
tk1 = ['tk1_%d' % i for i in range(16)]
tk2 = ['tk2_%d' % i for i in range(16)]
# 1 round
# recommended_mg = 8
# recommended_ms = 4
# 2 rounds
# recommended_mg = 16
# recommended_ms = 8
# 3 rounds
# recommended_mg = 19
# recommended_ms = 24
# 4 rounds
# recommended_mg = 21
# recommended_ms = 27
# 5 rounds
# recommended_mg = 22
# recommended_ms = 35
# 6 rounds
# recommended_mg = 25
# recommended_ms = 40
# 7 rounds
# recommended_mg = 26
# recommended_ms = 70
# 8 rounds
# recommended_mg = 28
# recommended_ms = 80
# 9 rounds
# recommended_mg = 28
# recommended_ms = 100
# 10 rounds
recommended_mg = 30
recommended_ms = 100
# 11 rounds
# recommended_mg = 31
# recommended_ms = 100
eqs = '#%s %d Rounds\n' % (cipher_name, R)
eqs += 'connection relations\n'
for r in range(R):
xin = ['x_%d_%d' % (r, i) for i in range(16)]
xout = ['x_%d_%d' % (r + 1, i) for i in range(16)]
y = ['y_%d_%d' % (r, i) for i in range(16)]
tk = ['tk_%d_%d' % (r, i) for i in range(8)]
# Generaete AddTweakey relations
for i in range(4):
for j in range(4):
if i < 2:
eqs += '%s, %s, %s\n' % (tk1[j + 4*i], tk2[j + 4*i], tk[j + 4*i])
eqs += '%s, %s, %s\n' % (xin[j + 4*i], tk[j + 4*i], y[j + 4*i])
else:
eqs += '%s, %s\n' % (xin[j + 4*i], y[j + 4*i])
# Apply ShiftRows
py = [y[P[i]] for i in range(16)]
# Generate MixColumn relations
for j in range(4):
eqs += '%s, %s, %s, %s\n' % (py[j + 0*4], py[j + 2*4], py[j + 3*4], xout[j + 0*4])
eqs += '%s, %s\n' % (py[j], xout[j + 1*4])
eqs += '%s, %s, %s\n' % (py[j + 1*4], py[j + 2*4], xout[j + 2*4])
eqs += '%s, %s, %s\n' % (py[j + 0*4], py[j + 2*4], xout[j + 3*4])
# Update Tweakey
temp1 = tk1.copy()
temp2 = tk2.copy()
tk1 = [temp1[TKP[i]] for i in range(16)]
tk2 = [temp2[TKP[i]] for i in range(16)]
plaintext = ['x_0_%d' % i for i in range(16)]
ciphertext = ['x_%d_%d' % (R, i) for i in range(16)]
eqs += 'known\n' + '\n'.join(plaintext + ciphertext)
eqs += '\nend'
relation_file_path = os.path.join(output_dir, 'relationfile_%s_%dr_mg%d_ms%d.txt' % (cipher_name, R, recommended_mg, recommended_ms))
with open(relation_file_path, 'w') as relation_file:
relation_file.write(eqs)
def main():
skinnytk2(R=10)
if __name__ == '__main__':
main()
| 2.84375 | 3 |
tests/test_bmipy.py | visr/bmi-python | 14 | 2287 | <filename>tests/test_bmipy.py<gh_stars>10-100
import pytest
from bmipy import Bmi
class EmptyBmi(Bmi):
def __init__(self):
pass
def initialize(self, config_file):
pass
def update(self):
pass
def update_until(self, then):
pass
def finalize(self):
pass
def get_var_type(self, var_name):
pass
def get_var_units(self, var_name):
pass
def get_var_nbytes(self, var_name):
pass
def get_var_itemsize(self, name):
pass
def get_var_location(self, name):
pass
def get_var_grid(self, var_name):
pass
def get_grid_rank(self, grid_id):
pass
def get_grid_size(self, grid_id):
pass
def get_value_ptr(self, var_name):
pass
def get_value(self, var_name):
pass
def get_value_at_indices(self, var_name, indices):
pass
def set_value(self, var_name, src):
pass
def set_value_at_indices(self, var_name, src, indices):
pass
def get_component_name(self):
pass
def get_input_item_count(self):
pass
def get_output_item_count(self):
pass
def get_input_var_names(self):
pass
def get_output_var_names(self):
pass
def get_grid_shape(self, grid_id):
pass
def get_grid_spacing(self, grid_id):
pass
def get_grid_origin(self, grid_id):
pass
def get_grid_type(self, grid_id):
pass
def get_start_time(self):
pass
def get_end_time(self):
pass
def get_current_time(self):
pass
def get_time_step(self):
pass
def get_time_units(self):
pass
def get_grid_edge_count(self, grid):
pass
def get_grid_edge_nodes(self, grid, edge_nodes):
pass
def get_grid_face_count(self, grid):
pass
def get_grid_face_nodes(self, grid, face_nodes):
pass
def get_grid_face_edges(self, grid, face_edges):
pass
def get_grid_node_count(self, grid):
pass
def get_grid_nodes_per_face(self, grid, nodes_per_face):
pass
def get_grid_x(self, grid, x):
pass
def get_grid_y(self, grid, y):
pass
def get_grid_z(self, grid, z):
pass
def test_bmi_not_implemented():
class MyBmi(Bmi):
pass
with pytest.raises(TypeError):
Bmi()
def test_bmi_implemented():
assert isinstance(EmptyBmi(), Bmi)
| 2.0625 | 2 |
scrapy_compose/fields/parser/string_field.py | Sphynx-HenryAY/scrapy-compose | 0 | 2288 | <reponame>Sphynx-HenryAY/scrapy-compose
from scrapy_compose.utils.context import realize
from .field import FuncField as BaseField
class StringField( BaseField ):
process_timing = [ "post_pack" ]
def __init__( self, key = None, value = None, selector = None, **kwargs ):
#unify value format
if isinstance( value, str ):
value = { "_type": "string", "value": value }
super( StringField, self ).__init__( key = key, value = value, selector = selector, **kwargs )
def make_field( self, selector, key = None, value = None, **kwargs ):
return { realize( selector, key ): self.post_pack( realize( selector, value ) ) }
| 2.3125 | 2 |
app/request.py | vincentmuya/News-highlight | 0 | 2289 | import urllib.request
import json
from .models import News
# Getting api key
api_key = None
# Getting the movie base url
base_url = None
def configure_request(app):
global api_key,base_url
api_key = app.config['NEWS_API_KEY']
base_url = app.config['NEWS_API_BASE_URL']
def get_news_source(country,category):
'''
Function that gets the json response to our url request
'''
get_news_source_url = base_url.format(country,category,api_key)
with urllib.request.urlopen(get_news_source_url)as url:
get_news_source_data = url.read()
get_news_source_response = json.loads(get_news_source_data)
print(get_news_source_response)
source_result = None
if get_news_source_response['articles']:
source_result_list = get_news_source_response['articles']
source_result = process_result(source_result_list)
return source_result
def process_result(source_list):
'''
this function processes the results and converts them into a list
the source list is a list of dictionaries containing news results
'''
source_result= []
for source_item in source_list:
source = source_item.get('source')
author = source_item.get('author')
title = source_item.get('title')
description = source_item.get('description')
url = source_item.get('url')
urlToImage = source_item.get('urlToImage')
publishedAt = source_item.get('publishedAt')
if urlToImage:
source_object = News(source,author,title,description,url,urlToImage,publishedAt)
source_result.append(source_object)
return source_result
def get_news(source):
get_news_details_url = base_url.format(source,api_key)
with urllib.request.urlopen(get_news_details_url) as url:
news_details_data = url.read()
news_details_response = json.loads(news_details_data)
news_object = None
if news_details_response:
source = news_details_response.get('source')
author = news_details_response.get('original_author')
title = news_details_response.get('title')
description = news_details_response.get('description')
url = news_details_response.get('url')
urlToImage = news_details_response.get('urlToImage')
news_object = news(source,author,title,description,url,urlToImage,publishedAt)
return news_object
| 3.046875 | 3 |
hypernet/src/thermophysicalModels/reactionThermo/mixture/multiComponent.py | christian-jacobsen/hypernet | 0 | 2290 | import numpy as np
from hypernet.src.general import const
from hypernet.src.general import utils
from hypernet.src.thermophysicalModels.reactionThermo.mixture import Basic
class MultiComponent(Basic):
# Initialization
###########################################################################
def __init__(
self,
specieThermos,
*args,
**kwargs
):
super(MultiComponent, self).__init__(specieThermos)
# Methods
###########################################################################
# Mixture properties ------------------------------------------------------
def update(self, XY, var='Y'):
# Update mass/molar fractions
for name, value in XY.items():
value = utils.check_XY(utils.convert_to_array(value))
setattr(self.spTh[name].specie, var, value)
# Update mixture/species properties
self.M = self.M_(var=var)
if var == 'Y':
self.Xi_()
elif var == 'X':
self.Yi_()
self.R = self.R_()
# Mixture properties ------------------------------------------------------
# Mass
def M_(self, var='Y'):
# [kg/mol]
if var == 'Y':
M = [spTh.specie.Y / spTh.specie.M for spTh in self.spTh.values()]
return 1./np.sum(np.concatenate(M))
elif var == 'X':
M = [spTh.specie.X * spTh.specie.M for spTh in self.spTh.values()]
return np.sum(np.concatenate(M))
# Specific gas constant
def R_(self):
R = [spTh.specie.Y * spTh.specie.R for spTh in self.spTh.values()]
return np.sum(np.concatenate(R))
# Pressure
def p_(self, rho, T):
return rho*self.R*T
# Density
def rho_(self, p, T):
return p/(self.R*T)
# Number density
def n_(self, rho):
self.ni_(rho=rho, var='Y')
n = [spTh.specie.n for spTh in self.spTh.values()]
return np.sum(np.concatenate(n))
# Enthalpy/Energy
def he_(self):
# [J/kg]
he = [spTh.specie.Y * spTh.thermo.he for spTh in self.spTh.values()]
return np.sum(np.concatenate(he))
def cpv_(self):
# [J/(kg K)]
cpv = [spTh.specie.Y * spTh.thermo.cpv for spTh in self.spTh.values()]
return np.sum(np.concatenate(cpv))
def dcpvdT_(self):
# [J/kg]
dcpvdT = [
spTh.specie.Y * spTh.thermo.dcpvdT for spTh in self.spTh.values()
]
return np.sum(np.concatenate(dcpvdT))
def dhedY_(self, dY):
# [J/kg]
dhedY = [
np.sum(dY[name] * spTh.thermo.he) \
for name, spTh in self.spTh.items()
]
return np.sum(dhedY)
# Species properties ------------------------------------------------------
def Yi_(self):
for spTh_ in self.spTh.values():
sp = spTh_.specie
sp.Y = sp.X * sp.M / self.M
def Xi_(self):
for spTh_ in self.spTh.values():
sp = spTh_.specie
sp.X = sp.Y * self.M / sp.M
def ni_(self, rho=None, n=None, var='Y'):
for spTh_ in self.spTh.values():
sp = spTh_.specie
if var == 'Y':
sp.n = sp.Y * rho / sp.M * const.UNA
elif var == 'X':
sp.n = sp.X * n
def rhoi_(self, rho=None, n=None, var='Y'):
for spTh_ in self.spTh.values():
sp = spTh_.specie
if var == 'Y':
sp.rho = sp.Y * rho
elif var == 'X':
sp.rho = sp.X * n * sp.M / const.UNA
| 2.3125 | 2 |
Exercises/W08D04_Exercise_01_Django_Cat_Collector/main_app/models.py | Roger-Takeshita/Software_Engineer | 2 | 2291 | <filename>Exercises/W08D04_Exercise_01_Django_Cat_Collector/main_app/models.py
from django.db import models
from django.urls import reverse
from datetime import date
from django.contrib.auth.models import User #! 1 - Import user models
MEALS = (
('B', 'Breakfast'),
('L', 'Lunch'),
('D', 'Dinner')
)
class Toy(models.Model):
name = models.CharField(max_length=50)
color = models.CharField(max_length=20)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('toys_detail', kwargs={'pk': self.id})
class Cat(models.Model):
name = models.CharField(max_length=100)
breed = models.CharField(max_length=100)
description = models.TextField(max_length=250)
age = models.IntegerField()
toys = models.ManyToManyField(Toy)
user = models.ForeignKey(User, on_delete=models.CASCADE) #+ 1.1 - Add user as ForeignKey (URL mapping, we use this to point to our class based views)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('detail', kwargs={'cat_id': self.id})
def fed_for_today(self):
return self.feeding_set.filter(date=date.today()).count() >= len(MEALS)
class Feeding(models.Model):
date = models.DateField('feeding date')
meal = models.CharField(
max_length=1,
choices=MEALS,
default=MEALS[0][0]
)
cat = models.ForeignKey(Cat, on_delete=models.CASCADE)
def __str__(self):
# Nice method for obtaining the friendly value of a Field.choice
return f"{self.get_meal_display()} on {self.date}"
# change the default sort
class Meta:
ordering = ['-date']
class Photo(models.Model):
url = models.CharField(max_length=200)
cat = models.ForeignKey(Cat, on_delete=models.CASCADE)
def __str__(self):
return f"Photo for cat_id: {self.cat_id} @{self.url}" | 2.71875 | 3 |
kedro-airflow/kedro_airflow/__init__.py | kedro-org/kedro-plugins | 6 | 2292 | <gh_stars>1-10
""" Kedro plugin for running a project with Airflow """
__version__ = "0.5.0"
| 0.9375 | 1 |
soccer/gameplay/plays/testing/debug_window_evaluator.py | AniruddhaG123/robocup-software | 1 | 2293 | <reponame>AniruddhaG123/robocup-software
import play
import behavior
import main
import robocup
import constants
import time
import math
## This isn't a real play, but it's pretty useful
# Turn it on and we'll draw the window evaluator stuff on-screen from the ball to our goal
class DebugWindowEvaluator(play.Play):
def __init__(self):
super().__init__(continuous=True)
self.add_transition(behavior.Behavior.State.start,
behavior.Behavior.State.running, lambda: True,
'immediately')
def execute_running(self):
win_eval = robocup.WindowEvaluator(main.context())
win_eval.debug = True
windows, best = win_eval.eval_pt_to_our_goal(main.ball().pos)
| 3.609375 | 4 |
rainbowconnection/sources/phoenix/utils.py | zkbt/rainbow-connection | 6 | 2294 | from ...imports import *
def stringify_metallicity(Z):
"""
Convert a metallicity into a PHOENIX-style string.
Parameters
----------
Z : float
[Fe/H]-style metallicity (= 0.0 for solar)
"""
if Z <= 0:
return "-{:03.1f}".format(np.abs(Z))
else:
return "+{:03.1f}".format(Z)
| 2.8125 | 3 |
shipane_sdk/transaction.py | awfssv/ShiPanE-Python-SDK | 1 | 2295 | # -*- coding: utf-8 -*-
class Transaction(object):
def __init__(self, **kwargs):
self._completed_at = kwargs.get('completed_at')
self._type = kwargs.get('type')
self._symbol = kwargs.get('symbol')
self._price = kwargs.get('price')
self._amount = kwargs.get('amount')
def __eq__(self, other):
if self.completed_at != other.completed_at:
return False
if self.type != other.type:
return False
if self.symbol != other.symbol:
return False
if self.price != other.price:
return False
if self.amount != other.amount:
return False
return True
def get_cn_type(self):
return u'买入' if self.type == 'BUY' else u'卖出'
@property
def completed_at(self):
return self._completed_at
@completed_at.setter
def completed_at(self, value):
self._completed_at = value
@property
def type(self):
return self._type
@type.setter
def type(self, value):
self._type = value
@property
def symbol(self):
return self._symbol
@symbol.setter
def symbol(self, value):
self._symbol = value
@property
def price(self):
return self._price
@price.setter
def price(self, value):
self._price = value
@property
def amount(self):
return self._amount
@amount.setter
def amount(self, value):
self._amount = value
| 2.890625 | 3 |
tensorflow_probability/python/distributions/laplace_test.py | wataruhashimoto52/probability | 1 | 2296 | <reponame>wataruhashimoto52/probability
# Copyright 2018 The TensorFlow Probability 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.
# ============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
from scipy import stats as sp_stats
import tensorflow.compat.v2 as tf
import tensorflow_probability as tfp
from tensorflow_probability.python.internal import samplers
from tensorflow_probability.python.internal import test_util
tfd = tfp.distributions
@test_util.test_all_tf_execution_regimes
class LaplaceTest(test_util.TestCase):
def testLaplaceShape(self):
loc = tf.constant([3.0] * 5)
scale = tf.constant(11.0)
laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)
self.assertEqual(self.evaluate(laplace.batch_shape_tensor()), (5,))
self.assertEqual(laplace.batch_shape, tf.TensorShape([5]))
self.assertAllEqual(self.evaluate(laplace.event_shape_tensor()), [])
self.assertEqual(laplace.event_shape, tf.TensorShape([]))
def testLaplaceLogPDF(self):
batch_size = 6
loc = tf.constant([2.0] * batch_size)
scale = tf.constant([3.0] * batch_size)
loc_v = 2.0
scale_v = 3.0
x = np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32)
laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)
log_pdf = laplace.log_prob(x)
self.assertEqual(log_pdf.shape, (6,))
expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v)
self.assertAllClose(self.evaluate(log_pdf), expected_log_pdf)
pdf = laplace.prob(x)
self.assertEqual(pdf.shape, (6,))
self.assertAllClose(self.evaluate(pdf), np.exp(expected_log_pdf))
def testLaplaceLogPDFMultidimensional(self):
batch_size = 6
loc = tf.constant([[2.0, 4.0]] * batch_size)
scale = tf.constant([[3.0, 4.0]] * batch_size)
loc_v = np.array([2.0, 4.0])
scale_v = np.array([3.0, 4.0])
x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T
laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)
log_pdf = laplace.log_prob(x)
log_pdf_values = self.evaluate(log_pdf)
self.assertEqual(log_pdf.shape, (6, 2))
pdf = laplace.prob(x)
pdf_values = self.evaluate(pdf)
self.assertEqual(pdf.shape, (6, 2))
expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v)
self.assertAllClose(log_pdf_values, expected_log_pdf)
self.assertAllClose(pdf_values, np.exp(expected_log_pdf))
def testLaplaceLogPDFMultidimensionalBroadcasting(self):
batch_size = 6
loc = tf.constant([[2.0, 4.0]] * batch_size)
scale = tf.constant(3.0)
loc_v = np.array([2.0, 4.0])
scale_v = 3.0
x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T
laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)
log_pdf = laplace.log_prob(x)
log_pdf_values = self.evaluate(log_pdf)
self.assertEqual(log_pdf.shape, (6, 2))
pdf = laplace.prob(x)
pdf_values = self.evaluate(pdf)
self.assertEqual(pdf.shape, (6, 2))
expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v)
self.assertAllClose(log_pdf_values, expected_log_pdf)
self.assertAllClose(pdf_values, np.exp(expected_log_pdf))
def testLaplaceCDF(self):
batch_size = 6
loc = tf.constant([2.0] * batch_size)
scale = tf.constant([3.0] * batch_size)
loc_v = 2.0
scale_v = 3.0
x = np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32)
laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)
cdf = laplace.cdf(x)
self.assertEqual(cdf.shape, (6,))
expected_cdf = sp_stats.laplace.cdf(x, loc_v, scale=scale_v)
self.assertAllClose(self.evaluate(cdf), expected_cdf)
def testLaplaceLogCDF(self):
batch_size = 6
loc = tf.constant([2.0] * batch_size)
scale = tf.constant([3.0] * batch_size)
loc_v = 2.0
scale_v = 3.0
x = np.array([-2.5, 2.5, -4.0, 0.1, 1.0, 2.0], dtype=np.float32)
laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)
cdf = laplace.log_cdf(x)
self.assertEqual(cdf.shape, (6,))
expected_cdf = sp_stats.laplace.logcdf(x, loc_v, scale=scale_v)
self.assertAllClose(self.evaluate(cdf), expected_cdf)
def testLaplaceQuantile(self):
qs = self.evaluate(
tf.concat(
[[0., 1],
samplers.uniform([10], minval=.1, maxval=.9,
seed=test_util.test_seed())],
axis=0))
d = tfd.Laplace(loc=1., scale=1.3, validate_args=True)
vals = d.quantile(qs)
self.assertAllClose([-np.inf, np.inf], vals[:2])
self.assertAllClose(qs[2:], d.cdf(vals[2:]))
def testLaplaceLogSurvivalFunction(self):
batch_size = 6
loc = tf.constant([2.0] * batch_size)
scale = tf.constant([3.0] * batch_size)
loc_v = 2.0
scale_v = 3.0
x = np.array([-2.5, 2.5, -4.0, 0.1, 1.0, 2.0], dtype=np.float32)
laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)
sf = laplace.log_survival_function(x)
self.assertEqual(sf.shape, (6,))
expected_sf = sp_stats.laplace.logsf(x, loc_v, scale=scale_v)
self.assertAllClose(self.evaluate(sf), expected_sf)
def testLaplaceMean(self):
loc_v = np.array([1.0, 3.0, 2.5])
scale_v = np.array([1.0, 4.0, 5.0])
laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True)
self.assertEqual(laplace.mean().shape, (3,))
expected_means = sp_stats.laplace.mean(loc_v, scale=scale_v)
self.assertAllClose(self.evaluate(laplace.mean()), expected_means)
def testLaplaceMode(self):
loc_v = np.array([0.5, 3.0, 2.5])
scale_v = np.array([1.0, 4.0, 5.0])
laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True)
self.assertEqual(laplace.mode().shape, (3,))
self.assertAllClose(self.evaluate(laplace.mode()), loc_v)
def testLaplaceVariance(self):
loc_v = np.array([1.0, 3.0, 2.5])
scale_v = np.array([1.0, 4.0, 5.0])
laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True)
self.assertEqual(laplace.variance().shape, (3,))
expected_variances = sp_stats.laplace.var(loc_v, scale=scale_v)
self.assertAllClose(self.evaluate(laplace.variance()), expected_variances)
def testLaplaceStd(self):
loc_v = np.array([1.0, 3.0, 2.5])
scale_v = np.array([1.0, 4.0, 5.0])
laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True)
self.assertEqual(laplace.stddev().shape, (3,))
expected_stddev = sp_stats.laplace.std(loc_v, scale=scale_v)
self.assertAllClose(self.evaluate(laplace.stddev()), expected_stddev)
def testLaplaceEntropy(self):
loc_v = np.array([1.0, 3.0, 2.5])
scale_v = np.array([1.0, 4.0, 5.0])
laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True)
self.assertEqual(laplace.entropy().shape, (3,))
expected_entropy = sp_stats.laplace.entropy(loc_v, scale=scale_v)
self.assertAllClose(self.evaluate(laplace.entropy()), expected_entropy)
def testLaplaceSample(self):
loc_v = 4.0
scale_v = 3.0
loc = tf.constant(loc_v)
scale = tf.constant(scale_v)
n = 100000
laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)
samples = laplace.sample(n, seed=test_util.test_seed())
sample_values = self.evaluate(samples)
self.assertEqual(samples.shape, (n,))
self.assertEqual(sample_values.shape, (n,))
self.assertAllClose(
sample_values.mean(),
sp_stats.laplace.mean(loc_v, scale=scale_v),
rtol=0.05,
atol=0.)
self.assertAllClose(
sample_values.var(),
sp_stats.laplace.var(loc_v, scale=scale_v),
rtol=0.05,
atol=0.)
self.assertTrue(self._kstest(loc_v, scale_v, sample_values))
def testLaplaceFullyReparameterized(self):
loc = tf.constant(4.0)
scale = tf.constant(3.0)
_, [grad_loc, grad_scale] = tfp.math.value_and_gradient(
lambda l, s: tfd.Laplace(loc=l, scale=s, validate_args=True).sample( # pylint: disable=g-long-lambda
100, seed=test_util.test_seed()), [loc, scale])
self.assertIsNotNone(grad_loc)
self.assertIsNotNone(grad_scale)
def testLaplaceSampleMultiDimensional(self):
loc_v = np.array([np.arange(1, 101, dtype=np.float32)]) # 1 x 100
scale_v = np.array([np.arange(1, 11, dtype=np.float32)]).T # 10 x 1
laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True)
n = 10000
samples = laplace.sample(n, seed=test_util.test_seed())
sample_values = self.evaluate(samples)
self.assertEqual(samples.shape, (n, 10, 100))
self.assertEqual(sample_values.shape, (n, 10, 100))
zeros = np.zeros_like(loc_v + scale_v) # 10 x 100
loc_bc = loc_v + zeros
scale_bc = scale_v + zeros
self.assertAllClose(
sample_values.mean(axis=0),
sp_stats.laplace.mean(loc_bc, scale=scale_bc),
rtol=0.35,
atol=0.)
self.assertAllClose(
sample_values.var(axis=0),
sp_stats.laplace.var(loc_bc, scale=scale_bc),
rtol=0.10,
atol=0.)
fails = 0
trials = 0
for ai, a in enumerate(np.reshape(loc_v, [-1])):
for bi, b in enumerate(np.reshape(scale_v, [-1])):
s = sample_values[:, bi, ai]
trials += 1
fails += 0 if self._kstest(a, b, s) else 1
self.assertLess(fails, trials * 0.03)
def _kstest(self, loc, scale, samples):
# Uses the Kolmogorov-Smirnov test for goodness of fit.
ks, _ = sp_stats.kstest(samples, sp_stats.laplace(loc, scale=scale).cdf)
# Return True when the test passes.
return ks < 0.02
def testLaplacePdfOfSampleMultiDims(self):
laplace = tfd.Laplace(loc=[7., 11.], scale=[[5.], [6.]], validate_args=True)
num = 50000
samples = laplace.sample(num, seed=test_util.test_seed())
pdfs = laplace.prob(samples)
sample_vals, pdf_vals = self.evaluate([samples, pdfs])
self.assertEqual(samples.shape, (num, 2, 2))
self.assertEqual(pdfs.shape, (num, 2, 2))
self._assertIntegral(sample_vals[:, 0, 0], pdf_vals[:, 0, 0], err=0.02)
self._assertIntegral(sample_vals[:, 0, 1], pdf_vals[:, 0, 1], err=0.02)
self._assertIntegral(sample_vals[:, 1, 0], pdf_vals[:, 1, 0], err=0.02)
self._assertIntegral(sample_vals[:, 1, 1], pdf_vals[:, 1, 1], err=0.02)
self.assertAllClose(
sp_stats.laplace.mean(
[[7., 11.], [7., 11.]], scale=np.array([[5., 5.], [6., 6.]])),
sample_vals.mean(axis=0),
rtol=0.05,
atol=0.)
self.assertAllClose(
sp_stats.laplace.var([[7., 11.], [7., 11.]],
scale=np.array([[5., 5.], [6., 6.]])),
sample_vals.var(axis=0),
rtol=0.05,
atol=0.)
def _assertIntegral(self, sample_vals, pdf_vals, err=1e-3):
s_p = zip(sample_vals, pdf_vals)
prev = (0, 0)
total = 0
for k in sorted(s_p, key=lambda x: x[0]):
pair_pdf = (k[1] + prev[1]) / 2
total += (k[0] - prev[0]) * pair_pdf
prev = k
self.assertNear(1., total, err=err)
def testLaplaceNonPositiveInitializationParamsRaises(self):
loc_v = tf.constant(0.0, name='loc')
scale_v = tf.constant(-1.0, name='scale')
with self.assertRaisesOpError('Argument `scale` must be positive.'):
laplace = tfd.Laplace(
loc=loc_v, scale=scale_v, validate_args=True)
self.evaluate(laplace.mean())
loc_v = tf.constant(1.0, name='loc')
scale_v = tf.constant(0.0, name='scale')
with self.assertRaisesOpError('Argument `scale` must be positive.'):
laplace = tfd.Laplace(
loc=loc_v, scale=scale_v, validate_args=True)
self.evaluate(laplace.mean())
scale = tf.Variable([1., 2., -3.])
self.evaluate(scale.initializer)
with self.assertRaisesOpError('Argument `scale` must be positive.'):
d = tfd.Laplace(loc=0, scale=scale, validate_args=True)
self.evaluate(d.sample(seed=test_util.test_seed()))
def testLaplaceLaplaceKL(self):
batch_size = 6
event_size = 3
a_loc = np.array([[0.5] * event_size] * batch_size, dtype=np.float32)
a_scale = np.array([[0.1] * event_size] * batch_size, dtype=np.float32)
b_loc = np.array([[0.4] * event_size] * batch_size, dtype=np.float32)
b_scale = np.array([[0.2] * event_size] * batch_size, dtype=np.float32)
a = tfd.Laplace(loc=a_loc, scale=a_scale, validate_args=True)
b = tfd.Laplace(loc=b_loc, scale=b_scale, validate_args=True)
distance = tf.abs(a_loc - b_loc)
ratio = a_scale / b_scale
true_kl = (-tf.math.log(ratio) - 1 + distance / b_scale +
ratio * tf.exp(-distance / a_scale))
kl = tfd.kl_divergence(a, b)
x = a.sample(int(1e4), seed=test_util.test_seed())
kl_sample = tf.reduce_mean(a.log_prob(x) - b.log_prob(x), axis=0)
true_kl_, kl_, kl_sample_ = self.evaluate([true_kl, kl, kl_sample])
self.assertAllClose(true_kl_, kl_, atol=1e-5, rtol=1e-5)
self.assertAllClose(true_kl_, kl_sample_, atol=0., rtol=1e-1)
zero_kl = tfd.kl_divergence(a, a)
true_zero_kl_, zero_kl_ = self.evaluate([tf.zeros_like(true_kl), zero_kl])
self.assertAllEqual(true_zero_kl_, zero_kl_)
@test_util.tf_tape_safety_test
def testGradientThroughParams(self):
loc = tf.Variable([-5., 0., 5.])
scale = tf.Variable(2.)
d = tfd.Laplace(loc=loc, scale=scale, validate_args=True)
with tf.GradientTape() as tape:
loss = -d.log_prob([1., 2., 3.])
grad = tape.gradient(loss, d.trainable_variables)
self.assertLen(grad, 2)
self.assertAllNotNone(grad)
def testAssertsPositiveScaleAfterMutation(self):
scale = tf.Variable([1., 2., 3.])
d = tfd.Laplace(loc=0., scale=scale, validate_args=True)
self.evaluate([v.initializer for v in d.variables])
with self.assertRaisesOpError('Argument `scale` must be positive.'):
with tf.control_dependencies([scale.assign([1., 2., -3.])]):
self.evaluate(tfd.Laplace(loc=0., scale=1.).kl_divergence(d))
def testAssertParamsAreFloats(self):
loc = tf.convert_to_tensor(0, dtype=tf.int32)
scale = tf.convert_to_tensor(1, dtype=tf.int32)
with self.assertRaisesRegexp(ValueError, 'Expected floating point'):
tfd.Laplace(loc=loc, scale=scale)
if __name__ == '__main__':
tf.test.main()
| 2.015625 | 2 |
app/__init__.py | credwood/bitplayers | 1 | 2297 | <reponame>credwood/bitplayers<filename>app/__init__.py
import dash
from flask import Flask
from flask.helpers import get_root_path
from flask_login import login_required
from flask_wtf.csrf import CSRFProtect
from flask_admin import Admin, BaseView, expose
from flask_admin.contrib.sqla import ModelView
from datetime import datetime
from dateutil import parser
import pytz
from pytz import timezone
from config import BaseConfig
csrf = CSRFProtect()
def create_app():
from app.models import Blog, User, MyModelView, Contact
from app.extensions import db
from app.dashapp1.layout import layout as layout_1
from app.dashapp1.callbacks import register_callbacks as register_callbacks_1
#from app.dashapp2.layout import layout as layout_2
#from app.dashapp2.callbacks import register_callbacks as register_callbacks_2
from app.dashapp3.layout import layout as layout_3
from app.dashapp3.callbacks import register_callbacks as register_callbacks_3
server = Flask(__name__)
server.config.from_object(BaseConfig)
csrf.init_app(server)
csrf._exempt_views.add('dash.dash.dispatch')
admin = Admin(server)
admin.add_view(MyModelView(User, db.session))
admin.add_view(MyModelView(Blog, db.session))
admin.add_view(MyModelView(Contact, db.session))
register_dashapp(server, 'dashapp1', 'dashboard1', layout_1, register_callbacks_1)
#register_dashapp(server, 'dashapp2', 'dashboard2', layout_2, register_callbacks_2)
register_dashapp(server, 'dashapp3', 'dashboard3', layout_3, register_callbacks_3)
register_extensions(server)
register_blueprints(server)
server.jinja_env.filters['formatdatetime'] = format_datetime
return server
def format_datetime(date,fmt=None):
western = timezone("America/Los_Angeles")
native=pytz.utc.localize(date, is_dst=None).astimezone(western)
#date = parser.parse(str(date))
#native = date.astimezone(western)
format='%m-%d-%Y %I:%M %p'
return native.strftime(format)
def register_dashapp(app, title, base_pathname, layout, register_callbacks_fun):
# Meta tags for viewport responsiveness
meta_viewport = {"name": "viewport", "content": "width=device-width, initial-scale=1, shrink-to-fit=no"}
my_dashapp = dash.Dash(__name__,
server=app,
url_base_pathname=f'/{base_pathname}/',
assets_folder=get_root_path(__name__) + f'/{base_pathname}/assets/',
meta_tags=[meta_viewport])
with app.app_context():
my_dashapp.title = title
my_dashapp.layout = layout
register_callbacks_fun(my_dashapp)
#_protect_dashviews(my_dashapp)
def _protect_dashviews(dashapp):
for view_func in dashapp.server.view_functions:
if view_func.startswith(dashapp.config.url_base_pathname):
dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func])
def register_extensions(server):
from app.extensions import db
from app.extensions import login_inst
from app.extensions import migrate
from app.extensions import mail
db.init_app(server)
login_inst.init_app(server)
login_inst.login_view = 'main.login'
migrate.init_app(server, db)
mail.init_app(server)
def register_blueprints(server):
from app.webapp import server_bp
server.register_blueprint(server_bp)
| 1.773438 | 2 |
selectinf/randomized/approx_reference_grouplasso.py | kevinbfry/selective-inference | 14 | 2298 | from __future__ import print_function
from scipy.linalg import block_diag
from scipy.stats import norm as ndist
from scipy.interpolate import interp1d
import collections
import numpy as np
from numpy import log
from numpy.linalg import norm, qr, inv, eig
import pandas as pd
import regreg.api as rr
from .randomization import randomization
from ..base import restricted_estimator
from ..algorithms.barrier_affine import solve_barrier_affine_py as solver
from ..distributions.discrete_family import discrete_family
class group_lasso(object):
def __init__(self,
loglike,
groups,
weights,
ridge_term,
randomizer,
use_lasso=True, # should lasso solver be used where applicable - defaults to True
perturb=None):
_check_groups(groups) # make sure groups looks sensible
# log likelihood : quadratic loss
self.loglike = loglike
self.nfeature = self.loglike.shape[0]
# ridge parameter
self.ridge_term = ridge_term
# group lasso penalty (from regreg)
# use regular lasso penalty if all groups are size 1
if use_lasso and groups.size == np.unique(groups).size:
# need to provide weights an an np.array rather than a dictionary
weights_np = np.array([w[1] for w in sorted(weights.items())])
self.penalty = rr.weighted_l1norm(weights=weights_np,
lagrange=1.)
else:
self.penalty = rr.group_lasso(groups,
weights=weights,
lagrange=1.)
# store groups as a class variable since the non-group lasso doesn't
self.groups = groups
self._initial_omega = perturb
# gaussian randomization
self.randomizer = randomizer
def fit(self,
solve_args={'tol': 1.e-12, 'min_its': 50},
perturb=None):
# solve the randomized version of group lasso
(self.initial_soln,
self.initial_subgrad) = self._solve_randomized_problem(perturb=perturb,
solve_args=solve_args)
# initialize variables
active_groups = [] # active group labels
active_dirs = {} # dictionary: keys are group labels, values are unit-norm coefficients
unpenalized = [] # selected groups with no penalty
overall = np.ones(self.nfeature, np.bool) # mask of active features
ordered_groups = [] # active group labels sorted by label
ordered_opt = [] # gamma's ordered by group labels
ordered_vars = [] # indices "ordered" by sorting group labels
tol = 1.e-20
_, self.randomizer_prec = self.randomizer.cov_prec
# now we are collecting the directions and norms of the active groups
for g in sorted(np.unique(self.groups)): # g is group label
group_mask = self.groups == g
soln = self.initial_soln # do not need to keep setting this
if norm(soln[group_mask]) > tol * norm(soln): # is group g appreciably nonzero
ordered_groups.append(g)
# variables in active group
ordered_vars.extend(np.flatnonzero(group_mask))
if self.penalty.weights[g] == 0:
unpenalized.append(g)
else:
active_groups.append(g)
active_dirs[g] = soln[group_mask] / norm(soln[group_mask])
ordered_opt.append(norm(soln[group_mask]))
else:
overall[group_mask] = False
self.selection_variable = {'directions': active_dirs,
'active_groups': active_groups} # kind of redundant with keys of active_dirs
self._ordered_groups = ordered_groups
# exception if no groups are selected
if len(self.selection_variable['active_groups']) == 0:
return np.sign(soln), soln
# otherwise continue as before
self.observed_opt_state = np.hstack(ordered_opt) # gammas as array
_beta_unpenalized = restricted_estimator(self.loglike, # refit OLS on E
overall,
solve_args=solve_args)
beta_bar = np.zeros(self.nfeature)
beta_bar[overall] = _beta_unpenalized # refit OLS beta with zeros
self._beta_full = beta_bar
X, y = self.loglike.data
W = self._W = self.loglike.saturated_loss.hessian(X.dot(beta_bar)) # all 1's for LS
opt_linearNoU = np.dot(X.T, X[:, ordered_vars] * W[:, np.newaxis])
for i, var in enumerate(ordered_vars):
opt_linearNoU[var, i] += self.ridge_term
opt_offset = self.initial_subgrad
self.observed_score_state = -opt_linearNoU.dot(_beta_unpenalized)
self.observed_score_state[~overall] += self.loglike.smooth_objective(beta_bar, 'grad')[~overall]
active_signs = np.sign(self.initial_soln)
active = np.flatnonzero(active_signs)
self.active = active
def compute_Vg(ug):
pg = ug.size # figure out size of g'th group
if pg > 1:
Z = np.column_stack((ug, np.eye(pg, pg - 1)))
Q, _ = qr(Z)
Vg = Q[:, 1:] # drop the first column
else:
Vg = np.zeros((1, 0)) # if the group is size one, the orthogonal complement is empty
return Vg
def compute_Lg(g):
pg = active_dirs[g].size
Lg = self.penalty.weights[g] * np.eye(pg)
return Lg
sorted_active_dirs = collections.OrderedDict(sorted(active_dirs.items()))
Vs = [compute_Vg(ug) for ug in sorted_active_dirs.values()]
V = block_diag(*Vs) # unpack the list
Ls = [compute_Lg(g) for g in sorted_active_dirs]
L = block_diag(*Ls) # unpack the list
XE = X[:, ordered_vars] # changed to ordered_vars
Q = XE.T.dot(self._W[:, None] * XE)
QI = inv(Q)
C = V.T.dot(QI).dot(L).dot(V)
self.XE = XE
self.Q = Q
self.QI = QI
self.C = C
U = block_diag(*[ug for ug in sorted_active_dirs.values()]).T
self.opt_linear = opt_linearNoU.dot(U)
self.active_dirs = active_dirs
self.opt_offset = opt_offset
self.ordered_vars = ordered_vars
self.linear_part = -np.eye(self.observed_opt_state.shape[0])
self.offset = np.zeros(self.observed_opt_state.shape[0])
return active_signs, soln
def _solve_randomized_problem(self,
perturb=None,
solve_args={'tol': 1.e-15, 'min_its': 100}):
# take a new perturbation if supplied
if perturb is not None:
self._initial_omega = perturb
if self._initial_omega is None:
self._initial_omega = self.randomizer.sample()
quad = rr.identity_quadratic(self.ridge_term,
0,
-self._initial_omega,
0)
problem = rr.simple_problem(self.loglike, self.penalty)
# if all groups are size 1, set up lasso penalty and run usual lasso solver... (see existing code)...
initial_soln = problem.solve(quad, **solve_args)
initial_subgrad = -(self.loglike.smooth_objective(initial_soln,
'grad') +
quad.objective(initial_soln, 'grad'))
return initial_soln, initial_subgrad
@staticmethod
def gaussian(X,
Y,
groups,
weights,
sigma=1.,
quadratic=None,
ridge_term=0.,
perturb=None,
use_lasso=True, # should lasso solver be used when applicable - defaults to True
randomizer_scale=None):
loglike = rr.glm.gaussian(X, Y, coef=1. / sigma ** 2, quadratic=quadratic)
n, p = X.shape
mean_diag = np.mean((X ** 2).sum(0))
if ridge_term is None:
ridge_term = np.std(Y) * np.sqrt(mean_diag) / np.sqrt(n - 1)
if randomizer_scale is None:
randomizer_scale = np.sqrt(mean_diag) * 0.5 * np.std(Y) * np.sqrt(n / (n - 1.))
randomizer = randomization.isotropic_gaussian((p,), randomizer_scale)
return group_lasso(loglike,
groups,
weights,
ridge_term,
randomizer,
use_lasso,
perturb)
def _setup_implied_gaussian(self):
_, prec = self.randomizer.cov_prec
if np.asarray(prec).shape in [(), (0,)]:
cond_precision = self.opt_linear.T.dot(self.opt_linear) * prec
cond_cov = inv(cond_precision)
logdens_linear = cond_cov.dot(self.opt_linear.T) * prec
else:
cond_precision = self.opt_linear.T.dot(prec.dot(self.opt_linear))
cond_cov = inv(cond_precision)
logdens_linear = cond_cov.dot(self.opt_linear.T).dot(prec)
cond_mean = -logdens_linear.dot(self.observed_score_state + self.opt_offset)
self.cond_mean = cond_mean
self.cond_cov = cond_cov
self.cond_precision = cond_precision
self.logdens_linear = logdens_linear
return cond_mean, cond_cov, cond_precision, logdens_linear
def selective_MLE(self,
solve_args={'tol': 1.e-12},
level=0.9,
useJacobian=True,
dispersion=None):
"""Do selective_MLE for group_lasso
Note: this masks the selective_MLE inherited from query
because that is not adapted for the group_lasso. Also, assumes
you have already run the fit method since this uses results
from that method.
Parameters
----------
observed_target: from selected_targets
target_cov: from selected_targets
target_cov_score: from selected_targets
init_soln: (opt_state) initial (observed) value of optimization variables
cond_mean: conditional mean of optimization variables (model on _setup_implied_gaussian)
cond_cov: conditional variance of optimization variables (model on _setup_implied_gaussian)
logdens_linear: (model on _setup_implied_gaussian)
linear_part: like A_scaling (from lasso)
offset: like b_scaling (from lasso)
solve_args: passed on to solver
level: level of confidence intervals
useC: whether to use python or C solver
JacobianPieces: (use self.C defined in fitting)
"""
self._setup_implied_gaussian() # Calculate useful quantities
(observed_target, target_cov, target_score_cov, alternatives) = self.selected_targets(dispersion)
init_soln = self.observed_opt_state # just the gammas
cond_mean = self.cond_mean
cond_cov = self.cond_cov
logdens_linear = self.logdens_linear
linear_part = self.linear_part
offset = self.offset
if np.asarray(observed_target).shape in [(), (0,)]:
raise ValueError('no target specified')
observed_target = np.atleast_1d(observed_target)
prec_target = inv(target_cov)
prec_opt = self.cond_precision
score_offset = self.observed_score_state + self.opt_offset
# target_lin determines how the conditional mean of optimization variables
# vary with target
# logdens_linear determines how the argument of the optimization density
# depends on the score, not how the mean depends on score, hence the minus sign
target_linear = target_score_cov.T.dot(prec_target)
target_offset = score_offset - target_linear.dot(observed_target)
target_lin = - logdens_linear.dot(target_linear)
target_off = cond_mean - target_lin.dot(observed_target)
if np.asarray(self.randomizer_prec).shape in [(), (0,)]:
_P = target_linear.T.dot(target_offset) * self.randomizer_prec
_prec = prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot(
prec_opt).dot(
target_lin)
else:
_P = target_linear.T.dot(self.randomizer_prec).dot(target_offset)
_prec = prec_target + (target_linear.T.dot(self.randomizer_prec).dot(target_linear)) - target_lin.T.dot(
prec_opt).dot(target_lin)
C = target_cov.dot(_P - target_lin.T.dot(prec_opt).dot(target_off))
conjugate_arg = prec_opt.dot(cond_mean)
val, soln, hess = solve_barrier_affine_jacobian_py(conjugate_arg,
prec_opt,
init_soln,
linear_part,
offset,
self.C,
self.active_dirs,
useJacobian,
**solve_args)
final_estimator = target_cov.dot(_prec).dot(observed_target) \
+ target_cov.dot(target_lin.T.dot(prec_opt.dot(cond_mean - soln))) + C
unbiased_estimator = target_cov.dot(_prec).dot(observed_target) + target_cov.dot(
_P - target_lin.T.dot(prec_opt).dot(target_off))
L = target_lin.T.dot(prec_opt)
observed_info_natural = _prec + L.dot(target_lin) - L.dot(hess.dot(L.T))
observed_info_mean = target_cov.dot(observed_info_natural.dot(target_cov))
Z_scores = final_estimator / np.sqrt(np.diag(observed_info_mean))
pvalues = ndist.cdf(Z_scores)
pvalues = 2 * np.minimum(pvalues, 1 - pvalues)
alpha = 1 - level
quantile = ndist.ppf(1 - alpha / 2.)
intervals = np.vstack([final_estimator -
quantile * np.sqrt(np.diag(observed_info_mean)),
final_estimator +
quantile * np.sqrt(np.diag(observed_info_mean))]).T
log_ref = val + conjugate_arg.T.dot(cond_cov).dot(conjugate_arg) / 2.
result = pd.DataFrame({'MLE': final_estimator,
'SE': np.sqrt(np.diag(observed_info_mean)),
'Zvalue': Z_scores,
'pvalue': pvalues,
'lower_confidence': intervals[:, 0],
'upper_confidence': intervals[:, 1],
'unbiased': unbiased_estimator})
return result, observed_info_mean, log_ref
def selected_targets(self,
dispersion=None,
solve_args={'tol': 1.e-12, 'min_its': 50}):
X, y = self.loglike.data
n, p = X.shape
XE = self.XE
Q = self.Q
observed_target = restricted_estimator(self.loglike, self.ordered_vars, solve_args=solve_args)
_score_linear = -XE.T.dot(self._W[:, None] * X).T
alternatives = ['twosided'] * len(self.active)
if dispersion is None: # use Pearson's X^2
dispersion = ((y - self.loglike.saturated_loss.mean_function(
XE.dot(observed_target))) ** 2 / self._W).sum() / (n - XE.shape[1])
cov_target = self.QI * dispersion
crosscov_target_score = _score_linear.dot(self.QI).T * dispersion
return (observed_target,
cov_target,
crosscov_target_score,
alternatives)
class approximate_grid_inference(object):
def __init__(self,
query,
dispersion,
solve_args={'tol': 1.e-12},
useIP=True):
"""
Produce p-values and confidence intervals for targets
of model including selected features
Parameters
----------
query : `gaussian_query`
A Gaussian query which has information
to describe implied Gaussian.
observed_target : ndarray
Observed estimate of target.
target_cov : ndarray
Estimated covaraince of target.
target_score_cov : ndarray
Estimated covariance of target and score of randomized query.
solve_args : dict, optional
Arguments passed to solver.
"""
self.solve_args = solve_args
result, inverse_info = query.selective_MLE(dispersion=dispersion)[:2]
self.linear_part = query.linear_part
self.offset = query.offset
self.logdens_linear = query.logdens_linear
self.cond_mean = query.cond_mean
self.prec_opt = np.linalg.inv(query.cond_cov)
self.cond_cov = query.cond_cov
self.C = query.C
self.active_dirs = query.active_dirs
(observed_target, target_cov, target_score_cov, alternatives) = query.selected_targets(dispersion)
self.observed_target = observed_target
self.target_score_cov = target_score_cov
self.target_cov = target_cov
self.init_soln = query.observed_opt_state
self.randomizer_prec = query.randomizer_prec
self.score_offset = query.observed_score_state + query.opt_offset
self.ntarget = ntarget = target_cov.shape[0]
_scale = 4 * np.sqrt(np.diag(inverse_info))
if useIP == False:
ngrid = 1000
self.stat_grid = np.zeros((ntarget, ngrid))
for j in range(ntarget):
self.stat_grid[j, :] = np.linspace(observed_target[j] - 1.5 * _scale[j],
observed_target[j] + 1.5 * _scale[j],
num=ngrid)
else:
ngrid = 100
self.stat_grid = np.zeros((ntarget, ngrid))
for j in range(ntarget):
self.stat_grid[j, :] = np.linspace(observed_target[j] - 1.5 * _scale[j],
observed_target[j] + 1.5 * _scale[j],
num=ngrid)
self.opt_linear = query.opt_linear
self.useIP = useIP
def summary(self,
alternatives=None,
parameter=None,
level=0.9):
"""
Produce p-values and confidence intervals for targets
of model including selected features
Parameters
----------
alternatives : [str], optional
Sequence of strings describing the alternatives,
should be values of ['twosided', 'less', 'greater']
parameter : np.array
Hypothesized value for parameter -- defaults to 0.
level : float
Confidence level.
"""
if parameter is not None:
pivots = self._approx_pivots(parameter,
alternatives=alternatives)
else:
pivots = None
pvalues = self._approx_pivots(np.zeros_like(self.observed_target),
alternatives=alternatives)
lower, upper = self._approx_intervals(level=level)
result = pd.DataFrame({'target': self.observed_target,
'pvalue': pvalues,
'lower_confidence': lower,
'upper_confidence': upper})
if not np.all(parameter == 0):
result.insert(4, 'pivot', pivots)
result.insert(5, 'parameter', parameter)
return result
def log_reference(self,
observed_target,
target_cov,
target_score_cov,
grid):
"""
Approximate the log of the reference density on a grid.
"""
if np.asarray(observed_target).shape in [(), (0,)]:
raise ValueError('no target specified')
prec_target = np.linalg.inv(target_cov)
target_lin = - self.logdens_linear.dot(target_score_cov.T.dot(prec_target))
ref_hat = []
for k in range(grid.shape[0]):
# in the usual D = N + Gamma theta.hat,
# target_lin is "something" times Gamma,
# where "something" comes from implied Gaussian
# cond_mean is "something" times D
# Gamma is target_score_cov.T.dot(prec_target)
num_opt = self.prec_opt.shape[0]
num_con = self.linear_part.shape[0]
cond_mean_grid = (target_lin.dot(np.atleast_1d(grid[k] - observed_target)) +
self.cond_mean)
#direction for decomposing o
eta = -self.prec_opt.dot(self.logdens_linear.dot(target_score_cov.T))
implied_mean = np.asscalar(eta.T.dot(cond_mean_grid))
implied_cov = np.asscalar(eta.T.dot(self.cond_cov).dot(eta))
implied_prec = 1./implied_cov
_A = self.cond_cov.dot(eta) * implied_prec
R = np.identity(num_opt) - _A.dot(eta.T)
A = self.linear_part.dot(_A).reshape((-1,))
b = self.offset-self.linear_part.dot(R).dot(self.init_soln)
conjugate_arg = implied_mean * implied_prec
val, soln, _ = solver(np.asarray([conjugate_arg]),
np.reshape(implied_prec, (1,1)),
eta.T.dot(self.init_soln),
A.reshape((A.shape[0],1)),
b,
**self.solve_args)
gamma_ = _A.dot(soln) + R.dot(self.init_soln)
log_jacob = jacobian_grad_hess(gamma_, self.C, self.active_dirs)
ref_hat.append(-val - ((conjugate_arg ** 2) * implied_cov)/ 2. + log_jacob[0])
return np.asarray(ref_hat)
def _construct_families(self):
self._construct_density()
self._families = []
for m in range(self.ntarget):
p = self.target_score_cov.shape[1]
observed_target_uni = (self.observed_target[m]).reshape((1,))
target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1))
target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p))
var_target = 1. / ((self.precs[m])[0, 0])
log_ref = self.log_reference(observed_target_uni,
target_cov_uni,
target_score_cov_uni,
self.stat_grid[m])
if self.useIP == False:
logW = (log_ref - 0.5 * (self.stat_grid[m] - self.observed_target[m]) ** 2 / var_target)
logW -= logW.max()
self._families.append(discrete_family(self.stat_grid[m],
np.exp(logW)))
else:
approx_fn = interp1d(self.stat_grid[m],
log_ref,
kind='quadratic',
bounds_error=False,
fill_value='extrapolate')
grid = np.linspace(self.stat_grid[m].min(), self.stat_grid[m].max(), 1000)
logW = (approx_fn(grid) -
0.5 * (grid - self.observed_target[m]) ** 2 / var_target)
logW -= logW.max()
self._families.append(discrete_family(grid,
np.exp(logW)))
def _approx_pivots(self,
mean_parameter,
alternatives=None):
if not hasattr(self, "_families"):
self._construct_families()
if alternatives is None:
alternatives = ['twosided'] * self.ntarget
pivot = []
for m in range(self.ntarget):
family = self._families[m]
var_target = 1. / ((self.precs[m])[0, 0])
mean = self.S[m].dot(mean_parameter[m].reshape((1,))) + self.r[m]
_cdf = family.cdf((mean[0] - self.observed_target[m]) / var_target, x=self.observed_target[m])
print("variable completed ", m)
if alternatives[m] == 'twosided':
pivot.append(2 * min(_cdf, 1 - _cdf))
elif alternatives[m] == 'greater':
pivot.append(1 - _cdf)
elif alternatives[m] == 'less':
pivot.append(_cdf)
else:
raise ValueError('alternative should be in ["twosided", "less", "greater"]')
return pivot
def _approx_intervals(self,
level=0.9):
if not hasattr(self, "_families"):
self._construct_families()
lower, upper = [], []
for m in range(self.ntarget):
# construction of intervals from families follows `selectinf.learning.core`
family = self._families[m]
observed_target = self.observed_target[m]
l, u = family.equal_tailed_interval(observed_target,
alpha=1 - level)
var_target = 1. / ((self.precs[m])[0, 0])
lower.append(l * var_target + observed_target)
upper.append(u * var_target + observed_target)
return np.asarray(lower), np.asarray(upper)
### Private method
def _construct_density(self):
precs = {}
S = {}
r = {}
p = self.target_score_cov.shape[1]
for m in range(self.ntarget):
observed_target_uni = (self.observed_target[m]).reshape((1,))
target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1))
prec_target = 1. / target_cov_uni
target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p))
target_linear = target_score_cov_uni.T.dot(prec_target)
target_offset = (self.score_offset - target_linear.dot(observed_target_uni)).reshape(
(target_linear.shape[0],))
target_lin = -self.logdens_linear.dot(target_linear)
target_off = (self.cond_mean - target_lin.dot(observed_target_uni)).reshape((target_lin.shape[0],))
_prec = prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot(
self.prec_opt).dot(target_lin)
_P = target_linear.T.dot(target_offset) * self.randomizer_prec
_r = (1. / _prec).dot(target_lin.T.dot(self.prec_opt).dot(target_off) - _P)
_S = np.linalg.inv(_prec).dot(prec_target)
S[m] = _S
r[m] = _r
precs[m] = _prec
self.precs = precs
self.S = S
self.r = r
def solve_barrier_affine_jacobian_py(conjugate_arg,
precision,
feasible_point,
con_linear,
con_offset,
C,
active_dirs,
useJacobian=True,
step=1,
nstep=2000,
min_its=500,
tol=1.e-12):
"""
This needs to be updated to actually use the Jacobian information (in self.C)
arguments
conjugate_arg: \\bar{\\Sigma}^{-1} \bar{\\mu}
precision: \\bar{\\Sigma}^{-1}
feasible_point: gamma's from fitting
con_linear: linear part of affine constraint used for barrier function
con_offset: offset part of affine constraint used for barrier function
C: V^T Q^{-1} \\Lambda V
active_dirs:
"""
scaling = np.sqrt(np.diag(con_linear.dot(precision).dot(con_linear.T)))
if feasible_point is None:
feasible_point = 1. / scaling
def objective(gs):
p1 = -gs.T.dot(conjugate_arg)
p2 = gs.T.dot(precision).dot(gs) / 2.
if useJacobian:
p3 = - jacobian_grad_hess(gs, C, active_dirs)[0]
else:
p3 = 0
p4 = log(1. + 1. / ((con_offset - con_linear.dot(gs)) / scaling)).sum()
return p1 + p2 + p3 + p4
def grad(gs):
p1 = -conjugate_arg + precision.dot(gs)
p2 = -con_linear.T.dot(1. / (scaling + con_offset - con_linear.dot(gs)))
if useJacobian:
p3 = - jacobian_grad_hess(gs, C, active_dirs)[1]
else:
p3 = 0
p4 = 1. / (con_offset - con_linear.dot(gs))
return p1 + p2 + p3 + p4
def barrier_hessian(gs): # contribution of barrier and jacobian to hessian
p1 = con_linear.T.dot(np.diag(-1. / ((scaling + con_offset - con_linear.dot(gs)) ** 2.)
+ 1. / ((con_offset - con_linear.dot(gs)) ** 2.))).dot(con_linear)
if useJacobian:
p2 = - jacobian_grad_hess(gs, C, active_dirs)[2]
else:
p2 = 0
return p1 + p2
current = feasible_point
current_value = np.inf
for itercount in range(nstep):
cur_grad = grad(current)
# make sure proposal is feasible
count = 0
while True:
count += 1
proposal = current - step * cur_grad
if np.all(con_offset - con_linear.dot(proposal) > 0):
break
step *= 0.5
if count >= 40:
raise ValueError('not finding a feasible point')
# make sure proposal is a descent
count = 0
while True:
count += 1
proposal = current - step * cur_grad
proposed_value = objective(proposal)
if proposed_value <= current_value:
break
step *= 0.5
if count >= 20:
if not (np.isnan(proposed_value) or np.isnan(current_value)):
break
else:
raise ValueError('value is NaN: %f, %f' % (proposed_value, current_value))
# stop if relative decrease is small
if np.fabs(current_value - proposed_value) < tol * np.fabs(current_value) and itercount >= min_its:
current = proposal
current_value = proposed_value
break
current = proposal
current_value = proposed_value
if itercount % 4 == 0:
step *= 2
hess = inv(precision + barrier_hessian(current))
return current_value, current, hess
# Jacobian calculations
def calc_GammaMinus(gamma, active_dirs):
"""Calculate Gamma^minus (as a function of gamma vector, active directions)
"""
to_diag = [[g] * (ug.size - 1) for (g, ug) in zip(gamma, active_dirs.values())]
return block_diag(*[i for gp in to_diag for i in gp])
def jacobian_grad_hess(gamma, C, active_dirs):
""" Calculate the log-Jacobian (scalar), gradient (gamma.size vector) and hessian (gamma.size square matrix)
"""
if C.shape == (0, 0): # when all groups are size one, C will be an empty array
return 0, 0, 0
else:
GammaMinus = calc_GammaMinus(gamma, active_dirs)
# eigendecomposition
#evalues, evectors = eig(GammaMinus + C)
# log Jacobian
#J = log(evalues).sum()
J = np.log(np.linalg.det(GammaMinus + C))
# inverse
#GpC_inv = evectors.dot(np.diag(1 / evalues).dot(evectors.T))
GpC_inv = np.linalg.inv(GammaMinus + C)
# summing matrix (gamma.size by C.shape[0])
S = block_diag(*[np.ones((1, ug.size - 1)) for ug in active_dirs.values()])
# gradient
grad_J = S.dot(GpC_inv.diagonal())
# hessian
hess_J = -S.dot(np.multiply(GpC_inv, GpC_inv.T).dot(S.T))
return J, grad_J, hess_J
def _check_groups(groups):
"""Make sure that the user-specific groups are ok
There are a number of assumptions that group_lasso makes about
how groups are specified. Specifically, we assume that
`groups` is a 1-d array_like of integers that are sorted in
increasing order, start at 0, and have no gaps (e.g., if there
is a group 2 and a group 4, there must also be at least one
feature in group 3).
This function checks the user-specified group scheme and
raises an exception if it finds any problems.
Sorting feature groups is potentially tedious for the user and
in future we might do this for them.
"""
# check array_like
agroups = np.array(groups)
# check dimension
if len(agroups.shape) != 1:
raise ValueError("Groups are not a 1D array_like")
# check sorted
if np.any(agroups[:-1] > agroups[1:]) < 0:
raise ValueError("Groups are not sorted")
# check integers
if not np.issubdtype(agroups.dtype, np.integer):
raise TypeError("Groups are not integers")
# check starts with 0
if not np.amin(agroups) == 0:
raise ValueError("First group is not 0")
# check for no skipped groups
if not np.all(np.diff(np.unique(agroups)) == 1):
raise ValueError("Some group is skipped")
| 2.09375 | 2 |
internals/states.py | mattjj/pyhsmm-collapsedinfinite | 0 | 2299 | <reponame>mattjj/pyhsmm-collapsedinfinite
from __future__ import division
import numpy as np
na = np.newaxis
import collections, itertools
import abc
from pyhsmm.util.stats import sample_discrete, sample_discrete_from_log, combinedata
from pyhsmm.util.general import rle as rle
# NOTE: assumes censoring. can make no censoring by adding to score of last
# segment
SAMPLING = -1 # special constant for indicating a state or state range that is being resampled
NEW = -2 # special constant indicating a potentially new label
ABIGNUMBER = 10000 # state labels are sampled uniformly from 0 to abignumber exclusive
####################
# States Classes #
####################
# TODO an array class that maintains its own rle
# must override set methods
# type(x).__setitem__(x,i) classmethod
# also has members norep and lens (or something)
# that are either read-only or also override setters
# for now, i'll just make sure outside that anything that sets self.stateseq
# also sets self.stateseq_norep and self.durations
# it should also call beta updates...
class collapsed_states(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def resample(self):
pass
@abc.abstractmethod
def _counts_from(self,k):
pass
@abc.abstractmethod
def _counts_to(self,k):
pass
@abc.abstractmethod
def _counts_fromto(self,k):
pass
def _new_label(self,ks):
assert SAMPLING not in ks
newlabel = np.random.randint(ABIGNUMBER)
while newlabel in ks:
newlabel = np.random.randint(ABIGNUMBER)
newweight = self.beta.betavec[newlabel] # instantiate, needed if new state at beginning of seq
return newlabel
def _data_withlabel(self,k):
assert k != SAMPLING
return self.data[self.stateseq == k]
def _occupied(self):
return set(self.stateseq) - set((SAMPLING,))
def plot(self,colors_dict):
from matplotlib import pyplot as plt
stateseq_norep, durations = rle(self.stateseq)
X,Y = np.meshgrid(np.hstack((0,durations.cumsum())),(0,1))
if colors_dict is not None:
C = np.array([[colors_dict[state] for state in stateseq_norep]])
else:
C = stateseq_norep[na,:]
plt.pcolor(X,Y,C,vmin=0,vmax=1)
plt.ylim((0,1))
plt.xlim((0,len(self.stateseq)))
plt.yticks([])
class collapsed_stickyhdphmm_states(collapsed_states):
def __init__(self,model,beta,alpha_0,kappa,obs,data=None,T=None,stateseq=None):
self.alpha_0 = alpha_0
self.kappa = kappa
self.model = model
self.beta = beta
self.obs = obs
self.data = data
if (data,stateseq) == (None,None):
# generating
assert T is not None, 'must pass in T when generating'
self._generate(T)
elif data is None:
self.T = stateseq.shape[0]
self.stateseq = stateseq
elif stateseq is None:
self.data = data
self._generate(data.shape[0])
else:
assert data.shape[0] == stateseq.shape[0]
self.stateseq = stateseq
self.data = data
self.T = data.shape[0]
def _generate(self,T):
self.T = T
alpha, kappa = self.alpha_0, self.kappa
betavec = self.beta.betavec
stateseq = np.zeros(T,dtype=np.int)
model = self.model
self.stateseq = stateseq[:0]
# NOTE: we have a choice of what state to start in; it's just a
# definition choice that isn't specified in the HDP-HMM
# Here, we choose just to sample from beta. Note that if this is the
# first chain being sampled in this model, this will always sample
# zero, since no states will be occupied.
ks = list(model._occupied()) + [None]
firststate = sample_discrete(np.arange(len(ks)))
if firststate == len(ks)-1:
stateseq[0] = self._new_label(ks)
else:
stateseq[0] = ks[firststate]
# runs a CRF with fixed weights beta forwards
for t in range(1,T):
self.stateseq = stateseq[:t]
ks = list(model._occupied() | self._occupied())
betarest = 1-sum(betavec[k] for k in ks)
# get the counts of new states coming out of our current state
# going to all other states
fromto_counts = np.array([model._counts_fromto(stateseq[t-1],k)
+ self._counts_fromto(stateseq[t-1],k)
for k in ks])
# for those states plus a new one, sample proportional to
scores = np.array([(alpha*betavec[k] + (kappa if k == stateseq[t+1] else 0) + ft)
for k,ft in zip(ks,fromto_counts)] + [alpha*betarest])
nextstateidx = sample_discrete(scores)
if nextstateidx == scores.shape[0]-1:
stateseq[t] = self._new_label(ks)
else:
stateseq[t] = ks[nextstateidx]
self.stateseq = stateseq
def resample(self):
model = self.model
for t in np.random.permutation(self.T):
# throw out old value
self.stateseq[t] = SAMPLING
ks = list(model._occupied())
self.beta.housekeeping(ks)
# form the scores and sample from them
scores = np.array([self._score(k,t) for k in ks]+[self._new_score(ks,t)])
idx = sample_discrete_from_log(scores)
# set the state
if idx == scores.shape[0]-1:
self.stateseq[t] = self._new_label(ks)
else:
self.stateseq[t] = ks[idx]
def _score(self,k,t):
alpha, kappa = self.alpha_0, self.kappa
betavec, model, o = self.beta.betavec, self.model, self.obs
data, stateseq = self.data, self.stateseq
score = 0
# left transition score
if t > 0:
score += np.log( (alpha*betavec[k] + (kappa if k == stateseq[t-1] else 0)
+ model._counts_fromto(stateseq[t-1],k))
/ (alpha+kappa+model._counts_from(stateseq[t-1])) )
# right transition score
if t < self.T - 1:
# indicators since we may need to include the left transition in
# counts (since we are scoring exchangeably, not independently)
another_from = 1 if t > 0 and stateseq[t-1] == k else 0
another_fromto = 1 if (t > 0 and stateseq[t-1] == k and stateseq[t+1] == k) else 0
score += np.log( (alpha*betavec[stateseq[t+1]] + (kappa if k == stateseq[t+1] else 0)
+ model._counts_fromto(k,stateseq[t+1]) + another_fromto)
/ (alpha+kappa+model._counts_from(k) + another_from) )
# observation score
score += o.log_predictive(data[t],model._data_withlabel(k))
return score
def _new_score(self,ks,t):
alpha, kappa = self.alpha_0, self.kappa
betavec, model, o = self.beta.betavec, self.model, self.obs
data, stateseq = self.data, self.stateseq
score = 0
# left transition score
if t > 0:
betarest = 1-sum(betavec[k] for k in ks)
score += np.log(alpha*betarest/(alpha+kappa+model._counts_from(stateseq[t-1])))
# right transition score
if t < self.T-1:
score += np.log(betavec[stateseq[t+1]])
# observation score
score += o.log_marginal_likelihood(data[t])
return score
def _counts_from(self,k):
assert k != SAMPLING
assert np.sum(self.stateseq == SAMPLING) in (0,1)
temp = np.sum(self.stateseq[:-1] == k)
if SAMPLING in self.stateseq[1:] and \
self.stateseq[np.where(self.stateseq == SAMPLING)[0]-1] == k:
temp -= 1
return temp
def _counts_to(self,k):
assert k != SAMPLING
assert np.sum(self.stateseq == SAMPLING) in (0,1)
temp = np.sum(self.stateseq[1:] == k)
if SAMPLING in self.stateseq[:-1] and \
self.stateseq[np.where(self.stateseq == SAMPLING)[0]+1] == k:
temp -= 1
return temp
def _counts_fromto(self,k1,k2):
assert k1 != SAMPLING and k2 != SAMPLING
if k1 not in self.stateseq or k2 not in self.stateseq:
return 0
else:
from_indices, = np.where(self.stateseq[:-1] == k1) # EXCEPT last
return np.sum(self.stateseq[from_indices+1] == k2)
class collapsed_hdphsmm_states(collapsed_states):
def __init__(self,model,beta,alpha_0,obs,dur,data=None,T=None,stateseq=None):
self.alpha_0 = alpha_0
self.model = model
self.beta = beta
self.obs = obs
self.dur = dur
self.data = data
if (data,stateseq) == (None,None):
# generating
assert T is not None, 'must pass in T when generating'
self._generate(T)
elif data is None:
self.T = stateseq.shape[0]
self.stateseq = stateseq
elif stateseq is None:
self.data = data
# self._generate(data.shape[0]) # initialized from the prior
# self.stateseq = self.stateseq[:self.T]
self.stateseq = np.random.randint(25,size=data.shape[0])
self.T = data.shape[0]
else:
assert data.shape[0] == stateseq.shape[0]
self.stateseq = stateseq
self.stateseq_norep, self.durations = rle(stateseq)
self.data = data
self.T = data.shape[0]
def _generate(self,T):
alpha = self.alpha_0
betavec = self.beta.betavec
model = self.model
self.stateseq = np.array([])
ks = list(model._occupied()) + [None]
firststateidx = sample_discrete(np.arange(len(ks)))
if firststateidx == len(ks)-1:
firststate = self._new_label(ks)
else:
firststate = ks[firststateidx]
self.dur.resample(combinedata((model._durs_withlabel(firststate),self._durs_withlabel(firststate))))
firststate_dur = self.dur.rvs()
self.stateseq = np.ones(firststate_dur,dtype=int)*firststate
t = firststate_dur
# run a family-CRF (CRF with durations) forwards
while t < T:
ks = list(model._occupied() | self._occupied())
betarest = 1-sum(betavec[k] for k in ks)
fromto_counts = np.array([model._counts_fromto(self.stateseq[t-1],k)
+ self._counts_fromto(self.stateseq[t-1],k)
for k in ks])
scores = np.array([(alpha*betavec[k] + ft if k != self.stateseq[t-1] else 0)
for k,ft in zip(ks,fromto_counts)]
+ [alpha*(1-betavec[self.stateseq[t-1]])*betarest])
nextstateidx = sample_discrete(scores)
if nextstateidx == scores.shape[0]-1:
nextstate = self._new_label(ks)
else:
nextstate = ks[nextstateidx]
# now get the duration of nextstate!
self.dur.resample(combinedata((model._durs_withlabel(nextstate),self._durs_withlabel(nextstate))))
nextstate_dur = self.dur.rvs()
self.stateseq = np.concatenate((self.stateseq,np.ones(nextstate_dur,dtype=int)*nextstate))
t += nextstate_dur
self.T = len(self.stateseq)
def resample(self):
self.resample_label_version()
def _durs_withlabel(self,k):
assert k != SAMPLING
if len(self.stateseq) > 0:
stateseq_norep, durations = rle(self.stateseq)
return durations[stateseq_norep == k]
else:
return []
def _counts_fromto(self,k1,k2):
assert k1 != SAMPLING and k2 != SAMPLING
if k1 not in self.stateseq or k2 not in self.stateseq or k1 == k2:
return 0
else:
stateseq_norep, _ = rle(self.stateseq)
from_indices, = np.where(stateseq_norep[:-1] == k1) # EXCEPT last
return np.sum(stateseq_norep[from_indices+1] == k2)
def _counts_from(self,k):
assert k != SAMPLING
stateseq_norep, _ = rle(self.stateseq)
temp = np.sum(stateseq_norep[:-1] == k)
if SAMPLING in stateseq_norep[1:] and \
stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]-1] == k:
temp -= 1
return temp
def _counts_to(self,k):
assert k != SAMPLING
stateseq_norep, _ = rle(self.stateseq)
temp = np.sum(stateseq_norep[1:] == k)
if SAMPLING in stateseq_norep[:-1] and \
stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]+1] == k:
temp -= 1
return temp
### label sampler stuff
def resample_label_version(self):
# NOTE never changes first label: we assume the initial state
# distribution is a delta at that label
for t in (np.random.permutation(self.T-1)+1):
self.stateseq[t] = SAMPLING
ks = self.model._occupied()
self.beta.housekeeping(ks)
ks = list(ks)
# sample a new value
scores = np.array([self._label_score(t,k) for k in ks] + [self._new_label_score(t,ks)])
newlabelidx = sample_discrete_from_log(scores)
if newlabelidx == scores.shape[0]-1:
self.stateseq[t] = self._new_label(ks)
else:
self.stateseq[t] = ks[newlabelidx]
def _label_score(self,t,k):
assert t > 0
score = 0.
# unpack variables
model = self.model
alpha = self.alpha_0
beta = self.beta.betavec
stateseq = self.stateseq
obs, durs = self.obs, self.dur
# left transition (if there is one)
if stateseq[t-1] != k:
score += np.log(alpha * beta[k] + model._counts_fromto(stateseq[t-1],k)) \
- np.log(alpha * (1-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1]))
# right transition (if there is one)
if t < self.T-1 and stateseq[t+1] != k:
score += np.log(alpha * beta[stateseq[t+1]] + model._counts_fromto(k,stateseq[t+1])) \
- np.log(alpha * (1-beta[k]) + model._counts_from(k))
# predictive likelihoods
for (data,otherdata), (dur,otherdurs) in self._local_group(t,k):
score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs)
return score
def _new_label_score(self,t,ks):
assert t > 0
score = 0.
# unpack
model = self.model
alpha = self.alpha_0
beta = self.beta.betavec
stateseq = self.stateseq
obs, durs = self.obs, self.dur
# left transition (only from counts, no to counts)
score += np.log(alpha) - np.log(alpha*(1.-beta[stateseq[t-1]])
+ model._counts_from(stateseq[t-1]))
# add in right transition (no counts)
if t < self.T-1:
score += np.log(beta[stateseq[t+1]])
# add in sum over k factor
if t < self.T-1:
betas = np.random.beta(1,self.beta.gamma_0,size=200)
betas[1:] *= (1-betas[:-1]).cumprod()
score += np.log(self.beta.remaining*(betas/(1-betas)).sum())
else:
score += np.log(self.beta.remaining)
# add in obs/dur scores of local pieces
for (data,otherdata), (dur,otherdurs) in self._local_group(t,NEW):
score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs)
return score
def _local_group(self,t,k):
'''
returns a sequence of length between 1 and 3, where each sequence element is
((data,otherdata), (dur,otherdurs))
'''
# temporarily modifies members, like self.stateseq and maybe self.data
assert self.stateseq[t] == SAMPLING
orig_stateseq = self.stateseq.copy()
# temporarily set stateseq to hypothetical stateseq
# so that we can get the indicator sequence
# TODO if i write the special stateseq class, this will need fixing
self.stateseq[t] = k
wholegroup, pieces = self._local_slices(self.stateseq,t)
self.stateseq[t] = SAMPLING
# build local group of statistics
localgroup = []
self.stateseq[wholegroup] = SAMPLING
for piece, val in pieces:
# get all the other data
otherdata, otherdurs = self.model._data_withlabel(val), self.model._durs_withlabel(val)
# add a piece to our localgroup
localgroup.append(((self.data[piece],otherdata),(piece.stop-piece.start,otherdurs)))
# remove the used piece from the exclusion
self.stateseq[piece] = orig_stateseq[piece]
# restore original views
self.stateseq = orig_stateseq
# return
return localgroup
@classmethod
def _local_slices(cls,stateseq,t):
'''
returns slices: wholegroup, (piece1, ...)
'''
A,B = fill(stateseq,t-1), fill(stateseq,t+1)
if A == B:
return A, ((A,stateseq[A.start]),)
elif A.start <= t < A.stop or B.start <= t < B.stop:
return slice(A.start,B.stop), [(x,stateseq[x.start]) for x in (A,B) if x.stop - x.start > 0]
else:
It = slice(t,t+1)
return slice(A.start,B.stop), [(x,stateseq[x.start]) for x in (A,It,B) if x.stop - x.start > 0]
#######################
# Utility Functions #
#######################
def fill(seq,t):
if t < 0:
return slice(0,0)
elif t > seq.shape[0]-1:
return slice(seq.shape[0],seq.shape[0])
else:
endindices, = np.where(np.diff(seq) != 0) # internal end indices (not incl -1 and T-1)
startindices = np.concatenate(((0,),endindices+1,(seq.shape[0],))) # incl 0 and T
idx = np.where(startindices <= t)[0][-1]
return slice(startindices[idx],startindices[idx+1])
def canonize(seq):
seq = seq.copy()
canondict = collections.defaultdict(itertools.count().next)
for idx,s in enumerate(seq):
seq[idx] = canondict[s]
reversedict = {}
for k,v in canondict.iteritems():
reversedict[v] = k
return seq, canondict, reversedict
class dummytrans(object):
def __init__(self,A):
self.A = A
def resample(self,*args,**kwargs):
pass
| 1.953125 | 2 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.