code
stringlengths 1
199k
|
|---|
import sys
import os
for path in [os.getcwd(),"SchemaExamples"]:
sys.path.insert( 1, path ) #Pickup libs from shipped lib directory
import logging
logging.basicConfig(level=logging.INFO) # dev_appserver.py --log_level debug .
log = logging.getLogger(__name__)
from schemaexamples import SchemaExamples, Example
SchemaExamples.loadExamplesFiles("default")
print("Loaded %d examples " % (SchemaExamples.count()))
log.info("Processing")
changedFiles=[]
changedCount = 0
for ex in SchemaExamples.allExamples(sort=True):
if not ex.hasValidId():
ex.setKey(Example.nextId())
changedCount += 1
if not ex.getMeta('file') in changedFiles:
changedFiles.append(ex.getMeta('file'))
filename = ""
f = None
examples = SchemaExamples.allExamples(sort=True)
log.info("Writing %s changed examples into %s files" % (changedCount,len(changedFiles)))
OUTFILESUFFIX = "" #Overwrite sourcefiles
for ex in examples:
source = ex.getMeta('file')
if source not in changedFiles:
continue
if source != filename:
if f:
f.close()
filename = source
fn = filename + OUTFILESUFFIX
log.info("Writing %s" % fn)
f = open(fn,"w")
f.write(ex.serialize())
f.write("\n")
if f:
f.close()
|
"""Handling e-mail messages."""
import datetime
import email.header
import email.message
import logging
import typing as t
import dateutil.parser
from .connection import Connection
_LOG = logging.getLogger(__name__)
def recode_header(raw_data: t.Union[bytes, str]) -> str:
"""Normalize the header value."""
decoded_data = email.header.decode_header(raw_data)
try:
return email.header.make_header(decoded_data)
except UnicodeDecodeError as err:
try:
return email.header.make_header([(decoded_data[0][0], 'utf-8')])
except:
_LOG.exception('both "%s" and "utf-8" fail to decode the header', decoded_data[0][1])
raise ValueError(f'after decoding {raw_data!r}, obtained {decoded_data!r}'
' which cannot be re-made into a header') from err
def is_name_and_address(text: str) -> bool:
return '<' in text and '>' in text
def split_name_and_address(text) -> tuple:
if is_name_and_address(text):
begin = text.rfind('<')
end = text.rfind('>')
assert begin < end
return text[begin + 1:end], text[:begin]
return text, None
def recode_timezone_info(dt: datetime.datetime):
name = dt.tzname()
dst = dt.dst()
dst = (' ' + dst) if dst != datetime.timedelta() else ''
if name == 'UTC':
return f'{name}{dst}'
offset = dt.utcoffset()
offset = ('+' if offset >= datetime.timedelta() else '') + str(offset.total_seconds() / 3600)
if name is None or not name:
return f'UTC{offset}{dst}'
return f'{name} (UTC{offset}{dst})'
class Message:
"""An e-mail message."""
def __init__(self, msg: email.message.EmailMessage = None, server: Connection = None,
folder: str = None, msg_id: int = None):
assert folder is None or isinstance(folder, str), type(folder)
assert msg_id is None or isinstance(msg_id, int), type(msg_id)
self._email_message = msg # type: email.message.EmailMessage
self._origin_server = server # type: Connection
self._origin_folder = folder # type: str
self._origin_id = msg_id # type: int
self.from_address = None # type: str
self.from_name = None # type: str
self.reply_to_address = None # type: str
self.reply_to_name = None # type: str
self.to_address = None # type: str
self.to_name = None # type: str
self.subject = None # type: str
self.datetime = None # type: datetime.datetime
self.timezone = None
self.local_date = None
self.local_time = None
self.received = []
self.return_path = None
self.envelope_to = None
self.message_id = None
self.content_type = None
self.other_headers = []
self.flags = set() # type: t.Set[str]
self.contents = []
self.attachments = []
if msg is not None:
self._init_headers_from_email_message(msg)
self._init_contents_from_email_message(msg)
@property
def date(self) -> datetime.date:
if self.datetime is None:
return None
return self.datetime.date()
@property
def time(self) -> datetime.time:
if self.datetime is None:
return None
return self.datetime.time()
@property
def is_read(self) -> bool:
return 'Seen' in self.flags
@property
def is_unread(self) -> bool:
return not self.is_read()
@property
def is_answered(self) -> bool:
return 'Answered' in self.flags
@property
def is_flagged(self) -> bool:
return 'Flagged' in self.flags
@property
def is_deleted(self) -> bool:
return 'Deleted' in self.flags
def _init_headers_from_email_message(self, msg: email.message.EmailMessage) -> None:
for key, value in msg.items():
self._init_header_from_keyvalue(key, value)
def _init_header_from_keyvalue(self, key: str, value: str) -> None:
if key == 'From':
self.from_address, self.from_name = split_name_and_address(str(recode_header(value)))
elif key == 'Reply-To':
self.reply_to_address, self.reply_to_name = split_name_and_address(
str(recode_header(value)))
elif key == 'To':
self.to_address, self.to_name = split_name_and_address(str(recode_header(value)))
elif key == 'Subject':
self.subject = str(recode_header(value))
elif key == 'Date':
self._init_datetime_from_header_value(value)
elif key == 'Received':
self.received.append(value)
elif key == 'Return-Path':
self.return_path = value
elif key == 'Envelope-To':
self.envelope_to = value
elif key == 'Message-Id':
self.message_id = value
elif key == 'Content-Type':
self.content_type = value
else:
self.other_headers.append((key, value))
def _init_datetime_from_header_value(self, value: str):
self.datetime = None
try:
self.datetime = dateutil.parser.parse(value)
except ValueError:
try:
self.datetime = dateutil.parser.parse(value, fuzzy=True)
_LOG.debug(
'dateutil failed to parse string "%s" into a date/time,'
' using fuzzy=True results in: %s', value, self.datetime, exc_info=1)
except ValueError:
_LOG.debug(
'dateutil failed to parse string "%s" into a date/time,'
' even using fuzzy=True', value, exc_info=1)
if self.datetime is not None:
self.timezone = recode_timezone_info(self.datetime)
def _init_contents_from_email_message(self, msg: email.message.EmailMessage) -> None:
if not msg.get_payload():
return
if msg.get_content_maintype() != 'multipart':
self._init_contents_part(msg)
return
content_type = msg.get_content_type()
parts = msg.get_payload()
if isinstance(parts, str):
_LOG.error('one of %i parts in a message is %s, but it has no subparts',
len(parts), content_type)
assert not parts, parts
return
assert isinstance(parts, list), type(parts)
assert parts
if content_type == 'multipart/alternative':
if len(parts) > 1:
_LOG.warning('taking last alternative of %i available in part type %s'
' - ignoring others', len(parts), content_type)
self._init_contents_from_email_message(parts[-1])
elif content_type == 'multipart/related':
if len(parts) > 1:
_LOG.warning('taking only first part of %i available in part type %s'
' - ignoring related parts', len(parts), content_type)
self._init_contents_from_email_message(parts[0])
elif content_type == 'multipart/mixed':
for part in parts:
self._init_contents_from_email_message(part)
else:
raise NotImplementedError(f'handling of "{content_type}" not implemented')
def _init_contents_part(self, part: email.message.Message):
content_type = part.get_content_type()
if content_type not in {'text/plain', 'text/html'}:
_LOG.info('treating message part with type %s as attachment', content_type)
self.attachments.append(part)
return
charset = part.get_content_charset()
if charset:
text = part.get_payload(decode=True)
try:
text = text.decode(charset)
except UnicodeDecodeError:
_LOG.exception('failed to decode %i-character text using encoding "%s"',
len(text), charset)
else:
text = part.get_payload()
try:
if isinstance(text, bytes):
text = text.decode('utf-8')
except UnicodeDecodeError:
_LOG.exception('failed to decode %i-character text using encoding "%s"',
len(text), 'utf-8')
if not isinstance(text, str):
_LOG.error('no content charset in a message %s in part %s -- attachment?',
self.str_headers_compact(), part.as_bytes()[:128])
self.attachments.append(part)
text = None
if not text:
return
self.contents.append(text)
def move_to(self, server: Connection, folder_name: str) -> None:
"""Move message to a specific folder on a specific server."""
assert isinstance(folder_name, str), type(folder_name)
if server is not self._origin_server:
from .imap_connection import IMAPConnection
assert isinstance(self._origin_server, IMAPConnection), type(self._origin_server)
assert isinstance(server, IMAPConnection), type(server)
parts = self._origin_server.retrieve_message_parts(
self._origin_id, ['UID', 'ENVELOPE', 'FLAGS', 'INTERNALDATE', 'BODY.PEEK[]'],
self._origin_folder)
_LOG.warning('moving %s between servers: from %s "%s" to %s "%s"',
self, self._origin_server, self._origin_folder, server, folder_name)
server.add_message(parts, folder_name)
self._origin_server.delete_message(self._origin_id, self._origin_folder)
return
if folder_name == self._origin_folder:
_LOG.debug('move_to() destination same as origin, nothing to do')
return
from .imap_connection import IMAPConnection
assert isinstance(self._origin_server, IMAPConnection), type(self._origin_server)
_LOG.warning('moving %s within same server %s: from "%s" to "%s"',
self, self._origin_server, self._origin_folder, folder_name)
self._origin_server.move_message(self._origin_id, folder_name, self._origin_folder)
def copy_to(self, server: Connection, folder: str) -> None:
raise NotImplementedError()
def send_via(self, server: Connection) -> None:
server.send_message(self._email_message)
def str_oneline(self):
return (f'{type(self).__name__}(From:{self.from_name}<{self.from_address}>,'
f'To:{self.to_name}<{self.to_address}>,Subject:{self.subject},'
f'DateAndTime:{self.datetime})')
def str_headers(self):
return '\n'.join([
f'From: {self.from_address}',
f' {self.from_name}',
f'Reply-To: {self.reply_to_address}',
f' {self.reply_to_name}',
f'To: {self.to_address}',
f' {self.to_name}',
f'Subject: {self.subject}',
f'Date: {self.date}',
f'Time: {self.time}',
f'Timezone: {self.timezone}',
f'Locally: {self.local_date}',
f' {self.local_time}',
# '',
# ' Received: {}'.format(self.received),
# ' Return-Path: {}'.format(self.return_path),
# ' Envelope-To: {}'.format(self.envelope_to),
# ' Message-Id: {}'.format(self.message_id),
# ' Content-Type: {}'.format(self.content_type),
# 'Other headers:',
# '\n'.join([' {}: {}'.format(k, v) for k, v in self.other_headers]),
])
def str_headers_compact(self):
return '\n'.join([
f'From: {self.from_address} {self.from_name}',
f'Reply-To: {self.reply_to_address} {self.reply_to_name}',
f'To: {self.to_address} {self.to_name}',
f'Subject: {self.subject}',
f'Datetime: {self.date} {self.time} {self.timezone}'
])
def str_quote(self):
raise NotImplementedError()
def str_forward(self):
raise NotImplementedError()
def str_complete(self):
return '\n'.join([
self.str_headers(),
'',
f'id: {self._origin_id}',
f'flags: {self.flags}',
'',
'contents{}:'.format(f' (multipart, {len(self.contents)} parts)'
if len(self.contents) > 1 else ''),
80*'=',
(80*'=' + '\n').join(self.contents),
80*'=',
])
def __str__(self):
return self.str_oneline()
def __repr__(self):
return self.str_headers_compact()
|
import proto # type: ignore
from google.ads.googleads.v9.enums.types import (
response_content_type as gage_response_content_type,
)
from google.ads.googleads.v9.resources.types import (
campaign_budget as gagr_campaign_budget,
)
from google.protobuf import field_mask_pb2 # type: ignore
from google.rpc import status_pb2 # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v9.services",
marshal="google.ads.googleads.v9",
manifest={
"GetCampaignBudgetRequest",
"MutateCampaignBudgetsRequest",
"CampaignBudgetOperation",
"MutateCampaignBudgetsResponse",
"MutateCampaignBudgetResult",
},
)
class GetCampaignBudgetRequest(proto.Message):
r"""Request message for
[CampaignBudgetService.GetCampaignBudget][google.ads.googleads.v9.services.CampaignBudgetService.GetCampaignBudget].
Attributes:
resource_name (str):
Required. The resource name of the campaign
budget to fetch.
"""
resource_name = proto.Field(proto.STRING, number=1,)
class MutateCampaignBudgetsRequest(proto.Message):
r"""Request message for
[CampaignBudgetService.MutateCampaignBudgets][google.ads.googleads.v9.services.CampaignBudgetService.MutateCampaignBudgets].
Attributes:
customer_id (str):
Required. The ID of the customer whose
campaign budgets are being modified.
operations (Sequence[google.ads.googleads.v9.services.types.CampaignBudgetOperation]):
Required. The list of operations to perform
on individual campaign budgets.
partial_failure (bool):
If true, successful operations will be
carried out and invalid operations will return
errors. If false, all operations will be carried
out in one transaction if and only if they are
all valid. Default is false.
validate_only (bool):
If true, the request is validated but not
executed. Only errors are returned, not results.
response_content_type (google.ads.googleads.v9.enums.types.ResponseContentTypeEnum.ResponseContentType):
The response content type setting. Determines
whether the mutable resource or just the
resource name should be returned post mutation.
"""
customer_id = proto.Field(proto.STRING, number=1,)
operations = proto.RepeatedField(
proto.MESSAGE, number=2, message="CampaignBudgetOperation",
)
partial_failure = proto.Field(proto.BOOL, number=3,)
validate_only = proto.Field(proto.BOOL, number=4,)
response_content_type = proto.Field(
proto.ENUM,
number=5,
enum=gage_response_content_type.ResponseContentTypeEnum.ResponseContentType,
)
class CampaignBudgetOperation(proto.Message):
r"""A single operation (create, update, remove) on a campaign
budget.
This message has `oneof`_ fields (mutually exclusive fields).
For each oneof, at most one member field can be set at the same time.
Setting any member of the oneof automatically clears all other
members.
.. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
Attributes:
update_mask (google.protobuf.field_mask_pb2.FieldMask):
FieldMask that determines which resource
fields are modified in an update.
create (google.ads.googleads.v9.resources.types.CampaignBudget):
Create operation: No resource name is
expected for the new budget.
This field is a member of `oneof`_ ``operation``.
update (google.ads.googleads.v9.resources.types.CampaignBudget):
Update operation: The campaign budget is
expected to have a valid resource name.
This field is a member of `oneof`_ ``operation``.
remove (str):
Remove operation: A resource name for the removed budget is
expected, in this format:
``customers/{customer_id}/campaignBudgets/{budget_id}``
This field is a member of `oneof`_ ``operation``.
"""
update_mask = proto.Field(
proto.MESSAGE, number=4, message=field_mask_pb2.FieldMask,
)
create = proto.Field(
proto.MESSAGE,
number=1,
oneof="operation",
message=gagr_campaign_budget.CampaignBudget,
)
update = proto.Field(
proto.MESSAGE,
number=2,
oneof="operation",
message=gagr_campaign_budget.CampaignBudget,
)
remove = proto.Field(proto.STRING, number=3, oneof="operation",)
class MutateCampaignBudgetsResponse(proto.Message):
r"""Response message for campaign budget mutate.
Attributes:
partial_failure_error (google.rpc.status_pb2.Status):
Errors that pertain to operation failures in the partial
failure mode. Returned only when partial_failure = true and
all errors occur inside the operations. If any errors occur
outside the operations (e.g. auth errors), we return an RPC
level error.
results (Sequence[google.ads.googleads.v9.services.types.MutateCampaignBudgetResult]):
All results for the mutate.
"""
partial_failure_error = proto.Field(
proto.MESSAGE, number=3, message=status_pb2.Status,
)
results = proto.RepeatedField(
proto.MESSAGE, number=2, message="MutateCampaignBudgetResult",
)
class MutateCampaignBudgetResult(proto.Message):
r"""The result for the campaign budget mutate.
Attributes:
resource_name (str):
Returned for successful operations.
campaign_budget (google.ads.googleads.v9.resources.types.CampaignBudget):
The mutated campaign budget with only mutable fields after
mutate. The field will only be returned when
response_content_type is set to "MUTABLE_RESOURCE".
"""
resource_name = proto.Field(proto.STRING, number=1,)
campaign_budget = proto.Field(
proto.MESSAGE, number=2, message=gagr_campaign_budget.CampaignBudget,
)
__all__ = tuple(sorted(__protobuf__.manifest))
|
import sys
data = sys.argv[1]
java_file = open("vsense-ide/VSenseSDK/src/vsense_app/VSenseApp.java", "w")
java_file.write(data)
'''def isfloat(x):
try:
a = float(x)
except ValueError:
return False
else:
return True
def isint(x):
try:
a = float(x)
b = int(a)
except ValueError:
return False
else:
return a == b
data = json.loads(sys.argv[1])
def forever(lines, value):
lines = "while(true){"
return lines
def end(lines, value):
lines += "}"
return lines
def repeat(lines, value):
lines += "for(int i=0;i<"+str(value)+";i++){"
return lines
def wait(lines, value):
lines += "try{Thread.sleep("+str(int(float(value)*1000))+");}catch(Exception e){System.out.println(e);}"
return lines
def init(lines, value):
if (str(value[1]) == 'integer'):
lines += "int "+str(value[0])+"=0;"
return lines
elif (str(value[1]) == 'float'):
lines += "double "+str(value[0])+"=0.0;"
return lines
elif (str(value[1]) == 'string'):
lines += "String "+str(value[0])+'="";'
return lines
def set_block(lines, value):
lines += ""+str(value)+"="
return lines
def var(lines, value):
lines += str(value[0])
if(str(value[1]) == "true"):
print value[1], 'dentro'
lines += ";"
return lines
def num(lines, value):
lines += str(value[0])
if(str(value[1]) == "true"):
lines += ";"
return lines
def text(lines, value):
lines += '"'+str(value[0])+'"'
if(str(value[1]) == "true"):
lines += ";"
return lines
def logic_operator(lines, value):
if(str(value[0]) == "and"):
lines += "&&"
if(str(value[0]) == "or"):
lines += "||"
if(str(value[0]) == "not"):
lines += "!"
return lines
def compare_operator(lines, value):
if(str(value[0]) == "="):
lines += "=="
else:
lines += str(value[0])
return lines
def math_operator(lines, value):
lines += str(value[0])
return lines
def if_block(lines, value):
lines += "if("
return lines
def then_block(lines, value):
lines += "){"
return lines
def else_block(lines, value):
lines += "}else{"
return lines
blocks = { 'forever' : forever,
'end' : end,
'repeat' : repeat,
'wait' : wait,
'init' : init,
'set' : set_block,
'var' : var,
'num' : num,
'text' : text,
'logic_operator' : logic_operator,
'compare_operator' : compare_operator,
'math_operator' : math_operator,
'if' : if_block,
'then' : then_block,
'else' : else_block
}
middleSource = ""
lines = ""
for i in range(len(data)):
id = str(data[i]['id'])
value = data[i]['value']
middleSource += blocks[id](lines, value)
templateOne = "import java.lang.Runtime;public class Main{public static void main(String args[]){"
templateTwo = "}}"
source = templateOne + middleSource + templateTwo'''
print "http://www.ebay.com"
|
from application.extensions import db
from configs.enum import TAG_TYPES
__all__ = ['Tag']
class Tag(db.Document):
meta = {
'db_alias': 'inventory_db',
'indexes': ['en']
}
en = db.StringField(required=True, unique=True)
cn = db.StringField()
kind = db.StringField(required=True, choices=TAG_TYPES, default=TAG_TYPES.CATEGORY)
def __unicode__(self):
return '%s' % self.en
@classmethod
def get_tags(cls):
return [dict(en=tag.en,
cn=tag.cn) for tag in Tag.objects.all()]
@classmethod
def get_tag_or_create(cls, en, cn=None):
if not Tag.objects(en=en):
Tag(en=en, cn=cn, kind=TAG_TYPES.CATEGORY).save()
@classmethod
def update_cn(cls, en, cn):
Tag.objects(en=en).update(set__cn=cn)
def to_json(self):
return dict(
id=str(self.id),
en=self.en,
cn=self.cn,
kind=self.kind)
|
from siconos.kernel import \
Model, MoreauJeanOSI, TimeDiscretisation, \
FrictionContact, NewtonImpactFrictionNSL
import siconos.kernel as sk
from siconos.mechanics.contact_detection.bullet import \
btConvexHullShape, btVector3, btCollisionObject, \
btBoxShape, btMatrix3x3, \
BulletSpaceFilter, \
BulletWeightedShape, BulletDS, BulletTimeStepping
from numpy import zeros
from numpy.linalg import norm
t0 = 0 # start time
T = 20 # end time
h = 0.005 # time step
g = 9.81 # gravity
theta = 0.5 # theta scheme
position_init = 10
velocity_init = 0
if (True):
box = btConvexHullShape()
box.addPoint(btVector3(-1.0, 1.0, -1.0))
box.addPoint(btVector3(-1.0, -1.0, -1.0))
box.addPoint(btVector3(-1.0, -1.0, 1.0))
box.addPoint(btVector3(-1.0, 1.0, 1.0))
box.addPoint(btVector3(1.0, 1.0, 1.0))
box.addPoint(btVector3(1.0, 1.0, -1.0))
box.addPoint(btVector3(1.0, -1.0, -1.0))
box.addPoint(btVector3(1.0, -1.0, 1.0))
else:
box = btBoxShape(btVector3(1.0, 1.0, 1.0))
box1 = BulletWeightedShape(box, 1.0)
body = BulletDS(box1,
[0, 0, position_init, 1., 0, 0, 0],
[0, 0, velocity_init, 0., 0., 0.])
weight = [0, 0, - box1.mass() * g]
body.setFExtPtr(weight)
bouncingBox = Model(t0, T)
bouncingBox.nonSmoothDynamicalSystem().insertDynamicalSystem(body)
osi = MoreauJeanOSI(theta)
osi.insertDynamicalSystem(body)
ground = btCollisionObject()
ground.setCollisionFlags(btCollisionObject.CF_STATIC_OBJECT)
groundShape = btBoxShape(btVector3(30, 30, .5))
basis = btMatrix3x3()
basis.setIdentity()
ground.getWorldTransform().setBasis(basis)
ground.setCollisionShape(groundShape)
ground.getWorldTransform().getOrigin().setZ(-.5)
timedisc = TimeDiscretisation(t0, h)
osnspb = FrictionContact(3)
osnspb.numericsSolverOptions().iparam[0] = 1000
osnspb.numericsSolverOptions().dparam[0] = 1e-5
osnspb.setMStorageType(1)
osnspb.setNumericsVerboseMode(False)
osnspb.setKeepLambdaAndYState(True)
nslaw = NewtonImpactFrictionNSL(0.8, 0., 0., 3)
broadphase = BulletSpaceFilter(bouncingBox)
broadphase.insert(nslaw, 0, 0)
broadphase.collisionConfiguration().setConvexConvexMultipointIterations()
broadphase.collisionConfiguration().setPlaneConvexMultipointIterations()
broadphase.addStaticObject(ground, 0)
simulation = BulletTimeStepping(timedisc)
simulation.insertIntegrator(osi)
simulation.insertNonSmoothProblem(osnspb)
bouncingBox.initialize(simulation)
N = (T - t0) / h
dataPlot = zeros((N+1, 4))
q = body.q()
v = body.velocity()
dataPlot[0, 0] = t0
dataPlot[0, 1] = q[2]
dataPlot[0, 2] = v[2]
k = 1
while(simulation.hasNextEvent()):
broadphase.buildInteractions(bouncingBox.currentTime())
simulation.computeOneStep()
dataPlot[k, 0] = simulation.nextTime()
dataPlot[k, 1] = q[2]
dataPlot[k, 2] = v[2]
if (broadphase.collisionWorld().getDispatcher().getNumManifolds() > 0):
if bouncingBox.nonSmoothDynamicalSystem().topology().\
numberOfIndexSet() > 1:
index1 = sk.interactions(simulation.indexSet(1))
if (len(index1) == 4):
dataPlot[k, 3] = norm(index1[0].lambda_(1)) + \
norm(index1[1].lambda_(1)) + norm(index1[2].lambda_(1)) + \
norm(index1[3].lambda_(1))
k += 1
simulation.nextStep()
from siconos.kernel import SimpleMatrix, getMatrix
from numpy.linalg import norm
ref = getMatrix(SimpleMatrix("result.ref"))
print("norm(dataPlot - ref) = {0}".format(norm(dataPlot - ref)))
if (norm(dataPlot - ref) > 1e-11):
print("Warning. The result is rather different from the reference file.")
from matplotlib.pyplot import subplot, title, plot, grid, show
subplot(511)
title('position')
plot(dataPlot[0:k, 0], dataPlot[0:k, 1])
grid()
subplot(513)
title('velocity')
plot(dataPlot[0:k, 0], dataPlot[0:k, 2])
grid()
subplot(515)
plot(dataPlot[0:k, 0], dataPlot[0:k, 3])
title('lambda')
grid()
show()
|
"""
Views for managing Nova floating IPs.
"""
import logging
from django import http
from django.contrib import messages
from django.utils.translation import ugettext as _
from horizon import api
from horizon import forms
from .forms import FloatingIpAssociate, FloatingIpAllocate
LOG = logging.getLogger(__name__)
class AssociateView(forms.ModalFormView):
form_class = FloatingIpAssociate
template_name = 'nova/access_and_security/floating_ips/associate.html'
context_object_name = 'floating_ip'
def get_object(self, *args, **kwargs):
ip_id = kwargs['ip_id']
try:
return api.tenant_floating_ip_get(self.request, ip_id)
except Exception as e:
LOG.exception('Error fetching floating ip with id "%s".' % ip_id)
messages.error(self.request,
_('Unable to associate floating ip: %s') % e)
raise http.Http404("Floating IP %s not available." % ip_id)
def get_initial(self):
instances = [(server.id, 'id: %s, name: %s' %
(server.id, server.name))
for server in api.server_list(self.request)]
return {'floating_ip_id': self.object.id,
'floating_ip': self.object.ip,
'instances': instances}
class AllocateView(forms.ModalFormView):
form_class = FloatingIpAllocate
template_name = 'nova/access_and_security/floating_ips/allocate.html'
context_object_name = 'floating_ip'
def get_initial(self):
pools = api.floating_ip_pools_list(self.request)
if pools:
pool_list = [(pool.name, pool.name)
for pool in api.floating_ip_pools_list(self.request)]
else:
pool_list = [(None, _("There are no Floating IP Pools"))]
return {'tenant_id': self.request.user.tenant_id,
'pool_list': pool_list}
|
"""template URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^web_app/', include('web_app.urls')),
url(r'^', views.default_site),
]
|
"""Test for MetricsPlotsAndValidationsEvaluator."""
import os
from absl.testing import parameterized
import apache_beam as beam
from apache_beam.testing import util
import numpy as np
import tensorflow as tf
from tensorflow_model_analysis import constants
from tensorflow_model_analysis.addons.fairness.metrics import lift
from tensorflow_model_analysis.api import model_eval_lib
from tensorflow_model_analysis.eval_saved_model import testutil
from tensorflow_model_analysis.eval_saved_model.example_trainers import dnn_classifier
from tensorflow_model_analysis.eval_saved_model.example_trainers import fixed_prediction_estimator_extra_fields
from tensorflow_model_analysis.eval_saved_model.example_trainers import linear_classifier
from tensorflow_model_analysis.eval_saved_model.example_trainers import multi_head
from tensorflow_model_analysis.evaluators import metrics_plots_and_validations_evaluator
from tensorflow_model_analysis.extractors import example_weights_extractor
from tensorflow_model_analysis.extractors import features_extractor
from tensorflow_model_analysis.extractors import labels_extractor
from tensorflow_model_analysis.extractors import legacy_predict_extractor
from tensorflow_model_analysis.extractors import predictions_extractor
from tensorflow_model_analysis.extractors import slice_key_extractor
from tensorflow_model_analysis.extractors import unbatch_extractor
from tensorflow_model_analysis.metrics import attributions
from tensorflow_model_analysis.metrics import binary_confusion_matrices
from tensorflow_model_analysis.metrics import calibration
from tensorflow_model_analysis.metrics import calibration_plot
from tensorflow_model_analysis.metrics import confusion_matrix_plot
from tensorflow_model_analysis.metrics import metric_specs
from tensorflow_model_analysis.metrics import metric_types
from tensorflow_model_analysis.metrics import ndcg
from tensorflow_model_analysis.post_export_metrics import metrics as metric_fns
from tensorflow_model_analysis.proto import config_pb2
from tensorflow_model_analysis.proto import validation_result_pb2
from tfx_bsl.tfxio import raw_tf_record
from tfx_bsl.tfxio import tensor_adapter
from tfx_bsl.tfxio import test_util
from google.protobuf import text_format
from tensorflow_metadata.proto.v0 import schema_pb2
_TF_MAJOR_VERSION = int(tf.version.VERSION.split('.')[0])
def _addExampleCountMetricCallback( # pylint: disable=invalid-name
features_dict, predictions_dict, labels_dict):
del features_dict
del labels_dict
metric_ops = {}
value_op, update_op = metric_fns.total(
tf.shape(input=predictions_dict['logits'])[0])
metric_ops['added_example_count'] = (value_op, update_op)
return metric_ops
class MetricsPlotsAndValidationsEvaluatorTest(
testutil.TensorflowModelAnalysisTest, parameterized.TestCase):
def _getExportDir(self):
return os.path.join(self._getTempDir(), 'export_dir')
def _getBaselineDir(self):
return os.path.join(self._getTempDir(), 'baseline_export_dir')
def _build_keras_model(self, model_name, model_dir, mul):
input_layer = tf.keras.layers.Input(shape=(1,), name='input_1')
output_layer = tf.keras.layers.Lambda(
lambda x, mul: x * mul, output_shape=(1,), arguments={'mul': mul})(
input_layer)
model = tf.keras.models.Model([input_layer], output_layer)
model.compile(
optimizer=tf.keras.optimizers.Adam(lr=.001),
loss=tf.keras.losses.BinaryCrossentropy(name='loss'),
metrics=['accuracy'])
model.save(model_dir, save_format='tf')
return self.createTestEvalSharedModel(
model_name=model_name, eval_saved_model_path=model_dir)
def testFilterAndSeparateComputations(self):
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(name='candidate', label_key='tips'),
config_pb2.ModelSpec(
name='baseline', label_key='tips', is_baseline=True)
],
cross_slicing_specs=[config_pb2.CrossSlicingSpec()])
metrics_specs = metric_specs.specs_from_metrics(
[
tf.keras.metrics.BinaryAccuracy(name='accuracy'),
tf.keras.metrics.AUC(name='auc', num_thresholds=10000),
tf.keras.metrics.AUC(
name='auc_precison_recall', curve='PR', num_thresholds=10000),
tf.keras.metrics.Precision(name='precision'),
tf.keras.metrics.Recall(name='recall'),
calibration.MeanLabel(name='mean_label'),
calibration.MeanPrediction(name='mean_prediction'),
calibration.Calibration(name='calibration'),
confusion_matrix_plot.ConfusionMatrixPlot(
name='confusion_matrix_plot'),
calibration_plot.CalibrationPlot(name='calibration_plot'),
lift.Lift(name='lift'),
],
model_names=['candidate', 'baseline'],
binarize=config_pb2.BinarizationOptions(class_ids={'values': [0, 5]}))
computations = metric_specs.to_computations(
metrics_specs, eval_config=eval_config)
non_derived, derived, cross_slice, ci_derived = metrics_plots_and_validations_evaluator._filter_and_separate_computations(
computations)
# 2 models x 2 classes x _binary_confusion_matrix_[0.5]_100,
# 2 models x 2 classes x _CalibrationHistogramCombiner
# 2 models x 2 classes x _calibration_historgram_27
# 2 models x 2 classes x _CompilableMetricsCombiner,
# 2 models x 2 classes x _WeightedLabelsPredictionsExamplesCombiner,
# 4 models x _ExampleCountCombiner
self.assertLen(non_derived, 20)
# 2 models x 2 classes x _binary_confusion_matrices_[0.5],
# 2 models x 2 classes x _binary_confusion_matrices_10000
# 2 models x 2 classes x _binary_confusion_matrices_confusion_matrix_plot
# 2 models x 2 classes x precision
# 2 models x 2 classes x recall
# 2 models x 2 classes x calibration
# 2 models x 2 classes x auc_precision_recall
# 2 models x 2 classes x mean_prediction
# 2 models x 2 classes x mean_label
# 2 models x 2 classes x confusion_matrix_plot
# 2 models x 2 classes x calibration_plot
# 2 models x 2 classes x auc
# 2 models x 2 classes x accuracy
self.assertLen(derived, 52)
# 2 models x 2 classes x lift
self.assertLen(cross_slice, 4)
# None of the metric has CIDerivedMetricComputation.
self.assertEmpty(ci_derived)
def testFilterAndSeparateComputationsWithCIDerivedMetrics(self):
def derived_metric_fn():
pass
def ci_derived_fn():
pass
computations = [
metric_types.DerivedMetricComputation([metric_types.MetricKey('key1')],
derived_metric_fn),
metric_types.CIDerivedMetricComputation(
[metric_types.MetricKey('key1')], ci_derived_fn),
metric_types.CIDerivedMetricComputation(
[metric_types.MetricKey('key1')], ci_derived_fn)
]
_, derived, _, ci_derived = metrics_plots_and_validations_evaluator._filter_and_separate_computations(
computations)
self.assertLen(derived, 1)
self.assertLen(ci_derived, 1)
def testEvaluateWithKerasAndValidateMetrics(self):
model_dir, baseline_dir = self._getExportDir(), self._getBaselineDir()
eval_shared_model = self._build_keras_model('candidate', model_dir, mul=0)
baseline_eval_shared_model = self._build_keras_model(
'baseline', baseline_dir, mul=1)
schema = text_format.Parse(
"""
tensor_representation_group {
key: ""
value {
tensor_representation {
key: "input_1"
value {
dense_tensor {
column_name: "input_1"
shape { dim { size: 1 } }
}
}
}
}
}
feature {
name: "input_1"
type: FLOAT
}
feature {
name: "label"
type: FLOAT
}
feature {
name: "example_weight"
type: FLOAT
}
feature {
name: "extra_feature"
type: BYTES
}
""", schema_pb2.Schema())
tfx_io = test_util.InMemoryTFExampleRecord(
schema=schema, raw_record_column_name=constants.ARROW_INPUT_COLUMN)
tensor_adapter_config = tensor_adapter.TensorAdapterConfig(
arrow_schema=tfx_io.ArrowSchema(),
tensor_representations=tfx_io.TensorRepresentations())
examples = [
self._makeExample(
input_1=0.0,
label=1.0,
example_weight=1.0,
extra_feature='non_model_feature'),
self._makeExample(
input_1=1.0,
label=0.0,
example_weight=0.5,
extra_feature='non_model_feature'),
]
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
name='candidate',
label_key='label',
example_weight_key='example_weight'),
config_pb2.ModelSpec(
name='baseline',
label_key='label',
example_weight_key='example_weight',
is_baseline=True)
],
slicing_specs=[config_pb2.SlicingSpec()],
metrics_specs=[
config_pb2.MetricsSpec(
metrics=[
config_pb2.MetricConfig(
class_name='ExampleCount',
# 2 > 10, NOT OK.
threshold=config_pb2.MetricThreshold(
value_threshold=config_pb2.GenericValueThreshold(
lower_bound={'value': 10}))),
],
model_names=['candidate', 'baseline'],
example_weights=config_pb2.ExampleWeightOptions(
unweighted=True)),
config_pb2.MetricsSpec(
metrics=[
config_pb2.MetricConfig(
class_name='WeightedExampleCount',
# 1.5 < 1, NOT OK.
threshold=config_pb2.MetricThreshold(
value_threshold=config_pb2.GenericValueThreshold(
upper_bound={'value': 1}))),
],
model_names=['candidate', 'baseline'],
example_weights=config_pb2.ExampleWeightOptions(weighted=True)),
config_pb2.MetricsSpec(
metrics=[
config_pb2.MetricConfig(
class_name='MeanLabel',
# 0 > 1 and 0 > 1?: NOT OK.
threshold=config_pb2.MetricThreshold(
change_threshold=config_pb2.GenericChangeThreshold(
direction=config_pb2.MetricDirection
.HIGHER_IS_BETTER,
relative={'value': 1},
absolute={'value': 1}))),
config_pb2.MetricConfig(
# MeanPrediction = (0+0)/(1+0.5) = 0
class_name='MeanPrediction',
# -.01 < 0 < .01, OK.
# Diff% = -.333/.333 = -100% < -99%, OK.
# Diff = 0 - .333 = -.333 < 0, OK.
threshold=config_pb2.MetricThreshold(
value_threshold=config_pb2.GenericValueThreshold(
upper_bound={'value': .01},
lower_bound={'value': -.01}),
change_threshold=config_pb2.GenericChangeThreshold(
direction=config_pb2.MetricDirection
.LOWER_IS_BETTER,
relative={'value': -.99},
absolute={'value': 0})))
],
thresholds={
'loss':
config_pb2.MetricThreshold(
value_threshold=config_pb2.GenericValueThreshold(
upper_bound={'value': 0}))
},
model_names=['candidate', 'baseline']),
],
)
eval_shared_models = [eval_shared_model, baseline_eval_shared_model]
extractors = [
features_extractor.FeaturesExtractor(
eval_config=eval_config,
tensor_representations=tensor_adapter_config.tensor_representations
),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(
eval_shared_model=eval_shared_models,
eval_config=eval_config,
tensor_adapter_config=tensor_adapter_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_models)
]
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
evaluations = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_validations(got):
try:
self.assertLen(got, 1)
got = got[0]
expected_metric_validations_per_slice = [
text_format.Parse(
"""
metric_key {
name: "loss"
model_name: "candidate"
}
metric_threshold {
value_threshold {
upper_bound {
value: 0.0
}
}
}
metric_value {
double_value {
value: 7.712474346160889
}
}
""", validation_result_pb2.ValidationFailure()),
text_format.Parse(
"""
metric_key {
name: "example_count"
model_name: "candidate"
example_weighted { }
}
metric_threshold {
value_threshold {
lower_bound {
value: 10.0
}
}
}
metric_value {
double_value {
value: 2.0
}
}
""", validation_result_pb2.ValidationFailure()),
text_format.Parse(
"""
metric_key {
name: "weighted_example_count"
model_name: "candidate"
example_weighted { value: true }
}
metric_threshold {
value_threshold {
upper_bound {
value: 1.0
}
}
}
metric_value {
double_value {
value: 1.5
}
}
""", validation_result_pb2.ValidationFailure()),
text_format.Parse(
"""
metric_key {
name: "mean_label"
model_name: "candidate"
is_diff: true
example_weighted { value: true }
}
metric_threshold {
change_threshold {
absolute {
value: 1.0
}
relative {
value: 1.0
}
direction: HIGHER_IS_BETTER
}
}
metric_value {
double_value {
value: 0.0
}
}
""", validation_result_pb2.ValidationFailure()),
]
# Loss not supported in TFv1
if _TF_MAJOR_VERSION < 2:
expected_metric_validations_per_slice[0].ClearField('metric_value')
expected_metric_validations_per_slice[0].message = (
'Metric not found.')
self.assertFalse(got.validation_ok)
self.assertLen(got.metric_validations_per_slice, 1)
self.assertLen(got.metric_validations_per_slice[0].failures,
len(expected_metric_validations_per_slice))
self.assertCountEqual(got.metric_validations_per_slice[0].failures,
expected_metric_validations_per_slice)
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(evaluations[constants.VALIDATIONS_KEY],
check_validations)
metric_filter = beam.metrics.metric.MetricsFilter().with_name(
'metric_computed_ExampleCount_v2_' + constants.TF_KERAS)
actual_metrics_count = pipeline.run().metrics().query(
filter=metric_filter)['counters'][0].committed
self.assertEqual(actual_metrics_count, 1)
def testEvaluateWithKerasAndDiffMetrics(self):
model_dir, baseline_dir = self._getExportDir(), self._getBaselineDir()
eval_shared_model = self._build_keras_model('candidate', model_dir, mul=0)
baseline_eval_shared_model = self._build_keras_model(
'baseline', baseline_dir, mul=1)
schema = text_format.Parse(
"""
tensor_representation_group {
key: ""
value {
tensor_representation {
key: "input_1"
value {
dense_tensor {
column_name: "input_1"
shape { dim { size: 1 } }
}
}
}
}
}
feature {
name: "input_1"
type: FLOAT
}
feature {
name: "label"
type: FLOAT
}
feature {
name: "example_weight"
type: FLOAT
}
feature {
name: "extra_feature"
type: BYTES
}
""", schema_pb2.Schema())
tfx_io = test_util.InMemoryTFExampleRecord(
schema=schema, raw_record_column_name=constants.ARROW_INPUT_COLUMN)
tensor_adapter_config = tensor_adapter.TensorAdapterConfig(
arrow_schema=tfx_io.ArrowSchema(),
tensor_representations=tfx_io.TensorRepresentations())
examples = [
self._makeExample(
input_1=0.0,
label=1.0,
example_weight=1.0,
extra_feature='non_model_feature'),
self._makeExample(
input_1=1.0,
label=0.0,
example_weight=0.5,
extra_feature='non_model_feature'),
]
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
name='candidate',
label_key='label',
example_weight_key='example_weight'),
config_pb2.ModelSpec(
name='baseline',
label_key='label',
example_weight_key='example_weight',
is_baseline=True)
],
slicing_specs=[config_pb2.SlicingSpec()],
metrics_specs=metric_specs.specs_from_metrics(
[
calibration.MeanLabel('mean_label'),
calibration.MeanPrediction('mean_prediction')
],
model_names=['candidate', 'baseline']))
eval_shared_models = [eval_shared_model, baseline_eval_shared_model]
extractors = [
features_extractor.FeaturesExtractor(
eval_config=eval_config,
tensor_representations=tensor_adapter_config.tensor_representations
),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(
eval_shared_model=eval_shared_models,
eval_config=eval_config,
tensor_adapter_config=tensor_adapter_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_models)
]
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 1)
got_slice_key, got_metrics = got[0]
self.assertEqual(got_slice_key, ())
# check only the diff metrics.
weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count',
model_name='candidate',
is_diff=True,
example_weighted=True)
prediction_key = metric_types.MetricKey(
name='mean_prediction',
model_name='candidate',
is_diff=True,
example_weighted=True)
label_key = metric_types.MetricKey(
name='mean_label',
model_name='candidate',
is_diff=True,
example_weighted=True)
self.assertDictElementsAlmostEqual(
got_metrics, {
weighted_example_count_key: 0,
label_key: 0,
prediction_key: 0 - (0 * 1 + 1 * 0.5) / (1 + 0.5)
})
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(
metrics[constants.METRICS_KEY], check_metrics, label='metrics')
def testEvaluateWithSlicing(self):
temp_export_dir = self._getExportDir()
_, export_dir = (
fixed_prediction_estimator_extra_fields
.simple_fixed_prediction_estimator_extra_fields(None, temp_export_dir))
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
label_key='label', example_weight_key='fixed_float')
],
slicing_specs=[
config_pb2.SlicingSpec(),
config_pb2.SlicingSpec(feature_keys=['fixed_string']),
],
metrics_specs=metric_specs.specs_from_metrics([
calibration.MeanLabel('mean_label'),
calibration.MeanPrediction('mean_prediction')
]))
eval_shared_model = self.createTestEvalSharedModel(
eval_saved_model_path=export_dir)
extractors = [
legacy_predict_extractor.PredictExtractor(
eval_shared_model=eval_shared_model, eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
# fixed_float used as example_weight key
examples = [
self._makeExample(
prediction=0.2,
label=1.0,
fixed_int=1,
fixed_float=1.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.8,
label=0.0,
fixed_int=1,
fixed_float=1.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.5,
label=0.0,
fixed_int=2,
fixed_float=2.0,
fixed_string='fixed_string2')
]
tfx_io = raw_tf_record.RawBeamRecordTFXIO(
physical_format='inmemory',
raw_record_column_name=constants.ARROW_INPUT_COLUMN,
telemetry_descriptors=['TFMATest'])
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 3)
slices = {}
for slice_key, value in got:
slices[slice_key] = value
overall_slice = ()
fixed_string1_slice = (('fixed_string', b'fixed_string1'),)
fixed_string2_slice = (('fixed_string', b'fixed_string2'),)
self.asssertCountEqual(
list(slices.keys()),
[overall_slice, fixed_string1_slice, fixed_string2_slice])
weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count', example_weighted=True)
label_key = metric_types.MetricKey(
name='mean_label', example_weighted=True)
pred_key = metric_types.MetricKey(
name='mean_prediction', example_weighted=True)
self.assertDictElementsAlmostEqual(
slices[overall_slice], {
weighted_example_count_key: 4.0,
label_key: (1.0 + 0.0 + 2 * 0.0) / (1.0 + 1.0 + 2.0),
pred_key: (0.2 + 0.8 + 2 * 0.5) / (1.0 + 1.0 + 2.0),
})
self.assertDictElementsAlmostEqual(
slices[fixed_string1_slice], {
weighted_example_count_key: 2.0,
label_key: (1.0 + 0.0) / (1.0 + 1.0),
pred_key: (0.2 + 0.8) / (1.0 + 1.0),
})
self.assertDictElementsAlmostEqual(
slices[fixed_string2_slice], {
weighted_example_count_key: 2.0,
label_key: (2 * 0.0) / 2.0,
pred_key: (2 * 0.5) / 2.0,
})
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(
metrics[constants.METRICS_KEY], check_metrics, label='metrics')
def testEvaluateWithAttributions(self):
eval_config = config_pb2.EvalConfig(
model_specs=[config_pb2.ModelSpec()],
metrics_specs=[
config_pb2.MetricsSpec(metrics=[
config_pb2.MetricConfig(class_name=attributions
.TotalAttributions().__class__.__name__)
])
],
options=config_pb2.Options(
disabled_outputs={'values': ['eval_config_pb2.json']}))
extractors = [slice_key_extractor.SliceKeyExtractor()]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(eval_config=eval_config)
]
example1 = {
'labels': None,
'predictions': None,
'example_weights': np.array(1.0),
'features': {},
'attributions': {
'feature1': 1.1,
'feature2': 1.2
}
}
example2 = {
'labels': None,
'predictions': None,
'example_weights': np.array(1.0),
'features': {},
'attributions': {
'feature1': 2.1,
'feature2': 2.2
}
}
example3 = {
'labels': None,
'predictions': None,
'example_weights': np.array(1.0),
'features': {},
'attributions': {
'feature1': np.array([3.1]),
'feature2': np.array([3.2])
}
}
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
results = (
pipeline
| 'Create' >> beam.Create([example1, example2, example3])
| 'ExtractEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_attributions(got):
try:
self.assertLen(got, 1)
got_slice_key, got_attributions = got[0]
self.assertEqual(got_slice_key, ())
total_attributions_key = metric_types.MetricKey(
name='total_attributions')
self.assertIn(total_attributions_key, got_attributions)
self.assertDictElementsAlmostEqual(
got_attributions[total_attributions_key], {
'feature1': (1.1 + 2.1 + 3.1),
'feature2': (1.2 + 2.2 + 3.2)
})
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(
results[constants.ATTRIBUTIONS_KEY],
check_attributions,
label='attributions')
def testEvaluateWithConfidenceIntervals(self):
# NOTE: This test does not actually test that confidence intervals are
# accurate it only tests that the proto output by the test is well formed.
# This test would pass if the confidence interval implementation did
# nothing at all except compute the unsampled value.
temp_export_dir = self._getExportDir()
_, export_dir = (
fixed_prediction_estimator_extra_fields
.simple_fixed_prediction_estimator_extra_fields(None, temp_export_dir))
options = config_pb2.Options()
options.compute_confidence_intervals.value = True
options.confidence_intervals.method = (
config_pb2.ConfidenceIntervalOptions.POISSON_BOOTSTRAP)
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
label_key='label', example_weight_key='fixed_float')
],
slicing_specs=[
config_pb2.SlicingSpec(),
config_pb2.SlicingSpec(feature_keys=['fixed_string']),
],
metrics_specs=metric_specs.specs_from_metrics([
calibration.MeanLabel('mean_label'),
calibration.MeanPrediction('mean_prediction')
]),
options=options)
eval_shared_model = self.createTestEvalSharedModel(
eval_saved_model_path=export_dir, tags=[tf.saved_model.SERVING])
extractors = [
features_extractor.FeaturesExtractor(eval_config),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(
eval_shared_model=eval_shared_model, eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
# fixed_float used as example_weight key
examples = [
self._makeExample(
prediction=0.2,
label=1.0,
fixed_int=1,
fixed_float=1.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.8,
label=0.0,
fixed_int=1,
fixed_float=1.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.5,
label=0.0,
fixed_int=2,
fixed_float=2.0,
fixed_string='fixed_string2')
]
tfx_io = test_util.InMemoryTFExampleRecord(
raw_record_column_name=constants.ARROW_INPUT_COLUMN)
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 3)
slices = {}
for slice_key, value in got:
slices[slice_key] = value
overall_slice = ()
fixed_string1_slice = (('fixed_string', 'fixed_string1'),)
fixed_string2_slice = (('fixed_string', 'fixed_string2'),)
self.assertCountEqual(
list(slices.keys()),
[overall_slice, fixed_string1_slice, fixed_string2_slice])
example_count_key = metric_types.MetricKey(name='example_count')
weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count', example_weighted=True)
label_key = metric_types.MetricKey(
name='mean_label', example_weighted=True)
pred_key = metric_types.MetricKey(
name='mean_prediction', example_weighted=True)
self.assertDictElementsAlmostEqual(slices[overall_slice], {
example_count_key: 3,
weighted_example_count_key: 4.0,
})
self.assertDictElementsWithTDistributionAlmostEqual(
slices[overall_slice], {
label_key: (1.0 + 0.0 + 2 * 0.0) / (1.0 + 1.0 + 2.0),
pred_key: (0.2 + 0.8 + 2 * 0.5) / (1.0 + 1.0 + 2.0),
})
self.assertDictElementsAlmostEqual(slices[fixed_string1_slice], {
example_count_key: 2,
weighted_example_count_key: 2.0,
})
self.assertDictElementsWithTDistributionAlmostEqual(
slices[fixed_string1_slice], {
label_key: (1.0 + 0.0) / (1.0 + 1.0),
pred_key: (0.2 + 0.8) / (1.0 + 1.0),
})
self.assertDictElementsAlmostEqual(slices[fixed_string2_slice], {
example_count_key: 1,
weighted_example_count_key: 2.0,
})
self.assertDictElementsWithTDistributionAlmostEqual(
slices[fixed_string2_slice], {
label_key: (2 * 0.0) / 2.0,
pred_key: (2 * 0.5) / 2.0,
})
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(
metrics[constants.METRICS_KEY], check_metrics, label='metrics')
def testEvaluateWithJackknife(self):
temp_export_dir = self._getExportDir()
_, export_dir = (
fixed_prediction_estimator_extra_fields
.simple_fixed_prediction_estimator_extra_fields(None, temp_export_dir))
options = config_pb2.Options()
options.include_default_metrics.value = False
options.compute_confidence_intervals.value = True
options.confidence_intervals.method = (
config_pb2.ConfidenceIntervalOptions.JACKKNIFE)
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
label_key='label', example_weight_key='fixed_float')
],
slicing_specs=[
config_pb2.SlicingSpec(),
config_pb2.SlicingSpec(feature_keys=['fixed_string']),
],
metrics_specs=metric_specs.specs_from_metrics([
calibration.MeanLabel('mean_label'),
calibration.MeanPrediction('mean_prediction')
]),
options=options)
eval_shared_model = self.createTestEvalSharedModel(
eval_saved_model_path=export_dir, tags=[tf.saved_model.SERVING])
extractors = [
features_extractor.FeaturesExtractor(eval_config),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(
eval_shared_model=eval_shared_model, eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
# fixed_float used as example_weight key
examples = [
self._makeExample(
prediction=0.2,
label=1.0,
fixed_int=1,
fixed_float=1.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.8,
label=0.0,
fixed_int=1,
fixed_float=1.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.5,
label=0.0,
fixed_int=2,
fixed_float=2.0,
fixed_string='fixed_string2')
]
tfx_io = test_util.InMemoryTFExampleRecord(
raw_record_column_name=constants.ARROW_INPUT_COLUMN)
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics = (
pipeline
| 'Create' >> beam.Create(
[e.SerializeToString() for e in examples * 1000])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 3)
slices = {}
for slice_key, value in got:
slices[slice_key] = value
overall_slice = ()
fixed_string1_slice = (('fixed_string', 'fixed_string1'),)
fixed_string2_slice = (('fixed_string', 'fixed_string2'),)
self.assertCountEqual(
list(slices.keys()),
[overall_slice, fixed_string1_slice, fixed_string2_slice])
example_count_key = metric_types.MetricKey(name='example_count')
weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count', example_weighted=True)
label_key = metric_types.MetricKey(
name='mean_label', example_weighted=True)
pred_key = metric_types.MetricKey(
name='mean_prediction', example_weighted=True)
self.assertLen(slices[overall_slice], 4)
self.assertDictElementsAlmostEqual(slices[overall_slice], {
example_count_key: 3000,
weighted_example_count_key: 4000.0
})
self.assertDictElementsWithTDistributionAlmostEqual(
slices[overall_slice], {
label_key: (1.0 + 0.0 + 2 * 0.0) / (1.0 + 1.0 + 2.0),
pred_key: (0.2 + 0.8 + 2 * 0.5) / (1.0 + 1.0 + 2.0),
})
self.assertDictElementsAlmostEqual(
slices[fixed_string1_slice], {weighted_example_count_key: 2000.0})
self.assertDictElementsWithTDistributionAlmostEqual(
slices[fixed_string1_slice], {
label_key: (1.0 + 0.0) / (1.0 + 1.0),
pred_key: (0.2 + 0.8) / (1.0 + 1.0),
})
self.assertDictElementsAlmostEqual(
slices[fixed_string2_slice], {weighted_example_count_key: 2000.0})
self.assertDictElementsWithTDistributionAlmostEqual(
slices[fixed_string2_slice], {
label_key: (2 * 0.0) / 2.0,
pred_key: (2 * 0.5) / 2.0,
})
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(metrics[constants.METRICS_KEY], check_metrics)
def testEvaluateWithJackknifeAndDiffMetrics(self):
model_dir, baseline_dir = self._getExportDir(), self._getBaselineDir()
eval_shared_model = self._build_keras_model('candidate', model_dir, mul=0)
baseline_eval_shared_model = self._build_keras_model(
'baseline', baseline_dir, mul=1)
options = config_pb2.Options()
options.compute_confidence_intervals.value = True
options.confidence_intervals.method = (
config_pb2.ConfidenceIntervalOptions.JACKKNIFE)
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
name='candidate',
label_key='label',
example_weight_key='example_weight'),
config_pb2.ModelSpec(
name='baseline',
label_key='label',
example_weight_key='example_weight',
is_baseline=True)
],
slicing_specs=[config_pb2.SlicingSpec()],
metrics_specs=metric_specs.specs_from_metrics(
[
calibration.MeanLabel('mean_label'),
calibration.MeanPrediction('mean_prediction')
],
model_names=['candidate', 'baseline']),
options=options)
eval_shared_models = {
'candidate': eval_shared_model,
'baseline': baseline_eval_shared_model
}
schema = text_format.Parse(
"""
tensor_representation_group {
key: ""
value {
tensor_representation {
key: "input_1"
value {
dense_tensor {
column_name: "input_1"
shape { dim { size: 1 } }
}
}
}
}
}
feature {
name: "input_1"
type: FLOAT
}
feature {
name: "label"
type: FLOAT
}
feature {
name: "example_weight"
type: FLOAT
}
feature {
name: "extra_feature"
type: BYTES
}
""", schema_pb2.Schema())
tfx_io = test_util.InMemoryTFExampleRecord(
schema=schema, raw_record_column_name=constants.ARROW_INPUT_COLUMN)
tensor_adapter_config = tensor_adapter.TensorAdapterConfig(
arrow_schema=tfx_io.ArrowSchema(),
tensor_representations=tfx_io.TensorRepresentations())
examples = [
self._makeExample(
input_1=0.0,
label=1.0,
example_weight=1.0,
extra_feature='non_model_feature'),
self._makeExample(
input_1=1.0,
label=0.0,
example_weight=0.5,
extra_feature='non_model_feature'),
]
extractors = [
features_extractor.FeaturesExtractor(
eval_config=eval_config,
tensor_representations=tensor_adapter_config.tensor_representations
),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(
eval_shared_model=eval_shared_models,
eval_config=eval_config,
tensor_adapter_config=tensor_adapter_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_models)
]
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics = (
pipeline
| 'Create' >> beam.Create(
[e.SerializeToString() for e in examples * 1000])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 1)
got_slice_key, got_metrics = got[0]
self.assertEqual(got_slice_key, ())
# check only the diff metrics.
weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count',
model_name='candidate',
is_diff=True,
example_weighted=True)
prediction_key = metric_types.MetricKey(
name='mean_prediction',
model_name='candidate',
is_diff=True,
example_weighted=True)
label_key = metric_types.MetricKey(
name='mean_label',
model_name='candidate',
is_diff=True,
example_weighted=True)
self.assertDictElementsWithTDistributionAlmostEqual(
got_metrics, {
weighted_example_count_key: 0,
label_key: 0,
prediction_key: 0 - (0 * 1 + 1 * 0.5) / (1 + 0.5)
})
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(metrics[constants.METRICS_KEY], check_metrics)
def testEvaluateWithRegressionModel(self):
temp_export_dir = self._getExportDir()
_, export_dir = (
fixed_prediction_estimator_extra_fields
.simple_fixed_prediction_estimator_extra_fields(None, temp_export_dir))
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
label_key='label', example_weight_key='fixed_float')
],
slicing_specs=[config_pb2.SlicingSpec()],
metrics_specs=metric_specs.specs_from_metrics([
calibration.MeanLabel('mean_label'),
calibration.MeanPrediction('mean_prediction')
]))
eval_shared_model = self.createTestEvalSharedModel(
eval_saved_model_path=export_dir, tags=[tf.saved_model.SERVING])
extractors = [
features_extractor.FeaturesExtractor(eval_config),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(
eval_shared_model=eval_shared_model, eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
# fixed_float used as example_weight key
examples = [
self._makeExample(
prediction=0.2,
label=1.0,
fixed_int=1,
fixed_float=1.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.8,
label=0.0,
fixed_int=1,
fixed_float=1.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.5,
label=0.0,
fixed_int=2,
fixed_float=2.0,
fixed_string='fixed_string2')
]
tfx_io = test_util.InMemoryTFExampleRecord(
raw_record_column_name=constants.ARROW_INPUT_COLUMN)
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 1)
got_slice_key, got_metrics = got[0]
example_count_key = metric_types.MetricKey(name='example_count')
weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count', example_weighted=True)
label_key = metric_types.MetricKey(
name='mean_label', example_weighted=True)
pred_key = metric_types.MetricKey(
name='mean_prediction', example_weighted=True)
self.assertEqual(got_slice_key, ())
self.assertDictElementsAlmostEqual(
got_metrics, {
example_count_key: 3,
weighted_example_count_key: 4.0,
label_key: (1.0 + 0.0 + 2 * 0.0) / (1.0 + 1.0 + 2.0),
pred_key: (0.2 + 0.8 + 2 * 0.5) / (1.0 + 1.0 + 2.0),
})
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(
metrics[constants.METRICS_KEY], check_metrics, label='metrics')
def testEvaluateWithCrossSliceLiftMetric(self):
temp_export_dir = self._getExportDir()
_, export_dir = (
fixed_prediction_estimator_extra_fields
.simple_fixed_prediction_estimator_extra_fields(None, temp_export_dir))
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
label_key='label', example_weight_key='fixed_float')
],
slicing_specs=[
config_pb2.SlicingSpec(
feature_values={'fixed_string': 'fixed_string1'}),
config_pb2.SlicingSpec(
feature_values={'fixed_string': 'fixed_string2'})
],
cross_slicing_specs=[
config_pb2.CrossSlicingSpec(
baseline_spec=config_pb2.SlicingSpec(
feature_values={'fixed_string': 'fixed_string1'}),
slicing_specs=[
config_pb2.SlicingSpec(
feature_values={'fixed_string': 'fixed_string2'})
]),
],
metrics_specs=metric_specs.specs_from_metrics(
[lift.Lift(num_buckets=3)]))
eval_shared_model = self.createTestEvalSharedModel(
eval_saved_model_path=export_dir, tags=[tf.saved_model.SERVING])
extractors = [
features_extractor.FeaturesExtractor(eval_config),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(
eval_shared_model=eval_shared_model, eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
# fixed_float used as example_weight key
examples = [
self._makeExample(
prediction=0.1,
label=0.0,
fixed_int=1,
fixed_float=3.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.5,
label=0.3,
fixed_int=1,
fixed_float=5.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.8,
label=0.6,
fixed_int=2,
fixed_float=2.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.3,
label=0.9,
fixed_int=1,
fixed_float=8.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.9,
label=1.0,
fixed_int=1,
fixed_float=3.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.8,
label=0.0,
fixed_int=2,
fixed_float=1.0,
fixed_string='fixed_string2'),
self._makeExample(
prediction=0.3,
label=0.2,
fixed_int=1,
fixed_float=2.0,
fixed_string='fixed_string2'),
self._makeExample(
prediction=0.5,
label=0.5,
fixed_int=1,
fixed_float=5.0,
fixed_string='fixed_string2'),
self._makeExample(
prediction=0.4,
label=0.7,
fixed_int=2,
fixed_float=2.0,
fixed_string='fixed_string2'),
self._makeExample(
prediction=0.3,
label=1.0,
fixed_int=2,
fixed_float=3.0,
fixed_string='fixed_string2')
]
tfx_io = test_util.InMemoryTFExampleRecord(
raw_record_column_name=constants.ARROW_INPUT_COLUMN)
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 3)
example_count_key = metric_types.MetricKey(name='example_count')
weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count', example_weighted=True)
lift_key = metric_types.MetricKey(
name='lift@3', example_weighted=True)
for slice_key, metrics in got:
if slice_key == (('fixed_string', 'fixed_string1'),):
self.assertDictElementsAlmostEqual(metrics, {
example_count_key: 5.0,
weighted_example_count_key: 21.0,
})
elif slice_key == (('fixed_string', 'fixed_string2'),):
self.assertDictElementsAlmostEqual(metrics, {
weighted_example_count_key: 13.0,
example_count_key: 5.0,
})
else:
self.assertDictElementsAlmostEqual(
metrics, {
example_count_key: 0.0,
weighted_example_count_key: 8.0,
lift_key: -0.211538456165,
})
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(
metrics[constants.METRICS_KEY], check_metrics, label='metrics')
def testEvaluateWithBinaryClassificationModel(self):
n_classes = 2
temp_export_dir = self._getExportDir()
_, export_dir = dnn_classifier.simple_dnn_classifier(
None, temp_export_dir, n_classes=n_classes)
# Add mean_label, example_count, weighted_example_count, calibration_plot
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(label_key='label', example_weight_key='age')
],
slicing_specs=[config_pb2.SlicingSpec()],
metrics_specs=metric_specs.specs_from_metrics([
calibration.MeanLabel('mean_label'),
calibration_plot.CalibrationPlot(
name='calibration_plot', num_buckets=10)
]))
eval_shared_model = self.createTestEvalSharedModel(
eval_saved_model_path=export_dir, tags=[tf.saved_model.SERVING])
extractors = [
features_extractor.FeaturesExtractor(eval_config),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(
eval_shared_model=eval_shared_model, eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
examples = [
self._makeExample(age=1.0, language='english', label=0.0),
self._makeExample(age=2.0, language='chinese', label=1.0),
self._makeExample(age=3.0, language='chinese', label=0.0),
]
tfx_io = test_util.InMemoryTFExampleRecord(
raw_record_column_name=constants.ARROW_INPUT_COLUMN)
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics_and_plots = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 1)
got_slice_key, got_metrics = got[0]
self.assertEqual(got_slice_key, ())
example_count_key = metric_types.MetricKey(name='example_count')
weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count', example_weighted=True)
label_key = metric_types.MetricKey(
name='mean_label', example_weighted=True)
self.assertDictElementsAlmostEqual(
got_metrics, {
example_count_key: 3,
weighted_example_count_key: (1.0 + 2.0 + 3.0),
label_key: (0 * 1.0 + 1 * 2.0 + 0 * 3.0) / (1.0 + 2.0 + 3.0),
})
except AssertionError as err:
raise util.BeamAssertException(err)
def check_plots(got):
try:
self.assertLen(got, 1)
got_slice_key, got_plots = got[0]
self.assertEqual(got_slice_key, ())
plot_key = metric_types.PlotKey(
'calibration_plot', example_weighted=True)
self.assertIn(plot_key, got_plots)
# 10 buckets + 2 for edge cases
self.assertLen(got_plots[plot_key].buckets, 12)
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(
metrics_and_plots[constants.METRICS_KEY],
check_metrics,
label='metrics')
util.assert_that(
metrics_and_plots[constants.PLOTS_KEY], check_plots, label='plots')
def testEvaluateWithMultiClassModel(self):
n_classes = 3
temp_export_dir = self._getExportDir()
_, export_dir = dnn_classifier.simple_dnn_classifier(
None, temp_export_dir, n_classes=n_classes)
# Add example_count and weighted_example_count
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(label_key='label', example_weight_key='age')
],
slicing_specs=[config_pb2.SlicingSpec()],
metrics_specs=metric_specs.specs_from_metrics(
[calibration.MeanLabel('mean_label')],
binarize=config_pb2.BinarizationOptions(
class_ids={'values': range(n_classes)})))
eval_shared_model = self.createTestEvalSharedModel(
eval_saved_model_path=export_dir, tags=[tf.saved_model.SERVING])
extractors = [
features_extractor.FeaturesExtractor(eval_config),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(
eval_shared_model=eval_shared_model, eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
examples = [
self._makeExample(age=1.0, language='english', label=0),
self._makeExample(age=2.0, language='chinese', label=1),
self._makeExample(age=3.0, language='english', label=2),
self._makeExample(age=4.0, language='chinese', label=1),
]
tfx_io = test_util.InMemoryTFExampleRecord(
raw_record_column_name=constants.ARROW_INPUT_COLUMN)
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 1)
got_slice_key, got_metrics = got[0]
example_count_key = metric_types.MetricKey(name='example_count')
weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count', example_weighted=True)
label_key_class_0 = metric_types.MetricKey(
name='mean_label',
sub_key=metric_types.SubKey(class_id=0),
example_weighted=True)
label_key_class_1 = metric_types.MetricKey(
name='mean_label',
sub_key=metric_types.SubKey(class_id=1),
example_weighted=True)
label_key_class_2 = metric_types.MetricKey(
name='mean_label',
sub_key=metric_types.SubKey(class_id=2),
example_weighted=True)
self.assertEqual(got_slice_key, ())
self.assertDictElementsAlmostEqual(
got_metrics, {
example_count_key:
4,
weighted_example_count_key: (1.0 + 2.0 + 3.0 + 4.0),
label_key_class_0: (1 * 1.0 + 0 * 2.0 + 0 * 3.0 + 0 * 4.0) /
(1.0 + 2.0 + 3.0 + 4.0),
label_key_class_1: (0 * 1.0 + 1 * 2.0 + 0 * 3.0 + 1 * 4.0) /
(1.0 + 2.0 + 3.0 + 4.0),
label_key_class_2: (0 * 1.0 + 0 * 2.0 + 1 * 3.0 + 0 * 4.0) /
(1.0 + 2.0 + 3.0 + 4.0)
})
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(
metrics[constants.METRICS_KEY], check_metrics, label='metrics')
def testEvaluateWithMultiOutputModel(self):
temp_export_dir = self._getExportDir()
_, export_dir = multi_head.simple_multi_head(None, temp_export_dir)
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
label_keys={
'chinese_head': 'chinese_label',
'english_head': 'english_label',
'other_head': 'other_label'
},
example_weight_keys={
'chinese_head': 'age',
'english_head': 'age',
'other_head': 'age'
})
],
slicing_specs=[config_pb2.SlicingSpec()],
metrics_specs=metric_specs.specs_from_metrics({
'chinese_head': [calibration.MeanLabel('mean_label')],
'english_head': [calibration.MeanLabel('mean_label')],
'other_head': [calibration.MeanLabel('mean_label')],
}))
eval_shared_model = self.createTestEvalSharedModel(
eval_saved_model_path=export_dir, tags=[tf.saved_model.SERVING])
extractors = [
features_extractor.FeaturesExtractor(eval_config),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(
eval_shared_model=eval_shared_model, eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
examples = [
self._makeExample(
age=1.0,
language='english',
english_label=1.0,
chinese_label=0.0,
other_label=0.0),
self._makeExample(
age=1.0,
language='chinese',
english_label=0.0,
chinese_label=1.0,
other_label=0.0),
self._makeExample(
age=2.0,
language='english',
english_label=1.0,
chinese_label=0.0,
other_label=0.0),
self._makeExample(
age=2.0,
language='other',
english_label=0.0,
chinese_label=1.0,
other_label=1.0),
]
tfx_io = test_util.InMemoryTFExampleRecord(
raw_record_column_name=constants.ARROW_INPUT_COLUMN)
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 1)
got_slice_key, got_metrics = got[0]
self.assertEqual(got_slice_key, ())
example_count_key = metric_types.MetricKey(name='example_count')
chinese_weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count',
output_name='chinese_head',
example_weighted=True)
chinese_label_key = metric_types.MetricKey(
name='mean_label',
output_name='chinese_head',
example_weighted=True)
english_weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count',
output_name='english_head',
example_weighted=True)
english_label_key = metric_types.MetricKey(
name='mean_label',
output_name='english_head',
example_weighted=True)
other_weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count',
output_name='other_head',
example_weighted=True)
other_label_key = metric_types.MetricKey(
name='mean_label',
output_name='other_head',
example_weighted=True)
self.assertDictElementsAlmostEqual(
got_metrics, {
example_count_key:
4,
chinese_label_key:
(0.0 + 1.0 + 2 * 0.0 + 2 * 1.0) / (1.0 + 1.0 + 2.0 + 2.0),
chinese_weighted_example_count_key: (1.0 + 1.0 + 2.0 + 2.0),
english_label_key:
(1.0 + 0.0 + 2 * 1.0 + 2 * 0.0) / (1.0 + 1.0 + 2.0 + 2.0),
english_weighted_example_count_key: (1.0 + 1.0 + 2.0 + 2.0),
other_label_key:
(0.0 + 0.0 + 2 * 0.0 + 2 * 1.0) / (1.0 + 1.0 + 2.0 + 2.0),
other_weighted_example_count_key: (1.0 + 1.0 + 2.0 + 2.0)
})
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(
metrics[constants.METRICS_KEY], check_metrics, label='metrics')
@parameterized.named_parameters(
('compiled_metrics', False),
('evaluate', True),
)
def testEvaluateWithKerasModelWithInGraphMetrics(self, add_custom_metrics):
# Custom metrics not supported in TFv1
if _TF_MAJOR_VERSION < 2:
add_custom_metrics = False
input1 = tf.keras.layers.Input(shape=(1,), name='input_1')
input2 = tf.keras.layers.Input(shape=(1,), name='input_2')
inputs = [input1, input2]
input_layer = tf.keras.layers.concatenate(inputs)
output_layer = tf.keras.layers.Dense(
1, activation=tf.nn.sigmoid, name='output')(
input_layer)
model = tf.keras.models.Model(inputs, output_layer)
# The model.evaluate API is used when custom metrics are used. Otherwise
# model.compiled_metrics is used.
if add_custom_metrics:
model.add_metric(tf.reduce_sum(input_layer), name='custom')
model.compile(
optimizer=tf.keras.optimizers.Adam(lr=.001),
loss=tf.keras.losses.BinaryCrossentropy(name='loss'),
metrics=[tf.keras.metrics.BinaryAccuracy(name='binary_accuracy')])
export_dir = self._getExportDir()
model.save(export_dir, save_format='tf')
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
label_key='label', example_weight_key='example_weight')
],
slicing_specs=[config_pb2.SlicingSpec()],
metrics_specs=metric_specs.specs_from_metrics(
[calibration.MeanLabel('mean_label')],
unweighted_metrics=[
tf.keras.metrics.BinaryAccuracy(name='binary_accuracy'),
calibration.MeanLabel('mean_label')
]))
eval_shared_model = self.createTestEvalSharedModel(
eval_saved_model_path=export_dir)
examples = [
self._makeExample(
input_1=0.0,
input_2=1.0,
label=1.0,
example_weight=1.0,
extra_feature='non_model_feature'),
self._makeExample(
input_1=1.0,
input_2=0.0,
label=0.0,
example_weight=0.5,
extra_feature='non_model_feature'),
]
schema = text_format.Parse(
"""
tensor_representation_group {
key: ""
value {
tensor_representation {
key: "input_1"
value {
dense_tensor {
column_name: "input_1"
shape { dim { size: 1 } }
}
}
}
tensor_representation {
key: "input_2"
value {
dense_tensor {
column_name: "input_2"
shape { dim { size: 1 } }
}
}
}
}
}
feature {
name: "input_1"
type: FLOAT
}
feature {
name: "input_2"
type: FLOAT
}
feature {
name: "label"
type: FLOAT
}
feature {
name: "example_weight"
type: FLOAT
}
feature {
name: "extra_feature"
type: BYTES
}
""", schema_pb2.Schema())
tfx_io = test_util.InMemoryTFExampleRecord(
schema=schema, raw_record_column_name=constants.ARROW_INPUT_COLUMN)
tensor_adapter_config = tensor_adapter.TensorAdapterConfig(
arrow_schema=tfx_io.ArrowSchema(),
tensor_representations=tfx_io.TensorRepresentations())
extractors = [
features_extractor.FeaturesExtractor(
eval_config=eval_config,
tensor_representations=tensor_adapter_config.tensor_representations
),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(
eval_shared_model=eval_shared_model,
eval_config=eval_config,
tensor_adapter_config=tensor_adapter_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 1)
got_slice_key, got_metrics = got[0]
self.assertEqual(got_slice_key, ())
example_count_key = metric_types.MetricKey(name='example_count')
weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count', example_weighted=True)
label_key = metric_types.MetricKey(
name='mean_label', example_weighted=True)
label_unweighted_key = metric_types.MetricKey(
name='mean_label', example_weighted=False)
binary_accuracy_key = metric_types.MetricKey(
name='binary_accuracy', example_weighted=None)
self.assertIn(binary_accuracy_key, got_metrics)
binary_accuracy_unweighted_key = metric_types.MetricKey(
name='binary_accuracy', example_weighted=False)
self.assertIn(binary_accuracy_unweighted_key, got_metrics)
# Loss not supported in TFv1
if _TF_MAJOR_VERSION > 1:
loss_key = metric_types.MetricKey(
name='loss', example_weighted=None)
self.assertIn(loss_key, got_metrics)
expected_values = {
example_count_key: 2,
weighted_example_count_key: (1.0 + 0.5),
label_key: (1.0 * 1.0 + 0.0 * 0.5) / (1.0 + 0.5),
label_unweighted_key: (1.0 + 0.0) / (1.0 + 1.0),
}
if add_custom_metrics:
custom_key = metric_types.MetricKey(
name='custom', example_weighted=None)
self.assertIn(custom_key, got_metrics)
expected_values[custom_key] = 0.0 + 1.0 + 0.0 + 1.0
self.assertDictElementsAlmostEqual(got_metrics, expected_values)
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(
metrics[constants.METRICS_KEY], check_metrics, label='metrics')
def testEvaluateWithQueryBasedMetrics(self):
temp_export_dir = self._getExportDir()
_, export_dir = (
fixed_prediction_estimator_extra_fields
.simple_fixed_prediction_estimator_extra_fields(None, temp_export_dir))
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
label_key='label', example_weight_key='fixed_int')
],
slicing_specs=[
config_pb2.SlicingSpec(),
config_pb2.SlicingSpec(feature_keys=['fixed_string']),
],
metrics_specs=metric_specs.specs_from_metrics(
[ndcg.NDCG(gain_key='fixed_float', name='ndcg')],
binarize=config_pb2.BinarizationOptions(
top_k_list={'values': [1, 2]}),
query_key='fixed_string'))
eval_shared_model = self.createTestEvalSharedModel(
eval_saved_model_path=export_dir, tags=[tf.saved_model.SERVING])
extractors = [
features_extractor.FeaturesExtractor(eval_config),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(
eval_shared_model=eval_shared_model, eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
# fixed_string used as query_key
# fixed_float used as gain_key for NDCG
# fixed_int used as example_weight_key for NDCG
examples = [
self._makeExample(
prediction=0.2,
label=1.0,
fixed_float=1.0,
fixed_string='query1',
fixed_int=1),
self._makeExample(
prediction=0.8,
label=0.0,
fixed_float=0.5,
fixed_string='query1',
fixed_int=1),
self._makeExample(
prediction=0.5,
label=0.0,
fixed_float=0.5,
fixed_string='query2',
fixed_int=2),
self._makeExample(
prediction=0.9,
label=1.0,
fixed_float=1.0,
fixed_string='query2',
fixed_int=2),
self._makeExample(
prediction=0.1,
label=0.0,
fixed_float=0.1,
fixed_string='query2',
fixed_int=2),
self._makeExample(
prediction=0.9,
label=1.0,
fixed_float=1.0,
fixed_string='query3',
fixed_int=3)
]
tfx_io = test_util.InMemoryTFExampleRecord(
raw_record_column_name=constants.ARROW_INPUT_COLUMN)
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 4)
slices = {}
for slice_key, value in got:
slices[slice_key] = value
overall_slice = ()
query1_slice = (('fixed_string', 'query1'),)
query2_slice = (('fixed_string', 'query2'),)
query3_slice = (('fixed_string', 'query3'),)
self.assertCountEqual(
list(slices.keys()),
[overall_slice, query1_slice, query2_slice, query3_slice])
example_count_key = metric_types.MetricKey(name='example_count')
weighted_example_count_key = metric_types.MetricKey(
name='weighted_example_count', example_weighted=True)
ndcg1_key = metric_types.MetricKey(
name='ndcg',
sub_key=metric_types.SubKey(top_k=1),
example_weighted=True)
ndcg2_key = metric_types.MetricKey(
name='ndcg',
sub_key=metric_types.SubKey(top_k=2),
example_weighted=True)
# Query1 (weight=1): (p=0.8, g=0.5) (p=0.2, g=1.0)
# Query2 (weight=2): (p=0.9, g=1.0) (p=0.5, g=0.5) (p=0.1, g=0.1)
# Query3 (weight=3): (p=0.9, g=1.0)
#
# DCG@1: 0.5, 1.0, 1.0
# NDCG@1: 0.5, 1.0, 1.0
# Average NDCG@1: (1 * 0.5 + 2 * 1.0 + 3 * 1.0) / (1 + 2 + 3) ~ 0.92
#
# DCG@2: (0.5 + 1.0/log(3) ~ 0.630930
# (1.0 + 0.5/log(3) ~ 1.315465
# 1.0
# NDCG@2: (0.5 + 1.0/log(3)) / (1.0 + 0.5/log(3)) ~ 0.85972
# (1.0 + 0.5/log(3)) / (1.0 + 0.5/log(3)) = 1.0
# 1.0
# Average NDCG@2: (1 * 0.860 + 2 * 1.0 + 3 * 1.0) / (1 + 2 + 3) ~ 0.97
self.assertDictElementsAlmostEqual(
slices[overall_slice], {
example_count_key: 6,
weighted_example_count_key: 11.0,
ndcg1_key: 0.9166667,
ndcg2_key: 0.9766198
})
self.assertDictElementsAlmostEqual(
slices[query1_slice], {
example_count_key: 2,
weighted_example_count_key: 2.0,
ndcg1_key: 0.5,
ndcg2_key: 0.85972
})
self.assertDictElementsAlmostEqual(
slices[query2_slice], {
example_count_key: 3,
weighted_example_count_key: 6.0,
ndcg1_key: 1.0,
ndcg2_key: 1.0
})
self.assertDictElementsAlmostEqual(
slices[query3_slice], {
example_count_key: 1,
weighted_example_count_key: 3.0,
ndcg1_key: 1.0,
ndcg2_key: 1.0
})
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(
metrics[constants.METRICS_KEY], check_metrics, label='metrics')
def testEvaluateWithEvalSavedModel(self):
temp_export_dir = self._getExportDir()
_, export_dir = linear_classifier.simple_linear_classifier(
None, temp_export_dir)
eval_config = config_pb2.EvalConfig(
model_specs=[config_pb2.ModelSpec(signature_name='eval')],
slicing_specs=[
config_pb2.SlicingSpec(),
config_pb2.SlicingSpec(feature_keys=['slice_key']),
])
eval_shared_model = self.createTestEvalSharedModel(
eval_saved_model_path=export_dir,
add_metrics_callbacks=[_addExampleCountMetricCallback])
extractors = [
legacy_predict_extractor.PredictExtractor(
eval_shared_model, eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
examples = [
self._makeExample(
age=3.0, language='english', label=1.0, slice_key='first_slice'),
self._makeExample(
age=3.0, language='chinese', label=0.0, slice_key='first_slice'),
self._makeExample(
age=4.0, language='english', label=0.0, slice_key='second_slice'),
self._makeExample(
age=5.0, language='chinese', label=1.0, slice_key='second_slice'),
self._makeExample(
age=5.0, language='chinese', label=1.0, slice_key='second_slice')
]
tfx_io = raw_tf_record.RawBeamRecordTFXIO(
physical_format='inmemory',
raw_record_column_name=constants.ARROW_INPUT_COLUMN,
telemetry_descriptors=['TFMATest'])
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
metrics = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_metrics(got):
try:
self.assertLen(got, 3)
slices = {}
for slice_key, value in got:
slices[slice_key] = value
overall_slice = ()
first_slice = (('slice_key', 'first_slice'),)
second_slice = (('slice_key', 'second_slice'),)
self.assertCountEqual(
list(slices.keys()), [overall_slice, first_slice, second_slice])
self.assertDictElementsAlmostEqual(
slices[overall_slice], {
metric_types.MetricKey(
name='accuracy', example_weighted=None):
0.4,
metric_types.MetricKey(
name='label/mean', example_weighted=None):
0.6,
metric_types.MetricKey(
name='my_mean_age', example_weighted=None):
4.0,
metric_types.MetricKey(
name='my_mean_age_times_label', example_weighted=None):
2.6,
metric_types.MetricKey(
name='added_example_count', example_weighted=None):
5.0
})
self.assertDictElementsAlmostEqual(
slices[first_slice], {
metric_types.MetricKey(
name='accuracy', example_weighted=None):
1.0,
metric_types.MetricKey(
name='label/mean', example_weighted=None):
0.5,
metric_types.MetricKey(
name='my_mean_age', example_weighted=None):
3.0,
metric_types.MetricKey(
name='my_mean_age_times_label', example_weighted=None):
1.5,
metric_types.MetricKey(
name='added_example_count', example_weighted=None):
2.0
})
self.assertDictElementsAlmostEqual(
slices[second_slice], {
metric_types.MetricKey(
name='accuracy', example_weighted=None):
0.0,
metric_types.MetricKey(
name='label/mean', example_weighted=None):
2.0 / 3.0,
metric_types.MetricKey(
name='my_mean_age', example_weighted=None):
14.0 / 3.0,
metric_types.MetricKey(
name='my_mean_age_times_label', example_weighted=None):
10.0 / 3.0,
metric_types.MetricKey(
name='added_example_count', example_weighted=None):
3.0
})
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(
metrics[constants.METRICS_KEY], check_metrics, label='metrics')
def testValidateWithEvalSavedModel(self):
temp_export_dir = self._getExportDir()
_, export_dir = linear_classifier.simple_linear_classifier(
None, temp_export_dir)
eval_config = config_pb2.EvalConfig(
model_specs=[config_pb2.ModelSpec(signature_name='eval')],
metrics_specs=[
config_pb2.MetricsSpec(
thresholds={
'accuracy':
config_pb2.MetricThreshold(
value_threshold=config_pb2.GenericValueThreshold(
lower_bound={'value': 0.9})),
'nonexistent_metrics':
config_pb2.MetricThreshold(
value_threshold=config_pb2.GenericValueThreshold(
lower_bound={'value': 0.1}))
})
],
slicing_specs=[
config_pb2.SlicingSpec(),
])
eval_shared_model = self.createTestEvalSharedModel(
eval_saved_model_path=export_dir,
add_metrics_callbacks=[_addExampleCountMetricCallback])
extractors = [
legacy_predict_extractor.PredictExtractor(
eval_shared_model, eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
examples = [
self._makeExample(
age=3.0, language='english', label=1.0, slice_key='first_slice'),
self._makeExample(
age=3.0, language='chinese', label=0.0, slice_key='first_slice'),
self._makeExample(
age=4.0, language='english', label=0.0, slice_key='second_slice'),
self._makeExample(
age=5.0, language='chinese', label=1.0, slice_key='second_slice'),
self._makeExample(
age=5.0, language='chinese', label=1.0, slice_key='second_slice')
]
tfx_io = raw_tf_record.RawBeamRecordTFXIO(
physical_format='inmemory',
raw_record_column_name=constants.ARROW_INPUT_COLUMN,
telemetry_descriptors=['TFMATest'])
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
evaluations = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_validations(got):
try:
self.assertLen(got, 1)
got = got[0]
expected_failures = [
text_format.Parse(
"""
metric_key {
name: "accuracy"
}
metric_threshold {
value_threshold {
lower_bound {
value: 0.9
}
}
}
""", validation_result_pb2.ValidationFailure()),
text_format.Parse(
"""
metric_key {
name: "nonexistent_metrics"
}
metric_threshold {
value_threshold {
lower_bound {
value: 0.1
}
}
}
message: "Metric not found."
""", validation_result_pb2.ValidationFailure()),
]
self.assertFalse(got.validation_ok)
self.assertLen(got.metric_validations_per_slice, 1)
# Ignore the metric_value to avoid fragility of float rounding issue.
# The correctness of the metric_value has been tested in other tests.
failures = got.metric_validations_per_slice[0].failures
self.assertLen(failures, len(expected_failures))
for failure, expected_failure in zip(failures, expected_failures):
failure.ClearField('metric_value')
self.assertProtoEquals(expected_failure, failure)
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(evaluations[constants.VALIDATIONS_KEY],
check_validations)
def testEvaluateWithCrossSlicing(self):
temp_export_dir1 = self._getExportDir()
_, export_dir1 = (
fixed_prediction_estimator_extra_fields
.simple_fixed_prediction_estimator_extra_fields(None, temp_export_dir1))
temp_export_dir2 = self._getExportDir()
_, export_dir2 = (
fixed_prediction_estimator_extra_fields
.simple_fixed_prediction_estimator_extra_fields(None, temp_export_dir2))
example_count_metric = config_pb2.MetricConfig(
class_name='ExampleCount',
# 5 >= 3, OK for overall slice
# 3 >= 3, OK for ('fixed_string', 'fixed_string1')
# 2 < 3, NOT OK for ('fixed_string', 'fixed_string2')
# Keep this for verifying cross slice thresholds and single slice
# thresholds are working together.
threshold=config_pb2.MetricThreshold(
value_threshold=config_pb2.GenericValueThreshold(
lower_bound={'value': 3})),
cross_slice_thresholds=[
config_pb2.CrossSliceMetricThreshold(
# 5-2 >= 2, OK for ((), (('fixed_string', 'fixed_string1'),))
# 5-3 < 3, NOT OK for ((), (('fixed_string', 'fixed_string2'),))
threshold=config_pb2.MetricThreshold(
value_threshold=config_pb2.GenericValueThreshold(
lower_bound={'value': 3})),
cross_slicing_specs=[
config_pb2.CrossSlicingSpec(
baseline_spec=config_pb2.SlicingSpec(),
slicing_specs=[
config_pb2.SlicingSpec(
feature_keys=['fixed_string'])
])
])
])
mean_prediction_metric = config_pb2.MetricConfig(
class_name='MeanPrediction',
cross_slice_thresholds=[
config_pb2.CrossSliceMetricThreshold(
# MeanPrediction values for slices:
# (0.2*2+0.9*2)/(2+2)=0.55
# for (('fixed_string', 'fixed_string1'),)
# (0.5*2+0.5*2+0.5*2)/(2+2+2)=0.5
# for (('fixed_string', 'fixed_string2'),)
threshold=config_pb2.MetricThreshold(
value_threshold=config_pb2.GenericValueThreshold(
# This config should give value threshold error because
# (0.55-0.5)=0.05 not inside the bound [0.1, 0.5].
upper_bound={'value': .5},
lower_bound={'value': .1}),
change_threshold=config_pb2.GenericChangeThreshold(
# This config should give change threshold error because
# baseline model and candidate model have same
# difference as 0.05 between cross slices. Cross slice
# difference value is not changed.
direction=config_pb2.MetricDirection.LOWER_IS_BETTER,
relative={'value': -.99},
absolute={'value': 0})),
cross_slicing_specs=[
config_pb2.CrossSlicingSpec(
baseline_spec=config_pb2.SlicingSpec(
feature_values={'fixed_string': 'fixed_string1'}),
slicing_specs=[
config_pb2.SlicingSpec(feature_values={
'fixed_string': 'fixed_string2'
})
])
])
])
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
name='candidate',
label_key='label',
example_weight_key='fixed_float'),
config_pb2.ModelSpec(
name='baseline',
label_key='label',
example_weight_key='fixed_float',
is_baseline=True)
],
slicing_specs=[
config_pb2.SlicingSpec(),
config_pb2.SlicingSpec(feature_keys=['fixed_string']),
],
cross_slicing_specs=[
config_pb2.CrossSlicingSpec(
baseline_spec=config_pb2.SlicingSpec(),
slicing_specs=[
config_pb2.SlicingSpec(feature_keys=['fixed_string'])
]),
config_pb2.CrossSlicingSpec(
baseline_spec=config_pb2.SlicingSpec(
feature_values={'fixed_string': 'fixed_string1'}),
slicing_specs=[
config_pb2.SlicingSpec(
feature_values={'fixed_string': 'fixed_string2'})
])
],
metrics_specs=[
config_pb2.MetricsSpec(
metrics=[example_count_metric],
model_names=['candidate', 'baseline'],
example_weights=config_pb2.ExampleWeightOptions(
unweighted=True)),
config_pb2.MetricsSpec(
metrics=[mean_prediction_metric],
model_names=['candidate', 'baseline']),
])
eval_shared_model = [
self.createTestEvalSharedModel(
model_name='candidate', eval_saved_model_path=export_dir1),
self.createTestEvalSharedModel(
model_name='baseline', eval_saved_model_path=export_dir2),
]
extractors = [
legacy_predict_extractor.PredictExtractor(
eval_shared_model=eval_shared_model, eval_config=eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(
eval_config=eval_config, eval_shared_model=eval_shared_model)
]
# fixed_float used as example_weight key
examples = [
self._makeExample(
prediction=0.2,
label=1.0,
fixed_int=1,
fixed_float=1.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.9,
label=0.0,
fixed_int=1,
fixed_float=1.0,
fixed_string='fixed_string1'),
self._makeExample(
prediction=0.5,
label=0.0,
fixed_int=2,
fixed_float=2.0,
fixed_string='fixed_string2'),
self._makeExample(
prediction=0.5,
label=0.0,
fixed_int=2,
fixed_float=2.0,
fixed_string='fixed_string2'),
self._makeExample(
prediction=0.5,
label=0.0,
fixed_int=2,
fixed_float=2.0,
fixed_string='fixed_string2'),
]
tfx_io = raw_tf_record.RawBeamRecordTFXIO(
physical_format='inmemory',
raw_record_column_name=constants.ARROW_INPUT_COLUMN,
telemetry_descriptors=['TFMATest'])
with beam.Pipeline() as pipeline:
# pylint: disable=no-value-for-parameter
evaluations = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractAndEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
# pylint: enable=no-value-for-parameter
def check_validations(got):
try:
self.assertLen(got, 6)
def get_slice_keys_hash(metric_validation):
slice_key, cross_slice_key = None, None
if metric_validation.slice_key:
slice_key = metric_validation.slice_key.SerializeToString()
if metric_validation.cross_slice_key:
cross_slice_key = (
metric_validation.cross_slice_key.SerializeToString())
return (slice_key, cross_slice_key)
successful_validations = []
failed_validations = {}
for validation_result in got:
if validation_result.validation_ok:
successful_validations.append(validation_result)
else:
self.assertLen(validation_result.metric_validations_per_slice, 1)
validation_result = (
validation_result.metric_validations_per_slice[0])
slice_keys_hash = get_slice_keys_hash(validation_result)
failed_validations[slice_keys_hash] = {}
for failure in validation_result.failures:
failure.ClearField('metric_value')
failed_validations[slice_keys_hash][
failure.metric_key.SerializeToString()] = failure
self.assertLen(successful_validations, 3)
self.assertLen(failed_validations.keys(), 3)
expected_validations = [
text_format.Parse(
"""
slice_key {
single_slice_keys {
column: "fixed_string"
bytes_value: "fixed_string1"
}
}
failures {
metric_key {
name: "example_count"
model_name: "candidate"
example_weighted { }
}
metric_threshold {
value_threshold {
lower_bound {
value: 3.0
}
}
}
}
""", validation_result_pb2.MetricsValidationForSlice()),
text_format.Parse(
"""
failures {
metric_key {
name: "example_count"
model_name: "candidate"
example_weighted { }
}
metric_threshold {
value_threshold {
lower_bound {
value: 3.0
}
}
}
}
cross_slice_key {
baseline_slice_key {
}
comparison_slice_key {
single_slice_keys {
column: "fixed_string"
bytes_value: "fixed_string2"
}
}
}
""", validation_result_pb2.MetricsValidationForSlice()),
text_format.Parse(
"""
failures {
metric_key {
name: "mean_prediction"
model_name: "candidate"
example_weighted { value: true }
}
metric_threshold {
value_threshold {
lower_bound {
value: 0.1
}
upper_bound {
value: 0.5
}
}
}
}
failures {
metric_key {
name: "mean_prediction"
model_name: "candidate"
is_diff: true
example_weighted { value: true }
}
metric_threshold {
change_threshold {
absolute {
}
relative {
value: -0.99
}
direction: LOWER_IS_BETTER
}
}
}
cross_slice_key {
baseline_slice_key {
single_slice_keys {
column: "fixed_string"
bytes_value: "fixed_string1"
}
}
comparison_slice_key {
single_slice_keys {
column: "fixed_string"
bytes_value: "fixed_string2"
}
}
}
""", validation_result_pb2.MetricsValidationForSlice())
]
expected_validations_dict = {}
for expected_validation in expected_validations:
slice_keys_hash = get_slice_keys_hash(expected_validation)
expected_validations_dict[slice_keys_hash] = {}
for failure in expected_validation.failures:
expected_validations_dict[slice_keys_hash][
failure.metric_key.SerializeToString()] = failure
self.assertEqual(
set(failed_validations.keys()),
set(expected_validations_dict.keys()))
for slice_key, validation in failed_validations.items():
self.assertEqual(
set(validation.keys()),
set(expected_validations_dict[slice_key].keys()))
for metric_key, failure in validation.items():
self.assertProtoEquals(
failure, expected_validations_dict[slice_key][metric_key])
except AssertionError as err:
raise util.BeamAssertException(err)
util.assert_that(evaluations[constants.VALIDATIONS_KEY],
check_validations)
def testAddCrossSliceMetricsMatchAll(self):
overall_slice_key = ()
slice_key1 = (('feature', 1),)
slice_key2 = (('feature', 2),)
slice_key3 = (('feature', 3),)
metrics_dict = {}
sliced_metrics = [(overall_slice_key, metrics_dict),
(slice_key1, metrics_dict), (slice_key2, metrics_dict),
(slice_key3, metrics_dict)]
with beam.Pipeline() as pipeline:
cross_sliced_metrics = (
pipeline | 'CreateSlicedMetrics' >> beam.Create(sliced_metrics)
| 'AddCrossSliceMetrics' >>
metrics_plots_and_validations_evaluator._AddCrossSliceMetrics(
cross_slice_specs=[
config_pb2.CrossSlicingSpec(
baseline_spec={}, slicing_specs=[])
],
cross_slice_computations=[]))
def check_result(got_sliced_metrics):
actual_slice_keys = [k for k, _ in got_sliced_metrics]
expected_slice_keys = [
# cross slice keys
(overall_slice_key, slice_key1),
(overall_slice_key, slice_key2),
(overall_slice_key, slice_key3),
# single slice keys
overall_slice_key,
slice_key1,
slice_key2,
slice_key3
]
self.assertCountEqual(expected_slice_keys, actual_slice_keys)
util.assert_that(cross_sliced_metrics, check_result)
@parameterized.named_parameters(
('IntIsDiffable', 1, True),
('FloatIsDiffable', 1.0, True),
('NumpyFloatDtypeIsDiffable', np.array([1.0], dtype=np.float64), True),
('NumpyIntDtypeIsDiffable', np.array([1], dtype=np.int64), True),
('MessageNotDiffable', validation_result_pb2.ValidationResult(), False),
('TupleNotDiffable',
binary_confusion_matrices.Matrices(
thresholds=[-1e-7, 0.5, 1.0 + 1e-7],
tp=[2.0, 1.0, 0.0],
fp=[2.0, 0.0, 0.0],
tn=[0.0, 2.0, 2.0],
fn=[0.0, 1.0, 2.0]), False),
('BytesNotDiffable', b'some bytes', False),
('NumpyObjectDtypeNotDiffable', np.array(['obj'],
dtype=np.object), False),
)
def testIsMetricDiffable(self, metric_value, expected_is_diffable):
self.assertEqual(
expected_is_diffable,
metrics_plots_and_validations_evaluator._is_metric_diffable(
metric_value))
def testMetricsSpecsCountersInModelAgnosticMode(self):
schema = text_format.Parse(
"""
feature {
name: "label"
type: FLOAT
}
feature {
name: "prediction"
type: FLOAT
}
""", schema_pb2.Schema())
tfx_io = test_util.InMemoryTFExampleRecord(
schema=schema, raw_record_column_name=constants.ARROW_INPUT_COLUMN)
examples = [
self._makeExample(label=1.0, prediction=0.7),
self._makeExample(label=0.0, prediction=0.3),
]
eval_config = config_pb2.EvalConfig(
model_specs=[
config_pb2.ModelSpec(
prediction_key='prediction', label_key='label')
],
metrics_specs=[
config_pb2.MetricsSpec(
metrics=[config_pb2.MetricConfig(class_name='ExampleCount')])
],
slicing_specs=[config_pb2.SlicingSpec()])
extractors = [
features_extractor.FeaturesExtractor(eval_config),
labels_extractor.LabelsExtractor(eval_config),
example_weights_extractor.ExampleWeightsExtractor(eval_config),
predictions_extractor.PredictionsExtractor(eval_config),
unbatch_extractor.UnbatchExtractor(),
slice_key_extractor.SliceKeyExtractor(eval_config=eval_config)
]
evaluators = [
metrics_plots_and_validations_evaluator
.MetricsPlotsAndValidationsEvaluator(eval_config)
]
with beam.Pipeline() as pipeline:
_ = (
pipeline
| 'Create' >> beam.Create([e.SerializeToString() for e in examples])
| 'BatchExamples' >> tfx_io.BeamSource()
| 'InputsToExtracts' >> model_eval_lib.BatchedInputsToExtracts()
| 'ExtractEvaluate' >> model_eval_lib.ExtractAndEvaluate(
extractors=extractors, evaluators=evaluators))
metric_filter = beam.metrics.metric.MetricsFilter().with_name(
'metric_computed_ExampleCount_v2_' + constants.MODEL_AGNOSTIC)
actual_metrics_count = pipeline.run().metrics().query(
filter=metric_filter)['counters'][0].committed
self.assertEqual(actual_metrics_count, 1)
if __name__ == '__main__':
tf.compat.v1.enable_v2_behavior()
tf.test.main()
|
from setuptools import setup, find_packages
setup(
name="sentinel",
version="3.0.2",
author="Joe Stahl (@happy-jo)",
url="https://github.com/PUNCH-Cyber/stoq-plugins-public",
license="Apache License 2.0",
description="Send reults to Azure Sentinel (Log Analytics Workspace) using the Azure Log Analytics API",
packages=find_packages(),
include_package_data=True,
)
|
def setup_ntp_test(request, bigip):
def teardown():
n.servers = servers
n.update()
request.addfinalizer(teardown)
n = bigip.sys.ntp.load()
servers = n.servers
return n, servers
class iTestGlobal_Setting(object):
def itest_RUL(self, request, bigip):
# Load
ip = '192.168.1.1'
ntp1, orig_servers = setup_ntp_test(request, bigip)
ntp2 = bigip.sys.ntp.load()
assert len(ntp1.servers) == len(ntp2.servers)
# Update
ntp1.servers = [ip]
ntp1.update()
assert ip in ntp1.servers
assert ip not in ntp2.servers
# Refresh
ntp2.refresh()
assert ip in ntp2.servers
|
from __future__ import absolute_import, division, print_function, unicode_literals
from logging import getLogger
from os.path import realpath
import re
import struct
from ..base.constants import PREFIX_PLACEHOLDER
from ..common.compat import on_win
from ..exceptions import CondaIOError, BinaryPrefixReplacementError
from ..gateways.disk.update import CancelOperation, update_file_in_place_as_binary
from ..models.enums import FileMode
log = getLogger(__name__)
SHEBANG_REGEX = (br'^(#!' # pretty much the whole match string
br'(?:[ ]*)' # allow spaces between #! and beginning of the executable path
br'(/(?:\\ |[^ \n\r\t])*)' # the executable is the next text block without an escaped space or non-space whitespace character # NOQA
br'(.*)' # the rest of the line can contain option flags
br')$') # end whole_shebang group
class _PaddingError(Exception):
pass
def update_prefix(path, new_prefix, placeholder=PREFIX_PLACEHOLDER, mode=FileMode.text):
if on_win and mode == FileMode.text:
# force all prefix replacements to forward slashes to simplify need to escape backslashes
# replace with unix-style path separators
new_prefix = new_prefix.replace('\\', '/')
def _update_prefix(original_data):
# Step 1. do all prefix replacement
data = replace_prefix(mode, original_data, placeholder, new_prefix)
# Step 2. if the shebang is too long, shorten it using /usr/bin/env trick
if not on_win:
data = replace_long_shebang(mode, data)
# Step 3. if the before and after content is the same, skip writing
if data == original_data:
raise CancelOperation()
# Step 4. if we have a binary file, make sure the byte size is the same before
# and after the update
if mode == FileMode.binary and len(data) != len(original_data):
raise BinaryPrefixReplacementError(path, placeholder, new_prefix,
len(original_data), len(data))
return data
update_file_in_place_as_binary(realpath(path), _update_prefix)
def replace_prefix(mode, data, placeholder, new_prefix):
if mode == FileMode.text:
data = data.replace(placeholder.encode('utf-8'), new_prefix.encode('utf-8'))
elif mode == FileMode.binary:
data = binary_replace(data, placeholder.encode('utf-8'), new_prefix.encode('utf-8'))
else:
raise CondaIOError("Invalid mode: %r" % mode)
return data
def binary_replace(data, a, b):
"""
Perform a binary replacement of `data`, where the placeholder `a` is
replaced with `b` and the remaining string is padded with null characters.
All input arguments are expected to be bytes objects.
"""
if on_win:
# on Windows for binary files, we currently only replace a pyzzer-type entry point
# we skip all other prefix replacement
if has_pyzzer_entry_point(data):
return replace_pyzzer_entry_point_shebang(data, a, b)
else:
return data
def replace(match):
occurances = match.group().count(a)
padding = (len(a) - len(b)) * occurances
if padding < 0:
raise _PaddingError
return match.group().replace(a, b) + b'\0' * padding
original_data_len = len(data)
pat = re.compile(re.escape(a) + b'([^\0]*?)\0')
data = pat.sub(replace, data)
assert len(data) == original_data_len
return data
def has_pyzzer_entry_point(data):
pos = data.rfind(b'PK\x05\x06')
return pos >= 0
def replace_pyzzer_entry_point_shebang(all_data, placeholder, new_prefix):
"""Code adapted from pyzzer. This is meant to deal with entry point exe's created by distlib,
which consist of a launcher, then a shebang, then a zip archive of the entry point code to run.
We need to change the shebang.
https://bitbucket.org/vinay.sajip/pyzzer/src/5d5740cb04308f067d5844a56fbe91e7a27efccc/pyzzer/__init__.py?at=default&fileviewer=file-view-default#__init__.py-112 # NOQA
"""
# Copyright (c) 2013 Vinay Sajip.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
launcher = shebang = None
pos = all_data.rfind(b'PK\x05\x06')
if pos >= 0:
end_cdr = all_data[pos + 12:pos + 20]
cdr_size, cdr_offset = struct.unpack('<LL', end_cdr)
arc_pos = pos - cdr_size - cdr_offset
data = all_data[arc_pos:]
if arc_pos > 0:
pos = all_data.rfind(b'#!', 0, arc_pos)
if pos >= 0:
shebang = all_data[pos:arc_pos]
if pos > 0:
launcher = all_data[:pos]
if data and shebang and launcher:
if hasattr(placeholder, 'encode'):
placeholder = placeholder.encode('utf-8')
if hasattr(new_prefix, 'encode'):
new_prefix = new_prefix.encode('utf-8')
shebang = shebang.replace(placeholder, new_prefix)
all_data = b"".join([launcher, shebang, data])
return all_data
def replace_long_shebang(mode, data):
# this function only changes a shebang line if it exists and is greater than 127 characters
if mode == FileMode.text:
shebang_match = re.match(SHEBANG_REGEX, data, re.MULTILINE)
if shebang_match:
whole_shebang, executable, options = shebang_match.groups()
if len(whole_shebang) > 127:
executable_name = executable.decode('utf-8').split('/')[-1]
new_shebang = '#!/usr/bin/env %s%s' % (executable_name, options.decode('utf-8'))
data = data.replace(whole_shebang, new_shebang.encode('utf-8'))
else:
# TODO: binary shebangs exist; figure this out in the future if text works well
pass
return data
|
import commands
import logging
import json
import time
from core.alive import alive
from core.voiceapplication import VoiceApplication
from core.voicesynthetizer import VoiceSynthetizer
from pprint import pprint
class VoiceApp(object):
def __init__(self, voicesynthetizer):
self.modulename = 'Voice Application'
self.voicesynthetizer = voicesynthetizer
self.voiceapplication = VoiceApplication()
def application(self):
logging.info(self.modulename)
repeater = 'python nuupxe.py -v \"Hola! En que puedo ayudarte?\"'
status, output = commands.getstatusoutput(repeater)
response = self.voiceapplication.action()
repeater = 'python nuupxe.py -m \"' + response + '\"'
status, output = commands.getstatusoutput(repeater)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import datetime
import logging
import os
import shutil
import unittest
import six
import socket
from tempfile import mkdtemp
from airflow import AirflowException, settings, models
from airflow.bin import cli
from airflow.executors import SequentialExecutor
from airflow.jobs import BackfillJob, SchedulerJob, LocalTaskJob
from airflow.models import DAG, DagModel, DagBag, DagRun, Pool, TaskInstance as TI
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.bash_operator import BashOperator
from airflow.utils.db import provide_session
from airflow.utils.state import State
from airflow.utils.timeout import timeout
from airflow.utils.dag_processing import SimpleDagBag
from mock import patch
from sqlalchemy.orm.session import make_transient
from tests.executors.test_executor import TestExecutor
from tests.core import TEST_DAG_FOLDER
from airflow import configuration
configuration.load_test_config()
import sqlalchemy
try:
from unittest import mock
except ImportError:
try:
import mock
except ImportError:
mock = None
DEV_NULL = '/dev/null'
DEFAULT_DATE = datetime.datetime(2016, 1, 1)
PARSEABLE_DAG_FILE_CONTENTS = '"airflow DAG"'
UNPARSEABLE_DAG_FILE_CONTENTS = 'airflow DAG'
TEMP_DAG_FILENAME = "temp_dag.py"
class BackfillJobTest(unittest.TestCase):
def setUp(self):
self.parser = cli.CLIFactory.get_parser()
self.dagbag = DagBag(include_examples=True)
@unittest.skipIf('sqlite' in configuration.get('core', 'sql_alchemy_conn'),
"concurrent access not supported in sqlite")
def test_trigger_controller_dag(self):
dag = self.dagbag.get_dag('example_trigger_controller_dag')
target_dag = self.dagbag.get_dag('example_trigger_target_dag')
dag.clear()
target_dag.clear()
scheduler = SchedulerJob()
queue = mock.Mock()
scheduler._process_task_instances(target_dag, queue=queue)
self.assertFalse(queue.append.called)
job = BackfillJob(
dag=dag,
start_date=DEFAULT_DATE,
end_date=DEFAULT_DATE,
ignore_first_depends_on_past=True
)
job.run()
scheduler = SchedulerJob()
queue = mock.Mock()
scheduler._process_task_instances(target_dag, queue=queue)
self.assertTrue(queue.append.called)
target_dag.clear()
dag.clear()
@unittest.skipIf('sqlite' in configuration.get('core', 'sql_alchemy_conn'),
"concurrent access not supported in sqlite")
def test_backfill_multi_dates(self):
dag = self.dagbag.get_dag('example_bash_operator')
dag.clear()
job = BackfillJob(
dag=dag,
start_date=DEFAULT_DATE,
end_date=DEFAULT_DATE + datetime.timedelta(days=1),
ignore_first_depends_on_past=True
)
job.run()
session = settings.Session()
drs = session.query(DagRun).filter(
DagRun.dag_id=='example_bash_operator'
).order_by(DagRun.execution_date).all()
self.assertTrue(drs[0].execution_date == DEFAULT_DATE)
self.assertTrue(drs[0].state == State.SUCCESS)
self.assertTrue(drs[1].execution_date ==
DEFAULT_DATE + datetime.timedelta(days=1))
self.assertTrue(drs[1].state == State.SUCCESS)
dag.clear()
session.close()
@unittest.skipIf('sqlite' in configuration.get('core', 'sql_alchemy_conn'),
"concurrent access not supported in sqlite")
def test_backfill_examples(self):
"""
Test backfilling example dags
"""
# some DAGs really are just examples... but try to make them work!
skip_dags = [
'example_http_operator',
'example_twitter_dag',
'example_trigger_target_dag',
'example_trigger_controller_dag', # tested above
'test_utils', # sleeps forever
]
logger = logging.getLogger('BackfillJobTest.test_backfill_examples')
dags = [
dag for dag in self.dagbag.dags.values()
if 'example_dags' in dag.full_filepath and dag.dag_id not in skip_dags
]
for dag in dags:
dag.clear(
start_date=DEFAULT_DATE,
end_date=DEFAULT_DATE)
for i, dag in enumerate(sorted(dags, key=lambda d: d.dag_id)):
logger.info('*** Running example DAG #{}: {}'.format(i, dag.dag_id))
job = BackfillJob(
dag=dag,
start_date=DEFAULT_DATE,
end_date=DEFAULT_DATE,
ignore_first_depends_on_past=True)
job.run()
def test_backfill_ordered_concurrent_execute(self):
dag = DAG(
dag_id='test_backfill_ordered_concurrent_execute',
start_date=DEFAULT_DATE,
schedule_interval="@daily")
with dag:
op1 = DummyOperator(task_id='leave1')
op2 = DummyOperator(task_id='leave2')
op3 = DummyOperator(task_id='upstream_level_1')
op4 = DummyOperator(task_id='upstream_level_2')
op5 = DummyOperator(task_id='upstream_level_3')
# order randomly
op2.set_downstream(op3)
op1.set_downstream(op3)
op4.set_downstream(op5)
op3.set_downstream(op4)
dag.clear()
executor = TestExecutor(do_update=True)
job = BackfillJob(dag=dag,
executor=executor,
start_date=DEFAULT_DATE,
end_date=DEFAULT_DATE + datetime.timedelta(days=2),
)
job.run()
# test executor history keeps a list
history = executor.history
# check if right order. Every loop has a 'pause' (0) to change state
# from RUNNING to SUCCESS.
# 6,0,3,0,3,0,3,0 = 8 loops
self.assertEqual(8, len(history))
loop_count = 0
while len(history) > 0:
queued_tasks = history.pop(0)
if loop_count == 0:
# first loop should contain 6 tasks (3 days x 2 tasks)
self.assertEqual(6, len(queued_tasks))
if loop_count == 2 or loop_count == 4 or loop_count == 6:
# 3 days x 1 task
self.assertEqual(3, len(queued_tasks))
loop_count += 1
def test_backfill_pooled_tasks(self):
"""
Test that queued tasks are executed by BackfillJob
Test for https://github.com/airbnb/airflow/pull/1225
"""
session = settings.Session()
pool = Pool(pool='test_backfill_pooled_task_pool', slots=1)
session.add(pool)
session.commit()
dag = self.dagbag.get_dag('test_backfill_pooled_task_dag')
dag.clear()
job = BackfillJob(
dag=dag,
start_date=DEFAULT_DATE,
end_date=DEFAULT_DATE)
# run with timeout because this creates an infinite loop if not
# caught
with timeout(seconds=30):
job.run()
ti = TI(
task=dag.get_task('test_backfill_pooled_task'),
execution_date=DEFAULT_DATE)
ti.refresh_from_db()
self.assertEqual(ti.state, State.SUCCESS)
def test_backfill_depends_on_past(self):
"""
Test that backfill respects ignore_depends_on_past
"""
dag = self.dagbag.get_dag('test_depends_on_past')
dag.clear()
run_date = DEFAULT_DATE + datetime.timedelta(days=5)
# backfill should deadlock
self.assertRaisesRegexp(
AirflowException,
'BackfillJob is deadlocked',
BackfillJob(dag=dag, start_date=run_date, end_date=run_date).run)
BackfillJob(
dag=dag,
start_date=run_date,
end_date=run_date,
ignore_first_depends_on_past=True).run()
# ti should have succeeded
ti = TI(dag.tasks[0], run_date)
ti.refresh_from_db()
self.assertEquals(ti.state, State.SUCCESS)
def test_cli_backfill_depends_on_past(self):
"""
Test that CLI respects -I argument
"""
dag_id = 'test_dagrun_states_deadlock'
run_date = DEFAULT_DATE + datetime.timedelta(days=1)
args = [
'backfill',
dag_id,
'-l',
'-s',
run_date.isoformat(),
]
dag = self.dagbag.get_dag(dag_id)
dag.clear()
self.assertRaisesRegexp(
AirflowException,
'BackfillJob is deadlocked',
cli.backfill,
self.parser.parse_args(args))
cli.backfill(self.parser.parse_args(args + ['-I']))
ti = TI(dag.get_task('test_depends_on_past'), run_date)
ti.refresh_from_db()
# task ran
self.assertEqual(ti.state, State.SUCCESS)
dag.clear()
def test_sub_set_subdag(self):
dag = DAG(
'test_sub_set_subdag',
start_date=DEFAULT_DATE,
default_args={'owner': 'owner1'})
with dag:
op1 = DummyOperator(task_id='leave1')
op2 = DummyOperator(task_id='leave2')
op3 = DummyOperator(task_id='upstream_level_1')
op4 = DummyOperator(task_id='upstream_level_2')
op5 = DummyOperator(task_id='upstream_level_3')
# order randomly
op2.set_downstream(op3)
op1.set_downstream(op3)
op4.set_downstream(op5)
op3.set_downstream(op4)
dag.clear()
dr = dag.create_dagrun(run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE)
executor = TestExecutor(do_update=True)
sub_dag = dag.sub_dag(task_regex="leave*",
include_downstream=False,
include_upstream=False)
job = BackfillJob(dag=sub_dag,
start_date=DEFAULT_DATE,
end_date=DEFAULT_DATE,
executor=executor)
job.run()
self.assertRaises(sqlalchemy.orm.exc.NoResultFound, dr.refresh_from_db)
# the run_id should have changed, so a refresh won't work
drs = DagRun.find(dag_id=dag.dag_id, execution_date=DEFAULT_DATE)
dr = drs[0]
self.assertEqual(BackfillJob.ID_FORMAT_PREFIX.format(DEFAULT_DATE.isoformat()),
dr.run_id)
for ti in dr.get_task_instances():
if ti.task_id == 'leave1' or ti.task_id == 'leave2':
self.assertEqual(State.SUCCESS, ti.state)
else:
self.assertEqual(State.NONE, ti.state)
def test_backfill_execute_subdag(self):
dag = self.dagbag.get_dag('example_subdag_operator')
subdag_op_task = dag.get_task('section-1')
subdag = subdag_op_task.subdag
subdag.schedule_interval = '@daily'
start_date = datetime.datetime.now()
executor = TestExecutor(do_update=True)
job = BackfillJob(dag=subdag,
start_date=start_date,
end_date=start_date,
executor=executor,
donot_pickle=True)
job.run()
history = executor.history
subdag_history = history[0]
# check that all 5 task instances of the subdag 'section-1' were executed
self.assertEqual(5, len(subdag_history))
for sdh in subdag_history:
ti = sdh[3]
self.assertIn('section-1-task-', ti.task_id)
subdag.clear()
dag.clear()
class LocalTaskJobTest(unittest.TestCase):
def setUp(self):
pass
@patch.object(LocalTaskJob, "_is_descendant_process")
def test_localtaskjob_heartbeat(self, is_descendant):
session = settings.Session()
dag = DAG(
'test_localtaskjob_heartbeat',
start_date=DEFAULT_DATE,
default_args={'owner': 'owner1'})
with dag:
op1 = DummyOperator(task_id='op1')
dag.clear()
dr = dag.create_dagrun(run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session)
ti = dr.get_task_instance(task_id=op1.task_id, session=session)
ti.state = State.RUNNING
ti.hostname = "blablabla"
session.commit()
job1 = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor())
self.assertRaises(AirflowException, job1.heartbeat_callback)
is_descendant.return_value = True
ti.state = State.RUNNING
ti.hostname = socket.getfqdn()
ti.pid = 1
session.merge(ti)
session.commit()
ret = job1.heartbeat_callback()
self.assertEqual(ret, None)
is_descendant.return_value = False
self.assertRaises(AirflowException, job1.heartbeat_callback)
def test_localtaskjob_double_trigger(self):
dagbag = models.DagBag(
dag_folder=TEST_DAG_FOLDER,
include_examples=False,
)
dag = dagbag.dags.get('test_localtaskjob_double_trigger')
task = dag.get_task('test_localtaskjob_double_trigger_task')
session = settings.Session()
dag.clear()
dr = dag.create_dagrun(run_id="test",
state=State.SUCCESS,
execution_date=DEFAULT_DATE,
start_date=DEFAULT_DATE,
session=session)
ti = dr.get_task_instance(task_id=task.task_id, session=session)
ti.state = State.RUNNING
ti.hostname = socket.getfqdn()
ti.pid = 1
session.commit()
ti_run = TI(task=task, execution_date=DEFAULT_DATE)
job1 = LocalTaskJob(task_instance=ti_run, ignore_ti_state=True, executor=SequentialExecutor())
self.assertRaises(AirflowException, job1.run)
ti = dr.get_task_instance(task_id=task.task_id, session=session)
self.assertEqual(ti.pid, 1)
self.assertEqual(ti.state, State.RUNNING)
session.close()
class SchedulerJobTest(unittest.TestCase):
# These defaults make the test faster to run
default_scheduler_args = {"file_process_interval": 0,
"processor_poll_interval": 0.5}
def setUp(self):
self.dagbag = DagBag()
session = settings.Session()
session.query(models.ImportError).delete()
session.commit()
@staticmethod
def run_single_scheduler_loop_with_no_dags(dags_folder):
"""
Utility function that runs a single scheduler loop without actually
changing/scheduling any dags. This is useful to simulate the other side effects of
running a scheduler loop, e.g. to see what parse errors there are in the
dags_folder.
:param dags_folder: the directory to traverse
:type directory: str
"""
scheduler = SchedulerJob(
dag_id='this_dag_doesnt_exist', # We don't want to actually run anything
num_runs=1,
subdir=os.path.join(dags_folder))
scheduler.heartrate = 0
scheduler.run()
def test_concurrency(self):
dag_id = 'SchedulerJobTest.test_concurrency'
task_id_1 = 'dummy_task'
task_id_2 = 'dummy_task_nonexistent_queue'
# important that len(tasks) is less than concurrency
# because before scheduler._execute_task_instances would only
# check the num tasks once so if concurrency was 3,
# we could execute arbitrarily many tasks in the second run
dag = DAG(dag_id=dag_id, start_date=DEFAULT_DATE, concurrency=3)
task1 = DummyOperator(dag=dag, task_id=task_id_1)
task2 = DummyOperator(dag=dag, task_id=task_id_2)
dagbag = SimpleDagBag([dag])
scheduler = SchedulerJob(**self.default_scheduler_args)
session = settings.Session()
# create first dag run with 1 running and 1 queued
dr1 = scheduler.create_dag_run(dag)
ti1 = TI(task1, dr1.execution_date)
ti2 = TI(task2, dr1.execution_date)
ti1.refresh_from_db()
ti2.refresh_from_db()
ti1.state = State.RUNNING
ti2.state = State.RUNNING
session.merge(ti1)
session.merge(ti2)
session.commit()
self.assertEqual(State.RUNNING, dr1.state)
self.assertEqual(2, DAG.get_num_task_instances(dag_id, dag.task_ids,
states=[State.RUNNING], session=session))
# create second dag run
dr2 = scheduler.create_dag_run(dag)
ti3 = TI(task1, dr2.execution_date)
ti4 = TI(task2, dr2.execution_date)
ti3.refresh_from_db()
ti4.refresh_from_db()
# manually set to scheduled so we can pick them up
ti3.state = State.SCHEDULED
ti4.state = State.SCHEDULED
session.merge(ti3)
session.merge(ti4)
session.commit()
self.assertEqual(State.RUNNING, dr2.state)
scheduler._execute_task_instances(dagbag, [State.SCHEDULED])
# check that concurrency is respected
ti1.refresh_from_db()
ti2.refresh_from_db()
ti3.refresh_from_db()
ti4.refresh_from_db()
self.assertEqual(3, DAG.get_num_task_instances(dag_id, dag.task_ids,
states=[State.RUNNING, State.QUEUED], session=session))
self.assertEqual(State.RUNNING, ti1.state)
self.assertEqual(State.RUNNING, ti2.state)
six.assertCountEqual(self, [State.QUEUED, State.SCHEDULED], [ti3.state, ti4.state])
session.close()
@provide_session
def evaluate_dagrun(
self,
dag_id,
expected_task_states, # dict of task_id: state
dagrun_state,
run_kwargs=None,
advance_execution_date=False,
session=None):
"""
Helper for testing DagRun states with simple two-task DAGS.
This is hackish: a dag run is created but its tasks are
run by a backfill.
"""
if run_kwargs is None:
run_kwargs = {}
scheduler = SchedulerJob(**self.default_scheduler_args)
dag = self.dagbag.get_dag(dag_id)
dag.clear()
dr = scheduler.create_dag_run(dag)
if advance_execution_date:
# run a second time to schedule a dagrun after the start_date
dr = scheduler.create_dag_run(dag)
ex_date = dr.execution_date
try:
dag.run(start_date=ex_date, end_date=ex_date, **run_kwargs)
except AirflowException:
pass
# test tasks
for task_id, expected_state in expected_task_states.items():
task = dag.get_task(task_id)
ti = TI(task, ex_date)
ti.refresh_from_db()
self.assertEqual(ti.state, expected_state)
# load dagrun
dr = DagRun.find(dag_id=dag_id, execution_date=ex_date)
dr = dr[0]
dr.dag = dag
self.assertEqual(dr.state, dagrun_state)
def test_dagrun_fail(self):
"""
DagRuns with one failed and one incomplete root task -> FAILED
"""
self.evaluate_dagrun(
dag_id='test_dagrun_states_fail',
expected_task_states={
'test_dagrun_fail': State.FAILED,
'test_dagrun_succeed': State.UPSTREAM_FAILED,
},
dagrun_state=State.FAILED)
def test_dagrun_success(self):
"""
DagRuns with one failed and one successful root task -> SUCCESS
"""
self.evaluate_dagrun(
dag_id='test_dagrun_states_success',
expected_task_states={
'test_dagrun_fail': State.FAILED,
'test_dagrun_succeed': State.SUCCESS,
},
dagrun_state=State.SUCCESS)
def test_dagrun_root_fail(self):
"""
DagRuns with one successful and one failed root task -> FAILED
"""
self.evaluate_dagrun(
dag_id='test_dagrun_states_root_fail',
expected_task_states={
'test_dagrun_succeed': State.SUCCESS,
'test_dagrun_fail': State.FAILED,
},
dagrun_state=State.FAILED)
def test_dagrun_root_fail_unfinished(self):
"""
DagRuns with one unfinished and one failed root task -> RUNNING
"""
# Run both the failed and successful tasks
scheduler = SchedulerJob(**self.default_scheduler_args)
dag_id = 'test_dagrun_states_root_fail_unfinished'
dag = self.dagbag.get_dag(dag_id)
dag.clear()
dr = scheduler.create_dag_run(dag)
try:
dag.run(start_date=dr.execution_date, end_date=dr.execution_date)
except AirflowException: # Expect an exception since there is a failed task
pass
# Mark the successful task as never having run since we want to see if the
# dagrun will be in a running state despite haveing an unfinished task.
session = settings.Session()
ti = dr.get_task_instance('test_dagrun_unfinished', session=session)
ti.state = State.NONE
session.commit()
dr_state = dr.update_state()
self.assertEqual(dr_state, State.RUNNING)
def test_dagrun_deadlock_ignore_depends_on_past_advance_ex_date(self):
"""
DagRun is marked a success if ignore_first_depends_on_past=True
Test that an otherwise-deadlocked dagrun is marked as a success
if ignore_first_depends_on_past=True and the dagrun execution_date
is after the start_date.
"""
self.evaluate_dagrun(
dag_id='test_dagrun_states_deadlock',
expected_task_states={
'test_depends_on_past': State.SUCCESS,
'test_depends_on_past_2': State.SUCCESS,
},
dagrun_state=State.SUCCESS,
advance_execution_date=True,
run_kwargs=dict(ignore_first_depends_on_past=True))
def test_dagrun_deadlock_ignore_depends_on_past(self):
"""
Test that ignore_first_depends_on_past doesn't affect results
(this is the same test as
test_dagrun_deadlock_ignore_depends_on_past_advance_ex_date except
that start_date == execution_date so depends_on_past is irrelevant).
"""
self.evaluate_dagrun(
dag_id='test_dagrun_states_deadlock',
expected_task_states={
'test_depends_on_past': State.SUCCESS,
'test_depends_on_past_2': State.SUCCESS,
},
dagrun_state=State.SUCCESS,
run_kwargs=dict(ignore_first_depends_on_past=True))
def test_scheduler_start_date(self):
"""
Test that the scheduler respects start_dates, even when DAGS have run
"""
dag_id = 'test_start_date_scheduling'
dag = self.dagbag.get_dag(dag_id)
dag.clear()
self.assertTrue(dag.start_date > DEFAULT_DATE)
scheduler = SchedulerJob(dag_id,
num_runs=2,
**self.default_scheduler_args)
scheduler.run()
# zero tasks ran
session = settings.Session()
self.assertEqual(
len(session.query(TI).filter(TI.dag_id == dag_id).all()), 0)
# previously, running this backfill would kick off the Scheduler
# because it would take the most recent run and start from there
# That behavior still exists, but now it will only do so if after the
# start date
backfill = BackfillJob(
dag=dag,
start_date=DEFAULT_DATE,
end_date=DEFAULT_DATE)
backfill.run()
# one task ran
session = settings.Session()
self.assertEqual(
len(session.query(TI).filter(TI.dag_id == dag_id).all()), 1)
scheduler = SchedulerJob(dag_id,
num_runs=2,
**self.default_scheduler_args)
scheduler.run()
# still one task
session = settings.Session()
self.assertEqual(
len(session.query(TI).filter(TI.dag_id == dag_id).all()), 1)
def test_scheduler_multiprocessing(self):
"""
Test that the scheduler can successfully queue multiple dags in parallel
"""
dag_ids = ['test_start_date_scheduling', 'test_dagrun_states_success']
for dag_id in dag_ids:
dag = self.dagbag.get_dag(dag_id)
dag.clear()
scheduler = SchedulerJob(dag_ids=dag_ids,
file_process_interval=0,
processor_poll_interval=0.5,
num_runs=2)
scheduler.run()
# zero tasks ran
dag_id = 'test_start_date_scheduling'
session = settings.Session()
self.assertEqual(
len(session.query(TI).filter(TI.dag_id == dag_id).all()), 0)
def test_scheduler_dagrun_once(self):
"""
Test if the scheduler does not create multiple dagruns
if a dag is scheduled with @once and a start_date
"""
dag = DAG(
'test_scheduler_dagrun_once',
start_date=datetime.datetime(2015, 1, 1),
schedule_interval="@once")
scheduler = SchedulerJob()
dag.clear()
dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr)
dr = scheduler.create_dag_run(dag)
self.assertIsNone(dr)
def test_scheduler_process_task_instances(self):
"""
Test if _process_task_instances puts the right task instances into the
queue.
"""
dag = DAG(
dag_id='test_scheduler_process_execute_task',
start_date=DEFAULT_DATE)
dag_task1 = DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow')
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
session.merge(orm_dag)
session.commit()
session.close()
scheduler = SchedulerJob()
dag.clear()
dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr)
queue = mock.Mock()
scheduler._process_task_instances(dag, queue=queue)
queue.append.assert_called_with(
(dag.dag_id, dag_task1.task_id, DEFAULT_DATE)
)
def test_scheduler_do_not_schedule_removed_task(self):
dag = DAG(
dag_id='test_scheduler_do_not_schedule_removed_task',
start_date=DEFAULT_DATE)
dag_task1 = DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow')
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
session.merge(orm_dag)
session.commit()
session.close()
scheduler = SchedulerJob()
dag.clear()
dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr)
dag = DAG(
dag_id='test_scheduler_do_not_schedule_removed_task',
start_date=DEFAULT_DATE)
queue = mock.Mock()
scheduler._process_task_instances(dag, queue=queue)
queue.put.assert_not_called()
def test_scheduler_do_not_schedule_too_early(self):
dag = DAG(
dag_id='test_scheduler_do_not_schedule_too_early',
start_date=datetime.datetime(2200, 1, 1))
dag_task1 = DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow')
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
session.merge(orm_dag)
session.commit()
session.close()
scheduler = SchedulerJob()
dag.clear()
dr = scheduler.create_dag_run(dag)
self.assertIsNone(dr)
queue = mock.Mock()
scheduler._process_task_instances(dag, queue=queue)
queue.put.assert_not_called()
def test_scheduler_do_not_run_finished(self):
dag = DAG(
dag_id='test_scheduler_do_not_run_finished',
start_date=DEFAULT_DATE)
dag_task1 = DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow')
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
session.merge(orm_dag)
session.commit()
scheduler = SchedulerJob()
dag.clear()
dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr)
tis = dr.get_task_instances(session=session)
for ti in tis:
ti.state = State.SUCCESS
session.commit()
session.close()
queue = mock.Mock()
scheduler._process_task_instances(dag, queue=queue)
queue.put.assert_not_called()
def test_scheduler_add_new_task(self):
"""
Test if a task instance will be added if the dag is updated
"""
dag = DAG(
dag_id='test_scheduler_add_new_task',
start_date=DEFAULT_DATE)
dag_task1 = DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow')
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
session.merge(orm_dag)
session.commit()
session.close()
scheduler = SchedulerJob()
dag.clear()
dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr)
tis = dr.get_task_instances()
self.assertEquals(len(tis), 1)
dag_task2 = DummyOperator(
task_id='dummy2',
dag=dag,
owner='airflow')
queue = mock.Mock()
scheduler._process_task_instances(dag, queue=queue)
tis = dr.get_task_instances()
self.assertEquals(len(tis), 2)
def test_scheduler_verify_max_active_runs(self):
"""
Test if a a dagrun will not be scheduled if max_dag_runs has been reached
"""
dag = DAG(
dag_id='test_scheduler_verify_max_active_runs',
start_date=DEFAULT_DATE)
dag.max_active_runs = 1
dag_task1 = DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow')
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
session.merge(orm_dag)
session.commit()
session.close()
scheduler = SchedulerJob()
dag.clear()
dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr)
dr = scheduler.create_dag_run(dag)
self.assertIsNone(dr)
def test_scheduler_fail_dagrun_timeout(self):
"""
Test if a a dagrun wil be set failed if timeout
"""
dag = DAG(
dag_id='test_scheduler_fail_dagrun_timeout',
start_date=DEFAULT_DATE)
dag.dagrun_timeout = datetime.timedelta(seconds=60)
dag_task1 = DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow')
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
session.merge(orm_dag)
session.commit()
scheduler = SchedulerJob()
dag.clear()
dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr)
dr.start_date = datetime.datetime.now() - datetime.timedelta(days=1)
session.merge(dr)
session.commit()
dr2 = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr2)
dr.refresh_from_db(session=session)
self.assertEquals(dr.state, State.FAILED)
def test_scheduler_verify_max_active_runs_and_dagrun_timeout(self):
"""
Test if a a dagrun will not be scheduled if max_dag_runs has been reached and dagrun_timeout is not reached
Test if a a dagrun will be scheduled if max_dag_runs has been reached but dagrun_timeout is also reached
"""
dag = DAG(
dag_id='test_scheduler_verify_max_active_runs_and_dagrun_timeout',
start_date=DEFAULT_DATE)
dag.max_active_runs = 1
dag.dagrun_timeout = datetime.timedelta(seconds=60)
dag_task1 = DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow')
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
session.merge(orm_dag)
session.commit()
session.close()
scheduler = SchedulerJob()
dag.clear()
dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr)
# Should not be scheduled as DagRun has not timedout and max_active_runs is reached
new_dr = scheduler.create_dag_run(dag)
self.assertIsNone(new_dr)
# Should be scheduled as dagrun_timeout has passed
dr.start_date = datetime.datetime.now() - datetime.timedelta(days=1)
session.merge(dr)
session.commit()
new_dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(new_dr)
def test_scheduler_max_active_runs_respected_after_clear(self):
"""
Test if _process_task_instances only schedules ti's up to max_active_runs
(related to issue AIRFLOW-137)
"""
dag = DAG(
dag_id='test_scheduler_max_active_runs_respected_after_clear',
start_date=DEFAULT_DATE)
dag.max_active_runs = 3
dag_task1 = DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow')
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
session.merge(orm_dag)
session.commit()
session.close()
scheduler = SchedulerJob()
dag.clear()
# First create up to 3 dagruns in RUNNING state.
scheduler.create_dag_run(dag)
# Reduce max_active_runs to 1
dag.max_active_runs = 1
queue = mock.Mock()
# and schedule them in, so we can check how many
# tasks are put on the queue (should be one, not 3)
scheduler._process_task_instances(dag, queue=queue)
queue.append.assert_called_with(
(dag.dag_id, dag_task1.task_id, DEFAULT_DATE)
)
@patch.object(TI, 'pool_full')
def test_scheduler_verify_pool_full(self, mock_pool_full):
"""
Test task instances not queued when pool is full
"""
mock_pool_full.return_value = False
dag = DAG(
dag_id='test_scheduler_verify_pool_full',
start_date=DEFAULT_DATE)
DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow',
pool='test_scheduler_verify_pool_full')
session = settings.Session()
pool = Pool(pool='test_scheduler_verify_pool_full', slots=1)
session.add(pool)
orm_dag = DagModel(dag_id=dag.dag_id)
orm_dag.is_paused = False
session.merge(orm_dag)
session.commit()
scheduler = SchedulerJob()
dag.clear()
# Create 2 dagruns, which will create 2 task instances.
dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr)
self.assertEquals(dr.execution_date, DEFAULT_DATE)
dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr)
queue = []
scheduler._process_task_instances(dag, queue=queue)
self.assertEquals(len(queue), 2)
dagbag = SimpleDagBag([dag])
# Recreated part of the scheduler here, to kick off tasks -> executor
for ti_key in queue:
task = dag.get_task(ti_key[1])
ti = TI(task, ti_key[2])
# Task starts out in the scheduled state. All tasks in the
# scheduled state will be sent to the executor
ti.state = State.SCHEDULED
# Also save this task instance to the DB.
session.merge(ti)
session.commit()
scheduler._execute_task_instances(dagbag,
(State.SCHEDULED,
State.UP_FOR_RETRY))
self.assertEquals(len(scheduler.executor.queued_tasks), 1)
def test_scheduler_auto_align(self):
"""
Test if the schedule_interval will be auto aligned with the start_date
such that if the start_date coincides with the schedule the first
execution_date will be start_date, otherwise it will be start_date +
interval.
"""
dag = DAG(
dag_id='test_scheduler_auto_align_1',
start_date=datetime.datetime(2016, 1, 1, 10, 10, 0),
schedule_interval="4 5 * * *"
)
dag_task1 = DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow')
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
session.merge(orm_dag)
session.commit()
scheduler = SchedulerJob()
dag.clear()
dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr)
self.assertEquals(dr.execution_date, datetime.datetime(2016, 1, 2, 5, 4))
dag = DAG(
dag_id='test_scheduler_auto_align_2',
start_date=datetime.datetime(2016, 1, 1, 10, 10, 0),
schedule_interval="10 10 * * *"
)
dag_task1 = DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow')
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
session.merge(orm_dag)
session.commit()
scheduler = SchedulerJob()
dag.clear()
dr = scheduler.create_dag_run(dag)
self.assertIsNotNone(dr)
self.assertEquals(dr.execution_date, datetime.datetime(2016, 1, 1, 10, 10))
def test_scheduler_reschedule(self):
"""
Checks if tasks that are not taken up by the executor
get rescheduled
"""
executor = TestExecutor()
dagbag = DagBag(executor=executor)
dagbag.dags.clear()
dagbag.executor = executor
dag = DAG(
dag_id='test_scheduler_reschedule',
start_date=DEFAULT_DATE)
dag_task1 = DummyOperator(
task_id='dummy',
dag=dag,
owner='airflow')
dag.clear()
dag.is_subdag = False
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
orm_dag.is_paused = False
session.merge(orm_dag)
session.commit()
dagbag.bag_dag(dag=dag, root_dag=dag, parent_dag=dag)
@mock.patch('airflow.models.DagBag', return_value=dagbag)
@mock.patch('airflow.models.DagBag.collect_dags')
def do_schedule(function, function2):
# Use a empty file since the above mock will return the
# expected DAGs. Also specify only a single file so that it doesn't
# try to schedule the above DAG repeatedly.
scheduler = SchedulerJob(num_runs=1,
executor=executor,
subdir=os.path.join(settings.DAGS_FOLDER,
"no_dags.py"))
scheduler.heartrate = 0
scheduler.run()
do_schedule()
self.assertEquals(1, len(executor.queued_tasks))
executor.queued_tasks.clear()
do_schedule()
self.assertEquals(2, len(executor.queued_tasks))
def test_retry_still_in_executor(self):
"""
Checks if the scheduler does not put a task in limbo, when a task is retried
but is still present in the executor.
"""
executor = TestExecutor()
dagbag = DagBag(executor=executor)
dagbag.dags.clear()
dagbag.executor = executor
dag = DAG(
dag_id='test_retry_still_in_executor',
start_date=DEFAULT_DATE,
schedule_interval="@once")
dag_task1 = BashOperator(
task_id='test_retry_handling_op',
bash_command='exit 1',
retries=1,
dag=dag,
owner='airflow')
dag.clear()
dag.is_subdag = False
session = settings.Session()
orm_dag = DagModel(dag_id=dag.dag_id)
orm_dag.is_paused = False
session.merge(orm_dag)
session.commit()
dagbag.bag_dag(dag=dag, root_dag=dag, parent_dag=dag)
@mock.patch('airflow.models.DagBag', return_value=dagbag)
@mock.patch('airflow.models.DagBag.collect_dags')
def do_schedule(function, function2):
# Use a empty file since the above mock will return the
# expected DAGs. Also specify only a single file so that it doesn't
# try to schedule the above DAG repeatedly.
scheduler = SchedulerJob(num_runs=1,
executor=executor,
subdir=os.path.join(settings.DAGS_FOLDER,
"no_dags.py"))
scheduler.heartrate = 0
scheduler.run()
do_schedule()
self.assertEquals(1, len(executor.queued_tasks))
def run_with_error(task):
try:
task.run()
except AirflowException:
pass
ti_tuple = six.next(six.itervalues(executor.queued_tasks))
(command, priority, queue, ti) = ti_tuple
ti.task = dag_task1
# fail execution
run_with_error(ti)
self.assertEqual(ti.state, State.UP_FOR_RETRY)
self.assertEqual(ti.try_number, 1)
ti.refresh_from_db(lock_for_update=True, session=session)
ti.state = State.SCHEDULED
session.merge(ti)
session.commit()
# do not schedule
do_schedule()
self.assertTrue(executor.has_task(ti))
ti.refresh_from_db()
self.assertEqual(ti.state, State.SCHEDULED)
# now the executor has cleared and it should be allowed the re-queue
executor.queued_tasks.clear()
do_schedule()
ti.refresh_from_db()
self.assertEqual(ti.state, State.QUEUED)
@unittest.skipUnless("INTEGRATION" in os.environ, "Can only run end to end")
def test_retry_handling_job(self):
"""
Integration test of the scheduler not accidentally resetting
the try_numbers for a task
"""
dag = self.dagbag.get_dag('test_retry_handling_job')
dag_task1 = dag.get_task("test_retry_handling_op")
dag.clear()
scheduler = SchedulerJob(dag_id=dag.dag_id,
num_runs=1)
scheduler.heartrate = 0
scheduler.run()
session = settings.Session()
ti = session.query(TI).filter(TI.dag_id==dag.dag_id,
TI.task_id==dag_task1.task_id).first()
# make sure the counter has increased
self.assertEqual(ti.try_number, 2)
self.assertEqual(ti.state, State.UP_FOR_RETRY)
def test_scheduler_run_duration(self):
"""
Verifies that the scheduler run duration limit is followed.
"""
dag_id = 'test_start_date_scheduling'
dag = self.dagbag.get_dag(dag_id)
dag.clear()
self.assertTrue(dag.start_date > DEFAULT_DATE)
expected_run_duration = 5
start_time = datetime.datetime.now()
scheduler = SchedulerJob(dag_id,
run_duration=expected_run_duration,
**self.default_scheduler_args)
scheduler.run()
end_time = datetime.datetime.now()
run_duration = (end_time - start_time).total_seconds()
logging.info("Test ran in %.2fs, expected %.2fs",
run_duration,
expected_run_duration)
self.assertLess(run_duration - expected_run_duration, 5.0)
def test_dag_with_system_exit(self):
"""
Test to check that a DAG with a system.exit() doesn't break the scheduler.
"""
dag_id = 'exit_test_dag'
dag_ids = [dag_id]
dag_directory = os.path.join(settings.DAGS_FOLDER,
"..",
"dags_with_system_exit")
dag_file = os.path.join(dag_directory,
'b_test_scheduler_dags.py')
dagbag = DagBag(dag_folder=dag_file)
for dag_id in dag_ids:
dag = dagbag.get_dag(dag_id)
dag.clear()
scheduler = SchedulerJob(dag_ids=dag_ids,
subdir= dag_directory,
num_runs=1,
**self.default_scheduler_args)
scheduler.run()
session = settings.Session()
self.assertEqual(
len(session.query(TI).filter(TI.dag_id == dag_id).all()), 1)
def test_dag_get_active_runs(self):
"""
Test to check that a DAG returns it's active runs
"""
now = datetime.datetime.now()
six_hours_ago_to_the_hour = (now - datetime.timedelta(hours=6)).replace(minute=0, second=0, microsecond=0)
START_DATE = six_hours_ago_to_the_hour
DAG_NAME1 = 'get_active_runs_test'
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': START_DATE
}
dag1 = DAG(DAG_NAME1,
schedule_interval='* * * * *',
max_active_runs=1,
default_args=default_args
)
run_this_1 = DummyOperator(task_id='run_this_1', dag=dag1)
run_this_2 = DummyOperator(task_id='run_this_2', dag=dag1)
run_this_2.set_upstream(run_this_1)
run_this_3 = DummyOperator(task_id='run_this_3', dag=dag1)
run_this_3.set_upstream(run_this_2)
session = settings.Session()
orm_dag = DagModel(dag_id=dag1.dag_id)
session.merge(orm_dag)
session.commit()
session.close()
scheduler = SchedulerJob()
dag1.clear()
dr = scheduler.create_dag_run(dag1)
# We had better get a dag run
self.assertIsNotNone(dr)
execution_date = dr.execution_date
running_dates = dag1.get_active_runs()
try:
running_date = running_dates[0]
except:
running_date = 'Except'
self.assertEqual(execution_date, running_date, 'Running Date must match Execution Date')
def test_dag_catchup_option(self):
"""
Test to check that a DAG with catchup = False only schedules beginning now, not back to the start date
"""
now = datetime.datetime.now()
six_hours_ago_to_the_hour = (now - datetime.timedelta(hours=6)).replace(minute=0, second=0, microsecond=0)
three_minutes_ago = now - datetime.timedelta(minutes=3)
two_hours_and_three_minutes_ago = three_minutes_ago - datetime.timedelta(hours=2)
START_DATE = six_hours_ago_to_the_hour
DAG_NAME1 = 'no_catchup_test1'
DAG_NAME2 = 'no_catchup_test2'
DAG_NAME3 = 'no_catchup_test3'
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': START_DATE
}
dag1 = DAG(DAG_NAME1,
schedule_interval='* * * * *',
max_active_runs=1,
default_args=default_args
)
default_catchup = configuration.getboolean('scheduler', 'catchup_by_default')
# Test configs have catchup by default ON
self.assertEqual(default_catchup, True)
# Correct default?
self.assertEqual(dag1.catchup, True)
dag2 = DAG(DAG_NAME2,
schedule_interval='* * * * *',
max_active_runs=1,
catchup=False,
default_args=default_args
)
run_this_1 = DummyOperator(task_id='run_this_1', dag=dag2)
run_this_2 = DummyOperator(task_id='run_this_2', dag=dag2)
run_this_2.set_upstream(run_this_1)
run_this_3 = DummyOperator(task_id='run_this_3', dag=dag2)
run_this_3.set_upstream(run_this_2)
session = settings.Session()
orm_dag = DagModel(dag_id=dag2.dag_id)
session.merge(orm_dag)
session.commit()
session.close()
scheduler = SchedulerJob()
dag2.clear()
dr = scheduler.create_dag_run(dag2)
# We had better get a dag run
self.assertIsNotNone(dr)
# The DR should be scheduled in the last 3 minutes, not 6 hours ago
self.assertGreater(dr.execution_date, three_minutes_ago)
# The DR should be scheduled BEFORE now
self.assertLess(dr.execution_date, datetime.datetime.now())
dag3 = DAG(DAG_NAME3,
schedule_interval='@hourly',
max_active_runs=1,
catchup=False,
default_args=default_args
)
run_this_1 = DummyOperator(task_id='run_this_1', dag=dag3)
run_this_2 = DummyOperator(task_id='run_this_2', dag=dag3)
run_this_2.set_upstream(run_this_1)
run_this_3 = DummyOperator(task_id='run_this_3', dag=dag3)
run_this_3.set_upstream(run_this_2)
session = settings.Session()
orm_dag = DagModel(dag_id=dag3.dag_id)
session.merge(orm_dag)
session.commit()
session.close()
scheduler = SchedulerJob()
dag3.clear()
dr = None
dr = scheduler.create_dag_run(dag3)
# We had better get a dag run
self.assertIsNotNone(dr)
# The DR should be scheduled in the last two hours, not 6 hours ago
self.assertGreater(dr.execution_date, two_hours_and_three_minutes_ago)
# The DR should be scheduled BEFORE now
self.assertLess(dr.execution_date, datetime.datetime.now())
def test_add_unparseable_file_before_sched_start_creates_import_error(self):
try:
dags_folder = mkdtemp()
unparseable_filename = os.path.join(dags_folder, TEMP_DAG_FILENAME)
with open(unparseable_filename, 'w') as unparseable_file:
unparseable_file.writelines(UNPARSEABLE_DAG_FILE_CONTENTS)
self.run_single_scheduler_loop_with_no_dags(dags_folder)
finally:
shutil.rmtree(dags_folder)
session = settings.Session()
import_errors = session.query(models.ImportError).all()
self.assertEqual(len(import_errors), 1)
import_error = import_errors[0]
self.assertEqual(import_error.filename,
unparseable_filename)
self.assertEqual(import_error.stacktrace,
"invalid syntax ({}, line 1)".format(TEMP_DAG_FILENAME))
def test_add_unparseable_file_after_sched_start_creates_import_error(self):
try:
dags_folder = mkdtemp()
unparseable_filename = os.path.join(dags_folder, TEMP_DAG_FILENAME)
self.run_single_scheduler_loop_with_no_dags(dags_folder)
with open(unparseable_filename, 'w') as unparseable_file:
unparseable_file.writelines(UNPARSEABLE_DAG_FILE_CONTENTS)
self.run_single_scheduler_loop_with_no_dags(dags_folder)
finally:
shutil.rmtree(dags_folder)
session = settings.Session()
import_errors = session.query(models.ImportError).all()
self.assertEqual(len(import_errors), 1)
import_error = import_errors[0]
self.assertEqual(import_error.filename,
unparseable_filename)
self.assertEqual(import_error.stacktrace,
"invalid syntax ({}, line 1)".format(TEMP_DAG_FILENAME))
def test_no_import_errors_with_parseable_dag(self):
try:
dags_folder = mkdtemp()
parseable_filename = os.path.join(dags_folder, TEMP_DAG_FILENAME)
with open(parseable_filename, 'w') as parseable_file:
parseable_file.writelines(PARSEABLE_DAG_FILE_CONTENTS)
self.run_single_scheduler_loop_with_no_dags(dags_folder)
finally:
shutil.rmtree(dags_folder)
session = settings.Session()
import_errors = session.query(models.ImportError).all()
self.assertEqual(len(import_errors), 0)
def test_new_import_error_replaces_old(self):
try:
dags_folder = mkdtemp()
unparseable_filename = os.path.join(dags_folder, TEMP_DAG_FILENAME)
# Generate original import error
with open(unparseable_filename, 'w') as unparseable_file:
unparseable_file.writelines(UNPARSEABLE_DAG_FILE_CONTENTS)
self.run_single_scheduler_loop_with_no_dags(dags_folder)
# Generate replacement import error (the error will be on the second line now)
with open(unparseable_filename, 'w') as unparseable_file:
unparseable_file.writelines(
PARSEABLE_DAG_FILE_CONTENTS +
os.linesep +
UNPARSEABLE_DAG_FILE_CONTENTS)
self.run_single_scheduler_loop_with_no_dags(dags_folder)
finally:
shutil.rmtree(dags_folder)
session = settings.Session()
import_errors = session.query(models.ImportError).all()
self.assertEqual(len(import_errors), 1)
import_error = import_errors[0]
self.assertEqual(import_error.filename,
unparseable_filename)
self.assertEqual(import_error.stacktrace,
"invalid syntax ({}, line 2)".format(TEMP_DAG_FILENAME))
def test_remove_error_clears_import_error(self):
try:
dags_folder = mkdtemp()
filename_to_parse = os.path.join(dags_folder, TEMP_DAG_FILENAME)
# Generate original import error
with open(filename_to_parse, 'w') as file_to_parse:
file_to_parse.writelines(UNPARSEABLE_DAG_FILE_CONTENTS)
self.run_single_scheduler_loop_with_no_dags(dags_folder)
# Remove the import error from the file
with open(filename_to_parse, 'w') as file_to_parse:
file_to_parse.writelines(
PARSEABLE_DAG_FILE_CONTENTS)
self.run_single_scheduler_loop_with_no_dags(dags_folder)
finally:
shutil.rmtree(dags_folder)
session = settings.Session()
import_errors = session.query(models.ImportError).all()
self.assertEqual(len(import_errors), 0)
def test_remove_file_clears_import_error(self):
try:
dags_folder = mkdtemp()
filename_to_parse = os.path.join(dags_folder, TEMP_DAG_FILENAME)
# Generate original import error
with open(filename_to_parse, 'w') as file_to_parse:
file_to_parse.writelines(UNPARSEABLE_DAG_FILE_CONTENTS)
self.run_single_scheduler_loop_with_no_dags(dags_folder)
finally:
shutil.rmtree(dags_folder)
# Rerun the scheduler once the dag file has been removed
self.run_single_scheduler_loop_with_no_dags(dags_folder)
session = settings.Session()
import_errors = session.query(models.ImportError).all()
self.assertEqual(len(import_errors), 0)
|
import shutil
import os.path
import pytest
import hashlib
import operator
from unittest import TestCase
from pyspark.sql.functions import col, concat, max, min, array, udf, lit
from pyspark.sql.types import StructType, StructField, StringType, IntegerType, ArrayType, \
DoubleType
from bigdl.orca import OrcaContext
from bigdl.friesian.feature import FeatureTable, StringIndex, TargetCode
from bigdl.dllib.nncontext import *
class TestTable(TestCase):
def setup_method(self, method):
""" setup any state tied to the execution of the given method in a
class. setup_method is invoked for every test method of a class.
"""
self.resource_path = os.path.join(os.path.split(__file__)[0], "../resources")
def test_apply(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
feature_tbl = feature_tbl.fillna(0, "col_1")
# udf on single column
transform = lambda x: x + 1
feature_tbl = feature_tbl.apply("col_1", "new_col_1", transform, dtype="int")
col1_values = feature_tbl.select("col_1").df.rdd.flatMap(lambda x: x).collect()
updated_col1_values = feature_tbl.select("new_col_1").df.rdd.flatMap(lambda x: x).collect()
assert [v + 1 for v in col1_values] == updated_col1_values
# udf on multi columns
transform = lambda x: "xxxx"
feature_tbl = feature_tbl.apply(["col_2", "col_4", "col_5"], "out", transform)
out_values = feature_tbl.select("out").df.rdd.flatMap(lambda x: x).collect()
assert out_values == ["xxxx"] * len(out_values)
def test_apply_with_data(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
feature_tbl = feature_tbl.fillna(0, "col_1")
# udf on single column
y = {"ace": 1, "aa": 2}
transform = lambda x: y.get(x, 0)
feature_tbl = feature_tbl.apply("col_5", "out", transform, "int")
assert(feature_tbl.filter(col("out") == 2).size() == 3)
assert(feature_tbl.filter(col("out") == 1).size() == 1)
assert(feature_tbl.filter(col("out") == 0).size() == 1)
def test_fillna_int(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
filled_tbl = feature_tbl.fillna(5, ["col_2", "col_3"])
assert isinstance(filled_tbl, FeatureTable), "filled_tbl should be a FeatureTable"
assert feature_tbl.df.filter("col_2 is null").count() != 0 and feature_tbl \
.df.filter("col_3 is null").count() != 0, "feature_tbl should not be changed"
assert filled_tbl.df.filter("col_2 == 5").count() == 1, "col_2 null values should be " \
"filled with 5"
assert filled_tbl.df.filter("col_3 == 5").count() == 1, "col_3 null values should be " \
"filled with 5"
filled_tbl = feature_tbl.fillna(5, None)
assert filled_tbl.df.filter("col_2 == 5").count() == 1, "col_2 null values should be " \
"filled with 5"
assert filled_tbl.df.filter("col_3 == 5").count() == 1, "col_3 null values should be " \
"filled with 5"
with self.assertRaises(Exception) as context:
feature_tbl.fillna(0, ["col_2", "col_3", "col_8"])
self.assertTrue('do not exist in this Table' in str(context.exception))
def test_fillna_double(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
filled_tbl = feature_tbl.fillna(3.2, ["col_2", "col_3"])
assert isinstance(filled_tbl, FeatureTable), "filled_tbl should be a FeatureTable"
assert feature_tbl.df.filter("col_2 is null").count() != 0 and feature_tbl \
.df.filter("col_3 is null").count() != 0, "feature_tbl should not be changed"
assert filled_tbl.df.filter("col_2 is null").count() == 0, "col_2 null values should be " \
"filled"
assert filled_tbl.df.filter("col_3 is null").count() == 0, "col_3 null values should be " \
"filled"
filled_tbl = feature_tbl.fillna(5, ["col_2", "col_3"])
assert filled_tbl.df.filter("col_2 == 5").count() == 1, "col_2 null values should be " \
"filled with 5"
assert filled_tbl.df.filter("col_3 == 5").count() == 1, "col_3 null values should be " \
"filled with 5"
def test_fillna_long(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
filled_tbl = feature_tbl.fillna(3, ["col_1", "col_2", "col_3"])
assert isinstance(filled_tbl, FeatureTable), "filled_tbl should be a FeatureTable"
assert feature_tbl.df.filter("col_2 is null").count() != 0 and feature_tbl \
.df.filter("col_3 is null").count() != 0, "feature_tbl should not be changed"
assert filled_tbl.df.filter("col_1 is null").count() == 0, "col_1 null values should be " \
"filled"
assert filled_tbl.df.filter("col_2 is null").count() == 0, "col_2 null values should be " \
"filled"
assert filled_tbl.df.filter("col_3 is null").count() == 0, "col_3 null values should be " \
"filled"
def test_fillna_string(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
with self.assertRaises(Exception) as context:
feature_tbl.fillna(3.2, ["col_4", "col_5"])
self.assertTrue('numeric does not match the type of column col_4' in str(context.exception))
filled_tbl = feature_tbl.fillna("bb", ["col_4", "col_5"])
assert isinstance(filled_tbl, FeatureTable), "filled_tbl should be a FeatureTable"
assert filled_tbl.df.filter("col_4 is null").count() == 0, "col_4 null values should be " \
"filled"
assert filled_tbl.df.filter("col_5 is null").count() == 0, "col_5 null values should be " \
"filled"
def test_filter_by_frequency(self):
data = [("a", "b", 1),
("b", "a", 2),
("a", "bc", 3),
("c", "c", 2),
("b", "a", 2),
("ab", "c", 1),
("c", "b", 1),
("a", "b", 1)]
schema = StructType([StructField("A", StringType(), True),
StructField("B", StringType(), True),
StructField("C", IntegerType(), True)])
spark = OrcaContext.get_spark_session()
df = spark.createDataFrame(data, schema)
tbl = FeatureTable(df).filter_by_frequency(["A", "B", "C"])
assert tbl.to_spark_df().count() == 2, "the count of frequency >=2 should be 2"
def test_hash_encode(self):
spark = OrcaContext.get_spark_session()
data = [("a", "b", 1),
("b", "a", 2),
("a", "c", 3),
("c", "c", 2),
("b", "a", 1),
("a", "d", 1)]
schema = StructType([StructField("A", StringType(), True),
StructField("B", StringType(), True),
StructField("C", IntegerType(), True)])
df = spark.createDataFrame(data, schema)
tbl = FeatureTable(df)
hash_str = lambda x: hashlib.md5(str(x).encode('utf-8', 'strict')).hexdigest()
hash_int = lambda x: int(hash_str(x), 16) % 100
hash_value = []
for row in df.collect():
hash_value.append(hash_int(row[0]))
tbl_hash = []
for record in tbl.hash_encode(["A"], 100).to_spark_df().collect():
tbl_hash.append(int(record[0]))
assert(operator.eq(hash_value, tbl_hash)), "the hash encoded value should be equal"
def test_cross_hash_encode(self):
spark = OrcaContext.get_spark_session()
data = [("a", "b", "c", 1),
("b", "a", "d", 2),
("a", "c", "e", 3),
("c", "c", "c", 2),
("b", "a", "d", 1),
("a", "d", "e", 1)]
schema = StructType([StructField("A", StringType(), True),
StructField("B", StringType(), True),
StructField("C", StringType(), True),
StructField("D", IntegerType(), True)])
df = spark.createDataFrame(data, schema)
cross_hash_df = df.withColumn("A_B_C", concat("A", "B", "C"))
tbl = FeatureTable(df)
cross_hash_str = lambda x: hashlib.md5(str(x).encode('utf-8', 'strict')).hexdigest()
cross_hash_int = lambda x: int(cross_hash_str(x), 16) % 100
cross_hash_value = []
for row in cross_hash_df.collect():
cross_hash_value.append(cross_hash_int(row[4]))
tbl_cross_hash = []
for record in tbl.cross_hash_encode(["A", "B", "C"], 100).to_spark_df().collect():
tbl_cross_hash.append(int(record[4]))
assert(operator.eq(cross_hash_value, tbl_cross_hash)), "the crossed hash encoded value" \
"should be equal"
def test_gen_string_idx(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
string_idx_list = feature_tbl.gen_string_idx(["col_4", "col_5"], freq_limit=1)
assert string_idx_list[0].size() == 3, "col_4 should have 3 indices"
assert string_idx_list[1].size() == 2, "col_5 should have 2 indices"
with tempfile.TemporaryDirectory() as local_path:
for str_idx in string_idx_list:
str_idx.write_parquet(local_path)
str_idx_log = str_idx.log(["id"])
assert str_idx.df.filter("id == 1").count() == 1, "id in str_idx should = 1"
assert str_idx_log.df.filter("id == 1").count() == 0, "id in str_idx_log should " \
"!= 1"
assert os.path.isdir(local_path + "/col_4.parquet")
assert os.path.isdir(local_path + "/col_5.parquet")
new_col_4_idx = StringIndex.read_parquet(local_path + "/col_4.parquet")
assert "col_4" in new_col_4_idx.df.columns, "col_4 should be a column of new_col_4_idx"
with self.assertRaises(Exception) as context:
StringIndex.read_parquet(local_path + "/col_5.parquet", "col_4")
self.assertTrue('col_4 should be a column of the DataFrame' in str(context.exception))
def test_gen_string_idx_dict(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
string_idx_list = feature_tbl.gen_string_idx(["col_4", "col_5"], freq_limit={"col_4": 1,
"col_5": 3})
with self.assertRaises(Exception) as context:
feature_tbl.gen_string_idx(["col_4", "col_5"], freq_limit="col_4:1,col_5:3")
self.assertTrue('freq_limit only supports int, dict or None, but get str' in str(
context.exception))
assert string_idx_list[0].size() == 3, "col_4 should have 3 indices"
assert string_idx_list[1].size() == 1, "col_5 should have 1 indices"
def test_gen_string_idx_none(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
string_idx_list = feature_tbl.gen_string_idx(["col_4", "col_5"], freq_limit=None)
assert string_idx_list[0].size() == 3, "col_4 should have 3 indices"
assert string_idx_list[1].size() == 2, "col_5 should have 2 indices"
def test_gen_reindex_mapping(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
string_idx_list = feature_tbl.gen_string_idx(["col_4", "col_5"],
freq_limit={"col_4": 1, "col_5": 1},
order_by_freq=False)
tbl = feature_tbl.encode_string(["col_4", "col_5"], string_idx_list)
index_tbls = tbl.gen_reindex_mapping(["col_4", "col_5"], 1)
assert(index_tbls[0].size() == 3)
assert(index_tbls[1].size() == 2)
def test_gen_string_idx_union(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
string_idx_list1 = feature_tbl \
.gen_string_idx(["col_4", 'col_5'],
freq_limit=1)
assert string_idx_list1[0].size() == 3, "col_4 should have 3 indices"
assert string_idx_list1[1].size() == 2, "col_5 should have 2 indices"
new_tbl1 = feature_tbl.encode_string(['col_4', 'col_5'], string_idx_list1)
assert new_tbl1.max("col_5").to_list("max")[0] == 2, "col_5 max value should be 2"
string_idx_list2 = feature_tbl \
.gen_string_idx(["col_4", {"src_cols": ["col_4", "col_5"], "col_name": 'col_5'}],
freq_limit=1)
assert string_idx_list2[0].size() == 3, "col_4 should have 3 indices"
assert string_idx_list2[1].size() == 4, "col_5 should have 4 indices"
new_tbl2 = feature_tbl.encode_string(['col_4', 'col_5'], string_idx_list2)
assert new_tbl2.max("col_5").to_list("max")[0] == 4, "col_5 max value should be 4"
string_idx_3 = feature_tbl \
.gen_string_idx({"src_cols": ["col_4", "col_5"], "col_name": 'col_5'}, freq_limit=1)
assert string_idx_3.size() == 4, "col_5 should have 4 indices"
new_tbl3 = feature_tbl.encode_string('col_5', string_idx_3)
assert new_tbl3.max("col_5").to_list("max")[0] == 4, "col_5 max value should be 4"
def test_gen_string_idx_split(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
to_list_str = udf(lambda arr: ','.join(arr))
df = feature_tbl.dropna(['col_4', 'col_5']).df.withColumn("list1", array('col_4', 'col_5'))\
.withColumn("list1", to_list_str(col("list1")))
tbl = FeatureTable(df)
string_idx_1 = tbl.gen_string_idx("list1", do_split=True, sep=",", freq_limit=1)
assert string_idx_1.size() == 4, "list1 should have 4 indices"
new_tbl1 = tbl.encode_string('list1', string_idx_1, do_split=True, sep=",")
assert isinstance(new_tbl1.to_list("list1"), list), \
"encode list should return list of int"
new_tbl2 = tbl.encode_string(['list1'], string_idx_1, do_split=True, sep=",",
sort_for_array=True)
l1 = new_tbl2.to_list("list1")[0]
l2 = l1.copy()
l2.sort()
assert l1 == l2, "encode list with sort should sort"
new_tbl3 = tbl.encode_string(['list1'], string_idx_1, do_split=True, sep=",",
keep_most_frequent=True)
assert isinstance(new_tbl3.to_list("list1")[0], int), \
"encode list with keep most frequent should only keep one int"
def test_clip(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
clip_tbl = feature_tbl.clip(["col_1", "col_2", "col_3"], min=2, max=None)
assert isinstance(clip_tbl, FeatureTable), "clip_tbl should be a FeatureTable"
assert feature_tbl.df.filter("col_1 < 2").count() != 0 and feature_tbl \
.df.filter("col_2 < 2").count() != 0, "feature_tbl should not be changed"
assert clip_tbl.df.filter("col_1 < 2").count() == 0, "col_1 should >= 2"
assert clip_tbl.df.filter("col_2 < 2").count() == 0, "col_2 should >= 2"
assert clip_tbl.df.filter("col_3 < 2").count() == 0, "col_3 should >= 2"
with self.assertRaises(Exception) as context:
feature_tbl.clip(None, 2)
self.assertTrue('columns should be str or a list of str, but got None.'
in str(context.exception))
feature_tbl = FeatureTable.read_parquet(file_path)
clip_tbl = feature_tbl.clip(["col_1", "col_2", "col_3"], min=None, max=1)
assert isinstance(clip_tbl, FeatureTable), "clip_tbl should be a FeatureTable"
assert feature_tbl.df.filter("col_1 > 1").count() != 0 and feature_tbl \
.df.filter("col_2 > 1").count() != 0, "feature_tbl should not be changed"
assert clip_tbl.df.filter("col_1 > 1").count() == 0, "col_1 should <= 1"
assert clip_tbl.df.filter("col_2 > 1").count() == 0, "col_2 should <= 1"
assert clip_tbl.df.filter("col_3 > 1").count() == 0, "col_3 should <= 1"
feature_tbl = FeatureTable.read_parquet(file_path)
clip_tbl = feature_tbl.clip(["col_1", "col_2", "col_3"], min=0, max=1)
assert isinstance(clip_tbl, FeatureTable), "clip_tbl should be a FeatureTable"
assert feature_tbl.df.filter("col_1 > 1 or col_1 < 0").count() != 0 and feature_tbl \
.df.filter("col_2 > 1 or col_2 < 0").count() != 0, "feature_tbl should not be changed"
assert clip_tbl.df.filter("col_1 < 0").count() == 0, "col_1 should >= 0"
assert clip_tbl.df.filter("col_2 > 1").count() == 0, "col_2 should <= 1"
assert clip_tbl.df.filter("col_3 < 0 or col_3 > 1").count() == 0, "col_3 should >=0 " \
"and <= 1"
def test_dropna(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
dropped_tbl = feature_tbl.dropna(["col_1", "col_4"])
assert isinstance(dropped_tbl, FeatureTable), "dropped_tbl should be a FeatureTable"
assert feature_tbl.df.filter("col_1 is null").count() != 0 and feature_tbl\
.df.filter("col_4 is null").count() != 0, "feature_tbl should not be changed"
assert dropped_tbl.df.filter("col_1 is null").count() == 0, "col_1 null values should " \
"be dropped"
assert dropped_tbl.df.filter("col_4 is null").count() == 0, "col_4 null values should " \
"be dropped"
assert 0 < dropped_tbl.df.count() < feature_tbl.df.count(), "the number of rows should " \
"be decreased"
dropped_tbl = feature_tbl.dropna(["col_1", "col_4"], how="all")
assert dropped_tbl.df.filter("col_1 is null and col_4 is null").count() == 0, \
"col_1 and col_4 should not both have null values"
dropped_tbl = feature_tbl.dropna(["col_2", "col_4"], how="all")
assert dropped_tbl.df.filter("col_2 is null").count() > 0, \
"col_2 should still have null values after dropna with how=all"
dropped_tbl = feature_tbl.dropna(["col_2", "col_3", "col_5"], thresh=2)
assert dropped_tbl.df.filter("col_2 is null").count() > 0, \
"col_2 should still have null values after dropna with thresh=2"
assert dropped_tbl.df.filter("col_3 is null and col_5 is null").count() == 0, \
"col_3 and col_5 should not both have null values"
def test_fill_median(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
with self.assertRaises(Exception) as context:
feature_tbl.fill_median(["col_4", "col_5"])
self.assertTrue('col_4 with data type StringType is not supported' in
str(context.exception))
filled_tbl = feature_tbl.fill_median(["col_1", "col_2"])
assert isinstance(filled_tbl, FeatureTable), "filled_tbl should be a FeatureTable"
assert filled_tbl.df.filter("col_1 is null").count() == 0, "col_1 null values should be " \
"filled"
assert filled_tbl.df.filter("col_2 is null").count() == 0, "col_2 null values should be " \
"filled"
def test_filter(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
filtered_tbl = feature_tbl.filter(feature_tbl.col_1 == 1)
assert filtered_tbl.size() == 3, "Only 3 out of 5 rows has value 1 for col_1"
filtered_tbl2 = feature_tbl.filter(
(feature_tbl.col("col_1") == 1) & (feature_tbl.col_2 == 1))
assert filtered_tbl2.size() == 1, "Only 1 out of 5 rows has value 1 for col_1 and col_2"
def test_random_split(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
table1, table2 = feature_tbl.random_split([0.8, 0.2], seed=1)
cnt1, cnt2 = table1.size(), table2.size()
cnt = feature_tbl.size()
assert cnt == cnt1 + cnt2, "size of full table should equal to sum of size of splited ones"
def test_rename(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
name_dict = {"col_1": "new_col1", "col_4": "new_col4"}
rename_tbl = feature_tbl.rename(name_dict)
cols = rename_tbl.df.columns
assert isinstance(rename_tbl, FeatureTable), "rename_tbl should be a FeatureTable"
assert "col_1" in feature_tbl.df.columns, "feature_tbl should not be changed"
assert "new_col1" in cols, "new_col1 should be a column of the renamed tbl."
assert "new_col4" in cols, "new_col4 should be a column of the renamed tbl."
def test_log(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
log_tbl = feature_tbl.log(["col_1", "col_2", "col_3"])
assert isinstance(log_tbl, FeatureTable), "log_tbl should be a FeatureTable"
assert feature_tbl.df.filter("col_1 == 1").count() != 0 and feature_tbl \
.df.filter("col_2 == 1").count() != 0, "feature_tbl should not be changed"
assert log_tbl.df.filter("col_1 == 1").count() == 0, "col_1 should != 1"
assert log_tbl.df.filter("col_2 == 1").count() == 0, "col_2 should != 1"
assert log_tbl.df.filter("col_3 == 1").count() == 0, "col_3 should != 1"
def test_merge(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
merged_tbl = feature_tbl.merge_cols(["col_1", "col_2", "col_3"], "int_cols")
assert "col_1" not in merged_tbl.df.columns, "col_1 shouldn't be a column of merged_tbl"
assert "int_cols" in merged_tbl.df.columns, "int_cols should be a column of merged_tbl"
assert "col_1" in feature_tbl.df.columns, "col_1 should be a column of feature_tbl"
def test_norm(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path).fillna(0, ["col_2", "col_3"])
normalized_tbl, min_max_dic = feature_tbl.min_max_scale(["col_2"])
max_value = normalized_tbl.df.select("col_2") \
.agg(max(col("col_2")).alias("max")) \
.rdd.map(lambda row: row['max']).collect()[0]
min_value = normalized_tbl.df.select("col_2") \
.agg(min(col("col_2")).alias("min")) \
.rdd.map(lambda row: row['min']).collect()[0]
assert max_value <= 1, "col_2 shouldn't be more than 1 after normalization"
assert min_value >= 0, "col_2 shouldn't be less than 0 after normalization"
tbl2 = FeatureTable(feature_tbl.df.withColumn("col2-col3", array(["col_2", "col_3"])))
normalized_tbl2, min_max_dic2 = tbl2.min_max_scale(["col_2", "col2-col3"])
test_file_path = os.path.join(self.resource_path, "parquet/data3.parquet")
test_tbl = FeatureTable.read_parquet(test_file_path).fillna(0, ["col_2", "col_3"])
scaled = test_tbl.transform_min_max_scale(["col_2"], min_max_dic)
max_value = scaled.df.select("col_2") \
.agg(max(col("col_2")).alias("max")) \
.rdd.map(lambda row: row['max']).collect()[0]
min_value = scaled.df.select("col_2") \
.agg(min(col("col_2")).alias("min")) \
.rdd.map(lambda row: row['min']).collect()[0]
assert max_value <= 1, "col_2 shouldn't be more than 1 after normalization"
assert min_value >= 0, "col_2 shouldn't be less than 0 after normalization"
test_tbl2 = FeatureTable(test_tbl.df.withColumn("col2-col3", array(["col_2", "col_3"])))
scaled2 = test_tbl2.transform_min_max_scale(["col_2", "col2-col3"], min_max_dic2)
max_value = scaled2.df.select("col2-col3") \
.agg(max(col("col2-col3")).alias("max")) \
.rdd.map(lambda row: row['max']).collect()[0]
min_value = scaled2.df.select("col2-col3") \
.agg(min(col("col2-col3")).alias("min")) \
.rdd.map(lambda row: row['min']).collect()[0]
assert max_value[0] <= 1 and max_value[1] <= 1, \
"col2-col3 shouldn't be more than 1 after normalization"
assert min_value[0] >= 0 and min_value[1] >= 0, \
"col2-col3 shouldn't be less than 0 after normalization"
def test_cross(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path).fillna(0, ["col_2", "col_3"])
crossed_tbl = feature_tbl.cross_columns([["col_2", "col_3"]], [100])
assert "col_2_col_3" in crossed_tbl.df.columns, "crossed column is not created"
max_value = crossed_tbl.df.select("col_2_col_3") \
.agg(max(col("col_2_col_3")).alias("max")) \
.rdd.map(lambda row: row['max']).collect()[0]
min_value = crossed_tbl.df.select("col_2_col_3") \
.agg(min(col("col_2_col_3")).alias("min")) \
.rdd.map(lambda row: row['min']).collect()[0]
assert max_value <= 100, "cross value shouldn't be more than 100 after cross"
assert min_value > 0, "cross value shouldn't be less than 0 after cross"
def test_add_negative_items(self):
spark = OrcaContext.get_spark_session()
data = [("jack", 1, "2019-07-01 12:01:19.000"),
("jack", 2, "2019-08-01 12:01:19.000"),
("jack", 3, "2019-09-01 12:01:19.000"),
("alice", 4, "2019-09-01 12:01:19.000"),
("alice", 5, "2019-10-01 12:01:19.000"),
("alice", 6, "2019-11-01 12:01:19.000")]
schema = StructType([
StructField("name", StringType(), True),
StructField("item", IntegerType(), True),
StructField("time", StringType(), True)
])
df = spark.createDataFrame(data=data, schema=schema)
tbl = FeatureTable(df).add_negative_samples(10)
dft = tbl.df
assert tbl.size() == 12
assert dft.filter("label == 1").count() == 6
assert dft.filter("label == 0").count() == 6
def test_add_hist_seq(self):
spark = OrcaContext.get_spark_session()
data = [("jack", 1, "2019-07-01 12:01:19.000"),
("jack", 2, "2019-08-01 12:01:19.000"),
("jack", 3, "2019-09-01 12:01:19.000"),
("jack", 4, "2019-07-02 12:01:19.000"),
("jack", 5, "2019-08-03 12:01:19.000"),
("jack", 6, "2019-07-04 12:01:19.000"),
("jack", 7, "2019-08-05 12:01:19.000"),
("alice", 4, "2019-09-01 12:01:19.000"),
("alice", 5, "2019-10-01 12:01:19.000"),
("alice", 6, "2019-11-01 12:01:19.000")]
schema = StructType([StructField("name", StringType(), True),
StructField("item", IntegerType(), True),
StructField("time", StringType(), True)])
df = spark.createDataFrame(data=data, schema=schema)
df = df.withColumn("ts", col("time").cast("timestamp").cast("long"))
tbl = FeatureTable(df.select("name", "item", "ts")) \
.add_hist_seq(["item"], "name", "ts", 1, 4)
tbl2 = FeatureTable(df.select("name", "item", "ts")) \
.add_hist_seq(["item"], "name", "ts", 1, 4, 1)
assert tbl.size() == 8
assert tbl.df.filter(col("name") == "alice").count() == 2
assert tbl.df.filter("name like '%jack'").count() == 6
assert "item_hist_seq" in tbl.df.columns
assert tbl2.size() == 2
assert tbl2.df.filter(col("name") == "alice").count() == 1
assert tbl2.df.filter("name like '%jack'").count() == 1
assert "item_hist_seq" in tbl2.df.columns
def test_gen_neg_hist_seq(self):
spark = OrcaContext.get_spark_session()
sc = OrcaContext.get_spark_context()
data = [
("jack", [1, 2, 3, 4, 5]),
("alice", [4, 5, 6, 7, 8]),
("rose", [1, 2])]
schema = StructType([
StructField("name", StringType(), True),
StructField("item_hist_seq", ArrayType(IntegerType()), True)])
df = spark.createDataFrame(data, schema)
df2 = sc \
.parallelize([(1, 0), (2, 0), (3, 0), (4, 1), (5, 1), (6, 1), (7, 2), (8, 2), (9, 2)]) \
.toDF(["item", "category"]).withColumn("item", col("item").cast("Integer")) \
.withColumn("category", col("category").cast("Integer"))
tbl = FeatureTable(df)
tbl = tbl.add_neg_hist_seq(9, "item_hist_seq", 4)
assert tbl.df.select("neg_item_hist_seq").count() == 3
def test_add_value_features(self):
spark = OrcaContext.get_spark_session()
sc = OrcaContext.get_spark_context()
data = [
("jack", [1, 2, 3, 4, 5]),
("alice", [4, 5, 6, 7, 8]),
("rose", [1, 2])]
schema = StructType([
StructField("name", StringType(), True),
StructField("item_hist_seq", ArrayType(IntegerType()), True)])
df = spark.createDataFrame(data, schema)
df.filter("name like '%alice%'").show()
df2 = sc \
.parallelize([(0, 0), (1, 0), (2, 0), (3, 0), (4, 1), (5, 1), (6, 1), (8, 2), (9, 2)]) \
.toDF(["item", "category"]).withColumn("item", col("item").cast("Integer")) \
.withColumn("category", col("category").cast("Integer"))
tbl = FeatureTable(df)
tbl2 = tbl.add_neg_hist_seq(9, "item_hist_seq", 4)
tbl3 = tbl2.add_value_features(["item_hist_seq", "neg_item_hist_seq"],
FeatureTable(df2), "item", "category")
assert tbl3.df.select("category_hist_seq").count() == 3
assert tbl3.df.select("neg_category_hist_seq").count() == 3
assert tbl3.df.filter("name like '%alice%'").select("neg_category_hist_seq").count() == 1
assert tbl3.df.filter("name == 'rose'").select("neg_category_hist_seq").count() == 1
def test_reindex(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
string_idx_list = feature_tbl.gen_string_idx(["col_4", "col_5"],
freq_limit={"col_4": 1, "col_5": 1},
order_by_freq=False)
tbl_with_index = feature_tbl.encode_string(["col_4", "col_5"], string_idx_list)
index_tbls = tbl_with_index.gen_reindex_mapping(["col_4", "col_5"], 2)
reindexed = tbl_with_index.reindex(["col_4", "col_5"], index_tbls)
assert(reindexed.filter(col("col_4") == 0).size() == 2)
assert(reindexed.filter(col("col_4") == 1).size() == 2)
assert(reindexed.filter(col("col_5") == 0).size() == 1)
assert(reindexed.filter(col("col_5") == 1).size() == 3)
def test_pad(self):
spark = OrcaContext.get_spark_session()
data = [
("jack", [1, 2, 3, 4, 5], [[1, 2, 3], [1, 2, 3]]),
("alice", [4, 5, 6, 7, 8], [[1, 2, 3], [1, 2, 3]]),
("rose", [1, 2], [[1, 2, 3]])]
schema = StructType([StructField("name", StringType(), True),
StructField("list", ArrayType(IntegerType()), True),
StructField("matrix", ArrayType(ArrayType(IntegerType())))])
df = spark.createDataFrame(data, schema)
tbl1 = FeatureTable(df).pad(["list", "matrix"], seq_len=4)
dft1 = tbl1.df
tbl2 = FeatureTable(df).pad(cols=["list", "matrix"], mask_cols=["list"], seq_len=4)
assert dft1.filter("size(matrix) = 4").count() == 3
assert dft1.filter("size(list) = 4").count() == 3
assert tbl2.df.filter("size(list_mask) = 4").count() == 3
assert tbl2.df.filter("size(list_mask) = 2").count() == 0
assert "list_mask" in tbl2.df.columns
def test_median(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
with self.assertRaises(Exception) as context:
feature_tbl.median(["col_4", "col_5"])
self.assertTrue('col_4 with data type StringType is not supported' in
str(context.exception))
median_tbl = feature_tbl.median(["col_1", "col_2", "col_3"])
assert isinstance(median_tbl, FeatureTable), "median_tbl should be a FeatureTable"
assert median_tbl.df.count() == 3, "the number of rows of median_tbl should be equal to " \
"the number of specified columns"
assert median_tbl.df.filter("column == 'col_1'").count() == 1, "col_1 should exist in " \
"'column' of median_tbl"
assert median_tbl.df.filter("column == 'col_2'").filter("median == 1.0").count() == 1, \
"the median of col_2 should be 1.0"
def test_cast(self):
spark = OrcaContext.get_spark_session()
data = [("jack", "123", 14, 8),
("alice", "34", 25, 9),
("rose", "25344", 23, 10)]
schema = StructType([StructField("name", StringType(), True),
StructField("a", StringType(), True),
StructField("b", IntegerType(), True),
StructField("c", IntegerType(), True)])
df = spark.createDataFrame(data, schema)
tbl = FeatureTable(df)
tbl = tbl.cast("a", "int")
assert dict(tbl.df.dtypes)['a'] == "int", "column a should be now be cast to integer type"
tbl = tbl.cast("a", "float")
assert dict(tbl.df.dtypes)['a'] == "float", "column a should be now be cast to float type"
tbl = tbl.cast(["b", "c"], "double")
assert dict(tbl.df.dtypes)['b'] == dict(tbl.df.dtypes)['c'] == "double", \
"column b and c should be now be cast to double type"
tbl = tbl.cast(None, "float")
assert dict(tbl.df.dtypes)['name'] == dict(tbl.df.dtypes)['a'] == dict(tbl.df.dtypes)['b'] \
== dict(tbl.df.dtypes)['c'] == "float", \
"all the columns should now be cast to float type"
with self.assertRaises(Exception) as context:
tbl = tbl.cast("a", "notvalid")
self.assertTrue(
"type should be string, boolean, int, long, short, float, double."
in str(context.exception))
def test_select(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
select_tbl = feature_tbl.select("col_1", "col_2")
assert "col_1" in select_tbl.df.columns, "col_1 shoul be selected"
assert "col_2" in select_tbl.df.columns, "col_2 shoud be selected"
assert "col_3" not in select_tbl.df.columns, "col_3 shoud not be selected"
assert feature_tbl.size() == select_tbl.size(), \
"the selected table should have the same rows"
with self.assertRaises(Exception) as context:
feature_tbl.select()
self.assertTrue("cols should be str or a list of str, but got None."
in str(context.exception))
def test_create_from_dict(self):
indices = {'a': 1, 'b': 2, 'c': 3}
col_name = 'letter'
tbl = StringIndex.from_dict(indices, col_name)
assert 'id' in tbl.df.columns, "id should be one column in the stringindex"
assert 'letter' in tbl.df.columns, "letter should be one column in the stringindex"
assert tbl.size() == 3, "the StringIndex should have three rows"
with self.assertRaises(Exception) as context:
StringIndex.from_dict(indices, None)
self.assertTrue("col_name should be str, but get None"
in str(context.exception))
with self.assertRaises(Exception) as context:
StringIndex.from_dict(indices, 12)
self.assertTrue("col_name should be str, but get int"
in str(context.exception))
with self.assertRaises(Exception) as context:
StringIndex.from_dict([indices], col_name)
self.assertTrue("indices should be dict, but get list"
in str(context.exception))
def test_encode_string_from_dict(self):
spark = OrcaContext.get_spark_session()
data = [("jack", "123", 14, 8),
("alice", "34", 25, 9),
("rose", "25344", 23, 10)]
schema = StructType([StructField("name", StringType(), True),
StructField("num", StringType(), True),
StructField("age", IntegerType(), True),
StructField("height", IntegerType(), True)])
tbl = FeatureTable(spark.createDataFrame(data, schema))
columns = ["name", "num"]
indices = []
indices.append({"jack": 1, "alice": 2, "rose": 3})
indices.append({"123": 3, "34": 1, "25344": 2})
tbl = tbl.encode_string(columns, indices)
assert 'name' in tbl.df.columns, "name should be still in the columns"
assert 'num' in tbl.df.columns, "num should be still in the columns"
assert tbl.df.where(tbl.df.age == 14).select("name").collect()[0]["name"] == 1, \
"the first row of name should be 1"
assert tbl.df.where(tbl.df.height == 10).select("num").collect()[0]["num"] == 2, \
"the third row of num should be 2"
def test_write_csv(self):
spark = OrcaContext.get_spark_session()
data = [("jack", 14, 8),
("alice", 25, 9),
("rose", 23, 10)]
schema = StructType([StructField("name", StringType(), True),
StructField("age", IntegerType(), True),
StructField("height", IntegerType(), True)])
tbl = FeatureTable(spark.createDataFrame(data, schema))
directory = "write.csv"
if os.path.exists("write.csv"):
shutil.rmtree("write.csv")
tbl.write_csv(directory, mode="overwrite", header=True, num_partitions=1)
assert os.path.exists("write.csv"), "files not write"
result = FeatureTable(spark.read.csv(directory, header=True))
assert isinstance(result, FeatureTable)
assert result.size() == 3, "the size of result should be 3"
assert result.filter("age == 23").size() == 1, "wrong age"
assert result.filter("name == 'jack'").size() == 1, "wrong name"
assert result.filter("name == 'alice'").size() == 1, "wrong name"
shutil.rmtree(directory)
def test_concat(self):
spark = OrcaContext.get_spark_session()
data1 = [("jack", 1)]
data2 = [(2, "alice")]
data3 = [("amy", 3, 50)]
schema1 = StructType([StructField("name", StringType(), True),
StructField("id", IntegerType(), True)])
schema2 = StructType([StructField("id", IntegerType(), True),
StructField("name", StringType(), True)])
schema3 = StructType([StructField("name", StringType(), True),
StructField("id", IntegerType(), True),
StructField("weight", IntegerType(), True)])
tbl1 = FeatureTable(spark.createDataFrame(data1, schema1))
tbl2 = FeatureTable(spark.createDataFrame(data2, schema2))
tbl3 = FeatureTable(spark.createDataFrame(data3, schema3))
tbl = tbl1.concat(tbl1)
assert tbl.size() == 2
tbl = tbl1.concat(tbl1, distinct=True)
assert tbl.size() == 1
tbl = tbl1.concat(tbl2)
assert tbl.filter("name == 'jack'").size() == 1
assert tbl.filter("name == 'alice'").size() == 1
tbl = tbl1.concat(tbl3, mode="inner")
assert tbl.df.schema.names == ["name", "id"]
tbl = tbl1.concat(tbl3, mode="outer")
assert tbl.df.schema.names == ["name", "id", "weight"]
assert tbl.fillna(0, "weight").filter("weight == 0").size() == 1
tbl = tbl1.concat([tbl1, tbl2, tbl3])
assert tbl.size() == 4
assert tbl.distinct().size() == 3
tbl = tbl1.concat([tbl1, tbl2, tbl3], distinct=True)
assert tbl.size() == 3
def test_drop_duplicates(self):
spark = OrcaContext.get_spark_session()
schema = StructType([StructField("name", StringType(), True),
StructField("grade", StringType(), True),
StructField("number", IntegerType(), True)])
data = [("jack", "a", 1), ("jack", "a", 3), ("jack", "b", 2), ("amy", "a", 2),
("amy", "a", 5), ("amy", "a", 4)]
tbl = FeatureTable(spark.createDataFrame(data, schema))
tbl2 = tbl.drop_duplicates(subset=['name', 'grade'], sort_cols='number', keep='min')
tbl2.df.show()
assert tbl2.size() == 3
assert tbl2.df.filter((tbl2.df.name == 'jack') & (tbl2.df.grade == 'a'))\
.select("number").collect()[0]["number"] == 1
assert tbl2.df.filter((tbl2.df.name == 'jack') & (tbl2.df.grade == 'b'))\
.select("number").collect()[0]["number"] == 2
assert tbl2.df.filter((tbl2.df.name == 'amy') & (tbl2.df.grade == 'a'))\
.select("number").collect()[0]["number"] == 2
tbl3 = tbl.drop_duplicates(subset=['name', 'grade'], sort_cols='number', keep='max')
tbl3.df.show()
assert tbl3.size() == 3
assert tbl3.df.filter((tbl2.df.name == 'jack') & (tbl2.df.grade == 'a'))\
.select("number").collect()[0]["number"] == 3
assert tbl3.df.filter((tbl2.df.name == 'jack') & (tbl2.df.grade == 'b'))\
.select("number").collect()[0]["number"] == 2
assert tbl3.df.filter((tbl2.df.name == 'amy') & (tbl2.df.grade == 'a'))\
.select("number").collect()[0]["number"] == 5
tbl4 = tbl.drop_duplicates(subset=None, sort_cols='number', keep='max')
tbl4.df.show()
assert tbl4.size() == 6
tbl5 = tbl.drop_duplicates(subset=['name', 'grade'], sort_cols=None, keep='max')
tbl5.df.show()
assert tbl5.size() == 3
tbl6 = tbl.drop_duplicates(subset=['name'], sort_cols=["grade", "number"], keep='max')
assert tbl6.size() == 2
tbl6.df.show()
assert tbl6.df.filter((tbl6.df.name == 'jack') & (tbl6.df.grade == 'b')
& (tbl6.df.number == 2))\
.select("number").collect()[0]["number"] == 2
assert tbl6.df.filter((tbl6.df.name == 'amy') & (tbl6.df.grade == 'a')
& (tbl6.df.number == 5))\
.select("number").collect()[0]["number"] == 5
def test_join(self):
spark = OrcaContext.get_spark_session()
schema = StructType([StructField("name", StringType(), True),
StructField("id", IntegerType(), True)])
data = [("jack", 1), ("jack", 2), ("jack", 3)]
tbl = FeatureTable(spark.createDataFrame(data, schema))
tbl2 = FeatureTable(spark.createDataFrame(data, schema))
tbl = tbl.join(tbl2, on="id", lsuffix="_l", rsuffix="_r")
assert "name_l" in tbl.df.schema.names
assert "id" in tbl.df.schema.names
assert "name_r" in tbl.df.schema.names
def test_cut_bins(self):
spark = OrcaContext.get_spark_session()
values = [("a", 23), ("b", 45), ("c", 10), ("d", 60), ("e", 56), ("f", 2),
("g", 25), ("h", 40), ("j", 33)]
tbl = FeatureTable(spark.createDataFrame(values, ["name", "ages"]))
splits = [6, 18, 60]
labels = ["infant", "minor", "adult", "senior"]
# test drop false, name defined
new_tbl = tbl.cut_bins(bins=splits, columns="ages", labels=labels,
out_cols="age_bucket", drop=False)
assert "age_bucket" in new_tbl.columns
assert "ages" in new_tbl.columns
assert new_tbl.df.select("age_bucket").rdd.flatMap(lambda x: x).collect() ==\
["adult", "adult", "minor", "senior", "adult", "infant", "adult", "adult", "adult"]
# test out_col equal to input column
new_tbl = tbl.cut_bins(bins=splits, columns="ages", labels=labels,
out_cols="ages", drop=True)
assert "ages" in new_tbl.columns
assert new_tbl.df.select("ages").rdd.flatMap(lambda x: x).collect() == \
["adult", "adult", "minor", "senior", "adult", "infant", "adult", "adult", "adult"]
# test name not defined
new_tbl = tbl.cut_bins(bins=splits, columns="ages", labels=labels, drop=True)
assert "ages_bin" in new_tbl.columns
assert new_tbl.df.select("ages_bin").rdd.flatMap(lambda x: x).collect() == \
["adult", "adult", "minor", "senior", "adult", "infant", "adult", "adult", "adult"]
# test integer bins
new_tbl = tbl.cut_bins(bins=2, columns="ages", labels=labels, drop=False)
assert "ages_bin" in new_tbl.columns
assert new_tbl.df.select("ages_bin").rdd.flatMap(lambda x: x).collect() \
== ["minor", "adult", "minor", "senior", "adult", "minor", "minor", "adult", "adult"]
# test label is None
new_tbl = tbl.cut_bins(bins=4, columns="ages", drop=True)
assert "ages_bin" in new_tbl.columns
assert new_tbl.df.select("ages_bin").rdd.flatMap(lambda x: x).collect() \
== [2, 3, 1, 5, 4, 1, 2, 3, 3]
# test multiple columns
values = [("a", 23, 23), ("b", 45, 45), ("c", 10, 10), ("d", 60, 60), ("e", 56, 56),
("f", 2, 2), ("g", 25, 25), ("h", 40, 40), ("j", 33, 33)]
tbl = FeatureTable(spark.createDataFrame(values, ["name", "ages", "number"]))
splits = [6, 18, 60]
splits2 = [6, 18, 60]
labels = ["infant", "minor", "adult", "senior"]
new_tbl = tbl.cut_bins(bins={'ages': splits, 'number': splits2}, columns=["ages", 'number'],
labels={'ages': labels, 'number': labels}, out_cols=None, drop=False)
assert "ages_bin" in new_tbl.columns
assert "ages" in new_tbl.columns
assert "number_bin" in new_tbl.columns
assert new_tbl.df.select("ages_bin").rdd.flatMap(lambda x: x).collect() ==\
["adult", "adult", "minor", "senior", "adult", "infant", "adult", "adult", "adult"]
def test_columns(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
col_names = feature_tbl.columns
assert isinstance(col_names, list), "col_names should be a list of strings"
assert col_names == ["col_1", "col_2", "col_3", "col_4", "col_5"], \
"column names are incorrenct"
def test_get_stats(self):
spark = OrcaContext.get_spark_session()
data = [("jack", "123", 14, 8.5),
("alice", "34", 25, 9.7),
("rose", "25344", 23, 10.0)]
schema = StructType([StructField("name", StringType(), True),
StructField("num", StringType(), True),
StructField("age", IntegerType(), True),
StructField("height", DoubleType(), True)])
tbl = FeatureTable(spark.createDataFrame(data, schema))
columns = ["age", "height"]
# test str
statistics = tbl.get_stats(columns, "min")
assert len(statistics) == 2, "the dict should contain two statistics"
assert statistics["age"] == 14, "the min value of age is not correct"
assert statistics["height"] == 8.5, "the min value of height is not correct"
columns = ["age", "height"]
# test dict
statistics = tbl.get_stats(columns, {"age": "max", "height": "avg"})
assert len(statistics) == 2, "the dict should contain two statistics"
assert statistics["age"] == 25, "the max value of age is not correct"
assert statistics["height"] == 9.4, "the avg value of height is not correct"
# test list
statistics = tbl.get_stats(columns, ["min", "max"])
assert len(statistics) == 2, "the dict should contain two statistics"
assert statistics["age"][0] == 14, "the min value of age is not correct"
assert statistics["age"][1] == 25, "the max value of age is not correct"
assert statistics["height"][0] == 8.5, "the min value of height is not correct"
assert statistics["height"][1] == 10.0, "the max value of height is not correct"
# test dict of list
statistics = tbl.get_stats(columns, {"age": ["min", "max"], "height": ["min", "avg"]})
assert len(statistics) == 2, "the dict should contain two statistics"
assert statistics["age"][0] == 14, "the min value of age is not correct"
assert statistics["age"][1] == 25, "the max value of age is not correct"
assert statistics["height"][0] == 8.5, "the min value of height is not correct"
assert statistics["height"][1] == 9.4, "the max value of height is not correct"
statistics = tbl.get_stats(None, "min")
assert len(statistics) == 2, "the dict should contain two statistics"
assert statistics["age"] == 14, "the min value of age is not correct"
assert statistics["height"] == 8.5, "the min value of height is not correct"
def test_min(self):
spark = OrcaContext.get_spark_session()
data = [("jack", "123", 14, 8.5),
("alice", "34", 25, 9.7),
("rose", "25344", 23, 10.0)]
schema = StructType([StructField("name", StringType(), True),
StructField("num", StringType(), True),
StructField("age", IntegerType(), True),
StructField("height", DoubleType(), True)])
tbl = FeatureTable(spark.createDataFrame(data, schema))
columns = ["age", "height"]
min_result = tbl.min(columns)
assert min_result.to_list("min") == [14, 8.5], \
"the min value for age and height is not correct"
def test_max(self):
spark = OrcaContext.get_spark_session()
data = [("jack", "123", 14, 8.5),
("alice", "34", 25, 9.7),
("rose", "25344", 23, 10.0)]
schema = StructType([StructField("name", StringType(), True),
StructField("num", StringType(), True),
StructField("age", IntegerType(), True),
StructField("height", DoubleType(), True)])
tbl = FeatureTable(spark.createDataFrame(data, schema))
columns = ["age", "height"]
min_result = tbl.max(columns)
assert min_result.to_list("max") == [25, 10.0], \
"the maximum value for age and height is not correct"
def test_to_list(self):
spark = OrcaContext.get_spark_session()
data = [("jack", "123", 14, 8.5, [0, 0]),
("alice", "34", 25, 9.6, [1, 1]),
("rose", "25344", 23, 10.0, [2, 2])]
schema = StructType([StructField("name", StringType(), True),
StructField("num", StringType(), True),
StructField("age", IntegerType(), True),
StructField("height", DoubleType(), True),
StructField("array", ArrayType(IntegerType()), True)])
tbl = FeatureTable(spark.createDataFrame(data, schema))
list1 = tbl.to_list("name")
list2 = tbl.to_list("num")
list3 = tbl.to_list("age")
list4 = tbl.to_list("height")
list5 = tbl.to_list("array")
assert list1 == ["jack", "alice", "rose"], "the result of name is not correct"
assert list2 == ["123", "34", "25344"], "the result of num is not correct"
assert list3 == [14, 25, 23], "the result of age is not correct"
assert list4 == [8.5, 9.6, 10.0], "the result of height is not correct"
assert list5 == [[0, 0], [1, 1], [2, 2]], "the result of array is not correct"
def test_to_dict(self):
spark = OrcaContext.get_spark_session()
# test the case the column of key is unique
data = [("jack", "123", 14),
("alice", "34", 25),
("rose", "25344", 23)]
schema = StructType([StructField("name", StringType(), True),
StructField("num", StringType(), True),
StructField("age", IntegerType(), True)])
tbl = FeatureTable(spark.createDataFrame(data, schema))
dictionary = tbl.to_dict()
print(dictionary)
assert dictionary["name"] == ['jack', 'alice', 'rose']
def test_to_pandas(self):
spark = OrcaContext.get_spark_session()
data = [("jack", "123", 14),
("alice", "34", 25),
("rose", "25344", 23)]
schema = StructType([StructField("name", StringType(), True),
StructField("num", StringType(), True),
StructField("age", IntegerType(), True)])
tbl = FeatureTable(spark.createDataFrame(data, schema))
pddf = tbl.to_pandas()
assert(pddf["name"].values.tolist() == ['jack', 'alice', 'rose'])
def test_from_pandas(self):
import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]
pddf = pd.DataFrame(data, columns=['Name', 'Age'])
tbl = FeatureTable.from_pandas(pddf)
assert(tbl.size() == 3)
def test_sort(self):
import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]
pddf = pd.DataFrame(data, columns=['Name', 'Age'])
tbl = FeatureTable.from_pandas(pddf)
tbl = tbl.sort("Age", ascending=False)
assert(tbl.select("Name").to_list("Name") == ["nick", "juli", "tom"])
tbl = tbl.sort("Name")
assert(tbl.select("Name").to_list("Name") == ["juli", "nick", "tom"])
def test_add(self):
spark = OrcaContext.get_spark_session()
data = [("jack", "123", 14, 8.5),
("alice", "34", 25, 9.6),
("rose", "25344", 23, 10.0)]
schema = StructType([StructField("name", StringType(), True),
StructField("num", StringType(), True),
StructField("age", IntegerType(), True),
StructField("height", DoubleType(), True)])
tbl = FeatureTable(spark.createDataFrame(data, schema))
columns = ["age", "height"]
new_tbl = tbl.add(columns, 1.5)
new_list = new_tbl.df.take(3)
assert len(new_list) == 3, "new_tbl should have 3 rows"
assert new_list[0]['age'] == 15.5, "the age of jack should increase 1.5"
assert new_list[0]['height'] == 10, "the height of jack should increase 1.5"
assert new_list[1]['age'] == 26.5, "the age of alice should increase 1.5"
assert new_list[1]['height'] == 11.1, "the height of alice should increase 1.5"
assert new_list[2]['age'] == 24.5, "the age of rose should increase 1.5"
assert new_list[2]['height'] == 11.5, "the height of rose should increase 1.5"
new_tbl = tbl.add(columns, -1)
new_list = new_tbl.df.take(3)
assert len(new_list) == 3, "new_tbl should have 3 rows"
assert new_list[0]['age'] == 13, "the age of jack should decrease 1"
assert new_list[0]['height'] == 7.5, "the height of jack should decrease 1"
assert new_list[1]['age'] == 24, "the age of alice should decrease 1"
assert new_list[1]['height'] == 8.6, "the height of alice should decrease 1"
assert new_list[2]['age'] == 22, "the age of rose should decrease 1"
assert new_list[2]['height'] == 9.0, "the height of rose should decrease 1"
def test_sample(self):
spark = OrcaContext.get_spark_session()
df = spark.range(1000)
feature_tbl = FeatureTable(df)
total_line_1 = feature_tbl.size()
feature_tbl2 = feature_tbl.sample(0.5)
total_line_2 = feature_tbl2.size()
assert int(total_line_1/2) - 100 < total_line_2 < int(total_line_1/2) + 100, \
"the number of rows should be half"
total_distinct_line = feature_tbl2.distinct().size()
assert total_line_2 == total_distinct_line, "all rows should be distinct"
def test_group_by(self):
file_path = os.path.join(self.resource_path, "parquet/data2.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
groupby_tbl1 = feature_tbl.group_by("col_4", agg={"col_1": ["sum", "count"]})
assert groupby_tbl1.df.filter("col_4 == 'a' and sum(col_1) == 3").count() == 1, \
"the sum of col_1 with col_4 = 'a' should be 3"
assert groupby_tbl1.df.filter("col_4 == 'b' and `count(col_1)` == 5").count() == 1, \
"the count of col_1 with col_4 = 'b' should be 5"
groupby_tbl2 = feature_tbl.group_by(agg={"target": "avg", "col_2": "last"})
assert groupby_tbl2.df.collect()[0]["avg(target)"] == 0.9, \
"the mean of target should be 0.9"
groupby_tbl3 = feature_tbl.group_by("col_5", agg=["max", "min"], join=True)
assert len(groupby_tbl3.df.columns) == len(feature_tbl.df.columns) + 10, \
"groupby_tbl3 should have (#df.columns - #columns)*len(agg)=10 more columns"
assert groupby_tbl3.df.filter("col_5 == 'cc' and `max(col_2)` == 9").count() == \
feature_tbl.df.filter("col_5 == 'cc'").count(), \
"max of col_2 should 9 for all col_5 = 'cc' in groupby_tbl3"
assert groupby_tbl3.df.filter("col_5 == 'aa' and `min(col_3)` == 1.0").count() == \
feature_tbl.df.filter("col_5 == 'aa'").count(), \
"min of col_3 should 1.0 for all col_5 = 'aa' in groupby_tbl3"
groupby_tbl4 = feature_tbl.group_by(["col_4", "col_5"], agg="first", join=True)
assert groupby_tbl4.df.filter("col_4 == 'b' and col_5 == 'dd' and `first(col_1)` == 0") \
.count() == feature_tbl.df.filter("col_4 == 'b' and col_5 == 'dd'").count(), \
"first of col_1 should be 0 for all col_4 = 'b' and col_5 = 'dd' in groupby_tbl4"
def test_append_column(self):
file_path = os.path.join(self.resource_path, "data.csv")
tbl = FeatureTable.read_csv(file_path, header=True)
tbl = tbl.append_column("z", lit(0))
assert tbl.select("z").size() == 4
assert tbl.filter("z == 0").size() == 4
tbl = tbl.append_column("str", lit("a"))
assert tbl.select("str").size() == 4
assert tbl.filter("str == 'a'").size() == 4
tbl = tbl.append_column("float", lit(1.2))
assert tbl.select("float").size() == 4
assert tbl.filter("float == 1.2").size() == 4
def test_ordinal_shuffle(self):
spark = OrcaContext.get_spark_session()
data = [("a", 14), ("b", 25), ("c", 23), ("d", 2), ("e", 1)]
schema = StructType([StructField("name", StringType(), True),
StructField("num", IntegerType(), True)])
tbl = FeatureTable(spark.createDataFrame(data, schema).repartition(1))
shuffled_tbl = tbl.ordinal_shuffle_partition()
rows = tbl.df.collect()
shuffled_rows = shuffled_tbl.df.collect()
rows.sort(key=lambda x: x[1])
shuffled_rows.sort(key=lambda x: x[1])
assert rows == shuffled_rows
def test_write_parquet(self):
file_path = os.path.join(self.resource_path, "parquet/data1.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
feature_tbl.write_parquet("saved.parquet")
loaded_tbl = FeatureTable.read_parquet("saved.parquet")
if os.path.exists("saved.parquet"):
shutil.rmtree("saved.parquet")
def test_read_csv(self):
file_path = os.path.join(self.resource_path, "data.csv")
feature_tbl = FeatureTable.read_csv(file_path, header=True)
assert feature_tbl.size() == 4
columns = feature_tbl.columns
assert columns == ["col1", "col2", "col3"]
records = feature_tbl.df.collect()
assert isinstance(records[0][0], float)
assert isinstance(records[0][1], str) and isinstance(records[0][1], str)
file_path2 = os.path.join(self.resource_path, "data_no_header.csv")
feature_tbl2 = FeatureTable.read_csv(file_path2, names=["col1", "_col2", "col3"],
dtype={"col1": "int"})
assert feature_tbl2.size() == 4
columns2 = feature_tbl2.columns
assert columns2 == ["col1", "_col2", "col3"]
records2 = feature_tbl2.df.collect()
assert isinstance(records2[0][0], int)
assert isinstance(records2[0][1], str) and isinstance(records2[0][1], str)
feature_tbl3 = FeatureTable.read_csv(file_path, header=True, dtype=["int", "str", "str"])
records3 = feature_tbl3.df.collect()
assert isinstance(records3[0][0], int)
assert isinstance(records3[0][1], str) and isinstance(records3[0][1], str)
def test_category_encode_and_one_hot_encode(self):
file_path = os.path.join(self.resource_path, "data.csv")
feature_tbl = FeatureTable.read_csv(file_path, header=True)
feature_tbl, indices = feature_tbl.category_encode(columns=["col2", "col3"])
assert isinstance(indices, list) and len(indices) == 2
assert isinstance(indices[0], StringIndex) and isinstance(indices[1], StringIndex)
assert indices[0].size() == 3 and indices[1].size() == 4
dict1 = indices[0].to_dict()
dict2 = indices[1].to_dict()
records = feature_tbl.df.collect()
assert records[0][1] == dict1["x"] and records[0][2] == dict2["abc"]
assert records[3][1] == dict1["z"] and records[2][2] == dict2["aaa"]
feature_tbl = feature_tbl.one_hot_encode(columns=["col2", "col3"], prefix=["o1", "o2"])
feature_tbl.show()
columns = feature_tbl.columns
assert columns == ["col1", "o1_0", "o1_1", "o1_2", "o1_3", "o2_0",
"o2_1", "o2_2", "o2_3", "o2_4"]
records = feature_tbl.df.collect()
record = records[0]
value1 = dict1["x"]
value2 = dict2["abc"]
for i in range(1, 4):
if i == value1:
assert record[i+1] == 1
else:
assert record[i+1] == 0
for i in range(1, 5):
if i == value2:
assert record[i+5] == 1
else:
assert record[i+5] == 0
def test_split(self):
file_path = os.path.join(self.resource_path, "ncf.csv")
feature_tbl = FeatureTable.read_csv(file_path, header=True, dtype="int")
tbl1, tbl2 = feature_tbl.split([0.8, 0.2], seed=1128)
total_size = feature_tbl.size()
size1 = tbl1.size()
size2 = tbl2.size()
assert size1 + size2 == total_size
def test_target_encode(self):
file_path = os.path.join(self.resource_path, "parquet/data2.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
with self.assertRaises(Exception) as context:
feature_tbl.target_encode("col_4", "target", kfold=-1)
self.assertTrue("kfold should be an integer larger than 0" in str(context.exception))
with self.assertRaises(Exception) as context:
feature_tbl.target_encode("col_4", "col_5")
self.assertTrue("target_cols should be numeric" in str(context.exception))
with self.assertRaises(Exception) as context:
feature_tbl.target_encode("col_4", "target", target_mean={"target": "2"})
self.assertTrue("mean in target_mean should be numeric" in str(context.exception))
with self.assertRaises(Exception) as context:
feature_tbl.target_encode("col_4", "target", kfold=2, fold_col="col_3")
self.assertTrue("fold_col should be integer type" in str(context.exception))
target_tbl1, target_list1 = feature_tbl.target_encode("col_4", "target", kfold=1, smooth=0)
assert len(target_list1) == 1, "len(target_list1) = len(cat_cols) of target_encode"
target_code1 = target_list1[0]
assert isinstance(target_code1, TargetCode), "target_list1 should be list of TargetCode"
assert target_code1.df.filter("col_4 == 'a'").collect()[0]["col_4_te_target"] == \
feature_tbl.df.filter("col_4 == 'a'").agg({"target": "mean"}) \
.collect()[0]["avg(target)"], \
"col_4_te_target should contain mean of target grouped by col_4"
cat_cols = ["col_4", "col_5"]
target_cols = ["col_3", "target"]
fold_col = "fold"
target_mean = {"col_3": 5, "target": 0.5}
out_cols = [[cat_col + target_col for target_col in target_cols] for cat_col in cat_cols]
target_tbl2, target_list2 = feature_tbl.target_encode(
cat_cols,
target_cols,
target_mean=target_mean,
kfold=3,
fold_seed=4,
fold_col=fold_col,
drop_cat=False,
drop_fold=False,
out_cols=out_cols)
assert fold_col in target_tbl2.df.columns, "fold_col should be in target_tbl2"
assert len(target_list2) == len(cat_cols), "len(target_list2) = len(cat_cols)"
for i in range(len(cat_cols)):
assert target_list2[i].cat_col == cat_cols[i], "each element in target_list2 should " \
"correspond to the element in cat_cols"
for out_col in out_cols[i]:
assert out_col in target_list2[i].df.columns, "every out_cols should be one of " \
"the columns in returned TargetCode"
assert target_mean[target_list2[i].out_target_mean[out_col][0]] == \
target_list2[i].out_target_mean[out_col][1], \
"the global mean in TargetCode should be the same as the assigned mean in " \
"target_mean"
target_tbl3, target_list3 = feature_tbl.target_encode([["col_4", "col_5"]], "target",
kfold=2, drop_cat=False)
assert len(target_tbl3.columns) == len(feature_tbl.columns) + 1, \
"target_tbl3 should have one more column col_4_col_5_te_target"
def test_encode_target(self):
file_path = os.path.join(self.resource_path, "parquet/data2.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
spark = OrcaContext.get_spark_session()
data = [("aa", 2, 1.0),
("bb", 4, 2.0),
("cc", 6, 3.0),
("dd", 8, 4.0)]
schema = StructType([StructField("unknown", StringType(), True),
StructField("target_encode_count", IntegerType(), True),
StructField("col_5_te_col_1", DoubleType(), True)])
df0 = spark.createDataFrame(data, schema)
target_code0 = TargetCode(df0,
cat_col="unknown",
out_target_mean={"col_5_te_col_1": ("col_1", 0.5)})
with self.assertRaises(Exception) as context:
feature_tbl.encode_target(target_code0)
self.assertTrue("unknown in TargetCode.cat_col in targets does not exist in Table"
in str(context.exception))
target_code1 = target_code0.rename({"unknown": "col_5"})
target_tbl1 = feature_tbl.encode_target(target_code1)
assert target_tbl1.df.filter("col_5_te_col_1 == 1").count() == \
feature_tbl.df.filter("col_5 == 'aa'").count(), \
"the row with col_5 = 'aa' be encoded as col_5_te_col_1 = 1 in target_tbl1"
assert target_tbl1.df.filter("col_3 == 8.0 and col_4 == 'd'") \
.filter("col_5_te_col_1 == 3"), \
"the row with col_3 = 8.0 and col_4 = 'd' has col_5 = 'cc', " \
"so it should be encoded with col_5_te_col_1 = 3 in target_tbl1"
target_tbl2, target_list2 = feature_tbl.target_encode(
["col_4", "col_5"],
["col_3", "target"],
kfold=2)
target_tbl3 = feature_tbl.encode_target(target_list2, target_cols="target", drop_cat=False)
assert "col_4" in target_tbl3.df.columns, \
"col_4 should exist in target_tbl2 since drop_cat is False"
assert "col_4_te_target" in target_tbl3.df.columns, \
"col_4_te_target should exist in target_tbl2 as encoded column"
assert "col_4_te_col_3" not in target_tbl3.df.columns, \
"col_4_te_col_3 should not exist in target_tbl2 since col_3 is not in target_cols"
def test_difference_lag(self):
file_path = os.path.join(self.resource_path, "parquet/data2.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
with self.assertRaises(Exception) as context:
feature_tbl.difference_lag("col_4", "col_4")
self.assertTrue("columns should be numeric" in str(context.exception))
diff_tbl1 = feature_tbl.difference_lag("col_1", "col_1")
assert diff_tbl1.df.filter("col_1_diff_lag_col_1_1 == 1").count() == 5 and \
diff_tbl1.df.filter("col_1_diff_lag_col_1_1 == 0").count() == 13 and \
diff_tbl1.df.filter("col_1_diff_lag_col_1_1 is null").count() == 2, \
"col_1 has 6 different values and 1 null, so after sorted by col_1, there should" \
" be 5 rows with (lag of col_1) = 1, 2 rows with (lag of col_1) = null," \
" and other rows with (lag of col_1) = 0"
diff_tbl2 = feature_tbl.difference_lag(
["col_1", "col_2"], ["col_3"], shifts=[1, -1],
partition_cols=["col_5"], out_cols=[["c1p1", "c1m1"], ["c2p1", "c2m1"]])
assert diff_tbl2.df.filter("col_3 == 8.0 and col_5 == 'cc'") \
.filter("c1p1 == 1 and c1m1 == 2 and c2p1 == -1 and c2m1 == -4") \
.count() == 1, "the row with col_3 = 8.0 and col_5 = 'cc' should have c1p1 = 1, " \
"c1m1 = 2, c2p1 = -1, c2m1 = -4 after difference_lag"
diff_tbl3 = feature_tbl.difference_lag("col_1", ["col_3"], shifts=[-1],
partition_cols=["col_5"], out_cols="c1m1")
assert diff_tbl3.df.filter("c1m1 == 2").count() == \
diff_tbl2.df.filter("c1m1 == 2").count(), \
"c1m1 should be the same in diff_tbl3 and in diff_tbl2"
diff_tbl4 = feature_tbl.difference_lag("col_1", ["col_3"], shifts=[-1, 1],
partition_cols=["col_5"], out_cols=["c1m1", "c1p1"])
assert diff_tbl4.df.filter("c1p1 == -1").count() == \
diff_tbl2.df.filter("c1p1 == -1").count(), \
"c1p1 should be the same in diff_tbl4 and in diff_tbl2"
def test_cache(self):
file_path = os.path.join(self.resource_path, "parquet/data2.parquet")
feature_tbl = FeatureTable.read_parquet(file_path)
feature_tbl.cache()
assert feature_tbl.df.is_cached, "Cache table should be cached"
feature_tbl.uncache()
assert not feature_tbl.df.is_cached, "Uncache table should be uncached"
if __name__ == "__main__":
pytest.main([__file__])
|
''' Uses the SymCC-AFL hybrid from SymCC. '''
import os
import time
import shutil
import threading
import subprocess
from fuzzers.afl import fuzzer as afl_fuzzer
from fuzzers.aflplusplus import fuzzer as aflplusplus_fuzzer
def get_symcc_build_dir(target_directory):
"""Return path to uninstrumented target directory."""
return os.path.join(target_directory, 'uninstrumented')
def build():
"""Build an AFL version and SymCC version of the benchmark"""
# Backup the environment.
orig_env = os.environ.copy()
#src = os.getenv('SRC')
#work = os.getenv('WORK')
build_directory = os.getenv('OUT')
fuzz_target = os.getenv('FUZZ_TARGET')
# First, build an uninstrumented binary for Eclipser.
aflplusplus_fuzzer.build("qemu", "eclipser")
eclipser_dir = get_symcc_build_dir(build_directory)
os.mkdir(eclipser_dir)
fuzz_binary = build_directory + '/' + fuzz_target
shutil.copy(fuzz_binary, eclipser_dir)
if os.path.isdir(build_directory + '/seeds'):
shutil.rmtree(build_directory + '/seeds')
# Second, build an instrumented binary for AFL++.
os.environ = orig_env
aflplusplus_fuzzer.build("tracepc")
print('[build] Copying afl-fuzz to $OUT directory')
# Copy afl-fuzz
shutil.copy('/afl/afl-fuzz', build_directory)
shutil.copy("/afl/afl-showmap", build_directory)
shutil.copy("/rust/bin/symcc_fuzzing_helper", eclipser_dir)
symcc_build_dir = get_symcc_build_dir(os.environ['OUT'])
# Copy over symcc artifacts and symbolic libc++.
shutil.copy(
"/symcc/build//SymRuntime-prefix/src/SymRuntime-build/libSymRuntime.so",
symcc_build_dir)
shutil.copy("/usr/lib/libz3.so", os.path.join(symcc_build_dir, "libz3.so"))
shutil.copy("/rust/bin/symcc_fuzzing_helper", symcc_build_dir)
shutil.copy("/symqemu/build/x86_64-linux-user/symqemu-x86_64",
symcc_build_dir)
def launch_afl_thread(input_corpus, output_corpus, target_binary,
additional_flags):
""" Simple wrapper for running AFL. """
afl_thread = threading.Thread(target=afl_fuzzer.run_afl_fuzz,
args=(input_corpus, output_corpus,
target_binary, additional_flags))
afl_thread.start()
return afl_thread
def fuzz(input_corpus, output_corpus, target_binary):
"""
Launches a master and a secondary instance of AFL, as well as
the symcc helper.
"""
target_binary_dir = os.path.dirname(target_binary)
symcc_workdir = get_symcc_build_dir(target_binary_dir)
target_binary_name = os.path.basename(target_binary)
symcc_target_binary = os.path.join(symcc_workdir, target_binary_name)
os.environ['AFL_DISABLE_TRIM'] = "1"
# Start a master and secondary instance of AFL.
# We need both because of the way SymCC works.
print('[run_fuzzer] Running AFL for SymCC')
afl_fuzzer.prepare_fuzz_environment(input_corpus)
launch_afl_thread(input_corpus, output_corpus, target_binary,
["-S", "afl-secondary"])
time.sleep(5)
# Start an instance of SymCC.
# We need to ensure it uses the symbolic version of libc++.
symqemu_target = os.path.join(symcc_workdir, "symqemu-x86_64")
if os.path.isfile(symqemu_target):
print("Found symqemu target")
else:
print("Did not find symqemu target")
print("Starting the SymCC helper")
new_environ = os.environ.copy()
new_environ['LD_LIBRARY_PATH'] = symcc_workdir
cmd = [
os.path.join(symcc_workdir, "symcc_fuzzing_helper"), "-o",
output_corpus, "-a", "afl-secondary", "-n", "symqemu", "-m", "--",
symqemu_target, symcc_target_binary, "@@"
]
print("Running command: %s" % (" ".join(cmd)))
subprocess.Popen(cmd, env=new_environ)
|
import os
import random
from collections import defaultdict
import xml.etree.ElementTree
def parse_annotations(dir):
all_files = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir, f)) and f.lower().endswith('.xml')]
filenames = defaultdict(list)
for f in all_files:
target_file = os.path.join(dir, f)
# check that the annotation's xml file exists
if os.path.isfile(target_file):
print('parsing %s' % target_file)
with open(target_file, 'r') as xml_file:
# get the raw xml file from the annotation file
raw_xml = xml_file.read().replace('\n', '')
# read it into an Element
data_xml = xml.etree.ElementTree.XML(raw_xml)
# get all instances of filename, there should only be one!
filename_xml = [f for f in data_xml.findall('filename')]
if len(filename_xml) > 1:
print('problem with %s, more than one filename!' % target_file)
fname = filename_xml[0]
# get all bounding boxes in this annotation
for obj in data_xml.findall('object'):
# get the animals present in this image, don't want the file extension
for classname in obj.findall('name'):
filenames[fname.text[0:-4]].append(classname.text)
else:
print('could not find %s, ignoring' % target_file)
#for k in filenames:
# print k, filenames[k]
return filenames
if __name__ == '__main__':
# the ratio of data to be set aside for training
training_ratio = 0.8
# class that will be marked as positive training examples
classname1 = 'zebra_grevys'
classname2 = 'zebra_plains'
# directory that contains the xml annotations
xml_dir = '/media/IBEIS/data/Annotations'
annotations = parse_annotations(xml_dir)
N = int(training_ratio * len(annotations))
keys = list(annotations.keys())
# shuffle the filenames to get a random training set
random.shuffle(keys)
# open the files to write the assignments to
with open(classname1 + '_train.txt', 'w') as training_file, \
open(classname1 + '_test.txt', 'w') as test_file, \
open('test.txt', 'w') as test, \
open('trainval.txt', 'w') as trainval:
for i, filename in enumerate(keys):
# write the first N files to the training set
if i < N:
trainval.write(filename + '\n')
# write 1 if the image contains the positive class, else -1
if classname1 in annotations[filename]:
training_file.write(filename + ' 1\n')
elif classname2 in annotations[filename]:
training_file.write(filename + ' 1\n')
else:
training_file.write(filename + ' -1\n')
# the rest of the files go to the test set, which all get 0s
else:
test.write(filename + '\n')
test_file.write(filename + ' 0\n')
|
"""ggrc.views
Handle non-RESTful views, e.g. routes which return HTML rather than JSON
"""
import collections
import json
from flask import flash
from flask import g
from flask import render_template
from flask import url_for
from werkzeug.exceptions import Forbidden
from ggrc import models
from ggrc import settings
from ggrc.app import app
from ggrc.app import db
from ggrc.builder.json import publish
from ggrc.builder.json import publish_representation
from ggrc.converters import get_importables, get_exportables
from ggrc.extensions import get_extension_modules
from ggrc.fulltext import get_indexer
from ggrc.fulltext.recordbuilder import fts_record_for
from ggrc.fulltext.recordbuilder import model_is_indexed
from ggrc.login import get_current_user
from ggrc.login import login_required
from ggrc.models import all_models
from ggrc.models.background_task import create_task
from ggrc.models.background_task import make_task_response
from ggrc.models.background_task import queued_task
from ggrc.models.reflection import AttributeInfo
from ggrc.rbac import permissions
from ggrc.services.common import as_json
from ggrc.services.common import inclusion_filter
from ggrc.views import converters
from ggrc.views import cron
from ggrc.views import filters
from ggrc.views import mockups
from ggrc.views import notifications
from ggrc.views.common import RedirectedPolymorphView
from ggrc.views.registry import object_view
@app.route("/_background_tasks/reindex", methods=["POST"])
@queued_task
def reindex(_):
"""
Web hook to update the full text search index
"""
do_reindex()
return app.make_response((
'success', 200, [('Content-Type', 'text/html')]))
def do_reindex():
"""
update the full text search index
"""
indexer = get_indexer()
indexer.delete_all_records(False)
# Find all models then remove base classes
# (If we don't remove base classes, we get duplicates in the index.)
inheritance_base_models = [
all_models.Directive, all_models.SystemOrProcess
]
models_ = set(all_models.all_models) - set(inheritance_base_models)
models_ = [model for model in models_ if model_is_indexed(model)]
for model in models_:
mapper_class = model._sa_class_manager.mapper.base_mapper.class_
query = model.query.options(
db.undefer_group(mapper_class.__name__ + '_complete'),
)
for query_chunk in generate_query_chunks(query):
for instance in query_chunk:
indexer.create_record(fts_record_for(instance), False)
db.session.commit()
def get_permissions_json():
"""Get all permissions for current user"""
permissions.permissions_for(permissions.get_user())
return json.dumps(getattr(g, '_request_permissions', None))
def get_config_json():
"""Get public app config"""
public_config = dict(app.config.public_config)
for extension_module in get_extension_modules():
if hasattr(extension_module, 'get_public_config'):
public_config.update(
extension_module.get_public_config(get_current_user()))
return json.dumps(public_config)
def get_current_user_json():
"""Get current user"""
from ggrc.models.person import Person
current_user = get_current_user()
person = Person.eager_query().filter_by(id=current_user.id).one()
result = publish_representation(publish(person, (), inclusion_filter))
return as_json(result)
def get_attributes_json():
"""Get a list of all custom attribute definitions"""
attrs = models.CustomAttributeDefinition.eager_query().all()
published = []
for attr in attrs:
published.append(publish(attr))
published = publish_representation(published)
return as_json(published)
def get_import_types(export_only=False):
types = get_exportables if export_only else get_importables
data = []
for model in set(types().values()):
data.append({
"model_singular": model.__name__,
"title_plural": model._inflector.title_plural
})
data.sort()
response_json = json.dumps(data)
return response_json
def get_export_definitions():
return get_import_types(export_only=True)
def get_import_definitions():
return get_import_types(export_only=False)
def get_all_attributes_json():
"""Get a list of all attribute definitions
This exports all attributes related to a given model, including custom
attributies and mapping attributes, that are used in csv import and export.
"""
published = {}
ca_cache = collections.defaultdict(list)
for attr in models.CustomAttributeDefinition.eager_query().all():
ca_cache[attr.definition_type].append(attr)
for model in all_models.all_models:
published[model.__name__] = \
AttributeInfo.get_attr_definitions_array(model, ca_cache=ca_cache)
return as_json(published)
@app.context_processor
def base_context():
"""Gets the base context"""
return dict(
get_model=models.get_model,
permissions_json=get_permissions_json,
permissions=permissions,
config_json=get_config_json,
current_user_json=get_current_user_json,
attributes_json=get_attributes_json,
all_attributes_json=get_all_attributes_json,
import_definitions=get_import_definitions,
export_definitions=get_export_definitions,
)
@app.route("/")
def index():
"""The initial entry point of the app
"""
if not settings.PRODUCTION:
flash(u"""<b>WARNING</b> - This is not the production instance
of the GGRC application.<br><br>
Company confidential, sensitive or personally identifiable
information <b>*MUST NOT*</b> be entered or stored here.
For any questions, please contact your administrator.""",
"alert alert-warning")
return render_template("welcome/index.haml")
@app.route("/dashboard")
@login_required
def dashboard():
"""The dashboard page
"""
return render_template("dashboard/index.haml")
@app.route("/objectBrowser")
@login_required
def objectBrowser():
"""The object Browser page
"""
return render_template("dashboard/index.haml")
def generate_query_chunks(query):
"""Generate query chunks used by pagination"""
chunk_size = 100
count = query.count()
for offset in range(0, count, chunk_size):
yield query.order_by('id').limit(chunk_size).offset(offset).all()
@app.route("/admin/reindex", methods=["POST"])
@login_required
def admin_reindex():
"""Calls a webhook that reindexes indexable objects
"""
if not permissions.is_allowed_read("/admin", None, 1):
raise Forbidden()
task_queue = create_task("reindex", url_for(reindex.__name__), reindex)
return task_queue.make_response(
app.make_response(("scheduled %s" % task_queue.name, 200,
[('Content-Type', 'text/html')])))
@app.route("/admin")
@login_required
def admin():
"""The admin dashboard page
"""
if not permissions.is_allowed_read("/admin", None, 1):
raise Forbidden()
return render_template("admin/index.haml")
@app.route("/assessments_view")
@login_required
def assessments_view():
"""The clutter-free list of all Person's Assessments"""
return render_template("assessments_view/index.haml")
@app.route("/background_task/<id_task>", methods=['GET'])
def get_task_response(id_task):
"""Gets the status of a background task"""
return make_task_response(id_task)
def contributed_object_views():
"""Contributed object views"""
return [
object_view(models.BackgroundTask),
object_view(models.Program),
object_view(models.Audit),
object_view(models.Directive, RedirectedPolymorphView),
object_view(models.Contract),
object_view(models.Policy),
object_view(models.Regulation),
object_view(models.Standard),
object_view(models.Clause),
object_view(models.Section),
object_view(models.Control),
object_view(models.Assessment),
object_view(models.AssessmentTemplate),
object_view(models.Objective),
object_view(models.System),
object_view(models.Process),
object_view(models.Product),
object_view(models.Request),
object_view(models.OrgGroup),
object_view(models.Facility),
object_view(models.Market),
object_view(models.Project),
object_view(models.DataAsset),
object_view(models.AccessGroup),
object_view(models.Person),
object_view(models.Vendor),
object_view(models.Issue),
]
def all_object_views():
"""Gets all object views defined in the application"""
views = contributed_object_views()
for extension_module in get_extension_modules():
contributions = getattr(extension_module, "contributed_object_views", None)
if contributions:
if callable(contributions):
contributions = contributions()
views.extend(contributions)
return views
def init_extra_views(app_):
"""Init any extra views needed by the app
This should be used for any views that might use extension modules.
"""
mockups.init_mockup_views()
filters.init_filter_views()
converters.init_converter_views()
cron.init_cron_views(app_)
notifications.init_notification_views(app_)
def init_all_views(app_):
"""Inits all views defined in the core module and submodules"""
for entry in all_object_views():
entry.service_class.add_to(
app_,
'/{0}'.format(entry.url),
entry.model_class,
decorators=(login_required,)
)
init_extra_views(app_)
for extension_module in get_extension_modules():
ext_extra_views = getattr(extension_module, "init_extra_views", None)
if ext_extra_views:
ext_extra_views(app_)
@app.route("/permissions")
@login_required
def user_permissions():
'''Permissions object for the currently
logged in user
'''
return get_permissions_json()
|
import datetime
import cotyledon
import threading
from racoon.storage import connection
from oslo_config import cfg
from oslo_log import log
from oslo_utils import timeutils
CONF = cfg.CONF
LOG = log.getLogger(__name__)
class SearcherService(cotyledon.Service):
def __init__(self, worker_id):
super(SearcherService, self).__init__(worker_id)
# this will keep set boolean atomic
self.__shutdown = threading.Event()
self.__shutdown_done = threading.Event()
self.delay = cfg.CONF.collector.searcher_delay
def run(self):
while not self.__shutdown.is_set():
with timeutils.StopWatch() as timer:
# therefore self.delay - time used by run job
self.__shutdown.wait(max(0, self.delay -
timer.elapsed()))
# wait a while then collect
self._run_job()
self.__shutdown_done.set()
def _run_job(self):
LOG.info('search resources')
con = connection.get_conn_from_config(CONF)
# get start and end time
end_timestamp = self._get_past()
resources = con.get_resource_by_timestamp(end_timestamp)
for r in resources:
print r.resource_id
print len(resources)
def _get_past(self):
start = datetime.datetime.utcnow()
end = start - datetime.timedelta(
seconds=self.delay)
# end = end.strftime('%Y-%m-%dT%H:%M:%SZ')
end = end.strftime('%Y-%m-%d %H:%M:%S')
return end
def terminate(self):
self.__shutdown.set()
LOG.info("Waiting ongoing processing to finish")
self.__shutdown_done.wait()
if __name__ == "__main__":
from racoon import service
service.prepare_service()
cs = SearcherService(1)
cs.run()
|
import unittest
import numpy as np
import SimpleITK as sitk
import miapy.data.conversion as img
class TestImageProperties(unittest.TestCase):
def test_is_two_dimensional(self):
x = 10
y = 10
image = sitk.Image([x, y], sitk.sitkUInt8)
dut = img.ImageProperties(image)
self.assertEqual(dut.is_two_dimensional(), True)
self.assertEqual(dut.is_three_dimensional(), False)
self.assertEqual(dut.is_vector_image(), False)
def test_is_three_dimensional(self):
x = 10
y = 10
z = 3
image = sitk.Image([x, y, z], sitk.sitkUInt8)
dut = img.ImageProperties(image)
self.assertEqual(dut.is_two_dimensional(), False)
self.assertEqual(dut.is_three_dimensional(), True)
self.assertEqual(dut.is_vector_image(), False)
def test_is_vector_image(self):
x = 10
y = 10
number_of_components_per_pixel = 3
image = sitk.Image([x, y], sitk.sitkVectorUInt8, number_of_components_per_pixel)
dut = img.ImageProperties(image)
self.assertEqual(dut.is_two_dimensional(), True)
self.assertEqual(dut.is_three_dimensional(), False)
self.assertEqual(dut.is_vector_image(), True)
def test_properties(self):
x = 10
y = 10
z = 3
pixel_id = sitk.sitkUInt8
size = (x, y, z)
direction = (0, 1, 0, 1, 0, 0, 0, 0, 1)
image = sitk.Image([x, y, z], pixel_id)
image.SetOrigin(size)
image.SetSpacing(size)
image.SetDirection(direction)
dut = img.ImageProperties(image)
self.assertEqual(dut.size, size)
self.assertEqual(dut.origin, size)
self.assertEqual(dut.spacing, size)
self.assertEqual(dut.direction, direction)
self.assertEqual(dut.dimensions, z)
self.assertEqual(dut.number_of_components_per_pixel, 1)
self.assertEqual(dut.pixel_id, pixel_id)
def test_equality(self):
x = 10
y = 10
z = 3
pixel_id = sitk.sitkUInt8
size = (x, y, z)
direction = (0, 1, 0, 1, 0, 0, 0, 0, 1)
image = sitk.Image([x, y, z], pixel_id)
image.SetOrigin(size)
image.SetSpacing(size)
image.SetDirection(direction)
dut1 = img.ImageProperties(image)
dut2 = img.ImageProperties(image)
self.assertTrue(dut1 == dut2)
self.assertFalse(dut1 != dut2)
image = sitk.Image([x, y, z], sitk.sitkInt8)
image.SetOrigin(size)
image.SetSpacing(size)
image.SetDirection(direction)
dut1 = img.ImageProperties(image)
self.assertTrue(dut1 == dut2)
self.assertFalse(dut1 != dut2)
image = sitk.Image([x, y, z], sitk.sitkVectorUInt8, 2)
image.SetOrigin(size)
image.SetSpacing(size)
image.SetDirection(direction)
dut1 = img.ImageProperties(image)
self.assertTrue(dut1 == dut2)
self.assertFalse(dut1 != dut2)
def test_non_equality(self):
x = 10
y = 10
z = 3
pixel_id = sitk.sitkUInt8
size = (x, y, z)
direction = (0, 1, 0, 1, 0, 0, 0, 0, 1)
image = sitk.Image([x, y, z], pixel_id)
image.SetOrigin(size)
image.SetSpacing(size)
image.SetDirection(direction)
dut1 = img.ImageProperties(image)
different_size = (x, y, 2)
# non-equal size
image = sitk.Image(different_size, pixel_id)
image.SetOrigin(size)
image.SetSpacing(size)
image.SetDirection(direction)
dut2 = img.ImageProperties(image)
self.assertFalse(dut1 == dut2)
self.assertTrue(dut1 != dut2)
# non-equal origin
image = sitk.Image(size, pixel_id)
image.SetOrigin(different_size)
image.SetSpacing(size)
image.SetDirection(direction)
dut2 = img.ImageProperties(image)
self.assertFalse(dut1 == dut2)
self.assertTrue(dut1 != dut2)
# non-equal spacing
different_size = (x, y, 2)
image = sitk.Image(size, pixel_id)
image.SetOrigin(size)
image.SetSpacing(different_size)
image.SetDirection(direction)
dut2 = img.ImageProperties(image)
self.assertFalse(dut1 == dut2)
self.assertTrue(dut1 != dut2)
# non-equal direction
different_size = (x, y, 2)
image = sitk.Image(size, pixel_id)
image.SetOrigin(size)
image.SetSpacing(size)
image.SetDirection((1, 0, 0, 0, 1, 0, 0, 0, 1))
dut2 = img.ImageProperties(image)
self.assertFalse(dut1 == dut2)
self.assertTrue(dut1 != dut2)
class TestNumpySimpleITKImageBridge(unittest.TestCase):
def setUp(self):
dim_x = 5
dim_y = 10
dim_z = 3
self.no_vector_components = 4
# some unordinary origins, spacings and directions
self.origin_spacing_2d = (dim_x, dim_y)
self.direction_2d = (0, 1, 1, 0)
self.origin_spacing_3d = (dim_x, dim_y, dim_z)
self.direction_3d = (1, 0, 0, 0, 1, 0, 0, 0, 1)
# set up images
image = sitk.Image((dim_x, dim_y, dim_z), sitk.sitkUInt8)
image.SetOrigin(self.origin_spacing_3d)
image.SetSpacing(self.origin_spacing_3d)
image.SetDirection(self.direction_3d)
self.properties_3d = img.ImageProperties(image)
image = sitk.Image((dim_x, dim_y), sitk.sitkUInt8)
image.SetOrigin(self.origin_spacing_2d)
image.SetSpacing(self.origin_spacing_2d)
image.SetDirection(self.direction_2d)
self.properties_2d = img.ImageProperties(image)
# set up numpy arrays (note the inverted order of the dimension)
self.array_image_shape_2d = np.zeros((dim_y, dim_x), np.uint8)
self.array_2d_vector = np.zeros((dim_y * dim_x, self.no_vector_components), np.uint8)
self.array_image_shape_2d_vector = np.zeros((dim_y, dim_x, self.no_vector_components), np.uint8)
self.array_image_shape_3d = np.zeros((dim_z, dim_y, dim_x), np.uint8)
self.array_3d_vector = np.zeros((dim_z * dim_y * dim_x, self.no_vector_components), np.uint8)
self.array_image_shape_3d_vector = np.zeros((dim_z, dim_y, dim_x, self.no_vector_components), np.uint8)
def test_vector_to_image(self):
# test array shape (n,) i.e., (x * y) and (x * y * z)
image = img.NumpySimpleITKImageBridge.convert(self.array_image_shape_3d.flatten(), self.properties_3d)
self._assert_3d(image)
image = img.NumpySimpleITKImageBridge.convert(self.array_image_shape_2d.flatten(), self.properties_2d)
self._assert_2d(image)
def test_array_to_image(self):
# test array shape (y, x) and (z, y, x)
image = img.NumpySimpleITKImageBridge.convert(self.array_image_shape_3d, self.properties_3d)
self._assert_3d(image)
image = img.NumpySimpleITKImageBridge.convert(self.array_image_shape_2d, self.properties_2d)
self._assert_2d(image)
def test_array_to_vector_image(self):
# test array shape (y, x, v) and (z, y, x, v), where v = number of vector component
image = img.NumpySimpleITKImageBridge.convert(self.array_image_shape_3d_vector, self.properties_3d)
self._assert_3d(image, True)
image = img.NumpySimpleITKImageBridge.convert(self.array_image_shape_2d_vector, self.properties_2d)
self._assert_2d(image, True)
def test_vector_to_vector_image(self):
# test array shape (y * x, v) and (z * y * x, v), where v = number of vector components
image = img.NumpySimpleITKImageBridge.convert(self.array_3d_vector, self.properties_3d)
self._assert_3d(image, True)
image = img.NumpySimpleITKImageBridge.convert(self.array_2d_vector, self.properties_2d)
self._assert_2d(image, True)
def test_convert_unknown_shape(self):
with self.assertRaises(ValueError):
img.NumpySimpleITKImageBridge.convert(self.array_image_shape_3d.flatten(), self.properties_2d)
def _assert_2d(self, image: sitk.Image, is_vector=False):
self.assertEqual(self.properties_2d.size, image.GetSize())
if is_vector:
self.assertEqual(self.no_vector_components, image.GetNumberOfComponentsPerPixel())
else:
self.assertEqual(1, image.GetNumberOfComponentsPerPixel())
self.assertEqual(self.origin_spacing_2d, image.GetOrigin())
self.assertEqual(self.origin_spacing_2d, image.GetSpacing())
self.assertEqual(self.direction_2d, image.GetDirection())
def _assert_3d(self, image: sitk.Image, is_vector=False):
self.assertEqual(self.properties_3d.size, image.GetSize())
if is_vector:
self.assertEqual(self.no_vector_components, image.GetNumberOfComponentsPerPixel())
else:
self.assertEqual(1, image.GetNumberOfComponentsPerPixel())
self.assertEqual(self.origin_spacing_3d, image.GetOrigin())
self.assertEqual(self.origin_spacing_3d, image.GetSpacing())
self.assertEqual(self.direction_3d, image.GetDirection())
class TestSimpleITKNumpyImageBridge(unittest.TestCase):
def test_convert(self):
x = 10
y = 10
z = 3
size = (x, y, z)
image = sitk.Image(size, sitk.sitkUInt8)
array, properties = img.SimpleITKNumpyImageBridge.convert(image)
self.assertEqual(isinstance(array, np.ndarray), True)
self.assertEqual(array.shape, size[::-1])
self.assertEqual(array.dtype, np.uint8)
self.assertEqual(isinstance(properties, img.ImageProperties), True)
self.assertEqual(properties.size, size)
def test_convert_None(self):
with self.assertRaises(ValueError):
img.SimpleITKNumpyImageBridge.convert(None)
|
"""
Assorted utilities for working with neural networks in AllenNLP.
"""
import copy
from collections import defaultdict, OrderedDict
from itertools import chain
import json
import logging
from os import PathLike
import re
from typing import Any, Dict, List, Optional, Sequence, Tuple, TypeVar, Union, NamedTuple
import math
import numpy
import torch
import torch.distributed as dist
from allennlp.common.checks import ConfigurationError
from allennlp.common.util import int_to_device, is_distributed, is_global_primary
logger = logging.getLogger(__name__)
T = TypeVar("T")
StateDictType = Union[Dict[str, torch.Tensor], "OrderedDict[str, torch.Tensor]"]
def move_to_device(obj, device: Union[torch.device, int]):
"""
Given a structure (possibly) containing Tensors,
move all the Tensors to the specified device (or do nothing, if they are already on
the target device).
"""
device = int_to_device(device)
if isinstance(obj, torch.Tensor):
# You may be wondering why we don't just always call `obj.to(device)` since that would
# be a no-op anyway if `obj` is already on `device`. Well that works fine except
# when PyTorch is not compiled with CUDA support, in which case even calling
# `obj.to(torch.device("cpu"))` would result in an error.
return obj if obj.device == device else obj.to(device=device)
elif isinstance(obj, dict):
for key, value in obj.items():
obj[key] = move_to_device(value, device)
return obj
elif isinstance(obj, list):
for i, item in enumerate(obj):
obj[i] = move_to_device(item, device)
return obj
elif isinstance(obj, tuple) and hasattr(obj, "_fields"):
# This is the best way to detect a NamedTuple, it turns out.
return obj.__class__(*(move_to_device(item, device) for item in obj))
elif isinstance(obj, tuple):
return tuple(move_to_device(item, device) for item in obj)
else:
return obj
def clamp_tensor(tensor, minimum, maximum):
"""
Supports sparse and dense tensors.
Returns a tensor with values clamped between the provided minimum and maximum,
without modifying the original tensor.
"""
if tensor.is_sparse:
coalesced_tensor = tensor.coalesce()
coalesced_tensor._values().clamp_(minimum, maximum)
return coalesced_tensor
else:
return tensor.clamp(minimum, maximum)
def batch_tensor_dicts(
tensor_dicts: List[Dict[str, torch.Tensor]], remove_trailing_dimension: bool = False
) -> Dict[str, torch.Tensor]:
"""
Takes a list of tensor dictionaries, where each dictionary is assumed to have matching keys,
and returns a single dictionary with all tensors with the same key batched together.
# Parameters
tensor_dicts : `List[Dict[str, torch.Tensor]]`
The list of tensor dictionaries to batch.
remove_trailing_dimension : `bool`
If `True`, we will check for a trailing dimension of size 1 on the tensors that are being
batched, and remove it if we find it.
"""
key_to_tensors: Dict[str, List[torch.Tensor]] = defaultdict(list)
for tensor_dict in tensor_dicts:
for key, tensor in tensor_dict.items():
key_to_tensors[key].append(tensor)
batched_tensors = {}
for key, tensor_list in key_to_tensors.items():
batched_tensor = torch.stack(tensor_list)
if remove_trailing_dimension and all(tensor.size(-1) == 1 for tensor in tensor_list):
batched_tensor = batched_tensor.squeeze(-1)
batched_tensors[key] = batched_tensor
return batched_tensors
def get_lengths_from_binary_sequence_mask(mask: torch.BoolTensor) -> torch.LongTensor:
"""
Compute sequence lengths for each batch element in a tensor using a
binary mask.
# Parameters
mask : `torch.BoolTensor`, required.
A 2D binary mask of shape (batch_size, sequence_length) to
calculate the per-batch sequence lengths from.
# Returns
`torch.LongTensor`
A torch.LongTensor of shape (batch_size,) representing the lengths
of the sequences in the batch.
"""
return mask.sum(-1)
def get_mask_from_sequence_lengths(
sequence_lengths: torch.Tensor, max_length: int
) -> torch.BoolTensor:
"""
Given a variable of shape `(batch_size,)` that represents the sequence lengths of each batch
element, this function returns a `(batch_size, max_length)` mask variable. For example, if
our input was `[2, 2, 3]`, with a `max_length` of 4, we'd return
`[[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0]]`.
We require `max_length` here instead of just computing it from the input `sequence_lengths`
because it lets us avoid finding the max, then copying that value from the GPU to the CPU so
that we can use it to construct a new tensor.
"""
# (batch_size, max_length)
ones = sequence_lengths.new_ones(sequence_lengths.size(0), max_length)
range_tensor = ones.cumsum(dim=1)
return sequence_lengths.unsqueeze(1) >= range_tensor
def sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor):
"""
Sort a batch first tensor by some specified lengths.
# Parameters
tensor : `torch.FloatTensor`, required.
A batch first Pytorch tensor.
sequence_lengths : `torch.LongTensor`, required.
A tensor representing the lengths of some dimension of the tensor which
we want to sort by.
# Returns
sorted_tensor : `torch.FloatTensor`
The original tensor sorted along the batch dimension with respect to sequence_lengths.
sorted_sequence_lengths : `torch.LongTensor`
The original sequence_lengths sorted by decreasing size.
restoration_indices : `torch.LongTensor`
Indices into the sorted_tensor such that
`sorted_tensor.index_select(0, restoration_indices) == original_tensor`
permutation_index : `torch.LongTensor`
The indices used to sort the tensor. This is useful if you want to sort many
tensors using the same ordering.
"""
if not isinstance(tensor, torch.Tensor) or not isinstance(sequence_lengths, torch.Tensor):
raise ConfigurationError("Both the tensor and sequence lengths must be torch.Tensors.")
sorted_sequence_lengths, permutation_index = sequence_lengths.sort(0, descending=True)
sorted_tensor = tensor.index_select(0, permutation_index)
index_range = torch.arange(0, len(sequence_lengths), device=sequence_lengths.device)
# This is the equivalent of zipping with index, sorting by the original
# sequence lengths and returning the now sorted indices.
_, reverse_mapping = permutation_index.sort(0, descending=False)
restoration_indices = index_range.index_select(0, reverse_mapping)
return sorted_tensor, sorted_sequence_lengths, restoration_indices, permutation_index
def get_final_encoder_states(
encoder_outputs: torch.Tensor, mask: torch.BoolTensor, bidirectional: bool = False
) -> torch.Tensor:
"""
Given the output from a `Seq2SeqEncoder`, with shape `(batch_size, sequence_length,
encoding_dim)`, this method returns the final hidden state for each element of the batch,
giving a tensor of shape `(batch_size, encoding_dim)`. This is not as simple as
`encoder_outputs[:, -1]`, because the sequences could have different lengths. We use the
mask (which has shape `(batch_size, sequence_length)`) to find the final state for each batch
instance.
Additionally, if `bidirectional` is `True`, we will split the final dimension of the
`encoder_outputs` into two and assume that the first half is for the forward direction of the
encoder and the second half is for the backward direction. We will concatenate the last state
for each encoder dimension, giving `encoder_outputs[:, -1, :encoding_dim/2]` concatenated with
`encoder_outputs[:, 0, encoding_dim/2:]`.
"""
# These are the indices of the last words in the sequences (i.e. length sans padding - 1). We
# are assuming sequences are right padded.
# Shape: (batch_size,)
last_word_indices = mask.sum(1) - 1
batch_size, _, encoder_output_dim = encoder_outputs.size()
expanded_indices = last_word_indices.view(-1, 1, 1).expand(batch_size, 1, encoder_output_dim)
# Shape: (batch_size, 1, encoder_output_dim)
final_encoder_output = encoder_outputs.gather(1, expanded_indices)
final_encoder_output = final_encoder_output.squeeze(1) # (batch_size, encoder_output_dim)
if bidirectional:
final_forward_output = final_encoder_output[:, : (encoder_output_dim // 2)]
final_backward_output = encoder_outputs[:, 0, (encoder_output_dim // 2) :]
final_encoder_output = torch.cat([final_forward_output, final_backward_output], dim=-1)
return final_encoder_output
def get_dropout_mask(dropout_probability: float, tensor_for_masking: torch.Tensor):
"""
Computes and returns an element-wise dropout mask for a given tensor, where
each element in the mask is dropped out with probability dropout_probability.
Note that the mask is NOT applied to the tensor - the tensor is passed to retain
the correct CUDA tensor type for the mask.
# Parameters
dropout_probability : `float`, required.
Probability of dropping a dimension of the input.
tensor_for_masking : `torch.Tensor`, required.
# Returns
`torch.FloatTensor`
A torch.FloatTensor consisting of the binary mask scaled by 1/ (1 - dropout_probability).
This scaling ensures expected values and variances of the output of applying this mask
and the original tensor are the same.
"""
binary_mask = (torch.rand(tensor_for_masking.size()) > dropout_probability).to(
tensor_for_masking.device
)
# Scale mask by 1/keep_prob to preserve output statistics.
dropout_mask = binary_mask.float().div(1.0 - dropout_probability)
return dropout_mask
def masked_softmax(
vector: torch.Tensor,
mask: torch.BoolTensor,
dim: int = -1,
memory_efficient: bool = False,
) -> torch.Tensor:
"""
`torch.nn.functional.softmax(vector)` does not work if some elements of `vector` should be
masked. This performs a softmax on just the non-masked portions of `vector`. Passing
`None` in for the mask is also acceptable; you'll just get a regular softmax.
`vector` can have an arbitrary number of dimensions; the only requirement is that `mask` is
broadcastable to `vector's` shape. If `mask` has fewer dimensions than `vector`, we will
unsqueeze on dimension 1 until they match. If you need a different unsqueezing of your mask,
do it yourself before passing the mask into this function.
If `memory_efficient` is set to true, we will simply use a very large negative number for those
masked positions so that the probabilities of those positions would be approximately 0.
This is not accurate in math, but works for most cases and consumes less memory.
In the case that the input vector is completely masked and `memory_efficient` is false, this function
returns an array of `0.0`. This behavior may cause `NaN` if this is used as the last layer of
a model that uses categorical cross-entropy loss. Instead, if `memory_efficient` is true, this function
will treat every element as equal, and do softmax over equal numbers.
"""
if mask is None:
result = torch.nn.functional.softmax(vector, dim=dim)
else:
while mask.dim() < vector.dim():
mask = mask.unsqueeze(1)
if not memory_efficient:
# To limit numerical errors from large vector elements outside the mask, we zero these out.
result = torch.nn.functional.softmax(vector * mask, dim=dim)
result = result * mask
result = result / (
result.sum(dim=dim, keepdim=True) + tiny_value_of_dtype(result.dtype)
)
else:
masked_vector = vector.masked_fill(~mask, min_value_of_dtype(vector.dtype))
result = torch.nn.functional.softmax(masked_vector, dim=dim)
return result
def masked_log_softmax(vector: torch.Tensor, mask: torch.BoolTensor, dim: int = -1) -> torch.Tensor:
"""
`torch.nn.functional.log_softmax(vector)` does not work if some elements of `vector` should be
masked. This performs a log_softmax on just the non-masked portions of `vector`. Passing
`None` in for the mask is also acceptable; you'll just get a regular log_softmax.
`vector` can have an arbitrary number of dimensions; the only requirement is that `mask` is
broadcastable to `vector's` shape. If `mask` has fewer dimensions than `vector`, we will
unsqueeze on dimension 1 until they match. If you need a different unsqueezing of your mask,
do it yourself before passing the mask into this function.
In the case that the input vector is completely masked, the return value of this function is
arbitrary, but not `nan`. You should be masking the result of whatever computation comes out
of this in that case, anyway, so the specific values returned shouldn't matter. Also, the way
that we deal with this case relies on having single-precision floats; mixing half-precision
floats with fully-masked vectors will likely give you `nans`.
If your logits are all extremely negative (i.e., the max value in your logit vector is -50 or
lower), the way we handle masking here could mess you up. But if you've got logit values that
extreme, you've got bigger problems than this.
"""
if mask is not None:
while mask.dim() < vector.dim():
mask = mask.unsqueeze(1)
# vector + mask.log() is an easy way to zero out masked elements in logspace, but it
# results in nans when the whole vector is masked. We need a very small value instead of a
# zero in the mask for these cases.
vector = vector + (mask + tiny_value_of_dtype(vector.dtype)).log()
return torch.nn.functional.log_softmax(vector, dim=dim)
def masked_max(
vector: torch.Tensor,
mask: torch.BoolTensor,
dim: int,
keepdim: bool = False,
) -> torch.Tensor:
"""
To calculate max along certain dimensions on masked values
# Parameters
vector : `torch.Tensor`
The vector to calculate max, assume unmasked parts are already zeros
mask : `torch.BoolTensor`
The mask of the vector. It must be broadcastable with vector.
dim : `int`
The dimension to calculate max
keepdim : `bool`
Whether to keep dimension
# Returns
`torch.Tensor`
A `torch.Tensor` of including the maximum values.
"""
replaced_vector = vector.masked_fill(~mask, min_value_of_dtype(vector.dtype))
max_value, _ = replaced_vector.max(dim=dim, keepdim=keepdim)
return max_value
def masked_mean(
vector: torch.Tensor, mask: torch.BoolTensor, dim: int, keepdim: bool = False
) -> torch.Tensor:
"""
To calculate mean along certain dimensions on masked values
# Parameters
vector : `torch.Tensor`
The vector to calculate mean.
mask : `torch.BoolTensor`
The mask of the vector. It must be broadcastable with vector.
dim : `int`
The dimension to calculate mean
keepdim : `bool`
Whether to keep dimension
# Returns
`torch.Tensor`
A `torch.Tensor` of including the mean values.
"""
replaced_vector = vector.masked_fill(~mask, 0.0)
value_sum = torch.sum(replaced_vector, dim=dim, keepdim=keepdim)
value_count = torch.sum(mask, dim=dim, keepdim=keepdim)
return value_sum / value_count.float().clamp(min=tiny_value_of_dtype(torch.float))
def masked_flip(padded_sequence: torch.Tensor, sequence_lengths: List[int]) -> torch.Tensor:
"""
Flips a padded tensor along the time dimension without affecting masked entries.
# Parameters
padded_sequence : `torch.Tensor`
The tensor to flip along the time dimension.
Assumed to be of dimensions (batch size, num timesteps, ...)
sequence_lengths : `torch.Tensor`
A list containing the lengths of each unpadded sequence in the batch.
# Returns
`torch.Tensor`
A `torch.Tensor` of the same shape as padded_sequence.
"""
assert padded_sequence.size(0) == len(
sequence_lengths
), f"sequence_lengths length ${len(sequence_lengths)} does not match batch size ${padded_sequence.size(0)}"
num_timesteps = padded_sequence.size(1)
flipped_padded_sequence = torch.flip(padded_sequence, [1])
sequences = [
flipped_padded_sequence[i, num_timesteps - length :]
for i, length in enumerate(sequence_lengths)
]
return torch.nn.utils.rnn.pad_sequence(sequences, batch_first=True)
def viterbi_decode(
tag_sequence: torch.Tensor,
transition_matrix: torch.Tensor,
tag_observations: Optional[List[int]] = None,
allowed_start_transitions: torch.Tensor = None,
allowed_end_transitions: torch.Tensor = None,
top_k: int = None,
):
"""
Perform Viterbi decoding in log space over a sequence given a transition matrix
specifying pairwise (transition) potentials between tags and a matrix of shape
(sequence_length, num_tags) specifying unary potentials for possible tags per
timestep.
# Parameters
tag_sequence : `torch.Tensor`, required.
A tensor of shape (sequence_length, num_tags) representing scores for
a set of tags over a given sequence.
transition_matrix : `torch.Tensor`, required.
A tensor of shape (num_tags, num_tags) representing the binary potentials
for transitioning between a given pair of tags.
tag_observations : `Optional[List[int]]`, optional, (default = `None`)
A list of length `sequence_length` containing the class ids of observed
elements in the sequence, with unobserved elements being set to -1. Note that
it is possible to provide evidence which results in degenerate labelings if
the sequences of tags you provide as evidence cannot transition between each
other, or those transitions are extremely unlikely. In this situation we log a
warning, but the responsibility for providing self-consistent evidence ultimately
lies with the user.
allowed_start_transitions : `torch.Tensor`, optional, (default = `None`)
An optional tensor of shape (num_tags,) describing which tags the START token
may transition *to*. If provided, additional transition constraints will be used for
determining the start element of the sequence.
allowed_end_transitions : `torch.Tensor`, optional, (default = `None`)
An optional tensor of shape (num_tags,) describing which tags may transition *to* the
end tag. If provided, additional transition constraints will be used for determining
the end element of the sequence.
top_k : `int`, optional, (default = `None`)
Optional integer specifying how many of the top paths to return. For top_k>=1, returns
a tuple of two lists: top_k_paths, top_k_scores, For top_k==None, returns a flattened
tuple with just the top path and its score (not in lists, for backwards compatibility).
# Returns
viterbi_path : `List[int]`
The tag indices of the maximum likelihood tag sequence.
viterbi_score : `torch.Tensor`
The score of the viterbi path.
"""
if top_k is None:
top_k = 1
flatten_output = True
elif top_k >= 1:
flatten_output = False
else:
raise ValueError(f"top_k must be either None or an integer >=1. Instead received {top_k}")
sequence_length, num_tags = list(tag_sequence.size())
has_start_end_restrictions = (
allowed_end_transitions is not None or allowed_start_transitions is not None
)
if has_start_end_restrictions:
if allowed_end_transitions is None:
allowed_end_transitions = torch.zeros(num_tags)
if allowed_start_transitions is None:
allowed_start_transitions = torch.zeros(num_tags)
num_tags = num_tags + 2
new_transition_matrix = torch.zeros(num_tags, num_tags)
new_transition_matrix[:-2, :-2] = transition_matrix
# Start and end transitions are fully defined, but cannot transition between each other.
allowed_start_transitions = torch.cat(
[allowed_start_transitions, torch.tensor([-math.inf, -math.inf])]
)
allowed_end_transitions = torch.cat(
[allowed_end_transitions, torch.tensor([-math.inf, -math.inf])]
)
# First define how we may transition FROM the start and end tags.
new_transition_matrix[-2, :] = allowed_start_transitions
# We cannot transition from the end tag to any tag.
new_transition_matrix[-1, :] = -math.inf
new_transition_matrix[:, -1] = allowed_end_transitions
# We cannot transition to the start tag from any tag.
new_transition_matrix[:, -2] = -math.inf
transition_matrix = new_transition_matrix
if tag_observations:
if len(tag_observations) != sequence_length:
raise ConfigurationError(
"Observations were provided, but they were not the same length "
"as the sequence. Found sequence of length: {} and evidence: {}".format(
sequence_length, tag_observations
)
)
else:
tag_observations = [-1 for _ in range(sequence_length)]
if has_start_end_restrictions:
tag_observations = [num_tags - 2] + tag_observations + [num_tags - 1]
zero_sentinel = torch.zeros(1, num_tags)
extra_tags_sentinel = torch.ones(sequence_length, 2) * -math.inf
tag_sequence = torch.cat([tag_sequence, extra_tags_sentinel], -1)
tag_sequence = torch.cat([zero_sentinel, tag_sequence, zero_sentinel], 0)
sequence_length = tag_sequence.size(0)
path_scores = []
path_indices = []
if tag_observations[0] != -1:
one_hot = torch.zeros(num_tags)
one_hot[tag_observations[0]] = 100000.0
path_scores.append(one_hot.unsqueeze(0))
else:
path_scores.append(tag_sequence[0, :].unsqueeze(0))
# Evaluate the scores for all possible paths.
for timestep in range(1, sequence_length):
# Add pairwise potentials to current scores.
summed_potentials = path_scores[timestep - 1].unsqueeze(2) + transition_matrix
summed_potentials = summed_potentials.view(-1, num_tags)
# Best pairwise potential path score from the previous timestep.
max_k = min(summed_potentials.size()[0], top_k)
scores, paths = torch.topk(summed_potentials, k=max_k, dim=0)
# If we have an observation for this timestep, use it
# instead of the distribution over tags.
observation = tag_observations[timestep]
# Warn the user if they have passed
# invalid/extremely unlikely evidence.
if tag_observations[timestep - 1] != -1 and observation != -1:
if transition_matrix[tag_observations[timestep - 1], observation] < -10000:
logger.warning(
"The pairwise potential between tags you have passed as "
"observations is extremely unlikely. Double check your evidence "
"or transition potentials!"
)
if observation != -1:
one_hot = torch.zeros(num_tags)
one_hot[observation] = 100000.0
path_scores.append(one_hot.unsqueeze(0))
else:
path_scores.append(tag_sequence[timestep, :] + scores)
path_indices.append(paths.squeeze())
# Construct the most likely sequence backwards.
path_scores_v = path_scores[-1].view(-1)
max_k = min(path_scores_v.size()[0], top_k)
viterbi_scores, best_paths = torch.topk(path_scores_v, k=max_k, dim=0)
viterbi_paths = []
for i in range(max_k):
viterbi_path = [best_paths[i]]
for backward_timestep in reversed(path_indices):
viterbi_path.append(int(backward_timestep.view(-1)[viterbi_path[-1]]))
# Reverse the backward path.
viterbi_path.reverse()
if has_start_end_restrictions:
viterbi_path = viterbi_path[1:-1]
# Viterbi paths uses (num_tags * n_permutations) nodes; therefore, we need to modulo.
viterbi_path = [j % num_tags for j in viterbi_path]
viterbi_paths.append(viterbi_path)
if flatten_output:
return viterbi_paths[0], viterbi_scores[0]
return viterbi_paths, viterbi_scores
def get_text_field_mask(
text_field_tensors: Dict[str, Dict[str, torch.Tensor]],
num_wrapping_dims: int = 0,
padding_id: int = 0,
) -> torch.BoolTensor:
"""
Takes the dictionary of tensors produced by a `TextField` and returns a mask
with 0 where the tokens are padding, and 1 otherwise. `padding_id` specifies the id of padding tokens.
We also handle `TextFields` wrapped by an arbitrary number of `ListFields`, where the number of wrapping
`ListFields` is given by `num_wrapping_dims`.
If `num_wrapping_dims == 0`, the returned mask has shape `(batch_size, num_tokens)`.
If `num_wrapping_dims > 0` then the returned mask has `num_wrapping_dims` extra
dimensions, so the shape will be `(batch_size, ..., num_tokens)`.
There could be several entries in the tensor dictionary with different shapes (e.g., one for
word ids, one for character ids). In order to get a token mask, we use the tensor in
the dictionary with the lowest number of dimensions. After subtracting `num_wrapping_dims`,
if this tensor has two dimensions we assume it has shape `(batch_size, ..., num_tokens)`,
and use it for the mask. If instead it has three dimensions, we assume it has shape
`(batch_size, ..., num_tokens, num_features)`, and sum over the last dimension to produce
the mask. Most frequently this will be a character id tensor, but it could also be a
featurized representation of each token, etc.
If the input `text_field_tensors` contains the "mask" key, this is returned instead of inferring the mask.
"""
masks = []
for indexer_name, indexer_tensors in text_field_tensors.items():
if "mask" in indexer_tensors:
masks.append(indexer_tensors["mask"].bool())
if len(masks) == 1:
return masks[0]
elif len(masks) > 1:
# TODO(mattg): My guess is this will basically never happen, so I'm not writing logic to
# handle it. Should be straightforward to handle, though. If you see this error in
# practice, open an issue on github.
raise ValueError("found two mask outputs; not sure which to use!")
tensor_dims = [
(tensor.dim(), tensor)
for indexer_output in text_field_tensors.values()
for tensor in indexer_output.values()
]
tensor_dims.sort(key=lambda x: x[0])
smallest_dim = tensor_dims[0][0] - num_wrapping_dims
if smallest_dim == 2:
token_tensor = tensor_dims[0][1]
return token_tensor != padding_id
elif smallest_dim == 3:
character_tensor = tensor_dims[0][1]
return (character_tensor != padding_id).any(dim=-1)
else:
raise ValueError("Expected a tensor with dimension 2 or 3, found {}".format(smallest_dim))
def get_token_ids_from_text_field_tensors(
text_field_tensors: Dict[str, Dict[str, torch.Tensor]],
) -> torch.Tensor:
"""
Our `TextFieldTensors` are complex output structures, because they try to handle a lot of
potential variation. Sometimes, you just want to grab the token ids from this data structure,
and that's not trivial without hard-coding assumptions about your data processing, which defeats
the entire purpose of that generality. This method tries to let you get the token ids out of the
data structure in your model without hard-coding any assumptions.
"""
for indexer_name, indexer_tensors in text_field_tensors.items():
for argument_name, tensor in indexer_tensors.items():
if argument_name in ["tokens", "token_ids", "input_ids"]:
return tensor
raise NotImplementedError(
"Our heuristic for guessing the right token ids failed. Please open an issue on "
"github with more detail on how you got this error, so we can implement more robust "
"logic in this method."
)
def weighted_sum(matrix: torch.Tensor, attention: torch.Tensor) -> torch.Tensor:
"""
Takes a matrix of vectors and a set of weights over the rows in the matrix (which we call an
"attention" vector), and returns a weighted sum of the rows in the matrix. This is the typical
computation performed after an attention mechanism.
Note that while we call this a "matrix" of vectors and an attention "vector", we also handle
higher-order tensors. We always sum over the second-to-last dimension of the "matrix", and we
assume that all dimensions in the "matrix" prior to the last dimension are matched in the
"vector". Non-matched dimensions in the "vector" must be `directly after the batch dimension`.
For example, say I have a "matrix" with dimensions `(batch_size, num_queries, num_words,
embedding_dim)`. The attention "vector" then must have at least those dimensions, and could
have more. Both:
- `(batch_size, num_queries, num_words)` (distribution over words for each query)
- `(batch_size, num_documents, num_queries, num_words)` (distribution over words in a
query for each document)
are valid input "vectors", producing tensors of shape:
`(batch_size, num_queries, embedding_dim)` and
`(batch_size, num_documents, num_queries, embedding_dim)` respectively.
"""
# We'll special-case a few settings here, where there are efficient (but poorly-named)
# operations in pytorch that already do the computation we need.
if attention.dim() == 2 and matrix.dim() == 3:
return attention.unsqueeze(1).bmm(matrix).squeeze(1)
if attention.dim() == 3 and matrix.dim() == 3:
return attention.bmm(matrix)
if matrix.dim() - 1 < attention.dim():
expanded_size = list(matrix.size())
for i in range(attention.dim() - matrix.dim() + 1):
matrix = matrix.unsqueeze(1)
expanded_size.insert(i + 1, attention.size(i + 1))
matrix = matrix.expand(*expanded_size)
intermediate = attention.unsqueeze(-1).expand_as(matrix) * matrix
return intermediate.sum(dim=-2)
def sequence_cross_entropy_with_logits(
logits: torch.FloatTensor,
targets: torch.LongTensor,
weights: Union[torch.FloatTensor, torch.BoolTensor],
average: str = "batch",
label_smoothing: float = None,
gamma: float = None,
alpha: Union[float, List[float], torch.FloatTensor] = None,
) -> torch.FloatTensor:
"""
Computes the cross entropy loss of a sequence, weighted with respect to
some user provided weights. Note that the weighting here is not the same as
in the `torch.nn.CrossEntropyLoss()` criterion, which is weighting
classes; here we are weighting the loss contribution from particular elements
in the sequence. This allows loss computations for models which use padding.
# Parameters
logits : `torch.FloatTensor`, required.
A `torch.FloatTensor` of size (batch_size, sequence_length, num_classes)
which contains the unnormalized probability for each class.
targets : `torch.LongTensor`, required.
A `torch.LongTensor` of size (batch, sequence_length) which contains the
index of the true class for each corresponding step.
weights : `Union[torch.FloatTensor, torch.BoolTensor]`, required.
A `torch.FloatTensor` of size (batch, sequence_length)
average: `str`, optional (default = `"batch"`)
If "batch", average the loss across the batches. If "token", average
the loss across each item in the input. If `None`, return a vector
of losses per batch element.
label_smoothing : `float`, optional (default = `None`)
Whether or not to apply label smoothing to the cross-entropy loss.
For example, with a label smoothing value of 0.2, a 4 class classification
target would look like `[0.05, 0.05, 0.85, 0.05]` if the 3rd class was
the correct label.
gamma : `float`, optional (default = `None`)
Focal loss[*] focusing parameter `gamma` to reduces the relative loss for
well-classified examples and put more focus on hard. The greater value
`gamma` is, the more focus on hard examples.
alpha : `Union[float, List[float]]`, optional (default = `None`)
Focal loss[*] weighting factor `alpha` to balance between classes. Can be
used independently with `gamma`. If a single `float` is provided, it
is assumed binary case using `alpha` and `1 - alpha` for positive and
negative respectively. If a list of `float` is provided, with the same
length as the number of classes, the weights will match the classes.
[*] T. Lin, P. Goyal, R. Girshick, K. He and P. Dollár, "Focal Loss for
Dense Object Detection," 2017 IEEE International Conference on Computer
Vision (ICCV), Venice, 2017, pp. 2999-3007.
# Returns
`torch.FloatTensor`
A torch.FloatTensor representing the cross entropy loss.
If `average=="batch"` or `average=="token"`, the returned loss is a scalar.
If `average is None`, the returned loss is a vector of shape (batch_size,).
"""
if average not in {None, "token", "batch"}:
raise ValueError("Got average f{average}, expected one of None, 'token', or 'batch'")
# make sure weights are float
weights = weights.to(logits.dtype)
# sum all dim except batch
non_batch_dims = tuple(range(1, len(weights.shape)))
# shape : (batch_size,)
weights_batch_sum = weights.sum(dim=non_batch_dims)
# shape : (batch * sequence_length, num_classes)
logits_flat = logits.view(-1, logits.size(-1))
# shape : (batch * sequence_length, num_classes)
log_probs_flat = torch.nn.functional.log_softmax(logits_flat, dim=-1)
# shape : (batch * max_len, 1)
targets_flat = targets.view(-1, 1).long()
# focal loss coefficient
if gamma:
# shape : (batch * sequence_length, num_classes)
probs_flat = log_probs_flat.exp()
# shape : (batch * sequence_length,)
probs_flat = torch.gather(probs_flat, dim=1, index=targets_flat)
# shape : (batch * sequence_length,)
focal_factor = (1.0 - probs_flat) ** gamma
# shape : (batch, sequence_length)
focal_factor = focal_factor.view(*targets.size())
weights = weights * focal_factor
if alpha is not None:
# shape : () / (num_classes,)
if isinstance(alpha, (float, int)):
# shape : (2,)
alpha_factor = torch.tensor(
[1.0 - float(alpha), float(alpha)], dtype=weights.dtype, device=weights.device
)
elif isinstance(alpha, (list, numpy.ndarray, torch.Tensor)):
# shape : (c,)
alpha_factor = torch.tensor(alpha, dtype=weights.dtype, device=weights.device)
if not alpha_factor.size():
# shape : (1,)
alpha_factor = alpha_factor.view(1)
# shape : (2,)
alpha_factor = torch.cat([1 - alpha_factor, alpha_factor])
else:
raise TypeError(
("alpha must be float, list of float, or torch.FloatTensor, {} provided.").format(
type(alpha)
)
)
# shape : (batch, max_len)
alpha_factor = torch.gather(alpha_factor, dim=0, index=targets_flat.view(-1)).view(
*targets.size()
)
weights = weights * alpha_factor
if label_smoothing is not None and label_smoothing > 0.0:
num_classes = logits.size(-1)
smoothing_value = label_smoothing / num_classes
# Fill all the correct indices with 1 - smoothing value.
smoothed_targets = torch.full_like(log_probs_flat, smoothing_value).scatter_(
-1, targets_flat, 1.0 - label_smoothing + smoothing_value
)
negative_log_likelihood_flat = -log_probs_flat * smoothed_targets
negative_log_likelihood_flat = negative_log_likelihood_flat.sum(-1, keepdim=True)
else:
# Contribution to the negative log likelihood only comes from the exact indices
# of the targets, as the target distributions are one-hot. Here we use torch.gather
# to extract the indices of the num_classes dimension which contribute to the loss.
# shape : (batch * sequence_length, 1)
negative_log_likelihood_flat = -torch.gather(log_probs_flat, dim=1, index=targets_flat)
# shape : (batch, sequence_length)
negative_log_likelihood = negative_log_likelihood_flat.view(*targets.size())
# shape : (batch, sequence_length)
negative_log_likelihood = negative_log_likelihood * weights
if average == "batch":
# shape : (batch_size,)
per_batch_loss = negative_log_likelihood.sum(non_batch_dims) / (
weights_batch_sum + tiny_value_of_dtype(negative_log_likelihood.dtype)
)
num_non_empty_sequences = (weights_batch_sum > 0).sum() + tiny_value_of_dtype(
negative_log_likelihood.dtype
)
return per_batch_loss.sum() / num_non_empty_sequences
elif average == "token":
return negative_log_likelihood.sum() / (
weights_batch_sum.sum() + tiny_value_of_dtype(negative_log_likelihood.dtype)
)
else:
# shape : (batch_size,)
per_batch_loss = negative_log_likelihood.sum(non_batch_dims) / (
weights_batch_sum + tiny_value_of_dtype(negative_log_likelihood.dtype)
)
return per_batch_loss
def replace_masked_values(
tensor: torch.Tensor, mask: torch.BoolTensor, replace_with: float
) -> torch.Tensor:
"""
Replaces all masked values in `tensor` with `replace_with`. `mask` must be broadcastable
to the same shape as `tensor`. We require that `tensor.dim() == mask.dim()`, as otherwise we
won't know which dimensions of the mask to unsqueeze.
This just does `tensor.masked_fill()`, except the pytorch method fills in things with a mask
value of 1, where we want the opposite. You can do this in your own code with
`tensor.masked_fill(~mask, replace_with)`.
"""
if tensor.dim() != mask.dim():
raise ConfigurationError(
"tensor.dim() (%d) != mask.dim() (%d)" % (tensor.dim(), mask.dim())
)
return tensor.masked_fill(~mask, replace_with)
def tensors_equal(tensor1: torch.Tensor, tensor2: torch.Tensor, tolerance: float = 1e-12) -> bool:
"""
A check for tensor equality (by value). We make sure that the tensors have the same shape,
then check all of the entries in the tensor for equality. We additionally allow the input
tensors to be lists or dictionaries, where we then do the above check on every position in the
list / item in the dictionary. If we find objects that aren't tensors as we're doing that, we
just defer to their equality check.
This is kind of a catch-all method that's designed to make implementing `__eq__` methods
easier, in a way that's really only intended to be useful for tests.
"""
if isinstance(tensor1, (list, tuple)):
if not isinstance(tensor2, (list, tuple)) or len(tensor1) != len(tensor2):
return False
return all(tensors_equal(t1, t2, tolerance) for t1, t2 in zip(tensor1, tensor2))
elif isinstance(tensor1, dict):
if not isinstance(tensor2, dict):
return False
if tensor1.keys() != tensor2.keys():
return False
return all(tensors_equal(tensor1[key], tensor2[key], tolerance) for key in tensor1)
elif isinstance(tensor1, torch.Tensor):
if not isinstance(tensor2, torch.Tensor):
return False
if tensor1.size() != tensor2.size():
return False
# Special case for bools since they don't support subtraction
if tensor1.dtype == torch.bool or tensor2.dtype == torch.bool:
return (tensor1 == tensor2).all()
return ((tensor1 - tensor2).abs().float() < tolerance).all()
else:
try:
return tensor1 == tensor2
except RuntimeError:
print(type(tensor1), type(tensor2))
raise
def device_mapping(cuda_device: int):
"""
In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU),
you have to supply a `map_location` function. Call this with
the desired `cuda_device` to get the function that `torch.load()` needs.
"""
def inner_device_mapping(storage: torch.Storage, location) -> torch.Storage:
if cuda_device >= 0:
return storage.cuda(cuda_device)
else:
return storage
return inner_device_mapping
def read_state_dict(
path: Union[PathLike, str],
strip_prefix: Optional[str] = None,
ignore: Optional[List[str]] = None,
strict: bool = True,
cuda_device: int = -1,
) -> Dict[str, torch.Tensor]:
"""
Read a PyTorch model state dictionary from a checkpoint at the given `path`.
# Parameters
path : `Union[PathLike, str]`, required
strip_prefix : `Optional[str]`, optional (default = `None`)
A prefix to remove from all of the state dict keys.
ignore : `Optional[List[str]]`, optional (default = `None`)
Optional list of regular expressions. Keys that match any of these will be removed
from the state dict.
!!! Note
If `strip_prefix` is given, the regular expressions in `ignore` are matched
before the prefix is stripped.
strict : `bool`, optional (default = `True`)
If `True` (the default) and `strip_prefix` was never used or any of the regular expressions
in `ignore` never matched, a `ValueError` will be raised.
cuda_device : `int`, optional (default = `-1`)
The device to load the parameters onto. Use `-1` (the default) for CPU.
# Returns
`Dict[str, torch.Tensor]`
An ordered dictionary of the state.
"""
state = torch.load(path, map_location=device_mapping(cuda_device))
out: Dict[str, torch.Tensor] = OrderedDict()
if ignore is not None and not isinstance(ignore, list):
# If user accidentally passed in something that is not a list - like a string,
# which is easy to do - the user would be confused why the resulting state dict
# is empty.
raise ValueError("'ignore' parameter should be a list")
# In 'strict' mode, we need to keep track of whether we've used `strip_prefix`
# and which regular expressions in `ignore` we've used.
strip_prefix_used: Optional[bool] = None
ignore_used: Optional[List[bool]] = None
if strict and strip_prefix is not None:
strip_prefix_used = False
if strict and ignore:
ignore_used = [False] * len(ignore)
for key in state.keys():
ignore_key = False
if ignore:
for i, pattern in enumerate(ignore):
if re.match(pattern, key):
if ignore_used:
ignore_used[i] = True
logger.warning("ignoring %s from state dict", key)
ignore_key = True
break
if ignore_key:
continue
new_key = key
if strip_prefix and key.startswith(strip_prefix):
strip_prefix_used = True
new_key = key[len(strip_prefix) :]
if not new_key:
raise ValueError("'strip_prefix' resulted in an empty string for a key")
out[new_key] = state[key]
if strip_prefix_used is False:
raise ValueError(f"'strip_prefix' of '{strip_prefix}' was never used")
if ignore is not None and ignore_used is not None:
for pattern, used in zip(ignore, ignore_used):
if not used:
raise ValueError(f"'ignore' pattern '{pattern}' didn't have any matches")
return out
def combine_tensors(combination: str, tensors: List[torch.Tensor]) -> torch.Tensor:
"""
Combines a list of tensors using element-wise operations and concatenation, specified by a
`combination` string. The string refers to (1-indexed) positions in the input tensor list,
and looks like `"1,2,1+2,3-1"`.
We allow the following kinds of combinations : `x`, `x*y`, `x+y`, `x-y`, and `x/y`,
where `x` and `y` are positive integers less than or equal to `len(tensors)`. Each of
the binary operations is performed elementwise. You can give as many combinations as you want
in the `combination` string. For example, for the input string `"1,2,1*2"`, the result
would be `[1;2;1*2]`, as you would expect, where `[;]` is concatenation along the last
dimension.
If you have a fixed, known way to combine tensors that you use in a model, you should probably
just use something like `torch.cat([x_tensor, y_tensor, x_tensor * y_tensor])`. This
function adds some complexity that is only necessary if you want the specific combination used
to be `configurable`.
If you want to do any element-wise operations, the tensors involved in each element-wise
operation must have the same shape.
This function also accepts `x` and `y` in place of `1` and `2` in the combination
string.
"""
if len(tensors) > 9:
raise ConfigurationError("Double-digit tensor lists not currently supported")
combination = combination.replace("x", "1").replace("y", "2")
to_concatenate = [_get_combination(piece, tensors) for piece in combination.split(",")]
return torch.cat(to_concatenate, dim=-1)
def _rindex(sequence: Sequence[T], obj: T) -> int:
"""
Return zero-based index in the sequence of the last item whose value is equal to obj. Raises a
ValueError if there is no such item.
# Parameters
sequence : `Sequence[T]`
obj : `T`
# Returns
`int`
zero-based index associated to the position of the last item equal to obj
"""
for i in range(len(sequence) - 1, -1, -1):
if sequence[i] == obj:
return i
raise ValueError(f"Unable to find {obj} in sequence {sequence}.")
def _get_combination(combination: str, tensors: List[torch.Tensor]) -> torch.Tensor:
if combination.isdigit():
index = int(combination) - 1
return tensors[index]
else:
if len(combination) != 3:
raise ConfigurationError("Invalid combination: " + combination)
first_tensor = _get_combination(combination[0], tensors)
second_tensor = _get_combination(combination[2], tensors)
operation = combination[1]
if operation == "*":
return first_tensor * second_tensor
elif operation == "/":
return first_tensor / second_tensor
elif operation == "+":
return first_tensor + second_tensor
elif operation == "-":
return first_tensor - second_tensor
else:
raise ConfigurationError("Invalid operation: " + operation)
def combine_tensors_and_multiply(
combination: str, tensors: List[torch.Tensor], weights: torch.nn.Parameter
) -> torch.Tensor:
"""
Like [`combine_tensors`](./util.md#combine_tensors), but does a weighted (linear)
multiplication while combining. This is a separate function from `combine_tensors`
because we try to avoid instantiating large intermediate tensors during the combination,
which is possible because we know that we're going to be multiplying by a weight vector in the end.
# Parameters
combination : `str`
Same as in `combine_tensors`
tensors : `List[torch.Tensor]`
A list of tensors to combine, where the integers in the `combination` are (1-indexed)
positions in this list of tensors. These tensors are all expected to have either three or
four dimensions, with the final dimension being an embedding. If there are four
dimensions, one of them must have length 1.
weights : `torch.nn.Parameter`
A vector of weights to use for the combinations. This should have shape (combined_dim,),
as calculated by `get_combined_dim`.
"""
if len(tensors) > 9:
raise ConfigurationError("Double-digit tensor lists not currently supported")
combination = combination.replace("x", "1").replace("y", "2")
pieces = combination.split(",")
tensor_dims = [tensor.size(-1) for tensor in tensors]
combination_dims = [_get_combination_dim(piece, tensor_dims) for piece in pieces]
dims_so_far = 0
to_sum = []
for piece, combination_dim in zip(pieces, combination_dims):
weight = weights[dims_so_far : (dims_so_far + combination_dim)]
dims_so_far += combination_dim
to_sum.append(_get_combination_and_multiply(piece, tensors, weight))
result = to_sum[0]
for result_piece in to_sum[1:]:
result = result + result_piece
return result
def _get_combination_and_multiply(
combination: str, tensors: List[torch.Tensor], weight: torch.nn.Parameter
) -> torch.Tensor:
if combination.isdigit():
index = int(combination) - 1
return torch.matmul(tensors[index], weight)
else:
if len(combination) != 3:
raise ConfigurationError("Invalid combination: " + combination)
first_tensor = _get_combination(combination[0], tensors)
second_tensor = _get_combination(combination[2], tensors)
operation = combination[1]
if operation == "*":
if first_tensor.dim() > 4 or second_tensor.dim() > 4:
raise ValueError("Tensors with dim > 4 not currently supported")
desired_dim = max(first_tensor.dim(), second_tensor.dim()) - 1
if first_tensor.dim() == 4:
expanded_dim = _rindex(first_tensor.size(), 1)
first_tensor = first_tensor.squeeze(expanded_dim)
if second_tensor.dim() == 4:
expanded_dim = _rindex(second_tensor.size(), 1)
second_tensor = second_tensor.squeeze(expanded_dim)
intermediate = first_tensor * weight
result = torch.matmul(intermediate, second_tensor.transpose(-1, -2))
if result.dim() == desired_dim + 1:
result = result.squeeze(-1)
return result
elif operation == "/":
if first_tensor.dim() > 4 or second_tensor.dim() > 4:
raise ValueError("Tensors with dim > 4 not currently supported")
desired_dim = max(first_tensor.dim(), second_tensor.dim()) - 1
if first_tensor.dim() == 4:
expanded_dim = _rindex(first_tensor.size(), 1)
first_tensor = first_tensor.squeeze(expanded_dim)
if second_tensor.dim() == 4:
expanded_dim = _rindex(second_tensor.size(), 1)
second_tensor = second_tensor.squeeze(expanded_dim)
intermediate = first_tensor * weight
result = torch.matmul(intermediate, second_tensor.pow(-1).transpose(-1, -2))
if result.dim() == desired_dim + 1:
result = result.squeeze(-1)
return result
elif operation == "+":
return torch.matmul(first_tensor, weight) + torch.matmul(second_tensor, weight)
elif operation == "-":
return torch.matmul(first_tensor, weight) - torch.matmul(second_tensor, weight)
else:
raise ConfigurationError("Invalid operation: " + operation)
def get_combined_dim(combination: str, tensor_dims: List[int]) -> int:
"""
For use with [`combine_tensors`](./util.md#combine_tensors).
This function computes the resultant dimension when calling `combine_tensors(combination, tensors)`,
when the tensor dimension is known. This is necessary for knowing the sizes of weight matrices
when building models that use `combine_tensors`.
# Parameters
combination : `str`
A comma-separated list of combination pieces, like `"1,2,1*2"`, specified identically to
`combination` in `combine_tensors`.
tensor_dims : `List[int]`
A list of tensor dimensions, where each dimension is from the `last axis` of the tensors
that will be input to `combine_tensors`.
"""
if len(tensor_dims) > 9:
raise ConfigurationError("Double-digit tensor lists not currently supported")
combination = combination.replace("x", "1").replace("y", "2")
return sum(_get_combination_dim(piece, tensor_dims) for piece in combination.split(","))
def _get_combination_dim(combination: str, tensor_dims: List[int]) -> int:
if combination.isdigit():
index = int(combination) - 1
return tensor_dims[index]
else:
if len(combination) != 3:
raise ConfigurationError("Invalid combination: " + combination)
first_tensor_dim = _get_combination_dim(combination[0], tensor_dims)
second_tensor_dim = _get_combination_dim(combination[2], tensor_dims)
operation = combination[1]
if first_tensor_dim != second_tensor_dim:
raise ConfigurationError('Tensor dims must match for operation "{}"'.format(operation))
return first_tensor_dim
def logsumexp(tensor: torch.Tensor, dim: int = -1, keepdim: bool = False) -> torch.Tensor:
"""
A numerically stable computation of logsumexp. This is mathematically equivalent to
`tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing log
probabilities.
# Parameters
tensor : `torch.FloatTensor`, required.
A tensor of arbitrary size.
dim : `int`, optional (default = `-1`)
The dimension of the tensor to apply the logsumexp to.
keepdim: `bool`, optional (default = `False`)
Whether to retain a dimension of size one at the dimension we reduce over.
"""
max_score, _ = tensor.max(dim, keepdim=keepdim)
if keepdim:
stable_vec = tensor - max_score
else:
stable_vec = tensor - max_score.unsqueeze(dim)
return max_score + (stable_vec.exp().sum(dim, keepdim=keepdim)).log()
def get_device_of(tensor: torch.Tensor) -> int:
"""
Returns the device of the tensor.
"""
if not tensor.is_cuda:
return -1
else:
return tensor.get_device()
def flatten_and_batch_shift_indices(indices: torch.Tensor, sequence_length: int) -> torch.Tensor:
"""
This is a subroutine for [`batched_index_select`](./util.md#batched_index_select).
The given `indices` of size `(batch_size, d_1, ..., d_n)` indexes into dimension 2 of a
target tensor, which has size `(batch_size, sequence_length, embedding_size)`. This
function returns a vector that correctly indexes into the flattened target. The sequence
length of the target must be provided to compute the appropriate offsets.
```python
indices = torch.ones([2,3], dtype=torch.long)
# Sequence length of the target tensor.
sequence_length = 10
shifted_indices = flatten_and_batch_shift_indices(indices, sequence_length)
# Indices into the second element in the batch are correctly shifted
# to take into account that the target tensor will be flattened before
# the indices are applied.
assert shifted_indices == [1, 1, 1, 11, 11, 11]
```
# Parameters
indices : `torch.LongTensor`, required.
sequence_length : `int`, required.
The length of the sequence the indices index into.
This must be the second dimension of the tensor.
# Returns
offset_indices : `torch.LongTensor`
"""
# Shape: (batch_size)
if torch.max(indices) >= sequence_length or torch.min(indices) < 0:
raise ConfigurationError(
f"All elements in indices should be in range (0, {sequence_length - 1})"
)
offsets = get_range_vector(indices.size(0), get_device_of(indices)) * sequence_length
for _ in range(len(indices.size()) - 1):
offsets = offsets.unsqueeze(1)
# Shape: (batch_size, d_1, ..., d_n)
offset_indices = indices + offsets
# Shape: (batch_size * d_1 * ... * d_n)
offset_indices = offset_indices.view(-1)
return offset_indices
def batched_index_select(
target: torch.Tensor,
indices: torch.LongTensor,
flattened_indices: Optional[torch.LongTensor] = None,
) -> torch.Tensor:
"""
The given `indices` of size `(batch_size, d_1, ..., d_n)` indexes into the sequence
dimension (dimension 2) of the target, which has size `(batch_size, sequence_length,
embedding_size)`.
This function returns selected values in the target with respect to the provided indices, which
have size `(batch_size, d_1, ..., d_n, embedding_size)`. This can use the optionally
precomputed `flattened_indices` with size `(batch_size * d_1 * ... * d_n)` if given.
An example use case of this function is looking up the start and end indices of spans in a
sequence tensor. This is used in the
[CoreferenceResolver](https://docs.allennlp.org/models/main/models/coref/models/coref/)
model to select contextual word representations corresponding to the start and end indices of
mentions.
The key reason this can't be done with basic torch functions is that we want to be able to use look-up
tensors with an arbitrary number of dimensions (for example, in the coref model, we don't know
a-priori how many spans we are looking up).
# Parameters
target : `torch.Tensor`, required.
A 3 dimensional tensor of shape (batch_size, sequence_length, embedding_size).
This is the tensor to be indexed.
indices : `torch.LongTensor`
A tensor of shape (batch_size, ...), where each element is an index into the
`sequence_length` dimension of the `target` tensor.
flattened_indices : `Optional[torch.Tensor]`, optional (default = `None`)
An optional tensor representing the result of calling `flatten_and_batch_shift_indices`
on `indices`. This is helpful in the case that the indices can be flattened once and
cached for many batch lookups.
# Returns
selected_targets : `torch.Tensor`
A tensor with shape [indices.size(), target.size(-1)] representing the embedded indices
extracted from the batch flattened target tensor.
"""
if flattened_indices is None:
# Shape: (batch_size * d_1 * ... * d_n)
flattened_indices = flatten_and_batch_shift_indices(indices, target.size(1))
# Shape: (batch_size * sequence_length, embedding_size)
flattened_target = target.view(-1, target.size(-1))
# Shape: (batch_size * d_1 * ... * d_n, embedding_size)
flattened_selected = flattened_target.index_select(0, flattened_indices)
selected_shape = list(indices.size()) + [target.size(-1)]
# Shape: (batch_size, d_1, ..., d_n, embedding_size)
selected_targets = flattened_selected.view(*selected_shape)
return selected_targets
def masked_index_fill(
target: torch.Tensor, indices: torch.LongTensor, mask: torch.BoolTensor, fill_value: int = 1
) -> torch.Tensor:
"""
The given `indices` in `target` will be will be filled with `fill_value` given a `mask`.
# Parameters
target : `torch.Tensor`, required.
A 2 dimensional tensor of shape (batch_size, sequence_length).
This is the tensor to be filled.
indices : `torch.LongTensor`, required
A 2 dimensional tensor of shape (batch_size, num_indices),
These are the indices that will be filled in the original tensor.
mask : `torch.Tensor`, required.
A 2 dimensional tensor of shape (batch_size, num_indices), mask.sum() == `nonzero_indices`.
fill_value : `int`, optional (default = `1`)
The value we fill the tensor with.
# Returns
filled_target : `torch.Tensor`
A tensor with shape (batch_size, sequence_length) where 'indices' are filled with `fill_value`
"""
mask = mask.bool()
prev_shape = target.size()
# Shape: (batch_size * num_indices)
flattened_indices = flatten_and_batch_shift_indices(indices * mask, target.size(1))
# Shape: (batch_size * num_indices, 1)
mask = mask.view(-1)
# Shape: (batch_size * sequence_length, 1)
flattened_target = target.view(-1, 1)
# Shape: (nonzero_indices, 1)
unmasked_indices = flattened_indices[mask].unsqueeze(-1)
flattened_target = flattened_target.scatter(0, unmasked_indices, fill_value)
filled_target = flattened_target.reshape(prev_shape)
return filled_target
def masked_index_replace(
target: torch.Tensor,
indices: torch.LongTensor,
mask: torch.BoolTensor,
replace: torch.Tensor,
) -> torch.Tensor:
"""
The given `indices` in `target` will be will be replaced with corresponding index
from the `replace` tensor given a `mask`.
# Parameters
target : `torch.Tensor`, required.
A 3 dimensional tensor of shape (batch_size, sequence_length, embedding_dim).
This is the tensor to be replaced into.
indices : `torch.LongTensor`, required
A 2 dimensional tensor of shape (batch_size, num_indices),
These are the indices that will be replaced in the original tensor.
mask : `torch.Tensor`, required.
A 2 dimensional tensor of shape (batch_size, num_indices), mask.sum() == `nonzero_indices`.
replace : `torch.Tensor`, required.
A 3 dimensional tensor of shape (batch_size, num_indices, embedding_dim),
The tensor to perform scatter from.
# Returns
replaced_target : `torch.Tensor`
A tensor with shape (batch_size, sequence_length, embedding_dim) where 'indices'
are replaced with the corrosponding vector from `replace`
"""
target = target.clone()
mask = mask.bool()
prev_shape = target.size()
# Shape: (batch_size * num_indices)
flattened_indices = flatten_and_batch_shift_indices(indices * mask, target.size(1))
# Shape: (batch_size * sequence_length, embedding_size)
flattened_target = target.view(-1, target.size(-1))
# Shape: (nonzero_indices, 1)
mask = mask.view(-1)
flattened_target[flattened_indices[mask]] = replace.view(-1, replace.size(-1))[mask]
# Shape: (batch_size, sequence_length, embedding_dim)
replaced_target = flattened_target.reshape(prev_shape)
return replaced_target
def batched_span_select(target: torch.Tensor, spans: torch.LongTensor) -> torch.Tensor:
"""
The given `spans` of size `(batch_size, num_spans, 2)` indexes into the sequence
dimension (dimension 2) of the target, which has size `(batch_size, sequence_length,
embedding_size)`.
This function returns segmented spans in the target with respect to the provided span indices.
# Parameters
target : `torch.Tensor`, required.
A 3 dimensional tensor of shape (batch_size, sequence_length, embedding_size).
This is the tensor to be indexed.
indices : `torch.LongTensor`
A 3 dimensional tensor of shape (batch_size, num_spans, 2) representing start and end
indices (both inclusive) into the `sequence_length` dimension of the `target` tensor.
# Returns
span_embeddings : `torch.Tensor`
A tensor with shape (batch_size, num_spans, max_batch_span_width, embedding_size]
representing the embedded spans extracted from the batch flattened target tensor.
span_mask: `torch.BoolTensor`
A tensor with shape (batch_size, num_spans, max_batch_span_width) representing the mask on
the returned span embeddings.
"""
# both of shape (batch_size, num_spans, 1)
span_starts, span_ends = spans.split(1, dim=-1)
# shape (batch_size, num_spans, 1)
# These span widths are off by 1, because the span ends are `inclusive`.
span_widths = span_ends - span_starts
# We need to know the maximum span width so we can
# generate indices to extract the spans from the sequence tensor.
# These indices will then get masked below, such that if the length
# of a given span is smaller than the max, the rest of the values
# are masked.
max_batch_span_width = span_widths.max().item() + 1
# Shape: (1, 1, max_batch_span_width)
max_span_range_indices = get_range_vector(max_batch_span_width, get_device_of(target)).view(
1, 1, -1
)
# Shape: (batch_size, num_spans, max_batch_span_width)
# This is a broadcasted comparison - for each span we are considering,
# we are creating a range vector of size max_span_width, but masking values
# which are greater than the actual length of the span.
#
# We're using <= here (and for the mask below) because the span ends are
# inclusive, so we want to include indices which are equal to span_widths rather
# than using it as a non-inclusive upper bound.
span_mask = max_span_range_indices <= span_widths
raw_span_indices = span_starts + max_span_range_indices
# We also don't want to include span indices which greater than the sequence_length,
# which happens because some spans near the end of the sequence
# have a start index + max_batch_span_width > sequence_length, so we add this to the mask here.
span_mask = span_mask & (raw_span_indices < target.size(1)) & (0 <= raw_span_indices)
span_indices = raw_span_indices * span_mask
# Shape: (batch_size, num_spans, max_batch_span_width, embedding_dim)
span_embeddings = batched_index_select(target, span_indices)
return span_embeddings, span_mask
def flattened_index_select(target: torch.Tensor, indices: torch.LongTensor) -> torch.Tensor:
"""
The given `indices` of size `(set_size, subset_size)` specifies subsets of the `target`
that each of the set_size rows should select. The `target` has size
`(batch_size, sequence_length, embedding_size)`, and the resulting selected tensor has size
`(batch_size, set_size, subset_size, embedding_size)`.
# Parameters
target : `torch.Tensor`, required.
A Tensor of shape (batch_size, sequence_length, embedding_size).
indices : `torch.LongTensor`, required.
A LongTensor of shape (set_size, subset_size). All indices must be < sequence_length
as this tensor is an index into the sequence_length dimension of the target.
# Returns
selected : `torch.Tensor`, required.
A Tensor of shape (batch_size, set_size, subset_size, embedding_size).
"""
if indices.dim() != 2:
raise ConfigurationError(
"Indices passed to flattened_index_select had shape {} but "
"only 2 dimensional inputs are supported.".format(indices.size())
)
# Shape: (batch_size, set_size * subset_size, embedding_size)
flattened_selected = target.index_select(1, indices.view(-1))
# Shape: (batch_size, set_size, subset_size, embedding_size)
selected = flattened_selected.view(target.size(0), indices.size(0), indices.size(1), -1)
return selected
def get_range_vector(size: int, device: int) -> torch.Tensor:
"""
Returns a range vector with the desired size, starting at 0. The CUDA implementation
is meant to avoid copy data from CPU to GPU.
"""
if device > -1:
return torch.cuda.LongTensor(size, device=device).fill_(1).cumsum(0) - 1
else:
return torch.arange(0, size, dtype=torch.long)
def bucket_values(
distances: torch.Tensor, num_identity_buckets: int = 4, num_total_buckets: int = 10
) -> torch.Tensor:
"""
Places the given values (designed for distances) into `num_total_buckets`semi-logscale
buckets, with `num_identity_buckets` of these capturing single values.
The default settings will bucket values into the following buckets:
[0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+].
# Parameters
distances : `torch.Tensor`, required.
A Tensor of any size, to be bucketed.
num_identity_buckets: `int`, optional (default = `4`).
The number of identity buckets (those only holding a single value).
num_total_buckets : `int`, (default = `10`)
The total number of buckets to bucket values into.
# Returns
`torch.Tensor`
A tensor of the same shape as the input, containing the indices of the buckets
the values were placed in.
"""
# Chunk the values into semi-logscale buckets using .floor().
# This is a semi-logscale bucketing because we divide by log(2) after taking the log.
# We do this to make the buckets more granular in the initial range, where we expect
# most values to fall. We then add (num_identity_buckets - 1) because we want these indices
# to start _after_ the fixed number of buckets which we specified would only hold single values.
logspace_index = (distances.float().log() / math.log(2)).floor().long() + (
num_identity_buckets - 1
)
# create a mask for values which will go into single number buckets (i.e not a range).
use_identity_mask = (distances <= num_identity_buckets).long()
use_buckets_mask = 1 + (-1 * use_identity_mask)
# Use the original values if they are less than num_identity_buckets, otherwise
# use the logspace indices.
combined_index = use_identity_mask * distances + use_buckets_mask * logspace_index
# Clamp to put anything > num_total_buckets into the final bucket.
return combined_index.clamp(0, num_total_buckets - 1)
def add_sentence_boundary_token_ids(
tensor: torch.Tensor, mask: torch.BoolTensor, sentence_begin_token: Any, sentence_end_token: Any
) -> Tuple[torch.Tensor, torch.BoolTensor]:
"""
Add begin/end of sentence tokens to the batch of sentences.
Given a batch of sentences with size `(batch_size, timesteps)` or
`(batch_size, timesteps, dim)` this returns a tensor of shape
`(batch_size, timesteps + 2)` or `(batch_size, timesteps + 2, dim)` respectively.
Returns both the new tensor and updated mask.
# Parameters
tensor : `torch.Tensor`
A tensor of shape `(batch_size, timesteps)` or `(batch_size, timesteps, dim)`
mask : `torch.BoolTensor`
A tensor of shape `(batch_size, timesteps)`
sentence_begin_token: `Any`
Can be anything that can be broadcast in torch for assignment.
For 2D input, a scalar with the `<S>` id. For 3D input, a tensor with length dim.
sentence_end_token: `Any`
Can be anything that can be broadcast in torch for assignment.
For 2D input, a scalar with the `</S>` id. For 3D input, a tensor with length dim.
# Returns
tensor_with_boundary_tokens : `torch.Tensor`
The tensor with the appended and prepended boundary tokens. If the input was 2D,
it has shape (batch_size, timesteps + 2) and if the input was 3D, it has shape
(batch_size, timesteps + 2, dim).
new_mask : `torch.BoolTensor`
The new mask for the tensor, taking into account the appended tokens
marking the beginning and end of the sentence.
"""
sequence_lengths = mask.sum(dim=1).detach().cpu().numpy()
tensor_shape = list(tensor.data.shape)
new_shape = list(tensor_shape)
new_shape[1] = tensor_shape[1] + 2
tensor_with_boundary_tokens = tensor.new_zeros(*new_shape, device=tensor.device)
if len(tensor_shape) == 2:
tensor_with_boundary_tokens[:, 1:-1] = tensor
tensor_with_boundary_tokens[:, 0] = sentence_begin_token
for i, j in enumerate(sequence_lengths):
tensor_with_boundary_tokens[i, j + 1] = sentence_end_token
new_mask = tensor_with_boundary_tokens != 0
elif len(tensor_shape) == 3:
tensor_with_boundary_tokens[:, 1:-1, :] = tensor
sentence_begin_token = sentence_begin_token.detach().to(tensor.device)
sentence_end_token = sentence_end_token.detach().to(tensor.device)
for i, j in enumerate(sequence_lengths):
tensor_with_boundary_tokens[i, 0, :] = sentence_begin_token
tensor_with_boundary_tokens[i, j + 1, :] = sentence_end_token
new_mask = (tensor_with_boundary_tokens > 0).sum(dim=-1) > 0
else:
raise ValueError("add_sentence_boundary_token_ids only accepts 2D and 3D input")
return tensor_with_boundary_tokens, new_mask
def remove_sentence_boundaries(
tensor: torch.Tensor, mask: torch.BoolTensor
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Remove begin/end of sentence embeddings from the batch of sentences.
Given a batch of sentences with size `(batch_size, timesteps, dim)`
this returns a tensor of shape `(batch_size, timesteps - 2, dim)` after removing
the beginning and end sentence markers. The sentences are assumed to be padded on the right,
with the beginning of each sentence assumed to occur at index 0 (i.e., `mask[:, 0]` is assumed
to be 1).
Returns both the new tensor and updated mask.
This function is the inverse of `add_sentence_boundary_token_ids`.
# Parameters
tensor : `torch.Tensor`
A tensor of shape `(batch_size, timesteps, dim)`
mask : `torch.BoolTensor`
A tensor of shape `(batch_size, timesteps)`
# Returns
tensor_without_boundary_tokens : `torch.Tensor`
The tensor after removing the boundary tokens of shape `(batch_size, timesteps - 2, dim)`
new_mask : `torch.BoolTensor`
The new mask for the tensor of shape `(batch_size, timesteps - 2)`.
"""
sequence_lengths = mask.sum(dim=1).detach().cpu().numpy()
tensor_shape = list(tensor.data.shape)
new_shape = list(tensor_shape)
new_shape[1] = tensor_shape[1] - 2
tensor_without_boundary_tokens = tensor.new_zeros(*new_shape)
new_mask = tensor.new_zeros((new_shape[0], new_shape[1]), dtype=torch.bool)
for i, j in enumerate(sequence_lengths):
if j > 2:
tensor_without_boundary_tokens[i, : (j - 2), :] = tensor[i, 1 : (j - 1), :]
new_mask[i, : (j - 2)] = True
return tensor_without_boundary_tokens, new_mask
def add_positional_features(
tensor: torch.Tensor, min_timescale: float = 1.0, max_timescale: float = 1.0e4
):
"""
Implements the frequency-based positional encoding described
in [Attention is All you Need][0].
Adds sinusoids of different frequencies to a `Tensor`. A sinusoid of a
different frequency and phase is added to each dimension of the input `Tensor`.
This allows the attention heads to use absolute and relative positions.
The number of timescales is equal to hidden_dim / 2 within the range
(min_timescale, max_timescale). For each timescale, the two sinusoidal
signals sin(timestep / timescale) and cos(timestep / timescale) are
generated and concatenated along the hidden_dim dimension.
[0]: https://www.semanticscholar.org/paper/Attention-Is-All-You-Need-Vaswani-Shazeer/0737da0767d77606169cbf4187b83e1ab62f6077
# Parameters
tensor : `torch.Tensor`
a Tensor with shape (batch_size, timesteps, hidden_dim).
min_timescale : `float`, optional (default = `1.0`)
The smallest timescale to use.
max_timescale : `float`, optional (default = `1.0e4`)
The largest timescale to use.
# Returns
`torch.Tensor`
The input tensor augmented with the sinusoidal frequencies.
""" # noqa
_, timesteps, hidden_dim = tensor.size()
timestep_range = get_range_vector(timesteps, get_device_of(tensor)).data.float()
# We're generating both cos and sin frequencies,
# so half for each.
num_timescales = hidden_dim // 2
timescale_range = get_range_vector(num_timescales, get_device_of(tensor)).data.float()
log_timescale_increments = math.log(float(max_timescale) / float(min_timescale)) / float(
num_timescales - 1
)
inverse_timescales = min_timescale * torch.exp(timescale_range * -log_timescale_increments)
# Broadcasted multiplication - shape (timesteps, num_timescales)
scaled_time = timestep_range.unsqueeze(1) * inverse_timescales.unsqueeze(0)
# shape (timesteps, 2 * num_timescales)
sinusoids = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 1)
if hidden_dim % 2 != 0:
# if the number of dimensions is odd, the cos and sin
# timescales had size (hidden_dim - 1) / 2, so we need
# to add a row of zeros to make up the difference.
sinusoids = torch.cat([sinusoids, sinusoids.new_zeros(timesteps, 1)], 1)
return tensor + sinusoids.unsqueeze(0)
def clone(module: torch.nn.Module, num_copies: int) -> torch.nn.ModuleList:
"""Produce N identical layers."""
return torch.nn.ModuleList(copy.deepcopy(module) for _ in range(num_copies))
def combine_initial_dims(tensor: torch.Tensor) -> torch.Tensor:
"""
Given a (possibly higher order) tensor of ids with shape
(d1, ..., dn, sequence_length)
Return a view that's (d1 * ... * dn, sequence_length).
If original tensor is 1-d or 2-d, return it as is.
"""
if tensor.dim() <= 2:
return tensor
else:
return tensor.view(-1, tensor.size(-1))
def uncombine_initial_dims(tensor: torch.Tensor, original_size: torch.Size) -> torch.Tensor:
"""
Given a tensor of embeddings with shape
(d1 * ... * dn, sequence_length, embedding_dim)
and the original shape
(d1, ..., dn, sequence_length),
return the reshaped tensor of embeddings with shape
(d1, ..., dn, sequence_length, embedding_dim).
If original size is 1-d or 2-d, return it as is.
"""
if len(original_size) <= 2:
return tensor
else:
view_args = list(original_size) + [tensor.size(-1)]
return tensor.view(*view_args)
def inspect_parameters(module: torch.nn.Module, quiet: bool = False) -> Dict[str, Any]:
"""
Inspects the model/module parameters and their tunability. The output is structured
in a nested dict so that parameters in same sub-modules are grouped together.
This can be helpful to setup module path based regex, for example in initializer.
It prints it by default (optional) and returns the inspection dict. Eg. output::
{
"_text_field_embedder": {
"token_embedder_tokens": {
"_projection": {
"bias": "tunable",
"weight": "tunable"
},
"weight": "frozen"
}
}
}
"""
results: Dict[str, Any] = {}
for name, param in sorted(module.named_parameters()):
keys = name.split(".")
write_to = results
for key in keys[:-1]:
if key not in write_to:
write_to[key] = {}
write_to = write_to[key]
write_to[keys[-1]] = "tunable" if param.requires_grad else "frozen"
if not quiet:
print(json.dumps(results, indent=4))
return results
def find_text_field_embedder(model: torch.nn.Module) -> torch.nn.Module:
"""
Takes a `Model` and returns the `Module` that is a `TextFieldEmbedder`. We return just the
first one, as it's very rare to have more than one. If there isn't a `TextFieldEmbedder` in the
given `Model`, we raise a `ValueError`.
"""
from allennlp.modules.text_field_embedders.text_field_embedder import TextFieldEmbedder
for module in model.modules():
if isinstance(module, TextFieldEmbedder):
return module
raise ValueError("Couldn't find TextFieldEmbedder!")
def find_embedding_layer(model: torch.nn.Module) -> torch.nn.Module:
"""
Takes a model (typically an AllenNLP `Model`, but this works for any `torch.nn.Module`) and
makes a best guess about which module is the embedding layer. For typical AllenNLP models,
this often is the `TextFieldEmbedder`, but if you're using a pre-trained contextualizer, we
really want layer 0 of that contextualizer, not the output. So there are a bunch of hacks in
here for specific pre-trained contextualizers.
"""
# We'll look for a few special cases in a first pass, then fall back to just finding a
# TextFieldEmbedder in a second pass if we didn't find a special case.
from transformers.models.gpt2.modeling_gpt2 import GPT2Model
from transformers.models.bert.modeling_bert import BertEmbeddings
from transformers.models.albert.modeling_albert import AlbertEmbeddings
from transformers.models.roberta.modeling_roberta import RobertaEmbeddings
from allennlp.modules.text_field_embedders.text_field_embedder import TextFieldEmbedder
from allennlp.modules.text_field_embedders.basic_text_field_embedder import (
BasicTextFieldEmbedder,
)
from allennlp.modules.token_embedders.embedding import Embedding
for module in model.modules():
if isinstance(module, BertEmbeddings):
return module.word_embeddings
if isinstance(module, RobertaEmbeddings):
return module.word_embeddings
if isinstance(module, AlbertEmbeddings):
return module.word_embeddings
if isinstance(module, GPT2Model):
return module.wte
for module in model.modules():
if isinstance(module, TextFieldEmbedder):
if isinstance(module, BasicTextFieldEmbedder):
# We'll have a check for single Embedding cases, because we can be more efficient
# in cases like this. If this check fails, then for something like hotflip we need
# to actually run the text field embedder and construct a vector for each token.
if len(module._token_embedders) == 1:
embedder = list(module._token_embedders.values())[0]
if isinstance(embedder, Embedding):
if embedder._projection is None:
# If there's a projection inside the Embedding, then we need to return
# the whole TextFieldEmbedder, because there's more computation that
# needs to be done than just multiply by an embedding matrix.
return embedder
return module
raise RuntimeError("No embedding module found!")
def get_token_offsets_from_text_field_inputs(
text_field_inputs: List[Any],
) -> Optional[torch.Tensor]:
"""
Given a list of inputs to a TextFieldEmbedder, tries to find token offsets from those inputs, if
there are any. You will have token offsets if you are using a mismatched token embedder; if
you're not, the return value from this function should be None. This function is intended to be
called from a `forward_hook` attached to a `TextFieldEmbedder`, so the inputs are formatted just
as a list.
It's possible in theory that you could have multiple offsets as inputs to a single call to a
`TextFieldEmbedder`, but that's an extremely rare use case (I can't really imagine anyone
wanting to do that). In that case, we'll only return the first one. If you need different
behavior for your model, open an issue on github describing what you're doing.
"""
for input_index, text_field_input in enumerate(text_field_inputs):
if not isinstance(text_field_input, dict):
continue
for input_value in text_field_input.values():
if not isinstance(input_value, dict):
continue
for embedder_arg_name, embedder_arg_value in input_value.items():
if embedder_arg_name == "offsets":
return embedder_arg_value
return None
def extend_layer(layer: torch.nn.Module, new_dim: int) -> None:
valid_layers = [torch.nn.Linear, torch.nn.Bilinear]
if not any([isinstance(layer, i) for i in valid_layers]):
raise ConfigurationError("Inappropriate layer type")
extend_dim = new_dim - layer.out_features
if not extend_dim:
return layer
if isinstance(layer, torch.nn.Linear):
new_weight = torch.FloatTensor(extend_dim, layer.in_features)
elif isinstance(layer, torch.nn.Bilinear):
new_weight = torch.FloatTensor(extend_dim, layer.in1_features, layer.in2_features)
new_bias = torch.FloatTensor(extend_dim)
torch.nn.init.xavier_uniform_(new_weight)
torch.nn.init.zeros_(new_bias)
device = layer.weight.device
layer.weight = torch.nn.Parameter(
torch.cat([layer.weight.data, new_weight.to(device)], dim=0),
requires_grad=layer.weight.requires_grad,
)
layer.bias = torch.nn.Parameter(
torch.cat([layer.bias.data, new_bias.to(device)], dim=0),
requires_grad=layer.bias.requires_grad,
)
layer.out_features = new_dim
def masked_topk(
input_: torch.FloatTensor,
mask: torch.BoolTensor,
k: Union[int, torch.LongTensor],
dim: int = -1,
) -> Tuple[torch.LongTensor, torch.LongTensor, torch.FloatTensor]:
"""
Extracts the top-k items along a certain dimension. This is similar to `torch.topk` except:
(1) we allow of a `mask` that makes the function not consider certain elements;
(2) the returned top input, mask, and indices are sorted in their original order in the input;
(3) May use the same k for all dimensions, or different k for each.
# Parameters
input_ : `torch.FloatTensor`, required.
A tensor containing the items that we want to prune.
mask : `torch.BoolTensor`, required.
A tensor with the same shape as `input_` that makes the function not consider masked out
(i.e. False) elements.
k : `Union[int, torch.LongTensor]`, required.
If a tensor of shape as `input_` except without dimension `dim`, specifies the number of
items to keep for each dimension.
If an int, keep the same number of items for all dimensions.
# Returns
top_input : `torch.FloatTensor`
The values of the top-k scoring items.
Has the same shape as `input_` except dimension `dim` has value `k` when it's an `int`
or `k.max()` when it's a tensor.
top_mask : `torch.BoolTensor`
The corresponding mask for `top_input`.
Has the shape as `top_input`.
top_indices : `torch.IntTensor`
The indices of the top-k scoring items into the original `input_`
tensor. This is returned because it can be useful to retain pointers to
the original items, if each item is being scored by multiple distinct
scorers, for instance.
Has the shape as `top_input`.
"""
if input_.size() != mask.size():
raise ValueError("`input_` and `mask` must have the same shape.")
if not -input_.dim() <= dim < input_.dim():
raise ValueError("`dim` must be in `[-input_.dim(), input_.dim())`")
dim = (dim + input_.dim()) % input_.dim()
max_k = k if isinstance(k, int) else k.max()
# We put the dim in question to the last dimension by permutation, and squash all leading dims.
# [0, 1, ..., dim - 1, dim + 1, ..., input.dim() - 1, dim]
permutation = list(range(input_.dim()))
permutation.pop(dim)
permutation += [dim]
# [0, 1, ..., dim - 1, -1, dim, ..., input.dim() - 2]; for restoration
reverse_permutation = list(range(input_.dim() - 1))
reverse_permutation.insert(dim, -1)
other_dims_size = list(input_.size())
other_dims_size.pop(dim)
permuted_size = other_dims_size + [max_k] # for restoration
# If an int was given for number of items to keep, construct tensor by repeating the value.
if isinstance(k, int):
# Put the tensor on same device as the mask.
k = k * torch.ones(*other_dims_size, dtype=torch.long, device=mask.device)
else:
if list(k.size()) != other_dims_size:
raise ValueError(
"`k` must have the same shape as `input_` with dimension `dim` removed."
)
num_items = input_.size(dim)
# (batch_size, num_items) -- "batch_size" refers to all other dimensions stacked together
input_ = input_.permute(*permutation).reshape(-1, num_items)
mask = mask.permute(*permutation).reshape(-1, num_items)
k = k.reshape(-1)
# Make sure that we don't select any masked items by setting their scores to be very
# negative.
input_ = replace_masked_values(input_, mask, min_value_of_dtype(input_.dtype))
# Shape: (batch_size, max_k)
_, top_indices = input_.topk(max_k, 1)
# Mask based on number of items to keep for each sentence.
# Shape: (batch_size, max_k)
top_indices_mask = get_mask_from_sequence_lengths(k, max_k).bool()
# Fill all masked indices with largest "top" index for that sentence, so that all masked
# indices will be sorted to the end.
# Shape: (batch_size, 1)
fill_value, _ = top_indices.max(dim=1, keepdim=True)
# Shape: (batch_size, max_num_items_to_keep)
top_indices = torch.where(top_indices_mask, top_indices, fill_value)
# Now we order the selected indices in increasing order with
# respect to their indices (and hence, with respect to the
# order they originally appeared in the `embeddings` tensor).
top_indices, _ = top_indices.sort(1)
# Combine the masks on spans that are out-of-bounds, and the mask on spans that are outside
# the top k for each sentence.
# Shape: (batch_size, max_k)
sequence_mask = mask.gather(1, top_indices)
top_mask = top_indices_mask & sequence_mask
# Shape: (batch_size, max_k)
top_input = input_.gather(1, top_indices)
return (
top_input.reshape(*permuted_size).permute(*reverse_permutation),
top_mask.reshape(*permuted_size).permute(*reverse_permutation),
top_indices.reshape(*permuted_size).permute(*reverse_permutation),
)
def info_value_of_dtype(dtype: torch.dtype):
"""
Returns the `finfo` or `iinfo` object of a given PyTorch data type. Does not allow torch.bool.
"""
if dtype == torch.bool:
raise TypeError("Does not support torch.bool")
elif dtype.is_floating_point:
return torch.finfo(dtype)
else:
return torch.iinfo(dtype)
def min_value_of_dtype(dtype: torch.dtype):
"""
Returns the minimum value of a given PyTorch data type. Does not allow torch.bool.
"""
return info_value_of_dtype(dtype).min
def max_value_of_dtype(dtype: torch.dtype):
"""
Returns the maximum value of a given PyTorch data type. Does not allow torch.bool.
"""
return info_value_of_dtype(dtype).max
def tiny_value_of_dtype(dtype: torch.dtype):
"""
Returns a moderately tiny value for a given PyTorch data type that is used to avoid numerical
issues such as division by zero.
This is different from `info_value_of_dtype(dtype).tiny` because it causes some NaN bugs.
Only supports floating point dtypes.
"""
if not dtype.is_floating_point:
raise TypeError("Only supports floating point dtypes.")
if dtype == torch.float or dtype == torch.double:
return 1e-13
elif dtype == torch.half:
return 1e-4
else:
raise TypeError("Does not support dtype " + str(dtype))
_V = TypeVar("_V", int, float, torch.Tensor)
def distributed_device() -> torch.device:
"""
Get the correct `torch.device` of the current process to use for distributed point-to-point communication.
"""
if not is_distributed():
raise RuntimeError(
"'distributed_device()' can only be called within a distributed process group"
)
return int_to_device(-1 if dist.get_backend() != "nccl" else torch.cuda.current_device())
def dist_reduce(value: _V, reduce_op) -> _V:
"""
Reduces the given `value` across all distributed worker nodes according the given
reduction operation.
If called outside of a distributed context, it will just return `value`.
# Parameters
value : `_V`
The value to reduce across distributed nodes.
reduce_op : `torch.distributed.ReduceOp`
The [reduction operation](https://pytorch.org/docs/stable/distributed.html#torch.distributed.ReduceOp)
to use.
**kwargs : `Any`
Additional arguments used to construct the tensor that will wrap `value`.
# Returns
`_V`
The final value.
"""
if not is_distributed():
return value
device = distributed_device()
if isinstance(value, torch.Tensor):
value_tensor = value.clone().to(device)
else:
value_tensor = torch.tensor(value, device=device)
dist.all_reduce(value_tensor, op=reduce_op)
if isinstance(value, torch.Tensor):
return value_tensor
return value_tensor.item() # type: ignore[return-value]
def dist_reduce_sum(value: _V) -> _V:
"""
Sums the given `value` across distributed worker nodes.
This is equivalent to calling `dist_reduce(v, dist.ReduceOp.SUM)`.
"""
# NOTE: Why have this check here even though the same check is in `dist_reduce()`?
# Because we want to be able to call this function even when torch's distributed framework
# is not available...
# If torch's distributed framework is not available on the system, then `torch.distributed`
# (imported here as `dist`) will just be an empty module. So calling `dist.ReduceOp.SUM` would
# result in an `AttributeError`.
if not is_distributed():
return value
return dist_reduce(value, dist.ReduceOp.SUM)
def _collect_state_dict(
module: torch.nn.Module,
state_dict: Optional[StateDictType],
recurse: bool = True,
prefix: str = "",
) -> Tuple[StateDictType, List[str], List[str]]:
"""
Collect a module's state dict across distributed processes.
Returns the syncronized state dictionary, which will always be a valid state dict,
and then the missing and unexpected keys corresponding to the original `state_dict`.
Parameters that missing from the original `state_dict` will be populated from the
corresponding parameter in the primary processes' module's state dict.
!!! Note
`missing_keys` and `unexpected_keys` are only populated in the primary process.
"""
# This is the device we'll use for the broadcast operation.
dist_device = distributed_device()
# We'll keep tensors on CPU in the returned state dict.
state_dict_device = int_to_device(-1)
missing_keys: List[str] = []
unexpected_keys: List[str] = []
# Gather current state dict and prepare to iterator over it.
# We iterate over this state dict instead of `state_dict` so we can be sure
# that the order is consistent across processes.
# We'll also update this state dict as we go and return it at the end.
if recurse:
current_state_dict = module.state_dict()
else:
# Only collect state of direct members, including both parameters and buffers.
current_state_dict = OrderedDict(
chain(
# Paramaters
((n, p.data) for (n, p) in module.named_parameters(recurse=False)),
# Buffers
module.named_buffers(recurse=False),
)
)
keys = list(current_state_dict.keys())
# Gather unexpected_keys.
if is_global_primary():
assert state_dict is not None
for key in state_dict:
if key not in keys:
unexpected_keys.append(key)
for key in keys:
tensor = current_state_dict[key]
if is_global_primary():
assert state_dict is not None
if key in state_dict:
# Update `tensor` to the value in `state_dict`.
tensor = state_dict[key]
else:
missing_keys.append(key)
logger.debug("Broadcasting distributed parameter '%s'", prefix + key)
tensor = tensor.to(dist_device)
dist.broadcast(tensor, 0)
current_state_dict[key] = tensor.to(state_dict_device)
return current_state_dict, missing_keys, unexpected_keys
class _IncompatibleKeys(NamedTuple):
missing_keys: List[str]
unexpected_keys: List[str]
def __repr__(self):
if not self.missing_keys and not self.unexpected_keys:
return "<All keys matched successfully>"
return f"(missing_keys = {self.missing_keys}, unexpected_keys = {self.unexpected_keys})"
def _check_incompatible_keys(
module, missing_keys: List[str], unexpected_keys: List[str], strict: bool
):
error_msgs: List[str] = []
if missing_keys:
error_msgs.append(
"Missing key(s) in state_dict: {}".format(", ".join(f'"{k}"' for k in missing_keys))
)
if unexpected_keys:
error_msgs.append(
"Unexpected key(s) in state_dict: {}".format(
", ".join(f'"{k}"' for k in unexpected_keys)
)
)
if error_msgs and strict:
raise RuntimeError(
"Error(s) in loading state_dict for {}:\n\t{}".format(
module.__class__.__name__, "\n\t".join(error_msgs)
)
)
def load_state_dict_distributed(
module: torch.nn.Module,
state_dict: Optional[StateDictType],
strict: bool = True,
prefix: str = "",
) -> _IncompatibleKeys:
"""
Load a `state_dict` to the `module` within a distributed process. Only the global
primary process requires the `state_dict` to not be `None`. All other processes
will have the state tensors broadcasted to them one-by-one.
If `strict` is `True`, then the keys of `state_dict` must exactly match the keys
returned by `module.state_dict()`.
!!! Note
The returned `missing_keys` and `unexpected_keys` will only be accurate
in the primary process.
# Returns
A `NamedTuple` with `missing_keys` and `unexpected_keys` fields, both of which
are lists of strings.
# Raises
`RuntimeError`
If `strict` is `True` and there are missing or unexpected keys.
"""
if not is_distributed():
return module.load_state_dict(state_dict, strict=strict)
if is_global_primary():
assert state_dict is not None
else:
assert state_dict is None
missing_keys: List[str] = []
unexpected_keys: List[str] = []
submodules = dict(module.named_children())
def update_key_list(original, updates):
for key in updates:
if key not in original:
original.append(key)
from allennlp.nn.parallel.sharded_module_mixin import ShardedModuleMixin
# If we've found a sharded module or there aren't any more submodules of the current module,
# we collect the state_dict and load it now instead of recursing further.
if isinstance(module, ShardedModuleMixin) or not submodules:
# Collect.
state_dict, _missing_keys, _unexpected_keys = _collect_state_dict(
module, state_dict, prefix=prefix
)
assert state_dict is not None
update_key_list(missing_keys, _missing_keys)
update_key_list(unexpected_keys, _unexpected_keys)
# And load.
_missing_keys, _unexpected_keys = module.load_state_dict(state_dict, strict=False)
update_key_list(missing_keys, _missing_keys)
update_key_list(unexpected_keys, _unexpected_keys)
else:
# We'll recursively call this function on each submodule, but first we need
# to collect any parameters that are direct members of this module.
direct_member_state_dict, _missing_keys, _unexpected_keys = _collect_state_dict(
module,
state_dict,
recurse=False,
prefix=prefix,
)
# `_unexpected_keys` will contain keys corresponding to submodules (not direct members)
# that may be legitimate, so we ignore any `_unexpected_keys` here that correspond to submodules.
_unexpected_keys = [
k for k in _unexpected_keys if "." not in k or k.split(".")[0] not in submodules.keys()
]
update_key_list(missing_keys, _missing_keys)
update_key_list(unexpected_keys, _unexpected_keys)
# `_missing_keys` here will contain any keys corresponding to submodules, but
# we'll remove those below.
_missing_keys, _unexpected_keys = module.load_state_dict(
direct_member_state_dict, strict=False
)
update_key_list(missing_keys, _missing_keys)
update_key_list(unexpected_keys, _unexpected_keys)
# Okay, now for the recursive part.
for name, submodule in submodules.items():
# Update `missing_keys` to remove keys corresponding to this submodule.
# If they are actually missing after this step, we add them back in below.
missing_keys = [k for k in missing_keys if not k.startswith(name + ".")]
submodule_state_dict: Optional[StateDictType] = None
if is_global_primary():
assert state_dict is not None
submodule_state_dict = {
key.replace(name + ".", "", 1): value
for key, value in state_dict.items()
if key.startswith(name + ".")
}
_missing_keys, _unexpected_keys = load_state_dict_distributed(
submodule,
submodule_state_dict,
strict=False,
prefix=prefix + name + ".",
)
update_key_list(missing_keys, [f"{name}.{key}" for key in _missing_keys])
update_key_list(unexpected_keys, [f"{name}.{key}" for key in _unexpected_keys])
_check_incompatible_keys(module, missing_keys, unexpected_keys, strict)
return _IncompatibleKeys(missing_keys, unexpected_keys)
|
__author__ = 'emalishenko'
from model.group import Group
from random import randrange
def test_modify_group_name(app):
group = Group(name="To be modified")
if app.group.count() == 0:
app.group.create(Group(name="New group name"))
old_groups = app.group.get_group_list()
index = randrange(len(old_groups))
group.id = old_groups[index].id
app.group.modify_group_by_index(group, index)
assert len(old_groups) == app.group.count()
new_groups = app.group.get_group_list()
old_groups[index] = group
assert sorted(old_groups, key = Group.id_or_max) == sorted(new_groups, key = Group.id_or_max)
|
"""
"""
import pygimli as pg
import pybert as pb
class DCMultiElectrodeModellingC(pb.DCMultiElectrodeModelling):
def __init__(self, mesh, data, verbose):
super().__init__(mesh, data, verbose)
self.setComplex(True)
self._J = pg.matrix.BlockMatrix()
self.setJacobian(self._J)
self._C = pg.matrix.BlockMatrix()
self.setConstraints(self._C)
self.matrixHeap = []
# super().createConstraints = self.createConstraints
def createDefaultStartModel(self):
"""
"""
res = pb.getComplexData(self.data())
parCount = self.regionManager().parameterCount()
re = pg.Vector(parCount, pg.mean(pg.math.real(res)))
im = pg.Vector(parCount, -pg.mean(pg.math.imag(res)))
return pg.cat(re, im)
def createJacobian(self, model):
print('=' * 100)
if self.complex():
modelRe = model[0:int(len(model)/2)]
modelIm = model[int(len(model)/2):len(model)]
modelC = pg.math.toComplex(modelRe, modelIm)
print("Real", min(modelRe), max(modelRe))
print("Imag", min(modelIm), max(modelIm))
u = self.prepareJacobian_(modelC)
if self._J.rows() == 0:
#re(data)/re(mod) = im(data)/im(mod)
# we need a local copy until we have a gimli internal reference counter FIXTHIS
M1 = pg.Matrix()
M2 = pg.Matrix()
self.matrixHeap.append(M1)
self.matrixHeap.append(M2)
JRe = self._J.addMatrix(M1)
JIm = self._J.addMatrix(M2)
self._J.addMatrixEntry(JRe, 0, 0)
self._J.addMatrixEntry(JIm, 0, len(modelRe), -1.0)
self._J.addMatrixEntry(JIm, self.data().size(), 0, 1.0)
self._J.addMatrixEntry(JRe, self.data().size(), len(modelRe))
else:
self._J.clean()
k = pg.Vector(self.data()('k'))
self.data().set('k', k*0.0 + 1.0)
dMapResponse = pb.DataMap()
dMapResponse.collect(self.electrodes(), self.solution())
respRe = dMapResponse.data(self.data(), False, False)
respIm = dMapResponse.data(self.data(), False, True)
#CVector resp(toComplex(respRe, respIm));
#RVector am(abs(resp) * dataContainer_->get("k"));
#RVector ph(-phase(resp));
print("respRe", pg.math.median(respRe), min(respRe), max(respRe))
print("respIm", pg.math.median(respIm), min(respIm), max(respIm))
JC = pg.matrix.CMatrix()
self.createJacobian_(modelC, u, JC)
for i in range(JC.rows()):
#JC[i] *= 1.0/(modelC*modelC) * k[i]
JC[i] /= (modelC * modelC) / k[i]
self._J.mat(0).copy(pg.math.real(JC))
self._J.mat(1).copy(pg.math.imag(JC))
#self.createJacobian_(modelRe*0.0+1.0, pg.math.real(u), self._J.mat(1))
#self.createJacobian_(modelRe*0.0+1.0, pg.math.imag(u), self._J.mat(2))
#self.createJacobian_(modelRe*0.0+1.0, pg.math.imag(u), self._J.mat(3))
sumsens0 = pg.Vector(self._J.mat(0).rows())
sumsens1 = pg.Vector(self._J.mat(0).rows())
sumsens2 = pg.Vector(self._J.mat(0).rows())
for i in range(self._J.mat(0).rows()):
#self._J.mat(0)[i] *= 1./modelRe / respRe[i]
#self._J.mat(1)[i] *= 1./modelIm / respRe[i]
#self._J.mat(2)[i] *= 1./modelRe / respIm[i]
#self._J.mat(3)[i] *= 1./modelIm / respIm[i]
#self._J.mat(0)[i] *= 1./(modelRe * modelRe) * k[i]
#self._J.mat(1)[i] *= 1./(modelRe * modelIm) * k[i]
#self._J.mat(2)[i] *= 1./(modelIm * modelRe) * k[i]
#self._J.mat(3)[i] *= 1./(modelIm * modelIm) * k[i]
sumsens0[i] = sum(self._J.mat(0)[i])
sumsens1[i] = sum(self._J.mat(1)[i])
sumsens2[i] = abs(sum(JC[i]))
print(pg.math.median(sumsens0), min(sumsens0), max(sumsens0))
print(pg.math.median(sumsens1), min(sumsens1), max(sumsens1))
print(pg.math.median(sumsens2), min(sumsens2), max(sumsens2))
self.data().set('k', k)
self._J.recalcMatrixSize()
else:
# self.setVerbose(True)
u = self.prepareJacobian_(model)
#J = pg.Matrix()
if self._J.rows() == 0:
print('#' * 100)
M1 = pg.Matrix()
Jid = self._J.addMatrix(M1)
self._J.addMatrixEntry(Jid, 0, 0)
else:
self._J.clean()
self.createJacobian_(model, u, self._J.mat(0))
self._J.recalcMatrixSize()
def createConstraints(self):
"""
"""
print ("createConstrains(self, model):")
Ctmp = pg.matrix.SparseMapMatrix()
self.matrixHeap.append(Ctmp)
self.regionManager().fillConstraints(Ctmp)
CiD = self._C.addMatrix(Ctmp)
self._C.addMatrixEntry(CiD, 0, 0)
self._C.addMatrixEntry(CiD, Ctmp.rows(), Ctmp.cols())
self._C.recalcMatrixSize()
data = pb.DataContainerERT('wa24c.dat')
print(data)
mesh = pg.meshtools.createParaMesh2dGrid(data.sensorPositions())
fop = DCMultiElectrodeModellingC(mesh, data, verbose=True)
print(dir(fop))
print(fop.jacobian())
print(fop.jacobian().rows())
fop.regionManager().region(1).setBackground(True)
fop.createRefinedForwardMesh(refine=True, pRefine=False)
cData = pb.getComplexData(data)
mag = pg.abs(cData)
phi = -pg.phase(cData)
print(pg.norm(mag-data('rhoa')))
print(pg.norm(phi-data('ip')/1000))
inv = pg.Inversion(pg.cat(mag, phi),
fop,
verbose=True, dosave=True)
dataTrans = pg.trans.TransCumulative()
datRe = pg.trans.TransLog()
datIm = pg.trans.Trans()
dataTrans.add(datRe, data.size())
dataTrans.add(datIm, data.size())
modRe = pg.trans.TransLog()
modIm = pg.trans.TransLog()
modelTrans = pg.trans.TransCumulative()
modelTrans.add(modRe, fop.regionManager().parameterCount())
modelTrans.add(modIm, fop.regionManager().parameterCount())
inv.setTransData(dataTrans)
inv.setTransModel(modelTrans)
inv.setAbsoluteError(pg.cat(data("err")*mag, mag*phi*10.01))
inv.setLambda(5)
inv.setMaxIter(5)
#pg.Vector(503, 100.0)))
model = inv.run()
jacRe = fop.jacobian()[0]
jacIm = fop.jacobian()[data.size()]
modelMesh = fop.regionManager().paraDomain()
pg.showLater(1)
fig = pg.plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
ax4 = fig.add_subplot(2, 2, 4)
ax, cbar = pg.show(modelMesh, model[0:len(model)/2], colorBar=1)
ax.set_title("model real")
ax, cbar = pg.show(modelMesh, model[len(model)/2:len(model)], colorBar=1)
ax.set_title("model imag")
pg.showLater(0)
|
from abc import ABCMeta, abstractmethod
import unittest
from ray.rllib.utils.from_config import from_config
from ray.rllib.utils.test_utils import check
from ray.rllib.utils.framework import try_import_tf, try_import_torch
tf = try_import_tf()
tf.enable_eager_execution()
torch, _ = try_import_torch()
class TestFrameWorkAgnosticComponents(unittest.TestCase):
"""
Tests the Component base class to implement framework-agnostic functional
units.
"""
def test_dummy_components(self):
# Switch on eager for testing purposes.
tf.enable_eager_execution()
# Try to create from an abstract class w/o default constructor.
# Expect None.
test = from_config({
"type": AbstractDummyComponent,
"framework": "torch"
})
check(test, None)
# Create a Component via python API (config dict).
component = from_config(
dict(type=DummyComponent, prop_a=1.0, prop_d="non_default"))
check(component.prop_d, "non_default")
# Create a tf Component from json file.
component = from_config("dummy_config.json")
check(component.prop_c, "default")
check(component.prop_d, 4) # default
check(component.add(3.3).numpy(), 5.3) # prop_b == 2.0
# Create a torch Component from yaml file.
component = from_config("dummy_config.yml")
check(component.prop_a, "something else")
check(component.prop_d, 3)
check(component.add(1.2), torch.Tensor([2.2])) # prop_b == 1.0
# Create tf Component from json-string (e.g. on command line).
component = from_config(
'{"type": "ray.rllib.utils.tests.'
'test_framework_agnostic_components.DummyComponent", '
'"prop_a": "A", "prop_b": -1.0, "prop_c": "non-default"}')
check(component.prop_a, "A")
check(component.prop_d, 4) # default
check(component.add(-1.1).numpy(), -2.1) # prop_b == -1.0
# Create torch Component from yaml-string.
component = from_config(
"type: ray.rllib.utils.tests."
"test_framework_agnostic_components.DummyComponent\n"
"prop_a: B\nprop_b: -1.5\nprop_c: non-default\nframework: torch")
check(component.prop_a, "B")
check(component.prop_d, 4) # default
check(component.add(-5.1), torch.Tensor([-6.6])) # prop_b == -1.5
class DummyComponent:
"""
A simple DummyComponent that can be used for testing framework-agnostic
logic. Implements a simple `add()` method for adding a value to
`self.prop_b`.
"""
def __init__(self,
prop_a,
prop_b=0.5,
prop_c=None,
framework="tf",
**kwargs):
self.framework = framework
self.prop_a = prop_a
self.prop_b = prop_b
self.prop_c = prop_c or "default"
self.prop_d = kwargs.pop("prop_d", 4)
self.kwargs = kwargs
def add(self, value):
if self.framework == "tf":
return self._add_tf(value)
return self.prop_b + value
def _add_tf(self, value):
return tf.add(self.prop_b, value)
class AbstractDummyComponent(DummyComponent, metaclass=ABCMeta):
"""
Used for testing `from_config()`.
"""
@abstractmethod
def some_abstract_method(self):
raise NotImplementedError
|
import khmer
from khmer import LabelHash
from screed.fasta import fasta_iter
import screed
import khmer_tst_utils as utils
from nose.plugins.attrib import attr
def teardown():
utils.cleanup()
def test_n_labels():
lh = LabelHash(20, 1e7, 4)
filename = utils.get_test_data('test-labels.fa')
lh.consume_fasta_and_tag_with_labels(filename)
print lh.n_labels()
assert lh.n_labels() == 4
def test_get_label_dict():
lb = LabelHash(20, 1e7, 4)
filename = utils.get_test_data('test-labels.fa')
lb.consume_fasta_and_tag_with_labels(filename)
labels = lb.get_label_dict()
expected = [0L, 1L, 2L, 3L]
for e_label in expected:
assert e_label in labels
for a_label in labels:
assert a_label in expected
def test_get_tag_labels():
lb = LabelHash(20, 1e7, 4)
filename = utils.get_test_data('single-read.fq')
lb.consume_fasta_and_tag_with_labels(filename)
tag = 173473779682L
labels = lb.get_tag_labels(tag)
assert len(labels) == 1
assert labels.pop() == 0L
def test_consume_fasta_and_tag_with_labels():
lb = LabelHash(20, 1e7, 4)
read_1 = 'ACGTAACCGGTTAAACCCGGGTTTAAAACCCCGGGGTTTT'
filename = utils.get_test_data('test-transcript.fa')
total_reads, n_consumed = lb.consume_fasta_and_tag_with_labels(filename)
print "doing get"
assert lb.get(read_1[:20])
assert total_reads == 3
print "doing n_labels"
print lb.n_labels()
print "doing label dict"
print lb.get_label_dict()
print "get tagset"
for tag in lb.get_tagset():
print "forward hash"
print tag, khmer.forward_hash(tag, 20)
for record in screed.open(filename):
print "Sweeping tags"
print lb.sweep_tag_neighborhood(record.sequence, 40)
print "Sweeping labels..."
print lb.sweep_label_neighborhood(record.sequence, 40)
assert lb.n_labels() == 3
def test_consume_partitioned_fasta_and_tag_with_labels():
lb = LabelHash(20, 1e7, 4)
filename = utils.get_test_data('real-partition-small.fa')
total_reads, n_consumed = lb.consume_partitioned_fasta_and_tag_with_labels(
filename)
labels = set()
for record in screed.open(filename):
seq = record.sequence
labels.update(lb.sweep_label_neighborhood(seq, 0, False, False))
# print lb.n_labels()
# print labels
assert len(labels) == 1
assert labels.pop() == 2L
assert lb.n_labels() == 1
def test_consume_sequence_and_tag_with_labels():
lb = LabelHash(20, 1e6, 4)
label = 0L
sequence = 'ATGCATCGATCGATCGATCGATCGATCGATCGATCGATCG'
n_consumed = lb.consume_sequence_and_tag_with_labels(sequence, label)
labels = set()
labels.update(lb.sweep_label_neighborhood(sequence))
assert label in labels
assert len(labels) == 1
def test_sweep_tag_neighborhood():
lb = LabelHash(20, 1e7, 4)
filename = utils.get_test_data('single-read.fq')
lb.consume_fasta_and_tag(filename)
tags = lb.sweep_tag_neighborhood('CAGGCGCCCACCACCGTGCCCTCCAACCTGATGGT')
assert len(tags) == 1
assert tags.pop() == 173473779682L
def test_sweep_label_neighborhood():
lb = LabelHash(20, 1e7, 4)
filename = utils.get_test_data('single-read.fq')
lb.consume_fasta_and_tag_with_labels(filename)
labels = lb.sweep_label_neighborhood('CAGGCGCCCACCACCGTGCCCTCCAACCTGATGGT')
assert len(labels) == 1
assert labels.pop() == 0L
'''
* The test data set as four reads: A, B, C, and D
* Overlaps are A <-> B <-> C, with D on its own
* Thus, traversing from A should find labels from A and B,
traversing from B should find labels from A, B, and C,
and traversing from C should find labels from B and C
'''
def test_label_tag_correctness():
lb = LabelHash(20, 1e7, 4)
filename = utils.get_test_data('test-labels.fa')
lb.consume_fasta_and_tag_with_labels(filename)
# read A
labels = lb.sweep_label_neighborhood(
'ATCGTGTAAGCTATCGTAATCGTAAGCTCTGCCTAGAGCTAGGCTAGGCTCTGCCTAGAG'
'CTAGGCTAGGTGTGCTCTGCCTAGAGCTAGGCTAGGTGT')
print lb.sweep_tag_neighborhood(
'TTCGTGTAAGCTATCGTAATCGTAAGCTCTGCCTAGAGCTAGGCTAGGCTCTGCCTAGAG'
'CTAGGCTAGGTGTGCTCTGCTAGAGCTAGGCTAGGTGT')
print labels
print len('ATCGTGTAAGCTATCGTAATCGTAAGCTCTGCCTAGAGCTAGGCTAG') - 19
assert len(labels) == 2
assert 0L in labels
assert 1L in labels
# read B
labels = lb.sweep_label_neighborhood(
'GCGTAATCGTAAGCTCTGCCTAGAGCTAGGCTAGCTCTGCCTAGAGCTAGGCTAGGTGTTGGGGATAG'
'ATAGATAGATGACCTAGAGCTAGGCTAGGTGTTGGGGATAGATAGATAGATGA')
print labels
assert len(labels) == 3
assert 0L in labels
assert 1L in labels
assert 2L in labels
# read C
labels = lb.sweep_label_neighborhood(
'TGGGATAGATAGATAGATGACCTAGAGCTAGGCTAGGTGTTGGGGATAGATAGATAGATGACCTAGAG'
'CTAGGCTAGGTGTTGGGGATAGATAGATAGATGAGTTGGGGATAGATAGATAGATGAGTGTAGATCCA'
'ACAACACATACA')
print labels
assert len(labels) == 2
assert 1L in labels
assert 2L in labels
# read D
labels = lb.sweep_label_neighborhood(
'TATATATATAGCTAGCTAGCTAACTAGCTAGCATCGATCGATCGATC')
print labels
assert len(labels) == 1
assert 3L in labels
def test__get_set_tag_density():
ht = khmer.LabelHash(32, 1, 1)
orig = ht._get_tag_density()
assert orig != 2
ht._set_tag_density(2)
assert ht._get_tag_density() == 2
def test_n_occupied_1():
filename = utils.get_test_data('random-20-a.fa')
K = 20 # size of kmer
HT_SIZE = 100000 # size of hashtable
N_HT = 1 # number of hashtables
# test modified c++ n_occupied code
ht1 = khmer.LabelHash(K, HT_SIZE, N_HT)
for n, record in enumerate(fasta_iter(open(filename))):
ht1.consume(record['sequence'])
# this number calculated independently
assert ht1.n_occupied() == 3877
def test_bloom_python_1():
# test python code to count unique kmers using bloom filter
filename = utils.get_test_data('random-20-a.fa')
K = 20 # size of kmer
HT_SIZE = 100000 # size of hashtable
N_HT = 3 # number of hashtables
ht2 = khmer.LabelHash(K, HT_SIZE, N_HT)
n_unique = 0
for n, record in enumerate(fasta_iter(open(filename))):
sequence = record['sequence']
seq_len = len(sequence)
for n in range(0, seq_len + 1 - K):
kmer = sequence[n:n + K]
if (not ht2.get(kmer)):
n_unique += 1
ht2.count(kmer)
assert n_unique == 3960
assert ht2.n_occupied() == 3882
assert ht2.n_unique_kmers() == 3960 # this number equals to n_unique
def test_bloom_c_1():
# test c++ code to count unique kmers using bloom filter
filename = utils.get_test_data('random-20-a.fa')
K = 20 # size of kmer
HT_SIZE = 100000 # size of hashtable
N_HT = 3 # number of hashtables
ht3 = khmer.LabelHash(K, HT_SIZE, N_HT)
for n, record in enumerate(fasta_iter(open(filename))):
ht3.consume(record['sequence'])
assert ht3.n_occupied() == 3882
assert ht3.n_unique_kmers() == 3960
def test_n_occupied_2(): # simple one
K = 4
HT_SIZE = 10 # use 11
N_HT = 1
ht1 = khmer.LabelHash(K, HT_SIZE, N_HT)
ht1.count('AAAA') # 00 00 00 00 = 0
assert ht1.n_occupied() == 1
ht1.count('ACTG') # 00 10 01 11 =
assert ht1.n_occupied() == 2
ht1.count('AACG') # 00 00 10 11 = 11 # collision 1
assert ht1.n_occupied() == 2
ht1.count('AGAC') # 00 11 00 10 # collision 2
assert ht1.n_occupied() == 2
def test_bloom_c_2(): # simple one
K = 4
HT_SIZE = 10 # use 11
N_HT1 = 1 # hashtable size = 11
N_HT2 = 2 # hashtable size = 11,13
# use only 1 hashtable, no bloom filter
ht1 = khmer.LabelHash(K, HT_SIZE, N_HT1)
ht1.count('AAAA') # 00 00 00 00 = 0
ht1.count('ACTG') # 00 10 01 11 =
assert ht1.n_unique_kmers() == 2
ht1.count('AACG') # 00 00 10 11 = 11 # collision with 1st kmer
assert ht1.n_unique_kmers() == 2
ht1.count('AGAC') # 00 11 00 10 # collision with 2nd kmer
assert ht1.n_unique_kmers() == 2
# use two hashtables with 11,13
ht2 = khmer.LabelHash(K, HT_SIZE, N_HT2)
ht2.count('AAAA') # 00 00 00 00 = 0
ht2.count('ACTG') # 00 10 01 11 = 2*16 +4 +3 = 39
assert ht2.n_unique_kmers() == 2
ht2.count('AACG') # 00 00 10 11 = 11 # collision with only 1st kmer
assert ht2.n_unique_kmers() == 3
ht2.count('AGAC') # 00 11 00 10 3*16 +2 = 50
# collision with both 2nd and 3rd kmers
assert ht2.n_unique_kmers() == 3
@attr('highmem')
def test_filter_if_present():
ht = khmer.LabelHash(32, 1e6, 2)
maskfile = utils.get_test_data('filter-test-A.fa')
inputfile = utils.get_test_data('filter-test-B.fa')
outfile = utils.get_temp_filename('filter')
ht.consume_fasta(maskfile)
ht.filter_if_present(inputfile, outfile)
records = list(fasta_iter(open(outfile)))
assert len(records) == 1
assert records[0]['name'] == '3'
@attr('highmem')
def test_combine_pe():
inpfile = utils.get_test_data('combine_parts_1.fa')
ht = khmer.LabelHash(32, 1, 1)
ht.consume_partitioned_fasta(inpfile)
assert ht.count_partitions() == (2, 0)
s1 = "CATGCAGAAGTTCCGCAACCATACCGTTCAGT"
pid1 = ht.get_partition_id(s1)
s2 = "CAAATGTACATGCACTTAAAATCATCCAGCCG"
pid2 = ht.get_partition_id(s2)
assert pid1 == 2
assert pid2 == 80293
ht.join_partitions(pid1, pid2)
pid1 = ht.get_partition_id(s1)
pid2 = ht.get_partition_id(s2)
assert pid1 == pid2
assert ht.count_partitions() == (1, 0)
@attr('highmem')
def test_load_partitioned():
inpfile = utils.get_test_data('combine_parts_1.fa')
ht = khmer.LabelHash(32, 1, 1)
ht.consume_partitioned_fasta(inpfile)
assert ht.count_partitions() == (2, 0)
s1 = "CATGCAGAAGTTCCGCAACCATACCGTTCAGT"
assert ht.get(s1)
s2 = "CAAATGTACATGCACTTAAAATCATCCAGCCG"
assert ht.get(s2)
s3 = "CATGCAGAAGTTCCGCAACCATACCGTTCAGTTCCTGGTGGCTA"[-32:]
assert ht.get(s3)
@attr('highmem')
def test_count_within_radius_simple():
inpfile = utils.get_test_data('all-A.fa')
ht = khmer.LabelHash(4, 1e6, 2)
print ht.consume_fasta(inpfile)
n = ht.count_kmers_within_radius('AAAA', 1)
assert n == 1
n = ht.count_kmers_within_radius('AAAA', 10)
assert n == 1
@attr('highmem')
def test_count_within_radius_big():
inpfile = utils.get_test_data('random-20-a.fa')
ht = khmer.LabelHash(20, 1e6, 4)
ht.consume_fasta(inpfile)
n = ht.count_kmers_within_radius('CGCAGGCTGGATTCTAGAGG', int(1e6))
assert n == 3960
ht = khmer.LabelHash(21, 1e6, 4)
ht.consume_fasta(inpfile)
n = ht.count_kmers_within_radius('CGCAGGCTGGATTCTAGAGGC', int(1e6))
assert n == 39
@attr('highmem')
def test_count_kmer_degree():
inpfile = utils.get_test_data('all-A.fa')
ht = khmer.LabelHash(4, 1e6, 2)
ht.consume_fasta(inpfile)
assert ht.kmer_degree('AAAA') == 2
assert ht.kmer_degree('AAAT') == 1
assert ht.kmer_degree('AATA') == 0
assert ht.kmer_degree('TAAA') == 1
@attr('highmem')
def test_find_radius_for_volume():
inpfile = utils.get_test_data('all-A.fa')
ht = khmer.LabelHash(4, 1e6, 2)
ht.consume_fasta(inpfile)
assert ht.find_radius_for_volume('AAAA', 0, 100) == 0
assert ht.find_radius_for_volume('AAAA', 1, 100) == 0
assert ht.find_radius_for_volume('AAAA', 2, 100) == 100
def test_circumference():
ht = khmer.LabelHash(4, 1e6, 2)
ht.count('ATGC')
ht.count('GATG')
ht.count('ATGG')
x = ht.count_kmers_on_radius('GATG', 1, 200)
assert x == 2
ht.count('ATGA')
x = ht.count_kmers_on_radius('GATG', 1, 200)
assert x == 3, x
ht.count('TGAT')
x = ht.count_kmers_on_radius('GATG', 1, 200)
assert x == 4, x
def test_save_load_tagset():
ht = khmer.LabelHash(32, 1, 1)
outfile = utils.get_temp_filename('tagset')
ht.add_tag('A' * 32)
ht.save_tagset(outfile)
ht.add_tag('G' * 32)
ht.load_tagset(outfile) # implicitly => clear_tags=True
ht.save_tagset(outfile)
# if tags have been cleared, then the new tagfile will be larger (34 bytes)
# else smaller (26 bytes).
fp = open(outfile, 'rb')
data = fp.read()
fp.close()
assert len(data) == 26, len(data)
def test_save_load_tagset_noclear():
ht = khmer.LabelHash(32, 1, 1)
outfile = utils.get_temp_filename('tagset')
ht.add_tag('A' * 32)
ht.save_tagset(outfile)
ht.add_tag('G' * 32)
ht.load_tagset(outfile, False) # set clear_tags => False; zero tags
ht.save_tagset(outfile)
# if tags have been cleared, then the new tagfile will be large (34 bytes);
# else small (26 bytes).
fp = open(outfile, 'rb')
data = fp.read()
fp.close()
assert len(data) == 34, len(data)
@attr('highmem')
def test_stop_traverse():
filename = utils.get_test_data('random-20-a.fa')
K = 20 # size of kmer
HT_SIZE = 100000 # size of hashtable
N_HT = 3 # number of hashtables
ht = khmer.LabelHash(K, HT_SIZE, N_HT)
# without tagging/joining across consume, this breaks into two partition;
# with, it is one partition.
ht.add_stop_tag('TTGCATACGTTGAGCCAGCG')
ht.consume_fasta_and_tag(filename) # DO NOT join reads across stoptags
subset = ht.do_subset_partition(0, 0, True)
ht.merge_subset(subset)
n, _ = ht.count_partitions()
assert n == 2, n
@attr('highmem')
def test_tag_across_stoptraverse():
filename = utils.get_test_data('random-20-a.fa')
K = 20 # size of kmer
HT_SIZE = 100000 # size of hashtable
N_HT = 3 # number of hashtables
ht = khmer.LabelHash(K, HT_SIZE, N_HT)
# without tagging/joining across consume, this breaks into two partition;
# with, it is one partition.
ht.add_stop_tag('CCGAATATATAACAGCGACG')
ht.consume_fasta_and_tag_with_stoptags(filename) # DO join reads across
subset = ht.do_subset_partition(0, 0)
n, _ = ht.count_partitions()
assert n == 99 # reads only connected by traversal...
n, _ = ht.subset_count_partitions(subset)
assert n == 2 # but need main to cross stoptags.
ht.merge_subset(subset)
n, _ = ht.count_partitions() # ta-da!
assert n == 1, n
@attr('highmem')
def test_notag_across_stoptraverse():
filename = utils.get_test_data('random-20-a.fa')
K = 20 # size of kmer
HT_SIZE = 100000 # size of hashtable
N_HT = 3 # number of hashtables
ht = khmer.LabelHash(K, HT_SIZE, N_HT)
# connecting k-mer at the beginning/end of a read: breaks up into two.
ht.add_stop_tag('TTGCATACGTTGAGCCAGCG')
ht.consume_fasta_and_tag_with_stoptags(filename)
subset = ht.do_subset_partition(0, 0)
ht.merge_subset(subset)
n, _ = ht.count_partitions()
assert n == 2, n
def test_find_stoptags():
ht = khmer.LabelHash(5, 1, 1)
ht.add_stop_tag("AAAAA")
assert ht.identify_stoptags_by_position("AAAAA") == [0]
assert ht.identify_stoptags_by_position("AAAAAA") == [0, 1]
assert ht.identify_stoptags_by_position("TTTTT") == [0]
assert ht.identify_stoptags_by_position("TTTTTT") == [0, 1]
def test_find_stoptags2():
ht = khmer.LabelHash(4, 1, 1)
ht.add_stop_tag("ATGC")
x = ht.identify_stoptags_by_position("ATGCATGCGCAT")
assert x == [0, 2, 4, 8], x
def test_get_ksize():
kh = khmer.LabelHash(22, 1, 1)
assert kh.ksize() == 22
def test_get_hashsizes():
kh = khmer.LabelHash(22, 100, 4)
assert kh.hashsizes() == [101, 103, 107, 109], kh.hashsizes()
def test_extract_unique_paths_0():
kh = khmer.LabelHash(10, 1e5, 4)
x = kh.extract_unique_paths('ATGGAGAGACACAGATAGACAGGAGTGGCGATG', 10, 1)
assert x == ['ATGGAGAGACACAGATAGACAGGAGTGGCGATG']
kh.consume('ATGGAGAGACACAGATAGACAGGAGTGGCGATG')
x = kh.extract_unique_paths('ATGGAGAGACACAGATAGACAGGAGTGGCGATG', 10, 1)
assert not x
def test_extract_unique_paths_1():
kh = khmer.LabelHash(10, 1e5, 4)
kh.consume('AGTGGCGATG')
x = kh.extract_unique_paths('ATGGAGAGACACAGATAGACAGGAGTGGCGATG', 10, 1)
print x
assert x == ['ATGGAGAGACACAGATAGACAGGAGTGGCGAT'] # all but the last k-mer
def test_extract_unique_paths_2():
kh = khmer.LabelHash(10, 1e5, 4)
kh.consume('ATGGAGAGAC')
x = kh.extract_unique_paths('ATGGAGAGACACAGATAGACAGGAGTGGCGATG', 10, 1)
print x
assert x == ['TGGAGAGACACAGATAGACAGGAGTGGCGATG'] # all but the 1st k-mer
def test_extract_unique_paths_3():
kh = khmer.LabelHash(10, 1e5, 4)
kh.consume('ATGGAGAGAC')
kh.consume('AGTGGCGATG')
x = kh.extract_unique_paths('ATGGAGAGACACAGATAGACAGGAGTGGCGATG', 10, 1)
print x
# all but the 1st/last k-mer
assert x == ['TGGAGAGACACAGATAGACAGGAGTGGCGAT']
def test_extract_unique_paths_4():
kh = khmer.LabelHash(10, 1e5, 4)
kh.consume('ATGGAGAGAC')
kh.consume('AGTGGCGATG')
kh.consume('ATAGACAGGA')
x = kh.extract_unique_paths('ATGGAGAGACACAGATAGACAGGAGTGGCGATG', 10, 1)
print x
assert x == ['TGGAGAGACACAGATAGACAGG', 'TAGACAGGAGTGGCGAT']
@attr('highmem')
def test_find_unpart():
filename = utils.get_test_data('random-20-a.odd.fa')
filename2 = utils.get_test_data('random-20-a.even.fa')
K = 20 # size of kmer
HT_SIZE = 100000 # size of hashtable
N_HT = 3 # number of hashtables
ht = khmer.LabelHash(K, HT_SIZE, N_HT)
ht.consume_fasta_and_tag(filename)
subset = ht.do_subset_partition(0, 0)
ht.merge_subset(subset)
n, _ = ht.count_partitions()
assert n == 49
ht.find_unpart(filename2, True, False)
n, _ = ht.count_partitions()
assert n == 1, n # all sequences connect
@attr('highmem')
def test_find_unpart_notraverse():
filename = utils.get_test_data('random-20-a.odd.fa')
filename2 = utils.get_test_data('random-20-a.even.fa')
K = 20 # size of kmer
HT_SIZE = 100000 # size of hashtable
N_HT = 3 # number of hashtables
ht = khmer.LabelHash(K, HT_SIZE, N_HT)
ht.consume_fasta_and_tag(filename)
subset = ht.do_subset_partition(0, 0)
ht.merge_subset(subset)
n, _ = ht.count_partitions()
assert n == 49
ht.find_unpart(filename2, False, False) # <-- don't traverse
n, _ = ht.count_partitions()
assert n == 99, n # all sequences disconnected
@attr('highmem')
def test_find_unpart_fail():
filename = utils.get_test_data('random-20-a.odd.fa')
filename2 = utils.get_test_data('random-20-a.odd.fa') # <- switch to odd
K = 20 # size of kmer
HT_SIZE = 100000 # size of hashtable
N_HT = 3 # number of hashtables
ht = khmer.LabelHash(K, HT_SIZE, N_HT)
ht.consume_fasta_and_tag(filename)
subset = ht.do_subset_partition(0, 0)
ht.merge_subset(subset)
n, _ = ht.count_partitions()
assert n == 49
ht.find_unpart(filename2, True, False)
n, _ = ht.count_partitions()
assert n == 49, n # only 49 sequences worth of tags
def test_simple_median():
hi = khmer.LabelHash(6, 1e6, 2)
(median, average, stddev) = hi.get_median_count("AAAAAA")
print median, average, stddev
assert median == 0
assert average == 0.0
assert stddev == 0.0
hi.consume("AAAAAA")
(median, average, stddev) = hi.get_median_count("AAAAAA")
print median, average, stddev
assert median == 1
assert average == 1.0
assert stddev == 0.0
def test_bad_primes():
try:
hi = khmer._LabelHash.__new__(khmer.LabelHash, 6, ["a", "b", "c"])
assert 0, "Non number prime list should fail"
except TypeError, e:
print str(e)
|
from google import pubsub_v1
async def sample_pull():
# Create a client
client = pubsub_v1.SubscriberAsyncClient()
# Initialize request argument(s)
request = pubsub_v1.PullRequest(
subscription="subscription_value",
max_messages=1277,
)
# Make the request
response = await client.pull(request=request)
# Handle the response
print(response)
|
from ncclient import manager
import ncclient
import xml.etree.ElementTree as ET
host = "192.168.1.1"
username="root"
password="root"
with manager.connect_ssh(host=host, port=830, username=username, password=password, hostkey_verify=False ) as m:
print m.get_config(source='startup').data_xml
|
"""
Server-side Keystone notification payload processing logic.
"""
from barbican.common import utils
from barbican import i18n as u
from barbican.model import repositories as rep
from barbican.tasks import resources
LOG = utils.getLogger(__name__)
class KeystoneEventConsumer(resources.BaseTask):
"""Event consumer listening for notifications sent by Keystone deployment.
Currently this processes only Keystone project delete event.
"""
def get_name(self):
return u._('Project cleanup via Keystone notifications')
def __init__(self, project_repo=None, order_repo=None,
secret_repo=None, project_secret_repo=None,
datum_repo=None, kek_repo=None, secret_meta_repo=None,
container_repo=None, repositories=None,
db_start=rep.start, db_commit=rep.commit,
db_rollback=rep.rollback, db_clear=rep.clear):
LOG.debug('Creating KeystoneEventConsumer task processor')
self.db_start = db_start
self.db_commit = db_commit
self.db_rollback = db_rollback
self.db_clear = db_clear
self.repos = repositories
if not repositories:
self.repos = rep.Repositories(
project_repo=project_repo,
order_repo=order_repo,
secret_repo=secret_repo,
project_secret_repo=project_secret_repo,
datum_repo=datum_repo,
kek_repo=kek_repo,
secret_meta_repo=secret_meta_repo,
container_repo=container_repo)
def process(self, *args, **kwargs):
try:
self.db_start()
super(KeystoneEventConsumer, self).process(*args, **kwargs)
self.db_commit()
except Exception as e:
"""Exceptions that reach here needs to revert the entire
transaction.
No need to log error message as its already done earlier.
"""
self.db_rollback()
raise e
finally:
self.db_clear()
def retrieve_entity(self, project_id, resource_type=None,
operation_type=None):
project_repo = self.repos.project_repo
return project_repo.find_by_external_project_id(
external_project_id=project_id,
suppress_exception=True)
def handle_processing(self, barbican_project, *args, **kwargs):
self.handle_cleanup(barbican_project, *args, **kwargs)
def handle_error(self, project, status, message, exception,
project_id=None, resource_type=None, operation_type=None):
LOG.error(
u._LE(
'Error processing Keystone event, project_id=%(project_id)s, '
'event resource=%(resource)s, event operation=%(operation)s, '
'status=%(status)s, error message=%(message)s'
),
{
'project_id': project.project_id,
'resource': resource_type,
'operation': operation_type,
'status': status,
'message': message
}
)
def handle_success(self, project, project_id=None, resource_type=None,
operation_type=None):
LOG.info(
u._LI(
'Successfully handled Keystone event, '
'project_id=%(project_id)s, event resource=%(resource)s, '
'event operation=%(operation)s'
),
{
'project_id': project_id,
'resource': resource_type,
'operation': operation_type
}
)
def handle_cleanup(self, project, project_id=None, resource_type=None,
operation_type=None):
"""Cleans up Barbican resources needed for Keystone project delete.
:param project: Barbican project entity which is retrieved by project
id available in Keystone notification.
:param project_id: project identifier as present in Keystone
notification.
:param resource_type: type of resource updated as part of Keystone
notification e.g. Keystone project, domain, user etc.
:param operation_type: type of operation (created, updated, deleted
etc.) performed on Keystone resource.
"""
if project is None:
LOG.info(u._LI('No action is needed as there are no Barbican '
'resources present for Keystone '
'project_id=%s'), project_id)
return
# barbican entities use projects table 'id' field as foreign key.
# Delete apis are using that id to lookup related entities and not
# keystone project id which requires additional project table join.
project_id = project.id
rep.delete_all_project_resources(project_id, self.repos)
# reached here means there is no error so log the successful
# cleanup log entry.
LOG.info(u._LI('Successfully completed Barbican resources cleanup for '
'Keystone project_id=%s'), project_id)
|
import re
import nltk
regex_url = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
# domain...
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
stopwords = nltk.corpus.stopwords.words('english') + [
'.',
'..',
'...',
',',
'--',
'\'s',
'?',
')',
'(',
':',
'\'',
'\'re',
'"',
'-',
'}',
'{',
'<',
'>',
'=',
'these',
'there',
'they',
'those',
'whose',
'ours',
'your',
'yours',
'others',
'anothers'
]
ignorewords = {'the', 'of', 'to', 'and', 'a', 'in', 'is', 'it', 'for', 'by',
'are', 'i', 'you', 'he', 'she', 'we', 'do', 'does', 'did',
'say', 'said', 'says', 'tell', 'told', 'what', 'where',
'when', 'how', 'who', 'whose', 'why', 'would'}
def is_url(word):
return regex_url.match(word)
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
class Words:
def __init__(self):
pass
def count_words(self, text):
w_aux = nltk.wordpunct_tokenize(text)
scored_words = {}
for word in w_aux:
word = word.lower()
if word not in stopwords and \
word not in ignorewords and \
len(word) > 1 and \
not is_url(word) and \
not is_number(word):
try:
scored_words[word] += 1
except:
scored_words[word] = 1
return scored_words
|
"""
Created on Thu Nov 23 11:23:03 2017
@author: tih
"""
import numpy as np
import os
import scipy.interpolate
import gdal
from openpyxl import load_workbook
import osr
from datetime import datetime, timedelta
import pandas as pd
import shutil
import glob
from netCDF4 import Dataset
import warnings
import SEBAL
def main():
VegetationExcel =r"$HOME\SEBAL\Excel_PreSEBAL_v1_0.xlsx" # This excel defines the p and c factor and vegetation height.
# Open Excel workbook used for Vegetation c and p factor conversions
wb_veg = load_workbook(VegetationExcel, data_only=True)
ws_veg = wb_veg['General_Input']
# Input for preSEBAL.py
start_date = "%s" %str(ws_veg['B2'].value)
end_date = "%s" %str(ws_veg['B3'].value)
inputExcel= r"%s" %str(ws_veg['B4'].value) # The excel with all the SEBAL input data
LU_data_FileName = r"%s" %str(ws_veg['B5'].value) # Path to Land Use map
output_folder = r"%s" %str(ws_veg['B7'].value)
# optional paramater
DSSF_Folder= r"%s" %str(ws_veg['B6'].value)
######################## Load Excels ##########################################
# Open Excel workbook for SEBAL inputs
wb = load_workbook(inputExcel)
# Get length of EXCEL sheet
ws = wb['General_Input']
ws2 = wb['VIIRS_PROBAV_Input']
endExcel=int(ws.max_row)
# Create Dict
SEBAL_RUNS = dict()
for number in range(2,endExcel+1):
input_folder_SEBAL = str(ws['B%d' % number].value)
output_folder_SEBAL = str(ws['C%d' % number].value)
Image_Type = int(ws['D%d' % number].value)
PROBA_V_name = str(ws2['D%d' % number].value)
VIIRS_name = str(ws2['B%d' % number].value)
SEBAL_RUNS[number] = {'input_folder': input_folder_SEBAL, 'output_folder': output_folder_SEBAL, 'image_type': Image_Type,'PROBA_V_name': PROBA_V_name,'VIIRS_name': VIIRS_name}
Kind_Of_Runs_Dict = {}
for k, v in SEBAL_RUNS.iteritems():
Kind_Of_Runs_Dict.setdefault(v['image_type'], []).append(k)
######################## Create output folders ##########################################
output_folder_PreSEBAL_SEBAL = os.path.join(output_folder,'PreSEBAL_SEBAL_out')
input_folder_HANTS = os.path.join(output_folder,'HANTS_in')
output_folder_PreSEBAL = os.path.join(output_folder,'PreSEBAL_out')
temp_folder_PreSEBAL = os.path.join(output_folder,'PreSEBAL_temp')
temp_folder_PreSEBAL_LST = os.path.join(temp_folder_PreSEBAL,'LST')
NDVI_outfolder = os.path.join(output_folder_PreSEBAL_SEBAL,'NDVI')
Albedo_outfolder = os.path.join(output_folder_PreSEBAL_SEBAL,'Albedo')
WaterMask_outfolder = os.path.join(output_folder_PreSEBAL_SEBAL,'WaterMask')
LAI_outfolder = os.path.join(output_folder_PreSEBAL_SEBAL,'LAI')
TRANS_outfolder = os.path.join(output_folder_PreSEBAL,'Transmissivity')
Surface_Temperature_outfolder = os.path.join(output_folder_PreSEBAL_SEBAL,'Surface_Temperature')
output_folder_HANTS_end_sharp = os.path.join(output_folder_PreSEBAL, 'LST_Sharpened')
output_folder_HANTS_end_LAI = os.path.join(output_folder_PreSEBAL, 'LAI')
output_folder_HANTS_end_Veg = os.path.join(output_folder_PreSEBAL, 'Vegetation_Height')
output_folder_p_factor = os.path.join(output_folder_PreSEBAL, 'p_factor')
output_folder_LUE = os.path.join(output_folder_PreSEBAL, 'LUE')
if not os.path.exists(output_folder_PreSEBAL_SEBAL):
os.makedirs(output_folder_PreSEBAL_SEBAL)
if not os.path.exists(output_folder_PreSEBAL):
os.mkdir(output_folder_PreSEBAL)
if not os.path.exists(temp_folder_PreSEBAL):
os.mkdir(temp_folder_PreSEBAL)
if not os.path.exists(NDVI_outfolder):
os.makedirs(NDVI_outfolder)
if not os.path.exists(Albedo_outfolder):
os.makedirs(Albedo_outfolder)
if not os.path.exists(WaterMask_outfolder):
os.makedirs(WaterMask_outfolder)
if not os.path.exists(LAI_outfolder):
os.makedirs(LAI_outfolder)
if not os.path.exists(temp_folder_PreSEBAL_LST):
os.makedirs(temp_folder_PreSEBAL_LST)
if not os.path.exists(Surface_Temperature_outfolder):
os.makedirs(Surface_Temperature_outfolder)
if not os.path.exists(TRANS_outfolder):
os.makedirs(TRANS_outfolder)
if not os.path.exists(output_folder_HANTS_end_sharp):
os.mkdir(output_folder_HANTS_end_sharp)
if not os.path.exists(output_folder_HANTS_end_LAI):
os.mkdir(output_folder_HANTS_end_LAI)
if not os.path.exists(output_folder_HANTS_end_Veg):
os.mkdir(output_folder_HANTS_end_Veg)
if not os.path.exists(output_folder_p_factor):
os.mkdir(output_folder_p_factor)
if not os.path.exists(output_folder_LUE):
os.mkdir(output_folder_LUE)
# Do not show warnings
warnings.filterwarnings('ignore')
############################## Define General info ############################
for number in Kind_Of_Runs_Dict[2]: # Number defines the column of the inputExcel
print(number)
if not (SEBAL_RUNS[number]['PROBA_V_name'] == 'None' and SEBAL_RUNS[number]['VIIRS_name'] == 'None'):
Rp = 0.91 # Path radiance in the 10.4-12.5 µm band (W/m2/sr/µm)
tau_sky = 0.866 # Narrow band transmissivity of air, range: [10.4-12.5 µm]
surf_temp_offset = 3 # Surface temperature offset for water
######################## Open General info from SEBAL Excel ###################
# Open the General_Input sheet
ws = wb['General_Input']
# Extract the input and output folder, and Image type from the excel file
input_folder = str(ws['B%d' % number].value)
Image_Type = int(2) # Type of Image (1=Landsat & 2 = VIIRS & GLOBA-V)
# Extract the Path to the DEM map from the excel file
DEM_fileName = '%s' %str(ws['E%d' % number].value) #'DEM_HydroShed_m'
# Open DEM and create Latitude and longitude files
lat,lon,lat_fileName,lon_fileName=SEBAL.DEM_lat_lon(DEM_fileName, temp_folder_PreSEBAL)
######################## Extract general data for Landsat ##########################################
if Image_Type == 1:
# Open the Landsat_Input sheet
ws = wb['Landsat_Input']
# Extract Landsat name, number and amount of thermal bands from excel file
Name_Landsat_Image = str(ws['B%d' % number].value) # From glovis.usgs.gov
Landsat_nr = int(ws['C%d' % number].value) # Type of Landsat (LS) image used (LS5, LS7, or LS8)
Bands_thermal = int(ws['D%d' %number].value) # Number of LS bands to use to retrieve land surface
# Pixel size of the model
pixel_spacing=int(30)
# the path to the MTL file of landsat
Landsat_meta_fileName = os.path.join(input_folder, '%s_MTL.txt' % Name_Landsat_Image)
# read out the general info out of the MTL file in Greenwich Time
year, DOY, hour, minutes, UTM_Zone, Sun_elevation = SEBAL.info_general_metadata(Landsat_meta_fileName) # call definition info_general_metadata
date=datetime.strptime('%s %s'%(year,DOY), '%Y %j')
month = date.month
day = date.day
# define the kind of sensor and resolution of the sensor
sensor1 = 'L%d' % Landsat_nr
sensor2 = 'L%d' % Landsat_nr
sensor3 = 'L%d' % Landsat_nr
res1 = '30m'
res2 = '%sm' %int(pixel_spacing)
res3 = '30m'
# Set the start parameter for determining transmissivity at 0
Determine_transmissivity = 0
######################## Extract general data for VIIRS-PROBAV ##########################################
if Image_Type == 2:
# Open the VIIRS_PROBAV_Input sheet
ws = wb['VIIRS_PROBAV_Input']
# Extract the name of the thermal and quality VIIRS image from the excel file
Name_VIIRS_Image_TB = '%s' %str(ws['B%d' % number].value)
# Extract the name to the PROBA-V image from the excel file
Name_PROBAV_Image = '%s' %str(ws['D%d' % number].value) # Must be a tiff file
# Pixel size of the model
pixel_spacing=int(100)
# UTM Zone of the end results
UTM_Zone = float(ws['G%d' % number].value)
if not Name_VIIRS_Image_TB == 'None':
#Get time from the VIIRS dataset name (IMPORTANT TO KEEP THE TEMPLATE OF THE VIIRS NAME CORRECT example: npp_viirs_i05_20150701_124752_wgs84_fit.tif)
Total_Day_VIIRS = Name_VIIRS_Image_TB.split('_')[3]
Total_Time_VIIRS = Name_VIIRS_Image_TB.split('_')[4]
# Get the information out of the VIIRS name in GMT (Greenwich time)
year = int(Total_Day_VIIRS[0:4])
month = int(Total_Day_VIIRS[4:6])
day = int(Total_Day_VIIRS[6:8])
Startdate = '%d-%02d-%02d' % (year,month,day)
DOY=datetime.strptime(Startdate,'%Y-%m-%d').timetuple().tm_yday
hour = int(Total_Time_VIIRS[0:2])
minutes = int(Total_Time_VIIRS[2:4])
# If this is runned correctly, we can determine transmissivity
ws = wb['Meteo_Input']
Field_Radiation_24 = '%s' %str(ws['J%d' % number].value)
Field_Trans_24 = '%s' %str(ws['K%d' % number].value)
Determine_transmissivity = 1
# else use PROBA-V day but than no transmissivity can be determined for now
else:
# Get the day and time from the PROBA-V
Band_PROBAVhdf_fileName = os.path.join(input_folder, '%s.HDF5' % (Name_PROBAV_Image))
g=gdal.Open(Band_PROBAVhdf_fileName, gdal.GA_ReadOnly)
Meta_data = g.GetMetadata()
Date_PROBAV = str(Meta_data['LEVEL3_RADIOMETRY_BLUE_OBSERVATION_START_DATE'])
year = int(Date_PROBAV.split("-")[0])
month = int(Date_PROBAV.split("-")[1])
day = int(Date_PROBAV.split("-")[2])
Var_name = '%d%02d%02d' %(year, month, day)
DOY=datetime.strptime(Var_name,'%Y%m%d').timetuple().tm_yday
# We cannot determine transmissivity
Determine_transmissivity = 0
# Determine the transmissivity if possible (Determine_transmissivity = 1)
if Determine_transmissivity == 1:
# Rounded difference of the local time from Greenwich (GMT) (hours):
delta_GTM = round(np.sign(lon[int(np.shape(lon)[0]/2), int(np.shape(lon)[1]/2)]) * lon[int(np.shape(lon)[0]/2), int(np.shape(lon)[1]/2)] * 24 / 360)
if np.isnan(delta_GTM) == True:
delta_GTM = round(np.nanmean(lon) * np.nanmean(lon) * 24 / 360)
# Calculate local time
hour += delta_GTM
if hour < 0.0:
day -= 1
hour += 24
if hour >= 24:
day += 1
hour -= 24
# define the kind of sensor and resolution of the sensor
sensor1 = 'PROBAV'
sensor2 = 'VIIRS'
res1 = '375m'
res2 = '%sm' %int(pixel_spacing)
res3 = '30m'
######################## Extract general data from DEM file and create Slope map ##########################################
# Variable date name
Var_name = '%d%02d%02d' %(year, month, day)
# Reproject from Geog Coord Syst to UTM -
# 1) DEM - Original DEM coordinates is Geographic: lat, lon
dest, ulx_dem, lry_dem, lrx_dem, uly_dem, epsg_to = SEBAL.reproject_dataset(
DEM_fileName, pixel_spacing, UTM_Zone=UTM_Zone)
band = dest.GetRasterBand(1) # Get the reprojected dem band
ncol = dest.RasterXSize # Get the reprojected dem column size
nrow = dest.RasterYSize # Get the reprojected dem row size
shape=[ncol, nrow]
# Read out the DEM band and print the DEM properties
data_DEM = band.ReadAsArray(0, 0, ncol, nrow)
# 2) Latitude file - reprojection
# reproject latitude to the landsat projection and save as tiff file
lat_rep, ulx_dem, lry_dem, lrx_dem, uly_dem, epsg_to = SEBAL.reproject_dataset(
lat_fileName, pixel_spacing, UTM_Zone=UTM_Zone)
# Get the reprojected latitude data
lat_proy = lat_rep.GetRasterBand(1).ReadAsArray(0, 0, ncol, nrow)
# 3) Longitude file - reprojection
# reproject longitude to the landsat projection and save as tiff file
lon_rep, ulx_dem, lry_dem, lrx_dem, uly_dem, epsg_to = SEBAL.reproject_dataset(lon_fileName, pixel_spacing, UTM_Zone=UTM_Zone)
# Get the reprojected longitude data
lon_proy = lon_rep.GetRasterBand(1).ReadAsArray(0, 0, ncol, nrow)
lon_fileName = os.path.join(temp_folder_PreSEBAL,'lon_resh.tif')
SEBAL.save_GeoTiff_proy(dest, lon_proy, lon_fileName, shape, nband=1)
# Calculate slope and aspect from the reprojected DEM
deg2rad,rad2deg,slope,aspect=SEBAL.Calc_Gradient(data_DEM, pixel_spacing)
if Determine_transmissivity == 1:
# calculate the coz zenith angle
Ra_mountain_24, Ra_inst, cos_zn_resh, dr, phi, delta = SEBAL.Calc_Ra_Mountain(lon,DOY,hour,minutes,lon_proy,lat_proy,slope,aspect)
cos_zn_fileName = os.path.join(temp_folder_PreSEBAL,'cos_zn.tif')
SEBAL.save_GeoTiff_proy(dest, cos_zn_resh, cos_zn_fileName, shape, nband=1)
# Save the Ra
Ra_inst_fileName = os.path.join(temp_folder_PreSEBAL,'Ra_inst.tif')
SEBAL.save_GeoTiff_proy(dest, Ra_inst, Ra_inst_fileName, shape, nband=1)
Ra_mountain_24_fileName = os.path.join(temp_folder_PreSEBAL,'Ra_mountain_24.tif')
SEBAL.save_GeoTiff_proy(dest, Ra_mountain_24, Ra_mountain_24_fileName, shape, nband=1)
#################### Calculate Transmissivity ##########################################
# Open the General_Input sheet
ws = wb['Meteo_Input']
# Extract the method radiation value
Value_Method_Radiation_inst = '%s' %str(ws['L%d' % number].value)
# Values to check if data is created
Check_Trans_inst = 0
Check_Trans_24 = 0
''' This is now turned off, so you need to fill in the instantanious transmissivity or Radiation
# Extract the data to the method of radiation
if int(Value_Method_Radiation_inst) == 2:
Field_Radiation_inst = '%s' %str(ws['N%d' % number].value)
if Field_Radiation_inst == 'None':
# Instantanious Transmissivity files must be created
Check_Trans_inst = 1
# Calculate Transmissivity
quarters_hours = np.ceil(minutes/30.) * 30
hours_GMT = hour - delta_GTM
if quarters_hours >= 60:
hours_GMT += 1
quarters_hours = 0
# Define the instantanious LANDSAF file
name_Landsaf_inst = 'HDF5_LSASAF_MSG_DSSF_MSG-Disk_%d%02d%02d%02d%02d.tif' %(year, month,day, hours_GMT, quarters_hours)
file_Landsaf_inst = os.path.join(DSSF_Folder,name_Landsaf_inst)
# Reproject the Ra_inst data to match the LANDSAF data
Ra_inst_3Km_dest, ulx, lry, lrx, uly, epsg_to = SEBAL.reproject_dataset_example(Ra_inst_fileName, file_Landsaf_inst, method = 1)
Ra_inst_3Km = Ra_inst_3Km_dest.GetRasterBand(1).ReadAsArray()
Ra_inst_3Km[Ra_inst_3Km==0] = np.nan
# Open the Rs LANDSAF data
dest_Rs_inst_3Km = gdal.Open(file_Landsaf_inst)
Rs_inst_3Km = dest_Rs_inst_3Km.GetRasterBand(1).ReadAsArray()
Rs_inst_3Km = np.float_(Rs_inst_3Km)/10
Rs_inst_3Km[Rs_inst_3Km<0]=np.nan
# Get shape LANDSAF data
shape_trans=[dest_Rs_inst_3Km.RasterXSize , dest_Rs_inst_3Km.RasterYSize ]
# Calculate Transmissivity 3Km
Transmissivity_3Km = Rs_inst_3Km/Ra_inst_3Km
Transmissivity_3Km_fileName = os.path.join(output_folder_temp,'Transmissivity_3Km.tif')
SEBAL.save_GeoTiff_proy(Ra_inst_3Km_dest, Transmissivity_3Km, Transmissivity_3Km_fileName, shape_trans, nband=1)
# Reproject Transmissivity to match DEM (now this is done by using the nearest neighbour method)
Transmissivity_inst_dest, ulx, lry, lrx, uly, epsg_to = SEBAL.reproject_dataset_example(Transmissivity_3Km_fileName, cos_zn_fileName, method = 3)
Transmissivity_inst = Transmissivity_inst_dest.GetRasterBand(1).ReadAsArray()
Transmissivity_inst[Transmissivity_inst>0.98] = 0.98
Transmissivity_inst_fileName = os.path.join(TRANS_outfolder,'Transmissivity_inst_%s.tif' %Var_name)
SEBAL.save_GeoTiff_proy(Transmissivity_inst_dest, Transmissivity_inst, Transmissivity_inst_fileName, shape, nband=1)
'''
# Extract the method radiation value
Value_Method_Radiation_24 = '%s' %str(ws['I%d' % number].value)
# Extract the data to the method of radiation
if int(Value_Method_Radiation_24) == 2:
Field_Radiation_24 = '%s' %str(ws['K%d' % number].value)
if Field_Radiation_24 == 'None':
# Daily Transmissivity files must be created
Check_Trans_24 = 1
# Create times that are needed to calculate daily Rs (LANDSAF)
Starttime_GMT = datetime.strptime(Startdate,'%Y-%m-%d') + timedelta(hours=-delta_GTM)
Endtime_GMT = Starttime_GMT + timedelta(days=1)
Times = pd.date_range(Starttime_GMT, Endtime_GMT,freq = '30min')
for Time in Times[:-1]:
year_LANDSAF = Time.year
month_LANDSAF = Time.month
day_LANDSAF = Time.day
hour_LANDSAF = Time.hour
min_LANDSAF = Time.minute
# Define the instantanious LANDSAF file
#re = glob.glob('')
name_Landsaf_inst = 'HDF5_LSASAF_MSG_DSSF_MSG-Disk_%d%02d%02d%02d%02d.tif' %(year_LANDSAF, month_LANDSAF,day_LANDSAF, hour_LANDSAF, min_LANDSAF)
file_Landsaf_inst = os.path.join(DSSF_Folder,name_Landsaf_inst)
# Open the Rs LANDSAF data
dest_Rs_inst_3Km = gdal.Open(file_Landsaf_inst)
Rs_one_3Km = dest_Rs_inst_3Km.GetRasterBand(1).ReadAsArray()
Rs_one_3Km = np.float_(Rs_one_3Km)/10
Rs_one_3Km[Rs_one_3Km < 0]=np.nan
if Time == Times[0]:
Rs_24_3Km_tot = Rs_one_3Km
else:
Rs_24_3Km_tot += Rs_one_3Km
Rs_24_3Km = Rs_24_3Km_tot / len(Times[:-1])
# Reproject the Ra_inst data to match the LANDSAF data
Ra_24_3Km_dest, ulx, lry, lrx, uly, epsg_to = SEBAL.reproject_dataset_example(Ra_mountain_24_fileName, file_Landsaf_inst, method = 3)
Ra_24_3Km = Ra_24_3Km_dest.GetRasterBand(1).ReadAsArray()
Ra_24_3Km[Ra_24_3Km==0] = np.nan
# Do gapfilling
Ra_24_3Km = gap_filling(Ra_24_3Km,np.nan)
# Get shape LANDSAF data
shape_trans=[dest_Rs_inst_3Km.RasterXSize , dest_Rs_inst_3Km.RasterYSize ]
# Calculate Transmissivity 3Km
Transmissivity_24_3Km = Rs_24_3Km/Ra_24_3Km
Transmissivity_24_3Km_fileName = os.path.join(temp_folder_PreSEBAL,'Transmissivity_24_3Km.tif')
SEBAL.save_GeoTiff_proy(Ra_24_3Km_dest, Transmissivity_24_3Km, Transmissivity_24_3Km_fileName, shape_trans, nband=1)
# Reproject Transmissivity to match DEM (now this is done by using the nearest neighbour method)
Transmissivity_24_dest, ulx, lry, lrx, uly, epsg_to = SEBAL.reproject_dataset_example(Transmissivity_24_3Km_fileName, lon_fileName, method = 3)
Transmissivity_24 = Transmissivity_24_dest.GetRasterBand(1).ReadAsArray()
Transmissivity_24[Transmissivity_24>0.98] = 0.98
Transmissivity_24_fileName = os.path.join(TRANS_outfolder,'Transmissivity_24_%s.tif' %Var_name)
SEBAL.save_GeoTiff_proy(Transmissivity_24_dest, Transmissivity_24, Transmissivity_24_fileName, shape, nband=1)
#################### Calculate NDVI for LANDSAT ##########################################
if Image_Type == 1:
# Define bands used for each Landsat number
if Landsat_nr == 5 or Landsat_nr == 7:
Bands = np.array([1, 2, 3, 4, 5, 7, 6])
elif Landsat_nr == 8:
Bands = np.array([2, 3, 4, 5, 6, 7, 10, 11])
else:
print('Landsat image not supported, use Landsat 7 or 8')
# Open MTL landsat and get the correction parameters
Landsat_meta_fileName = os.path.join(input_folder, '%s_MTL.txt' % Name_Landsat_Image)
Lmin, Lmax, k1_c, k2_c = SEBAL.info_band_metadata(Landsat_meta_fileName, Bands)
# Mean solar exo-atmospheric irradiance for each band (W/m2/microm)
# for the different Landsat images (L5, L7, or L8)
ESUN_L5 = np.array([1983, 1796, 1536, 1031, 220, 83.44])
ESUN_L7 = np.array([1997, 1812, 1533, 1039, 230.8, 84.9])
ESUN_L8 = np.array([1973.28, 1842.68, 1565.17, 963.69, 245, 82.106])
# Open one band - To get the metadata of the landsat images only once (to get the extend)
src_FileName = os.path.join(input_folder, '%s_B2.TIF' % Name_Landsat_Image) # before 10!
ls,band_data,ulx,uly,lrx,lry,x_size_ls,y_size_ls = SEBAL.Get_Extend_Landsat(src_FileName)
# Crop the Landsat images to the DEM extent -
dst_FileName = os.path.join(temp_folder_PreSEBAL,'cropped_LS_b2.tif') # Before 10 !!
# Clip the landsat image to match the DEM map
lsc, ulx, lry, lrx, uly, epsg_to = SEBAL.reproject_dataset_example(src_FileName, lon_fileName)
data_LS = lsc.GetRasterBand(1).ReadAsArray()
SEBAL.save_GeoTiff_proy(dest, data_LS, dst_FileName, shape, nband=1)
# Get the extend of the remaining landsat file after clipping based on the DEM file
lsc,band_data,ulx,uly,lrx,lry,x_size_lsc,y_size_lsc = SEBAL.Get_Extend_Landsat(dst_FileName)
# Create the corrected signals of Landsat in 1 array
Reflect = SEBAL.Landsat_Reflect(Bands,input_folder,Name_Landsat_Image,output_folder,shape,Lmax,Lmin,ESUN_L5,ESUN_L7,ESUN_L8,cos_zn_resh,dr,Landsat_nr, cos_zn_fileName)
# Calculate temporal water mask
water_mask_temp=SEBAL.Water_Mask(shape,Reflect)
# Calculate NDVI
NDVI = SEBAL.Calc_NDVI(Reflect)
# Calculate albedo
albedo = SEBAL.Calc_albedo(Reflect)
# Save NDVI
NDVI_FileName = os.path.join(NDVI_outfolder,'NDVI_LS_%s.tif'%Var_name)
SEBAL.save_GeoTiff_proy(dest, NDVI, NDVI_FileName, shape, nband=1)
# Save albedo
albedo_FileName = os.path.join(Albedo_outfolder,'Albedo_LS_%s.tif'%Var_name)
SEBAL.save_GeoTiff_proy(dest, albedo, albedo_FileName, shape, nband=1)
################### Extract Meteo data for Landsat days from SEBAL Excel ##################
# Open the Meteo_Input sheet
ws = wb['Meteo_Input']
# ---------------------------- Instantaneous Air Temperature ------------
# Open meteo data, first try to open as value, otherwise as string (path)
try:
Temp_inst = float(ws['B%d' %number].value) # Instantaneous Air Temperature (°C)
# if the data is not a value, than open as a string
except:
Temp_inst_name = '%s' %str(ws['B%d' %number].value)
Temp_inst_fileName = os.path.join(output_folder, 'Temp', 'Temp_inst_input.tif')
Temp_inst = SEBAL.Reshape_Reproject_Input_data(Temp_inst_name, Temp_inst_fileName, lon_fileName)
try:
RH_inst = float(ws['D%d' %number].value) # Instantaneous Relative humidity (%)
# if the data is not a value, than open as a string
except:
RH_inst_name = '%s' %str(ws['D%d' %number].value)
RH_inst_fileName = os.path.join(output_folder, 'Temp', 'RH_inst_input.tif')
RH_inst = SEBAL.Reshape_Reproject_Input_data(RH_inst_name, RH_inst_fileName, lon_fileName)
esat_inst = 0.6108 * np.exp(17.27 * Temp_inst / (Temp_inst + 237.3))
eact_inst = RH_inst * esat_inst / 100
#################### Calculate NDVI for VIIRS-PROBAV ##########################################
if Image_Type == 2:
if Name_PROBAV_Image == 'None':
offset_all = [-1, 1, -2, 2, -3, 3,-4, 4,-5 ,5 ,-6 , 6, -7, 7, -8, 8]
found_Name_PROBAV_Image = 0
for offset in offset_all:
if found_Name_PROBAV_Image == 1:
continue
else:
try:
Name_PROBAV_Image = SEBAL_RUNS[number + offset]['PROBA_V_name']
if not Name_PROBAV_Image == 'None':
found_Name_PROBAV_Image = 1
except:
pass
# Get the day and time from the PROBA-V
Band_PROBAVhdf_fileName = os.path.join(input_folder, '%s.HDF5' % (Name_PROBAV_Image))
g=gdal.Open(Band_PROBAVhdf_fileName, gdal.GA_ReadOnly)
Meta_data = g.GetMetadata()
Date_PROBAV = str(Meta_data['LEVEL3_RADIOMETRY_BLUE_OBSERVATION_START_DATE'])
year = int(Date_PROBAV.split("-")[0])
month = int(Date_PROBAV.split("-")[1])
day = int(Date_PROBAV.split("-")[2])
Var_name_2 = '%d%02d%02d' %(year, month, day)
# Define the output name
NDVI_FileName = os.path.join(NDVI_outfolder,'NDVI_PROBAV_%s.tif' %Var_name_2)
Albedo_FileName = os.path.join(Albedo_outfolder, 'Albedo_PROBAV_%s.tif' %Var_name_2)
water_mask_temp_FileName = os.path.join(WaterMask_outfolder, 'Water_Mask_PROBAV_%s.tif' %Var_name_2)
else:
NDVI_FileName = os.path.join(NDVI_outfolder,'NDVI_PROBAV_%s.tif' %Var_name)
Albedo_FileName = os.path.join(Albedo_outfolder, 'Albedo_PROBAV_%s.tif' %Var_name)
water_mask_temp_FileName = os.path.join(WaterMask_outfolder, 'Water_Mask_PROBAV_%s.tif' %Var_name)
# vegetation maps that will be generated
if not os.path.exists(NDVI_FileName):
# Define the bands that will be used
bands=['SM', 'B1', 'B2', 'B3', 'B4'] #'SM', 'BLUE', 'RED', 'NIR', 'SWIR'
# Set the index number at 0
index=0
# create a zero array with the shape of the reprojected DEM file
data_PROBAV=np.zeros((shape[1], shape[0]))
spectral_reflectance_PROBAV=np.zeros([shape[1], shape[0], 5])
# constants
n188_float=248 # Now it is 248, but we do not exactly know what this really means and if this is for constant for all images.
# write the data one by one to the spectral_reflectance_PROBAV
for bandnmr in bands:
# Translate the PROBA-V names to the Landsat band names
Band_number = {'SM':7,'B1':8,'B2':10,'B3':9,'B4':11}
# Open the dataset
Band_PROBAVhdf_fileName = os.path.join(input_folder, '%s.HDF5' % (Name_PROBAV_Image))
g=gdal.Open(Band_PROBAVhdf_fileName, gdal.GA_ReadOnly)
# define data if it is not there yet
if not 'Var_name' in locals():
Meta_data = g.GetMetadata()
Date_PROBAV = str(Meta_data['LEVEL3_RADIOMETRY_BLUE_OBSERVATION_START_DATE'])
year = int(Date_PROBAV.split("-")[0])
month = int(Date_PROBAV.split("-")[0])
day = int(Date_PROBAV.split("-")[0])
Var_name = '%d%02d%02d' %(year, month, day)
# Open the .hdf file
name_out = os.path.join(input_folder, '%s_test.tif' % (Name_PROBAV_Image))
name_in = g.GetSubDatasets()[Band_number[bandnmr]][0]
# Get environmental variable
SEBAL_env_paths = os.environ["SEBAL"].split(';')
GDAL_env_path = SEBAL_env_paths[0]
GDAL_TRANSLATE = os.path.join(GDAL_env_path, 'gdal_translate.exe')
# run gdal translate command
FullCmd = '%s -of GTiff %s %s' %(GDAL_TRANSLATE, name_in, name_out)
SEBAL.Run_command_window(FullCmd)
# Open data
dest_PV = gdal.Open(name_out)
Data = dest_PV.GetRasterBand(1).ReadAsArray()
dest_PV = None
# Remove temporary file
os.remove(name_out)
# Define the x and y spacing
Meta_data = g.GetMetadata()
Lat_Bottom = float(Meta_data['LEVEL3_GEOMETRY_BOTTOM_LEFT_LATITUDE'])
Lat_Top = float(Meta_data['LEVEL3_GEOMETRY_TOP_RIGHT_LATITUDE'])
Lon_Left = float(Meta_data['LEVEL3_GEOMETRY_BOTTOM_LEFT_LONGITUDE'])
Lon_Right = float(Meta_data['LEVEL3_GEOMETRY_TOP_RIGHT_LONGITUDE'])
Pixel_size = float((Meta_data['LEVEL3_GEOMETRY_VNIR_VAA_MAPPING']).split(' ')[-3])
# Define the georeference of the PROBA-V data
geo_PROBAV=[Lon_Left-0.5*Pixel_size, Pixel_size, 0, Lat_Top+0.5*Pixel_size, 0, -Pixel_size] #0.000992063492063
# Define the name of the output file
PROBAV_data_name=os.path.join(input_folder, '%s_%s.tif' % (Name_PROBAV_Image,bandnmr))
dst_fileName=os.path.join(input_folder, PROBAV_data_name)
# create gtiff output with the PROBA-V band
fmt = 'GTiff'
driver = gdal.GetDriverByName(fmt)
dst_dataset = driver.Create(dst_fileName, int(Data.shape[1]), int(Data.shape[0]), 1,gdal.GDT_Float32)
dst_dataset.SetGeoTransform(geo_PROBAV)
# set the reference info
srs = osr.SpatialReference()
srs.SetWellKnownGeogCS("WGS84")
dst_dataset.SetProjection(srs.ExportToWkt())
# write the array in the geotiff band
dst_dataset.GetRasterBand(1).WriteArray(Data)
dst_dataset = None
# Open the PROBA-V band in SEBAL
g=gdal.Open(PROBAV_data_name.replace("\\","/"))
# If the data cannot be opened, change the extension
if g is None:
PROBAV_data_name=os.path.join(input_folder, '%s_%s.tiff' % (Name_PROBAV_Image,bandnmr))
# Reproject the PROBA-V band to match DEM's resolution
PROBAV, ulx, lry, lrx, uly, epsg_to = SEBAL.reproject_dataset_example(
PROBAV_data_name, lon_fileName)
# Open the reprojected PROBA-V band data
data_PROBAV_DN = PROBAV.GetRasterBand(1).ReadAsArray(0, 0, ncol, nrow)
# Define the filename to store the cropped Landsat image
dst_FileName = os.path.join(output_folder, 'Output_PROBAV','proy_PROBAV_%s.tif' % bandnmr)
# close the PROBA-V
g=None
# If the band data is not SM change the DN values into PROBA-V values and write into the spectral_reflectance_PROBAV
if bandnmr is not 'SM':
data_PROBAV[:, :]=data_PROBAV_DN/2000
spectral_reflectance_PROBAV[:, :, index]=data_PROBAV[:, :]
# If the band data is the SM band than write the data into the spectral_reflectance_PROBAV and create cloud mask
else:
data_PROBAV[:, :]=data_PROBAV_DN
Cloud_Mask_PROBAV=np.zeros((shape[1], shape[0]))
Cloud_Mask_PROBAV[data_PROBAV[:,:]!=n188_float]=1
spectral_reflectance_PROBAV[:, :, index]=Cloud_Mask_PROBAV
# Change the spectral reflectance to meet certain limits
spectral_reflectance_PROBAV[:, :, index]=np.where(spectral_reflectance_PROBAV[:, :, index]<=0,np.nan,spectral_reflectance_PROBAV[:, :, index])
spectral_reflectance_PROBAV[:, :, index]=np.where(spectral_reflectance_PROBAV[:, :, index]>=150,np.nan,spectral_reflectance_PROBAV[:, :, index])
# Go to the next index
index=index+1
# Bands in PROBAV spectral reflectance
# 0 = MS
# 1 = BLUE
# 2 = NIR
# 3 = RED
# 4 = SWIR
# Calculate surface albedo based on PROBA-V
Surface_Albedo_PROBAV = 0.219 * spectral_reflectance_PROBAV[:, :, 1] + 0.361 * spectral_reflectance_PROBAV[:, :, 2] + 0.379 * spectral_reflectance_PROBAV[:, :, 3] + 0.041 * spectral_reflectance_PROBAV[:, :, 4]
# Create Water mask based on PROBA-V
water_mask_temp = np.zeros((shape[1], shape[0]))
water_mask_temp[np.logical_and(spectral_reflectance_PROBAV[:, :, 2] >= spectral_reflectance_PROBAV[:, :, 3],data_DEM>0)]=1
# Calculate the NDVI based on PROBA-V
n218_memory = spectral_reflectance_PROBAV[:, :, 2] + spectral_reflectance_PROBAV[:, :, 3]
NDVI = np.zeros((shape[1], shape[0]))
NDVI[n218_memory != 0] = ( spectral_reflectance_PROBAV[:, :, 3][n218_memory != 0] - spectral_reflectance_PROBAV[:, :, 2][n218_memory != 0] )/ ( spectral_reflectance_PROBAV[:, :, 2][n218_memory != 0] + spectral_reflectance_PROBAV[:, :, 3][n218_memory != 0] )
# Save Albedo for PROBA-V
SEBAL.save_GeoTiff_proy(dest, Surface_Albedo_PROBAV, Albedo_FileName, shape, nband=1)
# Save NDVI for PROBA-V
SEBAL.save_GeoTiff_proy(dest, NDVI, NDVI_FileName, shape, nband=1)
# Save Water Mask for PROBA-V
SEBAL.save_GeoTiff_proy(dest, water_mask_temp, water_mask_temp_FileName, shape, nband=1)
else:
dest_NDVI = gdal.Open(NDVI_FileName)
dest_water_mask_temp = gdal.Open(water_mask_temp_FileName)
NDVI = dest_NDVI.GetRasterBand(1).ReadAsArray()
water_mask_temp = dest_water_mask_temp.GetRasterBand(1).ReadAsArray()
############################ Calculate LAI ##########################################
# Calculate the LAI
FPAR,tir_emis,Nitrogen,vegt_cover,LAI,b10_emissivity = SEBAL.Calc_vegt_para(NDVI,water_mask_temp,shape)
# Create LAI name
if Image_Type == 1:
LAI_FileName = os.path.join(LAI_outfolder,'LAI_LS_%s.tif' %Var_name)
SEBAL.save_GeoTiff_proy(dest, LAI, LAI_FileName, shape, nband=1)
#################### Calculate thermal for Landsat ##########################################
if Image_Type == 1:
# Calculate thermal
therm_data = SEBAL.Landsat_therm_data(Bands,input_folder,Name_Landsat_Image,output_folder,ulx_dem,lry_dem,lrx_dem,uly_dem,shape)
# Calculate surface temperature
Surface_temp=SEBAL.Calc_surface_water_temp(Temp_inst,Landsat_nr,Lmax,Lmin,therm_data,b10_emissivity,k1_c,k2_c,eact_inst,shape,water_mask_temp,Bands_thermal,Rp,tau_sky,surf_temp_offset,Image_Type)
# Save surface temperature
therm_data_FileName = os.path.join(Surface_Temperature_outfolder,'Surface_Temperature_LS_%s.tif' %Var_name)
SEBAL.save_GeoTiff_proy(dest, Surface_temp, therm_data_FileName, shape, nband=1)
################################## Calculate VIIRS surface temperature ########################
if Image_Type == 2:
# If there is VIIRS data
if not Name_VIIRS_Image_TB == 'None':
# Define the VIIRS thermal data name
VIIRS_data_name=os.path.join(input_folder, '%s' % (Name_VIIRS_Image_TB))
# Reproject VIIRS thermal data
VIIRS, ulx, lry, lrx, uly, epsg_to = SEBAL.reproject_dataset_example(VIIRS_data_name, lon_fileName)
# Open VIIRS thermal data
data_VIIRS = VIIRS.GetRasterBand(1).ReadAsArray()
# Define the thermal VIIRS output name
proyVIIRS_fileName = os.path.join(temp_folder_PreSEBAL, 'Surface_Temp_VIIRS_%s.tif' %Var_name)
# Save the thermal VIIRS data
SEBAL.save_GeoTiff_proy(dest, data_VIIRS, proyVIIRS_fileName, shape, nband=1)
# Set the conditions for the brightness temperature (100m)
brightness_temp=np.where(data_VIIRS>=250, data_VIIRS, np.nan)
# Constants
k1=606.399172
k2=1258.78
L_lambda_b10_100=((2*6.63e-34*(3.0e8)**2)/((11.45e-6)**5*(np.exp((6.63e-34*3e8)/(1.38e-23*(11.45e-6)*brightness_temp))-1)))*1e-6
# Get Temperature for 100 and 375m resolution
Temp_TOA_100 = SEBAL.Get_Thermal(L_lambda_b10_100,Rp,Temp_inst,tau_sky,tir_emis,k1,k2)
# Conditions for surface temperature (100m)
n120_surface_temp=Temp_TOA_100.clip(250, 450)
# Save the surface temperature of the VIIRS in 100m resolution
temp_surface_100_fileName_beforeTS = os.path.join(Surface_Temperature_outfolder,'Surface_Temperature_VIIRS_%s.tif' %Var_name)
SEBAL.save_GeoTiff_proy(dest, n120_surface_temp, temp_surface_100_fileName_beforeTS, shape, nband=1)
###################### Create NC files for HANTS parameter testing ####################################
# All HANTS variables
VARS = ['NDVI', 'Albedo', 'Surface_Temperature']
# loop over the HANTS parameters
for VAR in VARS:
# Define paths for NDVI
input_folder_HANTS_VAR = os.path.join(output_folder_PreSEBAL_SEBAL, VAR)
if VAR == 'Surface_Temperature':
name_format = 'Surface_Temperature_VIIRS_{0}.tif'
else:
name_format = '%s_PROBAV_{0}.tif' %VAR
# define NC output for the 3D array
nc_path = os.path.join(input_folder_HANTS_VAR,'%s_NC.nc' %VAR)
# Set the working directory to the Tiff file of the HANTS parameter
os.chdir(input_folder_HANTS_VAR)
# Rename the variable in the name_format
name_format_var = name_format.replace('{0}','*')
# Find all tiff files equal to format
re_var = glob.glob(name_format_var)
# Open the first tiff file
path_to_first_variable = os.path.join(input_folder_HANTS_VAR,re_var[0])
dest_first_var = gdal.Open(path_to_first_variable)
# Read out the geo transforma paramters
geo_first_var = dest_first_var.GetGeoTransform()
x_size = int(dest_first_var.RasterXSize)
y_size = int(dest_first_var.RasterYSize)
cellsize = int(geo_first_var[1])
latlim = [geo_first_var[3]+geo_first_var[5]*y_size,geo_first_var[3]]
lonlim = [geo_first_var[0],geo_first_var[0]+geo_first_var[1]*x_size]
# Create netcdf
import hants.wa_gdal as hants_gdal
hants_gdal.create_netcdf(input_folder_HANTS_VAR, name_format, start_date, end_date,
latlim, lonlim, cellsize, nc_path)
def Create_Buffer(Data_In):
'''
This function creates a 3D array which is used to apply the moving window
'''
Buffer_area = 7 # A block of 2 times Buffer_area + 1 will be 1 if there is the pixel in the middle is 1
Data_Out=np.empty((len(Data_In),len(Data_In[1])))
Data_Out[:,:] = Data_In
for ypixel in range(0,Buffer_area + 1):
for xpixel in range(1,Buffer_area + 1):
if ypixel==0:
for xpixel in range(1,Buffer_area + 1):
Data_Out[:,0:-xpixel] += Data_In[:,xpixel:]
Data_Out[:,xpixel:] += Data_In[:,:-xpixel]
for ypixel in range(1,Buffer_area + 1):
Data_Out[ypixel:,:] += Data_In[:-ypixel,:]
Data_Out[0:-ypixel,:] += Data_In[ypixel:,:]
else:
Data_Out[0:-xpixel,ypixel:] += Data_In[xpixel:,:-ypixel]
Data_Out[xpixel:,ypixel:] += Data_In[:-xpixel,:-ypixel]
Data_Out[0:-xpixel,0:-ypixel] += Data_In[xpixel:,ypixel:]
Data_Out[xpixel:,0:-ypixel] += Data_In[:-xpixel,ypixel:]
Data_Out[Data_Out>0.1] = 1
Data_Out[Data_Out<=0.1] = 0
return(Data_Out)
def Get_epsg(g):
try:
# Get info of the dataset that is used for transforming
gland_proj = g.GetProjection()
Projection=gland_proj.split('EPSG","')
epsg_to=int((str(Projection[-1]).split(']')[0])[0:-1])
except:
epsg_to=4326
print('Was not able to get the projection, so WGS84 is assumed')
return(epsg_to)
def gap_filling(data,NoDataValue):
"""
This function fills the no data gaps in a numpy array
Keyword arguments:
dataset -- Array
NoDataValue -- Value that must be filled
"""
# fill the no data values
if NoDataValue is np.nan:
mask = ~(np.isnan(data))
else:
mask = ~(data==NoDataValue)
xx, yy = np.meshgrid(np.arange(data.shape[1]), np.arange(data.shape[0]))
xym = np.vstack( (np.ravel(xx[mask]), np.ravel(yy[mask])) ).T
data0 = np.ravel( data[:,:][mask] )
interp0 = scipy.interpolate.NearestNDInterpolator( xym, data0 )
data_end = interp0(np.ravel(xx), np.ravel(yy)).reshape( xx.shape )
return (data_end)
if __name__ == '__main__':
main()
|
import cPickle
import errno
import itertools
import os
import sys
import tempfile
import traceback
from conary import files, trove, callbacks
from conary.deps import deps
from conary.lib import util, openpgpfile, sha1helper, openpgpkey
from conary.repository import changeset, errors, filecontents
from conary.repository.datastore import DataStoreRepository, DataStore
from conary.repository.datastore import DataStoreSet
from conary.repository.repository import AbstractRepository
from conary.repository.repository import ChangeSetJob
from conary.repository import netclient
from conary.server import schema
class FilesystemChangeSetJob(ChangeSetJob):
def __init__(self, repos, cs, *args, **kw):
self.mirror = kw.get('mirror', False)
self.requireSigs = kw.pop('requireSigs', False)
self.callback = kw.get('callback', False)
self.addTroveSetStart(repos, cs)
ChangeSetJob.__init__(self, repos, cs, *args, **kw)
repos.troveStore.addTroveSetDone(self.callback)
def addTroveSetStart(self, repos, cs):
newDirNames = set()
newBaseNames = set()
oldTroves = []
for i, csTrove in enumerate(cs.iterNewTroveList()):
if csTrove.getOldVersion():
oldTroves.append(csTrove.getOldNameVersionFlavor())
for fileInfo in itertools.chain(
csTrove.getNewFileList(raw = True),
csTrove.getChangedFileList(raw = True)):
if fileInfo[1] is None:
continue
newDirNames.add(fileInfo[1])
newBaseNames.add(fileInfo[2])
repos.troveStore.addTroveSetStart(oldTroves, newDirNames, newBaseNames)
def _containsFileContents(self, sha1iter):
return self.repos.troveStore.hasFileContents(sha1iter)
def markTroveRemoved(self, name, version, flavor):
self.repos.markTroveRemoved(name, version, flavor)
def checkTroveCompleteness(self, trv):
if not self.mirror and not trv.troveInfo.sigs.sha1():
raise errors.TroveChecksumMissing(trv.getName(), trv.getVersion(),
trv.getFlavor())
if trv.troveInfo.incomplete():
if trv.troveInfo.troveVersion() > trove.TROVE_VERSION:
raise errors.TroveSchemaError(trv.getName(), trv.getVersion(),
trv.getFlavor(),
trv.troveInfo.troveVersion(),
trove.TROVE_VERSION)
else:
nvf = trv.getName(), trv.getVersion(), trv.getFlavor(),
err = 'Attempted to commit incomplete trove %s=%s[%s]' % nvf
raise errors.TroveIntegrityError(error=err, *nvf)
def checkTroveSignatures(self, trv, callback):
assert(hasattr(callback, 'verifyTroveSignatures'))
if callback.keyCache is None:
callback.keyCache = openpgpkey.getKeyCache()
for fingerprint, timestamp, sig in trv.troveInfo.sigs.digitalSigs.iter():
try:
pubKey = callback.keyCache.getPublicKey(fingerprint)
if pubKey.isRevoked():
raise openpgpfile.IncompatibleKey('Key %s is revoked'
%pubKey.getFingerprint())
expirationTime = pubKey.getTimestamp()
if expirationTime and expirationTime < timestamp:
raise openpgpfile.IncompatibleKey('Key %s is expired'
%pubKey.getFingerprint())
except openpgpfile.KeyNotFound:
# missing keys could be okay; that depends on the threshold
# we've set. it's the callbacks problem in any case.
pass
res = ChangeSetJob.checkTroveSignatures(self, trv, callback)
if len(res[1]) and self.requireSigs:
raise openpgpfile.KeyNotFound('Repository does not recognize '
'key: %s'% res[1][0])
class UpdateCallback(callbacks.UpdateCallback):
def __init__(self, statusPath, trustThreshold, keyCache):
self.path = statusPath
if statusPath:
self.tmpDir = os.path.dirname(statusPath)
callbacks.UpdateCallback.__init__(self, trustThreshold, keyCache)
def _dumpStatus(self, *args):
if self.path:
# make the new status dump in a temp location
# for atomicity
(fd, path) = tempfile.mkstemp(dir = self.tmpDir,
suffix = '.commit-status')
buf = cPickle.dumps(args)
os.write(fd, buf)
os.close(fd)
os.rename(path, self.path)
def creatingDatabaseTransaction(self, *args):
self._dumpStatus('creatingDatabaseTransaction', *args)
def updatingDatabase(self, *args):
self._dumpStatus('updatingDatabase', *args)
class FilesystemRepository(DataStoreRepository, AbstractRepository):
def __init__(self, serverNameList, troveStore, contentsDir, repositoryMap,
requireSigs = False, paranoidCommits = False):
self.serverNameList = serverNameList
self.paranoidCommits = paranoidCommits
map = dict(repositoryMap)
for serverName in serverNameList:
map[serverName] = self
# XXX this client needs to die
from conary import conarycfg
self.reposSet = netclient.NetworkRepositoryClient(map,
conarycfg.UserInformation())
self.troveStore = troveStore
self.requireSigs = requireSigs
for dir in contentsDir:
util.mkdirChain(dir)
if len(contentsDir) == 1:
store = DataStore(contentsDir[0])
else:
storeList = []
for dir in contentsDir:
storeList.append(DataStore(dir))
store = DataStoreSet(*storeList)
DataStoreRepository.__init__(self, dataStore = store)
AbstractRepository.__init__(self)
def close(self):
if self.troveStore is not None:
self.troveStore.db.close()
self.troveStore = None
### Package access functions
def thawFlavor(self, flavor):
return deps.ThawFlavor(flavor)
def hasTrove(self, pkgName, version, flavor):
return self.troveStore.hasTrove(pkgName, troveVersion = version,
troveFlavor = flavor)
def getTrove(self, pkgName, version, flavor, pristine = True,
withFiles = True, hidden = False):
return self.troveStore.getTrove(
pkgName, version, flavor, withFiles = withFiles,
hidden = hidden)
def iterTroves(self, troveList, withFiles = True, hidden = False):
return self.troveStore.iterTroves(troveList, withFiles = withFiles,
hidden = hidden)
def getParentTroves(self, troveList):
return self.troveStore.getParentTroves(troveList)
def addTrove(self, trv, trvCs, hidden = False, oldTroveSpec = None):
return self.troveStore.addTrove(trv, trvCs, hidden = hidden)
def addTroveDone(self, pkg, mirror=False):
self.troveStore.addTroveDone(pkg, mirror=mirror)
### File functions
def getFileVersion(self, pathId, fileId, fileVersion, withContents = 0):
# the get trove netclient provides doesn't work with a
# FilesystemRepository (it needs to create a change set which gets
# passed)
if fileVersion.getHost() not in self.serverNameList:
# XXX This code is not needed as of version 1.0.14 of the client.
assert(not withContents)
return self.reposSet.getFileVersion(pathId, fileId, fileVersion)
fileObj = self.troveStore.getFile(pathId, fileId)
if withContents:
if fileObj.hasContents:
cont = filecontents.FromDataStore(self.contentsStore,
file.contents.sha1())
else:
cont = None
return (fileObj, cont)
return fileObj
def getFileVersions(self, fileList, withContents = False):
# this is for compatibility with <= 1.0.13
crossRepos = False
for (pathId, fileId, fileVersion) in fileList:
if fileVersion.getHost() not in self.serverNameList:
crossRepos = True
if crossRepos:
for x in fileList:
yield self.getFileVersion(withContents = withContents, *x)
else:
fileDict = self.troveStore.getFiles(fileList)
for x in fileList:
# (pathId, fileId) lookup
try:
fileObj = fileDict[x[0:2]]
except KeyError:
raise errors.FileStreamMissing(x[1])
if withContents:
if file.hasContents:
cont = filecontents.FromDataStore(self.contentsStore,
file.contents.sha1())
else:
cont = None
yield (fileObj, cont)
yield fileObj
def addFileVersion(self, troveInfo, pathId, path, fileId,
fileVersion, fileStream = None, withContents = True):
troveInfo.addFile(pathId, path, fileId, fileVersion,
fileStream = fileStream, withContents = withContents)
###
def commitChangeSet(self, cs, mirror=False, hidden=False, serialize=False,
excludeCapsuleContents = False, callback = None,
statusPath = None):
# when we add troves (no removals) we disable constraints on
# the TroveFiles table; it speeds up large commits massively on
# postgres
enableConstraints = True
# let's make sure commiting this change set is a sane thing to attempt
for trvCs in cs.iterNewTroveList():
if trvCs.troveType() == trove.TROVE_TYPE_REMOVED:
enableConstraints = False
v = trvCs.getNewVersion()
if v.isOnLocalHost():
label = v.branch().label()
raise errors.CommitError('can not commit items on '
'%s label' %(label.asString()))
self.troveStore.begin(serialize)
if enableConstraints:
enableConstraints = self.troveStore.db.disableTableConstraints(
'TroveFiles')
if self.requireSigs:
threshold = openpgpfile.TRUST_FULL
else:
threshold = openpgpfile.TRUST_UNTRUSTED
# Callback for signature verification and progress
if statusPath:
assert not callback
callback = UpdateCallback(statusPath=statusPath,
trustThreshold=threshold,
keyCache=self.troveStore.keyTable.keyCache)
try:
# reset time stamps only if we're not mirroring.
FilesystemChangeSetJob(self, cs, self.serverNameList,
resetTimestamps = not mirror,
callback=callback,
mirror = mirror,
hidden = hidden,
excludeCapsuleContents =
excludeCapsuleContents,
requireSigs = self.requireSigs)
except openpgpfile.KeyNotFound:
# don't be quite so noisy, this is a common error
self.troveStore.rollback()
raise
except:
print >> sys.stderr, "exception occurred while committing change set"
print >> sys.stderr, ''.join(traceback.format_exception(*sys.exc_info()))
print >> sys.stderr, "attempting rollback"
self.troveStore.rollback()
raise
else:
if self.paranoidCommits:
for trvCs in cs.iterNewTroveList():
newTuple = trvCs.getNewNameVersionFlavor()
if newTuple[1] is None:
continue
trv = self.getTrove(withFiles = True, *newTuple)
assert(trv.verifyDigests())
if enableConstraints:
enableConstraints.enable()
self.troveStore.commit()
def markTroveRemoved(self, name, version, flavor):
sha1s = self.troveStore.markTroveRemoved(name, version, flavor)
for sha1 in sha1s:
try:
self.contentsStore.removeFile(sha1helper.sha1ToString(sha1))
except OSError, e:
if e.errno != errno.ENOENT:
raise
def getFileContents(self, itemList):
contents = []
for item in itemList:
(fileId, fileVersion) = item[0:2]
# the get trove netclient provides doesn't work with a
# FilesystemRepository (it needs to create a change set which gets
# passed)
if fileVersion.getHost() in self.serverNameList:
fileObj = item[2]
cont = filecontents.FromDataStore(self.contentsStore,
fileObj.contents.sha1())
else:
# XXX This code is not needed as of version 1.0.14 of the
# client.
#
# a bit of sleight of hand here... we look for this file in
# the trove it was first built in
#
# this could cause us to run out of file descriptors on large
# troves. it might be better to close the file and return
# a filecontents object?
cont = self.reposSet.getFileContents([ item ])[0]
contents.append(cont)
return contents
def createChangeSet(self, origTroveList, recurse = True,
withFiles = True, withFileContents = True,
excludeCapsuleContents = False,
excludeAutoSource = False,
mirrorMode = False, roleIds = None):
"""
@param origTroveList: a list of
C{(troveName, flavor, oldVersion, newVersion, absolute)} tuples.
If C{oldVersion == None} and C{absolute == 0}, then the trove is
assumed to be new for the purposes of the change set.
If C{newVersion == None} then the trove is being removed.
If recurse is set, this yields one result for the entire troveList.
If recurse is not set, it yields one result per troveList entry.
@param excludeCapsuleContents: If True, troves which include capsules
have all of their content excluded from the changeset no matter how
withFileContents is set.
"""
cs = changeset.ChangeSet()
externalTroveList = []
externalFileList = []
removedTroveList = []
dupFilter = set()
resultList = []
# make a copy to remove things from
troveList = origTroveList[:]
# def createChangeSet begins here
troveWrapper = _TroveListWrapper(troveList, self.troveStore, withFiles,
roleIds = roleIds)
for (job, old, new, streams) in troveWrapper:
(troveName, (oldVersion, oldFlavor),
(newVersion, newFlavor), absolute) = job
# make sure we haven't already generated this changeset; since
# troves can be included from other troves we could try
# to generate quite a few duplicates
if job in dupFilter:
continue
else:
dupFilter.add(job)
done = False
if not newVersion:
if oldVersion.getHost() not in self.serverNameList:
externalTroveList.append((troveName,
(oldVersion, oldFlavor),
(None, None), absolute))
else:
# remove this trove and any trove contained in it
cs.oldTrove(troveName, oldVersion, oldFlavor)
for (name, version, flavor) in \
old.iterTroveList(strongRefs=True):
troveWrapper.append((name, (version, flavor),
(None, None), absolute),
False)
done = True
elif (newVersion.getHost() not in self.serverNameList
or (oldVersion and
oldVersion.getHost() not in self.serverNameList)):
# don't try to make changesets between repositories; the
# client can do that itself
# we don't generate chagnesets between removed and
# present troves; that's up to the client
externalTroveList.append((troveName, (oldVersion, oldFlavor),
(newVersion, newFlavor), absolute))
done = True
elif (oldVersion and old.type() == trove.TROVE_TYPE_REMOVED):
removedTroveList.append((troveName, (oldVersion, oldFlavor),
(newVersion, newFlavor), absolute))
done = True
if done:
if not recurse:
yield (cs, externalTroveList, externalFileList,
removedTroveList)
cs = changeset.ChangeSet()
externalTroveList = []
externalFileList = []
removedTroveList = []
continue
(troveChgSet, filesNeeded, pkgsNeeded) = \
new.diff(old, absolute = absolute)
if recurse:
for refJob in pkgsNeeded:
refOldVersion = refJob[1][0]
refNewVersion = refJob[2][0]
if (refNewVersion and
(refNewVersion.getHost() not in self.serverNameList)
or (refOldVersion and
refOldVersion.getHost() not in self.serverNameList)
):
# don't try to make changesets between repositories; the
# client can do that itself
externalTroveList.append(refJob)
else:
troveWrapper.append(refJob, True)
cs.newTrove(troveChgSet)
if job in origTroveList and job[2][0] is not None:
# add the primary w/ timestamps on the version
try:
primary = troveChgSet.getNewNameVersionFlavor()
cs.addPrimaryTrove(*primary)
except KeyError:
# primary troves could be in the externalTroveList, in
# which case they aren't primries
pass
# sort the set of files we need into bins based on the server
# name
serverIdx = {}
getList = []
localFilesNeeded = []
for (pathId, oldFileId, oldFileVersion, newFileId, newFileVersion) in filesNeeded:
# if either the old or new file version is on a different
# repository, creating this diff is someone else's problem
if (newFileVersion.getHost() not in self.serverNameList
or (oldFileVersion and
oldFileVersion.getHost() not in self.serverNameList)):
externalFileList.append((pathId, troveName,
(oldVersion, oldFlavor, oldFileId, oldFileVersion),
(newVersion, newFlavor, newFileId, newFileVersion)))
else:
localFilesNeeded.append((pathId, oldFileId, oldFileVersion,
newFileId, newFileVersion))
if oldFileVersion:
getList.append((pathId, oldFileId, oldFileVersion))
getList.append((pathId, newFileId, newFileVersion))
# Walk this in reverse order. This may seem odd, but the
# order in the final changeset is set by sorting that happens
# in the change set object itself. The only reason we sort
# here at all is to make sure PTR file types come before the
# file they refer to. Reverse shorting makes this a bit easier.
localFilesNeeded.sort()
localFilesNeeded.reverse()
ptrTable = {}
for (pathId, oldFileId, oldFileVersion, newFileId, \
newFileVersion) in localFilesNeeded:
oldFile = None
if oldFileVersion:
#oldFile = idIdx[(pathId, oldFileId)]
oldFile = files.ThawFile(streams[oldFileId], pathId)
oldCont = None
newCont = None
#newFile = idIdx[(pathId, newFileId)]
newFile = files.ThawFile(streams[newFileId], pathId)
if mirrorMode:
(filecs, contentsHash) = changeset.fileChangeSet(pathId,
None,
newFile)
else:
(filecs, contentsHash) = changeset.fileChangeSet(pathId,
oldFile,
newFile)
cs.addFile(oldFileId, newFileId, filecs)
if (excludeCapsuleContents and new.troveInfo.capsule.type and
new.troveInfo.capsule.type()):
continue
if (not withFileContents
or (excludeAutoSource and newFile.flags.isAutoSource())
or (newFile.flags.isEncapsulatedContent()
and not newFile.flags.isCapsuleOverride())):
continue
# this test catches files which have changed from not
# config files to config files; these need to be included
# unconditionally so we always have the pristine contents
# to include in the local database
if ((mirrorMode and newFile.hasContents) or contentsHash or
(oldFile and newFile.flags.isConfig()
and not oldFile.flags.isConfig())):
if oldFileVersion and oldFile.hasContents:
oldCont = self.getFileContents(
[ (oldFileId, oldFileVersion, oldFile) ])[0]
newCont = self.getFileContents(
[ (newFileId, newFileVersion, newFile) ])[0]
(contType, cont) = changeset.fileContentsDiff(oldFile,
oldCont, newFile, newCont,
mirrorMode = mirrorMode)
# we don't let config files be ptr types; if they were
# they could be ptrs to things which aren't config files,
# which would completely hose the sort order we use. this
# could be relaxed someday to let them be ptr's to other
# config files
if not newFile.flags.isConfig() and \
contType == changeset.ChangedFileTypes.file:
contentsHash = newFile.contents.sha1()
ptr = ptrTable.get(contentsHash, None)
if ptr is not None:
contType = changeset.ChangedFileTypes.ptr
cont = filecontents.FromString(ptr)
else:
ptrTable[contentsHash] = pathId + newFileId
if not newFile.flags.isConfig() and \
contType == changeset.ChangedFileTypes.file:
cont = filecontents.CompressedFromDataStore(
self.contentsStore,
newFile.contents.sha1())
compressed = True
else:
compressed = False
# ptr entries are not compressed, whether or not they
# are config files. override the compressed rule from
# above
if contType == changeset.ChangedFileTypes.ptr:
compressed = False
cs.addFileContents(pathId, newFileId, contType, cont,
newFile.flags.isConfig(),
compressed = compressed)
if not recurse:
yield cs, externalTroveList, externalFileList, removedTroveList
cs = changeset.ChangeSet()
externalTroveList = []
externalFileList = []
removedTroveList = []
if recurse:
yield cs, externalTroveList, externalFileList, removedTroveList
class _TroveListWrapper:
def _handleJob(self, job, recursed, idx):
t = self.trvIterator.next()
if t is not None:
if self.withFiles:
t, streams = t
else:
streams = {}
if t is None:
if recursed:
# synthesize a removed trove for this missing
# trove
t = trove.Trove(job[0], job[idx][0], job[idx][1],
type=trove.TROVE_TYPE_REMOVED)
t.setIsMissing(True)
t.computeDigests()
# synthesize empty filestreams
streams = {}
else:
# drain the iterator, in order to complete
# the sql queries
for x in self.trvIterator: pass
raise errors.TroveMissing(job[0], job[idx][0])
return t, streams
def next(self):
if not self.l and self.new:
# self.l (and self.trvIterator) are empty; look to
# self.new for new jobs we need
troveList = []
for job, recursed in self.new:
# do we need the old trove?
if job[1][0] is not None:
troveList.append((job[0], job[1][0], job[1][1]))
# do we need the new trove?
if job[2][0] is not None:
troveList.append((job[0], job[2][0], job[2][1]))
# flip to the new job set and it's trove iterator, and
# reset self.new for later additions
self.trvIterator = self.troveStore.iterTroves(
troveList, withFiles = self.withFiles,
withFileStreams = self.withFiles,
permCheckFilter = self._permCheck,
hidden=True,
)
self.l = self.new
self.new = []
if self.l:
job, recursed = self.l.pop(0)
# Does it have an old job?
if job[1][0] is None:
old = None
oldStreams = {}
else:
old, oldStreams = self._handleJob(job, recursed, 1)
# Does it have a new job
if job[2][0] is None:
new = None
newStreams = {}
else:
new, newStreams = self._handleJob(job, recursed, 2)
newStreams.update(oldStreams)
return job, old, new, newStreams
else:
raise StopIteration
def _permCheck(self, cu, instanceTblName):
# returns a list of instance id's we're allowed to see
sql = """
DELETE FROM %s WHERE instanceId NOT IN
(SELECT DISTINCT ugi.instanceId
FROM %s JOIN UserGroupInstancesCache as ugi ON
%s.instanceId = ugi.instanceId
WHERE
ugi.userGroupId IN (%s))
""" % (instanceTblName, instanceTblName, instanceTblName,
",".join("%d" % x for x in self.roleIds))
cu.execute(sql, start_transaction = False)
def __iter__(self):
while True:
yield self.next()
def append(self, item, recurse):
self.new.append((item, recurse))
def __init__(self, l, troveStore, withFiles, roleIds = None):
self.trvIterator = None
self.new = [ (x, False) for x in l ]
self.l = []
self.troveStore = troveStore
self.withFiles = withFiles
self.roleIds = roleIds
|
def isSentenceCorrect(sentence):
pattern = '^[A-Z][^\?\!\.]*[!.?]{1}$'
return re.match(pattern, sentence) is not None
|
import abc
import six
import yaml
from nailgun import consts
from nailgun.errors import errors
from nailgun.expression import Expression
from nailgun.logger import logger
from nailgun import objects
from nailgun.orchestrator import deployment_serializers
from nailgun.orchestrator import tasks_templates as templates
from nailgun.settings import settings
def get_uids_for_tasks(nodes, tasks):
"""Return node uids where particular tasks should be executed
:param nodes: list of Node db objects
:param tasks: list of dicts
:returns: list of strings
"""
roles = []
for task in tasks:
# plugin tasks may store information about node
# role not only in `role` key but also in `groups`
task_role = task.get('role', task.get('groups'))
if task_role == consts.ALL_ROLES:
return get_uids_for_roles(nodes, consts.ALL_ROLES)
elif task_role == consts.MASTER_ROLE:
return [consts.MASTER_ROLE]
elif isinstance(task_role, list):
roles.extend(task_role)
# if task has 'skipped' status it is allowed that 'roles' and
# 'groups' are not be specified
elif task['type'] != consts.ORCHESTRATOR_TASK_TYPES.skipped:
logger.warn(
'Wrong roles format in task %s: either '
'`roles` or `groups` must be specified and contain '
'a list of roles or "*"',
task)
return get_uids_for_roles(nodes, roles)
def get_uids_for_roles(nodes, roles):
"""Returns list of uids for nodes that matches roles
:param nodes: list of nodes
:param roles: list of roles or consts.ALL_ROLES
:returns: list of strings
"""
uids = set()
if roles == consts.ALL_ROLES:
uids.update([n.uid for n in nodes])
elif roles == consts.MASTER_ROLE:
return [consts.MASTER_ROLE]
elif isinstance(roles, list):
for node in nodes:
if set(roles) & set(objects.Node.all_roles(node)):
uids.add(node.uid)
else:
logger.warn(
'Wrong roles format, `roles` should be a list or "*": %s',
roles)
return list(uids)
@six.add_metaclass(abc.ABCMeta)
class DeploymentHook(object):
def should_execute(self):
"""Should be used to define conditions when task should be executed."""
return True
@abc.abstractmethod
def serialize(self):
"""Serialize task in expected by orchestrator format.
This interface should return generator, because in some cases one
external task - should serialize several tasks internally.
"""
class ExpressionBasedTask(DeploymentHook):
def __init__(self, task, cluster):
self.task = task
self.cluster = cluster
@property
def _expression_context(self):
return {'cluster': self.cluster,
'settings': self.cluster.attributes.editable}
def should_execute(self):
if 'condition' not in self.task:
return True
return Expression(
self.task['condition'], self._expression_context).evaluate()
class GenericNodeHook(ExpressionBasedTask):
"""Should be used for node serialization.
"""
hook_type = abc.abstractproperty
def __init__(self, task, cluster, node):
self.node = node
super(GenericNodeHook, self).__init__(task, cluster)
class PuppetHook(GenericNodeHook):
hook_type = 'puppet'
def serialize(self):
yield templates.make_puppet_task([self.node['uid']], self.task)
class StandartConfigRolesHook(ExpressionBasedTask):
"""Role hooks that serializes task based on config file only."""
def __init__(self, task, cluster, nodes):
self.nodes = nodes
super(StandartConfigRolesHook, self).__init__(task, cluster)
def get_uids(self):
return get_uids_for_roles(self.nodes, self.task['role'])
def serialize(self):
uids = self.get_uids()
if uids:
yield templates.make_generic_task(uids, self.task)
class GenericRolesHook(StandartConfigRolesHook):
identity = abc.abstractproperty
class UploadMOSRepo(GenericRolesHook):
identity = 'upload_core_repos'
def get_uids(self):
return get_uids_for_roles(self.nodes, consts.ALL_ROLES)
def serialize(self):
uids = self.get_uids()
operating_system = self.cluster.release.operating_system
repos = objects.Attributes.merged_attrs_values(
self.cluster.attributes)['repo_setup']['repos']
if operating_system == consts.RELEASE_OS.centos:
for repo in repos:
yield templates.make_centos_repo_task(uids, repo)
yield templates.make_yum_clean(uids)
elif operating_system == consts.RELEASE_OS.ubuntu:
# NOTE(ikalnitsky):
# We have to clear /etc/apt/sources.list, because it
# has a lot of invalid repos right after provisioning
# and that lead us to deployment failures.
yield templates.make_shell_task(uids, {
'parameters': {
'cmd': '> /etc/apt/sources.list',
'timeout': 10
}})
yield templates.make_ubuntu_apt_disable_ipv6(uids)
# NOTE(kozhukalov):
# This task is to allow installing packages from
# unauthenticated repositories.
yield templates.make_ubuntu_unauth_repos_task(uids)
for repo in repos:
yield templates.make_ubuntu_sources_task(uids, repo)
if repo.get('priority'):
# do not add preferences task to task list if we can't
# complete it (e.g. can't retrieve or parse Release file)
task = templates.make_ubuntu_preferences_task(uids, repo)
if task is not None:
yield task
yield templates.make_apt_update_task(uids)
class RsyncPuppet(GenericRolesHook):
identity = 'rsync_core_puppet'
def get_uids(self):
return get_uids_for_roles(self.nodes, consts.ALL_ROLES)
def serialize(self):
src_path = self.task['parameters']['src'].format(
MASTER_IP=settings.MASTER_IP,
OPENSTACK_VERSION=self.cluster.release.version)
uids = self.get_uids()
yield templates.make_sync_scripts_task(
uids, src_path, self.task['parameters']['dst'])
class GenerateKeys(GenericRolesHook):
identity = 'generate_keys'
def serialize(self):
uids = self.get_uids()
self.task['parameters']['cmd'] = self.task['parameters']['cmd'].format(
CLUSTER_ID=self.cluster.id)
yield templates.make_shell_task(uids, self.task)
class CopyKeys(GenericRolesHook):
identity = 'copy_keys'
def serialize(self):
for file_path in self.task['parameters']['files']:
file_path['src'] = file_path['src'].format(
CLUSTER_ID=self.cluster.id)
uids = self.get_uids()
yield templates.make_generic_task(
uids, self.task)
class GenerateCephKeys(GenerateKeys):
identity = 'generate_keys_ceph'
class CopyCephKeys(CopyKeys):
identity = 'copy_keys_ceph'
class GenerateHaproxyKeys(GenericRolesHook):
identity = 'generate_haproxy_keys'
def serialize(self):
uids = self.get_uids()
self.task['parameters']['cmd'] = self.task['parameters']['cmd'].format(
CLUSTER_ID=self.cluster.id,
CN_HOSTNAME=self.cluster.attributes.editable
['public_ssl']['hostname']['value'])
yield templates.make_shell_task(uids, self.task)
class CopyHaproxyKeys(CopyKeys):
identity = 'copy_haproxy_keys'
class RestartRadosGW(GenericRolesHook):
identity = 'restart_radosgw'
def should_execute(self):
for node in self.nodes:
if 'ceph-osd' in node.all_roles:
return True
return False
class CreateVMsOnCompute(GenericRolesHook):
"""Hook that uploads info about all nodes in cluster."""
identity = 'generate_vms'
hook_type = 'puppet'
def should_execute(self):
return len(self.get_nodes()) > 0
def get_uids(self):
return [node.uid for node in self.get_nodes()]
def get_nodes(self):
return objects.Cluster.get_nodes_to_spawn_vms(self.cluster)
def serialize(self):
uids = self.get_uids()
yield templates.make_puppet_task(uids, self.task)
class UploadNodesInfo(GenericRolesHook):
"""Hook that uploads info about all nodes in cluster."""
identity = 'upload_nodes_info'
def serialize(self):
q_nodes = objects.Cluster.get_nodes_not_for_deletion(self.cluster)
# task can be executed only on deployed nodes
nodes = set(q_nodes.filter_by(status=consts.NODE_STATUSES.ready))
# add nodes scheduled for deployment since they could be filtered out
# above and task must be run also on them
nodes.update(self.nodes)
uids = [n.uid for n in nodes]
# every node must have data about every other good node in cluster
serialized_nodes = self._serialize_nodes(nodes)
data = yaml.safe_dump({
'nodes': serialized_nodes,
})
path = self.task['parameters']['path']
yield templates.make_upload_task(uids, path=path, data=data)
def _serialize_nodes(self, nodes):
serializer = deployment_serializers.get_serializer_for_cluster(
self.cluster)
net_serializer = serializer.get_net_provider_serializer(self.cluster)
serialized_nodes = serializer.node_list(nodes)
serialized_nodes = net_serializer.update_nodes_net_info(
self.cluster, serialized_nodes)
return serialized_nodes
class UpdateHosts(GenericRolesHook):
"""Updates hosts info on nodes in cluster."""
identity = 'update_hosts'
def serialize(self):
q_nodes = objects.Cluster.get_nodes_not_for_deletion(self.cluster)
# task can be executed only on deployed nodes
nodes = set(q_nodes.filter_by(status=consts.NODE_STATUSES.ready))
# add nodes scheduled for deployment since they could be filtered out
# above and task must be run also on them
nodes.update(self.nodes)
uids = [n.uid for n in nodes]
yield templates.make_puppet_task(uids, self.task)
class TaskSerializers(object):
"""Class serves as fabric for different types of task serializers."""
stage_serializers = [UploadMOSRepo, RsyncPuppet, CopyKeys, RestartRadosGW,
UploadNodesInfo, UpdateHosts, GenerateKeys,
GenerateHaproxyKeys, CopyHaproxyKeys,
GenerateCephKeys, CopyCephKeys]
deploy_serializers = [PuppetHook, CreateVMsOnCompute]
def __init__(self, stage_serializers=None, deploy_serializers=None):
"""Task serializers for stage (pre/post) are different from
serializers used for main deployment.
This should be considered as limitation of current architecture,
and will be solved in next releases.
:param stage_serializers: list of GenericRoleHook classes
:param deploy_serializers: list of GenericNodeHook classes
"""
self._stage_serializers_map = {}
self._deploy_serializers_map = {}
if stage_serializers is None:
stage_serializers = self.stage_serializers
for serializer in stage_serializers:
self.add_stage_serializer(serializer)
if deploy_serializers is None:
deploy_serializers = self.deploy_serializers
for serializer in deploy_serializers:
self.add_deploy_serializer(serializer)
def add_stage_serializer(self, serializer):
self._stage_serializers_map[serializer.identity] = serializer
def add_deploy_serializer(self, serializer):
if getattr(serializer, 'identity', None):
self._deploy_serializers_map[serializer.identity] = serializer
else:
self._deploy_serializers_map[serializer.hook_type] = serializer
def get_deploy_serializer(self, task):
if 'type' not in task:
raise errors.InvalidData('Task %s should have type', task)
if task['id'] and task['id'] in self._deploy_serializers_map:
return self._deploy_serializers_map[task['id']]
elif task['type'] in self._deploy_serializers_map:
return self._deploy_serializers_map[task['type']]
else:
# Currently we are not supporting anything except puppet as main
# deployment engine, therefore exception should be raised,
# but it should be verified by validation as well
raise errors.SerializerNotSupported(
'Serialization of type {0} not supported. Task {1}'.format(
task['type'], task))
def get_stage_serializer(self, task):
if 'id' not in task:
raise errors.InvalidData('Task %s should have id', task)
if task['id'] in self._stage_serializers_map:
return self._stage_serializers_map[task['id']]
else:
return StandartConfigRolesHook
|
import click
import sys
import time
from solar.core import actions
from solar.core import resource
from solar.core import signals
from solar.core import validation
from solar.core.resource import virtual_resource as vr
from solar import errors
from solar import events as evapi
from solar.interfaces.db import get_db
PROFILE = False
if PROFILE:
import StringIO
import cProfile
import pstats
pr = cProfile.Profile()
GIT_PUPPET_LIBS_URL = 'https://github.com/CGenie/puppet-libs-resource'
db = get_db()
@click.group()
def main():
pass
def setup_resources():
db.clear()
if PROFILE:
pr.enable()
node1, node2 = vr.create('nodes', 'templates/nodes.yaml', {})
# MARIADB
mariadb_service1 = vr.create('mariadb_service1', 'resources/mariadb_service', {
'image': 'mariadb',
'port': 3306
})[0]
signals.connect(node1, mariadb_service1)
# RABBIT
rabbitmq_service1 = vr.create('rabbitmq_service1', 'resources/rabbitmq_service/', {
'management_port': 15672,
'port': 5672,
})[0]
openstack_vhost = vr.create('openstack_vhost', 'resources/rabbitmq_vhost/', {
'vhost_name': 'openstack'
})[0]
openstack_rabbitmq_user = vr.create('openstack_rabbitmq_user', 'resources/rabbitmq_user/', {
'user_name': 'openstack',
'password': 'openstack_password'
})[0]
signals.connect(node1, rabbitmq_service1)
signals.connect(rabbitmq_service1, openstack_vhost)
signals.connect(rabbitmq_service1, openstack_rabbitmq_user)
signals.connect(openstack_vhost, openstack_rabbitmq_user, {
'vhost_name',
})
# KEYSTONE
keystone_puppet = vr.create('keystone_puppet', 'resources/keystone_puppet', {})[0]
evapi.add_dep(rabbitmq_service1.name, keystone_puppet.name, actions=('run', 'update'))
keystone_db = vr.create('keystone_db', 'resources/mariadb_db/', {
'db_name': 'keystone_db',
'login_user': 'root'
})[0]
keystone_db_user = vr.create('keystone_db_user', 'resources/mariadb_user/', {
'user_name': 'keystone',
'user_password': 'keystone',
})[0]
keystone_service_endpoint = vr.create('keystone_service_endpoint', 'resources/keystone_service_endpoint', {
'endpoint_name': 'keystone',
'adminurl': 'http://{{admin_ip}}:{{admin_port}}/v2.0',
'internalurl': 'http://{{internal_ip}}:{{internal_port}}/v2.0',
'publicurl': 'http://{{public_ip}}:{{public_port}}/v2.0',
'description': 'OpenStack Identity Service',
'type': 'identity'
})[0]
admin_tenant = vr.create('admin_tenant', 'resources/keystone_tenant', {
'tenant_name': 'admin'
})[0]
admin_user = vr.create('admin_user', 'resources/keystone_user', {
'user_name': 'admin',
'user_password': 'admin'
})[0]
admin_role = vr.create('admin_role', 'resources/keystone_role', {
'role_name': 'admin'
})[0]
services_tenant = vr.create('services_tenant', 'resources/keystone_tenant', {
'tenant_name': 'services'
})[0]
admin_role_services = vr.create('admin_role_services', 'resources/keystone_role', {
'role_name': 'admin'
})[0]
signals.connect(node1, keystone_db)
signals.connect(node1, keystone_db_user)
signals.connect(node1, keystone_puppet)
signals.connect(mariadb_service1, keystone_db, {
'port': 'login_port',
'root_user': 'login_user',
'root_password': 'login_password',
'ip' : 'db_host',
})
signals.connect(keystone_db, keystone_db_user, {
'db_name',
'login_port',
'login_user',
'login_password',
'db_host'
})
signals.connect(node1, keystone_service_endpoint)
signals.connect(keystone_puppet, keystone_service_endpoint, {
'admin_token': 'admin_token',
'admin_port': ['admin_port', 'keystone_admin_port'],
'ip': ['keystone_host', 'admin_ip', 'internal_ip', 'public_ip'],
'port': ['internal_port', 'public_port'],
})
signals.connect(keystone_puppet, admin_tenant)
signals.connect(keystone_puppet, admin_tenant, {
'admin_port': 'keystone_port',
'ip': 'keystone_host'
})
signals.connect(admin_tenant, admin_user)
signals.connect(admin_user, admin_role)
signals.connect(admin_user, admin_role_services)
signals.connect(services_tenant, admin_role_services, { 'tenant_name' })
signals.connect(keystone_puppet, services_tenant)
signals.connect(keystone_puppet, services_tenant, {
'admin_port': 'keystone_port',
'ip': 'keystone_host'
})
signals.connect(keystone_db, keystone_puppet, {
'db_name',
})
signals.connect(keystone_db_user, keystone_puppet, {
'user_name': 'db_user',
'user_password': 'db_password',
'db_host' : 'db_host'
})
# OPENRC
openrc = vr.create('openrc_file', 'resources/openrc_file', {})[0]
signals.connect(node1, openrc)
signals.connect(keystone_puppet, openrc, {'ip': 'keystone_host', 'admin_port':'keystone_port'})
signals.connect(admin_user, openrc, {'user_name': 'user_name','user_password':'password', 'tenant_name': 'tenant'})
# NEUTRON
# Deploy chain neutron -> (plugins) -> neutron_server -> ( agents )
neutron_puppet = vr.create('neutron_puppet', 'resources/neutron_puppet', {
'core_plugin': 'neutron.plugins.ml2.plugin.Ml2Plugin'
})[0]
signals.connect(node1, neutron_puppet)
signals.connect(rabbitmq_service1, neutron_puppet, {
'ip': 'rabbit_host',
'port': 'rabbit_port'
})
signals.connect(openstack_rabbitmq_user, neutron_puppet, {
'user_name': 'rabbit_user',
'password': 'rabbit_password'})
signals.connect(openstack_vhost, neutron_puppet, {
'vhost_name': 'rabbit_virtual_host'})
# NEUTRON API (SERVER)
neutron_server_puppet = vr.create('neutron_server_puppet', 'resources/neutron_server_puppet', {
'sync_db': True,
})[0]
neutron_db = vr.create('neutron_db', 'resources/mariadb_db/', {
'db_name': 'neutron_db', 'login_user': 'root'})[0]
neutron_db_user = vr.create('neutron_db_user', 'resources/mariadb_user/', {
'user_name': 'neutron', 'user_password': 'neutron', 'login_user': 'root'})[0]
neutron_keystone_user = vr.create('neutron_keystone_user', 'resources/keystone_user', {
'user_name': 'neutron',
'user_password': 'neutron'
})[0]
neutron_keystone_role = vr.create('neutron_keystone_role', 'resources/keystone_role', {
'role_name': 'admin'
})[0]
neutron_keystone_service_endpoint = vr.create('neutron_keystone_service_endpoint', 'resources/keystone_service_endpoint', {
'endpoint_name': 'neutron',
'adminurl': 'http://{{admin_ip}}:{{admin_port}}',
'internalurl': 'http://{{internal_ip}}:{{internal_port}}',
'publicurl': 'http://{{public_ip}}:{{public_port}}',
'description': 'OpenStack Network Service',
'type': 'network'
})[0]
signals.connect(node1, neutron_db)
signals.connect(node1, neutron_db_user)
signals.connect(mariadb_service1, neutron_db, {
'port': 'login_port',
'root_password': 'login_password',
'root_user': 'login_user',
'ip' : 'db_host'})
signals.connect(mariadb_service1, neutron_db_user, {'port': 'login_port', 'root_password': 'login_password'})
signals.connect(neutron_db, neutron_db_user, {'db_name', 'db_host'})
signals.connect(neutron_db_user, neutron_server_puppet, {
'user_name':'db_user',
'db_name':'db_name',
'user_password':'db_password',
'db_host' : 'db_host'})
signals.connect(node1, neutron_server_puppet)
signals.connect(admin_user, neutron_server_puppet, {
'user_name': 'auth_user',
'user_password': 'auth_password',
'tenant_name': 'auth_tenant'
})
signals.connect(keystone_puppet, neutron_server_puppet, {
'ip': 'auth_host',
'port': 'auth_port'
})
signals.connect(services_tenant, neutron_keystone_user)
signals.connect(neutron_keystone_user, neutron_keystone_role)
signals.connect(keystone_puppet, neutron_keystone_service_endpoint, {
'ip': ['ip', 'keystone_host'],
'ssh_key': 'ssh_key',
'ssh_user': 'ssh_user',
'admin_port': 'keystone_admin_port',
'admin_token': 'admin_token',
})
signals.connect(neutron_puppet, neutron_keystone_service_endpoint, {
'ip': ['admin_ip', 'internal_ip', 'public_ip'],
'bind_port': ['admin_port', 'internal_port', 'public_port'],
})
# NEUTRON ML2 PLUGIN & ML2-OVS AGENT WITH GRE
neutron_plugins_ml2 = vr.create('neutron_plugins_ml2', 'resources/neutron_plugins_ml2_puppet', {})[0]
signals.connect(node1, neutron_plugins_ml2)
neutron_agents_ml2 = vr.create('neutron_agents_ml2', 'resources/neutron_agents_ml2_ovs_puppet', {
# TODO(bogdando) these should come from the node network resource
'enable_tunneling': True,
'tunnel_types': ['gre'],
'local_ip': '10.1.0.13' # should be the IP addr of the br-mesh int.
})[0]
signals.connect(node1, neutron_agents_ml2)
# NEUTRON DHCP, L3, metadata agents
neutron_agents_dhcp = vr.create('neutron_agents_dhcp', 'resources/neutron_agents_dhcp_puppet', {})[0]
signals.connect(node1, neutron_agents_dhcp)
neutron_agents_l3 = vr.create('neutron_agents_l3', 'resources/neutron_agents_l3_puppet', {
# TODO(bogdando) these should come from the node network resource
'metadata_port': 8775,
'external_network_bridge': 'br-floating',
})[0]
signals.connect(node1, neutron_agents_l3)
neutron_agents_metadata = vr.create('neutron_agents_metadata', 'resources/neutron_agents_metadata_puppet', {
'shared_secret': 'secret',
})[0]
signals.connect(node1, neutron_agents_metadata)
signals.connect(neutron_server_puppet, neutron_agents_metadata, {
'auth_host', 'auth_port', 'auth_password',
'auth_tenant', 'auth_user',
})
# NEUTRON FOR COMPUTE (node2)
# Deploy chain neutron -> (plugins) -> ( agents )
neutron_puppet2 = vr.create('neutron_puppet2', 'resources/neutron_puppet', {})[0]
signals.connect(node2, neutron_puppet2)
signals.connect(neutron_puppet, neutron_puppet2, {
'rabbit_host', 'rabbit_port',
'rabbit_user', 'rabbit_password',
'rabbit_virtual_host',
'package_ensure', 'core_plugin',
})
# NEUTRON OVS PLUGIN & AGENT WITH GRE FOR COMPUTE (node2)
neutron_plugins_ml22 = vr.create('neutron_plugins_ml22', 'resources/neutron_plugins_ml2_puppet', {})[0]
signals.connect(node2, neutron_plugins_ml22)
neutron_agents_ml22 = vr.create('neutron_agents_ml22', 'resources/neutron_agents_ml2_ovs_puppet', {
# TODO(bogdando) these should come from the node network resource
'enable_tunneling': True,
'tunnel_types': ['gre'],
'local_ip': '10.1.0.14' # Should be the IP addr of the br-mesh int.
})[0]
signals.connect(node2, neutron_agents_ml22)
# CINDER
cinder_puppet = vr.create('cinder_puppet', 'resources/cinder_puppet', {})[0]
cinder_db = vr.create('cinder_db', 'resources/mariadb_db/', {
'db_name': 'cinder_db', 'login_user': 'root'})[0]
cinder_db_user = vr.create('cinder_db_user', 'resources/mariadb_user/', {
'user_name': 'cinder', 'user_password': 'cinder', 'login_user': 'root'})[0]
cinder_keystone_user = vr.create('cinder_keystone_user', 'resources/keystone_user', {
'user_name': 'cinder', 'user_password': 'cinder'})[0]
cinder_keystone_role = vr.create('cinder_keystone_role', 'resources/keystone_role', {
'role_name': 'admin'})[0]
cinder_keystone_service_endpoint = vr.create(
'cinder_keystone_service_endpoint',
'resources/keystone_service_endpoint', {
'endpoint_name': 'cinder',
'adminurl': 'http://{{admin_ip}}:{{admin_port}}/v2/%(tenant_id)s',
'internalurl': 'http://{{internal_ip}}:{{internal_port}}/v2/%(tenant_id)s',
'publicurl': 'http://{{public_ip}}:{{public_port}}/v2/%(tenant_id)s',
'description': 'OpenStack Block Storage Service', 'type': 'volumev2'})[0]
signals.connect(node1, cinder_puppet)
signals.connect(node1, cinder_db)
signals.connect(node1, cinder_db_user)
signals.connect(rabbitmq_service1, cinder_puppet, {'ip': 'rabbit_host', 'port': 'rabbit_port'})
signals.connect(admin_user, cinder_puppet, {'user_name': 'keystone_user', 'user_password': 'keystone_password', 'tenant_name': 'keystone_tenant'}) #?
signals.connect(openstack_vhost, cinder_puppet, {'vhost_name': 'rabbit_virtual_host'})
signals.connect(openstack_rabbitmq_user, cinder_puppet, {'user_name': 'rabbit_userid', 'password': 'rabbit_password'})
signals.connect(mariadb_service1, cinder_db, {
'port': 'login_port',
'root_password': 'login_password',
'root_user': 'login_user',
'ip' : 'db_host'})
signals.connect(mariadb_service1, cinder_db_user, {'port': 'login_port', 'root_password': 'login_password'})
signals.connect(cinder_db, cinder_db_user, {'db_name', 'db_host'})
signals.connect(cinder_db_user, cinder_puppet, {
'user_name':'db_user',
'db_name':'db_name',
'user_password':'db_password',
'db_host' : 'db_host'})
signals.connect(keystone_puppet, cinder_puppet, {'ip': 'keystone_host', 'admin_port': 'keystone_port'}) #or non admin port?
signals.connect(services_tenant, cinder_keystone_user)
signals.connect(cinder_keystone_user, cinder_keystone_role)
signals.connect(cinder_keystone_user, cinder_puppet, {'user_name': 'keystone_user', 'tenant_name': 'keystone_tenant', 'user_password': 'keystone_password'})
signals.connect(mariadb_service1, cinder_puppet, {'ip':'ip'})
signals.connect(cinder_puppet, cinder_keystone_service_endpoint, {
'ssh_key': 'ssh_key', 'ssh_user': 'ssh_user',
'ip': ['ip', 'keystone_host', 'admin_ip', 'internal_ip', 'public_ip'],
'port': ['admin_port', 'internal_port', 'public_port'],})
signals.connect(keystone_puppet, cinder_keystone_service_endpoint, {
'admin_port': 'keystone_admin_port', 'admin_token': 'admin_token'})
# CINDER GLANCE
# Deploy chain: cinder_puppet -> cinder_glance -> ( cinder_api, cinder_scheduler, cinder_volume )
cinder_glance_puppet = vr.create('cinder_glance_puppet', 'resources/cinder_glance_puppet', {})[0]
signals.connect(node1, cinder_glance_puppet)
# CINDER API
cinder_api_puppet = vr.create('cinder_api_puppet', 'resources/cinder_api_puppet', {})[0]
signals.connect(node1, cinder_api_puppet)
signals.connect(cinder_puppet, cinder_api_puppet, {
'keystone_password', 'keystone_tenant', 'keystone_user'})
signals.connect(cinder_puppet, cinder_api_puppet, {
'keystone_host': 'keystone_auth_host',
'keystone_port': 'keystone_auth_port'})
evapi.add_react(cinder_puppet.name, cinder_api_puppet.name, actions=('update',))
# CINDER SCHEDULER
cinder_scheduler_puppet = vr.create('cinder_scheduler_puppet', 'resources/cinder_scheduler_puppet', {})[0]
signals.connect(node1, cinder_scheduler_puppet)
signals.connect(cinder_puppet, cinder_scheduler_puppet)
evapi.add_react(cinder_puppet.name, cinder_scheduler_puppet.name, actions=('update',))
# CINDER VOLUME
cinder_volume_puppet = vr.create('cinder_volume_puppet', 'resources/cinder_volume_puppet', {})[0]
signals.connect(node1, cinder_volume_puppet)
signals.connect(cinder_puppet, cinder_volume_puppet)
evapi.add_react(cinder_puppet.name, cinder_volume_puppet.name, actions=('update',))
# NOVA
nova_puppet = vr.create('nova_puppet', 'resources/nova_puppet', {})[0]
nova_db = vr.create('nova_db', 'resources/mariadb_db/', {
'db_name': 'nova_db',
'login_user': 'root'})[0]
nova_db_user = vr.create('nova_db_user', 'resources/mariadb_user/', {
'user_name': 'nova',
'user_password': 'nova',
'login_user': 'root'})[0]
nova_keystone_user = vr.create('nova_keystone_user', 'resources/keystone_user', {
'user_name': 'nova',
'user_password': 'nova'})[0]
nova_keystone_role = vr.create('nova_keystone_role', 'resources/keystone_role', {
'role_name': 'admin'})[0]
nova_keystone_service_endpoint = vr.create('nova_keystone_service_endpoint', 'resources/keystone_service_endpoint', {
'endpoint_name': 'nova',
'adminurl': 'http://{{admin_ip}}:{{admin_port}}/v2/%(tenant_id)s',
'internalurl': 'http://{{internal_ip}}:{{internal_port}}/v2/%(tenant_id)s',
'publicurl': 'http://{{public_ip}}:{{public_port}}/v2/%(tenant_id)s',
'description': 'OpenStack Compute Service',
'type': 'compute'})[0]
signals.connect(node1, nova_puppet)
signals.connect(node1, nova_db)
signals.connect(node1, nova_db_user)
signals.connect(mariadb_service1, nova_db, {
'port': 'login_port',
'root_password': 'login_password',
'root_user': 'login_user',
'ip' : 'db_host'})
signals.connect(mariadb_service1, nova_db_user, {
'port': 'login_port',
'root_password': 'login_password'})
signals.connect(admin_user, nova_puppet, {'user_name': 'keystone_user', 'user_password': 'keystone_password', 'tenant_name': 'keystone_tenant'}) #?
signals.connect(openstack_vhost, nova_puppet, {'vhost_name': 'rabbit_virtual_host'})
signals.connect(nova_db, nova_db_user, {'db_name', 'db_host'})
signals.connect(services_tenant, nova_keystone_user)
signals.connect(nova_keystone_user, nova_keystone_role)
signals.connect(keystone_puppet, nova_puppet, {
'ip': 'keystone_host',
'admin_port': 'keystone_port'})
signals.connect(nova_keystone_user, nova_puppet, {
'user_name': 'keystone_user',
'tenant_name': 'keystone_tenant',
'user_password': 'keystone_password'})
signals.connect(rabbitmq_service1, nova_puppet, {
'ip': 'rabbit_host', 'port': 'rabbit_port'})
signals.connect(openstack_rabbitmq_user, nova_puppet, {
'user_name': 'rabbit_userid',
'password': 'rabbit_password'})
signals.connect(keystone_puppet, nova_keystone_service_endpoint, {
'ip': 'keystone_host',
'admin_port': 'keystone_admin_port',
'admin_token': 'admin_token'})
signals.connect(mariadb_service1, nova_puppet, {
'ip':'db_host'})
signals.connect(nova_db_user, nova_puppet, {
'user_name':'db_user',
'db_name':'db_name',
'user_password':'db_password',
'db_host' : 'db_host'})
signals.connect(nova_puppet, nova_keystone_service_endpoint, {
'ip': ['ip', 'keystone_host', 'public_ip', 'internal_ip', 'admin_ip'],
'port': ['admin_port', 'internal_port', 'public_port'],
'ssh_key': 'ssh_key',
'ssh_user': 'ssh_user'})
# NOVA API
nova_api_puppet = vr.create('nova_api_puppet', 'resources/nova_api_puppet', {})[0]
signals.connect(node1, nova_api_puppet)
signals.connect(nova_puppet, nova_api_puppet, {
'keystone_tenant': 'admin_tenant_name',
'keystone_user': 'admin_user',
'keystone_password': 'admin_password',
'keystone_host': 'auth_host',
'keystone_port': 'auth_port'})
signals.connect(nova_api_puppet, neutron_agents_metadata, {'ip': 'metadata_ip'})
# NOVA CONDUCTOR
nova_conductor_puppet = vr.create('nova_conductor_puppet', 'resources/nova_conductor_puppet', {})[0]
signals.connect(node1, nova_conductor_puppet)
signals.connect(nova_puppet, nova_conductor_puppet)
# NOVA SCHEDULER
# NOTE(bogdando) Generic service is used. Package and service names for Ubuntu case
# come from https://github.com/openstack/puppet-nova/blob/5.1.0/manifests/params.pp
nova_scheduler_puppet = vr.create('nova_scheduler_puppet', 'resources/nova_generic_service_puppet', {
'title' : 'scheduler', 'package_name': 'nova-scheduler', 'service_name': 'nova-scheduler',
})[0]
signals.connect(node1, nova_scheduler_puppet)
# NOVA COMPUTE
# Deploy chain (nova, node_networking(TODO)) -> (nova_compute_libvirt, nova_neutron) -> nova_compute
nova_compute_puppet = vr.create('nova_compute_puppet', 'resources/nova_compute_puppet', {})[0]
# TODO (bogdando) figure out how to use it for multiple glance api servers
nova_puppet2 = vr.create('nova_puppet2', 'resources/nova_puppet', {
'glance_api_servers': '{{glance_api_servers_host}}:{{glance_api_servers_port}}'
})[0]
signals.connect(nova_puppet, nova_puppet2, {
'ensure_package', 'rabbit_host',
'rabbit_password', 'rabbit_port', 'rabbit_userid',
'rabbit_virtual_host', 'db_user', 'db_password',
'db_name', 'db_host', 'keystone_password',
'keystone_port', 'keystone_host', 'keystone_tenant',
'keystone_user',
})
# TODO(bogdando): Make a connection for nova_puppet2.glance_api_servers = "glance_api_puppet.ip:glance_api_puppet.bind_port"
signals.connect(node2, nova_puppet2)
signals.connect(node2, nova_compute_puppet)
# NOVA COMPUTE LIBVIRT, NOVA_NEUTRON
# NOTE(bogdando): changes nova config, so should notify nova compute service
nova_compute_libvirt_puppet = vr.create('nova_compute_libvirt_puppet', 'resources/nova_compute_libvirt_puppet', {})[0]
signals.connect(node2, nova_compute_libvirt_puppet)
# compute configuration for neutron, use http auth/endpoint protocols, keystone v2 auth hardcoded for the resource
nova_neutron_puppet = vr.create('nova_neutron_puppet', 'resources/nova_neutron_puppet', {})[0]
signals.connect(node2, nova_neutron_puppet)
signals.connect(neutron_server_puppet, nova_neutron_puppet, {
'auth_password': 'neutron_admin_password',
'auth_user': 'neutron_admin_username',
'auth_type': 'neutron_auth_strategy',
'auth_host': 'auth_host', 'auth_port': 'auth_port',
'auth_protocol': 'auth_protocol',
})
signals.connect(neutron_keystone_service_endpoint, nova_neutron_puppet, {
'internal_ip':'neutron_endpoint_host',
'internal_port':'neutron_endpoint_port',
})
# signals.connect(keystone_puppet, nova_network_puppet, {'ip': 'keystone_host', 'port': 'keystone_port'})
# signals.connect(keystone_puppet, nova_keystone_service_endpoint, {'ip': 'keystone_host', 'admin_port': 'keystone_port', 'admin_token': 'admin_token'})
# signals.connect(rabbitmq_service1, nova_network_puppet, {'ip': 'rabbitmq_host', 'port': 'rabbitmq_port'})
# GLANCE (base and API)
glance_api_puppet = vr.create('glance_api_puppet', 'resources/glance_puppet', {})[0]
glance_db_user = vr.create('glance_db_user', 'resources/mariadb_user/', {
'user_name': 'glance', 'user_password': 'glance', 'login_user': 'root'})[0]
glance_db = vr.create('glance_db', 'resources/mariadb_db/', {
'db_name': 'glance', 'login_user': 'root'})[0]
glance_keystone_user = vr.create('glance_keystone_user', 'resources/keystone_user', {
'user_name': 'glance', 'user_password': 'glance123'})[0]
glance_keystone_role = vr.create('glance_keystone_role', 'resources/keystone_role', {
'role_name': 'admin'})[0]
glance_keystone_service_endpoint = vr.create(
'glance_keystone_service_endpoint',
'resources/keystone_service_endpoint', {
'endpoint_name': 'glance',
'adminurl': 'http://{{admin_ip}}:{{admin_port}}',
'internalurl': 'http://{{internal_ip}}:{{internal_port}}',
'publicurl': 'http://{{public_ip}}:{{public_port}}',
'description': 'OpenStack Image Service', 'type': 'image'})[0]
signals.connect(node1, glance_api_puppet)
signals.connect(node1, glance_db)
signals.connect(node1, glance_db_user)
signals.connect(admin_user, glance_api_puppet, {
'user_name': 'keystone_user', 'user_password': 'keystone_password',
'tenant_name': 'keystone_tenant'}) #?
signals.connect(mariadb_service1, glance_db, {
'port': 'login_port',
'root_password': 'login_password',
'root_user': 'login_user',
'ip' : 'db_host'})
signals.connect(mariadb_service1, glance_db_user, {'port': 'login_port', 'root_password': 'login_password'})
signals.connect(glance_db, glance_db_user, {'db_name', 'db_host'})
signals.connect(glance_db_user, glance_api_puppet, {
'user_name':'db_user',
'db_name':'db_name',
'user_password':'db_password',
'db_host' : 'db_host'})
signals.connect(keystone_puppet, glance_api_puppet, {'ip': 'keystone_host', 'admin_port': 'keystone_port'}) #or non admin port?
signals.connect(services_tenant, glance_keystone_user)
signals.connect(glance_keystone_user, glance_keystone_role)
signals.connect(glance_keystone_user, glance_api_puppet, {
'user_name': 'keystone_user', 'tenant_name': 'keystone_tenant',
'user_password': 'keystone_password'})
signals.connect(mariadb_service1, glance_api_puppet, {'ip':'ip'})
signals.connect(glance_api_puppet, glance_keystone_service_endpoint, {
'ssh_key': 'ssh_key', 'ssh_user': 'ssh_user',
'ip': ['ip', 'keystone_host', 'admin_ip', 'internal_ip', 'public_ip'],
'bind_port': ['admin_port', 'internal_port', 'public_port'],})
signals.connect(keystone_puppet, glance_keystone_service_endpoint, {
'admin_port': 'keystone_admin_port', 'admin_token': 'admin_token'})
# GLANCE REGISTRY
glance_registry_puppet = vr.create('glance_registry_puppet', 'resources/glance_registry_puppet', {})[0]
signals.connect(node1, glance_registry_puppet)
signals.connect(glance_api_puppet, glance_registry_puppet)
# API and registry should not listen same ports
# should not use the same log destination and a pipeline,
# so disconnect them and restore the defaults
signals.disconnect_receiver_by_input(glance_registry_puppet, 'bind_port')
signals.disconnect_receiver_by_input(glance_registry_puppet, 'log_file')
signals.disconnect_receiver_by_input(glance_registry_puppet, 'pipeline')
glance_registry_puppet.update({
'bind_port': 9191,
'log_file': '/var/log/glance/registry.log',
'pipeline': 'keystone',
})
# Update glance_api_service for cinder
signals.connect(glance_api_puppet, cinder_glance_puppet, {
'ip': 'glance_api_servers_host',
'bind_port': 'glance_api_servers_port'
})
# Update glance_api_service for nova compute
signals.connect(glance_api_puppet, nova_puppet2, {
'ip': 'glance_api_servers_host',
'bind_port': 'glance_api_servers_port'
})
if PROFILE:
pr.disable()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print s.getvalue()
sys.exit(0)
has_errors = False
for r in locals().values():
if not isinstance(r, resource.Resource):
continue
print 'Validating {}'.format(r.name)
errors = validation.validate_resource(r)
if errors:
has_errors = True
print 'ERROR: %s: %s' % (r.name, errors)
if has_errors:
sys.exit(1)
resources_to_run = [
'rabbitmq_service1',
'openstack_vhost',
'openstack_rabbitmq_user',
'mariadb_service1',
'keystone_db',
'keystone_db_user',
'keystone_puppet',
'openrc_file',
'admin_tenant',
'admin_user',
'admin_role',
'keystone_service_endpoint',
'services_tenant',
'neutron_db',
'neutron_db_user',
'neutron_keystone_user',
'neutron_keystone_role',
'neutron_puppet',
'neutron_keystone_service_endpoint',
'neutron_plugins_ml2',
'neutron_server_puppet',
'neutron_agents_ml2',
'neutron_agents_dhcp',
'neutron_agents_l3',
'neutron_agents_metadata',
'cinder_db',
'cinder_db_user',
'cinder_keystone_user',
'cinder_keystone_role',
'cinder_puppet',
'cinder_keystone_service_endpoint',
'cinder_glance_puppet',
'cinder_api_puppet',
'cinder_scheduler_puppet',
'cinder_volume_puppet',
'nova_db',
'nova_db_user',
'nova_keystone_user',
'nova_keystone_role',
'nova_puppet',
'nova_keystone_service_endpoint',
'nova_api_puppet',
'nova_conductor_puppet',
'nova_scheduler_puppet',
'glance_db',
'glance_db_user',
'glance_keystone_user',
'glance_keystone_role',
'glance_keystone_service_endpoint',
'glance_api_puppet',
'glance_registry_puppet',
'nova_puppet2',
'nova_compute_libvirt_puppet',
'nova_neutron_puppet',
'nova_compute_puppet',
'neutron_puppet2',
'neutron_plugins_ml22',
'neutron_agents_ml22',
]
@click.command()
def deploy():
setup_resources()
# run
resources = resource.load_all()
resources = {r.name: r for r in resources}
for name in resources_to_run:
try:
actions.resource_action(resources[name], 'run')
except errors.SolarError as e:
print 'WARNING: %s' % str(e)
raise
time.sleep(10)
@click.command()
def undeploy():
resources = resource.load_all()
resources = {r.name: r for r in resources}
for name in reversed(resources_to_run):
try:
actions.resource_action(resources[name], 'remove')
except errors.SolarError as e:
print 'WARNING: %s' % str(e)
db.clear()
main.add_command(deploy)
main.add_command(undeploy)
if __name__ == '__main__':
main()
|
from __future__ import annotations
from typing import *
import asyncio
import contextlib
import datetime
import logging
import os
import os.path
import pathlib
import resource
import signal
import socket
import sys
import tempfile
import uuid
import uvloop
import click
import setproctitle
from . import logsetup
logsetup.early_setup()
from edb import buildmeta
from edb.common import exceptions
from edb.common import devmode
from edb.common import signalctl
from . import args as srvargs
from . import daemon
from . import defines
from . import pgconnparams
from . import pgcluster
if TYPE_CHECKING:
from . import server
else:
# Import server lazily to make sure that most of imports happen
# under coverage (if we're testing with it). Otherwise
# coverage will fail to detect that "import edb..." lines
# actually were run.
server = None
logger = logging.getLogger('edb.server')
_server_initialized = False
def abort(msg, *args, exit_code=1) -> NoReturn:
logger.critical(msg, *args)
sys.exit(exit_code)
@contextlib.contextmanager
def _ensure_runstate_dir(
default_runstate_dir: Optional[pathlib.Path],
specified_runstate_dir: Optional[pathlib.Path]
) -> Iterator[pathlib.Path]:
temp_runstate_dir = None
if specified_runstate_dir is None:
if default_runstate_dir is None:
temp_runstate_dir = tempfile.TemporaryDirectory(prefix='edbrun-')
runstate_parent = pathlib.Path(temp_runstate_dir.name)
else:
runstate_parent = default_runstate_dir
try:
runstate_dir = buildmeta.get_runstate_path(runstate_parent)
except buildmeta.MetadataError:
abort(
f'cannot determine the runstate directory location; '
f'please use --runstate-dir to specify the correct location')
else:
runstate_dir = specified_runstate_dir
runstate_dir = pathlib.Path(runstate_dir)
if not runstate_dir.exists():
if not runstate_dir.parent.exists():
abort(
f'cannot create the runstate directory: '
f'{str(runstate_dir.parent)!r} does not exist; please use '
f'--runstate-dir to specify the correct location')
try:
runstate_dir.mkdir()
except PermissionError as ex:
abort(
f'cannot create the runstate directory: '
f'{ex!s}; please use --runstate-dir to specify '
f'the correct location')
if not os.path.isdir(runstate_dir):
abort(f'{str(runstate_dir)!r} is not a directory; please use '
f'--runstate-dir to specify the correct location')
try:
yield runstate_dir
finally:
if temp_runstate_dir is not None:
temp_runstate_dir.cleanup()
@contextlib.contextmanager
def _internal_state_dir(runstate_dir):
try:
with tempfile.TemporaryDirectory(prefix="", dir=runstate_dir) as td:
yield td
except PermissionError as ex:
abort(f'cannot write to the runstate directory: '
f'{ex!s}; please fix the permissions or use '
f'--runstate-dir to specify the correct location')
async def _init_cluster(cluster, args: srvargs.ServerConfig) -> bool:
from edb.server import bootstrap
need_restart = await bootstrap.ensure_bootstrapped(cluster, args)
global _server_initialized
_server_initialized = True
return need_restart
def _sd_notify(message):
notify_socket = os.environ.get('NOTIFY_SOCKET')
if not notify_socket:
return
if notify_socket[0] == '@':
notify_socket = '\0' + notify_socket[1:]
sd_sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
try:
sd_sock.connect(notify_socket)
sd_sock.sendall(message.encode())
except Exception as e:
logger.info('Could not send systemd notification: %s', e)
finally:
sd_sock.close()
def _init_parsers():
# Initialize all parsers, rebuilding grammars if
# necessary. Do it earlier than later so that we don't
# end up in a situation where all our compiler processes
# are building parsers in parallel.
from edb.edgeql import parser as ql_parser
ql_parser.preload(allow_rebuild=devmode.is_in_dev_mode(), paralellize=True)
async def _run_server(
cluster,
args: srvargs.ServerConfig,
runstate_dir,
internal_runstate_dir,
*,
do_setproctitle: bool,
new_instance: bool,
):
with signalctl.SignalController(signal.SIGINT, signal.SIGTERM) as sc:
ss = server.Server(
cluster=cluster,
runstate_dir=runstate_dir,
internal_runstate_dir=internal_runstate_dir,
max_backend_connections=args.max_backend_connections,
compiler_pool_size=args.compiler_pool_size,
compiler_pool_mode=args.compiler_pool_mode,
nethosts=args.bind_addresses,
netport=args.port,
auto_shutdown_after=args.auto_shutdown_after,
echo_runtime_info=args.echo_runtime_info,
status_sinks=args.status_sinks,
startup_script=args.startup_script,
binary_endpoint_security=args.binary_endpoint_security,
http_endpoint_security=args.http_endpoint_security,
backend_adaptive_ha=args.backend_adaptive_ha,
default_auth_method=args.default_auth_method,
testmode=args.testmode,
new_instance=new_instance,
)
await sc.wait_for(ss.init())
tls_cert_newly_generated = False
if args.tls_cert_mode is srvargs.ServerTlsCertMode.SelfSigned:
assert args.tls_cert_file is not None
if not args.tls_cert_file.exists():
assert args.tls_key_file is not None
_generate_cert(
args.tls_cert_file,
args.tls_key_file,
ss.get_listen_hosts(),
)
tls_cert_newly_generated = True
ss.init_tls(
args.tls_cert_file, args.tls_key_file, tls_cert_newly_generated)
if args.bootstrap_only:
if args.startup_script and new_instance:
await sc.wait_for(ss.run_startup_script_and_exit())
return
try:
await sc.wait_for(ss.start())
if do_setproctitle:
setproctitle.setproctitle(
f"edgedb-server-{ss.get_listen_port()}"
)
# Notify systemd that we've started up.
_sd_notify('READY=1')
try:
await sc.wait_for(ss.serve_forever())
except signalctl.SignalError as e:
logger.info('Received signal: %s.', e.signo)
finally:
_sd_notify('STOPPING=1')
logger.info('Shutting down.')
await sc.wait_for(ss.stop())
def _generate_cert(
tls_cert_file: pathlib.Path,
tls_key_file: pathlib.Path,
listen_hosts: Iterable[str]
) -> None:
logger.info(f'generating self-signed TLS certificate in "{tls_cert_file}"')
from cryptography import x509
from cryptography.hazmat import backends
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509 import oid
backend = backends.default_backend()
private_key = rsa.generate_private_key(
public_exponent=65537, key_size=2048, backend=backend
)
subject = x509.Name(
[x509.NameAttribute(oid.NameOID.COMMON_NAME, "EdgeDB Server")]
)
certificate = (
x509.CertificateBuilder()
.subject_name(subject)
.public_key(private_key.public_key())
.serial_number(int(uuid.uuid4()))
.issuer_name(subject)
.not_valid_before(
datetime.datetime.today() - datetime.timedelta(days=1)
)
.not_valid_after(
datetime.datetime.today() + datetime.timedelta(weeks=1000)
)
.add_extension(
x509.SubjectAlternativeName(
[
x509.DNSName(name) for name in listen_hosts
if name not in {'0.0.0.0', '::'}
]
),
critical=False,
)
.sign(
private_key=private_key,
algorithm=hashes.SHA256(),
backend=backend,
)
)
with tls_cert_file.open("wb") as f:
f.write(certificate.public_bytes(encoding=serialization.Encoding.PEM))
tls_cert_file.chmod(0o644)
with tls_key_file.open("wb") as f:
f.write(
private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption(),
)
)
tls_key_file.chmod(0o600)
async def _get_local_pgcluster(
args: srvargs.ServerConfig,
runstate_dir: pathlib.Path,
tenant_id: str,
) -> Tuple[pgcluster.Cluster, srvargs.ServerConfig]:
pg_max_connections = args.max_backend_connections
if not pg_max_connections:
max_conns = srvargs.compute_default_max_backend_connections()
pg_max_connections = max_conns
if args.testmode:
max_conns = srvargs.adjust_testmode_max_connections(max_conns)
logger.info(f'Configuring Postgres max_connections='
f'{pg_max_connections} under test mode.')
args = args._replace(max_backend_connections=max_conns)
logger.info(f'Using {max_conns} max backend connections based on '
f'total memory.')
cluster = await pgcluster.get_local_pg_cluster(
args.data_dir,
runstate_dir=runstate_dir,
# Plus two below to account for system connections.
max_connections=pg_max_connections + 2,
tenant_id=tenant_id,
log_level=args.log_level,
)
cluster.set_connection_params(
pgconnparams.ConnectionParameters(
user='postgres',
database='template1',
),
)
return cluster, args
async def _get_remote_pgcluster(
args: srvargs.ServerConfig,
tenant_id: str,
) -> Tuple[pgcluster.RemoteCluster, srvargs.ServerConfig]:
cluster = await pgcluster.get_remote_pg_cluster(
args.backend_dsn,
tenant_id=tenant_id,
)
instance_params = cluster.get_runtime_params().instance_params
max_conns = (
instance_params.max_connections -
instance_params.reserved_connections)
if not args.max_backend_connections:
logger.info(f'Detected {max_conns} backend connections available.')
if args.testmode:
max_conns = srvargs.adjust_testmode_max_connections(max_conns)
logger.info(f'Using max_backend_connections={max_conns} '
f'under test mode.')
args = args._replace(max_backend_connections=max_conns)
elif args.max_backend_connections > max_conns:
abort(f'--max-backend-connections is too large for this backend; '
f'detected maximum available NUM: {max_conns}')
return cluster, args
async def run_server(
args: srvargs.ServerConfig,
*,
do_setproctitle: bool=False,
) -> None:
from . import server as server_mod
global server
server = server_mod
ver_meta = buildmeta.get_version_metadata()
extras = []
source = ""
if build_date := ver_meta["build_date"]:
nice_date = build_date.strftime("%Y-%m-%dT%H:%MZ")
source += f" on {nice_date}"
if ver_meta["scm_revision"]:
source += f" from revision {ver_meta['scm_revision']}"
if source_date := ver_meta["source_date"]:
nice_date = source_date.strftime("%Y-%m-%dT%H:%MZ")
source += f" ({nice_date})"
if source:
extras.append(f", built{source}")
if ver_meta["target"]:
extras.append(f"for {ver_meta['target']}")
ver_line = buildmeta.get_version_string() + " ".join(extras)
logger.info(f"starting EdgeDB server {ver_line}")
if args.instance_name:
logger.info(f'instance name: {args.instance_name!r}')
if devmode.is_in_dev_mode():
logger.info(f'development mode active')
logger.debug(
f"defaulting to the '{args.default_auth_method}' authentication method"
)
_init_parsers()
pg_cluster_init_by_us = False
pg_cluster_started_by_us = False
if args.tenant_id is None:
tenant_id = buildmeta.get_default_tenant_id()
else:
tenant_id = f'C{args.tenant_id}'
cluster: Union[pgcluster.Cluster, pgcluster.RemoteCluster]
default_runstate_dir: Optional[pathlib.Path]
if args.data_dir:
default_runstate_dir = args.data_dir
else:
default_runstate_dir = None
specified_runstate_dir: Optional[pathlib.Path]
if args.runstate_dir:
specified_runstate_dir = args.runstate_dir
elif args.bootstrap_only:
# When bootstrapping a new EdgeDB instance it is often necessary
# to avoid using the main runstate dir due to lack of permissions,
# possibility of conflict with another running instance, etc.
# The --bootstrap mode is also often runs unattended, i.e.
# as a post-install hook during package installation.
specified_runstate_dir = default_runstate_dir
else:
specified_runstate_dir = None
runstate_dir_mgr = _ensure_runstate_dir(
default_runstate_dir,
specified_runstate_dir,
)
with runstate_dir_mgr as runstate_dir:
runstate_dir_str = str(runstate_dir)
runstate_dir_str_len = len(
runstate_dir_str.encode(
sys.getfilesystemencoding(),
errors=sys.getfilesystemencodeerrors(),
),
)
if runstate_dir_str_len > defines.MAX_RUNSTATE_DIR_PATH:
abort(
f'the length of the specified path for server run state '
f'exceeds the maximum of {defines.MAX_RUNSTATE_DIR_PATH} '
f'bytes: {runstate_dir_str!r} ({runstate_dir_str_len} bytes)',
exit_code=11,
)
try:
if args.data_dir:
cluster, args = await _get_local_pgcluster(
args, runstate_dir, tenant_id)
elif args.backend_dsn:
cluster, args = await _get_remote_pgcluster(args, tenant_id)
else:
# This should have been checked by main() already,
# but be extra careful.
abort('neither the data directory nor the remote Postgres DSN '
'have been specified')
except pgcluster.ClusterError as e:
abort(str(e))
try:
pg_cluster_init_by_us = await cluster.ensure_initialized()
cluster_status = await cluster.get_status()
if cluster_status == 'stopped':
await cluster.start()
pg_cluster_started_by_us = True
elif cluster_status != 'running':
abort('Could not start database cluster in %s', args.data_dir)
need_cluster_restart = await _init_cluster(cluster, args)
if need_cluster_restart and pg_cluster_started_by_us:
logger.info('Restarting server to reload configuration...')
await cluster.stop()
await cluster.start()
if (
not args.bootstrap_only
or args.bootstrap_script
or args.bootstrap_command
or (
args.tls_cert_mode
is srvargs.ServerTlsCertMode.SelfSigned
)
):
if args.data_dir:
cluster.set_connection_params(
pgconnparams.ConnectionParameters(
user='postgres',
database=pgcluster.get_database_backend_name(
defines.EDGEDB_TEMPLATE_DB,
tenant_id=tenant_id,
),
),
)
with _internal_state_dir(runstate_dir) as int_runstate_dir:
if (
args.tls_cert_file
and '<runstate>' in str(args.tls_cert_file)
):
args = args._replace(
tls_cert_file=pathlib.Path(
str(args.tls_cert_file).replace(
'<runstate>', int_runstate_dir)
),
tls_key_file=pathlib.Path(
str(args.tls_key_file).replace(
'<runstate>', int_runstate_dir)
)
)
await _run_server(
cluster,
args,
runstate_dir,
int_runstate_dir,
do_setproctitle=do_setproctitle,
new_instance=need_cluster_restart,
)
except server.StartupError as e:
abort(str(e))
except BaseException:
if pg_cluster_init_by_us and not _server_initialized:
logger.warning(
'server bootstrap did not complete successfully, '
'removing the data directory')
if await cluster.get_status() == 'running':
await cluster.stop()
cluster.destroy()
raise
finally:
if args.temp_dir:
if await cluster.get_status() == 'running':
await cluster.stop()
cluster.destroy()
elif pg_cluster_started_by_us:
if await cluster.get_status() == 'running':
await cluster.stop()
def bump_rlimit_nofile() -> None:
try:
fno_soft, fno_hard = resource.getrlimit(resource.RLIMIT_NOFILE)
except resource.error:
logger.warning('could not read RLIMIT_NOFILE')
else:
if fno_soft < defines.EDGEDB_MIN_RLIMIT_NOFILE:
try:
resource.setrlimit(
resource.RLIMIT_NOFILE,
(min(defines.EDGEDB_MIN_RLIMIT_NOFILE, fno_hard),
fno_hard))
except resource.error:
logger.warning('could not set RLIMIT_NOFILE')
def server_main(**kwargs):
logsetup.setup_logging(kwargs['log_level'], kwargs['log_to'])
exceptions.install_excepthook()
bump_rlimit_nofile()
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
if kwargs['devmode'] is not None:
devmode.enable_dev_mode(kwargs['devmode'])
try:
server_args = srvargs.parse_args(**kwargs)
except srvargs.InvalidUsageError as e:
abort(e.args[0], exit_code=e.args[1])
if kwargs['background']:
daemon_opts = {'detach_process': True}
pidfile = kwargs['pidfile_dir'] / f".s.EDGEDB.{kwargs['port']}.lock"
daemon_opts['pidfile'] = pidfile
if kwargs['daemon_user']:
daemon_opts['uid'] = kwargs['daemon_user']
if kwargs['daemon_group']:
daemon_opts['gid'] = kwargs['daemon_group']
with daemon.DaemonContext(**daemon_opts):
asyncio.run(run_server(server_args, setproctitle=True))
else:
with devmode.CoverageConfig.enable_coverage_if_requested():
asyncio.run(run_server(server_args))
@click.command(
'EdgeDB Server',
context_settings=dict(help_option_names=['-h', '--help']))
@srvargs.server_options
def main(version=False, **kwargs):
if kwargs.get('testmode') and 'EDGEDB_TEST_CATALOG_VERSION' in os.environ:
buildmeta.EDGEDB_CATALOG_VERSION = int(
os.environ['EDGEDB_TEST_CATALOG_VERSION']
)
if version:
print(f"edgedb-server, version {buildmeta.get_version()}")
sys.exit(0)
server_main(**kwargs)
def main_dev():
devmode.enable_dev_mode()
main()
if __name__ == '__main__':
main()
|
_HTML_TYPES = {
'a': 'HTMLAnchorElement',
'abbr': 'HTMLUnknownElement',
'acronym': 'HTMLUnknownElement',
'address': 'HTMLUnknownElement',
'applet': 'HTMLUnknownElement',
'area': 'HTMLAreaElement',
'article': 'HTMLUnknownElement',
'aside': 'HTMLUnknownElement',
'audio': 'HTMLAudioElement',
'b': 'HTMLUnknownElement',
'base': 'HTMLBaseElement',
'basefont': 'HTMLUnknownElement',
'bdi': 'HTMLUnknownElement',
'bdo': 'HTMLUnknownElement',
'bgsound': 'HTMLUnknownElement',
'big': 'HTMLUnknownElement',
'blockquote': 'HTMLUnknownElement',
'br': 'HTMLBRElement',
'button': 'HTMLButtonElement',
'canvas': 'HTMLCanvasElement',
'caption': 'HTMLTableCaptionElement',
'center': 'HTMLUnknownElement',
'cite': 'HTMLUnknownElement',
'code': 'HTMLUnknownElement',
'col': 'HTMLTableColElement',
'colgroup': 'HTMLUnknownElement',
'command': 'HTMLUnknownElement',
'content': 'HTMLContentElement',
'data': 'HTMLDataElement',
'datalist': 'HTMLDataListElement',
'dd': 'HTMLUnknownElement',
'del': 'HTMLModElement',
'details': 'HTMLDetailsElement',
'dfn': 'HTMLUnknownElement',
'dialog': 'HTMLDialogElement',
'dir': 'HTMLDirectoryElement',
'div': 'HTMLDivElement',
'dl': 'HTMLDListElement',
'dt': 'HTMLUnknownElement',
'em': 'HTMLUnknownElement',
'embed': 'HTMLEmbedElement',
'fieldset': 'HTMLFieldSetElement',
'figcaption': 'HTMLUnknownElement',
'figure': 'HTMLUnknownElement',
'font': 'HTMLFontElement',
'footer': 'HTMLUnknownElement',
'form': 'HTMLFormElement',
'frame': 'HTMLFrameElement',
'frameset': 'HTMLFrameSetElement',
'h1': 'HTMLHeadingElement',
'h2': 'HTMLHeadingElement',
'h3': 'HTMLHeadingElement',
'h4': 'HTMLHeadingElement',
'h5': 'HTMLHeadingElement',
'h6': 'HTMLHeadingElement',
'header': 'HTMLUnknownElement',
'hgroup': 'HTMLUnknownElement',
'hr': 'HTMLHRElement',
'i': 'HTMLUnknownElement',
'iframe': 'HTMLIFrameElement',
'image': 'HTMLImageElement',
'img': 'HTMLImageElement',
'input': 'HTMLInputElement',
'ins': 'HTMLModElement',
'isindex': 'HTMLUnknownElement',
'kbd': 'HTMLUnknownElement',
'keygen': 'HTMLKeygenElement',
'label': 'HTMLLabelElement',
'layer': 'HTMLUnknownElement',
'legend': 'HTMLLegendElement',
'li': 'HTMLLIElement',
'link': 'HTMLLinkElement',
'listing': 'HTMLUnknownElement',
'main': 'HTMLUnknownElement',
'map': 'HTMLMapElement',
'mark': 'HTMLUnknownElement',
'marquee': 'HTMLMarqueeElement',
'menu': 'HTMLMenuElement',
'menuitem': 'HTMLMenuItemElement',
'meta': 'HTMLMetaElement',
'meter': 'HTMLMeterElement',
'nav': 'HTMLUnknownElement',
'nobr': 'HTMLUnknownElement',
'noembed': 'HTMLUnknownElement',
'noframes': 'HTMLUnknownElement',
'nolayer': 'HTMLUnknownElement',
'noscript': 'HTMLUnknownElement',
'object': 'HTMLObjectElement',
'ol': 'HTMLOListElement',
'optgroup': 'HTMLOptGroupElement',
'option': 'HTMLOptionElement',
'output': 'HTMLOutputElement',
'p': 'HTMLParagraphElement',
'param': 'HTMLParamElement',
'picture': 'HTMLPictureElement',
'plaintext': 'HTMLUnknownElement',
'pre': 'HTMLPreElement',
'progress': 'HTMLProgressElement',
'q': 'HTMLQuoteElement',
'rp': 'HTMLUnknownElement',
'rt': 'HTMLUnknownElement',
'ruby': 'HTMLUnknownElement',
's': 'HTMLUnknownElement',
'samp': 'HTMLUnknownElement',
'section': 'HTMLUnknownElement',
'select': 'HTMLSelectElement',
'shadow': 'HTMLShadowElement',
'small': 'HTMLUnknownElement',
'source': 'HTMLSourceElement',
'span': 'HTMLSpanElement',
'strike': 'HTMLUnknownElement',
'strong': 'HTMLUnknownElement',
'style': 'HTMLStyleElement',
'sub': 'HTMLUnknownElement',
'summary': 'HTMLUnknownElement',
'sup': 'HTMLUnknownElement',
'table': 'HTMLTableElement',
'tbody': 'HTMLTableSectionElement',
'td': 'HTMLUnknownElement',
'template': 'HTMLTemplateElement',
'textarea': 'HTMLTextAreaElement',
'tfoot': 'HTMLTableSectionElement',
'th': 'HTMLTableCellElement',
'thead': 'HTMLTableSectionElement',
'time': 'HTMLTimeElement',
'title': 'HTMLTitleElement',
'tr': 'HTMLTableRowElement',
'track': 'HTMLTrackElement',
'tt': 'HTMLUnknownElement',
'u': 'HTMLUnknownElement',
'ul': 'HTMLUListElement',
'var': 'HTMLUnknownElement',
'video': 'HTMLVideoElement',
'wbr': 'HTMLUnknownElement',
'xmp': 'HTMLUnknownElement'
}
|
import sh
from claw import configuration
from claw import tests
class StatusTest(tests.BaseTestWithInit):
def test_basic(self):
test_version = 'TEST_VERSION'
port = self.server({'version': lambda: {'version': test_version}})
self.claw.generate(tests.STUB_CONFIGURATION)
conf = configuration.Configuration(tests.STUB_CONFIGURATION)
with conf.patch.handler_configuration as patch:
patch.set_value('manager_ip', 'localhost')
patch.set_value('manager_port', port)
output = self.claw.status(tests.STUB_CONFIGURATION).stdout
self.assertIn(test_version, output)
def test_no_configuration(self):
with self.assertRaises(sh.ErrorReturnCode) as c:
self.claw.status(tests.STUB_CONFIGURATION)
self.assertIn('Not initialized', c.exception.stderr)
def test_no_manager_ip(self):
self.claw.generate(tests.STUB_CONFIGURATION)
with self.assertRaises(sh.ErrorReturnCode) as c:
self.claw.status(tests.STUB_CONFIGURATION)
self.assertIn('Configuration not bootstrapped', c.exception.stderr)
def test_no_connectivity_to_manager(self):
self.claw.generate(tests.STUB_CONFIGURATION)
conf = configuration.Configuration(tests.STUB_CONFIGURATION)
ip = '127.0.0.1'
with conf.patch.handler_configuration as patch:
patch.set_value('manager_ip', ip)
with self.assertRaises(sh.ErrorReturnCode) as c:
self.claw.status(tests.STUB_CONFIGURATION)
self.assertIn('Not reachable', c.exception.stderr)
self.assertIn(ip, c.exception.stderr)
|
rightPort = "COM9"
if ('virtual' in globals() and virtual):
virtualArduinoRight = Runtime.start("virtualArduinoRight", "VirtualArduino")
virtualArduinoRight.connect(rightPort)
Voice="cmu-bdl-hsmm" #Male US voice
mouth = Runtime.start("i01.mouth", "MarySpeech")
mouth.setVoice(Voice)
i01 = Runtime.create("i01", "InMoov")
right = Runtime.createAndStart("i01.right", "Arduino")
right.connect(rightPort)
i01.startEar()
webgui = Runtime.create("WebGui","WebGui")
webgui.autoStartBrowser(False)
webgui.startService()
webgui.startBrowser("http://localhost:8888/#/service/i01.ear")
i01.startMouth()
rightHand = Runtime.create("i01.rightHand","InMoovHand")
rightHand.thumb.setVelocity(-1)
rightHand.index.setVelocity(-1)
rightHand.majeure.setVelocity(-1)
rightHand.ringFinger.setVelocity(-1)
rightHand.pinky.setVelocity(-1)
rightHand.wrist.setVelocity(-1)
rightHand.thumb.map(0,180,64,135)
rightHand.index.map(0,180,42,160)
rightHand.majeure.map(0,180,35,165)
rightHand.ringFinger.map(0,180,40,140)
rightHand.pinky.map(0,180,45,130)
rightHand.wrist.map(0,180,30,135)
rightHand.thumb.setRest(0)
rightHand.index.setRest(0)
rightHand.majeure.setRest(0)
rightHand.ringFinger.setRest(0)
rightHand.pinky.setRest(0)
rightHand.wrist.setRest(0)
i01 = Runtime.start("i01","InMoov")
i01.startRightHand(rightPort)
i01.rightHand.setAutoDisable(True)
ear = i01.ear
ear.addCommand("attach your right hand", "i01.rightHand", "enable")
ear.addCommand("disconnect your right hand", "i01.rightHand", "disable")
ear.addCommand("rest", "i01.rightHand", "rest")#hardcoded gesture
ear.addCommand("relax", "python", "relax")
ear.addCommand("open your hand", "python", "handopen")
ear.addCommand("close your hand", "python", "handclose")
ear.addCommand("capture gesture", ear.getName(), "captureGesture")
ear.addCommand("manual", ear.getName(), "lockOutAllGrammarExcept", "voice control")
ear.addCommand("voice control", ear.getName(), "clearLock")
ear.addComfirmations("yes","correct","yeah","ya")
ear.addNegations("no","wrong","nope","nah")
ear.startListening()
def relax():
i01.setHandVelocity("right", 30, 30, 30, 30, 30, 30)
i01.moveHand("right",90,90,90,90,90,140)
def handopen():
i01.setHandVelocity("right", -1.0, -1.0, -1.0, -1.0, -1.0, -1.0)
i01.moveHand("right",0,0,0,0,0,0)
i01.mouth.speak("ok I open my hand")
def handclose():
i01.setHandVelocity("right", -1.0, -1.0, -1.0, -1.0, -1.0, -1.0)
i01.moveHand("right",180,180,180,180,180,180)
i01.mouth.speak("a nice and closed hand that is")
relax()
|
from distutils.core import setup
setup(name='ctctwspylib',
version='0.1.1a1',
description='A clone of the original lib from SourceForge (https://sourceforge.net/projects/ctctwspylib/)',
author='Serdar Tumgoren',
author_email='zstumgoren@gmail.com',
url='https://github.com/zstumgoren/ctctwspylib',
license='Apache 2.0',
packages=['ctctwspylib'],
install_requires=['csvkit'],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License 2.0',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries',
]
)
|
"""
This Python module contains tests for the prepifg.py PyRate module.
"""
import shutil
import os
from os.path import exists, join
import sys
import subprocess
import tempfile
from math import floor
from itertools import product
from pathlib import Path
import pytest
import numpy as np
from numpy import isnan, nanmax, nanmin, nanmean, ones, nan, reshape, sum as npsum
from numpy.testing import assert_array_almost_equal, assert_array_equal
from osgeo import gdal
import pyrate.configuration
import pyrate.constants as C
from pyrate.core.logger import pyratelogger as log
from pyrate.core.shared import Ifg, DEM, dem_or_ifg
from pyrate.core.shared import InputTypes
from pyrate.core.prepifg_helper import CUSTOM_CROP, MAXIMUM_CROP, MINIMUM_CROP, ALREADY_SAME_SIZE
from pyrate.core import roipac
from pyrate.core.prepifg_helper import prepare_ifg, _resample, PreprocessError, CustomExts
from pyrate.core.prepifg_helper import get_analysis_extent
from pyrate.core import ifgconstants as ifc
from pyrate.configuration import Configuration, MultiplePaths
from pyrate import conv2tif, prepifg
from tests import common
from tests.common import SML_TEST_LEGACY_PREPIFG_DIR, PY37GDAL302, BASE_TEST, WORKING_DIR
from tests.common import PREP_TEST_TIF, PREP_TEST_OBS, MEXICO_CROPA_CONF, assert_two_dirs_equal
from tests.common import SML_TEST_DEM_TIF, SML_TEST_DEM_HDR, manipulate_test_conf, UnitTestAdaptation
gdal.UseExceptions()
DUMMY_SECTION_NAME = 'pyrate'
if not exists(PREP_TEST_TIF):
sys.exit("ERROR: Missing 'prepifg' dir for unittests\n")
def test_prepifg_treats_inputs_and_outputs_read_only(gamma_conf, tempdir, coh_mask):
tdir = Path(tempdir())
params = common.manipulate_test_conf(gamma_conf, tdir)
params[C.COH_MASK] = coh_mask
output_conf = tdir.joinpath('conf.cfg')
pyrate.configuration.write_config_file(params=params, output_conf_file=output_conf)
params = Configuration(output_conf.as_posix()).__dict__
conv2tif.main(params)
tifs = list(Path(params[C.INTERFEROGRAM_DIR]).glob('*_unw.tif'))
assert len(tifs) == 17
params = Configuration(output_conf.as_posix()).__dict__
prepifg.main(params)
cropped_ifgs = list(Path(params[C.INTERFEROGRAM_DIR]).glob('*_ifg.tif'))
cropped_cohs = list(Path(params[C.COHERENCE_DIR]).glob('*_coh.tif'))
cropped_dem = list(Path(params[C.GEOMETRY_DIR]).glob('*_dem.tif'))
if params[C.COH_FILE_LIST] is not None: # 17 + 1 dem + 17 coh files
assert len(cropped_ifgs) + len(cropped_cohs) + len(cropped_dem) == 35
else: # 17 + 1 dem
assert len(cropped_ifgs) + len(cropped_cohs) + len(cropped_dem) == 18
# check all tifs from conv2tif are still readonly
for t in tifs:
assert t.stat().st_mode == 33060
# check all prepifg outputs are readonly
for c in cropped_cohs + cropped_ifgs + cropped_dem:
assert c.stat().st_mode == 33060
def test_prepifg_file_types(tempdir, gamma_conf, coh_mask):
tdir = Path(tempdir())
params = manipulate_test_conf(gamma_conf, tdir)
params[C.COH_MASK] = coh_mask
params[C.PARALLEL] = 0
output_conf_file = 'conf.conf'
output_conf = tdir.joinpath(output_conf_file)
pyrate.configuration.write_config_file(params=params, output_conf_file=output_conf)
params_s = Configuration(output_conf).__dict__
conv2tif.main(params_s)
# reread params from config
params_s = Configuration(output_conf).__dict__
prepifg.main(params_s)
ifg_files = list(Path(tdir.joinpath(params_s[C.INTERFEROGRAM_DIR])).glob('*_unw.tif'))
assert len(ifg_files) == 17
mlooked_files = list(Path(tdir.joinpath(params_s[C.INTERFEROGRAM_DIR])).glob('*_ifg.tif'))
assert len(mlooked_files) == 17
coh_files = list(Path(tdir.joinpath(params_s[C.COHERENCE_DIR])).glob('*_cc.tif'))
mlooked_coh_files = list(Path(tdir.joinpath(params_s[C.COHERENCE_DIR])).glob('*_coh.tif'))
if coh_mask:
assert len(coh_files) == 17
assert len(mlooked_coh_files) == 17
dem_file = list(Path(tdir.joinpath(params_s[C.GEOMETRY_DIR])).glob('*_dem.tif'))[0]
mlooked_dem_file = list(Path(tdir.joinpath(params_s[C.GEOMETRY_DIR])).glob('dem.tif'))[0]
import itertools
# assert coherence and ifgs have correct metadata
for i in itertools.chain(*[ifg_files, mlooked_files, coh_files, mlooked_coh_files]):
ifg = Ifg(i)
ifg.open()
md = ifg.meta_data
if i.name.endswith('_unw.tif'):
assert md[ifc.DATA_TYPE] == ifc.ORIG
assert ifc.IFG_LKSX not in md
assert ifc.IFG_LKSY not in md
assert ifc.IFG_CROP not in md
continue
if i.name.endswith('_cc.tif'):
assert md[ifc.DATA_TYPE] == ifc.COH
assert ifc.IFG_LKSX not in md
assert ifc.IFG_LKSY not in md
assert ifc.IFG_CROP not in md
continue
if i.name.endswith('_coh.tif'):
assert md[ifc.DATA_TYPE] == ifc.MULTILOOKED_COH
assert md[ifc.IFG_LKSX] == '1'
assert md[ifc.IFG_LKSY] == '1'
assert md[ifc.IFG_CROP] == '1'
continue
if i.name.endswith('_ifg.tif'):
if coh_mask:
assert md[ifc.DATA_TYPE] == ifc.MLOOKED_COH_MASKED_IFG
assert md[ifc.IFG_LKSX] == '1'
assert md[ifc.IFG_LKSY] == '1'
assert md[ifc.IFG_CROP] == '1'
else:
assert md[ifc.DATA_TYPE] == ifc.MULTILOOKED
assert md[ifc.IFG_LKSX] == '1'
assert md[ifc.IFG_LKSY] == '1'
assert md[ifc.IFG_CROP] == '1'
continue
# assert dem has correct metadata
dem = DEM(dem_file.as_posix())
dem.open()
md = dem.dataset.GetMetadata()
assert md[ifc.DATA_TYPE] == ifc.DEM
assert ifc.IFG_LKSX not in md
assert ifc.IFG_LKSY not in md
assert ifc.IFG_CROP not in md
dem = DEM(mlooked_dem_file.as_posix())
dem.open()
md = dem.dataset.GetMetadata()
assert md[ifc.DATA_TYPE] == ifc.MLOOKED_DEM
assert ifc.IFG_LKSX in md
assert ifc.IFG_LKSY in md
assert ifc.IFG_CROP in md
shutil.rmtree(tdir)
def diff_exts_ifgs():
"""Returns pair of test Ifgs with different extents"""
bases = ['geo_060619-061002_unw.tif', 'geo_070326-070917_unw.tif']
headers = ['geo_060619-061002.unw.rsc', 'geo_070326-070917.unw.rsc']
random_dir = tempfile.mkdtemp()
for p, h in zip(bases, headers):
shutil.copy(src=os.path.join(PREP_TEST_TIF, p),
dst=os.path.join(random_dir, p))
shutil.copy(src=os.path.join(PREP_TEST_OBS, h),
dst=os.path.join(random_dir, h))
return [Ifg(join(random_dir, p)) for p in bases], random_dir
def same_exts_ifgs():
"""Return pair of Ifgs with same extents"""
return [Ifg(join(PREP_TEST_TIF, f)) for f in ('geo_060619-061002.tif', 'geo_070326-070917.tif')]
def extents_from_params(params):
"""Custom extents from supplied parameters"""
keys = (
C.IFG_XFIRST, C.IFG_YFIRST, C.IFG_XLAST, C.IFG_YLAST)
return CustomExts(*[params[k] for k in keys])
def test_extents_from_params():
xf, yf = 1.0, 2.0
xl, yl = 5.0, 7.0
pars = {C.IFG_XFIRST: xf, C.IFG_XLAST: xl,
C.IFG_YFIRST: yf, C.IFG_YLAST: yl}
assert extents_from_params(pars) == CustomExts(xf, yf, xl, yl)
class TestPrepifgOutput(UnitTestAdaptation):
"""Tests aspects of the prepifg.py script, such as resampling."""
@staticmethod
def assert_geotransform_equal(files):
"""
Asserts geotransforms for the given files are equivalent. Files can be paths
to datasets, or GDAL dataset objects.
"""
assert len(files) > 1, "Need more than 1 file to compare"
if not all([hasattr(f, "GetGeoTransform") for f in files]):
datasets = [gdal.Open(f) for f in files]
assert all(datasets)
else:
datasets = files
transforms = [ds.GetGeoTransform() for ds in datasets]
head = transforms[0]
for t in transforms[1:]:
assert_array_almost_equal(t, head, decimal=6, err_msg="Extents do not match!")
@classmethod
def setup_class(cls):
cls.xs = 0.000833333
cls.ys = -cls.xs
cls.ifgs, cls.random_dir = diff_exts_ifgs()
cls.ifg_paths = [i.data_path for i in cls.ifgs]
cls.params = Configuration(common.TEST_CONF_ROIPAC).__dict__
cls.params[C.OUT_DIR] = cls.random_dir
cls.params[C.GEOMETRY_DIR] = Path(cls.random_dir).joinpath(C.GEOMETRY_DIR)
cls.params[C.GEOMETRY_DIR].mkdir(exist_ok=True)
cls.params[C.INTERFEROGRAM_DIR] = Path(cls.random_dir).joinpath(C.INTERFEROGRAM_DIR)
cls.params[C.INTERFEROGRAM_DIR].mkdir(exist_ok=True)
cls.headers = [roipac.roipac_header(i.data_path, cls.params) for i in cls.ifgs]
paths = ["060619-061002_ifg.tif",
"060619-061002_ifg.tif",
"060619-061002_ifg.tif",
"060619-061002_ifg.tif",
"070326-070917_ifg.tif",
"070326-070917_ifg.tif",
"070326-070917_ifg.tif",
"070326-070917_ifg.tif"]
cls.exp_files = [join(cls.random_dir, C.INTERFEROGRAM_DIR, p) for p in paths]
@staticmethod
def test_mlooked_paths():
test_mlooked_path()
@staticmethod
def test_extents_from_params():
test_extents_from_params()
@classmethod
def teardown_class(cls):
for exp_file in cls.exp_files:
if exists(exp_file):
os.remove(exp_file)
for ifg in cls.ifgs:
ifg.close()
shutil.rmtree(cls.random_dir)
def _custom_ext_latlons(self):
return [150.91 + (7 * self.xs), # xfirst
-34.17 + (16 * self.ys), # yfirst
150.91 + (27 * self.xs), # 20 cells from xfirst
-34.17 + (44 * self.ys)] # 28 cells from yfirst
def _custom_extents_tuple(self):
return CustomExts(*self._custom_ext_latlons())
def assert_projection_equal(self, files):
"""
Asserts preojections for the given files are equivalent.
Files can be paths to datasets, or GDAL dataset objects.
"""
assert len(files) > 1, "Need more than 1 file to compare"
if not all([hasattr(f, "GetGeoTransform") for f in files]):
datasets = [gdal.Open(f) for f in files]
assert all(datasets)
else:
datasets = files
projections = [ds.GetProjection() for ds in datasets]
head = projections[0]
for t in projections[1:]:
self.assertEqual(t, head)
def test_multilooked_projection_same_as_geotiff(self):
xlooks = ylooks = 1
exts = get_analysis_extent(crop_opt=MAXIMUM_CROP, rasters=self.ifgs, xlooks=xlooks, ylooks=ylooks,
user_exts=None)
out_dir = tempfile.mkdtemp()
params = common.min_params(out_dir)
params[C.IFG_LKSX] = xlooks
params[C.IFG_LKSY] = ylooks
params[C.IFG_CROP_OPT] = MAXIMUM_CROP
params[C.GEOMETRY_DIR] = Path(out_dir).joinpath(C.GEOMETRY_DIR)
params[C.GEOMETRY_DIR].mkdir(exist_ok=True)
params[C.INTERFEROGRAM_DIR] = Path(out_dir).joinpath(C.INTERFEROGRAM_DIR)
params[C.INTERFEROGRAM_DIR].mkdir(exist_ok=True)
mlooked_paths = [mlooked_path(f, params, input_type=InputTypes.IFG)
for f in self.ifg_paths]
for i, h, m in zip(self.ifg_paths, self.headers, mlooked_paths):
prepare_ifg(i, xlooks, ylooks, exts, thresh=0.5, crop_opt=MAXIMUM_CROP, header=h, write_to_disk=True,
out_path=m)
self.assert_projection_equal(self.ifg_paths + mlooked_paths)
def test_default_max_extents(self):
"""Test ifgcropopt=2 crops datasets to max bounding box extents."""
xlooks = ylooks = 1
prepare_ifgs(self.ifg_paths, MAXIMUM_CROP, xlooks, ylooks, self.headers, params=self.params)
for f in [self.exp_files[1], self.exp_files[5]]:
self.assertTrue(exists(f), msg="Output files not created")
# output files should have same extents
# NB: also verifies gdalwarp correctly copies geotransform across
ifg = Ifg(self.exp_files[1])
ifg.open()
gt = ifg.dataset.GetGeoTransform()
# copied from gdalinfo output
exp_gt = (150.91, 0.000833333, 0, -34.17, 0, -0.000833333)
for i, j in zip(gt, exp_gt):
self.assertAlmostEqual(i, j)
self.assert_geotransform_equal([self.exp_files[1], self.exp_files[5]])
ifg.close()
for i in self.ifgs:
i.close()
def test_min_extents(self):
"""Test ifgcropopt=1 crops datasets to min extents."""
xlooks = ylooks = 1
prepare_ifgs(self.ifg_paths, MINIMUM_CROP, xlooks, ylooks, headers=self.headers, params=self.params)
ifg = Ifg(self.exp_files[0])
ifg.open()
# output files should have same extents
# NB: also verifies gdalwarp correctly copies geotransform across
# NB: expected data copied from gdalinfo output
gt = ifg.dataset.GetGeoTransform()
exp_gt = (150.911666666, 0.000833333, 0, -34.172499999, 0, -0.000833333)
for i, j in zip(gt, exp_gt):
self.assertAlmostEqual(i, j)
self.assert_geotransform_equal([self.exp_files[0], self.exp_files[4]])
ifg.close()
for i in self.ifgs:
i.close()
def test_custom_extents(self):
xlooks = ylooks = 1
cext = self._custom_extents_tuple()
prepare_ifgs(self.ifg_paths, CUSTOM_CROP, xlooks, ylooks, headers=self.headers,
user_exts=cext, params=self.params)
ifg = Ifg(self.exp_files[2])
ifg.open()
gt = ifg.dataset.GetGeoTransform()
exp_gt = (cext.xfirst, self.xs, 0, cext.yfirst, 0, self.ys)
for i, j in zip(gt, exp_gt):
self.assertAlmostEqual(i, j)
self.assert_geotransform_equal([self.exp_files[2], self.exp_files[6]])
# close ifgs
ifg.close()
for i in self.ifgs:
i.close()
def test_exception_without_all_4_crop_parameters(self):
"""Test misaligned cropping extents raise errors."""
xlooks = ylooks = 1
# empty string and none raises exceptio
for i in [None, '']:
cext = (150.92, -34.18, 150.94, i)
self.assertRaises(PreprocessError, prepare_ifgs, self.ifg_paths,
CUSTOM_CROP, xlooks, ylooks, self.headers, user_exts=cext, params=self.params)
# three parameters provided
self.assertRaises(PreprocessError, prepare_ifgs, self.ifg_paths,
CUSTOM_CROP, xlooks, ylooks, self.headers, params=self.params,
user_exts=(150.92, -34.18, 150.94))
# close ifgs
for i in self.ifgs:
i.close()
def test_custom_extents_misalignment(self):
"""Test misaligned cropping extents raise errors."""
xlooks = ylooks = 1
latlons = tuple(self._custom_ext_latlons())
for i, _ in enumerate(['xfirst', 'yfirst', 'xlast', 'ylast']):
# error = step / pi * [1000 100]
for error in [0.265258, 0.026526]:
tmp_latlon = list(latlons)
tmp_latlon[i] += error
cext = CustomExts(*tmp_latlon)
self.assertRaises(PreprocessError, prepare_ifgs, self.ifg_paths, CUSTOM_CROP, xlooks, ylooks,
user_exts=cext, headers=self.headers, params=self.params)
# close ifgs
for i in self.ifgs:
i.close()
def test_nodata(self):
"""Verify NODATA value copied correctly (amplitude band not copied)"""
xlooks = ylooks = 1
prepare_ifgs(self.ifg_paths, MINIMUM_CROP, xlooks, ylooks, self.headers, self.params)
for ex in [self.exp_files[0], self.exp_files[4]]:
ifg = Ifg(ex)
ifg.open()
# NB: amplitude band doesn't have a NODATA value
self.assertTrue(isnan(ifg.dataset.GetRasterBand(1).GetNoDataValue()))
ifg.close()
for i in self.ifgs:
i.close()
def test_nans(self):
"""Verify NaNs replace 0 in the multilooked phase band"""
xlooks = ylooks = 1
prepare_ifgs(self.ifg_paths, MINIMUM_CROP, xlooks, ylooks, self.headers, self.params)
for ex in [self.exp_files[0], self.exp_files[4]]:
ifg = Ifg(ex)
ifg.open()
phase = ifg.phase_band.ReadAsArray()
self.assertFalse((phase == 0).any())
self.assertTrue((isnan(phase)).any())
ifg.close()
self.assertAlmostEqual(nanmax(phase), 4.247, 3) # copied from gdalinfo
self.assertAlmostEqual(nanmin(phase), 0.009, 3) # copied from gdalinfo
for i in self.ifgs:
i.close()
def test_multilook(self):
"""Test resampling method using a scaling factor of 4"""
scale = 4 # assumes square cells
self.ifgs.append(DEM(SML_TEST_DEM_TIF))
self.ifg_paths = [i.data_path for i in self.ifgs]
# append the dem header
self.headers.append(SML_TEST_DEM_HDR)
cext = self._custom_extents_tuple()
xlooks = ylooks = scale
prepare_ifgs(self.ifg_paths, CUSTOM_CROP, xlooks, ylooks, thresh=1.0, user_exts=cext,
headers=self.headers, params=self.params)
for n, ipath in enumerate([self.exp_files[3], self.exp_files[7]]):
i = Ifg(ipath)
i.open()
self.assertEqual(i.dataset.RasterXSize, 20 / scale)
self.assertEqual(i.dataset.RasterYSize, 28 / scale)
# verify resampling
path = join(PREP_TEST_TIF, "geo_%s.tif" % Path(ipath).name.split('_ifg')[0])
ds = gdal.Open(path)
src_data = ds.GetRasterBand(2).ReadAsArray()
exp_resample = multilooking(src_data, scale, scale, thresh=0)
self.assertEqual(exp_resample.shape, (7, 5))
assert_array_almost_equal(exp_resample, i.phase_band.ReadAsArray())
ds = None
i.close()
os.remove(ipath)
# verify DEM has been correctly processed
# ignore output values as resampling has already been tested for phase
exp_dem_path = join(self.params[C.GEOMETRY_DIR], 'dem.tif')
self.assertTrue(exists(exp_dem_path))
orignal_dem = DEM(SML_TEST_DEM_TIF)
orignal_dem.open()
dem_dtype = orignal_dem.dataset.GetRasterBand(1).DataType
orignal_dem.close()
dem = DEM(exp_dem_path)
dem.open()
# test multilooked dem is of the same datatype as the original dem tif
self.assertEqual(dem_dtype, dem.dataset.GetRasterBand(1).DataType)
self.assertEqual(dem.dataset.RasterXSize, 20 / scale)
self.assertEqual(dem.dataset.RasterYSize, 28 / scale)
data = dem.data
self.assertTrue(data.ptp() != 0)
# close ifgs
dem.close()
for i in self.ifgs:
i.close()
os.remove(exp_dem_path)
def test_output_datatype(self):
"""Test resampling method using a scaling factor of 4"""
scale = 4 # assumes square cells
self.ifgs.append(DEM(SML_TEST_DEM_TIF))
ifg_paths = [i.data_path for i in self.ifgs]
data_types = [InputTypes.IFG] * len(self.ifg_paths)
ifg_paths.append(SML_TEST_DEM_TIF)
data_types.append(InputTypes.DEM)
self.headers.append(SML_TEST_DEM_HDR)
cext = self._custom_extents_tuple()
xlooks = ylooks = scale
prepare_ifgs(ifg_paths, CUSTOM_CROP, xlooks, ylooks, thresh=1.0, user_exts=cext, headers=self.headers,
params=self.params)
self.params[C.IFG_LKSX] = xlooks
self.params[C.IFG_LKSY] = ylooks
self.params[C.IFG_CROP_OPT] = CUSTOM_CROP
for i, t in zip(ifg_paths, data_types):
mlooked_ifg = mlooked_path(i, self.params, input_type=t)
ds1 = DEM(mlooked_ifg)
ds1.open()
ds2 = DEM(i)
ds2.open()
self.assertEqual(ds1.dataset.GetRasterBand(1).DataType,
ds2.dataset.GetRasterBand(1).DataType)
ds1 = ds2 = None
def test_invalid_looks(self):
"""Verify only numeric values can be given for multilooking"""
values = [0, -1, -10, -100000.6, ""]
for v in values:
self.assertRaises(PreprocessError, prepare_ifgs, self.ifg_paths,
CUSTOM_CROP, xlooks=v, ylooks=1, headers=self.headers, params=self.params)
self.assertRaises(PreprocessError, prepare_ifgs, self.ifg_paths,
CUSTOM_CROP, xlooks=1, ylooks=v, headers=self.headers, params=self.params)
class TestThresholdTests(UnitTestAdaptation):
"""Tests for threshold of data -> NaN during resampling."""
def test_nan_threshold_inputs(self):
data = ones((1, 1))
for thresh in [-10, -1, -0.5, 1.000001, 10]:
self.assertRaises(ValueError, _resample, data, 2, 2, thresh)
@staticmethod
def test_nan_threshold():
# test threshold based on number of NaNs per averaging tile
data = ones((2, 10))
data[0, 3:] = nan
data[1, 7:] = nan
# key: NaN threshold as a % of pixels, expected result
expected = [(0.0, [1, nan, nan, nan, nan]),
(0.25, [1, nan, nan, nan, nan]),
(0.5, [1, 1, nan, nan, nan]),
(0.75, [1, 1, 1, nan, nan]),
(1.0, [1, 1, 1, 1, nan])]
for thresh, exp in expected:
res = _resample(data, xscale=2, yscale=2, thresh=thresh)
assert_array_equal(res, reshape(exp, res.shape))
@staticmethod
def test_nan_threshold_alt():
# test threshold on odd numbers
data = ones((3, 6))
data[0] = nan
data[1, 2:5] = nan
expected = [(0.4, [nan, nan]), (0.5, [1, nan]), (0.7, [1, 1])]
for thresh, exp in expected:
res = _resample(data, xscale=3, yscale=3, thresh=thresh)
assert_array_equal(res, reshape(exp, res.shape))
class TestSameSizeTests(UnitTestAdaptation):
"""Tests aspects of the prepifg.py script, such as resampling."""
@classmethod
def setup_class(cls):
import datetime
cls.xs = 0.000833333
cls.ys = -cls.xs
cls.headers = [
{'NCOLS': 47, 'NROWS': 72, 'LAT': -34.17, 'LONG': 150.91, 'X_STEP': 0.000833333, 'Y_STEP': -0.000833333,
'WAVELENGTH_METRES': 0.0562356424, 'FIRST_DATE': datetime.date(2007, 3, 26),
'SECOND_DATE': datetime.date(2007, 9, 17), 'TIME_SPAN_YEAR': 0.4791238877481177,
'DATA_UNITS': 'RADIANS', 'INSAR_PROCESSOR': 'ROIPAC', 'X_LAST': 150.94916665099998,
'Y_LAST': -34.229999976, 'DATUM': 'WGS84', 'DATA_TYPE': 'ORIGINAL_IFG'},
{'NCOLS': 47, 'NROWS': 72, 'LAT': -34.17, 'LONG': 150.91, 'X_STEP': 0.000833333, 'Y_STEP': -0.000833333,
'WAVELENGTH_METRES': 0.0562356424, 'FIRST_DATE': datetime.date(2007, 3, 26),
'SECOND_DATE': datetime.date(2007, 9, 17), 'TIME_SPAN_YEAR': 0.4791238877481177,
'DATA_UNITS': 'RADIANS', 'INSAR_PROCESSOR': 'ROIPAC', 'X_LAST': 150.94916665099998,
'Y_LAST': -34.229999976, 'DATUM': 'WGS84', 'DATA_TYPE': 'ORIGINAL_IFG'}
]
out_dir = tempfile.mkdtemp()
cls.params = common.min_params(out_dir)
cls.params[C.GEOMETRY_DIR] = Path(cls.params[C.OUT_DIR]).joinpath(C.GEOMETRY_DIR)
cls.params[C.GEOMETRY_DIR].mkdir(exist_ok=True)
cls.params[C.INTERFEROGRAM_DIR] = Path(cls.params[C.OUT_DIR]).joinpath(C.INTERFEROGRAM_DIR)
cls.params[C.INTERFEROGRAM_DIR].mkdir(exist_ok=True)
# TODO: check output files for same extents?
# TODO: make prepifg dir readonly to test output to temp dir
# TODO: move to class for testing same size option?
def test_already_same_size(self):
# should do nothing as layers are same size & no multilooking required
ifgs = same_exts_ifgs()
ifg_data_paths = [d.data_path for d in ifgs]
res_tup = prepare_ifgs(ifg_data_paths, ALREADY_SAME_SIZE, 1, 1, self.headers, self.params)
res = [r[1] for r in res_tup]
self.assertTrue(all(res))
def test_already_same_size_mismatch(self):
ifgs, random_dir = diff_exts_ifgs()
ifg_data_paths = [d.data_path for d in ifgs]
self.assertRaises(PreprocessError, prepare_ifgs, ifg_data_paths, ALREADY_SAME_SIZE, 1, 1, self.headers,
self.params)
for i in ifgs:
i.close()
shutil.rmtree(random_dir)
# TODO: ensure multilooked files written to output dir
def test_same_size_multilooking(self):
ifgs = same_exts_ifgs()
ifg_data_paths = [d.data_path for d in ifgs]
xlooks = ylooks = 2
out_dir = tempfile.mkdtemp()
params = common.min_params(out_dir)
params[C.IFG_LKSX] = xlooks
params[C.IFG_LKSY] = ylooks
params[C.IFG_CROP_OPT] = ALREADY_SAME_SIZE
params[C.GEOMETRY_DIR] = Path(params[C.OUT_DIR]).joinpath(C.GEOMETRY_DIR)
params[C.GEOMETRY_DIR].mkdir(exist_ok=True)
params[C.INTERFEROGRAM_DIR] = Path(params[C.OUT_DIR]).joinpath(C.INTERFEROGRAM_DIR)
params[C.INTERFEROGRAM_DIR].mkdir(exist_ok=True)
prepare_ifgs(ifg_data_paths, ALREADY_SAME_SIZE, xlooks, ylooks, self.headers, params)
looks_paths = [mlooked_path(d, params, input_type=InputTypes.IFG) for d in ifg_data_paths]
mlooked = [Ifg(i) for i in looks_paths]
for m in mlooked:
m.open()
self.assertEqual(len(mlooked), 2)
for ifg in mlooked:
self.assertAlmostEqual(ifg.x_step, xlooks * self.xs)
self.assertAlmostEqual(ifg.x_step, ylooks * self.xs)
os.remove(ifg.data_path)
def mlooked_path(path, params, input_type):
m = MultiplePaths(path, params=params, input_type=input_type)
return m.sampled_path
def test_mlooked_path():
path = 'geo_060619-061002_unw.tif'
for xlks, ylks, cr, input_type in product([2, 4, 8], [4, 2, 5], [1, 2, 3, 4], [InputTypes.IFG, InputTypes.COH]):
out_dir = tempfile.mkdtemp()
params = common.min_params(out_dir)
params[C.IFG_LKSX] = xlks
params[C.IFG_LKSY] = ylks
params[C.IFG_CROP_OPT] = cr
m = mlooked_path(path, params, input_type=input_type)
assert Path(m).name == f'060619-061002_{input_type.value}.tif'
class TestLocalMultilookTests:
"""Tests for local testing functions"""
@staticmethod
def test_multilooking_thresh():
data = ones((3, 6))
data[0] = nan
data[1, 2:5] = nan
expected = [(6, [nan, nan]),
(5, [1, nan]),
(4, [1, 1])]
scale = 3
for thresh, exp in expected:
res = multilooking(data, scale, scale, thresh)
assert_array_equal(res, reshape(exp, res.shape))
def multilooking(src, xscale, yscale, thresh=0):
"""
src: numpy array of phase data
thresh: min number of non-NaNs required for a valid tile resampling
"""
thresh = int(thresh)
num_cells = xscale * yscale
if thresh > num_cells or thresh < 0:
msg = "Invalid threshold: %s (need 0 <= thr <= %s" % (thresh, num_cells)
raise ValueError(msg)
rows, cols = src.shape
rows_lowres = int(floor(rows / yscale))
cols_lowres = int(floor(cols / xscale))
dest = ones((rows_lowres, cols_lowres)) * nan
size = xscale * yscale
for row in range(rows_lowres):
for col in range(cols_lowres):
ys = row * yscale
ye = ys + yscale
xs = col * xscale
xe = xs + xscale
patch = src[ys:ye, xs:xe]
num_values = num_cells - npsum(isnan(patch))
if num_values >= thresh and num_values > 0:
# nanmean() only works on 1g axis
reshaped = patch.reshape(size)
dest[row, col] = nanmean(reshaped)
return dest
class TestLegacyEqualityTestRoipacSmallTestData(UnitTestAdaptation):
"""
Legacy roipac prepifg equality test for small test data
"""
def setup_class(cls):
from tests.common import small_data_setup
cls.ifgs = small_data_setup()
cls.ifg_paths = [i.data_path for i in cls.ifgs]
params = Configuration(common.TEST_CONF_ROIPAC).__dict__
cls.headers = [roipac.roipac_header(i.data_path, params) for i in cls.ifgs]
params[C.IFG_LKSX], params[C.IFG_LKSY], params[
C.IFG_CROP_OPT] = 1, 1, 1
prepare_ifgs(cls.ifg_paths, crop_opt=1, xlooks=1, ylooks=1, headers=cls.headers, params=params)
looks_paths = [mlooked_path(d, params, t) for d, t in zip(cls.ifg_paths, [InputTypes.IFG]*len(cls.ifgs))]
cls.ifgs_with_nan = [Ifg(i) for i in looks_paths]
for ifg in cls.ifgs_with_nan:
ifg.open()
@classmethod
def teardown_class(cls):
for i in cls.ifgs_with_nan:
if os.path.exists(i.data_path):
i.close()
os.remove(i.data_path)
def test_legacy_prepifg_equality_array(self):
"""
Legacy prepifg equality test
"""
# path to csv folders from legacy output
onlyfiles = [
fln for fln in os.listdir(SML_TEST_LEGACY_PREPIFG_DIR)
if os.path.isfile(os.path.join(SML_TEST_LEGACY_PREPIFG_DIR, fln))
and fln.endswith('.csv') and fln.__contains__('_rad_')
]
for fln in onlyfiles:
ifg_data = np.genfromtxt(os.path.join(
SML_TEST_LEGACY_PREPIFG_DIR, fln), delimiter=',')
for k, j in enumerate(self.ifgs):
if fln.split('_rad_')[-1].split('.')[0] == \
os.path.split(j.data_path)[-1].split('.')[0]:
np.testing.assert_array_almost_equal(ifg_data,
self.ifgs_with_nan[
k].phase_data,
decimal=2)
def test_legacy_prepifg_and_convert_phase(self):
"""
Legacy data prepifg equality test
"""
# path to csv folders from legacy output
for i in self.ifgs_with_nan:
if not i.mm_converted:
i.convert_to_mm()
onlyfiles = [
f for f in os.listdir(SML_TEST_LEGACY_PREPIFG_DIR)
if os.path.isfile(os.path.join(SML_TEST_LEGACY_PREPIFG_DIR, f))
and f.endswith('.csv') and f.__contains__('_mm_')]
count = 0
for i, f in enumerate(onlyfiles):
ifg_data = np.genfromtxt(os.path.join(
SML_TEST_LEGACY_PREPIFG_DIR, f), delimiter=',')
for k, j in enumerate(self.ifgs):
if f.split('_mm_')[-1].split('.')[0] == \
os.path.split(j.data_path)[-1].split('_unw.')[0]:
count += 1
# all numbers equal
np.testing.assert_array_almost_equal(
ifg_data, self.ifgs_with_nan[k].phase_data, decimal=2)
# means must also be equal
self.assertAlmostEqual(
nanmean(ifg_data),
nanmean(self.ifgs_with_nan[k].phase_data),
places=4)
# number of nans must equal
self.assertEqual(
np.sum(np.isnan(ifg_data)),
np.sum(np.isnan(self.ifgs_with_nan[k].phase_data)))
# ensure we have the correct number of matches
self.assertEqual(count, len(self.ifgs))
class TestOneIncidenceOrElevationMap(UnitTestAdaptation):
@classmethod
def setup_class(cls):
cls.base_dir = tempfile.mkdtemp()
cls.conf_file = tempfile.mktemp(suffix='.conf', dir=cls.base_dir)
cls.ifgListFile = os.path.join(common.GAMMA_SML_TEST_DIR, 'ifms_17')
cls.baseListFile = os.path.join(common.GAMMA_SML_TEST_DIR, 'baseline_17')
@classmethod
def teardown_class(cls):
params = Configuration(cls.conf_file).__dict__
shutil.rmtree(cls.base_dir)
common.remove_tifs(params[WORKING_DIR])
def make_input_files(self, inc='', ele=''):
with open(self.conf_file, 'w') as conf:
conf.write('{}: {}\n'.format(C.NO_DATA_VALUE, '0.0'))
conf.write('{}: {}\n'.format(WORKING_DIR, common.GAMMA_SML_TEST_DIR))
conf.write('{}: {}\n'.format(C.OUT_DIR, self.base_dir))
conf.write('{}: {}\n'.format(C.IFG_FILE_LIST, self.ifgListFile))
conf.write('{}: {}\n'.format(C.BASE_FILE_LIST, self.baseListFile))
conf.write('{}: {}\n'.format(C.PROCESSOR, '1'))
conf.write('{}: {}\n'.format(
C.DEM_HEADER_FILE, os.path.join(
common.GAMMA_SML_TEST_DIR, '20060619_utm_dem.par')))
conf.write('{}: {}\n'.format(C.IFG_LKSX, '1'))
conf.write('{}: {}\n'.format(C.IFG_LKSY, '1'))
conf.write('{}: {}\n'.format(C.IFG_CROP_OPT, '1'))
conf.write('{}: {}\n'.format(C.NO_DATA_AVERAGING_THRESHOLD, '0.5'))
conf.write('{}: {}\n'.format(C.HDR_FILE_LIST,
common.SML_TEST_GAMMA_HEADER_LIST))
conf.write('{}: {}\n'.format(C.DEM_FILE, common.SML_TEST_DEM_GAMMA))
conf.write('{}: {}\n'.format(C.APS_INCIDENCE_MAP, inc))
conf.write('{}: {}\n'.format(C.APS_ELEVATION_MAP, ele))
conf.write('{}: {}\n'.format(C.APS_CORRECTION, '1'))
conf.write('{}: {}\n'.format(C.APS_METHOD, '2'))
conf.write('{}: {}\n'.format(C.TIME_SERIES_SM_ORDER, 1))
def common_check(self, ele, inc):
import glob
from pyrate.configuration import Configuration
assert os.path.exists(self.conf_file)
params = Configuration(self.conf_file).__dict__
conv2tif.main(params)
sys.argv = ['dummy', self.conf_file]
prepifg.main(params)
# test 17 geotiffs created
geotifs = glob.glob(os.path.join(params[C.OUT_DIR], '*_unw.tif'))
self.assertEqual(17, len(geotifs))
# test dem geotiff created
demtif = glob.glob(os.path.join(params[C.OUT_DIR], '*_dem.tif'))
self.assertEqual(1, len(demtif))
# mlooked tifs
mlooked_tifs = glob.glob(os.path.join(self.base_dir, '*_ifg.tif'))
mlooked_tifs.append(os.path.join(self.base_dir, 'dem.tif'))
# 19 including 17 ifgs, 1 dem and one incidence
self.assertEqual(18, len(mlooked_tifs))
inc = glob.glob(os.path.join(self.base_dir, '*utm_{inc}.tif'.format(inc=inc)))
self.assertEqual(0, len(inc))
def prepare_ifgs(raster_data_paths, crop_opt, xlooks, ylooks, headers, params, thresh=0.5, user_exts=None,
write_to_disc=True):
"""
Wrapper function to prepare a sequence of interferogram files for
PyRate analysis. See prepifg.prepare_ifg() for full description of
inputs and returns.
Note: function need refining for crop options
:param list raster_data_paths: List of interferogram file paths
:param int crop_opt: Crop option
:param int xlooks: Number of multi-looks in x; 5 is 5 times smaller, 1 is no change
:param int ylooks: Number of multi-looks in y
:param float thresh: see thresh in prepare_ifgs()
:param tuple user_exts: Tuple of user defined georeferenced extents for
new file: (xfirst, yfirst, xlast, ylast)cropping coordinates
:param bool write_to_disc: Write new data to disk
:return: resampled_data: output cropped and resampled image
:rtype: ndarray
:return: out_ds: destination gdal dataset object
:rtype: List[gdal.Dataset]
"""
if xlooks != ylooks:
log.warning('X and Y multi-look factors are not equal')
# use metadata check to check whether it's a dem or ifg
rasters = [dem_or_ifg(r) for r in raster_data_paths]
exts = get_analysis_extent(crop_opt, rasters, xlooks, ylooks, user_exts)
out_paths = []
for r, t in zip(raster_data_paths, rasters):
if isinstance(t, DEM):
input_type = InputTypes.DEM
else:
input_type = InputTypes.IFG
out_path = MultiplePaths(r, params, input_type).sampled_path
out_paths.append(out_path)
return [prepare_ifg(d, xlooks, ylooks, exts, thresh, crop_opt, h, write_to_disc, p) for d, h, p
in zip(raster_data_paths, headers, out_paths)]
@pytest.mark.mpi
@pytest.mark.slow
@pytest.mark.skipif(not PY37GDAL302, reason="Only run in one CI env")
def test_coh_stats_equality(mexico_cropa_params):
subprocess.run(f"mpirun -n 3 pyrate prepifg -f {MEXICO_CROPA_CONF.as_posix()}", shell=True)
params = mexico_cropa_params
mexico_cropa_coh_stats_dir = Path(BASE_TEST).joinpath("cropA", 'coherence_stats')
assert_two_dirs_equal(params[C.COHERENCE_DIR], mexico_cropa_coh_stats_dir, ext="coh*.tif", num_files=3)
# assert metadata was written
from pyrate.prepifg import out_type_md_dict
for stat_tif in mexico_cropa_coh_stats_dir.glob("coh*.tif"):
ds = gdal.Open(stat_tif.as_posix())
md = ds.GetMetadata()
expected_md = out_type_md_dict[stat_tif.stem.upper()]
assert ifc.DATA_TYPE in md.keys()
assert expected_md in md.values()
|
import csv
import tushare as ts
import datetime
import os
def getStockHistoryData(stockId,timeToMarket):
if not re.match('^\d{8}$',timeToMarket) :
timeToMarket = '20000101'
endDate = datetime.datetime.strptime(timeToMarket,'%Y%m%d')
toDate = datetime.datetime.now()
fromDate = toDate - datetime.timedelta(days=96)
path = '/home/cano/data/historykdata/historydata60/historydata' + stockId + '.csv'
while(fromDate >= endDate):
if (fromDate < endDate):
fromDate = endDate
print(fromDate)
print(toDate)
print('')
data = ts.get_h_data(stockId,start=fromDate.strftime('%Y-%m-%d'),end=toDate.strftime('%Y-%m-%d'),autype='qfq',ktype='60')
if data is not None :
if os.path.exists(path):
data.to_csv(path,mode='a',header=False)
else:
data.to_csv(path)
toDate = fromDate - datetime.timedelta(days=1)
fromDate = fromDate - datetime.timedelta(days=96)
csvfile = open('/home/cano/data/stocklist.csv', 'r')
reader = csv.reader(csvfile)
for line in reader:
if os.path.exists('/home/cano/data/historykdata/historydata60/historydata' + line[0] + '.csv'):
continue
print(line[0])
getStockHistoryData(line[0],line[15])
csvfile.close()
|
import unittest
from mock import patch
from mock import MagicMock as Mock
from pyrax.clouddatabases import CloudDatabaseBackupManager
from pyrax.clouddatabases import CloudDatabaseDatabase
from pyrax.clouddatabases import CloudDatabaseFlavor
from pyrax.clouddatabases import CloudDatabaseInstance
from pyrax.clouddatabases import CloudDatabaseUser
from pyrax.clouddatabases import CloudDatabaseVolume
from pyrax.clouddatabases import assure_instance
import pyrax.exceptions as exc
from pyrax.resource import BaseResource
import pyrax.utils as utils
from pyrax import fakes
example_uri = "http://example.com"
class CloudDatabasesTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(CloudDatabasesTest, self).__init__(*args, **kwargs)
def setUp(self):
self.instance = fakes.FakeDatabaseInstance()
self.client = fakes.FakeDatabaseClient()
def tearDown(self):
pass
def test_assure_instance(self):
class TestClient(object):
_manager = fakes.FakeManager()
@assure_instance
def test_method(self, instance):
return instance
client = TestClient()
client._manager.get = Mock(return_value=self.instance)
# Pass the instance
ret = client.test_method(self.instance)
self.assertTrue(ret is self.instance)
# Pass the ID
ret = client.test_method(self.instance.id)
self.assertTrue(ret is self.instance)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_instantiate_instance(self):
inst = CloudDatabaseInstance(fakes.FakeManager(), {"id": 42,
"volume": {"size": 1, "used": 0.2}})
self.assertTrue(isinstance(inst, CloudDatabaseInstance))
self.assertTrue(isinstance(inst.volume, CloudDatabaseVolume))
def test_list_databases(self):
inst = self.instance
inst._database_manager.list = Mock()
limit = utils.random_unicode()
marker = utils.random_unicode()
inst.list_databases(limit=limit, marker=marker)
inst._database_manager.list.assert_called_once_with(limit=limit,
marker=marker)
def test_list_users(self):
inst = self.instance
inst._user_manager.list = Mock()
limit = utils.random_unicode()
marker = utils.random_unicode()
inst.list_users(limit=limit, marker=marker)
inst._user_manager.list.assert_called_once_with(limit=limit,
marker=marker)
def test_get_database(self):
inst = self.instance
db1 = fakes.FakeEntity()
db1.name = "a"
db2 = fakes.FakeEntity()
db2.name = "b"
inst.list_databases = Mock(return_value=[db1, db2])
ret = inst.get_database("a")
self.assertEqual(ret, db1)
def test_get_database_bad(self):
inst = self.instance
db1 = fakes.FakeEntity()
db1.name = "a"
db2 = fakes.FakeEntity()
db2.name = "b"
inst.list_databases = Mock(return_value=[db1, db2])
self.assertRaises(exc.NoSuchDatabase, inst.get_database, "z")
def test_dbmgr_get(self):
mgr = fakes.FakeDatabaseManager()
rsrc = fakes.FakeDatabaseInstance()
rsrc.volume = {}
mgr._get = Mock(return_value=rsrc)
ret = mgr.get("fake")
self.assertTrue(isinstance(ret, CloudDatabaseInstance))
self.assertTrue(isinstance(ret.volume, CloudDatabaseVolume))
def test_dbmgr_create_backup(self):
inst = self.instance
mgr = inst.manager
name = utils.random_unicode()
description = utils.random_unicode()
mgr.api.method_post = Mock(return_value=(None, {"backup": {}}))
expected_uri = "/backups"
expected_body = {"backup": {"instance": inst.id, "name": name,
"description": description}}
mgr.create_backup(inst, name, description=description)
mgr.api.method_post.assert_called_once_with(expected_uri,
body=expected_body)
@patch('pyrax.clouddatabases.CloudDatabaseInstance',
new=fakes.FakeDatabaseInstance)
def test_mgr_restore_backup(self):
inst = self.instance
mgr = inst.manager
name = utils.random_unicode()
flavor = utils.random_unicode()
fref = utils.random_unicode()
volume = utils.random_unicode()
backup = utils.random_unicode()
mgr.api.method_post = Mock(return_value=(None, {"instance": {}}))
mgr.api._get_flavor_ref = Mock(return_value=fref)
expected_uri = "/%s" % mgr.uri_base
expected_body = {"instance": {"name": name, "flavorRef": fref,
"volume": {"size": volume}, "restorePoint":
{"backupRef": backup}}}
mgr.restore_backup(backup, name, flavor, volume)
mgr.api.method_post.assert_called_once_with(expected_uri,
body=expected_body)
def test_mgr_list_backups(self):
inst = self.instance
mgr = inst.manager
mgr.api._backup_manager.list = Mock(return_value=(None, None))
mgr.list_backups(inst)
mgr.api._backup_manager.list.assert_called_once_with(instance=inst,
limit=20, marker=0)
def test_mgr_list_backups_for_instance(self):
inst = self.instance
mgr = inst.manager
mgr.api.method_get = Mock(return_value=(None, {"backups": []}))
expected_uri = "/%s/%s/backups?limit=20&marker=0" % (mgr.uri_base, inst.id)
mgr._list_backups_for_instance(inst)
mgr.api.method_get.assert_called_once_with(expected_uri)
def test_create_database(self):
inst = self.instance
inst._database_manager.create = Mock()
inst._database_manager.find = Mock()
db = inst.create_database(name="test")
inst._database_manager.create.assert_called_once_with(name="test",
character_set="utf8", collate="utf8_general_ci",
return_none=True)
def test_create_user(self):
inst = self.instance
inst._user_manager.create = Mock()
inst._user_manager.find = Mock()
name = utils.random_unicode()
password = utils.random_unicode()
database_names = utils.random_unicode()
host = utils.random_unicode()
inst.create_user(name=name, password=password,
database_names=database_names, host=host)
inst._user_manager.create.assert_called_once_with(name=name,
password=password, database_names=[database_names], host=host,
return_none=True)
def test_delete_database(self):
inst = self.instance
inst._database_manager.delete = Mock()
inst.delete_database("dbname")
inst._database_manager.delete.assert_called_once_with("dbname")
def test_delete_user(self):
inst = self.instance
inst._user_manager.delete = Mock()
inst.delete_user("username")
inst._user_manager.delete.assert_called_once_with("username")
def test_delete_database_direct(self):
inst = self.instance
mgr = inst.manager
name = utils.random_unicode()
db = CloudDatabaseDatabase(mgr, info={"name": name})
mgr.delete = Mock()
db.delete()
mgr.delete.assert_called_once_with(name)
def test_delete_user_direct(self):
inst = self.instance
mgr = inst.manager
name = utils.random_unicode()
user = CloudDatabaseUser(mgr, info={"name": name})
mgr.delete = Mock()
user.delete()
mgr.delete.assert_called_once_with(name)
def test_enable_root_user(self):
inst = self.instance
pw = utils.random_unicode()
fake_body = {"user": {"password": pw}}
inst.manager.api.method_post = Mock(return_value=(None, fake_body))
ret = inst.enable_root_user()
call_uri = "/instances/%s/root" % inst.id
inst.manager.api.method_post.assert_called_once_with(call_uri)
self.assertEqual(ret, pw)
def test_root_user_status(self):
inst = self.instance
fake_body = {"rootEnabled": True}
inst.manager.api.method_get = Mock(return_value=(None, fake_body))
ret = inst.root_user_status()
call_uri = "/instances/%s/root" % inst.id
inst.manager.api.method_get.assert_called_once_with(call_uri)
self.assertTrue(ret)
def test_restart(self):
inst = self.instance
inst.manager.action = Mock()
ret = inst.restart()
inst.manager.action.assert_called_once_with(inst, "restart")
def test_resize(self):
inst = self.instance
flavor_ref = utils.random_unicode()
inst.manager.api._get_flavor_ref = Mock(return_value=flavor_ref)
fake_body = {"flavorRef": flavor_ref}
inst.manager.action = Mock()
ret = inst.resize(42)
call_uri = "/instances/%s/action" % inst.id
inst.manager.action.assert_called_once_with(inst, "resize",
body=fake_body)
def test_resize_volume_too_small(self):
inst = self.instance
inst.volume.get = Mock(return_value=2)
self.assertRaises(exc.InvalidVolumeResize, inst.resize_volume, 1)
def test_resize_volume(self):
inst = self.instance
fake_body = {"volume": {"size": 2}}
inst.manager.action = Mock()
ret = inst.resize_volume(2)
inst.manager.action.assert_called_once_with(inst, "resize",
body=fake_body)
def test_resize_volume_direct(self):
inst = self.instance
vol = inst.volume
fake_body = {"volume": {"size": 2}}
inst.manager.action = Mock()
ret = vol.resize(2)
inst.manager.action.assert_called_once_with(inst, "resize",
body=fake_body)
def test_volume_get(self):
inst = self.instance
vol = inst.volume
att = vol.size
using_get = vol.get("size")
self.assertEqual(att, using_get)
def test_volume_get_fail(self):
inst = self.instance
vol = inst.volume
self.assertRaises(AttributeError, vol.get, "fake")
def test_inst_list_backups(self):
inst = self.instance
mgr = inst.manager
mgr._list_backups_for_instance = Mock()
inst.list_backups()
mgr._list_backups_for_instance.assert_called_once_with(inst, limit=20,
marker=0)
def test_inst_create_backup(self):
inst = self.instance
mgr = inst.manager
name = utils.random_unicode()
description = utils.random_unicode()
mgr.create_backup = Mock()
inst.create_backup(name, description=description)
mgr.create_backup.assert_called_once_with(inst, name,
description=description)
def test_get_flavor_property(self):
inst = self.instance
inst._loaded = True
flavor = inst.flavor
self.assertTrue(isinstance(flavor, CloudDatabaseFlavor))
def test_set_flavor_property_dict(self):
inst = self.instance
inst._loaded = True
inst.flavor = {"name": "test"}
self.assertTrue(isinstance(inst.flavor, CloudDatabaseFlavor))
def test_set_flavor_property_instance(self):
inst = self.instance
inst._loaded = True
flavor = CloudDatabaseFlavor(inst.manager, {"name": "test"})
inst.flavor = flavor
self.assertTrue(isinstance(inst.flavor, CloudDatabaseFlavor))
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_list_databases_for_instance(self):
clt = self.client
inst = self.instance
limit = utils.random_unicode()
marker = utils.random_unicode()
inst.list_databases = Mock(return_value=["db"])
ret = clt.list_databases(inst, limit=limit, marker=marker)
self.assertEqual(ret, ["db"])
inst.list_databases.assert_called_once_with(limit=limit, marker=marker)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_create_database_for_instance(self):
clt = self.client
inst = self.instance
inst.create_database = Mock(return_value=["db"])
nm = utils.random_unicode()
ret = clt.create_database(inst, nm)
self.assertEqual(ret, ["db"])
inst.create_database.assert_called_once_with(nm,
character_set=None, collate=None)
def test_clt_get_database(self):
clt = self.client
inst = self.instance
inst.get_database = Mock()
nm = utils.random_unicode()
clt.get_database(inst, nm)
inst.get_database.assert_called_once_with(nm)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_delete_database_for_instance(self):
clt = self.client
inst = self.instance
inst.delete_database = Mock()
nm = utils.random_unicode()
clt.delete_database(inst, nm)
inst.delete_database.assert_called_once_with(nm)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_list_users_for_instance(self):
clt = self.client
inst = self.instance
limit = utils.random_unicode()
marker = utils.random_unicode()
inst.list_users = Mock(return_value=["user"])
ret = clt.list_users(inst, limit=limit, marker=marker)
self.assertEqual(ret, ["user"])
inst.list_users.assert_called_once_with(limit=limit, marker=marker)
def test_create_user_for_instance(self):
clt = self.client
inst = self.instance
inst.create_user = Mock()
nm = utils.random_unicode()
pw = utils.random_unicode()
host = utils.random_unicode()
ret = clt.create_user(inst, nm, pw, ["db"], host=host)
inst.create_user.assert_called_once_with(name=nm, password=pw,
database_names=["db"], host=host)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_delete_user_for_instance(self):
clt = self.client
inst = self.instance
inst.delete_user = Mock()
nm = utils.random_unicode()
clt.delete_user(inst, nm)
inst.delete_user.assert_called_once_with(nm)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_enable_root_user_for_instance(self):
clt = self.client
inst = self.instance
inst.enable_root_user = Mock()
clt.enable_root_user(inst)
inst.enable_root_user.assert_called_once_with()
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_root_user_status_for_instance(self):
clt = self.client
inst = self.instance
inst.root_user_status = Mock()
clt.root_user_status(inst)
inst.root_user_status.assert_called_once_with()
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_get_user_by_client(self):
clt = self.client
inst = self.instance
inst.get_user = Mock()
fakeuser = utils.random_unicode()
clt.get_user(inst, fakeuser)
inst.get_user.assert_called_once_with(fakeuser)
def test_get_user(self):
inst = self.instance
good_name = utils.random_unicode()
user = fakes.FakeDatabaseUser(manager=None, info={"name": good_name})
inst._user_manager.get = Mock(return_value=user)
returned = inst.get_user(good_name)
self.assertEqual(returned, user)
def test_get_user_fail(self):
inst = self.instance
bad_name = utils.random_unicode()
inst._user_manager.get = Mock(side_effect=exc.NotFound(""))
self.assertRaises(exc.NoSuchDatabaseUser, inst.get_user, bad_name)
def test_get_db_names(self):
inst = self.instance
mgr = inst._user_manager
mgr.instance = inst
dbname1 = utils.random_ascii()
dbname2 = utils.random_ascii()
inst.list_databases = Mock(return_value=((dbname1, dbname2)))
resp = mgr._get_db_names(dbname1)
self.assertEqual(resp, [dbname1])
def test_get_db_names_not_strict(self):
inst = self.instance
mgr = inst._user_manager
mgr.instance = inst
dbname1 = utils.random_ascii()
dbname2 = utils.random_ascii()
inst.list_databases = Mock(return_value=((dbname1, dbname2)))
resp = mgr._get_db_names("BAD", strict=False)
self.assertEqual(resp, ["BAD"])
def test_get_db_names_fail(self):
inst = self.instance
mgr = inst._user_manager
mgr.instance = inst
dbname1 = utils.random_ascii()
dbname2 = utils.random_ascii()
inst.list_databases = Mock(return_value=((dbname1, dbname2)))
self.assertRaises(exc.NoSuchDatabase, mgr._get_db_names, "BAD")
def test_change_user_password(self):
inst = self.instance
fakename = utils.random_ascii()
newpass = utils.random_ascii()
resp = fakes.FakeResponse()
resp.status_code = 202
inst._user_manager.api.method_put = Mock(return_value=(resp, {}))
fakeuser = fakes.FakeDatabaseUser(inst._user_manager, {"name": fakename})
inst._user_manager.get = Mock(return_value=fakeuser)
inst.change_user_password(fakename, newpass)
inst._user_manager.api.method_put.assert_called_once_with(
"/None/%s" % fakename, body={"user": {"password": newpass}})
def test_update_user(self):
inst = self.instance
mgr = inst._user_manager
user = utils.random_unicode()
name = utils.random_unicode()
password = utils.random_unicode()
host = utils.random_unicode()
mgr.update = Mock()
inst.update_user(user, name=name, password=password, host=host)
mgr.update.assert_called_once_with(user, name=name, password=password,
host=host)
def test_user_manager_update(self):
inst = self.instance
mgr = inst._user_manager
username = utils.random_unicode()
user = fakes.FakeDatabaseUser(mgr, info={"name": username})
name = utils.random_unicode()
host = utils.random_unicode()
password = utils.random_unicode()
mgr.api.method_put = Mock(return_value=(None, None))
expected_uri = "/%s/%s" % (mgr.uri_base, username)
expected_body = {"user": {"name": name, "host": host,
"password": password}}
mgr.update(user, name=name, host=host, password=password)
mgr.api.method_put.assert_called_once_with(expected_uri,
body=expected_body)
def test_user_manager_update_missing(self):
inst = self.instance
mgr = inst._user_manager
username = utils.random_unicode()
user = fakes.FakeDatabaseUser(mgr, info={"name": username})
self.assertRaises(exc.MissingDBUserParameters, mgr.update, user)
def test_user_manager_update_unchanged(self):
inst = self.instance
mgr = inst._user_manager
username = utils.random_unicode()
user = fakes.FakeDatabaseUser(mgr, info={"name": username})
self.assertRaises(exc.DBUpdateUnchanged, mgr.update, user,
name=username)
def test_list_user_access(self):
inst = self.instance
dbname1 = utils.random_ascii()
dbname2 = utils.random_ascii()
acc = {"databases": [{"name": dbname1}, {"name": dbname2}]}
inst._user_manager.api.method_get = Mock(return_value=(None, acc))
db_list = inst.list_user_access("fakeuser")
self.assertEqual(len(db_list), 2)
self.assertTrue(db_list[0].name in (dbname1, dbname2))
def test_list_user_access_not_found(self):
inst = self.instance
mgr = inst._user_manager
mgr.api.method_get = Mock(side_effect=exc.NotFound(""))
username = utils.random_unicode()
user = fakes.FakeDatabaseUser(mgr, info={"name": username})
self.assertRaises(exc.NoSuchDatabaseUser, mgr.list_user_access, user)
def test_grant_user_access(self):
inst = self.instance
fakeuser = utils.random_ascii()
dbname1 = utils.random_ascii()
inst._user_manager.api.method_put = Mock(return_value=(None, None))
inst.grant_user_access(fakeuser, dbname1, strict=False)
inst._user_manager.api.method_put.assert_called_once_with(
"/None/%s/databases" % fakeuser, body={"databases": [{"name":
dbname1}]})
def test_grant_user_access_not_found(self):
inst = self.instance
mgr = inst._user_manager
mgr.api.method_put = Mock(side_effect=exc.NotFound(""))
username = utils.random_unicode()
user = fakes.FakeDatabaseUser(mgr, info={"name": username})
db_names = utils.random_unicode()
mgr._get_db_names = Mock(return_value=[])
self.assertRaises(exc.NoSuchDatabaseUser, mgr.grant_user_access, user,
db_names)
def test_revoke_user_access(self):
inst = self.instance
fakeuser = utils.random_ascii()
dbname1 = utils.random_ascii()
inst._user_manager.api.method_delete = Mock(return_value=(None, None))
inst.revoke_user_access(fakeuser, dbname1, strict=False)
inst._user_manager.api.method_delete.assert_called_once_with(
"/None/%s/databases/%s" % (fakeuser, dbname1))
def test_backup_mgr_create_body(self):
inst = self.instance
mgr = inst.manager
bu_mgr = mgr.api._backup_manager
name = utils.random_unicode()
description = utils.random_unicode()
expected_body = {"backup": {"instance": inst.id, "name": name,
"description": description}}
ret = bu_mgr._create_body(name, inst, description=description)
self.assertEqual(ret, expected_body)
def test_backup_mgr_list(self):
inst = self.instance
mgr = inst.manager
bu_mgr = mgr.api._backup_manager
fake_val = utils.random_unicode()
bu_mgr._list = Mock(return_value=fake_val)
ret = bu_mgr.list()
self.assertEqual(ret, fake_val)
def test_backup_mgr_list_instance(self):
inst = self.instance
mgr = inst.manager
bu_mgr = mgr.api._backup_manager
db_mgr = mgr.api._manager
db_mgr._list_backups_for_instance = Mock()
bu_mgr.list(instance=inst)
db_mgr._list_backups_for_instance.assert_called_once_with(inst, limit=20,
marker=0)
def test_clt_change_user_password(self):
clt = self.client
inst = self.instance
inst.change_user_password = Mock()
user = utils.random_unicode()
pw = utils.random_unicode()
clt.change_user_password(inst, user, pw)
inst.change_user_password.assert_called_once_with(user, pw)
def test_user_change_password(self):
inst = self.instance
mgr = inst.manager
password = utils.random_unicode()
user = CloudDatabaseUser(mgr, info={"name": "fake"})
mgr.change_user_password = Mock()
user.change_password(password)
mgr.change_user_password.assert_called_once_with(user, password)
def test_clt_update_user(self):
clt = self.client
inst = self.instance
inst.update_user = Mock()
user = utils.random_unicode()
name = utils.random_unicode()
password = utils.random_unicode()
host = utils.random_unicode()
clt.update_user(inst, user, name=name, password=password, host=host)
inst.update_user.assert_called_once_with(user, name=name,
password=password, host=host)
def test_user_update(self):
inst = self.instance
mgr = inst.manager
name = utils.random_unicode()
password = utils.random_unicode()
host = utils.random_unicode()
user = CloudDatabaseUser(mgr, info={"name": "fake"})
mgr.update = Mock()
user.update(name=name, password=password, host=host)
mgr.update.assert_called_once_with(user, name=name, password=password,
host=host)
def test_clt_list_user_access(self):
clt = self.client
inst = self.instance
inst.list_user_access = Mock()
user = utils.random_unicode()
clt.list_user_access(inst, user)
inst.list_user_access.assert_called_once_with(user)
def test_user_list_user_access(self):
inst = self.instance
mgr = inst.manager
user = CloudDatabaseUser(mgr, info={"name": "fake"})
mgr.list_user_access = Mock()
user.list_user_access()
mgr.list_user_access.assert_called_once_with(user)
def test_clt_grant_user_access(self):
clt = self.client
inst = self.instance
inst.grant_user_access = Mock()
user = utils.random_unicode()
db_names = utils.random_unicode()
clt.grant_user_access(inst, user, db_names)
inst.grant_user_access.assert_called_once_with(user, db_names,
strict=True)
def test_user_grant_user_access(self):
inst = self.instance
mgr = inst.manager
user = CloudDatabaseUser(mgr, info={"name": "fake"})
db_names = utils.random_unicode()
strict = utils.random_unicode()
mgr.grant_user_access = Mock()
user.grant_user_access(db_names, strict=strict)
mgr.grant_user_access.assert_called_once_with(user, db_names,
strict=strict)
def test_clt_revoke_user_access(self):
clt = self.client
inst = self.instance
inst.revoke_user_access = Mock()
user = utils.random_unicode()
db_names = utils.random_unicode()
clt.revoke_user_access(inst, user, db_names)
inst.revoke_user_access.assert_called_once_with(user, db_names,
strict=True)
def test_user_revoke_user_access(self):
inst = self.instance
mgr = inst.manager
user = CloudDatabaseUser(mgr, info={"name": "fake"})
db_names = utils.random_unicode()
strict = utils.random_unicode()
mgr.revoke_user_access = Mock()
user.revoke_user_access(db_names, strict=strict)
mgr.revoke_user_access.assert_called_once_with(user, db_names,
strict=strict)
def test_clt_restart(self):
clt = self.client
inst = self.instance
inst.restart = Mock()
clt.restart(inst)
inst.restart.assert_called_once_with()
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_inst_resize(self):
clt = self.client
inst = self.instance
inst.resize = Mock()
clt.resize(inst, "flavor")
inst.resize.assert_called_once_with("flavor")
def test_get_limits(self):
self.assertRaises(NotImplementedError, self.client.get_limits)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_list_flavors(self):
clt = self.client
clt._flavor_manager.list = Mock()
limit = utils.random_unicode()
marker = utils.random_unicode()
clt.list_flavors(limit=limit, marker=marker)
clt._flavor_manager.list.assert_called_once_with(limit=limit,
marker=marker)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_get_flavor(self):
clt = self.client
clt._flavor_manager.get = Mock()
clt.get_flavor("flavorid")
clt._flavor_manager.get.assert_called_once_with("flavorid")
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_get_flavor_ref_for_obj(self):
clt = self.client
info = {"id": 1,
"name": "test_flavor",
"ram": 42,
"links": [{
"href": example_uri,
"rel": "self"}]}
flavor_obj = CloudDatabaseFlavor(clt._manager, info)
ret = clt._get_flavor_ref(flavor_obj)
self.assertEqual(ret, example_uri)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_get_flavor_ref_for_id(self):
clt = self.client
info = {"id": 1,
"name": "test_flavor",
"ram": 42,
"links": [{
"href": example_uri,
"rel": "self"}]}
flavor_obj = CloudDatabaseFlavor(clt._manager, info)
clt.get_flavor = Mock(return_value=flavor_obj)
ret = clt._get_flavor_ref(1)
self.assertEqual(ret, example_uri)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_get_flavor_ref_for_name(self):
clt = self.client
info = {"id": 1,
"name": "test_flavor",
"ram": 42,
"links": [{
"href": example_uri,
"rel": "self"}]}
flavor_obj = CloudDatabaseFlavor(clt._manager, info)
clt.get_flavor = Mock(side_effect=exc.NotFound(""))
clt.list_flavors = Mock(return_value=[flavor_obj])
ret = clt._get_flavor_ref("test_flavor")
self.assertEqual(ret, example_uri)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_get_flavor_ref_for_ram(self):
clt = self.client
info = {"id": 1,
"name": "test_flavor",
"ram": 42,
"links": [{
"href": example_uri,
"rel": "self"}]}
flavor_obj = CloudDatabaseFlavor(clt._manager, info)
clt.get_flavor = Mock(side_effect=exc.NotFound(""))
clt.list_flavors = Mock(return_value=[flavor_obj])
ret = clt._get_flavor_ref(42)
self.assertEqual(ret, example_uri)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_get_flavor_ref_not_found(self):
clt = self.client
info = {"id": 1,
"name": "test_flavor",
"ram": 42,
"links": [{
"href": example_uri,
"rel": "self"}]}
flavor_obj = CloudDatabaseFlavor(clt._manager, info)
clt.get_flavor = Mock(side_effect=exc.NotFound(""))
clt.list_flavors = Mock(return_value=[flavor_obj])
self.assertRaises(exc.FlavorNotFound, clt._get_flavor_ref, "nonsense")
def test_clt_list_backups(self):
clt = self.client
mgr = clt._backup_manager
mgr.list = Mock()
clt.list_backups()
mgr.list.assert_called_once_with(instance=None, limit=20, marker=0)
def test_clt_list_backups_for_instance(self):
clt = self.client
mgr = clt._backup_manager
mgr.list = Mock()
inst = utils.random_unicode()
clt.list_backups(instance=inst)
mgr.list.assert_called_once_with(instance=inst, limit=20, marker=0)
def test_clt_get_backup(self):
clt = self.client
mgr = clt._backup_manager
mgr.get = Mock()
backup = utils.random_unicode()
clt.get_backup(backup)
mgr.get.assert_called_once_with(backup)
def test_clt_delete_backup(self):
clt = self.client
mgr = clt._backup_manager
mgr.delete = Mock()
backup = utils.random_unicode()
clt.delete_backup(backup)
mgr.delete.assert_called_once_with(backup)
def test_clt_create_backup(self):
clt = self.client
inst = self.instance
name = utils.random_unicode()
description = utils.random_unicode()
inst.create_backup = Mock()
clt.create_backup(inst, name, description=description)
inst.create_backup.assert_called_once_with(name,
description=description)
def test_clt_restore_backup(self):
clt = self.client
mgr = clt._manager
backup = utils.random_unicode()
name = utils.random_unicode()
flavor = utils.random_unicode()
volume = utils.random_unicode()
mgr.restore_backup = Mock()
clt.restore_backup(backup, name, flavor, volume)
mgr.restore_backup.assert_called_once_with(backup, name, flavor, volume)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_create_body_db(self):
mgr = self.instance._database_manager
nm = utils.random_unicode()
ret = mgr._create_body(nm, character_set="CS", collate="CO")
expected = {"databases": [
{"name": nm,
"character_set": "CS",
"collate": "CO"}]}
self.assertEqual(ret, expected)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_create_body_user(self):
inst = self.instance
mgr = inst._user_manager
nm = utils.random_unicode()
pw = utils.random_unicode()
dbnames = [utils.random_unicode(), utils.random_unicode()]
ret = mgr._create_body(nm, password=pw, database_names=dbnames)
expected = {"users": [
{"name": nm,
"password": pw,
"databases": [{"name": dbnames[0]}, {"name": dbnames[1]}]}]}
self.assertEqual(ret, expected)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_create_body_user_host(self):
inst = self.instance
mgr = inst._user_manager
nm = utils.random_unicode()
host = utils.random_unicode()
pw = utils.random_unicode()
dbnames = [utils.random_unicode(), utils.random_unicode()]
ret = mgr._create_body(nm, host=host, password=pw,
database_names=dbnames)
expected = {"users": [
{"name": nm,
"password": pw,
"host": host,
"databases": [{"name": dbnames[0]}, {"name": dbnames[1]}]}]}
self.assertEqual(ret, expected)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_create_body_flavor(self):
clt = self.client
nm = utils.random_unicode()
clt._get_flavor_ref = Mock(return_value=example_uri)
ret = clt._manager._create_body(nm)
expected = {"instance": {
"name": nm,
"flavorRef": example_uri,
"volume": {"size": 1},
"databases": [],
"users": []}}
self.assertEqual(ret, expected)
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_missing_db_parameters(self):
clt = self.client
nm = utils.random_unicode()
clt._get_flavor_ref = Mock(return_value=example_uri)
self.assertRaises(exc.MissingCloudDatabaseParameter,
clt._manager._create_body,nm, version="10")
@patch("pyrax.manager.BaseManager", new=fakes.FakeManager)
def test_create_body_datastore(self):
clt = self.client
nm = utils.random_unicode()
clt._get_flavor_ref = Mock(return_value=example_uri)
ret = clt._manager._create_body(nm, version="10", type="MariaDB")
expected = {"instance": {
"name": nm,
"flavorRef": example_uri,
"volume": {"size": 1},
"databases": [],
"users": [],
"datastore": {"type": "MariaDB", "version": "10"}}}
self.assertEqual(ret, expected)
if __name__ == "__main__":
unittest.main()
|
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
def InitDebugTagTypes():
return enum( 'GroupToParagraph', 'MergeSubtitles', 'PrintSubtitles', 'File' )
def InitDebugTags():
DebugTagType = InitDebugTagTypes()
debugTags = []
debugTags.append(DebugTagType.GroupToParagraph)
#debugTags.append(DebugTagType.MergeSubtitles)
debugTags.append(DebugTagType.PrintSubtitles)
#debugTags.append(DebugTagType.File)
return debugTags
|
""" Builtin vars node.
Not used much, esp. not in the form with arguments. Maybe used in some meta programming,
and hopefully can be predicted, because at run time, it is hard to support.
"""
from .ExpressionBases import ExpressionChildHavingBase
class ExpressionBuiltinVars(ExpressionChildHavingBase):
kind = "EXPRESSION_BUILTIN_VARS"
named_child = "source"
def __init__(self, source, source_ref):
ExpressionChildHavingBase.__init__(self, value=source, source_ref=source_ref)
def computeExpression(self, trace_collection):
# TODO: Should be possible to predict this.
trace_collection.onExceptionRaiseExit(BaseException)
return self, None, None
|
import feedparser
import socket
from urllib.request import Request, urlopen
class Bot:
def __init__(self, host, port, nick, ident, realname, testchannel):
self.host = host
self.port = port
self.nick = nick
self.ident = ident
self.realname = realname
self.testchannel = testchannel
self.readbuffer = ""
self.connection = None
@property
def connect_to_server(self):
self.connection = socket.socket()
self.connection.connect((self.host, int(self.port)))
print("Connecting...")
return self.connection
def set_nick(self):
self.connection.send(("NICK %s\r\n" % self.nick).encode('utf-8'))
print("Sending Nick request.")
self.connection.send(("USER %s %s bla :%s\r\n" % (self.ident, self.host, self.realname)).encode('utf-8'))
print("Sending User info.")
def join_channel(self):
self.connection.send(("JOIN %s\r\n" % self.testchannel).encode('utf-8'))
print("Joining %s." % self.testchannel)
def ping_pong(self, line):
self.connection.send(("PONG %s\r\n" % line[1]).encode('utf-8'))
def parse_irc_line(self, line, run_loop):
print(line)
line_split = line.split()
if line_split[0] == "PING":
self.ping_pong(line_split)
elif line_split[0] == (":" + self.host) or line_split[0] == (":" + self.nick) or len(line_split) < 4:
pass
elif line_split[3] == (":" + self.nick):
run_loop = self.parse_message(line_split, run_loop)
return run_loop
def parse_message(self, line_split, run_loop):
sender = line_split[0].split("~")[1].split("@")[0]
message = line_split[4:]
if message[0] == "Hello!":
print("Responding to \"Hello\" from %s." % sender)
self.connection.send(("PRIVMSG %s :Hello %s!\r\n" % (self.testchannel, sender)).encode('utf-8'))
elif message[0] == "Bye!":
self.connection.send(("PRIVMSG %s :Good bye!\r\n" % self.testchannel).encode('utf-8'))
print("Quiting IRC.")
self.connection.send("QUIT\r\n".encode('utf-8'))
run_loop = 0
elif message[0] == "news":
try:
if message[1] == "defcon":
url = 'https://defcon.org/defconrss.xml'
elif message[1] == "reddit":
try:
if message[2] == "security":
linkpath = "security"
elif message[2] == "netsec":
linkpath = "netsec"
else:
linkpath = ""
url = ("https://www.reddit.com/r/%s/.rss" % linkpath)
except IndexError:
url = "https://www.reddit.com/.rss"
else:
url = "https://news.google.com/news?&topic=tc&output=rss"
except IndexError:
url = "https://news.google.com/news?&topic=tc&output=rss"
self.get_news(url)
elif message[0] == "stock":
try:
self.get_stock(message[1])
except IndexError:
send_message = ("PRIVMSG %s :%s Missing stock symbol.\r\n" % (self.testchannel, sender)).encode('utf-8')
self.connection.send(send_message)
return run_loop
def get_stock(self, symbol):
quote = urlopen(Request('http://finance.yahoo.com/d/quotes.csv?s=%s&f=l1' % symbol))
compname = urlopen(Request('http://finance.yahoo.com/d/quotes.csv?s=%s&f=n' % symbol))
amount = quote.read().decode('utf-8').strip()
name = str(compname.read().decode('utf-8').strip())
self.connection.send(("PRIVMSG #%s :%s is at %s.\r\n" % (self.testchannel, name, amount)).encode('utf-8'))
def get_news(self, url):
rawdata = feedparser.parse(url)
self.connection.send(("PRIVMSG %s :%s\r\n" % (self.testchannel, rawdata.entries[0].title)).encode('utf-8'))
self.connection.send(("PRIVMSG %s :%s\r\n" % (self.testchannel, rawdata.entries[0].link)).encode('utf-8'))
|
__author__ = "Markus Gumbel"
__copyright__ = "The authors"
__license__ = "Apache 2"
__email__ = "m.gumbel@hs-mannheim.de"
__status__ = "Test"
from math import pi as PI
from Core.CellType import CellType
from Core.ExecConfig import ExecConfig
from Core.ModelConfig import ModelConfig
from Steppable.InitializerSteppable import InitializerSteppable
from Test.Steppable.MonitorSteppable import MonitorSteppable
class SphereTest(ModelConfig):
'''
Some experiments on a cell's shape.
'''
def __init__(self, sim, simthread):
ModelConfig.__init__(self, sim, simthread)
def _initModel(self):
self.name = "SphereTest"
self.adhFactor = 0.5 # average adhesion = 0.5
self.cellTypes = self._createCellTypes()
self.energyMatrix = self._createEnergyMatrix()
self._run() # Must be the last statement.
def _createCellTypes(self):
cellTypes = []
medium = CellType(name="Medium", frozen=True, minDiameter=0, maxDiameter=0,
growthVolumePerDay=0, nutrientRequirement=0, apoptosisTimeInDays=0,
volFit=1.0, surFit=1.0)
cellTypes.append(medium)
cell = CellType(name="Cell", minDiameter=20, maxDiameter=20,
growthVolumePerDay=10 * self.calcVolume(10),
nutrientRequirement=1.0, apoptosisTimeInDays=180000,
volFit=0.9, surFit=0.5)
cellTypes.append(cell)
return cellTypes
def _initCells(self, stepable):
r = self.cellTypes[1].getAvgDiameter() / 2.0
length = PI ** (1.0 / 2.0) * r if self.execConfig.dimensions == 2 \
else (4.0 / 3.0 * PI) ** (1.0 / 3.0) * r
x = self.execConfig.xLength * 0.3 - length / 2.0
y = self.execConfig.yLength * 0.3 - length / 2.0
z = self.execConfig.zLength * 0.3 - length / 2.0 \
if self.execConfig.dimensions == 3 else 0
xl = length
yl = length
zl = 1 if self.execConfig.dimensions == 2 else length
self._addCubicCell(0, x, y, z, xl, yl, zl, stepable)
x = self.execConfig.xLength * 0.7 - length / 2.0
y = self.execConfig.yLength * 0.7 - length / 2.0
z = self.execConfig.zLength * 0.7 - length / 2.0 \
if self.execConfig.dimensions == 3 else 0
self._addCubicCell(1, x, y, z, xl, yl, zl, stepable)
def _getSteppables(self):
steppableList = []
steppableList.append(InitializerSteppable(self.sim, self))
steppableList.append(MonitorSteppable(self.sim, self))
return steppableList
def _createExecConfig(self):
return ExecConfig(xLength=70, yLength=70, zLength=70, voxelDensity=1.5)
|
from jinja2 import Environment, FileSystemLoader
import os
import pathlib
from typing import List
root_directory = pathlib.Path(
os.path.realpath(os.path.dirname(os.path.realpath(__file__)))
).parent.parent
print(root_directory)
jinja_env = Environment(
loader=FileSystemLoader(str(root_directory / "templates" / "poms")),
keep_trailing_newline=True,
)
def render(template_name: str, output_name: str, **kwargs):
template = jinja_env.get_template(template_name)
t = template.stream(kwargs)
directory = os.path.dirname(output_name)
if not os.path.isdir(directory):
os.makedirs(directory)
t.dump(str(output_name))
|
from keystoneclient.v2_0 import client as keystoneclient
from heatclient import client as heatclient
from Deployer import Deployer
import uuid
import logging
HEAT_VERSION = '1'
class HeatclientProvider():
@staticmethod
def get_heatclient(extras):
# first, a connection to keystone has to be established in order to load the service catalog for the orchestration endpoint (heat)
# the design_uri has to be given in the sm.cfg file so that no other OpenStack deployment can be used
kc = keystoneclient.Client(auth_url=extras['design_uri'],
username=extras['username'],
password=extras['password'],
tenant_name=extras['tenant_name']
)
# get the orchestration part of the service catalog
orch = kc.service_catalog.get_endpoints(service_type='orchestration',
region_name=extras['region'],
endpoint_type='publicURL'
)
# create a heat client with acquired public endpoint
# if the correct region had been given, there is supposed to be but one entry for the orchestrator URLs
hc = heatclient.Client(HEAT_VERSION, endpoint=orch['orchestration'][0]['publicURL'],token=kc.auth_token)
return hc
class OpenstackDeployer(Deployer):
def __init__(self, *args, **kwargs):
"""Create a heatclient instance.
In kwargs, the following values have to be set: design_uri, username, password, tenant_name and region. These credentials need to be a valid Openstack login.
"""
self.logger = logging.getLogger("disco")
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
self.stack_name = args[0]['stack_name']
self.logger.addHandler(ch)
self.hc = HeatclientProvider.get_heatclient(args[0])
def deploy(self, heatTemplate):
"""Deploy given Heat template on Openstack.
:param heatTemplate: Heat template as a string which describes the cluster
:return: stack.create's return value if successful, otherwise the thrown Exception
"""
# set the required attributes (stack name and Heat template) to what is needed
heatTemplate = heatTemplate.rstrip()
body = {
'stack_name': self.stack_name,
'template': heatTemplate
}
self.logger.info('the stack\'s name is '+body['stack_name'])
tmp = None
try:
tmp = self.hc.stacks.create(**body)
except Exception as e:
tmp = e
return tmp
def retrieve(self, stack_id):
'''
retrieve the requested output values given in list
:param stack_id: ID of requested stack's outputs
:return: each available requested output value as dictionary or None in case of exception
'''
current_stack = self.hc.stacks.get(stack_id)
return_value = {}
if current_stack.stack_status=="CREATE_FAILED":
current_stack.outputs.append({'output_key':'stack_status_reason','output_value':current_stack.stack_status_reason})
try:
return current_stack.outputs
except:
return None
# the value will be saved among the attributes which will be returned to the user
return return_value
def delete(self, stack_id):
"""
delete will delete the stack with the given stack id from OpenStack
:param stack_id: stack's id on OpenStack
:return: True for successful, False otherwise
"""
try:
body = {
'stack_id': stack_id
}
try:
self.hc.stacks.delete(**body)
except:
return False
return True
except:
return False
|
N = int(input())
for i in range(0,N):
nums = input().split(" ")
X = int(nums[0])
Y = int(nums[1])
if(Y == 0):
print("divisao impossivel")
else:
print("{0:.1f}".format(X/Y))
|
"""Classes and global objects related to resolving U{XML
Namespaces<http://www.w3.org/TR/2006/REC-xml-names-20060816/index.html>}."""
import pyxb_114
import os
import fnmatch
import pyxb_114.utils.utility
import archive
import utility
class _Resolvable_mixin (pyxb_114.cscRoot):
"""Mix-in indicating that this object may have references to unseen named components.
This class is mixed-in to those XMLSchema components that have a reference
to another component that is identified by a QName. Resolution of that
component may need to be delayed if the definition of the component has
not yet been read.
"""
#_TraceResolution = True
_TraceResolution = False
def isResolved (self):
"""Determine whether this named component is resolved.
Override this in the child class."""
raise pyxb_114.LogicError('Resolved check not implemented in %s' % (self.__class__,))
def _resolve (self):
"""Perform whatever steps are required to resolve this component.
Resolution is performed in the context of the namespace to which the
component belongs. Invoking this method may fail to complete the
resolution process if the component itself depends on unresolved
components. The sole caller of this should be
L{_NamespaceResolution_mixin.resolveDefinitions}.
This method is permitted (nay, encouraged) to raise an exception if
resolution requires interpreting a QName and the named component
cannot be found.
Override this in the child class. In the prefix, if L{isResolved} is
true, return right away. If something prevents you from completing
resolution, invoke L{self._queueForResolution()} (so it is retried
later) and immediately return self. Prior to leaving after successful
resolution discard any cached dom node by setting C{self.__domNode=None}.
@return: C{self}, whether or not resolution succeeds.
@raise pyxb_114.SchemaValidationError: if resolution requlres a reference to an unknown component
"""
raise pyxb_114.LogicError('Resolution not implemented in %s' % (self.__class__,))
def _queueForResolution (self, why=None, depends_on=None):
"""Short-hand to requeue an object if the class implements _namespaceContext().
"""
if (why is not None) and self._TraceResolution:
print 'Resolution delayed for %s: %s\n\tDepends on: %s' % (self, why, depends_on)
self._namespaceContext().queueForResolution(self, depends_on)
class _NamespaceResolution_mixin (pyxb_114.cscRoot):
"""Mix-in that aggregates those aspects of XMLNamespaces relevant to
resolving component references.
"""
# A set of namespaces which some schema imported while processing with
# this namespace as target.
__importedNamespaces = None
# A set of namespaces which appear in namespace declarations of schema
# with this namespace as target.
__referencedNamespaces = None
# A list of Namespace._Resolvable_mixin instances that have yet to be
# resolved.
__unresolvedComponents = None
# A map from Namespace._Resolvable_mixin instances in
# __unresolvedComponents to sets of other unresolved objects on which they
# depend.
__unresolvedDependents = None
def _reset (self):
"""CSC extension to reset fields of a Namespace.
This one handles component-resolution--related data."""
getattr(super(_NamespaceResolution_mixin, self), '_reset', lambda *args, **kw: None)()
self.__unresolvedComponents = []
self.__unresolvedDependents = {}
self.__importedNamespaces = set()
self.__referencedNamespaces = set()
def _getState_csc (self, kw):
kw.update({
'importedNamespaces': self.__importedNamespaces,
'referencedNamespaces': self.__referencedNamespaces,
})
return getattr(super(_NamespaceResolution_mixin, self), '_getState_csc', lambda _kw: _kw)(kw)
def _setState_csc (self, kw):
self.__importedNamespaces = kw['importedNamespaces']
self.__referencedNamespaces = kw['referencedNamespaces']
return getattr(super(_NamespaceResolution_mixin, self), '_setState_csc', lambda _kw: self)(kw)
def importNamespace (self, namespace):
self.__importedNamespaces.add(namespace)
return self
def _referenceNamespace (self, namespace):
self._activate()
self.__referencedNamespaces.add(namespace)
return self
def importedNamespaces (self):
"""Return the set of namespaces which some schema imported while
processing with this namespace as target."""
return frozenset(self.__importedNamespaces)
def _transferReferencedNamespaces (self, module_record):
assert isinstance(module_record, archive.ModuleRecord)
module_record._setReferencedNamespaces(self.__referencedNamespaces)
self.__referencedNamespaces.clear()
def referencedNamespaces (self):
"""Return the set of namespaces which appear in namespace declarations
of schema with this namespace as target."""
return frozenset(self.__referencedNamespaces)
rn = self.__referencedNamespaces.copy()
for mr in self.moduleRecords():
if mr.isIncorporated():
rn.update(mr.referencedNamespaces())
return rn
def queueForResolution (self, resolvable, depends_on=None):
"""Invoked to note that a component may have references that will need
to be resolved.
Newly created named components are often unresolved, as are components
which, in the course of resolution, are found to depend on another
unresolved component.
@param resolvable: An instance of L{_Resolvable_mixin} that is later to
be resolved.
@keyword depends_on: C{None}, or an instance of L{_Resolvable_mixin}
which C{resolvable} requires to be resolved in order to resolve
itself.
@return: C{resolvable}
"""
assert isinstance(resolvable, _Resolvable_mixin)
if not resolvable.isResolved():
assert depends_on is None or isinstance(depends_on, _Resolvable_mixin)
self.__unresolvedComponents.append(resolvable)
if depends_on is not None and not depends_on.isResolved():
import pyxb_114.xmlschema.structures
assert isinstance(depends_on, _Resolvable_mixin)
assert isinstance(depends_on, pyxb_114.xmlschema.structures._NamedComponent_mixin)
self.__unresolvedDependents.setdefault(resolvable, set()).add(depends_on)
return resolvable
def needsResolution (self):
"""Return C{True} iff this namespace has not been resolved."""
return self.__unresolvedComponents is not None
def _replaceComponent_csc (self, existing_def, replacement_def):
"""Replace a component definition if present in the list of unresolved components.
"""
try:
index = self.__unresolvedComponents.index(existing_def)
print 'Replacing unresolved %s' % (existing_def,)
if (replacement_def is None) or (replacement_def in self.__unresolvedComponents):
del self.__unresolvedComponents[index]
else:
assert isinstance(replacement_def, _Resolvable_mixin)
self.__unresolvedComponents[index] = replacement_def
# Rather than assume the replacement depends on the same
# resolvables as the original, just wipe the dependency record:
# it'll get recomputed later if it's still important.
if existing_def in self.__unresolvedDependents:
del self.__unresolvedDependents[existing_def]
except ValueError:
pass
return getattr(super(_NamespaceResolution_mixin, self), '_replaceComponent_csc', lambda *args, **kw: replacement_def)(existing_def, replacement_def)
def resolveDefinitions (self, allow_unresolved=False):
"""Loop until all references within the associated resolvable objects
have been resolved.
This method iterates through all components on the unresolved list,
invoking the _resolve method of each. If the component could not be
resolved in this pass, it iis placed back on the list for the next
iteration. If an iteration completes without resolving any of the
unresolved components, a pyxb_114.NotInNamespaceError exception is raised.
@note: Do not invoke this until all top-level definitions for the
namespace have been provided. The resolution routines are entitled to
raise a validation exception if a reference to an unrecognized
component is encountered.
"""
num_loops = 0
if not self.needsResolution():
return True
while 0 < len(self.__unresolvedComponents):
# Save the list of unresolved objects, reset the list to capture
# any new objects defined during resolution, and attempt the
# resolution for everything that isn't resolved.
unresolved = self.__unresolvedComponents
#print 'Looping for %d unresolved definitions: %s' % (len(unresolved), ' '.join([ str(_r) for _r in unresolved]))
num_loops += 1
#assert num_loops < 18
self.__unresolvedComponents = []
self.__unresolvedDependents = {}
for resolvable in unresolved:
# Attempt the resolution.
resolvable._resolve()
# Either we resolved it, or we queued it to try again later
assert resolvable.isResolved() or (resolvable in self.__unresolvedComponents), 'Lost resolvable %s' % (resolvable,)
# We only clone things that have scope None. We never
# resolve things that have scope None. Therefore, we
# should never have resolved something that has
# clones.
if (resolvable.isResolved() and (resolvable._clones() is not None)):
assert False
if self.__unresolvedComponents == unresolved:
if allow_unresolved:
return False
# This only happens if we didn't code things right, or the
# there is a circular dependency in some named component
# (i.e., the schema designer didn't do things right).
failed_components = []
import pyxb_114.xmlschema.structures
for d in self.__unresolvedComponents:
if isinstance(d, pyxb_114.xmlschema.structures._NamedComponent_mixin):
failed_components.append('%s named %s' % (d.__class__.__name__, d.name()))
else:
if isinstance(d, pyxb_114.xmlschema.structures.AttributeUse):
print d.attributeDeclaration()
failed_components.append('Anonymous %s' % (d.__class__.__name__,))
raise pyxb_114.NotInNamespaceError('Infinite loop in resolution:\n %s' % ("\n ".join(failed_components),))
# Replace the list of unresolved components with None, so that
# attempts to subsequently add another component fail.
self.__unresolvedComponents = None
self.__unresolvedDependents = None
# NOTE: Dependencies may require that we keep these around for a while
# longer.
#
# Remove the namespace context from everything, since we won't be
# resolving anything else.
self._releaseNamespaceContexts()
return True
def _unresolvedComponents (self):
"""Returns a reference to the list of unresolved components."""
return self.__unresolvedComponents
def _unresolvedDependents (self):
"""Returns a map from unresolved components to sets of components that
must be resolved first."""
return self.__unresolvedDependents
def ResolveSiblingNamespaces (sibling_namespaces):
"""Resolve all components in the sibling_namespaces.
@param sibling_namespaces : A set of namespaces expected to be closed
under dependency."""
for ns in sibling_namespaces:
ns.configureCategories([archive.NamespaceArchive._AnonymousCategory()])
ns.validateComponentModel()
def cmp_for_deps (ns1, ns2):
"""Sort namespaces so dependencies get resolved first"""
if ns2 not in dependency_map.get(ns1, set()):
return -1
if ns1 not in dependency_map.get(ns2, set()):
return 1
return 0
need_resolved_set = set(sibling_namespaces)
dependency_map = {}
last_state = None
while need_resolved_set:
need_resolved_list = list(need_resolved_set)
if dependency_map:
need_resolved_list.sort(cmp_for_deps)
need_resolved_set = set()
dependency_map = {}
for ns in need_resolved_list:
if not ns.needsResolution():
continue
#print 'Attempting resolution %s' % (ns.uri(),)
if not ns.resolveDefinitions(allow_unresolved=True):
print 'Holding incomplete resolution %s' % (ns.uri(),)
deps = dependency_map.setdefault(ns, set())
for (c, dcs) in ns._unresolvedDependents().iteritems():
for dc in dcs:
dns = dc.expandedName().namespace()
if dns != ns:
deps.add(dns)
print '%s depends on %s' % (ns, ' ; '.join([ str(_dns) for _dns in deps ]))
need_resolved_set.add(ns)
# Exception termination check: if we have the same set of incompletely
# resolved namespaces, and each has the same number of unresolved
# components, assume there's an truly unresolvable dependency: either
# due to circularity, or because there was an external namespace that
# was missed from the sibling list.
state = []
for ns in need_resolved_set:
state.append( (ns, len(ns._unresolvedComponents())) )
state = tuple(state)
if last_state == state:
raise pyxb_114.LogicError('Unexpected external dependency in sibling namespaces: %s' % ("\n ".join( [str(_ns) for _ns in need_resolved_set ]),))
last_state = state
class NamespaceContext (object):
"""Records information associated with namespaces at a DOM node.
"""
def __str__ (self):
rv = [ 'NamespaceContext ' ]
if self.defaultNamespace() is not None:
rv.extend([ '(defaultNamespace=', str(self.defaultNamespace()), ') '])
if self.targetNamespace() is not None:
rv.extend([ '(targetNamespace=', str(self.targetNamespace()), ') '])
rv.append("\n")
for (pfx, ns) in self.inScopeNamespaces().items():
if pfx is not None:
rv.append(' xmlns:%s=%s' % (pfx, str(ns)))
return ''.join(rv)
__TargetNamespaceAttributes = { }
@classmethod
def _AddTargetNamespaceAttribute (cls, expanded_name, attribute_name):
assert expanded_name is not None
cls.__TargetNamespaceAttributes[expanded_name] = attribute_name
@classmethod
def _TargetNamespaceAttribute (cls, expanded_name):
return cls.__TargetNamespaceAttributes.get(expanded_name, None)
# Support for holding onto referenced namespaces until we have a target
# namespace to give them to.
__pendingReferencedNamespaces = None
def defaultNamespace (self):
"""The default namespace in effect at this node. E.g., C{xmlns="URN:default"}."""
return self.__defaultNamespace
__defaultNamespace = None
# If C{True}, this context is within a schema that has no target
# namespace, and we should use the target namespace as a fallback if no
# default namespace is available and no namespace prefix appears on a
# QName. This situation arises when a top-level schema has an absent
# target namespace, or when a schema with an absent target namespace is
# being included into a schema with a non-absent target namespace.
__fallbackToTargetNamespace = False
def targetNamespace (self):
"""The target namespace in effect at this node. Usually from the
C{targetNamespace} attribute. If no namespace is specified for the
schema, an absent namespace was assigned upon creation and will be
returned."""
return self.__targetNamespace
__targetNamespace = None
def inScopeNamespaces (self):
"""Map from prefix strings to L{Namespace} instances associated with those
prefixes. The prefix C{None} identifies the default namespace."""
return self.__inScopeNamespaces
__inScopeNamespaces = None
def prefixForNamespace (self, namespace):
"""Return a prefix associated with the given namespace in this
context, or None if the namespace is the default or is not in
scope."""
for (pfx, ns) in self.__inScopeNamespaces.items():
if namespace == ns:
return pfx
return None
@classmethod
def GetNodeContext (cls, node, **kw):
"""Get the L{NamespaceContext} instance that was assigned to the node.
If none has been assigned and keyword parameters are present, create
one treating this as the root node and the keyword parameters as
configuration information (e.g., default_namespace).
@raise pyxb_114.LogicError: no context is available and the keywords
required to create one were not provided
"""
try:
return node.__namespaceContext
except AttributeError:
return NamespaceContext(node, **kw)
def setNodeContext (self, node):
node.__namespaceContext = self
def processXMLNS (self, prefix, uri):
if not self.__mutableInScopeNamespaces:
self.__inScopeNamespaces = self.__inScopeNamespaces.copy()
self.__mutableInScopeNamespaces = True
if uri:
if prefix is None:
ns = self.__defaultNamespace = utility.NamespaceForURI(uri, create_if_missing=True)
self.__inScopeNamespaces[None] = self.__defaultNamespace
else:
ns = utility.NamespaceForURI(uri, create_if_missing=True)
self.__inScopeNamespaces[prefix] = ns
#if ns.prefix() is None:
# ns.setPrefix(prefix)
# @todo should we record prefix in namespace so we can use it
# during generation? I'd rather make the user specify what to
# use.
if self.__targetNamespace:
self.__targetNamespace._referenceNamespace(ns)
else:
self.__pendingReferencedNamespaces.add(ns)
else:
# NB: XMLNS 6.2 says that you can undefine a default
# namespace, but does not say anything explicitly about
# undefining a prefixed namespace. XML-Infoset 2.2
# paragraph 6 implies you can do this, but expat blows up
# if you try it. I don't think it's legal.
if prefix is not None:
raise pyxb_114.NamespaceError(self, 'Attempt to undefine non-default namespace %s' % (attr.localName,))
self.__inScopeNamespaces.pop(prefix, None)
self.__defaultNamespace = None
def finalizeTargetNamespace (self, tns_uri=None, including_context=None):
if tns_uri is not None:
assert 0 < len(tns_uri)
# Do not prevent overwriting target namespace; need this for WSDL
# files where an embedded schema inadvertently inherits a target
# namespace from its enclosing definitions element. Note that if
# we don't check this here, we do have to check it when schema
# documents are included into parent schema documents.
self.__targetNamespace = utility.NamespaceForURI(tns_uri, create_if_missing=True)
elif self.__targetNamespace is None:
if including_context is not None:
self.__targetNamespace = including_context.targetNamespace()
self.__fallbackToTargetNamespace = True
elif tns_uri is None:
self.__targetNamespace = utility.CreateAbsentNamespace()
else:
self.__targetNamespace = utility.NamespaceForURI(tns_uri, create_if_missing=True)
if self.__pendingReferencedNamespaces is not None:
[ self.__targetNamespace._referenceNamespace(_ns) for _ns in self.__pendingReferencedNamespaces ]
self.__pendingReferencedNamespace = None
assert self.__targetNamespace is not None
if (not self.__fallbackToTargetNamespace) and self.__targetNamespace.isAbsentNamespace():
self.__fallbackToTargetNamespace = True
def __init__ (self,
dom_node=None,
parent_context=None,
including_context=None,
recurse=True,
default_namespace=None,
target_namespace=None,
in_scope_namespaces=None,
expanded_name=None,
finalize_target_namespace=True): # MUST BE True for WSDL to work with minidom
"""Determine the namespace context that should be associated with the
given node and, optionally, its element children.
@param dom_node: The DOM node
@type dom_node: C{xml.dom.Element}
@keyword parent_context: Optional value that specifies the context
associated with C{dom_node}'s parent node. If not provided, only the
C{xml} namespace is in scope.
@type parent_context: L{NamespaceContext}
@keyword recurse: If True (default), create namespace contexts for all
element children of C{dom_node}
@type recurse: C{bool}
@keyword default_namespace: Optional value to set as the default
namespace. Values from C{parent_context} would override this, as
would an C{xmlns} attribute in the C{dom_node}.
@type default_namespace: L{NamespaceContext}
@keyword target_namespace: Optional value to set as the target
namespace. Values from C{parent_context} would override this, as
would a C{targetNamespace} attribute in the C{dom_node}
@type target_namespace: L{NamespaceContext}
@keyword in_scope_namespaces: Optional value to set as the initial set
of in-scope namespaces. The always-present namespaces are added to
this if necessary.
@type in_scope_namespaces: C{dict} mapping C{string} to L{Namespace}.
"""
import builtin
if dom_node is not None:
try:
assert dom_node.__namespaceContext is None
except AttributeError:
pass
dom_node.__namespaceContext = self
self.__defaultNamespace = default_namespace
self.__targetNamespace = target_namespace
self.__inScopeNamespaces = builtin._UndeclaredNamespaceMap
self.__mutableInScopeNamespaces = False
if in_scope_namespaces is not None:
if parent_context is not None:
raise LogicError('Cannot provide both parent_context and in_scope_namespaces')
self.__inScopeNamespaces = builtin._UndeclaredNamespaceMap.copy()
self.__inScopeNamespaces.update(in_scope_namespaces)
self.__mutableInScopeNamespaces = True
if parent_context is not None:
self.__inScopeNamespaces = parent_context.inScopeNamespaces()
self.__mutableInScopeNamespaces = False
self.__defaultNamespace = parent_context.defaultNamespace()
self.__targetNamespace = parent_context.targetNamespace()
self.__fallbackToTargetNamespace = parent_context.__fallbackToTargetNamespace
if self.__targetNamespace is None:
self.__pendingReferencedNamespaces = set()
attribute_map = {}
if dom_node is not None:
if expanded_name is None:
expanded_name = pyxb_114.namespace.ExpandedName(dom_node)
for ai in range(dom_node.attributes.length):
attr = dom_node.attributes.item(ai)
if builtin.XMLNamespaces.uri() == attr.namespaceURI:
prefix = attr.localName
if 'xmlns' == prefix:
prefix = None
self.processXMLNS(prefix, attr.value)
else:
if attr.namespaceURI is not None:
uri = utility.NamespaceForURI(attr.namespaceURI, create_if_missing=True)
key = pyxb_114.namespace.ExpandedName(uri, attr.localName)
else:
key = pyxb_114.namespace.ExpandedName(None, attr.localName)
attribute_map[key] = attr.value
if finalize_target_namespace:
tns_uri = None
tns_attr = self._TargetNamespaceAttribute(expanded_name)
if tns_attr is not None:
tns_uri = attribute_map.get(tns_attr)
self.finalizeTargetNamespace(tns_uri, including_context=including_context)
# Store in each node the in-scope namespaces at that node;
# we'll need them for QName interpretation of attribute
# values.
if (dom_node is not None) and recurse:
from xml.dom import Node
assert Node.ELEMENT_NODE == dom_node.nodeType
for cn in dom_node.childNodes:
if Node.ELEMENT_NODE == cn.nodeType:
NamespaceContext(cn, self, True)
def interpretQName (self, name, namespace=None):
"""Convert the provided name into an L{ExpandedName}, i.e. a tuple of
L{Namespace} and local name.
If the name includes a prefix, that prefix must map to an in-scope
namespace in this context. Absence of a prefix maps to
L{defaultNamespace()}, which must be provided (or defaults to the
target namespace, if that is absent).
@param name: A QName.
@type name: C{str} or C{unicode}
@param name: Optional namespace to use for unqualified names when
there is no default namespace. Note that a defined default namespace,
even if absent, supersedes this value.
@return: An L{ExpandedName} tuple: ( L{Namespace}, C{str} )
@raise pyxb_114.SchemaValidationError: The prefix is not in scope
@raise pyxb_114.SchemaValidationError: No prefix is given and the default namespace is absent
"""
assert isinstance(name, (str, unicode))
if 0 <= name.find(':'):
(prefix, local_name) = name.split(':', 1)
assert self.inScopeNamespaces() is not None
namespace = self.inScopeNamespaces().get(prefix)
if namespace is None:
raise pyxb_114.SchemaValidationError('No namespace declared for QName %s prefix' % (name,))
else:
local_name = name
# Context default supersedes caller-provided namespace
if self.defaultNamespace() is not None:
namespace = self.defaultNamespace()
# If there's no default namespace, but there is a fallback
# namespace, use that instead.
if (namespace is None) and self.__fallbackToTargetNamespace:
namespace = self.targetNamespace()
if namespace is None:
raise pyxb_114.SchemaValidationError('QName %s with absent default namespace cannot be resolved' % (local_name,))
# Anything we're going to look stuff up in requires a component model.
# Make sure we can load one, unless we're looking up in the thing
# we're constructing (in which case it's being built right now).
if (namespace != self.targetNamespace()):
namespace.validateComponentModel()
return pyxb_114.namespace.ExpandedName(namespace, local_name)
def queueForResolution (self, component, depends_on=None):
"""Forwards to L{queueForResolution()<Namespace.queueForResolution>} in L{targetNamespace()}."""
assert isinstance(component, _Resolvable_mixin)
return self.targetNamespace().queueForResolution(component, depends_on)
|
"""
django-critic: urls
"""
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('critic.views',
url(r'^add/$',
'add_rating',
name='critic_add_rating'),
url(r'^render/(?P<content_type_id>\d+)/(?P<object_id>\d+)/$',
'render_rating',
name='critic_rating_render'),
url(r'^user_rating/(?P<content_type_id>\d+)/(?P<object_id>\d+)/$',
'user_rating_json',
name='critic_user_rating_json'),
url(r'^data/(?P<content_type_id>\d+)/(?P<object_id>\d+)/(?P<option>.*)/$',
'rating_data_json',
name='critic_rating_data_json_by_option'),
url(r'^data/(?P<content_type_id>\d+)/(?P<object_id>\d+)/$',
'rating_data_json',
name='critic_rating_data_json'),
)
|
import logging
from distutils.version import LooseVersion
from moksha.common.lib.converters import asbool
from moksha.hub.reactor import reactor
try:
# stomper is not ready for py3
try:
# Try first to use modern stomp-1.1
import stomper.stomp_11 as stomper
except ImportError:
# Failing that, use whatever is available.
try:
import stomper
except ImportError:
pass
from stomper.stompbuffer import StompBuffer
from twisted.internet.protocol import Protocol
class Base(Protocol, stomper.Engine):
pass
except ImportError:
Base = object
log = logging.getLogger(__name__)
class StompProtocol(Base):
def __init__(self, client, username='', password=''):
stomper.Engine.__init__(self)
self.username = username
self.password = password
self.counter = 1
self.client = client
self.buffer = StompBuffer()
def connected(self, msg):
"""Once connected, subscribe to message queues """
stomper.Engine.connected(self, msg)
log.info("StompProtocol Connected: session %s." %
msg['headers']['session'])
# https://stomp.github.io/stomp-specification-1.1.html#Heart-beating
server_heartbeat = msg['headers'].get('heart-beat', 0)
if server_heartbeat:
log.debug("(server wants heart-beat (%s))" % server_heartbeat)
sx, sy = server_heartbeat.split(',')
server_heartbeat = int(sy)
self.client.connected(server_heartbeat)
def subscribe(self, dest, **headers):
f = stomper.Frame()
# https://stomp.github.io/stomp-specification-1.2.html#SUBSCRIBE_ack_Header
ack = self.client.hub.config.get('stomp_ack_mode', 'auto')
if stomper.STOMP_VERSION != '1.0':
f.unpack(stomper.subscribe(dest, dest, ack=ack))
else:
f.unpack(stomper.subscribe(dest, ack=ack))
f.headers.update(headers)
cmd = f.pack()
log.debug(cmd)
self.transport.write(cmd.encode('utf-8'))
def connectionMade(self):
""" Register with stomp server """
log.debug("Connecting with stomp-%s" % stomper.STOMP_VERSION)
if stomper.STOMP_VERSION != '1.0':
host, port = self.client.addresses[self.client.address_index]
interval = (self.client.client_heartbeat, 0)
log.debug("(proposing heartbeat of (%i,%i))" % interval)
cmd = stomper.connect(self.username, self.password, host, interval)
else:
cmd = stomper.connect(self.username, self.password)
log.debug(cmd)
self.transport.write(cmd.encode('utf-8'))
def error(self, msg):
""" Extend stomper's own error method to kill the hub. """
super(StompProtocol, self).error(msg)
log.error("Requesting shutdown of hub for STOMP error.")
reactor.callLater(0, self.client.hub.close)
reactor.callLater(0, reactor.stop)
def ack(self, msg):
""" Override stomper's own ack to be smarter, based on mode. """
# stomper does the incorrect thing when the ack mode is auto. It acks
# every message, regardless of the mode. However, if the mode is
# 'auto', then we should *not* send acks. Here, make sure we don't
# send an ack in that mode.
if self.client.hub.config.get('stomp_ack_mode', 'auto') == 'auto':
return stomper.NO_REPONSE_NEEDED
# Otherwise, do what stomper do if the mode is *not* auto.
return super(StompProtocol, self).ack(msg)
def dataReceived(self, data):
"""Data received, react to it and respond if needed """
self.buffer.appendData(data.decode('utf-8', errors='replace'))
while True:
msg = self.buffer.getOneMessage()
if msg is None:
break
handled = self.client.hub.consume_stomp_message(msg)
# See if stomper thinks we need to send anything back.
response = self.react(msg)
# If this kind of message doesn't need any response, then quit.
if not response:
log.debug("StompProtocol sending no response to broker.")
return
# Otherwise, see if we need to turn a naive 'ack' from stomper into
# a 'nack' if our consumers failed to do their jobs.
if handled is False and response.startswith("ACK\n"):
send_nacks = asbool(self.client.hub.config.get('stomp_send_explicit_nacks', True))
if not send_nacks:
log.warn("Message handling failed. stomp_send_explicit_nacks=%r. "
"Sending no reply to the broker.", send_nacks)
# Return, so as not to send an erroneous ack.
return
if LooseVersion(stomper.STOMP_VERSION) < LooseVersion('1.1'):
log.error("Unable to NACK stomp %r" % stomper.STOMP_VERSION)
# Also, not sending an erroneous ack.
return
message_id = msg['headers']['message-id']
subscription = msg['headers']['subscription']
transaction_id = msg['headers'].get('transaction-id')
response = stomper.nack(message_id, subscription, transaction_id)
# Finally, send our response (ACK or NACK) back to the broker.
if not handled:
log.warn("handled=%r. Responding with %s" % (handled, response))
else:
log.debug("handled=%r. Responding with %s" % (handled, response))
self.transport.write(response.encode('utf-8'))
|
ATTR_NOT_SPECIFIED = object()
SHARED = 'shared'
import logging
import netaddr
import re
from quantum.common import exceptions as q_exc
LOG = logging.getLogger(__name__)
def is_attr_set(attribute):
return attribute not in (None, ATTR_NOT_SPECIFIED)
def _validate_boolean(data, valid_values=None):
if data in [True, False]:
return
else:
msg = _("'%s' is not boolean") % data
LOG.debug("validate_boolean: %s", msg)
return msg
def _validate_values(data, valid_values=None):
if data in valid_values:
return
else:
msg_dict = dict(data=data, values=valid_values)
msg = _("%(data)s is not in %(values)s") % msg_dict
LOG.debug("validate_values: %s", msg)
return msg
def _validate_string(data, max_len=None):
if not isinstance(data, basestring):
msg = _("'%s' is not a valid string") % data
LOG.debug("validate_string: %s", msg)
return msg
if max_len is not None:
if len(data) > max_len:
msg = _("'%(data)s' exceeds maximum length of "
"%(max_len)s.") % locals()
LOG.debug("validate_string: %s", msg)
return msg
def _validate_range(data, valid_values=None):
min_value = valid_values[0]
max_value = valid_values[1]
if data >= min_value and data <= max_value:
return
else:
msg_dict = dict(data=data, min_value=min_value, max_value=max_value)
msg = _("%(data)s is not in range %(min_value)s through "
"%(max_value)s") % msg_dict
LOG.debug("validate_range: %s", msg)
return msg
def _validate_mac_address(data, valid_values=None):
try:
netaddr.EUI(data)
return
except Exception:
msg = _("'%s' is not a valid MAC address") % data
LOG.debug("validate_mac_address: %s", msg)
return msg
def _validate_ip_address(data, valid_values=None):
try:
netaddr.IPAddress(data)
return
except Exception:
msg = _("'%s' is not a valid IP address") % data
LOG.debug("validate_ip_address: %s", msg)
return msg
def _validate_ip_pools(data, valid_values=None):
"""Validate that start and end IP addresses are present
In addition to this the IP addresses will also be validated"""
if not isinstance(data, list):
msg = _("'%s' in not a valid IP pool") % data
LOG.debug("validate_ip_pools: %s", msg)
return msg
expected_keys = set(['start', 'end'])
try:
for ip_pool in data:
if set(ip_pool.keys()) != expected_keys:
msg = _("Expected keys not found. Expected: %s "
"Provided: %s") % (expected_keys, ip_pool.keys())
LOG.debug("validate_ip_pools: %s", msg)
return msg
for k in expected_keys:
msg = _validate_ip_address(ip_pool[k])
if msg:
LOG.debug("validate_ip_pools: %s", msg)
return msg
except KeyError, e:
args = {'key_name': e.message, 'ip_pool': ip_pool}
msg = _("Invalid input. Required key: '%(key_name)s' "
"missing from %(ip_pool)s.") % args
LOG.debug("validate_ip_pools: %s", msg)
return msg
except TypeError, e:
msg = _("Invalid input. Pool %s must be a dictionary.") % ip_pool
LOG.debug("validate_ip_pools: %s", msg)
return msg
except Exception:
msg = _("'%s' in not a valid IP pool") % data
LOG.debug("validate_ip_pools: %s", msg)
return msg
def _validate_fixed_ips(data, valid_values=None):
if not isinstance(data, list):
msg = _("'%s' in not a valid fixed IP") % data
LOG.debug("validate_fixed_ips: %s", msg)
return msg
ips = []
try:
for fixed_ip in data:
if 'ip_address' in fixed_ip:
msg = _validate_ip_address(fixed_ip['ip_address'])
if msg:
LOG.debug("validate_fixed_ips: %s", msg)
return msg
if 'subnet_id' in fixed_ip:
msg = _validate_regex(fixed_ip['subnet_id'], UUID_PATTERN)
if msg:
LOG.debug("validate_fixed_ips: %s", msg)
return msg
# Ensure that duplicate entries are not set - just checking IP
# suffices. Duplicate subnet_id's are legitimate.
if 'ip_address' in fixed_ip:
if fixed_ip['ip_address'] in ips:
msg = _("Duplicate entry %s") % fixed_ip
LOG.debug("validate_fixed_ips: %s", msg)
return msg
ips.append(fixed_ip['ip_address'])
except Exception:
msg = _("'%s' in not a valid fixed IP") % data
LOG.debug("validate_fixed_ips: %s", msg)
return msg
def _validate_nameservers(data, valid_values=None):
if not hasattr(data, '__iter__'):
msg = _("'%s' in not a valid nameserver") % data
LOG.debug("validate_nameservers: %s", msg)
return msg
ips = set()
for ip in data:
msg = _validate_ip_address(ip)
if msg:
# This may be a hostname
msg = _validate_regex(ip, HOSTNAME_PATTERN)
if msg:
msg = _("'%s' in not a valid nameserver") % ip
LOG.debug("validate_nameservers: %s", msg)
return msg
if ip in ips:
msg = _("Duplicate nameserver %s") % ip
LOG.debug("validate_nameservers: %s", msg)
return msg
ips.add(ip)
def _validate_hostroutes(data, valid_values=None):
if not isinstance(data, list):
msg = _("'%s' in not a valid hostroute") % data
LOG.debug("validate_hostroutes: %s", msg)
return msg
hostroutes = []
try:
for hostroute in data:
msg = _validate_subnet(hostroute['destination'])
if msg:
LOG.debug("validate_hostroutes: %s", msg)
return msg
msg = _validate_ip_address(hostroute['nexthop'])
if msg:
LOG.debug("validate_hostroutes: %s", msg)
return msg
if hostroute in hostroutes:
msg = _("Duplicate hostroute %s") % hostroute
LOG.debug("validate_hostroutes: %s", msg)
if msg:
return msg
hostroutes.append(hostroute)
except:
msg = _("'%s' in not a valid hostroute") % data
LOG.debug("validate_hostroutes: %s", msg)
return msg
def _validate_ip_address_or_none(data, valid_values=None):
if data is None:
return None
return _validate_ip_address(data, valid_values)
def _validate_subnet(data, valid_values=None):
try:
netaddr.IPNetwork(data)
if len(data.split('/')) == 2:
return
except Exception:
pass
msg = _("'%s' is not a valid IP subnet") % data
LOG.debug("validate_subnet: %s", msg)
return msg
def _validate_regex(data, valid_values=None):
try:
if re.match(valid_values, data):
return
except TypeError:
pass
msg = _("'%s' is not valid input") % data
LOG.debug("validate_regex: %s", msg)
return msg
def convert_to_boolean(data):
try:
i = int(data)
if i in [True, False]:
# Ensure that the value is True or False
if i:
return True
else:
return False
except (ValueError, TypeError):
if (data == "True" or data == "true"):
return True
if (data == "False" or data == "false"):
return False
msg = _("'%s' is not boolean") % data
raise q_exc.InvalidInput(error_message=msg)
def convert_to_int(data):
try:
return int(data)
except (ValueError, TypeError):
msg = _("'%s' is not a integer") % data
raise q_exc.InvalidInput(error_message=msg)
def convert_kvp_str_to_list(data):
"""Convert a value of the form 'key=value' to ['key', 'value'].
:raises: q_exc.InvalidInput if any of the strings are malformed
(e.g. do not contain a key).
"""
kvp = [x.strip() for x in data.split('=', 1)]
if len(kvp) == 2 and kvp[0]:
return kvp
msg = _("'%s' is not of the form <key>=[value]") % data
raise q_exc.InvalidInput(error_message=msg)
def convert_kvp_list_to_dict(kvp_list):
"""Convert a list of 'key=value' strings to a dict.
:raises: q_exc.InvalidInput if any of the strings are malformed
(e.g. do not contain a key) or if any
of the keys appear more than once.
"""
if kvp_list == ['True']:
# No values were provided (i.e. '--flag-name')
return {}
kvp_map = {}
for kvp_str in kvp_list:
key, value = convert_kvp_str_to_list(kvp_str)
kvp_map.setdefault(key, set())
kvp_map[key].add(value)
return dict((x, list(y)) for x, y in kvp_map.iteritems())
HOSTNAME_PATTERN = ("(?=^.{1,254}$)(^(?:(?!\d+\.|-)[a-zA-Z0-9_\-]"
"{1,63}(?<!-)\.?)+(?:[a-zA-Z]{2,})$)")
HEX_ELEM = '[0-9A-Fa-f]'
UUID_PATTERN = '-'.join([HEX_ELEM + '{8}', HEX_ELEM + '{4}',
HEX_ELEM + '{4}', HEX_ELEM + '{4}',
HEX_ELEM + '{12}'])
MAC_PATTERN = "^%s[aceACE02468](:%s{2}){5}$" % (HEX_ELEM, HEX_ELEM)
validators = {'type:boolean': _validate_boolean,
'type:values': _validate_values,
'type:string': _validate_string,
'type:range': _validate_range,
'type:mac_address': _validate_mac_address,
'type:fixed_ips': _validate_fixed_ips,
'type:ip_address': _validate_ip_address,
'type:ip_address_or_none': _validate_ip_address_or_none,
'type:subnet': _validate_subnet,
'type:regex': _validate_regex,
'type:ip_pools': _validate_ip_pools,
'type:hostroutes': _validate_hostroutes,
'type:nameservers': _validate_nameservers}
RESOURCE_ATTRIBUTE_MAP = {
'networks': {
'id': {'allow_post': False, 'allow_put': False,
'validate': {'type:regex': UUID_PATTERN},
'is_visible': True},
'name': {'allow_post': True, 'allow_put': True,
'validate': {'type:string': None},
'default': '', 'is_visible': True},
'subnets': {'allow_post': False, 'allow_put': False,
'default': [],
'is_visible': True},
'admin_state_up': {'allow_post': True, 'allow_put': True,
'default': True,
'convert_to': convert_to_boolean,
'validate': {'type:boolean': None},
'is_visible': True},
'status': {'allow_post': False, 'allow_put': False,
'is_visible': True},
'tenant_id': {'allow_post': True, 'allow_put': False,
'validate': {'type:string': None},
'required_by_policy': True,
'is_visible': True},
SHARED: {'allow_post': True,
'allow_put': True,
'default': False,
'convert_to': convert_to_boolean,
'validate': {'type:boolean': None},
'is_visible': True,
'required_by_policy': True,
'enforce_policy': True},
},
'ports': {
'id': {'allow_post': False, 'allow_put': False,
'validate': {'type:regex': UUID_PATTERN},
'is_visible': True},
'name': {'allow_post': True, 'allow_put': True, 'default': '',
'validate': {'type:string': None},
'is_visible': True},
'network_id': {'allow_post': True, 'allow_put': False,
'required_by_policy': True,
'validate': {'type:regex': UUID_PATTERN},
'is_visible': True},
'admin_state_up': {'allow_post': True, 'allow_put': True,
'default': True,
'convert_to': convert_to_boolean,
'validate': {'type:boolean': None},
'is_visible': True},
'mac_address': {'allow_post': True, 'allow_put': False,
'default': ATTR_NOT_SPECIFIED,
'validate': {'type:mac_address': None},
'enforce_policy': True,
'is_visible': True},
'fixed_ips': {'allow_post': True, 'allow_put': True,
'default': ATTR_NOT_SPECIFIED,
'convert_list_to': convert_kvp_list_to_dict,
'validate': {'type:fixed_ips': None},
'enforce_policy': True,
'is_visible': True},
'device_id': {'allow_post': True, 'allow_put': True,
'validate': {'type:string': None},
'default': '',
'is_visible': True},
'device_owner': {'allow_post': True, 'allow_put': True,
'validate': {'type:string': None},
'default': '',
'is_visible': True},
'tenant_id': {'allow_post': True, 'allow_put': False,
'validate': {'type:string': None},
'required_by_policy': True,
'is_visible': True},
'status': {'allow_post': False, 'allow_put': False,
'is_visible': True},
},
'subnets': {
'id': {'allow_post': False, 'allow_put': False,
'validate': {'type:regex': UUID_PATTERN},
'is_visible': True},
'name': {'allow_post': True, 'allow_put': True, 'default': '',
'validate': {'type:string': None},
'is_visible': True},
'ip_version': {'allow_post': True, 'allow_put': False,
'convert_to': convert_to_int,
'validate': {'type:values': [4, 6]},
'is_visible': True},
'network_id': {'allow_post': True, 'allow_put': False,
'required_by_policy': True,
'validate': {'type:regex': UUID_PATTERN},
'is_visible': True},
'cidr': {'allow_post': True, 'allow_put': False,
'validate': {'type:subnet': None},
'is_visible': True},
'gateway_ip': {'allow_post': True, 'allow_put': True,
'default': ATTR_NOT_SPECIFIED,
'validate': {'type:ip_address_or_none': None},
'is_visible': True},
#TODO(salvatore-orlando): Enable PUT on allocation_pools
'allocation_pools': {'allow_post': True, 'allow_put': False,
'default': ATTR_NOT_SPECIFIED,
'validate': {'type:ip_pools': None},
'is_visible': True},
'dns_nameservers': {'allow_post': True, 'allow_put': True,
'default': ATTR_NOT_SPECIFIED,
'validate': {'type:nameservers': None},
'is_visible': True},
'host_routes': {'allow_post': True, 'allow_put': True,
'default': ATTR_NOT_SPECIFIED,
'validate': {'type:hostroutes': None},
'is_visible': True},
'tenant_id': {'allow_post': True, 'allow_put': False,
'validate': {'type:string': None},
'required_by_policy': True,
'is_visible': True},
'enable_dhcp': {'allow_post': True, 'allow_put': True,
'default': True,
'convert_to': convert_to_boolean,
'validate': {'type:boolean': None},
'is_visible': True},
SHARED: {'allow_post': False,
'allow_put': False,
'default': False,
'convert_to': convert_to_boolean,
'validate': {'type:boolean': None},
'is_visible': False,
'required_by_policy': True,
'enforce_policy': True},
}
}
RESOURCE_HIERARCHY_MAP = {
'ports': {'parent': 'networks', 'identified_by': 'network_id'},
'subnets': {'parent': 'networks', 'identified_by': 'network_id'}
}
|
"""Gym-specific (non-Atari) utilities.
Some network specifications specific to certain Gym environments are provided
here.
Includes a wrapper class around Gym environments. This class makes general Gym
environments conformant with the API Dopamine is expecting.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import math
from dopamine.discrete_domains import atari_lib
import gin
import gym
from gym.wrappers.time_limit import TimeLimit
import numpy as np
import tensorflow as tf
CARTPOLE_MIN_VALS = np.array([-2.4, -5., -math.pi/12., -math.pi*2.])
CARTPOLE_MAX_VALS = np.array([2.4, 5., math.pi/12., math.pi*2.])
ACROBOT_MIN_VALS = np.array([-1., -1., -1., -1., -5., -5.])
ACROBOT_MAX_VALS = np.array([1., 1., 1., 1., 5., 5.])
MOUNTAINCAR_MIN_VALS = np.array([-1.2, -0.07])
MOUNTAINCAR_MAX_VALS = np.array([0.6, 0.07])
gin.constant('gym_lib.CARTPOLE_OBSERVATION_SHAPE', (4, 1))
gin.constant('gym_lib.CARTPOLE_OBSERVATION_DTYPE', tf.float64)
gin.constant('gym_lib.CARTPOLE_STACK_SIZE', 1)
gin.constant('gym_lib.ACROBOT_OBSERVATION_SHAPE', (6, 1))
gin.constant('gym_lib.ACROBOT_OBSERVATION_DTYPE', tf.float64)
gin.constant('gym_lib.ACROBOT_STACK_SIZE', 1)
gin.constant('gym_lib.LUNAR_OBSERVATION_SHAPE', (8, 1))
gin.constant('gym_lib.LUNAR_OBSERVATION_DTYPE', tf.float64)
gin.constant('gym_lib.LUNAR_STACK_SIZE', 1)
gin.constant('gym_lib.MOUNTAINCAR_OBSERVATION_SHAPE', (2, 1))
gin.constant('gym_lib.MOUNTAINCAR_OBSERVATION_DTYPE', tf.float64)
gin.constant('gym_lib.MOUNTAINCAR_STACK_SIZE', 1)
MUJOCO_GAMES = ('Ant', 'HalfCheetah', 'Hopper', 'Humanoid', 'Walker2d')
@gin.configurable
def create_gym_environment(environment_name=None, version='v0'):
"""Wraps a Gym environment with some basic preprocessing.
Args:
environment_name: str, the name of the environment to run.
version: str, version of the environment to run.
Returns:
A Gym environment with some standard preprocessing.
"""
assert environment_name is not None
full_game_name = '{}-{}'.format(environment_name, version)
env = gym.make(full_game_name)
# Strip out the TimeLimit wrapper from Gym, which caps us at 200 steps.
if isinstance(env, TimeLimit):
env = env.env
# Wrap the returned environment in a class which conforms to the API expected
# by Dopamine.
env = GymPreprocessing(env)
return env
@gin.configurable
class BasicDiscreteDomainNetwork(tf.keras.layers.Layer):
"""The fully connected network used to compute the agent's Q-values.
This sub network used within various other models. Since it is an inner
block, we define it as a layer. These sub networks normalize their inputs to
lie in range [-1, 1], using min_/max_vals. It supports both DQN- and
Rainbow- style networks.
Attributes:
min_vals: float, minimum attainable values (must be same shape as
`state`).
max_vals: float, maximum attainable values (must be same shape as
`state`).
num_actions: int, number of actions.
num_atoms: int or None, if None will construct a DQN-style network,
otherwise will construct a Rainbow-style network.
name: str, used to create scope for network parameters.
activation_fn: function, passed to the layer constructors.
"""
def __init__(self, min_vals, max_vals, num_actions,
num_atoms=None, name=None,
activation_fn=tf.keras.activations.relu):
super(BasicDiscreteDomainNetwork, self).__init__(name=name)
self.num_actions = num_actions
self.num_atoms = num_atoms
self.min_vals = min_vals
self.max_vals = max_vals
# Defining layers.
self.flatten = tf.keras.layers.Flatten()
self.dense1 = tf.keras.layers.Dense(512, activation=activation_fn,
name='fully_connected')
self.dense2 = tf.keras.layers.Dense(512, activation=activation_fn,
name='fully_connected')
if num_atoms is None:
self.last_layer = tf.keras.layers.Dense(num_actions,
name='fully_connected')
else:
self.last_layer = tf.keras.layers.Dense(num_actions * num_atoms,
name='fully_connected')
def call(self, state):
"""Creates the output tensor/op given the state tensor as input."""
x = tf.cast(state, tf.float32)
x = self.flatten(x)
if self.min_vals is not None:
x -= self.min_vals
x /= self.max_vals - self.min_vals
x = 2.0 * x - 1.0 # Rescale in range [-1, 1].
x = self.dense1(x)
x = self.dense2(x)
x = self.last_layer(x)
return x
@gin.configurable
class CartpoleDQNNetwork(tf.keras.Model):
"""Keras DQN network for Cartpole."""
def __init__(self, num_actions, name=None):
"""Builds the deep network used to compute the agent's Q-values.
It rescales the input features so they lie in range [-1, 1].
Args:
num_actions: int, number of actions.
name: str, used to create scope for network parameters.
"""
super(CartpoleDQNNetwork, self).__init__(name=name)
self.net = BasicDiscreteDomainNetwork(
CARTPOLE_MIN_VALS, CARTPOLE_MAX_VALS, num_actions)
def call(self, state):
"""Creates the output tensor/op given the state tensor as input."""
x = self.net(state)
return atari_lib.DQNNetworkType(x)
class FourierBasis(object):
"""Fourier Basis linear function approximation.
Requires the ranges for each dimension, and is thus able to use only sine or
cosine (and uses cosine). So, this has half the coefficients that a full
Fourier approximation would use.
Many thanks to Will Dabney (wdabney@) for this implementation.
From the paper:
G.D. Konidaris, S. Osentoski and P.S. Thomas. (2011)
Value Function Approximation in Reinforcement Learning using the Fourier Basis
"""
def __init__(self, nvars, min_vals=0, max_vals=None, order=3):
self.order = order
self.min_vals = min_vals
self.max_vals = max_vals
terms = itertools.product(range(order + 1), repeat=nvars)
# Removing first iterate because it corresponds to the constant bias
self.multipliers = tf.constant(
[list(map(int, x)) for x in terms][1:], dtype=tf.float32)
def scale(self, values):
shifted = values - self.min_vals
if self.max_vals is None:
return shifted
return shifted / (self.max_vals - self.min_vals)
def compute_features(self, features):
# Important to rescale features to be between [0,1]
scaled = self.scale(features)
return tf.cos(np.pi * tf.matmul(scaled, self.multipliers, transpose_b=True))
@gin.configurable
class FourierDQNNetwork(tf.keras.Model):
"""Keras model for DQN."""
def __init__(self, min_vals, max_vals, num_actions, fourier_basis_order=3,
name=None):
"""Builds the function approximator used to compute the agent's Q-values.
It uses the features of the FourierBasis class and a linear layer
without bias.
Value Function Approximation in Reinforcement Learning using the Fourier
Basis", Konidaris, Osentoski and Thomas (2011).
Args:
min_vals: float, minimum attainable values (must be same shape as
`state`).
max_vals: float, maximum attainable values (must be same shape as
`state`).
num_actions: int, number of actions.
fourier_basis_order: int, order of the Fourier basis functions.
name: str, used to create scope for network parameters.
"""
super(FourierDQNNetwork, self).__init__(name=name)
self.num_actions = num_actions
self.fourier_basis_order = fourier_basis_order
self.min_vals = min_vals
self.max_vals = max_vals
# Defining layers.
self.flatten = tf.keras.layers.Flatten()
self.last_layer = tf.keras.layers.Dense(num_actions, use_bias=False,
name='fully_connected')
def call(self, state):
"""Creates the output tensor/op given the state tensor as input."""
x = tf.cast(state, tf.float32)
x = self.flatten(x)
# Since FourierBasis needs the shape of the input, we can only initialize
# it during the first forward pass when we know the shape of the input.
if not hasattr(self, 'feature_generator'):
self.feature_generator = FourierBasis(
x.get_shape().as_list()[-1],
self.min_vals,
self.max_vals,
order=self.fourier_basis_order)
x = self.feature_generator.compute_features(x)
x = self.last_layer(x)
return atari_lib.DQNNetworkType(x)
@gin.configurable
class CartpoleFourierDQNNetwork(FourierDQNNetwork):
"""Keras network for fourier Cartpole."""
def __init__(self, num_actions, name=None):
"""Builds the function approximator used to compute the agent's Q-values.
It uses the Fourier basis features and a linear function approximator.
Args:
num_actions: int, number of actions.
name: str, used to create scope for network parameters.
"""
super(CartpoleFourierDQNNetwork, self).__init__(
CARTPOLE_MIN_VALS, CARTPOLE_MAX_VALS, num_actions, name=name)
@gin.configurable
class CartpoleRainbowNetwork(tf.keras.Model):
"""Keras Rainbow network for Cartpole."""
def __init__(self, num_actions, num_atoms, support, name=None):
"""Builds the deep network used to compute the agent's Q-values.
It rescales the input features to a range that yields improved performance.
Args:
num_actions: int, number of actions.
num_atoms: int, the number of buckets of the value function distribution.
support: tf.linspace, the support of the Q-value distribution.
name: str, used to create scope for network parameters.
"""
super(CartpoleRainbowNetwork, self).__init__(name=name)
self.net = BasicDiscreteDomainNetwork(
CARTPOLE_MIN_VALS, CARTPOLE_MAX_VALS, num_actions, num_atoms=num_atoms)
self.num_actions = num_actions
self.num_atoms = num_atoms
self.support = support
def call(self, state):
x = self.net(state)
logits = tf.reshape(x, [-1, self.num_actions, self.num_atoms])
probabilities = tf.keras.activations.softmax(logits)
q_values = tf.reduce_sum(self.support * probabilities, axis=2)
return atari_lib.RainbowNetworkType(q_values, logits, probabilities)
@gin.configurable
class AcrobotDQNNetwork(tf.keras.Model):
"""Keras DQN network for Acrobot."""
def __init__(self, num_actions, name=None):
"""Builds the deep network used to compute the agent's Q-values.
It rescales the input features to a range that yields improved performance.
Args:
num_actions: int, number of actions.
name: str, used to create scope for network parameters.
"""
super(AcrobotDQNNetwork, self).__init__(name=name)
self.net = BasicDiscreteDomainNetwork(
ACROBOT_MIN_VALS, ACROBOT_MAX_VALS, num_actions)
def call(self, state):
x = self.net(state)
return atari_lib.DQNNetworkType(x)
@gin.configurable
class AcrobotFourierDQNNetwork(FourierDQNNetwork):
"""Keras fourier DQN network for Acrobot."""
def __init__(self, num_actions, name=None):
"""Builds the function approximator used to compute the agent's Q-values.
It uses the Fourier basis features and a linear function approximator.
Args:
num_actions: int, number of actions.
name: str, used to create scope for network parameters.
"""
super(AcrobotFourierDQNNetwork, self).__init__(
ACROBOT_MIN_VALS, ACROBOT_MAX_VALS, num_actions, name=name)
@gin.configurable
class AcrobotRainbowNetwork(tf.keras.Model):
"""Keras Rainbow network for Acrobot."""
def __init__(self, num_actions, num_atoms, support, name=None):
"""Builds the deep network used to compute the agent's Q-values.
It rescales the input features to a range that yields improved performance.
Args:
num_actions: int, number of actions.
num_atoms: int, the number of buckets of the value function distribution.
support: Tensor, the support of the Q-value distribution.
name: str, used to create scope for network parameters.
"""
super(AcrobotRainbowNetwork, self).__init__(name=name)
self.net = BasicDiscreteDomainNetwork(
ACROBOT_MIN_VALS, ACROBOT_MAX_VALS, num_actions, num_atoms=num_atoms)
self.num_actions = num_actions
self.num_atoms = num_atoms
self.support = support
def call(self, state):
x = self.net(state)
logits = tf.reshape(x, [-1, self.num_actions, self.num_atoms])
probabilities = tf.keras.activations.softmax(logits)
q_values = tf.reduce_sum(self.support * probabilities, axis=2)
return atari_lib.RainbowNetworkType(q_values, logits, probabilities)
@gin.configurable
class LunarLanderDQNNetwork(tf.keras.Model):
"""Keras DQN network for LunarLander."""
def __init__(self, num_actions, name=None):
"""Builds the deep network used to compute the agent's Q-values.
Args:
num_actions: int, number of actions.
name: str, used to create scope for network parameters.
"""
super(LunarLanderDQNNetwork, self).__init__(name=name)
self.net = BasicDiscreteDomainNetwork(None, None, num_actions)
def call(self, state):
"""Creates the output tensor/op given the state tensor as input."""
x = self.net(state)
return atari_lib.DQNNetworkType(x)
@gin.configurable
class MountainCarDQNNetwork(tf.keras.Model):
"""Keras DQN network for MountainCar."""
def __init__(self, num_actions, name=None):
"""Builds the deep network used to compute the agent's Q-values.
Args:
num_actions: int, number of actions.
name: str, used to create scope for network parameters.
"""
super(MountainCarDQNNetwork, self).__init__(name=name)
self.net = BasicDiscreteDomainNetwork(
MOUNTAINCAR_MIN_VALS, MOUNTAINCAR_MAX_VALS, num_actions)
def call(self, state):
"""Creates the output tensor/op given the state tensor as input."""
x = self.net(state)
return atari_lib.DQNNetworkType(x)
@gin.configurable
class GymPreprocessing(object):
"""A Wrapper class around Gym environments."""
def __init__(self, environment):
self.environment = environment
self.game_over = False
@property
def observation_space(self):
return self.environment.observation_space
@property
def action_space(self):
return self.environment.action_space
@property
def reward_range(self):
return self.environment.reward_range
@property
def metadata(self):
return self.environment.metadata
def reset(self):
return self.environment.reset()
def step(self, action):
observation, reward, game_over, info = self.environment.step(action)
was_truncated = info.get('TimeLimit.truncated', False)
game_over = game_over and not was_truncated
self.game_over = game_over
return observation, reward, game_over, info
|
"""
This tool checks GitHub for the latest version of Modis and can produce the name
of the current official version and the difference between that version and the
version currently being used.
"""
import logging
import requests
from modis.tools import config
logger = logging.getLogger(__name__)
def infostr():
"""
Get the version comparison info.
Returns:
version_str (str): A friendly response detailing the current version
"""
latest = _get()
state = _compare(latest)
if state == -1:
return "A new version of Modis is available (v{})".format(latest)
elif state == 0:
return "You are running the latest version of Modis (v{})".format(config.VERSION)
elif state == 1:
return "You are running a preview version of Modis (v{} pre-release)".format(config.VERSION)
def _get():
"""Compare the current version to the latest on GitHub.
Returns:
version (list): The latest live version numbers
"""
logger.debug("Checking version...")
# Get version info from GitHub
try:
r = requests.get("https://api.github.com/repos/Infraxion/Modis/releases/latest").json()
if "message" not in r or r["message"] == "Not Found":
r = requests.get("https://api.github.com/repos/Infraxion/Modis/releases").json()[0]
except requests.ConnectionError:
logger.warning("Could not connect to GitHub for version info")
return []
# Parse version info
if "tag_name" in r:
version_name = r["tag_name"]
version_tag = version_name.split('.')
return version_tag
else:
return []
def _compare(release_version):
"""Compare the current version to the latest on GitHub.
Args:
release_version (list): The latest live version numbers
Returns:
comparison (int): -1=behind, 0=latest, 1=ahead
"""
current_version = config.VERSION.split('.')
for vi in range(len(release_version)):
if len(current_version) > vi:
if current_version[vi] > release_version[vi]:
return 1
elif current_version[vi] < release_version[vi]:
return -1
elif release_version[vi] != "0":
return -1
return 0
|
import os
import subprocess
os.system("kubectl delete -f cloudone-controller-glusterfs.json")
os.system("kubectl delete -f cloudone-service.json")
p = subprocess.Popen(['kubectl', 'get', 'pod'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = p.communicate()
output_line_list = output.split("\n")
for output_line in output_line_list:
if output_line.startswith("cloudone"):
os.system("kubectl delete pod " + output_line.split(" ")[0])
|
"""Tests for tensorflow.python.framework.importer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from google.protobuf import text_format
from tensorflow.core.framework import op_def_pb2
from tensorflow.python.framework import device
from tensorflow.python.framework import op_def_registry
_op_list = op_def_pb2.OpList()
text_format.Merge("""
op {
name: 'None'
}
op {
name: 'Oi'
output_arg { name: 'a' type: DT_INT32 }
}
op {
name: 'Or'
output_arg { name: 'a' type: DT_INT32 is_ref: true }
}
op {
name: 'Of'
output_arg { name: 'a' type: DT_FLOAT }
}
op {
name: 'Ii'
input_arg { name: 'a' type: DT_INT32 }
}
op {
name: 'If'
input_arg { name: 'a' type: DT_FLOAT }
}
op {
name: 'Oii'
output_arg { name: 'a' type: DT_INT32 }
output_arg { name: 'b' type: DT_INT32 }
}
op {
name: 'Oif'
output_arg { name: 'a' type: DT_INT32 }
output_arg { name: 'b' type: DT_FLOAT }
}
op {
name: 'Iii'
input_arg { name: 'a' type: DT_INT32 }
input_arg { name: 'b' type: DT_INT32 }
}
op {
name: 'Iff'
input_arg { name: 'a' type: DT_FLOAT }
input_arg { name: 'b' type: DT_FLOAT }
}
op {
name: 'Iif'
input_arg { name: 'a' type: DT_INT32 }
input_arg { name: 'b' type: DT_FLOAT }
}
op {
name: 'Iri'
input_arg { name: 'a' type: DT_INT32 is_ref: true }
input_arg { name: 'b' type: DT_INT32 }
}
op {
name: 'In'
input_arg { name: 'a' number_attr: 'N' type_attr: 'T' }
attr { name: 'N' type: 'int' minimum: 1 }
attr { name: 'T' type: 'type' }
}
op {
name: 'Otl'
output_arg { name: 'a' type_list_attr: 't' }
attr { name: 'T' type: 'list(type)' minimum: 1 }
}
op {
name: 'Unary'
input_arg { name: 'a' type_attr: 'T' }
output_arg { name: 'b' type_attr: 'T' }
attr { name: 'T' type: 'type' }
}
op {
name: 'OpWithDefaultAttr'
output_arg { name: 'a' type: DT_INT32 }
attr { name: 'default_float' type: 'float' default_value { f: 123.0 } }
}
op {
name: 'OpWithFutureDefaultAttr'
}
""", _op_list)
op_def_registry.register_op_list(_op_list)
for op_def in _op_list.op:
tf.RegisterShape(op_def.name)(None)
class ImportGraphDefTest(tf.test.TestCase):
def _MakeGraphDef(self, text, producer=tf.GRAPH_DEF_VERSION,
min_consumer=tf.GRAPH_DEF_VERSION_MIN_CONSUMER):
text = "versions: { producer: %d min_consumer: %d };\n%s" % (
producer, min_consumer, text)
ret = tf.GraphDef()
text_format.Merge(text, ret)
return ret
def testBasic(self):
with tf.Graph().as_default():
a, b, c, d = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oif' }
node { name: 'B' op: 'Otl'
attr { key: 't'
value { list { type: DT_INT32 type: DT_FLOAT } } } }
node { name: 'C' op: 'In'
attr { key: 'N' value { i: 2 } }
attr { key: 'T' value { type: DT_INT32 } }
input: 'A:0' input: 'B:0' }
node { name: 'D' op: 'In'
attr { key: 'N' value { i: 2 } }
attr { key: 'T' value { type: DT_FLOAT } }
input: 'A:1' input: 'B:1' }
"""),
return_elements=["A", "B", "C", "D"],
name="import")
# Assert that the import process creates distinct tensors.
self.assertNotEqual(a.outputs[0].name, a.outputs[1].name)
self.assertNotEqual(b.outputs[0].name, b.outputs[1].name)
self.assertNotEqual(a.outputs[0].name, b.outputs[0].name)
self.assertNotEqual(a.outputs[0].name, b.outputs[1].name)
self.assertNotEqual(a.outputs[1].name, b.outputs[0].name)
self.assertNotEqual(a.outputs[1].name, b.outputs[1].name)
# Assert that the ops are connected according to the GraphDef topology.
self.assertEqual(c.inputs[0], a.outputs[0])
self.assertEqual(c.inputs[1], b.outputs[0])
self.assertEqual(d.inputs[0], a.outputs[1])
self.assertEqual(d.inputs[1], b.outputs[1])
# Check the types of the returned ops and tensors.
self.assertEqual(a.type, "Oif")
self.assertEqual(b.type, "Otl")
self.assertEqual(c.type, "In")
self.assertEqual(d.type, "In")
self.assertEqual(a.outputs[0].dtype, tf.int32)
self.assertEqual(a.outputs[1].dtype, tf.float32)
self.assertEqual(b.outputs[0].dtype, tf.int32)
self.assertEqual(b.outputs[1].dtype, tf.float32)
# Check the names of the returned ops.
self.assertEqual(a.name, "import/A")
self.assertEqual(b.name, "import/B")
self.assertEqual(c.name, "import/C")
self.assertEqual(d.name, "import/D")
# Check that the op_def is still available.
self.assertNotEqual(None, a.op_def)
def testInputMap(self):
with tf.Graph().as_default():
feed_a_0 = tf.constant(0, dtype=tf.int32)
feed_b_1 = tf.constant(1, dtype=tf.int32)
a, b, c, d = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oii' }
node { name: 'B' op: 'Oii' }
node { name: 'C' op: 'In'
attr { key: 'N' value { i: 2 } }
attr { key: 'T' value { type: DT_INT32 } }
input: 'A:0' input: 'B:0' }
node { name: 'D' op: 'In'
attr { key: 'N' value { i: 2 } }
attr { key: 'T' value { type: DT_INT32 } }
input: 'A:1' input: 'B:1' }
"""),
input_map={"A:0": feed_a_0, "B:1": feed_b_1},
return_elements=["A", "B", "C", "D"])
self.assertEqual(c.inputs[0], feed_a_0)
self.assertEqual(c.inputs[1], b.outputs[0])
self.assertEqual(d.inputs[0], a.outputs[1])
self.assertEqual(d.inputs[1], feed_b_1)
def testInputMapBytes(self):
with tf.Graph().as_default():
feed_a_0 = tf.constant(0, dtype=tf.int32)
feed_b_1 = tf.constant(1, dtype=tf.int32)
a, b, c, d = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oii' }
node { name: 'B' op: 'Oii' }
node { name: 'C' op: 'In'
attr { key: 'N' value { i: 2 } }
attr { key: 'T' value { type: DT_INT32 } }
input: 'A:0' input: 'B:0' }
node { name: 'D' op: 'In'
attr { key: 'N' value { i: 2 } }
attr { key: 'T' value { type: DT_INT32 } }
input: 'A:1' input: 'B:1' }
"""),
input_map={b"A:0": feed_a_0, b"B:1": feed_b_1},
return_elements=[b"A", b"B", b"C", b"D"])
self.assertEqual(c.inputs[0], feed_a_0)
self.assertEqual(c.inputs[1], b.outputs[0])
self.assertEqual(d.inputs[0], a.outputs[1])
self.assertEqual(d.inputs[1], feed_b_1)
def testInputMapUnicode(self):
with tf.Graph().as_default():
feed_a_0 = tf.constant(0, dtype=tf.int32)
feed_b_1 = tf.constant(1, dtype=tf.int32)
a, b, c, d = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oii' }
node { name: 'B' op: 'Oii' }
node { name: 'C' op: 'In'
attr { key: 'N' value { i: 2 } }
attr { key: 'T' value { type: DT_INT32 } }
input: 'A:0' input: 'B:0' }
node { name: 'D' op: 'In'
attr { key: 'N' value { i: 2 } }
attr { key: 'T' value { type: DT_INT32 } }
input: 'A:1' input: 'B:1' }
"""),
input_map={u"A:0": feed_a_0, u"B:1": feed_b_1},
return_elements=[u"A", u"B", u"C", u"D"])
self.assertEqual(c.inputs[0], feed_a_0)
self.assertEqual(c.inputs[1], b.outputs[0])
self.assertEqual(d.inputs[0], a.outputs[1])
self.assertEqual(d.inputs[1], feed_b_1)
def testImplicitZerothOutput(self):
with tf.Graph().as_default():
a, b = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oii' }
node { name: 'B' op: 'Ii' input: 'A' }
"""),
return_elements=["A", "B"])
self.assertEqual(b.inputs[0], a.outputs[0])
def testInputMapImplicitZerothOutput(self):
with tf.Graph().as_default():
feed_a_0 = tf.constant(0, dtype=tf.int32)
b, = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oii' }
node { name: 'B' op: 'Ii' input: 'A:0' }
"""),
input_map={"A": feed_a_0},
return_elements=["B"])
self.assertEqual(b.inputs[0], feed_a_0)
def testWithControlDependency(self):
with tf.Graph().as_default():
a, b = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'None' }
node { name: 'B' op: 'None' input: '^A' }
"""),
return_elements=["A", "B"])
self.assertEqual(b.control_inputs, [a])
def testWithRefs(self):
with tf.Graph().as_default():
a, b, c, d = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Or' }
node { name: 'B' op: 'Oi' }
node { name: 'C' op: 'Iii' input: 'A:0' input: 'B:0' }
node { name: 'D' op: 'Iri' input: 'A:0' input: 'B:0' }
"""),
return_elements=["A", "B", "C", "D"])
self.assertEqual(c.inputs[0], a.outputs[0])
self.assertEqual(c.inputs[1], b.outputs[0])
self.assertEqual(d.inputs[0], a.outputs[0])
self.assertEqual(d.inputs[1], b.outputs[0])
self.assertEqual(a.outputs[0].dtype, tf.int32_ref)
self.assertEqual(c._input_dtypes, [tf.int32, tf.int32])
self.assertEqual(c.outputs, [])
self.assertEqual(d._input_dtypes,
[tf.int32_ref, tf.int32])
self.assertEqual(d.outputs, [])
def testCyclic(self):
with tf.Graph().as_default():
a, b = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Unary'
attr { key: 'T' value { type: DT_INT32 } } input: 'B:0' }
node { name: 'B' op: 'Unary'
attr { key: 'T' value { type: DT_INT32 } } input: 'A:0' }
"""),
return_elements=["A", "B"])
self.assertEqual(a.inputs[0], b.outputs[0])
self.assertEqual(b.inputs[0], a.outputs[0])
def testTypeMismatchInGraphDef(self):
with tf.Graph().as_default():
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oi' }
node { name: 'B' op: 'If' input: 'A:0' }
"""))
self.assertTrue(
"Cannot convert a tensor of type int32 to an input of type float" in
str(e.exception))
def testInvalidSignatureTooManyInputsInGraphDef(self):
with tf.Graph().as_default():
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oi' }
node { name: 'B' op: 'None' input: 'A:0' }
"""))
self.assertTrue("More inputs specified ('A:0') than the op expects" in
str(e.exception))
def testInvalidSignatureNotEnoughInputsInGraphDef(self):
with tf.Graph().as_default():
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oi' }
node { name: 'B' op: 'Iif' input: 'A:0' }
"""))
self.assertTrue("Input types mismatch (expected 'int32, float32' but "
"got 'int32')" in str(e.exception))
def testMissingInputOpInGraphDef(self):
with tf.Graph().as_default():
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'B' op: 'If' input: 'A:0' }
"""))
self.assertTrue("Input tensor 'A:0' not found" in str(e.exception))
def testMissingInputOpInGraphDefButAppearsInInputMap(self):
with tf.Graph().as_default():
feed_a_0 = tf.constant(5.0)
b, = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'B' op: 'If' input: 'A:0' }
"""),
input_map={"A:0": feed_a_0},
return_elements=["B"])
self.assertEqual(b.inputs[0], feed_a_0)
def testMissingInputTensorInGraphDef(self):
with tf.Graph().as_default():
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Of' }
node { name: 'B' op: 'If' input: 'A:1' }
"""))
self.assertTrue("Input tensor 'A:1' not found" in str(e.exception))
def testMissingControlInputInGraphDef(self):
with tf.Graph().as_default():
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'B' op: 'None' input: '^A' }
"""))
self.assertTrue("Control input '^A' not found" in str(e.exception))
def testInvalidTensorNameOutputIndexInGraphDef(self):
with tf.Graph().as_default():
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'B' op: 'None' input: 'A:B' }
"""))
self.assertEqual("Cannot convert 'A:B' to a tensor name.",
str(e.exception))
def testInvalidTensorNameInGraphDef(self):
with tf.Graph().as_default():
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'B' op: 'None' input: 'A:B:0' }
"""))
self.assertEqual("Cannot convert 'A:B:0' to a tensor name.",
str(e.exception))
def testMissingReturnOperation(self):
with tf.Graph().as_default():
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'None' }
"""),
return_elements=["B"])
self.assertTrue("return_element 'B' not found in graph_def." in
str(e.exception))
def testMissingReturnTensor(self):
with tf.Graph().as_default():
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oi' }
"""),
return_elements=["A:1"])
self.assertTrue("return_element 'A:1' not found in graph_def." in
str(e.exception))
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oi' }
"""),
return_elements=["B:0"])
self.assertTrue("return_element 'B:0' not found in graph_def." in
str(e.exception))
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oi' }
"""),
return_elements=["A:B:0"])
self.assertTrue("return_element 'A:B:0' not found in graph_def." in
str(e.exception))
def testMissingInputMap(self):
with tf.Graph().as_default():
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'None' }
"""),
input_map={"B:0": tf.constant(5.0)})
self.assertTrue("not found in graph_def: [B:0]" in str(e.exception))
def testInputMapTypeMismatch(self):
with tf.Graph().as_default():
with self.assertRaises(ValueError) as e:
tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'Oi' }
node { name: 'B' op: 'Ii' input: 'A:0' }
"""),
input_map={"A:0": tf.constant(5.0)})
self.assertTrue(
"Cannot convert a tensor of type float32 to an input of type int32."
in str(e.exception))
def testNoReturns(self):
with tf.Graph().as_default() as g:
ret = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'None' }
"""))
self.assertEqual(ret, None)
a = g.get_operation_by_name("import/A")
self.assertEqual(a.type, "None")
def testOverrideNamePrefix(self):
with tf.Graph().as_default():
a, = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'None' }
"""),
return_elements=["A"], name="imported_graph")
self.assertEqual(a.name, "imported_graph/A")
def testNamePrefixColocationAttrs(self):
original_graph_def = self._MakeGraphDef("""
node { name: 'A' op: 'None' }
node { name: 'B' op: 'None' attr {
key: '_class'
value { list { s: 'loc:@A' } }
} }""")
with tf.Graph().as_default():
b, = tf.import_graph_def(original_graph_def,
return_elements=["B"], name="imported_graph")
self.assertProtoEqualsVersion("""
node { name: 'imported_graph/A' op: 'None' }
node { name: 'imported_graph/B' op: 'None' attr {
key: '_class'
value { list { s: 'loc:@imported_graph/A' } }
} }""", b.graph.as_graph_def())
def testNamePrefixColocationAttrsMultipleImport(self):
original_graph_def = self._MakeGraphDef("""
node { name: 'A' op: 'None' }
node { name: 'B' op: 'None' attr {
key: '_class'
value { list { s: 'loc:@A' } }
} }""")
with tf.Graph().as_default():
b, = tf.import_graph_def(original_graph_def,
return_elements=["B"], name="")
_, = tf.import_graph_def(original_graph_def,
return_elements=["B"], name="")
self.assertProtoEqualsVersion("""
node { name: 'A' op: 'None' }
node { name: 'B' op: 'None' attr {
key: '_class'
value { list { s: 'loc:@A' } }
} }
node { name: 'A_1' op: 'None' }
node { name: 'B_1' op: 'None' attr {
key: '_class'
value { list { s: 'loc:@A_1' } }
} }""", b.graph.as_graph_def())
def testNamePrefixColocationAttrsNotFound(self):
original_graph_def = self._MakeGraphDef("""
node { name: 'B' op: 'None' attr {
key: '_class'
value { list { s: 'loc:@A' } }
} }""")
with tf.Graph().as_default():
with self.assertRaisesRegexp(ValueError, "does not exist during import"):
tf.import_graph_def(original_graph_def,
return_elements=["B"], name="imported_graph")
def testEmptyGraph(self):
with tf.Graph().as_default() as g:
init_version = g.version
tf.import_graph_def(self._MakeGraphDef(""))
self.assertEqual(init_version, g.version)
def testInvalidInputForGraphDef(self):
with tf.Graph().as_default():
with self.assertRaises(TypeError) as e:
tf.import_graph_def("")
self.assertEqual(
"graph_def must be a GraphDef proto.", str(e.exception))
def testInvalidInputForInputMap(self):
with tf.Graph().as_default():
with self.assertRaises(TypeError) as e:
tf.import_graph_def(self._MakeGraphDef(""),
input_map=[tf.constant(5.0)])
self.assertEqual("input_map must be a dictionary mapping strings to "
"Tensor objects.", str(e.exception))
def testInvalidInputForReturnOperations(self):
with tf.Graph().as_default():
with self.assertRaises(TypeError) as e:
tf.import_graph_def(self._MakeGraphDef(""), return_elements=[7])
self.assertEqual(
"return_elements must be a list of strings.", str(e.exception))
def testWithExtensionAndAttr(self):
with tf.Graph().as_default() as g:
c = tf.constant(5.0, dtype=tf.float32, name="c")
tf.pack([c, c], name="pack")
gdef = g.as_graph_def()
with self.test_session():
pack, = tf.import_graph_def(gdef, return_elements=["pack"])
self.assertAllEqual(pack.outputs[0].eval(), [5.0, 5.0])
def testWithDevice(self):
with tf.Graph().as_default() as g:
# No device.
a = tf.constant(3.0, name="a")
with tf.device("/cpu:0"):
b = tf.constant(4.0, name="b")
with tf.device("/job:worker"):
c = tf.constant(5.0, name="c")
gdef = g.as_graph_def()
with tf.Graph().as_default():
a2, b2, c2 = tf.import_graph_def(
gdef, return_elements=["a", "b", "c"])
self.assertEqual(a.device, a2.device)
self.assertEqual(b.device, b2.device)
self.assertEqual(c.device, c2.device)
with tf.Graph().as_default():
with tf.device(device.merge_device("/task:0")):
a3, b3, c3 = tf.import_graph_def(
gdef, return_elements=["a", "b", "c"])
self.assertEqual("/task:0", a3.device)
self.assertEqual("/task:0/device:CPU:0", b3.device) # canonicalized.
self.assertEqual(c.device + "/task:0", c3.device)
with tf.Graph().as_default():
with tf.device(device.merge_device("/job:ps")):
a4, b4, c4 = tf.import_graph_def(
gdef, return_elements=["a", "b", "c"])
self.assertEqual("/job:ps", a4.device)
self.assertEqual("/job:ps/device:CPU:0", b4.device) # canonicalized.
self.assertEqual(c.device, c4.device) # worker overrides ps.
with tf.Graph().as_default():
with tf.device(device.merge_device("/gpu:0")):
a5, b5, c5 = tf.import_graph_def(
gdef, return_elements=["a", "b", "c"])
self.assertEqual("/device:GPU:0", a5.device)
self.assertEqual("/device:CPU:0", b5.device) # cpu overrides gpu.
self.assertEqual(c.device + "/device:GPU:0", c5.device)
def testWithDeviceFunctionDependingOnInputs(self):
with tf.Graph().as_default() as g:
with tf.device("/job:ps"):
v = tf.Variable(1.0)
unused_assign_op = v.assign(2.0)
unused_assign_2_op = v.assign(3.0)
unused_add_t = v + v
gdef = g.as_graph_def()
# We'll use the following device function to observe ops with two inputs.
ops_with_two_inputs = []
def input_counter(op):
if any(in_t.dtype.is_ref_dtype for in_t in op.inputs):
ops_with_two_inputs.append(op)
return ""
with tf.Graph().as_default() as g:
with tf.device(input_counter):
tf.import_graph_def(gdef)
# We expect to see the initializer, two assign operations, and the add op.
self.assertEqual(4, len(ops_with_two_inputs))
def testGradient(self):
with tf.Graph().as_default() as g:
inputs = tf.placeholder(tf.float32, shape=[None, 100], name="input")
weights = tf.placeholder(tf.float32, shape=[100, 10], name="weights")
biases = tf.placeholder(tf.float32, shape=[10], name="biases")
activations = tf.nn.relu(tf.matmul(inputs, weights) + biases,
name="activations")
loss = tf.reduce_mean(activations, name="loss")
gdef = g.as_graph_def()
with tf.Graph().as_default() as g:
input_placeholder = tf.placeholder(tf.float32, shape=[32, 100])
weights_var = tf.Variable(tf.truncated_normal([100, 10]), name="weights")
biases_var = tf.Variable(tf.zeros([10]), name="biases")
activations, loss = tf.import_graph_def(
gdef,
input_map={"input:0": input_placeholder,
"weights:0": weights_var,
"biases:0": biases_var},
return_elements=["activations:0", "loss:0"])
self.assertEqual([32, 10], activations.get_shape())
self.assertEqual([], loss.get_shape())
weights_grad, biases_grad = tf.gradients(loss, [weights_var, biases_var])
self.assertEqual([100, 10], weights_grad.get_shape())
self.assertEqual([10], biases_grad.get_shape())
def testLargeGraph(self):
with self.test_session():
# The default message byte limit is 64M. Ours is 2G with a warning at 512.
# Adding a 130M entries float32 tensor should exceed the warning, but not
# the hard limit.
input_shape = [130, 1000, 1000]
tensor_input = np.ones(input_shape, dtype=np.float32)
t = tf.constant(tensor_input, shape=input_shape)
g = tf.identity(t)
g.eval()
def testVersion(self):
v0 = tf.GRAPH_DEF_VERSION_MIN_CONSUMER
v2 = tf.GRAPH_DEF_VERSION
v1 = (v0 + v2) // 2
for producer in v0, v1, v2:
for min_consumer in v0, v1, v2:
with tf.Graph().as_default():
a, = tf.import_graph_def(
self._MakeGraphDef("node { name: 'A' op: 'Oii' }",
producer=producer, min_consumer=min_consumer),
return_elements=["A"])
self.assertEqual(a.graph.graph_def_versions.producer, producer)
self.assertEqual(a.graph.graph_def_versions.min_consumer,
min_consumer)
def testVersionLow(self):
with tf.Graph().as_default() as g:
pat = (r"GraphDef producer version -1 below min producer %d supported "
r"by TensorFlow \S+\. Please regenerate your graph.$" %
tf.GRAPH_DEF_VERSION_MIN_PRODUCER)
tf.import_graph_def(self._MakeGraphDef("", producer=-1))
x = tf.constant(7) # Need at least one op to get a C++ graph generated
with self.test_session(graph=g) as sess:
with self.assertRaisesRegexp(Exception, pat):
sess.run(x)
def testVersionHigh(self):
with tf.Graph().as_default() as g:
pat = (r"GraphDef min consumer version %d above current version %d "
r"for TensorFlow \S+\. Please upgrade TensorFlow\.$" %
(1 << 30, tf.GRAPH_DEF_VERSION))
tf.import_graph_def(self._MakeGraphDef("", min_consumer=1 << 30))
x = tf.constant(7) # Need at least one op to get a C++ graph generated
with self.test_session(graph=g) as sess:
with self.assertRaisesRegexp(Exception, pat):
sess.run(x)
def testDefaultAttrsAdded(self):
with tf.Graph().as_default():
a = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'OpWithDefaultAttr' }
"""),
return_elements=["A"])
self.assertEqual(123.0, a[0].get_attr("default_float"))
def testDefaultAttrsRemoved(self):
producer_op_list = op_def_pb2.OpList()
text_format.Merge("""
op {
name: 'OpWithFutureDefaultAttr'
attr { name: 'default_int' type: 'int' default_value { i: 456 } }
}
""", producer_op_list)
# Attr only in producer_op_list with default value gets removed.
with tf.Graph().as_default():
a = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'OpWithFutureDefaultAttr'
attr { key: 'default_int' value { i: 456 } } }
"""),
return_elements=["A"], producer_op_list=producer_op_list)
with self.assertRaisesRegexp(ValueError, "No attr named 'default_int'"):
a[0].get_attr("default_int")
# Attr only in producer_op_list with non-default value is preserved.
with tf.Graph().as_default():
a = tf.import_graph_def(
self._MakeGraphDef("""
node { name: 'A' op: 'OpWithFutureDefaultAttr'
attr { key: 'default_int' value { i: 987 } } }
"""),
return_elements=["A"], producer_op_list=producer_op_list)
self.assertEqual(987, a[0].get_attr("default_int"))
if __name__ == "__main__":
tf.test.main()
|
import unittest
from pyramid import testing
class ViewTests(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def test_my_view(self):
from .views import my_view
request = testing.DummyRequest()
info = my_view(request)
# self.assertEqual(info['project'], 'angular-tictactoe')
|
from __future__ import unicode_literals, division, absolute_import, print_function
import functools
import itertools
import operator
import sys
import os
import codecs
import types
from . import unipath as path
from .const import PY2, PY3, PY35, PYPY, OS_WIN, ASCII_CHARS, URL_SAFE, IRI_UNSAFE
def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc
def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name]
if PY2:
string_types = basestring,
integer_types = (int, long)
class_types = (type, types.ClassType)
text_type = unicode
binary_type = str
xrange = xrange
str = unicode
basestring = basestring
unicode = unicode
bytes = str
long = long
builtin_str = str
raw_input = raw_input
MAXSIZE = int((1 << 31) - 1)
else:
string_types = str,
integer_types = int,
class_types = type,
text_type = str
binary_type = bytes
next = next
unichr = chr
imap = map
izip = zip
xrange = range
str = str
basestring = str
unicode = str
bytes = bytes
long = int
builtin_str = str
raw_input = input
MAXSIZE = sys.maxsize
if PY2:
from urllib import (
quote, unquote, quote_plus, unquote_plus, urlencode, getproxies,
proxy_bypass, proxy_bypass_environment, getproxies_environment)
from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag, parse_qs
from urllib2 import parse_http_list, urlopen, Request, HTTPError
import cookielib
from Cookie import Morsel
from StringIO import StringIO
else:
from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag, parse_qs
from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment, urlopen, Request
from http import cookiejar as cookielib
from http.cookies import Morsel
from urllib.error import HTTPError
from io import StringIO
if PY2:
from ConfigParser import ConfigParser
from Queue import Queue, heapq, deque
from repr import aRepr, repr
from UserDict import UserDict
from UserList import UserList
from UserString import UserString
from urllib3.packages.ordered_dict import OrderedDict
else:
from configparser import ConfigParser
from queue import Queue
import heapq
from collections import deque
from reprlib import aRepr, repr
from collections import UserDict, UserList, UserString, OrderedDict
if PY2:
import __builtin__
# Python 2-builtin ranges produce lists
lrange = __builtin__.range
lzip = __builtin__.zip
lmap = __builtin__.map
lfilter = __builtin__.filter
from itertools import ifilterfalse, izip_longest
else:
# list-producing versions of the major Python iterating functions
def lrange(*args, **kwargs):
return list(range(*args, **kwargs))
def lzip(*args, **kwargs):
return list(zip(*args, **kwargs))
def lmap(*args, **kwargs):
return list(map(*args, **kwargs))
def lfilter(*args, **kwargs):
return list(filter(*args, **kwargs))
from itertools import filterfalse, zip_longest
try:
import simplejson as json
except ImportError:
import json
try:
advance_iterator = next
except NameError:
def advance_iterator(it):
return it.next()
next = advance_iterator
try:
callable = callable
except NameError:
def callable(obj):
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
if PY2:
def iterkeys(d, **kw):
return d.iterkeys(**kw)
def itervalues(d, **kw):
return d.itervalues(**kw)
def iteritems(d, **kw):
return d.iteritems(**kw)
def iterlists(d, **kw):
return d.iterlists(**kw)
viewkeys = operator.methodcaller("viewkeys")
viewvalues = operator.methodcaller("viewvalues")
viewitems = operator.methodcaller("viewitems")
else:
def iterkeys(d, **kw):
return iter(d.keys(**kw))
def itervalues(d, **kw):
return iter(d.values(**kw))
def iteritems(d, **kw):
return iter(d.items(**kw))
def iterlists(d, **kw):
return iter(d.lists(**kw))
viewkeys = operator.methodcaller("keys")
viewvalues = operator.methodcaller("values")
viewitems = operator.methodcaller("items")
_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
_add_doc(itervalues, "Return an iterator over the values of a dictionary.")
_add_doc(iteritems,
"Return an iterator over the (key, value) pairs of a dictionary.")
_add_doc(iterlists,
"Return an iterator over the (key, [values]) pairs of a dictionary.")
if PY2:
def b(s):
return s
# Workaround for standalone backslash
def u(s):
return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
unichr = unichr
int2byte = chr
def byte2int(bs):
return ord(bs[0])
def indexbytes(buf, i):
return ord(buf[i])
iterbytes = functools.partial(itertools.imap, ord)
import StringIO
StringIO = BytesIO = StringIO.StringIO
else:
def b(s):
return s.encode("latin-1")
def u(s):
return s
unichr = chr
import struct
int2byte = struct.Struct(">B").pack
del struct
byte2int = operator.itemgetter(0)
indexbytes = operator.getitem
iterbytes = iter
import io
StringIO = io.StringIO
BytesIO = io.BytesIO
_add_doc(b, """Byte literal""")
_add_doc(u, """Text literal""")
if sys.version_info[0:2] < (3, 4):
def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
updated=functools.WRAPPER_UPDATES):
def wrapper(f):
f = functools.wraps(wrapped, assigned, updated)(f)
f.__wrapped__ = wrapped
return f
return wrapper
else:
wraps = functools.wraps
def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
def utf8_str(p, enc='utf-8'):
if p is None:
return None
if isinstance(p, text_type):
return p.encode('utf-8')
if enc != 'utf-8':
return p.decode(enc).encode('utf-8')
return p
def unicode_str(p, enc='utf-8'):
if p is None:
return None
if isinstance(p, text_type):
return p
return p.decode(enc)
def to_text(data, encoding='utf8'):
"""
Make sure string is unicode type, decode with given encoding if it's not.
If parameter is a object, object.__str__ will been called
"""
if isinstance(data, text_type):
return data
elif isinstance(data, binary_type):
return data.decode(encoding, 'ignore')
else:
return text_type(data)
def to_binary(data, encoding='utf8'):
"""
Make sure string is binary type, encode with given encoding if it's not.
If parameter is a object, object.__str__ will been called
"""
if isinstance(data, binary_type):
return data
elif isinstance(data, text_type):
return data.encode(encoding, 'ignore')
else:
return binary_type(data)
def unicode_dict(_dict):
"""
Make sure keys and values of dict is unicode.
"""
r = {}
for k, v in iteritems(_dict):
r[unicode_obj(k)] = unicode_obj(v)
return r
def unicode_list(_list):
"""
Make sure every element in list is unicode. bytes will encode in base64
"""
return [unicode_obj(x) for x in _list]
def unicode_obj(obj):
"""
Make sure keys and values of dict/list/tuple is unicode. bytes will encode in base64.
Can been decode by `decode_unicode_obj`
"""
if isinstance(obj, dict):
return unicode_dict(obj)
elif isinstance(obj, (list, tuple)):
return unicode_list(obj)
elif isinstance(obj, string_types):
return to_text(obj)
elif isinstance(obj, (int, float)):
return obj
elif obj is None:
return obj
else:
try:
return to_text(obj)
except:
return to_text(repr(obj))
def decode_unicode_obj(obj):
"""
Decode unicoded dict/list/tuple encoded by `unicode_obj`
"""
if isinstance(obj, dict):
r = {}
for k, v in iteritems(obj):
r[to_binary(k)] = decode_unicode_obj(v)
return r
elif isinstance(obj, string_types):
return to_binary(obj)
elif isinstance(obj, (list, tuple)):
return [decode_unicode_obj(x) for x in obj]
else:
return obj
def unicode_argv():
if PY3:
return sys.argv
if OS_WIN:
# Versions 2.x of Python don't support Unicode in sys.argv on
# Windows, with the underlying Windows API instead replacing multi-byte
# characters with '?'. So use shell32.GetCommandLineArgvW to get sys.argv
# as a list of Unicode strings
from ctypes import POINTER, byref, cdll, c_int, windll
from ctypes.wintypes import LPCWSTR, LPWSTR
GetCommandLineW = cdll.kernel32.GetCommandLineW
GetCommandLineW.argtypes = []
GetCommandLineW.restype = LPCWSTR
CommandLineToArgvW = windll.shell32.CommandLineToArgvW
CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
CommandLineToArgvW.restype = POINTER(LPWSTR)
cmd = GetCommandLineW()
argc = c_int(0)
argv = CommandLineToArgvW(cmd, byref(argc))
if argc.value > 0:
# Remove Python executable and commands if present
start = argc.value - len(sys.argv)
return [argv[i] for i in
range(start, argc.value)]
# this should never happen
return None
else:
argv = []
argvencoding = sys.stdin.encoding
if argvencoding is None:
argvencoding = sys.getfilesystemencoding()
if argvencoding is None:
argvencoding = 'utf-8'
for arg in sys.argv:
if isinstance(arg, text_type):
argv.append(arg)
else:
argv.append(arg.decode(argvencoding))
return argv
def main():
print(path.pathof(sys.argv[1]))
if __name__ == '__main__':
main()
|
import logging
import os
import sys
def wire():
here = os.path.dirname(os.path.abspath(__file__))
parent = os.path.dirname(here)
lib = os.path.join(parent, "lib")
sys.path.append(lib)
config = os.path.join(parent, "config")
sys.path.append(config)
wire()
from ss2config import *
import selfserve.tokens
os.chdir(os.path.dirname(sys.argv[0])) # for STATE_DIR
logger = logging.getLogger("%s.maint" % LOGGER_NAME)
if __name__ == '__main__':
if not sys.stderr.isatty():
logging.basicConfig(level=logging.__dict__[LOG_LEVEL_INTERACTIVE])
else:
logging.basicConfig(level=logging.DEBUG)
logger.debug('enabled verbose logging since isatty(%d)', sys.stderr.fileno())
for magics in [(PW_RESET_MAGIC, SESSION_MAGIC), ]:
for hextoken, availid, expiry, _ in selfserve.tokens.iter_tokens(magics):
if not selfserve.tokens.is_semantically_valid_token(hextoken, availid, expiry, None, None):
# ### ignore NoSuchToken errors?
selfserve.tokens.kill_token(hextoken)
|
"""Keepalived configuration datamodel
Revision ID: 1e4c1d83044c
Revises: 5a3ee5472c31
Create Date: 2015-08-06 10:39:54.998797
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import sql
revision = '1e4c1d83044c'
down_revision = '5a3ee5472c31'
def upgrade():
op.create_table(
u'vrrp_auth_method',
sa.Column(u'name', sa.String(36), primary_key=True),
sa.Column(u'description', sa.String(255), nullable=True)
)
insert_table = sql.table(
u'vrrp_auth_method',
sql.column(u'name', sa.String),
sql.column(u'description', sa.String)
)
op.bulk_insert(
insert_table,
[
{'name': 'PASS'},
{'name': 'AH'}
]
)
op.create_table(
u'vrrp_group',
sa.Column(u'load_balancer_id', sa.String(36), nullable=False),
sa.Column(u'vrrp_group_name', sa.String(36), nullable=True),
sa.Column(u'vrrp_auth_type', sa.String(16), nullable=True),
sa.Column(u'vrrp_auth_pass', sa.String(36), nullable=True),
sa.Column(u'advert_int', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint(u'load_balancer_id'),
sa.ForeignKeyConstraint([u'load_balancer_id'], [u'load_balancer.id'],
name=u'fk_vrrp_group_load_balancer_id'),
sa.ForeignKeyConstraint([u'vrrp_auth_type'],
[u'vrrp_auth_method.name'],
name=u'fk_load_balancer_vrrp_auth_method_name')
)
op.add_column(
u'listener',
sa.Column(u'peer_port', sa.Integer(), nullable=True)
)
op.add_column(
u'amphora',
sa.Column(u'vrrp_interface', sa.String(16), nullable=True)
)
op.add_column(
u'amphora',
sa.Column(u'vrrp_id', sa.Integer(), nullable=True)
)
op.add_column(
u'amphora',
sa.Column(u'vrrp_priority', sa.Integer(), nullable=True)
)
|
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql+mysqldb://root:root@localhost/test?charset=utf8', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
from application.db import models
Base.metadata.create_all(bind=engine)
|
from oslo_config import cfg
from stevedore import driver
from cloudkitty import config # noqa
from cloudkitty import service
CONF = cfg.CONF
STORAGES_NAMESPACE = 'cloudkitty.storage.backends'
def init_storage_backend():
CONF.import_opt('backend', 'cloudkitty.storage', 'storage')
backend = driver.DriverManager(
STORAGES_NAMESPACE,
CONF.storage.backend)
backend.driver.init()
def main():
service.prepare_service()
init_storage_backend()
|
"""
Django settings for SegmentationService project.
Generated by 'django-admin startproject' using Django 1.11.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = "+3kqv!q9^nky=07w%e8j_orelgln(j$)f&)gy=j+bef24+47j0"
DEBUG = False
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
'api.apps.ApiConfig',
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'SegmentationService.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'SegmentationService.wsgi.application'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.handlers.TimedRotatingFileHandler',
'filename': os.path.join(BASE_DIR, 'log/segmentation.log'),
'when': 'W0',
'backupCount': 52,
'formatter': 'verbose'
},
},
'loggers': {
'segmentation': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
'segmentation.request': {
'handlers': ['file'],
'level': 'ERROR',
'propagate': False,
},
},
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Toronto'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
BINARIZATION_SERIVICE_BASE_URL = "http://segmentationservice.acis.ufl.edu"
MEDIA_ROOT = os.path.join(BASE_DIR, 'data')
MEDIA_URL = '/data/'
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECUR = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_BROWSER_XSS_FILTER = True
|
import tushare as ts
df = ts.get_h_data('600848',start='2016-08-05',end='2016-08-23', autype='hfq')
print("#0", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23')
print("#1", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='W')
print("#2", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='M')
print("#3", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='5')
print("#4", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='15')
print("#5", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='30')
print("#6", df)
df = ts.get_hist_data('600848',start='2016-08-05',end='2016-08-23', ktype='60')
print("#7", df)
|
import sys
def kaprekar(n):
n_digit_count = len(str(n))
m_str = str(n*n)
r_str = m_str[-n_digit_count:]
l_str = m_str[:-n_digit_count]
l = 0 if len(l_str) == 0 else int(l_str)
r = int(r_str)
return l + r == n
p = int(sys.stdin.readline())
q = int(sys.stdin.readline())
exists = False
for i in range(p,q+1,1):
if kaprekar(i):
print(i, end=' ')
exists = True
if not exists:
print('INVALID RANGE')
|
from pymongo import MongoClient
import datetime
import pymongo
client = MongoClient()
client = MongoClient('mongodb://mongodb_server:27017')
db = client['test']
posts = db.posts
post_data = {
'title': 'Python and MongoDB',
'content': 'PyMongo is fun, you guys',
'author': 'Scott'
}
result = posts.insert_one(post_data)
print('One post: {0}'.format(result.inserted_id))
post_2 = {
'title': 'Virtual Environments',
'content': 'Use virtual environments, you guys',
'author': 'Scott',
'date': '2021-11-21'
}
post_3 = {
'title': 'Learning Python',
'content': 'Learn Python, it is easy',
'author': 'Bill'
}
new_result = posts.insert_many([post_2, post_3])
print('Multiple posts: {0}'.format(new_result.inserted_ids))
bills_post = posts.find_one({'author': 'Bill'})
print(bills_post)
print("View all documents: ")
cursor = posts.find()
for document in cursor:
print(document)
print("Remove All Documents: ")
result = posts.delete_many({})
print("To see the number of documents deleted: ", result.deleted_count)
|
import sys
import synapseclient
syn = synapseclient.login(silent=True)
files = syn.restGET('/entity/md5/%s' % sys.argv[1])
for item in files['results']:
print sys.argv[1], item['name'], item['id'], item['versionNumber']
|
"""Tests for asserts module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.autograph.converters import asserts
from tensorflow.python.autograph.converters import functions
from tensorflow.python.autograph.core import converter_testing
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.platform import test
class AssertsTest(converter_testing.TestCase):
def test_basic(self):
def test_fn(a):
assert a, 'testmsg'
return a
with ops.Graph().as_default():
with self.converted(test_fn, (functions, asserts), {}) as result:
op = result.test_fn(constant_op.constant(False))
with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, 'testmsg'):
self.evaluate(op)
if __name__ == '__main__':
test.main()
|
import mock
import os
import sh
import shutil
import tempfile
from six.moves import configparser
import dlrn.shell
from dlrn.build import build
from dlrn.build import build_rpm_wrapper
from dlrn.config import ConfigOptions
from dlrn import db
from dlrn.tests import base
from dlrn import utils
class FakePkgInfo(object):
def preprocess(self, **argv):
return
dlrn.shell.pkginfo = FakePkgInfo()
def mocked_listdir(directory):
return ['python-pysaml2-3.0-1a.el7.centos.src.rpm']
@mock.patch('sh.restorecon', create=True)
@mock.patch('sh.env', create=True)
@mock.patch.object(sh.Command, '__call__', autospec=True)
class TestBuild(base.TestCase):
def setUp(self):
super(TestBuild, self).setUp()
self.configfile = configparser.RawConfigParser()
self.configfile.read("projects.ini")
self.configfile.set('DEFAULT', 'datadir', tempfile.mkdtemp())
self.configfile.set('DEFAULT', 'scriptsdir', tempfile.mkdtemp())
self.configfile.set('DEFAULT', 'baseurl', "file://%s" %
self.configfile.get('DEFAULT', 'datadir'))
self.config = ConfigOptions(self.configfile)
shutil.copyfile(os.path.join("scripts", "centos8.cfg"),
os.path.join(self.config.scriptsdir, "centos8.cfg"))
with open(os.path.join(self.config.datadir,
"delorean-deps.repo"), "w") as fp:
fp.write("[test]\nname=test\nenabled=0\n")
self.db_fd, filepath = tempfile.mkstemp()
self.session = db.getSession("sqlite:///%s" % filepath)
utils.loadYAML(self.session, './dlrn/tests/samples/commits_1.yaml')
def tearDown(self):
super(TestBuild, self).tearDown()
shutil.rmtree(self.config.datadir)
shutil.rmtree(self.config.scriptsdir)
os.close(self.db_fd)
# Make sure env vars are cleaned up
if 'RELEASE_NUMBERING' in os.environ:
del os.environ['RELEASE_NUMBERING']
if 'RELEASE_MINOR' in os.environ:
del os.environ['RELEASE_MINOR']
@mock.patch('os.listdir', side_effect=mocked_listdir)
def test_build_rpm_wrapper(self, ld_mock, sh_mock, env_mock, rc_mock):
self.configfile.set('DEFAULT', 'build_driver',
'dlrn.drivers.mockdriver.MockBuildDriver')
self.config = ConfigOptions(self.configfile)
commit = db.getCommits(self.session)[-1]
build_rpm_wrapper(commit, False, False, False, None, True)
# 3 sh calls:
# 1- build_srpm.sh
# 2- mock (handled by env_mock)
# 3- restorecon (handled by rc_mock)
self.assertEqual(env_mock.call_count, 2)
self.assertEqual(rc_mock.call_count, 1)
self.assertTrue(os.path.exists(os.path.join(self.config.datadir,
"dlrn-1.cfg")))
@mock.patch('dlrn.build.fetch_remote_file')
@mock.patch('os.listdir', side_effect=mocked_listdir)
def test_build_rpm_wrapper_custom_deps_url(self, ld_mock, get_mock,
sh_mock, env_mock, rc_mock):
self.configfile.set('DEFAULT', 'build_driver',
'dlrn.drivers.mockdriver.MockBuildDriver')
self.configfile.set('DEFAULT', 'deps_url',
'file://%s/custom-deps.repo' %
self.configfile.get('DEFAULT', 'datadir'))
self.config = ConfigOptions(self.configfile)
commit = db.getCommits(self.session)[-1]
build_rpm_wrapper(commit, False, False, False, None, True)
expected = [mock.call('file://%s/custom-deps.repo' %
self.configfile.get('DEFAULT', 'datadir'))]
self.assertEqual(expected, get_mock.call_args_list)
@mock.patch('dlrn.build.fetch_remote_file')
@mock.patch('os.listdir', side_effect=mocked_listdir)
def test_build_rpm_wrapper_default_deps_url(self, ld_mock, url_mock,
sh_mock, env_mock, rc_mock):
self.configfile.set('DEFAULT', 'build_driver',
'dlrn.drivers.mockdriver.MockBuildDriver')
self.config = ConfigOptions(self.configfile)
commit = db.getCommits(self.session)[-1]
build_rpm_wrapper(commit, False, False, False, None, True)
expected = [mock.call('file://%s/delorean-deps.repo' %
self.configfile.get('DEFAULT', 'datadir'))]
self.assertEqual(expected, url_mock.call_args_list)
@mock.patch('os.listdir', side_effect=mocked_listdir)
def test_build_rpm_wrapper_release_numbering(self, ld_mock, sh_mock,
env_mock, rc_mock):
self.configfile.set('DEFAULT', 'build_driver',
'dlrn.drivers.mockdriver.MockBuildDriver')
self.configfile.set('DEFAULT', 'release_numbering',
'minor.date.hash')
self.configfile.set('DEFAULT', 'release_minor',
'2')
self.config = ConfigOptions(self.configfile)
commit = db.getCommits(self.session)[-1]
build_rpm_wrapper(commit, False, False, False, None, True)
self.assertEqual(os.environ['RELEASE_NUMBERING'], 'minor.date.hash')
self.assertEqual(os.environ['RELEASE_MINOR'], '2')
@mock.patch('os.listdir', side_effect=mocked_listdir)
def test_build(self, ld_mock, sh_mock, env_mock, rc_mock):
self.configfile.set('DEFAULT', 'build_driver',
'dlrn.drivers.mockdriver.MockBuildDriver')
self.config = ConfigOptions(self.configfile)
commit = db.getCommits(self.session)[-1]
try:
build([], commit, None, False, False, False, True)
except Exception as e:
self.assertIn("No rpms built for", str(e))
@mock.patch('os.listdir', side_effect=mocked_listdir)
def test_build_configdir(self, ld_mock, sh_mock, env_mock, rc_mock):
configdir = tempfile.mkdtemp()
self.configfile.set('DEFAULT', 'configdir', configdir)
self.configfile.set('DEFAULT', 'build_driver',
'dlrn.drivers.mockdriver.MockBuildDriver')
self.config = ConfigOptions(self.configfile)
shutil.copyfile(os.path.join("scripts", "centos8.cfg"),
os.path.join(configdir, "centos8.cfg"))
commit = db.getCommits(self.session)[-1]
expected = [mock.call('%s/centos8.cfg' % configdir,
'%s/dlrn-1.cfg.new' % self.config.datadir),
mock.call('%s/dlrn-1.cfg.new' % self.config.datadir,
'%s/dlrn-1.cfg' % self.config.datadir)]
with mock.patch('shutil.copyfile',
side_effect=shutil.copyfile) as cp_mock:
build_rpm_wrapper(commit, False, False, False, None, True)
self.assertEqual(expected, cp_mock.call_args_list)
@mock.patch('dlrn.drivers.kojidriver.KojiBuildDriver.build_package')
@mock.patch('os.listdir', side_effect=mocked_listdir)
@mock.patch('dlrn.drivers.kojidriver.KojiBuildDriver.write_mock_config',
create=True)
def test_build_rpm_wrapper_mock_config(self, wm_mock, ld_mock, bp_mock,
sh_mock, env_mock, rc_mock):
self.configfile.set('kojibuild_driver', 'fetch_mock_config', 'True')
self.configfile.set('DEFAULT', 'build_driver',
'dlrn.drivers.kojidriver.KojiBuildDriver')
self.config = ConfigOptions(self.configfile)
commit = db.getCommits(self.session)[-1]
build_rpm_wrapper(commit, False, False, False, None, True)
self.assertEqual(wm_mock.call_count, 1)
|
import mock
import six
import webob
import ddt
from cinder.api.contrib import types_manage
from cinder import context
from cinder import exception
from cinder import test
from cinder.tests.unit.api import fakes
from cinder.tests.unit import fake_constants as fake
from cinder.volume import volume_types
DEFAULT_VOLUME_TYPE = fake.VOLUME_TYPE_ID
IN_USE_VOLUME_TYPE = fake.VOLUME_TYPE2_ID
UPDATE_DESC_ONLY_TYPE = fake.VOLUME_TYPE3_ID
UPDATE_NAME_ONLY_TYPE = fake.VOLUME_TYPE4_ID
UPDATE_NAME_AFTER_DELETE_TYPE = fake.VOLUME_TYPE5_ID
NOT_FOUND_VOLUME_TYPE = fake.WILL_NOT_BE_FOUND_ID
def stub_volume_type(id):
specs = {"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"}
return dict(id=id,
name='vol_type_%s' % six.text_type(id),
description='vol_type_desc_%s' % six.text_type(id),
extra_specs=specs)
def stub_volume_type_updated(id, is_public=True):
return dict(id=id,
name='vol_type_%s_%s' % (six.text_type(id), six.text_type(id)),
is_public=is_public,
description='vol_type_desc_%s_%s' % (
six.text_type(id), six.text_type(id)))
def stub_volume_type_updated_desc_only(id):
return dict(id=id,
name='vol_type_%s' % six.text_type(id),
description='vol_type_desc_%s_%s' % (
six.text_type(id), six.text_type(id)))
def return_volume_types_get_volume_type(context, id):
if id == fake.WILL_NOT_BE_FOUND_ID:
raise exception.VolumeTypeNotFound(volume_type_id=id)
return stub_volume_type(id)
def return_volume_types_destroy(context, name):
if name == fake.WILL_NOT_BE_FOUND_ID:
raise exception.VolumeTypeNotFoundByName(volume_type_name=name)
pass
def return_volume_types_with_volumes_destroy(context, id):
if id == IN_USE_VOLUME_TYPE:
raise exception.VolumeTypeInUse(volume_type_id=id)
pass
def return_volume_types_create(context,
name,
specs,
is_public,
description):
pass
def return_volume_types_create_duplicate_type(context,
name,
specs,
is_public,
description):
raise exception.VolumeTypeExists(id=name)
def stub_volume_type_updated_name_only(id):
return dict(id=id,
name='vol_type_%s_%s' % (six.text_type(id), six.text_type(id)),
description='vol_type_desc_%s' % six.text_type(id))
def stub_volume_type_updated_name_after_delete(id):
return dict(id=id,
name='vol_type_%s' % six.text_type(id),
description='vol_type_desc_%s' % six.text_type(id))
def return_volume_types_get_volume_type_updated(id, is_public=True):
if id == NOT_FOUND_VOLUME_TYPE:
raise exception.VolumeTypeNotFound(volume_type_id=id)
if id == UPDATE_DESC_ONLY_TYPE:
return stub_volume_type_updated_desc_only(id)
if id == UPDATE_NAME_ONLY_TYPE:
return stub_volume_type_updated_name_only(id)
if id == UPDATE_NAME_AFTER_DELETE_TYPE:
return stub_volume_type_updated_name_after_delete(id)
# anything else
return stub_volume_type_updated(id, is_public=is_public)
def return_volume_types_get_by_name(context, name):
if name == NOT_FOUND_VOLUME_TYPE:
raise exception.VolumeTypeNotFoundByName(volume_type_name=name)
return stub_volume_type(name.split("_")[2])
def return_volume_types_get_default():
return stub_volume_type(DEFAULT_VOLUME_TYPE)
def return_volume_types_get_default_not_found():
return {}
@ddt.ddt
class VolumeTypesManageApiTest(test.TestCase):
def setUp(self):
super(VolumeTypesManageApiTest, self).setUp()
self.flags(host='fake')
self.controller = types_manage.VolumeTypesManageController()
"""to reset notifier drivers left over from other api/contrib tests"""
def tearDown(self):
super(VolumeTypesManageApiTest, self).tearDown()
def test_volume_types_delete(self):
self.stubs.Set(volume_types, 'get_volume_type',
return_volume_types_get_volume_type)
self.stubs.Set(volume_types, 'destroy',
return_volume_types_destroy)
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, DEFAULT_VOLUME_TYPE))
self.assertEqual(0, len(self.notifier.notifications))
self.controller._delete(req, DEFAULT_VOLUME_TYPE)
self.assertEqual(1, len(self.notifier.notifications))
def test_volume_types_delete_not_found(self):
self.stubs.Set(volume_types, 'get_volume_type',
return_volume_types_get_volume_type)
self.stubs.Set(volume_types, 'destroy',
return_volume_types_destroy)
self.assertEqual(0, len(self.notifier.notifications))
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, NOT_FOUND_VOLUME_TYPE))
self.assertRaises(webob.exc.HTTPNotFound, self.controller._delete,
req, NOT_FOUND_VOLUME_TYPE)
self.assertEqual(1, len(self.notifier.notifications))
def test_volume_types_with_volumes_destroy(self):
self.stubs.Set(volume_types, 'get_volume_type',
return_volume_types_get_volume_type)
self.stubs.Set(volume_types, 'destroy',
return_volume_types_with_volumes_destroy)
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, DEFAULT_VOLUME_TYPE))
self.assertEqual(0, len(self.notifier.notifications))
self.controller._delete(req, DEFAULT_VOLUME_TYPE)
self.assertEqual(1, len(self.notifier.notifications))
@mock.patch('cinder.volume.volume_types.destroy')
@mock.patch('cinder.volume.volume_types.get_volume_type')
@mock.patch('cinder.policy.enforce')
def test_volume_types_delete_with_non_admin(self, mock_policy_enforce,
mock_get, mock_destroy):
# allow policy authorized user to delete type
mock_policy_enforce.return_value = None
mock_get.return_value = \
{'extra_specs': {"key1": "value1"},
'id': DEFAULT_VOLUME_TYPE,
'name': u'vol_type_1',
'description': u'vol_type_desc_%s' % DEFAULT_VOLUME_TYPE}
mock_destroy.side_effect = return_volume_types_destroy
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' %
(fake.PROJECT_ID, DEFAULT_VOLUME_TYPE),
use_admin_context=False)
self.assertEqual(0, len(self.notifier.notifications))
self.controller._delete(req, DEFAULT_VOLUME_TYPE)
self.assertEqual(1, len(self.notifier.notifications))
# non policy authorized user fails to delete type
mock_policy_enforce.side_effect = (
exception.PolicyNotAuthorized(action='type_delete'))
self.assertRaises(exception.PolicyNotAuthorized,
self.controller._delete,
req, DEFAULT_VOLUME_TYPE)
def test_create(self):
self.stubs.Set(volume_types, 'create',
return_volume_types_create)
self.stubs.Set(volume_types, 'get_volume_type_by_name',
return_volume_types_get_by_name)
body = {"volume_type": {"name": "vol_type_1",
"os-volume-type-access:is_public": True,
"extra_specs": {"key1": "value1"}}}
req = fakes.HTTPRequest.blank('/v2/%s/types' % fake.PROJECT_ID)
self.assertEqual(0, len(self.notifier.notifications))
res_dict = self.controller._create(req, body)
self.assertEqual(1, len(self.notifier.notifications))
id = res_dict['volume_type']['id']
self._check_test_results(res_dict, {
'expected_name': 'vol_type_1',
'expected_desc': 'vol_type_desc_%s' % id})
@mock.patch('cinder.volume.volume_types.create')
@mock.patch('cinder.volume.volume_types.get_volume_type_by_name')
def test_create_with_description_of_zero_length(
self, mock_get_volume_type_by_name, mock_create_type):
mock_get_volume_type_by_name.return_value = \
{'extra_specs': {"key1": "value1"},
'id': DEFAULT_VOLUME_TYPE,
'name': u'vol_type_1',
'description': u''}
type_description = ""
body = {"volume_type": {"name": "vol_type_1",
"description": type_description,
"extra_specs": {"key1": "value1"}}}
req = fakes.HTTPRequest.blank('/v2/%s/types' % fake.PROJECT_ID)
res_dict = self.controller._create(req, body)
self._check_test_results(res_dict, {
'expected_name': 'vol_type_1', 'expected_desc': ''})
def test_create_type_with_name_too_long(self):
type_name = 'a' * 256
body = {"volume_type": {"name": type_name,
"extra_specs": {"key1": "value1"}}}
req = fakes.HTTPRequest.blank('/v2/%s/types' % fake.PROJECT_ID)
self.assertRaises(exception.InvalidInput,
self.controller._create, req, body)
def test_create_type_with_description_too_long(self):
type_description = 'a' * 256
body = {"volume_type": {"name": "vol_type_1",
"description": type_description,
"extra_specs": {"key1": "value1"}}}
req = fakes.HTTPRequest.blank('/v2/%s/types' % fake.PROJECT_ID)
self.assertRaises(exception.InvalidInput,
self.controller._create, req, body)
def test_create_duplicate_type_fail(self):
self.stubs.Set(volume_types, 'create',
return_volume_types_create_duplicate_type)
self.stubs.Set(volume_types, 'get_volume_type_by_name',
return_volume_types_get_by_name)
body = {"volume_type": {"name": "vol_type_1",
"extra_specs": {"key1": "value1"}}}
req = fakes.HTTPRequest.blank('/v2/%s/types' % fake.PROJECT_ID)
self.assertRaises(webob.exc.HTTPConflict,
self.controller._create, req, body)
def test_create_type_with_invalid_is_public(self):
body = {"volume_type": {"name": "vol_type_1",
"os-volume-type-access:is_public": "fake",
"description": "test description",
"extra_specs": {"key1": "value1"}}}
req = fakes.HTTPRequest.blank('/v2/%s/types' % fake.PROJECT_ID)
self.assertRaises(webob.exc.HTTPBadRequest,
self.controller._create, req, body)
def _create_volume_type_bad_body(self, body):
req = fakes.HTTPRequest.blank('/v2/%s/types' % fake.PROJECT_ID)
req.method = 'POST'
self.assertRaises(webob.exc.HTTPBadRequest,
self.controller._create, req, body)
def test_create_no_body(self):
self._create_volume_type_bad_body(body=None)
def test_create_missing_volume(self):
body = {'foo': {'a': 'b'}}
self._create_volume_type_bad_body(body=body)
def test_create_malformed_entity(self):
body = {'volume_type': 'string'}
self._create_volume_type_bad_body(body=body)
@mock.patch('cinder.volume.volume_types.create')
@mock.patch('cinder.volume.volume_types.get_volume_type_by_name')
@mock.patch('cinder.policy.enforce')
def test_create_with_none_admin(self, mock_policy_enforce,
mock_get_volume_type_by_name,
mock_create_type):
# allow policy authorized user to create type
mock_policy_enforce.return_value = None
mock_get_volume_type_by_name.return_value = \
{'extra_specs': {"key1": "value1"},
'id': DEFAULT_VOLUME_TYPE,
'name': u'vol_type_1',
'description': u'vol_type_desc_1'}
body = {"volume_type": {"name": "vol_type_1",
"os-volume-type-access:is_public": True,
"extra_specs": {"key1": "value1"}}}
req = fakes.HTTPRequest.blank('/v2/%s/types' % fake.PROJECT_ID,
use_admin_context=False)
self.assertEqual(0, len(self.notifier.notifications))
res_dict = self.controller._create(req, body)
self.assertEqual(1, len(self.notifier.notifications))
self._check_test_results(res_dict, {
'expected_name': 'vol_type_1', 'expected_desc': 'vol_type_desc_1'})
# non policy authorized user fails to create type
mock_policy_enforce.side_effect = (
exception.PolicyNotAuthorized(action='type_create'))
self.assertRaises(exception.PolicyNotAuthorized,
self.controller._create,
req, body)
@ddt.data({'a' * 256: 'a'},
{'a': 'a' * 256},
{'': 'a'},
'foo',
None)
def test_create_type_with_invalid_extra_specs(self, value):
body = {"volume_type": {"name": "vol_type_1",
"os-volume-type-access:is_public": False,
"description": "test description"}}
body['volume_type']['extra_specs'] = value
req = fakes.HTTPRequest.blank('/v2/%s/types' % fake.PROJECT_ID)
self.assertRaises(exception.InvalidInput,
self.controller._create, req, body)
@mock.patch('cinder.volume.volume_types.update')
@mock.patch('cinder.volume.volume_types.get_volume_type')
def test_update(self, mock_get, mock_update):
mock_get.return_value = return_volume_types_get_volume_type_updated(
DEFAULT_VOLUME_TYPE, is_public=False)
body = {"volume_type": {"is_public": False}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, DEFAULT_VOLUME_TYPE))
req.method = 'PUT'
self.assertEqual(0, len(self.notifier.notifications))
res_dict = self.controller._update(req, DEFAULT_VOLUME_TYPE, body)
self.assertEqual(1, len(self.notifier.notifications))
self._check_test_results(
res_dict,
{'expected_desc': 'vol_type_desc_%s_%s' %
(DEFAULT_VOLUME_TYPE, DEFAULT_VOLUME_TYPE),
'expected_name': 'vol_type_%s_%s' %
(DEFAULT_VOLUME_TYPE, DEFAULT_VOLUME_TYPE),
'is_public': False})
@mock.patch('cinder.volume.volume_types.update')
@mock.patch('cinder.volume.volume_types.get_volume_type')
def test_update_type_with_description_having_length_zero(
self, mock_get_volume_type, mock_type_update):
mock_get_volume_type.return_value = \
{'id': DEFAULT_VOLUME_TYPE, 'name': u'vol_type_1',
'description': u''}
type_description = ""
body = {"volume_type": {"description": type_description}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, DEFAULT_VOLUME_TYPE))
req.method = 'PUT'
resp = self.controller._update(req, DEFAULT_VOLUME_TYPE, body)
self._check_test_results(resp,
{'expected_desc': '',
'expected_name': 'vol_type_1'})
def test_update_type_with_name_too_long(self):
type_name = 'a' * 256
body = {"volume_type": {"name": type_name,
"description": ""}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, DEFAULT_VOLUME_TYPE))
req.method = 'PUT'
self.assertRaises(exception.InvalidInput,
self.controller._update, req,
DEFAULT_VOLUME_TYPE, body)
def test_update_type_with_description_too_long(self):
type_description = 'a' * 256
body = {"volume_type": {"description": type_description}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, DEFAULT_VOLUME_TYPE))
req.method = 'PUT'
self.assertRaises(exception.InvalidInput,
self.controller._update, req,
DEFAULT_VOLUME_TYPE, body)
@mock.patch('cinder.volume.volume_types.get_volume_type')
@mock.patch('cinder.volume.volume_types.update')
def test_update_non_exist(self, mock_update, mock_get_volume_type):
mock_get_volume_type.side_effect = exception.VolumeTypeNotFound(
volume_type_id=NOT_FOUND_VOLUME_TYPE)
body = {"volume_type": {"name": "vol_type_1_1",
"description": "vol_type_desc_1_1"}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, NOT_FOUND_VOLUME_TYPE))
req.method = 'PUT'
self.assertEqual(0, len(self.notifier.notifications))
self.assertRaises(webob.exc.HTTPNotFound,
self.controller._update, req,
NOT_FOUND_VOLUME_TYPE, body)
self.assertEqual(1, len(self.notifier.notifications))
@mock.patch('cinder.volume.volume_types.get_volume_type')
@mock.patch('cinder.volume.volume_types.update')
def test_update_db_fail(self, mock_update, mock_get_volume_type):
mock_update.side_effect = exception.VolumeTypeUpdateFailed(
id=DEFAULT_VOLUME_TYPE)
mock_get_volume_type.return_value = stub_volume_type(
DEFAULT_VOLUME_TYPE)
body = {"volume_type": {"name": "vol_type_1_1",
"description": "vol_type_desc_1_1"}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, DEFAULT_VOLUME_TYPE))
req.method = 'PUT'
self.assertEqual(0, len(self.notifier.notifications))
self.assertRaises(webob.exc.HTTPInternalServerError,
self.controller._update, req,
DEFAULT_VOLUME_TYPE, body)
self.assertEqual(1, len(self.notifier.notifications))
def test_update_no_name_no_description(self):
body = {"volume_type": {}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, DEFAULT_VOLUME_TYPE))
req.method = 'PUT'
self.assertRaises(webob.exc.HTTPBadRequest,
self.controller._update, req,
DEFAULT_VOLUME_TYPE, body)
def test_update_empty_name(self):
body = {"volume_type": {"name": " ",
"description": "something"}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, DEFAULT_VOLUME_TYPE))
req.method = 'PUT'
self.assertRaises(webob.exc.HTTPBadRequest,
self.controller._update, req,
DEFAULT_VOLUME_TYPE, body)
@mock.patch('cinder.volume.volume_types.get_volume_type')
@mock.patch('cinder.db.volume_type_update')
@mock.patch('cinder.quota.VolumeTypeQuotaEngine.'
'update_quota_resource')
def test_update_only_name(self, mock_update_quota,
mock_update, mock_get):
mock_get.return_value = return_volume_types_get_volume_type_updated(
UPDATE_NAME_ONLY_TYPE)
ctxt = context.RequestContext(fake.USER_ID, fake.PROJECT_ID, True)
name = "vol_type_%s" % UPDATE_NAME_ONLY_TYPE
updated_name = "%s_%s" % (name, UPDATE_NAME_ONLY_TYPE)
desc = "vol_type_desc_%s" % UPDATE_NAME_ONLY_TYPE
body = {"volume_type": {"name": name}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' %
(fake.PROJECT_ID, UPDATE_NAME_ONLY_TYPE))
req.method = 'PUT'
req.environ['cinder.context'] = ctxt
self.assertEqual(0, len(self.notifier.notifications))
res_dict = self.controller._update(req, UPDATE_NAME_ONLY_TYPE, body)
self.assertEqual(1, len(self.notifier.notifications))
mock_update_quota.assert_called_once_with(ctxt, updated_name, name)
self._check_test_results(res_dict,
{'expected_name': updated_name,
'expected_desc': desc})
@mock.patch('cinder.volume.volume_types.update')
@mock.patch('cinder.volume.volume_types.get_volume_type')
def test_update_only_description(self, mock_get, mock_update):
mock_get.return_value = return_volume_types_get_volume_type_updated(
UPDATE_DESC_ONLY_TYPE)
name = "vol_type_%s" % UPDATE_DESC_ONLY_TYPE
desc = "vol_type_desc_%s" % UPDATE_DESC_ONLY_TYPE
updated_desc = "%s_%s" % (desc, UPDATE_DESC_ONLY_TYPE)
body = {"volume_type": {"description": updated_desc}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, UPDATE_DESC_ONLY_TYPE))
req.method = 'PUT'
self.assertEqual(0, len(self.notifier.notifications))
res_dict = self.controller._update(req, UPDATE_DESC_ONLY_TYPE, body)
self.assertEqual(1, len(self.notifier.notifications))
self._check_test_results(res_dict,
{'expected_name': name,
'expected_desc': updated_desc})
@mock.patch('cinder.volume.volume_types.update')
@mock.patch('cinder.volume.volume_types.get_volume_type')
def test_update_only_is_public(self, mock_get, mock_update):
is_public = False
mock_get.return_value = return_volume_types_get_volume_type_updated(
DEFAULT_VOLUME_TYPE, is_public=is_public)
name = "vol_type_%s" % DEFAULT_VOLUME_TYPE
updated_name = '%s_%s' % (name, DEFAULT_VOLUME_TYPE)
desc = "vol_type_desc_%s" % DEFAULT_VOLUME_TYPE
updated_desc = "%s_%s" % (desc, DEFAULT_VOLUME_TYPE)
body = {"volume_type": {"is_public": is_public}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, DEFAULT_VOLUME_TYPE))
req.method = 'PUT'
self.assertEqual(0, len(self.notifier.notifications))
res_dict = self.controller._update(req, DEFAULT_VOLUME_TYPE, body)
self.assertEqual(1, len(self.notifier.notifications))
self._check_test_results(res_dict,
{'expected_name': updated_name,
'expected_desc': updated_desc,
'is_public': False})
def test_update_invalid_is_public(self):
body = {"volume_type": {"name": "test",
"description": "something",
"is_public": "fake"}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, DEFAULT_VOLUME_TYPE))
req.method = 'PUT'
self.assertRaises(webob.exc.HTTPBadRequest,
self.controller._update, req,
DEFAULT_VOLUME_TYPE, body)
@mock.patch('cinder.volume.volume_types.update')
@mock.patch('cinder.volume.volume_types.get_volume_type')
def test_rename_existing_name(self, mock_get, mock_update):
id = UPDATE_NAME_AFTER_DELETE_TYPE
name = "vol_type_%s" % id
updated_name = "%s_%s" % (name, id)
desc = "vol_type_desc_%s" % id
mock_update.side_effect = exception.VolumeTypeExists(
id=id, name=name)
mock_get.return_value = return_volume_types_get_volume_type_updated(
UPDATE_NAME_AFTER_DELETE_TYPE)
# first attempt fail
body = {"volume_type": {"name": name}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, UPDATE_NAME_AFTER_DELETE_TYPE))
req.method = 'PUT'
self.assertEqual(0, len(self.notifier.notifications))
self.assertRaises(webob.exc.HTTPConflict,
self.controller._update, req,
UPDATE_NAME_AFTER_DELETE_TYPE, body)
self.assertEqual(1, len(self.notifier.notifications))
# delete
self.notifier.reset()
self.stubs.Set(volume_types, 'destroy',
return_volume_types_destroy)
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, UPDATE_NAME_AFTER_DELETE_TYPE))
self.assertEqual(0, len(self.notifier.notifications))
self.controller._delete(req, UPDATE_NAME_AFTER_DELETE_TYPE)
self.assertEqual(1, len(self.notifier.notifications))
# update again
mock_update.side_effect = mock.MagicMock()
body = {"volume_type": {"name": updated_name}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, UPDATE_NAME_AFTER_DELETE_TYPE))
req.method = 'PUT'
self.notifier.reset()
self.assertEqual(0, len(self.notifier.notifications))
res_dict = self.controller._update(req, UPDATE_NAME_AFTER_DELETE_TYPE,
body)
self._check_test_results(res_dict,
{'expected_name': name,
'expected_desc': desc})
self.assertEqual(1, len(self.notifier.notifications))
@mock.patch('cinder.volume.volume_types.update')
@mock.patch('cinder.volume.volume_types.get_volume_type')
@mock.patch('cinder.policy.enforce')
def test_update_with_non_admin(self, mock_policy_enforce, mock_get,
mock_update):
# allow policy authorized user to update type
mock_policy_enforce.return_value = None
mock_get.return_value = return_volume_types_get_volume_type_updated(
DEFAULT_VOLUME_TYPE, is_public=False)
name = "vol_type_%s" % DEFAULT_VOLUME_TYPE
updated_name = "%s_%s" % (name, DEFAULT_VOLUME_TYPE)
desc = "vol_type_desc_%s" % DEFAULT_VOLUME_TYPE
updated_desc = "%s_%s" % (desc, DEFAULT_VOLUME_TYPE)
body = {"volume_type": {"name": updated_name,
"description": updated_desc,
"is_public": False}}
req = fakes.HTTPRequest.blank('/v2/%s/types/%s' % (
fake.PROJECT_ID, DEFAULT_VOLUME_TYPE),
use_admin_context=False)
req.method = 'PUT'
self.assertEqual(0, len(self.notifier.notifications))
res_dict = self.controller._update(req, DEFAULT_VOLUME_TYPE, body)
self.assertEqual(1, len(self.notifier.notifications))
self._check_test_results(res_dict,
{'expected_desc': updated_desc,
'expected_name': updated_name,
'is_public': False})
# non policy authorized user fails to update type
mock_policy_enforce.side_effect = (
exception.PolicyNotAuthorized(action='type_update'))
self.assertRaises(exception.PolicyNotAuthorized,
self.controller._update,
req, DEFAULT_VOLUME_TYPE, body)
def _check_test_results(self, results, expected_results):
self.assertEqual(1, len(results))
self.assertEqual(expected_results['expected_desc'],
results['volume_type']['description'])
if expected_results.get('expected_name'):
self.assertEqual(expected_results['expected_name'],
results['volume_type']['name'])
if expected_results.get('is_public') is not None:
self.assertEqual(expected_results['is_public'],
results['volume_type']['is_public'])
|
from __future__ import print_function
import time
from RF24 import *
import RPi.GPIO as GPIO
irq_gpio_pin = None
radio = RF24(22, 0);
def try_read_data(channel=0):
if radio.available():
while radio.available():
len = radio.getDynamicPayloadSize()
receive_payload = radio.read(len)
print('Got payload size={} value="{}"'.format(len, receive_payload.decode('utf-8')))
# First, stop listening so we can talk
radio.stopListening()
# Send the final one back.
radio.write(receive_payload)
print('Sent response.')
# Now, resume listening so we catch the next packets.
radio.startListening()
pipes = [0xF0F0F0F0E1, 0xF0F0F0F0D2]
min_payload_size = 4
max_payload_size = 32
payload_size_increments_by = 1
next_payload_size = min_payload_size
inp_role = 'none'
send_payload = b'ABCDEFGHIJKLMNOPQRSTUVWXYZ789012'
millis = lambda: int(round(time.time() * 1000))
print('pyRF24/examples/pingpair_dyn/')
radio.begin()
radio.enableDynamicPayloads()
radio.setRetries(5, 15)
radio.printDetails()
print(' ************ Role Setup *********** ')
while (inp_role != '0') and (inp_role != '1'):
inp_role = str(input('Choose a role: Enter 0 for receiver, 1 for transmitter (CTRL+C to exit) '))
if inp_role == '0':
print('Role: Pong Back, awaiting transmission')
if irq_gpio_pin is not None:
# set up callback for irq pin
GPIO.setmode(GPIO.BCM)
GPIO.setup(irq_gpio_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(irq_gpio_pin, GPIO.FALLING, callback=try_read_data)
radio.openWritingPipe(pipes[1])
radio.openReadingPipe(1, pipes[0])
radio.startListening()
else:
print('Role: Ping Out, starting transmission')
radio.openWritingPipe(pipes[0])
radio.openReadingPipe(1, pipes[1])
while 1:
if inp_role == '1': # ping out
# The payload will always be the same, what will change is how much of it we send.
# First, stop listening so we can talk.
radio.stopListening()
# Take the time, and send it. This will block until complete
print('Now sending length {} ... '.format(next_payload_size), end="")
radio.write(send_payload[:next_payload_size])
# Now, continue listening
radio.startListening()
# Wait here until we get a response, or timeout
started_waiting_at = millis()
timeout = False
while (not radio.available()) and (not timeout):
if (millis() - started_waiting_at) > 500:
timeout = True
# Describe the results
if timeout:
print('failed, response timed out.')
else:
# Grab the response, compare, and send to debugging spew
len = radio.getDynamicPayloadSize()
receive_payload = radio.read(len)
# Spew it
print('got response size={} value="{}"'.format(len, receive_payload.decode('utf-8')))
# Update size for next time.
next_payload_size += payload_size_increments_by
if next_payload_size > max_payload_size:
next_payload_size = min_payload_size
time.sleep(0.1)
else:
# Pong back role. Receive each packet, dump it out, and send it back
# if there is data ready
if irq_gpio_pin is None:
# no irq pin is set up -> poll it
try_read_data()
else:
# callback routine set for irq pin takes care for reading -
# do nothing, just sleeps in order not to burn cpu by looping
time.sleep(1000)
|
from tensorforce import TensorforceError
from tensorforce.core import tf_function
from tensorforce.core.optimizers import UpdateModifier
class OptimizerWrapper(UpdateModifier):
"""
Optimizer wrapper, which performs additional update modifications, argument order indicates
modifier nesting from outside to inside
(specification key: `optimizer_wrapper`).
Args:
optimizer (specification): Optimizer
(<span style="color:#C00000"><b>required</b></span>).
learning_rate (parameter, float > 0.0): Learning rate
(<span style="color:#00C000"><b>default</b></span>: 1e-3).
clipping_threshold (parameter, float > 0.0): Clipping threshold
(<span style="color:#00C000"><b>default</b></span>: no clipping).
multi_step (parameter, int >= 1): Number of optimization steps
(<span style="color:#00C000"><b>default</b></span>: single step).
subsampling_fraction (parameter, int > 0 | 0.0 < float <= 1.0): Absolute/relative fraction
of batch timesteps to subsample
(<span style="color:#00C000"><b>default</b></span>: no subsampling).
linesearch_iterations (parameter, int >= 0): Maximum number of line search iterations, using
a backtracking factor of 0.75
(<span style="color:#00C000"><b>default</b></span>: no line search).
doublecheck_update (bool): Check whether update has decreased loss and otherwise reverse it
name (string): (<span style="color:#0000C0"><b>internal use</b></span>).
arguments_spec (specification): <span style="color:#0000C0"><b>internal use</b></span>.
"""
def __init__(
self, optimizer, *, learning_rate=1e-3, clipping_threshold=None, multi_step=1,
subsampling_fraction=1.0, linesearch_iterations=0, doublecheck_update=False, name=None,
arguments_spec=None,
# Deprecated
optimizing_iterations=None, **kwargs
):
if optimizing_iterations is not None:
raise TensorforceError.deprecated(
name='Optimizer', argument='optimizing_iterations',
replacement='linesearch_iterations'
)
if isinstance(optimizer, dict):
if 'learning_rate' not in optimizer:
optimizer['learning_rate'] = learning_rate
else:
optimizer = dict(type=optimizer)
optimizer['learning_rate'] = learning_rate
optimizer.update(kwargs)
if doublecheck_update:
optimizer = dict(type='doublecheck_step', optimizer=optimizer)
if not isinstance(linesearch_iterations, int) or linesearch_iterations > 0:
optimizer = dict(
type='linesearch_step', optimizer=optimizer, max_iterations=linesearch_iterations
)
if not isinstance(subsampling_fraction, float) or subsampling_fraction != 1.0:
optimizer = dict(
type='subsampling_step', optimizer=optimizer, fraction=subsampling_fraction
)
if not isinstance(multi_step, int) or multi_step > 1:
optimizer = dict(type='multi_step', optimizer=optimizer, num_steps=multi_step)
if clipping_threshold is not None:
optimizer = dict(
type='clipping_step', optimizer=optimizer, threshold=clipping_threshold
)
super().__init__(optimizer=optimizer, name=name, arguments_spec=arguments_spec)
@tf_function(num_args=1)
def step(self, *, arguments, variables, **kwargs):
return self.optimizer.step(arguments=arguments, variables=variables, **kwargs)
|
import os
import json
import shutil
import tempfile
from solar.core.handlers import base
from solar.core.handlers.base import SOLAR_TEMP_LOCAL_LOCATION
from solar.core.handlers.base import TempFileHandler
from solar.core.log import log
from solar.core.provider import SVNProvider
ROLES_PATH = '/etc/ansible/roles'
class AnsiblePlaybookBase(base.BaseHandler):
def download_roles(self, urls):
if not os.path.exists(ROLES_PATH):
os.makedirs(ROLES_PATH)
for url in urls:
provider = SVNProvider(url)
provider.run()
shutil.copytree(provider.directory, ROLES_PATH)
class AnsiblePlaybook(AnsiblePlaybookBase, TempFileHandler):
def _make_playbook(self, resource, action, action_path):
dir_path = self.dirs[resource.name]
dest_file = tempfile.mkstemp(text=True, prefix=action, dir=dir_path)[1]
shutil.copyfile(action_path, dest_file)
inventory_path = os.path.join(dir_path, 'inventory')
with open(inventory_path, 'w') as inv:
inv.write(self._make_inventory(resource))
extra_vars_path = os.path.join(dir_path, 'extra_vars')
with open(extra_vars_path, 'w') as extra:
extra.write(self._make_extra_vars(resource))
return dest_file, inventory_path, extra_vars_path
def _make_inventory(self, resource):
inventory = '{0} ansible_connection=local user={1}'
user = self.transport_run.get_transport_data(resource)['user']
host = 'localhost'
return inventory.format(host, user)
def _make_extra_vars(self, resource):
r_args = resource.args
return json.dumps(r_args)
def action(self, resource, action):
action_file = os.path.join(
resource.db_obj.actions_path,
resource.actions[action])
self.prepare_templates_and_scripts(resource, action)
ansible_library_path = self._copy_ansible_library(resource)
files = self._make_playbook(resource,
action,
action_file)
playbook_file, inventory_file, extra_vars_file = files
self.transport_sync.copy(resource, self.dst, '/tmp')
variables = resource.args
if 'roles' in variables:
self.download_roles(variables['roles'])
self.transport_sync.copy(resource, ROLES_PATH, ROLES_PATH)
self.transport_sync.sync_all()
remote_playbook_file = playbook_file.replace(
SOLAR_TEMP_LOCAL_LOCATION, '/tmp/')
remote_inventory_file = inventory_file.replace(
SOLAR_TEMP_LOCAL_LOCATION, '/tmp/')
remote_extra_vars_file = extra_vars_file.replace(
SOLAR_TEMP_LOCAL_LOCATION, '/tmp/')
if ansible_library_path:
remote_ansible_library_path = ansible_library_path.replace(
SOLAR_TEMP_LOCAL_LOCATION, '/tmp/')
call_args = [
'ansible-playbook',
'--module-path',
remote_ansible_library_path,
'-i',
remote_inventory_file,
'--extra-vars',
'@%s' % remote_extra_vars_file,
remote_playbook_file
]
else:
call_args = [
'ansible-playbook',
'-i',
remote_inventory_file,
'--extra-vars',
'@%s' % remote_extra_vars_file,
remote_playbook_file
]
log.debug('EXECUTING: %s', ' '.join(call_args))
rst = self.transport_run.run(resource, *call_args)
self.verify_run_result(call_args, rst)
|
from __future__ import unicode_literals
import mock
from moto.packages.httpretty.core import HTTPrettyRequest, fake_gethostname, fake_gethostbyname
def test_parse_querystring():
core = HTTPrettyRequest(headers='test test HTTP/1.1')
qs = 'test test'
response = core.parse_querystring(qs)
assert response == {}
def test_parse_request_body():
core = HTTPrettyRequest(headers='test test HTTP/1.1')
qs = 'test'
response = core.parse_request_body(qs)
assert response == 'test'
def test_fake_gethostname():
response = fake_gethostname()
assert response == 'localhost'
def test_fake_gethostbyname():
host = 'test'
response = fake_gethostbyname(host=host)
assert response == '127.0.0.1'
|
import ldap
from ldap import filter as ldap_filter
from keystone.common.ldap import fakeldap
from keystone.common import logging
from keystone import exception
LOG = logging.getLogger(__name__)
LDAP_VALUES = {'TRUE': True, 'FALSE': False}
CONTROL_TREEDELETE = '1.2.840.113556.1.4.805'
LDAP_SCOPES = {'one': ldap.SCOPE_ONELEVEL,
'sub': ldap.SCOPE_SUBTREE}
LDAP_DEREF = {'always': ldap.DEREF_ALWAYS,
'default': None,
'finding': ldap.DEREF_FINDING,
'never': ldap.DEREF_NEVER,
'searching': ldap.DEREF_SEARCHING}
def py2ldap(val):
if isinstance(val, str):
return val
elif isinstance(val, bool):
return 'TRUE' if val else 'FALSE'
else:
return str(val)
def ldap2py(val):
try:
return LDAP_VALUES[val]
except KeyError:
pass
try:
return int(val)
except ValueError:
pass
return val
def safe_iter(attrs):
if attrs is None:
return
elif isinstance(attrs, list):
for e in attrs:
yield e
else:
yield attrs
def parse_deref(opt):
try:
return LDAP_DEREF[opt]
except KeyError:
raise ValueError((_('Invalid LDAP deref option: %s. Choose one of: ') %
opt) + ', '.join(LDAP_DEREF.keys()))
def ldap_scope(scope):
try:
return LDAP_SCOPES[scope]
except KeyError:
raise ValueError(_('Invalid LDAP scope: %s. Choose one of: ' % scope) +
', '.join(LDAP_SCOPES.keys()))
class BaseLdap(object):
DEFAULT_SUFFIX = "dc=example,dc=com"
DEFAULT_OU = None
DEFAULT_STRUCTURAL_CLASSES = None
DEFAULT_ID_ATTR = 'cn'
DEFAULT_OBJECTCLASS = None
DEFAULT_FILTER = None
DUMB_MEMBER_DN = 'cn=dumb,dc=nonexistent'
NotFound = None
notfound_arg = None
options_name = None
model = None
attribute_mapping = {}
attribute_ignore = []
tree_dn = None
def __init__(self, conf):
self.LDAP_URL = conf.ldap.url
self.LDAP_USER = conf.ldap.user
self.LDAP_PASSWORD = conf.ldap.password
self.LDAP_SCOPE = ldap_scope(conf.ldap.query_scope)
self.alias_dereferencing = parse_deref(conf.ldap.alias_dereferencing)
self.page_size = conf.ldap.page_size
if self.options_name is not None:
self.suffix = conf.ldap.suffix
if self.suffix is None:
self.suffix = self.DEFAULT_SUFFIX
dn = '%s_tree_dn' % self.options_name
self.tree_dn = (getattr(conf.ldap, dn)
or '%s,%s' % (self.DEFAULT_OU, self.suffix))
idatt = '%s_id_attribute' % self.options_name
self.id_attr = getattr(conf.ldap, idatt) or self.DEFAULT_ID_ATTR
objclass = '%s_objectclass' % self.options_name
self.object_class = (getattr(conf.ldap, objclass)
or self.DEFAULT_OBJECTCLASS)
filter = '%s_filter' % self.options_name
self.filter = getattr(conf.ldap, filter) or self.DEFAULT_FILTER
allow_create = '%s_allow_create' % self.options_name
self.allow_create = getattr(conf.ldap, allow_create)
allow_update = '%s_allow_update' % self.options_name
self.allow_update = getattr(conf.ldap, allow_update)
allow_delete = '%s_allow_delete' % self.options_name
self.allow_delete = getattr(conf.ldap, allow_delete)
self.structural_classes = self.DEFAULT_STRUCTURAL_CLASSES
if self.notfound_arg is None:
self.notfound_arg = self.options_name + '_id'
self.use_dumb_member = getattr(conf.ldap, 'use_dumb_member')
self.dumb_member = (getattr(conf.ldap, 'dumb_member') or
self.DUMB_MEMBER_DN)
self.subtree_delete_enabled = getattr(conf.ldap,
'allow_subtree_delete')
def _not_found(self, object_id):
if self.NotFound is None:
return exception.NotFound(target=object_id)
else:
return self.NotFound(**{self.notfound_arg: object_id})
def get_connection(self, user=None, password=None):
if self.LDAP_URL.startswith('fake://'):
conn = fakeldap.FakeLdap(self.LDAP_URL)
else:
conn = LdapWrapper(self.LDAP_URL,
self.page_size,
alias_dereferencing=self.alias_dereferencing)
if user is None:
user = self.LDAP_USER
if password is None:
password = self.LDAP_PASSWORD
# not all LDAP servers require authentication, so we don't bind
# if we don't have any user/pass
if user and password:
conn.simple_bind_s(user, password)
return conn
def _id_to_dn_string(self, id):
return '%s=%s,%s' % (self.id_attr,
ldap.dn.escape_dn_chars(str(id)),
self.tree_dn)
def _id_to_dn(self, id):
if self.LDAP_SCOPE == ldap.SCOPE_ONELEVEL:
return self._id_to_dn_string(id)
conn = self.get_connection()
search_result = conn.search_s(
self.tree_dn, self.LDAP_SCOPE,
'(&(%(id_attr)s=%(id)s)(objectclass=%(objclass)s))' %
{'id_attr': self.id_attr,
'id': ldap.filter.escape_filter_chars(str(id)),
'objclass': self.object_class})
if search_result:
dn, attrs = search_result[0]
return dn
else:
return self._id_to_dn_string(id)
@staticmethod
def _dn_to_id(dn):
return ldap.dn.str2dn(dn)[0][0][1]
def _ldap_res_to_model(self, res):
obj = self.model(id=self._dn_to_id(res[0]))
for k in obj.known_keys:
if k in self.attribute_ignore:
continue
try:
v = res[1][self.attribute_mapping.get(k, k)]
except KeyError:
pass
else:
try:
obj[k] = v[0]
except IndexError:
obj[k] = None
return obj
def affirm_unique(self, values):
if values.get('name') is not None:
try:
self.get_by_name(values['name'])
except exception.NotFound:
pass
else:
raise exception.Conflict(type=self.options_name,
details=_('Duplicate name, %s.') %
values['name'])
if values.get('id') is not None:
try:
self.get(values['id'])
except exception.NotFound:
pass
else:
raise exception.Conflict(type=self.options_name,
details=_('Duplicate ID, %s.') %
values['id'])
def create(self, values):
if not self.allow_create:
action = _('LDAP %s create') % self.options_name
raise exception.ForbiddenAction(action=action)
conn = self.get_connection()
object_classes = self.structural_classes + [self.object_class]
attrs = [('objectClass', object_classes)]
for k, v in values.iteritems():
if k == 'id' or k in self.attribute_ignore:
continue
if v is not None:
attr_type = self.attribute_mapping.get(k, k)
attrs.append((attr_type, [v]))
if 'groupOfNames' in object_classes and self.use_dumb_member:
attrs.append(('member', [self.dumb_member]))
conn.add_s(self._id_to_dn(values['id']), attrs)
return values
def _ldap_get(self, id, filter=None):
conn = self.get_connection()
query = ('(&(%(id_attr)s=%(id)s)'
'%(filter)s'
'(objectClass=%(object_class)s))'
% {'id_attr': self.id_attr,
'id': ldap.filter.escape_filter_chars(str(id)),
'filter': (filter or self.filter or ''),
'object_class': self.object_class})
try:
res = conn.search_s(self.tree_dn, self.LDAP_SCOPE, query,
self.attribute_mapping.values())
except ldap.NO_SUCH_OBJECT:
return None
try:
return res[0]
except IndexError:
return None
def _ldap_get_all(self, filter=None):
conn = self.get_connection()
query = '(&%s(objectClass=%s))' % (filter or self.filter or '',
self.object_class)
try:
return conn.search_s(self.tree_dn,
self.LDAP_SCOPE,
query,
self.attribute_mapping.values())
except ldap.NO_SUCH_OBJECT:
return []
def get(self, id, filter=None):
res = self._ldap_get(id, filter)
if res is None:
raise self._not_found(id)
else:
return self._ldap_res_to_model(res)
def get_by_name(self, name, filter=None):
query = ('(%s=%s)' % (self.attribute_mapping['name'],
ldap_filter.escape_filter_chars(name)))
res = self.get_all(query)
try:
return res[0]
except IndexError:
raise self._not_found(name)
def get_all(self, filter=None):
return [self._ldap_res_to_model(x)
for x in self._ldap_get_all(filter)]
def update(self, id, values, old_obj=None):
if not self.allow_update:
action = _('LDAP %s update') % self.options_name
raise exception.ForbiddenAction(action=action)
if old_obj is None:
old_obj = self.get(id)
modlist = []
for k, v in values.iteritems():
if k == 'id' or k in self.attribute_ignore:
continue
if v is None:
if old_obj[k] is not None:
modlist.append((ldap.MOD_DELETE,
self.attribute_mapping.get(k, k),
None))
elif old_obj[k] != v:
if old_obj[k] is None:
op = ldap.MOD_ADD
else:
op = ldap.MOD_REPLACE
modlist.append((op, self.attribute_mapping.get(k, k), [v]))
if modlist:
conn = self.get_connection()
try:
conn.modify_s(self._id_to_dn(id), modlist)
except ldap.NO_SUCH_OBJECT:
raise self._not_found(id)
def delete(self, id):
if not self.allow_delete:
action = _('LDAP %s delete') % self.options_name
raise exception.ForbiddenAction(action=action)
conn = self.get_connection()
try:
conn.delete_s(self._id_to_dn(id))
except ldap.NO_SUCH_OBJECT:
raise self._not_found(id)
def deleteTree(self, id):
conn = self.get_connection()
tree_delete_control = ldap.controls.LDAPControl(CONTROL_TREEDELETE,
0,
None)
try:
conn.delete_ext_s(self._id_to_dn(id),
serverctrls=[tree_delete_control])
except ldap.NO_SUCH_OBJECT:
raise self._not_found(id)
class LdapWrapper(object):
def __init__(self, url, page_size, alias_dereferencing=None):
LOG.debug(_("LDAP init: url=%s"), url)
self.conn = ldap.initialize(url)
if alias_dereferencing is not None:
self.conn.set_option(ldap.OPT_DEREF, alias_dereferencing)
self.page_size = page_size
def simple_bind_s(self, user, password):
LOG.debug(_("LDAP bind: dn=%s"), user)
return self.conn.simple_bind_s(user, password)
def add_s(self, dn, attrs):
ldap_attrs = [(kind, [py2ldap(x) for x in safe_iter(values)])
for kind, values in attrs]
if LOG.isEnabledFor(logging.DEBUG):
sane_attrs = [(kind, values
if kind != 'userPassword'
else ['****'])
for kind, values in ldap_attrs]
LOG.debug(_('LDAP add: dn=%s, attrs=%s'), dn, sane_attrs)
return self.conn.add_s(dn, ldap_attrs)
def search_s(self, dn, scope, query, attrlist=None):
if LOG.isEnabledFor(logging.DEBUG):
LOG.debug(_('LDAP search: dn=%s, scope=%s, query=%s, attrs=%s'),
dn,
scope,
query,
attrlist)
if self.page_size:
res = self.paged_search_s(dn, scope, query, attrlist)
else:
res = self.conn.search_s(dn, scope, query, attrlist)
o = []
for dn, attrs in res:
o.append((dn, dict((kind, [ldap2py(x) for x in values])
for kind, values in attrs.iteritems())))
return o
def paged_search_s(self, dn, scope, query, attrlist=None):
res = []
lc = ldap.controls.SimplePagedResultsControl(
controlType=ldap.LDAP_CONTROL_PAGE_OID,
criticality=True,
controlValue=(self.page_size, ''))
msgid = self.conn.search_ext(dn,
scope,
query,
attrlist,
serverctrls=[lc])
# Endless loop request pages on ldap server until it has no data
while True:
# Request to the ldap server a page with 'page_size' entries
rtype, rdata, rmsgid, serverctrls = self.conn.result3(msgid)
# Receive the data
res.extend(rdata)
pctrls = [c for c in serverctrls
if c.controlType == ldap.LDAP_CONTROL_PAGE_OID]
if pctrls:
# LDAP server supports pagination
est, cookie = pctrls[0].controlValue
if cookie:
# There is more data still on the server
# so we request another page
lc.controlValue = (self.page_size, cookie)
msgid = self.conn.search_ext(dn,
scope,
query,
attrlist,
serverctrls=[lc])
else:
# Exit condition no more data on server
break
else:
LOG.warning(_('LDAP Server does not support paging. '
'Disable paging in keystone.conf to '
'avoid this message.'))
self._disable_paging()
break
return res
def modify_s(self, dn, modlist):
ldap_modlist = [
(op, kind, (None if values is None
else [py2ldap(x) for x in safe_iter(values)]))
for op, kind, values in modlist]
if LOG.isEnabledFor(logging.DEBUG):
sane_modlist = [(op, kind, (values if kind != 'userPassword'
else ['****']))
for op, kind, values in ldap_modlist]
LOG.debug(_("LDAP modify: dn=%s, modlist=%s"), dn, sane_modlist)
return self.conn.modify_s(dn, ldap_modlist)
def delete_s(self, dn):
LOG.debug(_("LDAP delete: dn=%s"), dn)
return self.conn.delete_s(dn)
def delete_ext_s(self, dn, serverctrls):
LOG.debug(_("LDAP delete_ext: dn=%s, serverctrls=%s"), dn, serverctrls)
return self.conn.delete_ext_s(dn, serverctrls)
def _disable_paging(self):
# Disable the pagination from now on
self.page_size = 0
class EnabledEmuMixIn(BaseLdap):
"""Emulates boolean 'enabled' attribute if turned on.
Creates groupOfNames holding all enabled objects of this class, all missing
objects are considered disabled.
Options:
* $name_enabled_emulation - boolean, on/off
* $name_enabled_emulation_dn - DN of that groupOfNames, default is
cn=enabled_$name,$tree_dn
Where $name is self.options_name ('user' or 'tenant'), $tree_dn is
self.tree_dn.
"""
def __init__(self, conf):
super(EnabledEmuMixIn, self).__init__(conf)
enabled_emulation = '%s_enabled_emulation' % self.options_name
self.enabled_emulation = getattr(conf.ldap, enabled_emulation)
enabled_emulation_dn = '%s_enabled_emulation_dn' % self.options_name
self.enabled_emulation_dn = getattr(conf.ldap, enabled_emulation_dn)
if not self.enabled_emulation_dn:
self.enabled_emulation_dn = ('cn=enabled_%ss,%s' %
(self.options_name, self.tree_dn))
def _get_enabled(self, object_id):
conn = self.get_connection()
dn = self._id_to_dn(object_id)
query = '(member=%s)' % dn
try:
enabled_value = conn.search_s(self.enabled_emulation_dn,
ldap.SCOPE_BASE,
query)
except ldap.NO_SUCH_OBJECT:
return False
else:
return bool(enabled_value)
def _add_enabled(self, object_id):
if not self._get_enabled(object_id):
conn = self.get_connection()
modlist = [(ldap.MOD_ADD,
'member',
[self._id_to_dn(object_id)])]
try:
conn.modify_s(self.enabled_emulation_dn, modlist)
except ldap.NO_SUCH_OBJECT:
attr_list = [('objectClass', ['groupOfNames']),
('member',
[self._id_to_dn(object_id)])]
if self.use_dumb_member:
attr_list[1][1].append(self.dumb_member)
conn.add_s(self.enabled_emulation_dn, attr_list)
def _remove_enabled(self, object_id):
conn = self.get_connection()
modlist = [(ldap.MOD_DELETE,
'member',
[self._id_to_dn(object_id)])]
try:
conn.modify_s(self.enabled_emulation_dn, modlist)
except (ldap.NO_SUCH_OBJECT, ldap.NO_SUCH_ATTRIBUTE):
pass
def create(self, values):
if self.enabled_emulation:
enabled_value = values.pop('enabled', True)
ref = super(EnabledEmuMixIn, self).create(values)
if 'enabled' not in self.attribute_ignore:
if enabled_value:
self._add_enabled(ref['id'])
ref['enabled'] = enabled_value
return ref
else:
return super(EnabledEmuMixIn, self).create(values)
def get(self, object_id, filter=None):
ref = super(EnabledEmuMixIn, self).get(object_id, filter)
if 'enabled' not in self.attribute_ignore and self.enabled_emulation:
ref['enabled'] = self._get_enabled(object_id)
return ref
def get_all(self, filter=None):
if 'enabled' not in self.attribute_ignore and self.enabled_emulation:
# had to copy BaseLdap.get_all here to filter by DN
tenant_list = [self._ldap_res_to_model(x)
for x in self._ldap_get_all(filter)
if x[0] != self.enabled_emulation_dn]
for tenant_ref in tenant_list:
tenant_ref['enabled'] = self._get_enabled(tenant_ref['id'])
return tenant_list
else:
return super(EnabledEmuMixIn, self).get_all(filter)
def update(self, object_id, values, old_obj=None):
if 'enabled' not in self.attribute_ignore and self.enabled_emulation:
data = values.copy()
enabled_value = data.pop('enabled', None)
super(EnabledEmuMixIn, self).update(object_id, data, old_obj)
if enabled_value is not None:
if enabled_value:
self._add_enabled(object_id)
else:
self._remove_enabled(object_id)
else:
super(EnabledEmuMixIn, self).update(object_id, values, old_obj)
def delete(self, object_id):
if self.enabled_emulation:
self._remove_enabled(object_id)
super(EnabledEmuMixIn, self).delete(object_id)
|
__author__ = 'dominiczippilli'
def foo():
pass
|
"""Loop utilities."""
import jax
import jax.numpy as jnp
def _while_loop_scan(cond_fun, body_fun, init_val, max_iter):
"""Scan-based implementation (jit ok, reverse-mode autodiff ok)."""
def _iter(val):
next_val = body_fun(val)
next_cond = cond_fun(next_val)
return next_val, next_cond
def _fun(tup, it):
val, cond = tup
# When cond is met, we start doing no-ops.
return jax.lax.cond(cond, _iter, lambda x: (x, False), val), it
init = (init_val, cond_fun(init_val))
return jax.lax.scan(_fun, init, None, length=max_iter)[0][0]
def _while_loop_python(cond_fun, body_fun, init_val, maxiter):
"""Python based implementation (no jit, reverse-mode autodiff ok)."""
val = init_val
for _ in range(maxiter):
cond = cond_fun(val)
if not cond:
# When condition is met, break (not jittable).
break
val = body_fun(val)
return val
def _while_loop_lax(cond_fun, body_fun, init_val, maxiter):
"""lax.while_loop based implementation (jit by default, no reverse-mode)."""
def _cond_fun(_val):
it, val = _val
return jnp.logical_and(cond_fun(val), it <= maxiter - 1)
def _body_fun(_val):
it, val = _val
val = body_fun(val)
return it+1, val
return jax.lax.while_loop(_cond_fun, _body_fun, (0, init_val))[1]
def while_loop(cond_fun, body_fun, init_val, maxiter, unroll=False, jit=False):
"""A while loop with a bounded number of iterations."""
if unroll:
if jit:
fun = _while_loop_scan
else:
fun = _while_loop_python
else:
if jit:
fun = _while_loop_lax
else:
raise ValueError("unroll=False and jit=False cannot be used together")
if jit and fun is not _while_loop_lax:
# jit of a lax while_loop is redundant, and this jit would only
# constrain maxiter to be static where it is not required.
fun = jax.jit(fun, static_argnums=(0, 1, 3))
return fun(cond_fun, body_fun, init_val, maxiter)
|
from __future__ import unicode_literals
from django.apps import AppConfig
class SensorConfig(AppConfig):
name = 'sensor'
|
"""
WSGI config for BRB project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "brb.settings")
application = get_wsgi_application()
|
"""The data range file system implementation."""
from dfvfs.lib import definitions
from dfvfs.lib import errors
from dfvfs.path import data_range_path_spec
from dfvfs.vfs import data_range_file_entry
from dfvfs.vfs import root_only_file_system
class DataRangeFileSystem(root_only_file_system.RootOnlyFileSystem):
"""Class that implements a compresses stream file system object."""
TYPE_INDICATOR = definitions.TYPE_INDICATOR_DATA_RANGE
def __init__(self, resolver_context):
"""Initializes a file system object.
Args:
resolver_context: the resolver context (instance of resolver.Context).
"""
super(DataRangeFileSystem, self).__init__(resolver_context)
self._range_offset = None
self._range_size = None
def _Close(self):
"""Closes the file system object.
Raises:
IOError: if the close failed.
"""
self._range_offset = None
self._range_size = None
def _Open(self, path_spec, mode='rb'):
"""Opens the file system object defined by path specification.
Args:
path_spec: a path specification (instance of PathSpec).
mode: optional file access mode. The default is 'rb' read-only binary.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the file system object could not be opened.
PathSpecError: if the path specification is incorrect.
ValueError: if the path specification is invalid.
"""
if not path_spec.HasParent():
raise errors.PathSpecError(
u'Unsupported path specification without parent.')
range_offset = getattr(path_spec, u'range_offset', None)
if range_offset is None:
raise errors.PathSpecError(
u'Unsupported path specification without encoding method.')
range_size = getattr(path_spec, u'range_size', None)
if range_size is None:
raise errors.PathSpecError(
u'Unsupported path specification without encoding method.')
self._range_offset = range_offset
self._range_size = range_size
def GetFileEntryByPathSpec(self, path_spec):
"""Retrieves a file entry for a path specification.
Args:
path_spec: a path specification (instance of PathSpec).
Returns:
A file entry (instance of vfs.FileEntry) or None.
"""
return data_range_file_entry.DataRangeFileEntry(
self._resolver_context, self, path_spec, is_root=True, is_virtual=True)
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
A file entry (instance of vfs.FileEntry) or None.
"""
path_spec = data_range_path_spec.DataRangePathSpec(
range_offset=self._range_offset,
range_size=self._range_size,
parent=self._path_spec.parent)
return self.GetFileEntryByPathSpec(path_spec)
|
"""
PyCOMPSs Testbench
========================
"""
import unittest
from modules.testNoReturn import testNoReturn
from modules.testNoReturnClasses import testNoReturnClasses
def main():
suite = unittest.TestLoader().loadTestsFromTestCase(testNoReturn)
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(testNoReturnClasses))
unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == "__main__":
main()
|
import logging
from six import moves
from tempest_lib import exceptions as lib_exc
from testtools import matchers
from tempest.api.messaging import base
from tempest.common.utils import data_utils
from tempest import test
LOG = logging.getLogger(__name__)
class TestQueues(base.BaseMessagingTest):
@test.attr(type='smoke')
def test_create_delete_queue(self):
# Create & Delete Queue
queue_name = data_utils.rand_name('test-')
_, body = self.create_queue(queue_name)
self.addCleanup(self.client.delete_queue, queue_name)
# NOTE(gmann): create_queue returns response status code as 201
# so specifically checking the expected empty response body as
# this is not going to be checked in response_checker().
self.assertEqual('', body)
self.delete_queue(queue_name)
self.assertRaises(lib_exc.NotFound,
self.client.get_queue,
queue_name)
class TestManageQueue(base.BaseMessagingTest):
@classmethod
def resource_setup(cls):
super(TestManageQueue, cls).resource_setup()
cls.queues = list()
for _ in moves.xrange(5):
queue_name = data_utils.rand_name('Queues-Test')
cls.queues.append(queue_name)
# Create Queue
cls.client.create_queue(queue_name)
@test.attr(type='smoke')
def test_check_queue_existence(self):
# Checking Queue Existence
for queue_name in self.queues:
self.check_queue_exists(queue_name)
@test.attr(type='smoke')
def test_check_queue_head(self):
# Checking Queue Existence by calling HEAD
for queue_name in self.queues:
self.check_queue_exists_head(queue_name)
@test.attr(type='smoke')
def test_list_queues(self):
# Listing queues
_, body = self.list_queues()
self.assertEqual(len(body['queues']), len(self.queues))
for item in body['queues']:
self.assertIn(item['name'], self.queues)
@test.attr(type='smoke')
def test_get_queue_stats(self):
# Retrieve random queue
queue_name = self.queues[data_utils.rand_int_id(0,
len(self.queues) - 1)]
# Get Queue Stats for a newly created Queue
_, body = self.get_queue_stats(queue_name)
msgs = body['messages']
for element in ('free', 'claimed', 'total'):
self.assertEqual(0, msgs[element])
for element in ('oldest', 'newest'):
self.assertNotIn(element, msgs)
@test.attr(type='smoke')
def test_set_and_get_queue_metadata(self):
# Retrieve random queue
queue_name = self.queues[data_utils.rand_int_id(0,
len(self.queues) - 1)]
# Check the Queue has no metadata
_, body = self.get_queue_metadata(queue_name)
self.assertThat(body, matchers.HasLength(0))
# Create metadata
key3 = [0, 1, 2, 3, 4]
key2 = data_utils.rand_name('value')
req_body1 = dict()
req_body1[data_utils.rand_name('key3')] = key3
req_body1[data_utils.rand_name('key2')] = key2
req_body = dict()
req_body[data_utils.rand_name('key1')] = req_body1
# Set Queue Metadata
self.set_queue_metadata(queue_name, req_body)
# Get Queue Metadata
_, body = self.get_queue_metadata(queue_name)
self.assertThat(body, matchers.Equals(req_body))
@classmethod
def resource_cleanup(cls):
for queue_name in cls.queues:
cls.client.delete_queue(queue_name)
super(TestManageQueue, cls).resource_cleanup()
|
import pytest, requests, json
from kubernetes.client.rest import ApiException
from suite.resources_utils import (
wait_before_test,
replace_configmap_from_yaml,
get_last_reload_time,
get_test_file_name,
write_to_json,
)
from suite.custom_resources_utils import (
read_custom_resource,
)
from suite.vs_vsr_resources_utils import (
delete_virtual_server,
create_virtual_server_from_yaml,
patch_virtual_server_from_yaml,
)
from suite.policy_resources_utils import (
create_policy_from_yaml,
delete_policy,
read_policy,
)
from settings import TEST_DATA, DEPLOYMENTS
std_cm_src = f"{DEPLOYMENTS}/common/nginx-config.yaml"
test_cm_src = f"{TEST_DATA}/access-control/configmap/nginx-config.yaml"
std_vs_src = f"{TEST_DATA}/access-control/standard/virtual-server.yaml"
deny_pol_src = f"{TEST_DATA}/access-control/policies/access-control-policy-deny.yaml"
deny_vs_src = f"{TEST_DATA}/access-control/spec/virtual-server-deny.yaml"
allow_pol_src = f"{TEST_DATA}/access-control/policies/access-control-policy-allow.yaml"
allow_vs_src = f"{TEST_DATA}/access-control/spec/virtual-server-allow.yaml"
override_vs_src = f"{TEST_DATA}/access-control/spec/virtual-server-override.yaml"
invalid_pol_src = f"{TEST_DATA}/access-control/policies/access-control-policy-invalid.yaml"
invalid_vs_src = f"{TEST_DATA}/access-control/spec/virtual-server-invalid.yaml"
allow_vs_src_route = f"{TEST_DATA}/access-control/route-subroute/virtual-server-allow-route.yaml"
deny_vs_src_route = f"{TEST_DATA}/access-control/route-subroute/virtual-server-deny-route.yaml"
invalid_vs_src_route = (
f"{TEST_DATA}/access-control/route-subroute/virtual-server-invalid-route.yaml"
)
override_vs_src_route = (
f"{TEST_DATA}/access-control/route-subroute/virtual-server-override-route.yaml"
)
override_vs_spec_route_src = (
f"{TEST_DATA}/access-control/route-subroute/virtual-server-override-spec-route.yaml"
)
reload_times = {}
@pytest.fixture(scope="class")
def config_setup(request, kube_apis, ingress_controller_prerequisites) -> None:
"""
Replace configmap to add "set-real-ip-from"
:param request: pytest fixture
:param kube_apis: client apis
:param ingress_controller_prerequisites: IC pre-requisites
"""
print(f"------------- Replace ConfigMap --------------")
replace_configmap_from_yaml(
kube_apis.v1,
ingress_controller_prerequisites.config_map["metadata"]["name"],
ingress_controller_prerequisites.namespace,
test_cm_src,
)
def fin():
print(f"------------- Restore ConfigMap --------------")
replace_configmap_from_yaml(
kube_apis.v1,
ingress_controller_prerequisites.config_map["metadata"]["name"],
ingress_controller_prerequisites.namespace,
std_cm_src,
)
write_to_json(
f"reload-{get_test_file_name(request.node.fspath)}.json",
reload_times
)
request.addfinalizer(fin)
@pytest.mark.policies
@pytest.mark.parametrize(
"crd_ingress_controller, virtual_server_setup",
[
(
{
"type": "complete",
"extra_args": [
f"-enable-custom-resources",
f"-enable-leader-election=false",
f"-enable-prometheus-metrics",
],
},
{
"example": "access-control",
"app_type": "simple",
},
)
],
indirect=True,
)
class TestAccessControlPoliciesVs:
def restore_default_vs(self, kube_apis, virtual_server_setup) -> None:
"""
Restore VirtualServer without policy spec
"""
delete_virtual_server(
kube_apis.custom_objects, virtual_server_setup.vs_name, virtual_server_setup.namespace
)
create_virtual_server_from_yaml(
kube_apis.custom_objects, std_vs_src, virtual_server_setup.namespace
)
wait_before_test()
@pytest.mark.parametrize("src", [deny_vs_src, deny_vs_src_route])
@pytest.mark.smoke
def test_deny_policy(
self,
request,
kube_apis,
crd_ingress_controller,
virtual_server_setup,
test_namespace,
config_setup,
src,
):
"""
Test if ip (10.0.0.1) block-listing is working: default(no policy) -> deny
"""
resp = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.1"},
)
print(f"Response: {resp.status_code}\n{resp.text}")
assert resp.status_code == 200
print(f"Create deny policy")
pol_name = create_policy_from_yaml(kube_apis.custom_objects, deny_pol_src, test_namespace)
print(f"Patch vs with policy: {src}")
patch_virtual_server_from_yaml(
kube_apis.custom_objects,
virtual_server_setup.vs_name,
src,
virtual_server_setup.namespace,
)
wait_before_test()
policy_info = read_custom_resource(
kube_apis.custom_objects, test_namespace, "policies", pol_name
)
print(f"\nUse IP listed in deny block: 10.0.0.1")
resp1 = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.1"},
)
print(f"Response: {resp1.status_code}\n{resp1.text}")
print(f"\nUse IP not listed in deny block: 10.0.0.2")
resp2 = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.2"},
)
print(f"Response: {resp2.status_code}\n{resp2.text}")
reload_ms = get_last_reload_time(virtual_server_setup.metrics_url, "nginx")
print(f"last reload duration: {reload_ms} ms")
reload_times[f"{request.node.name}"] = f"last reload duration: {reload_ms} ms"
delete_policy(kube_apis.custom_objects, pol_name, test_namespace)
self.restore_default_vs(kube_apis, virtual_server_setup)
assert (
policy_info["status"]
and policy_info["status"]["reason"] == "AddedOrUpdated"
and policy_info["status"]["state"] == "Valid"
)
assert (
resp1.status_code == 403
and "403 Forbidden" in resp1.text
and resp2.status_code == 200
and "Server address:" in resp2.text
)
@pytest.mark.parametrize("src", [allow_vs_src, allow_vs_src_route])
@pytest.mark.smoke
def test_allow_policy(
self,
kube_apis,
crd_ingress_controller,
virtual_server_setup,
test_namespace,
config_setup,
src,
):
"""
Test if ip (10.0.0.1) allow-listing is working: default(no policy) -> allow
"""
resp = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.1"},
)
print(f"Response: {resp.status_code}\n{resp.text}")
assert resp.status_code == 200
print(f"Create allow policy")
pol_name = create_policy_from_yaml(kube_apis.custom_objects, allow_pol_src, test_namespace)
patch_virtual_server_from_yaml(
kube_apis.custom_objects,
virtual_server_setup.vs_name,
src,
virtual_server_setup.namespace,
)
wait_before_test()
policy_info = read_custom_resource(
kube_apis.custom_objects, test_namespace, "policies", pol_name
)
print(f"\nUse IP listed in allow block: 10.0.0.1")
resp1 = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.1"},
)
print(f"\nUse IP listed not in allow block: 10.0.0.2")
print(f"Response: {resp1.status_code}\n{resp1.text}")
resp2 = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.2"},
)
print(f"Response: {resp2.status_code}\n{resp2.text}")
delete_policy(kube_apis.custom_objects, pol_name, test_namespace)
self.restore_default_vs(kube_apis, virtual_server_setup)
assert (
policy_info["status"]
and policy_info["status"]["reason"] == "AddedOrUpdated"
and policy_info["status"]["state"] == "Valid"
)
assert (
resp1.status_code == 200
and "Server address:" in resp1.text
and resp2.status_code == 403
and "403 Forbidden" in resp2.text
)
@pytest.mark.parametrize("src", [override_vs_src, override_vs_src_route])
def test_override_policy(
self,
kube_apis,
crd_ingress_controller,
virtual_server_setup,
test_namespace,
config_setup,
src,
):
"""
Test if ip allow-listing overrides block-listing: default(no policy) -> deny and allow
"""
resp = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.1"},
)
print(f"Response: {resp.status_code}\n{resp.text}")
assert resp.status_code == 200
print(f"Create deny policy")
deny_pol_name = create_policy_from_yaml(
kube_apis.custom_objects, deny_pol_src, test_namespace
)
print(f"Create allow policy")
allow_pol_name = create_policy_from_yaml(
kube_apis.custom_objects, allow_pol_src, test_namespace
)
patch_virtual_server_from_yaml(
kube_apis.custom_objects,
virtual_server_setup.vs_name,
src,
virtual_server_setup.namespace,
)
wait_before_test()
print(f"Use IP listed in both deny and allow policies: 10.0.0.1")
resp = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.1"},
)
print(f"Response: {resp.status_code}\n{resp.text}")
delete_policy(kube_apis.custom_objects, deny_pol_name, test_namespace)
delete_policy(kube_apis.custom_objects, allow_pol_name, test_namespace)
self.restore_default_vs(kube_apis, virtual_server_setup)
assert resp.status_code == 200 and "Server address:" in resp.text
@pytest.mark.parametrize("src", [invalid_vs_src, invalid_vs_src_route])
def test_invalid_policy(
self,
kube_apis,
crd_ingress_controller,
virtual_server_setup,
test_namespace,
config_setup,
src,
):
"""
Test if invalid policy is applied then response is 500
"""
resp = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.1"},
)
print(f"Response: {resp.status_code}\n{resp.text}")
assert resp.status_code == 200
print(f"Create invalid policy")
invalid_pol_name = create_policy_from_yaml(
kube_apis.custom_objects, invalid_pol_src, test_namespace
)
patch_virtual_server_from_yaml(
kube_apis.custom_objects,
virtual_server_setup.vs_name,
src,
virtual_server_setup.namespace,
)
wait_before_test()
resp = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.1"},
)
print(f"Response: {resp.status_code}\n{resp.text}")
vs_info = read_custom_resource(
kube_apis.custom_objects,
virtual_server_setup.namespace,
"virtualservers",
virtual_server_setup.vs_name,
)
policy_info = read_custom_resource(
kube_apis.custom_objects, test_namespace, "policies", invalid_pol_name
)
delete_policy(kube_apis.custom_objects, invalid_pol_name, test_namespace)
self.restore_default_vs(kube_apis, virtual_server_setup)
assert resp.status_code == 500 and "500 Internal Server Error" in resp.text
assert (
policy_info["status"]
and policy_info["status"]["reason"] == "Rejected"
and policy_info["status"]["state"] == "Invalid"
)
assert (
vs_info["status"]["state"] == "Warning"
and vs_info["status"]["reason"] == "AddedOrUpdatedWithWarning"
)
@pytest.mark.parametrize("src", [deny_vs_src, deny_vs_src_route])
def test_deleted_policy(
self,
kube_apis,
crd_ingress_controller,
virtual_server_setup,
test_namespace,
config_setup,
src,
):
"""
Test if valid policy is deleted then response is 500
"""
resp = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.1"},
)
print(f"Response: {resp.status_code}\n{resp.text}")
assert resp.status_code == 200
print(f"Create deny policy")
pol_name = create_policy_from_yaml(kube_apis.custom_objects, deny_pol_src, test_namespace)
patch_virtual_server_from_yaml(
kube_apis.custom_objects,
virtual_server_setup.vs_name,
src,
virtual_server_setup.namespace,
)
wait_before_test()
vs_info = read_custom_resource(
kube_apis.custom_objects,
virtual_server_setup.namespace,
"virtualservers",
virtual_server_setup.vs_name,
)
assert vs_info["status"]["state"] == "Valid"
delete_policy(kube_apis.custom_objects, pol_name, test_namespace)
wait_before_test()
resp = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.1"},
)
print(f"Response: {resp.status_code}\n{resp.text}")
vs_info = read_custom_resource(
kube_apis.custom_objects,
virtual_server_setup.namespace,
"virtualservers",
virtual_server_setup.vs_name,
)
self.restore_default_vs(kube_apis, virtual_server_setup)
assert resp.status_code == 500 and "500 Internal Server Error" in resp.text
assert (
vs_info["status"]["state"] == "Warning"
and vs_info["status"]["reason"] == "AddedOrUpdatedWithWarning"
)
def test_route_override_spec(
self,
kube_apis,
crd_ingress_controller,
virtual_server_setup,
test_namespace,
config_setup,
):
"""
Test allow policy specified under routes overrides block in spec
"""
resp = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.1"},
)
print(f"Response: {resp.status_code}\n{resp.text}")
assert resp.status_code == 200
print(f"Create deny policy")
deny_pol_name = create_policy_from_yaml(
kube_apis.custom_objects, deny_pol_src, test_namespace
)
print(f"Create allow policy")
allow_pol_name = create_policy_from_yaml(
kube_apis.custom_objects, allow_pol_src, test_namespace
)
patch_virtual_server_from_yaml(
kube_apis.custom_objects,
virtual_server_setup.vs_name,
override_vs_spec_route_src,
virtual_server_setup.namespace,
)
wait_before_test()
print(f"Use IP listed in both deny and allow policies: 10.0.0.1")
resp = requests.get(
virtual_server_setup.backend_1_url,
headers={"host": virtual_server_setup.vs_host, "X-Real-IP": "10.0.0.1"},
)
print(f"Response: {resp.status_code}\n{resp.text}")
self.restore_default_vs(kube_apis, virtual_server_setup)
delete_policy(kube_apis.custom_objects, deny_pol_name, test_namespace)
delete_policy(kube_apis.custom_objects, allow_pol_name, test_namespace)
assert resp.status_code == 200 and "Server address:" in resp.text
|
from __future__ import unicode_literals
from __future__ import absolute_import
"""
pypuppetdb PuppetDB API library
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pypuppetdb is a library to work with PuppetDB's REST API. It provides a way
to query PuppetDB and a set of additional methods and objects to make working
with PuppetDB's API and the responses easier:
>>> from pypuppetdb import connect
>>> db = connect()
>>> nodes = db.nodes()
>>> print(nodes)
<generator object 'nodes'>
>>> for node in nodes:
>>> print(node)
host1
host2
...
This will return a generator object yielding Node objects for every returned
node from PuppetDB.
To query a single node the singular db.node() can be used:
>>> node = db.node('hostname')
>>> print(node)
hostname
The Node objects are a bit more special in that they can query for facts and
resources themselves. Using those methods from a node object will automatically
add a query to the request scoping the request to the node.
>>> node = db.node('hostname')
>>> print node.fact('osfamily')
osfamily/hostname
We can also query for facts:
>>> facts = db.facts('osfamily')
>>> print(facts)
<generator object 'facts')
>>> for fact in facts:
>>> print(fact)
osfamily/host1
osfamily/host2
That querries PuppetDB for the 'osfamily' fact and will yield Fact objects,
one per node this fact is found on.
>>> resources = db.resources('file')
Will return a generator object containing all file resources you're managing
across your infrastructure. This is probably a bad idea if you have a big
number of nodes as the response will be huge.
"""
import logging
from pypuppetdb.api import v2
from pypuppetdb.api import v3
from pypuppetdb.api import v4
from pypuppetdb.errors import UnsupportedVersionError
try: # Python 2.7+
from logging import NullHandler
except ImportError: # pragma: notest
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
def connect(api_version=3, host='localhost', port=8080, ssl_verify=False,
ssl_key=None, ssl_cert=None, timeout=10, protocol=None,
url_path='/', username=None, password=None):
"""Connect with PuppetDB. This will return an object allowing you
to query the API through its methods.
:param api_version: Version of the API we're initialising.
:type api_version: :obj:`int`
:param host: (optional) Hostname or IP of PuppetDB.
:type host: :obj:`string`
:param port: (optional) Port on which to talk to PuppetDB.
:type port: :obj:`int`
:param ssl_verify: (optional) Verify PuppetDB server certificate.
:type ssl_verify: :obj:`bool` or :obj:`string` True, False or filesystem \
path to CA certificate.
:param ssl_key: (optional) Path to our client secret key.
:type ssl_key: :obj:`None` or :obj:`string` representing a filesystem\
path.
:param ssl_cert: (optional) Path to our client certificate.
:type ssl_cert: :obj:`None` or :obj:`string` representing a filesystem\
path.
:param timeout: (optional) Number of seconds to wait for a response.
:type timeout: :obj:`int`
:param protocol: (optional) Explicitly specify the protocol to be used
(especially handy when using HTTPS with ssl_verify=False and
without certs)
:type protocol: :obj:`None` or :obj:`string`
:param url_path: (optional) The URL path where PuppetDB is served
(if not at the root / path)
:type url_path: :obj:`None` or :obj:`string`
:param username: (optional) The username to use for HTTP basic
authentication
:type username: :obj:`None` or :obj:`string`
:param password: (optional) The password to use for HTTP basic
authentication
:type password: :obj:`None` or :obj:`string`
:raises: :class:`~pypuppetdb.errors.UnsupportedVersionError`
"""
if api_version == 4:
return v4.API(host=host, port=port,
timeout=timeout, ssl_verify=ssl_verify, ssl_key=ssl_key,
ssl_cert=ssl_cert, protocol=protocol, url_path=url_path,
username=username, password=password)
if api_version == 3:
return v3.API(host=host, port=port,
timeout=timeout, ssl_verify=ssl_verify, ssl_key=ssl_key,
ssl_cert=ssl_cert, protocol=protocol, url_path=url_path,
username=username, password=password)
if api_version == 2:
return v2.API(host=host, port=port,
timeout=timeout, ssl_verify=ssl_verify, ssl_key=ssl_key,
ssl_cert=ssl_cert, protocol=protocol, url_path=url_path,
username=username, password=password)
else:
raise UnsupportedVersionError
|
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.api.v2 import resource_helper
from oslo_log import log as logging
LOG = logging.getLogger(__name__)
def _validate_list_of_port_dicts(values, data):
if not isinstance(values, list):
msg = _("'%s' is not a list") % data
return msg
for item in values:
msg = _validate_port_dict(item)
if msg:
return msg
items = [tuple(entry.items()) for entry in values]
if len(items) != len(set(items)):
msg = _("Duplicate items in the list: '%s'") % values
return msg
def _validate_port_dict(values):
if not isinstance(values, dict):
msg = _("%s is not a valid dictionary") % values
LOG.debug(msg)
return msg
port_id = values.get('port_id')
fixed_ip = values.get('fixed_ip_address')
msg = attr._validate_uuid(port_id)
if msg:
return msg
if fixed_ip is None:
return
msg = attr._validate_ip_address(fixed_ip)
if msg:
return msg
attr.validators['type:validate_list_of_port_dicts'] = (
_validate_list_of_port_dicts
)
RESOURCE_NAME = "scalingip"
RESOURCE_COLLECTION = RESOURCE_NAME + "s"
RESOURCE_ATTRIBUTE_MAP = {
RESOURCE_COLLECTION: {
'id': {
'allow_post': False, 'allow_put': False,
'validate': {'type:uuid': None},
'is_visible': True,
'primary_key': True
},
"scaling_ip_address": {
'allow_post': True, 'allow_put': False,
'validate': {'type:ip_address_or_none': None},
'is_visible': True, 'default': None,
'enforce_policy': True
},
"tenant_id": {
'allow_post': True, 'allow_put': False,
'required_by_policy': True,
'validate': {'type:string': attr.TENANT_ID_MAX_LEN},
'is_visible': True
},
"scaling_network_id": {
'allow_post': True, 'allow_put': False,
'validate': {'type:uuid': None},
'is_visible': True
},
"ports": {
'allow_post': True, 'allow_put': True,
'validate': {
'type:validate_list_of_port_dicts': None
},
'is_visible': True,
'required_by_policy': True
}
}
}
class Scalingip(extensions.ExtensionDescriptor):
@classmethod
def get_name(cls):
return RESOURCE_NAME
@classmethod
def get_alias(cls):
return RESOURCE_NAME
@classmethod
def get_description(cls):
return "Scaling IPs"
@classmethod
def get_namespace(cls):
return ("http://docs.openstack.org/network/ext/"
"networks_quark/api/v2.0")
@classmethod
def get_updated(cls):
return "2016-01-20T19:00:00-00:00"
@classmethod
def get_resources(cls):
"""Returns Ext Resources."""
plural_mappings = resource_helper.build_plural_mappings(
{}, RESOURCE_ATTRIBUTE_MAP)
attr.PLURALS.update(plural_mappings)
return resource_helper.build_resource_info(plural_mappings,
RESOURCE_ATTRIBUTE_MAP,
None,
register_quota=True)
def get_extended_resources(self, version):
if version == "2.0":
return RESOURCE_ATTRIBUTE_MAP
else:
return {}
|
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import logging
import re
import time
from collections import namedtuple
logger = logging.getLogger()
AlertUri = namedtuple('AlertUri', 'uri is_ssl_enabled')
class BaseAlert(object):
# will force a kinit even if klist says there are valid tickets (4 hour default)
_DEFAULT_KINIT_TIMEOUT = 14400000
RESULT_OK = "OK"
RESULT_WARNING = "WARNING"
RESULT_CRITICAL = "CRITICAL"
RESULT_UNKNOWN = "UNKNOWN"
RESULT_SKIPPED = "SKIPPED"
HA_NAMESERVICE_PARAM = "{{ha-nameservice}}"
HA_ALIAS_PARAM = "{{alias}}"
def __init__(self, alert_meta, alert_source_meta, config):
self.alert_meta = alert_meta
self.alert_source_meta = alert_source_meta
self.cluster_name = ''
self.host_name = ''
self.public_host_name = ''
self.config = config
def interval(self):
""" gets the defined interval this check should run """
if not self.alert_meta.has_key('interval'):
return 1
else:
interval = self.alert_meta['interval']
return 1 if interval < 1 else interval
def is_enabled(self):
"""
gets whether the definition is enabled
"""
return self.alert_meta['enabled']
def get_name(self):
"""
gets the unique name of the alert definition
"""
return self.alert_meta['name']
def get_uuid(self):
"""
gets the unique has of the alert definition
"""
return self.alert_meta['uuid']
def set_helpers(self, collector, cluster_configuration):
"""
sets helper objects for alerts without having to use them in a constructor
"""
self.collector = collector
self.cluster_configuration = cluster_configuration
def set_cluster(self, cluster_name, host_name, public_host_name = None):
""" sets cluster information for the alert """
self.cluster_name = cluster_name
self.host_name = host_name
self.public_host_name = host_name
if public_host_name:
self.public_host_name = public_host_name
def _get_alert_meta_value_safely(self, meta_key):
"""
safe way to get a value when outputting result json. will not throw an exception
"""
if self.alert_meta.has_key(meta_key):
return self.alert_meta[meta_key]
else:
return None
def collect(self):
""" method used for collection. defers to _collect() """
res = (BaseAlert.RESULT_UNKNOWN, [])
res_base_text = None
try:
res = self._collect()
result_state = res[0]
reporting_state = result_state.lower()
# it's possible that the alert definition doesn't have reporting; safely
# check for it and fallback to default text if it doesn't exist
if ('reporting' in self.alert_source_meta) and \
(reporting_state in self.alert_source_meta['reporting']) and \
('text' in self.alert_source_meta['reporting'][reporting_state]):
res_base_text = self.alert_source_meta['reporting'][reporting_state]['text']
if res_base_text is None:
res_base_text = self._get_reporting_text(result_state)
except Exception as exception:
message = "[Alert][{0}] Unable to execute alert. {1}".format(
self.get_name(), str(exception))
# print the exception if in DEBUG, otherwise just log the warning
if logger.isEnabledFor(logging.DEBUG):
logger.exception(message)
else:
logger.warning(message)
res = (BaseAlert.RESULT_UNKNOWN, [str(exception)])
res_base_text = "{0}"
if logger.isEnabledFor(logging.DEBUG):
logger.debug("[Alert][{0}] result = {1}".format(self.get_name(), str(res)))
data = {}
data['name'] = self._get_alert_meta_value_safely('name')
data['label'] = self._get_alert_meta_value_safely('label')
data['uuid'] = self._get_alert_meta_value_safely('uuid')
data['cluster'] = self.cluster_name
data['service'] = self._get_alert_meta_value_safely('serviceName')
data['component'] = self._get_alert_meta_value_safely('componentName')
data['timestamp'] = long(time.time() * 1000)
data['enabled'] = self._get_alert_meta_value_safely('enabled')
try:
data['state'] = res[0]
# * is the splat operator, which flattens a collection into positional arguments
# flatten the array and then try formatting it
try:
data['text'] = res_base_text.format(*res[1])
except ValueError, value_error:
logger.warn("[Alert][{0}] - {1}".format(self.get_name(), str(value_error)))
# if there is a ValueError, it's probably because the text doesn't match the type of
# positional arguemtns (ie {0:d} with a float)
res_base_text = res_base_text.replace("d}", "s}")
data_as_strings = map(str, res[1])
data['text'] = res_base_text.format(*data_as_strings)
if logger.isEnabledFor(logging.DEBUG):
logger.debug("[Alert][{0}] text = {1}".format(self.get_name(), data['text']))
except Exception, exception:
logger.exception("[Alert][{0}] - The alert's data is not properly formatted".format(self.get_name()))
# if there's a problem with getting the data returned from collect() then mark this
# alert as UNKNOWN
data['state'] = self.RESULT_UNKNOWN
data['text'] = "There is a problem with the alert definition: {0}".format(str(exception))
finally:
# put the alert into the collector so it can be collected on the next run
self.collector.put(self.cluster_name, data)
def _get_configuration_value(self, key):
"""
Gets the value of the specified configuration key from the cache. The key
should be of the form {{foo-bar/baz}}. If the key given is not a lookup key
and is instead a constant, such as "foo" or "5", then the constant is
returned.
If the key contains more than 1 parameter to lookup, then each match is
looked up and replaced.
If the value does not exist in the configs, then return None to indicate
that this key could not be found.
This should turn {{hdfs-site/value}}/whatever/{{hdfs-site/value2}}
into
value/whatever/value2
:return: the resolved value or None if any of the placeholder parameters
does not exist in the configs
"""
if key is None:
return None
# parse {{foo-bar/baz}}/whatever/{{foobar-site/blah}}
# into
# ['foo-bar/baz', 'foobar-site/blah']
placeholder_keys = re.findall("{{(\S+?)}}", key)
# if none found, then return the original
if placeholder_keys is None or len(placeholder_keys) == 0:
return key
# for every match, get its configuration value and replace it in the key
resolved_key = key
for placeholder_key in placeholder_keys:
value = self.cluster_configuration.get_configuration_value(
self.cluster_name, placeholder_key)
# if any of the placeholder keys is missing from the configuration, then
# return None as per the contract of this function
if value is None:
return None
# it's possible that a dictionary was request (ie {{hdfs-site}} instead
# of {{hdfs-site/foo}} - in which case, we should just return the
# dictionary as is
if isinstance(value, dict):
return value
# {{foo-bar/baz}}/whatever -> http://server/whatever
resolved_key = resolved_key.replace("{{%s}}" % placeholder_key, value)
return resolved_key
def _lookup_uri_property_keys(self, uri_structure):
"""
Loads the configuration lookup keys that the URI structure needs. This
will return a named tuple that contains the keys needed to lookup
parameterized URI values from the cached configuration.
The URI structure looks something like:
"uri":{
"http": foo,
"https": bar,
...
}
"""
if uri_structure is None:
return None
http_key = None
https_key = None
https_property_key = None
https_property_value_key = None
default_port = None
kerberos_keytab = None
kerberos_principal = None
ha_nameservice = None
ha_alias_key = None
ha_http_pattern = None
ha_https_pattern = None
if 'http' in uri_structure:
http_key = uri_structure['http']
if 'https' in uri_structure:
https_key = uri_structure['https']
if 'https_property' in uri_structure:
https_property_key = uri_structure['https_property']
if 'https_property_value' in uri_structure:
https_property_value_key = uri_structure['https_property_value']
if 'default_port' in uri_structure:
default_port = uri_structure['default_port']
if 'kerberos_keytab' in uri_structure:
kerberos_keytab = uri_structure['kerberos_keytab']
if 'kerberos_principal' in uri_structure:
kerberos_principal = uri_structure['kerberos_principal']
if 'high_availability' in uri_structure:
ha = uri_structure['high_availability']
if 'nameservice' in ha:
ha_nameservice = ha['nameservice']
if 'alias_key' in ha:
ha_alias_key = ha['alias_key']
if 'http_pattern' in ha:
ha_http_pattern = ha['http_pattern']
if 'https_pattern' in ha:
ha_https_pattern = ha['https_pattern']
AlertUriLookupKeys = namedtuple('AlertUriLookupKeys',
'http https https_property https_property_value default_port '
'kerberos_keytab kerberos_principal '
'ha_nameservice ha_alias_key ha_http_pattern ha_https_pattern')
alert_uri_lookup_keys = AlertUriLookupKeys(http=http_key, https=https_key,
https_property=https_property_key,
https_property_value=https_property_value_key, default_port=default_port,
kerberos_keytab=kerberos_keytab, kerberos_principal=kerberos_principal,
ha_nameservice=ha_nameservice, ha_alias_key=ha_alias_key,
ha_http_pattern=ha_http_pattern, ha_https_pattern=ha_https_pattern
)
return alert_uri_lookup_keys
def _get_uri_from_structure(self, alert_uri_lookup_keys):
"""
Gets the URI to use by examining the URI structure from the definition.
This will return a named tuple that has the uri and the SSL flag. The
URI structure looks something like:
"uri":{
"http": foo,
"https": bar,
...
}
"""
if alert_uri_lookup_keys is None:
return None
http_uri = None
https_uri = None
# first thing is first; if there are HA keys then try to dynamically build
# the property which is used to get the actual value of the uri
# (ie dfs.namenode.http-address.c1ha.nn2)
if alert_uri_lookup_keys.ha_nameservice is not None or alert_uri_lookup_keys.ha_alias_key is not None:
alert_uri = self._get_uri_from_ha_structure(alert_uri_lookup_keys)
if alert_uri is not None:
return alert_uri
# attempt to parse and parameterize the various URIs; properties that
# do not exist int he lookup map are returned as None
if alert_uri_lookup_keys.http is not None:
http_uri = self._get_configuration_value(alert_uri_lookup_keys.http)
if alert_uri_lookup_keys.https is not None:
https_uri = self._get_configuration_value(alert_uri_lookup_keys.https)
# without a URI, there's no way to create the structure we need - return
# the default port if specified, otherwise throw an exception
if http_uri is None and https_uri is None:
if alert_uri_lookup_keys.default_port is not None:
alert_uri = AlertUri(uri=alert_uri_lookup_keys.default_port, is_ssl_enabled=False)
return alert_uri
else:
raise Exception("Could not determine result. Either the http or https URI must be specified.")
# start out assuming plaintext
uri = http_uri
is_ssl_enabled = False
if https_uri is not None:
# https without http implies SSL, otherwise look it up based on the properties
if http_uri is None:
is_ssl_enabled = True
uri = https_uri
elif self._check_uri_ssl_property(alert_uri_lookup_keys):
is_ssl_enabled = True
uri = https_uri
alert_uri = AlertUri(uri=uri, is_ssl_enabled=is_ssl_enabled)
return alert_uri
def _get_uri_from_ha_structure(self, alert_uri_lookup_keys):
"""
Attempts to parse the HA URI structure in order to build a dynamic key
that represents the correct host URI to check.
:param alert_uri_lookup_keys:
:return: the AlertUri named tuple if there is a valid HA URL, otherwise None
"""
if alert_uri_lookup_keys is None:
return None
logger.debug("[Alert][{0}] HA URI structure detected in definition, attempting to lookup dynamic HA properties".format(self.get_name()))
ha_nameservice = self._get_configuration_value(alert_uri_lookup_keys.ha_nameservice)
ha_alias_key = alert_uri_lookup_keys.ha_alias_key
ha_http_pattern = alert_uri_lookup_keys.ha_http_pattern
ha_https_pattern = alert_uri_lookup_keys.ha_https_pattern
# if HA alias key is not defined then it's not HA environment
if ha_alias_key is None:
return None
if alert_uri_lookup_keys.ha_nameservice is not None:
# if there is a HA nameservice defined, but it can not be evaluated then it's not HA environment
if ha_nameservice is None:
return None
# convert dfs.ha.namenodes.{{ha-nameservice}} into dfs.ha.namenodes.c1ha
ha_alias_key = ha_alias_key.replace(self.HA_NAMESERVICE_PARAM, ha_nameservice)
ha_nameservice_alias = self._get_configuration_value(ha_alias_key)
if ha_nameservice_alias is None:
logger.warning("[Alert][{0}] HA nameservice value is present but there are no aliases for {1}".format(
self.get_name(), ha_alias_key))
return None
else:
ha_nameservice_alias = self._get_configuration_value(ha_alias_key)
# if HA nameservice is not defined then the fact that the HA alias_key could not be evaluated shows that it's not HA environment
if ha_nameservice_alias is None:
return None
# determine which pattern to use (http or https)
ha_pattern = ha_http_pattern
is_ssl_enabled = self._check_uri_ssl_property(alert_uri_lookup_keys)
if is_ssl_enabled:
ha_pattern = ha_https_pattern
# no pattern found
if ha_pattern is None:
logger.warning("[Alert][{0}] There is no matching http(s) pattern for the HA URI".format(
self.get_name()))
return None
if self.HA_NAMESERVICE_PARAM in ha_pattern and ha_nameservice is None:
logger.warning("[Alert][{0}] An HA URI pattern of {1} was detected, but there is no nameservice key".format(
self.get_name(), ha_pattern))
return None
# convert dfs.namenode.http-address.{{ha-nameservice}}.{{alias}} into
# dfs.namenode.http-address.c1ha.{{alias}}
if ha_nameservice is not None:
ha_pattern = ha_pattern.replace(self.HA_NAMESERVICE_PARAM, ha_nameservice)
# for each alias, grab it and check to see if this host matches
for alias in ha_nameservice_alias.split(','):
# convert dfs.namenode.http-address.c1ha.{{alias}} into
# dfs.namenode.http-address.c1ha.nn1
key = ha_pattern.replace(self.HA_ALIAS_PARAM, alias.strip())
# get the host for dfs.namenode.http-address.c1ha.nn1 and see if it's
# this host
value = self._get_configuration_value(key)
if value is not None and (self.host_name in value or self.public_host_name in value):
return AlertUri(uri=value, is_ssl_enabled=is_ssl_enabled)
return None
def _check_uri_ssl_property(self, alert_uri_lookup_keys):
"""
Gets whether the SSL property and value on the URI indicate an SSL
connection.
:param alert_uri_lookup_keys:
:return: True if the SSL check property and value are defined and match
otherwise False
"""
https_property = None
https_property_value = None
if alert_uri_lookup_keys.https_property is not None:
https_property = self._get_configuration_value(alert_uri_lookup_keys.https_property)
if alert_uri_lookup_keys.https_property_value is not None:
https_property_value = self._get_configuration_value(alert_uri_lookup_keys.https_property_value)
if https_property is None:
return False
return https_property == https_property_value
def _collect(self):
"""
Low level function to collect alert data. The result is a tuple as:
res[0] = the result code
res[1] = the list of arguments supplied to the reporting text for the result code
"""
#TODO: After implementation uncomment /src/test/python/ambari_agent/TestMetricAlert.py:194
# and /src/test/python/ambari_agent/TestScriptAlert.py:52
raise NotImplementedError
def _get_reporting_text(self, state):
'''
Gets the default reporting text to use when the alert definition does not
contain any. Subclasses can override this to return specific text.
:param state: the state of the alert in uppercase (such as OK, WARNING, etc)
:return: the parameterized text
'''
return '{0}'
"""
See RFC3986, Appendix B
Tested on the following cases:
"192.168.54.1"
"192.168.54.2:7661
"hdfs://192.168.54.3/foo/bar"
"ftp://192.168.54.4:7842/foo/bar"
Returns None if only a port is passed in
"""
@staticmethod
def get_host_from_url(uri):
if uri is None:
return None
# if not a string, return None
if not isinstance(uri, basestring):
return None
# RFC3986, Appendix B
parts = re.findall('^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?', uri)
# index of parts
# scheme = 1
# authority = 3
# path = 4
# query = 6
# fragment = 8
host_and_port = uri
if 0 == len(parts[0][1]):
host_and_port = parts[0][4]
elif 0 == len(parts[0][2]):
host_and_port = parts[0][1]
elif parts[0][2].startswith("//"):
host_and_port = parts[0][3]
if -1 == host_and_port.find(':'):
if host_and_port.isdigit():
return None
return host_and_port
else:
return host_and_port.split(':')[0]
|
import errno
import os
import re
import subprocess
import sys
git_refnames = "$Format:%d$"
git_full = "$Format:%H$"
tag_prefix = ""
parentdir_prefix = "myproject-"
versionfile_source = "cameo/_version.py"
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
assert isinstance(commands, list)
p = None
for c in commands:
try:
# remember shell=False, so use git.cmd on windows, not just git
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
break
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
if verbose:
print("unable to run %s" % args[0])
print(e)
return None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
return None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
stdout = stdout.decode()
if p.returncode != 0:
if verbose:
print("unable to run %s (error)" % args[0])
return None
return stdout
def versions_from_parentdir(parentdir_prefix, root, verbose=False):
# Source tarballs conventionally unpack into a directory that includes
# both the project name and a version string.
dirname = os.path.basename(root)
if not dirname.startswith(parentdir_prefix):
if verbose:
print("guessing rootdir is '%s', but '%s' doesn't start with "
"prefix '%s'" % (root, dirname, parentdir_prefix))
return None
return {"version": dirname[len(parentdir_prefix):], "full": ""}
def git_get_keywords(versionfile_abs):
# the code embedded in _version.py can just fetch the value of these
# keywords. When used from setup.py, we don't want to import _version.py,
# so we do it with a regexp instead. This function is not used from
# _version.py.
keywords = {}
try:
f = open(versionfile_abs, "r")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
f.close()
except EnvironmentError:
pass
return keywords
def git_versions_from_keywords(keywords, tag_prefix, verbose=False):
if not keywords:
return {} # keyword-finding function failed to find keywords
refnames = keywords["refnames"].strip()
if refnames.startswith("$Format"):
if verbose:
print("keywords are unexpanded, not using")
return {} # unexpanded, so not in an unpacked git-archive tarball
refs = set([r.strip() for r in refnames.strip("()").split(",")])
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])
if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d
# expansion behaves like git log --decorate=short and strips out the
# refs/heads/ and refs/tags/ prefixes that would let us distinguish
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = set([r for r in refs if re.search(r'\d', r)])
if verbose:
print("discarding '%s', no digits" % ",".join(refs-tags))
if verbose:
print("likely tags: %s" % ",".join(sorted(tags)))
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):]
if verbose:
print("picking %s" % r)
return {"version": r,
"full": keywords["full"].strip()}
# no suitable tags, so version is "0+unknown", but full hex is still there
if verbose:
print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown",
"full": keywords["full"].strip()}
def git_parse_vcs_describe(git_describe, tag_prefix, verbose=False):
# TAG-NUM-gHEX[-dirty] or HEX[-dirty] . TAG might have hyphens.
# dirty
dirty = git_describe.endswith("-dirty")
if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")]
dirty_suffix = ".dirty" if dirty else ""
# now we have TAG-NUM-gHEX or HEX
if "-" not in git_describe: # just HEX
return "0+untagged.g"+git_describe+dirty_suffix, dirty
# just TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
return "0+unparseable"+dirty_suffix, dirty
# tag
full_tag = mo.group(1)
if not full_tag.startswith(tag_prefix):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
return None, dirty
tag = full_tag[len(tag_prefix):]
# distance: number of commits since tag
distance = int(mo.group(2))
# commit: short hex revision ID
commit = mo.group(3)
# now build up version string, with post-release "local version
# identifier". Our goal: TAG[+NUM.gHEX[.dirty]] . Note that if you get a
# tagged build and then dirty it, you'll get TAG+0.gHEX.dirty . So you
# can always test version.endswith(".dirty").
version = tag
if distance or dirty:
version += "+%d.g%s" % (distance, commit) + dirty_suffix
return version, dirty
def git_versions_from_vcs(tag_prefix, root, verbose=False):
# this runs 'git' from the root of the source tree. This only gets called
# if the git-archive 'subst' keywords were *not* expanded, and
# _version.py hasn't already been rewritten with a short version string,
# meaning we're inside a checked out source tree.
if not os.path.exists(os.path.join(root, ".git")):
if verbose:
print("no .git in %s" % root)
return {} # get_versions() will try next method
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
# if there is a tag, this yields TAG-NUM-gHEX[-dirty]
# if there are no tags, this yields HEX[-dirty] (no NUM)
stdout = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long"],
cwd=root)
# --long was added in git-1.5.5
if stdout is None:
return {} # try next method
version, dirty = git_parse_vcs_describe(stdout, tag_prefix, verbose)
# build "full", which is FULLHEX[.dirty]
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
if stdout is None:
return {}
full = stdout.strip()
if dirty:
full += ".dirty"
return {"version": version, "full": full}
def get_versions(default={"version": "0+unknown", "full": ""}, verbose=False):
# I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have
# __file__, we can work backwards from there to the root. Some
# py2exe/bbfreeze/non-CPython implementations don't do __file__, in which
# case we can only use expanded keywords.
keywords = {"refnames": git_refnames, "full": git_full}
ver = git_versions_from_keywords(keywords, tag_prefix, verbose)
if ver:
return ver
try:
root = os.path.realpath(__file__)
# versionfile_source is the relative path from the top of the source
# tree (where the .git directory might live) to this file. Invert
# this to find the root from __file__.
for i in versionfile_source.split('/'):
root = os.path.dirname(root)
except NameError:
return default
return (git_versions_from_vcs(tag_prefix, root, verbose)
or versions_from_parentdir(parentdir_prefix, root, verbose)
or default)
|
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.yangtypes import YANGDynClass
from pyangbind.lib.yangtypes import ReferenceType
from pyangbind.lib.base import PybindBase
from collections import OrderedDict
from decimal import Decimal
from bitarray import bitarray
import six
if six.PY3:
import builtins as __builtin__
long = int
elif six.PY2:
import __builtin__
from . import area
class areas(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-network-instance - based on the path /network-instances/network-instance/protocols/protocol/ospfv2/areas. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Configuration and operational state relating to an
OSPFv2 area.
"""
__slots__ = ("_path_helper", "_extmethods", "__area")
_yang_name = "areas"
_pybind_generated_by = "container"
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__area = YANGDynClass(
base=YANGListType(
"identifier",
area.area,
yang_name="area",
parent=self,
is_container="list",
user_ordered=False,
path_helper=self._path_helper,
yang_keys="identifier",
extensions=None,
),
is_container="list",
yang_name="area",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
extensions=None,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="list",
is_config=True,
)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path() + [self._yang_name]
else:
return [
"network-instances",
"network-instance",
"protocols",
"protocol",
"ospfv2",
"areas",
]
def _get_area(self):
"""
Getter method for area, mapped from YANG variable /network_instances/network_instance/protocols/protocol/ospfv2/areas/area (list)
YANG Description: The OSPFv2 areas within which the local system exists
"""
return self.__area
def _set_area(self, v, load=False):
"""
Setter method for area, mapped from YANG variable /network_instances/network_instance/protocols/protocol/ospfv2/areas/area (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_area is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_area() directly.
YANG Description: The OSPFv2 areas within which the local system exists
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=YANGListType(
"identifier",
area.area,
yang_name="area",
parent=self,
is_container="list",
user_ordered=False,
path_helper=self._path_helper,
yang_keys="identifier",
extensions=None,
),
is_container="list",
yang_name="area",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
extensions=None,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="list",
is_config=True,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """area must be of a type compatible with list""",
"defined-type": "list",
"generated-type": """YANGDynClass(base=YANGListType("identifier",area.area, yang_name="area", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='identifier', extensions=None), is_container='list', yang_name="area", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='list', is_config=True)""",
}
)
self.__area = t
if hasattr(self, "_set"):
self._set()
def _unset_area(self):
self.__area = YANGDynClass(
base=YANGListType(
"identifier",
area.area,
yang_name="area",
parent=self,
is_container="list",
user_ordered=False,
path_helper=self._path_helper,
yang_keys="identifier",
extensions=None,
),
is_container="list",
yang_name="area",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
extensions=None,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="list",
is_config=True,
)
area = __builtin__.property(_get_area, _set_area)
_pyangbind_elements = OrderedDict([("area", area)])
from . import area
class areas(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-network-instance-l2 - based on the path /network-instances/network-instance/protocols/protocol/ospfv2/areas. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Configuration and operational state relating to an
OSPFv2 area.
"""
__slots__ = ("_path_helper", "_extmethods", "__area")
_yang_name = "areas"
_pybind_generated_by = "container"
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__area = YANGDynClass(
base=YANGListType(
"identifier",
area.area,
yang_name="area",
parent=self,
is_container="list",
user_ordered=False,
path_helper=self._path_helper,
yang_keys="identifier",
extensions=None,
),
is_container="list",
yang_name="area",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
extensions=None,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="list",
is_config=True,
)
load = kwargs.pop("load", None)
if args:
if len(args) > 1:
raise TypeError("cannot create a YANG container with >1 argument")
all_attr = True
for e in self._pyangbind_elements:
if not hasattr(args[0], e):
all_attr = False
break
if not all_attr:
raise ValueError("Supplied object did not have the correct attributes")
for e in self._pyangbind_elements:
nobj = getattr(args[0], e)
if nobj._changed() is False:
continue
setmethod = getattr(self, "_set_%s" % e)
if load is None:
setmethod(getattr(args[0], e))
else:
setmethod(getattr(args[0], e), load=load)
def _path(self):
if hasattr(self, "_parent"):
return self._parent._path() + [self._yang_name]
else:
return [
"network-instances",
"network-instance",
"protocols",
"protocol",
"ospfv2",
"areas",
]
def _get_area(self):
"""
Getter method for area, mapped from YANG variable /network_instances/network_instance/protocols/protocol/ospfv2/areas/area (list)
YANG Description: The OSPFv2 areas within which the local system exists
"""
return self.__area
def _set_area(self, v, load=False):
"""
Setter method for area, mapped from YANG variable /network_instances/network_instance/protocols/protocol/ospfv2/areas/area (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_area is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_area() directly.
YANG Description: The OSPFv2 areas within which the local system exists
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(
v,
base=YANGListType(
"identifier",
area.area,
yang_name="area",
parent=self,
is_container="list",
user_ordered=False,
path_helper=self._path_helper,
yang_keys="identifier",
extensions=None,
),
is_container="list",
yang_name="area",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
extensions=None,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="list",
is_config=True,
)
except (TypeError, ValueError):
raise ValueError(
{
"error-string": """area must be of a type compatible with list""",
"defined-type": "list",
"generated-type": """YANGDynClass(base=YANGListType("identifier",area.area, yang_name="area", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='identifier', extensions=None), is_container='list', yang_name="area", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/network-instance', defining_module='openconfig-network-instance', yang_type='list', is_config=True)""",
}
)
self.__area = t
if hasattr(self, "_set"):
self._set()
def _unset_area(self):
self.__area = YANGDynClass(
base=YANGListType(
"identifier",
area.area,
yang_name="area",
parent=self,
is_container="list",
user_ordered=False,
path_helper=self._path_helper,
yang_keys="identifier",
extensions=None,
),
is_container="list",
yang_name="area",
parent=self,
path_helper=self._path_helper,
extmethods=self._extmethods,
register_paths=True,
extensions=None,
namespace="http://openconfig.net/yang/network-instance",
defining_module="openconfig-network-instance",
yang_type="list",
is_config=True,
)
area = __builtin__.property(_get_area, _set_area)
_pyangbind_elements = OrderedDict([("area", area)])
|
import unittest
from datetime import datetime, timedelta
from rx import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable
from rx.disposables import Disposable, SerialDisposable
from rx.subjects import Subject
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
subscribed = ReactiveTest.subscribed
disposed = ReactiveTest.disposed
created = ReactiveTest.created
class TimeInterval(object):
def __init__(self, value, interval):
if isinstance(interval, timedelta):
interval = int(interval.microseconds/1000.0)
self.value = value
self.interval = interval
def __str__(self):
return "%s@%s" % (self.value, self.interval)
def equals(other):
return other.interval == self.interval and other.value == self.value
class TestTimeInterval(unittest.TestCase):
def test_time_interval_regular(self):
scheduler = TestScheduler()
xs = scheduler.create_hot_observable(on_next(150, 1), on_next(210, 2), on_next(230, 3), on_next(260, 4), on_next(300, 5), on_next(350, 6), on_completed(400))
def create():
def selector(x):
return TimeInterval(x.value, x.interval)
return xs.time_interval(scheduler).map(selector)
results = scheduler.start(create)
results.messages.assert_equal(on_next(210, TimeInterval(2, 10)), on_next(230, TimeInterval(3, 20)), on_next(260, TimeInterval(4, 30)), on_next(300, TimeInterval(5, 40)), on_next(350, TimeInterval(6, 50)), on_completed(400))
def test_time_interval_empty(self):
scheduler = TestScheduler()
def create():
return Observable.empty(scheduler).time_interval(scheduler)
results = scheduler.start(create)
results.messages.assert_equal(on_completed(201))
def test_time_interval_error(self):
ex = 'ex'
scheduler = TestScheduler()
def create():
return Observable.throw_exception(ex, scheduler).time_interval(scheduler)
results = scheduler.start(create)
results.messages.assert_equal(on_error(201, ex))
def test_time_interval_never(self):
scheduler = TestScheduler()
def create():
return Observable.never().time_interval(scheduler)
results = scheduler.start(create)
results.messages.assert_equal()
|
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('lexicon', '0089_fix_citation'),
]
operations = [
migrations.RemoveField(
model_name='meaninglist',
name='data',
),
]
|
from bambino.appenv import Repository, WebAppDir
from contextlib import contextmanager
from path import path
import os
import shutil
import subprocess
import tempfile
import unittest
class TestAppEnvIdentification(unittest.TestCase):
def setUp(self):
sb = self.sandbox = path(tempfile.mkdtemp())
ae1 = sb / 'ae1'
ae2 = sb / 'ae2'
ne1 = sb / 'ne2'
for env in ae1, ae2:
(env / '.git').makedirs_p()
(env / 'etc').mkdir()
ne1.mkdir()
def makeone(self):
return WebAppDir(self.sandbox)
def test_envid(self):
aef = self.makeone()
assert aef.services
envs = set(x.name for x in aef.services)
assert envs == set(('ae1', 'ae2')), envs
class TestAppEnvRepo(unittest.TestCase):
temp_dir = os.getcwd() + '/temp'
temp_etc_dir = temp_dir + '/etc'
def setUp(self):
# Create a simulated app env directory
if not os.path.isdir(TestAppEnvRepo.temp_etc_dir):
os.makedirs(TestAppEnvRepo.temp_etc_dir)
def tearDown(self):
# Remove the directory
if os.path.isdir(TestAppEnvRepo.temp_dir):
shutil.rmtree(TestAppEnvRepo.temp_dir, True)
def test_config_billweb(self):
"""
Test the Repository.config property. This test WILL NOT
be a true unit test because it requires a Git repository
"""
git_path = '/opt/webapp/billweb/etc'
repository = Repository(git_path)
config = repository.config
self.assertTrue(config["author"])
self.assertTrue(config["date"])
self.assertTrue(config["commit"])
self.assertTrue(config["latest_commit"])
self.assertTrue(config["changed_files"])
def test_config_anweb(self):
"""
Test the Repository.config property. This test WILL NOT
be a true unit test because it requires a Git repository
"""
git_path = '/opt/webapp/anweb/etc'
repository = Repository(git_path)
config = repository.config
self.assertTrue(config["author"])
self.assertTrue(config["date"])
self.assertTrue(config["commit"])
self.assertTrue(config["latest_commit"])
self.assertTrue(config["changed_files"])
def make_env_app(self, args=[]):
sb = self.sandbox = path(tempfile.mkdtemp())
with pushd(sb):
predefined = [
'git init', 'touch root.txt', 'git add .',
'git commit -a -m "commit to root"',
'mkdir etc', 'cd etc',
'git init', 'touch etc.txt', 'git add .',
'git commit -a -m "commit to etc"',
'cd ..']
devnul = '| > /dev/null 2>&1'
for deffed in predefined:
subprocess.check_output(deffed + devnul, shell=True)
for arg in args:
subprocess.check_output(arg + devnul, shell=True)
from bambino.appenv import Service
return Service(sb)
def test_no_tag(self):
repo = self.make_env_app()
assert repo.app.last_tag == 'HEAD'
def test_dirty(self):
repo = self.make_env_app(['echo "hi" >> root.txt'])
assert repo.app.is_dirty, repo
def test_change_count(self):
args = ['echo "hi" >> root.txt', 'git tag first_tag',
'git commit -a -m "im just saying"']
repo = self.make_env_app(args)
assert repo.app.change_count == 1
def test_current_branch(self):
args = ['git checkout -b my_branch']
repo = self.make_env_app(args)
assert repo.app.current_branch == 'my_branch'
def test_unchanged(self):
repo = self.make_env_app()
assert repo.status == 'tagged'
def test_uncommitted_changes(self):
args = ['echo "hi" >> root.txt']
repo = self.make_env_app(args)
assert repo.status == 'uncommitted_changes'
def test__get_latest_commit_sha1_from_log(self):
git_path = '/opt/webapp/billweb/etc'
repository = Repository(git_path)
log_text = """commit 0fab9fbd022c71d4883dc153c2730f771b534c0a
Author: Doug Morgan <doug@surveymonkey.com>
Date: Tue Nov 13 11:30:22 2012 -0800
Update app.ini
Testing changing path"""
sha1 = repository._get_latest_commit_sha1_from_log(log_text)
self.assertEqual(sha1, '0fab9fbd022c71d4883dc153c2730f771b534c0a')
def test_committed_changes(self):
args = ['echo "hi" >> root.txt',
'git tag first_tag',
'git commit -a -m "im just saying"']
repo = self.make_env_app(args)
assert repo.status == 'change_to_app_and_config'
@contextmanager
def pushd(dir):
old_dir = os.getcwd()
os.chdir(dir)
try:
yield old_dir
finally:
os.chdir(old_dir)
if __name__ == '__main__':
unittest.main()
|
import simuvex
from simuvex.s_type import SimTypeString
class strcpy(simuvex.SimProcedure):
#pylint:disable=arguments-differ
def run(self, dst, src):
self.argument_types = {0: self.ty_ptr(SimTypeString()),
1: self.ty_ptr(SimTypeString())}
self.return_type = self.ty_ptr(SimTypeString())
strlen = simuvex.SimProcedures['libc.so.6']['strlen']
strncpy = simuvex.SimProcedures['libc.so.6']['strncpy']
src_len = self.inline_call(strlen, src)
ret_expr = self.inline_call(strncpy, dst, src, src_len.ret_expr+1, src_len=src_len.ret_expr).ret_expr
return ret_expr
|
"""
Based on https://djangosnippets.org/snippets/1179/
"""
from re import compile
from django.conf import settings as django_settings
from django.contrib.auth.views import redirect_to_login
from django.urls import reverse
from django_auth_adfs.exceptions import MFARequired
from django_auth_adfs.config import settings
LOGIN_EXEMPT_URLS = [
compile(django_settings.LOGIN_URL.lstrip('/')),
compile(reverse("django_auth_adfs:login").lstrip('/')),
compile(reverse("django_auth_adfs:logout").lstrip('/')),
compile(reverse("django_auth_adfs:callback").lstrip('/')),
]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
LOGIN_EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]
class LoginRequiredMiddleware:
"""
Middleware that requires a user to be authenticated to view any page other
than LOGIN_URL. Exemptions to this requirement can optionally be specified
in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
you can copy from your urls.py).
Requires authentication middleware and template context processors to be
loaded. You'll get an error if they aren't.
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
assert hasattr(request, 'user'), "The Login Required middleware requires " \
"authentication middleware to be installed. " \
"Edit your MIDDLEWARE setting to insert " \
"'django.contrib.auth.middleware.AuthenticationMiddleware'. " \
"If that doesn't work, ensure your TEMPLATE_CONTEXT_PROCESSORS " \
"setting includes 'django.core.context_processors.auth'."
if not request.user.is_authenticated:
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in LOGIN_EXEMPT_URLS):
try:
return redirect_to_login(request.get_full_path())
except MFARequired:
return redirect_to_login('django_auth_adfs:login-force-mfa')
return self.get_response(request)
|
import sys, os
sys.path.insert(0, '..')
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
intersphinx_mapping = {'python': ('http://docs.python.org/3.2', None),
'pymongo': ('http://api.mongodb.org/python/current/', None)}
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Mongotron'
copyright = u'2013, The Montogron Authors'
version = '0.1'
release = '0.1'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
htmlhelp_basename = 'Mongotrondoc'
latex_elements = {
}
latex_documents = [
('index', 'Mongotron.tex', u'Mongotron Documentation',
u'The Montogron Authors', 'manual'),
]
man_pages = [
('index', 'mongotron', u'Mongotron Documentation',
[u'The Montogron Authors'], 1)
]
texinfo_documents = [
('index', 'Mongotron', u'Mongotron Documentation',
u'The Montogron Authors', 'Mongotron', 'One line description of project.',
'Miscellaneous'),
]
|
import tempfile
import subprocess
import numpy as np
from os.path import dirname
class SelfTuningSpectralClustering():
# src_pat ex.) "^.*/X_(\d{3}).csv$"
def __init__(self,n_clusters_max):
self.exe=dirname(__file__)+"/self_tuning_spectral_clustering"
self.n_clusters_max=n_clusters_max
def mktemp(self):
return tempfile.TemporaryFile()
def fit_predict(self,X):
ftemp_y = tempfile.NamedTemporaryFile()
ftemp_X = tempfile.NamedTemporaryFile()
np.savetxt(ftemp_X.name,X,delimiter=',')
command="%s %d %s %s"%(self.exe,int(self.n_clusters_max),ftemp_X.name,ftemp_y.name)
print(command)
p = subprocess.call( command, shell=True )
#p.wait()
y = np.loadtxt(ftemp_y.name,delimiter=',')
return y
|
"""
Implements parsing of Grako's EBNF idiom for grammars, and grammar model
creation using the .grammars module.
GrakoParserRoot is the bootstrap parser. It uses the facilities of parsing.Parser
as generated parsers do, but it does not conform to the patterns in the generated
code. Why? Because having Grako bootstrap itself from its grammar would be cool,
but very bad engineering. GrakoParserRoot is hand-crafted.
The GrakoGrammarGenerator class, a descendant of GrakoParserRoot constructs
a model of the grammar using semantic actions the model elements defined
in the .grammars module.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from grako.bootstrap import GrakoBootstrapParser
from grako.grammars import GrakoContext
from grako.semantics import GrakoASTSemantics, GrakoSemantics
__all__ = ['GrakoParser', 'GrakoGrammarGenerator']
class GrakoParserBase(GrakoBootstrapParser, GrakoContext):
pass
class GrakoParser(GrakoParserBase):
def __init__(self, grammar_name, semantics=None, **kwargs):
if semantics is None:
semantics = GrakoASTSemantics()
super(GrakoParser, self).__init__(semantics=semantics, **kwargs)
class GrakoGrammarGenerator(GrakoParserBase):
def __init__(self, grammar_name, semantics=None, parseinfo=True, **kwargs):
if semantics is None:
semantics = GrakoSemantics(grammar_name)
super(GrakoGrammarGenerator, self).__init__(
semantics=semantics,
parseinfo=True,
**kwargs
)
|
from AnyQt.QtWidgets import QGroupBox, QHBoxLayout, QVBoxLayout
from Orange.widgets import gui
from Orange.widgets import settings
from Orange.widgets.widget import OWWidget
from orangecontrib.text.corpus import Corpus
class Input:
CORPUS = 'Corpus'
class Output:
CORPUS = 'Corpus'
class OWBaseVectorizer(OWWidget):
""" A base class for feature extraction methods.
Notes:
Ensure that `create_configuration_layout` and `update_method` are overwritten.
"""
# Input/output
inputs = [
(Input.CORPUS, Corpus, 'set_data'),
]
outputs = [
(Output.CORPUS, Corpus)
]
want_main_area = False
resizing_enabled = False
# Settings
autocommit = settings.Setting(True)
Method = NotImplemented
def __init__(self):
super().__init__()
self.corpus = None
self.method = None
box = QGroupBox(title='Options')
box.setLayout(self.create_configuration_layout())
self.controlArea.layout().addWidget(box)
buttons_layout = QHBoxLayout()
buttons_layout.addWidget(self.report_button)
buttons_layout.addSpacing(15)
buttons_layout.addWidget(
gui.auto_commit(None, self, 'autocommit', 'Commit', box=False)
)
self.controlArea.layout().addLayout(buttons_layout)
self.update_method()
def set_data(self, data):
self.corpus = data
self.commit()
def commit(self):
self.apply()
def apply(self):
if self.corpus is not None:
new_corpus = self.method.transform(self.corpus)
self.send(Output.CORPUS, new_corpus)
def update_method(self):
self.method = self.Method()
def on_change(self):
self.update_method()
self.commit()
def send_report(self):
self.report_items(self.method.report())
def create_configuration_layout(self):
return QVBoxLayout()
|
def SimIRStmt_CAS(engine, state, stmt):
# first, get the expression of the add
with state.history.subscribe_actions() as addr_actions:
addr = engine.handle_expression(state, stmt.addr)
# figure out if it's a single or double
double_element = (stmt.oldHi != 0xFFFFFFFF) and (stmt.expdHi is not None)
if double_element:
# translate the expected values
with state.history.subscribe_actions() as cond_actions:
expd_lo = engine.handle_expression(state, stmt.expdLo)
expd_hi = engine.handle_expression(state, stmt.expdHi)
# read the old values
old_cnt = state.memory.load(addr, len(expd_lo)*2//8, endness=stmt.endness)
old_hi, old_lo = old_cnt.chop(bits=len(expd_lo))
state.scratch.store_tmp(stmt.oldLo, old_lo, None, None)
state.scratch.store_tmp(stmt.oldHi, old_hi, None, None)
# the write data
with state.history.subscribe_actions() as data_actions:
data_lo = engine.handle_expression(state, stmt.dataLo)
data_hi = engine.handle_expression(state, stmt.dataHi)
data = state.solver.Concat(data_hi, data_lo)
# do it
condition = state.solver.And(old_lo == expd_lo, old_hi == expd_hi)
data_ao = SimActionObject(data, deps=data_actions, state=state)
addr_ao = SimActionObject(addr, deps=addr_actions, state=state)
guard_ao = SimActionObject(condition, deps=cond_actions, state=state)
size_ao = SimActionObject(len(data))
a = SimActionData(state, state.memory.id, SimActionData.WRITE, addr=addr_ao, data=data_ao, condition=guard_ao, size=size_ao)
state.memory.store(addr, data, condition=condition, endness=stmt.endness, action=a)
state.history.add_action(a)
else:
# translate the expected value
with state.history.subscribe_actions() as cond_actions:
expd_lo = engine.handle_expression(state, stmt.expdLo)
# read the old values
old_lo = state.memory.load(addr, len(expd_lo)//state.arch.byte_width, endness=stmt.endness)
state.scratch.store_tmp(stmt.oldLo, old_lo, None, None)
# the write data
with state.history.subscribe_actions() as data_actions:
data = engine.handle_expression(state, stmt.dataLo)
# do it
condition = old_lo == expd_lo
data_ao = SimActionObject(data, deps=data_actions, state=state)
addr_ao = SimActionObject(addr, deps=addr_actions, state=state)
guard_ao = SimActionObject(condition, deps=cond_actions, state=state)
size_ao = SimActionObject(len(data))
a = SimActionData(state, state.memory.id, SimActionData.WRITE, addr=addr_ao, data=data_ao, condition=guard_ao, size=size_ao)
state.memory.store(addr, data, condition=condition, endness=stmt.endness, action=a)
from ....state_plugins.sim_action import SimActionData
from ....state_plugins.sim_action_object import SimActionObject
|
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'dot_app.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.