input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
notchwidth / 2.0,
thefreq + notchwidth / 2.0,
)
def harmonicnotchfilter(timecourse, Fs, Ffundamental, notchpct=1.0, debug=False):
r"""Harmonic notch filter - removes a fundamental and its harmonics from a timecourse.
Parameters
----------
timecourse: 1D numpy array
Input data
Fs: float
Sample rate
Ffundamental: float
Fundamental frequency to be removed from the data
notchpct: float, optional
Width of the notch relative to the filter frequency in percent. Default is 1.0.
debug: bool, optional
Set to True for additiona information on function internals. Default is False.
Returns
-------
filteredtc: 1D numpy array
The filtered data
"""
# delete the fundamental and its harmonics
filteredtc = timecourse + 0.0
maxpass = Fs / 2.0
if notchpct is not None:
stopfreq = Ffundamental
freqstep = 0.5 * Fs / len(filteredtc)
maxharmonic = int(maxpass // stopfreq)
if debug:
print("highest harmonic is", maxharmonic, "(", maxharmonic * stopfreq, "Hz)")
thenotchfilter = NoncausalFilter()
for harmonic in range(1, maxharmonic + 1):
notchfreq = harmonic * stopfreq
if debug:
print("removing harmonic at", notchfreq)
notchwidth = np.max([notchpct * harmonic * stopfreq * 0.01, freqstep])
if debug:
print("\tFs:", Fs)
print("\tstopfreq:", stopfreq)
print("\tnotchpct:", notchpct)
print("\tnotchwidth:", notchwidth)
print("\tnotchfreq:", notchfreq)
print("\tfreqstep:", freqstep)
print("\tminfreqstep:", freqstep / notchfreq)
print("\tbins:", int(notchwidth // freqstep))
print()
setnotchfilter(thenotchfilter, notchfreq, notchwidth=notchwidth)
filteredtc = thenotchfilter.apply(Fs, filteredtc)
return filteredtc
def savgolsmooth(data, smoothlen=101, polyorder=3):
return savgol_filter(data, smoothlen, polyorder)
def csdfilter(obsdata, commondata, padlen=20, cyclic=False, debug=False):
r"""Cross spectral density filter - makes a filter transfer function that preserves common frequencies.
Parameters
----------
obsdata: 1D numpy array
Input data
commondata: 1D numpy array
Shared data
padlen: int, optional
Number of reflected points to add on each end of the input data. Default is 20.
cyclic : bool, optional
If True, pad by wrapping the data in a cyclic manner rather than reflecting at the ends
debug: bool, optional
Set to True for additiona information on function internals. Default is False.
Returns
-------
filtereddata: 1D numpy array
The filtered data
"""
padobsdata = padvec(obsdata, padlen=padlen, cyclic=cyclic)
padcommondata = padvec(commondata, padlen=padlen, cyclic=cyclic)
obsdata_trans = fftpack.fft(padobsdata)
transferfunc = np.sqrt(np.abs(fftpack.fft(padobsdata) * np.conj(fftpack.fft(padcommondata))))
obsdata_trans *= transferfunc
return unpadvec(fftpack.ifft(obsdata_trans).real, padlen=padlen)
@conditionaljit()
def arb_pass(
Fs,
inputdata,
lowerstop,
lowerpass,
upperpass,
upperstop,
transferfunc="trapezoidal",
butterorder=6,
padlen=20,
cyclic=False,
debug=False,
):
r"""Filters an input waveform over a specified range. By default it is a trapezoidal
FFT filter, but brickwall and butterworth filters are also available. Ends are padded to reduce
transients.
Parameters
----------
Fs : float
Sample rate in Hz
:param Fs:
inputdata : 1D numpy array
Input data to be filtered
:param inputdata:
lowerstop : float
Upper end of lower stopband in Hz
:param lowerstop:
lowerpass : float
Lower end of passband in Hz
:param lowerpass:
upperpass : float
Upper end of passband in Hz
:param upperpass:
upperstop : float
Lower end of upper stopband in Hz
:param upperstop:
butterorder : int, optional
Order of Butterworth filter, if used. Default is 6.
:param butterorder:
padlen : int, optional
Amount of points to reflect around each end of the input vector prior to filtering. Default is 20.
:param padlen:
cyclic : bool, optional
If True, pad by wrapping the data in a cyclic manner rather than reflecting at the ends
:param cyclic:
debug : boolean, optional
When True, internal states of the function will be printed to help debugging.
:param debug:
Returns
-------
filtereddata : 1D float array
The filtered data
"""
# check filter limits to see if we should do a lowpass, bandpass, or highpass
if lowerpass <= 0.0:
# set up for lowpass
if transferfunc == "butterworth":
retvec = dolpfiltfilt(
Fs, upperpass, inputdata, butterorder, padlen=padlen, cyclic=False, debug=debug,
)
return retvec
else:
return dolptransfuncfilt(
Fs,
inputdata,
upperpass=upperpass,
upperstop=upperstop,
type=transferfunc,
padlen=padlen,
cyclic=cyclic,
debug=debug,
)
elif (upperpass >= Fs / 2.0) or (upperpass <= 0.0):
# set up for highpass
if transferfunc == "butterworth":
return dohpfiltfilt(
Fs, lowerpass, inputdata, butterorder, padlen=padlen, cyclic=False, debug=debug,
)
else:
return dohptransfuncfilt(
Fs,
inputdata,
lowerstop=lowerstop,
lowerpass=lowerpass,
type=transferfunc,
padlen=padlen,
cyclic=cyclic,
debug=debug,
)
else:
# set up for bandpass
if transferfunc == "butterworth":
return dohpfiltfilt(
Fs,
lowerpass,
dolpfiltfilt(
Fs,
upperpass,
inputdata,
butterorder,
padlen=padlen,
cyclic=False,
debug=debug,
),
butterorder,
padlen=padlen,
debug=debug,
)
else:
return dobptransfuncfilt(
Fs,
inputdata,
lowerstop=lowerstop,
lowerpass=lowerpass,
upperpass=upperpass,
upperstop=upperstop,
type=transferfunc,
padlen=padlen,
cyclic=cyclic,
debug=debug,
)
class Plethfilter:
def __init_(self, Fs, Fl, Fh, order=4, attenuation=20):
self.Fs = Fs
self.Fh = Fh
self.Fl = Fl
self.attenuation = attenuation
self.order = order
retvec = signal.cheby2(
self.order,
self.attenuation,
[self.Fl / self.Fn, self.Fh / self.Fn],
btype="bandpass",
analog=False,
output="ba",
)
self.b = retvec[0]
self.a = retvec[1]
def apply(self, data):
return signal.filtfilt(self.b, self.a, data, axis=-1, padtype="odd", padlen=None)
class NoncausalFilter:
def __init__(
self,
filtertype="None",
transitionfrac=0.05,
transferfunc="trapezoidal",
initlowerstop=None,
initlowerpass=None,
initupperpass=None,
initupperstop=None,
butterworthorder=6,
correctfreq=True,
padtime=30.0,
cyclic=False,
debug=False,
):
r"""A zero time delay filter for one dimensional signals, especially physiological ones.
Parameters
----------
filtertype : {'None' 'vlf', 'lfo', 'resp', 'card', 'vlf_stop', 'lfo_stop', 'resp_stop', 'card_stop', 'arb', 'arb_stop', 'ringstop'}, optional
The type of filter.
butterworthorder: int, optional
Butterworth filter order. Default is 6.
correctfreq: boolean, optional
Fix pass frequencies that are impossible. Default is True.
padtime: float, optional
Amount of time to end pad to reduce edge effects. Default is 30.0 seconds
cyclic : boolean, optional
If True, pad vectors cyclicly rather than reflecting data around the ends
debug: boolean, optional
Enable extended debugging messages. Default is False.
Methods
-------
settype(thetype)
Set the filter type. Options are 'None' (default), 'vlf', 'lfo', 'resp', 'card', 'vlf_stop', 'lfo_stop',
'resp_stop', 'card_stop', 'arb', 'arb_stop', 'ringstop'.
gettype()
Return the current filter type.
getfreqs()
Return the current frequency limits.
setbutterorder(order=self.butterworthorder)
Set the order for Butterworth filter
setpadtime(padtime)
Set the end pad time in seconds.
setdebug(debug)
Turn debugging on and off with the debug flag.
getpadtime()
Return the current end pad time.
setfreqs(lowerstop, lowerpass, upperpass, upperstop)
Set the frequency parameters of the 'arb' and 'arb_stop' filter.
"""
self.filtertype = filtertype
self.species = "human"
self.transitionfrac = transitionfrac
self.transferfunc = transferfunc
if initlowerpass is None:
self.arb_lowerpass = 0.05
self.arb_lowerstop = 0.9 * self.arb_lowerpass
else:
self.arb_lowerpass = initlowerpass
self.arb_lowerstop = initlowerstop
if initupperpass is None:
self.arb_upperpass = 0.20
self.arb_upperstop = 1.1 * self.arb_upperpass
else:
self.arb_upperpass = initupperpass
self.arb_upperstop = initupperstop
self.lowerstop = 0.0
self.lowerpass = 0.0
self.upperpass = -1.0
self.upperstop = -1.0
self.butterworthorder = butterworthorder
self.correctfreq = correctfreq
self.padtime = padtime
self.cyclic = cyclic
self.debug = debug
self.VLF_UPPERPASS = 0.009
self.VLF_UPPERSTOP = self.VLF_UPPERPASS * (1.0 + self.transitionfrac)
self.LF_LOWERPASS = 0.01
self.LF_UPPERPASS = 0.15
self.LF_LOWERSTOP = self.LF_LOWERPASS * (1.0 - self.transitionfrac)
self.LF_UPPERSTOP = self.LF_UPPERPASS * (1.0 + self.transitionfrac)
self.LF_LEGACY_LOWERPASS = 0.01
self.LF_LEGACY_UPPERPASS = 0.15
self.LF_LEGACY_LOWERSTOP = 0.009
self.LF_LEGACY_UPPERSTOP = 0.2
self.RESP_LOWERPASS = 0.2
self.RESP_UPPERPASS = 0.5
self.RESP_LOWERSTOP = self.RESP_LOWERPASS * (1.0 - self.transitionfrac)
self.RESP_UPPERSTOP = self.RESP_UPPERPASS * (1.0 + self.transitionfrac)
self.CARD_LOWERPASS = 0.66
self.CARD_UPPERPASS = 3.0
self.CARD_LOWERSTOP = self.CARD_LOWERPASS * (1.0 - self.transitionfrac)
self.CARD_UPPERSTOP = self.CARD_UPPERPASS * (1.0 + self.transitionfrac)
self.settype(self.filtertype)
def settype(self, thetype):
self.filtertype = thetype
if self.filtertype == "vlf" or self.filtertype == "vlf_stop":
self.lowerstop = 0.0
self.lowerpass = 0.0
self.upperpass = 1.0 * self.VLF_UPPERPASS
self.upperstop = 1.0 * self.VLF_UPPERSTOP
elif self.filtertype == "lfo" or self.filtertype == "lfo_stop":
self.lowerstop = 1.0 * self.LF_LOWERSTOP
self.lowerpass = 1.0 * self.LF_LOWERPASS
self.upperpass = 1.0 * self.LF_UPPERPASS
self.upperstop = 1.0 * self.LF_UPPERSTOP
elif self.filtertype == "lfo_legacy" or self.filtertype == "lfo_legacy_stop":
self.lowerstop = 1.0 * self.LF_LEGACY_LOWERSTOP
self.lowerpass = 1.0 * self.LF_LEGACY_LOWERPASS
self.upperpass = 1.0 * self.LF_LEGACY_UPPERPASS
self.upperstop = 1.0 * self.LF_LEGACY_UPPERSTOP
elif self.filtertype == "resp" or self.filtertype == "resp_stop":
self.lowerstop = 1.0 * self.RESP_LOWERSTOP
self.lowerpass = 1.0 * self.RESP_LOWERPASS
self.upperpass = 1.0 * self.RESP_UPPERPASS
self.upperstop = 1.0 * self.RESP_UPPERSTOP
elif self.filtertype == "cardiac" or self.filtertype == "cardiac_stop":
self.lowerstop = 1.0 * self.CARD_LOWERSTOP
self.lowerpass = 1.0 * self.CARD_LOWERPASS
self.upperpass = 1.0 * self.CARD_UPPERPASS
self.upperstop = 1.0 * self.CARD_UPPERSTOP
elif self.filtertype == "arb" or self.filtertype == "arb_stop":
self.lowerstop = 1.0 * self.arb_lowerstop
self.lowerpass = 1.0 * self.arb_lowerpass
self.upperpass = 1.0 * self.arb_upperpass
self.upperstop = 1.0 * self.arb_upperstop
else:
self.lowerstop = 0.0
self.lowerpass = 0.0
self.upperpass = -1.0
self.upperstop = -1.0
def gettype(self):
return self.filtertype
def setbutterorder(self, order=3):
self.butterworthorder = order
def setdebug(self, debug):
self.debug = debug
def setpadtime(self, padtime):
| |
# Copyright 2004-2019 <NAME> <<EMAIL>>
#
# 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.
# TODO: Use overlap (rather than simple pointer location) to determine
# drag and drop.
from __future__ import print_function
import renpy.display
from renpy.display.render import render, Render, redraw
from renpy.display.core import absolute
from renpy.display.behavior import map_event, run, run_unhovered
import pygame_sdl2 as pygame
def default_drag_group():
"""
Gets the default drag group. If it doesn't exist yet, creates it.
"""
sls = renpy.game.context().scene_lists
rv = sls.drag_group
if rv is None:
rv = DragGroup()
sls.drag_group = rv
return rv
def default_drag_joined(drag):
return [ (drag, 0, 0) ]
def default_drop_allowable(drop, drags):
return True
class Drag(renpy.display.core.Displayable, renpy.python.RevertableObject):
"""
:doc: drag_drop class
:args: (d=None, drag_name=None, draggable=True, droppable=True, drag_raise=True, dragged=None, dropped=None, drag_handle=(0.0, 0.0, 1.0, 1.0), drag_joined=..., clicked=None, hovered=None, unhovered=None, mouse_drop=False, **properties)
A displayable that represents an object that can be dragged around
its enclosing area. A Drag can also represent an area that
other Drags can be dropped on.
A Drag can be moved around inside is parent. Generally, its parent
should be either a :func:`Fixed` or :class:`DragGroup`.
A Drag has one child. The child's state reflects the status
of the drag and drop operation:
* ``selected_hover`` - when it is being dragged.
* ``selected_idle`` - when it can be dropped on.
* ``hover`` - when the draggable will be dragged when the mouse is
clicked.
* ``idle`` - otherwise.
The drag handle is a rectangle inside the child. The mouse must be over
a non-transparent pixel inside the drag handle for dragging or clicking
to occur.
A newly-created draggable is added to the default DragGroup. A draggable
can only be in a single DragGroup - if it's added to a second group,
it's removed from the first.
When a Drag is first rendered, if it's position cannot be determined
from the DragGroup it is in, the position of its upper-left corner
is computed using the standard layout algorithm. Once that position
`d`
If present, the child of this Drag. Drags use the child style
in preference to this, if it's not None.
`drag_name`
If not None, the name of this draggable. This is available
as the `name` property of draggable objects. If a Drag
with the same name is or was in the DragGroup, the starting
position of this Drag is taken from that Draggable.
`draggable`
If true, the Drag can be dragged around the screen with
the mouse.
`droppable`
If true, other Drags can be dropped on this Drag.
`drag_raise`
If true, this Drag is raised to the top when it is dragged. If
it is joined to other Drags, all joined drags are raised.
`activated`
A callback (or list of callbacks) that is called when the mouse
is pressed down on the drag. It is called with one argument, a
a list of Drags that are being dragged. The return value of this
callback is ignored.
`dragged`
A callback (or list of callbacks) that is called when the Drag
has been dragged. It is called with two arguments. The first is
a list of Drags that are being dragged. The second is either
a Drag that is being dropped onto, or None of a drop did not
occur. If the callback returns a value other than None, that
value is returned as the result of the interaction.
`dropped`
A callback (or list of callbacks) that is called when this Drag
is dropped onto. It is called with two arguments. The first
is the Drag being dropped onto. The second is a list of Drags that
are being dragged. If the callback returns a value other than None,
that value is returned as the result of the interaction.
When a dragged and dropped callback are triggered for the same
event, the dropped callback is only called if dragged returns
None.
`clicked`
A callback this is called, with no arguments, when the Drag is
clicked without being moved. A droppable can also be focused
and clicked. If the callback returns a value other than None,
that value is returned as the result of the interaction.
`alternate`
An action that is run when the Drag is right-clicked (on the
desktop) or long-pressed without moving (on mobile). It may
be necessary to increase :var:`config.longpress_duration` if
this triggers to early on mobile platforms.
`drag_handle`
A (x, y, width, height) tuple, giving the position of the drag
handle within the child. In this tuple, integers are considered
to be a literal number of pixels, while floats are relative to
the size of the child.
`drag_joined`
This is called with the current Drag as an argument. It's
expected to return a list of [ (drag, x, y) ] tuples, giving
the draggables to drag as a unit. `x` and `y` are the offsets
of the drags relative to each other, they are not relative
to the corner of this drag.
`drag_offscreen`
If true, this draggable can be moved offscreen. This can be
dangerous to use with drag_joined or drags that can change
size, as the drags can leave the screen entirely, with no
way to get them back on the screen.
`mouse_drop`
If true, the drag is dropped on the first droppable under the cursor.
If false, the default, the drag is dropped onto the droppable with
the largest degree of overlap.
`drop_allowable`
A callback that is called to determine whether this drop allow
the current drags dropped onto. It is called with two arguments.
The first is the Drag which determines its sensitivity.
The second is a list of Drags that are being dragged.
Except for `d`, all of the parameters are available as fields (with
the same name) on the Drag object. In addition, after the drag has
been rendered, the following fields become available:
`x`, `y`
The position of the Drag relative to its parent, in pixels.
`w`, `h`
The width and height of the Drag's child, in pixels.
"""
z = 0
focusable = True
drag_group = None
old_position = None
drag_offscreen = False
activated = None
alternate = None
# The time a click started, or None if a click is not in progress.
click_time = None
def __init__(self,
d=None,
drag_name=None,
draggable=True,
droppable=True,
drag_raise=True,
dragged=None,
dropped=None,
drop_allowable=default_drop_allowable,
drag_handle=(0.0, 0.0, 1.0, 1.0),
drag_joined=default_drag_joined,
clicked=None,
hovered=None,
unhovered=None,
replaces=None,
drag_offscreen=False,
mouse_drop=False,
activated=None,
alternate=None,
style="drag",
**properties):
super(Drag, self).__init__(style=style, **properties)
self.drag_name = drag_name
self.draggable = draggable
self.droppable = droppable
self.drag_raise = drag_raise
self.dragged = dragged
self.dropped = dropped
self.drop_allowable = drop_allowable
self.drag_handle = drag_handle
self.drag_joined = drag_joined
self.clicked = clicked
self.hovered = hovered
self.unhovered = unhovered
self.activated = activated
self.alternate = alternate
self.drag_offscreen = drag_offscreen
# if mouse_drop_check is True (default False), the drop will not
# use default major overlap between droppables but instead
# will use mouse coordinates to select droppable
self.mouse_drop = mouse_drop
# We're focusable if we can be dragged.
self.focusable = draggable
self.child = None
# Add us to a drag group | |
"""RefineNet-LightWeight
RefineNet-LigthWeight PyTorch for non-commercial purposes
Copyright (c) 2018, <NAME> (<EMAIL>)
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
# general libs
import argparse
import logging
import os
import random
import re
import time
# misc
import cv2
import numpy as np
# pytorch libs
import torch
import torch.nn as nn
# custom libs
from config import *
from miou_utils import compute_iu, fast_cm
from util import *
def get_arguments():
"""Parse all the arguments provided from the CLI.
Returns:
A list of parsed arguments.
"""
parser = argparse.ArgumentParser(description="Full Pipeline Training")
# Dataset
parser.add_argument("--train-dir", type=str, default=TRAIN_DIR, help="Path to the training set directory.")
parser.add_argument("--val-dir", type=str, default=VAL_DIR, help="Path to the validation set directory.")
parser.add_argument("--train-list", type=str, nargs="+", default=TRAIN_LIST, help="Path to the training set list.")
parser.add_argument("--val-list", type=str, nargs="+", default=VAL_LIST, help="Path to the validation set list.")
parser.add_argument("--shorter-side", type=int, nargs="+", default=SHORTER_SIDE, help="Shorter side transformation.")
parser.add_argument("--crop-size", type=int, nargs="+", default=CROP_SIZE, help="Crop size for training,")
parser.add_argument("--normalise-params", type=list, default=NORMALISE_PARAMS, help="Normalisation parameters [scale, mean, std],")
parser.add_argument("--batch-size", type=int, nargs="+", default=BATCH_SIZE, help="Batch size to train the segmenter model.")
parser.add_argument("--num-workers", type=int, default=NUM_WORKERS, help="Number of workers for pytorch's dataloader.")
parser.add_argument("--num-classes", type=int, nargs="+", default=NUM_CLASSES, help="Number of output classes for each task.")
parser.add_argument("--low-scale", type=float, nargs="+", default=LOW_SCALE, help="Lower bound for random scale")
parser.add_argument("--high-scale", type=float, nargs="+", default=HIGH_SCALE, help="Upper bound for random scale")
parser.add_argument("--ignore-label", type=int, default=IGNORE_LABEL, help="Label to ignore during training")
# Encoder
parser.add_argument("--enc", type=str, default=ENC, help="Encoder net type.")
parser.add_argument("--enc-pretrained", type=bool, default=ENC_PRETRAINED, help="Whether to init with imagenet weights.")
parser.add_argument("--resume", default=RESUME, type=str, metavar="PATH", help="path to latest checkpoint")
# General
parser.add_argument("--evaluate", type=bool, default=EVALUATE, help="If true, only validate segmentation.")
parser.add_argument("--freeze-bn", type=bool, nargs="+", default=FREEZE_BN, help="Whether to keep batch norm statistics intact.")
parser.add_argument("--num-segm-epochs", type=int, nargs="+", default=NUM_SEGM_EPOCHS, help="Number of epochs to train for segmentation network.")
parser.add_argument("--print-every", type=int, default=PRINT_EVERY, help="Print information every often.")
parser.add_argument("--random-seed", type=int, default=RANDOM_SEED, help="Seed to provide (near-)reproducibility.")
# parser.add_argument("--snapshot-dir", type=str, default=SNAPSHOT_DIR, help="Path to directory for storing checkpoints.")
parser.add_argument("--ckpt-path", type=str, default=CKPT_PATH, help="Path to the checkpoint file." )
parser.add_argument("--val-every", nargs="+", type=int, default=VAL_EVERY, help="How often to validate current architecture.")
# Optimisers
parser.add_argument("--lr-enc", type=float, nargs="+", default=LR_ENC, help="Learning rate for encoder.")
parser.add_argument("--lr-dec", type=float, nargs="+", default=LR_DEC, help="Learning rate for decoder.")
parser.add_argument("--mom-enc", type=float, nargs="+", default=MOM_ENC, help="Momentum for encoder.")
parser.add_argument("--mom-dec", type=float, nargs="+", default=MOM_DEC, help="Momentum for decoder.")
parser.add_argument("--wd-enc", type=float, nargs="+", default=WD_ENC, help="Weight decay for encoder.")
parser.add_argument("--wd-dec", type=float, nargs="+", default=WD_DEC, help="Weight decay for decoder.")
parser.add_argument("--optim-dec", type=str, default=OPTIM_DEC, help="Optimiser algorithm for decoder.")
return parser.parse_args()
def create_segmenter(net, pretrained, num_classes):
"""Create Encoder; for now only ResNet [50,101,152]"""
from models.resnet import rf_lw50, rf_lw101, rf_lw152
if str(net) == "50":
return rf_lw50(num_classes, imagenet=pretrained)
elif str(net) == "101":
return rf_lw101(num_classes, imagenet=pretrained)
elif str(net) == "152":
return rf_lw152(num_classes, imagenet=pretrained)
else:
raise ValueError("{} is not supported".format(str(net)))
def create_loaders(train_dir, val_dir, train_list, val_list, shorter_side,
crop_size, low_scale, high_scale, normalise_params, batch_size,
num_workers, ignore_label):
"""
Args:
train_dir (str) : path to the root directory of the training set.
val_dir (str) : path to the root directory of the validation set.
train_list (str) : path to the training list.
val_list (str) : path to the validation list.
shorter_side (int) : parameter of the shorter_side resize transformation.
crop_size (int) : square crop to apply during the training.
low_scale (float) : lowest scale ratio for augmentations.
high_scale (float) : highest scale ratio for augmentations.
normalise_params (list / tuple) : img_scale, img_mean, img_std.
batch_size (int) : training batch size.
num_workers (int) : number of workers to parallelise data loading operations.
ignore_label (int) : label to pad segmentation masks with
Returns:
train_loader, val loader
"""
# Torch libraries
from torchvision import transforms
from torch.utils.data import DataLoader
# Custom libraries
from datasets import NYUDataset as Dataset
from datasets import (
Pad,
RandomCrop,
RandomMirror,
ResizeShorterScale,
ToTensor,
Normalise,
)
## Transformations during training ##
composed_trn = transforms.Compose(
[
ResizeShorterScale(shorter_side, low_scale, high_scale),
Pad(crop_size, [123.675, 116.28, 103.53], ignore_label),
RandomMirror(),
RandomCrop(crop_size),
Normalise(*normalise_params),
ToTensor(),
]
)
composed_val = transforms.Compose([Normalise(*normalise_params), ToTensor()])
## Training and validation sets ##
trainset = Dataset(
data_file=train_list,
data_dir=train_dir,
transform_trn=composed_trn,
transform_val=composed_val,
)
valset = Dataset(
data_file=val_list,
data_dir=val_dir,
transform_trn=None,
transform_val=composed_val,
)
logger.info(
" Created train set = {} examples, val set = {} examples".format(
len(trainset), len(valset)
)
)
## Training and validation loaders ##
train_loader = DataLoader(
trainset,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers,
pin_memory=True,
drop_last=True,
)
val_loader = DataLoader(
valset, batch_size=1, shuffle=False, num_workers=num_workers, pin_memory=True
)
return train_loader, val_loader
def create_optimisers(
lr_enc, lr_dec, mom_enc, mom_dec, wd_enc, wd_dec, param_enc, param_dec, optim_dec
):
"""Create optimisers for encoder, decoder and controller"""
optim_enc = torch.optim.SGD(
param_enc, lr=lr_enc, momentum=mom_enc, weight_decay=wd_enc
)
if optim_dec == "sgd":
optim_dec = torch.optim.SGD(
param_dec, lr=lr_dec, momentum=mom_dec, weight_decay=wd_dec
)
elif optim_dec == "adam":
optim_dec = torch.optim.Adam(
param_dec, lr=lr_dec, weight_decay=wd_dec, eps=1e-3
)
return optim_enc, optim_dec
def load_ckpt(ckpt_path, ckpt_dict, mode):
PATH = ckpt_path + mode + '.pth.tar'
ckpt = torch.load(PATH, map_location='cpu')
if mode == 'numbers':
return ckpt.get('epoch_start', 0)
if mode == 'best':
return ckpt.get('best_val', 0)
if mode == 'opt':
return ckpt['opt_enc'], ckpt['opt_dec']
def train_segmenter(
segmenter, train_loader, optim_enc, optim_dec, epoch, segm_crit, freeze_bn
):
"""Training segmenter
Args:
segmenter (nn.Module) : segmentation network
train_loader (DataLoader) : training data iterator
optim_enc (optim) : optimiser for encoder
optim_dec (optim) : optimiser for decoder
epoch (int) : current epoch
segm_crit (nn.Loss) : segmentation criterion
freeze_bn (bool) : whether to keep BN params intact
"""
train_loader.dataset.set_stage("train")
segmenter.train()
if freeze_bn:
for m in segmenter.modules():
if isinstance(m, nn.BatchNorm2d):
m.eval()
batch_time = AverageMeter()
losses = AverageMeter()
for i, sample in enumerate(train_loader):
start = time.time()
input = sample["image"].cuda()
target = sample["mask"].cuda()
input_var = torch.autograd.Variable(input).float()
target_var = torch.autograd.Variable(target).long()
# Compute output
output = segmenter(input_var)
output = nn.functional.interpolate(
output, size=target_var.size()[1:], mode="bilinear", align_corners=False
)
soft_output = nn.LogSoftmax()(output)
# Compute loss and backpropagate
loss = segm_crit(soft_output, target_var)
optim_enc.zero_grad()
optim_dec.zero_grad()
loss.backward()
optim_enc.step()
optim_dec.step()
losses.update(loss.item())
batch_time.update(time.time() - start)
if i % args.print_every == 0:
logger.info(
" Train epoch: {} [{}/{}]\t"
"Avg. Loss: {:.3f}\t"
"Avg. Time: {:.3f}".format(
epoch, i, len(train_loader), losses.avg, batch_time.avg
)
)
def validate(segmenter, val_loader, epoch, num_classes=-1):
"""Validate segmenter
Args:
segmenter (nn.Module) : segmentation network
val_loader (DataLoader) : training data iterator
epoch (int) : current epoch
num_classes (int) : number of classes to consider
Returns:
Mean IoU (float)
"""
val_loader.dataset.set_stage("val")
segmenter.eval()
cm = np.zeros((num_classes, num_classes), dtype=int)
with torch.no_grad():
for i, sample in enumerate(val_loader):
input = sample["image"]
target = sample["mask"]
input_var = torch.autograd.Variable(input).float().cuda()
# Compute output
output = segmenter(input_var)
output = (
cv2.resize(
output[0, :num_classes].data.cpu().numpy().transpose(1, 2, 0),
target.size()[1:][::-1],
interpolation=cv2.INTER_CUBIC,
)
.argmax(axis=2)
.astype(np.uint8)
)
# Compute IoU
gt = target[0].data.cpu().numpy().astype(np.uint8)
gt_idx = (
gt < num_classes
) # Ignore every class index larger than the number of classes
cm += fast_cm(output[gt_idx], gt[gt_idx], num_classes)
if i % args.print_every == 0:
logger.info(
" Val epoch: {} [{}/{}]\t"
"Mean IoU: {:.3f}".format(
epoch, i, len(val_loader), compute_iu(cm).mean()
)
)
ious = compute_iu(cm)
logger.info(" IoUs: {}".format(ious))
miou = np.mean(ious)
logger.info(" Val epoch: {}\tMean IoU: {:.3f}".format(epoch, miou))
return miou
def main():
global args, logger
args = get_arguments()
logger = logging.getLogger(__name__)
## Add args ##
args.num_stages = len(args.num_classes)
## Set random seeds ##
torch.backends.cudnn.deterministic = True
torch.manual_seed(args.random_seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(args.random_seed)
np.random.seed(args.random_seed)
random.seed(args.random_seed)
## Generate Segmenter ##
segmenter = nn.DataParallel(
create_segmenter(args.enc, args.enc_pretrained, args.num_classes[0])).cuda()
logger.info(
" Loaded Segmenter {}, ImageNet-Pre-Trained={}, #PARAMS={:3.2f}M".format(
args.enc, args.enc_pretrained, compute_params(segmenter) / 1e6))
# Restore if any
best_val, epoch_start = 0, 0
if args.resume:
saved_model = args.resume + 'model.pth.tar'
if os.path.isfile(saved_model):
print(372)
segmenter.load_state_dict(torch.load(saved_model, map_location='cpu'))
epoch_start = load_ckpt(args.resume, None, mode='numbers')
best_val = load_ckpt(args.resume, None, | |
<reponame>aidotse/Team-rahma.ai<gh_stars>0
import numpy
import cellprofiler_core.utilities.grid
import cellprofiler_core.image
import cellprofiler_core.measurement
import cellprofiler.modules.definegrid
import cellprofiler.modules.identifyobjectsingrid
import cellprofiler_core.object
import cellprofiler_core.pipeline
import cellprofiler_core.workspace
OUTPUT_OBJECTS_NAME = "outputobjects"
GRID_NAME = "mygrid"
GUIDING_OBJECTS_NAME = "inputobjects"
def make_workspace(gridding, labels=None):
module = cellprofiler.modules.identifyobjectsingrid.IdentifyObjectsInGrid()
module.set_module_num(1)
module.grid_name.value = GRID_NAME
module.output_objects_name.value = OUTPUT_OBJECTS_NAME
module.guiding_object_name.value = GUIDING_OBJECTS_NAME
image_set_list = cellprofiler_core.image.ImageSetList()
object_set = cellprofiler_core.object.ObjectSet()
if labels is not None:
my_objects = cellprofiler_core.object.Objects()
my_objects.segmented = labels
object_set.add_objects(my_objects, GUIDING_OBJECTS_NAME)
pipeline = cellprofiler_core.pipeline.Pipeline()
def callback(caller, event):
assert not isinstance(event, cellprofiler_core.pipeline.event.RunException)
pipeline.add_listener(callback)
pipeline.add_module(module)
workspace = cellprofiler_core.workspace.Workspace(
pipeline,
module,
image_set_list.get_image_set(0),
object_set,
cellprofiler_core.measurement.Measurements(),
image_set_list,
)
workspace.set_grid(GRID_NAME, gridding)
return workspace, module
def make_rectangular_grid(gridding):
assert isinstance(gridding, cellprofiler_core.utilities.grid.Grid)
i0 = gridding.y_location_of_lowest_y_spot
j0 = gridding.x_location_of_lowest_x_spot
di = gridding.y_spacing
dj = gridding.x_spacing
ni = gridding.rows
nj = gridding.columns
i, j = numpy.mgrid[0 : (i0 + di * (ni + 1)), 0 : (j0 + di * (nj + 1))]
i = numpy.round((i - i0).astype(float) / di).astype(int)
j = numpy.round((j - j0).astype(float) / dj).astype(int)
mask = (i >= 0) & (j >= 0) & (i < ni) & (j < nj)
grid = numpy.zeros((int(gridding.image_height), int(gridding.image_width)), int)
g = grid[: i.shape[0], : i.shape[1]]
g[mask[: g.shape[0], : g.shape[1]]] = gridding.spot_table[i[mask], j[mask]]
return grid
def test_forced_location():
d = cellprofiler.modules.definegrid.DefineGrid()
d.ordering.value = cellprofiler.modules.definegrid.NUM_BY_COLUMNS
#
# Grid with x spacing = 10, y spacing = 20
#
diameter = 6
gridding = d.build_grid_info(15, 25, 1, 1, 25, 45, 2, 2)
expected = make_rectangular_grid(gridding)
i, j = numpy.mgrid[0 : expected.shape[0], 0 : expected.shape[1]]
ispot, jspot = numpy.mgrid[0 : gridding.rows, 0 : gridding.columns]
y_locations = numpy.zeros(numpy.max(gridding.spot_table) + 1, int)
y_locations[gridding.spot_table.flatten()] = gridding.y_locations[ispot.flatten()]
x_locations = numpy.zeros(numpy.max(gridding.spot_table) + 1, int)
x_locations[gridding.spot_table.flatten()] = gridding.x_locations[jspot.flatten()]
idist = i - y_locations[expected]
jdist = j - x_locations[expected]
expected[idist ** 2 + jdist ** 2 > (float(diameter + 1) / 2) ** 2] = 0
workspace, module = make_workspace(gridding)
assert isinstance(
module, cellprofiler.modules.identifyobjectsingrid.IdentifyObjectsInGrid
)
module.diameter_choice.value = cellprofiler.modules.identifyobjectsingrid.AM_MANUAL
module.diameter.value = diameter
module.shape_choice.value = (
cellprofiler.modules.identifyobjectsingrid.SHAPE_CIRCLE_FORCED
)
module.run(workspace)
labels = workspace.object_set.get_objects(OUTPUT_OBJECTS_NAME).segmented
assert numpy.all(labels == expected[0 : labels.shape[0], 0 : labels.shape[1]])
#
# Check measurements
#
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
xm = m.get_current_measurement(OUTPUT_OBJECTS_NAME, "Location_Center_X")
assert numpy.all(xm == x_locations[1:])
ym = m.get_current_measurement(OUTPUT_OBJECTS_NAME, "Location_Center_Y")
assert numpy.all(ym == y_locations[1:])
count = m.get_current_image_measurement("Count_%s" % OUTPUT_OBJECTS_NAME)
assert count == gridding.rows * gridding.columns
columns = module.get_measurement_columns(workspace.pipeline)
assert len(columns) == 4
count_feature = "Count_%s" % OUTPUT_OBJECTS_NAME
assert all(
[
column[0]
== ("Image" if column[1] == count_feature else OUTPUT_OBJECTS_NAME)
for column in columns
]
)
assert all(
[
column[1]
in (
"Location_Center_X",
"Location_Center_Y",
count_feature,
"Number_Object_Number",
)
for column in columns
]
)
#
# Check the measurements
#
categories = list(module.get_categories(None, OUTPUT_OBJECTS_NAME))
assert len(categories) == 2
categories.sort()
assert categories[0] == "Location"
assert categories[1] == "Number"
categories = module.get_categories(None, "Image")
assert len(categories) == 1
assert categories[0] == "Count"
measurements = module.get_measurements(
None, "Image", "Count"
)
assert len(measurements) == 1
assert measurements[0] == OUTPUT_OBJECTS_NAME
measurements = module.get_measurements(None, OUTPUT_OBJECTS_NAME, "Location")
assert len(measurements) == 2
assert all(m in ("Center_X", "Center_Y") for m in measurements)
assert "Center_X" in measurements
assert "Center_Y" in measurements
measurements = module.get_measurements(None, OUTPUT_OBJECTS_NAME, "Number")
assert len(measurements) == 1
assert measurements[0] == "Object_Number"
def test_forced_location_auto():
#
# Automatic diameter
#
d = cellprofiler.modules.definegrid.DefineGrid()
d.ordering.value = cellprofiler.modules.definegrid.NUM_BY_COLUMNS
diameter = 7
gridding = d.build_grid_info(15, 25, 1, 1, 25, 45, 2, 2)
expected = make_rectangular_grid(gridding)
i, j = numpy.mgrid[0 : expected.shape[0], 0 : expected.shape[1]]
ispot, jspot = numpy.mgrid[0 : gridding.rows, 0 : gridding.columns]
y_locations = numpy.zeros(numpy.max(gridding.spot_table) + 1, int)
y_locations[gridding.spot_table.flatten()] = gridding.y_locations[ispot.flatten()]
x_locations = numpy.zeros(numpy.max(gridding.spot_table) + 1, int)
x_locations[gridding.spot_table.flatten()] = gridding.x_locations[jspot.flatten()]
idist = i - y_locations[expected]
jdist = j - x_locations[expected]
expected[idist ** 2 + jdist ** 2 > (float(diameter + 1) / 2) ** 2] = 0
#
# Make a fuzzy mask to account for the diameter being +/- 1
#
mask = numpy.ones(expected.shape, bool)
mask[
numpy.abs(numpy.sqrt(idist ** 2 + jdist ** 2) - float(diameter + 1) / 2) <= 1
] = False
#
# Make a labels matrix that's like the expected one, but
# is relabeled randomly
#
guide_labels = expected.copy()
numpy.random.seed(0)
p = numpy.random.permutation(numpy.arange(expected.max() + 1))
p[p == 0] = p[0]
p[0] = 0
guide_labels = p[guide_labels]
workspace, module = make_workspace(gridding, guide_labels)
assert isinstance(
module, cellprofiler.modules.identifyobjectsingrid.IdentifyObjectsInGrid
)
module.diameter_choice.value = (
cellprofiler.modules.identifyobjectsingrid.AM_AUTOMATIC
)
module.shape_choice.value = (
cellprofiler.modules.identifyobjectsingrid.SHAPE_CIRCLE_FORCED
)
module.run(workspace)
labels = workspace.object_set.get_objects(OUTPUT_OBJECTS_NAME).segmented
assert numpy.all(
labels[mask] == expected[0 : labels.shape[0], 0 : labels.shape[1]][mask]
)
def test_natural_circle():
d = cellprofiler.modules.definegrid.DefineGrid()
d.ordering.value = cellprofiler.modules.definegrid.NUM_BY_COLUMNS
#
# Grid with x spacing = 10, y spacing = 20
#
diameter = 6
gridding = d.build_grid_info(15, 25, 1, 1, 32, 45, 2, 2)
expected = make_rectangular_grid(gridding)
i, j = numpy.mgrid[0 : expected.shape[0], 0 : expected.shape[1]]
ispot, jspot = numpy.mgrid[0 : gridding.rows, 0 : gridding.columns]
y_locations = numpy.zeros(numpy.max(gridding.spot_table) + 1, int)
y_locations[gridding.spot_table.flatten()] = gridding.y_locations[ispot.flatten()]
x_locations = numpy.zeros(numpy.max(gridding.spot_table) + 1, int)
x_locations[gridding.spot_table.flatten()] = gridding.x_locations[jspot.flatten()]
#
# Perturb the X and Y locations and diameters randomly
#
numpy.random.seed(0)
x_locations += (numpy.random.uniform(size=x_locations.shape[0]) * 3 - 1).astype(int)
y_locations += (numpy.random.uniform(size=y_locations.shape[0]) * 3 - 1).astype(int)
random_diameters = numpy.random.uniform(size=y_locations.shape[0] + 1) * 4 * 3
idist = i - y_locations[expected]
jdist = j - x_locations[expected]
guide_labels = expected.copy()
expected[idist ** 2 + jdist ** 2 > (float(diameter + 1) / 2) ** 2] = 0
guide_labels[
idist ** 2 + jdist ** 2 > ((random_diameters[guide_labels] + 1) / 2) ** 2
] = 0
workspace, module = make_workspace(gridding, guide_labels)
assert isinstance(
module, cellprofiler.modules.identifyobjectsingrid.IdentifyObjectsInGrid
)
module.diameter_choice.value = cellprofiler.modules.identifyobjectsingrid.AM_MANUAL
module.diameter.value = diameter
module.shape_choice.value = (
cellprofiler.modules.identifyobjectsingrid.SHAPE_CIRCLE_NATURAL
)
module.run(workspace)
labels = workspace.object_set.get_objects(OUTPUT_OBJECTS_NAME).segmented
assert numpy.all(labels == expected[0 : labels.shape[0], 0 : labels.shape[1]])
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
xm = m.get_current_measurement(OUTPUT_OBJECTS_NAME, "Location_Center_X")
assert numpy.all(xm == x_locations[1:])
ym = m.get_current_measurement(OUTPUT_OBJECTS_NAME, "Location_Center_Y")
assert numpy.all(ym == y_locations[1:])
count = m.get_current_image_measurement("Count_%s" % OUTPUT_OBJECTS_NAME)
assert count == gridding.rows * gridding.columns
def test_natural_circle_edges():
#
# Put objects near the edges of the circle and make sure
# they are filtered out
#
d = cellprofiler.modules.definegrid.DefineGrid()
d.ordering.value = cellprofiler.modules.definegrid.NUM_BY_COLUMNS
#
# Grid with x spacing = 10, y spacing = 20
#
diameter = 6
gridding = d.build_grid_info(15, 25, 1, 1, 32, 45, 2, 2)
expected = make_rectangular_grid(gridding)
i, j = numpy.mgrid[0 : expected.shape[0], 0 : expected.shape[1]]
ispot, jspot = numpy.mgrid[0 : gridding.rows, 0 : gridding.columns]
y_locations = numpy.zeros(numpy.max(gridding.spot_table) + 1, int)
y_locations[gridding.spot_table.flatten()] = gridding.y_locations[ispot.flatten()]
x_locations = numpy.zeros(numpy.max(gridding.spot_table) + 1, int)
x_locations[gridding.spot_table.flatten()] = gridding.x_locations[jspot.flatten()]
#
# save some bad places - at the corners of the grids
#
bad_x_locations = (x_locations - gridding.x_spacing / 2).astype(int)
bad_y_locations = (y_locations - gridding.y_spacing / 2).astype(int)
#
# Perturb the X and Y locations and diameters randomly
#
numpy.random.seed(0)
x_locations += (numpy.random.uniform(size=x_locations.shape[0]) * 3 - 1).astype(int)
y_locations += (numpy.random.uniform(size=y_locations.shape[0]) * 3 - 1).astype(int)
random_diameters = numpy.random.uniform(size=y_locations.shape[0] + 1) * 4 * 3
idist = i - y_locations[expected]
jdist = j - x_locations[expected]
guide_labels = expected.copy()
expected[idist ** 2 + jdist ** 2 > (float(diameter + 1) / 2) ** 2] = 0
guide_labels[
idist ** 2 + jdist ** 2 > ((random_diameters[guide_labels] + 1) / 2) ** 2
] = 0
#
# Add objects in bad places
#
for i_off in (-1, 0, 1):
for j_off in (-1, 0, 1):
guide_labels[bad_y_locations + i_off, bad_x_locations + j_off] = (
numpy.arange(len(bad_y_locations))
+ gridding.rows * gridding.columns
+ 1
)
#
# run the module
#
workspace, module = make_workspace(gridding, guide_labels)
assert isinstance(
module, cellprofiler.modules.identifyobjectsingrid.IdentifyObjectsInGrid
)
module.diameter_choice.value = cellprofiler.modules.identifyobjectsingrid.AM_MANUAL
module.diameter.value = diameter
module.shape_choice.value = (
cellprofiler.modules.identifyobjectsingrid.SHAPE_CIRCLE_NATURAL
)
module.run(workspace)
labels = workspace.object_set.get_objects(OUTPUT_OBJECTS_NAME).segmented
assert numpy.all(labels == expected[0 : labels.shape[0], 0 : labels.shape[1]])
m = workspace.measurements
assert isinstance(m,cellprofiler_core.measurement.Measurements)
xm = m.get_current_measurement(OUTPUT_OBJECTS_NAME, "Location_Center_X")
assert numpy.all(xm == x_locations[1:])
ym = m.get_current_measurement(OUTPUT_OBJECTS_NAME, "Location_Center_Y")
assert numpy.all(ym == y_locations[1:])
count = m.get_current_image_measurement("Count_%s" % OUTPUT_OBJECTS_NAME)
assert count == gridding.rows * gridding.columns
def test_img_891():
"""Regression test of img-891, last spot filtered out"""
d = cellprofiler.modules.definegrid.DefineGrid()
d.ordering.value = cellprofiler.modules.definegrid.NUM_BY_COLUMNS
#
# Grid with x spacing = 10, y spacing = 20
#
diameter = 6
gridding = d.build_grid_info(15, 25, 1, 1, 32, 45, 2, 2)
expected = make_rectangular_grid(gridding)
i, j = numpy.mgrid[0 : expected.shape[0], 0 : expected.shape[1]]
ispot, jspot = numpy.mgrid[0 : gridding.rows, 0 : gridding.columns]
y_locations = numpy.zeros(numpy.max(gridding.spot_table) + 1, int)
| |
<filename>src/melange/src/soc/views/helper/surveys.py
#!/usr/bin/env python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Custom widgets used for Survey form fields, plus the SurveyContent form.
"""
__authors__ = [
'"<NAME>" <<EMAIL>>',
'"<NAME>" <<EMAIL>>',
'"<NAME>" <<EMAIL>>',
'"<NAME>" <<EMAIL>>',
]
from itertools import chain
import csv
import datetime
import logging
import StringIO
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
from django import forms
from django.forms import widgets
from django.forms.fields import CharField
from django.template import loader
from django.utils.datastructures import SortedDict
from django.utils.encoding import force_unicode
from django.utils.html import escape
from soc.models.survey import COMMENT_PREFIX
from soc.models.survey import SurveyContent
from soc.views.helper import widgets as custom_widgets
CHOICE_TYPES = set(('selection', 'pick_multi', 'choice', 'pick_quant'))
# TODO(ajaksu) add this to template
REQUIRED_COMMENT_TPL = """
<label for="required_for_{{ name }}">Required</label>
<select id="required_for_{{ name }}" name="required_for_{{ name }}">
<option value="True" {% if is_required %} selected='selected' {% endif %}
>True</option>
<option value="False" {% if not is_required %} selected='selected'
{% endif %}>False</option>
</select>
<label for="comment_for_{{ name }}">Allow Comments</label>
<select id="comment_for_{{ name }}" name="comment_for_{{ name }}">
<option value="True" {% if has_comment %} selected='selected' {% endif %}
>True</option>
<option value="False" {% if not has_comment %} selected='selected'
{% endif %}>False</option>
</select>
"""
class SurveyTakeForm(djangoforms.ModelForm):
"""SurveyContent form for recording survey answers.
This class is used to produce survey forms for survey taking:
- User taking survey
- User updating already taken survey
Using dynamic properties of the survey model (if passed as an arg) the
survey form is dynamically formed.
"""
def __init__(self, *args, **kwargs):
"""Store special kwargs as attributes.
params:
survey: a Survey entity
survey_content: a SuveryContent entity (if no Survey is provided).
survey_logic: instance of SurveyLogic.
survey_record: optionally a SurveyRecord entity.
read_only: controls whether the survey taking UI allows data entry.
data: dictionary mapping fields to data for validation.
"""
self.kwargs = kwargs
self.survey = self.kwargs.pop('survey', None)
if self.survey:
self.survey_content = self.survey.survey_content
else:
self.survey_content = self.kwargs.pop('survey_content', None)
self.survey_logic = self.kwargs.pop('survey_logic', None)
self.survey_record = self.kwargs.pop('survey_record', None)
# TODO: This should be removed since readonly is covered by the RecordForm
self.read_only = self.kwargs.pop('read_only', None)
self.fields_map = dict(
long_answer=self.addLongField,
short_answer=self.addShortField,
selection=self.addSingleField,
pick_multi=self.addMultiField,
pick_quant=self.addQuantField,
)
# get the POST data dict if present
post_data = self.kwargs.pop('data', None)
# set cleaner methods for fields, only needed if we have POST data
if post_data:
# prepare to render a bound, validating form
self.has_post = True
clean_data = self.setCleaners(post_data)
else:
self.has_post = False
clean_data = self.setCleaners()
# update with fields from subclasses
if hasattr(self, 'data') and self.data:
clean_data.update(self.data)
delattr(self, 'data')
# pass data, so form is bound
if post_data:
self.kwargs['data'] = clean_data
super(SurveyTakeForm, self).__init__(*args, **self.kwargs)
self.fields = self.getFields(clean_data)
def setCleaners(self, post_dict=None):
"""Set cleaner methods for dynamic fields.
Used for storing textual input as Text instead of StringProperty. If
passed a dict of field names/values (as the kwarg 'data' to __init__),
it's possible to set clean_[field_id] methods for validation.
This method populates the 'data' dict used for generating form fields.
Args:
post_dict: dictionary used to populate the fields
"""
# prefix for method names
clean = 'clean_'
# data is passed to super's __init__ as the 'data' kwarg
data = {}
# flag whether we can use getlist to retrieve multiple values
is_post = hasattr(post_dict, 'getlist')
schema = {}
if self.survey_content:
schema = eval(self.survey_content.schema)
for key, val in schema.items():
if val['type'] == 'long_answer':
# store > 500 chars per long answer
setattr(self, clean + key,
lambda key=key: db.Text(self.cleaned_data.get(key))
)
if val['has_comment']:
comment = COMMENT_PREFIX + key
#store > 500 chars per comment field
setattr(self, clean + comment,
lambda comment=comment: db.Text(self.cleaned_data.get(comment))
)
# put comment in self.data
if post_dict:
comment_val = post_dict.get(comment) or None
else:
comment_val = getattr(self.survey_record, comment, None)
data[comment] = comment_val
# put POST or record value for field in self.data
is_multi = val['type'] == 'pick_multi'
if post_dict:
if is_multi and is_post:
key_val = post_dict.getlist(key)
else:
key_val = post_dict.get(key)
else:
key_val = getattr(self.survey_record, key, None)
if is_multi and isinstance(key_val, basestring):
# TODO(ajaksu): find out if we still need this safety net
key_val = key_val.split(',')
elif not is_multi and isinstance(key_val, list):
# old pick_multi record for a question that is now single choice
key_val = key_val[0] if key_val else ''
data[key] = key_val
return data
def getFields(self, post_dict=None):
"""Build the SurveyContent (questions) form fields.
params:
post_dict: dict with POST data that will be used for validation
Populates self.survey_fields, which will be ordered in self.insertFields.
"""
if not self.survey_content:
return
post_dict = post_dict or {}
self.survey_fields = {}
schema = SurveyContentSchema(self.survey_content.schema)
attrs = {}
# figure out whether we want a read-only view
read_only = self.read_only
if not read_only:
survey_content = self.survey_content
survey_entity = self.survey_logic.getSurveyForContent(survey_content)
deadline = survey_entity.survey_end
read_only = deadline and (datetime.datetime.now() > deadline)
if read_only:
attrs['disabled'] = 'disabled'
# add unordered fields to self.survey_fields
for field in self.survey_content.dynamic_properties():
value = post_dict.get(field)
# skip comments, as they should go below their corresponding questions
if field.startswith(COMMENT_PREFIX):
continue
label = schema.getLabel(field)
if label is None:
# we log this error in getLabel
continue
# find correct field type
addField = self.fields_map[schema.getType(field)]
# check if question is required, it's never required when editing
required = schema.getRequired(field)
tip = schema.getTip(field)
kwargs = dict(label=label, req=required, tip=tip)
# copy attrs
extra_attrs = attrs.copy()
# add new field
addField(field, value, extra_attrs, schema, **kwargs)
# handle comments if question allows them
if schema.getHasComment(field):
comment = post_dict.get(COMMENT_PREFIX + field)
self.addCommentField(field, comment, extra_attrs, tip='Add a comment.')
return self.insertFields()
def insertFields(self):
"""Add ordered fields to self.fields.
"""
fields = SortedDict()
survey_order = self.survey_content.getSurveyOrder()
# first, insert dynamic survey fields
for _, property in sorted(survey_order.items()):
fields.insert(len(fields) + 1, property, self.survey_fields[property])
# add comment if field has one and this isn't an edit view
property = COMMENT_PREFIX + property
if property in self.survey_fields:
fields.insert(len(fields) + 1, property, self.survey_fields[property])
return fields
def addLongField(self, field, value, attrs, schema, req=True, label='',
tip='', comment=''):
"""Add a long answer fields to this form.
params:
field: the current field
value: the initial value for this field
attrs: additional attributes for field
schema: schema for survey
req: required bool
label: label for field
tip: tooltip text for field
comment: initial comment value for field
"""
#fix growfield wrapping
attrs['wrap'] = 'hard'
widget = widgets.Textarea(attrs=attrs)
if not tip:
tip = 'Please provide a long answer to this question.'
question = CharField(help_text=tip, required=req, label=label,
widget=widget, initial=value)
self.survey_fields[field] = question
def addShortField(self, field, value, attrs, schema, req=False, label='',
tip='', comment=''):
"""Add a short answer fields to this form.
params:
field: the current field
value: the initial value for this field
attrs: additional attributes for field
schema: schema for survey
req: required bool
label: label for field
tip: tooltip text for field
comment: initial comment value for field
"""
attrs['class'] = "text_question"
widget = widgets.TextInput(attrs=attrs)
if not tip:
tip = 'Please provide a short answer to this question.'
question = CharField(help_text=tip, required=req, label=label,
widget=widget, max_length=140, initial=value)
self.survey_fields[field] = question
def addSingleField(self, field, value, attrs, schema, req=False, label='',
tip='', comment=''):
"""Add a selection field to this form.
params:
field: the current field
value: the initial value for this field
attrs: additional attributes for field
schema: schema for survey
req: required bool
label: label for field
tip: tooltip text for field
comment: initial comment value for field
"""
widget = PickOneSelect(attrs)
these_choices = []
# add all properties, but select chosen one
# TODO(ajaksu): this breaks ordering and blocks merging choice methods
options = getattr(self.survey_content, field)
if self.survey_record and hasattr(self.survey_record, field):
these_choices.append((value, value))
if value in options:
options.remove(value)
for option in options:
these_choices.append((option, option))
if not tip:
tip = 'Please select an answer this question.'
question = PickOneField(help_text=tip, required=req, label=label,
choices=tuple(these_choices), widget=widget)
self.survey_fields[field] = question
def addMultiField(self, field, value, attrs, schema, req=False, label='',
tip='', | |
None:
query = query.filter(cls.gateway_id == gateway_id)
if since:
query = query.filter(cls.created_at >= since)
if until:
query = query.filter(cls.created_at <= until)
if types and len(types) > 0:
query = query.filter(cls.type.in_(types))
if resolved is not None:
if resolved:
query = query.filter(cls.resolved_at != None)
else:
query = query.filter(cls.resolved_at == None)
if risks and len(risks) > 0:
query = query.filter(AlertTypeExplicit.risk.in_(risks))
#Get only alerts of types that correlates with the value of the param alert_asset_type
if alert_asset_type == AlertAssetType.BOTH:
valid_types = [AlertAssetType.BOTH, AlertAssetType.DEVICE, AlertAssetType.GATEWAY]
elif alert_asset_type == AlertAssetType.DEVICE or alert_asset_type == AlertAssetType.GATEWAY:
valid_types = [AlertAssetType.BOTH, alert_asset_type]
else:
valid_types = [alert_asset_type]
query = query.filter(or_(
AlertTypeExplicit.for_asset_type.in_(valid_types),
and_(
AlertTypeExplicit.for_asset_type == AlertAssetType.LOOK_IN_ALERT_PARAMS,
AlertTypeImplicit.for_asset_type.in_(valid_types)
)
))
if order_by:
order_field = order_by[0]
order_direction = order_by[1]
if 'ASC' == order_direction:
query = query.order_by(asc(getattr(cls, order_field)))
else:
query = query.order_by(desc(getattr(cls, order_field)))
else:
query = query.order_by(desc(cls.created_at)) # newest first if no order_by parameter is specified
if page and size:
return query.paginate(page=page, per_page=size, error_out=config.ERROR_OUT, max_per_page=config.MAX_PER_PAGE)
return query.all()
@classmethod
def count(cls, organization_id, since, until, types, resolved, risks, data_collectors):
try:
query = db.session.query(func.count(1).label('count'))\
.filter(cls.data_collector_id == DataCollector.id)\
.filter(DataCollector.organization_id == organization_id) \
.filter(cls.show == True)
if since:
query = query.filter(cls.created_at >= since)
if until:
query = query.filter(cls.created_at <= until)
if types and len(types) > 0:
query = query.filter(cls.type.in_(types))
if resolved is not None:
if resolved:
query = query.filter(cls.resolved_at != None)
else:
query = query.filter(cls.resolved_at == None)
if risks and len(risks) > 0:
query = query.filter(cls.type == AlertType.code).filter(AlertType.risk.in_(risks))
if data_collectors and len(data_collectors) > 0:
query = query.filter(cls.data_collector_id.in_(data_collectors))
return query.scalar()
except Exception as e:
LOG.error(e)
@classmethod
def count_by_date(cls, organization_id, since, until, types, resolved, risks):
try:
query = db.session.query(func.date(cls.created_at).label('date'), func.count(1).label('count'))\
.filter(cls.data_collector_id == DataCollector.id)\
.filter(DataCollector.organization_id == organization_id) \
.filter(cls.show == True)
if risks and len(risks) > 0:
query = query.join(AlertType).filter(AlertType.risk.in_(risks))
if since:
query = query.filter(cls.created_at >= since)
if until:
query = query.filter(cls.created_at <= until)
if types and len(types) > 0:
query = query.filter(cls.type.in_(types))
if resolved is not None:
if resolved:
query = query.filter(cls.resolved_at != None)
else:
query = query.filter(cls.resolved_at == None)
query = query.group_by(func.date(cls.created_at)).order_by(asc(func.date(cls.created_at)))
return query.all()
except Exception as e:
LOG.error(e)
@classmethod
def count_by_hour(cls, organization_id, since, until, types, resolved, risks):
try:
query = db.session\
.query(func.date_trunc('hour', cls.created_at).label('hour'), func.count(1).label('count'))\
.filter(cls.data_collector_id == DataCollector.id)\
.filter(DataCollector.organization_id == organization_id) \
.filter(cls.show == True)
if since:
query = query.filter(cls.created_at >= since)
if until:
query = query.filter(cls.created_at <= until)
if types and len(types) > 0:
query = query.filter(cls.type.in_(types))
if resolved is not None:
if resolved:
query = query.filter(cls.resolved_at != None)
else:
query = query.filter(cls.resolved_at == None)
if risks and len(risks) > 0:
query = query.join(AlertType).filter(AlertType.risk.in_(risks))
query = query\
.group_by(func.date_trunc('hour', cls.created_at))\
.order_by(asc(func.date_trunc('hour', cls.created_at)))
return query.all()
except Exception as e:
LOG.error(e)
def update(self):
db.session.commit()
@classmethod
def group_by_date_and_risk(cls, organization_id, since, until, types, resolved, data_collectors):
try:
query = db.session.query(func.date(cls.created_at).label('date'), AlertType.risk.label('risk'))\
.filter(cls.data_collector_id == DataCollector.id)\
.filter(DataCollector.organization_id == organization_id) \
.filter(cls.show == True)
query = query.join(AlertType)
if since:
query = query.filter(cls.created_at >= since)
if until:
query = query.filter(cls.created_at <= until)
if types and len(types) > 0:
query = query.filter(cls.type.in_(types))
if resolved is not None:
if resolved:
query = query.filter(cls.resolved_at != None)
else:
query = query.filter(cls.resolved_at == None)
if data_collectors and len(data_collectors) > 0:
query = query.filter(cls.data_collector_id.in_(data_collectors))
return query.distinct().all()
except Exception as e:
LOG.error(e)
@classmethod
def group_by_hour_and_risk(cls, organization_id, since, until, types, resolved, data_collectors):
try:
query = db.session\
.query(func.date_trunc('hour', cls.created_at).label('hour'), AlertType.risk.label('risk'))\
.filter(cls.data_collector_id == DataCollector.id)\
.filter(DataCollector.organization_id == organization_id) \
.filter(cls.show == True)
query = query.join(AlertType)
if since:
query = query.filter(cls.created_at >= since)
if until:
query = query.filter(cls.created_at <= until)
if types and len(types) > 0:
query = query.filter(cls.type.in_(types))
if resolved is not None:
if resolved:
query = query.filter(cls.resolved_at != None)
else:
query = query.filter(cls.resolved_at == None)
if data_collectors and len(data_collectors) > 0:
query = query.filter(cls.data_collector_id.in_(data_collectors))
return query.distinct().all()
except Exception as e:
LOG.error(e)
class AssetImportance(Enum):
LOW = 'LOW'
MEDIUM = 'MEDIUM'
HIGH = 'HIGH'
class Gateway(db.Model):
__tablename__ = 'gateway'
id = Column(BigInteger, primary_key=True, autoincrement=True)
gw_hex_id = Column(String(100), nullable=True)
name = Column(String, nullable=True)
vendor = Column(String, nullable=True)
location_latitude = Column(Float, nullable=True)
location_longitude = Column(Float, nullable=True)
data_collector_id = Column(BigInteger, db.ForeignKey("data_collector.id"), nullable=False)
organization_id = Column(BigInteger, db.ForeignKey("organization.id"), nullable=False)
connected = Column(Boolean, nullable=False, default=True)
first_activity = Column(DateTime(timezone=True), nullable=True)
last_activity = Column(DateTime(timezone=True), nullable=False)
activity_freq = Column(Float, nullable=True)
npackets_up = Column(BigInteger, nullable=False, default=0)
npackets_down = Column(BigInteger, nullable=False, default=0)
importance = Column(SQLEnum(AssetImportance))
def to_json(self):
return {
'id': self.id,
'gw_hex_id': self.gw_hex_id,
'name': self.name,
'vendor': self.vendor,
'location': {
'latitude': self.location_latitude,
'longitude': self.location_longitude
},
'data_collector_id': self.data_collector_id,
'organization_id': self.organization_id,
'connected': self.connected,
'last_activity': "{}".format(self.last_activity),
'activity_freq': self.activity_freq,
'importance': self.importance.value,
'npackets_up': self.npackets_up,
'npackets_down': self.npackets_down
}
class Device(db.Model):
__tablename__ = 'device'
id = Column(BigInteger, primary_key=True, autoincrement=True)
dev_eui = Column(String(16), nullable=False)
name = Column(String, nullable=True)
vendor = Column(String, nullable=True)
app_name = Column(String, nullable=True)
join_eui = Column(String(16), nullable=True)
organization_id = Column(BigInteger, ForeignKey("organization.id"), nullable=False)
data_collector_id = Column(BigInteger, db.ForeignKey("data_collector.id"), nullable=False)
importance = Column(SQLEnum(AssetImportance))
repeated_dev_nonce = Column(Boolean, nullable=True)
join_request_counter = Column(Integer, nullable=False, default=0)
join_accept_counter = Column(Integer, nullable=False, default=0)
has_joined = Column(Boolean, nullable=True, default=False)
join_inferred = Column(Boolean, nullable=True, default=False)
is_otaa = Column(Boolean, nullable=True)
last_packet_id = Column(BigInteger, ForeignKey("packet.id"), nullable=True)
first_up_timestamp = Column(db.DateTime(timezone=True), nullable=True)
last_up_timestamp = Column(DateTime(timezone=True), nullable=True)
pending_first_connection = Column(Boolean, nullable=False, default=True)
connected = Column(Boolean, nullable=False, default=True)
first_activity = Column(DateTime(timezone=True), nullable=True)
last_activity = Column(DateTime(timezone=True), nullable=True)
activity_freq = Column(Float, nullable=True)
activity_freq_variance = Column(Float, nullable=False, default=0)
npackets_up = Column(BigInteger, nullable=False, default=0)
npackets_down = Column(BigInteger, nullable=False, default=0)
npackets_lost = Column(Float, nullable=False, default=0)
max_rssi = Column(Float, nullable=True)
max_lsnr = Column(Float, nullable=True)
ngateways_connected_to = Column(BigInteger, nullable=False, default=0)
payload_size = Column(BigInteger, nullable=True)
last_packets_list = Column(String(4096), nullable=True, default='[]')
def to_json(self):
return {
'id': self.id,
'dev_eui': self.dev_eui,
'name': self.name,
'vendor': self.vendor,
'app_name': self.app_name,
'join_eui': self.join_eui,
'data_collector_id': self.data_collector_id,
'organization_id': self.organization_id,
'first_up_timestamp': "{}".format(self.first_up_timestamp),
'last_up_timestamp': "{}".format(self.last_up_timestamp),
'repeated_dev_nonce': self.repeated_dev_nonce,
'join_request_counter': self.join_request_counter,
'join_accept_counter': self.join_request_counter,
'has_joined': self.has_joined,
'join_inferred': self.join_inferred,
'is_otaa': self.is_otaa,
'last_packet_id': self.last_packet_id,
'connected': self.connected,
'last_activity': "{}".format(self.last_activity),
'activity_freq': self.activity_freq,
'activity_freq_variance': self.activity_freq_variance,
'importance': self.importance.value,
'npackets_up': self.npackets_up,
'npackets_down': self.npackets_down,
'npackets_lost': self.npackets_lost,
'max_rssi': self.max_rssi,
'pending_first_connection': self.pending_first_connection
}
@classmethod
def find(cls, organization_id, since, until, page, size):
query = cls.query.filter(cls.organization_id == organization_id)
if since:
query = query.filter(cls.last_up_timestamp >= since)
if until:
query = query.filter(cls.last_up_timestamp <= until)
query = query.order_by(desc(cls.last_up_timestamp))
if page is not None and size:
query = query.limit(size).offset(page*size)
return query.all()
@classmethod
def count_by_date(cls, organization_id, since, until):
query = db.session.query(func.date(cls.last_up_timestamp).label('date'), func.count(1).label('count'))\
.filter(cls.organization_id == organization_id)
if since:
query = query.filter(cls.last_up_timestamp >= since)
if until:
query = query.filter(cls.last_up_timestamp <= until)
query = query.group_by(func.date(cls.last_up_timestamp))
return query.all()
@classmethod
def count_by_hour(cls, organization_id, since, until):
query = db.session\
.query(func.date_trunc('hour', cls.last_up_timestamp).label('hour'), func.count(1).label('count'))\
.filter(cls.organization_id == organization_id)
if since:
query = query.filter(cls.last_up_timestamp >= since)
if until:
query = query.filter(cls.last_up_timestamp <= until)
query = query.group_by(func.date_trunc('hour', cls.last_up_timestamp))
return query.all()
class GatewayToDevice(db.Model):
__tablename__ = 'gateway_to_device'
gateway_id = Column(BigInteger, db.ForeignKey("gateway.id"), nullable=False, primary_key=True)
device_id = Column(BigInteger, db.ForeignKey("device.id"), nullable=False, primary_key=True)
class DeviceSession(db.Model):
__tablename__ = 'device_session'
id = Column(BigInteger, primary_key=True, autoincrement=True)
may_be_abp = Column(Boolean, nullable=True)
reset_counter = Column(Integer, nullable=False, default=0)
is_confirmed = Column(Boolean, nullable=True)
dev_addr = Column(String(8), nullable=False)
up_link_counter = Column(Integer, nullable=False, default=-1)
down_link_counter = Column(Integer, nullable=False, default=-1)
max_down_counter = Column(Integer, nullable=False, default=-1)
max_up_counter = Column(Integer, nullable=False, default=-1)
total_down_link_packets = Column(BigInteger, nullable=False, default=0)
total_up_link_packets = Column(BigInteger, nullable=False, default=0)
first_down_timestamp = Column(DateTime(timezone=True), nullable=True)
first_up_timestamp = Column(DateTime(timezone=True), nullable=True)
last_down_timestamp = Column(DateTime(timezone=True), nullable=True)
last_up_timestamp = Column(DateTime(timezone=True), nullable=True)
device_id = Column(BigInteger, ForeignKey("device.id"), nullable=True)
organization_id = Column(BigInteger, ForeignKey("organization.id"), nullable=False)
data_collector_id = Column(BigInteger, db.ForeignKey("data_collector.id"), nullable=False)
device_auth_data_id = Column(BigInteger, ForeignKey("device_auth_data.id"), nullable=True)
last_packet_id = Column(BigInteger, ForeignKey("packet.id"), nullable=True)
last_activity = Column(DateTime(timezone=True), nullable=False)
connected = Column(Boolean, nullable=False, default=True)
class Packet(db.Model):
__tablename__ = 'packet'
id = Column(BigInteger, primary_key=True, autoincrement=True)
date = Column(DateTime(timezone=True), nullable=False)
topic = Column(String(256), nullable=True)
data_collector_id = Column(BigInteger, ForeignKey("data_collector.id"), nullable=False)
organization_id = Column(BigInteger, ForeignKey("organization.id"), nullable=False)
gateway = Column(String(16), nullable=True)
tmst = Column(BigInteger, nullable=True)
chan = Column(SmallInteger, nullable=True)
rfch = Column(Integer, nullable=True)
seqn = Column(Integer, nullable=True)
opts = Column(String(20), nullable=True)
port = Column(Integer, nullable=True)
freq = Column(Float, nullable=True)
stat = Column(SmallInteger, nullable=True)
modu = Column(String(4), nullable=True)
datr = Column(String(50), nullable=True)
codr = Column(String(10), nullable=True)
lsnr = Column(Float, nullable=True)
rssi = Column(Integer, nullable=True)
size = Column(Integer, nullable=True)
data = Column(String(300), nullable=True)
m_type = Column(String(20), nullable=True)
major = Column(String(10), nullable=True)
mic = Column(String(8), nullable=True)
join_eui = Column(String(16), nullable=True)
dev_eui = Column(String(16), nullable=True)
dev_nonce = Column(Integer, nullable=True)
dev_addr = Column(String(8), nullable=True)
adr = Column(Boolean, nullable=True)
ack = Column(Boolean, nullable=True)
adr_ack_req = Column(Boolean, nullable=True)
f_pending = | |
is None:
percentile_delta = 0.005
max_values = self.extreme_values[:, :, 1].compressed()
min_values = self.extreme_values[:, :, 0].compressed()
# Remove masked values.
max_values.sort()
min_values.sort()
length = len(max_values)
index = int((1.0 - percentile_delta) * length)
max_val = max_values[index]
index = int(percentile_delta * length)
min_val = min_values[index]
# Exact fit.
elif float(self.vertical_scaling_range) == 0.0:
max_val = self.extreme_values[:, :, 1].max()
min_val = self.extreme_values[:, :, 0].min()
# Fit with custom range.
else:
max_val = min_val = abs(self.vertical_scaling_range) / 2.0
# Normalization factor.
self._normalization_factor = max(abs(max_val), abs(min_val)) * 2
# Scale from 0 to 1.
self.extreme_values = self.extreme_values / self._normalization_factor
self.extreme_values += 0.5
def __dayplotSetXTicks(self, *args, **kwargs): # @UnusedVariable
"""
Sets the xticks for the dayplot.
"""
localization_dict = kwargs.get('localization_dict', {})
localization_dict.setdefault('seconds', 'seconds')
localization_dict.setdefault('minutes', 'minutes')
localization_dict.setdefault('hours', 'hours')
localization_dict.setdefault('time in', 'time in')
max_value = self.width - 1
# Check whether it is sec/mins/hours and convert to a universal unit.
if self.interval < 240:
time_type = localization_dict['seconds']
time_value = self.interval
elif self.interval < 24000:
time_type = localization_dict['minutes']
time_value = self.interval / 60
else:
time_type = localization_dict['hours']
time_value = self.interval / 3600
count = None
# Hardcode some common values. The plus one is intentional. It had
# hardly any performance impact and enhances readability.
if self.interval == 15 * 60:
count = 15 + 1
elif self.interval == 20 * 60:
count = 4 + 1
elif self.interval == 30 * 60:
count = 6 + 1
elif self.interval == 60 * 60:
count = 4 + 1
elif self.interval == 90 * 60:
count = 6 + 1
elif self.interval == 120 * 60:
count = 4 + 1
elif self.interval == 180 * 60:
count = 6 + 1
elif self.interval == 240 * 60:
count = 6 + 1
elif self.interval == 300 * 60:
count = 6 + 1
elif self.interval == 360 * 60:
count = 12 + 1
elif self.interval == 720 * 60:
count = 12 + 1
# Otherwise run some kind of autodetection routine.
if not count:
# Up to 15 time units and if it's a full number, show every unit.
if time_value <= 15 and time_value % 1 == 0:
count = time_value
# Otherwise determine whether they are divisible for numbers up to
# 15. If a number is not divisible just show 10 units.
else:
count = 10
for _i in range(15, 1, -1):
if time_value % _i == 0:
count = _i
break
# Show at least 5 ticks.
if count < 5:
count = 5
# Everything can be overwritten by user-specified number of ticks.
if self.number_of_ticks:
count = self.number_of_ticks
# Calculate and set ticks.
ticks = np.linspace(0.0, max_value, count)
ticklabels = ['%i' % _i for _i in np.linspace(0.0, time_value, count)]
self.axis[0].set_xticks(ticks)
self.axis[0].set_xticklabels(ticklabels, rotation=self.tick_rotation,
size=self.x_labels_size)
self.axis[0].set_xlabel('%s %s' % (localization_dict['time in'],
time_type), size=self.x_labels_size)
def __dayplotSetYTicks(self, *args, **kwargs): # @UnusedVariable
"""
Sets the yticks for the dayplot.
"""
intervals = self.extreme_values.shape[0]
# Only display all ticks if there are five or less steps or if option
# is set.
if intervals <= 5 or self.one_tick_per_line:
tick_steps = list(range(0, intervals))
ticks = np.arange(intervals, 0, -1, dtype=np.float)
ticks -= 0.5
else:
tick_steps = list(range(0, intervals, self.repeat))
ticks = np.arange(intervals, 0, -1 * self.repeat, dtype=np.float)
ticks -= 0.5
# Complicated way to calculate the label of
# the y-axis showing the second time zone.
sign = '%+i' % self.time_offset
sign = sign[0]
label = "UTC (%s = UTC %s %02i:%02i)" % (
self.timezone.strip(), sign, abs(self.time_offset),
(self.time_offset % 1 * 60))
ticklabels = [(self.starttime + _i *
self.interval).strftime(self.tick_format)
for _i in tick_steps]
self.axis[0].set_yticks(ticks)
self.axis[0].set_yticklabels(ticklabels, size=self.y_labels_size)
# Show time zone label if requested
if self.show_y_UTC_label:
self.axis[0].set_ylabel(label)
if self.right_vertical_labels:
yrange = self.axis[0].get_ylim()
self.twin_x = self.axis[0].twinx()
self.twin_x.set_ylim(yrange)
self.twin_x.set_yticks(ticks)
y_ticklabels_twin = [(self.starttime + (_i + 1) *
self.interval).strftime(self.tick_format)
for _i in tick_steps]
self.twin_x.set_yticklabels(y_ticklabels_twin,
size=self.y_labels_size)
def plotSection(self, *args, **kwargs): # @UnusedVariable
"""
Plots multiple waveforms as a record section on a single plot.
"""
# Initialise data and plot
self.__sectInitTraces()
ax, lines = self.__sectInitPlot()
# Setting up line properties
for line in lines:
line.set_alpha(self.alpha)
line.set_linewidth(self.linewidth)
line.set_color(self.color)
# Setting up plot axes
if self.sect_offset_min is not None:
ax.set_xlim(left=self.__sectOffsetToFraction(self._offset_min))
if self.sect_offset_max is not None:
ax.set_xlim(right=self.__sectOffsetToFraction(self._offset_max))
# Set up offset ticks
tick_min, tick_max = \
self.__sectFractionToOffset(np.array(ax.get_xlim()))
if tick_min != 0.0 and self.sect_plot_dx is not None:
tick_min += self.sect_plot_dx - (tick_min % self.sect_plot_dx)
# Define tick vector for offset axis
if self.sect_plot_dx is None:
ticks = np.int_(np.linspace(tick_min, tick_max, 10))
else:
ticks = np.arange(tick_min, tick_max, self.sect_plot_dx)
if len(ticks) > 100:
self.fig.clf()
msg = 'Too many ticks! Try changing plot_dx.'
raise ValueError(msg)
ax.set_xticks(self.__sectOffsetToFraction(ticks))
# Setting up tick labels
ax.set_ylabel('Time [s]')
if not self.sect_dist_degree:
ax.set_xlabel('Offset [km]')
ax.set_xticklabels(ticks / 1e3)
else:
ax.set_xlabel(u'Offset [°]')
ax.set_xticklabels(ticks)
ax.minorticks_on()
# Limit time axis
ax.set_ylim([self._time_min, self._time_max])
if self.sect_recordstart is not None:
ax.set_ylim(bottom=self.sect_recordstart)
if self.sect_recordlength is not None:
ax.set_ylim(top=self.sect_recordlength + ax.get_ylim()[0])
# Invert time axis if requested
if self.sect_timedown:
ax.invert_yaxis()
# Draw grid on xaxis only
ax.grid(
color=self.grid_color,
linestyle=self.grid_linestyle,
linewidth=self.grid_linewidth)
ax.xaxis.grid(False)
def __sectInitTraces(self):
"""
Arrange the trace data used for plotting.
If necessary the data is resampled before
being collected in a continuous list.
"""
# Extract distances from st[].stats.distance
# or from st.[].stats.coordinates.latitude...
self._tr_offsets = np.empty(len(self.stream))
if not self.sect_dist_degree:
# Define offset in km from tr.stats.distance
try:
for _i, tr in enumerate(self.stream):
self._tr_offsets[_i] = tr.stats.distance
except:
msg = 'Define trace.stats.distance in meters to epicenter'
raise ValueError(msg)
else:
# Define offset as degree from epicenter
try:
for _i, tr in enumerate(self.stream):
self._tr_offsets[_i] = locations2degrees(
tr.stats.coordinates.latitude,
tr.stats.coordinates.longitude,
self.ev_coord[0], self.ev_coord[1])
except:
msg = 'Define latitude/longitude in trace.stats.' + \
'coordinates and ev_coord. See documentation.'
raise ValueError(msg)
# Define minimum and maximum offsets
if self.sect_offset_min is None:
self._offset_min = self._tr_offsets.min()
else:
self._offset_min = self.sect_offset_min
if self.sect_offset_max is None:
self._offset_max = self._tr_offsets.max()
else:
self._offset_max = self.sect_offset_max
# Reduce data to indexes within offset_min/max
mask = ((self._tr_offsets >= self._offset_min) &
(self._tr_offsets <= self._offset_max))
self._tr_offsets = self._tr_offsets[mask]
stream = [tr for m, tr in zip(mask, self.stream) if m]
# Normalized offsets for plotting
self._tr_offsets_norm = self._tr_offsets / self._tr_offsets.max()
# Number of traces
self._tr_num = len(self._tr_offsets)
# Arranging trace data in single list
self._tr_data = []
# Maximum counts, npts, starttime and delta of each selected trace
self._tr_starttimes = []
self._tr_max_count = np.empty(self._tr_num)
self._tr_npts = np.empty(self._tr_num)
self._tr_delta = np.empty(self._tr_num)
# TODO dynamic DATA_MAXLENGTH according to dpi
for _i, tr in enumerate(stream):
if len(tr.data) >= self.max_npts:
tmp_data = signal.resample(tr.data, self.max_npts)
else:
tmp_data = tr.data
# Initialising trace stats
self._tr_data.append(tmp_data)
self._tr_starttimes.append(tr.stats.starttime)
self._tr_max_count[_i] = tmp_data.max()
self._tr_npts[_i] = tmp_data.size
self._tr_delta[_i] = (
tr.stats.endtime -
tr.stats.starttime) / self._tr_npts[_i]
# Init time vectors
self.__sectInitTime()
def __sectScaleTraces(self):
"""
The traces have to be scaled to fit between 0-1., each trace
gets 1./num_traces space. adjustable by scale=1.0.
"""
self._sect_scale = self.sect_user_scale / (self._tr_num * 1.5)
def __sectInitTime(self):
"""
Define the time vector for each trace
"""
reftime = self.sect_reftime or min(self._tr_starttimes)
self._tr_times = []
for _tr in range(self._tr_num):
self._tr_times.append(
(np.arange(self._tr_npts[_tr]) +
(self._tr_starttimes[_tr] - reftime)) * self._tr_delta[_tr])
if self.sect_vred:
self._tr_times[-1] -= self._tr_offsets[_tr] / self.sect_vred
self._time_min = np.concatenate(self._tr_times).min()
self._time_max = np.concatenate(self._tr_times).max()
def __sectOffsetToFraction(self, offset):
"""
Helper function to return offsets from fractions
"""
return offset / self._tr_offsets.max()
def __sectFractionToOffset(self, fraction):
"""
Helper function to return fractions from offsets
"""
return fraction * self._tr_offsets.max()
def __sectInitPlot(self):
"""
Function initialises plot all the illustration is done by
self.plotSection()
"""
ax = self.fig.gca()
# Calculate normalizing factor
self.__sectNormalizeTraces()
# Calculate scaling factor
self.__sectScaleTraces()
lines = []
# ax.plot() preferred over containers
for _tr in range(self._tr_num):
# Scale, normalize and shift traces by offset for plotting
data = ((self._tr_data[_tr] / self._tr_normfac[_tr] *
self._sect_scale) +
self._tr_offsets_norm[_tr])
time = self._tr_times[_tr]
lines += ax.plot(data, time)
return ax, lines
def __sectNormalizeTraces(self):
"""
This helper function normalizes the traces
"""
self._tr_normfac = np.ones(self._tr_num)
if self.sect_norm_method == 'trace':
# Normalize against each traces' maximum
for tr in range(self._tr_num):
self._tr_normfac[tr] = np.abs(self._tr_data[tr]).max()
elif self.sect_norm_method == 'stream':
# Normalize the whole stream
tr_max_count_glob = np.abs(self._tr_max_count).max()
self._tr_normfac.fill(tr_max_count_glob)
else:
msg = | |
<filename>addon.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import base64
import hashlib
import html
import json
import random
import re
import string
import sys
import time
import urllib
import requests
# import xbmcgui
from bs4 import BeautifulSoup
from xbmcswift2 import Plugin, xbmcgui, xbmc, xbmcaddon, xbmcplugin
import danmuku
# class BPlayer(xbmc.Player):
# def __init__(self):
# xbmc.Player.__init__(self)
# def onAVStarted(self):
# global cid, dpath
# if xbmcplugin.getSetting(int(sys.argv[1]),'damakustatus') == 'true':
# dpath = xbmcplugin.getSetting(int(sys.argv[1]),'damakufolder')
# self.setSubtitles(os.path.join(dpath, "%s.ass" % (str(cid))))
def random_sentence(size):
char_lists = string.ascii_lowercase + string.digits
return ''.join(random.choice(char_lists) for _ in range(size))
def unescape(string):
string = urllib.parse.unquote(string).decode('utf8')
quoted = html.unescape(string)
# 转成中文
return re.sub(r'%u([a-fA-F0-9]{4}|[a-fA-F0-9]{2})', lambda m: str(int(m.group(1), 16)), quoted)
plugin = Plugin()
# uuid = xbmcplugin.getSetting(int(sys.argv[1]),'baipiao')
# if uuid == 'true':
# dialog = xbmcgui.Dialog()
# dialog.textviewer('错误提示', str(uuid))
# 超过10000换算
def zh(num):
if int(num) >= 100000000:
p = round(float(num) / float(100000000), 1)
p = str(p) + '亿'
else:
if int(num) >= 10000:
p = round(float(num) / float(10000), 1)
p = str(p) + '万'
else:
p = str(num)
return p
# 白嫖计算
def bp(li):
li = sorted(li)
minnum = li[0]
v = 0
for index in range(len(li)):
v += li[index] - minnum
v += minnum
return v
his = plugin.get_storage('his')
cache = plugin.get_storage('cache')
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36',
'Connection': 'close'}
mheaders = {
'user-agent': 'Mozilla/5.0 (Linux; Android 10; Z832 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Mobile Safari/537.36'}
# 仿b站随机输出主播正在xx
def rd_live_gz():
gz = ['思考人生', '抠脚丫', '俯卧撑热身', '卖萌', '打滚', '换女装', '觅食', '海扁小电视', '成为魔法少女', '修电锯', '跳广播体操', '吸猫', '渡劫中', '学习', '梳妆打扮',
'撩妹', '逛漫展', '拔腿毛', '逛b站']
return '主播正在' + gz[random.randint(0, (len(gz) - 1))] + '...'
# b站二级目录tid反查一级目录名字,没有api,只能自己造轮子
def two_one(tid):
# 动画区
douga = [1, 24, 25, 47, 86, 27]
# 番剧区
anime = [51, 152]
# 音乐区
music = [3, 28, 31, 30, 194, 59, 193, 29, 130]
# 国创区
guochuang = [153, 168, 169, 195, 170]
# 舞蹈区
dance = [129, 20, 198, 199, 200, 154, 156]
# 游戏区
game = [4, 17, 171, 172, 65, 173, 121, 136, 19]
# 科技区
technology = [36, 124, 122, 39, 96, 98, 176]
# 数码区
digital = [188, 95, 189, 190, 191]
# 生活区
life = [160, 138, 21, 76, 75, 161, 162, 163, 174]
# 鬼畜区
kichiku = [119, 22, 26, 126, 127]
# 时尚区
fashion = [155, 157, 158, 164, 159, 192]
# 广告区
ad = [165, 166]
# 娱乐区
ent = [5, 71, 137, 131]
# 影视区
cinephile = [181, 182, 183, 85, 184]
re = ''
if int(tid) in douga:
re = '动画'
if int(tid) in anime:
re = '番剧'
if int(tid) in music:
re = '音乐'
if int(tid) in guochuang:
re = '国创'
if int(tid) in dance:
re = '舞蹈'
if int(tid) in game:
re = '游戏'
if int(tid) in technology:
re = '科技'
if int(tid) in digital:
re = '数码'
if int(tid) in life:
re = '生活'
if int(tid) in kichiku:
re = '鬼畜'
if int(tid) in fashion:
re = '时尚'
if int(tid) in ad:
re = '广告'
if int(tid) in ent:
re = '娱乐'
if int(tid) in cinephile:
re = '影视'
if re == '':
re = '未知'
return re
# 显示等级颜色
def level_color(level):
if int(level) == 0:
lev = ' [COLOR grey]Lv.' + str(level) + '[/COLOR]'
if int(level) == 1:
lev = ' [COLOR grey]Lv.' + str(level) + '[/COLOR]'
if int(level) == 2:
lev = ' [COLOR green]Lv.' + str(level) + '[/COLOR]'
if int(level) == 3:
lev = ' [COLOR blue]Lv.' + str(level) + '[/COLOR]'
if int(level) == 4:
lev = ' [COLOR yellow]Lv.' + str(level) + '[/COLOR]'
if int(level) == 5:
lev = ' [COLOR orange]Lv.' + str(level) + '[/COLOR]'
if int(level) == 6:
lev = ' [COLOR red]Lv.' + str(level) + '[/COLOR]'
return lev
def sessdata(mode=''):
vipstatus = xbmcplugin.getSetting(int(sys.argv[1]), 'vipstatus')
sessdata = ''
if mode == 'vip' and vipstatus == 'true':
if xbmcplugin.getSetting(int(sys.argv[1]), 'vipsessdata') != '':
sessdata = 'SESSDATA=' + xbmcplugin.getSetting(int(sys.argv[1]), 'vipsessdata')
else:
if xbmcplugin.getSetting(int(sys.argv[1]), 'sessdata') != '':
sessdata = 'SESSDATA=' + xbmcplugin.getSetting(int(sys.argv[1]), 'sessdata')
return sessdata
def uid():
uid = xbmcplugin.getSetting(int(sys.argv[1]), 'uid')
return uid
def get_html(url, t=1, debug='no', head=''):
cachestatus = xbmcplugin.getSetting(int(sys.argv[1]), 'cachestatus')
if debug == 'no' and cachestatus == 'false':
if head == '':
if t == 1:
r = get_html_1min(url)
if t == 10:
r = get_html_10min(url)
if t == 60:
r = get_html_1hour(url)
else:
if t == 1:
r = get_html_1min(url, head=head)
if t == 10:
r = get_html_10min(url, head=head)
if t == 60:
r = get_html_1hour(url, head=head)
else:
if head == '':
r = requests.get(url, headers=headers)
r.encoding = 'utf-8'
r = r.text
else:
r = requests.get(url, headers=json.loads(head))
r.encoding = 'utf-8'
r = r.text
return r
@plugin.cached(TTL=60)
def get_html_1hour(url, head=''):
if head == '':
r = requests.get(url, headers=headers)
else:
r = requests.get(url, headers=json.loads(head))
r.encoding = 'utf-8'
r = r.text
return r
@plugin.cached(TTL=10)
def get_html_10min(url, head=''):
if head == '':
r = requests.get(url, headers=headers)
else:
r = requests.get(url, headers=json.loads(head))
r.encoding = 'utf-8'
r = r.text
return r
@plugin.cached(TTL=1)
def get_html_1min(url, head=''):
if head == '':
r = requests.get(url, headers=headers)
else:
r = requests.get(url, headers=json.loads(head))
r.encoding = 'utf-8'
r = r.text
return r
# 修改了API,参见Issue: https://github.com/MoyuScript/bilibili-api/issues/244
def get_up_roominfo(uid):
head = headers
head['Referer'] = 'https://www.bilibili.com'
return get_html(
'https://api.bilibili.com/x/space/acc/info?mid=' + str(uid),
head=json.dumps(head),
)
def get_up_baseinfo(uid):
r = get_html('https://api.bilibili.com/x/space/acc/info?mid=' + str(uid) + '&jsonp=jsonp', t=60)
return r
def get_upinfo(uid):
j = json.loads(get_up_baseinfo(uid))
u = j['data']
# up数据
di = up_allnum(uid)
# 最新数据
new = up_sort_vid(uid, '')
# 热门数据
click = up_sort_vid(uid, 'click')
# 热门数据
stow = up_sort_vid(uid, 'stow')
text = ''
# 大会员判断
vip = u''
if u['vip']['status'] == 1:
if u['vip']['type'] == 2:
vip += u'[COLOR pink][年度大会员][/COLOR]'
else:
vip += u'[COLOR pink][大会员][/COLOR]'
# 性别判断
if u['sex'] == u'男':
sex = u'[COLOR blue][♂][/COLOR]'
else:
if u['sex'] == u'女':
sex = u'[COLOR pink][♀][/COLOR]'
else:
sex = u'?'
text += u'UP主:' + u['name'] + u' 性别:' + sex + u' ' + level_color(u['level']) + vip + '\n'
if u['official']['role'] != 0:
text += u['official']['title'] + '\n'
if u['sign'] == '':
sign = u'这个人很懒,什么都没有写'
else:
sign = u['sign']
text += u'个性签名:' + sign + '\n'
text += u'生日:' + u['birthday'] + '\n'
text += u'----------' * 5 + u'up主大数据' + u'----------' * 5 + '\n\n'
if u['official']['role'] != 0:
text += u'「' + u['name'] + u'」是经过认证的「' + u['official']['title'] + u'」。' + '\n'
else:
text += u'「' + u['name'] + u'」是一个不太出名的up主。' + '\n'
tlist = new['list']['tlist']
try:
tt = list(tlist.keys())
ttt = []
for index in range(len(tt)):
ttt.append(tlist[tt[index]])
hotp = sorted(ttt, key=lambda x: x['count'], reverse=True)
text += u'TA是主要活跃在「' + hotp[0]['name'] + u'区」的UP主,在该分区共投稿「' + str(hotp[0]['count']) + u' 个稿件」' + '\n'
if two_one(click['list']['vlist'][0]['typeid']) != hotp[0]['name']:
text += u'然而TA在「' + two_one(click['list']['vlist'][0]['typeid']) + '」拥有着表现最好的作品' + '\n'
text += u'代表作是《 ' + click['list']['vlist'][0]['title'] + u'》。' + '\n'
jinqi = []
for index in range(len(new['list']['vlist'])):
jinqi.append(two_one(new['list']['vlist'][index]['typeid']))
jinqi2 = []
for index in range(len(jinqi)):
if jinqi[index] != max(jinqi, key=jinqi.count):
jinqi2.append(jinqi[index])
if jinqi2 != []:
if jinqi2.count(max(jinqi2, key=jinqi2.count)) < jinqi.count(max(jinqi, key=jinqi.count)):
text += u'近期,TA的投稿仍然大多在「' + max(jinqi, key=jinqi.count) + u'区」。' + '\n\n'
else:
text += u'虽然TA的投稿仍然大多在「' + max(jinqi, key=jinqi.count) + u'」,不过TA有向「' \
+ max(jinqi2, key=jinqi2.count) + u'」转型的可能性。' + '\n\n'
else:
text += u'近期,TA的投稿1000%在「' + max(jinqi, key=jinqi.count) + u'区」。' + '\n\n'
except AttributeError:
text += u'没有更多关于TA的情报信息了\n\n'
text += u'----------' * 5 + u'up主最新数据' + u'----------' * 5 + '\n\n'
if di['follower'] != -1:
text += u'粉丝总数:' + zh(di['follower']) \
+ u' 播放总数:' + zh(di['archive']) \
+ u' 获赞总数:' + zh(di['likes']) + u' 专栏阅读:' \
+ zh(di['article']) + '\n\n'
else:
text += u'请设置sessdata后显示\n\n'
try:
text += u'----------' * 5 + u'up主投稿分区' + u'----------' * 5 + '\n\n'
for index in range(len(hotp)):
co = u'|' * int((float(hotp[index]['count']) / float(new['page']['count'])) * 100)
if len(hotp[index]['name']) == 2:
name = hotp[index]['name'] + u'区'
else:
name = hotp[index]['name']
text += name + u':' + str(co) + u' ' + str(
round((float(hotp[index]['count']) / float(new['page']['count'])) * 100, 2)) + u'% - ' + str(
hotp[index]['count']) + u'个投稿\n'
except UnboundLocalError:
text += u'没有更多关于TA的情报信息了'
return text
# 最新投稿 ‘’ 播放最多 click 收藏最多stow
def up_sort_vid(uid, sort):
if sort == '':
so = ''
else:
so = '&order=' + sort
r = get_html('https://api.bilibili.com/x/space/arc/search?mid=' + uid + '&pn=1&ps=25' + so + '&jsonp=jsonp', t=10)
j = json.loads(r)
return j['data']
# up播放数据
def up_allnum(uid):
di = {}
r = get_html('https://api.bilibili.com/x/relation/stat?vmid=' + uid + '&jsonp=jsonp', | |
import numpy
import scipy.constants as codata
from numpy.testing import assert_almost_equal
import h5py
import time
# IMPORTANT: Column 11 (index 10) is wavenumber (cm^-1) as internally in Shadow
class Beam(object):
def __init__(self, N=1000, array=None):
"""
:param N:
:param array:
:return:
"""
if array is not None:
N, ncol = array.shape
if ncol != 18:
raise Exception ("Bad array shape: must be (npoints,18)")
self.rays = array.copy()
else:
self.rays = numpy.zeros((N,18))
@classmethod
def initialize_from_array(cls, array):
"""
:param array:
:return:
"""
if array.shape[1] != 18:
raise Exception("Bad array shape: must be (npoints,18)")
return Beam(array=array)
@classmethod
def initialize_as_pencil(cls, N=1000):
"""
:param array:
:return:
"""
beam = Beam(N)
beam.set_column(5,1.0) # Vy
beam.set_column(7,1.0) # Es
beam.set_column(10,1.0) # flag
beam.set_column(11,2*numpy.pi/1e-8) # wavenumber (1 A)
beam.set_column(12,numpy.arange(N,dtype=float)) # index
return beam
def duplicate(self):
return Beam.initialize_from_array(self.rays.copy())
#
# getters
#
def get_rays(self):
"""
:return: numpy array (npoints,18)
"""
return self.rays.copy()
def get_number_of_rays(self,nolost=0):
"""
:param nolost: flag (default=0)
:return: number of rays
"""
try:
w = self.get_column(10)
except Exception:
print("Error: Empty beam...")
return 0
if nolost == 0:
return w.size
if nolost == 1:
return numpy.array(numpy.where(w >= 0)).size
if nolost == 2:
return numpy.array(numpy.where(w < 0)).size
return self.rays.shape[0]
def get_photon_energy_eV(self,nolost=0):
"""
returns the array with photon energy
:param nolost: 0: all rays 1: good rays, 2: bad rays
:return: array
"""
A2EV = 2.0*numpy.pi/(codata.h*codata.c/codata.e*1e2)
return self.get_column(11,nolost=nolost) / A2EV
def get_photon_wavelength(self):
return 2*numpy.pi/self.get_column(11) * 1e-2
def get_intensity(self,nolost=0):
w = self.get_column(23,nolost=nolost)
return w.sum()
def get_column(self,column,nolost=0):
"""
Possible choice for column are:
1 X spatial coordinate [user's unit]
2 Y spatial coordinate [user's unit]
3 Z spatial coordinate [user's unit]
4 Xp direction or divergence [rads]
5 Yp direction or divergence [rads]
6 Zp direction or divergence [rads]
7 X component of the electromagnetic vector (s-polariz)
8 Y component of the electromagnetic vector (s-polariz)
9 Z component of the electromagnetic vector (s-polariz)
10 Lost ray flag
11 wavenumber (2 pi / lambda[cm])
12 Ray index
13 Optical path length
14 Phase (s-polarization) in rad
15 Phase (p-polarization) in rad
16 X component of the electromagnetic vector (p-polariz)
17 Y component of the electromagnetic vector (p-polariz)
18 Z component of the electromagnetic vector (p-polariz)
19 Wavelength [A]
20 R= SQRT(X^2+Y^2+Z^2)
21 angle from Y axis
22 the magnituse of the Electromagnetic vector
23 |E|^2 (total intensity)
24 total intensity for s-polarization
25 total intensity for p-polarization
26 K = 2 pi / lambda [A^-1]
27 K = 2 pi / lambda * col4 [A^-1]
28 K = 2 pi / lambda * col5 [A^-1]
29 K = 2 pi / lambda * col6 [A^-1]
30 S0-stokes = |Ep|^2 + |Es|^2
31 S1-stokes = |Ep|^2 - |Es|^2
32 S2-stokes = 2 |Es| |Ep| cos(phase_s-phase_p)
33 S3-stokes = 2 |Es| |Ep| sin(phase_s-phase_p)
:param column:
:return:
"""
if column <= 18:
out = self.rays[:,column-1]
else:
A2EV = 2.0*numpy.pi/(codata.h*codata.c/codata.e*1e2)
col = column - 1
ray = self.rays
if col==10: out = ray[:,col]/A2EV
if col==18: out = 2*numpy.pi*1.0e8/ray[:,10]
if col==19: out = numpy.sqrt(ray[:,0]*ray[:,0]+ray[:,1]*ray[:,1]+ray[:,2]*ray[:,2])
if col==20: out = numpy.arccos(ray[:,4])
if col==21: out = numpy.sqrt(numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [6,7,8,15,16,17] ]),axis=0))
if col==22: out = numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [6,7,8,15,16,17] ]),axis=0)
if col==23: out = numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [6,7,8] ]),axis=0)
if col==24: out = numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [15,16,17] ]),axis=0)
if col==25: out = ray[:,10]*1.0e8
if col==26: out = ray[:,3]*ray[:,10]*1.0e8
if col==27: out = ray[:,4]*ray[:,10]*1.0e8
if col==28: out = ray[:,5]*ray[:,10]*1.0e8
if col==29:
E2s = numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [6,7,8] ]),axis=0)
E2p = numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [15,16,17] ]),axis=0)
out = E2p+E2s
if col==30:
E2s = numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [6,7,8] ]),axis=0)
E2p = numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [15,16,17] ]),axis=0)
out = E2p-E2s
if col==31:
E2s = numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [6,7,8] ]),axis=0)
E2p = numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [15,16,17] ]),axis=0)
Cos = numpy.cos(ray[:,13]-ray[:,14])
out = 2*numpy.sqrt(E2s*E2p)*Cos
if col==32:
E2s = numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [6,7,8] ]),axis=0)
E2p = numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [15,16,17] ]),axis=0)
Sin = numpy.sin(ray[:,13]-ray[:,14])
out = 2*numpy.sqrt(E2s*E2p)*Sin
if col==33:
out = numpy.sum(numpy.array([ ray[:,i]*ray[:,i] for i in [6,7,8,15,16,17] ]),axis=0) *\
ray[:,10]/A2EV
if col==34:
out = numpy.abs(numpy.arcsin(ray[:,3]))
if col==35:
out = numpy.abs(numpy.arcsin(ray[:,5]))
if col==36:
f = self.getshonecol(10)
w = self.getshonecol(23)
xp = self.getshonecol(4)
if nolost == 1:
findices = numpy.where(f > 0.0)
if len(findices[0])==0:
col_mean = numpy.average(xp, weights=w)
else:
col_mean = numpy.average(xp[findices], weights=w[findices])
else:
col_mean = numpy.average(xp, weights=w)
out = numpy.abs(numpy.arcsin(xp - col_mean))
if col==37:
f = self.getshonecol(10)
w = self.getshonecol(23)
zp = self.getshonecol(6)
if nolost == 1:
findices = numpy.where(f > 0.0)
if len(findices[0])==0:
col_mean = numpy.average(zp, weights=w)
else:
col_mean = numpy.average(zp[findices], weights=w[findices])
else:
col_mean = numpy.average(zp, weights=w)
out = numpy.abs(numpy.arcsin(zp - col_mean))
if nolost == 0:
return out.copy()
if nolost == 1:
f = numpy.where(self.rays[:,9] > 0.0)
if len(f[0])==0:
print ('Beam.get_column: no GOOD rays, returning empty array')
return numpy.empty(0)
return out[f].copy()
if nolost == 2:
f = numpy.where(self.rays[:,9] < 0.0)
if len(f[0])==0:
print ('Beam.get_column: no BAD rays, returning empty array')
return numpy.empty(0)
return out[f].copy()
def get_columns(self,columns,nolost=0):
ret = []
if isinstance(columns, int): return self.get_column(columns,nolost=nolost)
for c in columns:
ret.append(self.get_column(c,nolost=nolost))
return numpy.array(tuple(ret))
def get_standard_deviation(self,col, nolost=1, ref=0):
'''
returns the standard deviation of one viariable in the beam
:param col: variable (shadow column number)
:param nolost: 0 = use all rays, 1=good only, 2= lost only
:param ref: 0 = no weight, 1=weight with intensity (col23)
:return:
'''
x = self.get_column(col,nolost=nolost)
if ref == 0:
return x.std()
else:
w = self.get_column(23,nolost=nolost)
average = numpy.average(x, weights=w)
variance = numpy.average( (x-average)**2, weights=w)
return(numpy.sqrt(variance))
def intensity(self,nolost=0):
w = self.get_column(23,nolost=nolost)
return w.sum()
def histo2(self,col_h,col_v,nbins=25,ref=23, nbins_h=None, nbins_v=None, nolost=0,xrange=None,yrange=None,
calculate_widths=1):
"""
performs 2d histogram to prepare data for a plotxy plot
It uses histogram2d for calculations
Note that this Shadow.Beam.histo2 was previously called Shadow.Beam.plotxy
:param col_h: the horizontal column
:param col_v: the vertical column
:param nbins: number of bins
:param ref :
0, None, "no", "NO" or "No": only count the rays
23, "Yes", "YES" or "yes": weight with intensity (look at col=23 |E|^2 total intensity)
other value: use that column as weight
:param nbins_h: number of bins in H
:param nbins_v: number of bins in V
:param nolost: 0 or None: all rays, 1=good rays, 2=only losses
:param xrange: range for H
:param yrange: range for V
:param calculate_widths: 0=No, 1=calculate FWHM (default), 2=Calculate FWHM and FW at 25% and 75% if Maximum
:return: a dictionary with all data needed for plot
"""
ticket = {'error':1}
if ref == None: ref = 0
if ref == "No": ref = 0
if ref == "NO": ref = 0
if ref == "no": ref = 0
if ref == "Yes": ref = 23
if ref == "YES": ref = 23
if ref == "yes": ref = 23
if ref == 1:
print("Shadow.Beam.histo2: Warning: weighting with column 1 (X) [not with intensity as may happen in old versions]")
if nbins_h == None: nbins_h = nbins
if nbins_v == None: nbins_v = nbins
# copy the inputs
ticket['col_h'] = col_h
ticket['col_v'] = col_v
ticket['nolost'] = nolost
ticket['nbins_h'] = nbins_h
ticket['nbins_v'] = nbins_v
ticket['ref'] = ref
(col1,col2) = self.get_columns((col_h,col_v),nolost=nolost)
if xrange==None: xrange = self.get_good_range(col_h,nolost=nolost)
if yrange==None: yrange = self.get_good_range(col_v,nolost=nolost)
if ref == 0:
weights = col1*0+1
else:
weights = self.get_column(ref,nolost=nolost)
(hh,xx,yy) = numpy.histogram2d(col1, col2, bins=[nbins_h,nbins_v], range=[xrange,yrange], normed=False, weights=weights)
ticket['xrange'] = xrange
ticket['yrange'] = yrange
ticket['bin_h_edges'] = xx
ticket['bin_v_edges'] = yy
ticket['bin_h_left'] = numpy.delete(xx,-1)
ticket['bin_v_left'] = numpy.delete(yy,-1)
ticket['bin_h_right'] = numpy.delete(xx,0)
ticket['bin_v_right'] = numpy.delete(yy,0)
ticket['bin_h_center'] = 0.5*(ticket['bin_h_left']+ticket['bin_h_right'])
ticket['bin_v_center'] = 0.5*(ticket['bin_v_left']+ticket['bin_v_right'])
ticket['histogram'] = hh
ticket['histogram_h'] = hh.sum(axis=1)
ticket['histogram_v'] = hh.sum(axis=0)
ticket['intensity'] = self.intensity(nolost=nolost)
ticket['nrays'] = self.get_number_of_rays(nolost=0)
ticket['good_rays'] = self.get_number_of_rays(nolost=1)
# CALCULATE fwhm
if calculate_widths > 0:
h = ticket['histogram_h']
tt = numpy.where(h>=max(h)*0.5)
if h[tt].size > 1:
binSize = ticket['bin_h_center'][1]-ticket['bin_h_center'][0]
ticket['fwhm_h'] = binSize*(tt[0][-1]-tt[0][0])
ticket['fwhm_coordinates_h'] = (ticket['bin_h_center'][tt[0][0]],ticket['bin_h_center'][tt[0][-1]])
else:
ticket["fwhm_h"] = None
h = ticket['histogram_v']
tt = numpy.where(h>=max(h)*0.5)
if h[tt].size > 1:
binSize = ticket['bin_v_center'][1]-ticket['bin_v_center'][0]
ticket['fwhm_v'] = binSize*(tt[0][-1]-tt[0][0])
ticket['fwhm_coordinates_v'] = (ticket['bin_v_center'][tt[0][0]],ticket['bin_v_center'][tt[0][-1]])
else:
ticket["fwhm_v"] = None
if calculate_widths == 2:
# CALCULATE FW | |
import numpy as np
import pytest
from shapecheck import (ShapeError, check_shapes, is_checking_enabled, is_compatible,
set_checking_enabled, str_to_shape)
from .utils import CaptureStdOut
def test_basic():
@check_shapes('3', '4', out_='2')
def f(x, y):
return x[:2]**2 + y[:2]**2
f(np.array([1, 2, 3]), np.array([1, 2, 3, 4]))
with pytest.raises(ShapeError):
f(np.array([1, 2, 3]), np.array([2, 3, 4]))
def test_named_dim():
@check_shapes('3,N', 'N', out_='1,N')
def f(x, y):
return (x + y).sum(0, keepdims=True)
f(np.ones((3, 5)), np.ones((5,)))
with pytest.raises(ShapeError):
f(np.ones((3, 4)), np.ones((5,)))
def test_named_dim_one_arg():
@check_shapes('A,A,N', out_='N')
def f(x):
return x.sum((0, 1))
f(np.ones((5, 5, 7)))
with pytest.raises(ShapeError):
f(np.ones((6, 5, 7)))
def test_any_dim():
@check_shapes('N,-1', out_='N,1')
def f(x):
return x.sum(-1, keepdims=True)
f(np.ones((5, 3)))
f(np.ones((5, 7)))
def test_ndim_mismatch():
@check_shapes('-1,-1')
def f(x):
return x
f(np.ones((1, 2)))
with pytest.raises(ShapeError):
f(np.ones((1,)))
with pytest.raises(ShapeError):
f(np.ones((1, 2, 3)))
def test_no_stdout():
# Prevent pushing debug messages.
with CaptureStdOut() as output:
@check_shapes('3,A,A,N', out_='N')
def f(x):
return x.sum((0, 2, 1))
f(np.ones((3, 5, 5, 7)))
with pytest.raises(ShapeError):
f(np.ones((3, 6, 5, 7)))
assert len(output) == 0
def test_readme_example():
import numpy as np
from shapecheck import check_shapes
@check_shapes('-1,N', 'N', None, '3,N', out_='3,N')
def f(a, b, c, d):
return (a + b).sum(0, keepdims=True) + d
f(np.ones((7, 5)), np.ones(5), 'anything', np.ones((3, 5))) # succeeds
f(np.ones((2, 6)), np.ones(6), np.ones(1), np.ones((3, 6))) # succeeds
with pytest.raises(ShapeError):
f(np.ones((2, 6)), np.ones(5), np.ones(1), np.ones((3, 6))) # fails
@check_shapes('1,...,1', '...,1,1')
def g(a, b):
pass
g(np.ones((1, 3, 4, 1)), np.ones((2, 1, 1))) # succeeds
g(np.ones((1, 1)), np.ones((1, 1))) # succeeds
with pytest.raises(ShapeError):
g(np.ones((2, 3, 4, 1)), np.ones((1, 1))) # fails
@check_shapes('batch,variadic...', 'variadic...')
def h(a, b):
pass
h(np.ones((7, 1, 2)), np.ones((1, 2))) # succeeds
with pytest.raises(ShapeError):
h(np.ones((6, 2)), np.ones((1, 1))) # fails
with pytest.raises(ShapeError):
h(np.ones((6, 2)), np.ones((1))) # fails
def test_non_array_args():
@check_shapes(None, '2,N', None)
def f(x, y, z):
return 1
f('some string', np.ones((2, 5)), np.ones((5,)))
f(np.ones((1, 2, 3)), np.ones((2, 6)), 'non-array object')
with pytest.raises(ShapeError):
f(np.ones((1, 1)), np.ones((3, 5)), np.ones((5,)))
with pytest.raises(ShapeError):
f('another-test', np.ones((3, 6)), 'non-array object')
@pytest.mark.parametrize('string, shape', [('N,1,3,M', ('N', 1, 3, 'M')),
('N, 1, 3, M', ('N', 1, 3, 'M')),
('...,a,1', ('...', 'a', 1)),
('1, ... ,2', (1, '...', 2)),
('a,b,c,...', ('a', 'b', 'c', '...')),
('...', ('...',))])
def test_shape_to_str(string, shape):
result = str_to_shape(string)
for a, b in zip(shape, result):
assert a == b, f'Expected: {shape} Got: {result}'
@pytest.mark.parametrize('string', [
'...,...,...', 'a,...,b,...', '...,1,...', (1, 2), 3, 4.0, [5.0], ['1,2'], ('1,2',)
])
def test_shape_to_str_error(string):
with pytest.raises(RuntimeError):
str_to_shape(string)
@pytest.mark.parametrize('shape, expected_shape', [
((3, 2, 3), ('n', 2, 'n')),
((3, 2, 3), ('n', '...', 2, 'n')),
((3, 1, 1, 2, 3), ('n', '...', 2, 'n')),
((3, 2, 3), ('...', 'n', 2, 'n')),
((1, 1, 3, 2, 3), ('...', 'n', 2, 'n')),
((3, 2, 3), ('n', 2, 'n', '...')),
((3, 2, 3, 1, 1), ('n', 2, 'n', '...')),
((3, 2, 3), ('...',)),
])
def test_compatible_variadic_shapes(shape, expected_shape):
assert is_compatible(shape, expected_shape)
@pytest.mark.parametrize('shape, expected_shape', [
((3, 3, 3), ('n', 2, 'n')),
((3, 2, 4), ('n', '...', 2, 'n')),
((3, 1, 1, 3, 3), ('n', '...', 2, 'n')),
((4, 2, 3), ('...', 'n', 2, 'n')),
((1, 1, 2, 3), ('...', 'n', 2, 'n')),
((3, 3), ('n', 2, 'n', '...')),
((2, 3, 1, 1), ('n', 2, 'n', '...')),
])
def test_incompatible_variadic_shapes(shape, expected_shape):
assert not is_compatible(shape, expected_shape)
@pytest.mark.parametrize('e_shape1, e_shape2, shape1, shape2', [
(('n...,1,1', 'n...', (1, 2, 3, 1, 1), (1, 2, 3))),
(('...,1,1', 'n...', (1, 2, 3, 1, 1), (1, 2, 3))),
(('n...,2,2', '1,n...', (2, 2), (1,))),
(('n...,1,1', 'a...', (1, 2, 3, 1, 1), (1, 3))),
(('1,2,a...,3,4', '6,a...,7', (1, 2, 9, 9, 3, 4), (6, 9, 9, 7))),
(('1,2,a...,3,4', '6,a...,7', (1, 2, 9, 3, 4), (6, 9, 7))),
(('1,2,a...,3,4', '6,a...,7', (1, 2, 3, 4), (6, 7))),
])
def test_named_variadic_shapes(e_shape1, e_shape2, shape1, shape2):
@check_shapes(e_shape1, e_shape2)
def f(a, b):
pass
f(np.ones(shape1), np.ones(shape2))
@pytest.mark.parametrize('e_shape1, e_shape2, shape1, shape2', [
(('n...,1,1', 'n...', (1, 2, 3, 1, 1), (1, 3, 3))),
(('n...,1,1', 'n...', (1, 2, 3, 1, 1), (1, 3))),
(('n...,2,2', '1,n...', (2, 2), (1, 1))),
(('n...,2,2', 'n...', (2, 2), (1,))),
(('n...,', 'n...', (2, 2), (1,))),
(('1,2,a...,3,4', '6,a...,7', (1, 2, 8, 9, 3, 4), (6, 9, 9, 7))),
(('1,2,a...,3,4', '6,a...,7', (1, 2, 7, 3, 4), (6, 9, 7))),
(('1,2,a...,3,4', '6,a...,7', (1, 2, 3, 4), (6, 1, 7))),
])
def test_bad_named_variadic_shapes(e_shape1, e_shape2, shape1, shape2):
@check_shapes(e_shape1, e_shape2)
def f(a, b):
pass
with pytest.raises(ShapeError):
f(np.ones(shape1), np.ones(shape2))
def test_incompatible_output():
@check_shapes(out_='1,1')
def f():
return np.ones((1,))
with pytest.raises(ShapeError):
f()
def test_nested_structs():
@check_shapes(('N,1', 'N'), '1,2', out_={'one': ('N,1', 'N'), 'two': ('1,2')})
def f(one, two):
return {'one': one, 'two': two}
f((np.ones((7, 1)), np.ones((7,))), np.ones((1, 2)))
with pytest.raises(ShapeError):
f((np.ones((7, 1)), np.ones((6,))), np.ones((1, 2)))
def test_readme_nested_example():
@check_shapes(('N,1', 'N'), '1,2', out_={'one': ('N,1', 'N'), 'two': ('1,2')})
def f(one, two):
return {'one': (one[1], one[1]), 'two': two.sum()}
with pytest.raises(ShapeError):
f((np.ones((7, 1)), np.ones((7,))), np.ones((1, 2)))
def test_readme_set_checking_enabled():
from shapecheck import is_checking_enabled, set_checking_enabled
assert is_checking_enabled()
set_checking_enabled(False)
assert not is_checking_enabled()
set_checking_enabled(True)
assert is_checking_enabled()
with set_checking_enabled(False):
assert not is_checking_enabled()
assert is_checking_enabled()
def test_set_checking_enabled():
@check_shapes('3', '4', out_='2')
def f(x, y):
return x[:2]**2 + y[:2]**2
set_checking_enabled(False)
assert not is_checking_enabled()
f(np.array([1, 2, 3]), np.array([1, 2, 3, 4]))
f(np.array([1, 2, 3]), np.array([2, 3, 4]))
@check_shapes('3', '4', out_='2')
def g(x, y):
return x[:2]**2 + y[:2]**2
set_checking_enabled(True)
assert is_checking_enabled()
with pytest.raises(ShapeError):
f(np.array([1, 2, 3]), np.array([2, 3, 4]))
with pytest.raises(ShapeError):
g(np.array([1, 2, 3]), np.array([2, 3, 4]))
def test_set_checking_enabled_context():
@check_shapes('3', '4', out_='2')
def f(x, y):
return x[:2]**2 + y[:2]**2
assert is_checking_enabled()
with set_checking_enabled(False):
assert not is_checking_enabled()
f(np.array([1, 2, 3]), np.array([1, 2, 3, 4]))
f(np.array([1, 2, 3]), np.array([2, 3, 4]))
@check_shapes('3', '4', out_='2')
def g(x, y):
return x[:2]**2 + y[:2]**2
assert is_checking_enabled()
with pytest.raises(ShapeError):
f(np.array([1, 2, 3]), np.array([2, 3, 4]))
with pytest.raises(ShapeError):
g(np.array([1, 2, 3]), np.array([2, 3, 4]))
def test_match_callees():
@check_shapes('N', 'M', 'O', out_='N')
def f(x, y, z):
return x
@check_shapes('N', 'M', 'R', match_callees_=True)
def g(x, y, z):
return f(x, y, z)
g(np.ones(5), np.ones(6), np.ones(7))
def test_match_callees_error():
@check_shapes('N', 'M', 'O', out_='N')
def f(x, y, z):
return x
@check_shapes('M', 'N', 'R', match_callees_=True)
def g(x, y, z):
return f(x, y, z)
with pytest.raises(ShapeError):
g(np.ones(5), np.ones(6), np.ones(7))
def test_match_callees_complex():
@check_shapes('a, v...', 'v...', out_='v...')
def f(x, y):
return x.sum(0) + y
@check_shapes('v...')
def g(x):
return x.sum()
@check_shapes('a', match_callees_=True)
def h(x):
a = np.ones((x.shape[0], 2, 3, 4))
b = np.ones((2, 3, 4))
f(a, b)
return g(np.ones((5, 4, 3)))
h(np.ones((8)))
@check_shapes('a', match_callees_=True)
def h(x):
a = np.ones((x.shape[0] - 1, 2, 3, 4))
b = np.ones((2, 3, 4))
f(a, b)
return g(np.ones((5, 4, 3)))
with pytest.raises(ShapeError):
h(np.ones((8)))
def test_match_callees_readme():
@check_shapes('M', 'N', 'O', out_='M')
def child_fn(a, b, c):
return a
@check_shapes('M', 'N', 'R')
def parent_fn_1(x, y, z):
return child_fn(y, x, z)
@check_shapes('M', 'N', 'R', match_callees_=True)
def parent_fn_2(x, y, z):
return child_fn(y, x, z)
parent_fn_1(np.ones(5), np.ones(6), np.ones(7)) # succeeds
with pytest.raises(ShapeError):
parent_fn_2(np.ones(5), np.ones(6), np.ones(7)) # fails
@pytest.mark.parametrize('cs_args, cs_kwargs, f_args, f_kwargs', [
(('N', 'M', 'O', 'P'), {}, (1, 2, 3), {}),
(('N', 'M', 'O', 'P'), {}, (1, 2), {'c': 3}),
(('N', 'M', 'O',), {}, (1, 2, 3), {}),
(('N', 'M'), {}, (1, 2), {'c': 3}),
(('N', 'M', 'O', 'P'), {}, (1,), {'c': 3, 'b': 2}),
(('N', 'M', 'O'), {'d': 'P'}, (1, 2, 3), {}),
(('N', 'M'), {'c': 'O', 'd': 'P'}, (1, 2, 3), {}),
(('N',), {'b': 'M', 'c': 'O', 'd': 'P'}, (1, 2), {'c': 3}),
((), {'a': 'N', 'b': 'M', 'c': 'O', 'd': 'P'}, (1, 2, 3), {}),
((), {'a': 'N', 'b': 'M', 'c': 'O', 'd': 'P'}, (1, 2), {'c': 3}),
]) # yapf: disable
def test_check_shapes_signature(cs_args, cs_kwargs, f_args, f_kwargs):
# TODO: write more rigorous shape signature tests
@check_shapes(*cs_args, **cs_kwargs)
def f(a, b, c, *, d):
pass
f_kwargs = {k: np.ones(v) for k, v in f_kwargs.items()}
f(*map(np.ones, f_args), d=np.ones(4), **f_kwargs)
def test_readme_example2():
# yapf: disable
@check_shapes({'imgs': 'N,W,W,-1', 'labels': 'N,1'}, 'N', None, out_='')
def loss_fn(batch, arg2, arg3):
diff = (batch['imgs'].mean((1, 2, 3)) - batch['labels'].squeeze())
return np.mean(diff**2 + arg2)
loss_fn({'imgs': np.ones((3, 2, 2, 1)), 'labels': np.ones((3, 1))},
arg2=np.ones(3), arg3=np.ones((2, 3))) # succeeds
loss_fn({'imgs': np.ones((5, 3, 3, 4)), 'labels': np.ones((5, 1))},
arg2=np.ones(5), arg3='any') # succeeds
with pytest.raises(ShapeError):
loss_fn({'imgs': np.ones((3, 5, 2, 1)), 'labels': np.ones((3, 1))},
arg2=np.ones(3), arg3='any') # fails
# yapf: enable
def test_readme_example3():
@check_shapes({'imgs': 'N,W,W,-1', 'labels': 'N,1'}, aux_info=None, out_='')
def loss(batch, aux_info):
# do something with aux_info
diff = (batch['imgs'].mean((1, 2, 3)) - batch['labels'].squeeze())
return np.mean(diff**2)
loss({'imgs': np.ones((3, 2, 2, 1)), 'labels': np.ones((3, 1))}, np.ones(1))
loss({'imgs': np.ones((5, 3, 3, 4)), 'labels': np.ones((5, 1))}, 'any')
with pytest.raises(ShapeError):
loss({'imgs': np.ones((3, 5, 2, 1)), 'labels': np.ones((3, 1))}, 'any')
@pytest.mark.parametrize('inp, out', [(1, 1), (np.array(2), 2), (3, np.array(4)),
(np.array(5), np.array(6))])
def test_scalar_output(inp, out):
@check_shapes(x='', out_='')
def loss_fn(x):
| |
choice = await self.wait_for('message', check=check)
while choice.content not in ('1', '2', '/стоп'):
await message.channel.send(user_player + ', чтобы ответить,'
' введите один из следующих вариантов: \n1\n2\n/стоп')
choice = await self.wait_for('message', check=check)
if choice.content == '/стоп':
# игрок отказался играть. В конце блока игры его статус автоматически поменяется.
pass
elif choice.content == '1':
# генерируем число, выводим быки и коровы, пока игрок не выиграет
answer = Bnc.generate_answer()
await message.channel.send('Вы в одиночной игре, ' + user_player + '! Бот уже загадал число,'
' попробуйте угадать его.'
' Введите четырехзначное число'
' с неповторяющимися цифрами.')
win = False
number = 1
user_input = await bnc_user_input()
# количество попыток
while not win:
if user_input == '/стоп':
break
bulls_count, cows_count = Bnc.bulls_n_cows(user_input, answer)
bulls, cows = Bnc.bulls_n_cows_morph(bulls_count, cows_count)
await message.channel.send(user_player + f"\n{number} попытка. Ваше число {user_input}."
f" У вас {bulls} и {cows}.")
if bulls_count == 4:
win = True
break
else:
await message.channel.send('Введите четырехзначное число с неповторяющимися цифрами.')
user_input = await bnc_user_input()
number += 1
if win:
morph = pymorphy2.MorphAnalyzer()
await message.channel.send('Невероятная победа, ' + user_player + '! Вы сделали это'
' всего за ' + str(number)
+ ' ' +
morph.parse('попытку')[0].make_agree_with_number(number).word + '.')
else:
await message.channel.send(user_player + ', вы играете против бота. Для того, чтобы решить,'
' кто будет ходить первым, бот использует бинарную'
' монетку. Выберите 0 или 1.\nВо время вашего хода также'
' будет доступна команда "/история", эта команда покажет'
' все ваши попытки и ответы соперника.')
# определяет, кто ходит первым.
bin_coin = str(random.choice((0, 1)))
choice = await self.wait_for('message', check=check)
while choice.content not in ('1', '0', '/стоп'):
await message.channel.send(user_player + ', выберите\n0\tили\t1\n Для прекращения игры '
'напишите команду "/стоп"')
choice = await self.wait_for('message', check=check)
# объект класса Быки и Коровы, в игре против бота используются все его функции.
game = Bnc()
# 0 означает, что игра в процессе. 1 - что игрок победил. 2 - что победил бот.
# -1 - что игра была прервана потому, что игрок жульничал, или потому, что он ее прервал.
playing = 0
# True, если сейчас ход игрока
player_turn = False
# ведет подсчет попыток игрока
if choice.content == '/стоп':
playing = -1
elif choice.content == bin_coin:
player_turn = True
await message.channel.send('Вы угадали, ' + user_player + '.')
else:
await message.channel.send('Вы не угадали, ' + user_player + '. ')
# игра длится до остановки командой или победы одной из сторон
while playing == 0:
if player_turn:
await message.channel.send(user_player + ', введите четырехзначное число '
'с неповторяющимися цифрами. Также вы можете'
' ввести команду "/история".')
user_input = await bnc_user_input(history=game.history)
if user_input == '/стоп':
playing = -1
break
bulls_count, cows_count = game.bulls_n_cows(user_input, game.answer)
# считаем быков и коров, и, если они подходят под условие, генерируем число заново,
# в связи с историей попыток.
if bulls_count >= 2 or cows_count >= 3 or bulls_count + cows_count in (4, 0):
game.cheat(user_input)
bulls_count, cows_count = game.bulls_n_cows(user_input, game.answer)
# добавляем в историю попытку и ее результаты
game.history.append([user_input, bulls_count, cows_count])
bulls, cows = game.bulls_n_cows_morph(bulls_count, cows_count)
await message.channel.send(user_player + f"\nВаша {len(game.history)} попытка. Ваше число"
f" {user_input}. У вас {bulls} и {cows}.")
if bulls_count == 4:
# игрок победил
await message.channel.send('Вы победили, ' + user_player + '! Я загадал число '
+ str(game.answer))
playing = 1
player_turn = False
else:
guess = None
while True:
if len(game.guess_space) == 0:
await message.channel.send(user_player + ', вы попытались обмануть бота. '
'Вы проиграли.')
playing = -1
break
guess = random.choice(list(game.guess_space))
game.guess_space.remove(guess)
if game.is_compatible(guess):
break
# если бот обнаружил, что игрок жульничает - прерываем игру
if playing != 0:
break
await message.channel.send(user_player + ', я думаю, что вы загадали число '
+ str(guess) + '\nВведите через пробел количество быков и коров.'
' (например -- 0 2)')
bulls_n_cows = await self.wait_for('message', check=check)
bulls_n_cows = bulls_n_cows.content.split(' ')
while len(bulls_n_cows) != 2 or not all(j in [str(d) for d in range(0, 5)]
for j in bulls_n_cows) \
or sum([int(c) for c in bulls_n_cows]) > 4:
if bulls_n_cows == ['/стоп']:
playing = -1
break
await message.channel.send(user_player + ', введите через пробел количество'
' "быков" и "коров".\nЕсли в названном числе '
'цифра какого-то разряда совпала с цифрой'
' в том же разряде правильного ответа, эт'
'о называется "быком". Если указанная циф'
'ра есть в ответе, но на неверной позиции,'
' это "корова". Пример -- у чисел 1234 и 5631 '
' 1 "бык" (это цифра 3) и 1 "корова"'
' (это цифра 1). Сумма "быков" и "коров" не может'
' быть больше 4.')
bulls_n_cows = await self.wait_for('message', check=check)
bulls_n_cows = bulls_n_cows.content.split(' ')
# это условие приходится дублировать из-за того, что во время хода бота 2 варианта
# прерывания игры. 1 - игрок жульничал. 2 - игрок прервал игру. В обоих случаях игра
# должна прекратиться незамедлительно.
if playing != 0:
break
game.historys.append((guess, int(bulls_n_cows[0]), int(bulls_n_cows[1])))
bulls, cows = game.bulls_n_cows_morph(bulls_n_cows[0], bulls_n_cows[1])
await message.channel.send(user_player + f"\nМоя {len(game.history) + 1} попытка. Мое число"
f" {guess}. У меня {bulls} и {cows}.")
if bulls_n_cows[0] == 4:
# бот победил
await message.channel.send('Бот победил, ' + user_player + '! Вы загадали число '
+ str(guess))
playing = 2
player_turn = True
if playing != -1:
await message.channel.send('Спасибо за игру! Если вы желаете еще поиграть --'
' введите команду "/игры".')
await message.channel.send(f'Игра окончена, {user_player}. Если желаете еще раз сыграть в эту или'
f' иную игру -- введите команду "/игры".')
# запуск игры "Кости"
elif message.content == '/кости':
# изменение статуса.
await self.db_edit(message.author.name + message.author.discriminator, 'dices', user_chan_guild)
# объяснение правил игры
await message.channel.send('Хорошо, ' + user_player + '! Правила таковы -- у вас ровно 100 монет. Вам нужно'
' увеличить их количество. На каждый бросок можно с'
'делать ставку, от 5 до 20 монет. Ставка делается '
'на сумму цифр, которые будет на верхн(их/ей) гран(я'
'х/и) кост(ей/и) после броска. Также вы можете '
'выбрать какие кости будете бросать. Кости каждый р'
'аз выбираются случайно, из следующих вариантов:'
'\n\tодна шестигранная кость, коэффициент ставки - 3.'
'\n\tдве шестигранные кости коэффициент ставки - 6'
'\n\tодна восьмигранная кость, коэффициент ставки - '
'4\n\tдве восьмигранные кости, коэффициент ставки - '
'8\n\tодна двадцатигранная кость,'
' коэффициент ставки - 10\nТакже вам всегда будет д'
'оступна моентка со стабильным коэффициентом 2.\n'
'Коэффициент ставки - это то число, на которое '
'будет умножена ваша ставка. При проигрыше у вас '
'вычтут вашу ставку. Но есть одно условие - ,'
' все коэффициенты, кроме стабильного, варируются'
' от 2 до самих себя.\nЕсли вы будете'
' играть, то выберите число, которого хотите '
'достигнуть, из нижеперечисленных. В противном случ'
'ае, напишите команду "/стоп"\n'
'200 | 300 | 500 | 1000 | /стоп')
choice = await self.wait_for('message', check=check)
# проверка на правильный ввод
while choice.content not in ('200', '300', '/стоп', '500', '1000'):
await message.channel.send(user_player + ', чтобы ответить,'
' введите один из следующих вариантов: \n200\n300\n500\n100'
'0\n/стоп')
choice = await self.wait_for('message', check=check)
if choice.content == '/стоп':
# игрок отказался играть. В конце блока игры его статус автоматически поменяется.
pass
else:
start_cash = 100
end_cash = int(choice.content)
# начальные и стартовые суммы, словарь названий костей и их коэффициентов.
dash_set = {'один шестигранник': 3,
'два шестигранника': 6,
'один восьмигранник': 4,
'два восьмигранника': 8,
'один двадцатигранник': 10}
# все возможные результаты бросков для разных наборов костей.
values = {'один шестигранник': range(1, 7),
'два шестигранника': range(2, 13),
'один восьмигранник': range(1, 9),
'два восьмигранника': range(2, 17),
'один двадцатигранник': range(1, 21),
'монета': range(1, 3)}
# использовалась ли монета в прошлый раз.
d2_used = False
# пока игрок не проиграет, или не выиграет.
while start_cash != 0 or start_cash != end_cash:
# экспериментальным путем было определено, что именно такая генерация
random.seed(random.randint(10 ** 10, 10 ** 20))
# те наборы кубиков, которые буду предоставлены игроку в этот раз.
cur_set = [random.choice([d for d in dash_set.keys()]) for _ in range(2)]
for i in range(len(cur_set)):
# устранение и замена дупликатов.
while cur_set.count(cur_set[i]) > 1:
del cur_set[i]
cur_set.append(random.choice([d for d in dash_set.keys()]))
cur_set[i] = f'{i + 1}){cur_set[i]} -- {str(random.randint(2, dash_set[cur_set[i]]))}'
if not d2_used:
cur_set.append('3)монета -- 2')
else:
d2_used | |
<gh_stars>10-100
# -*- coding: utf-8 -*-
# Copyright 2022, SERTIT-ICube - France, https:#sertit.unistra.fr/
# This file is part of eoreader project
# https:#github.com/sertit/eoreader
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http:#www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Sentinel-3 OLCI products
.. WARNING:
Not georeferenced NetCDF files are badly opened by GDAL and therefore by rasterio !
-> use xr.open_dataset that manages that correctly
"""
import logging
from pathlib import Path
from typing import Union
import numpy as np
import rasterio
import xarray as xr
from cloudpathlib import CloudPath
from rasterio.enums import Resampling
from sertit import rasters, rasters_rio
from sertit.rasters import MAX_CORES, XDS_TYPE
from sertit.vectors import WGS84
from eoreader import cache, utils
from eoreader.bands import BandNames
from eoreader.bands import OpticalBandNames as obn
from eoreader.exceptions import InvalidProductError, InvalidTypeError
from eoreader.products import S3DataType, S3Instrument, S3Product, S3ProductType
from eoreader.reader import Platform
from eoreader.utils import EOREADER_NAME
LOGGER = logging.getLogger(EOREADER_NAME)
# FROM SNAP:
# https://github.com/senbox-org/s3tbx/blob/197c9a471002eb2ec1fbd54e9a31bfc963446645/s3tbx-rad2refl/src/main/java/org/esa/s3tbx/processor/rad2refl/Rad2ReflConstants.java#L97
# Not used for now
OLCI_SOLAR_FLUXES_DEFAULT = {
obn.Oa01: 1714.9084,
obn.Oa02: 1872.3961,
obn.CA: 1926.6102,
obn.BLUE: 1930.2483,
obn.Oa05: 1804.2762,
obn.GREEN: 1651.5836,
obn.YELLOW: 1531.4067,
obn.RED: 1475.615,
obn.Oa09: 1408.9949,
obn.Oa10: 1265.5425,
obn.VRE_1: 1255.4227,
obn.VRE_2: 1178.0286,
obn.Oa13: 955.07043,
obn.Oa14: 914.18945,
obn.Oa15: 882.8275,
obn.VRE_3: 882.8275,
obn.NIR: 882.8275,
obn.NARROW_NIR: 882.8275,
obn.Oa18: 882.8275,
obn.Oa19: 882.8275,
obn.WV: 882.8275,
obn.Oa21: 882.8275,
}
class S3OlciProduct(S3Product):
"""
Class of Sentinel-3 OLCI Products
"""
def __init__(
self,
product_path: Union[str, CloudPath, Path],
archive_path: Union[str, CloudPath, Path] = None,
output_path: Union[str, CloudPath, Path] = None,
remove_tmp: bool = False,
) -> None:
"""
https://sentinels.copernicus.eu/web/sentinel/technical-guides/sentinel-3-slstr/level-1/observation-mode-desc
Note that the name of each netCDF file provides information about its content.
"""
super().__init__(
product_path, archive_path, output_path, remove_tmp
) # Order is important here
self._gcps = []
def _get_preprocessed_band_path(
self,
band: Union[obn, str],
resolution: Union[float, tuple, list] = None,
writable=True,
) -> Union[CloudPath, Path]:
"""
Create the pre-processed band path
Args:
band (band: Union[obn, str]): Wanted band (quality flags accepted)
resolution (Union[float, tuple, list]): Resolution of the wanted UTM band
writable (bool): Do we need to write the pre-processed band ?
Returns:
Union[CloudPath, Path]: Pre-processed band path
"""
res_str = self._resolution_to_str(resolution)
band_str = band.name if isinstance(band, obn) else band
return self._get_band_folder(writable=writable).joinpath(
f"{self.condensed_name}_{band_str}_{res_str}.tif"
)
def _set_preprocess_members(self):
""" Set pre-process members """
# Radiance bands
self._radiance_file = "{band}_radiance.nc"
self._radiance_subds = "{band}_radiance"
# Geocoding
self._geo_file = "geo_coordinates.nc"
self._lat_nc_name = "latitude"
self._lon_nc_name = "longitude"
self._alt_nc_name = "altitude"
# Tie geocoding
self._tie_geo_file = "tie_geo_coordinates.nc"
self._tie_lat_nc_name = "latitude"
self._tie_lon_nc_name = "longitude"
# Mean Sun angles
self._geom_file = "tie_geometries.nc"
self._saa_name = "SAA"
self._sza_name = "SZA"
# Rad 2 Refl
self._misc_file = "instrument_data.nc"
self._solar_flux_name = "solar_flux"
self._det_index = "detector_index"
def _pre_init(self) -> None:
"""
Function used to pre_init the products
(setting needs_extraction and so on)
"""
self.needs_extraction = False
# Post init done by the super class
super()._pre_init()
def _get_platform(self) -> Platform:
""" Getter of the platform """
if "OL" in self.name:
# Instrument
self._instrument = S3Instrument.OLCI
sat_id = self._instrument.value
else:
raise InvalidProductError(
f"Only OLCI and SLSTR are valid Sentinel-3 instruments : {self.name}"
)
return getattr(Platform, sat_id)
def _set_resolution(self) -> float:
"""
Set product default resolution (in meters)
"""
return 300.0
def _set_product_type(self) -> None:
"""Set products type"""
# Product type
if self.name[7] != "1":
raise InvalidTypeError("Only L1 products are used for Sentinel-3 data.")
self.product_type = S3ProductType.OLCI_EFR
self._data_type = S3DataType.EFR
# Bands
self.band_names.map_bands(
{
obn.Oa01: "Oa01",
obn.Oa02: "Oa02",
obn.CA: "Oa03",
obn.BLUE: "Oa04",
obn.Oa05: "Oa05",
obn.GREEN: "Oa06",
obn.YELLOW: "Oa07",
obn.RED: "Oa08",
obn.Oa09: "Oa09",
obn.Oa10: "Oa10",
obn.VRE_1: "Oa11",
obn.VRE_2: "Oa12",
obn.Oa13: "Oa13",
obn.Oa14: "Oa14",
obn.Oa15: "Oa15",
obn.VRE_3: "Oa16",
obn.NIR: "Oa17",
obn.NARROW_NIR: "Oa17",
obn.Oa18: "Oa18",
obn.Oa19: "Oa19",
obn.WV: "Oa20",
obn.Oa21: "Oa21",
}
)
def _create_gcps(self) -> None:
"""
Create the GCPs sequence
"""
# Compute only ig needed
if not self._gcps:
# Open lon/lat/alt files to populate the GCPs
lat = self._read_nc(self._geo_file, self._lat_nc_name)
lon = self._read_nc(self._geo_file, self._lon_nc_name)
alt = self._read_nc(self._geo_file, self._alt_nc_name)
# Create GCPs
self._gcps = utils.create_gcps(lon, lat, alt)
def _preprocess(
self,
band: Union[obn, str],
resolution: float = None,
to_reflectance: bool = True,
subdataset: str = None,
**kwargs,
) -> Union[CloudPath, Path]:
"""
Pre-process S3 OLCI bands:
- Convert radiance to reflectance
- Geocode
Args:
band (Union[obn, str]): Band to preprocess (quality flags or others are accepted)
resolution (float): Resolution
to_reflectance (bool): Convert band to reflectance
subdataset (str): Subdataset
kwargs: Other arguments used to load bands
Returns:
dict: Dictionary containing {band: path}
"""
band_str = band if isinstance(band, str) else band.name
path = self._get_preprocessed_band_path(band, resolution=resolution)
if not path.is_file():
path = self._get_preprocessed_band_path(
band, resolution=resolution, writable=True
)
# Get band regex
if isinstance(band, obn):
band_name = self.band_names[band]
if not subdataset:
subdataset = self._replace(self._radiance_subds, band=band_name)
filename = self._replace(self._radiance_file, band=band_name)
else:
filename = band
# Get raw band
band_arr = self._read_nc(
filename, subdataset, dtype=kwargs.get("dtype", np.float32)
)
# Convert radiance to reflectances if needed
# Convert first pixel by pixel before reprojection !
if to_reflectance:
LOGGER.debug(f"Converting {band_str} to reflectance")
band_arr = self._rad_2_refl(band_arr, band)
# Debug
# utils.write(
# band_arr,
# self._get_band_folder(writable=True).joinpath(
# f"{self.condensed_name}_{band.name}_rad2refl.tif"
# ),
# )
# Geocode
LOGGER.debug(f"Geocoding {band_str}")
pp_arr = self._geocode(band_arr, resolution=resolution)
# Write on disk
utils.write(pp_arr, path)
return path
def _geocode(
self, band_arr: xr.DataArray, resolution: float = None
) -> xr.DataArray:
"""
Geocode Sentinel-3 bands
Args:
band_arr (xr.DataArray): Band array
resolution (float): Resolution
Returns:
xr.DataArray: Geocoded DataArray
"""
# Create GCPs if not existing
self._create_gcps()
# Assign a projection
band_arr.rio.write_crs(WGS84, inplace=True)
return band_arr.rio.reproject(
dst_crs=self.crs,
resolution=resolution,
gcps=self._gcps,
nodata=self._mask_nodata if band_arr.dtype == np.uint8 else self.nodata,
num_threads=MAX_CORES,
**{"SRC_METHOD": "GCP_TPS"},
)
def _rad_2_refl(self, band_arr: xr.DataArray, band: obn = None) -> xr.DataArray:
"""
Convert radiance to reflectance
Args:
band_arr (xr.DataArray): Band array
band (obn): Optical Band (for SLSTR only)
Returns:
dict: Dictionary containing {band: path}
"""
rad_2_refl_path = self._get_band_folder() / f"rad_2_refl_{band.name}.npy"
if not rad_2_refl_path.is_file():
rad_2_refl_path = (
self._get_band_folder(writable=True) / f"rad_2_refl_{band.name}.npy"
)
# Open SZA array (resampled to band_arr size)
sza_path = self._get_band_folder() / "sza.tif"
if not sza_path.is_file():
sza_path = self._get_band_folder(writable=True) / "sza.tif"
sza_nc = self._read_nc(self._geom_file, self._sza_name)
utils.write(sza_nc, sza_path)
with rasterio.open(sza_path) as ds_sza:
# Values can be easily interpolated at pixels from Tie Points by linear interpolation using the
# image column coordinate.
sza, _ = rasters_rio.read(
ds_sza,
size=(band_arr.rio.width, band_arr.rio.height),
resampling=Resampling.bilinear,
masked=False,
)
sza_rad = sza.astype(np.float32) * np.pi / 180.0
# Open solar flux (resampled to band_arr size)
e0 = self._compute_e0(band)
# Compute rad_2_refl coeff
rad_2_refl_coeff = (np.pi / e0 / np.cos(sza_rad)).astype(np.float32)
# Write on disk
np.save(rad_2_refl_path, rad_2_refl_coeff)
else:
# Open rad_2_refl_coeff (resampled to band_arr size)
rad_2_refl_coeff = np.load(rad_2_refl_path)
return band_arr * rad_2_refl_coeff
def _compute_e0(self, band: obn = None) -> np.ndarray:
"""
Compute the solar spectral flux in mW / (m^2 * sr * nm)
The Level 1 product provides measurements of top of atmosphere (ToA) radiances (mW/m2/sr/nm). These
values can be converted to normalised reflectance for better comparison or merging of data with different
sun angles as follows:
reflectance = π* (ToA radiance / solar irradiance / cos(solar zenith angle))
where the solar irradiance at ToA is given in the ‘solar_flux’ dataset (instrument_data.nc file) for each
detector and each channel, and the solar zenith angle is given at Tie Points in the ‘SZA’ dataset
(tie_geometry.nc file). The appropriate instrument detector is given at each pixel by the ‘detector_index’
dataset (instrument_data.nc file).
In https://sentinel.esa.int/documents/247904/4598069/Sentinel-3-OLCI-Land-Handbook.pdf/455f8c88-520f-da18-d744-f5cda41d2d91
Args:
band (obn): Optical Band (for SLSTR only)
Returns:
np.ndarray: Solar Flux
"""
# Do not convert to int here as we want to keep the nans
det_idx = self._read_nc(self._misc_file, self._det_index).data
e0_det = self._read_nc(self._misc_file, self._solar_flux_name).data
# Get band slice and open corresponding e0 for the detectors
band_slice = int(self.band_names[band][-2:]) - 1
e0_det = np.squeeze(e0_det[0, band_slice, :])
# Create e0
e0 = det_idx
not_nan_idx = ~np.isnan(det_idx)
e0[not_nan_idx] = e0_det[det_idx[not_nan_idx].astype(int)]
return e0
def _manage_invalid_pixels(
self, band_arr: XDS_TYPE, band: obn, **kwargs
) -> XDS_TYPE:
"""
Manage invalid pixels (Nodata, saturated, defective...) for OLCI data.
See there:
https:sentinel.esa.int/documents/247904/1872756/Sentinel-3-OLCI-Product-Data-Format-Specification-OLCI-Level-1
QUALITY FLAGS (From end to start of the | |
<filename>pyNastran/op2/result_objects/grid_point_weight.py<gh_stars>0
"""defines the GridPointWeight class"""
from io import StringIO
from struct import pack
import numpy as np
from pyNastran.utils import object_attributes, object_methods
from pyNastran.op2.result_objects.op2_objects import _write_table_header
from pyNastran.op2.op2_interface.write_utils import export_to_hdf5
float_types = (float, np.float32)
integer_types = (int, np.int32)
# ? ? ? ?
#good = (4, 2, 4, 8, 1464878927, 538976327, 8, 4, -1, 4, 4, 7, 4, 28, 101, 0, 0, 0, 0, 0, 1, 28, 4, -2, 4, 4, 1, 4, 4, 0, 4, 4, 2, 4, 8, 1464878927, 538976327, 8, 4, -3, 4, 4, 1, 4, 4, 0, 4, 4, 146, 4)
#bad = (4, 2, 4, 8, 1464878927, 538976327, 8, 4, -1, 4, 4, 7, 4, 28, 102, 0, 0, 0, 512, 0, 0, 28, 4, -2, 4, 4, 1, 4, 4, 0, 4, 4, 7, 4, 28, 1464878927, 538976327, 9, 27, 19, 0, 1, 28, 4, -3, 4, 4, 1, 4, 4)
class GridPointWeight:
def __init__(self):
"""
.. seealso:: http://www.6dof.com/index.php?option=com_content&view=article&id=298:output-from-the-grid-point-weight-generator&catid=178:courses-and-trainings&Itemid=61
"""
# The Grid Point Weight Generator (GPWG) module computes the rigid body
# mass properties of an entire structure with respect to a user specified point and with
# respect to the center of mass. Output from the module is requested by a PARAM
# GRDPNT card in the Bulk Data Deck which specifies from which grid point mass
# computations are to be referenced. Optionally, the absence of a specific grid point
# (i.e. PARAM, GRDPNT, 0) automatically causes the origin of the basic
# coordinate system to be utilized as a reference. The mass properties are initially
# defined in the basic coordinate system. Subsequently, the mass properties are
# transformed to principal mass axes and to principal inertia axes. The actual printout
# is composed of several elements. These are:
self.reference_point = None
# M0 RIGID BODY MASS MATRIX IN BASIC COORDINATE SYSTEM
# This is the rigid body mass matrix of the entire structure in the basic coordinate
# system with respect to a reference point chosen by the analyst.
self.MO = None
# S TRANSFORMATION MATRIX FOR SCALAR MASS PARTITION
# S is the transformation from the basic coordinate system to the set of principal axes
# for the 3 x 3 scalar mass partition of the 6 x 6 mass matrix. The principal axes for
# just the scalar partition are known as the principal mass axes.
self.S = None
self.mass = None
# XC.G. YC.G. ZC.G.
# It is possible in NASTRAN to assemble a structural model having different values of
# mass in each coordinate direction at a grid point. This can arise, for example, by
# assembling scalar mass components or from omitting some components by means of bar
# element pin flags. Consequently three distinct mass systems are assembled one in each of
# the three directions of the principal mass axes (the S system). This third tabulation
# has five columns. The first column lists the axis direction in the S coordinates. The
# second column lists the mass associated with the appropriate axis direction. The final
# three columns list the x, y, and z coordinate distances from the reference point to the
# center of mass for each of the three mass systems.
self.cg = None
# I(S) INERTIAS RELATIVE TO C.G.
# This is the 3 x 3 mass moment of inertia partition with respect to the center of
# gravity referred to the principal mass axes (the S system). This is not necessarily a
# diagonal matrix because the determination of the S system does not involve second
# moments. The values of inertias at the center of gravity are found from the values at
# the reference point employing the parallel axes rule.
self.IS = None
# I(Q) PRINCIPAL INERTIAS
# The principal moments of inertia at the center of gravity are displayed in matrix
# form with reference to the Q system of axes. The Q system is obtained from an eigenvalue
# analysis of the I(S) matrix.
self.IQ = None
# Q TRANSFORMATION MATRIX I(Q) = QT*IBAR(S)*Q
# Q is the coordinate transformation between the S axes and the Q axes. IBAR(S) is the
# same as I(s) except that the signs of the offdiagonal terms are reversed.
self.Q = None
self.title = ''
self.subtitle = ''
self.label = ''
self.superelement_adaptivity_index = ''
def export_to_hdf5(self, group, log) -> None:
"""exports the object to HDF5 format"""
export_to_hdf5(self, group, log)
def object_attributes(self, mode='public', keys_to_skip=None,
filter_properties=False):
if keys_to_skip is None:
keys_to_skip = []
my_keys_to_skip = [
'object_methods', 'object_attributes',
]
return object_attributes(self, mode=mode,
keys_to_skip=keys_to_skip+my_keys_to_skip,
filter_properties=filter_properties)
def object_methods(self, mode='public', keys_to_skip=None):
if keys_to_skip is None:
keys_to_skip = []
my_keys_to_skip = []
my_keys_to_skip = [
'object_methods', 'object_attributes',
]
return object_methods(self, mode=mode, keys_to_skip=keys_to_skip+my_keys_to_skip)
def __eq__(self, weight):
msg = ''
if not self.reference_point == weight.reference_point:
msg += f'reference_point: {self.reference_point} -> {weight.reference_point}\n'
if not np.array_equal(self.MO, weight.MO):
msg += f'reference_point: {self.MO} -> {weight.MO}\n'
if not np.array_equal(self.S, weight.S):
msg += f'reference_point: {self.S} -> {weight.S}\n'
if not np.array_equal(self.mass, weight.mass):
msg += f'reference_point: {self.mass} -> {weight.mass}\n'
if not np.array_equal(self.cg, weight.cg):
msg += f'reference_point: {self.cg} -> {weight.cg}\n'
if not np.array_equal(self.IS, weight.IS):
msg += f'reference_point: {self.IS} -> {weight.IS}\n'
if not np.array_equal(self.IQ, weight.IQ):
msg += f'reference_point: {self.IQ} -> {weight.IQ}\n'
if not np.array_equal(self.Q, weight.Q):
msg += f'reference_point: {self.Q} -> {weight.Q}'
if msg:
raise ValueError('GridPointWeight:\n' + msg)
return True
def set_grid_point_weight(self, reference_point, MO, S, mass, cg, IS, IQ, Q,
approach_code=1, table_code=13,
title='', subtitle='', label='',
superelement_adaptivity_index=''):
"""used by the op2 reader to set the table parameters"""
self.reference_point = reference_point
self.approach_code = approach_code
self.table_code = table_code
self.MO = MO
self.S = S
self.mass = mass
self.cg = cg
self.IS = IS
self.IQ = IQ
self.Q = Q
self.title = title
self.subtitle = subtitle
self.label = label
self.superelement_adaptivity_index = superelement_adaptivity_index
def get_stats(self, key='', short=True):
key2 = f'[{key!r}]'
if short:
msg = (f'GridPointWeight{key2}: ref_point=%s mass=%g; '
'[reference_point, M0, S, mass, cg, IS, IQ, Q]\n' % (
self.reference_point, self.mass.max()))
else:
msg = (
f'GridPointWeight{key2}:'
' reference_point=%s\n'
' mass=[%10g %10g %10g]\n'
' cg =[%10g %10g %10g]\n'
' [%10g %10g %10g]\n'
' [%10g %10g %10g]\n\n'
' IS =[%10g %10g %10g]\n'
' [%10g %10g %10g]\n'
' [%10g %10g %10g]\n\n'
' IQ =[%10g %10s %10s]\n'
' [%10s %10g %10s]\n'
' [%10s %10s %10g]\n\n'
' Q = [%10g %10g %10g]\n'
' [%10g %10g %10g]\n'
' [%10g %10g %10g]\n' % (
self.reference_point, self.mass[0], self.mass[1], self.mass[2],
self.cg[0, 0], self.cg[0, 1], self.cg[0, 2],
self.cg[1, 0], self.cg[1, 1], self.cg[1, 2],
self.cg[2, 0], self.cg[2, 1], self.cg[2, 2],
self.IS[0, 0], self.IS[0, 1], self.IS[0, 2],
self.IS[1, 0], self.IS[1, 1], self.IS[1, 2],
self.IS[2, 0], self.IS[2, 1], self.IS[2, 2],
self.IQ[0], '', '',
'', self.IQ[1], '',
'', '', self.IQ[2],
self.Q[0, 0], self.Q[0, 1], self.Q[0, 2],
self.Q[1, 0], self.Q[1, 1], self.Q[1, 2],
self.Q[2, 0], self.Q[2, 1], self.Q[2, 2],
)
)
return msg
def __repr__(self):
f = StringIO()
page_stamp = 'PAGE %i'
page_num = 1
self.write_f06(f, page_stamp, page_num)
msg = f.getvalue()
return msg
def _write_table_3(self, op2_file, fascii, new_result, table_name, itable=-3):
import inspect
frame = inspect.currentframe()
call_frame = inspect.getouterframes(frame, 2)
fascii.write('%s.write_table_3: %s\n' % (self.__class__.__name__, call_frame[1][3]))
if new_result and itable != -3:
header = [
4, 146, 4,
]
else:
header = [
4, itable, 4,
4, 1, 4,
4, 0, 4,
4, 146, 4,
]
op2_file.write(pack(b'%ii' % len(header), *header))
fascii.write('table_3_header = %s\n' % header)
#op2_file.write(pack('12i', *[4, itable, 4,
#4, 1, 4,
#4, 0, 4,
#4, 146, 4,
#]))
approach_code = self.approach_code
table_code = self.table_code
#isubcase = self.isubcase
#random_code = self.random_code
#format_code = 1
isubcase = 0
num_wide = 79 # self.num_wide
#acoustic_flag = self.acoustic_flag if hasattr(self, 'acoustic_flag') else 0
reference_point = self.reference_point
reference_point = 22
#thermal = self.thermal
title = b'%-128s' % self.title.encode('ascii')
subtitle = b'%-128s' % self.subtitle.encode('ascii') # missing superelement_adaptivity_index
label = b'%-128s' % self.label.encode('ascii')
#1, 13, 0, 0, 0, 0, 0, 0, 0, 78, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, | |
<filename>widgets/history.py
from utils import pmts
from kivy.clock import Clock
from kivy.core.text import Label
from kivy.graphics import Color, Rectangle
from kivy.metrics import pt
from kivy.uix.behaviors.focus import FocusBehavior
from kivy.uix.widget import Widget
from dsn.history.construct import eh_note_play
from dsn.history.structure import EHStructure
from dsn.s_expr.score import Score
# from dsn.s_expr.construct import play_score
from dsn.s_expr.structure import Atom, List
from dsn.s_expr.clef_address import play_simple_score, score_with_global_address
from dsn.s_expr.simple_score import SimpleScore
from dsn.s_expr.note_address import els18_root_address, ELS18RenderingAddress
from spacetime import get_s_address_for_t_address
from s_address import node_for_s_address
from dsn.history.clef import (
EHCursorSet,
EHCursorChild,
EHCursorDFS,
EHCursorParent,
)
from widgets.utils import (
annotate_boxes_with_s_addresses,
apply_offset,
BoxNonTerminal,
BoxTerminal,
bring_into_offset,
cursor_dimensions,
from_point,
no_offset,
OffsetBox,
X,
Y,
flatten_nt_to_dict,
)
from widgets.animate import animate, animate_scalar
from colorscheme import (
BLACK,
WHITE,
)
from widgets.layout_constants import (
get_font_size,
PADDING,
MARGIN,
)
from dsn.viewports.structure import ViewportStructure, VRTC, ViewportContext
from dsn.viewports.construct import play_viewport_note
from dsn.viewports.clef import (
ViewportContextChange,
MoveViewportRelativeToCursor,
CURSOR_TO_BOTTOM,
CURSOR_TO_CENTER,
CURSOR_TO_TOP,
ELSEWHERE,
HERE,
VIEWPORT_LINE_DOWN,
VIEWPORT_LINE_UP,
)
ANIMATION_LENGTH = .5 # Seconds
class HistoryWidget(FocusBehavior, Widget):
def __init__(self, **kwargs):
self._invalidated = False
self.m = kwargs.pop('m')
kwargs.pop('tree_widget') # symmetry w/ ic_history.py, even though unused in history.py
# Not the best name ever, but at least it clearly indicates we're talking about the channel which contains
# information on "data" changes (as opposed to "cursor" changes)
self.data_channel = None
super(HistoryWidget, self).__init__(**kwargs)
# In __init__ we don't have any information available yet on our state. Which means we cannot draw ourselves.
# This gets fixed the moment we get some data from e.g. our parent. In practice this happens before we get to
# refresh from e.g. the size/pos bindings, but I'd like to make that flow a bit more explicit.
#
# AFAIU:
# 1. We could basically set any value below.
self.ds = EHStructure(Score.empty(), List([], address=els18_root_address), [0], [])
self.z_pressed = False
self.viewport_ds = ViewportStructure(
ViewportContext(0, 0, 0, 0),
VRTC(0),
)
self.present_viewport_position, self.target_viewport_position = 0, 0
self.present = {}
self.animation_time_remaining = 0
Clock.schedule_interval(self.tick, 1 / 60)
self.bind(pos=self.invalidate)
self.bind(size=self.size_change)
def _best_new_cursor(self, prev_s_cursor, prev_node, new_node, default):
"""Finds a best new cursor given a previous cursor"""
# Note: I find all this mapping between various address schemes rather ad hoc, but it works.
def _best(s_expr_node, global_address, path_so_far):
"""Find the best match for global_address in s_expr_node;
Return an s_address to this (which is collected in a variable path_so_far)"""
if global_address == s_expr_node.address:
return path_so_far # precise match, return
for i, child in enumerate(getattr(s_expr_node, 'children', [])):
if child.address.is_prefix_of(global_address):
return _best(child, global_address, path_so_far + [i]) # it's better
return path_so_far # no child is better; return yourself
prev_selected_node = node_for_s_address(prev_node, prev_s_cursor)
global_address = prev_selected_node.address
result = _best(new_node, global_address, [])
if result == []:
return default
return result
def parent_cursor_update(self, data):
t_address = data
local_score = self._local_score(self.ds.score, t_address)
as_s_expr = List([n.to_s_expression() for n in local_score.notes()], address=els18_root_address)
self.ds = EHStructure(
self.ds.score,
as_s_expr,
self._best_new_cursor(self.ds.s_cursor, self.ds.node, as_s_expr, [len(local_score) - 1]),
t_address,
)
self._construct_target_box_structure()
# The desirable behavior is: keep the cursor still; Hence: change_source=ELSEWHERE (which matches with the fact
# that the history-cursor moving is a consequence of cursor move elsewhere)
self._update_viewport_for_change(change_source=ELSEWHERE)
self.invalidate()
def receive_from_parent(self, data):
pmts(data, Score)
self.update_score(data)
def _local_score(self, score, tree_t_address):
annotated_score = score_with_global_address(score)
tree = play_simple_score(annotated_score)
s_address = get_s_address_for_t_address(tree, tree_t_address)
if s_address is None:
# because changes to the Score and the Cursor are not communicated to us in a transactional way, deletions
# in the tree will lead to a (temporarily) invalid cursor. We set our own score to the empty one in that
# case; the cursor_update that follows right after will restore the situation
return SimpleScore.empty()
cursor_node = node_for_s_address(tree, s_address)
return cursor_node.score
def update_score(self, score):
local_score = self._local_score(score, self.ds.tree_t_address)
self.ds = EHStructure(
score,
List([n.to_s_expression() for n in local_score.notes()], address=els18_root_address),
self.ds.s_cursor,
self.ds.tree_t_address,
)
self._construct_target_box_structure()
# The desirable behavior is: keep the cursor still; Hence: change_source=ELSEWHERE (which matches with the fact
# that the history-cursor moving is a consequence of cursor move elsewhere)
self._update_viewport_for_change(change_source=ELSEWHERE)
self.invalidate()
def _handle_eh_note(self, eh_note):
new_s_cursor, error = eh_note_play(self.ds, eh_note)
local_score = self._local_score(self.ds.score, self.ds.tree_t_address)
self.ds = EHStructure(
self.ds.score,
List([n.to_s_expression() for n in local_score.notes()], address=els18_root_address),
new_s_cursor,
self.ds.tree_t_address,
)
self._construct_target_box_structure()
self._update_viewport_for_change(change_source=HERE)
self.invalidate()
def keyboard_on_key_down(self, window, keycode, text, modifiers):
FocusBehavior.keyboard_on_key_down(self, window, keycode, text, modifiers)
code, textual_code = keycode
if modifiers == ['ctrl'] and textual_code in ['e', 'y']:
# For now, these are the only ctrl-key keys we handle; once we get more of those, they should get a better
# home.
note = MoveViewportRelativeToCursor({'e': VIEWPORT_LINE_UP, 'y': VIEWPORT_LINE_DOWN}[textual_code])
self.viewport_ds = play_viewport_note(note, self.viewport_ds)
self.invalidate()
elif self.z_pressed:
self.z_pressed = False
if textual_code in ['z', 'b', 't']:
lookup = {
'z': CURSOR_TO_CENTER,
'b': CURSOR_TO_BOTTOM,
't': CURSOR_TO_TOP,
}
note = MoveViewportRelativeToCursor(lookup[textual_code])
self.viewport_ds = play_viewport_note(note, self.viewport_ds)
self.invalidate()
elif textual_code in ['z']:
self.z_pressed = True
elif textual_code in ['f']: # f for follow
self.asdf()
elif textual_code in ['left', 'h']:
self._handle_eh_note(EHCursorParent())
elif textual_code in ['right', 'l']:
self._handle_eh_note(EHCursorChild())
elif textual_code in ['up', 'k']:
self._handle_eh_note(EHCursorDFS(-1))
elif textual_code in ['down', 'j']:
self._handle_eh_note(EHCursorDFS(1))
return True
def size_change(self, *args):
self._update_viewport_for_change(change_source=ELSEWHERE)
self.invalidate()
def invalidate(self, *args):
self._invalidated = True
def _update_viewport_for_change(self, change_source):
# As it stands: copy-pasta from TreeWidget width changes
cursor_position, cursor_size = cursor_dimensions(self.target_box_structure, self.ds.s_cursor)
# In the below, all sizes and positions are brought into the positive integers; there is a mirroring `+` in the
# offset calculation when we actually apply the viewport.
context = ViewportContext(
document_size=self.target_box_structure.underlying_node.outer_dimensions[Y] * -1,
viewport_size=self.size[Y],
cursor_size=cursor_size * -1,
cursor_position=cursor_position * -1)
note = ViewportContextChange(
context=context,
change_source=change_source,
)
self.viewport_ds = play_viewport_note(note, self.viewport_ds)
self.target_viewport_position = self.viewport_ds.get_position()
self.animation_time_remaining = ANIMATION_LENGTH
def _construct_target_box_structure(self):
offset_nonterminals = self._nts(self.ds.node)
root_nt = BoxNonTerminal(offset_nonterminals, [])
self.target_box_structure = annotate_boxes_with_s_addresses(root_nt, [])
self.target = flatten_nt_to_dict(root_nt, (0, 0))
self.animation_time_remaining = ANIMATION_LENGTH
def tick(self, dt):
if self.animation_time_remaining > 0:
self.present = animate(dt / self.animation_time_remaining, self.present, self.target)
self.present_viewport_position = animate_scalar(
dt / self.animation_time_remaining, self.present_viewport_position, self.target_viewport_position)
self.animation_time_remaining = self.animation_time_remaining - dt
self._invalidated = True
if not self._invalidated: # either b/c animation, or explicitly
return
# Actually draw
self.canvas.clear()
self.offset = (self.pos[X], self.pos[Y] + self.size[Y] + self.present_viewport_position)
with self.canvas:
Color(1, 1, 1, 1)
Rectangle(pos=self.pos, size=self.size,)
with apply_offset(self.canvas, self.offset):
self._render_box(BoxNonTerminal([], list(self.present.values())))
self._invalidated = False
def colors_for_cursor(self, is_cursor):
if is_cursor:
return WHITE, BLACK
return BLACK, None
def _nts(self, s_expr_node):
result = []
offset_y = 0
for i, node in enumerate(s_expr_node.children):
per_step_result = self.bottom_up_construct(self._nt_for_node_single_line, node, [i])
result.append(OffsetBox((0, offset_y), per_step_result))
offset_y += per_step_result.outer_dimensions[Y]
return result
def bottom_up_construct(self, alg, node, s_address):
# combines the idea of a catamorphism (with explicit passing of child_results, rather than the more canonical
# approach which reconstructs nodes with child_results) with the the passing of the s_address in the tree for
# each visited node.
node_children = node.children if hasattr(node, 'children') else []
child_results = [self.bottom_up_construct(alg, child, s_address + [i]) for i, child in enumerate(node_children)]
return alg(node, child_results, s_address)
def _nt_for_node_single_line(self, node, children_nts, s_address):
is_cursor = s_address == self.ds.s_cursor
if isinstance(node, Atom):
return BoxNonTerminal([], [no_offset(
self._t_for_text(node.atom, self.colors_for_cursor(is_cursor), node.address.with_render()))])
t = self._t_for_text("(", self.colors_for_cursor(is_cursor), node.address.with_render("open-paren"))
offset_terminals = [
no_offset(t),
]
offset_nonterminals = []
offset_right = t.outer_dimensions[X]
offset_down = 0
for nt in children_nts:
offset_nonterminals.append(OffsetBox((offset_right, offset_down), nt))
offset_right += nt.outer_dimensions[X]
t = self._t_for_text(")", self.colors_for_cursor(is_cursor), node.address.with_render("close-paren"))
offset_terminals.append(OffsetBox((offset_right, offset_down), t))
return BoxNonTerminal(offset_nonterminals, offset_terminals)
def _render_box(self, box):
# Pure copy/pasta.
for o, t in box.offset_terminals:
with apply_offset(self.canvas, o):
for instruction in t.instructions:
# This is rather ad hoc (a.k.a. hackish) but I cannot find a more proper way to do it in Kivy.
# i.e. there is no PushMatrix / Translate equivalent for alpha-blending.
if isinstance(instruction, Color):
self.canvas.add(Color(instruction.r, instruction.g, instruction.b, o.alpha))
else:
self.canvas.add(instruction)
for o, nt in box.offset_nonterminals:
with apply_offset(self.canvas, o):
self._render_box(nt)
# ## Section for drawing boxes
def _t_for_text(self, text, colors, address):
# Copy/pasta from tree.py (w/ addressing)
pmts(address, ELS18RenderingAddress)
fg, bg = colors
text_texture = self._texture_for_text(text)
content_height = text_texture.height
content_width = text_texture.width
top_left = 0, 0
bottom_left = (top_left[X], top_left[Y] - MARGIN - PADDING - content_height - PADDING - MARGIN)
bottom_right = (bottom_left[X] + MARGIN + PADDING + content_width + PADDING + MARGIN, bottom_left[Y])
if bg is None:
instructions = []
else:
instructions = [
Color(*bg),
Rectangle(
pos=(bottom_left[0] + MARGIN, bottom_left[1] + MARGIN),
size=(content_width + 2 * PADDING, content_height + 2 * PADDING),
),
]
instructions += [
Color(*fg),
Rectangle(
pos=(bottom_left[0] + MARGIN + PADDING, bottom_left[1] + MARGIN + PADDING),
size=text_texture.size,
texture=text_texture,
),
]
return BoxTerminal(instructions, bottom_right, address)
def _texture_for_text(self, text):
if | |
<filename>DeepBach/model_manager.py
"""
Created on 15 mars 2016
@author: <NAME>
"""
import os
import pickle
from keras.models import model_from_json, model_from_yaml
from music21 import midi
from tqdm import tqdm
from .data_utils import generator_from_raw_dataset, BACH_DATASET, \
all_features, START_SYMBOL, END_SYMBOL, all_metadatas, \
standard_note, SOP, BASS, PACKAGE_DIR
from .metadata import *
from .models_zoo import deepBach, deepbach_skip_connections
def generation(model_base_name, models, timesteps, melody=None,
chorale_metas=None,
initial_seq=None, temperature=1.0, parallel=False,
batch_size_per_voice=8, num_iterations=None,
sequence_length=160,
output_file=None, pickled_dataset=BACH_DATASET):
# Test by generating a sequence
print()
print("GENERATION BEGIN")
print()
# todo -p parameter
parallel = True
if parallel:
seq = parallel_gibbs(models=models, model_base_name=model_base_name,
melody=melody, chorale_metas=chorale_metas,
timesteps=timesteps,
num_iterations=num_iterations,
sequence_length=sequence_length,
temperature=temperature,
initial_seq=initial_seq,
batch_size_per_voice=batch_size_per_voice,
parallel_updates=True,
pickled_dataset=pickled_dataset)
else:
# todo refactor
print('gibbs function must be refactored!')
# seq = gibbs(models=models, model_base_name=model_base_name,
# timesteps=timesteps,
# melody=melody, fermatas_melody=fermatas_melody,
# num_iterations=num_iterations, sequence_length=sequence_length,
# temperature=temperature,
# initial_seq=initial_seq,
# pickled_dataset=pickled_dataset)
raise NotImplementedError
# convert
#score = indexed_chorale_to_score(np.transpose(seq, axes=(1, 0)),
# pickled_dataset=pickled_dataset)
# save as MIDI file
if output_file:
mf = midi.translate.music21ObjectToMidiFile(score)
mf.open(output_file, 'wb')
mf.write()
mf.close()
print("File " + output_file + " written")
# display in editor
#score.show()
pickle.dump(seq, open("Results"+ pickled_dataset[pickled_dataset.rfind("/"):pickled_dataset.rfind(".")], 'wb'), pickle.HIGHEST_PROTOCOL)
return seq
# def gibbs(models=None, melody=None, fermatas_melody=None, sequence_length=50, num_iterations=1000,
# timesteps=16,
# model_base_name='models/raw_dataset/tmp/',
# num_voices=4, temperature=1., min_pitches=None,
# max_pitches=None, initial_seq=None,
# pickled_dataset=BACH_DATASET):
# """
# samples from models in model_base_name
#
# """
# X, X_metadatas, min_pitches, max_pitches, num_voices = pickle.load(open(pickled_dataset, 'rb'))
#
# # load models if not
# if models is None:
# for expert_index in range(num_voices):
# model_name = model_base_name + str(expert_index)
#
# model = load_model(model_name=model_name, yaml=False)
# models.append(model)
#
# # initialization sequence
# if melody is not None:
# sequence_length = len(melody)
#
# if fermatas_melody is not None:
# sequence_length = len(fermatas_melody)
# if melody is not None:
# assert len(melody) == len(fermatas_melody)
#
# seq = np.zeros(shape=(2 * timesteps + sequence_length, num_voices))
# for expert_index in range(num_voices):
# # Add slur_symbol
# seq[timesteps:-timesteps, expert_index] = np.random.random_integers(min_pitches[expert_index],
# max_pitches[expert_index] + 1,
# size=sequence_length)
#
# if initial_seq is not None:
# seq = initial_seq
# min_voice = 1
# # works only with reharmonization
#
# # melody = X[-1][0, :, 0]
# # melody is pa !
# if melody is not None:
# seq[timesteps:-timesteps, 0] = melody[:, 0]
# mask = melody[:, 1] == 0
# seq[timesteps:-timesteps, 0][mask] = max_pitches[0] + 1
# min_voice = 1
# else:
# min_voice = 0
#
# if fermatas_melody is not None:
# fermatas_melody = np.concatenate((np.zeros((timesteps,)),
# fermatas_melody,
# np.zeros((timesteps,)))
# )
#
# min_temperature = temperature
# temperature = 1.2
# # Main loop
# for iteration in tqdm(range(num_iterations)):
#
# temperature = max(min_temperature, temperature * 0.99996) # Recuit
#
# voice_index = np.random.randint(min_voice, num_voices)
# time_index = np.random.randint(timesteps, sequence_length + timesteps)
#
# (left_feature,
# central_feature,
# right_feature,
# (beats_left, beat, beats_right),
# label) = all_features(seq, voice_index, time_index, timesteps, min_pitches, max_pitches, chorale_as_pas=False)
#
# input_features = {'left_features': left_feature[None, :, :],
# 'central_features': central_feature[None, :],
# 'right_features': right_feature[None, :, :],
# 'beat': beat[None, :],
# 'beats_left': beats_left[None, :, :],
# 'beats_right': beats_right[None, :, :]}
#
# # add fermatas evenly spaced
# if fermatas_melody is None:
# (fermatas_left,
# central_fermata,
# fermatas_right) = to_fermata(time_index, timesteps=timesteps)
# input_features.update({'fermatas_left': fermatas_left[None, :, :],
# 'central_fermata': central_fermata[None, :],
# 'fermatas_right': fermatas_right[None, :, :]
# })
# else:
# (fermatas_left,
# central_fermata,
# fermatas_right) = fermata_melody_to_fermata(time_index, timesteps=timesteps,
# fermatas_melody=fermatas_melody)
# input_features.update({'fermatas_left': fermatas_left[None, :, :],
# 'central_fermata': central_fermata[None, :],
# 'fermatas_right': fermatas_right[None, :, :]
# })
#
# probas = models[voice_index].predict(input_features, batch_size=1)
#
# probas_pitch = probas[0]
#
# # use temperature
# probas_pitch = np.log(probas_pitch) / temperature
# probas_pitch = np.exp(probas_pitch) / np.sum(np.exp(probas_pitch)) - 1e-7
#
# # pitch can include slur_symbol
# pitch = np.argmax(np.random.multinomial(1, probas_pitch)) + min_pitches[voice_index]
#
# seq[time_index, voice_index] = pitch
#
# return seq[timesteps:-timesteps, :]
def parallel_gibbs(models=None, melody=None, chorale_metas=None,
sequence_length=50, num_iterations=1000,
timesteps=16,
model_base_name='models/raw_dataset/tmp/',
temperature=1., initial_seq=None, batch_size_per_voice=16,
parallel_updates=True,
pickled_dataset=BACH_DATASET):
"""
samples from models in model_base_name
"""
X, X_metadatas, voices_ids, index2notes, note2indexes, metadatas = pickle.load(
open(pickled_dataset, 'rb'))
num_pitches = list(map(len, index2notes))
num_voices = len(voices_ids)
print("FICHIER : ", pickled_dataset)
# load models if not
if models is None:
for expert_index in range(num_voices):
model_name = model_base_name + str(expert_index)
model = load_model(model_name=model_name, yaml=False)
models.append(model)
# initialization sequence
if melody is not None:
sequence_length = len(melody)
if chorale_metas is not None:
sequence_length = min(sequence_length, len(chorale_metas[0]))
elif chorale_metas is not None:
sequence_length = len(chorale_metas[0])
seq = np.zeros(shape=(2 * timesteps + sequence_length, num_voices))
for expert_index in range(num_voices):
# Add start and end symbol + random init
seq[:timesteps, expert_index] = [note2indexes[expert_index][
START_SYMBOL]] * timesteps
seq[timesteps:-timesteps, expert_index] = np.random.randint(
num_pitches[expert_index],
size=sequence_length)
seq[-timesteps:, expert_index] = [note2indexes[expert_index][
END_SYMBOL]] * timesteps
if initial_seq is not None:
seq = initial_seq
min_voice = 1
# works only with reharmonization
if melody is not None:
seq[timesteps:-timesteps, 0] = melody
min_voice = 1
else:
min_voice = 0
if chorale_metas is not None:
# chorale_metas is a list
extended_chorale_metas = [np.concatenate((np.zeros((timesteps,)),
chorale_meta,
np.zeros((timesteps,))),
axis=0)
for chorale_meta in chorale_metas]
else:
raise NotImplementedError
min_temperature = temperature
temperature = 1.5
# Main loop
for iteration in tqdm(range(num_iterations)):
temperature = max(min_temperature, temperature * 0.9992) # Recuit
# print(temperature)
time_indexes = {}
probas = {}
for voice_index in range(min_voice, num_voices):
batch_input_features = []
time_indexes[voice_index] = []
for batch_index in range(batch_size_per_voice):
time_index = np.random.randint(timesteps,
sequence_length + timesteps)
time_indexes[voice_index].append(time_index)
(left_feature,
central_feature,
right_feature,
label) = all_features(seq, voice_index, time_index, timesteps,
num_pitches, num_voices)
left_metas, central_metas, right_metas = all_metadatas(
chorale_metadatas=extended_chorale_metas,
metadatas=metadatas,
time_index=time_index, timesteps=timesteps)
input_features = {'left_features': left_feature[:, :],
'central_features': central_feature[:],
'right_features': right_feature[:, :],
'left_metas': left_metas,
'central_metas': central_metas,
'right_metas': right_metas}
# list of dicts: predict need dict of numpy arrays
batch_input_features.append(input_features)
# convert input_features
batch_input_features = {key: np.array(
[input_features[key] for input_features in
batch_input_features])
for key in batch_input_features[0].keys()
}
#for elem in batch_input_features:
# print(batch_input_features[elem].shape)
# make all estimations
#L = batch_input_features["central_features"][0].tolist()[:91]
#L = np.array([L])
#del batch_input_features["central_features"]
#batch_input_features["central_features"] = L
probas[voice_index] = models[voice_index].predict(
batch_input_features,
batch_size=batch_size_per_voice)
if not parallel_updates:
# update
for batch_index in range(batch_size_per_voice):
probas_pitch = probas[voice_index][batch_index]
# use temperature
probas_pitch = np.log(probas_pitch) / temperature
probas_pitch = np.exp(probas_pitch) / np.sum(
np.exp(probas_pitch)) - 1e-7
# pitch can include slur_symbol
pitch = np.argmax(np.random.multinomial(1, probas_pitch))
seq[time_indexes[voice_index][
batch_index], voice_index] = pitch
if parallel_updates:
# update
for voice_index in range(min_voice, num_voices):
for batch_index in range(batch_size_per_voice):
probas_pitch = probas[voice_index][batch_index]
# use temperature
probas_pitch = np.log(probas_pitch) / temperature
probas_pitch = np.exp(probas_pitch) / np.sum(
np.exp(probas_pitch)) - 1e-7
# pitch can include slur_symbol
pitch = np.argmax(np.random.multinomial(1, probas_pitch))
seq[time_indexes[voice_index][
batch_index], voice_index] = pitch
return seq[timesteps:-timesteps, :]
def _diatonic_note_names2indexes(index2notes):
ds = []
# build diatonic_note_num 2 indexes dict
for voice_index, index2note in enumerate(index2notes):
d = {}
for i in range(len(index2note)):
n = standard_note(index2note[i])
if n.isNote:
diatonic_note_num = n.pitch.diatonicNoteNum
else:
diatonic_note_num = -1
if diatonic_note_num in d:
d.update({diatonic_note_num: d.get(diatonic_note_num) + [i]})
else:
d.update({diatonic_note_num: [i]})
ds.append(d)
# transform as numpy arrays
for d in ds:
for k in d:
d.update({k: np.array(d.get(k))})
return ds
def canon(models=None, chorale_metas=None, sequence_length=50,
num_iterations=1000,
timesteps=16,
model_base_name='models/raw_dataset/tmp/',
temperature=1., batch_size_per_voice=16,
pickled_dataset=BACH_DATASET,
intervals=[7], delays=[32],
):
"""
samples from models in model_base_name
"""
# load dataset
X, X_metadatas, voice_ids, index2notes, note2indexes, metadatas = pickle.load(
open(pickled_dataset, 'rb'))
# variables
num_voices = len(voice_ids)
assert num_voices == 2
num_pitches = list(map(len, index2notes))
max_delay = max(delays)
delays = np.array([0] + delays)
intervals = np.array([0] + intervals)
# compute tables
diatonic_note_names2indexes = _diatonic_note_names2indexes(index2notes)
print(diatonic_note_names2indexes)
# load models if not
if models is None:
for expert_index in range(num_voices):
model_name = model_base_name + str(expert_index)
model = load_model(model_name=model_name, yaml=False)
models.append(model)
seq = np.zeros(
shape=(2 * timesteps + max_delay + sequence_length, num_voices))
for expert_index in range(num_voices):
# Add start and end symbol + random init
seq[:timesteps, expert_index] = [note2indexes[expert_index][
START_SYMBOL]] * timesteps
seq[timesteps:-timesteps - max_delay,
expert_index] = np.random.randint(num_pitches[expert_index],
size=sequence_length)
seq[-timesteps - max_delay:, expert_index] = [note2indexes[
expert_index][
END_SYMBOL]] * (
timesteps + max_delay)
if chorale_metas is not None:
# chorale_metas is a list
extended_chorale_metas = [np.concatenate((np.zeros((timesteps,)),
chorale_meta,
np.zeros((
timesteps + max_delay,))),
axis=0)
for chorale_meta in chorale_metas]
else:
raise NotImplementedError
min_temperature = temperature
temperature = 1.5
# Main loop
for iteration in tqdm(range(num_iterations)):
temperature = max(min_temperature, temperature * 0.9995) # Recuit
print(temperature)
time_indexes = {}
probas = {}
for voice_index in range(num_voices):
batch_input_features = []
time_indexes[voice_index] = []
for batch_index in range(batch_size_per_voice):
# soprano based
if voice_index == 0:
time_index = np.random.randint(timesteps,
sequence_length + timesteps)
else:
# time_index = sequence_length + timesteps * 2 - time_indexes[0][batch_index]
time_index = time_indexes[0][batch_index] + delays[
voice_index]
time_indexes[voice_index].append(time_index)
(left_feature,
central_feature,
right_feature,
label) = all_features(seq, voice_index, time_index, timesteps,
num_pitches, num_voices)
left_metas, central_metas, right_metas = all_metadatas(
chorale_metadatas=extended_chorale_metas,
metadatas=metadatas,
time_index=time_index, timesteps=timesteps)
input_features = {'left_features': left_feature[:, :],
'central_features': central_feature[:],
'right_features': right_feature[:, :],
'left_metas': left_metas,
'central_metas': central_metas,
'right_metas': right_metas}
# list of dicts: predict need dict of numpy arrays
batch_input_features.append(input_features)
# convert input_features
batch_input_features = {key: np.array(
[input_features[key] for input_features in
batch_input_features])
for key in batch_input_features[0].keys()
}
# make all estimations
probas[voice_index] = models[voice_index].predict(
batch_input_features,
batch_size=batch_size_per_voice)
# parallel updates
| |
<filename>bmdal/feature_maps.py<gh_stars>1-10
from .feature_data import *
import math
import utils
def robust_cholesky(matrix: torch.Tensor) -> torch.Tensor:
"""
Implements a Cholesky decomposition.
If the Cholesky decomposition fails, it is retried with increasing added jitter on the diagonal.
:param matrix: Symmetric positive semi-definite matrix to factorize.
:return: Approximate cholesky factor L such that (approximately) LL^T = matrix
"""
eps = 1e-5 * matrix.trace() / matrix.shape[-1]
L = None
for i in range(10):
try:
L = torch.linalg.cholesky(matrix)
break
except RuntimeError:
print('Increasing jitter for Cholesky decomposition', flush=True)
matrix += eps * torch.eye(matrix.shape[-1], device=matrix.device, dtype=matrix.dtype)
eps *= 2
if L is None:
raise RuntimeError('Could not Cholesky decompose the matrix')
return L
def robust_cholesky_inv(matrix: torch.Tensor) -> torch.Tensor:
"""
:param matrix: Symmetric positive semi-definite matrix.
:return: A matrix A such that (approximately) matrix^{-1} = A^T A, where A = L^{-1} for the Cholesky factor L.
"""
# returns a matrix A such that matrix^{-1} = A^T A
L = robust_cholesky(matrix)
# there might be a better solution, but I found no direct triangular inversion function
return L.inverse()
class DataTransform:
"""
Abstract base class for representing functions that transform FeatureData objects into other FeatureData objects,
usually by applying the same function to each sample in the FeatureData object.
This is typically used for (parts of) feature maps, except that it is more general than a feature map
since it does not need to allow the computation of (inner products of) vector-valued features.
For example, in a feature map phi(x) = f(g(x)), f is also a feature map, but g only needs to be a DataTransform.
"""
def __call__(self, feature_data: FeatureData, idxs: Optional[Indexes] = None) -> FeatureData:
"""
Method to apply the transformation to (a subset of) the given feature data.
Subclasses should not override this method, but override forward() instead.
:param feature_data: FeatureData to apply this transformation to.
:param idxs: An object to index the feature data with, or None if all of the feature data should be used.
:return: Returns a FeatureData object.
"""
idxs = Indexes(feature_data.get_n_samples(), idxs)
pieces = [self.forward(sub_data, sub_idxs)
for sub_idxs, sub_data in feature_data.iterate(idxs)]
return ConcatFeatureData(pieces) if len(pieces) != 1 else pieces[0]
def forward(self, feature_data: FeatureData, idxs: Indexes) -> FeatureData:
"""
Internal function for subclasses to override.
:param feature_data: FeatureData to apply the transformation to.
:param idxs: Indexes object corresponding to the subset of the feature data that should be processed.
:return: Transformed FeatureData.
"""
raise NotImplementedError()
class FeatureMap(DataTransform):
"""
Abstract base class for representing feature maps and their corresponding kernel.
For kernels with infinite-dimensional feature space,
the corresponding sub-classes may only allow evaluation of the kernel and not of the feature map.
"""
def __init__(self, n_features: int, allow_precompute_features: bool = True):
"""
:param n_features: Feature space dimension of the feature map.
Should be -1 if the feature space dimension is infinite.
:param allow_precompute_features: Specifies whether the default behavior of precompute()
should be to simply precompute the feature matrix.
This might not be desirable for kernels with high feature-space dimension
where more efficient kernel evaluation methods than the inner product between feature vectors exist.
"""
self.n_features = n_features
self.allow_precompute_features = allow_precompute_features
def get_n_features(self):
"""
:return: Returns the feature space dimension.
"""
return self.n_features
def forward(self, feature_data: FeatureData, idxs: Indexes) -> FeatureData:
"""
Implements the forward() method from DataTransform,
which in this case computes the feature matrix wrapped in TensorFeatureData.
This method can only be called if self.get_feature_matrix_impl_() is implemented.
:param feature_data: Input data to the feature map.
:param idxs: Indexes to index feature_data with.
:return: Returns a TensorFeatureData object containing the feature matrix.
"""
return TensorFeatureData(self.get_feature_matrix(feature_data, idxs))
def precompute(self, feature_data: FeatureData, idxs: Optional[Indexes] = None) -> Tuple['FeatureMap', FeatureData]:
"""
Returns a tuple (fm, fd) such that the feature map fm on the feature data fd
behaves identically to this feature map on feature_data, in terms of kernel matrix values.
For example, this method may transform (phi, x) to (id, phi(x)), if self = phi and x = feature_data.
The returned tuple should be at least as fast to evaluate as before.
Subclasses should not override precompute() but precompute_soft_().
:param feature_data: Input to this feature map.
:param idxs: Indexes to index feature_data with, or None if the full data should be used.
:return: Returns an equivalent tuple of FeatureMap and FeatureData.
"""
idxs = Indexes(feature_data.get_n_samples(), idxs)
if self.allow_precompute_features:
# simply compute the feature matrix and apply an identity feature map to it
return IdentityFeatureMap(n_features=self.n_features), self(feature_data, idxs)
else:
# use another precomputation method that can be overridden by a subclass.
results = [self.precompute_soft_(sub_data, sub_idxs) for sub_idxs, sub_data in feature_data.iterate(idxs)]
if len(results) == 1:
return results[0]
# we do not call .simplify() on the feature data here
# since precompute() might be called recursively on smaller parts of the data,
# and we do not want to simplify() multiple times but only once after precompute()
return results[0][0], ConcatFeatureData([r[1] for r in results])
def precompute_soft_(self, feature_data: FeatureData, idxs: Indexes) -> Tuple['FeatureMap', FeatureData]:
"""
Internal method to precompute the feature map
in the case that precomputing the whole feature matrix is not allowed.
This method can be overridden by subclasses if needed.
By default, it does not perform any precomputations and just returns (self, feature_data[idxs]).
:param feature_data: Feature data to apply this feature map to.
:param idxs: Indexes to index the feature data with.
:return: Potentially precomputed tuple (FeatureMap, FeatureData).
"""
# we do not call .simplify() on the feature data here
# since precompute() might be called recursively on smaller parts of the data,
# and we do not want to simplify() multiple times but only once after precompute()
return self, feature_data[idxs]
def posterior(self, feature_data: FeatureData, sigma: float, allow_kernel_space_posterior: bool = True) \
-> 'FeatureMap':
"""
Returns a feature map that represents the Gaussian Process posterior kernel after observing feature_data,
if the noise variance is sigma^2.
:param feature_data: Feature data to condition the Gaussian Process with.
:param sigma: Noise standard deviation for the Gaussian Process.
:param allow_kernel_space_posterior: Whether the method is allowed to use the kernel-space posterior formula
if it is deemed more efficient but not strictly necessary. The kernel-space posterior feature map returned
will not allow a computation of the feature matrix, which could be detrimental
for methods that want to operate in feature space.
:return: Returns a feature map that represents the Gaussian Process posterior kernel after observing feature_data,
if the noise variance is sigma^2.
"""
if self.n_features < 0 or (allow_kernel_space_posterior and self.n_features > max(1024, 3 * len(feature_data))):
# compute the posterior in kernel space
return KernelSpacePosteriorFeatureMap(feature_map=self, cond_data=feature_data, sigma=sigma)
feature_matrix = self.get_feature_matrix(feature_data)
eye = torch.eye(self.n_features, device=feature_matrix.device, dtype=feature_matrix.dtype)
cov_matrix = feature_matrix.t().matmul(feature_matrix) + (sigma ** 2) * eye
return SequentialFeatureMap(LinearFeatureMap(sigma * robust_cholesky_inv(cov_matrix).t()), [self])
def get_feature_matrix(self, feature_data: FeatureData, idxs: Optional[Indexes] = None) -> torch.Tensor:
"""
Returns the feature matrix obtained by applying this feature map to feature_data[idxs].
This method can only be used if get_feature_matrix_impl_() is implemented,
in particular it cannot be used if the feature space dimension is infinite.
Subclasses should not override this method but get_feature_matrix_impl_() instead.
:param feature_data: FeatureData to apply this feature map to.
:param idxs: Indexes to index feature_data with, or None to use the full feature_data.
:return: Feature matrix as torch.Tensor of shape n_samples x n_features
"""
idxs = Indexes(feature_data.get_n_samples(), idxs)
return torch_cat([self.get_feature_matrix_impl_(sub_data, sub_idxs)
for sub_idxs, sub_data in feature_data.iterate(idxs)], dim=-2)
def get_kernel_matrix(self, feature_data_1: FeatureData, feature_data_2: FeatureData,
idxs_1: Optional[Indexes] = None, idxs_2: Optional[Indexes] = None) -> torch.Tensor:
"""
Returns the kernel matrix k(feature_data_1[idxs_1], feature_data_2[idxs_2]),
where k is the kernel corresponding to the current feature map.
Subclasses should not override this method but get_kernel_matrix_impl_() instead.
:param feature_data_1: First feature data.
:param feature_data_2: Second feature data.
:param idxs_1: Indexes for first feature data, or None.
:param idxs_2: Indexes for second feature data, or None.
:return: Kernel matrix as torch.Tensor of shape n_samples_1 x n_samples_2
"""
idxs_1 = Indexes(feature_data_1.get_n_samples(), idxs_1)
idxs_2 = Indexes(feature_data_2.get_n_samples(), idxs_2)
return torch_cat([torch_cat([self.get_kernel_matrix_impl_(sub_data_1, sub_data_2, sub_idxs_1, sub_idxs_2)
for sub_idxs_2, sub_data_2 in feature_data_2.iterate(idxs_2)], dim=-1)
| |
<reponame>Khan/rbtools<gh_stars>0
#!/usr/bin/env python
import base64
import cookielib
import getpass
import logging
import mimetools
import os
import re
import sys
import urllib2
from optparse import OptionParser
from pkg_resources import parse_version
from urlparse import urljoin, urlparse
# We may have a problem: rbtools can be installed twice on the system:
# the 'canonical' rbtools, in /usr/lib or /usr/local/lib somewhere,
# and our branch of it, which lives here. We want to make sure our
# branch 'wins'. To do that, we add the root of our branch to the
# beginning of the path. The root is the directory above us.
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from rbtools import get_package_version, get_version_string
from rbtools.api.errors import APIError
from rbtools.clients import scan_usable_client
from rbtools.clients.perforce import PerforceClient
from rbtools.clients.plastic import PlasticClient
from rbtools.utils.filesystem import get_config_value, load_config_files
from rbtools.utils.process import die
try:
# Specifically import json_loads, to work around some issues with
# installations containing incompatible modules named "json".
from json import loads as json_loads
except ImportError:
from simplejson import loads as json_loads
options = None
configs = []
ADD_REPOSITORY_DOCS_URL = \
'http://www.reviewboard.org/docs/manual/dev/admin/configuration/repositories/'
class HTTPRequest(urllib2.Request):
def __init__(self, url, body='', headers={}, method="PUT"):
urllib2.Request.__init__(self, url, body, headers)
self.method = method
def get_method(self):
return self.method
class PresetHTTPAuthHandler(urllib2.BaseHandler):
"""urllib2 handler that conditionally presets the use of HTTP Basic Auth.
This is used when specifying --username= on the command line. It will
force an HTTP_AUTHORIZATION header with the user info, asking the user
for any missing info beforehand. It will then try this header for that
first request.
It will only do this once.
"""
handler_order = 480 # After Basic auth
def __init__(self, url, password_mgr):
self.url = url
self.password_mgr = password_mgr
self.used = False
def reset(self):
self.password_mgr.rb_user = options.http_username
self.password_mgr.rb_pass = options.http_password
self.used = False
def http_request(self, request):
if options.username and not self.used:
# Note that we call password_mgr.find_user_password to get the
# username and password we're working with. This allows us to
# prompt if, say, --username was specified but --password was not.
username, password = \
self.password_mgr.find_user_password('Web API', self.url)
raw = '%s:%s' % (username, password)
request.add_header(
urllib2.HTTPBasicAuthHandler.auth_header,
'Basic %s' % base64.b64encode(raw).strip())
self.used = True
return request
https_request = http_request
class ReviewBoardHTTPErrorProcessor(urllib2.HTTPErrorProcessor):
"""Processes HTTP error codes.
Python 2.6 gets HTTP error code processing right, but 2.4 and 2.5 only
accepts HTTP 200 and 206 as success codes. This handler ensures that
anything in the 200 range is a success.
"""
def http_response(self, request, response):
if not (200 <= response.code < 300):
response = self.parent.error('http', request, response,
response.code, response.msg,
response.info())
return response
https_response = http_response
class ReviewBoardHTTPBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
"""Custom Basic Auth handler that doesn't retry excessively.
urllib2's HTTPBasicAuthHandler retries over and over, which is useless.
This subclass only retries once to make sure we've attempted with a
valid username and password. It will then fail so we can use
tempt_fate's retry handler.
"""
def __init__(self, *args, **kwargs):
urllib2.HTTPBasicAuthHandler.__init__(self, *args, **kwargs)
self._retried = False
self._lasturl = ""
def retry_http_basic_auth(self, *args, **kwargs):
if self._lasturl != args[0]:
self._retried = False
self._lasturl = args[0]
if not self._retried:
self._retried = True
self.retried = 0
response = urllib2.HTTPBasicAuthHandler.retry_http_basic_auth(
self, *args, **kwargs)
if response.code != 401:
self._retried = False
return response
else:
return None
class ReviewBoardHTTPPasswordMgr(urllib2.HTTPPasswordMgr):
"""
Adds HTTP authentication support for URLs.
Python 2.4's password manager has a bug in http authentication when the
target server uses a non-standard port. This works around that bug on
Python 2.4 installs. This also allows post-review to prompt for passwords
in a consistent way.
See: http://bugs.python.org/issue974757
"""
def __init__(self, reviewboard_url, rb_user=None, rb_pass=None):
self.passwd = {}
self.rb_url = reviewboard_url
self.rb_user = rb_user
self.rb_pass = rb_pass
def find_user_password(self, realm, uri):
if realm == 'Web API':
if self.rb_user is None or self.rb_pass is None:
if options.diff_filename == '-':
die('HTTP authentication is required, but cannot be '
'used with --diff-filename=-')
print "==> HTTP Authentication Required"
print 'Enter authorization information for "%s" at %s' % \
(realm, urlparse(uri)[1])
if not self.rb_user:
self.rb_user = raw_input('Username: ')
if not self.rb_pass:
self.rb_pass = getpass.getpass('Password: ')
return self.rb_user, self.rb_pass
else:
# If this is an auth request for some other domain (since HTTP
# handlers are global), fall back to standard password management.
return urllib2.HTTPPasswordMgr.find_user_password(self, realm, uri)
class ReviewBoardServer(object):
"""
An instance of a Review Board server.
"""
def __init__(self, url, info, cookie_file):
self.url = url
if self.url[-1] != '/':
self.url += '/'
self._info = info
self._server_info = None
self.root_resource = None
self.deprecated_api = False
self.cookie_file = cookie_file
self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
if self.cookie_file:
try:
self.cookie_jar.load(self.cookie_file, ignore_expires=True)
except IOError:
pass
# Set up the HTTP libraries to support all of the features we need.
password_mgr = ReviewBoardHTTPPasswordMgr(self.url,
options.username,
options.password)
self.preset_auth_handler = PresetHTTPAuthHandler(self.url, password_mgr)
handlers = []
if options.disable_proxy:
debug('Disabling HTTP(s) proxy support')
handlers.append(urllib2.ProxyHandler({}))
handlers += [
urllib2.HTTPCookieProcessor(self.cookie_jar),
ReviewBoardHTTPBasicAuthHandler(password_mgr),
urllib2.HTTPDigestAuthHandler(password_mgr),
self.preset_auth_handler,
ReviewBoardHTTPErrorProcessor(),
]
opener = urllib2.build_opener(*handlers)
opener.addheaders = [('User-agent', 'RBTools/' + get_package_version())]
urllib2.install_opener(opener)
def check_api_version(self):
"""Checks the API version on the server to determine which to use."""
try:
root_resource = self.api_get('api/')
rsp = self.api_get(root_resource['links']['info']['href'])
self.rb_version = rsp['info']['product']['package_version']
if parse_version(self.rb_version) >= parse_version('1.5.2'):
self.deprecated_api = False
self.root_resource = root_resource
debug('Using the new web API')
return True
except APIError, e:
if e.http_status not in (401, 404):
# We shouldn't reach this. If there's a permission denied
# from lack of logging in, then the basic auth handler
# should have hit it.
#
# However in some versions it wants you to be logged in
# and returns a 401 from the application after you've
# done your http basic auth
die("Unable to access the root /api/ URL on the server.")
return False
# This is an older Review Board server with the old API.
self.deprecated_api = True
debug('Using the deprecated Review Board 1.0 web API')
return True
def login(self, force=False):
"""
Logs in to a Review Board server, prompting the user for login
information if needed.
"""
if (options.diff_filename == '-' and
not (self.has_valid_cookie() or
(options.username and options.password))):
die('Authentication information needs to be provided on '
'the command line when using --diff-filename=-')
if self.deprecated_api:
print "==> Review Board Login Required"
print "Enter username and password for Review Board at %s" % \
self.url
if options.username:
username = options.username
elif options.submit_as:
username = options.submit_as
elif not force and self.has_valid_cookie():
# We delay the check for a valid cookie until after looking
# at args, so that it doesn't override the command line.
return
else:
username = raw_input('Username: ')
if not options.password:
password = getpass.getpass('Password: ')
else:
password = options.password
debug('Logging in with username "%s"' % username)
try:
self.api_post('api/json/accounts/login/', {
'username': username,
'password': password,
})
except APIError, e:
die("Unable to log in: %s" % e)
debug("Logged in.")
elif force:
self.preset_auth_handler.reset()
def has_valid_cookie(self):
"""
Load the user's cookie file and see if they have a valid
'rbsessionid' cookie for the current Review Board server. Returns
true if so and false otherwise.
"""
try:
parsed_url = urlparse(self.url)
host = parsed_url[1]
path = parsed_url[2] or '/'
# Cookie files don't store port numbers, unfortunately, so
# get rid of the port number if it's present.
host = host.split(":")[0]
# Cookie files also append .local to bare hostnames
if '.' not in host:
host += '.local'
debug("Looking for '%s %s' cookie in %s" % \
(host, path, self.cookie_file))
try:
cookie = self.cookie_jar._cookies[host][path]['rbsessionid']
if not cookie.is_expired():
debug("Loaded valid cookie -- no login required")
return True
debug("Cookie file loaded, but cookie has expired")
except KeyError:
debug("Cookie file loaded, but no cookie for this server")
except IOError, error:
debug("Couldn't load cookie file: %s" % error)
return False
def new_review_request(self, changenum, submit_as=None):
"""
Creates a review request on a Review Board server, updating an
existing one if the changeset number already exists.
If submit_as is provided, the specified user name will be recorded as
the submitter of the review request (given that the logged in user has
the appropriate permissions).
"""
# If repository_path is a list, find a name in the list that's
# registered on the server.
if isinstance(self.info.path, list):
repositories = self.get_repositories()
debug("Repositories on Server: %s" % repositories)
debug("Server Aliases: %s" % self.info.path)
for repository in repositories:
if repository['path'] in self.info.path:
self.info.path = repository['path']
break
if isinstance(self.info.path, list):
sys.stderr.write('\n')
sys.stderr.write('There was | |
updated podcast
'''
self._check_arguement_type(podcast_id, int, 'Podcast ID must be int type')
pod = self.db_session.query(Podcast).get(podcast_id)
if not pod:
self._fail("Podcast not found for ID:%s" % podcast_id)
if podcast_name is not None:
self._check_arguement_type(podcast_name, str, 'Podcast name must be string type or None')
self.logger.debug("Updating podcast name to %s for podcast %s", podcast_name, podcast_id)
pod.name = utils.clean_string(podcast_name)
if artist_name is not None:
self._check_arguement_type(artist_name, str, 'Podcast name must be string type or None')
self.logger.debug("Updating artist name to %s for podcast %s", artist_name, podcast_id)
pod.artist_name = utils.clean_string(artist_name)
if archive_type is not None:
self._check_arguement_type(archive_type, str, 'Archive Type must be string type or None')
self._check_argument_oneof(archive_type, ARCHIVE_KEYS, 'Archive Type must be in accepted list')
self.logger.debug("Updating archive to %s for podcast %s", archive_type, podcast_id)
pod.archive_type = archive_type
if broadcast_id is not None:
self._check_arguement_type(broadcast_id, str, 'Broadcast ID must be string type or None')
self.logger.debug("Updating broadcast id to %s for podcast %s", broadcast_id, podcast_id)
pod.broadcast_id = utils.clean_string(broadcast_id)
if max_allowed is not None:
self._check_arguement_type(max_allowed, int, 'Max allowed must be int type or None')
if max_allowed < 0:
self._fail('Max allowed must be positive integer or 0')
if max_allowed == 0:
pod.max_allowed = None
else:
pod.max_allowed = max_allowed
self.logger.debug("Updating max allowed to %s for podcast %s", max_allowed, podcast_id)
if automatic_download is not None:
self._check_arguement_type(automatic_download, bool, 'Automatic download must be bool type')
self.logger.debug("Updating automatic download to %s for podcast %s", automatic_download, podcast_id)
pod.automatic_episode_download = automatic_download
try:
self.db_session.commit()
self.logger.info("Podcast %s update commited", pod.id)
except IntegrityError:
self.db_session.rollback()
self._fail('Cannot update podcast id:%s' % podcast_id)
return pod.as_dict(self.datetime_output_format)
@run_plugins()
def podcast_update_file_location(self, podcast_id, file_location, move_files=True):
'''
Update file location of podcast files
podcast_id : ID of podcast to edit
file_location : New location for podcast files
move_files : Whether or not episode files will be moved to new directory
Returns: null
'''
self._check_arguement_type(podcast_id, int, 'Podcast ID must be int type')
self._check_arguement_type(file_location, str, 'File location must be None or string type')
pod = self.db_session.query(Podcast).get(podcast_id)
if not pod:
self._fail("Podcast not found for ID:%s" % podcast_id)
old_podcast_dir = pod.file_location
pod.file_location = os.path.abspath(file_location)
self.db_session.commit()
self.logger.info("Updated podcast id:%s file location to %s", podcast_id, file_location)
if move_files:
self.logger.info("Moving files from old dir:%s to new dir:%s", old_podcast_dir, pod.file_location)
self._ensure_path(pod.file_location)
episodes = self.db_session.query(PodcastEpisode).filter(PodcastEpisode.podcast_id == podcast_id)
episodes = episodes.filter(PodcastEpisode.file_path != None)
for episode in episodes:
episode_name_path = os.path.basename(episode.file_path)
new_path = os.path.join(pod.file_location, episode_name_path)
os.rename(episode.file_path, new_path)
episode.file_path = new_path
self.logger.info("Updating episode %s to path %s in db", episode.id, episode.file_path)
self.db_session.commit()
self._remove_directory(old_podcast_dir)
return pod.as_dict(self.datetime_output_format)
@run_plugins()
def podcast_delete(self, podcast_input, delete_files=True):
'''
Delete podcasts and their episodes
podcast_input : Either a single integer id, or list of integer ids
delete_files : Delete episode media files along with database entries
Returns: List of integers IDs of podcasts deleted
'''
query = self._database_select(Podcast, podcast_input)
return self.__podcast_delete_input(query, delete_files)
@run_plugins()
def __podcast_delete_input(self, podcast_input, delete_files):
podcasts_deleted = []
for podcast in podcast_input:
# first delete all episodes
episodes = self.db_session.query(PodcastEpisode).filter(PodcastEpisode.podcast_id == podcast.id).all()
self.__episode_delete_input(episodes, delete_files=delete_files)
# delete all filters
filters = self.db_session.query(PodcastTitleFilter).filter(PodcastTitleFilter.podcast_id == podcast.id).all()
self.__podcast_title_filter_delete_input(filters)
# delete record
self.db_session.delete(podcast)
self.db_session.commit()
self.logger.info("Deleted podcast record:%s", podcast.id)
# delete files if needed
if delete_files:
self._remove_directory(podcast.file_location)
podcasts_deleted.append(podcast.id)
return podcasts_deleted
@run_plugins()
def filter_create(self, podcast_id, regex_string):
'''
Add a new title filter to podcast. When running an episode sync, if a title in the archive does
not match the regex string, it will be ignored.
podcast_id : ID of podcast to add filter to
regex_string : Regex string to use when matching against an archive item title
Returns: dict object representing new podcast filter
'''
self._check_arguement_type(podcast_id, int, 'Podcast ID must be int type')
self._check_arguement_type(regex_string, str, 'Regex string must be string type')
podcast = self.db_session.query(Podcast).get(podcast_id)
if not podcast:
self._fail("Unable to find podcast with id:%s" % podcast_id)
new_args = {
'podcast_id' : podcast.id,
'regex_string' : regex_string,
}
new_filter = PodcastTitleFilter(**new_args)
self.db_session.add(new_filter)
self.db_session.commit()
self.logger.info("Created new podcast filter:%s, podcast_id:%s and regex:%s",
new_filter.id, podcast.id, regex_string)
return new_filter.as_dict(self.datetime_output_format)
@run_plugins()
def filter_list(self, include_podcasts=None, exclude_podcasts=None):
'''
List podcast title filters
include_podcasts : Include only certain podcasts in results
exclude_podcasts : Exclude certain podcasts in results
Returns: list of dictionaries representing the podcast title filters
'''
include_podcasts, exclude_podcasts = self._check_includers(include_podcasts, exclude_podcasts)
query = self.db_session.query(PodcastTitleFilter)
if include_podcasts:
opts = (PodcastTitleFilter.podcast_id == pod for pod in include_podcasts)
query = query.filter(or_(opts))
if exclude_podcasts:
opts = (PodcastTitleFilter.podcast_id != pod for pod in exclude_podcasts)
query = query.filter(and_(opts))
filters = []
for title_filter in query:
filters.append(title_filter.as_dict(self.datetime_output_format))
return filters
@run_plugins()
def filter_delete(self, filter_input):
'''
Delete one or many title filters
filter_input : Either a single int id, or a list of int ids
Returns: list of ids of deleted podcast title filters
'''
query = self._database_select(PodcastTitleFilter, filter_input)
return self.__podcast_title_filter_delete_input(query)
@run_plugins()
def __podcast_title_filter_delete_input(self, filter_input):
filters_deleted = []
for title_filter in filter_input:
self.db_session.delete(title_filter)
self.db_session.commit()
filters_deleted.append(title_filter.id)
self.logger.info("Deleted podcast title filter:%s", title_filter.id)
return filters_deleted
@run_plugins()
def episode_sync(self, include_podcasts=None, exclude_podcasts=None, max_episode_sync=None):
'''
Sync podcast episode data with the interwebs. Will not download episode files
include_podcasts : Include only certain podcasts in sync
exclude_podcasts : Exclude certain podcasts in sync
max_episode_sync : Sync up to N number of episodes, to override each podcasts max allowed
For unlimited number of episodes, use 0
Returns: list of dictionaries representing new episodes added
'''
include_podcasts, exclude_podcasts = self._check_includers(include_podcasts, exclude_podcasts)
self._check_arguement_type(max_episode_sync, [None, int], 'Max episode sync must be None or int type')
return self.__episode_sync_cluders(include_podcasts, exclude_podcasts, max_episode_sync=max_episode_sync)
@run_plugins()
def __episode_sync_cluders(self, include_podcasts, exclude_podcasts,
max_episode_sync=None, automatic_sync=True):
query = self.db_session.query(Podcast)
if include_podcasts:
opts = (Podcast.id == pod for pod in include_podcasts)
query = query.filter(or_(opts))
if exclude_podcasts:
opts = (Podcast.id != pod for pod in exclude_podcasts)
query = query.filter(and_(opts))
new_episodes = []
for podcast in query:
if not automatic_sync and not podcast.automatic_episode_download:
self.logger.debug("Skipping episode sync on podcast:%s", podcast.id)
continue
self.logger.debug("Running episode sync on podcast %s", podcast.id)
manager = self._archive_manager(podcast.archive_type)
# if sync all episodes, give no max results so all episodes returned
if max_episode_sync is None:
max_results = podcast.max_allowed
elif max_episode_sync is 0:
max_results = None
else:
max_results = max_episode_sync
# check for filters for podcast
compiled_filters = [re.compile(f.regex_string) for f in \
self.db_session.query(PodcastTitleFilter).\
filter(PodcastTitleFilter.podcast_id == podcast.id)]
current_episodes = manager.broadcast_update(podcast.broadcast_id,
max_results=max_results,
filters=compiled_filters)
for episode in current_episodes:
episode_args = {
'title' : episode['title'],
'date' : episode['date'],
'description' : episode['description'],
'download_url' : episode['download_link'],
'podcast_id' : podcast.id,
'prevent_deletion' : False,
}
new_episode = PodcastEpisode(**episode_args)
try:
self.db_session.add(new_episode)
self.db_session.commit()
self.logger.debug("Created new podcast episode %s with args %s", new_episode.id,
' -- '.join('%s-%s' % (k, v) for k, v in episode_args.items()))
new_episodes.append(new_episode.as_dict(self.datetime_output_format))
except IntegrityError:
# if you attempt to add another episode with the same
# url, it will fail here, thats expected, we dont want
# duplicate episodes
self.db_session.rollback()
self.logger.debug("Podcast episode is duplicate, title was %s", episode_args['title'])
return new_episodes
@run_plugins()
def episode_list(self, only_files=True, sort_date=False, include_podcasts=None, exclude_podcasts=None):
'''
List Podcast Episodes
only_files : Indicates you only want to list episodes with a file_path
sort_date : Sort by date, most recent first
include_podcasts : Only include these podcasts. Single ID or lists of IDs
exclude_podcasts : Do not include these podcasts. Single ID or list of IDs
Returns: List of dictionaries for all episodes requested
'''
self._check_arguement_type(only_files, bool, 'Only Files must be boolean type')
self._check_arguement_type(sort_date, bool, 'Sort date must be boolean type')
include_podcasts, exclude_podcasts = self._check_includers(include_podcasts, exclude_podcasts)
query = self.db_session.query(PodcastEpisode)
if only_files:
query = query.filter(PodcastEpisode.file_path != None)
if sort_date:
query = query.order_by(desc(PodcastEpisode.date))
if include_podcasts:
opts = (PodcastEpisode.podcast_id == pod for pod in include_podcasts)
query = query.filter(or_(opts))
if exclude_podcasts:
opts = (PodcastEpisode.podcast_id != pod for pod in exclude_podcasts)
query = query.filter(and_(opts))
episode_data = []
for episode in query.all():
episode_data.append(episode.as_dict(self.datetime_output_format))
return episode_data
@run_plugins()
def episode_show(self, episode_input):
'''
Get information about one or many podcast episodes
episode_input : Either a single integer id or list of integer ids
Returns: List of dictionaries for all episodes requested
'''
query = self._database_select(PodcastEpisode, episode_input)
episode_list = []
for episode in query:
episode_list.append(episode.as_dict(self.datetime_output_format))
return episode_list
@run_plugins()
def episode_update(self, episode_id, prevent_delete=None):
'''
Update episode information
episode_id : ID of episode to update
prevent_deletion : Prevent deletion of episode from podcast sync
Returns: dict representing updated episodes
'''
episode = self.db_session.query(PodcastEpisode).get(episode_id)
if not episode:
self._fail("Podcast Episode not found for ID:%s" % episode_id)
self._check_arguement_type(prevent_delete, [None, bool], 'Prevent delete | |
#
# Copyright (C) 2013 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
{
'includes': [
'../build/features.gypi',
'../build/scripts/scripts.gypi',
'../build/win/precompile.gypi',
'blink_platform.gypi',
'heap/blink_heap.gypi',
],
'targets': [{
'target_name': 'blink_common',
'type': '<(component)',
'variables': { 'enable_wexit_time_destructors': 1 },
'dependencies': [
'../config.gyp:config',
'../wtf/wtf.gyp:wtf',
# FIXME: Can we remove the dependency on Skia?
'<(DEPTH)/skia/skia.gyp:skia',
],
'all_dependent_settings': {
'include_dirs': [
'..',
],
},
'export_dependent_settings': [
'<(DEPTH)/skia/skia.gyp:skia',
],
'defines': [
'BLINK_COMMON_IMPLEMENTATION=1',
'INSIDE_BLINK',
],
'include_dirs': [
'<(SHARED_INTERMEDIATE_DIR)/blink',
],
'sources': [
'exported/WebCString.cpp',
'exported/WebString.cpp',
'exported/WebCommon.cpp',
],
},
{
'target_name': 'blink_heap_asm_stubs',
'type': 'static_library',
# VS2010 does not correctly incrementally link obj files generated
# from asm files. This flag disables UseLibraryDependencyInputs to
# avoid this problem.
'msvs_2010_disable_uldi_when_referenced': 1,
'includes': [
'../../../yasm/yasm_compile.gypi',
],
'sources': [
'<@(platform_heap_asm_files)',
],
'variables': {
'more_yasm_flags': [],
'conditions': [
['OS == "mac"', {
'more_yasm_flags': [
# Necessary to ensure symbols end up with a _ prefix; added by
# yasm_compile.gypi for Windows, but not Mac.
'-DPREFIX',
],
}],
['OS == "win" and target_arch == "x64"', {
'more_yasm_flags': [
'-DX64WIN=1',
],
}],
['OS != "win" and target_arch == "x64"', {
'more_yasm_flags': [
'-DX64POSIX=1',
],
}],
['target_arch == "ia32"', {
'more_yasm_flags': [
'-DIA32=1',
],
}],
['target_arch == "arm"', {
'more_yasm_flags': [
'-DARM=1',
],
}],
],
'yasm_flags': [
'>@(more_yasm_flags)',
],
'yasm_output_path': '<(SHARED_INTERMEDIATE_DIR)/webcore/heap'
},
},
{
'target_name': 'blink_prerequisites',
'type': 'none',
'conditions': [
['OS=="mac"', {
'direct_dependent_settings': {
'defines': [
# Chromium's version of WebCore includes the following Objective-C
# classes. The system-provided WebCore framework may also provide
# these classes. Because of the nature of Objective-C binding
# (dynamically at runtime), it's possible for the
# Chromium-provided versions to interfere with the system-provided
# versions. This may happen when a system framework attempts to
# use core.framework, such as when converting an HTML-flavored
# string to an NSAttributedString. The solution is to force
# Objective-C class names that would conflict to use alternate
# names.
#
# This list will hopefully shrink but may also grow. Its
# performance is monitored by the "Check Objective-C Rename"
# postbuild step, and any suspicious-looking symbols not handled
# here or whitelisted in that step will cause a build failure.
#
# If this is unhandled, the console will receive log messages
# such as:
# com.google.Chrome[] objc[]: Class ScrollbarPrefsObserver is implemented in both .../Google Chrome.app/Contents/Versions/.../Google Chrome Helper.app/Contents/MacOS/../../../Google Chrome Framework.framework/Google Chrome Framework and /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/WebCore. One of the two will be used. Which one is undefined.
'WebCascadeList=ChromiumWebCoreObjCWebCascadeList',
'WebScrollAnimationHelperDelegate=ChromiumWebCoreObjCWebScrollAnimationHelperDelegate',
'WebScrollbarPainterControllerDelegate=ChromiumWebCoreObjCWebScrollbarPainterControllerDelegate',
'WebScrollbarPainterDelegate=ChromiumWebCoreObjCWebScrollbarPainterDelegate',
'WebScrollbarPartAnimation=ChromiumWebCoreObjCWebScrollbarPartAnimation',
'WebCoreFlippedView=ChromiumWebCoreObjCWebCoreFlippedView',
'WebCoreTextFieldCell=ChromiumWebCoreObjCWebCoreTextFieldCell',
],
'postbuilds': [
{
# This step ensures that any Objective-C names that aren't
# redefined to be "safe" above will cause a build failure.
'postbuild_name': 'Check Objective-C Rename',
'variables': {
'class_whitelist_regex':
'ChromiumWebCoreObjC|TCMVisibleView|RTCMFlippedView|ScrollerStyleObserver|LayoutThemeNotificationObserver',
'category_whitelist_regex':
'WebCoreFocusRingDrawing|WebCoreTheme',
},
'action': [
'../build/scripts/check_objc_rename.sh',
'<(class_whitelist_regex)',
'<(category_whitelist_regex)',
],
},
],
},
}],
],
},
{
'target_name': 'blink_platform',
'type': '<(component)',
'dependencies': [
'../config.gyp:config',
'../wtf/wtf.gyp:wtf',
'blink_common',
'blink_heap_asm_stubs',
'blink_prerequisites',
'<(DEPTH)/gpu/gpu.gyp:gles2_c_lib',
'<(DEPTH)/skia/skia.gyp:skia',
'<(DEPTH)/third_party/icu/icu.gyp:icui18n',
'<(DEPTH)/third_party/icu/icu.gyp:icuuc',
'<(DEPTH)/third_party/libpng/libpng.gyp:libpng',
'<(DEPTH)/third_party/libwebp/libwebp.gyp:libwebp',
'<(DEPTH)/third_party/ots/ots.gyp:ots',
'<(DEPTH)/third_party/qcms/qcms.gyp:qcms',
'<(DEPTH)/url/url.gyp:url_lib',
'<(DEPTH)/v8/tools/gyp/v8.gyp:v8',
'platform_generated.gyp:make_platform_generated',
'<(DEPTH)/third_party/iccjpeg/iccjpeg.gyp:iccjpeg',
'<(libjpeg_gyp_path):libjpeg',
],
'export_dependent_settings': [
'<(DEPTH)/gpu/gpu.gyp:gles2_c_lib',
'<(DEPTH)/skia/skia.gyp:skia',
'<(DEPTH)/third_party/libpng/libpng.gyp:libpng',
'<(DEPTH)/third_party/libwebp/libwebp.gyp:libwebp',
'<(DEPTH)/third_party/ots/ots.gyp:ots',
'<(DEPTH)/third_party/qcms/qcms.gyp:qcms',
'<(DEPTH)/v8/tools/gyp/v8.gyp:v8',
'<(DEPTH)/url/url.gyp:url_lib',
'<(DEPTH)/third_party/iccjpeg/iccjpeg.gyp:iccjpeg',
'<(libjpeg_gyp_path):libjpeg',
],
'defines': [
'BLINK_PLATFORM_IMPLEMENTATION=1',
'INSIDE_BLINK',
],
'include_dirs': [
'<(angle_path)/include',
'<(SHARED_INTERMEDIATE_DIR)/blink',
],
'xcode_settings': {
# Some Mac-specific parts of WebKit won't compile without having this
# prefix header injected.
'GCC_PREFIX_HEADER': '<(DEPTH)/third_party/WebKit/Source/build/mac/Prefix.h',
},
'sources': [
'<@(platform_files)',
'<@(platform_heap_files)',
# Additional .cpp files from platform_generated.gyp:make_platform_generated actions.
'<(blink_platform_output_dir)/FontFamilyNames.cpp',
'<(blink_platform_output_dir)/RuntimeEnabledFeatures.cpp',
'<(blink_platform_output_dir)/RuntimeEnabledFeatures.h',
'<(blink_platform_output_dir)/ColorData.cpp',
],
'sources/': [
# Exclude all platform specific things, reinclude them below on a per-platform basis
# FIXME: Figure out how to store these patterns in a variable.
['exclude', '(cf|cg|mac|opentype|win)/'],
['exclude', '(?<!Chromium)(CF|CG|Mac|Win)\\.(cpp|mm?)$'],
# *NEON.cpp files need special compile options.
# They are moved to the webcore_0_neon target.
['exclude', 'graphics/cpu/arm/.*NEON\\.(cpp|h)'],
['exclude', 'graphics/cpu/arm/filters/.*NEON\\.(cpp|h)'],
],
# Disable c4267 warnings until we fix size_t to int truncations.
# Disable c4724 warnings which is generated in VS2012 due to improper
# compiler optimizations, see crbug.com/237063
'msvs_disabled_warnings': [ 4267, 4334, 4724 ],
'conditions': [
['OS=="linux" or OS=="android" or OS=="win"', {
'sources/': [
# Cherry-pick files excluded by the broader regular expressions above.
['include', 'fonts/opentype/OpenTypeTypes\\.h$'],
['include', 'fonts/opentype/OpenTypeVerticalData\\.(cpp|h)$'],
],
'dependencies': [
'<(DEPTH)/third_party/harfbuzz-ng/harfbuzz.gyp:harfbuzz-ng',
],
},
],
['OS=="linux" or OS=="android"', {
'sources/': [
['include', 'fonts/linux/FontPlatformDataLinux\\.cpp$'],
]
}, { # OS!="linux" and OS!="android"
'sources/': [
['exclude', 'fonts/linux/FontPlatformDataLinux\\.cpp$'],
]
}],
['OS=="mac"', {
'dependencies': [
'<(DEPTH)/third_party/harfbuzz-ng/harfbuzz.gyp:harfbuzz-ng',
],
'link_settings': {
'libraries': [
'$(SDKROOT)/System/Library/Frameworks/Accelerate.framework',
'$(SDKROOT)/System/Library/Frameworks/Carbon.framework',
'$(SDKROOT)/System/Library/Frameworks/Foundation.framework',
]
},
'sources/': [
# We use LocaleMac.mm instead of LocaleICU.cpp
['exclude', 'text/LocaleICU\\.(cpp|h)$'],
['include', 'text/LocaleMac\\.mm$'],
# The Mac uses mac/KillRingMac.mm instead of the dummy
# implementation.
['exclude', 'KillRingNone\\.cpp$'],
# The Mac build is USE(CF).
['include', 'CF\\.cpp$'],
# Use native Mac font code from core.
['include', '(fonts/)?mac/[^/]*Font[^/]*\\.(cpp|mm?)$'],
# TODO(dro): Merge the opentype vertical data files inclusion across all platforms.
['include', 'fonts/opentype/OpenTypeTypes\\.h$'],
['include', 'fonts/opentype/OpenTypeVerticalData\\.(cpp|h)$'],
# Cherry-pick some files that can't be included by broader regexps.
# Some of these are used instead of Chromium platform files, see
# the specific exclusions in the "exclude" list below.
['include', 'audio/mac/FFTFrameMac\\.cpp$'],
['include', 'fonts/mac/GlyphPageTreeNodeMac\\.cpp$'],
['include', 'mac/ColorMac\\.mm$'],
['include', 'mac/BlockExceptions\\.mm$'],
['include', 'mac/KillRingMac\\.mm$'],
['include', 'mac/LocalCurrentGraphicsContext\\.mm$'],
['include', 'mac/NSScrollerImpDetails\\.mm$'],
['include', 'mac/ScrollAnimatorMac\\.mm$'],
['include', 'mac/ThemeMac\\.h$'],
['include', 'mac/ThemeMac\\.mm$'],
['include', 'mac/WebCoreNSCellExtras\\.h$'],
['include', 'mac/WebCoreNSCellExtras\\.mm$'],
# Mac uses only ScrollAnimatorMac.
['exclude', 'scroll/ScrollbarThemeNonMacCommon\\.(cpp|h)$'],
['exclude', 'scroll/ScrollAnimatorNone\\.cpp$'],
['exclude', 'scroll/ScrollAnimatorNone\\.h$'],
['exclude', 'fonts/skia/FontCacheSkia\\.cpp$'],
['include', 'geometry/mac/FloatPointMac\\.mm$'],
['include', 'geometry/mac/FloatRectMac\\.mm$'],
['include', 'geometry/mac/FloatSizeMac\\.mm$'],
['include', 'geometry/mac/IntPointMac\\.mm$'],
['include', 'geometry/mac/IntRectMac\\.mm$'],
['include', 'geometry/cg/FloatPointCG\\.cpp$'],
['include', 'geometry/cg/FloatRectCG\\.cpp$'],
['include', 'geometry/cg/FloatSizeCG\\.cpp$'],
['include', 'geometry/cg/IntPointCG\\.cpp$'],
['include', 'geometry/cg/IntRectCG\\.cpp$'],
['include', 'geometry/cg/IntSizeCG\\.cpp$'],
],
}, { # OS!="mac"
'sources/': [
['exclude', 'mac/'],
['exclude', 'geometry/mac/'],
['exclude', 'geometry/cg/'],
['exclude', 'scroll/ScrollbarThemeMac'],
],
}],
['OS != "linux" and OS != "mac" and OS != "win"', {
'sources/': [
['exclude', 'VDMX[^/]+\\.(cpp|h)$'],
],
}],
['OS=="win"', {
'sources/': [
# We use LocaleWin.cpp instead of LocaleICU.cpp
['exclude', 'text/LocaleICU\\.(cpp|h)$'],
['include', 'text/LocaleWin\\.(cpp|h)$'],
['include', 'clipboard/ClipboardUtilitiesWin\\.(cpp|h)$'],
['include', 'fonts/opentype/'],
['include', 'fonts/win/FontCacheSkiaWin\\.cpp$'],
['include', 'fonts/win/FontFallbackWin\\.(cpp|h)$'],
['include', 'fonts/win/FontPlatformDataWin\\.cpp$'],
# SystemInfo.cpp is useful and we don't want to copy it.
['include', 'win/SystemInfo\\.cpp$'],
],
}, { # OS!="win"
'sources/': [
['exclude', 'win/'],
['exclude', 'Win\\.cpp$'],
['exclude', '/(Windows)[^/]*\\.cpp$'],
['include', 'fonts/opentype/OpenTypeSanitizer\\.cpp$'],
],
}],
['OS=="win" and chromium_win_pch==1', {
'sources/': [
['include', '<(DEPTH)/third_party/WebKit/Source/build/win/Precompile.cpp'],
],
}],
['OS=="android"', {
'sources/': [
['include', '^fonts/VDMXParser\\.cpp$'],
],
}, { # OS!="android"
'sources/': [
['exclude', 'Android\\.cpp$'],
],
}],
['OS=="linux"', {
'dependencies': [
'<(DEPTH)/build/linux/system.gyp:fontconfig',
],
'export_dependent_settings': [
'<(DEPTH)/build/linux/system.gyp:fontconfig',
],
}],
['use_default_render_theme==0', {
'sources/': [
['exclude', 'scroll/ScrollbarThemeAura\\.(cpp|h)'],
],
}],
['"WTF_USE_WEBAUDIO_FFMPEG=1" in feature_defines', {
'include_dirs': [
'<(DEPTH)/third_party/ffmpeg',
],
'dependencies': [
'<(DEPTH)/third_party/ffmpeg/ffmpeg.gyp:ffmpeg',
],
}],
['"WTF_USE_WEBAUDIO_OPENMAX_DL_FFT=1" in feature_defines', {
'include_dirs': [
'<(DEPTH)/third_party/openmax_dl',
],
'dependencies': [
'<(DEPTH)/third_party/openmax_dl/dl/dl.gyp:openmax_dl',
],
}],
['target_arch=="arm"', {
'dependencies': [
'blink_arm_neon',
],
}],
],
'target_conditions': [
['OS=="android"', {
'sources/': [
['include', 'exported/linux/WebFontRenderStyle\\.cpp$'],
['include', 'fonts/linux/FontPlatformDataLinux\\.cpp$'],
],
}],
],
},
# The *NEON.cpp files fail to compile when -mthumb is passed. Force
# them to build in ARM mode.
# See https://bugs.webkit.org/show_bug.cgi?id=62916.
{
'target_name': 'blink_arm_neon',
'conditions': [
['target_arch=="arm"', {
'type': 'static_library',
'dependencies': [
'blink_common',
],
'hard_dependency': 1,
'sources': [
'<@(platform_files)',
],
'sources/': [
['exclude', '.*'],
['include', 'graphics/cpu/arm/filters/.*NEON\\.(cpp|h)'],
],
'cflags': ['-marm'],
'conditions': [
['OS=="android"', {
'cflags!': | |
project_path)
plot.delete()
return file_to_add
return None
@aedt_exception_handler
def plot_model_obj(
self,
objects=None,
show=True,
export_path=None,
plot_as_separate_objects=True,
plot_air_objects=False,
force_opacity_value=None,
clean_files=False,
):
"""Plot the model or a substet of objects.
Parameters
----------
objects : list, optional
Optional list of objects to plot. If `None` all objects will be exported.
show : bool, optional
Show the plot after generation or simply return the
generated Class for more customization before plot.
export_path : str, optional
If available, an image is saved to file. If `None` no image will be saved.
plot_as_separate_objects : bool, optional
Plot each object separately. It may require more time to export from AEDT.
plot_air_objects : bool, optional
Plot also air and vacuum objects.
force_opacity_value : float, optional
Opacity value between 0 and 1 to be applied to all model.
If `None` aedt opacity will be applied to each object.
clean_files : bool, optional
Clean created files after plot. Cache is mainteined into the model object returned.
Returns
-------
:class:`pyaedt.modules.AdvancedPostProcessing.ModelPlotter`
Model Object.
"""
assert self._app._aedt_version >= "2021.2", self.logger.error("Object is supported from AEDT 2021 R2.")
files = self.export_model_obj(
obj_list=objects,
export_as_single_objects=plot_as_separate_objects,
air_objects=plot_air_objects,
)
if not files:
self.logger.warning("No Objects exported. Try other options or include Air objects.")
return False
model = ModelPlotter()
for file in files:
if force_opacity_value:
model.add_object(file[0], file[1], force_opacity_value, self.modeler.model_units)
else:
model.add_object(file[0], file[1], file[2], self.modeler.model_units)
if not show:
model.off_screen = True
if export_path:
model.plot(export_path)
elif show:
model.plot()
if clean_files:
model.clean_cache_and_files(clean_cache=False)
return model
@aedt_exception_handler
def plot_field_from_fieldplot(
self,
plotname,
project_path="",
meshplot=False,
imageformat="jpg",
view="isometric",
plot_label="Temperature",
plot_folder=None,
show=True,
scale_min=None,
scale_max=None,
):
"""Export a field plot to an image file (JPG or PNG) using Python Plotly.
.. note::
The Plotly module rebuilds the mesh and the overlap fields on the mesh.
Parameters
----------
plotname : str
Name of the field plot to export.
project_path : str, optional
Path for saving the image file. The default is ``""``.
meshplot : bool, optional
Whether to create and plot the mesh over the fields. The
default is ``False``.
imageformat : str, optional
Format of the image file. Options are ``"jpg"``,
``"png"``, ``"svg"``, and ``"webp"``. The default is
``"jpg"``.
view : str, optional
View to export. Options are ``isometric``, ``top``, ``front``,
``left``, ``all``.. The default is ``"iso"``. If ``"all"``, all views are exported.
plot_label : str, optional
Type of the plot. The default is ``"Temperature"``.
plot_folder : str, optional
Plot folder to update before exporting the field.
The default is ``None``, in which case all plot
folders are updated.
show : bool, optional
Export Image without plotting on UI.
scale_min : float, optional
Fix the Scale Minimum value.
scale_max : float, optional
Fix the Scale Maximum value.
Returns
-------
:class:`pyaedt.modules.AdvancedPostProcessing.ModelPlotter`
Model Object.
"""
if not plot_folder:
self.ofieldsreporter.UpdateAllFieldsPlots()
else:
self.ofieldsreporter.UpdateQuantityFieldsPlots(plot_folder)
start = time.time()
file_to_add = self.export_field_plot(plotname, self._app.project_path)
models = None
if not file_to_add:
return False
else:
if meshplot:
if self._app._aedt_version >= "2021.2":
models = self.export_model_obj(export_as_single_objects=True, air_objects=False)
model = ModelPlotter()
model.off_screen = not show
if file_to_add:
model.add_field_from_file(file_to_add, coordinate_units=self.modeler.model_units)
if plot_label:
model.fields[0].label = plot_label
if models:
for m in models:
model.add_object(m[0], m[1], m[2])
model.view = view
if scale_min and scale_max:
model.range_min = scale_min
model.range_max = scale_max
if show or project_path:
model.plot(os.path.join(project_path, self._app.project_name + "." + imageformat))
model.clean_cache_and_files(clean_cache=False)
return model
@aedt_exception_handler
def animate_fields_from_aedtplt(
self,
plotname,
plot_folder=None,
meshplot=False,
variation_variable="Phi",
variation_list=["0deg"],
project_path="",
export_gif=False,
show=True,
):
"""Generate a field plot to an image file (JPG or PNG) using PyVista.
.. note::
The PyVista module rebuilds the mesh and the overlap fields on the mesh.
Parameters
----------
plotname : str
Name of the plot or the name of the object.
plot_folder : str, optional
Name of the folder in which the plot resides. The default
is ``None``.
variation_variable : str, optional
Variable to vary. The default is ``"Phi"``.
variation_list : list, optional
List of variation values with units. The default is
``["0deg"]``.
project_path : str, optional
Path for the export. The default is ``""``.
meshplot : bool, optional
The default is ``False``. Valid from Version 2021.2.
export_gif : bool, optional
The default is ``False``.
show=False,
show : bool, optional
Generate the animation without showing an interactive plot. The default is ``True``.
Returns
-------
:class:`pyaedt.modules.AdvancedPostProcessing.ModelPlotter`
Model Object.
"""
if not plot_folder:
self.ofieldsreporter.UpdateAllFieldsPlots()
else:
self.ofieldsreporter.UpdateQuantityFieldsPlots(plot_folder)
models_to_add = []
if meshplot:
if self._app._aedt_version >= "2021.2":
models_to_add = self.export_model_obj(export_as_single_objects=True, air_objects=False)
fields_to_add = []
if not project_path:
project_path = self._app.project_path
for el in variation_list:
self._app._odesign.ChangeProperty(
[
"NAME:AllTabs",
[
"NAME:FieldsPostProcessorTab",
["NAME:PropServers", "FieldsReporter:" + plotname],
["NAME:ChangedProps", ["NAME:" + variation_variable, "Value:=", el]],
],
]
)
fields_to_add.append(
self.export_field_plot(plotname, project_path, plotname + variation_variable + str(el))
)
model = ModelPlotter()
model.off_screen = not show
if models_to_add:
for m in models_to_add:
model.add_object(m[0], cad_color=m[1], opacity=m[2])
if fields_to_add:
model.add_frames_from_file(fields_to_add)
if export_gif:
model.gif_file = os.path.join(self._app.project_path, self._app.project_name + ".gif")
if show or export_gif:
model.animate()
model.clean_cache_and_files(clean_cache=False)
return model
@aedt_exception_handler
def animate_fields_from_aedtplt_2(
self,
quantityname,
object_list,
plottype,
meshplot=False,
setup_name=None,
intrinsic_dict={},
variation_variable="Phi",
variation_list=["0deg"],
project_path="",
export_gif=False,
show=True,
):
"""Generate a field plot to an animated gif file using PyVista.
.. note::
The PyVista module rebuilds the mesh and the overlap fields on the mesh.
This method creates the plot and exports it.
It is an alternative to the method :func:`animate_fields_from_aedtplt`,
which uses an existing plot.
Parameters
----------
quantityname : str
Name of the plot or the name of the object.
object_list : list, optional
Name of the ``folderplot`` folder.
plottype : str
Type of the plot. Options are ``"Surface"``, ``"Volume"``, and
``"CutPlane"``.
meshplot : bool, optional
The default is ``False``.
setup_name : str, optional
Name of the setup (sweep) to use for the export. The default is
``None``.
intrinsic_dict : dict, optional
Intrinsic dictionary that is needed for the export.
The default is ``{}``.
variation_variable : str, optional
Variable to vary. The default is ``"Phi"``.
variation_list : list, option
List of variation values with units. The default is
``["0deg"]``.
project_path : str, optional
Path for the export. The default is ``""``.
export_gif : bool, optional
Whether to export to a GIF file. The default is ``False``,
in which case the plot is exported to a JPG file.
show : bool, optional
Generate the animation without showing an interactive plot. The default is ``True``.
Returns
-------
:class:`pyaedt.modules.AdvancedPostProcessing.ModelPlotter`
Model Object.
"""
if not project_path:
project_path = self._app.project_path
models_to_add = []
if meshplot:
if self._app._aedt_version >= "2021.2":
models_to_add = self.export_model_obj(export_as_single_objects=True, air_objects=False)
v = 0
fields_to_add = []
for el in variation_list:
intrinsic_dict[variation_variable] = el
if plottype == "Surface":
plotf = self.create_fieldplot_surface(object_list, quantityname, setup_name, intrinsic_dict)
elif plottype == "Volume":
plotf = self.create_fieldplot_volume(object_list, quantityname, setup_name, intrinsic_dict)
else:
plotf = self.create_fieldplot_cutplane(object_list, quantityname, setup_name, intrinsic_dict)
if plotf:
file_to_add = self.export_field_plot(plotf.name, project_path, plotf.name + str(v))
if file_to_add:
fields_to_add.append(file_to_add)
plotf.delete()
v += 1
model = ModelPlotter()
model.off_screen = not show
if models_to_add:
for m in models_to_add:
model.add_object(m[0], cad_color=m[1], opacity=m[2])
if fields_to_add:
model.add_frames_from_file(fields_to_add)
if export_gif:
model.gif_file = os.path.join(self._app.project_path, self._app.project_name + ".gif")
if show or export_gif:
model.animate()
model.clean_cache_and_files(clean_cache=False)
return model
@aedt_exception_handler
def far_field_plot(self, ff_data, x=0, y=0, qty="rETotal", dB=True, array_size=[4, 4]):
"""Generate a far field plot.
Parameters
----------
ff_data :
x : float, optional
The default is ``0``.
y : float, optional
The default is ``0``.
qty : str, optional
The default is ``"rETotal"``.
dB : bool, optional
The default is ``True``.
array_size : list
List for the array size. The default is ``[4, 4]``.
Returns
-------
bool
``True`` when successful, ``False`` when failed.
"""
loc_offset = 2 # if array index is not starting at [1,1]
xphase = float(y)
yphase = float(x)
array_shape = (array_size[0], array_size[1])
weight = np.zeros(array_shape, dtype=complex)
mag = np.ones(array_shape, dtype="object")
port_names_arranged = np.chararray(array_shape)
all_ports = ff_data.keys()
w_dict = {}
# calculate weights based off of progressive phase shift
port_name = []
for m in range(array_shape[0]):
for n in range(array_shape[1]):
mag_val = mag[m][n]
ang = np.radians(xphase * m) + np.radians(yphase * n)
weight[m][n] = np.sqrt(mag_val) * np.exp(1j * ang)
current_index_str = "[" + str(m + 1 + loc_offset) + "," + str(n + 1 + loc_offset) + "]"
port_name = [y for y in all_ports if current_index_str in y]
w_dict[port_name[0]] | |
specified control.
c: The System.Windows.Forms.Control to assign the System.Windows.Forms.Control.Paint event to.
e: An System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def InvokePaintBackground(self, *args): #cannot find CLR method
"""
InvokePaintBackground(self: Control, c: Control, e: PaintEventArgs)
Raises the PaintBackground event for the specified control.
c: The System.Windows.Forms.Control to assign the System.Windows.Forms.Control.Paint event to.
e: An System.Windows.Forms.PaintEventArgs that contains the event data.
"""
pass
def IsInputChar(self, *args): #cannot find CLR method
"""
IsInputChar(self: Control, charCode: Char) -> bool
Determines if a character is an input character that the control recognizes.
charCode: The character to test.
Returns: true if the character should be sent directly to the control and not preprocessed; otherwise,
false.
"""
pass
def IsInputKey(self, *args): #cannot find CLR method
"""
IsInputKey(self: Control, keyData: Keys) -> bool
Determines whether the specified key is a regular input key or a special key that requires
preprocessing.
keyData: One of the System.Windows.Forms.Keys values.
Returns: true if the specified key is a regular input key; otherwise, false.
"""
pass
def IsLayoutLoaded(self, file):
""" IsLayoutLoaded(self: GH_Ribbon, file: str) -> bool """
pass
def IsLayoutVisible(self, file):
""" IsLayoutVisible(self: GH_Ribbon, file: str) -> bool """
pass
def LayoutRibbon(self):
""" LayoutRibbon(self: GH_Ribbon) """
pass
def MemberwiseClone(self, *args): #cannot find CLR method
"""
MemberwiseClone(self: MarshalByRefObject, cloneIdentity: bool) -> MarshalByRefObject
Creates a shallow copy of the current System.MarshalByRefObject object.
cloneIdentity: false to delete the current System.MarshalByRefObject object's identity, which will cause the
object to be assigned a new identity when it is marshaled across a remoting boundary. A value of
false is usually appropriate. true to copy the current System.MarshalByRefObject object's
identity to its clone, which will cause remoting client calls to be routed to the remote server
object.
Returns: A shallow copy of the current System.MarshalByRefObject object.
MemberwiseClone(self: object) -> object
Creates a shallow copy of the current System.Object.
Returns: A shallow copy of the current System.Object.
"""
pass
def NearestHeight(self, h):
""" NearestHeight(self: GH_Ribbon, h: int) -> int """
pass
def NearestWidth(self, w):
""" NearestWidth(self: GH_Ribbon, w: int) -> int """
pass
def NotifyInvalidate(self, *args): #cannot find CLR method
"""
NotifyInvalidate(self: Control, invalidatedArea: Rectangle)
Raises the System.Windows.Forms.Control.Invalidated event with a specified region of the control
to invalidate.
invalidatedArea: A System.Drawing.Rectangle representing the area to invalidate.
"""
pass
def OnAutoSizeChanged(self, *args): #cannot find CLR method
"""
OnAutoSizeChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.AutoSizeChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnAutoValidateChanged(self, *args): #cannot find CLR method
"""
OnAutoValidateChanged(self: ContainerControl, e: EventArgs)
Raises the System.Windows.Forms.ContainerControl.AutoValidateChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBackColorChanged(self, *args): #cannot find CLR method
"""
OnBackColorChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.BackColorChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBackgroundImageChanged(self, *args): #cannot find CLR method
"""
OnBackgroundImageChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.BackgroundImageChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBackgroundImageLayoutChanged(self, *args): #cannot find CLR method
"""
OnBackgroundImageLayoutChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.BackgroundImageLayoutChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnBindingContextChanged(self, *args): #cannot find CLR method
"""
OnBindingContextChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.BindingContextChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnCausesValidationChanged(self, *args): #cannot find CLR method
"""
OnCausesValidationChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.CausesValidationChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnChangeUICues(self, *args): #cannot find CLR method
"""
OnChangeUICues(self: Control, e: UICuesEventArgs)
Raises the System.Windows.Forms.Control.ChangeUICues event.
e: A System.Windows.Forms.UICuesEventArgs that contains the event data.
"""
pass
def OnClick(self, *args): #cannot find CLR method
"""
OnClick(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.Click event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnClientSizeChanged(self, *args): #cannot find CLR method
"""
OnClientSizeChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.ClientSizeChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnContextMenuChanged(self, *args): #cannot find CLR method
"""
OnContextMenuChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.ContextMenuChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnContextMenuStripChanged(self, *args): #cannot find CLR method
"""
OnContextMenuStripChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.ContextMenuStripChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnControlAdded(self, *args): #cannot find CLR method
"""
OnControlAdded(self: Control, e: ControlEventArgs)
Raises the System.Windows.Forms.Control.ControlAdded event.
e: A System.Windows.Forms.ControlEventArgs that contains the event data.
"""
pass
def OnControlRemoved(self, *args): #cannot find CLR method
"""
OnControlRemoved(self: Control, e: ControlEventArgs)
Raises the System.Windows.Forms.Control.ControlRemoved event.
e: A System.Windows.Forms.ControlEventArgs that contains the event data.
"""
pass
def OnCreateControl(self, *args): #cannot find CLR method
"""
OnCreateControl(self: UserControl)
Raises the CreateControl event.
"""
pass
def OnCursorChanged(self, *args): #cannot find CLR method
"""
OnCursorChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.CursorChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDockChanged(self, *args): #cannot find CLR method
"""
OnDockChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.DockChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDoubleClick(self, *args): #cannot find CLR method
"""
OnDoubleClick(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.DoubleClick event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDpiChangedAfterParent(self, *args): #cannot find CLR method
""" OnDpiChangedAfterParent(self: Control, e: EventArgs) """
pass
def OnDpiChangedBeforeParent(self, *args): #cannot find CLR method
""" OnDpiChangedBeforeParent(self: Control, e: EventArgs) """
pass
def OnDragDrop(self, *args): #cannot find CLR method
"""
OnDragDrop(self: Control, drgevent: DragEventArgs)
Raises the System.Windows.Forms.Control.DragDrop event.
drgevent: A System.Windows.Forms.DragEventArgs that contains the event data.
"""
pass
def OnDragEnter(self, *args): #cannot find CLR method
"""
OnDragEnter(self: Control, drgevent: DragEventArgs)
Raises the System.Windows.Forms.Control.DragEnter event.
drgevent: A System.Windows.Forms.DragEventArgs that contains the event data.
"""
pass
def OnDragLeave(self, *args): #cannot find CLR method
"""
OnDragLeave(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.DragLeave event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnDragOver(self, *args): #cannot find CLR method
"""
OnDragOver(self: Control, drgevent: DragEventArgs)
Raises the System.Windows.Forms.Control.DragOver event.
drgevent: A System.Windows.Forms.DragEventArgs that contains the event data.
"""
pass
def OnEnabledChanged(self, *args): #cannot find CLR method
"""
OnEnabledChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.EnabledChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnEnter(self, *args): #cannot find CLR method
"""
OnEnter(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.Enter event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnFontChanged(self, *args): #cannot find CLR method
"""
OnFontChanged(self: ContainerControl, e: EventArgs)
Raises the System.Windows.Forms.Control.FontChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnForeColorChanged(self, *args): #cannot find CLR method
"""
OnForeColorChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.ForeColorChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnGiveFeedback(self, *args): #cannot find CLR method
"""
OnGiveFeedback(self: Control, gfbevent: GiveFeedbackEventArgs)
Raises the System.Windows.Forms.Control.GiveFeedback event.
gfbevent: A System.Windows.Forms.GiveFeedbackEventArgs that contains the event data.
"""
pass
def OnGotFocus(self, *args): #cannot find CLR method
"""
OnGotFocus(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.GotFocus event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnHandleCreated(self, *args): #cannot find CLR method
"""
OnHandleCreated(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.HandleCreated event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnHandleDestroyed(self, *args): #cannot find CLR method
"""
OnHandleDestroyed(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.HandleDestroyed event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnHelpRequested(self, *args): #cannot find CLR method
"""
OnHelpRequested(self: Control, hevent: HelpEventArgs)
Raises the System.Windows.Forms.Control.HelpRequested event.
hevent: A System.Windows.Forms.HelpEventArgs that contains the event data.
"""
pass
def OnImeModeChanged(self, *args): #cannot find CLR method
"""
OnImeModeChanged(self: Control, e: EventArgs)
Raises the System.Windows.Forms.Control.ImeModeChanged event.
e: An System.EventArgs that contains the event data.
"""
pass
def OnInvalidated(self, *args): #cannot find CLR method
"""
OnInvalidated(self: Control, e: | |
[ 38497 : 78598 ] wmpLDDT: 88.44
# score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
--- ------ ----- --------- --------- ------- ------- ------- ------- ------- ------- ----
1 ! 31.5 11.0 3.6e-10 3.6e-06 87 124 .. 27 64 .. 15 74 .. 0.87
2 ? -1.1 0.3 3.4 3.4e+04 129 168 .. 225 236 .. 202 271 .. 0.69
Alignments for each domain:
== domain 1 score: 31.5 bits; conditional E-value: 3.6e-10
2UVO:A|PDBID|CHAIN|SEQUENCE 87 ikcgsqaggklcpnnlccsqwgfcglgsefcgggcqsg 124
+cg+ + lcp lccs+wgfcg +cg+gcqs
AF-A0A1D6GWN1-F1-model_v1 27 PQCGANSTTALCPYCLCCSKWGFCGSTEAYCGNGCQSQ 64
47**********************************95 PP
== domain 2 score: -1.1 bits; conditional E-value: 3.4
2UVO:A|PDBID|CHAIN|SEQUENCE 129 dkpcgkdaggrvctnnyccskwgscgigpgycgagcqsgg 168
d c g g +gg
AF-A0A1D6GWN1-F1-model_v1 225 DAEC----------------------------GRGPDAGG 236
3333............................22222222 PP
>> AF-P24626-F1-model_v1 resolution: 1.00 experiment: AFDB release_date: 01-JUL-21 [ 23336 : 87298 ] wmpLDDT: 90.83
# score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
--- ------ ----- --------- --------- ------- ------- ------- ------- ------- ------- ----
1 ! 31.1 27.6 5e-10 5e-06 88 127 .. 20 62 .. 14 81 .. 0.74
Alignments for each domain:
== domain 1 score: 31.1 bits; conditional E-value: 5e-10
2UVO:A|PDBID|CHAIN|SEQUENCE 88 kcgsqaggklcpnnlccsqwgfcglgsefcgggcqs...gacs 127
+cgsqagg lcpn lccsq+g+cg s++cg+gcqs g c
AF-P24626-F1-model_v1 20 QCGSQAGGALCPNCLCCSQYGWCGSTSDYCGAGCQSqcsGGCG 62
6999999999999999999999999999999999862224443 PP
>> AF-O24658-F1-model_v1 resolution: 1.00 experiment: AFDB release_date: 01-JUL-21 [ 3457 : 54868 ] wmpLDDT: 89.68
# score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
--- ------ ----- --------- --------- ------- ------- ------- ------- ------- ------- ----
1 ! 30.8 14.1 6.2e-10 6.3e-06 53 97 .. 27 68 .. 17 97 .. 0.67
2 ? 0.5 1.6 1.1 1.1e+04 141 163 .. 141 165 .. 135 183 .. 0.73
3 ? -1.0 0.6 3.1 3.1e+04 54 76 .. 231 253 .. 223 263 .. 0.52
Alignments for each domain:
== domain 1 score: 30.8 bits; conditional E-value: 6.2e-10
2UVO:A|PDBID|CHAIN|SEQUENCE 53 atctnnqccsqygycgfgaeycgagcqggpcradikcgsqaggkl 97
c n ccsq+gycg ycg gc++gpcr g+ gg +
AF-O24658-F1-model_v1 27 CGCAPNLCCSQFGYCGTDDAYCGVGCRSGPCRGS---GTPTGGSV 68
4577888888888888888888888888888864...44444443 PP
== domain 2 score: 0.5 bits; conditional E-value: 1.1
2UVO:A|PDBID|CHAIN|SEQUENCE 141 ctnnyccsk..wgscgigpgycgag 163
+t nyc s c+ g gy g g
AF-O24658-F1-model_v1 141 ATRNYCQSSntQYPCAPGKGYFGRG 165
5778887651134688888888876 PP
== domain 3 score: -1.0 bits; conditional E-value: 3.1
2UVO:A|PDBID|CHAIN|SEQUENCE 54 tctnnqccsqygycgfgaeycga 76
c + + g+ +ycg
AF-O24658-F1-model_v1 231 ECNGGNSGAVNARIGYYRDYCGQ 253
44444444444445555555553 PP
>> AF-Q0JC38-F1-model_v1 resolution: 1.00 experiment: AFDB release_date: 01-JUL-21 [ 10185 : 87298 ] wmpLDDT: 71.85
# score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
--- ------ ----- --------- --------- ------- ------- ------- ------- ------- ------- ----
1 ! 30.1 17.6 9.6e-10 9.7e-06 8 47 .. 28 65 .. 22 82 .. 0.80
Alignments for each domain:
== domain 1 score: 30.1 bits; conditional E-value: 9.6e-10
2UVO:A|PDBID|CHAIN|SEQUENCE 8 snmecpnnlccsqygycgmggdycgkgcqngacwtskrcg 47
n c + ccsq+gycg ycg+gcq+g cw s g
AF-Q0JC38-F1-model_v1 28 QNCGCQDGYCCSQWGYCGTTEAYCGQGCQSGPCWGSG--G 65
6888999999999999999999999999999999874..2 PP
>> AF-P19171-F1-model_v1 resolution: 1.00 experiment: AFDB release_date: 01-JUL-21 [ 1685 : 54868 ] wmpLDDT: 89.30
# score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
--- ------ ----- --------- --------- ------- ------- ------- ------- ------- ------- ----
1 ! 30.4 12.2 8e-10 8.1e-06 88 133 .. 35 81 .. 30 96 .. 0.80
2 ? -2.6 0.7 9.6 9.7e+04 130 142 .. 286 298 .. 268 321 .. 0.58
Alignments for each domain:
== domain 1 score: 30.4 bits; conditional E-value: 8e-10
2UVO:A|PDBID|CHAIN|SEQUENCE 88 kcgsqaggklcpnnlccsqwgfcglgsefcg.ggcqsgacstdkpcg 133
+cg qagg lcpn lccs++g+cg +c gcqs p g
AF-P19171-F1-model_v1 35 QCGRQAGGALCPNGLCCSEFGWCGNTEPYCKqPGCQSQCTPGGTPPG 81
7*****************************6369*997666666665 PP
== domain 2 score: -2.6 bits; conditional E-value: 9.6
2UVO:A|PDBID|CHAIN|SEQUENCE 130 kpcgkdaggrvct 142
cg+ grv+
AF-P19171-F1-model_v1 286 LECGRGQDGRVAD 298
3444444444443 PP
>> AF-A0A1X7YIJ7-F1-model_v1 resolution: 1.00 experiment: AFDB release_date: 01-JUL-21 [ 27631 : 78598 ] wmpLDDT: 86.49
# score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
--- ------ ----- --------- --------- ------- ------- ------- ------- ------- ------- ----
1 ! 28.8 21.2 2.4e-09 2.5e-05 10 80 .. 34 99 .. 28 104 .. 0.76
Alignments for each domain:
== domain 1 score: 28.8 bits; conditional E-value: 2.4e-09
2UVO:A|PDBID|CHAIN|SEQUENCE 10 mecpnnlccsqygycgmggdycgkgcqngacwtskrcgsqaggatctnnqccsqygycgfgaeycgagcqg 80
c +ccs+ygycg + ycg+gc++g cw s cg gga+ ++ + g+ ++g+ c+g
AF-A0A1X7YIJ7-F1-model_v1 34 CGCQPGFCCSKYGYCGKTSAYCGEGCKSGPCWGSAGCGG--GGASVARV--VTKSFFNGIK-SHAGSWCEG 99
568899*******************************95..77776543..3333344443.456666665 PP
>> AF-O04138-F1-model_v1 resolution: 1.00 experiment: AFDB release_date: 01-JUL-21 [ 3513 : 87298 ] wmpLDDT: 86.78
# score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
--- ------ ----- --------- --------- ------- ------- ------- ------- ------- ------- ----
1 ! 29.4 15.2 1.6e-09 1.7e-05 8 44 .. 28 64 .. 22 88 .. 0.82
2 ? -0.6 0.4 2.4 2.5e+04 25 45 .. 160 180 .. 146 200 .. 0.70
Alignments for each domain:
== domain 1 score: 29.4 bits; conditional E-value: 1.6e-09
2UVO:A|PDBID|CHAIN|SEQUENCE 8 snmecpnnlccsqygycgmggdycgkgcqngacwtsk 44
n c + ccsq+gycg ycg+gcq+g cw s
AF-O04138-F1-model_v1 28 QNCGCQDGYCCSQWGYCGTTEAYCGQGCQSGPCWGSG 64
6888999999999999999999999999999999874 PP
== domain 2 score: -0.6 bits; conditional E-value: 2.4
2UVO:A|PDBID|CHAIN|SEQUENCE 25 gmggdycgkgcqngacwtskr 45
g + dyc k+ + c k+
AF-O04138-F1-model_v1 160 GANMDYCDKSNKQWPCQPGKK 180
555567776666666665554 PP
>> AF-P29023-F1-model_v1 resolution: 1.00 experiment: AFDB release_date: 01-JUL-21 [ 9277 : 78598 ] wmpLDDT: 88.81
# score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
--- ------ ----- --------- --------- ------- ------- ------- ------- ------- ------- ----
1 ! 27.6 25.6 5.7e-09 5.8e-05 9 123 .. 22 91 .. 12 99 .. 0.50
2 ? -2.1 0.3 6.8 6.9e+04 153 163 .. 159 169 .. 143 193 .. 0.59
Alignments for each domain:
== domain 1 score: 27.6 bits; conditional E-value: 5.7e-09
2UVO:A|PDBID|CHAIN|SEQUENCE 9 nmecpnnlccsqygycgmggdycgkgcqngacwtskrcgsqaggatctnnqccsqygycgfgaeycgagcqggpcradikcgsqaggklcpnnlccsqwgfcglgsefcgggcqs 123
n c n+ccs++gycg +ycg gcq+g c r+ g gg ++ s + f g+ ++ +g+gc+
AF-P29023-F1-model_v1 22 NCGCQPNVCCSKFGYCGTTDEYCGDGCQSGPC-------------------------------------------RSGRGGGGSGGGGANVASVVTSSF-FNGIKNQ-AGSGCEG 91
44455555555555555555555555555555...........................................555444444444444334433332.4444433.3444443 PP
== domain 2 score: -2.1 bits; conditional E-value: 6.8
2UVO:A|PDBID|CHAIN|SEQUENCE 153 cgigpgycgag 163
c+ g y g g
AF-P29023-F1-model_v1 159 CAAGQKYYGRG 169
33333333322 PP
>> AF-C0P451-F1-model_v1 resolution: 1.00 experiment: AFDB release_date: 01-JUL-21 [ 32177 : 78598 ] wmpLDDT: 88.36
# score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
--- ------ ----- --------- --------- ------- ------- ------- ------- ------- ------- ----
1 ! 26.5 24.9 1.2e-08 0.00012 51 123 .. 34 103 .. 23 111 .. 0.59
2 ? -2.3 0.4 8.2 8.3e+04 153 163 .. 171 181 .. 156 204 .. 0.59
3 ? -2.4 0.3 8.8 8.9e+04 51 75 .. 245 269 .. 238 278 .. 0.64
Alignments for each domain:
== domain 1 score: 26.5 bits; conditional E-value: 1.2e-08
2UVO:A|PDBID|CHAIN|SEQUENCE 51 ggatctnnqccsqygycgfgaeycgagcqggpcradikcgsqaggklcpnnlccsqwgfcglgsefcgggcqs 123
+ c n ccs++gycg eycg gcq+gpcr+ gs gg ++ f g+ s+ +g+gc+
AF-C0P451-F1-model_v1 34 QNCGCQPNVCCSKFGYCGTTDEYCGDGCQSGPCRSGG-GGSSGGGGANVASVVTGS-FFNGIKSQ-AGSGCEG 103
3445677777777777777777777777777777654.344444443333333332.35566555.5666654 PP
== domain 2 score: -2.3 bits; conditional E-value: 8.2
2UVO:A|PDBID|CHAIN|SEQUENCE 153 cgigpgycgag 163
c+ g y g g
AF-C0P451-F1-model_v1 171 CAAGQKYYGRG 181
33333333322 PP
== domain 3 score: -2.4 bits; conditional E-value: 8.8
2UVO:A|PDBID|CHAIN|SEQUENCE 51 ggatctnnqccsqygycgfgaeycg 75
g+ c n + + g+ +yc
AF-C0P451-F1-model_v1 245 GALECGGNNPAQMNARVGYYRQYCR 269
4456777777777777777777774 PP
>> AF-I1NCA0-F1-model_v1 resolution: 1.00 experiment: AFDB release_date: 01-JUL-21 [ 3766 : 111598 ] wmpLDDT: 85.61
# score bias c-Evalue i-Evalue hmmfrom hmm to alifrom ali to envfrom env to acc
--- ------ ----- --------- --------- ------- ------- ------- ------- ------- ------- ----
1 ! 25.0 27.8 3.6e-08 0.00036 1 62 [. 21 83 .. 21 103 .. 0.81
2 ? -1.8 0.7 5.6 5.7e+04 27 40 .. 131 138 .. 113 163 .. 0.48
Alignments for each domain:
== domain 1 score: 25.0 bits; conditional E-value: 3.6e-08
2UVO:A|PDBID|CHAIN|SEQUENCE 1 ercgeqgsnmecpnnlccsqygycgmggdycg..kgcqngacwtskrcgsqaggatctnnqccs 62
e+cg q+ + cpnnlccsqyg+cg +yc+ k+cq++ cw g gg +n ++
AF-I1NCA0-F1-model_v1 21 EQCGRQAGGQTCPNNLCCSQYGWCGNTEEYCSpsKNCQSN-CWGGGGGGGGGGGGESASNVRAT 83
78*****************************544899975.99998888877777666664443 PP
== domain 2 score: -1.8 bits; conditional E-value: 5.6
2UVO:A|PDBID|CHAIN|SEQUENCE 27 ggdycgkgcqngac 40
g d c g c
AF-I1NCA0-F1-model_v1 131 GRDSC------GKC 138
22222......333 PP
>> AF-A0A0P0Y930-F1-model_v1 resolution: 1.00 experiment: AFDB release_date: 01-JUL-21 [ 31777 : 87298 ] | |
<gh_stars>1-10
"""
The Monroe domain knowledge base, re-encoded as a copct causal relation.
The causes function is implemented with two separate sub-routines:
One for the top-level causes, and one for all other mid-level causes.
This way the top-level causes can be easily omitted in the modified Monroe experiments.
The causes functions have a separate case for each rule in the original knowledge base.
Original lisp rule for each case is copied verbatim in the comments.
Original lisp operator format is:
(:method (name param1 param2 ...) branch1 branch2 ...)
Branch format is:
branch-label
(precond1 precond2 ...)
(subtask1 subtask2 ...)
Sometimes effects are omitted from the original corpus data if they wouldn't change anything.
For example, a GET-TO will be missing if things are already where they need to be gotten to.
Additional cases are included in the causes implementation for these situations.
"""
from monroe_static import locs, watercos, powercos, poslocs, sleaders, gens, food, pcrews
from monroe_utils import unify, single_unify
"""
M: maximum length of v for all (u,v) in causal relation
"""
M = 6
def mid_causes(v):
"""
Encodes all mid-level causal relations in the knowledge base.
Inputs:
v: A sequence of tasks in the form (state, taskname, parameters)
Each state has the form (objects, facts)
Outputs:
g: The set of all possible causes of v, each also in the form (state, taskname, parameters).
"""
states = tuple(s for (s,t,x) in v) # states (each of the form (objs, facts))
tasknames = tuple(t for (s,t,x) in v) # Task names
params = tuple((None,)+x for (s,t,x) in v) # Parameter lists, leading None for task name offset
g = set()
"""
;; clean-up-hazard
(:method (clean-up-hazard ?from ?to)
very-hazardous ;; just call the feds
((hazard-seriousness ?from ?to very-hazardous))
((!call fema))
normal ;; we can take care of it
((hazard-team ?ht))
((get-to ?ht ?from) (!clean-hazard ?ht ?from ?to)))
"""
if tasknames == ('!CALL',) and params[0][1] == 'FEMA':
m = unify(states[0][1], ('HAZARD-SERIOUSNESS', None, None, 'VERY-HAZARDOUS'))
for (fromloc, toloc) in m:
g.add((states[0],'CLEAN-UP-HAZARD', (fromloc, toloc)))
if tasknames == ('GET-TO','!CLEAN-HAZARD'):
fromloc, toloc = params[1][2], params[1][3]
if fromloc == params[0][2]:
g.add((states[0],'CLEAN-UP-HAZARD', (fromloc, toloc)))
# Missing get-to
if tasknames == ('!CLEAN-HAZARD',):
fromloc, toloc = params[0][2], params[0][3]
g.add((states[0],'CLEAN-UP-HAZARD', (fromloc, toloc)))
"""
;; block-road - blocks off a road
(:method (block-road ?from ?to)
normal
((police-unit ?police))
(:unordered (set-up-cones ?from ?to)
(get-to ?police ?from)))
"""
if tasknames == ('SET-UP-CONES','GET-TO'):
fromloc, toloc = params[0][1], params[0][2]
if fromloc == params[1][2]:
g.add((states[0],'BLOCK-ROAD', (fromloc, toloc)))
if tasknames == ('GET-TO','SET-UP-CONES'):
fromloc, toloc = params[1][1], params[1][2]
if fromloc == params[0][2]:
g.add((states[0],'BLOCK-ROAD', (fromloc, toloc)))
# Missing get-to
if tasknames == ('SET-UP-CONES',):
fromloc, toloc = params[0][1], params[0][2]
g.add((states[0],'BLOCK-ROAD', (fromloc, toloc)))
"""
;; unblock-road - unblocks a road
(:method (unblock-road ?from ?to)
normal
()
((take-down-cones ?from ?to)))
"""
if tasknames == ('TAKE-DOWN-CONES',):
fromloc, toloc = params[0][1], params[0][2]
g.add((states[0],'UNBLOCK-ROAD', (fromloc, toloc)))
"""
;; get-electricity provides electricity to a site (if not already there)
(:method (get-electricity ?loc)
already-has-electricity ;; do nothing
((not (no-electricity ?loc)))
()
no-electricity
()
((generate-temp-electricity ?loc))
)
"""
if tasknames == ('GENERATE-TEMP-ELECTRICITY',):
loc = params[0][1]
g.add((states[0],'GET-ELECTRICITY', (loc,)))
"""
;; repair-pipe
(:method (repair-pipe ?from ?to) ;; repairs a pipe at location
normal
((water-crew ?crew))
((get-to ?crew ?from)
(set-up-cones ?from ?to)
(open-hole ?from ?to)
(!replace-pipe ?crew ?from ?to)
(close-hole ?from ?to)
(take-down-cones ?from ?to)))
"""
if tasknames == ('GET-TO','SET-UP-CONES','OPEN-HOLE','!REPLACE-PIPE','CLOSE-HOLE','TAKE-DOWN-CONES'):
fromloc, toloc = params[0][2], params[1][2]
if (fromloc == params[1][1] == params[2][1] == params[3][2] == params[4][1] == params[5][1]) and (toloc == params[2][2] == params[3][3] == params[4][2] == params[5][2]):
g.add((states[0],'REPAIR-PIPE', (fromloc, toloc)))
# Missing get-to
if tasknames == ('SET-UP-CONES','OPEN-HOLE','!REPLACE-PIPE','CLOSE-HOLE','TAKE-DOWN-CONES'):
fromloc, toloc = params[0][1], params[0][2]
if (fromloc == params[1][1] == params[2][2] == params[3][1] == params[4][1]) and (toloc == params[2][3] == params[3][2] == params[4][2]):
g.add((states[0],'REPAIR-PIPE', (fromloc, toloc)))
"""
;; open-hole
(:method (open-hole ?from ?to) ;; opens a hole in the street
normal
((backhoe ?backhoe))
((get-to ?backhoe ?from)
(!dig ?backhoe ?from)))
"""
if tasknames == ('GET-TO','!DIG'):
fromloc = params[0][2]
if fromloc == params[1][2]:
for toloc in poslocs:
g.add((states[0],'OPEN-HOLE', (fromloc, toloc)))
# Missing get-to
if tasknames == ('!DIG',):
fromloc = params[0][2]
for toloc in poslocs:
g.add((states[0],'OPEN-HOLE', (fromloc, toloc)))
"""
;; close-hole
(:method (close-hole ?from ?to) ;; opens a hole in the street
normal
((backhoe ?backhoe))
((get-to ?backhoe ?from)
(!fill-in ?backhoe ?from)))
"""
if tasknames == ('GET-TO','!FILL-IN'):
fromloc = params[0][2]
if fromloc == params[1][2]:
for toloc in poslocs:
g.add((states[0],'CLOSE-HOLE', (fromloc, toloc)))
# Missing get-to
if tasknames == ('!FILL-IN',):
fromloc = params[0][2]
for toloc in poslocs:
g.add((states[0],'CLOSE-HOLE', (fromloc, toloc)))
"""
;; set-up-cones
(:method (set-up-cones ?from ?to) ;; sets up orange cones at road
normal
((work-crew ?crew))
((get-to ?crew ?from) (!place-cones ?crew)))
"""
if tasknames == ('GET-TO','!PLACE-CONES'):
fromloc = params[0][2]
for toloc in poslocs:
g.add((states[0],'SET-UP-CONES', (fromloc, toloc)))
# Missing get-to
if tasknames == ('!PLACE-CONES',):
crew = params[0][1]
m = unify(states[0][1], ('ATLOC', crew, None))
# crew could be at both a town and posloc within a town
if len(m)==1:
fromloc = m.pop()[0]
for toloc in poslocs:
g.add((states[0],'SET-UP-CONES', (fromloc, toloc)))
else:
for fromloc in poslocs:
for toloc in poslocs:
g.add((states[0],'SET-UP-CONES', (fromloc, toloc)))
"""
;; take-down-cones
(:method (take-down-cones ?from ?to) ;; takes down cones
normal
((work-crew ?crew))
((get-to ?crew ?from) (!pickup-cones ?crew)))
"""
if tasknames == ('GET-TO','!PICKUP-CONES'):
fromloc = params[0][2]
for toloc in poslocs:
g.add((states[0],'TAKE-DOWN-CONES', (fromloc, toloc)))
# Missing get-to
if tasknames == ('!PICKUP-CONES',):
crew = params[0][1]
m = unify(states[0][1], ('ATLOC', crew, None))
# crew could be at both a town and posloc within a town
if len(m)==1:
fromloc = m.pop()[0]
for toloc in poslocs:
g.add((states[0],'TAKE-DOWN-CONES', (fromloc, toloc)))
else:
for fromloc in poslocs:
for toloc in poslocs:
g.add((states[0],'TAKE-DOWN-CONES', (fromloc, toloc)))
"""
;; clear-wreck
(:method (clear-wreck ?from ?to) ;; gets rid of a wreck in any loc
normal
((wrecked-vehicle ?from ?to ?veh) (garbage-dump ?dump))
((tow-to ?veh ?dump)))
"""
if tasknames == ('TOW-TO',):
m = unify(states[0][1], ('WRECKED-VEHICLE', None, None, None))
for (fromloc, toloc, veh) in m:
g.add((states[0],'CLEAR-WRECK', (fromloc, toloc)))
"""
;; tow-to - tows a vehicle somewhere
(:method (tow-to ?veh ?to)
normal
((tow-truck ?ttruck) (vehicle ?veh) (atloc ?veh ?vehloc))
((get-to ?ttruck ?vehloc)
(!hook-to-tow-truck ?ttruck ?veh)
(get-to ?ttruck ?to)
(!unhook-from-tow-truck ?ttruck ?veh)))
"""
if tasknames == ('GET-TO','!HOOK-TO-TOW-TRUCK','GET-TO','!UNHOOK-FROM-TOW-TRUCK'):
veh, toloc = params[1][2], params[2][2]
g.add((states[0],'TOW-TO', (veh, toloc)))
# Missing get-to branches
if tasknames == ('!HOOK-TO-TOW-TRUCK','GET-TO','!UNHOOK-FROM-TOW-TRUCK'):
veh, toloc = params[0][2], params[1][2]
g.add((states[0],'TOW-TO', (veh, toloc)))
if tasknames == ('GET-TO','!HOOK-TO-TOW-TRUCK','!UNHOOK-FROM-TOW-TRUCK'):
veh = params[1][2]
for toloc in ['BRIGHTON-DUMP','HENRIETTA-DUMP']:
g.add((states[0],'TOW-TO', (veh, toloc)))
if tasknames == ('!HOOK-TO-TOW-TRUCK','!UNHOOK-FROM-TOW-TRUCK'):
veh = params[0][2]
for toloc in ['BRIGHTON-DUMP','HENRIETTA-DUMP']:
g.add((states[0],'TOW-TO', (veh, toloc)))
"""
;; clear-tree
(:method (clear-tree ?tree) ;; this gets rid of a tree in any loc
normal
((tree-crew ?tcrew) (tree ?tree)
(atloc ?tree ?treeloc))
((get-to ?tcrew ?treeloc) (!cut-tree ?tcrew ?tree)
(remove-blockage ?tree)))
"""
if tasknames == ('GET-TO','!CUT-TREE','REMOVE-BLOCKAGE'):
tree = params[1][2]
g.add((states[0],'CLEAR-TREE', (tree,)))
# Missing get-to
if tasknames == ('GET-TO','!CUT-TREE'):
tree = params[1][2]
g.add((states[0],'CLEAR-TREE', (tree,)))
if tasknames == ('!CUT-TREE','REMOVE-BLOCKAGE'):
tree = params[0][2]
g.add((states[0],'CLEAR-TREE', (tree,)))
if tasknames == ('!CUT-TREE'):
tree = params[0][2]
g.add((states[0],'CLEAR-TREE', (tree,)))
"""
;; remove-blockage
(:method (remove-blockage ?stuff)
move-to-side-of-street
((work-crew ?crew) (atloc ?stuff ?loc))
((get-to ?crew ?loc)
(!carry-blockage-out-of-way ?crew ?stuff)))
"""
if tasknames == ('GET-TO','!CARRY-BLOCKAGE-OUT-OF-WAY'):
stuff = params[1][2]
g.add((states[0],'REMOVE-BLOCKAGE', (stuff,)))
# Missing get-to
if tasknames == ('!CARRY-BLOCKAGE-OUT-OF-WAY',):
stuff = params[0][2]
g.add((states[0],'REMOVE-BLOCKAGE', (stuff,)))
"""
(:method (remove-blockage ?stuff)
carry-away
((garbage-dump ?dump))
((get-to ?stuff ?dump)))
"""
if tasknames == ('GET-TO',):
dump = params[0][2]
if dump in ('HENRIETTA-DUMP','BRIGHTON-DUMP'):
stuff = params[0][1]
g.add((states[0],'REMOVE-BLOCKAGE', (stuff,)))
"""
;; declare-curfew
(:method (declare-curfew ?town)
normal
()
(:unordered (!call EBS) (!call police-chief)))
"""
if tasknames == ('!CALL', '!CALL'):
if 'EBS' in (params[0][1], params[1][1]):
for town in locs:
g.add((states[0],'DECLARE-CURFEW', (town,)))
"""
;; generate-temp-electricity
(:method (generate-temp-electricity ?loc)
with-generator
((generator ?gen))
((make-full-fuel ?gen) (get-to ?gen ?loc) (!hook-up ?gen ?loc)
(!turn-on ?gen)))
"""
if tasknames == ('MAKE-FULL-FUEL','GET-TO','!HOOK-UP','!TURN-ON'):
loc = params[1][2]
if loc == params[2][2]:
g.add((states[0],'GENERATE-TEMP-ELECTRICITY', (loc,)))
# Missing get-to
if tasknames == ('MAKE-FULL-FUEL','!HOOK-UP','!TURN-ON'):
loc = params[1][2]
g.add((states[0],'GENERATE-TEMP-ELECTRICITY', (loc,)))
"""
;; make-full-fuel - makes sure arg1 is full of fuel
(:method (make-full-fuel ?gen)
with-gas-can
((gas-can ?gc) (atloc ?gen ?genloc) (service-station ?ss))
((get-to ?gc ?ss) (add-fuel ?ss ?gc) (get-to ?gc ?genloc)
(!pour-into ?gc ?gen)))
"""
if tasknames == ('GET-TO','ADD-FUEL','GET-TO','!POUR-INTO'):
gen = params[3][2]
if params[0][1] == params[1][2] == params[2][1]:
g.add((states[0],'MAKE-FULL-FUEL', (gen,)))
"""
(:method (make-full-fuel ?gen)
| |
<reponame>Accelize/drm
# -*- coding: utf-8 -*-
"""
Test logging mechanism of DRM Library.
"""
import pytest
from glob import glob
from os import remove, getpid, makedirs, access, R_OK, W_OK
from os.path import getsize, isfile, dirname, join, realpath, isdir, expanduser
from re import search, findall, finditer, MULTILINE
from time import time, sleep
from shutil import rmtree
from random import randrange
from tests.conftest import wait_func_true
LOG_FORMAT_SHORT = "[%^%=8l%$] %-6t, %v"
LOG_FORMAT_LONG = "%Y-%m-%d %H:%M:%S.%e - %18s:%-4# [%=8l] %=6t, %v"
REGEX_FORMAT_SHORT = r'\[\s*(\w+)\s*\] \s*\d+\s*, %s'
REGEX_FORMAT_LONG = r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{3} - \s*\S+:\d+\s* \[\s*(\w+)\s*\] \s*\d+\s*, %s'
def test_file_path(accelize_drm, conf_json, cred_json, async_handler, request,
log_file_factory):
"""Test logging file path"""
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
async_cb.reset()
logfile = log_file_factory.create(2)
conf_json.reset()
conf_json['settings']['log_verbosity'] = 6
conf_json['settings'].update(logfile.json)
conf_json.save()
with accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
) as drm_manager:
assert drm_manager.get('log_file_path') == logfile.path
logfile.read()
async_cb.assert_NoError()
logfile.remove()
def test_file_verbosity(accelize_drm, conf_json, cred_json, async_handler, request,
log_file_factory):
"""Test logging file verbosity"""
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
msg = 'This is a %s message'
level_dict = {0:'trace', 1:'debug', 2:'info', 3:'warning', 4:'error', 5:'critical'}
for verbosity in range(len(level_dict)+1):
async_cb.reset()
logfile = log_file_factory.create(2, 1, LOG_FORMAT_LONG)
conf_json.reset()
conf_json['settings'].update(logfile.json)
conf_json['settings']['log_verbosity'] = 6
conf_json.save()
with accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
) as drm_manager:
drm_manager.set(log_file_verbosity=verbosity)
assert drm_manager.get('log_file_verbosity') == verbosity
for i in sorted(level_dict.keys()):
drm_manager.set(log_message_level=i)
drm_manager.set(log_message=msg % level_dict[i])
log_content = logfile.read()
regex = REGEX_FORMAT_LONG % (msg % '(.*)')
trace_hit = 0
for i, m in enumerate(finditer(regex, log_content)):
assert m.group(1) == m.group(2)
assert m.group(1) == level_dict[verbosity + i]
trace_hit += 1
assert trace_hit == 6-verbosity
async_cb.assert_NoError()
logfile.remove()
def test_file_short_format(accelize_drm, conf_json, cred_json, async_handler, request,
log_file_factory):
"""Test logging file short format"""
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
async_cb.reset()
msg = 'This is a message'
regex_short = REGEX_FORMAT_SHORT % msg
logfile = log_file_factory.create(2, 1, LOG_FORMAT_SHORT)
conf_json.reset()
conf_json['settings'].update(logfile.json)
conf_json['settings']['log_verbosity'] = 6
conf_json.save()
with accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
) as drm_manager:
drm_manager.set(log_message_level=2)
drm_manager.set(log_message=msg)
log_content = logfile.read()
m = search(regex_short, log_content, MULTILINE)
assert m is not None
assert m.group(1) == 'info'
async_cb.assert_NoError()
logfile.remove()
def test_file_long_format(accelize_drm, conf_json, cred_json, async_handler, request,
log_file_factory):
"""Test logging file long format"""
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
async_cb.reset()
msg = 'This is a message'
regex_long = REGEX_FORMAT_LONG % msg
logfile = log_file_factory.create(2, 1, LOG_FORMAT_LONG)
conf_json.reset()
conf_json['settings'].update(logfile.json)
conf_json['settings']['log_verbosity'] = 6
conf_json.save()
with accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
) as drm_manager:
drm_manager.set(log_message_level=2)
drm_manager.set(log_message=msg)
log_content = logfile.read()
m = search(regex_long, log_content, MULTILINE)
assert m is not None
assert m.group(1) == 'info'
async_cb.assert_NoError()
logfile.remove()
def test_file_types(accelize_drm, conf_json, cred_json, async_handler, request,
log_file_factory):
"""Test logging file types"""
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
msg = 'This is a message'
rotating_size = 1
rotating_num = 5
size = rotating_size * 1024 * rotating_num
for log_type in range(3):
logfile = log_file_factory.create(2, log_type, LOG_FORMAT_LONG, False, rotating_size, rotating_num)
async_cb.reset()
conf_json.reset()
conf_json['settings'].update(logfile.json)
conf_json['settings']['log_verbosity'] = 6
conf_json.save()
with accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
) as drm_manager:
assert drm_manager.get('log_file_type') == log_type
drm_manager.set(log_message_level=logfile.verbosity)
assert drm_manager.get('log_message_level') == logfile.verbosity
for _ in range(2 * int(size / len(msg)) + 1):
drm_manager.set(log_message=msg)
if log_type == 0:
assert not isfile(logfile.path)
elif log_type == 1:
# Basic file
log_content = logfile.read()
assert len(log_content) >= 2 * size
else:
# Rotating file
assert rotating_size == drm_manager.get('log_file_rotating_size')
assert rotating_num == drm_manager.get('log_file_rotating_num')
for i in range(rotating_num+1):
log_content = logfile.read(i)
if i == 0:
assert len(log_content) < 2 * rotating_size*1024
else:
assert len(log_content) >= rotating_size*1024 / 2
async_cb.assert_NoError()
logfile.remove()
def test_file_append(accelize_drm, conf_json, cred_json, async_handler, request,
log_file_factory):
"""Test logging file append mode"""
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
async_cb.reset()
logfile = log_file_factory.create(2, type=1, append=True)
conf_json.reset()
conf_json['settings'].update(logfile.json)
conf_json['settings']['log_verbosity'] = 6
conf_json.save()
nb_loop = 5
for i in range(nb_loop):
with accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
) as drm_manager:
pass
log_content = logfile.read()
assert len(findall(r'Installed versions', log_content)) == nb_loop
async_cb.assert_NoError()
logfile.remove()
def test_file_truncate(accelize_drm, conf_json, cred_json, async_handler, request,
log_file_factory):
"""Test logging file truncate mode"""
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
async_cb.reset()
logfile = log_file_factory.create(2, type=1, append=False)
conf_json.reset()
conf_json['settings'].update(logfile.json)
conf_json['settings']['log_verbosity'] = 6
conf_json.save()
nb_loop = 5
for i in range(nb_loop):
with accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
) as drm_manager:
pass
log_content = logfile.read()
assert len(findall(r'Installed versions', log_content)) == 1
async_cb.assert_NoError()
logfile.remove()
def test_file_rotating_parameters(accelize_drm, conf_json, cred_json, async_handler, request,
log_file_factory):
"""Test logging file rotating parameters"""
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
async_cb.reset()
logfile = log_file_factory.create(2, type=2,
rotating_size_kb=1, rotating_num=5)
conf_json.reset()
conf_json['settings'].update(logfile.json)
conf_json['settings']['log_verbosity'] = 6
conf_json.save()
msg = 'This is a message'
with accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
) as drm_manager:
assert drm_manager.get('log_file_rotating_size') == logfile.rotating_size_kb
assert drm_manager.get('log_file_rotating_num') == logfile.rotating_num
drm_manager.set(log_message_level=logfile.verbosity)
assert drm_manager.get('log_message_level') == logfile.verbosity
for _ in range(2 * logfile.rotating_num * int(logfile.rotating_size_kb*1024 / len(msg) + 10)):
drm_manager.set(log_message=msg)
for i in range(logfile.rotating_num+1):
log_content = logfile.read(i)
assert len(log_content) < 2 * logfile.rotating_size_kb*1024
try:
logfile.read(logfile.rotating_num+1)
except IOError:
pass
async_cb.assert_NoError()
logfile.remove()
def test_versions_displayed_in_log_file(accelize_drm, conf_json, cred_json, async_handler, request,
log_file_factory):
"""Test versions of dependent libraries are displayed in log file"""
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
async_cb.reset()
logfile = log_file_factory.create(5, type=1)
conf_json.reset()
conf_json['settings'].update(logfile.json)
conf_json['settings']['log_verbosity'] = 6
conf_json.save()
with accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
) as drm_manager:
assert drm_manager.get('log_file_verbosity') == logfile.verbosity
log_content = logfile.read()
assert search(r'drmlib\s*:\s*\d+\.\d+\.\d+', log_content)
assert search(r'libcurl\s*:(\s+[^/]+/\d+\.\d+(\.\d+)?)+', log_content)
assert search(r'jsoncpp\s*:\s*\d+\.\d+\.\d+\n', log_content)
assert search(r'spdlog\s*:\s*\d+\.\d+\.\d+\n', log_content)
async_cb.assert_NoError()
logfile.remove()
def test_log_file_parameters_modifiability(accelize_drm, conf_json, cred_json, async_handler, request,
log_file_factory):
"""Once the log file has been created, test the parameters cannot be modified except verbosity and format """
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
async_cb.reset()
logfile = log_file_factory.create(3, type=2, format=LOG_FORMAT_LONG,
rotating_size_kb=10, rotating_num=0)
# Test from config file
conf_json.reset()
conf_json['settings'].update(logfile.json)
conf_json['settings']['log_verbosity'] = 6
conf_json.save()
with accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
) as drm_manager:
assert drm_manager.get('log_file_verbosity') == logfile.verbosity
assert drm_manager.get('log_file_format') == logfile.format
assert drm_manager.get('log_file_path') == logfile.path
assert drm_manager.get('log_file_type') == logfile.type
assert drm_manager.get('log_file_rotating_size') == logfile.rotating_size_kb
assert drm_manager.get('log_file_rotating_num') == logfile.rotating_num
# Try to modify verbosity => authorized
exp_value = logfile.verbosity - 1
drm_manager.set(log_file_verbosity=exp_value)
assert drm_manager.get('log_file_verbosity') == exp_value
# Try to modify format => authorized
exp_value = LOG_FORMAT_SHORT
drm_manager.set(log_file_format=exp_value)
assert drm_manager.get('log_file_format') == exp_value
# Try to modify path => not authorized
exp_value = realpath("./unexpected-%d.%d.log" % (getpid(), randrange(0xFFFFFFFF)))
with pytest.raises(accelize_drm.exceptions.DRMBadArg) as excinfo:
drm_manager.set(log_file_path=exp_value)
assert drm_manager.get('log_file_path') == logfile.path
# Try to modify rotating size => not authorized
exp_value = int(logfile.rotating_size_kb / 2)
with pytest.raises(accelize_drm.exceptions.DRMBadArg) as excinfo:
drm_manager.set(log_file_rotating_size=exp_value)
assert drm_manager.get('log_file_rotating_size') == logfile.rotating_size_kb
# Try to modify rotating num => not authorized
exp_value = int(logfile.rotating_num / 2)
with pytest.raises(accelize_drm.exceptions.DRMBadArg) as excinfo:
drm_manager.set(log_file_rotating_num=exp_value)
assert drm_manager.get('log_file_rotating_num') == logfile.rotating_num
log_content = logfile.read()
critical_list = findall(r'\[\s*critical\s*\].* Parameter \S* cannot be overwritten', log_content)
assert len(critical_list) == 3
async_cb.assert_Error(accelize_drm.exceptions.DRMBadArg.error_code, 'cannot be overwritten')
async_cb.reset()
logfile.remove()
def test_log_file_error_on_directory_creation(accelize_drm, conf_json, cred_json, async_handler):
""" Test an error occurred when log file directory does not exist and cannot be created """
from subprocess import check_call
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
async_cb.reset()
log_type = 1
log_dir = realpath(expanduser('~/tmp_log_dir.%s.%d' % (str(time()), randrange(0xFFFFFFFF))))
if not isdir(log_dir):
makedirs(log_dir)
log_path = join(log_dir, "tmp", "drmlib.%d.%s.log" % (getpid(), str(time())))
try:
# Create immutable folder
check_call('sudo chattr +i %s' % log_dir, shell=True)
assert not access(log_dir, W_OK)
assert not isdir(dirname(log_path))
conf_json.reset()
conf_json['settings']['log_file_path'] = log_path
conf_json['settings']['log_file_type'] = log_type
conf_json.save()
with pytest.raises(accelize_drm.exceptions.DRMExternFail) as excinfo:
drm_manager = accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
)
assert "Failed to create log file %s" % log_path in str(excinfo.value)
finally:
# Restore to mutable folder
check_call('sudo chattr -i %s' % log_dir, shell=True)
assert access(log_dir, W_OK)
if isdir(log_dir):
rmtree(log_dir)
def test_log_file_on_existing_directory(accelize_drm, conf_json, cred_json, async_handler):
""" Test when log file directory already exists """
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
async_cb.reset()
log_type = 1
log_dir = realpath(expanduser('~/tmp_log_dir.%s.%d' % (str(time()), randrange(0xFFFFFFFF))))
if not isdir(log_dir):
makedirs(log_dir)
log_path = join(log_dir, "drmlib.%d.%s.log" % (getpid(), time()))
assert isdir(log_dir)
assert access(log_dir, W_OK)
assert not isfile(log_path)
conf_json.reset()
conf_json['settings']['log_file_path'] = log_path
conf_json['settings']['log_file_type'] = log_type
conf_json.save()
with accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
) as drm_manager:
pass
wait_func_true(lambda: isfile(log_path), 10)
if isdir(log_dir):
rmtree(log_dir)
def test_log_file_directory_creation(accelize_drm, conf_json, cred_json, async_handler):
""" Test the non existing sub-directories in the log file path are created by the DRMLib """
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
log_type = 1
log_dir = realpath(expanduser('~/tmp_log_dir.%s.%d' % (str(time()), randrange(0xFFFFFFFF))))
if not isdir(log_dir):
makedirs(log_dir)
log_path = join(log_dir, 'tmp', "drmlib.%d.%s.log" % (getpid(), time()))
try:
assert isdir(log_dir)
assert access(log_dir, W_OK)
async_cb.reset()
conf_json.reset()
conf_json['settings']['log_file_path'] = log_path
conf_json['settings']['log_file_type'] = log_type
conf_json.save()
with accelize_drm.DrmManager(
conf_json.path,
cred_json.path,
driver.read_register_callback,
driver.write_register_callback,
async_cb.callback
) as drm_manager:
pass
wait_func_true(lambda: isfile(log_path), 10)
finally:
if isdir(log_dir):
rmtree(log_dir)
def test_log_file_without_credential_data_in_debug(accelize_drm, conf_json, cred_json, async_handler,
log_file_factory, request):
""" Test no credential information is saved | |
0): (0, 1),
(8, 15, 4, 1): (0, 1),
(8, 15, 4, 2): (0, 1),
(8, 15, 4, 3): (0, 0),
(8, 15, 4, 4): (0, 1),
(8, 15, 4, 5): (0, 1),
(8, 15, 5, -5): (0, 1),
(8, 15, 5, -4): (0, 1),
(8, 15, 5, -3): (0, 1),
(8, 15, 5, -2): (0, 1),
(8, 15, 5, -1): (0, 1),
(8, 15, 5, 0): (0, 1),
(8, 15, 5, 1): (0, 1),
(8, 15, 5, 2): (0, 1),
(8, 15, 5, 3): (0, 0),
(8, 15, 5, 4): (0, 1),
(8, 15, 5, 5): (0, 1),
(8, 16, -5, -5): (0, 1),
(8, 16, -5, -4): (0, 1),
(8, 16, -5, -3): (0, 1),
(8, 16, -5, -2): (0, 1),
(8, 16, -5, -1): (0, 1),
(8, 16, -5, 0): (0, 1),
(8, 16, -5, 1): (0, 1),
(8, 16, -5, 2): (0, 0),
(8, 16, -5, 3): (0, 1),
(8, 16, -5, 4): (0, 1),
(8, 16, -5, 5): (0, 1),
(8, 16, -4, -5): (0, 1),
(8, 16, -4, -4): (0, 1),
(8, 16, -4, -3): (0, 1),
(8, 16, -4, -2): (0, 1),
(8, 16, -4, -1): (0, 1),
(8, 16, -4, 0): (0, 1),
(8, 16, -4, 1): (0, 1),
(8, 16, -4, 2): (0, 0),
(8, 16, -4, 3): (0, 1),
(8, 16, -4, 4): (0, 1),
(8, 16, -4, 5): (0, 1),
(8, 16, -3, -5): (0, 1),
(8, 16, -3, -4): (0, 1),
(8, 16, -3, -3): (0, 1),
(8, 16, -3, -2): (0, 1),
(8, 16, -3, -1): (0, 1),
(8, 16, -3, 0): (0, 1),
(8, 16, -3, 1): (0, 1),
(8, 16, -3, 2): (1, 1),
(8, 16, -3, 3): (0, 1),
(8, 16, -3, 4): (1, 1),
(8, 16, -3, 5): (1, 0),
(8, 16, -2, -5): (-1, 1),
(8, 16, -2, -4): (-1, 1),
(8, 16, -2, -3): (-1, 1),
(8, 16, -2, -2): (-1, 1),
(8, 16, -2, -1): (-1, 1),
(8, 16, -2, 0): (1, 1),
(8, 16, -2, 1): (1, 1),
(8, 16, -2, 2): (1, 1),
(8, 16, -2, 3): (1, 1),
(8, 16, -2, 4): (1, 1),
(8, 16, -2, 5): (1, 0),
(8, 16, -1, -5): (-1, 1),
(8, 16, -1, -4): (-1, 1),
(8, 16, -1, -3): (-1, 1),
(8, 16, -1, -2): (-1, 1),
(8, 16, -1, -1): (1, 1),
(8, 16, -1, 0): (1, 1),
(8, 16, -1, 1): (1, 1),
(8, 16, -1, 2): (1, 1),
(8, 16, -1, 3): (1, 1),
(8, 16, -1, 4): (0, 1),
(8, 16, -1, 5): (0, 1),
(8, 16, 0, -5): (1, 1),
(8, 16, 0, -4): (1, 1),
(8, 16, 0, -3): (1, 1),
(8, 16, 0, -2): (1, 1),
(8, 16, 0, -1): (1, 1),
(8, 16, 0, 0): (1, 1),
(8, 16, 0, 1): (0, 1),
(8, 16, 0, 2): (0, 1),
(8, 16, 0, 3): (0, 1),
(8, 16, 0, 4): (-1, 1),
(8, 16, 0, 5): (-1, 1),
(8, 16, 1, -5): (1, 1),
(8, 16, 1, -4): (1, 1),
(8, 16, 1, -3): (1, 1),
(8, 16, 1, -2): (1, 1),
(8, 16, 1, -1): (0, 1),
(8, 16, 1, 0): (0, 1),
(8, 16, 1, 1): (-1, 1),
(8, 16, 1, 2): (-1, 1),
(8, 16, 1, 3): (-1, 1),
(8, 16, 1, 4): (-1, 0),
(8, 16, 1, 5): (-1, -1),
(8, 16, 2, -5): (0, 1),
(8, 16, 2, -4): (0, 1),
(8, 16, 2, -3): (0, 1),
(8, 16, 2, -2): (0, 1),
(8, 16, 2, -1): (0, 1),
(8, 16, 2, 0): (-1, 1),
(8, 16, 2, 1): (-1, 1),
(8, 16, 2, 2): (-1, 1),
(8, 16, 2, 3): (-1, 1),
(8, 16, 2, 4): (-1, 1),
(8, 16, 2, 5): (-1, 1),
(8, 16, 3, -5): (0, 1),
(8, 16, 3, -4): (0, 1),
(8, 16, 3, -3): (0, 1),
(8, 16, 3, -2): (0, 1),
(8, 16, 3, -1): (0, 1),
(8, 16, 3, 0): (0, 1),
(8, 16, 3, 1): (0, 1),
(8, 16, 3, 2): (0, 0),
(8, 16, 3, 3): (0, 1),
(8, 16, 3, 4): (0, 1),
(8, 16, 3, 5): (0, 1),
(8, 16, 4, -5): (0, 1),
(8, 16, 4, -4): (0, 1),
(8, 16, 4, -3): (0, 1),
(8, 16, 4, -2): (0, 1),
(8, 16, 4, -1): (0, 1),
(8, 16, 4, 0): (0, 1),
(8, 16, 4, 1): (0, 1),
(8, 16, 4, 2): (0, 0),
(8, 16, 4, 3): (0, 1),
(8, 16, 4, 4): (0, 1),
(8, 16, 4, 5): (0, 1),
(8, 16, 5, -5): (0, 1),
(8, 16, 5, -4): (0, 1),
(8, 16, 5, -3): (0, 1),
(8, 16, 5, -2): (0, 1),
(8, 16, 5, -1): (0, 1),
(8, 16, 5, 0): (0, 1),
(8, 16, 5, 1): (0, 1),
(8, 16, 5, 2): (0, 0),
(8, 16, 5, 3): (0, 1),
(8, 16, 5, 4): (0, 1),
(8, 16, 5, 5): (0, 1),
(8, 17, -5, -5): (0, 1),
(8, 17, -5, -4): (0, 1),
(8, 17, -5, -3): (0, 1),
(8, 17, -5, -2): (0, 1),
(8, 17, -5, -1): (0, 1),
(8, 17, -5, 0): (0, 1),
(8, 17, -5, 1): (0, 0),
(8, 17, -5, 2): (0, 1),
(8, 17, -5, 3): (0, 1),
(8, 17, -5, 4): (0, 1),
(8, 17, -5, 5): (0, 1),
(8, 17, -4, -5): (0, 1),
(8, 17, -4, -4): (0, 1),
(8, 17, -4, -3): (0, 1),
(8, 17, -4, -2): (0, 1),
(8, 17, -4, -1): (0, 1),
(8, 17, -4, 0): (0, 1),
(8, 17, -4, 1): (0, 0),
(8, 17, -4, 2): (0, 1),
(8, 17, -4, 3): (0, 1),
(8, 17, -4, 4): (0, 1),
(8, 17, -4, 5): (0, 1),
(8, 17, -3, -5): (0, 1),
(8, 17, -3, -4): (0, 1),
(8, 17, -3, -3): (0, 1),
(8, 17, -3, -2): (0, 1),
(8, 17, -3, -1): (0, 1),
(8, 17, -3, 0): (0, 1),
(8, 17, -3, 1): (0, 0),
(8, 17, -3, 2): (0, 1),
(8, 17, -3, 3): (1, 1),
(8, 17, -3, 4): (0, 1),
(8, 17, -3, 5): (0, 1),
(8, 17, -2, -5): (-1, 1),
(8, 17, -2, -4): (-1, 1),
(8, 17, -2, -3): (-1, 1),
(8, 17, -2, -2): (-1, 1),
(8, 17, -2, -1): (-1, 1),
(8, 17, -2, 0): (1, 1),
(8, 17, -2, 1): (1, 1),
(8, 17, -2, 2): (1, 1),
(8, 17, -2, 3): (1, 1),
(8, 17, -2, 4): (1, 1),
(8, 17, -2, 5): (1, 0),
(8, 17, -1, -5): (-1, 1),
(8, 17, -1, -4): (-1, 1),
(8, 17, -1, -3): (-1, 1),
(8, 17, -1, -2): (1, 1),
(8, 17, -1, -1): (1, 1),
(8, 17, -1, 0): (1, 1),
(8, 17, -1, 1): (1, 1),
(8, 17, -1, 2): (1, 1),
(8, 17, -1, 3): (1, 0),
(8, 17, -1, 4): (0, 1),
(8, 17, -1, 5): (0, 1),
(8, 17, 0, -5): (1, 1),
(8, 17, 0, -4): (1, 1),
(8, 17, 0, -3): (1, 1),
(8, 17, 0, -2): (1, 1),
(8, 17, 0, -1): (1, 1),
(8, 17, 0, 0): (1, 1),
(8, 17, 0, 1): (0, 1),
(8, 17, 0, 2): (0, 1),
(8, 17, 0, 3): (0, 0),
(8, 17, 0, 4): (-1, 1),
(8, 17, 0, 5): (-1, 1),
(8, 17, 1, -5): (1, 1),
(8, 17, 1, -4): (1, 1),
(8, 17, 1, -3): (1, 1),
(8, 17, 1, -2): (1, 1),
(8, 17, 1, -1): (0, 1),
(8, 17, 1, 0): (0, 1),
(8, 17, 1, 1): (-1, 1),
(8, 17, 1, 2): (-1, 1),
(8, 17, 1, 3): (-1, 0),
(8, 17, 1, 4): (-1, | |
p, pub_content pc
where pc.pub_id = p.pub_id
and pc.title_id = t1.title_id)
and c.report_type = 275
and t1.title_id = c.record_id
order by t1.title_title"""
cleanup.none = 'Title Dates Before First Publication Dates'
cleanup.note = 'This report is currently limited to ANTHOLOGY, CHAPBOOK, COLLECTION, COVERART, OMNIBUS, and SERIAL <b>variant</b> titles'
cleanup.print_title_table()
def function276():
cleanup.query = """select t1.title_id, t1.title_title, c.cleanup_id
from titles t1, titles t2, cleanup c
where t1.title_parent = t2.title_id
and t1.title_copyright < t2.title_copyright
and t1.title_copyright != '0000-00-00'
and t2.title_copyright != '0000-00-00'
and month(t1.title_copyright) != '00'
and month(t2.title_copyright) != '00'
and t1.title_ttype != 'SERIAL'
and c.report_type = 276
and c.resolved IS NULL
and t1.title_id = c.record_id
order by t1.title_title"""
cleanup.none = 'Variant Title Dates Before Canonical Title Dates'
cleanup.ignore = 1
cleanup.print_title_table()
def function277():
containers_grid(277, 'incomplete_contents')
def function278():
cleanup.invalid_title_types('ANTHOLOGY', ('CHAPBOOK','NONFICTION','OMNIBUS','EDITOR'))
def function279():
cleanup.invalid_title_types('COLLECTION', ('ANTHOLOGY','CHAPBOOK','NONFICTION','OMNIBUS','EDITOR'))
def function280():
cleanup.invalid_title_types('CHAPBOOK', ('ANTHOLOGY','COLLECTION','NONFICTION','OMNIBUS','EDITOR','NOVEL'))
def function281():
cleanup.invalid_title_types('MAGAZINE', ('CHAPBOOK','NONFICTION','OMNIBUS'))
def function282():
cleanup.invalid_title_types('FANZINE', ('ANTHOLOGY','CHAPBOOK','NONFICTION','OMNIBUS'))
def function283():
cleanup.invalid_title_types('NONFICTION', ('ANTHOLOGY','COLLECTION','EDITOR','NOVEL','OMNIBUS','SERIAL','CHAPBOOK'))
def function284():
cleanup.invalid_title_types('NOVEL', ('ANTHOLOGY','COLLECTION','EDITOR','NONFICTION','OMNIBUS','SERIAL','CHAPBOOK'))
def function285():
cleanup.invalid_title_types('OMNIBUS', ('EDITOR','SERIAL','CHAPBOOK'))
def function286():
cleanup.query = """select distinct t1.title_id, t1.title_title
from titles t1, titles t2, cleanup c
where t1.title_parent = t2.title_id
and (
(t1.title_storylen != t2.title_storylen)
or
(t1.title_storylen is not NULL and t2.title_storylen is NULL)
)
and t1.title_id = c.record_id
and c.report_type = 286
order by t1.title_title"""
cleanup.none = 'Variant Title Length Mismatches'
cleanup.print_title_table()
def function287():
cleanup.note = """This cleanup report finds publications with Contents page
number values containing "del" and the HTML pipe character ǀ."""
cleanup.query = """select distinct p.pub_id, p.pub_title
from pubs p, pub_content pc, cleanup c
where (pc.pubc_page like '%del%' or pc.pubc_page like '%ǀ%')
and pc.pub_id = p.pub_id
and c.record_id = p.pub_id
and c.report_type = 287
order by p.pub_title"""
cleanup.none = 'Publications with Invalid Page Numbers'
cleanup.print_pub_table()
def function288():
query = """select distinct p.pub_id, p.pub_title, p.pub_pages
from pubs p, pub_content pc, cleanup c
where p.pub_pages REGEXP '[^\]\[0-9ivxlcdm+ ,]'
and pc.pub_id = p.pub_id
and c.record_id = p.pub_id
and c.report_type = 288
order by p.pub_title"""
db.query(query)
result = db.store_result()
num = result.num_rows()
if num:
record = result.fetch_row()
bgcolor = 1
count = 1
PrintTableColumns(('', 'Publication', 'Page Count'))
while record:
pub_id = record[0][0]
pub_title = record[0][1]
pub_pages = record[0][2]
if bgcolor:
print '<tr align=left class="table1">'
else:
print '<tr align=left class="table2">'
print '<td>%d</td>' % int(count)
print '<td>%s</td>' % ISFDBLink('pl.cgi', pub_id, pub_title)
print '<td>%s</td>' % pub_pages
print '</tr>'
bgcolor ^= 1
count += 1
record = result.fetch_row()
print '</table>'
else:
print '<h2>No Publications with Invalid Page Numbers</h2>'
def function289():
cleanup.query = """select distinct p.pub_id, p.pub_title, c.cleanup_id
from pubs p, cleanup c
where p.pub_ctype='CHAPBOOK'
and
(select count(t.title_id)
from pub_content pc, titles t
where p.pub_id = pc.pub_id
and pc.title_id = t.title_id
and t.title_ttype in ('SHORTFICTION', 'POEM', 'SERIAL'))
> 1
and c.record_id = p.pub_id
and c.report_type = 289
and c.resolved IS NULL
order by p.pub_title"""
cleanup.none = 'CHAPBOOKs with Multiple Fiction Titles'
cleanup.ignore = 1
cleanup.print_pub_table()
def function290():
cleanup.query = """select distinct t1.title_id, t1.title_title, c.cleanup_id
from titles t1, title_relationships tr, titles t2, pubs p, pub_content pc, cleanup c
where t1.title_ttype = 'NONFICTION'
and t1.title_id = tr.title_id
and t2.title_id = tr.review_id
and t2.title_ttype = 'REVIEW'
and t1.title_id = pc.title_id
and p.pub_id = pc.pub_id
and c.record_id = t1.title_id
and c.report_type = 290
and c.resolved IS NULL
order by t1.title_title"""
cleanup.none = 'NONFICTION Titles Which Exist Only Due to Reviews'
cleanup.ignore = 1
cleanup.note = 'Note: Reviews of ineligible non-fiction titles should be entered as ESSAYs.'
cleanup.print_title_table()
def function291():
cleanup.note = """This cleanup report finds publications with a non-audio
format and the Narrator template in the Note field."""
cleanup.query = """select distinct p.pub_id, p.pub_title, c.cleanup_id
from pubs p, notes n, cleanup c
where p.note_id = n.note_id
and note_note like '%{{narrator%'
and p.pub_ptype not like '%audio%'
and c.record_id = p.pub_id
and c.report_type = 291
and c.resolved IS NULL
order by p.pub_title"""
cleanup.none = 'No suspected invalid uses of the Narrator template'
cleanup.ignore = 1
cleanup.print_pub_table()
def function292():
cleanup.query = """select distinct p.pub_id, p.pub_title
from pubs p, notes n, cleanup c
where p.pub_ptype like '%audio%'
and p.note_id = n.note_id
and n.note_note not like '%{{narrator%'
and c.record_id = p.pub_id
and c.report_type = 292
order by p.pub_title"""
cleanup.none = 'No audio books without the Narrator template'
cleanup.print_pub_table()
def function293():
cleanup.query = """select t.title_id, t.title_title, c.cleanup_id
from titles t, cleanup c
where binary t.title_title REGEXP "[^\:\.\!\;\/](%s)"
and t.title_language = 17
and c.record_id = t.title_id
and c.report_type = 293
and c.resolved IS NULL
order by t.title_title""" % requiredLowerCase()
cleanup.note = """This cleanup report finds English language title records with
capitalized words which should not be capitalized as per the ISFDB
data entry rules. The words are: %s""" % ", ".join(ENGLISH_LOWER_CASE)
cleanup.ignore = 1
cleanup.print_title_table()
def function294():
cleanup.query = """select p.pub_id, p.pub_title, c.cleanup_id
from pubs p, cleanup c
where binary p.pub_title REGEXP "[^\:\.\!\;\/](%s)"
and exists (
select 1 from titles t, pub_content pc
where t.title_id = pc.title_id
and p.pub_id = pc.pub_id
and t.title_language = 17
)
and c.record_id = p.pub_id
and c.report_type = 294
and c.resolved IS NULL
order by p.pub_title""" % requiredLowerCase()
cleanup.note = """This cleanup report finds publications whose titles include
capitalized words which should not be capitalized as per
the ISFDB data entry rules. The report is curently limited
to publications with English language title records.
The words are: %s""" % ", ".join(ENGLISH_LOWER_CASE)
cleanup.ignore = 1
cleanup.print_pub_table()
def function295():
cleanup.query = """select distinct p.pub_id, p.pub_title, p.pub_year
from pubs p, notes n, cleanup c
where p.note_id = n.note_id
and n.note_note like '%{{WatchDate}}%'
and c.record_id = p.pub_id
and c.report_type = 295
order by p.pub_year, p.pub_title"""
cleanup.none = 'No publications with the WatchDate template'
cleanup.print_pub_with_date_table()
def function296():
cleanup.query = """select distinct p.pub_id, p.pub_title, c.cleanup_id
from pubs p, notes n, cleanup c
where p.note_id = n.note_id
and n.note_note like '%first printing%'
and n.note_note not like '%apparent first printing%'
and n.note_note not like '%assumed first printing%'
and c.record_id = p.pub_id
and c.report_type = 296
and c.resolved IS NULL
order by p.pub_title"""
cleanup.none = 'No suspect publications with "First printing" in Notes'
cleanup.ignore = 1
cleanup.print_pub_table()
def function297():
cleanup.query = """select distinct t.title_id, t.title_title, c.cleanup_id
from titles t, cleanup c
where title_title like '%(Part %'
and title_ttype = 'SHORTFICTION'
and c.record_id = t.title_id
and c.report_type = 297
and c.resolved IS NULL
order by t.title_title"""
cleanup.none = 'No suspect SHORTFICTION title records with "(Part " in the title field'
cleanup.ignore = 1
cleanup.print_title_table()
def function298():
cleanup.note = """Title-based awards capture the title and the name of the title's
author(s) when a new award is created. However, the captured information
stored in the award record is never used: the software always uses the
current title and the current author(s) of the linked title record for
display and sorting purposes.<br>
In the past, some ISFDB Web pages used the captured title/author(s) data
instead, which allowed title-based awards to be adjusted to point to
other authors/titles. This cleanup report exists to help make sure that
all title-based awards are linked to the intended title."""
cleanup.query = """select a.award_id, a.award_title, c.cleanup_id
from awards a, cleanup c
where exists(select 1 from title_awards ta1 where ta1.award_id = a.award_id)
and not exists(
select 1 from title_awards ta2, titles t, canonical_author ca, authors au
where ta2.award_id = a.award_id
and ta2.title_id = t.title_id
and t.title_id = ca.title_id
and ca.ca_status = 1
and ca.author_id = au.author_id
and (
(au.author_canonical = a.award_author)
or (a.award_author like concat(au.author_canonical, '+%'))
or (a.award_author like concat('%+', au.author_canonical))
or (a.award_author like concat('%+', au.author_canonical, '+%'))
))
and c.record_id = a.award_id
and c.report_type = 298
and c.resolved IS NULL
order by a.award_title"""
cleanup.none = 'No Suspect Title-Based Awards with a Different Stored Author Name'
cleanup.ignore = 1
cleanup.print_award_table()
def function299():
cleanup.query = """select distinct p.pub_id, p.pub_title, c.cleanup_id
from pubs p, titles t, pub_content pc, languages l, cleanup c
where p.pub_id = pc.pub_id
and pc.title_id = t.title_id
and t.title_language = l.lang_id
and l.lang_name = 'Swedish'
and p.pub_ctype not in ('MAGAZINE', 'FANZINE')
and t.title_ttype not in ('INTERIORART')
and not exists
(select 1 from identifiers i, identifier_types it
where p.pub_id = i.pub_id
and i.identifier_type_id = it.identifier_type_id
and it.identifier_type_name = 'Libris XL')
and c.record_id = p.pub_id
and c.report_type = 299
and c.resolved | |
"""Tests for module state accessors in the protocol engine state store."""
import pytest
from pytest_lazyfixture import lazy_fixture # type: ignore[import]
from contextlib import nullcontext
from typing import ContextManager, Dict, NamedTuple, Optional, Type, Union
from opentrons_shared_data import load_shared_data
from opentrons.types import DeckSlotName
from opentrons.protocol_engine import errors
from opentrons.protocol_engine.types import (
LoadedModule,
DeckSlotLocation,
ModuleDefinition,
ModuleModel,
)
from opentrons.protocol_engine.state.modules import (
ModuleView,
ModuleState,
HardwareModule,
)
from opentrons.protocol_engine.state.module_substates import (
HeaterShakerModuleSubState,
HeaterShakerModuleId,
MagneticModuleSubState,
MagneticModuleId,
TemperatureModuleSubState,
TemperatureModuleId,
ThermocyclerModuleSubState,
ThermocyclerModuleId,
ModuleSubStateType,
)
def make_module_view(
slot_by_module_id: Optional[Dict[str, Optional[DeckSlotName]]] = None,
hardware_by_module_id: Optional[Dict[str, HardwareModule]] = None,
substate_by_module_id: Optional[Dict[str, ModuleSubStateType]] = None,
virtualize_modules: bool = False,
) -> ModuleView:
"""Get a module view test subject with the specified state."""
state = ModuleState(
slot_by_module_id=slot_by_module_id or {},
hardware_by_module_id=hardware_by_module_id or {},
substate_by_module_id=substate_by_module_id or {},
)
return ModuleView(state=state, virtualize_modules=virtualize_modules)
def get_sample_parent_module_view(
matching_module_def: ModuleDefinition,
matching_module_id: str,
) -> ModuleView:
"""Get a ModuleView with attached modules including a requested matching module."""
definition = load_shared_data("module/definitions/2/magneticModuleV1.json")
magdeck_def = ModuleDefinition.parse_raw(definition)
return make_module_view(
slot_by_module_id={
"id-non-matching": DeckSlotName.SLOT_1,
matching_module_id: DeckSlotName.SLOT_2,
"id-another-non-matching": DeckSlotName.SLOT_3,
},
hardware_by_module_id={
"id-non-matching": HardwareModule(
serial_number="serial-non-matching",
definition=magdeck_def,
),
matching_module_id: HardwareModule(
serial_number="serial-matching",
definition=matching_module_def,
),
"id-another-non-matching": HardwareModule(
serial_number="serial-another-non-matching",
definition=magdeck_def,
),
},
)
def test_initial_module_data_by_id() -> None:
"""It should raise if module ID doesn't exist."""
subject = make_module_view()
with pytest.raises(errors.ModuleNotLoadedError):
subject.get("helloWorld")
def test_get_missing_hardware() -> None:
"""It should raise if no loaded hardware."""
subject = make_module_view(slot_by_module_id={"module-id": DeckSlotName.SLOT_1})
with pytest.raises(errors.ModuleNotLoadedError):
subject.get("module-id")
def test_get_module_data(tempdeck_v1_def: ModuleDefinition) -> None:
"""It should get module data from state by ID."""
subject = make_module_view(
slot_by_module_id={"module-id": DeckSlotName.SLOT_1},
hardware_by_module_id={
"module-id": HardwareModule(
serial_number="serial-number",
definition=tempdeck_v1_def,
)
},
)
assert subject.get("module-id") == LoadedModule(
id="module-id",
model=ModuleModel.TEMPERATURE_MODULE_V1,
location=DeckSlotLocation(slotName=DeckSlotName.SLOT_1),
serialNumber="serial-number",
)
def test_get_location(tempdeck_v1_def: ModuleDefinition) -> None:
"""It should return the module's location or raise."""
subject = make_module_view(
slot_by_module_id={
"module-1": DeckSlotName.SLOT_1,
"module-2": None,
},
hardware_by_module_id={
"module-1": HardwareModule(
serial_number="serial-1",
definition=tempdeck_v1_def,
),
"module-2": HardwareModule(
serial_number="serial-2",
definition=tempdeck_v1_def,
),
},
)
assert subject.get_location("module-1") == DeckSlotLocation(
slotName=DeckSlotName.SLOT_1
)
with pytest.raises(errors.ModuleNotOnDeckError):
assert subject.get_location("module-2")
def test_get_all_modules(
tempdeck_v1_def: ModuleDefinition,
tempdeck_v2_def: ModuleDefinition,
) -> None:
"""It should return all modules in state."""
subject = make_module_view(
slot_by_module_id={
"module-1": DeckSlotName.SLOT_1,
"module-2": DeckSlotName.SLOT_2,
},
hardware_by_module_id={
"module-1": HardwareModule(
serial_number="serial-1",
definition=tempdeck_v1_def,
),
"module-2": HardwareModule(
serial_number="serial-2",
definition=tempdeck_v2_def,
),
},
)
assert subject.get_all() == [
LoadedModule(
id="module-1",
serialNumber="serial-1",
model=ModuleModel.TEMPERATURE_MODULE_V1,
location=DeckSlotLocation(slotName=DeckSlotName.SLOT_1),
),
LoadedModule(
id="module-2",
serialNumber="serial-2",
model=ModuleModel.TEMPERATURE_MODULE_V2,
location=DeckSlotLocation(slotName=DeckSlotName.SLOT_2),
),
]
def test_get_magnetic_module_substate(
magdeck_v1_def: ModuleDefinition,
magdeck_v2_def: ModuleDefinition,
heater_shaker_v1_def: ModuleDefinition,
) -> None:
"""It should return a substate for the given Magnetic Module, if valid."""
subject = make_module_view(
slot_by_module_id={
"magnetic-module-gen1-id": DeckSlotName.SLOT_1,
"magnetic-module-gen2-id": DeckSlotName.SLOT_2,
"heatshake-module-id": DeckSlotName.SLOT_3,
},
hardware_by_module_id={
"magnetic-module-gen1-id": HardwareModule(
serial_number="magnetic-module-gen1-serial",
definition=magdeck_v1_def,
),
"magnetic-module-gen2-id": HardwareModule(
serial_number="magnetic-module-gen2-serial",
definition=magdeck_v2_def,
),
"heatshake-module-id": HardwareModule(
serial_number="heatshake-module-serial",
definition=heater_shaker_v1_def,
),
},
substate_by_module_id={
"magnetic-module-gen1-id": MagneticModuleSubState(
module_id=MagneticModuleId("magnetic-module-gen1-id"),
model=ModuleModel.MAGNETIC_MODULE_V1,
),
"magnetic-module-gen2-id": MagneticModuleSubState(
module_id=MagneticModuleId("magnetic-module-gen2-id"),
model=ModuleModel.MAGNETIC_MODULE_V2,
),
"heatshake-module-id": HeaterShakerModuleSubState(
module_id=HeaterShakerModuleId("heatshake-module-id"),
plate_target_temperature=None,
),
},
)
module_1_substate = subject.get_magnetic_module_substate(
module_id="magnetic-module-gen1-id"
)
assert module_1_substate.module_id == "magnetic-module-gen1-id"
assert module_1_substate.model == ModuleModel.MAGNETIC_MODULE_V1
module_2_substate = subject.get_magnetic_module_substate(
module_id="magnetic-module-gen2-id"
)
assert module_2_substate.module_id == "magnetic-module-gen2-id"
assert module_2_substate.model == ModuleModel.MAGNETIC_MODULE_V2
with pytest.raises(errors.WrongModuleTypeError):
subject.get_magnetic_module_substate(module_id="heatshake-module-id")
with pytest.raises(errors.ModuleNotLoadedError):
subject.get_magnetic_module_substate(module_id="nonexistent-module-id")
def test_get_heater_shaker_module_substate(
magdeck_v2_def: ModuleDefinition,
heater_shaker_v1_def: ModuleDefinition,
) -> None:
"""It should return a heater-shaker module substate."""
subject = make_module_view(
slot_by_module_id={
"magnetic-module-gen2-id": DeckSlotName.SLOT_2,
"heatshake-module-id": DeckSlotName.SLOT_3,
},
hardware_by_module_id={
"magnetic-module-gen2-id": HardwareModule(
serial_number="magnetic-module-gen2-serial",
definition=magdeck_v2_def,
),
"heatshake-module-id": HardwareModule(
serial_number="heatshake-module-serial",
definition=heater_shaker_v1_def,
),
},
substate_by_module_id={
"magnetic-module-gen2-id": MagneticModuleSubState(
module_id=MagneticModuleId("magnetic-module-gen2-id"),
model=ModuleModel.MAGNETIC_MODULE_V2,
),
"heatshake-module-id": HeaterShakerModuleSubState(
module_id=HeaterShakerModuleId("heatshake-module-id"),
plate_target_temperature=432,
),
},
)
hs_substate = subject.get_heater_shaker_module_substate(
module_id="heatshake-module-id"
)
assert hs_substate.module_id == "heatshake-module-id"
assert hs_substate.plate_target_temperature == 432
with pytest.raises(errors.WrongModuleTypeError):
subject.get_heater_shaker_module_substate(module_id="magnetic-module-gen2-id")
with pytest.raises(errors.ModuleNotLoadedError):
subject.get_heater_shaker_module_substate(module_id="nonexistent-module-id")
def test_get_temperature_module_substate(
tempdeck_v1_def: ModuleDefinition,
tempdeck_v2_def: ModuleDefinition,
heater_shaker_v1_def: ModuleDefinition,
) -> None:
"""It should return a substate for the given Temperature Module, if valid."""
subject = make_module_view(
slot_by_module_id={
"temp-module-gen1-id": DeckSlotName.SLOT_1,
"temp-module-gen2-id": DeckSlotName.SLOT_2,
"heatshake-module-id": DeckSlotName.SLOT_3,
},
hardware_by_module_id={
"temp-module-gen1-id": HardwareModule(
serial_number="temp-module-gen1-serial",
definition=tempdeck_v1_def,
),
"temp-module-gen2-id": HardwareModule(
serial_number="temp-module-gen2-serial",
definition=tempdeck_v2_def,
),
"heatshake-module-id": HardwareModule(
serial_number="heatshake-module-serial",
definition=heater_shaker_v1_def,
),
},
substate_by_module_id={
"temp-module-gen1-id": TemperatureModuleSubState(
module_id=TemperatureModuleId("temp-module-gen1-id"),
plate_target_temperature=None,
),
"temp-module-gen2-id": TemperatureModuleSubState(
module_id=TemperatureModuleId("temp-module-gen2-id"),
plate_target_temperature=123,
),
"heatshake-module-id": HeaterShakerModuleSubState(
module_id=HeaterShakerModuleId("heatshake-module-id"),
plate_target_temperature=None,
),
},
)
module_1_substate = subject.get_temperature_module_substate(
module_id="temp-module-gen1-id"
)
assert module_1_substate.module_id == "temp-module-gen1-id"
assert module_1_substate.plate_target_temperature is None
module_2_substate = subject.get_temperature_module_substate(
module_id="temp-module-gen2-id"
)
assert module_2_substate.module_id == "temp-module-gen2-id"
assert module_2_substate.plate_target_temperature == 123
with pytest.raises(errors.WrongModuleTypeError):
subject.get_temperature_module_substate(module_id="heatshake-module-id")
with pytest.raises(errors.ModuleNotLoadedError):
subject.get_temperature_module_substate(module_id="nonexistent-module-id")
def test_get_properties_by_id(
tempdeck_v1_def: ModuleDefinition,
tempdeck_v2_def: ModuleDefinition,
) -> None:
"""It should return a loaded module's properties by ID."""
subject = make_module_view(
slot_by_module_id={
"module-1": DeckSlotName.SLOT_1,
"module-2": DeckSlotName.SLOT_2,
},
hardware_by_module_id={
"module-1": HardwareModule(
serial_number="serial-1",
definition=tempdeck_v1_def,
),
"module-2": HardwareModule(
serial_number="serial-2",
definition=tempdeck_v2_def,
),
},
)
assert subject.get_definition("module-1") == tempdeck_v1_def
assert subject.get_dimensions("module-1") == tempdeck_v1_def.dimensions
assert subject.get_model("module-1") == ModuleModel.TEMPERATURE_MODULE_V1
assert subject.get_serial_number("module-1") == "serial-1"
assert subject.get_location("module-1") == DeckSlotLocation(
slotName=DeckSlotName.SLOT_1
)
assert subject.get_definition("module-2") == tempdeck_v2_def
assert subject.get_dimensions("module-2") == tempdeck_v2_def.dimensions
assert subject.get_model("module-2") == ModuleModel.TEMPERATURE_MODULE_V2
assert subject.get_serial_number("module-2") == "serial-2"
assert subject.get_location("module-2") == DeckSlotLocation(
slotName=DeckSlotName.SLOT_2
)
with pytest.raises(errors.ModuleNotLoadedError):
subject.get_definition("Not a module ID oh no")
def test_get_plate_target_temperature(heater_shaker_v1_def: ModuleDefinition) -> None:
"""It should return whether target temperature is set."""
module_view = make_module_view(
slot_by_module_id={"module-id": DeckSlotName.SLOT_1},
hardware_by_module_id={
"module-id": HardwareModule(
serial_number="serial-number",
definition=heater_shaker_v1_def,
)
},
substate_by_module_id={
"module-id": HeaterShakerModuleSubState(
module_id=HeaterShakerModuleId("module-id"),
plate_target_temperature=12.3,
)
},
)
subject = module_view.get_heater_shaker_module_substate("module-id")
assert subject.get_plate_target_temperature() == 12.3
def test_get_plate_target_temperature_no_target(
heater_shaker_v1_def: ModuleDefinition,
) -> None:
"""It should raise if no target temperature is set."""
module_view = make_module_view(
slot_by_module_id={"module-id": DeckSlotName.SLOT_1},
hardware_by_module_id={
"module-id": HardwareModule(
serial_number="serial-number",
definition=heater_shaker_v1_def,
)
},
substate_by_module_id={
"module-id": HeaterShakerModuleSubState(
module_id=HeaterShakerModuleId("module-id"),
plate_target_temperature=None,
)
},
)
subject = module_view.get_heater_shaker_module_substate("module-id")
with pytest.raises(errors.NoTargetTemperatureSetError):
subject.get_plate_target_temperature()
def test_get_magnet_home_to_base_offset() -> None:
"""It should return the model-specific offset to bottom."""
subject = make_module_view()
assert (
subject.get_magnet_home_to_base_offset(
module_model=ModuleModel.MAGNETIC_MODULE_V1
)
== 2.5
)
assert (
subject.get_magnet_home_to_base_offset(
module_model=ModuleModel.MAGNETIC_MODULE_V2
)
== 2.5
)
@pytest.mark.parametrize(
"module_model", [ModuleModel.MAGNETIC_MODULE_V1, ModuleModel.MAGNETIC_MODULE_V2]
)
def test_calculate_magnet_height(module_model: ModuleModel) -> None:
"""It should use true millimeters as hardware units."""
subject = make_module_view()
assert (
subject.calculate_magnet_height(
module_model=module_model,
height_from_base=100,
)
== 100
)
# todo(mm, 2022-02-28):
# It's unclear whether this expected result should actually be the same
# between GEN1 and GEN2.
# The GEN1 homing backoff distance looks accidentally halved, for the same reason
# that its heights are halved. If the limit switch hardware is the same for both
# modules, we'd expect the backoff difference to cause a difference in the
# height_from_home test, even though we're measuring everything in true mm.
# https://github.com/Opentrons/opentrons/issues/9585
assert (
subject.calculate_magnet_height(
module_model=module_model,
height_from_home=100,
)
== 97.5
)
assert (
subject.calculate_magnet_height(
module_model=module_model,
labware_default_height=100,
offset_from_labware_default=10.0,
)
== 110
)
@pytest.mark.parametrize(
argnames=["from_slot", "to_slot", "should_dodge"],
argvalues=[
(DeckSlotName.SLOT_1, DeckSlotName.FIXED_TRASH, True),
(DeckSlotName.FIXED_TRASH, DeckSlotName.SLOT_1, True),
(DeckSlotName.SLOT_4, DeckSlotName.FIXED_TRASH, True),
(DeckSlotName.FIXED_TRASH, DeckSlotName.SLOT_4, True),
(DeckSlotName.SLOT_4, DeckSlotName.SLOT_9, True),
(DeckSlotName.SLOT_9, DeckSlotName.SLOT_4, True),
(DeckSlotName.SLOT_4, DeckSlotName.SLOT_8, True),
(DeckSlotName.SLOT_8, DeckSlotName.SLOT_4, True),
(DeckSlotName.SLOT_1, DeckSlotName.SLOT_8, True),
(DeckSlotName.SLOT_8, DeckSlotName.SLOT_1, True),
(DeckSlotName.SLOT_4, DeckSlotName.SLOT_11, True),
(DeckSlotName.SLOT_11, DeckSlotName.SLOT_4, True),
(DeckSlotName.SLOT_1, DeckSlotName.SLOT_11, True),
(DeckSlotName.SLOT_11, DeckSlotName.SLOT_1, True),
(DeckSlotName.SLOT_2, DeckSlotName.SLOT_4, False),
],
)
def test_thermocycler_dodging(
thermocycler_v1_def: ModuleDefinition,
from_slot: DeckSlotName,
to_slot: DeckSlotName,
should_dodge: bool,
) -> None:
"""It should specify if thermocycler dodging is needed.
It should return True if thermocycler exists and movement is between bad pairs of
slot locations.
"""
subject = make_module_view(
slot_by_module_id={"module-id": DeckSlotName.SLOT_1},
hardware_by_module_id={
"module-id": HardwareModule(
serial_number="serial-number",
definition=thermocycler_v1_def,
)
},
)
assert (
subject.should_dodge_thermocycler(from_slot=from_slot, to_slot=to_slot)
is should_dodge
)
def test_select_hardware_module_to_load_rejects_missing() -> None:
"""It should raise if the correct module isn't attached."""
subject = make_module_view()
with pytest.raises(errors.ModuleNotAttachedError):
subject.select_hardware_module_to_load(
model=ModuleModel.TEMPERATURE_MODULE_V1,
location=DeckSlotLocation(slotName=DeckSlotName.SLOT_1),
attached_modules=[],
)
@pytest.mark.parametrize(
argnames=["requested_model", "attached_definition"],
argvalues=[
(ModuleModel.TEMPERATURE_MODULE_V1, lazy_fixture("tempdeck_v1_def")),
(ModuleModel.TEMPERATURE_MODULE_V2, lazy_fixture("tempdeck_v2_def")),
(ModuleModel.TEMPERATURE_MODULE_V1, lazy_fixture("tempdeck_v2_def")),
(ModuleModel.TEMPERATURE_MODULE_V2, lazy_fixture("tempdeck_v1_def")),
(ModuleModel.MAGNETIC_MODULE_V1, lazy_fixture("magdeck_v1_def")),
(ModuleModel.MAGNETIC_MODULE_V2, lazy_fixture("magdeck_v2_def")),
(ModuleModel.THERMOCYCLER_MODULE_V1, lazy_fixture("thermocycler_v1_def")),
(ModuleModel.THERMOCYCLER_MODULE_V2, lazy_fixture("thermocycler_v2_def")),
],
)
def test_select_hardware_module_to_load(
requested_model: ModuleModel,
attached_definition: ModuleDefinition,
) -> None:
"""It should return the first attached module that matches."""
subject = make_module_view()
attached_modules = [
HardwareModule(serial_number="serial-1", definition=attached_definition),
HardwareModule(serial_number="serial-2", definition=attached_definition),
]
result = subject.select_hardware_module_to_load(
model=requested_model,
location=DeckSlotLocation(slotName=DeckSlotName.SLOT_1),
attached_modules=attached_modules,
)
assert result == attached_modules[0]
def test_select_hardware_module_to_load_skips_non_matching(
magdeck_v1_def: ModuleDefinition,
magdeck_v2_def: ModuleDefinition,
) -> None:
"""It should skip over non-matching modules."""
subject = make_module_view()
attached_modules = [
HardwareModule(serial_number="serial-1", definition=magdeck_v1_def),
HardwareModule(serial_number="serial-2", definition=magdeck_v2_def),
]
result = subject.select_hardware_module_to_load(
model=ModuleModel.MAGNETIC_MODULE_V2,
location=DeckSlotLocation(slotName=DeckSlotName.SLOT_1),
attached_modules=attached_modules,
)
assert result == attached_modules[1]
def test_select_hardware_module_to_load_skips_already_loaded(
magdeck_v1_def: ModuleDefinition,
) -> None:
"""It should skip over already assigned modules."""
subject = make_module_view(
hardware_by_module_id={
"module-1": HardwareModule(
serial_number="serial-1",
definition=magdeck_v1_def,
)
}
)
attached_modules = [
HardwareModule(serial_number="serial-1", definition=magdeck_v1_def),
HardwareModule(serial_number="serial-2", definition=magdeck_v1_def),
]
result = subject.select_hardware_module_to_load(
model=ModuleModel.MAGNETIC_MODULE_V1,
location=DeckSlotLocation(slotName=DeckSlotName.SLOT_3),
attached_modules=attached_modules,
)
assert result == attached_modules[1]
def test_select_hardware_module_to_load_reuses_already_loaded(
magdeck_v1_def: ModuleDefinition,
) -> None:
"""It should reuse over already assigned modules in the same location."""
subject = make_module_view(
slot_by_module_id={
"module-1": DeckSlotName.SLOT_1,
},
hardware_by_module_id={
"module-1": HardwareModule(
serial_number="serial-1",
definition=magdeck_v1_def,
)
},
)
attached_modules = [
HardwareModule(serial_number="serial-1", definition=magdeck_v1_def),
HardwareModule(serial_number="serial-2", definition=magdeck_v1_def),
]
result = subject.select_hardware_module_to_load(
model=ModuleModel.MAGNETIC_MODULE_V1,
location=DeckSlotLocation(slotName=DeckSlotName.SLOT_1),
attached_modules=attached_modules,
)
assert result == attached_modules[0]
def test_select_hardware_module_to_load_rejects_location_reassignment(
magdeck_v1_def: ModuleDefinition,
tempdeck_v1_def: ModuleDefinition,
) -> None:
"""It should raise if a non-matching module is already present in the slot."""
subject = make_module_view(
slot_by_module_id={
"module-1": DeckSlotName.SLOT_1,
},
hardware_by_module_id={
"module-1": HardwareModule(
serial_number="serial-1",
definition=magdeck_v1_def,
)
},
)
attached_modules = [
HardwareModule(serial_number="serial-1", definition=magdeck_v1_def),
HardwareModule(serial_number="serial-2", definition=tempdeck_v1_def),
]
with pytest.raises(errors.ModuleAlreadyPresentError):
subject.select_hardware_module_to_load(
model=ModuleModel.TEMPERATURE_MODULE_V1,
location=DeckSlotLocation(slotName=DeckSlotName.SLOT_1),
attached_modules=attached_modules,
)
class _CalculateMagnetHardwareHeightTestParams(NamedTuple):
definition: ModuleDefinition
| |
<reponame>draguscloud/MultiWorld-Utilities<gh_stars>0
#!/usr/bin/env python3
import argparse
import copy
import os
import logging
import random
import textwrap
import shlex
import sys
from Main import main, get_seed
from Rom import get_sprite_from_name
from Utils import is_bundled, close_console
class ArgumentDefaultsHelpFormatter(argparse.RawTextHelpFormatter):
def _get_help_string(self, action):
return textwrap.dedent(action.help)
def parse_arguments(argv, no_defaults=False):
def defval(value):
return value if not no_defaults else None
# we need to know how many players we have first
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--multi', default=defval(1), type=lambda value: min(max(int(value), 1), 255))
multiargs, _ = parser.parse_known_args(argv)
parser = argparse.ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument('--create_spoiler', help='Output a Spoiler File', action='store_true')
parser.add_argument('--logic', default=defval('noglitches'), const='noglitches', nargs='?', choices=['noglitches', 'minorglitches', 'owglitches', 'nologic'],
help='''\
Select Enforcement of Item Requirements. (default: %(default)s)
No Glitches:
Minor Glitches: May require Fake Flippers, Bunny Revival
and Dark Room Navigation.
Overworld Glitches: May require overworld glitches.
No Logic: Distribute items without regard for
item requirements.
''')
parser.add_argument('--mode', default=defval('open'), const='open', nargs='?', choices=['standard', 'open', 'inverted'],
help='''\
Select game mode. (default: %(default)s)
Open: World starts with Zelda rescued.
Standard: Fixes Hyrule Castle Secret Entrance and Front Door
but may lead to weird rain state issues if you exit
through the Hyrule Castle side exits before rescuing
Zelda in a full shuffle.
Inverted: Starting locations are Dark Sanctuary in West Dark
World or at Link's House, which is shuffled freely.
Requires the moon pearl to be Link in the Light World
instead of a bunny.
''')
parser.add_argument('--swords', default=defval('random'), const='random', nargs='?', choices= ['random', 'assured', 'swordless', 'vanilla'],
help='''\
Select sword placement. (default: %(default)s)
Random: All swords placed randomly.
Assured: Start game with a sword already.
Swordless: No swords. Curtains in Skull Woods and Agahnim\'s
Tower are removed, Agahnim\'s Tower barrier can be
destroyed with hammer. Misery Mire and Turtle Rock
can be opened without a sword. Hammer damages Ganon.
Ether and Bombos Tablet can be activated with Hammer
(and Book). Bombos pads have been added in Ice
Palace, to allow for an alternative to firerod.
Vanilla: Swords are in vanilla locations.
''')
parser.add_argument('--goal', default=defval('ganon'), const='ganon', nargs='?',
choices=['ganon', 'pedestal', 'dungeons', 'triforcehunt', 'localtriforcehunt', 'ganontriforcehunt', 'localganontriforcehunt', 'crystals'],
help='''\
Select completion goal. (default: %(default)s)
Ganon: Collect all crystals, beat Agahnim 2 then
defeat Ganon.
Crystals: Collect all crystals then defeat Ganon.
Pedestal: Places the Triforce at the Master Sword Pedestal.
All Dungeons: Collect all crystals, pendants, beat both
Agahnim fights and then defeat Ganon.
Triforce Hunt: Places 30 Triforce Pieces in the world, collect
20 of them to beat the game.
Local Triforce Hunt: Places 30 Triforce Pieces in your world, collect
20 of them to beat the game.
Ganon Triforce Hunt: Places 30 Triforce Pieces in the world, collect
20 of them, then defeat Ganon.
Local Ganon Triforce Hunt: Places 30 Triforce Pieces in your world,
collect 20 of them, then defeat Ganon.
''')
parser.add_argument('--triforce_pieces_available', default=defval(30),
type=lambda value: min(max(int(value), 1), 90),
help='''Set Triforce Pieces available in item pool.''')
parser.add_argument('--triforce_pieces_required', default=defval(20),
type=lambda value: min(max(int(value), 1), 90),
help='''Set Triforce Pieces required to win a Triforce Hunt''')
parser.add_argument('--difficulty', default=defval('normal'), const='normal', nargs='?',
choices=['normal', 'hard', 'expert'],
help='''\
Select game difficulty. Affects available itempool. (default: %(default)s)
Normal: Normal difficulty.
Hard: A harder setting with less equipment and reduced health.
Expert: A harder yet setting with minimum equipment and health.
''')
parser.add_argument('--item_functionality', default=defval('normal'), const='normal', nargs='?',
choices=['normal', 'hard', 'expert'],
help='''\
Select limits on item functionality to increase difficulty. (default: %(default)s)
Normal: Normal functionality.
Hard: Reduced functionality.
Expert: Greatly reduced functionality.
''')
parser.add_argument('--timer', default=defval('none'), const='normal', nargs='?', choices=['none', 'display', 'timed', 'timed-ohko', 'ohko', 'timed-countdown'],
help='''\
Select game timer setting. Affects available itempool. (default: %(default)s)
None: No timer.
Display: Displays a timer but does not affect
the itempool.
Timed: Starts with clock at zero. Green Clocks
subtract 4 minutes (Total: 20), Blue Clocks
subtract 2 minutes (Total: 10), Red Clocks add
2 minutes (Total: 10). Winner is player with
lowest time at the end.
Timed OHKO: Starts clock at 10 minutes. Green Clocks add
5 minutes (Total: 25). As long as clock is at 0,
Link will die in one hit.
OHKO: Like Timed OHKO, but no clock items are present
and the clock is permenantly at zero.
Timed Countdown: Starts with clock at 40 minutes. Same clocks as
Timed mode. If time runs out, you lose (but can
still keep playing).
''')
parser.add_argument('--dungeon_counters', default=defval('default'), const='default', nargs='?', choices=['default', 'on', 'pickup', 'off'],
help='''\
Select dungeon counter display settings. (default: %(default)s)
(Note, since timer takes up the same space on the hud as dungeon
counters, timer settings override dungeon counter settings.)
Default: Dungeon counters only show when the compass is
picked up, or otherwise sent, only when compass
shuffle is turned on.
On: Dungeon counters are always displayed.
Pickup: Dungeon counters are shown when the compass is
picked up, even when compass shuffle is turned
off.
Off: Dungeon counters are never shown.
''')
parser.add_argument('--progressive', default=defval('on'), const='normal', nargs='?', choices=['on', 'off', 'random'],
help='''\
Select progressive equipment setting. Affects available itempool. (default: %(default)s)
On: Swords, Shields, Armor, and Gloves will
all be progressive equipment. Each subsequent
item of the same type the player finds will
upgrade that piece of equipment by one stage.
Off: Swords, Shields, Armor, and Gloves will not
be progressive equipment. Higher level items may
be found at any time. Downgrades are not possible.
Random: Swords, Shields, Armor, and Gloves will, per
category, be randomly progressive or not.
Link will die in one hit.
''')
parser.add_argument('--algorithm', default=defval('balanced'), const='balanced', nargs='?', choices=['freshness', 'flood', 'vt21', 'vt22', 'vt25', 'vt26', 'balanced'],
help='''\
Select item filling algorithm. (default: %(default)s
balanced: vt26 derivitive that aims to strike a balance between
the overworld heavy vt25 and the dungeon heavy vt26
algorithm.
vt26: Shuffle items and place them in a random location
that it is not impossible to be in. This includes
dungeon keys and items.
vt25: Shuffle items and place them in a random location
that it is not impossible to be in.
vt21: Unbiased in its selection, but has tendency to put
Ice Rod in Turtle Rock.
vt22: Drops off stale locations after 1/3 of progress
items were placed to try to circumvent vt21\'s
shortcomings.
Freshness: Keep track of stale locations (ones that cannot be
reached yet) and decrease likeliness of selecting
them the more often they were found unreachable.
Flood: Push out items starting from Link\'s House and
slightly biased to placing progression items with
less restrictions.
''')
parser.add_argument('--shuffle', default=defval('full'), const='full', nargs='?', choices=['vanilla', 'simple', 'restricted', 'full', 'crossed', 'insanity', 'restricted_legacy', 'full_legacy', 'madness_legacy', 'insanity_legacy', 'dungeonsfull', 'dungeonssimple'],
help='''\
Select Entrance Shuffling Algorithm. (default: %(default)s)
Full: Mix cave and dungeon entrances freely while limiting
multi-entrance caves to one world.
Simple: Shuffle Dungeon Entrances/Exits between each other
and keep all 4-entrance dungeons confined to one
location. All caves outside of death mountain are
shuffled in pairs and matched by original type.
Restricted: Use Dungeons shuffling from Simple but freely
connect remaining entrances.
Crossed: Mix cave and dungeon entrances freely while allowing
caves to cross between worlds.
Insanity: Decouple entrances and exits from each other and
shuffle them freely. Caves that used to be single
entrance will still exit to the same location from
which they are entered.
Vanilla: All entrances are in the same locations they were
in the base game.
Legacy shuffles preserve behavior from older versions of the
entrance randomizer including significant technical limitations.
The dungeon variants only mix up dungeons and keep the rest of
the overworld vanilla.
''')
parser.add_argument('--crystals_ganon', default=defval('7'), const='7', nargs='?', choices=['random', '0', '1', '2', '3', '4', '5', '6', '7'],
help='''\
How many crystals are needed to defeat ganon. Any other
requirements for ganon for the selected goal still apply.
This setting does not apply when the all dungeons goal is
selected. (default: %(default)s)
Random: Picks a random value between 0 and 7 (inclusive).
0-7: Number of crystals needed
''')
parser.add_argument('--crystals_gt', default=defval('7'), const='7', nargs='?', choices=['random', '0', '1', '2', '3', '4', '5', '6', '7'],
help='''\
How many crystals are needed to open GT. For inverted mode
this applies to the castle tower door instead. (default: %(default)s)
Random: Picks a random value between 0 and 7 (inclusive).
| |
Compute moments
M = createImageF(numMoments,numMoments)
for m,n in itertools.product(range(0, numMoments), range(0, numMoments)):
for indexPixel in range(0, numPoints):
y = (pixelList[indexPixel])[0]
x = (pixelList[indexPixel])[1]
val = (pixelList[indexPixel])[2]
M[n,m] += (x**n) * (y**m) * val
# Geometric central Moments
xc,yc = M[1,0]/M[0,0], M[0,1]/M[0,0]
m11 = M[1,1]/M[0,0] - xc*yc
m20 = M[2,0]/M[0,0] - xc**2
m02 = M[0,2]/M[0,0] - yc**2
if m20 < m02:
t = -(0.5 * atan(2.0*m11/(m20-m02)) + pi/2.0)
else:
t = -(0.5 * atan(2.0*m11/(m20-m02)))
# Geometric invariant moments
v = createImageF(numMoments,numMoments)
vn = createImageF(numMoments,numMoments)
for m,n in itertools.product(range(0, numMoments), range(0, numMoments)):
for indexPixel in range(0, numPoints):
y = (pixelList[indexPixel])[0]
x = (pixelList[indexPixel])[1]
val = (pixelList[indexPixel])[2]
v[n,m] += ((x-xc)*cos(t) - (y-yc)*sin(t))**n * ((x-xc)*sin(t) + (y-yc)*cos(t))**m * val
l = (1 + ((n + m) / 2.0))
vn[n,m] = v[n,m] / pow(M[0,0],l)
return vn
# WaterShed transform
def watherShed(distanceImage, shapeImage, suppWindow):
height, width = len(distanceImage), len(distanceImage[0])
watershedImage = createImageF(width, height)
# Initial regions by finding the maximum
regionIndex = 1 # Start id for a region. Any number different from zero
numPoints = len(shapeImage)
for indexPixel in range(0, numPoints):
y, x = (shapeImage[indexPixel])[0], (shapeImage[indexPixel])[1]
if watershedImage[y,x] == 0:
peak = True
for wx,wy in itertools.product(range(x-suppWindow, x+suppWindow+1), \
range(y-suppWindow, y+suppWindow+1)):
if wy>=0 and wy<height and wx>=0 and wx<width:
if watershedImage[wy, wx] != 0 or \
distanceImage[y, x] < distanceImage[wy, wx]:
peak = False
if peak:
for wx,wy in itertools.product(range(x-suppWindow, x+suppWindow+1), \
range(y-suppWindow, y+suppWindow+1)):
if wy>=0 and wy<height and wx>=0 and wx<width:
watershedImage[wy, wx] = regionIndex
regionIndex += 1
floodRegion = [ ] # The region we need to flood
for indexPixel in range(0, numPoints):
y, x = (shapeImage[indexPixel])[0], (shapeImage[indexPixel])[1]
if watershedImage[y,x] == 0:
floodRegion.append((y,x))
# This is not required. We do it to get a better display
# Create random regions ID. We change the ID for a random value so we get a random gray level when showing the regions
c = sample(range(regionIndex), regionIndex)
for indexPixel in range(0, numPoints):
y, x = (shapeImage[indexPixel])[0], (shapeImage[indexPixel])[1]
if watershedImage[y, x] != 0:
watershedImage[y, x] = c[int(watershedImage[y, x])] + 1
# Flooding
maxDistance, _ = imageMaxMin(distanceImage)
for floodValue in range(int(maxDistance), 0, -1):
flooded = True
while flooded:
flooded = False
newFloodRegion = [ ]
growRegion = [ ]
shuffle(floodRegion)
for indexPixel in range(0, len(floodRegion)):
y, x = (floodRegion[indexPixel])[0], (floodRegion[indexPixel])[1]
# Points not flooded will be considered in following iterations
if distanceImage[y,x] <= floodValue:
newFloodRegion.append((y,x))
else:
# list of neighbours
n = [ ]
for wx,wy in itertools.product(range(-1, 2), range(-1, 2)):
posX, posY = x + wx, y+ wy
if posY > -1 and posY < height and posX > -1 and posX < width:
if watershedImage[posY, posX] != 0:
n.append(watershedImage[posY, posX])
# No neighbours, so we cannot grow
if(len(n) == 0):
newFloodRegion.append((y,x))
else:
# Grow of only one type of region
if len(set(n)) == 1:
growRegion.append((y,x,n[0]))
flooded = True
for pixel in growRegion:
watershedImage[pixel[0], pixel[1]] = pixel[2]
floodRegion = newFloodRegion
# Set the borders
shedID = regionIndex + 1
for indexPixel in range(0, numPoints):
y, x = (shapeImage[indexPixel])[0], (shapeImage[indexPixel])[1]
if watershedImage[y,x] == 0 and distanceImage[y, x] > 0.5:
watershedImage[y, x] = shedID
return watershedImage
# Return the maximum and minimum points in a shape
def shapeMaxMin(shape):
x,y = shape[1,:], shape[0,:]
maxY, maxX = amax(x), amax(y)
if maxY > maxX:
maxX = maxY
minY = amin(x)
minX = amin(y)
if minY < minX:
minX = minY
return maxX, minX
def showShapeinImage(shape, centre, width, height):
segmentsImage = createImageL(width, height)
numPoints = len(shape[0])
for p in range(0, numPoints):
y,x = int(centre[0]+shape[0,p]), int(centre[1]+shape[1,p])
if x > 0 and y > 0 and x < width and y < height:
segmentsImage[y,x] = 255
showImageL(segmentsImage)
# Compute density function from a region in an image
def densityHistogram(image, position, regionRadius, sigma, histoSize):
height = len(image)
width = len(image[0])
# Quantization scale
colourScale = 256.0 / histoSize
histogram = createImageF(histoSize, histoSize)
sumValue = 0
for deltaX, deltaY in itertools.product(range(-regionRadius[0],regionRadius[0]), range(-regionRadius[1], regionRadius[1])):
x, y = position[0] + deltaX, position[1] + deltaY
if x>0 and y>0 and x<width and y<height :
w = exp(-(deltaX*deltaX + deltaY*deltaY)/(2*sigma*sigma));
rgb = image[y,x] / 256.0
Cb = int((128 - 37.79*rgb[0] - 74.203*rgb[1] + 112*rgb[2])/colourScale)
Cr = int((128 + 112*rgb[0] - 93.786*rgb[1] - 18.214*rgb[2])/colourScale)
histogram[Cr,Cb] += w
sumValue += w
for r,b in itertools.product(range(0, histoSize), range(0, histoSize)):
histogram[r,b] /= sumValue
return histogram
# Get a 2D colour description from a RGB value
def colourFeature(rgb, colourScale):
nRGB = rgb / 256.0
cB = int((128 - 37.79*nRGB[0] - 74.203*nRGB[1] + 112*nRGB[2])/colourScale)
cR = int((128 + 112*nRGB[0] - 93.786*nRGB[1] - 18.214*nRGB[2])/colourScale)
return cB, cR
# Implementation of meanshift
def meanShift(inputImage, q, sizeReg, sigma, histoSize, newPos):
# Weights
weights = createImageF(2*sizeReg[0], 2*sizeReg[1])
currPos = [0, 0]
colourScale = 256.0 / histoSize
while(currPos != newPos):
currPos = newPos
qs = densityHistogram(inputImage, currPos, sizeReg, sigma, histoSize)
# Weights
for deltaX, deltaY in itertools.product(range(-sizeReg[0],sizeReg[0]), \
range(-sizeReg[1], sizeReg[1])):
# Position of the pixel in the image and in the weight array
x, y = currPos[0] + deltaX, currPos[1] + deltaY
px,py = deltaX+sizeReg[0], deltaY+sizeReg[1]
# Features
Cb,Cr= colourFeature(inputImage[y,x], colourScale)
# Update
if qs[Cr, Cb] > 0:
weights[py, px] = sqrt(q[Cr, Cb] / qs[Cr, Cb])
else:
weights[py, px] = sqrt(q[Cr, Cb] / .000000000001)
# Compute mean shift sums
meanSum = [0, 0]
kernelSum = 0
for deltaX, deltaY in itertools.product(range(-sizeReg[0],sizeReg[0]), \
range(-sizeReg[1], sizeReg[1])):
# Position of the pixel in the image
x, y = currPos[0] + deltaX, currPos[1] + deltaY
# Kernel parameter
w = exp(-(deltaX*deltaX + deltaY*deltaY)/(2*sigma*sigma));
# Weight index
px, py = deltaX+sizeReg[0], deltaY+sizeReg[1]
# Mean sum
meanSum[0] += w * weights[py, px] * x
meanSum[1] += w * weights[py, px] * y
# Kernel sum
kernelSum += w * weights[py, px]
# Mean shift
newPos = [int(meanSum[0] / kernelSum), int(meanSum[1] / kernelSum)]
return newPos
# Back project a source image into the target
def backProjection(sourceImage, targetImage, qSource, pSource, pTarget, sizeReg, histoSize):
height, width = len(sourceImage), len(sourceImage[0])
colourScale = 256.0 / histoSize
# Projection
projectionSource = createImageF(width, height)
projectionTarget = createImageF(width, height)
for x, y in itertools.product(range(0,width), range(0, height)):
Cb,Cr = colourFeature(sourceImage[y,x], colourScale)
projectionSource[y,x] = qSource[Cr,Cb]
Cb,Cr = colourFeature(targetImage[y,x], colourScale)
projectionTarget[y,x] = qSource[Cr,Cb]
# Compute geometric moments
momS = createImageF(3, 3)
momT = createImageF(3, 3)
sizeSearch = [int(sizeReg[0] *1.5), int(sizeReg[1] *1.5)]
for deltaX, deltaY in itertools.product(range(-sizeSearch[0], sizeSearch[0]), \
range(-sizeSearch[1], sizeSearch[1])):
x, y = pSource[0] + deltaX, pSource[1] + deltaY
for m,n in itertools.product(range(0, 3), range(0, 3)):
momS[n,m] += (x**n) * (y**m) * projectionSource[y,x]
x, y = pTarget[0] + deltaX, pTarget[1] + deltaY
for m,n in itertools.product(range(0, 3), range(0, 3)):
momT[n,m] += (x**n) * (y**m) * projectionTarget[y,x]
xc,yc = momS[1,0]/momS[0,0], momS[0,1]/momS[0,0]
a = momS[2,0]/momS[0,0] - xc*xc;
b = 2*(momS[1,1]/momS[0,0] - xc * yc);
c = momS[0,2]/momS[0,0]- yc*yc;
sxS = int(sqrt((a+c-sqrt(b*b+(a-c)*(a-c))/2)));
syS = int(sqrt((a+c+sqrt(b*b+(a-c)*(a-c))/2)));
xc,yc = momT[1,0]/momT[0,0], momT[0,1]/momT[0,0]
a = momT[2,0]/momT[0,0] - xc*xc;
b = 2*(momT[1,1]/momT[0,0] - xc * yc);
c = momT[0,2]/momT[0,0]- yc*yc;
sx = int(sqrt((a+c-sqrt(b*b+(a-c)*(a-c))/2)));
sy = int(sqrt((a+c+sqrt(b*b+(a-c)*(a-c))/2)));
sy = sy * sizeReg[1] / syS
sx = sx * sizeReg[0] / sxS
return [int(xc),int(yc)], [int(sx),int(sy)]
# Back project an image
def backProjectionImage(image, q, histoSize):
height, width = len(image), len(image[0])
colourScale = 256.0 / histoSize
# Projection
projection = createImageF(width, height)
for x, y in itertools.product(range(0,width), range(0, height)):
Cb,Cr = colourFeature(image[y,x], colourScale)
projection[y,x] = q[Cr,Cb]
return projection
# Determine the size of a region
def regionSize(backProjImage, newBackProjImage, pos, newPos, sizeReg):
# Compute geometric moments
momS = createImageF(3, 3)
momT = createImageF(3, 3)
sizeSearch = [int(sizeReg[0] *1.5), int(sizeReg[1] *1.5)]
for deltaX, deltaY in | |
= self._default_is_radian if is_radian is None else is_radian
_pose1 = [pose1[i] if i <= 2 or is_radian else math.radians(pose1[i]) for i in range(6)]
_pose2 = [pose2[i] if i <= 2 or is_radian else math.radians(pose2[i]) for i in range(6)]
ret = self.arm_cmd.get_pose_offset(_pose1, _pose2, orient_type_in, orient_type_out)
if ret[0] in [0, XCONF.UxbusState.ERR_CODE, XCONF.UxbusState.WAR_CODE] and len(ret) > 6:
pose = [float('{:.6f}'.format(ret[i] if i <= 3 or is_radian else math.degrees(ret[i]))) for i in range(1, 7)]
return ret[0], pose
return ret[0], ret[1:7]
@xarm_is_connected(_type='get')
def get_servo_angle(self, servo_id=None, is_radian=None):
is_radian = self._default_is_radian if is_radian is None else is_radian
ret = self.arm_cmd.get_joint_pos()
if ret[0] in [0, XCONF.UxbusState.ERR_CODE, XCONF.UxbusState.WAR_CODE] and len(ret) > 7:
# self._angles = [float('{:.6f}'.format(ret[i][0])) for i in range(1, 8)]
self._angles = [float('{:.6f}'.format(ret[i])) for i in range(1, 8)]
ret[0] = 0
if servo_id is None or servo_id == 8 or len(self._angles) < servo_id:
return ret[0], list(map(lambda x: float('{:.6f}'.format(x if is_radian else math.degrees(x))), self._angles))
else:
return ret[0], float('{:.6f}'.format(self._angles[servo_id-1] if is_radian else math.degrees(self._angles[servo_id-1])))
def _is_out_of_joint_range(self, angle, i):
if not self._check_joint_limit or self._stream_type != 'socket' or not self._enable_report:
return False
joint_limit = XCONF.Robot.JOINT_LIMITS.get(self.axis).get(self.device_type, [])
if i < len(joint_limit):
angle_range = joint_limit[i]
if angle < angle_range[0] or angle > angle_range[1]:
logger.info('API -> set_servo_angle -> ret={}, i={} value={}'.format(APIState.OUT_OF_RANGE, i, angle))
return True
return False
@xarm_is_ready(_type='set')
@xarm_is_pause(_type='set')
def set_servo_angle(self, servo_id=None, angle=None, speed=None, mvacc=None, mvtime=None,
relative=False, is_radian=None, wait=False, timeout=None, **kwargs):
assert ((servo_id is None or servo_id == 8) and isinstance(angle, Iterable)) \
or (1 <= servo_id <= 7 and angle is not None and not isinstance(angle, Iterable)), \
'param servo_id or angle error'
ret = self._wait_until_cmdnum_lt_max()
if ret is not None:
logger.info('API -> set_servo_angle -> ret={}'.format(ret))
return ret
last_used_angle = self._last_angles.copy()
last_used_joint_speed = self._last_joint_speed
last_used_joint_acc = self._last_joint_acc
is_radian = self._default_is_radian if is_radian is None else is_radian
if servo_id is None or servo_id == 8:
for i in range(min(len(angle), len(self._last_angles))):
value = angle[i]
if value is None or i >= self.axis:
continue
if isinstance(value, str):
if value.isdigit():
value = float(value)
else:
continue
if relative:
if is_radian:
if self._is_out_of_joint_range(self._last_angles[i] + value, i):
self._last_angles = last_used_angle
return APIState.OUT_OF_RANGE
self._last_angles[i] += value
else:
if self._is_out_of_joint_range(self._last_angles[i] + math.radians(value), i):
self._last_angles = last_used_angle
return APIState.OUT_OF_RANGE
self._last_angles[i] += math.radians(value)
else:
if is_radian:
if self._is_out_of_joint_range(value, i):
self._last_angles = last_used_angle
return APIState.OUT_OF_RANGE
self._last_angles[i] = value
else:
if self._is_out_of_joint_range(math.radians(value), i):
self._last_angles = last_used_angle
return APIState.OUT_OF_RANGE
self._last_angles[i] = math.radians(value)
else:
if servo_id > self.axis:
return APIState.SERVO_NOT_EXIST
if isinstance(angle, str):
if angle.isdigit():
angle = float(angle)
else:
raise Exception('param angle error')
if relative:
if is_radian:
if self._is_out_of_joint_range(self._last_angles[servo_id - 1] + angle, servo_id - 1):
self._last_angles = last_used_angle
return APIState.OUT_OF_RANGE
self._last_angles[servo_id - 1] += angle
else:
if self._is_out_of_joint_range(self._last_angles[servo_id - 1] + math.radians(angle), servo_id - 1):
self._last_angles = last_used_angle
return APIState.OUT_OF_RANGE
self._last_angles[servo_id - 1] += math.radians(angle)
else:
if is_radian:
if self._is_out_of_joint_range(angle, servo_id - 1):
self._last_angles = last_used_angle
return APIState.OUT_OF_RANGE
self._last_angles[servo_id - 1] = angle
else:
if self._is_out_of_joint_range(math.radians(angle), servo_id - 1):
self._last_angles = last_used_angle
return APIState.OUT_OF_RANGE
self._last_angles[servo_id - 1] = math.radians(angle)
if speed is not None:
if isinstance(speed, str):
if speed.isdigit():
speed = float(speed)
else:
speed = self._last_joint_speed if is_radian else math.degrees(self._last_joint_speed)
if not is_radian:
speed = math.radians(speed)
self._last_joint_speed = min(max(speed, self._min_joint_speed), self._max_joint_speed)
elif kwargs.get('mvvelo', None) is not None:
mvvelo = kwargs.get('mvvelo')
if isinstance(mvvelo, str):
if mvvelo.isdigit():
mvvelo = float(mvvelo)
else:
mvvelo = self._last_joint_speed if is_radian else math.degrees(self._last_joint_speed)
if not is_radian:
mvvelo = math.radians(mvvelo)
self._last_joint_speed = min(max(mvvelo, self._min_joint_speed), self._max_joint_speed)
if mvacc is not None:
if isinstance(mvacc, str):
if mvacc.isdigit():
mvacc = float(mvacc)
else:
mvacc = self._last_joint_acc if is_radian else math.degrees(self._last_joint_acc)
if not is_radian:
mvacc = math.radians(mvacc)
self._last_joint_acc = min(max(mvacc, self._min_joint_acc), self._max_joint_acc)
if mvtime is not None:
if isinstance(mvtime, str):
if mvacc.isdigit():
mvtime = float(mvtime)
else:
mvtime = self._mvtime
self._mvtime = mvtime
if kwargs.get('check', False):
_, limit = self.is_joint_limit(self._last_angles)
if _ == 0 and limit is True:
self._last_angles = last_used_angle
self._last_joint_speed = last_used_joint_speed
self._last_joint_acc = last_used_joint_acc
return APIState.JOINT_LIMIT
ret = self.arm_cmd.move_joint(self._last_angles, self._last_joint_speed, self._last_joint_acc, self._mvtime)
logger.info('API -> set_servo_angle -> ret={}, angles={}, velo={}, acc={}'.format(
ret[0], self._last_angles, self._last_joint_speed, self._last_joint_acc
))
self._is_set_move = True
if wait and ret[0] in [0, XCONF.UxbusState.WAR_CODE, XCONF.UxbusState.ERR_CODE]:
if not self._enable_report:
warnings.warn('if you want to wait, please enable report')
else:
self._is_stop = False
self._WaitMove(self, timeout).start()
self._is_stop = False
return APIState.HAS_ERROR if self.error_code != 0 else APIState.HAS_WARN if self.warn_code != 0 else APIState.NORMAL
if ret[0] < 0 and not self.get_is_moving():
self._last_angles = last_used_angle
self._last_joint_speed = last_used_joint_speed
self._last_joint_acc = last_used_joint_acc
return ret[0]
@xarm_is_ready(_type='set')
def set_servo_angle_j(self, angles, speed=None, mvacc=None, mvtime=None, is_radian=None, **kwargs):
is_radian = self._default_is_radian if is_radian is None else is_radian
_angles = [angle if is_radian else math.radians(angle) for angle in angles]
for i in range(self.axis):
if self._is_out_of_joint_range(_angles[i], i):
return APIState.OUT_OF_RANGE
while len(_angles) < 7:
_angles.append(0)
_speed = self._last_joint_speed if speed is None else speed
_mvacc = self._last_joint_acc if mvacc is None else mvacc
_mvtime = self._mvtime if mvtime is None else mvtime
ret = self.arm_cmd.move_servoj(_angles, _speed, _mvacc, _mvtime)
logger.info('API -> set_servo_angle_j -> ret={}, angles={}, velo={}, acc={}'.format(
ret[0], _angles, _speed, _mvacc
))
self._is_set_move = True
return ret[0]
@xarm_is_ready(_type='set')
def set_servo_cartesian(self, mvpose, speed=None, mvacc=None, mvtime=None, is_radian=None, is_tool_coord=False, **kwargs):
assert len(mvpose) >= 6
is_radian = self._default_is_radian if is_radian is None else is_radian
if not is_radian:
pose = [mvpose[i] if i < 3 else math.radians(mvpose[i]) for i in range(6)]
else:
pose = mvpose
_speed = self.last_used_tcp_speed if speed is None else speed
_mvacc = self.last_used_tcp_acc if mvacc is None else mvacc
# _mvtime = self._mvtime if mvtime is None else mvtime
_mvtime = int(is_tool_coord)
ret = self.arm_cmd.move_servo_cartesian(pose, _speed, _mvacc, _mvtime)
logger.info('API -> set_servo_cartisian -> ret={}, pose={}, velo={}, acc={}'.format(
ret[0], pose, _speed, _mvacc
))
self._is_set_move = True
return ret[0]
@xarm_is_ready(_type='set')
@xarm_is_pause(_type='set')
def move_circle(self, pose1, pose2, percent, speed=None, mvacc=None, mvtime=None, is_radian=None, wait=False, timeout=None, **kwargs):
ret = self._wait_until_cmdnum_lt_max()
if ret is not None:
logger.info('API -> move_circle -> ret={}'.format(ret))
return ret
last_used_tcp_speed = self._last_tcp_speed
last_used_tcp_acc = self._last_tcp_acc
is_radian = self._default_is_radian if is_radian is None else is_radian
pose_1 = []
pose_2 = []
for i in range(6):
pose_1.append(pose1[i] if i < 3 or is_radian else math.radians(pose1[i]))
pose_2.append(pose2[i] if i < 3 or is_radian else math.radians(pose2[i]))
if speed is not None:
if isinstance(speed, str):
if speed.isdigit():
speed = float(speed)
else:
speed = self._last_tcp_speed
self._last_tcp_speed = min(max(speed, self._min_tcp_speed), self._max_tcp_speed)
elif kwargs.get('mvvelo', None) is not None:
mvvelo = kwargs.get('mvvelo')
if isinstance(mvvelo, str):
if mvvelo.isdigit():
mvvelo = float(mvvelo)
else:
mvvelo = self._last_tcp_speed
self._last_tcp_speed = min(max(mvvelo, self._min_tcp_speed), self._max_tcp_speed)
if mvacc is not None:
if isinstance(mvacc, str):
if mvacc.isdigit():
mvacc = float(mvacc)
else:
mvacc = self._last_tcp_acc
self._last_tcp_acc = min(max(mvacc, self._min_tcp_acc), self._max_tcp_acc)
if mvtime is not None:
if isinstance(mvtime, str):
if mvacc.isdigit():
mvtime = float(mvtime)
else:
mvtime = self._mvtime
self._mvtime = mvtime
ret = self.arm_cmd.move_circle(pose_1, pose_2, self._last_tcp_speed, self._last_tcp_acc, self._mvtime, percent)
logger.info('API -> move_circle -> ret={}, pos1={}, pos2={}, percent={}%, velo={}, acc={}'.format(
ret[0], pose_1, pose_2, percent, self._last_tcp_speed, self._last_tcp_acc
))
self._is_set_move = True
if wait and ret[0] in [0, XCONF.UxbusState.WAR_CODE, XCONF.UxbusState.ERR_CODE]:
if not self._enable_report:
print('if you want to wait, please enable report')
else:
self._is_stop = False
self._WaitMove(self, timeout).start()
self._is_stop = False
return APIState.HAS_ERROR if self.error_code != 0 else APIState.HAS_WARN if self.warn_code != 0 else APIState.NORMAL
if ret[0] < 0 and not self.get_is_moving():
self._last_tcp_speed = last_used_tcp_speed
self._last_tcp_acc = last_used_tcp_acc
return ret[0]
@xarm_is_ready(_type='set')
@xarm_is_pause(_type='set')
def move_gohome(self, speed=None, mvacc=None, mvtime=None, is_radian=None, wait=False, timeout=None, **kwargs):
is_radian = self._default_is_radian if is_radian is None else is_radian
# if speed is None:
# speed = 0.8726646259971648 # 50 °/s
# else:
# if not is_radian:
# speed = math.radians(speed)
# if mvacc is None:
# mvacc = 17.453292519943297 # 1000 °/s^2
# else:
# if not is_radian:
# mvacc = math.radians(mvacc)
# if mvtime is None:
# mvtime = 0
if speed is not None:
if isinstance(speed, str):
if speed.isdigit():
speed = float(speed)
else:
speed = self._last_joint_speed if is_radian else math.degrees(self._last_joint_speed)
if not is_radian:
speed = math.radians(speed)
self._last_joint_speed = min(max(speed, self._min_joint_speed), self._max_joint_speed)
elif kwargs.get('mvvelo', None) is not None:
mvvelo = kwargs.get('mvvelo')
if isinstance(mvvelo, str):
if mvvelo.isdigit():
mvvelo = float(mvvelo)
else:
mvvelo = self._last_joint_speed if is_radian else math.degrees(self._last_joint_speed)
if not is_radian:
mvvelo = math.radians(mvvelo)
self._last_joint_speed = min(max(mvvelo, self._min_joint_speed), self._max_joint_speed)
if mvacc | |
<reponame>jbeilstenedmands/cctbx_project<filename>iota/components/iota_ui_init.py
from __future__ import division, print_function, absolute_import
from past.builtins import range
'''
Author : Lyubimov, A.Y.
Created : 04/14/2014
Last Changed: 11/05/2018
Description : IOTA GUI Initialization module
'''
import os
import wx
import wx.lib.agw.ultimatelistctrl as ulc
from wxtbx import bitmaps
import multiprocessing
import argparse
from iotbx import phil as ip
from libtbx import easy_pickle as ep
from libtbx.phil.command_line import argument_interpreter as argint
from libtbx.utils import Sorry
from cctbx import miller
assert miller
from iota import iota_version, gui_description, gui_license
import iota.components.iota_input as inp
import iota.components.iota_utils as util
import iota.components.iota_ui_frames as frm
import iota.components.iota_ui_dialogs as dlg
ginp = util.InputFinder()
pid = os.getpid()
try:
user = os.getlogin()
except OSError:
user = 'iota'
# Platform-specific stuff
# TODO: Will need to test this on Windows at some point
if wx.Platform == '__WXGTK__':
norm_font_size = 10
button_font_size = 12
LABEL_SIZE = 14
CAPTION_SIZE = 12
python = 'python'
elif wx.Platform == '__WXMAC__':
norm_font_size = 12
button_font_size = 14
LABEL_SIZE = 14
CAPTION_SIZE = 12
python = "Python"
elif (wx.Platform == '__WXMSW__'):
norm_font_size = 9
button_font_size = 11
LABEL_SIZE = 11
CAPTION_SIZE = 9
python = "Python" #TODO: make sure it's right!
# --------------------------- Command-line Parser ---------------------------- #
def parse_command_args(help_message):
""" Parses command line arguments (only options for now) """
parser = argparse.ArgumentParser(prog = 'iota',
formatter_class=argparse.RawDescriptionHelpFormatter,
description=(help_message),
epilog=('\n{:-^70}\n'.format('')))
parser.add_argument('path', type=str, nargs = '*', default = None,
help = 'Path to data or file with IOTA parameters')
parser.add_argument('--version', action = 'version',
version = 'IOTA {}'.format(iota_version),
help = 'Prints version info of IOTA')
parser.add_argument('-w', type=int, nargs=1, default=0, dest='watch',
help = 'Run IOTA in watch mode - check for new images')
parser.add_argument('-r', type=int, nargs=1, default=0, dest='random',
help = 'Run IOTA with a random subset of images, e.g. "-r 5"')
parser.add_argument('-n', type=int, nargs='?', default=0, dest='nproc',
help = 'Specify a number of cores for a multiprocessor run"')
parser.add_argument('--tmp', type=str, nargs = 1, default = None,
help = 'Path to temp folder')
return parser
# ------------------------------- Main Window -------------------------------- #
class MainWindow(wx.Frame):
""" Frame housing the entire app; all windows open from this one """
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(800, 500))
self.parent = parent
self.iota_phil = inp.master_phil
self.prefs_phil = None
self.target_phil = None
self.term_file = None
# Create some defaults on startup
# Figure out temp folder
self.gparams = self.iota_phil.extract()
tmp_folder = '/tmp/{}_{}'.format(user, pid)
self.gparams.advanced.temporary_output_folder = tmp_folder
self.iota_phil = self.iota_phil.format(python_object=self.gparams)
# Menu bar
menubar = wx.MenuBar()
# Status bar
self.sb = self.CreateStatusBar()
# Help menu item with the about dialog
m_help = wx.Menu()
m_file = wx.Menu()
self.mb_load_script = m_file.Append(wx.ID_OPEN, '&Load Script...')
self.mb_save_script = m_file.Append(wx.ID_SAVE, '&Save Script...')
m_file.AppendSeparator()
self.mb_reset = m_file.Append(wx.ID_ANY, '&Reset Settings')
self.mb_about = m_help.Append(wx.ID_ANY, '&About')
menubar.Append(m_file, '&File')
menubar.Append(m_help, '&Help')
self.SetMenuBar(menubar)
self.main_sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.main_sizer)
# Toolbar
self.toolbar = self.CreateToolBar(style=wx.TB_3DBUTTONS | wx.TB_TEXT)
quit_bmp = bitmaps.fetch_icon_bitmap('actions', 'exit')
self.tb_btn_quit = self.toolbar.AddLabelTool(wx.ID_EXIT, label='Quit',
bitmap=quit_bmp,
shortHelp='Quit',
longHelp='Quit IOTA')
pref_bmp = bitmaps.fetch_icon_bitmap('apps', 'advancedsettings')
self.tb_btn_prefs = self.toolbar.AddLabelTool(wx.ID_ANY,
label='Preferences',
bitmap=pref_bmp,
shortHelp='Preferences',
longHelp='IOTA Preferences')
self.toolbar.AddSeparator()
load_bmp = bitmaps.fetch_icon_bitmap('actions', 'open')
self.tb_btn_load = self.toolbar.AddLabelTool(wx.ID_ANY,
label='Load Script',
bitmap=load_bmp,
shortHelp='Load Script',
longHelp='Load IOTA Script')
save_bmp = bitmaps.fetch_icon_bitmap('actions', 'save')
self.tb_btn_save = self.toolbar.AddLabelTool(wx.ID_ANY,
label='Save Script',
bitmap=save_bmp,
shortHelp='Save Script',
longHelp='Save IOTA Script')
reset_bmp = bitmaps.fetch_icon_bitmap('actions', 'reload')
self.tb_btn_reset = self.toolbar.AddLabelTool(wx.ID_ANY,
label='Reset',
bitmap=reset_bmp,
shortHelp='Reset Settings',
longHelp='Reset IOTA settings with defaults')
self.toolbar.AddSeparator()
analyze_bmp = bitmaps.fetch_icon_bitmap('mimetypes', 'text-x-generic-2')
self.tb_btn_analysis = self.toolbar.AddLabelTool(wx.ID_ANY, label='Recover',
bitmap=analyze_bmp,
shortHelp='Recover',
longHelp='Recover run, show statistics and restart if aborted ')
run_bmp = bitmaps.fetch_icon_bitmap('actions', 'run')
self.tb_btn_run = self.toolbar.AddLabelTool(wx.ID_ANY, label='Run',
bitmap=run_bmp,
shortHelp='Run',
longHelp='Run all stages of refinement')
# Test buttons for test windows - comment out when not needed
# self.toolbar.AddSeparator()
test_bmp = bitmaps.fetch_icon_bitmap('actions', 'utilities')
self.tb_btn_test = self.toolbar.AddLabelTool(wx.ID_ANY,
label='Test',
bitmap=test_bmp)
self.Bind(wx.EVT_TOOL, self.onRun, self.tb_btn_test)
self.toolbar.RemoveTool(self.tb_btn_test.GetId())
# These buttons will be disabled until input path is provided
self.toolbar.EnableTool(self.tb_btn_run.GetId(), False)
self.toolbar.Realize()
# Instantiate windows
self.input_window = frm.InputWindow(self, phil=self.iota_phil)
# Single input window
self.main_sizer.Add(self.input_window, 1,
flag=wx.ALL | wx.EXPAND,
border=10)
self.main_sizer.Add((-1, 20))
# button bindings
self.Bind(wx.EVT_TOOL, self.onQuit, self.tb_btn_quit)
self.Bind(wx.EVT_TOOL, self.onPreferences, self.tb_btn_prefs)
self.Bind(wx.EVT_TOOL, self.onRun, self.tb_btn_run)
self.Bind(wx.EVT_TOOL, self.onRecovery, self.tb_btn_analysis)
self.Bind(wx.EVT_TOOL, self.onLoadScript, self.tb_btn_load)
self.Bind(wx.EVT_TOOL, self.onOutputScript, self.tb_btn_save)
self.Bind(wx.EVT_TOOL, self.onReset, self.tb_btn_reset)
# Menubar button bindings
self.Bind(wx.EVT_MENU, self.OnAboutBox, self.mb_about)
self.Bind(wx.EVT_MENU, self.onOutputScript, self.mb_save_script)
self.Bind(wx.EVT_MENU, self.onLoadScript, self.mb_load_script)
self.Bind(wx.EVT_MENU, self.onReset, self.mb_reset)
# Bindings to Input Window
self.Bind(wx.EVT_BUTTON, self.onImportOptions,
self.input_window.opt_btn_import)
self.Bind(wx.EVT_BUTTON, self.onProcessOptions,
self.input_window.opt_btn_process)
self.Bind(wx.EVT_BUTTON, self.onAnalysisOptions,
self.input_window.opt_btn_analysis)
# File list control bindings
self.Bind(ulc.EVT_LIST_INSERT_ITEM, self.onItemInserted,
self.input_window.input)
def place_and_size(self):
""" Place and size the frame"""
# Determine effective minimum size
self.SetMinSize(self.GetEffectiveMinSize())
# Find mouse position
mx, my = wx.GetMousePosition()
# Center on display
self.SetPosition((mx, my))
self.Center()
def read_command_line_options(self):
help_message = '''This command will run the IOTA GUI '''
self.args, self.phil_args = parse_command_args('').parse_known_args()
if self.args.path is not None and len(self.args.path) > 0:
for carg in self.args.path:
if os.path.exists(carg):
if os.path.isfile(carg) and os.path.basename(carg).endswith('.param'):
self.load_script(filepath=carg, update_input_window=False)
else:
self.input_window.input.add_item(os.path.abspath(carg))
if self.args.watch > 0:
self.gparams.gui.monitor_mode = True
self.gparams.gui.monitor_mode_timeout = True
self.gparams.gui.monitor_mode_timeout_length = self.args.watch[0]
if self.args.random > 0:
self.gparams.advanced.random_sample.flag_on = True
self.gparams.advanced.random_sample.number = self.args.random[0]
if self.args.tmp is not None:
self.gparams.advanced.temporary_output_folder = self.args.tmp[0]
if self.args.nproc is not None:
self.gparams.mp.n_processors = self.args.nproc
self.iota_phil = self.iota_phil.format(python_object=self.gparams)
# Parse in-line params into phil
argument_interpreter = argint(master_phil=self.iota_phil)
consume = []
for arg in self.phil_args:
try:
command_line_params = argument_interpreter.process(arg=arg)
self.iota_phil = self.iota_phil.fetch(sources=[command_line_params, ])
consume.append(arg)
except Sorry:
pass
for item in consume:
self.phil_args.remove(item)
if len(self.phil_args) > 0:
raise Sorry(
"Not all arguments processed, remaining: {}".format(self.phil_args))
self.gparams = self.iota_phil.extract()
self.update_input_window()
def onItemInserted(self, e):
print (self.input_window.input.all_data_images)
def onReset(self, e):
self.reset_settings()
def onPreferences(self, e):
""" Opens dialog for IOTA preferences
:param e: event object for self.tb_btn_prefs
:return: modifies self.iota_phil with updated parameters
"""
prefs = dlg.IOTAPreferences(self, phil=self.iota_phil)
prefs.set_choices()
if prefs.ShowModal() == wx.ID_OK:
self.iota_phil = self.iota_phil.fetch(source=prefs.prefs_phil)
prefs.Destroy()
self.input_window.input_phil = self.iota_phil
self.gparams = self.iota_phil.extract()
self.input_window.gparams = self.gparams
def onImportOptions(self, e):
""" Opens dialog for image import options
:param e: event object for self.input_window.opt_btn_import
:return: modifies self.iota_phil with updated parameters
"""
imp_dialog = dlg.ImportWindow(self,
phil=self.iota_phil,
title='Import Options',
style=wx.DEFAULT_DIALOG_STYLE | wx.STAY_ON_TOP)
imp_dialog.Fit()
if (imp_dialog.ShowModal() == wx.ID_OK):
self.iota_phil = self.iota_phil.fetch(source=imp_dialog.import_phil)
imp_dialog.Destroy()
def onProcessOptions(self, e):
""" Opens dialog for image processing options, either for cctbx or DIALS
depending on user selection.
:param e: event object for self.input_window.opt_btn_process
:return: modifies self.iota_phil with updated parameters
"""
# For current cctbx.xfel options
if self.gparams.advanced.processing_backend == 'cctbx.xfel':
int_dialog = dlg.BackendOptions(self,
phil=self.iota_phil,
target=self.target_phil,
title='cctbx.xfel Options',
style=wx.DEFAULT_DIALOG_STYLE |
wx.STAY_ON_TOP | wx.RESIZE_BORDER)
int_dialog.SetMinSize((600, -1))
int_dialog.Fit()
# For deprecated cctbx.xfel HA14 options
elif self.gparams.advanced.processing_backend == 'ha14':
int_dialog = dlg.OldBackendOptions(self,
phil=self.iota_phil,
target=self.target_phil,
title='cctbx.xfel HA14 Options',
style=wx.DEFAULT_DIALOG_STYLE |
wx.STAY_ON_TOP | wx.RESIZE_BORDER)
int_dialog.SetMinSize((600, -1))
int_dialog.Fit()
else:
int_dialog = None
# Get values and set parameters
if int_dialog and (int_dialog.ShowModal() == wx.ID_OK):
self.iota_phil = self.iota_phil.fetch(source=int_dialog.proc_phil)
self.target_phil = int_dialog.target_phil
int_dialog.Destroy()
def onAnalysisOptions(self, e):
""" Opens dialog for integrated dataset analysis options
:param e: event object for self.input_window.opt_btn_analysis
:return: modifies self.iota_phil with updated parameters
"""
an_dialog = dlg.AnalysisWindow(self,
phil=self.iota_phil,
title='Dataset Analysis Options',
style=wx.DEFAULT_DIALOG_STYLE |
wx.STAY_ON_TOP | wx.RESIZE_BORDER)
an_dialog.SetMinSize((600, -1))
an_dialog.Fit()
# Get values and set parameters
if (an_dialog.ShowModal() == wx.ID_OK):
self.iota_phil = self.iota_phil.fetch(source=an_dialog.viz_phil)
an_dialog.Destroy()
def init_settings(self):
# Grab params from main window class
# Get list of inputs from input window
idxs = self.input_window.input.ctr.GetItemCount()
inputs = [self.input_window.input.ctr.GetItemData(i).path for i in range(idxs)]
# Set all main window params (including inputs)
self.gparams = self.iota_phil.extract()
self.gparams.input = inputs
self.gparams.description = util.noneset(
self.input_window.project_title.ctr.GetValue())
self.gparams.output = self.input_window.project_folder.ctr.GetValue()
self.gparams.mp.n_processors = self.input_window.opt_spc_nprocs.ctr.GetValue()
# Format main IOTA PHIL
self.iota_phil = self.iota_phil.format(python_object=self.gparams)
def OnAboutBox(self, e):
""" About dialog """
info = wx.AboutDialogInfo()
info.SetName('IOTA')
info.SetVersion(iota_version)
info.SetDescription(gui_description)
info.SetWebSite('http://cci.lbl.gov/xfel')
info.SetLicense(gui_license)
info.AddDeveloper('<NAME>')
info.AddDeveloper('<NAME>')
info.AddDeveloper('<NAME>')
info.AddDeveloper('<NAME>')
info.AddDeveloper('<NAME>')
info.AddDocWriter('<NAME>')
info.AddTranslator('<NAME>')
wx.AboutBox(info)
def onInput(self, e):
if self.input_window.inp_box.ctr.GetValue() != '':
self.toolbar.EnableTool(self.tb_btn_run.GetId(), True)
else:
self.toolbar.EnableTool(self.tb_btn_run.GetId(), False)
def onRecovery(self, e):
# Find finished runs and display results
int_folder = os.path.abspath('{}/integration'.format(os.curdir))
if not os.path.isdir(int_folder):
open_dlg = wx.DirDialog(self, "Choose the integration folder:",
style=wx.DD_DEFAULT_STYLE)
if open_dlg.ShowModal() == wx.ID_OK:
int_folder = open_dlg.GetPath()
open_dlg.Destroy()
else:
open_dlg.Destroy()
return
paths = [os.path.join(int_folder, p) for p in os.listdir(int_folder)]
paths = [p for p in paths if os.path.isdir(p)]
path_dlg = dlg.RecoveryDialog(self)
path_dlg.insert_paths(paths)
if path_dlg.ShowModal() == wx.ID_OK:
self.reset_settings()
selected = path_dlg.selected
recovery_mode = path_dlg.recovery_mode
int_path = selected[1]
init_file = os.path.join(int_path, 'init.cfg')
if os.path.isfile(init_file):
rec_init = ep.load(init_file)
tmp_phil = inp.master_phil.format(python_object=rec_init.params)
self.iota_phil = self.iota_phil.fetch(source=tmp_phil)
else:
rec_init = UIInitAll()
rec_init.int_base = int_path
rec_init.obj_base = os.path.join(int_path, 'image_objects')
rec_init.fin_base = os.path.join(int_path, 'final')
rec_init.log_base = os.path.join(int_path, 'logs')
rec_init.viz_base = os.path.join(int_path, 'visualization')
rec_init.logfile = os.path.join(int_path, 'iota.log')
with open(rec_init.logfile, 'r') as lf:
lines = lf.readlines()[4:86]
log_phil = ip.parse(''.join(lines))
self.iota_phil = self.iota_phil.fetch(source=log_phil)
rec_init.params = self.iota_phil.extract()
input_entries = [i for i in rec_init.params.input if i is | |
+ m.x388 - m.x423 + m.x472 + m.x486 - m.x521 + m.x570 + m.x584 - m.x619 + m.x668
+ m.x682 - m.x717 + m.x766 + m.x780 - m.x815 <= 100)
m.c2543 = Constraint(expr= m.x375 + m.x389 - m.x424 + m.x473 + m.x487 - m.x522 + m.x571 + m.x585 - m.x620 + m.x669
+ m.x683 - m.x718 + m.x767 + m.x781 - m.x816 <= 100)
m.c2544 = Constraint(expr= m.x376 + m.x390 - m.x425 + m.x474 + m.x488 - m.x523 + m.x572 + m.x586 - m.x621 + m.x670
+ m.x684 - m.x719 + m.x768 + m.x782 - m.x817 <= 100)
m.c2545 = Constraint(expr= m.x377 + m.x391 - m.x426 + m.x475 + m.x489 - m.x524 + m.x573 + m.x587 - m.x622 + m.x671
+ m.x685 - m.x720 + m.x769 + m.x783 - m.x818 <= 100)
m.c2546 = Constraint(expr= m.x378 + m.x392 - m.x427 + m.x476 + m.x490 - m.x525 + m.x574 + m.x588 - m.x623 + m.x672
+ m.x686 - m.x721 + m.x770 + m.x784 - m.x819 <= 100)
m.c2547 = Constraint(expr= m.x379 + m.x393 - m.x428 + m.x477 + m.x491 - m.x526 + m.x575 + m.x589 - m.x624 + m.x673
+ m.x687 - m.x722 + m.x771 + m.x785 - m.x820 <= 70)
m.c2548 = Constraint(expr= m.x380 + m.x394 + m.x408 - m.x429 - m.x436 + m.x478 + m.x492 + m.x506 - m.x527 - m.x534
+ m.x576 + m.x590 + m.x604 - m.x625 - m.x632 + m.x674 + m.x688 + m.x702 - m.x723 - m.x730
+ m.x772 + m.x786 + m.x800 - m.x821 - m.x828 <= 100)
m.c2549 = Constraint(expr= m.x381 + m.x395 + m.x409 - m.x430 - m.x437 + m.x479 + m.x493 + m.x507 - m.x528 - m.x535
+ m.x577 + m.x591 + m.x605 - m.x626 - m.x633 + m.x675 + m.x689 + m.x703 - m.x724 - m.x731
+ m.x773 + m.x787 + m.x801 - m.x822 - m.x829 <= 100)
m.c2550 = Constraint(expr= m.x382 + m.x396 + m.x410 - m.x431 - m.x438 + m.x480 + m.x494 + m.x508 - m.x529 - m.x536
+ m.x578 + m.x592 + m.x606 - m.x627 - m.x634 + m.x676 + m.x690 + m.x704 - m.x725 - m.x732
+ m.x774 + m.x788 + m.x802 - m.x823 - m.x830 <= 100)
m.c2551 = Constraint(expr= m.x383 + m.x397 + m.x411 - m.x432 - m.x439 + m.x481 + m.x495 + m.x509 - m.x530 - m.x537
+ m.x579 + m.x593 + m.x607 - m.x628 - m.x635 + m.x677 + m.x691 + m.x705 - m.x726 - m.x733
+ m.x775 + m.x789 + m.x803 - m.x824 - m.x831 <= 100)
m.c2552 = Constraint(expr= m.x384 + m.x398 + m.x412 - m.x433 - m.x440 + m.x482 + m.x496 + m.x510 - m.x531 - m.x538
+ m.x580 + m.x594 + m.x608 - m.x629 - m.x636 + m.x678 + m.x692 + m.x706 - m.x727 - m.x734
+ m.x776 + m.x790 + m.x804 - m.x825 - m.x832 <= 50)
m.c2553 = Constraint(expr= m.x385 + m.x399 + m.x413 - m.x434 - m.x441 + m.x483 + m.x497 + m.x511 - m.x532 - m.x539
+ m.x581 + m.x595 + m.x609 - m.x630 - m.x637 + m.x679 + m.x693 + m.x707 - m.x728 - m.x735
+ m.x777 + m.x791 + m.x805 - m.x826 - m.x833 <= 100)
m.c2554 = Constraint(expr= m.x386 + m.x400 + m.x414 - m.x435 - m.x442 + m.x484 + m.x498 + m.x512 - m.x533 - m.x540
+ m.x582 + m.x596 + m.x610 - m.x631 - m.x638 + m.x680 + m.x694 + m.x708 - m.x729 - m.x736
+ m.x778 + m.x792 + m.x806 - m.x827 - m.x834 <= 100)
m.c2555 = Constraint(expr= m.x401 + m.x415 - m.x443 + m.x499 + m.x513 - m.x541 + m.x597 + m.x611 - m.x639 + m.x695
+ m.x709 - m.x737 + m.x793 + m.x807 - m.x835 <= 100)
m.c2556 = Constraint(expr= m.x402 + m.x416 - m.x444 + m.x500 + m.x514 - m.x542 + m.x598 + m.x612 - m.x640 + m.x696
+ m.x710 - m.x738 + m.x794 + m.x808 - m.x836 <= 100)
m.c2557 = Constraint(expr= m.x403 + m.x417 - m.x445 + m.x501 + m.x515 - m.x543 + m.x599 + m.x613 - m.x641 + m.x697
+ m.x711 - m.x739 + m.x795 + m.x809 - m.x837 <= 100)
m.c2558 = Constraint(expr= m.x404 + m.x418 - m.x446 + m.x502 + m.x516 - m.x544 + m.x600 + m.x614 - m.x642 + m.x698
+ m.x712 - m.x740 + m.x796 + m.x810 - m.x838 <= 100)
m.c2559 = Constraint(expr= m.x405 + m.x419 - m.x447 + m.x503 + m.x517 - m.x545 + m.x601 + m.x615 - m.x643 + m.x699
+ m.x713 - m.x741 + m.x797 + m.x811 - m.x839 <= 100)
m.c2560 = Constraint(expr= m.x406 + m.x420 - m.x448 + m.x504 + m.x518 - m.x546 + m.x602 + m.x616 - m.x644 + m.x700
+ m.x714 - m.x742 + m.x798 + m.x812 - m.x840 <= 70)
m.c2561 = Constraint(expr= m.x407 + m.x421 - m.x449 + m.x505 + m.x519 - m.x547 + m.x603 + m.x617 - m.x645 + m.x701
+ m.x715 - m.x743 + m.x799 + m.x813 - m.x841 <= 100)
m.c2562 = Constraint(expr= 12*m.b16 + 12*m.b19 - m.x86 - m.x89 + m.x212 + m.x215 <= 12)
m.c2563 = Constraint(expr= 12*m.b16 + 12*m.b20 - m.x86 - m.x90 + m.x212 + m.x216 <= 12)
m.c2564 = Constraint(expr= 12*m.b17 + 12*m.b21 - m.x87 - m.x91 + m.x213 + m.x217 <= 12)
m.c2565 = Constraint(expr= 12*m.b17 + 12*m.b22 - m.x87 - m.x92 + m.x213 + m.x218 <= 12)
m.c2566 = Constraint(expr= 12*m.b17 + 12*m.b23 - m.x87 - m.x93 + m.x213 + m.x219 <= 12)
m.c2567 = Constraint(expr= 12*m.b18 + 12*m.b24 - m.x88 - m.x94 + m.x214 + m.x220 <= 12)
m.c2568 = Constraint(expr= 12*m.b18 + 12*m.b25 - m.x88 - m.x95 + m.x214 + m.x221 <= 12)
m.c2569 = Constraint(expr= 12*m.b19 + 12*m.b26 - m.x89 - m.x96 + m.x215 + m.x222 <= 12)
m.c2570 = Constraint(expr= 12*m.b21 + 12*m.b26 - m.x91 - m.x96 + m.x217 + m.x222 <= 12)
m.c2571 = Constraint(expr= 12*m.b23 + 12*m.b29 - m.x93 - m.x99 + m.x219 + m.x225 <= 12)
m.c2572 = Constraint(expr= 12*m.b25 + 12*m.b29 - m.x95 - m.x99 + m.x221 + m.x225 <= 12)
m.c2573 = Constraint(expr= 12*m.b26 + 12*m.b27 - m.x96 - m.x97 + m.x222 + m.x223 <= 12)
m.c2574 = Constraint(expr= 12*m.b28 + 12*m.b29 - m.x98 - m.x99 + m.x224 + m.x225 <= 12)
m.c2575 = Constraint(expr= 12*m.b16 + 12*m.b17 + 12*m.b18 - m.x86 - m.x87 - m.x88 + m.x212 + m.x213 + m.x214 <= 12)
m.c2576 = Constraint(expr= 12*m.b20 + 12*m.b27 + 12*m.b28 - m.x90 - m.x97 - m.x98 + m.x216 + m.x223 + m.x224 <= 12)
m.c2577 = Constraint(expr= 12*m.b22 + 12*m.b27 + 12*m.b28 - m.x92 - m.x97 - m.x98 + m.x218 + m.x223 + m.x224 <= 12)
m.c2578 = Constraint(expr= 12*m.b24 + 12*m.b27 + 12*m.b28 - m.x94 - m.x97 - m.x98 + m.x220 + m.x223 + m.x224 <= 12)
m.c2579 = Constraint(expr= 12*m.b30 + 12*m.b33 - m.x100 - m.x103 + m.x156 + m.x159 + m.x212 + m.x215 <= 12)
m.c2580 = Constraint(expr= 12*m.b30 + 12*m.b34 - m.x100 - m.x104 + m.x156 + m.x160 + m.x212 + m.x216 <= 12)
m.c2581 = Constraint(expr= 12*m.b31 + 12*m.b35 - m.x101 - m.x105 + m.x157 + m.x161 + m.x213 + m.x217 <= 12)
m.c2582 = Constraint(expr= 12*m.b31 + 12*m.b36 - m.x101 - m.x106 + m.x157 + m.x162 + m.x213 + m.x218 <= 12)
m.c2583 = Constraint(expr= 12*m.b31 + 12*m.b37 - m.x101 - m.x107 + m.x157 + m.x163 + m.x213 + m.x219 <= 12)
m.c2584 = Constraint(expr= 12*m.b32 + 12*m.b38 - m.x102 - m.x108 + m.x158 + m.x164 + m.x214 + m.x220 <= 12)
m.c2585 = Constraint(expr= 12*m.b32 + 12*m.b39 - m.x102 - m.x109 + m.x158 + m.x165 + m.x214 + m.x221 <= 12)
m.c2586 = Constraint(expr= 12*m.b33 + 12*m.b40 - m.x103 - m.x110 + m.x159 + m.x166 + m.x215 + m.x222 <= 12)
m.c2587 = Constraint(expr= 12*m.b35 + 12*m.b40 - m.x105 - m.x110 + m.x161 + m.x166 + m.x217 + m.x222 <= 12)
m.c2588 = Constraint(expr= 12*m.b37 + 12*m.b43 - m.x107 - m.x113 + m.x163 + m.x169 + m.x219 + m.x225 <= 12)
m.c2589 = Constraint(expr= 12*m.b39 + 12*m.b43 - m.x109 - m.x113 + m.x165 + m.x169 + | |
other objects as well.
Parameters:
- animation: may be a Trajectory or a list of configurations.
- speed: a modulator on the animation speed. If the animation is a list of
milestones, it is by default run at 1 milestone per second.
- endBehavior: either 'loop' (animation repeats forever) or 'halt' (plays once).
"""
global _vis
if _vis==None:
print "Visualization disabled"
return
_vis.animate(name,animation,speed,endBehavior)
def pauseAnimation(paused=True):
global _vis
if _vis==None:
print "Visualization disabled"
return
_vis.pauseAnimation(paused)
def stepAnimation(amount):
global _vis
if _vis==None:
print "Visualization disabled"
return
_vis.stepAnimation(amount)
def animationTime(newtime=None):
"""Gets/sets the current animation time
If newtime == None (default), this gets the animation time.
If newtime != None, this sets a new animation time.
"""
global _vis
if _vis==None:
print "Visualization disabled"
return 0
return _vis.animationTime(newtime)
def remove(name):
global _vis
if _vis==None:
return
return _vis.remove(name)
def getItemConfig(name):
global _vis
if _vis==None:
return None
return _vis.getItemConfig(name)
def setItemConfig(name,value):
global _vis
if _vis==None:
return
return _vis.setItemConfig(name,value)
def hideLabel(name,hidden=True):
global _vis
if _vis==None:
return
return _vis.hideLabel(name,hidden)
def hide(name,hidden=True):
global _vis
if _vis==None:
return
_vis.hide(name,hidden)
def edit(name,doedit=True):
"""Turns on/off visual editing of some item. Only points, transforms,
coordinate.Point's, coordinate.Transform's, coordinate.Frame's, robots,
and objects are currently accepted."""
global _vis
if _vis==None:
return
_vis.edit(name,doedit)
def setAppearance(name,appearance):
global _vis
if _vis==None:
return
_vis.setAppearance(name,appearance)
def setAttribute(name,attr,value):
global _vis
if _vis==None:
return
_vis.setAttribute(name,attr,value)
def revertAppearance(name):
global _vis
if _vis==None:
return
_vis.revertAppearance(name)
def setColor(name,r,g,b,a=1.0):
global _vis
if _vis==None:
return
_vis.setColor(name,r,g,b,a)
def setDrawFunc(name,func):
global _vis
if _vis==None:
return
_vis.setDrawFunc(name,func)
def _getOffsets(object):
if isinstance(object,WorldModel):
res = []
for i in range(object.numRobots()):
res += _getOffsets(object.robot(i))
for i in range(object.numRigidObjects()):
res += _getOffsets(object.rigidObject(i))
return res
elif isinstance(object,RobotModel):
q = object.getConfig()
object.setConfig([0.0]*len(q))
worig = [object.link(i).getTransform()[1] for i in range(object.numLinks())]
object.setConfig(q)
wnew = [object.link(i).getTransform()[1] for i in range(object.numLinks())]
return [vectorops.sub(b,a) for a,b in zip(worig,wnew)]
elif isinstance(object,RigidObjectModel):
return [object.getTransform()[1]]
elif isinstance(object,Geometry3D):
return object.getCurrentTransform()[1]
elif isinstance(object,VisAppearance):
res = _getOffsets(object.item)
if len(res) != 0: return res
if len(object.subAppearances) == 0:
bb = object.getBounds()
if bb != None and not aabb_empty(bb):
return [vectorops.mul(vectorops.add(bb[0],bb[1]),0.5)]
else:
res = []
for a in object.subAppearances.itervalues():
res += _getOffsets(a)
return res
return []
def _getBounds(object):
if isinstance(object,WorldModel):
res = []
for i in range(object.numRobots()):
res += _getBounds(object.robots(i))
for i in range(object.numRigidObjects()):
res += _getBounds(object.rigidObject(i))
return res
elif isinstance(object,RobotModel):
return sum([object.link(i).geometry().getBB() for i in range(object.numLinks())],[])
elif isinstance(object,RigidObjectModel):
return object.geometry().getAABB()
elif isinstance(object,Geometry3D):
return object.getAABB()
elif isinstance(object,VisAppearance):
if len(object.subAppearances) == 0:
if isinstance(object.item,TerrainModel):
return []
bb = object.getBounds()
if bb != None and not aabb_empty(bb):
return list(bb)
else:
res = []
for a in object.subAppearances.itervalues():
res += _getBounds(a)
return res
return []
def _fitPlane(pts):
import numpy as np
if len(pts) < 3:
raise ValueError("Point set is degenerate")
centroid = vectorops.div(vectorops.add(*pts),len(pts))
A = np.array([vectorops.sub(pt,centroid) for pt in pts])
U,S,V = np.linalg.svd(A,full_matrices=False)
imin = 0
smin = S[0]
zeros = []
for i in xrange(len(S)):
if abs(S[i]) < 1e-6:
zeros.append(i)
if abs(S[i]) < smin:
smin = S[i]
imin = i
if len(zeros) > 1:
raise ValueError("Point set is degenerate")
assert V.shape == (3,3)
#normal is the corresponding row of U
normal = V[imin,:]
return centroid,normal.tolist()
def autoFitViewport(viewport,objects):
ofs = sum([_getOffsets(o) for o in objects],[])
pts = sum([_getBounds(o) for o in objects],[])
#print "Bounding box",bb,"center",center
#raw_input()
#reset
viewport.camera.rot = [0.,0.,0.]
viewport.camera.tgt = [0.,0.,0.]
viewport.camera.dist = 6.0
viewport.clippingplanes = (0.2,20)
if len(ofs) == 0:
return
bb = aabb_create(*pts)
center = vectorops.mul(vectorops.add(bb[0],bb[1]),0.5)
viewport.camera.tgt = center
radius = max(vectorops.distance(bb[0],center),0.1)
viewport.camera.dist = 1.2*radius / math.tan(math.radians(viewport.fov*0.5))
#default: oblique view
viewport.camera.rot = [0,math.radians(30),math.radians(45)]
#fit a plane to these points
try:
centroid,normal = _fitPlane(ofs)
except Exception as e:
try:
centroid,normal = _fitPlane(pts)
except Exception as e:
print "Exception occurred during fitting to points"
print ofs
print pts
raise
return
if normal[2] > 0:
normal = vectorops.mul(normal,-1)
z,x,y = so3.matrix(so3.inv(so3.canonical(normal)))
#print z,x,y
#raw_input()
radius = max([abs(vectorops.dot(x,vectorops.sub(center,pt))) for pt in pts] + [abs(vectorops.dot(y,vectorops.sub(center,pt)))*viewport.w/viewport.h for pt in pts])
zmin = min([vectorops.dot(z,vectorops.sub(center,pt)) for pt in pts])
zmax = max([vectorops.dot(z,vectorops.sub(center,pt)) for pt in pts])
#print "Viewing direction",normal,"at point",center,"with scene size",radius
#orient camera to point along normal direction
viewport.camera.tgt = center
viewport.camera.dist = 1.2*radius / math.tan(math.radians(viewport.fov*0.5))
near,far = viewport.clippingplanes
if viewport.camera.dist + zmin < near:
near = max((viewport.camera.dist + zmin)*0.5, radius*0.1)
if viewport.camera.dist + zmax > far:
far = max((viewport.camera.dist + zmax)*1.5, radius*3)
viewport.clippingplanes = (near,far)
roll = 0
yaw = math.atan2(normal[0],normal[1])
pitch = math.atan2(-normal[2],vectorops.norm(normal[0:2]))
#print "Roll pitch and yaw",roll,pitch,yaw
#print "Distance",viewport.camera.dist
viewport.camera.rot = [roll,pitch,yaw]
def addText(name,text,pos=None):
"""Adds text to the visualizer. You must give an identifier to all pieces of
text, which will be used to access the text as any other vis object.
Parameters:
- name: the text's unique identifier.
- text: the string to be drawn
- pos: the position of the string. If pos=None, this is added to the on-screen "console" display.
If pos has length 2, it is the (x,y) position of the upper left corner of the text on the
screen. Negative units anchor the text to the right or bottom of the window.
If pos has length 3, the text is drawn in the world coordinates.
To customize the text appearance, you can set the color, 'size' attribute, and 'position'
attribute of the text using the identifier given in 'name'.
"""
global _vis
_vis.add(name,text,True)
if pos is not None:
_vis.setAttribute(name,'position',pos)
def clearText():
"""Clears all text in the visualization."""
global _vis
if _vis==None:
return
_vis.clearText()
def addPlot(name):
add(name,VisPlot())
def addPlotItem(name,itemname):
global _vis
if _vis==None:
return
_vis.addPlotItem(name,itemname)
def logPlot(name,itemname,value):
"""Logs a custom visualization item to a plot"""
global _vis
if _vis==None:
return
_vis.logPlot(name,itemname,value)
def logPlotEvent(name,eventname,color=None):
"""Logs an event on the plot."""
global _vis
if _vis==None:
return
_vis.logPlotEvent(name,eventname,color)
def hidePlotItem(name,itemname,hidden=True):
global _vis
if _vis==None:
return
_vis.hidePlotItem(name,itemname,hidden)
def setPlotDuration(name,time):
setAttribute(name,'duration',time)
def setPlotRange(name,vmin,vmax):
setAttribute(name,'range',(vmin,vmax))
def setPlotPosition(name,x,y):
setAttribute(name,'position',(x,y))
def setPlotSize(name,w,h):
setAttribute(name,'size',(w,h))
def savePlot(name,fn):
global _vis
if _vis==None:
return
_vis.savePlot(name,fn)
def autoFitCamera(scale=1):
global _vis
if _vis==None:
return
print "klampt.vis: auto-fitting camera to scene."
_vis.autoFitCamera(scale)
def objectToVisType(item,world):
itypes = types.objectToTypes(item,world)
if isinstance(itypes,(list,tuple)):
#ambiguous, still need to figure out what to draw
validtypes = []
for t in itypes:
if t == 'Config':
if world != None and len(item) == world.robot(0).numLinks():
validtypes.append(t)
elif t=='Vector3':
validtypes.append(t)
elif t=='RigidTransform':
validtypes.append(t)
if len(validtypes) > 1:
print "Unable to draw item of ambiguous types",validtypes
print " (Try vis.setAttribute(item,'type',desired_type_str) to disambiguate)"
return
if len(validtypes) == 0:
print "Unable to draw any of types",itypes
return
return validtypes[0]
return itypes
def aabb_create(*ptlist):
if len(ptlist) == 0:
return [float('inf')]*3,[float('-inf')]*3
else:
bmin,bmax = list(ptlist[0]),list(ptlist[0])
for i in xrange(1,len(ptlist)):
x = ptlist[i]
bmin = [min(a,b) for (a,b) in zip(bmin,x)]
bmax = [max(a,b) for (a,b) in zip(bmax,x)]
return bmin,bmax
def aabb_expand(bb,bb2):
bmin = [min(a,b) for a,b in zip(bb[0],bb2[0])]
bmax = [max(a,b) for a,b in zip(bb[1],bb2[1])]
return (bmin,bmax)
def aabb_empty(bb):
return any((a > b) for (a,b) in zip(bb[0],bb[1]))
_defaultCompressThreshold = 1e-2
class VisPlotItem:
def __init__(self,itemname,linkitem):
self.name = itemname
self.itemnames = []
self.linkitem = linkitem
self.traces = []
self.hidden = []
self.traceRanges = []
self.luminosity = []
self.compressThreshold = _defaultCompressThreshold
if linkitem is not None:
q = config.getConfig(linkitem.item)
assert q is not None
from collections import deque
self.traces = [deque() for i in range(len(q))]
self.itemnames = config.getConfigNames(linkitem.item)
def customUpdate(self,item,t,v):
for i,itemname in enumerate(self.itemnames):
if item == itemname:
self.updateTrace(i,t,v)
self.traceRanges[i] = (min(self.traceRanges[i][0],v),max(self.traceRanges[i][1],v))
return
else:
from collections import deque
self.itemnames.append(item)
self.traces.append(deque())
i = len(self.itemnames)-1
self.updateTrace(i,t,v)
self.traceRanges[i] = (min(self.traceRanges[i][0],v),max(self.traceRanges[i][1],v))
#raise ValueError("Invalid item specified: "+str(item))
def update(self,t):
if self.linkitem is None:
return
q = config.getConfig(self.linkitem.item)
assert len(self.traces) == len(q)
for i,v in enumerate(q):
self.updateTrace(i,t,v)
self.traceRanges[i] = (min(self.traceRanges[i][0],v),max(self.traceRanges[i][1],v))
def discard(self,tstart):
for t in self.traces:
if len(t)<=1: return
while len(t) >= 2:
if t[1][0] < tstart:
t.popleft()
else:
break
def updateTrace(self,i,t,v):
import random
assert i < len(self.traces)
assert i <= len(self.hidden)
assert i <= len(self.luminosity)
while i >= len(self.hidden):
self.hidden.append(False)
while i >= len(self.traceRanges):
self.traceRanges.append((v,v))
if i >= len(self.luminosity):
initialLuminosity = [0.5,0.25,0.75,1.0]
while i >= len(self.luminosity):
if len(self.luminosity)<len(initialLuminosity):
self.luminosity.append(initialLuminosity[len(self.luminosity)])
else:
self.luminosity.append(random.uniform(0,1))
trace = self.traces[i]
if len(trace) > 0 and trace[-1][0] == t:
trace[-1] = (t,v)
return
if self.compressThreshold is None:
trace.append((t,v))
else:
if len(trace) < 2:
trace.append((t,v))
else:
pprev = trace[-2]
prev = trace[-1]
assert prev > pprev,"Added two items with the same time?"
assert t > prev[0]
slope_old = (prev[1]-pprev[1])/(prev[0]-pprev[0])
slope_new = (v-prev[1])/(t-prev[0])
if (slope_old > 0 | |
field.name == 'date' or field.name == 'startTime':
setattr(sf, field.name, str(getattr(session, field.name)))
else:
setattr(sf, field.name, getattr(session, field.name))
sf.websafeKey = session.key.urlsafe()
sf.check_initialized()
return sf
def _createSessionObject(self, request):
"""Create or update Session object, returning SessionForm/request."""
# preload necessary data items
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
if not request.name:
raise endpoints.BadRequestException(
"Session 'name' field required"
)
wsck = request.websafeConferenceKey
conf = self._checkEntityKey(wsck, CONFERENCE)
if conf.organizerUserId != user_id:
raise endpoints.UnauthorizedException(
"Not authorized. Only conference owner can add sessions"
)
# copy SessionForm/ProtoRPC Message into dict
data = {
field.name: getattr(
request, field.name
) for field in request.all_fields()
}
websafeConferenceKey = data['websafeConferenceKey']
del data['websafeConferenceKey']
del data['websafeKey']
# convert dates from strings to Date objects;
# set month based on start_date
if data['date']:
data['date'] = datetime.strptime(
data['date'][:10], "%Y-%m-%d"
).date()
if data['startTime']:
data['startTime'] = datetime.strptime(
data['startTime'], '%H:%M'
).time()
# generate Session Key based on Conference
s_id = Session.allocate_ids(size=1, parent=conf.key)[0]
s_key = ndb.Key(Session, s_id, parent=conf.key)
data['key'] = s_key
# create Session, add the set speaker task to the queue
# creation of Session & return (modified) SessionForm
session = Session(**data)
session.put()
taskqueue.add(params={'speaker': data["speaker"],
'websafeConferenceKey': websafeConferenceKey},
url='/tasks/set_speaker')
return self._copySessionToForm(session)
@endpoints.method(
SessionForm,
SessionForm,
path='session',
http_method='POST',
name='createSession'
)
def createSession(self, request):
"""Create new session."""
return self._createSessionObject(request)
@endpoints.method(
SESSION_GET_REQUEST,
SessionForms,
path='conference/{websafeConferenceKey}/sessions',
http_method='GET',
name='getConferenceSessions'
)
def getConferenceSessions(self, request):
"""Return conference sessions (by websafeConferenceKey)."""
# get Conference object from request
wsck = request.websafeConferenceKey
conf = self._checkEntityKey(wsck, CONFERENCE)
# get all Session objects with the conf ancestor
sessions = Session.query(ancestor=conf.key)
# return list of SessionForm objects
return SessionForms(
items=[self._copySessionToForm(session) for session in sessions]
)
@endpoints.method(
SESSION_GET_REQUEST,
SessionForms,
path='conference/{websafeConferenceKey}/sessions/type/{typeOfSession}',
http_method='GET', name='getConferenceSessionsByType'
)
def getConferenceSessionsByType(self, request):
"""Given a conference, return all sessions of a specified type"""
wsck = request.websafeConferenceKey
conf = self._checkEntityKey(wsck, CONFERENCE)
# get all sessions of specified type for a specified conference
sessions = Session.query(
Session.typeOfSession == request.typeOfSession, ancestor=conf.key
)
# return set of SessionForm objects per Session
return SessionForms(
items=[self._copySessionToForm(session) for session in sessions]
)
@endpoints.method(
SESSION_GET_REQUEST,
SessionForms,
path='speaker/{speaker}/sessions',
http_method='GET',
name='getSessionsBySpeaker'
)
def getSessionsBySpeaker(self, request):
"""Return all sessions of a specified type"""
# get all sessions with the provided speaker
sessions = Session.query(Session.speaker == request.speaker)
# return set of SessionForm objects per Session
return SessionForms(
items=[self._copySessionToForm(session) for session in sessions]
)
@endpoints.method(
SESSION_GET_REQUEST,
SessionForms,
path='conference/{websafeConferenceKey}/sessions/date/{date}',
http_method='GET',
name='getConferenceSessionsByDate'
)
def getConferenceSessionsByDate(self, request):
"""Given a conference, return all sessions of a specified date"""
wsck = request.websafeConferenceKey
conf = self._checkEntityKey(wsck, CONFERENCE)
# get all sessions on a specified date for a specified conference
sessions = Session.query(
Session.date == datetime.strptime(
request.date[:10], "%Y-%m-%d"
).date(), ancestor=conf.key
)
# return set of SessionForm objects per Session
return SessionForms(
items=[self._copySessionToForm(session) for session in sessions]
)
@endpoints.method(
SESSION_GET_REQUEST,
SessionForms,
path='conference/{websafeConferenceKey}/'
'sessions/highlight/{highlight}',
http_method='GET',
name='getConferenceSessionsByHighlight'
)
def getConferenceSessionsByHighlight(self, request):
"""Given a conference, return all sessions with specified highlight"""
# fetch existing conference
wsck = request.websafeConferenceKey
conf = self._checkEntityKey(wsck, CONFERENCE)
# get all sessions with specified highlight for a specified conference
sessions = Session.query(
Session.highlights == request.highlight,
ancestor=conf.key
)
# return set of SessionForm objects per Session
return SessionForms(
items=[self._copySessionToForm(session) for session in sessions]
)
# - - - Wishlist objects - - - - - - - - - - - - - - - - - -
@endpoints.method(
WISHLIST_POST_REQUEST, StringMessage,
path='profile/wishlist/add/{websafeSessionKey}',
http_method='POST', name='addSessionToWishList')
def addSessionToWishlist(self, request):
"""Given a session, add it to the users wishlist"""
# Get the current user
user = endpoints.get_current_user()
user_id = getUserId(user)
# Get the profile for the current user
profile_key = ndb.Key(Profile, user_id)
profile = profile_key.get()
# Check if the session is already in the wishlist
# if it's not add it
session = self._checkEntityKey(request.websafeSessionKey, SESSION)
if session.key in profile.wishlist:
return StringMessage(data="Session already in wishlist!")
else:
profile.wishlist.append(session.key)
profile.put()
return StringMessage(data="Session added to wishlist!")
@endpoints.method(
WISHLIST_POST_REQUEST, StringMessage,
path='profile/wishlist/delete/{websafeSessionKey}',
http_method='DELETE', name='deleteSessionInWishlist')
def deleteSessionInWishlist(self, request):
"""Given a session, delete it from the users wishlist"""
# Get the current user
user = endpoints.get_current_user()
user_id = getUserId(user)
# Get the profile for the current user
profile_key = ndb.Key(Profile, user_id)
profile = profile_key.get()
session = self._checkEntityKey(request.websafeSessionKey, SESSION)
# Check if the session is already in the wishlist
# if it is, remove it
if session.key in profile.wishlist:
profile.wishlist.remove(session.key)
profile.put()
return StringMessage(data="Session deleted from wishlist!")
else:
return StringMessage(data="Session not in wishlist!")
@endpoints.method(
message_types.VoidMessage, SessionForms,
path='profile/wishlist',
http_method='GET', name='getSessionsInWishlist')
def getSessionsInWishlist(self, request):
"""Return all sessions in logged-in user's wishlist."""
profile = self._getProfileFromUser()
sessions = ndb.get_multi(profile.wishlist)
return SessionForms(
items=[self._copySessionToForm(s) for s in sessions])
# - - - Profile objects - - - - - - - - - - - - - - - - - - -
def _copyProfileToForm(self, prof):
"""Copy relevant fields from Profile to ProfileForm."""
# copy relevant fields from Profile to ProfileForm
pf = ProfileForm()
for field in pf.all_fields():
if hasattr(prof, field.name):
# convert t-shirt string to Enum; just copy others
if field.name == 'teeShirtSize':
setattr(
pf,
field.name,
getattr(TeeShirtSize, getattr(prof, field.name))
)
else:
setattr(pf, field.name, getattr(prof, field.name))
pf.check_initialized()
return pf
def _getProfileFromUser(self):
"""
Return user Profile from datastore, creating new one if non-existent.
"""
# make sure user is authed
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
# get Profile from datastore
user_id = getUserId(user)
p_key = ndb.Key(Profile, user_id)
profile = p_key.get()
# create new Profile if not there
if not profile:
profile = Profile(
key=p_key,
displayName=user.nickname(),
mainEmail=user.email(),
teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
)
profile.put()
return profile # return Profile
def _doProfile(self, save_request=None):
"""Get user Profile and return to user, possibly updating it first."""
# get user Profile
prof = self._getProfileFromUser()
# if saveProfile(), process user-modifyable fields
if save_request:
for field in ('displayName', 'teeShirtSize'):
if hasattr(save_request, field):
val = getattr(save_request, field)
if val:
setattr(prof, field, str(val))
prof.put()
# return ProfileForm
return self._copyProfileToForm(prof)
@endpoints.method(
message_types.VoidMessage,
ProfileForm,
path='profile',
http_method='GET',
name='getProfile'
)
def getProfile(self, request):
"""Return user profile."""
return self._doProfile()
@endpoints.method(
ProfileMiniForm,
ProfileForm,
path='profile',
http_method='POST',
name='saveProfile'
)
def saveProfile(self, request):
"""Update & return user profile."""
return self._doProfile(request)
# - - - Announcements - - - - - - - - - - - - - - - - - - - -
@staticmethod
def _cacheAnnouncement():
"""Create Announcement & assign to memcache; used by
memcache cron job & putAnnouncement().
"""
confs = Conference.query(ndb.AND(
Conference.seatsAvailable <= 5,
Conference.seatsAvailable > 0)
).fetch(projection=[Conference.name])
if confs:
# If there are almost sold out conferences,
# format announcement and set it in memcache
announcement = ANNOUNCEMENT_TPL % (
', '.join(conf.name for conf in confs))
memcache.set(MEMCACHE_ANNOUNCEMENTS_KEY, announcement)
else:
# If there are no sold out conferences,
# delete the memcache announcements entry
announcement = ""
memcache.delete(MEMCACHE_ANNOUNCEMENTS_KEY)
return announcement
@endpoints.method(
message_types.VoidMessage,
StringMessage,
path='conference/announcement/get',
http_method='GET',
name='getAnnouncement'
)
def getAnnouncement(self, request):
"""Return Announcement from memcache."""
announcement = memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY)
if not announcement:
announcement = ""
return StringMessage(data=announcement)
# - - - Featured Speaker - - - - - - - - - - - - - - - - - - - -
@endpoints.method(
message_types.VoidMessage,
StringMessage,
path='conference/featured_speaker/get',
http_method='GET',
name='getFeaturedSpeaker'
)
def getFeaturedSpeaker(self, request):
"""Return Featured Speaker from memcache."""
speaker = memcache.get(MEMCACHE_SPEAKER_KEY)
return StringMessage(data=speaker or "")
@staticmethod
def _cacheSpeaker(speaker, wsck):
"""
Create Featured Speaker and assign to memcache via task queue
"""
speaker_message = memcache.get(MEMCACHE_SPEAKER_KEY) or ""
conf = ConferenceApi._checkEntityKey(wsck, CONFERENCE)
sessions = Session.query(ancestor=conf.key)
sessions = sessions.filter(Session.speaker == speaker)
if sessions.count() > 1:
# If the sessions with the speaker is more than one
# format speaker_message and set it in memcache
speaker_message = SPEAKER_TPL % (
speaker, ', '.join(session.name for session in sessions)
)
memcache.set(MEMCACHE_SPEAKER_KEY, speaker_message)
# - - - Registration - - - - - - - - - - - - - - - - - - - -
@ndb.transactional(xg=True)
def _conferenceRegistration(self, request, reg=True):
"""Register or unregister user for selected conference."""
retval = None
prof = self._getProfileFromUser() # get user Profile
# check if conf exists given websafeConfKey
# get conference; check that it exists
wsck = request.websafeConferenceKey
conf = self._checkEntityKey(wsck, CONFERENCE)
# register
if reg:
# check if user already registered otherwise add
if wsck in prof.conferenceKeysToAttend:
raise ConflictException(
"You have already registered for this conference")
# | |
# -----------------------------------------------------------------------------
# Copyright (c) 2013-2021, NeXpy Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING, distributed with this software.
# -----------------------------------------------------------------------------
"""Simple sqlite-based logging for NXrefine.
The database file is located by default at GUP-xxx/tasks/nxdatabase.db.
It contains two tables:
1. Files: Meant for quickly checking the completion status of scans.
For each task, records if it is not started, queued but not yet
running, in progress (started for at least one entry), or done
(finished for all entries).
2. Tasks: Detailed information about all tasks. Records queue time
(when it was placed in the NXserver's fifo, or null if it was
run from the command line), start time, end time, the task's
PID, the wrapper file and entry it is working on, and its
status.
Example
-------
Before any other calls, use init() to establish a connection to the
database
>>> from nxrefine.nxdatabase import NXDatabase
>>> nxdb = NXDatabase('relative/path/to/database/file')
Use sync_db() to scan the sample directory and update the database to
match the contents of the wrapper files. This only needs to be run if
there are changes to the files outside of NXrefine code (eg manually
deleting an entry or adding a new .nxs files). Other changes are tracked
automatically.
NXDatabase assumes that no identical tasks (i.e., same task, entry, and
wrapper file) will be queued or running at the same time
"""
import datetime
import os
from nexusformat.nexus import NeXusError, NXLock, nxload
from sqlalchemy import (Column, ForeignKey, Integer, String, create_engine,
inspect)
from sqlalchemy.dialects import mysql
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
Base = declarative_base()
# Records files that have: not been processed, queued on the NXserver
# but not started, started processing, finished processing
_prog = {'not started': 0, 'queued': 1, 'in progress': 2, 'done': 3}
NOT_STARTED, QUEUED, IN_PROGRESS, DONE, FAILED = 0, 1, 2, 3, -1
class File(Base):
__tablename__ = 'files'
filename = Column(String(255), nullable=False, primary_key=True)
entries = Column(String(128), nullable=True)
data = Column(Integer, default=NOT_STARTED)
nxlink = Column(Integer, default=NOT_STARTED)
nxmax = Column(Integer, default=NOT_STARTED)
nxfind = Column(Integer, default=NOT_STARTED)
nxcopy = Column(Integer, default=NOT_STARTED)
nxrefine = Column(Integer, default=NOT_STARTED)
nxprepare = Column(Integer, default=NOT_STARTED)
nxtransform = Column(Integer, default=NOT_STARTED)
nxmasked_transform = Column(Integer, default=NOT_STARTED)
nxcombine = Column(Integer, default=NOT_STARTED)
nxmasked_combine = Column(Integer, default=NOT_STARTED)
nxpdf = Column(Integer, default=NOT_STARTED)
nxmasked_pdf = Column(Integer, default=NOT_STARTED)
def __repr__(self):
not_started = [k for k, v in vars(self).items() if v == NOT_STARTED]
queued = [k for k, v in vars(self).items() if v == QUEUED]
in_progress = [k for k, v in vars(self).items() if v == IN_PROGRESS]
done = [k for k, v in vars(self).items() if v == DONE]
return "File path='{}',\n\tnot started={}\n\tqueued={}\n\t" \
"in_progress={}\n\tdone={}".format(
self.filename, not_started, queued, in_progress, done)
def get_entries(self):
if self.entries:
return self.entries.split('|')
else:
return []
def set_entries(self, entries):
self.entries = '|'.join(entries)
class Task(Base):
__tablename__ = 'tasks'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
entry = Column(String, default='')
status = Column(Integer, default=QUEUED)
entries = Column(Integer, default=NOT_STARTED)
# Timestamps with microsecond precision
queue_time = Column(mysql.TIMESTAMP(fsp=6))
start_time = Column(mysql.TIMESTAMP(fsp=6))
end_time = Column(mysql.TIMESTAMP(fsp=6))
pid = Column(Integer)
filename = Column(String(255), ForeignKey('files.filename'),
nullable=False)
file = relationship('File', back_populates='tasks')
def __repr__(self):
return "<Task {} on {}, entry {}, pid={}>".format(
self.name, self.filename, self.entry, self.pid)
File.tasks = relationship('Task', back_populates='file', order_by=Task.id)
class NXDatabase(object):
task_names = ('data', 'nxlink', 'nxmax', 'nxfind', 'nxcopy', 'nxrefine',
'nxprepare', 'nxtransform', 'nxmasked_transform',
'nxcombine', 'nxmasked_combine', 'nxpdf', 'nxmasked_pdf')
NOT_STARTED, QUEUED, IN_PROGRESS, DONE, FAILED = 0, 1, 2, 3, -1
def __init__(self, db_file, echo=False):
"""Connect to the database, creating tables if necessary.
Parameters
----------
db_file : str
Path to the database file
echo : bool, optional
True if SQL statements are echoed to `stdout`, by default False.
"""
with NXLock(db_file):
connection = 'sqlite:///' + db_file
self.engine = create_engine(connection, echo=echo)
Base.metadata.create_all(self.engine)
self.database = os.path.realpath(self.engine.url.database)
self._session = None
@property
def session(self):
if self._session is None:
self._session = sessionmaker(bind=self.engine)()
return self._session
def get_filename(self, filename):
"""Return the relative path of the requested filename."""
root = os.path.dirname(os.path.dirname(self.database))
return os.path.relpath(os.path.realpath(filename), root)
def get_file(self, filename):
"""Return the File object (and associated tasks) matching filename.
Parameters
----------
filename : str
Path of wrapper file.
Returns
-------
File
File object.
"""
self.check_tasks()
f = self.query(filename)
if f is None:
filename = os.path.realpath(filename)
if not os.path.exists(filename):
raise NeXusError(f"'{filename}' does not exist")
self.session.add(File(filename=self.get_filename(filename)))
self.session.commit()
f = self.sync_file(filename)
else:
if (f.entries is None or f.entries == ''
or isinstance(f.entries, int)):
root = nxload(filename)
f.set_entries([e for e in root.entries if e != 'entry'])
f = self.sync_data(filename)
return f
def query(self, filename):
return self.session.query(File) \
.filter(File.filename == self.get_filename(filename)) \
.one_or_none()
def sync_file(self, filename):
"""Synchronize the NeXus file contents to the database.
Parameters
----------
filename : str
Path of wrapper file relative to GUP directory.
Returns
-------
File
Updated File object.
"""
f = self.get_file(filename)
sample_dir = os.path.dirname(filename)
if f:
try:
scan_files = os.listdir(get_directory(filename))
except OSError:
scan_files = []
root = nxload(filename)
entries = [e for e in root.entries if e != 'entry']
tasks = {t: 0 for t in self.task_names}
for e in entries:
nxentry = root[e]
if e in root and 'data' in nxentry and 'instrument' in nxentry:
if e+'.h5' in scan_files or e+'.nxs' in scan_files:
tasks['data'] += 1
if 'nxlink' in nxentry:
tasks['nxlink'] += 1
if 'nxmax' in nxentry:
tasks['nxmax'] += 1
if 'nxfind' in nxentry:
tasks['nxfind'] += 1
if 'nxcopy' in nxentry or is_parent(filename, sample_dir):
tasks['nxcopy'] += 1
if 'nxrefine' in nxentry:
tasks['nxrefine'] += 1
if 'nxprepare_mask' in nxentry:
tasks['nxprepare'] += 1
if 'nxtransform' in nxentry:
tasks['nxtransform'] += 1
if 'nxmasked_transform' in nxentry or 'nxmask' in nxentry:
tasks['nxmasked_transform'] += 1
if 'nxcombine' in root['entry']:
tasks['nxcombine'] = len(entries)
if 'nxmasked_combine' in root['entry']:
tasks['nxmasked_combine'] = len(entries)
if 'nxpdf' in root['entry']:
tasks['nxpdf'] = len(entries)
if 'nxmasked_pdf' in root['entry']:
tasks['nxmasked_pdf'] = len(entries)
for task, value in tasks.items():
if value == 0:
setattr(f, task, NOT_STARTED)
elif value == len(entries):
setattr(f, task, DONE)
else:
setattr(f, task, IN_PROGRESS)
f.set_entries(entries)
self.session.commit()
return f
def sync_data(self, filename):
"""Update status of raw data linked from File.
Parameters
----------
filename : str
Path of wrapper file relative to GUP directory.
Returns
-------
File
Updated File object.
"""
f = self.query(filename)
if f:
scan_dir = get_directory(filename)
entries = f.get_entries()
data = 0
for e in entries:
if os.path.exists(os.path.join(scan_dir, e+'.h5')):
data += 1
if data == 0:
f.data = NOT_STARTED
elif data == len(entries):
f.data = DONE
else:
f.data = IN_PROGRESS
self.session.commit()
return f
def get_task(self, f, task, entry):
"""Return the latest database entry for the specified task.
This creates a new task if one does not exist.
Parameters
----------
file : File
File object.
task : str
Task being checked.
entry : str
Entry of NeXus file being checked.
"""
for t in reversed(f.tasks):
if t.name == task and t.entry == entry:
break
else:
# This task was started from command line
t = Task(name=task, entry=entry)
f.tasks.append(t)
return t
def task_status(self, filename, task, entry=None):
"""Return the status of the task.
Parameters
----------
filename : str
Path of wrapper file.
task : str
Task being checked.
entry : str
Entry of NeXus file being checked.
"""
with NXLock(self.database):
f = self.get_file(filename)
if entry:
for t in reversed(f.tasks):
if t.name == task and t.entry == entry:
status = t.status
break
else:
status = NOT_STARTED
else:
status = getattr(f, task)
return status
def task_complete(self, filename, task, entry=None):
return self.task_status(filename, task, entry) == DONE
def queue_task(self, filename, task, entry, queue_time=None):
"""Update a file to 'queued' status and create a matching task.
Parameters
----------
filename : str
Path of wrapper file relative to GUP directory.
task : str
Task being updated.
entry : str
Entry of NeXus file being updated.
"""
with NXLock(self.database):
f = self.get_file(filename)
t = self.get_task(f, task, entry)
t.status = QUEUED
if queue_time:
t.queue_time = queue_time
else:
t.queue_time = datetime.datetime.now()
t.start_time = t.end_time = None
self.update_status(f, task)
def start_task(self, filename, task, entry, start_time=None):
"""Record that a task has begun execution.
Parameters
----------
filename : str
Path of wrapper file relative to GUP directory.
task : str
Task being updated.
entry : str
Entry of NeXus file being updated.
"""
with NXLock(self.database):
f = self.get_file(filename)
t = self.get_task(f, task, entry)
t.status = IN_PROGRESS
if start_time:
t.start_time | |
#!/usr/bin/env python3
"""Command-line interface to gruut"""
import argparse
import csv
import dataclasses
import itertools
import json
import logging
import os
import shutil
import sys
import tempfile
import typing
from collections import Counter
from pathlib import Path
import jsonlines
import pydash
import yaml
import gruut_ipa
from . import Language
from .toksen import Token
from .utils import (
WordPronunciation,
env_constructor,
load_lexicon,
maybe_gzip_open,
pairwise,
)
# -----------------------------------------------------------------------------
_LOGGER = logging.getLogger("gruut")
_DIR = Path(__file__).parent
# -----------------------------------------------------------------------------
def main():
"""Main entry point"""
# Expand environment variables in string value
yaml.SafeLoader.add_constructor("!env", env_constructor)
args = get_args()
if args.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
_LOGGER.debug(args)
if not args.data_dir:
# Set to ${XDG_CONFIG_HOME}/gruut or ${HOME}/gruut
maybe_config_home = os.environ.get("XDG_CONFIG_HOME")
if maybe_config_home:
args.data_dir = Path(maybe_config_home) / "gruut"
else:
args.data_dir = Path.home() / ".config" / "gruut"
if args.command == "download":
# Download language-specific files
do_download(args)
else:
# Directories to search for language-specific data files
data_dirs = Language.get_data_dirs([args.data_dir])
for data_dir in data_dirs:
maybe_lang_dir = data_dir / args.language
if maybe_lang_dir.is_dir():
config_path = maybe_lang_dir / "language.yml"
if config_path.is_file():
break
assert maybe_lang_dir, "Language '{args.language}' not found in {data_dirs}"
setattr(args, "lang_dir", maybe_lang_dir)
# Load configuration
config_path = args.lang_dir / "language.yml"
assert config_path.is_file(), f"Missing {config_path}"
# Set environment variable for config loading
os.environ["config_dir"] = str(config_path.parent)
with open(config_path, "r") as config_file:
config = yaml.safe_load(config_file)
args.func(config, args)
# -----------------------------------------------------------------------------
def try_load_language(args, language: typing.Optional[str] = None, **kwargs):
"""Attempt to load a language by code (e.g. en-us)"""
if not language:
language = args.language
assert language
_LOGGER.debug("Loading %s from %s", language, args.lang_dir)
gruut_lang = Language.load(language=language, lang_dir=args.lang_dir, **kwargs)
assert gruut_lang, f"Language not found: {language} in {args.lang_dir}"
return gruut_lang
# -----------------------------------------------------------------------------
def do_download(args):
"""
Downloads and extracts pre-trained model to args.data_dir
"""
from . import __version__
from .download import download_file
# x.y.z -> x.y.0
version_parts = __version__.split(".")
version = ".".join(version_parts[:-1] + ["0"])
lang_dir = args.data_dir / args.language
_LOGGER.debug("Creating %s", lang_dir)
lang_dir.mkdir(parents=True, exist_ok=True)
url = args.url_format.format(lang=args.language, version=version)
with tempfile.NamedTemporaryFile(mode="wb+", suffix=".tar.gz") as lang_file:
_LOGGER.debug("Downloading %s to %s", url, lang_file.name)
download_file(url, lang_file.name, f"{args.language}.tar.gz")
_LOGGER.debug("Extracting %s to %s", lang_file.name, lang_dir)
shutil.unpack_archive(lang_file.name, lang_dir)
_LOGGER.info("Successfully downloaded %s to %s", args.language, lang_dir)
# -----------------------------------------------------------------------------
def do_tokenize(config, args):
"""
Split lines from stdin into sentences, tokenize and clean.
Prints a line of JSON for each sentence.
"""
gruut_lang = try_load_language(args, custom_tokenizers=(not args.no_pos))
tokenizer = gruut_lang.tokenizer
if args.text:
# Use arguments
texts = args.text
else:
# Use stdin
texts = sys.stdin
if os.isatty(sys.stdin.fileno()):
print("Reading text from stdin...", file=sys.stderr)
writer = jsonlines.Writer(sys.stdout, flush=True)
for line in texts:
line = line.strip()
if not line:
continue
utt_id = ""
if args.csv:
# Input format is id|text
utt_id, line = line.split(args.csv_delimiter, maxsplit=1)
sentences = list(
tokenizer.tokenize(
line,
number_converters=args.number_converters,
replace_currency=(not args.disable_currency),
guess_pos=(not args.no_pos),
)
)
if args.split_sentences:
# One output line per sentence
for sentence_idx, sentence in enumerate(sentences):
sentence_id = str(sentence_idx)
if utt_id:
sentence_id = f"{utt_id}_{sentence_id}"
clean_words = sentence.clean_words
tokens = sentence.tokens
if args.exclude_non_words:
# Exclude punctuations, etc.
clean_words = []
tokens = []
for token in sentence.tokens:
if tokenizer.is_word(token.text):
clean_words.append(token.text)
tokens.append(token)
writer.write(
{
"id": sentence_id,
"raw_text": sentence.raw_text,
"raw_words": sentence.raw_words,
"clean_words": clean_words,
"clean_text": tokenizer.token_join.join(clean_words),
"sentences": [],
}
)
else:
# One output line per input line
raw_words = []
clean_words = []
tokens = []
for sentence in sentences:
raw_words.extend(sentence.raw_words)
clean_words.extend(sentence.clean_words)
tokens.extend(sentence.tokens)
if args.exclude_non_words:
# Exclude punctuations, etc.
all_tokens = tokens
clean_words = []
tokens = []
for token in all_tokens:
if tokenizer.is_word(token.text):
clean_words.append(token.text)
tokens.append(token)
writer.write(
{
"id": utt_id,
"raw_text": line,
"raw_words": raw_words,
"clean_words": clean_words,
"tokens": [dataclasses.asdict(t) for t in tokens],
"clean_text": tokenizer.token_join.join(clean_words),
"sentences": [dataclasses.asdict(s) for s in sentences],
}
)
# -----------------------------------------------------------------------------
def do_phonemize(config, args):
"""
Reads JSONL from stdin with "clean_words" property.
Looks up or guesses phonetic pronuncation(s) for all clean words.
Prints a line of JSON for each input line.
"""
from .phonemize import UnknownWordsError
gruut_lang = try_load_language(
args, custom_tokenizers=False, preload_lexicon=args.read_all
)
tokenizer = gruut_lang.tokenizer
phonemizer = gruut_lang.phonemizer
process_pronunciation = None
# Load phoneme maps
phoneme_maps: typing.Dict[str, typing.Dict[str, str]] = {}
if args.map:
for map_name in args.map:
map_path = args.lang_dir / "maps" / (map_name + ".txt")
_LOGGER.debug("Loading phoneme map %s (%s)", map_name, map_path)
current_map = {}
with open(map_path, "r") as map_file:
for line in map_file:
line = line.strip()
# Skip blank lines and comments
if not line or line.startswith("#"):
continue
gruut_phoneme, _, mapped_phoneme = line.split(maxsplit=2)
current_map[gruut_phoneme] = mapped_phoneme
# Automatically add mappings for breaks
current_map[gruut_ipa.IPA.BREAK_MINOR] = gruut_ipa.IPA.BREAK_MINOR
current_map[gruut_ipa.IPA.BREAK_MAJOR] = gruut_ipa.IPA.BREAK_MAJOR
phoneme_maps[map_name] = current_map
# Handle language-specific cases
if args.language == "fa":
# Genitive case
def fa_process_pronunciation(word_pron, token):
if token.pos == "Ne":
word_pron = list(word_pron)
word_pron.append("e̞")
return word_pron
process_pronunciation = fa_process_pronunciation
def process_sentence(sentence_obj):
token_dicts = sentence_obj.get("tokens")
if token_dicts:
tokens = [Token(**t) for t in token_dicts]
else:
clean_words = sentence_obj["clean_words"]
tokens = [Token(text=w) for w in clean_words]
fail_on_unknown_words = args.fail_on_unknown_words or args.skip_on_unknown_words
try:
sentence_prons = phonemizer.phonemize(
tokens,
word_indexes=args.word_indexes,
word_breaks=args.word_breaks,
process_pronunciation=process_pronunciation,
use_pos=(not args.no_pos),
fail_on_unknown_words=fail_on_unknown_words,
)
sentence_obj["pronunciations"] = [
wp.phonemes for word_prons in sentence_prons for wp in word_prons
]
# Pick first pronunciation for each word
first_pron = []
for word_prons in sentence_prons:
if word_prons:
first_pron.append(word_prons[0].phonemes)
# Post-process first pronunciation
# first_pron = gruut_lang.phonemizer.post_process_sentence(
# args.language, tokens, first_pron, word_breaks=args.word_breaks
# )
sentence_obj["pronunciation"] = first_pron
# Create string of first pronunciation
sentence_obj["pronunciation_text"] = args.word_separator.join(
args.phoneme_separator.join(word_pron) for word_pron in first_pron
)
# Get Sampa pronunciation
if args.other_phonemes:
sentence_obj["sampa"] = [
[gruut_ipa.ipa_to_sampa(phoneme) for phoneme in word_pron]
for word_pron in first_pron
]
sentence_obj["sampa_text"] = " ".join(
"".join(word_pron) for word_pron in sentence_obj["sampa"]
).strip()
# Get eSpeak pronunciation
sentence_obj["espeak"] = [
[gruut_ipa.ipa_to_espeak(phoneme) for phoneme in word_pron]
for word_pron in first_pron
]
sentence_obj["espeak_text"] = (
"[["
+ " ".join(
"".join(word_pron) for word_pron in sentence_obj["espeak"]
).strip()
+ "]]"
)
# Map phonemes
sentence_obj["mapped_phonemes"] = {}
for map_name, phoneme_map in phoneme_maps.items():
mapped_phonemes = []
for word_pron in first_pron:
mapped_word_phonemes = []
for phoneme in word_pron:
# Exclude stress for now
phoneme = gruut_ipa.IPA.without_stress(phoneme)
mapped_phoneme = phoneme_map.get(phoneme)
if mapped_phoneme:
mapped_word_phonemes.append(mapped_phoneme)
mapped_phonemes.append(mapped_word_phonemes)
sentence_obj["mapped_phonemes"][map_name] = mapped_phonemes
# Print back out with extra info
writer.write(sentence_obj)
except UnknownWordsError as e:
if args.skip_on_unknown_words:
_LOGGER.warning(
"Skipping utterance %s due to unknown words: %s",
sentence_obj.get("id", ""),
sentence_obj.get("raw_text", ""),
)
else:
# Fail instead of skipping
raise e
# -------------------------------------------------------------------------
if os.isatty(sys.stdin.fileno()):
print("Reading tokenize JSONL from stdin...", file=sys.stderr)
sentence_objs = []
missing_words = set()
writer = jsonlines.Writer(sys.stdout, flush=True)
for line in sys.stdin:
line = line.strip()
if not line:
continue
sentence_obj = json.loads(line)
if args.read_all:
# Store and check for missing words
sentence_objs.append(sentence_obj)
for word in sentence_obj["clean_words"]:
if (word not in phonemizer.lexicon) and tokenizer.is_word(word):
missing_words.add(word)
else:
# Process immediate
process_sentence(sentence_obj)
if sentence_objs:
# Guess missing words together (faster)
if missing_words:
_LOGGER.debug("Guessing pronunciations for %s word(s)", len(missing_words))
for word, word_pron in phonemizer.predict(missing_words, nbest=1):
phonemizer.lexicon[word] = [WordPronunciation(word_pron)]
# Process delayed sentences
for sentence_obj in sentence_objs:
process_sentence(sentence_obj)
# -----------------------------------------------------------------------------
def do_phones_to_phonemes(config, args):
"""Transform/group phones in a pronuncation into language phonemes"""
phonemes_path = Path(pydash.get(config, "language.phonemes"))
with open(phonemes_path, "r") as phonemes_file:
phonemes = gruut_ipa.Phonemes.from_text(phonemes_file)
keep_stress = pydash.get(config, "language.keep_stress", False)
if args.phones:
phones = args.phones
else:
# Read from stdin
phones = sys.stdin
if os.isatty(sys.stdin.fileno()):
print("Reading pronunciations from stdin...", file=sys.stderr)
writer = jsonlines.Writer(sys.stdout, flush=True)
for line in phones:
line = line.strip()
if line:
line_phonemes = phonemes.split(line, keep_stress=keep_stress)
phonemes_list = [p.text for p in line_phonemes]
writer.write(
{
"language": args.language,
"raw_text": line,
"phonemes_text": " ".join(phonemes_list),
"phonemes_list": phonemes_list,
"phonemes": [p.to_dict() for p in line_phonemes],
}
)
# -----------------------------------------------------------------------------
def do_coverage(config, args):
"""Get phoneme coverage"""
gruut_lang = try_load_language(args, preload_lexicon=True)
# List of possible phonemes in the language
phonemes = [p.text for p in gruut_lang.phonemes]
_LOGGER.debug("Getting phoneme pairs from lexicon")
# Get set of phoneme pairs from the lexicon.
# This is done instead of using all possible phoneme pairs, because there
# are many pairs that either humans cannot produce or are not used.
# We assume the lexicon will contain an example of each useful pairs.
all_pairs = set()
for word_prons in gruut_lang.phonemizer.lexicon.values():
for word_pron in word_prons:
for p1, p2 in pairwise(word_pron.phonemes):
p1 = gruut_ipa.IPA.without_stress(p1)
p2 = gruut_ipa.IPA.without_stress(p2)
all_pairs.update((p1, p2))
single_counts = Counter()
pair_counts = Counter()
# Process output from phonemize command
if os.isatty(sys.stdin.fileno()):
print("Reading phonemize JSONL from stdin...", file=sys.stderr)
for line in sys.stdin:
line = line.strip()
if not line:
continue
# JSON object with "pronunciation" property
phonemize_obj = json.loads(line)
sentence_prons = []
for word_pron in phonemize_obj.get("pronunciation", []):
word_pron = [p for p in word_pron if not gruut_ipa.IPA.is_break(p)]
sentence_prons.extend(word_pron)
| |
# Unit testing for the Event socket
import logging
import io
import random
import socket
import os
import errno
import time
from collections import deque
from chai import Chai
import eventsocket
from eventsocket import EventSocket
class EventSocketTest(Chai):
def setUp(self):
super(EventSocketTest,self).setUp()
# mock all event callbacks
mock( eventsocket, 'event' )
def test_init_without_args(self):
sock = EventSocket()
assert_false( sock._debug )
assert_equal( None, sock._logger )
assert_equal( None, sock._read_event )
assert_equal( None, sock._write_event )
assert_equal( None, sock._accept_event )
assert_equal( None, sock._connect_event )
assert_equal( None, sock._pending_read_cb_event )
assert_equal( 'unknown', sock._peername )
assert_true( isinstance(sock._sock, socket.socket) )
assert_equal( sock.listen, sock._sock.listen )
assert_equal( sock.setsockopt, sock._sock.setsockopt )
assert_equal( sock.fileno, sock._sock.fileno )
assert_equal( sock.getpeername, sock._sock.getpeername )
assert_equal( sock.getsockname, sock._sock.getsockname )
assert_equal( sock.getsockopt, sock._sock.getsockopt )
assert_equal( sock.setblocking, sock._sock.setblocking )
assert_equal( sock.settimeout, sock._sock.settimeout )
assert_equal( sock.gettimeout, sock._sock.gettimeout )
assert_equal( sock.shutdown, sock._sock.shutdown )
assert_equal( 0, sock._max_read_buffer )
assert_equal( deque(), sock._write_buf )
assert_equal( bytearray(), sock._read_buf )
assert_equal( None, sock._parent_accept_cb )
assert_equal( None, sock._parent_read_cb )
assert_equal( None, sock._parent_error_cb )
assert_equal( None, sock._parent_close_cb )
assert_equal( None, sock._parent_output_empty_cb )
assert_equal( None, sock._error_msg )
assert_false( sock._closed )
assert_equal( None, sock._inactive_event )
# TODO: mock instead that we're calling setinactivetimeout() ?
assert_equal( 0, sock._inactive_timeout )
# TODO: test with all possible args
def test_closed_property(self):
sock = EventSocket()
sock._closed = 'yes'
assert_equals( 'yes', sock.closed )
# TODO: test close which needs mocks
# don't test accept because it's a no-op
def test_set_read_cb_when_no_reason_to_schedule_flush(self):
sock = EventSocket()
sock._set_read_cb( 'readit' )
assert_equals( 'readit', sock._parent_read_cb )
def test_set_read_cb_when_should_flush(self):
sock = EventSocket()
sock._read_buf = bytearray('somedata')
sock._parent_read_cb = None
sock._pending_read_cb_event = None
expect(eventsocket.event.timeout).args(0, sock._protected_cb, sock._parent_read_timer_cb).returns('timeout_event')
sock._set_read_cb( 'parent_read_cb' )
assert_equals( 'parent_read_cb', sock._parent_read_cb )
assert_equals( 'timeout_event', sock._pending_read_cb_event )
def test_set_read_cb_when_data_to_flush_but_pending_read_event(self):
sock = EventSocket()
sock._read_buf = bytearray('somedata')
sock._parent_read_cb = None
sock._pending_read_cb_event = 'pending_event'
sock._set_read_cb( 'parent_read_cb' )
assert_equals( 'parent_read_cb', sock._parent_read_cb )
assert_equals( 'pending_event', sock._pending_read_cb_event )
def test_read_cb_property(self):
sock = EventSocket()
assert_equals( None, sock._parent_read_cb )
sock.read_cb = 'read_cb'
assert_equals( 'read_cb', sock._parent_read_cb )
def test_accept_cb_property(self):
sock = EventSocket()
assert_equals( None, sock._parent_accept_cb )
sock.accept_cb = 'accept_cb'
assert_equals( 'accept_cb', sock._parent_accept_cb )
def test_close_cb_property(self):
sock = EventSocket()
assert_equals( None, sock._parent_close_cb )
sock.close_cb = 'close_cb'
assert_equals( 'close_cb', sock._parent_close_cb )
def test_error_cb_property(self):
sock = EventSocket()
assert_equals( None, sock._parent_error_cb )
sock.error_cb = 'error_cb'
assert_equals( 'error_cb', sock._parent_error_cb )
def test_output_empty_cb_property(self):
sock = EventSocket()
assert_equals( None, sock._parent_output_empty_cb )
sock.output_empty_cb = 'output_empty_cb'
assert_equals( 'output_empty_cb', sock._parent_output_empty_cb )
def test_bind_without_debugging(self):
sock = EventSocket()
sock._sock = mock()
mock(sock, 'getsockname')
expect(sock._sock.bind).args( 'arg1', 'arg2' )
expect(sock.getsockname).returns( ('foo',1234) )
expect(eventsocket.event.read).args( sock, sock._protected_cb, sock._accept_cb )
sock.bind( 'arg1', 'arg2' )
def test_bind_with_debugging(self):
sock = EventSocket()
sock._sock = mock()
sock._debug = True
sock._logger = mock()
mock( sock, 'getsockname' )
expect(sock._logger.debug).args( "binding to %s", str(('arg1','arg2')) )
expect(sock._sock.bind).args( 'arg1', 'arg2' )
expect(sock.getsockname).returns( ('foo',1234) )
expect(eventsocket.event.read).args( sock, sock._protected_cb, sock._accept_cb ).returns('accept_event')
sock.bind( 'arg1', 'arg2' )
assert_equals( "foo:1234", sock._peername )
assert_equals( 'accept_event', sock._accept_event )
# TODO: test connect after merging connect() and connect_blocking()
def test_connect_sets_timeoutat_from_kwargs(self):
now = time.time()
sock = EventSocket()
expect( time, 'time' ).returns( now )
expect( sock._connect_cb ).args( now+5.3, ('localhost',5309), immediate_raise=True )
sock.connect( ('localhost',5309), timeout=5.3 )
expect( sock._connect_cb ).args( now+5.7, ('localhost',5309), immediate_raise=True )
sock.connect( ('localhost',5309), timeout_at=now+5.7 )
def test_connect_sets_default_timeout_from_socket(self):
now = time.time()
sock = EventSocket()
expect( time, 'time' ).returns( now )
sock._sock.settimeout( 8.67 )
expect( sock._connect_cb ).args( now+8.67, ('localhost',5309), immediate_raise=True )
sock.connect( ('localhost',5309) )
def test_connect_cb_when_no_err(self):
sock = EventSocket()
mock( sock, '_sock' )
expect( sock._sock.connect_ex ).args( ('.com', 1234) )
expect( sock._sock.getpeername ).returns( ('.com', 1234) )
expect( eventsocket.event.read ).args( sock._sock, sock._protected_cb, sock._read_cb ).returns( 'readev' )
expect( eventsocket.event.write ).args( sock._sock, sock._protected_cb, sock._write_cb ).returns( 'writeev' )
sock._connect_cb( 3.14, ('.com',1234) )
assert_equals( '.com:1234', sock._peername )
assert_equals( 'readev', sock._read_event )
assert_equals( 'writeev', sock._write_event )
assert_equals( None, sock._connect_event )
def test_connect_cb_when_no_err_and_pending_connect_event(self):
sock = EventSocket()
mock( sock, '_sock' )
mock( sock, '_connect_event' )
expect( sock._sock.connect_ex ).args( ('.com', 1234) )
expect( sock._sock.getpeername ).returns( ('.com', 1234) )
expect( eventsocket.event.read ).any_args()
expect( eventsocket.event.write ).any_args()
expect( sock._connect_event.delete )
sock._connect_cb( 3.14, ('.com',1234) )
assert_equals( None, sock._connect_event )
def test_connect_cb_when_einprogress_and_notimeout_and_no_pending_connect(self):
sock = EventSocket()
mock( sock, '_sock' )
timeout_at = time.time()+3
expect( sock._sock.connect_ex ).args( ('.com', 1234) ).returns( errno.EINPROGRESS )
expect( eventsocket.event.timeout ).args( 0.1, sock._connect_cb, timeout_at, ('.com', 1234) ).returns( 'connectev' )
sock._connect_cb( timeout_at, ('.com',1234) )
assert_equals( 'connectev', sock._connect_event )
def test_connect_cb_when_einprogress_and_notimeout_and_pending_connect(self):
sock = EventSocket()
mock( sock, '_sock' )
mock( sock, '_connect_event' )
timeout_at = time.time()+3
expect( sock._sock.connect_ex ).args( ('.com', 1234) ).returns( errno.EINPROGRESS )
expect( sock._connect_event.delete )
expect( eventsocket.event.timeout ).args( 0.1, sock._connect_cb, timeout_at, ('.com', 1234) ).returns( 'connectev' )
sock._connect_cb( timeout_at, ('.com',1234) )
assert_equals( 'connectev', sock._connect_event )
def test_connect_cb_when_ealready_and_timeout(self):
sock = EventSocket()
mock( sock, '_sock' )
mock( sock, '_connect_event' ) # assert delete() not called
timeout_at = time.time()-3
expect( sock._sock.connect_ex ).args( ('.com', 1234) ).returns( errno.EALREADY )
expect( sock.close )
sock._connect_cb( timeout_at, ('.com',1234) )
def test_connect_cb_when_fail_and_immediateraise(self):
sock = EventSocket()
mock( sock, '_sock' )
mock( sock, '_connect_event' )
expect( sock._sock.connect_ex ).args( ('.com', 1234) ).returns( errno.ECONNREFUSED )
expect( sock._connect_event.delete )
assert_raises( socket.error, sock._connect_cb, time.time(), ('.com',1234), immediate_raise=True )
def test_connect_cb_when_fail_and_not_immediateraise(self):
sock = EventSocket()
mock( sock, '_sock' )
mock( sock, '_connect_event' )
expect( sock._sock.connect_ex ).args( ('.com', 1234) ).returns( errno.ECONNREFUSED )
expect( sock._connect_event.delete )
expect( sock._handle_error ).args( socket.error )
sock._connect_cb( time.time(), ('.com',1234) )
def test_set_inactive_timeout_when_turning_off(self):
sock = EventSocket()
sock._inactive_event = mock()
expect( sock._inactive_event.delete )
sock.set_inactive_timeout(0)
assert_equals( None, sock._inactive_event )
assert_equals( 0, sock._inactive_timeout )
def test_set_inactive_timeout_when_turning_off(self):
sock = EventSocket()
sock._inactive_event = mock()
expect( sock._inactive_event.delete )
expect( eventsocket.event.timeout ).args( 32, sock._inactive_cb ).returns( 'new_timeout' )
sock.set_inactive_timeout(32)
assert_equals( 'new_timeout', sock._inactive_event )
assert_equals( 32, sock._inactive_timeout )
def test_set_inactive_timeout_on_stupid_input(self):
sock = EventSocket()
assert_raises( TypeError, sock.set_inactive_timeout, 'blah' )
def test_handle_error_with_handler_and_err_msg(self):
sock = EventSocket()
sock._parent_error_cb = mock()
sock._error_msg = 'isanerror'
expect(sock._parent_error_cb).args( sock, 'isanerror', 'exception' )
sock._handle_error( 'exception' )
def test_handle_error_with_handler_and_no_err_msg(self):
sock = EventSocket()
sock._parent_error_cb = mock()
expect(sock._parent_error_cb).args( sock, 'unknown error', 'exception' )
sock._handle_error( 'exception' )
def test_handle_error_no_handler_and_logger_and_err_msg(self):
sock = EventSocket()
sock._logger = mock()
sock._error_msg = 'isanerror'
expect(sock._logger.error).args( 'unhandled error isanerror', exc_info=True )
sock._handle_error( 'exception' )
def test_handle_error_no_handler_and_logger_and_no_err_msg(self):
sock = EventSocket()
sock._logger = mock()
expect(sock._logger.error).args( 'unhandled unknown error', exc_info=True )
sock._handle_error( 'exception' )
def test_handle_error_no_handler_and_no_logger(self):
sock = EventSocket()
mock( eventsocket, 'traceback' )
expect(eventsocket.traceback.print_exc)
sock._handle_error( 'exception' )
def test_protected_cb_when_no_error(self):
sock = EventSocket()
cb = mock()
expect( cb ).args( 'arg1', 'arg2', arg3='foo' ).returns( 'result' )
assert_equals( 'result',
sock._protected_cb( cb, 'arg1', 'arg2', arg3='foo' ) )
def test_protected_cb_when_an_error(self):
sock = EventSocket()
#mock( sock, '_handle_error' )
cb = mock()
sock._error_msg = 'it broked'
exc = RuntimeError('fale')
expect( cb ).args( 'arg1', 'arg2', arg3='foo' ).raises( exc )
expect( sock._handle_error ).args( exc )
assert_equals( None,
sock._protected_cb( cb, 'arg1', 'arg2', arg3='foo' ) )
assert_equals( None, sock._error_msg )
def test_accept_cb_when_no_logger_and_no_parent_cb(self):
sock = EventSocket()
sock._sock = mock()
sock._parent_read_cb = 'p_read_cb'
sock._parent_error_cb = 'p_error_cb'
sock._parent_close_cb = 'p_close_cb'
sock._debug = False
sock._logger = None
sock._max_read_buffer = 42
expect(sock._sock.accept).returns( ('connection', 'address') )
expect(EventSocket.__init__).args( read_cb='p_read_cb', error_cb='p_error_cb',
close_cb='p_close_cb', sock='connection', debug=False,
logger=None, max_read_buffer=42 )
assert_true( sock._accept_cb() )
assert_equals( 'error accepting new socket', sock._error_msg )
def test_accept_cb_when_logger_and_parent_cb(self):
sock = EventSocket()
sock._sock = mock()
sock._parent_accept_cb = 'p_accept_cb'
sock._parent_read_cb = 'p_read_cb'
sock._parent_error_cb = 'p_error_cb'
sock._parent_close_cb = 'p_close_cb'
sock._debug = True
sock._logger = mock()
sock._max_read_buffer = 42
expect(sock._sock.accept).returns( ('connection', 'address') )
expect(sock._logger.debug).args( "accepted connection from address" )
expect(EventSocket.__init__).args( read_cb='p_read_cb', error_cb='p_error_cb',
close_cb='p_close_cb', sock='connection', debug=True,
logger=sock._logger, max_read_buffer=42 )
expect(sock._protected_cb).args( 'p_accept_cb', is_a(EventSocket) )
assert_true( sock._accept_cb() )
def test_read_cb_simplest_case(self):
sock = EventSocket()
sock._sock = mock()
mock( sock, 'getsockopt' )
expect( sock.getsockopt ).args( socket.SOL_SOCKET, socket.SO_RCVBUF ).returns( 42 )
expect( sock._sock.recv ).args( 42 ).returns( 'sumdata' )
expect( sock._flag_activity )
assert_true( sock._read_cb() )
assert_equals( bytearray('sumdata'), sock._read_buf )
assert_equals( 'error reading from socket', sock._error_msg )
def test_read_cb_when_debugging_and_parent_cb_and_no_pending_event(self):
sock = EventSocket()
sock._sock = mock()
sock._logger = mock()
sock._peername = 'peername'
sock._debug = True
sock._parent_read_cb = 'p_read_cb'
mock( sock, 'getsockopt' )
expect( sock.getsockopt ).args( socket.SOL_SOCKET, socket.SO_RCVBUF ).returns( 42 )
expect( sock._sock.recv ).args( 42 ).returns( 'sumdata' )
expect( sock._logger.debug ).args( 'read 7 bytes from peername' )
expect( sock._flag_activity )
expect( eventsocket.event.timeout ).args( 0, sock._protected_cb, sock._parent_read_timer_cb ).returns('pending_read')
assert_true( sock._read_cb() )
assert_equals( bytearray('sumdata'), sock._read_buf )
assert_equals( 'pending_read', sock._pending_read_cb_event )
def test_read_cb_when_parent_cb_and_is_a_pending_event_and_already_buffered_data(self):
sock = EventSocket()
sock._read_buf = bytearray('foo')
sock._sock = mock()
sock._peername = 'peername'
sock._parent_read_cb = 'p_read_cb'
sock._pending_read_cb_event = 'pending_read'
mock( sock, 'getsockopt' )
expect( sock.getsockopt ).args( socket.SOL_SOCKET, socket.SO_RCVBUF ).returns( 42 )
expect( sock._sock.recv ).args( 42 ).returns( 'sumdata' )
expect( sock._flag_activity )
| |
"""Stockham kernel generator."""
import functools
import sys
from collections import namedtuple
from math import ceil
from pathlib import Path
from types import SimpleNamespace as NS
from generator import *
#
# Stockham FFTs!
#
LaunchParams = namedtuple('LaunchParams', ['transforms_per_block', 'threads_per_block', 'threads_per_transform'])
def kernel_launch_name(length, precision):
"""Return kernel name."""
return f'rocfft_internal_dfn_{precision}_ci_ci_stoc_{length}'
def product(factors):
"""Return the product of the factors."""
if factors:
return functools.reduce(lambda a, b: a * b, factors)
return 1
def get_launch_params(factors, flavour='uwide', bytes_per_element=16, lds_byte_limit=32 * 1024, threads_per_block=256):
"""Return kernel launch parameters.
Computes the maximum number of batches-per-block without:
- going over 'lds_byte_limit' (32KiB by default) per block
- going beyond 'threads_per_block' threads per block.
"""
length = product(factors)
bytes_per_batch = length * bytes_per_element
if flavour == 'uwide':
threads_per_transform = length // min(factors)
elif flavour == 'wide':
threads_per_transform = length // max(factors)
bpb = lds_byte_limit // bytes_per_batch
while threads_per_transform * bpb > threads_per_block:
bpb -= 1
return LaunchParams(bpb, threads_per_transform * bpb, threads_per_transform)
def stockham_uwide_device(factors, **kwargs):
"""Stockham kernel.
Each thread does at-most one butterfly.
"""
length = product(factors)
# arguments
scalar_type = Variable('scalar_type', 'typename')
Z = Variable('buf', 'scalar_type', array=True)
X = Variable('lds', 'scalar_type', array=True)
T = Variable('twiddles', 'const scalar_type', array=True)
stride = Variable('stride', 'size_t')
offset = Variable('offset', 'size_t')
offset_lds = Variable('offset_lds', 'size_t')
# locals
thread = Variable('thread', 'int')
thread_id = Variable('threadIdx.x', 'int')
W = Variable('W', 'scalar_type')
t = Variable('t', 'scalar_type')
R = Variable('R', 'scalar_type', max(factors))
body = StatementList()
body += Declarations(thread, R, W, t)
body += LineBreak()
body += Assign(thread, thread_id % (length // min(factors)))
body += LineBreak()
body += CommentLines('load global')
width = min(factors)
for b in range(width):
idx = thread + b * (length // width)
body += Assign(X[offset_lds + idx], Z[offset + B(idx) * stride])
# body += Assign(X[offset_lds + idx], Z[offset + idx])
#
# transform
#
for npass, width in enumerate(factors):
cumheight = product(factors[:npass])
body += LineBreak()
body += CommentLines(f'pass {npass}')
body += LineBreak()
body += SyncThreads()
body += LineBreak()
body += CommentLines('load lds')
for w in range(width):
idx = offset_lds + thread + length // width * w
body += Assign(R[w], X[idx])
body += LineBreak()
if npass > 0:
body += CommentLines('twiddle')
for w in range(1, width):
tidx = cumheight - 1 + w - 1 + (width - 1) * B(thread % cumheight)
body += Assign(W, T[tidx])
body += Assign(t.x, W.x * R[w].x - W.y * R[w].y)
body += Assign(t.y, W.y * R[w].x + W.x * R[w].y)
body += Assign(R[w], t)
body += LineBreak()
body += CommentLines('butterfly')
body += Call(name=f'FwdRad{width}B1',
arguments=ArgumentList(*[R[w].address() for w in range(width)]))
body += LineBreak()
if npass == len(factors) - 1:
body += CommentLines('store global')
stmts = StatementList()
width = factors[-1]
for w in range(width):
idx = thread + w * (length // width)
# stmts += Assign(Z[offset + idx], R[w])
stmts += Assign(Z[offset + B(idx) * stride], R[w])
body += If(thread < length // width, stmts)
else:
body += CommentLines('store lds')
body += SyncThreads()
stmts = StatementList()
for w in range(width):
idx = offset_lds + B(thread / cumheight) * (width * cumheight) + thread % cumheight + w * cumheight
stmts += Assign(X[idx], R[w])
body += If(thread < length // width, stmts)
body += LineBreak()
body += LineBreak()
return Function(f'forward_length{length}_device',
arguments=ArgumentList(Z, X, T, stride, offset, offset_lds),
templates=TemplateList(scalar_type),
body=body,
qualifier='__device__')
def stockham_wide_device(factors, **kwargs):
"""Stockham kernel.
Each thread does at-least one butterfly.
"""
length = product(factors)
# arguments
scalar_type = Variable('scalar_type', 'typename')
Z = Variable('buf', 'scalar_type', array=True)
X = Variable('lds', 'scalar_type', array=True)
T = Variable('twiddles', 'const scalar_type', array=True)
stride = Variable('stride', 'size_t')
offset = Variable('offset', 'size_t')
offset_lds = Variable('offset_lds', 'size_t')
# locals
thread = Variable('thread', 'int')
thread_id = Variable('threadIdx.x', 'int')
W = Variable('W', 'scalar_type')
t = Variable('t', 'scalar_type')
R = Variable('R', 'scalar_type', 2*max(factors))
height0 = length // max(factors)
def load_global():
stmts = StatementList()
stmts += Assign(thread, thread_id % height0)
stmts += LineBreak()
for b in range(max(factors)):
idx = thread + b * height0
stmts += Assign(X[offset_lds + idx], Z[offset + idx])
return stmts
def load_lds():
stmts = StatementList()
stmts += Assign(thread, thread_id % height0 + nsubpass * height0)
for w in range(width):
idx = offset_lds + thread + length//width * w
stmts += Assign(R[nsubpass*width+w], X[idx])
return stmts
def twiddle():
stmts = StatementList()
stmts += Assign(thread, thread_id % height0 + nsubpass * height0)
for w in range(1, width):
tidx = cumheight - 1 + w - 1 + (width - 1) * B(thread % cumheight)
ridx = nsubpass*width + w
stmts += Assign(W, T[tidx])
stmts += Assign(t.x, W.x * R[ridx].x - W.y * R[ridx].y)
stmts += Assign(t.y, W.y * R[ridx].x + W.x * R[ridx].y)
stmts += Assign(R[ridx], t)
return stmts
def butterfly():
stmts = StatementList()
stmts += Call(name=f'FwdRad{width}B1',
arguments=ArgumentList(*[R[nsubpass*width+w].address() for w in range(width)]))
return stmts
def store_lds():
stmts = StatementList()
stmts += Assign(thread, thread_id % height0 + nsubpass * height0)
stmts += LineBreak()
for w in range(width):
idx = offset_lds + B(thread / cumheight) * (width * cumheight) + thread % cumheight + w * cumheight
stmts += Assign(X[idx], R[nsubpass*width+w])
stmts += LineBreak()
return stmts
def store_global():
stmts = StatementList()
stmts += SyncThreads()
stmts += Assign(thread, thread_id % height0)
for b in range(max(factors)):
idx = thread + b * height0
stmts += Assign(Z[offset + idx], X[offset_lds + idx])
return stmts
def add_work(codelet):
if nsubpasses == 1 or nsubpass < nsubpasses - 1:
return codelet()
needs_work = thread_id % height0 + nsubpass * height0 < length // width
return If(needs_work, codelet())
body = StatementList()
body += Declarations(thread, R, W, t)
body += LineBreak()
body += CommentLines('load global')
body += load_global()
body += LineBreak()
body += SyncThreads()
body += LineBreak()
#
# transform
#
for npass, width in enumerate(factors):
cumheight = product(factors[:npass])
nsubpasses = ceil(max(factors) / factors[npass])
body += CommentLines(f'pass {npass}')
if npass > 0:
body += SyncThreads()
body += LineBreak()
body += CommentLines('load lds')
for nsubpass in range(nsubpasses):
body += add_work(load_lds)
body += LineBreak()
if npass > 0:
body += CommentLines('twiddle')
for nsubpass in range(nsubpasses):
body += add_work(twiddle)
body += LineBreak()
body += CommentLines('butterfly')
for nsubpass in range(nsubpasses):
body += add_work(butterfly)
body += LineBreak()
body += CommentLines('store lds')
for nsubpass in range(nsubpasses):
body += add_work(store_lds)
body += LineBreak()
body += CommentLines('store global')
body += store_global()
return Function(f'forward_length{length}_device',
arguments=ArgumentList(Z, X, T, stride, offset, offset_lds),
templates=TemplateList(scalar_type),
body=body,
qualifier='__device__')
def stockham_global(factors, **kwargs):
"""Global Stockham function."""
length = product(factors)
params = get_launch_params(factors, **kwargs)
# arguments
scalar_type = Variable('scalar_type', 'typename')
sb = Variable('sb', 'StrideBin')
buf = Variable('buf', 'scalar_type', array=True)
twiddles = Variable('twiddles', 'const scalar_type', array=True)
dim = Variable('dim', 'size_t')
lengths = Variable('lengths', 'size_t', array=True)
stride = Variable('stride', 'size_t', array=True)
nbatch = Variable('nbatch', 'size_t')
# locals
lds = Variable('lds', '__shared__ scalar_type', size=length * params.transforms_per_block)
block_id = Variable('blockIdx.x')
thread_id = Variable('threadIdx.x')
offset = Variable('offset', 'size_t')
offset_lds = Variable('offset_lds', 'size_t')
batch = Variable('batch', 'size_t')
transform = Variable('transform', 'size_t')
remaining = Variable('remaining', 'size_t')
plength = Variable('plength', 'size_t')
d = Variable('d', 'size_t')
i_d = Variable('i_d', 'size_t')
body = StatementList()
body += CommentLines(
f'this kernel:',
f' uses {params.threads_per_transform} threads per transform',
f' does {params.transforms_per_block} transforms per thread block',
f'therefore it should be called with {params.threads_per_block} threads per thread block')
body += Declarations(lds, offset, offset_lds, batch, transform, remaining, plength, d, i_d)
body += LineBreak()
body += Assign(transform, block_id * params.transforms_per_block + thread_id / params.threads_per_transform)
body += LineBreak()
body += Assign(offset, 0)
body += Assign(plength, 1)
body += Assign(remaining, transform)
body += For(InlineAssign(d, 1), d < dim, Increment(d),
StatementList(
Assign(plength, plength * lengths[d]),
Assign(i_d, remaining % lengths[d]),
Assign(remaining, remaining / lengths[d]),
Assign(offset, offset + i_d * stride[d])))
body += LineBreak()
body += Assign(batch, transform / plength)
body += Assign(offset, offset + batch * stride[dim])
body += If(GreaterEqual(batch, nbatch), [ReturnStatement()])
body += LineBreak()
body += Assign(offset_lds, length * B(transform % params.transforms_per_block))
body += Call(f'forward_length{length}_device',
arguments=ArgumentList(buf, lds, twiddles, stride[0], offset, offset_lds),
templates=TemplateList(scalar_type))
return Function(name=f'forward_length{length}',
qualifier='__global__',
templates=TemplateList(scalar_type, sb),
arguments=ArgumentList(twiddles, dim, lengths, stride, nbatch, buf),
meta=NS(factors=factors,
length=product(factors),
transforms_per_block=params.transforms_per_block,
threads_per_block=params.threads_per_block,
scheme='CS_KERNEL_STOCKHAM',
pool=None),
body=body)
# XXX: move this to generator
def make_variants(kdevice, kglobal):
"""Given in-place complex-interleaved kernels, create all other variations.
The ASTs in 'kglobal' and 'kdevice' are assumed to be in-place,
complex-interleaved kernels.
Return out-of-place | |
<gh_stars>0
import asyncio
import os
import unicodedata
import aiohttp
import discord
import lavalink
import unidecode
from redbot.core import Config, checks, commands
from redbot.core.utils.chat_formatting import pagify
from redbot.core.utils.predicates import MessagePredicate
from .api import generate_urls
try:
from redbot.core.utils._dpy_menus_utils import dpymenu
DPY_MENUS = True
except ImportError:
from redbot.core.utils.menus import DEFAULT_CONTROLS, menu
DPY_MENUS = False
from .voices import voices
class SFX(commands.Cog):
"""Plays uploaded sounds or text-to-speech."""
__version__ = "2.0.0"
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, identifier=134621854878007296)
self.session = aiohttp.ClientSession()
user_config = {"voice": "Clara", "speed": 5}
guild_config = {"sounds": {}, "channels": []}
global_config = {"sounds": {}, "schema_version": 0}
self.config.register_user(**user_config)
self.config.register_guild(**guild_config)
self.config.register_global(**global_config)
lavalink.register_event_listener(self.ll_check)
self.bot.loop.create_task(self.check_config_version())
self.bot.loop.create_task(self.fill_channel_cache())
self.last_track_info = {}
self.current_sfx = {}
self.channel_cache = {}
# lag_time to compensate for skipping lavalink lag
self.lag_time = 1000
self.repeat_state = {}
def cog_unload(self):
self.bot.loop.create_task(self.session.close())
lavalink.unregister_event_listener(self.ll_check)
def format_help_for_context(self, ctx):
"""Thanks Sinbad"""
pre_processed = super().format_help_for_context(ctx)
return f"{pre_processed}\nCog Version: {self.__version__}"
async def check_config_version(self):
schema_version = await self.config.schema_version()
if schema_version == 0:
await self.config.clear_all_users()
await self.config.sounds.clear()
all_guilds = await self.config.all_guilds()
for guild in all_guilds:
await self.config.guild_from_id(guild).sounds.clear()
await self.config.schema_version.set(1)
async def fill_channel_cache(self):
all_guilds = await self.config.all_guilds()
for guild in all_guilds:
try:
self.channel_cache[guild] = all_guilds[guild]["channels"]
except KeyError:
pass # no channels set
# full credits to kable
# https://github.com/kablekompany/Kable-Kogs/blob/master/decancer/decancer.py#L67
@staticmethod
def decancer_text(text):
text = unicodedata.normalize("NFKC", text)
text = unicodedata.normalize("NFD", text)
text = unidecode.unidecode(text)
text = text.encode("ascii", "ignore")
text = text.decode("utf-8")
if text == "":
return
return text
@commands.command()
@commands.cooldown(
rate=1, per=1, type=discord.ext.commands.cooldowns.BucketType.guild
)
@commands.guild_only()
async def tts(self, ctx, *, text):
"""
Plays the given text as TTS in your current voice channel.
"""
if not ctx.author.voice or not ctx.author.voice.channel:
await ctx.send("You are not connected to a voice channel.")
return
author_data = await self.config.user(ctx.author).all()
author_voice = author_data["voice"]
author_speed = author_data["speed"]
text = self.decancer_text(text)
if text is None:
await ctx.send("That's not a valid message, sorry.")
return
char_number = len(text)
if char_number > 1000:
await ctx.send(
f"Sorry, I limit TTS to 1000 characters to avoid abuse. ({char_number}/1000)"
)
return
urls = generate_urls(author_voice, text, author_speed)
await self.play_sfx(ctx.author.voice.channel, ctx.channel, urls)
try:
1 + 1
except Exception:
await ctx.send(
"Oops, an error occured. If this continues please use the contact command to inform the bot owner."
)
@commands.command()
@commands.cooldown(
rate=1, per=1, type=discord.ext.commands.cooldowns.BucketType.guild
)
@commands.guild_only()
async def sfx(self, ctx, sound: str):
"""
Plays an existing sound in your current voice channel.
If a guild SFX exists with the same name as a global one, the guild SFX will be played.
"""
if not ctx.author.voice or not ctx.author.voice.channel:
await ctx.send("You are not connected to a voice channel.")
return
guild_sounds = await self.config.guild(ctx.guild).sounds()
global_sounds = await self.config.sounds()
if sound not in guild_sounds.keys() and sound not in global_sounds.keys():
await ctx.send(
f"Sound **{sound}** does not exist. Try `{ctx.clean_prefix}listsfx` for a list."
)
return
if sound in guild_sounds.keys():
link = guild_sounds[sound]
else:
link = global_sounds[sound]
try:
await self.play_sfx(ctx.author.voice.channel, ctx.channel, [link])
except Exception:
await ctx.send(
"Oops, an error occured. If this continues please use the contact command to inform the bot owner."
)
@commands.command()
@commands.cooldown(
rate=1, per=1, type=discord.ext.commands.cooldowns.BucketType.guild
)
@commands.guild_only()
async def qsfx(self, ctx, sound: str):
"""
Queues an existing sound in your current voice channel.
If a guild SFX exists with the same name as a global one, the guild SFX will be played.
"""
if not ctx.author.voice or not ctx.author.voice.channel:
await ctx.send("You are not connected to a voice channel.")
return
guild_sounds = await self.config.guild(ctx.guild).sounds()
global_sounds = await self.config.sounds()
if sound not in guild_sounds.keys() and sound not in global_sounds.keys():
await ctx.send(
f"Sound **{sound}** does not exist. Try `{ctx.clean_prefix}listsfx` for a list."
)
return
if sound in guild_sounds.keys():
link = guild_sounds[sound]
else:
link = global_sounds[sound]
try:
await self.queue_sfx(ctx.author.voice.channel, ctx.channel, [link])
except Exception:
await ctx.send(
"Oops, an error occured. If this continues please use the contact command to inform the bot owner."
)
@commands.command()
@commands.admin_or_permissions(manage_guild=True)
@commands.guild_only()
async def addsfx(self, ctx, name: str, link: str = None):
"""
Adds a new SFX to this guild.
Either upload the file as a Discord attachment or use a link.
Syntax:`[p]addsfx <name>` or `[p]addsfx <name> <link>`.
"""
guild_sounds = await self.config.guild(ctx.guild).sounds()
attachments = ctx.message.attachments
if len(attachments) > 1 or (attachments and link):
await ctx.send("Please only try to add one SFX at a time.")
return
url = ""
filename = ""
if attachments:
attachment = attachments[0]
url = attachment.url
elif link:
url = "".join(link)
else:
await ctx.send(
"You must provide either a Discord attachment or a direct link to a sound."
)
return
filename = "".join(url.split("/")[-1:]).replace("%20", "_")
file_name, file_extension = os.path.splitext(filename)
if file_extension not in [".wav", ".mp3"]:
await ctx.send(
"Sorry, only SFX in .mp3 and .wav format are supported at this time."
)
return
if name in guild_sounds.keys():
await ctx.send(
f"A sound with that filename already exists. Either choose a new name or use {ctx.clean_prefix}delsfx to remove it."
)
return
guild_sounds[name] = url
await self.config.guild(ctx.guild).sounds.set(guild_sounds)
await ctx.send(f"Sound **{name}** has been added.")
@commands.command()
@commands.admin_or_permissions(manage_guild=True)
@commands.guild_only()
async def delsfx(self, ctx, soundname: str):
"""
Deletes an existing sound.
"""
guild_sounds = await self.config.guild(ctx.guild).sounds()
if soundname not in guild_sounds.keys():
await ctx.send(
f"Sound **{soundname}** does not exist. Try `{ctx.prefix}listsfx` for a list."
)
return
del guild_sounds[soundname]
await self.config.guild(ctx.guild).sounds.set(guild_sounds)
await ctx.send(f"Sound **{soundname}** deleted.")
@commands.command()
@commands.guild_only()
async def addglobalsfx(self, ctx, name: str, link: str = None):
"""
Adds a new SFX to this the bot globally.
Either upload the file as a Discord attachment or use a link.
Syntax:`[p]addsfx <name>` or `[p]addsfx <name> <link>`.
"""
global_sounds = await self.config.sounds()
attachments = ctx.message.attachments
if len(attachments) > 1 or (attachments and link):
await ctx.send("Please only try to add one SFX at a time.")
return
url = ""
if attachments:
attachment = attachments[0]
url = attachment.url
elif link:
url = "".join(link)
else:
await ctx.send(
"You must provide either a Discord attachment or a direct link to a sound."
)
return
filename = "".join(url.split("/")[-1:]).replace("%20", "_")
file_name, file_extension = os.path.splitext(filename)
if file_extension not in [".wav", ".mp3"]:
await ctx.send(
"Sorry, only SFX in .mp3 and .wav format are supported at this time."
)
return
if name in global_sounds.keys():
await ctx.send(
f"A sound with that filename already exists. Either choose a new name or use {ctx.clean_prefix}delglobalsfx to remove it."
)
return
global_sounds[name] = link
await self.config.sounds.set(global_sounds)
await ctx.send(f"Sound **{name}** has been added.")
@commands.command()
@checks.is_owner()
async def delglobalsfx(self, ctx, name: str):
"""
Deletes an existing global sound.
"""
global_sounds = await self.config.sounds()
if name not in global_sounds.keys():
await ctx.send(
f"Sound **{name}** does not exist. Try `{ctx.prefix}listsfx` for a list."
)
return
del global_sounds[name]
await self.config.sounds.set(global_sounds)
await ctx.send(f"Sound **{name}** deleted.")
@commands.command()
@commands.guild_only()
async def listsfx(self, ctx):
"""
Lists all available sounds for this server.
"""
guild_sounds = await self.config.guild(ctx.guild).sounds()
global_sounds = await self.config.sounds()
if (len(guild_sounds.items()) + len(global_sounds.items())) == 0:
await ctx.send(f"No sounds found. Use `{ctx.prefix}addsfx` to add one.")
return
txt = ""
if guild_sounds:
txt += "**Guild Sounds**:\n"
for sound in guild_sounds:
txt += sound + "\n"
if global_sounds:
txt += "\n**Global Sounds**:\n"
for sound in global_sounds:
if guild_sounds and sound in guild_sounds:
txt += sound + " (disabled)\n"
txt += sound + "\n"
pages = [p for p in pagify(text=txt, delims="\n")]
for page in pages:
await ctx.send(page)
@commands.command()
@commands.guild_only()
async def fplay(self, ctx, link: str = None):
"""
Adds a file to the music queue.
Either upload the file as a Discord attachment or use a link.
Syntax:`[p]fplay` or `[p]fplay <link>`.
"""
attachments = ctx.message.attachments
if len(attachments) > 1 or (attachments and link):
await ctx.send("Please only try to add one file at a time.")
return
url = ""
filename = ""
if attachments:
attachment = attachments[0]
url = attachment.url
elif link:
url = "".join(link)
else:
await ctx.send(
"You must provide either a Discord attachment or a direct link to a sound."
)
return
filename = "".join(url.split("/")[-1:]).replace("%20", "_")
file_name, file_extension = os.path.splitext(filename)
if file_extension not in [".wav", ".mp3"]:
await ctx.send(
"Sorry, only files in .mp3 and .wav format are supported at this time."
)
return
if not ctx.author.voice or not ctx.author.voice.channel:
await ctx.send("You are not connected to a voice channel.")
return
guild_sounds = await self.config.guild(ctx.guild).sounds()
global_sounds = await self.config.sounds()
try:
await self.queue_sfx(ctx.author.voice.channel, | |
<filename>tests/diag/test_ccsd.py
import wicked as w
def print_comparison(val, val2):
print(f"Result: {val}")
print(f"Test: {val2}")
def compare_expressions(test, ref):
test_expr = w.Expression()
ref_expr = w.Expression()
for s in ref:
ref_expr += w.string_to_expr(s)
for eq in test:
test_expr += eq.rhs_expression()
print_comparison(test_expr, ref_expr)
assert test_expr == ref_expr
def initialize():
w.reset_space()
w.add_space("o", "fermion", "occupied", ["i", "j", "k", "l", "m", "n"])
w.add_space("v", "fermion", "unoccupied", ["a", "b", "c", "d", "e", "f"])
def test_energy1():
"""CCSD Energy <F T1> (1)"""
initialize()
T1 = w.op("t", ["v+ o"])
Fov = w.op("f", ["o+ v"])
wt = w.WickTheorem()
val = wt.contract(w.rational(1), Fov @ T1, 0, 0)
val2 = w.expression("f^{v_0}_{o_0} t^{o_0}_{v_0}")
print_comparison(val, val2)
assert val == val2
def test_energy2():
"""CCSD Energy <V T2> (2)"""
initialize()
T2 = w.op("t", ["v+ v+ o o"])
Voovv = w.op("v", ["o+ o+ v v"])
wt = w.WickTheorem()
val = wt.contract(w.rational(1), Voovv @ T2, 0, 0)
val2 = w.expression("1/4 t^{o_0,o_1}_{v_0,v_1} v^{v_0,v_1}_{o_0,o_1}")
print_comparison(val, val2)
assert val == val2
def test_energy3():
"""CCSD Energy 1/2 <V T1 T1> (3)"""
initialize()
T1 = w.op("t", ["v+ o"])
Voovv = w.op("v", ["o+ o+ v v"])
wt = w.WickTheorem()
val = wt.contract(w.rational(1, 2), Voovv @ T1 @ T1, 0, 0)
val2 = w.expression("1/2 t^{o0}_{v0} t^{o1}_{v1} v^{v0,v1}_{o0,o1}")
print_comparison(val, val2)
assert val == val2
def test_r1_1():
"""CCSD T1 Residual Fov (1)"""
initialize()
Fvo = w.op("f", ["v+ o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), Fvo, 2, 2)
val = sum.to_manybody_equation("r")["o|v"][0].rhs_expression()
val2 = w.expression("f^{o0}_{v0}").canonicalize()
# print(val[0].rhs_term())
print_comparison(val, val2)
assert val == val2
def test_r1_2():
"""CCSD T1 Residual [Fvv,T1] (2)"""
initialize()
T1 = w.op("t", ["v+ o"])
Fvv = w.op("f", ["v+ v"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), Fvv @ T1, 2, 2)
val = sum.to_manybody_equation("r")["o|v"][0].rhs_expression()
val2 = w.expression("f^{v1}_{v0} t^{o0}_{v1}")
print_comparison(val, val2)
assert val == val2
def test_r1_3():
"""CCSD T1 Residual [Foo,T1] (3)"""
initialize()
T1 = w.op("t", ["v+ o"])
Foo = w.op("f", ["o+ o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), Foo @ T1, 2, 2)
val = sum.to_manybody_equation("r")["o|v"][0].rhs_expression()
val2 = w.expression("-1 f^{o0}_{o1} t^{o1}_{v0}")
print_comparison(val, val2)
assert val == val2
def test_r1_4():
"""CCSD T1 Residual [Vovov,T1] (4)"""
initialize()
T1 = w.op("t", ["v+ o"])
Vovov = w.op("v", ["o+ v+ v o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), Vovov @ T1, 2, 2)
val = sum.to_manybody_equation("r")["o|v"][0].rhs_expression()
val2 = w.expression("-1 t^{o1}_{v1} v^{o0,v1}_{o1,v0}")
print_comparison(val, val2)
assert val == val2
def test_r1_5():
"""CCSD T1 Residual [Fvo,T2] (5)"""
initialize()
T2 = w.op("t", ["v+ v+ o o"])
Fov = w.op("f", ["o+ v"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), Fov @ T2, 2, 2)
val = sum.to_manybody_equation("r")["o|v"][0].rhs_expression()
val2 = w.expression("1 f^{v1}_{o1} t^{o0,o1}_{v0,v1}")
print_comparison(val, val2)
assert val == val2
def test_r1_6():
"""CCSD T1 Residual [Vovvv,T2] (6)"""
initialize()
T2 = w.op("t", ["v+ v+ o o"])
Vovvv = w.op("v", ["o+ v+ v v"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), Vovvv @ T2, 2, 2)
val = sum.to_manybody_equation("r")["o|v"][0].rhs_expression()
val2 = w.expression("-1/2 t^{o0,o1}_{v1,v2} v^{v1,v2}_{o1,v0}")
print_comparison(val, val2)
assert val == val2
def test_r1_7():
"""CCSD T1 Residual [Vooov,T2] (7)"""
initialize()
T2 = w.op("t", ["v+ v+ o o"])
Vooov = w.op("v", ["o+ o+ v o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), Vooov @ T2, 2, 2)
val = sum.to_manybody_equation("r")["o|v"][0].rhs_expression()
val2 = w.expression("-1/2 t^{o1,o2}_{v0,v1} v^{o0,v1}_{o1,o2}")
print_comparison(val, val2)
assert val == val2
def test_r1_8():
"""CCSD T1 Residual 1/2 [[Fov,T1],T1] (8)"""
initialize()
T1 = w.op("t", ["v+ o"])
Fov = w.op("f", ["o+ v"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1, 2), w.commutator(w.commutator(Fov, T1), T1), 2, 2)
val = sum.to_manybody_equation("r")["o|v"][0].rhs_expression()
val2 = w.expression("-1 f^{v1}_{o1} t^{o1}_{v0} t^{o0}_{v1}")
print_comparison(val, val2)
assert val == val2
def test_r1_9():
"""CCSD T1 Residual 1/2 [[Vooov,T1],T1] (9)"""
initialize()
T1 = w.op("t", ["v+ o"])
Vooov = w.op("v", ["o+ o+ v o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1, 2), w.commutator(w.commutator(Vooov, T1), T1), 2, 2)
val = sum.to_manybody_equation("r")["o|v"][0].rhs_expression()
val2 = w.expression("-1 t^{o1}_{v0} t^{o2}_{v1} v^{o0,v1}_{o1,o2}")
print_comparison(val, val2)
assert val == val2
def test_r1_10():
"""CCSD T1 Residual 1/2 [[Vovvv,T1],T1] (10)"""
initialize()
T1 = w.op("t", ["v+ o"])
Vovvv = w.op("v", ["o+ v+ v v"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1, 2), w.commutator(w.commutator(Vovvv, T1), T1), 2, 2)
val = sum.to_manybody_equation("r")["o|v"][0].rhs_expression()
val2 = w.expression("-1 t^{o0}_{v1} t^{o1}_{v2} v^{v1,v2}_{o1,v0}")
print_comparison(val, val2)
assert val == val2
def test_r1_11():
"""CCSD T1 Residual 1/6 [[[Voovv,T1],T1],T1] (11)"""
initialize()
T1 = w.op("t", ["v+ o"])
Voovv = w.op("v", ["o+ o+ v v"])
wt = w.WickTheorem()
sum = wt.contract(
w.rational(1, 6),
w.commutator(w.commutator(w.commutator(Voovv, T1), T1), T1),
2,
2,
)
val = sum.to_manybody_equation("r")["o|v"][0].rhs_expression()
val2 = w.expression("-1 t^{o1}_{v0} t^{o0}_{v1} t^{o2}_{v2} v^{v1,v2}_{o1,o2}")
print_comparison(val, val2)
assert val == val2
def test_r1_12_14():
"""CCSD T1 Residual [[Voovv,T1],T2] (12-14)"""
initialize()
T1 = w.op("t", ["v+ o"])
T2 = w.op("t", ["v+ v+ o o"])
Voovv = w.op("v", ["o+ o+ v v"])
wt = w.WickTheorem()
sum = wt.contract(
w.rational(1),
w.commutator(w.commutator(Voovv, T1), T2),
2,
2,
)
val = sum.to_manybody_equation("r")["o|v"][0].rhs_expression()
val += sum.to_manybody_equation("r")["o|v"][1].rhs_expression()
val += sum.to_manybody_equation("r")["o|v"][2].rhs_expression()
val2 = (
w.expression("1 t^{o1}_{v1} t^{o0,o2}_{v0,v2} v^{v1,v2}_{o1,o2}")
+ w.expression("-1/2 t^{o0}_{v1} t^{o1,o2}_{v0,v2} v^{v1,v2}_{o1,o2}")
+ w.expression("-1/2 t^{o1}_{v0} t^{o0,o2}_{v1,v2} v^{v1,v2}_{o1,o2}")
)
print_comparison(val, val2)
assert val == val2
def test_r2_1():
"""CCSD T2 Residual Vvvoo (1)"""
Vvvoo = w.op("v", ["v+ v+ o o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), Vvvoo, 4, 4)
val = sum.to_manybody_equation("r")["oo|vv"][0].rhs_expression()
val2 = w.expression("1/4 v^{o0,o1}_{v0,v1}")
print_comparison(val, val2)
assert val == val2
def test_r2_2():
"""CCSD T2 Residual [Fvv,T2] (2)"""
T2 = w.op("t", ["v+ v+ o o"])
Fvv = w.op("f", ["v+ v"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), w.commutator(Fvv, T2), 4, 4)
val = sum.to_manybody_equation("r")["oo|vv"][0].rhs_expression()
val2 = w.expression("-1/2 f^{v2}_{v0} t^{o0,o1}_{v1,v2}")
print_comparison(val, val2)
assert val == val2
def test_r2_3():
"""CCSD T2 Residual [Foo,T2] (3)"""
T2 = w.op("t", ["v+ v+ o o"])
Foo = w.op("f", ["o+ o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), w.commutator(Foo, T2), 4, 4)
val = sum.to_manybody_equation("r")["oo|vv"][0].rhs_expression()
val2 = w.expression("1/2 f^{o0}_{o2} t^{o1,o2}_{v0,v1}")
print_comparison(val, val2)
assert val == val2
def test_r2_4():
"""CCSD T2 Residual [Voooo,T2] (4)"""
T2 = w.op("t", ["v+ v+ o o"])
Voooo = w.op("v", ["o+ o+ o o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), w.commutator(Voooo, T2), 4, 4)
val = sum.to_manybody_equation("r")["oo|vv"][0].rhs_expression()
val2 = w.expression("1/8 t^{o2,o3}_{v0,v1} v^{o0,o1}_{o2,o3}")
print_comparison(val, val2)
assert val == val2
def test_r2_5():
"""CCSD T2 Residual [Vvvvv,T2] (5)"""
T2 = w.op("t", ["v+ v+ o o"])
Vvvvv = w.op("v", ["v+ v+ v v"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), w.commutator(Vvvvv, T2), 4, 4)
val = sum.to_manybody_equation("r")["oo|vv"][0].rhs_expression()
val2 = w.expression("1/8 t^{o0,o1}_{v2,v3} v^{v2,v3}_{v0,v1}")
print_comparison(val, val2)
assert val == val2
def test_r2_6():
"""CCSD T2 Residual [Vovov,T2] (6)"""
T2 = w.op("t", ["v+ v+ o o"])
Vovov = w.op("v", ["o+ v+ v o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), w.commutator(Vovov, T2), 4, 4)
val = sum.to_manybody_equation("r")["oo|vv"][0].rhs_expression()
val2 = w.expression("- t^{o0,o2}_{v0,v2} v^{o1,v2}_{o2,v1}")
print_comparison(val, val2)
assert val == val2
def test_r2_7():
"""CCSD T2 Residual [Vvvov,T1] (7)"""
T1 = w.op("t", ["v+ o"])
Vvvov = w.op("v", ["v+ v+ v o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), w.commutator(Vvvov, T1), 4, 4)
val = sum.to_manybody_equation("r")["oo|vv"][0].rhs_expression()
val2 = w.expression("-1/2 t^{o0}_{v2} v^{o1,v2}_{v0,v1}")
print_comparison(val, val2)
assert val == val2
def test_r2_8():
"""CCSD T2 Residual [Vovoo,T1] (8)"""
T1 = w.op("t", ["v+ o"])
Vovoo = w.op("v", ["o+ v+ o o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1), w.commutator(Vovoo, T1), 4, 4)
val = sum.to_manybody_equation("r")["oo|vv"][0].rhs_expression()
val2 = w.expression("-1/2 t^{o2}_{v0} v^{o0,o1}_{o2,v1}")
print_comparison(val, val2)
assert val == val2
def test_r2_9_12():
"""CCSD T2 Residual 1/2 [[Voovv,T2],T2] (9-12)"""
T2 = w.op("t", ["v+ v+ o o"])
Voovv = w.op("v", ["o+ o+ v v"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1, 2), w.commutator(w.commutator(Voovv, T2), T2), 4, 4)
compare_expressions(
sum.to_manybody_equation("r")["oo|vv"],
[
"1/2 t^{o0,o2}_{v0,v2} t^{o1,o3}_{v1,v3} v^{v2,v3}_{o2,o3}",
"-1/4 t^{o0,o1}_{v0,v2} t^{o2,o3}_{v1,v3} v^{v2,v3}_{o2,o3}",
"1/16 t^{o2,o3}_{v0,v1} t^{o0,o1}_{v2,v3} v^{v2,v3}_{o2,o3}",
"-1/4 t^{o0,o2}_{v0,v1} t^{o1,o3}_{v2,v3} v^{v2,v3}_{o2,o3}",
],
)
def test_r2_13():
"""CCSD T2 Residual 1/2 [[Voooo,T1],T1] (13)"""
T1 = w.op("t", ["v+ o"])
Voooo = w.op("v", ["o+ o+ o o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1, 2), w.commutator(w.commutator(Voooo, T1), T1), 4, 4)
val = sum.to_manybody_equation("r")["oo|vv"][0].rhs_expression()
val2 = w.expression("1/4 t^{o2}_{v0} t^{o3}_{v1} v^{o0,o1}_{o2,o3}")
print_comparison(val, val2)
assert val == val2
def test_r2_14():
"""CCSD T2 Residual 1/2 [[Vvvvv,T1],T1] (14)"""
T1 = w.op("t", ["v+ o"])
Vvvvv = w.op("v", ["v+ v+ v v"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1, 2), w.commutator(w.commutator(Vvvvv, T1), T1), 4, 4)
val = sum.to_manybody_equation("r")["oo|vv"][0].rhs_expression()
val2 = w.expression("1/4 t^{o0}_{v2} t^{o1}_{v3} v^{v2,v3}_{v0,v1}")
print_comparison(val, val2)
assert val == val2
def test_r2_15():
"""CCSD T2 Residual 1/2 [[Vovov,T1],T1] (15)"""
T1 = w.op("t", ["v+ o"])
Vovov = w.op("v", ["o+ v+ v o"])
wt = w.WickTheorem()
sum = wt.contract(w.rational(1, 2), w.commutator(w.commutator(Vovov, T1), T1), 4, 4)
val = sum.to_manybody_equation("r")["oo|vv"][0].rhs_expression()
val2 = w.expression("t^{o2}_{v0} t^{o0}_{v2} v^{o1,v2}_{o2,v1}")
print_comparison(val, val2)
assert val == val2
def test_r2_16_17():
"""CCSD T2 Residual [[Fov,T1],T2] (16-17)"""
T1 = | |
# Copyright (c) 2011, <NAME> [see LICENSE.txt]
# This software is funded in part by NIH Grant P20 RR016454.
# Python 2 to 3 workarounds
import sys
if sys.version_info[0] == 2:
_strobj = str
_xrange = xrange
elif sys.version_info[0] == 3:
_strobj = str
_xrange = range
import collections
import csv
import itertools
import inspect
import math
import sqlite3
import warnings
from pprint import pprint as pp
from copy import copy, deepcopy
from collections import OrderedDict, Counter, namedtuple
import pylab
import scipy
import numpy as np
import pystaggrelite3
from dictset import DictSet
from . import stats
from .stats.qsturng import qsturng, psturng
from .misc.texttable import Texttable as TextTable
from .misc.support import *
from . import plotting
# base.py holds DataFrame and Pyvttbl
# this file is a bit long but they can't be split without
# running into circular import complications
class DataFrame(OrderedDict):
"""holds the data in a dummy-coded group format"""
def __init__(self, *args, **kwds):
"""
initialize a :class:`DataFrame` object.
| Subclass of :mod:`collections`. :class:`OrderedDict`.
| Understands the typical initialization :class:`dict` signatures.
| Keys must be hashable.
| Values become numpy.arrays or numpy.ma.MaskedArrays.
"""
super(DataFrame, self).__init__()
#: sqlite3 connection
self.conn = sqlite3.connect(':memory:')
#: sqlite3 cursor
self.cur = self.conn.cursor()
#: list of sqlite3 aggregates
self.aggregates = tuple('avg count count group_concat ' \
'group_concat max min sum total tolist' \
.split())
# Bind pystaggrelite3 aggregators to sqlite3
for n, a, f in pystaggrelite3.getaggregators():
self.bind_aggregate(n, a, f)
#: prints the sqlite3 queries to stdout before
#: executing them for debugging purposes
self.PRINTQUERIES = False
#: controls whether plot functions return the test dictionaries
self.TESTMODE = False
#: holds the factors conditions in a DictSet Singleton
self.conditions = DictSet()
#: dict to map keys to sqlite3 types
self._sqltypesdict = {}
super(DataFrame, self).update(*args, **kwds)
def bind_aggregate(self, name, arity, func):
"""
binds a sqlite3 aggregator to :class:`DataFrame`
args:
name: string to be associated with the aggregator
arity: the number of inputs required by the aggregator
func: the aggregator class
returns:
None
| :class:`DataFrame`.aggregates is a list of the available aggregators.
| For information on rolling your own aggregators see:
http://docs.python.org/library/sqlite3.html
"""
self.conn.create_aggregate(name, arity, func)
self.aggregates = list(self.aggregates)
self.aggregates.append(name)
self.aggregates = tuple(self.aggregates)
def _get_sqltype(self, key):
"""
returns the sqlite3 type associated with the provided key
args:
key: key in :class:`DataFrame` (raises KeyError if key not in self)
returns:
a string specifiying the sqlite3 type associated with the data in self[key]:
{ 'null', 'integer', 'real', 'text'}
"""
return self._sqltypesdict[key]
def _get_nptype(self, key):
"""
returns the numpy type object associated with the provided key
args:
key: key in :class:`DataFrame` (raises KeyError if key not in self)
returns:
a numpy object specifiying the type associated with the data in self[key]:
========= ================
sql type numpy type
========= ================
'null' np.dtype(object)
'integer' np.dtype(int)
'real' np.dtype(float)
'text' np.dtype(str)
========= ================
"""
return {'null' : np.dtype(object),
'integer' : np.dtype(int),
'real' : np.dtype(float),
'text' : np.dtype(str)}[self._sqltypesdict[key]]
def _get_mafillvalue(self, key):
"""
returns the default fill value for invalid data associated with the provided key.
args:
key: key in :class:`DataFrame` (raises KeyError if key not in self)
returns:
string, float, or int associated with the data in self[key]
========= ============
sql type default
========= ============
'null' '?'
'integer' 999999
'real' 1e20
'text' 'N/A'
========= ============
| returned values match the defaults associated with np.ma.MaskedArray
"""
return {'null' : '?',
'integer' : 999999,
'real' : 1e20,
'text' : 'N/A'}[self._sqltypesdict[key]]
def read_tbl(self, fname, skip=0, delimiter=',',labels=True):
"""
loads tabulated data from a plain text file
args:
fname: path and name of datafile
kwds:
skip: number of lines to skip before looking for column labels. (default = 0)
delimiter: string to seperate values (default = "'")
labels: bool specifiying whether first row (after skip) contains labels.
(default = True)
returns:
None
| Checks and renames duplicate column labels as well as checking
| for missing cells. readTbl will warn and skip over missing lines.
"""
# open and read dummy coded data results file to data dictionary
fid = open(fname, 'r')
csv_reader = csv.reader(fid, delimiter=delimiter)
data = OrderedDict()
mask = {}
colnames = []
for i, row in enumerate(csv_reader):
# skip requested rows
if i < skip:
pass
# read column labels from ith+1 line
elif i == skip and labels:
colnameCounter = Counter()
for k, colname in enumerate(row):
colname = colname.strip()#.replace(' ','_')
colnameCounter[colname] += 1
if colnameCounter[colname] > 1:
warnings.warn("Duplicate label '%s' found"
%colname,
RuntimeWarning)
colname += '_%i'%colnameCounter[colname]
colnames.append(colname)
data[colname] = []
mask[colname] = []
# if labels is false we need to make labels
elif i == skip and not labels:
colnames = ['COL_%s'%(k+1) for k in range(len(row))]
for j,colname in enumerate(colnames):
if _isfloat(row[j]):
data[colname] = [float(row[j])]
mask[colname] = [0]
else:
data[colname] = [row[i]]
if row[i] == '':
mask[colname] = [1]
else:
mask[colname] = [0]
# for remaining lines where i>skip...
else:
if len(row) != len(colnames):
warnings.warn('Skipping line %i of file. '
'Expected %i cells found %i'\
%(i+1, len(colnames), len(row)),
RuntimeWarning)
else:
for j, colname in enumerate(colnames):
colname = colname.strip()
if _isfloat(row[j]):
data[colname].append(float(row[j]))
mask[colname].append(0)
else:
data[colname].append(row[j])
if row[j] == '':
mask[colname].append(1)
else:
mask[colname].append(0)
# close data file
fid.close()
self.clear()
for k, v in list(data.items()):
## In __setitem__ the conditions DictSet and datatype are set
self.__setitem__(k, v, mask[k])
del data
def __setitem__(self, key, item, mask=None):
"""
assign a column in the table
args:
key: hashable object to associate with item
item: an iterable that is put in an np.array or np.ma.array
kwds:
mask: mask value passed to np.ma.MaskedArray.__init__()
returns:
None
| df.__setitem__(key, item) <==> df[key] = item
| The assigned item must be iterable. To add a single row use
the insert method. To another table to this one use
the attach method.
example:
>>> ...
>>> print(df)
first last age gender
==================================
Roger Lew 28 male
Bosco Robinson 5 male
Megan Whittington 26 female
John Smith 51 male
<NAME> 49 female
>>> import numpy as np
>>> df['log10(age)'] = np.log10(df['age'])
>>> print(df)
first last age gender log10(age)
===============================================
<NAME> 28 male 1.447
<NAME> 5 male 0.699
<NAME> 26 female 1.415
<NAME> 51 male 1.708
<NAME> 49 female 1.690
>>>
"""
# check item
if not hasattr(item, '__iter__'):
raise TypeError("'%s' object is not iterable"%type(item).__name__)
if key in list(self.keys()):
del self[key]
# a mask was provided
if mask != None:
# data contains invalid entries and a masked array should be created
# this needs to be nested incase mask != None
if not all([m==0 for m in mask]):
# figure out the datatype of the valid entries
self._sqltypesdict[key] = \
self._determine_sqlite3_type([d for d,m in zip(item,mask) if not m])
# replace invalid values
fill_val = self._get_mafillvalue(key)
x = np.array([(d, fill_val)[m] for d,m in zip(item,mask)])
# call super.__setitem__
super(DataFrame, self).\
__setitem__(key, \
np.ma.array(x, mask=mask, dtype=self._get_nptype(key)))
# set or update self.conditions DictSet
self.conditions[key] = self[key]
# return if successful
return
# no mask provided or mask is all true
self._sqltypesdict[key] = self._determine_sqlite3_type(item)
super(DataFrame, self).\
__setitem__(key, np.array(item, dtype=self._get_nptype(key)))
self.conditions[key] = self[key]
## def __iter__(self):
## raise NotImplementedError('use .keys() to iterate')
def __delitem__(self, key):
"""
delete a column from the table
args:
key: associated with the item to delete
returns:
None
| df.__delitem__(key) <==> del df[key]
example:
>>> ...
>>> print(df)
first last age gender log10(age)
===============================================
<NAME> 28 male 1.447
Bosco Robinson 5 male 0.699
Megan Whittington 26 female 1.415
John Smith 51 male 1.708
Jane Doe 49 female 1.690
>>> del df['log10(age)']
>>> print(df)
first last age gender
==================================
Roger Lew 28 male
Bosco Robinson 5 male
Megan Whittington 26 female
John Smith 51 male
Jane Doe 49 female
>>>
"""
del self._sqltypesdict[key]
del self.conditions[key]
super(DataFrame, self).__delitem__(key)
def __str__(self):
"""
returns human friendly string representation of object
args:
| |
<gh_stars>0
import requests
import random
from datetime import datetime, timedelta
import os
from lxml import etree
# Define Path Variables
CURDIR = os.path.dirname(__file__)
def elapsed_time(previous_time):
"""
Calculates the elapsed time, in seconds, since a given previous time.
:param previous_time: Datetime string formatted as YYYY-mm-dd HH:MM:SS.FF
:return: Seconds float object.
"""
# Create Datetime Object from Previous Time ( in standard datetime.now() format )
before = datetime.strptime(previous_time, '%Y-%m-%d %H:%M:%S.%f')
# Get Nowtime
now = datetime.now()
# Return elapsed time, in seconds as ssss.ssss
return timedelta.total_seconds(now - before)
class Proxy(object):
"""
Handles proxy requests with proxies provided by BuyProxies.org.
Requests handled via requests library.
NOTE: Creates a 'proxydata.xml' datafile in whatever directory file is located to store proxies to avoid
unnecessary lookups.
"""
def __init__(self, userid, apikey):
# Define Record variables
self.record = os.path.join(CURDIR, 'proxydata.xml')
self.root = 'update'
# Define Nuances
self.delimiter = ':'
self.protocol = 'https'
# Define Format Options
self.formats = {
'1': ('proxy', 'port', 'username', 'password')
}
# Define Format
self.format = '1'
# Ingest Credentials
self.USERID = userid
self.APIKEY = apikey
# Enforce type for commonly mistyped.
if type(self.USERID) is int:
self.USERID = str(self.USERID)
# Define Check Frequency
self.check_frequency = 86400 * 1 # 1 day
# Create Record if Not Already Found
if os.path.exists(self.record) is False:
# Create New File
with open(self.record, 'w') as file:
file.write(f'<{self.root}></{self.root}>')
# Parse Datafile
tree = etree.parse(self.record)
root = tree.getroot()
# Create Update & Empty Proxy Element
updated = etree.SubElement(root, 'time')
updated.text = str(datetime.now())
# Save File
tree.write(self.record)
self.last_update = datetime.now()
self.proxies = None
# Get Existing File & Find Last Update Time (checks proxies for validity)
else:
# Parse File
with open(self.record, 'r')as file:
data = "".join(file.readlines())
root = etree.fromstring(data)
# Get last Updated Time
self.last_update = root.find('time').text
# Get Proxies as [(proxy, status)]
self.proxies = []
for x in root.findall('proxy'):
self.proxies.append((
x.text, # Host IP
x.get('port'),
x.get('user'),
x.get('password'),
))
# Define API URL
self.apiurl = f'http://api.buyproxies.org/?a=showProxies&pid={userid}&key={apikey}'
@staticmethod
def random_test_url():
"""
Gets a random url to use in testing proxy health.
NOTE: All urls are assumed to be highly-likely as active, and each page is lightweight.
:return: url string
"""
# Define Trusted Urls
urls = [
'http://yahoo.com/robots.txt',
'https://www.reddit.com//robots.txt',
'http://www.cnn.com//robots.txt',
'https://twitter.com/robots.txt',
'https://pinterest.com/robots.txt',
'https://plus.google.com/robots.txt',
'https://tumblr.com/robots.txt',
'http://last.fm/robots.txt',
'https://amazon.com/robots.txt',
'https://bing.com/robots.txt',
'http://instagram.com/robots.txt',
'http://ebay.com/robots.txt',
'http://netflix.com/robots.txt',
'http://microsoft.com/robots.txt',
'https://wordpress.com/robots.txt',
'https://medium.com/robots.txt',
'https://blogger.com/robots.txt',
'https://stackoverflow.com/robots.txt',
'https://imgur.com/robots.txt'
]
return urls[random.sample(range(0, len(urls)), 1)[0]]
@staticmethod
def random_user_agent():
"""
Provides a random user-agent from a list.
@Reference: https://developers.whatismybrowser.com/useragents/explore/
NOTES: This method generates a random user-agent to assign to proxies. Using a different user-agent with each
proxy request is likely to trigger bot filters. For example, most single IP addresses wouldn't present with 10+
user-agents. However, most IP addresses WOULD present with several, as well as several devices. Consider
implementing an IP:User-Agent record that limits x number of User-Agents (assigned) per IP.
@todo implement generative approach for user agents rather than simple lists
:return: http user-agent request header formatted string
"""
user_agents = [
# Chrome
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 5.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36',
# Internet Explorer
'Mozilla/5.0 (Windows NT 6.2; WOW64; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; Trident/7.0; rv:11.0) like Gecko',
'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko',
# Mozilla
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:61.0) Gecko/20100101 Firefox/61.0',
'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:63.0) Gecko/20100101 Firefox/63.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0'
]
# Get Random Index
r = random.sample(range(0, len(user_agents)), 1)[0]
return user_agents[r]
def request_proxies(self):
"""
Gets a list of proxies using the BuyProxies.org API.
:return: List of tuple Proxy Data formatted as [(ip, port, username, password)]
"""
# Update & Check Proxies
data = requests.get(self.apiurl)
# Parse API Response
proxies = []
for line in data.text.split('\n')[:-1]:
# Get Raw Response Data
parts = line.split(self.delimiter)
# ID Data, given format
if self.format == '1':
# ID Data
proxy = parts[0]
port = parts[1]
username = parts[2]
password = parts[3]
# Save to Check Later
proxies.append((proxy, port, username, password))
return proxies
def get_proxies(self):
"""
Gets list of most current proxies. If none, fetches new.
:return: list of proxy data tuples as [(proxy, port, username, password)]
"""
# If no existing proxies
if self.proxies is None or len(self.proxies) == 0:
# Get Proxies
self.proxies = self.request_proxies()
# Update Record
self.update_record(self.proxies)
return self.proxies
def get_proxy(self):
"""
Gets a single random proxy from available proxies
:return: proxy as (host, port, username, password)
"""
if self.proxies is None or len(self.proxies) == 0:
self.get_proxies()
return self.proxies[random.sample(range(0, len(self.proxies)), 1)[0]]
def format_proxy(self, user, password, port, host):
"""
Formats a proxy for use as requests.proxies argument.
:param user: string username
:param password: string password
:param port: string port
:param host: string ip address
:return: dict as {'protocol': 'protocol://user:password@host:port'}
"""
return {f'{self.protocol}': f'{self.protocol}://{user}:{password}@{host}:{port}'}
def check_proxy(self, user, password, host, port):
"""
Checks if proxy is valid.
:param user: string username text.
:param password: string password
:param host: string IP address as xx.xxx.xxx.xxx
:param port: string port. ex 80
:return: Boolean for active or not, determined by http request status code of random url request.
"""
# Define Proxy for Check
proxy = self.format_proxy(user=user, password=password, host=host, port=port)
# Check health, as much as 3 times before assuming proxy is dead.
errors = 0
valid = False
while errors < 3:
r = requests.get(self.random_test_url(), proxies=proxy)
if r.status_code == 200:
valid = True
break
else:
errors += 1
return valid
def update_record(self, proxy_list):
"""
Updates the proxy record with active proxies.
NOTE: Updates the Class variable self.proxies as well.
:param proxy_list: list of tuples as such: [(host, user, password, port)]
"""
# Create New File
with open(self.record, 'w')as file:
file.write(f'<{self.root}></{self.root}>')
# Define Root Node
tree = etree.parse(self.record)
root = tree.getroot()
# Do Update Time
updated = etree.SubElement(root, 'time')
updated.text = str(datetime.now())
# Save Each Proxy
proxies = etree.SubElement(root, 'proxies')
for p in proxy_list:
# Create Proxy Node
proxy = etree.SubElement(proxies, 'proxy')
# Add Data
proxy.text = p[0]
# Add Attributes
proxy.attrib['user'] = p[2]
proxy.attrib['password'] = p[3]
proxy.attrib['port'] = p[1]
# Update Global List
self.proxies = [(x[0], x[1], x[2], x[3]) for x in proxy_list]
# Save Data
tree.write(self.record)
def update(self, force=False):
"""
Checks if proxies still active.
:param force: Boolean argument check status regardless of time elapsed since last check.
NOTE: Updates the self.record datafile.
"""
# If existing proxies
if len(self.proxies) > 0:
# If elapsed time long enough or force is true
if elapsed_time(self.last_update) > self.check_frequency or force is True:
# Check Each proxy
good = []
for p in self.proxies:
# ID Data
user = p[2]
pwrd = p[3]
host = p[0]
port = p[1]
# Check if Active
valid = self.check_proxy(user=user, password=<PASSWORD>, host=host, port=port)
# Keep good proxies
if valid is True:
good.append(p) # (host, user, password, port)
# Update Proxy Datafile
self.update_record(good)
# Update class variable
self.proxies = good
# If no existing proxies are found do update
else:
# Get New Proxies
proxies = self.request_proxies() # (ip, port, user, password)
# Check Each proxy
good = []
for p in proxies:
# ID Data
user = p[2]
pwrd = p[3]
host = p[0]
port = p[1]
# Check if Active
valid = self.check_proxy(user=user, password=<PASSWORD>, host=host, port=port)
# Keep Good Proxies
if valid is True:
good.append(p)
# Update Proxy Record
# NOTE: Updates self.proxies variable as well.
self.update_record(good)
def get(self, url, headers=None, **kwargs):
"""
Makes a proxy request using | |
<reponame>kirmerzlikin/intellij-community
r'''
This module provides utilities to get the absolute filenames so that we can be sure that:
- The case of a file will match the actual file in the filesystem (otherwise breakpoints won't be hit).
- Providing means for the user to make path conversions when doing a remote debugging session in
one machine and debugging in another.
To do that, the PATHS_FROM_ECLIPSE_TO_PYTHON constant must be filled with the appropriate paths.
@note:
in this context, the server is where your python process is running
and the client is where eclipse is running.
E.g.:
If the server (your python process) has the structure
/user/projects/my_project/src/package/module1.py
and the client has:
c:\my_project\src\package\module1.py
the PATHS_FROM_ECLIPSE_TO_PYTHON would have to be:
PATHS_FROM_ECLIPSE_TO_PYTHON = [(r'c:\my_project\src', r'/user/projects/my_project/src')]
alternatively, this can be set with an environment variable from the command line:
set PATHS_FROM_ECLIPSE_TO_PYTHON=[['c:\my_project\src','/user/projects/my_project/src']]
@note: DEBUG_CLIENT_SERVER_TRANSLATION can be set to True to debug the result of those translations
@note: the case of the paths is important! Note that this can be tricky to get right when one machine
uses a case-independent filesystem and the other uses a case-dependent filesystem (if the system being
debugged is case-independent, 'normcase()' should be used on the paths defined in PATHS_FROM_ECLIPSE_TO_PYTHON).
@note: all the paths with breakpoints must be translated (otherwise they won't be found in the server)
@note: to enable remote debugging in the target machine (pydev extensions in the eclipse installation)
import pydevd;pydevd.settrace(host, stdoutToServer, stderrToServer, port, suspend)
see parameter docs on pydevd.py
@note: for doing a remote debugging session, all the pydevd_ files must be on the server accessible
through the PYTHONPATH (and the PATHS_FROM_ECLIPSE_TO_PYTHON only needs to be set on the target
machine for the paths that'll actually have breakpoints).
'''
from _pydevd_bundle.pydevd_constants import IS_PY2, IS_PY3K, DebugInfoHolder, IS_WINDOWS, IS_JYTHON
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
import json
import os.path
import sys
import traceback
_os_normcase = os.path.normcase
basename = os.path.basename
exists = os.path.exists
join = os.path.join
try:
rPath = os.path.realpath # @UndefinedVariable
except:
# jython does not support os.path.realpath
# realpath is a no-op on systems without islink support
rPath = os.path.abspath
# defined as a list of tuples where the 1st element of the tuple is the path in the client machine
# and the 2nd element is the path in the server machine.
# see module docstring for more details.
try:
PATHS_FROM_ECLIPSE_TO_PYTHON = json.loads(os.environ.get('PATHS_FROM_ECLIPSE_TO_PYTHON', '[]'))
except Exception:
sys.stderr.write('Error loading PATHS_FROM_ECLIPSE_TO_PYTHON from environment variable.\n')
traceback.print_exc()
PATHS_FROM_ECLIPSE_TO_PYTHON = []
else:
if not isinstance(PATHS_FROM_ECLIPSE_TO_PYTHON, list):
sys.stderr.write('Expected PATHS_FROM_ECLIPSE_TO_PYTHON loaded from environment variable to be a list.\n')
PATHS_FROM_ECLIPSE_TO_PYTHON = []
else:
# Converting json lists to tuple
PATHS_FROM_ECLIPSE_TO_PYTHON = [tuple(x) for x in PATHS_FROM_ECLIPSE_TO_PYTHON]
# example:
# PATHS_FROM_ECLIPSE_TO_PYTHON = [
# (r'd:\temp\temp_workspace_2\test_python\src\yyy\yyy',
# r'd:\temp\temp_workspace_2\test_python\src\hhh\xxx')
# ]
convert_to_long_pathname = lambda filename:filename
convert_to_short_pathname = lambda filename:filename
get_path_with_real_case = lambda filename:filename
if sys.platform == 'win32':
try:
import ctypes
from ctypes.wintypes import MAX_PATH, LPCWSTR, LPWSTR, DWORD
GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
GetLongPathName.argtypes = [LPCWSTR, LPWSTR, DWORD]
GetLongPathName.restype = DWORD
GetShortPathName = ctypes.windll.kernel32.GetShortPathNameW
GetShortPathName.argtypes = [LPCWSTR, LPWSTR, DWORD]
GetShortPathName.restype = DWORD
def _convert_to_long_pathname(filename):
buf = ctypes.create_unicode_buffer(MAX_PATH)
if IS_PY2 and isinstance(filename, str):
filename = filename.decode(getfilesystemencoding())
rv = GetLongPathName(filename, buf, MAX_PATH)
if rv != 0 and rv <= MAX_PATH:
filename = buf.value
if IS_PY2:
filename = filename.encode(getfilesystemencoding())
return filename
def _convert_to_short_pathname(filename):
buf = ctypes.create_unicode_buffer(MAX_PATH)
if IS_PY2 and isinstance(filename, str):
filename = filename.decode(getfilesystemencoding())
rv = GetShortPathName(filename, buf, MAX_PATH)
if rv != 0 and rv <= MAX_PATH:
filename = buf.value
if IS_PY2:
filename = filename.encode(getfilesystemencoding())
return filename
def _get_path_with_real_case(filename):
ret = convert_to_long_pathname(convert_to_short_pathname(filename))
# This doesn't handle the drive letter properly (it'll be unchanged).
# Make sure the drive letter is always uppercase.
if len(ret) > 1 and ret[1] == ':' and ret[0].islower():
return ret[0].upper() + ret[1:]
return ret
# Check that it actually works
_get_path_with_real_case(__file__)
except:
# Something didn't quite work out, leave no-op conversions in place.
if DebugInfoHolder.DEBUG_TRACE_LEVEL > 2:
traceback.print_exc()
else:
convert_to_long_pathname = _convert_to_long_pathname
convert_to_short_pathname = _convert_to_short_pathname
get_path_with_real_case = _get_path_with_real_case
elif IS_JYTHON and IS_WINDOWS:
def get_path_with_real_case(filename):
from java.io import File
f = File(filename)
ret = f.getCanonicalPath()
if IS_PY2 and not isinstance(ret, str):
return ret.encode(getfilesystemencoding())
return ret
if IS_WINDOWS:
if IS_JYTHON:
def normcase(filename):
return filename.lower()
else:
def normcase(filename):
# `normcase` doesn't lower case on Python 2 for non-English locale, but Java
# side does it, so we should do it manually.
if '~' in filename:
filename = convert_to_long_pathname(filename)
filename = _os_normcase(filename)
return filename.lower()
else:
def normcase(filename):
return filename # no-op
_ide_os = 'WINDOWS' if IS_WINDOWS else 'UNIX'
def set_ide_os(os):
'''
We need to set the IDE os because the host where the code is running may be
actually different from the client (and the point is that we want the proper
paths to translate from the client to the server).
:param os:
'UNIX' or 'WINDOWS'
'''
global _ide_os
prev = _ide_os
if os == 'WIN': # Apparently PyCharm uses 'WIN' (https://github.com/fabioz/PyDev.Debugger/issues/116)
os = 'WINDOWS'
assert os in ('WINDOWS', 'UNIX')
if prev != os:
_ide_os = os
# We need to (re)setup how the client <-> server translation works to provide proper separators.
setup_client_server_paths(_last_client_server_paths_set)
DEBUG_CLIENT_SERVER_TRANSLATION = os.environ.get('DEBUG_PYDEVD_PATHS_TRANSLATION', 'False').lower() in ('1', 'true')
# Caches filled as requested during the debug session.
NORM_PATHS_CONTAINER = {}
NORM_PATHS_AND_BASE_CONTAINER = {}
def _NormFile(filename):
abs_path, real_path = _NormPaths(filename)
return real_path
def _AbsFile(filename):
abs_path, real_path = _NormPaths(filename)
return abs_path
# Returns tuple of absolute path and real path for given filename
def _NormPaths(filename):
try:
return NORM_PATHS_CONTAINER[filename]
except KeyError:
if filename.__class__ != str:
raise AssertionError('Paths passed to _NormPaths must be str. Found: %s (%s)' % (filename, type(filename)))
abs_path = _NormPath(filename, os.path.abspath)
real_path = _NormPath(filename, rPath)
# cache it for fast access later
NORM_PATHS_CONTAINER[filename] = abs_path, real_path
return abs_path, real_path
def _NormPath(filename, normpath):
r = normpath(filename)
ind = r.find('.zip')
if ind == -1:
ind = r.find('.egg')
if ind != -1:
ind += 4
zip_path = r[:ind]
inner_path = r[ind:]
if inner_path.startswith('!'):
# Note (fabioz): although I can replicate this by creating a file ending as
# .zip! or .egg!, I don't really know what's the real-world case for this
# (still kept as it was added by @jetbrains, but it should probably be reviewed
# later on).
# Note 2: it goes hand-in-hand with 'exists'.
inner_path = inner_path[1:]
zip_path = zip_path + '!'
if inner_path.startswith('/') or inner_path.startswith('\\'):
inner_path = inner_path[1:]
if inner_path:
r = join(normcase(zip_path), inner_path)
return r
r = normcase(r)
return r
_ZIP_SEARCH_CACHE = {}
_NOT_FOUND_SENTINEL = object()
def exists(file):
if os.path.exists(file):
return file
ind = file.find('.zip')
if ind == -1:
ind = file.find('.egg')
if ind != -1:
ind += 4
zip_path = file[:ind]
inner_path = file[ind:]
if inner_path.startswith("!"):
# Note (fabioz): although I can replicate this by creating a file ending as
# .zip! or .egg!, I don't really know what's the real-world case for this
# (still kept as it was added by @jetbrains, but it should probably be reviewed
# later on).
# Note 2: it goes hand-in-hand with '_NormPath'.
inner_path = inner_path[1:]
zip_path = zip_path + '!'
zip_file_obj = _ZIP_SEARCH_CACHE.get(zip_path, _NOT_FOUND_SENTINEL)
if zip_file_obj is None:
return False
elif zip_file_obj is _NOT_FOUND_SENTINEL:
try:
import zipfile
zip_file_obj = zipfile.ZipFile(zip_path, 'r')
_ZIP_SEARCH_CACHE[zip_path] = zip_file_obj
except:
_ZIP_SEARCH_CACHE[zip_path] = _NOT_FOUND_SENTINEL
return False
try:
if inner_path.startswith('/') or inner_path.startswith('\\'):
inner_path = inner_path[1:]
_info = zip_file_obj.getinfo(inner_path.replace('\\', '/'))
return join(zip_path, inner_path)
except KeyError:
return None
return None
# Now, let's do a quick test to see if we're working with a version of python that has no problems
# related to the names generated...
try:
try:
code = rPath.func_code
except AttributeError:
code = rPath.__code__
if not exists(_NormFile(code.co_filename)):
sys.stderr.write('-------------------------------------------------------------------------------\n')
sys.stderr.write('pydev debugger: CRITICAL WARNING: This version of python seems to be incorrectly compiled (internal generated filenames are not absolute)\n')
sys.stderr.write('pydev debugger: The debugger may still function, but it will work slower and may miss breakpoints.\n')
sys.stderr.write('pydev debugger: Related bug: http://bugs.python.org/issue1666807\n')
sys.stderr.write('-------------------------------------------------------------------------------\n')
sys.stderr.flush()
NORM_SEARCH_CACHE = {}
initial_norm_paths = _NormPaths
def _NormPaths(filename): # Let's redefine _NormPaths to work with paths that may be incorrect
try:
return NORM_SEARCH_CACHE[filename]
except KeyError:
abs_path, real_path = initial_norm_paths(filename)
if not exists(real_path):
# We must actually go on and check if we can find it as if it was a relative path for some of the paths in the pythonpath
for path in sys.path:
abs_path, real_path = initial_norm_paths(join(path, filename))
if | |
# review, is copy really needed?
if edge[0] > vertex:
self.edges[ei][0] = edge[0] - 1
if edge[1] > vertex:
self.edges[ei][1] = edge[1] - 1
if self.hasEdgeLabels():
newEdgeLabels = {}
for key, value in self.edge_labels.items():
key0 = key[0]
key1 = key[1]
if key0 >= vertex:
key0 -= 1
if key1 >= vertex:
key1 -= 1
newEdgeLabels[(key0, key1)] = value
self.edge_labels = newEdgeLabels
if self.hasEdgeWeights():
newEdgeWeights = {}
for key, value in self.edge_weights.items():
key0 = key[0]
key1 = key[1]
if key0 >= vertex:
key0 -= 1
if key1 >= vertex:
key1 -= 1
newEdgeWeights[(key0, key1)] = value
self.edge_weights = newEdgeWeights
# decrement graph order
self.n -= 1
# Note there is no need to sort edges after a delete
self.clearCaches()
def deleteEdge(self, edge):
"""
Delete an edge specified as vertex-index-list.
Parameters
----------
edge : list of two integers
The two integers are the indices of the endpoint vertices.
Raises
------
Exception
If Graph does not contain indicated edge.
"""
edge = self.canonicalizeEdge(edge)
ei = -1
try:
ei = self.edges.index(edge)
except ValueError:
print(f"WARNING: deleteEdge: graph does not contain {edge}")
if ei < 0:
return
self.deleteEdgeByIndex(ei)
def deleteEdgeByIndex(self, ei):
"""
Delete edge by edge index.
Parameters
----------
ei : int
The index of the edge to delete in the .edges list.
Raises
------
Exception
If edge index is out of range.
"""
if ei < 0 or ei >= len(self.edges):
raise Exception(f"Invalid edge index: {ei}")
edge = self.edges[ei]
if None == edge:
raise Exception(f"No edge found at index {ei}")
if self.hasEdgeLabels():
if (edge[0], edge[1]) in self.edge_labels:
del self.edge_labels[(edge[0], edge[1])]
if self.hasEdgeWeights():
if (edge[0], edge[1]) in self.edge_weights:
del self.edge_weights[(edge[0], edge[1])]
del self.edges[ei]
# Note there is no need to sort edges after a delete
self.clearCaches()
def getEdgesForVertex(self, vertex):
"""
Get a list of edges for a vertex.
Parameters
----------
vertex : int
The index of the vertex.
Returns list of edges; each edge is a two-element vertex list [v1, v2]
"""
retEdges = []
for edge in self.edges:
if vertex in edge:
retEdges.append(edge)
else:
if not self.directed:
# optimization for sorted edges of undirected graphs -
# once we're past our vertex in edge-position 0 we're done
if edge[0] > vertex:
break
return retEdges
def getNeighbors(self, vertex):
"""
Get a list of vertices adjacent to vertex.
Parameters
----------
vertex : int
The vertex index
Returns list of adjacent vertex integer indices.
"""
neighbors = []
for edge in self.edges:
if edge[0] == vertex:
neighbors.append(edge[1])
elif edge[1] == vertex:
neighbors.append(edge[0])
else:
if not self.directed:
if edge[0] > vertex:
# when undirected, sorting means we won't find
# any more neighbors
break
return neighbors
def isEven(self):
"""
Returns True if all vertex degrees in Graph are even.
"""
for v in range(0, self.n):
deg = self.vertexDegree(v)
if deg % 2 == 1:
return False
return True
def isComplete(self):
"""
Returns True if this is a complete graph (all vertices adjacent to
each other)
"""
# a complete graph needs n(n-1)/2
numEdges = len(self.edges)
expected = self.n * (self.n - 1) / 2
if numEdges != expected:
return False
# For now we assume we don't have loops or
# multiple edges, so we return true - may need
# to refine later
return True
def complement(self):
"""
Returns a new Graph object that is the complement of the current
graph, i.e., a graph of the same order with edges only between
vertices that are not adjacent in the current graph.
"""
comp = Graph(self.n)
for i in range(0, self.n):
for j in range(i+1, self.n):
if i == j:
continue
if not self.hasEdge(i, j):
comp.edges.append([i, j])
return comp
def inducedSubgraph(self, vertices):
"""
Construct and return a new Graph that is isomorphic to the subgraph
induced on the list of vertices.
Parameters
----------
vertices : list of int
The vertices used to induce the subgraph.
Behavior
--------
Note that the returned graph will *not* have identical vertex-indices
to the original graph in most cases; vertex indicies are shifted to
reflect the order of the subgraph.
For example if vertices 3, 4, 5 are supplied, the resulting graph
will have order 3 and vertex indicies 0, 1, 2, but the resulting
edges will be isomorphic (e.g. if original graph had an edge between
4 and 5, the induced subgraph will have an edge between 1 and 2).
If the source graph is labeled, labels will be correctly assigned to
the induced subgraph (e.g. above if vertex 4 was labeled 'd', in the
induced subgraph the corresponding vertex 1 will be labeled 'd').
Returns a new Graph object.
"""
vertices.sort()
inducedEdges = []
for edge in self.edges:
if edge[0] in vertices and edge[1] in vertices:
if not edge in inducedEdges:
inducedEdges.append(edge)
vtxMap = {}
for vNew in range(0, len(vertices)):
vtxMap[vertices[vNew]] = vNew
sub = Graph(len(vertices))
if self.hasVertexLabels():
for vNew in range(0, len(vertices)):
if vertices[vNew] in self.vtx_labels:
sub.vtx_labels[vNew] = self.vtx_labels[vertices[vNew]]
for inducedEdge in inducedEdges:
newEdge = [vtxMap[inducedEdge[0]], vtxMap[inducedEdge[1]]]
if self.hasEdgeLabels():
if (inducedEdge[0], inducedEdge[1]) in self.edge_labels:
sub.edge_labels[(newEdge[0], newEdge[1])] = self.edge_labels[(inducedEdge[0], inducedEdge[1])]
sub.edges.append(newEdge)
return sub
# ------------------------------ vertex labels
def hasVertexLabels(self):
"""
Returns true if this Graph object has any vertex labels set.
"""
if None == self.vtx_labels:
return False
return len(self.vtx_labels) > 0
def clearVertexLabels(self):
"""
Delete any existing vertex labels.
"""
if self.hasVertexLabels():
del self.vtx_labels
self.vtx_labels = None
def setVertexLabel(self, vertex, label):
if vertex < 0 or vertex >= self.n:
raise Exception("vertex out of range")
if None == self.vtx_labels:
self.vtx_labels = {}
self.vtx_labels[vertex] = label
def getVertexLabel(self, vertex):
if self.hasVertexLabels():
return self.vtx_labels[vertex]
return None
def getVertexByLabel(self, label, useCache=True):
if useCache:
if None == self.vertex_by_label_cache:
self.udpateVertexByLabelCache()
if label in self.vertex_by_label_cache:
return self.vertex_by_label_cache[label]
return None
else:
for key, value in self.vtx_labels.items():
if value == label:
return key
def updateVertexByLabelCache(self):
self.vertex_by_label_cache = dict([(value, key) for key, value in self.vtx_labels.items()])
def clearVertexByLabelCache(self):
del self.vertex_by_label_cache
self.vertex_by_label_cache = None
# ------------------------------ edge labels
def hasEdgeLabels(self):
"""
Returns true if this Graph object has any edge labels set.
"""
return None != self.edge_labels and len(self.edge_labels) > 0
def clearEdgeLabels(self):
if self.hasEdgeLabels():
del self.edge_labels
self.edge_labels = None
def setEdgeLabel(self, edge, label):
edge = self.canonicalizeEdge(edge)
if None == self.edge_labels:
self.edge_labels = {}
self.edge_labels[edge] = label
def getEdgeLabel(self, edge):
label = None
if self.hasEdgeLabels():
label = self.edge_labels.get(edge)
return label
def getEdgeByLabel(self, label, useCache=True):
edge = None
if useCache:
if None == self.edge_by_label_cache:
self.updateEdgeByLabelCache()
edge = self.edge_by_label_cache.get(label)
else:
for key, value in self.edge_labels.items():
if value == label:
edge = key
return edge
def updateEdgeByLabelCache(self):
self.edge_by_label_cache = dict([(value, key) for key, value in self.vtx_labels.items()])
def clearEdgeByLabelCache(self):
del self.edge_by_label_cache
self.edge_by_label_cache = None
# ------------------------------ vertex weights
def hasVertexWeights(self):
"""
Returns true if this Graph object has any vertex weights set.
"""
return None != self.vtx_weights and len(self.vtx_weights) > 0
def setVertexWeight(self, vertex, weight):
if None == self.vtx_weights:
self.vtx_weights = {}
self.vtx_weights[vertex] = weight
def getVertexWeight(self, vertex):
weight = None
if self.hasVertexWeights():
weight = self.vtx_weights.get(vertex)
return weight
# ------------------------------ edge weights
def hasEdgeWeights(self):
"""
Returns true if this Graph object has any edge weights set.
"""
return None != self.edge_weights and len(self.edge_weights) > 0
def setEdgeWeight(self, v1, v2, weight):
if None == self.edge_weights:
self.edge_weights = {}
self.edge_weights[(v1, v2)] = weight
def getEdgeWeight(self, v1, v2, default=None):
if None == self.edge_weights:
return default
key = (v1, v2)
if key in self.edge_weights:
return self.edge_weights[key]
return default
# ------------------------------ vertex colors
def hasVertexColors(self):
"""
Returns true if this Graph object has any vertex colors set.
| |
## attack.py -- generate audio adversarial examples
##
## Copyright (C) 2017, <NAME> <<EMAIL>>.
##
## This program is licenced under the BSD 2-Clause licence,
## contained in the LICENCE file in this directory.
import numpy as np
import tensorflow as tf
import argparse
from shutil import copyfile
import scipy.io.wavfile as wav
from model_util import *
import struct
import time
import os
import sys
import logging
from collections import namedtuple
sys.path.append("DeepSpeech")
os.environ["CUDA_VISIBLE_DEVICES"] = "3"
try:
import pydub
except:
print("pydub was not loaded, MP3 compression will not work")
import DeepSpeech
from tensorflow.python.keras.backend import ctc_label_dense_to_sparse
from tf_logits import get_logits
#############################################
sav_path = '/mnt/data/audio_adversarial_examples_deepspeech/Data/Expriment_Data/IPC_CW'
if not os.path.exists(sav_path):
os.makedirs(sav_path)
t = time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime())
current_sav_path = sav_path + '/' + t
try:
os.makedirs(current_sav_path)
except:
raise Exception("make ouput dir failed")
else:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s",
handlers=[
logging.FileHandler(current_sav_path + '/' + t + '.log', mode='w'),
logging.StreamHandler()
]
)
#############################################
# These are the tokens that we're allowed to use.
# The - token is special and corresponds to the epsilon
# value in CTC decoding, and can not occur in the phrase.
toks = " abcdefghijklmnopqrstuvwxyz'-"
def convert_mp3(new, lengths):
import pydub
wav.write("/tmp/load.wav", 16000,
np.array(np.clip(np.round(new[0][:lengths[0]]),
-2 ** 15, 2 ** 15 - 1), dtype=np.int16))
pydub.AudioSegment.from_wav("/tmp/load.wav").export("/tmp/saved.mp3")
raw = pydub.AudioSegment.from_mp3("/tmp/saved.mp3")
mp3ed = np.array([struct.unpack("<h", raw.raw_data[i:i + 2])[0] for i in range(0, len(raw.raw_data), 2)])[
np.newaxis, :lengths[0]]
return mp3ed
class Attack:
def __init__(self, sess, loss_fn, phrase_length, max_audio_len,
learning_rate=10, num_iterations=5000, batch_size=1,
mp3=False, l2penalty=float('inf'), restore_path=None):
"""
Set up the attack procedure.
Here we create the TF graph that we're going to use to
actually generate the adversarial examples.
"""
self.sess = sess
#######################
self.learning_rate = learning_rate = 20
# l2penalty = float('inf') # > 500
l2penalty = 100000 # > 500
logging.info("--> Parameter: lr = %f, l2penalty = %f\n" % (learning_rate, l2penalty))
self.B = tf.Variable(np.zeros((batch_size, 1), dtype=np.float32), name='qq_B')
######################
self.num_iterations = num_iterations
self.batch_size = batch_size
self.phrase_length = phrase_length
self.max_audio_len = max_audio_len
self.mp3 = mp3
# Create all the variables necessary
# they are prefixed with qq_ just so that we know which
# ones are ours so when we restore the session we don't
# clobber them.
self.delta = delta = tf.Variable(np.zeros((batch_size, max_audio_len), dtype=np.float32), name='qq_delta')
self.mask = mask = tf.Variable(np.zeros((batch_size, max_audio_len), dtype=np.float32), name='qq_mask')
self.cwmask = cwmask = tf.Variable(np.zeros((batch_size, phrase_length), dtype=np.float32), name='qq_cwmask')
self.original = original = tf.Variable(np.zeros((batch_size, max_audio_len), dtype=np.float32), name='qq_original')
self.lengths = lengths = tf.Variable(np.zeros(batch_size, dtype=np.int32), name='qq_lengths')
self.importance = tf.Variable(np.zeros((batch_size, phrase_length), dtype=np.float32), name='qq_importance')
self.target_phrase = tf.Variable(np.zeros((batch_size, phrase_length), dtype=np.int32), name='qq_phrase')
self.target_phrase_lengths = tf.Variable(np.zeros((batch_size), dtype=np.int32), name='qq_phrase_lengths')
self.rescale = tf.Variable(np.zeros((batch_size, 1), dtype=np.float32), name='qq_rescale')
# Initially we bound the l_infty norm by 2000, increase this
# constant if it's not big enough of a distortion for your dataset.
# self.apply_delta = tf.clip_by_value(delta, -2000, 2000) * self.rescale
self.apply_delta = tf.clip_by_value(delta, -abs(original) * self.B, abs(original) * self.B)
# We set the new input to the model to be the abve delta
# plus a mask, which allows us to enforce that certain
# values remain constant 0 for length padding sequences.
self.new_input = new_input = self.apply_delta * mask + original
# We add a tiny bit of noise to help make sure that we can
# clip our values to 16-bit integers and not break things.
noise = tf.random_normal(new_input.shape,
stddev=2)
pass_in = tf.clip_by_value(new_input + noise, -2 ** 15, 2 ** 15 - 1)
# Feed this final value to get the logits.
self.logits = logits = get_logits(pass_in, lengths)
# And finally restore the graph to make the classifier
# actually do something interesting.
saver = tf.train.Saver([x for x in tf.global_variables() if 'qq' not in x.name])
saver.restore(sess, restore_path)
# Choose the loss function we want -- either CTC or CW
self.loss_fn = loss_fn
if loss_fn == "CTC":
target = ctc_label_dense_to_sparse(self.target_phrase, self.target_phrase_lengths)
ctcloss = tf.nn.ctc_loss(labels=tf.cast(target, tf.int32),
inputs=logits, sequence_length=lengths)
# Slight hack: an infinite l2 penalty means that we don't penalize l2 distortion
# The code runs faster at a slight cost of distortion, and also leaves one less
# paramaeter that requires tuning.
if not np.isinf(l2penalty):
loss = tf.reduce_mean((self.new_input - self.original) ** 2, axis=1) + l2penalty * ctcloss
else:
loss = ctcloss
self.expanded_loss = tf.constant(0)
elif loss_fn == "CW":
raise NotImplemented("The current version of this project does not include the CW loss function implementation.")
else:
raise
self.loss = loss
self.ctcloss = ctcloss
# Set up the Adam optimizer to perform gradient descent for us
start_vars = set(x.name for x in tf.global_variables())
optimizer = tf.train.AdamOptimizer(learning_rate)
grad, var = optimizer.compute_gradients(self.loss, [delta])[0]
self.train = optimizer.apply_gradients([(tf.sign(grad), var)])
end_vars = tf.global_variables()
new_vars = [x for x in end_vars if x.name not in start_vars]
sess.run(tf.variables_initializer(new_vars + [delta]))
# Decoder from the logits, to see how we're doing
self.decoded, _ = tf.nn.ctc_beam_search_decoder(logits, lengths, merge_repeated=False, beam_width=100)
def attack(self, audio, lengths, target, target_phrase, finetune=None):
sess = self.sess
# Initialize all of the variables
# TODO: each of these assign ops creates a new TF graph
# object, and they should be all created only once in the
# constructor. It works fine as long as you don't call
# attack() a bunch of times.
sess.run(tf.variables_initializer([self.delta]))
sess.run(self.original.assign(np.array(audio)))
sess.run(self.lengths.assign((np.array(lengths) - 1) // 320))
sess.run(self.mask.assign(np.array([[1 if i < l else 0 for i in range(self.max_audio_len)] for l in lengths])))
sess.run(self.cwmask.assign(np.array([[1 if i < l else 0 for i in range(self.phrase_length)] for l in (np.array(lengths) - 1) // 320])))
sess.run(self.target_phrase_lengths.assign(np.array([len(x) for x in target])))
sess.run(self.target_phrase.assign(np.array([list(t) + [0] * (self.phrase_length - len(t)) for t in target])))
c = np.ones((self.batch_size, self.phrase_length))
sess.run(self.importance.assign(c))
sess.run(self.rescale.assign(np.ones((self.batch_size, 1))))
###############################
initial_B = 100
B_decay = 0.8
rescale_decay = 0.8
logging.info("--> Parameter: initial_B = {}, B_decay = {}, rescale_decay = {}".format(initial_B, B_decay, rescale_decay))
################################
sess.run(self.B.assign(initial_B * np.ones((self.batch_size, 1))))
# Here we'll keep track of the best solution we've found so far
final_deltas = [None] * self.batch_size
if finetune is not None and len(finetune) > 0:
sess.run(self.delta.assign(finetune - audio))
# print initial asr output
new, delta, r_out, r_logits = sess.run((self.new_input, self.delta, self.decoded, self.logits))
lst = [(r_out, r_logits)]
if self.mp3:
mp3ed = convert_mp3(new, lengths)
mp3_out, mp3_logits = sess.run((self.decoded, self.logits),
{self.new_input: mp3ed})
lst.append((mp3_out, mp3_logits))
for out, logits in lst:
chars = out[0].values
res = np.zeros(out[0].dense_shape) + len(toks) - 1
for ii in range(len(out[0].values)):
x, y = out[0].indices[ii]
res[x, y] = out[0].values[ii]
# Here we print the strings that are recognized.
res = ["".join(toks[int(x)] for x in y).replace("-", "") for y in res]
logging.info("--> Original recogonized text: %s" % res)
logging.info("--> Target phrase: %s\n\n" % target_phrase)
# We'll make a bunch of iterations of gradient descent here
now = time.time()
MAX = self.num_iterations
for i in range(1, MAX):
iteration = i
now = time.time()
if self.mp3:
new = sess.run(self.new_input)
mp3ed = convert_mp3(new, lengths)
feed_dict = {self.new_input: mp3ed}
else:
feed_dict = {}
# Actually do the optimization ste
d, el, cl, l, logits, new_input, _ = sess.run((self.delta, self.expanded_loss,
self.ctcloss, self.loss,
self.logits, self.new_input,
self.train),
feed_dict)
# Report progress
print("%.3f" % np.mean(cl), "\t", "\t".join("%.3f" % x for x in cl))
############################################
# Print the strings that are recognized and the argmax of the alignment.
# new, delta, r_out, r_logits = sess.run((self.new_input, self.delta, self.decoded, self.logits))
new, delta, r_out, r_logits = sess.run((self.new_input, self.delta, self.decoded, self.logits))
lst = [(r_out, r_logits)]
if self.mp3:
mp3ed = convert_mp3(new, lengths)
mp3_out, mp3_logits = sess.run((self.decoded, self.logits),
{self.new_input: mp3ed})
lst.append((mp3_out, mp3_logits))
for out, logits in lst:
chars = out[0].values
res = np.zeros(out[0].dense_shape) + len(toks) - 1
for ii in range(len(out[0].values)):
x, y = out[0].indices[ii]
res[x, y] = out[0].values[ii]
# Here we print the strings that are recognized.
res = ["".join(toks[int(x)] for x in y).replace("-", "") for y in res]
# print("\n".join(res))
# And here we print the argmax of the alignment.
res2 = np.argmax(logits, axis=2).T
res2 = ["".join(toks[int(x)] for x in y[:(l - 1) // 320]) for y, l in zip(res2, lengths)]
# print("\n".join(res2))
if i % 10 == 0:
logging.info("\n".join(res2))
signal = np.sum(self.original.eval() ** 2)
noise = np.sum(self.apply_delta.eval() ** 2)
snr = 10 * np.log10(signal / noise)
# Report progress, print value of loss function
# print("%.3f" % np.mean(cl), "\t", "\t".join("%.3f" % x for x in cl))
new_input = self.original.eval() + self.apply_delta.eval()
logging.info(
"--> i: {:d}, B:{:.3f}, snr: {:.6f}, success: {:d}, loss:{:>8.3f}, cc: {:.6f}, l2 distance: {:.2f}, WER: {:.3f}, CER: {:.3f}, lcp: {:s}, result: {:s}".format(
i, self.B.eval()[0][0], | |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""TensorFlow Debugger: Tools for debugging gradients."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import uuid
import six
from tensorflow.python.debug.lib import debug_data
from tensorflow.python.framework import ops
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.ops import variables
_GRADIENT_DEBUG_TAG = "gradient_debug_"
_gradient_debuggers = {}
def _tensor_to_grad_debug_op_name(tensor, grad_debugger_uuid):
op_name, slot = debug_data.parse_node_or_tensor_name(tensor.name)
return "%s_%d/%s%s" % (op_name, slot, _GRADIENT_DEBUG_TAG, grad_debugger_uuid)
def _parse_grad_debug_op_name(op_name):
"""Parse the name of a debug gradient op.
Args:
op_name: the name of the debug gradient op.
Returns:
1) The UUID of the GradientsDebugger that created the debug gradient op.
2) Name of the original tensor whose gradient is debugged by the debug
gradient op.
"""
name_items = op_name.split("/")
assert len(name_items) > 1
assert name_items[-1].startswith(_GRADIENT_DEBUG_TAG)
grad_debugger_uuid = name_items[-1][len(_GRADIENT_DEBUG_TAG):]
if "_" in grad_debugger_uuid:
grad_debugger_uuid = grad_debugger_uuid[:grad_debugger_uuid.index("_")]
orig_tensor_slot = int(name_items[-2][name_items[-2].rfind("_") + 1:])
orig_base_op_name = name_items[-2][:name_items[-2].rfind("_")]
orig_tensor_name = ("/".join(name_items[:-2] + [orig_base_op_name]) +
":%d" % orig_tensor_slot)
return grad_debugger_uuid, orig_tensor_name
class GradientsDebugger(object):
"""Gradients Debugger.
Allows retrieval of gradient tensors created by TensorFlow's automatic
differentiation algorithm, i.e., @{tf.gradients} and optimizer classes that
use it.
"""
# TODO(cais): Add examples code in the doc string?
def __init__(self, y_tensor=None):
"""Constructor of GradientsDebugger.
Args:
y_tensor: optional: the `tf.Tensor` to be differentiated, i.e., the tensor
on the numerator of the differentiation.
"""
self._uuid = uuid.uuid4().hex
_gradient_debuggers[self._uuid] = self
# A dict mapping x-tensor names to gradient tensor. x-tensor refers to the
# independent tf.Tensor, i.e., the tensor on the denominator of the
# differentiation.
self._gradient_tensors = {}
self._y_tensor = y_tensor
self._graph = None
if y_tensor:
self._graph = y_tensor.graph
self._is_active_context = False
@property
def y_tensor(self):
return self._y_tensor
@property
def graph(self):
return self._graph
def __enter__(self):
self._is_active_context = True
def __exit__(self, unused_type, unused_value, unused_traceback):
self._is_active_context = False
def identify_gradient(self, input_tensor):
"""Create a debug identity tensor that registers and forwards gradients.
The side effect of this method is that when gradient tensor(s) are created
with respect to the any paths that include the `input_tensor`, the gradient
tensor(s) with repsect to `input_tensor` will be registered with this
this `GradientsDebugger` instance and can later be retrieved, with the
methods `gradient_tensor` and `gradient_tensors`.
Example:
```python
x = tf.Variable(1.0)
y = tf.add(x, x)
grad_debugger = tf_debug.GradientsDebugger()
debug_y = grad_debugger.identify_gradient(y)
z = tf.square(debug_y)
# Create a train op under the grad_debugger context.
with grad_debugger:
train_op = tf.train.GradientDescentOptimizer(z)
# Now we can reflect through grad_debugger to get the gradient tensor
# with respect to y.
y_grad = grad_debugger.gradient_tensor(y)
```
Args:
input_tensor: the input `tf.Tensor` object whose related gradient tensors
are to be reigstered with this `GradientsDebugger` instance when they
are created, e.g., during @{tf.gradients} calls or the construction
of optimization (training) op that uses @{tf.gradients}.
Returns:
A forwarded identity of `input_tensor`, as a `tf.Tensor`.
Raises:
ValueError: If an op with name that duplicates the gradient-debugging op
already exists in the graph (highly unlikely).
"""
# TODO(cais): Allow overriding gradient.
# TODO(cais): Implement value_stack.
grad_debug_op_name = _tensor_to_grad_debug_op_name(input_tensor, self._uuid)
# pylint: disable=protected-access
debug_grad_identity = gen_array_ops._debug_gradient_identity(
input_tensor, name=grad_debug_op_name)
# pylint: enable=protected-access
if debug_grad_identity.op.name != grad_debug_op_name:
raise ValueError(
"The graph already contains an op named %s" % grad_debug_op_name)
return debug_grad_identity
def watch_gradients_by_tensors(self, graph, tensors):
"""Watch gradient tensors by x-tensor(s).
The side effect of this method is that when gradient tensor(s) are created
with respect to the any paths that include the `x_tensor`s, the gradient
tensor(s) with repsect to the tensor will be registered with this
this `GradientsDebugger` instance and can later be retrieved, with the
methods `gradient_tensor` and `gradient_tensors`.
Unlike the method `identify_gradient`, this method is used to retrieve
gradient tensors after the construction of the forward subgraph has
completed (but before the construction of the backward subgraph).
This method is the same as `watch_gradients_by_x_tensor_names` except that
the tensors are specified by the Python `tf.Tensor` or `tf.Variable`
objects, instead by name patterns.
Example:
```python
x = tf.Variable(1.0)
y = tf.add(x, x, name="y")
z = tf.square(debug_y)
# Create a train op under the grad_debugger context.
grad_debugger = tf_debug.GradientsDebugger()
with grad_debugger.watch_gradients_by_tensors(y):
train_op = tf.train.GradientDescentOptimizer(z)
# Now we can reflect through grad_debugger to get the gradient tensor
# with respect to y.
y_grad = grad_debugger.gradient_tensor(y)
# or
y_grad = grad_debugger.gradient_tensor("y:0")
```
Args:
graph: the `tf.Graph` to watch the gradients on.
tensors: a `tf.Tensor` or `tf.Variable` object, or a list of such objects.
Returns:
The GradientsDebugger instance itself.
"""
if not isinstance(tensors, list):
tensors = [tensors]
tensor_name_regex = []
for tensor in tensors:
tensor_name_regex.append(re.escape(tensor.name) + "$")
tensor_name_regex = "(" + "|".join(tensor_name_regex) + ")"
return self.watch_gradients_by_tensor_names(graph, tensor_name_regex)
def watch_gradients_by_tensor_names(self, graph, tensor_name_regex):
"""Watch gradient tensors by name(s) of the x-tensor(s).
The side effect of this method is that when gradient tensor(s) are created
with respect to the x-tensors, the gradient tensor(s) will be registered
with this `GradientsDebugger` instance and can later be retrieved.
Unlike the `identify_gradient` method, this method is used after the
construction of the forward graph has completed. Unlike the
`watch_gradients_by_tensor` method, this method does not use handles to the
tensors of interest; it uses their names.
This method is the same as `watch_gradients_by_tensors` except that the
x-tensors are specified by name patterns, instead of `tf.Tensor` or
`tf.Variable` objects.
Example:
```python
x = tf.Variable(1.0, name="x")
y = tf.add(x, x, name="y")
z = tf.square(debug_y)
# Create a train op under the grad_debugger context.
grad_debugger = tf_debug.GradientsDebugger()
with grad_debugger.watch_gradients_by_tensor_names(r"(x|y):0$"):
train_op = tf.train.GradientDescentOptimizer(z)
# Now we can reflect through grad_debugger to get the gradient tensor
# with respect to x and y.
x_grad = grad_debugger.gradient_tensor("x:0")
y_grad = grad_debugger.gradient_tensor("y:0")
```
Args:
graph: the `tf.Graph` to watch the gradients on.
tensor_name_regex: the regular-expression pattern of the name(s) of the
x-tensor(s) to watch. x-tensor refers to the tensors on the denominator
of the differentiation.
Returns:
The GradientsDebugger instance itself.
"""
tensor_name_pattern = re.compile(tensor_name_regex)
# pylint: disable=protected-access
with graph.as_default():
for op in graph.get_operations():
for output in op.outputs:
if tensor_name_pattern.match(output.name):
debug_op = self.identify_gradient(output)
for consumer in output.consumers():
if consumer == debug_op.op:
continue
# Locate the slot index of the original input.
input_slots = []
for i, consumer_input in enumerate(consumer._inputs):
if consumer_input == output:
input_slots.append(i)
for slot in input_slots:
consumer._inputs[slot] = debug_op
debug_op._consumers.append(consumer)
del output._consumers[:]
output._consumers.append(debug_op.op)
# pylint: enable=protected-access
return self
def _check_same_graph(self, tensor):
if self._graph is None:
self._graph = tensor.graph
elif self._graph != tensor.graph:
raise ValueError(
"The graph of the value (%s) is not the same as the graph %s" %
(tensor.graph, self._graph))
def register_gradient_tensor(self,
x_tensor_name,
gradient_tensor):
"""Register the gradient tensor for an x-tensor.
Args:
x_tensor_name: (`str`) the name of the independent `tf.Tensor`, i.e.,
the tensor on the denominator of the differentiation.
gradient_tensor: the gradient `tf.Tensor`.
"""
if len(_gradient_debuggers) == 1 or self._is_active_context:
self._check_same_graph(gradient_tensor)
self._gradient_tensors[x_tensor_name] = gradient_tensor
def gradient_tensor(self, x_tensor):
"""Get the gradient tensor of an x-tensor.
Args:
x_tensor: (`tf.Tensor`, `tf.Variable` or `str`) The x-tensor object or its
name. x-tensor refers to the independent `tf.Tensor`, i.e., the tensor
on the denominator of the differentiation.
Returns:
If found, the gradient tensor.
Raises:
TypeError: If `x_tensor` is not a `tf.Tensor`, `tf.Variable` or `str`.
LookupError: If the `x_tensor` has not been registered with a gradient
tensor.
"""
x_tensor_name = self._get_tensor_name(x_tensor)
if x_tensor_name not in self._gradient_tensors:
raise LookupError(
"This GradientsDebugger has not received any gradient tensor for "
"x-tensor %s" % x_tensor_name)
return self._gradient_tensors[x_tensor_name]
def gradient_tensors(self):
"""Get the gradient tensors that this object is aware of.
Returns:
A dict mapping x-tensor names to gradient tensor objects. x-tensor refers
to the tensors on the denominator of the differentation.
"""
return self._gradient_tensors
def _get_tensor_name(self, tensor):
if isinstance(tensor, (ops.Tensor, variables.Variable)):
return tensor.name
elif isinstance(tensor, six.string_types):
return tensor
else:
raise | |
## Zaszi's config.py for Qutebrowser
# ----------------------------------------------------------------------------
# GENERAL
# ----------------------------------------------------------------------------
## This is here so configs done via the GUI are still loaded.
## Remove it to not load settings done via the GUI.
config.load_autoconfig()
## Force a Qt platform to use. This sets the `QT_QPA_PLATFORM`
## environment variable and is useful to force using the XCB plugin when
## running QtWebEngine on Wayland.
## Type: String
c.qt.force_platform = 'wayland'
## Number of commands to save in the command history. 0: no history / -1:
## unlimited
## Type: Int
c.completion.cmd_history_max_items = 1000
## Enable smooth scrolling for web pages. Note smooth scrolling does not
## work with the `:scroll-px` command.
## Type: Bool
c.scrolling.smooth = True
# ----------------------------------------------------------------------------
# KEYBINDINGS & ALIASES
# ----------------------------------------------------------------------------
## Aliases for commands. The keys of the given dictionary are the
## aliases, while the values are the commands they map to.
## Type: Dict
c.aliases = {'w': 'session-save', 'q': 'close', 'qa': 'quit', 'wq': 'quit --save', 'x': 'quit --save', 'wqa': 'quit --save'}
# ----------------------------------------------------------------------------
# SEARCH & COMPLETION
# ----------------------------------------------------------------------------
## Which categories to show (in which order) in the :open completion.
## Type: FlagList
## Valid values:
## - searchengines
## - quickmarks
## - bookmarks
## - history
c.completion.open_categories = ['quickmarks', 'bookmarks', 'history', 'searchengines']
# ----------------------------------------------------------------------------
# MEDIA & CONTENT
# ----------------------------------------------------------------------------
## Automatically start playing `<video>` elements. Note: On Qt < 5.11,
## this option needs a restart and does not support URL patterns.
## Type: Bool
c.content.autoplay = False
## Allow pdf.js to view PDF files in the browser. Note that the files can
## still be downloaded by clicking the download button in the pdf.js
## viewer.
## Type: Bool
c.content.pdfjs = True
## Directory to save downloads to. If unset, a sensible OS-specific
## default is used.
## Type: Directory
c.downloads.location.directory = '~/downloads'
## Prompt the user for the download location. If set to false,
## `downloads.location.directory` will be used.
## Type: Bool
c.downloads.location.prompt = False
## Editor (and arguments) to use for the `open-editor` command. The
## following placeholders are defined: * `{file}`: Filename of the file
## to be edited. * `{line}`: Line in which the caret is found in the
## text. * `{column}`: Column in which the caret is found in the text. *
## `{line0}`: Same as `{line}`, but starting from index 0. * `{column0}`:
## Same as `{column}`, but starting from index 0.
## Type: ShellCommand
c.editor.command = ['alacritty', '--command', 'nvim','{file}', '--cmd', 'normal {line}G{column0}l']
# ----------------------------------------------------------------------------
# SECURITY
# ----------------------------------------------------------------------------
## Which cookies to accept. With QtWebEngine, this setting also controls
## other features with tracking capabilities similar to those of cookies;
## including IndexedDB, DOM storage, filesystem API, service workers, and
## AppCache. Note that with QtWebKit, only `all` and `never` are
## supported as per-domain values. Setting `no-3rdparty` or `no-
## unknown-3rdparty` per-domain on QtWebKit will have the same effect as
## `all`. If this setting is used with URL patterns, the pattern gets
## applied to the origin/first party URL of the page making the request,
## not the request URL.
## Type: String
## Valid values:
## - all: Accept all cookies.
## - no-3rdparty: Accept cookies from the same origin only. This is known to break some sites, such as GMail.
## - no-unknown-3rdparty: Accept cookies from the same origin only, unless a cookie is already set for the domain. On QtWebEngine, this is the same as no-3rdparty.
## - never: Don't accept cookies at all.
c.content.cookies.accept = 'no-3rdparty'
# ----------------------------------------------------------------------------
# COLOR
# ----------------------------------------------------------------------------
# base16-qutebrowser (https://github.com/theova/base16-qutebrowser)
# Base16 qutebrowser template by theova
# Gruvbox dark, hard scheme by <NAME> (<EMAIL>), morhetz (https://github.com/morhetz/gruvbox)
# Define color values
base00 = "#1d2021"
base01 = "#3c3836"
base02 = "#504945"
base03 = "#665c54"
base04 = "#bdae93"
base05 = "#d5c4a1"
base06 = "#ebdbb2"
base07 = "#fbf1c7"
base08 = "#fb4934"
base09 = "#fe8019"
base0A = "#fabd2f"
base0B = "#b8bb26"
base0C = "#8ec07c"
base0D = "#83a598"
base0E = "#d3869b"
base0F = "#d65d0e"
# set qutebrowser colors
# Text color of the completion widget. May be a single color to use for
# all columns or a list of three colors, one for each column.
c.colors.completion.fg = base05
# Background color of the completion widget for odd rows.
c.colors.completion.odd.bg = base01
# Background color of the completion widget for even rows.
c.colors.completion.even.bg = base00
# Foreground color of completion widget category headers.
c.colors.completion.category.fg = base0A
# Background color of the completion widget category headers.
c.colors.completion.category.bg = base00
# Top border color of the completion widget category headers.
c.colors.completion.category.border.top = base00
# Bottom border color of the completion widget category headers.
c.colors.completion.category.border.bottom = base00
# Foreground color of the selected completion item.
c.colors.completion.item.selected.fg = base05
# Background color of the selected completion item.
c.colors.completion.item.selected.bg = base02
# Top border color of the selected completion item.
c.colors.completion.item.selected.border.top = base02
# Bottom border color of the selected completion item.
c.colors.completion.item.selected.border.bottom = base02
# Foreground color of the matched text in the selected completion item.
c.colors.completion.item.selected.match.fg = base0B
# Foreground color of the matched text in the completion.
c.colors.completion.match.fg = base0B
# Color of the scrollbar handle in the completion view.
c.colors.completion.scrollbar.fg = base05
# Color of the scrollbar in the completion view.
c.colors.completion.scrollbar.bg = base00
# Background color of disabled items in the context menu.
c.colors.contextmenu.disabled.bg = base01
# Foreground color of disabled items in the context menu.
c.colors.contextmenu.disabled.fg = base04
# Background color of the context menu. If set to null, the Qt default is used.
c.colors.contextmenu.menu.bg = base00
# Foreground color of the context menu. If set to null, the Qt default is used.
c.colors.contextmenu.menu.fg = base05
# Background color of the context menu’s selected item. If set to null, the Qt default is used.
c.colors.contextmenu.selected.bg = base02
#Foreground color of the context menu’s selected item. If set to null, the Qt default is used.
c.colors.contextmenu.selected.fg = base05
# Background color for the download bar.
c.colors.downloads.bar.bg = base00
# Color gradient start for download text.
c.colors.downloads.start.fg = base00
# Color gradient start for download backgrounds.
c.colors.downloads.start.bg = base0D
# Color gradient end for download text.
c.colors.downloads.stop.fg = base00
# Color gradient stop for download backgrounds.
c.colors.downloads.stop.bg = base0C
# Foreground color for downloads with errors.
c.colors.downloads.error.fg = base08
# Font color for hints.
c.colors.hints.fg = base00
# Background color for hints. Note that you can use a `rgba(...)` value
# for transparency.
c.colors.hints.bg = base0A
# Font color for the matched part of hints.
c.colors.hints.match.fg = base05
# Text color for the keyhint widget.
c.colors.keyhint.fg = base05
# Highlight color for keys to complete the current keychain.
c.colors.keyhint.suffix.fg = base05
# Background color of the keyhint widget.
c.colors.keyhint.bg = base00
# Foreground color of an error message.
c.colors.messages.error.fg = base00
# Background color of an error message.
c.colors.messages.error.bg = base08
# Border color of an error message.
c.colors.messages.error.border = base08
# Foreground color of a warning message.
c.colors.messages.warning.fg = base00
# Background color of a warning message.
c.colors.messages.warning.bg = base0E
# Border color of a warning message.
c.colors.messages.warning.border = base0E
# Foreground color of an info message.
c.colors.messages.info.fg = base05
# Background color of an info message.
c.colors.messages.info.bg = base00
# Border color of an info message.
c.colors.messages.info.border = base00
# Foreground color for prompts.
c.colors.prompts.fg = base05
# Border used around UI elements in prompts.
c.colors.prompts.border = base00
# Background color for prompts.
c.colors.prompts.bg = base00
# Background color for the selected item in filename prompts.
c.colors.prompts.selected.bg = base02
# Foreground color of the statusbar.
c.colors.statusbar.normal.fg = base0B
# Background color of the statusbar.
c.colors.statusbar.normal.bg = base00
# Foreground color of the statusbar in insert mode.
c.colors.statusbar.insert.fg = base00
# Background color of the statusbar in insert mode.
c.colors.statusbar.insert.bg = base0D
# Foreground color of the statusbar in passthrough mode.
c.colors.statusbar.passthrough.fg = base00
# Background color of the statusbar in passthrough mode.
c.colors.statusbar.passthrough.bg = base0C
# Foreground color of the statusbar in private browsing mode.
c.colors.statusbar.private.fg = base00
# Background color of the statusbar in private browsing mode.
c.colors.statusbar.private.bg = base01
# Foreground color of the statusbar in command mode.
c.colors.statusbar.command.fg = base05
# Background color of the statusbar in command mode.
c.colors.statusbar.command.bg = base00
# Foreground color of the statusbar in private browsing + command mode.
c.colors.statusbar.command.private.fg = base05
# Background color of the statusbar in private browsing + command mode.
c.colors.statusbar.command.private.bg = base00
# Foreground color of the statusbar in caret mode.
c.colors.statusbar.caret.fg = base00
# Background color of the statusbar in caret mode.
c.colors.statusbar.caret.bg = base0E
# Foreground color of the statusbar in caret mode with a selection.
c.colors.statusbar.caret.selection.fg = base00
# Background color of the statusbar in caret mode with a selection.
c.colors.statusbar.caret.selection.bg = base0D
# Background color of the progress bar.
c.colors.statusbar.progress.bg = base0D
# Default foreground color of the URL in the statusbar.
c.colors.statusbar.url.fg = base05
# Foreground color of the URL in the statusbar on error.
c.colors.statusbar.url.error.fg = base08
# Foreground color of the URL in the statusbar for hovered links.
c.colors.statusbar.url.hover.fg = base05
# Foreground color of the URL in the statusbar on successful load
# (http).
c.colors.statusbar.url.success.http.fg = base0C
# Foreground color of the URL in the statusbar on successful load
# (https).
c.colors.statusbar.url.success.https.fg = base0B
# Foreground color of the URL in | |
'Ethernet Controller X710 for 10GbE SFP+ [1572]', 'link_mode': '0',
'driver': 'i40e', 'pclass': 'Ethernet controller [0200]', 'mtu': 9216,
'psdevice': 'Ethernet Converged Network Adapter X710-2 [0008]',
'mac': '3c:fd:fe:b5:73:28', 'prevision': '-r01', 'sriov_vf_pdevice_id': None,
'sriov_totalvfs': 64, 'pciaddr': '0000:87:00.0', 'dpdksupport': True,
'pname': 'enp135s0f0', 'speed': 10000, 'psvendor': 'Intel Corporation [8086]',
'sriov_vf_driver': None, 'pvendor': 'Intel Corporation [8086]'}
enp135s0f1 = {'dev_id': 0, 'numa_node': 1, 'sriov_numvfs': 0, 'sriov_vfs_pci_address': '',
'pdevice': 'Ethernet Controller X710 for 10GbE SFP+ [1572]', 'link_mode': '0',
'driver': 'i40e', 'pclass': 'Ethernet controller [0200]', 'mtu': 1500,
'psdevice': 'Ethernet Converged Network Adapter X710 [0000]',
'mac': '3c:fd:fe:b5:73:29', 'prevision': '-r01', 'sriov_vf_pdevice_id': None,
'sriov_totalvfs': 64, 'pciaddr': '0000:87:00.1', 'dpdksupport': True,
'pname': 'enp135s0f1', 'speed': None, 'psvendor': 'Intel Corporation [8086]',
'sriov_vf_driver': None, 'pvendor': 'Intel Corporation [8086]'}
enp177s0f0 = {'dev_id': 0, 'numa_node': 1, 'sriov_numvfs': 0, 'sriov_vfs_pci_address': '',
'pdevice': 'Device [0d58]', 'link_mode': '0', 'driver': 'i40e',
'pclass': 'Ethernet controller [0200]', 'mtu': 1500, 'psdevice': 'Device [0000]',
'mac': '64:4c:36:12:9b:78', 'prevision': '-r02', 'sriov_vf_pdevice_id': None,
'sriov_totalvfs': 64, 'pciaddr': '0000:b1:00.0', 'dpdksupport': False,
'pname': 'enp177s0f0', 'speed': None, 'psvendor': 'Intel Corporation [8086]',
'sriov_vf_driver': None, 'pvendor': 'Intel Corporation [8086]'}
enp177s0f1 = {'dev_id': 0, 'numa_node': 1, 'sriov_numvfs': 0, 'sriov_vfs_pci_address': '',
'pdevice': 'Device [0d58]', 'link_mode': '0', 'driver': 'i40e',
'pclass': 'Ethernet controller [0200]', 'mtu': 1500, 'psdevice': 'Device [0000]',
'mac': '64:4c:36:12:9b:79', 'prevision': '-r02', 'sriov_vf_pdevice_id': None,
'sriov_totalvfs': 64, 'pciaddr': '0000:b1:00.1', 'dpdksupport': False,
'pname': 'enp177s0f1', 'speed': None, 'psvendor': 'Intel Corporation [8086]',
'sriov_vf_driver': None, 'pvendor': 'Intel Corporation [8086]'}
enp181s0f0 = {'dev_id': 0, 'numa_node': 1, 'sriov_numvfs': 0, 'sriov_vfs_pci_address': '',
'pdevice': 'Device [0d58]', 'link_mode': '0', 'driver': 'i40e',
'pclass': 'Ethernet controller [0200]', 'mtu': 1500, 'psdevice': 'Device [0000]',
'mac': '64:4c:36:12:9b:7c', 'prevision': '-r02', 'sriov_vf_pdevice_id': None,
'sriov_totalvfs': 64, 'pciaddr': '0000:b3:00.0', 'dpdksupport': False,
'pname': 'enp181s0f0', 'speed': None, 'psvendor': 'Intel Corporation [8086]',
'sriov_vf_driver': None, 'pvendor': 'Intel Corporation [8086]'}
enp181s0f1 = {'dev_id': 0, 'numa_node': 1, 'sriov_numvfs': 0, 'sriov_vfs_pci_address': '',
'pdevice': 'Device [0d58]', 'link_mode': '0', 'driver': 'i40e',
'pclass': 'Ethernet controller [0200]', 'mtu': 1500, 'psdevice': 'Device [0000]',
'mac': '64:4c:36:12:9b:7d', 'prevision': '-r02', 'sriov_vf_pdevice_id': None,
'sriov_totalvfs': 64, 'pciaddr': '0000:b3:00.1', 'dpdksupport': False,
'pname': 'enp181s0f1', 'speed': None, 'psvendor': 'Intel Corporation [8086]',
'sriov_vf_driver': None, 'pvendor': 'Intel Corporation [8086]'}
inic_dict_array = [enp25s0f0, enp25s0f1, enp134s0f0, enp134s0f1,
enp135s0f0, enp135s0f1, enp177s0f0, enp177s0f1, enp181s0f0, enp181s0f1]
return inic_dict_array
def _create_test_networks(self, mgmt_vlan_id):
address_pool_mgmt = utils.create_test_address_pool(id=1, network='192.168.204.0',
name='management', ranges=[['192.168.204.2', '192.168.204.254']], prefix=24)
mgmt_net = utils.create_test_network(id=1, name='mgmt', type=constants.NETWORK_TYPE_MGMT,
link_capacity=1000, vlan_id=mgmt_vlan_id, address_pool_id=address_pool_mgmt.id)
address_pool_pxeboot = utils.create_test_address_pool(id=2, network='192.168.205.0',
name='pxeboot', ranges=[['192.168.205.2', '192.168.205.254']], prefix=24)
pxeboot_net = utils.create_test_network(id=2, name='pxeboot',
type=constants.NETWORK_TYPE_PXEBOOT,
link_capacity=1000, address_pool_id=address_pool_pxeboot.id)
return mgmt_net, pxeboot_net
def test_get_ihost_by_macs(self):
self._create_test_ihosts()
ihost_macs = ['22:44:33:55:11:66', '22:44:33:88:11:66']
ihost = self.service.get_ihost_by_macs(self.context, ihost_macs)
self.assertEqual(ihost.mgmt_mac, '22:44:33:55:11:66')
def test_get_ihost_by_macs_no_match(self):
self._create_test_ihosts()
ihost = None
ihost_macs = ['22:44:33:99:11:66', '22:44:33:88:11:66']
ihost = self.service.get_ihost_by_macs(self.context, ihost_macs)
self.assertEqual(ihost, None)
def test_get_ihost_by_hostname(self):
self._create_test_ihosts()
ihost_hostname = 'controller-1'
ihost = self.service.get_ihost_by_hostname(self.context, ihost_hostname)
self.assertEqual(ihost.mgmt_mac, '22:44:33:55:11:66')
self.assertEqual(ihost.mgmt_ip, '1.2.3.5')
self.assertEqual(ihost.hostname, 'controller-1')
def test_get_ihost_by_hostname_invalid_name(self):
self._create_test_ihosts()
ihost_hostname = 'compute'
ihost = None
ihost = self.service.get_ihost_by_hostname(self.context, ihost_hostname)
self.assertEqual(ihost, None)
def test_iport_update_by_ihost_basic_creation(self):
"""Test the sysinv-agent port inventory basic port and interface creation
This test creates the port and interfaces based on the incoming report without any entry
matching the MAC address. The objective of this test if the data is stored on the correct
database tables
"""
# Create compute-0 node
config_uuid = str(uuid.uuid4())
ihost = self._create_test_ihost(
hostname='compute-0', mgmt_mac='22:44:33:55:11:77', uuid=str(uuid.uuid4()),
personality=constants.WORKER, config_status=None, config_applied=config_uuid,
config_target=config_uuid, invprovision=constants.PROVISIONED,
administrative=constants.ADMIN_UNLOCKED, operational=constants.OPERATIONAL_ENABLED,
availability=constants.AVAILABILITY_ONLINE,
)
mock_find_local_mgmt_interface_vlan_id = mock.MagicMock()
p = mock.patch(
'sysinv.conductor.manager.ConductorManager._find_local_mgmt_interface_vlan_id',
mock_find_local_mgmt_interface_vlan_id)
p.start().return_value = 0
self.addCleanup(p.stop)
mock_socket_gethostname = mock.MagicMock()
p2 = mock.patch('socket.gethostname', mock_socket_gethostname)
p2.start().return_value = 'controller-0'
self.addCleanup(p2.stop)
inic_dict_array = self._create_test_iports()
inic_mac_dict = dict()
for inic in inic_dict_array:
inic_mac_dict[inic['mac']] = inic
inic_pciaddr_dict = dict()
for inic in inic_dict_array:
inic_pciaddr_dict[inic['pciaddr']] = inic
self.service.iport_update_by_ihost(self.context, ihost['uuid'], inic_dict_array)
# check fields for each table
iface_db_list = self.dbapi.iinterface_get_by_ihost(ihost['uuid'])
self.assertEqual(len(iface_db_list), len(inic_dict_array))
for iface in iface_db_list:
self.assertIn(iface.imac, inic_mac_dict.keys())
self.assertEqual(inic_mac_dict[iface.imac]['pname'], iface.ifname)
self.assertEqual(inic_mac_dict[iface.imac]['mac'], iface.imac)
eth_iface_db_list = self.dbapi.ethernet_interface_get_by_ihost(ihost['uuid'])
self.assertEqual(len(eth_iface_db_list), len(inic_dict_array))
port_db_list = self.dbapi.port_get_by_host(ihost['uuid'])
self.assertEqual(len(port_db_list), len(inic_dict_array))
for port in port_db_list:
self.assertIn(port.pciaddr, inic_pciaddr_dict.keys())
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['pciaddr'], port.pciaddr)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['pname'], port.name)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['numa_node'], port.numa_node)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['pdevice'], port.pdevice)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['driver'], port.driver)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['pclass'], port.pclass)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['psdevice'], port.psdevice)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['psvendor'], port.psvendor)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['pvendor'], port.pvendor)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['sriov_vf_driver'],
port.sriov_vf_driver)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['sriov_numvfs'], port.sriov_numvfs)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['sriov_totalvfs'], port.sriov_totalvfs)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['sriov_vfs_pci_address'],
port.sriov_vfs_pci_address)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['sriov_vf_pdevice_id'],
port.sriov_vf_pdevice_id)
eth_port_db_list = self.dbapi.ethernet_port_get_by_host(ihost['uuid'])
self.assertEqual(len(eth_port_db_list), len(inic_dict_array))
for port in eth_port_db_list:
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['mtu'], port.mtu)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['speed'], port.speed)
self.assertEqual(inic_pciaddr_dict[port.pciaddr]['link_mode'], port.link_mode)
def test_iport_update_by_ihost_report_with_mgmt_untagged(self):
"""Test the sysinv-agent port inventory for managemet interface without VLAN
If the port MAC matches the host's MAC and it is not the active controller, test the entry
update to become a managemet interface and attached to the management network. The port
must receive the bootp flag.
"""
mgmt_vlan_id = 0
# Create compute-0 node
config_uuid = str(uuid.uuid4())
ihost = self._create_test_ihost(
hostname='compute-0', mgmt_mac='22:44:33:55:11:77', uuid=str(uuid.uuid4()),
personality=constants.WORKER, config_status=None, config_applied=config_uuid,
config_target=config_uuid, invprovision=constants.PROVISIONED,
administrative=constants.ADMIN_UNLOCKED, operational=constants.OPERATIONAL_ENABLED,
availability=constants.AVAILABILITY_ONLINE,
)
self._create_test_networks(mgmt_vlan_id)
mock_find_local_mgmt_interface_vlan_id = mock.MagicMock()
p = mock.patch(
'sysinv.conductor.manager.ConductorManager._find_local_mgmt_interface_vlan_id',
mock_find_local_mgmt_interface_vlan_id)
p.start().return_value = mgmt_vlan_id
self.addCleanup(p.stop)
mock_socket_gethostname = mock.MagicMock()
p2 = mock.patch('socket.gethostname', mock_socket_gethostname)
p2.start().return_value = 'controller-0'
self.addCleanup(p2.stop)
inic_dict_array = self._create_test_iports()
inic_dict_array[2]['mac'] = ihost['mgmt_mac']
self.service.iport_update_by_ihost(self.context, ihost['uuid'], inic_dict_array)
iface_db_list = self.dbapi.iinterface_get_by_ihost(ihost['uuid'])
self.assertEqual(len(iface_db_list), len(inic_dict_array))
has_mgmt = False
for iface in iface_db_list:
if (iface.imac == ihost['mgmt_mac']):
self.assertEqual('mgmt0', iface.ifname)
self.assertEqual('ethernet', iface.iftype)
self.assertEqual('platform', iface.ifclass)
ifnets = self.dbapi.interface_network_get_by_interface(iface.uuid)
self.assertEqual(len(ifnets), 1)
network = self.dbapi.network_get_by_id(ifnets[0].network_id)
self.assertEqual(network.type, constants.NETWORK_TYPE_MGMT)
has_mgmt = True
self.assertTrue(has_mgmt)
eth_port_db_list = self.dbapi.ethernet_port_get_by_host(ihost['uuid'])
for eth_port in eth_port_db_list:
if (eth_port.mac == ihost['mgmt_mac']):
self.assertTrue(eth_port.bootp)
else:
self.assertFalse(eth_port.bootp)
def test_iport_update_by_ihost_report_with_mgmt_vlan(self):
"""Test the sysinv-agent port inventory for managemet interface with VLAN
If the port MAC matches the host's MAC and it is not the active controller, there should
be 2 interfaces with the same MAC, one without VLAN and marked for pxeboot usage and the
other for management on the selected VLAN. The port must receive the bootp flag.
"""
mgmt_vlan_id = 111
# Create compute-0 node
config_uuid = str(uuid.uuid4())
ihost = self._create_test_ihost(
hostname='compute-0', mgmt_mac='22:44:33:55:11:77', uuid=str(uuid.uuid4()),
personality=constants.WORKER, config_status=None, config_applied=config_uuid,
config_target=config_uuid, invprovision=constants.PROVISIONED,
administrative=constants.ADMIN_UNLOCKED, operational=constants.OPERATIONAL_ENABLED,
availability=constants.AVAILABILITY_ONLINE,
)
self._create_test_networks(mgmt_vlan_id)
mock_find_local_mgmt_interface_vlan_id = mock.MagicMock()
p = mock.patch(
'sysinv.conductor.manager.ConductorManager._find_local_mgmt_interface_vlan_id',
mock_find_local_mgmt_interface_vlan_id)
p.start().return_value = mgmt_vlan_id
self.addCleanup(p.stop)
mock_socket_gethostname = mock.MagicMock()
p2 = mock.patch('socket.gethostname', mock_socket_gethostname)
p2.start().return_value = 'controller-0'
self.addCleanup(p2.stop)
inic_dict_array = self._create_test_iports()
inic_dict_array[2]['mac'] = ihost['mgmt_mac']
self.service.iport_update_by_ihost(self.context, ihost['uuid'], inic_dict_array)
iface_db_list = self.dbapi.iinterface_get_by_ihost(ihost['uuid'])
self.assertEqual(len(iface_db_list), len(inic_dict_array) + 1)
has_mgmt = False
has_pxeboot = False
for iface in iface_db_list:
if (iface.imac == ihost['mgmt_mac']):
ifnets = self.dbapi.interface_network_get_by_interface(iface.uuid)
if ('mgmt0' == iface.ifname):
self.assertEqual('vlan', iface.iftype)
self.assertEqual('platform', iface.ifclass)
self.assertEqual(mgmt_vlan_id, iface.vlan_id)
self.assertIn('mgmt', iface.networktypelist)
self.assertIn('pxeboot0', iface.uses)
has_mgmt = True
self.assertEqual(len(ifnets), 1)
network = self.dbapi.network_get_by_id(ifnets[0].network_id)
self.assertEqual(network.type, constants.NETWORK_TYPE_MGMT)
if ('pxeboot0' == iface.ifname):
self.assertEqual('ethernet', iface.iftype)
self.assertEqual('platform', iface.ifclass)
self.assertIn('mgmt0', iface.used_by)
has_pxeboot = True
self.assertEqual(len(ifnets), 1)
network = self.dbapi.network_get_by_id(ifnets[0].network_id)
self.assertEqual(network.type, constants.NETWORK_TYPE_PXEBOOT)
self.assertTrue(has_pxeboot and has_mgmt)
eth_port_db_list = self.dbapi.ethernet_port_get_by_host(ihost['uuid'])
for eth_port in eth_port_db_list:
if (eth_port.mac == ihost['mgmt_mac']):
self.assertTrue(eth_port.bootp)
else:
self.assertFalse(eth_port.bootp)
def test_iport_update_by_ihost_report_active_controller_with_mgmt_untagged(self):
"""Test the port inventory for managemet interface without VLAN on the active controller
If the port MAC matches the host's MAC and it is the active controller, no managemet
interface is created and the port receive the bootp flag
"""
mgmt_vlan_id = 0
# Create controller-0 node
config_uuid = str(uuid.uuid4())
ihost = self._create_test_ihost(
personality=constants.CONTROLLER, hostname='controller-0', uuid=str(uuid.uuid4()),
config_status=None, config_applied=config_uuid, config_target=config_uuid,
invprovision=constants.PROVISIONED, administrative=constants.ADMIN_UNLOCKED,
operational=constants.OPERATIONAL_ENABLED, availability=constants.AVAILABILITY_ONLINE,
mgmt_mac='00:11:22:33:44:55', mgmt_ip='1.2.3.4')
self._create_test_networks(mgmt_vlan_id)
mock_find_local_mgmt_interface_vlan_id = mock.MagicMock()
p = mock.patch(
'sysinv.conductor.manager.ConductorManager._find_local_mgmt_interface_vlan_id',
mock_find_local_mgmt_interface_vlan_id)
p.start().return_value = mgmt_vlan_id
self.addCleanup(p.stop)
mock_socket_gethostname = mock.MagicMock()
p2 = mock.patch('socket.gethostname', mock_socket_gethostname)
p2.start().return_value = 'controller-0'
self.addCleanup(p2.stop)
inic_dict_array = self._create_test_iports()
inic_dict_array[2]['mac'] = ihost['mgmt_mac']
self.service.iport_update_by_ihost(self.context, ihost['uuid'], inic_dict_array)
iface_db_list = self.dbapi.iinterface_get_by_ihost(ihost['uuid'])
for iface in iface_db_list:
if (iface.imac == ihost['mgmt_mac']):
self.assertNotEqual('mgmt0', iface.ifname)
self.assertNotEqual('platform', iface.ifclass)
ifnets = self.dbapi.interface_network_get_by_interface(iface.uuid)
self.assertEqual(len(ifnets), 0)
eth_port_db_list = self.dbapi.ethernet_port_get_by_host(ihost['uuid'])
for eth_port in eth_port_db_list:
if (eth_port.mac == ihost['mgmt_mac']):
self.assertTrue(eth_port.bootp)
def test_iport_update_by_ihost_report_install_from_clone(self):
"""Test the port inventory MAC update when DB is in install from clone
When installing from clone the database interfaces will have the MAC filed with a special
marker, the inventory report will be used to update with the actual port MAC.
"""
mgmt_vlan_id = 111
inic_dict_array = self._create_test_iports()
hostname = 'compute-0'
clone_mgmt_mac = (constants.CLONE_ISO_MAC + hostname + inic_dict_array[3]['pname'])
# Create compute-0 node
config_uuid = str(uuid.uuid4())
ihost = self._create_test_ihost(
hostname=hostname, mgmt_mac=clone_mgmt_mac, uuid=str(uuid.uuid4()),
personality=constants.WORKER, config_status=None, config_applied=config_uuid,
config_target=config_uuid, invprovision=constants.PROVISIONED,
administrative=constants.ADMIN_UNLOCKED, operational=constants.OPERATIONAL_ENABLED,
availability=constants.AVAILABILITY_ONLINE,
)
self._create_test_networks(mgmt_vlan_id)
mock_find_local_mgmt_interface_vlan_id = mock.MagicMock()
p = mock.patch(
'sysinv.conductor.manager.ConductorManager._find_local_mgmt_interface_vlan_id',
mock_find_local_mgmt_interface_vlan_id)
p.start().return_value = mgmt_vlan_id
self.addCleanup(p.stop)
mock_socket_gethostname = mock.MagicMock()
p2 = mock.patch('socket.gethostname', mock_socket_gethostname)
p2.start().return_value = 'controller-0'
self.addCleanup(p2.stop)
sriov0 = utils.create_test_interface(ifname='sriov0',
forihostid=ihost.id, ihost_uuid=ihost.uuid,
iftype=constants.INTERFACE_TYPE_ETHERNET,
ifclass=constants.INTERFACE_CLASS_PCI_SRIOV,
imac=(constants.CLONE_ISO_MAC + ihost['hostname']
+ inic_dict_array[0]['pname']))
sriov0a = utils.create_test_interface(ifname='sriov0a',
forihostid=ihost.id, ihost_uuid=ihost.uuid,
iftype=constants.INTERFACE_TYPE_VF, uses=['sriov0'],
ifclass=constants.INTERFACE_CLASS_PCI_SRIOV,
imac=(constants.CLONE_ISO_MAC + ihost['hostname']
+ inic_dict_array[0]['pname']))
data0 = utils.create_test_interface(ifname='data0',
forihostid=ihost.id, ihost_uuid=ihost.uuid,
ifclass=constants.INTERFACE_CLASS_DATA,
imac=(constants.CLONE_ISO_MAC + ihost['hostname']
+ inic_dict_array[1]['pname']))
pcipt0 = utils.create_test_interface(ifname='pcipt0',
forihostid=ihost.id, ihost_uuid=ihost.uuid,
ifclass=constants.INTERFACE_CLASS_PCI_PASSTHROUGH,
imac=(constants.CLONE_ISO_MAC + ihost['hostname']
+ inic_dict_array[2]['pname']))
pxeboot0 = utils.create_test_interface(ifname='pxeboot0',
forihostid=ihost.id, | |
from physicsTable import *
from operator import itemgetter
import sys
import geometry
import numpy as np
# Constants for ease
L = 101
R = -101
T = 103
B = -103
# Wall class for various operations
class Wall(object):
def __init__(self, p1, p2):
self.l = p1[0]
self.t = p1[1]
self.r = p2[0]
self.b = p2[1]
self.grouped = False
self.is_touching = []
# Returns boolean if two walls are touching
# NOTE: Only works for auto-generated trials where pixels are aligned
def touches(self, other):
# Do they touch on the side?
if self.r == other.l or self.l == other.r:
# Make sure that there is some overlap (e.g., the bottom of other is not above the top, or top of other not below the bottom)
return not (self.t > other.b or self.b < other.t)
# Do they touch on the top or bottom?
elif self.t == other.b or self.b == other.t:
# Make sure there is some overlap
return not (self.r < other.l or self.l > other.r)
else:
return False
# Figures out all touching walls and adds them to internal state
def get_touch_indices(self, others):
tidxs = [i for i in range(len(others)) if self.touches(others[i])]
self.is_touching = [others[i] for i in tidxs]
return tidxs
# Determines whether a point touches any side
def touches_wall(self, point):
return geometry.point_on_line(point, [self.l, self.t], [self.r, self.t]) or \
geometry.point_on_line(point, [self.r, self.t], [self.r, self.b]) or \
geometry.point_on_line(point, [self.r, self.b], [self.l, self.b]) or \
geometry.point_on_line(point, [self.l, self.b], [self.l, self.t])
def touches_top_wall(self, point):
return geometry.point_on_line(point, [self.l, self.t], [self.r, self.t])
# From a given point, traverses clockwise on the inside to collect points
def get_next_point_and_wall_and_dir(self, lastpt, dir):
# Traveling along the bottom wall
if dir == B:
# Sort touching walls from left to right
walls = sort_by_direction(self.is_touching, L)
for w in walls:
# Skip anything to the left of the last point
if w.l > lastpt[0]:
# The next wall is under the current one - this wall's top left is new, go down along the left wall
if w.t == self.b:
return (w.l, w.t), w, L
# The next wall is adjacent to this one and continues along the bottom
elif (self.r, self.b) == (w.l, w.b):
# Check along the bottom of this wall
return w.get_next_point_and_wall_and_dir((w.l, w.b), B)
# The next wall is to the right of this one
elif w.l == self.r:
return (self.r, self.b), w, L
return (self.r, self.b), self, R
# Traveling along the left wall
elif dir == L:
# Sort touching walls from top to bottom
walls = sort_by_direction(self.is_touching, T)
for w in walls:
# Skip anything above the last point
if w.t > lastpt[1]:
# The next wall is to the left of thecurrent one
if w.r == self.l:
return (w.r, w.t), w, T
# The next wall is adjacent and continues along the left
elif (self.l, self.b) == (w.l, w.t):
return w.get_next_point_and_wall_and_dir((w.l, w.t), L)
# The next wall is below the current one
elif w.t == self.b:
return (self.l, self.b), w, T
return (self.l, self.b), self, B
# Traveling along the top wall
elif dir == T:
# Sort touching walls from right to left
walls = sort_by_direction(self.is_touching, R)
for w in walls:
# Skip anything to the right of the last point
if w.r < lastpt[0]:
# The next wall is above the current one
if w.b == self.t:
return (w.r, w.b), w, R
# The next wall is adjancent and continues along the top
elif (self.l, self.t) == (w.r, w.t):
return w.get_next_point_and_wall_and_dir((w.r, w.t), T)
# The next wall is to the left of this one
elif w.r == self.l:
return (self.l, self.t), w, R
return (self.l, self.t), self, L
# Traveling along the right wall
elif dir == R:
walls = sort_by_direction(self.is_touching, B)
for w in walls:
# Skip anything below
if w.b < lastpt[1]:
# The next wall is to the right of the current one
if w.l == self.r:
return (w.l, w.b), w, B
# The next wall is adjancent and continues along the right
elif (self.r, self.t) == (w.r, w.b):
return w.get_next_point_and_wall_and_dir((w.r, w.b), R)
# The next wall is above this one
elif w.b == self.t:
return (self.r, self.t), w, B
return (self.r, self.t), self, T
def get_next_outer_point_and_wall_and_dir(self, lastpt, dir):
# Traveling along the bottom wall
if dir == B:
# Sort touching walls from right to left
walls = sort_by_outside_direction(self.is_touching, R)
for w in walls:
# Skip anything to the right of the last point
if w.r < lastpt[0]:
# The next wall is under the current one - this wall's top left is new, go down along the right wall
if w.t == self.b:
return (w.r, w.t), w, R
# The next wall is adjacent to this one and continues along the bottom
elif (self.l, self.b) == (w.r, w.b):
# Check along the bottom of this wall
return w.get_next_outer_point_and_wall_and_dir((w.r, w.b), B)
# The next wall is to the left of this one
elif w.r == self.l:
return (self.l, self.b), w, R
return (self.l, self.b), self, L
# Traveling along the left wall
elif dir == L:
# Sort touching walls from bottom to top
walls = sort_by_outside_direction(self.is_touching, B)
for w in walls:
# Skip anything below the last point
if w.b < lastpt[1]:
# The next wall is to the left of thecurrent one
if w.r == self.l:
return (w.r, w.b), w, B
# The next wall is adjacent and continues along the left
elif (self.l, self.t) == (w.l, w.b):
return w.get_next_outer_point_and_wall_and_dir((w.l, w.b), L)
# The next wall is above the current one
elif w.b == self.t:
return (self.l, self.t), w, B
return (self.l, self.t), self, T
# Traveling along the top wall
elif dir == T:
# Sort touching walls from left to right
walls = sort_by_outside_direction(self.is_touching, L)
for w in walls:
# Skip anything to the left of the last point
if w.l > lastpt[0]:
# The next wall is above the current one
if w.b == self.t:
return (w.l, w.b), w, L
# The next wall is adjancent and continues along the top
elif (self.r, self.t) == (w.l, w.t):
return w.get_next_outer_point_and_wall_and_dir((w.l, w.t), T)
# The next wall is to the right of this one
elif w.l == self.r:
return (self.r, self.t), w, L
return (self.r, self.t), self, R
# Traveling along the right wall
elif dir == R:
walls = sort_by_outside_direction(self.is_touching, T)
for w in walls:
# Skip anything above
if w.t > lastpt[1]:
# The next wall is to the right of the current one
if w.l == self.r:
return (w.l, w.t), w, T
# The next wall is adjancent and continues along the right
elif (self.r, self.b) == (w.r, w.t):
return w.get_next_outer_point_and_wall_and_dir((w.r, w.t), R)
# The next wall is below this one
elif w.t == self.b:
return (self.r, self.b), w, T
return (self.r, self.b), self, B
def to_pg_rect(self):
w = self.r - self.l
h = self.b - self.t
return pg.Rect((self.l, self.t), (w,h))
# Converts trial into a set of wall rectangles [right, top, left, bottom]
def convert_trial_2_wallrects(trial):
return [Wall(w[0],w[1]) for w in trial.normwalls]
def get_topleft_wall(walls):
best_idx = 0
most_top = walls[0].t
most_left = walls[0].l
for i in range(1,len(walls)):
w = walls[i]
if w.t < most_top or \
(w.t == most_top and w.l < most_left):
best_idx = i
most_top = w.t
most_left = w.l
return best_idx, walls[best_idx]
def get_topright_wall(walls):
best_idx = 0
most_top = walls[0].t
most_right = walls[0].r
for i in range(1, len(walls)):
w = walls[i]
if w.t < most_top or \
(w.t == most_top and w.r > most_right):
best_idx = i
most_top = w.t
most_right = w.r
return best_idx, walls[best_idx]
def sort_by_direction(walls, dir):
if dir == L:
pfnc = lambda x: (x.l, -x.b)
elif dir == R:
pfnc = lambda x: (-x.r, x.t)
elif dir == T:
pfnc = lambda x: (x.t, x.l)
elif dir == B:
pfnc = lambda x: (-x.b, -x.r)
vals = zip(map(pfnc, walls), walls)
vsort = sorted(vals, key=itemgetter(0))
return [w for | |
value="INYU_LIT - INYU_LIT (Taught at NYU)">INYU_LIT - INYU_LIT (Taught at NYU)</option>
<option value="INYU_MES - INYU_MES (Taught at NYU)">INYU_MES - INYU_MES (Taught at NYU)</option>
<option value="INYU_MET - INYU_METRO ST (Taught at NYU)">INYU_MET - INYU_METRO ST (Taught at NYU)</option>
<option value="INYU_MJL - INYU_MJL">INYU_MJL - INYU_MJL</option>
<option value="INYU_MMS - INYU_MMS (Taught at NYU)">INYU_MMS - INYU_MMS (Taught at NYU)</option>
<option value="INYU_MTH - INYU_MTH (Taught at NYU)">INYU_MTH - INYU_MTH (Taught at NYU)</option>
<option value="INYU_MUS - INYU_MUS (Taught at NYU)">INYU_MUS - INYU_MUS (Taught at NYU)</option>
<option value="INYU_NSC - INYU_NSC (Taught at NYU)">INYU_NSC - INYU_NSC (Taught at NYU)</option>
<option value="INYU_OAR - INYU_OAR(Taught at NYU)">INYU_OAR - INYU_OAR(Taught at NYU)</option>
<option value="INYU_PHE - INYU_PHYSEDU (Taught at NYU)">INYU_PHE - INYU_PHYSEDU (Taught at NYU)</option>
<option value="INYU_PHL - INYU_PHL (Taught at NYU)">INYU_PHL - INYU_PHL (Taught at NYU)</option>
<option value="INYU_PJ - INYU_PJ (Taught at NYU)">INYU_PJ - INYU_PJ (Taught at NYU)</option>
<option value="INYU_PPS - INYU_PUBPOL (Taught at NYU)">INYU_PPS - INYU_PUBPOL (Taught at NYU)</option>
<option value="INYU_PS - INYU_PS (Taught at NYU)">INYU_PS - INYU_PS (Taught at NYU)</option>
<option value="INYU_PSY - INYU_PSY (Taught at NYU)">INYU_PSY - INYU_PSY (Taught at NYU)</option>
<option value="INYU_PTG - INYU_PTG (Taught at NYU)">INYU_PTG - INYU_PTG (Taught at NYU)</option>
<option value="INYU_REL - INYU_REL (Taught at NYU)">INYU_REL - INYU_REL (Taught at NYU)</option>
<option value="INYU_RS - ROMANCE STUDIES">INYU_RS - ROMANCE STUDIES</option>
<option value="INYU_SEM - INYU_SEM (Taught at NYU)">INYU_SEM - INYU_SEM (Taught at NYU)</option>
<option value="INYU_SOC - INYU_SOC (Taught at NYU)">INYU_SOC - INYU_SOC (Taught at NYU)</option>
<option value="INYU_SP - INYU_SPANISH (Taught at NYU)">INYU_SP - INYU_SPANISH (Taught at NYU)</option>
<option value="INYU_STA - INYU_STA (Taught at NYU)">INYU_STA - INYU_STA (Taught at NYU)</option>
<option value="INYU_SXL - INYU_SXL (Taught at NYU)">INYU_SXL - INYU_SXL (Taught at NYU)</option>
<option value="INYU_THS - INYU_THS (Taught at NYU)">INYU_THS - INYU_THS (Taught at NYU)</option>
<option value="INYU_TS - INYU-TS(Taught at NYU)">INYU_TS - INYU-TS(Taught at NYU)</option>
<option value="INYU_VMS - INYU_VMS (Taught at NYU)">INYU_VMS - INYU_VMS (Taught at NYU)</option>
<option value="INYU_WST - INYU_WST (Taught at NYU)">INYU_WST - INYU_WST (Taught at NYU)</option>
<option value="ISIS - Inf Science and Inf Studies">ISIS - Inf Science and Inf Studies</option>
<option value="ISP - Immunology Study Program">ISP - Immunology Study Program</option>
<option value="ISS - Information Science + Studies">ISS - Information Science + Studies</option>
<option value="ITALIAN - Italian">ITALIAN - Italian</option>
<option value="IUSC-PSY - IUSC_PSYC (Taught at USC)">IUSC-PSY - IUSC_PSYC (Taught at USC)</option>
<option value="IUSC_AME - IUSC_AME (Taught at USC)">IUSC_AME - IUSC_AME (Taught at USC)</option>
<option value="IUSC_AMI - IUSC_AMI (Taught at USC)">IUSC_AMI - IUSC_AMI (Taught at USC)</option>
<option value="IUSC_CE - IUSC_CE (Taught at USC)">IUSC_CE - IUSC_CE (Taught at USC)</option>
<option value="IUSC_COM - IUSC_COM (Taught at USC)">IUSC_COM - IUSC_COM (Taught at USC)</option>
<option value="IUSC_CSC - IUSC_CSC (Taught at USC)">IUSC_CSC - IUSC_CSC (Taught at USC)</option>
<option value="IUSC_CTA - IUSC_CTA (Taught at USC)">IUSC_CTA - IUSC_CTA (Taught at USC)</option>
<option value="IUSC_CTC - IUSC_CTC (Taught at USC)">IUSC_CTC - IUSC_CTC (Taught at USC)</option>
<option value="IUSC_CTP - IUSC_CTP (Taught at USC)">IUSC_CTP - IUSC_CTP (Taught at USC)</option>
<option value="IUSC_CTV - IUSC_CTV (Taught at USC)">IUSC_CTV - IUSC_CTV (Taught at USC)</option>
<option value="IUSC_CTW - IUSC_CTW (Taught at USC)">IUSC_CTW - IUSC_CTW (Taught at USC)</option>
<option value="IUSC_FA - IUSC_FA (Taught at USC)">IUSC_FA - IUSC_FA (Taught at USC)</option>
<option value="IUSC_FVD - IUSC_FVD (Taught at USC)">IUSC_FVD - IUSC_FVD (Taught at USC)</option>
<option value="IUSC_JRN - IUSC_JRN (Taught at USC)">IUSC_JRN - IUSC_JRN (Taught at USC)</option>
<option value="IUSC_LIT - IUSC_LIT (Taught at USC)">IUSC_LIT - IUSC_LIT (Taught at USC)</option>
<option value="IUSC_MUI - IUSC_MUI (Taught at USC)">IUSC_MUI - IUSC_MUI (Taught at USC)</option>
<option value="IUSC_MUS - IUSC_MUS (Taught at USC)">IUSC_MUS - IUSC_MUS (Taught at USC)</option>
<option value="IUSC_PE - IUSC_PE (Tuahgt at USC)">IUSC_PE - IUSC_PE (Tuahgt at USC)</option>
<option value="IUSC_PJM - IUSC_PJMS (Taught at USC)">IUSC_PJM - IUSC_PJMS (Taught at USC)</option>
<option value="IUSC_PPS - IUSC_PPS (Taught at USC)">IUSC_PPS - IUSC_PPS (Taught at USC)</option>
<option value="IUSC_PS - IUSC_PS (Taught at USC)">IUSC_PS - IUSC_PS (Taught at USC)</option>
<option value="IUSC_SOC - IUSC_SOC (Taught at USC)">IUSC_SOC - IUSC_SOC (Taught at USC)</option>
<option value="IUSC_THT - IUSC_THT (Taught at USC)">IUSC_THT - IUSC_THT (Taught at USC)</option>
<option value="IUSC_VIS - IUSC_ARTSVIS (Taught at USC)">IUSC_VIS - IUSC_ARTSVIS (Taught at USC)</option>
<option value="JEWISHST - Jewish Studies">JEWISHST - Jewish Studies</option>
<option value="JGER_ART - Art">JGER_ART - Art</option>
<option value="JGER_CMM - Communication Studies">JGER_CMM - Communication Studies</option>
<option value="JGER_CPL - Comparative Literature">JGER_CPL - Comparative Literature</option>
<option value="JGER_CZH - Czech">JGER_CZH - Czech</option>
<option value="JGER_ENG - English">JGER_ENG - English</option>
<option value="JGER_FRE - French">JGER_FRE - French</option>
<option value="JGER_GEG - Geography">JGER_GEG - Geography</option>
<option value="JGER_GER - German">JGER_GER - German</option>
<option value="JGER_GRK - Greek">JGER_GRK - Greek</option>
<option value="JGER_HST - History">JGER_HST - History</option>
<option value="JGER_JWS - Jewish Studies">JGER_JWS - Jewish Studies</option>
<option value="JGER_LAT - Latin">JGER_LAT - Latin</option>
<option value="JGER_LAW - Law">JGER_LAW - Law</option>
<option value="JGER_PHA - Physical Activities">JGER_PHA - Physical Activities</option>
<option value="JGER_PHL - Philosophy">JGER_PHL - Philosophy</option>
<option value="JGER_PLN - City and Regional Planning">JGER_PLN - City and Regional Planning</option>
<option value="JGER_PLS - Polish">JGER_PLS - Polish</option>
<option value="JGER_REL - Religion">JGER_REL - Religion</option>
<option value="JGER_SLV - Slavic Languages">JGER_SLV - Slavic Languages</option>
<option value="JGER_SOC - Sociology">JGER_SOC - Sociology</option>
<option value="JGER_WST - Women's Studies">JGER_WST - Women's Studies</option>
<option value="JPN - Japanese">JPN - Japanese</option>
<option value="KICHE - K’iche Mayan">KICHE - K’iche Mayan</option>
<option value="KOREAN - Korean">KOREAN - Korean</option>
<option value="LATAMER - Latin American Studies">LATAMER - Latin American Studies</option>
<option value="LATIN - Latin">LATIN - Latin</option>
<option value="LAW - Law">LAW - Law</option>
<option value="LIBRARY - LIBRARY">LIBRARY - LIBRARY</option>
<option value="LINGUIST - Linguistics">LINGUIST - Linguistics</option>
<option value="LIT - Literature">LIT - Literature</option>
<option value="LS - Liberal Studies">LS - Liberal Studies</option>
<option value="LSGS - Latino Studies Global South">LSGS - Latino Studies Global South</option>
<option value="LTS - Liturgical Studies">LTS - Liturgical Studies</option>
<option value="MALS - Liberal Studies">MALS - Liberal Studies</option>
<option value="MANAGEMT - Management">MANAGEMT - Management</option>
<option value="MARKETNG - Marketing">MARKETNG - Marketing</option>
<option value="MAT - Master of Arts in Teaching">MAT - Master of Arts in Teaching</option>
<option value="MATH - Mathematics">MATH - Mathematics</option>
<option value="MBP - Molecular Biophysics">MBP - Molecular Biophysics</option>
<option value="MBS - Modeling Biological Systems">MBS - Modeling Biological Systems</option>
<option value="MCH - MCH">MCH - MCH</option>
<option value="MDP - Molecular Development">MDP - Molecular Development</option>
<option value="ME - Mechanical Engr/Materials Sci">ME - Mechanical Engr/Materials Sci</option>
<option value="MEDHUM - Medical Humanities Study Progr">MEDHUM - Medical Humanities Study Progr</option>
<option value="MEDICINE - Medicine">MEDICINE - Medicine</option>
<option value="MEDINFO - Medical Information Sciences">MEDINFO - Medical Information Sciences</option>
<option value="MEDPHY - Medical Physics">MEDPHY - Medical Physics</option>
<option value="MEDREN - Medieval and Renaissance">MEDREN - Medieval and Renaissance</option>
<option value="MENG - Master of Engineering">MENG - Master of Engineering</option>
<option value="MFAEDA - MFA in Experimental & Doc Arts">MFAEDA - MFA in Experimental & Doc Arts</option>
<option value="MGM - Molec Genetics & Microbiology">MGM - Molec Genetics & Microbiology</option>
<option value="MGMTCOM - Management Communications">MGMTCOM - Management Communications</option>
<option value="MGP - Medical Genomics">MGP - Medical Genomics</option>
<option value="MGRECON - Economics">MGRECON - Economics</option>
<option value="MICROBIO - Microbiology">MICROBIO - Microbiology</option>
<option value="MIDIP - MIDIP">MIDIP - MIDIP</option>
<option value="MIDP - Micro and Infect Disease">MIDP - Micro and Infect Disease</option>
<option value="MILITSCI - Military Science (Army ROTC)">MILITSCI - Military Science (Army ROTC)</option>
<option value="MIS - Medical Information Sciences">MIS - Medical Information Sciences</option>
<option value="MMCI - Mstrs in Manage in Cln Info">MMCI - Mstrs in Manage in Cln Info</option>
<option value="MMS - Markets and Management Studies">MMS - Markets and Management Studies</option>
<option value="MOLBPHY - Molecular Biophysics">MOLBPHY - Molecular Biophysics</option>
<option value="MOLCAN - Molecular Cancer Biology">MOLCAN - Molecular Cancer Biology</option>
<option value="MOLMED - Molecular Medicine">MOLMED - Molecular Medicine</option>
<option value="MPS - MPS">MPS - MPS</option>
<option value="MSIS - M of Sci of Info Sci Study Pro">MSIS - M of Sci of Info Sci Study Pro</option>
<option value="MSLS - M of Sci of Lib Sci Study Pro">MSLS - M of Sci of Lib Sci Study Pro</option>
<option value="MUSIC - Music">MUSIC - Music</option>
<option value="NANOSCI - Nanosciences">NANOSCI - Nanosciences</option>
<option value="NAVALSCI - Naval Science (Navy ROTC)">NAVALSCI - Naval Science (Navy ROTC)</option>
<option value="NBP - Neurobiology Study Program">NBP - Neurobiology Study Program</option>
<option value="NCS - Nonlinear and Complex Systems">NCS - Nonlinear and Complex Systems</option>
<option value="NEURO - Neurology">NEURO - Neurology</option>
<option value="NEUROBIO - Neurobiology">NEUROBIO - Neurobiology</option>
<option value="NEUROSCI - Neuroscience">NEUROSCI - Neuroscience</option>
<option | |
<span class="js-select-button-text hidden-select-button-text">
<svg aria-hidden="true" class="octicon octicon-mute" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M8 2.81v10.38c0 .67-.81 1-1.28.53L3 10H1c-.55 0-1-.45-1-1V7c0-.55.45-1 1-1h2l3.72-3.72C7.19 1.81 8 2.14 8 2.81zm7.53 3.22l-1.06-1.06-1.97 1.97-1.97-1.97-1.06 1.06L11.44 8 9.47 9.97l1.06 1.06 1.97-1.97 1.97 1.97 1.06-1.06L13.56 8l1.97-1.97z"/></svg>
Stop ignoring
</span>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</li>
<li>
<div class="js-toggler-container js-social-container starring-container ">
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/SpartanByte/Python_CalculationsExample/unstar" class="starred" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<button
type="submit"
class="btn btn-sm btn-with-count js-toggler-target"
aria-label="Unstar this repository" title="Unstar SpartanByte/Python_CalculationsExample"
data-ga-click="Repository, click unstar button, action:blob#show; text:Unstar">
<svg aria-hidden="true" class="octicon octicon-star" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74z"/></svg>
Unstar
</button>
<a class="social-count js-social-count" href="/SpartanByte/Python_CalculationsExample/stargazers"
aria-label="0 users starred this repository">
0
</a>
</form>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/SpartanByte/Python_CalculationsExample/star" class="unstarred" data-remote="true" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<button
type="submit"
class="btn btn-sm btn-with-count js-toggler-target"
aria-label="Star this repository" title="Star SpartanByte/Python_CalculationsExample"
data-ga-click="Repository, click star button, action:blob#show; text:Star">
<svg aria-hidden="true" class="octicon octicon-star" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M14 6l-4.9-.64L7 1 4.9 5.36 0 6l3.6 3.26L2.67 14 7 11.67 11.33 14l-.93-4.74z"/></svg>
Star
</button>
<a class="social-count js-social-count" href="/SpartanByte/Python_CalculationsExample/stargazers"
aria-label="0 users starred this repository">
0
</a>
</form> </div>
</li>
<li>
<a href="#fork-destination-box" class="btn btn-sm btn-with-count"
title="Fork your own copy of SpartanByte/Python_CalculationsExample to your account"
aria-label="Fork your own copy of SpartanByte/Python_CalculationsExample to your account"
rel="facebox"
data-ga-click="Repository, show fork modal, action:blob#show; text:Fork">
<svg aria-hidden="true" class="octicon octicon-repo-forked" height="16" version="1.1" viewBox="0 0 10 16" width="10"><path fill-rule="evenodd" d="M8 1a1.993 1.993 0 0 0-1 3.72V6L5 8 3 6V4.72A1.993 1.993 0 0 0 2 1a1.993 1.993 0 0 0-1 3.72V6.5l3 3v1.78A1.993 1.993 0 0 0 5 15a1.993 1.993 0 0 0 1-3.72V9.5l3-3V4.72A1.993 1.993 0 0 0 8 1zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3 10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm3-10c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg>
Fork
</a>
<div id="fork-destination-box" style="display: none;">
<h2 class="facebox-header" data-facebox-id="facebox-header">Where should we fork this repository?</h2>
<include-fragment src=""
class="js-fork-select-fragment fork-select-fragment"
data-url="/SpartanByte/Python_CalculationsExample/fork?fragment=1">
<img alt="Loading" height="64" src="https://assets-cdn.github.com/images/spinners/octocat-spinner-128.gif" width="64" />
</include-fragment>
</div>
<a href="/SpartanByte/Python_CalculationsExample/network" class="social-count"
aria-label="0 users forked this repository">
0
</a>
</li>
</ul>
<h1 class="public ">
<svg aria-hidden="true" class="octicon octicon-repo" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M4 9H3V8h1v1zm0-3H3v1h1V6zm0-2H3v1h1V4zm0-2H3v1h1V2zm8-1v12c0 .55-.45 1-1 1H6v2l-1.5-1.5L3 16v-2H1c-.55 0-1-.45-1-1V1c0-.55.45-1 1-1h10c.55 0 1 .45 1 1zm-1 10H1v2h2v-1h3v1h5v-2zm0-10H2v9h9V1z"/></svg>
<span class="author" itemprop="author"><a href="/SpartanByte" class="url fn" rel="author">SpartanByte</a></span><!--
--><span class="path-divider">/</span><!--
--><strong itemprop="name"><a href="/SpartanByte/Python_CalculationsExample" data-pjax="#js-repo-pjax-container">Python_CalculationsExample</a></strong>
</h1>
</div>
<div class="container">
<nav class="reponav js-repo-nav js-sidenav-container-pjax"
itemscope
itemtype="http://schema.org/BreadcrumbList"
role="navigation"
data-pjax="#js-repo-pjax-container">
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a href="/SpartanByte/Python_CalculationsExample" class="js-selected-navigation-item selected reponav-item" data-hotkey="g c" data-selected-links="repo_source repo_downloads repo_commits repo_releases repo_tags repo_branches /SpartanByte/Python_CalculationsExample" itemprop="url">
<svg aria-hidden="true" class="octicon octicon-code" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M9.5 3L8 4.5 11.5 8 8 11.5 9.5 13 14 8 9.5 3zm-5 0L0 8l4.5 5L6 11.5 2.5 8 6 4.5 4.5 3z"/></svg>
<span itemprop="name">Code</span>
<meta itemprop="position" content="1">
</a> </span>
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a href="/SpartanByte/Python_CalculationsExample/issues" class="js-selected-navigation-item reponav-item" data-hotkey="g i" data-selected-links="repo_issues repo_labels repo_milestones /SpartanByte/Python_CalculationsExample/issues" itemprop="url">
<svg aria-hidden="true" class="octicon octicon-issue-opened" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"/></svg>
<span itemprop="name">Issues</span>
<span class="counter">0</span>
<meta itemprop="position" content="2">
</a> </span>
<span itemscope itemtype="http://schema.org/ListItem" itemprop="itemListElement">
<a href="/SpartanByte/Python_CalculationsExample/pulls" class="js-selected-navigation-item reponav-item" data-hotkey="g p" data-selected-links="repo_pulls /SpartanByte/Python_CalculationsExample/pulls" itemprop="url">
<svg aria-hidden="true" class="octicon octicon-git-pull-request" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M11 11.28V5c-.03-.78-.34-1.47-.94-2.06C9.46 2.35 8.78 2.03 8 2H7V0L4 3l3 3V4h1c.27.02.48.11.69.31.21.2.3.42.31.69v6.28A1.993 1.993 0 0 0 10 15a1.993 1.993 0 0 0 1-3.72zm-1 2.92c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zM4 3c0-1.11-.89-2-2-2a1.993 1.993 0 0 0-1 3.72v6.56A1.993 1.993 0 0 0 2 15a1.993 1.993 0 0 0 1-3.72V4.72c.59-.34 1-.98 1-1.72zm-.8 10c0 .66-.55 1.2-1.2 1.2-.65 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2zM2 4.2C1.34 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg>
<span itemprop="name">Pull requests</span>
<span class="counter">0</span>
<meta itemprop="position" content="3">
</a> </span>
<a href="/SpartanByte/Python_CalculationsExample/projects" class="js-selected-navigation-item reponav-item" data-selected-links="repo_projects new_repo_project repo_project /SpartanByte/Python_CalculationsExample/projects">
<svg aria-hidden="true" class="octicon octicon-project" height="16" version="1.1" viewBox="0 0 15 16" width="15"><path fill-rule="evenodd" d="M10 12h3V2h-3v10zm-4-2h3V2H6v8zm-4 4h3V2H2v12zm-1 1h13V1H1v14zM14 0H1a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1V1a1 1 0 0 0-1-1z"/></svg>
Projects
<span class="counter">0</span>
</a>
<a href="/SpartanByte/Python_CalculationsExample/wiki" class="js-selected-navigation-item reponav-item" data-hotkey="g w" data-selected-links="repo_wiki /SpartanByte/Python_CalculationsExample/wiki">
<svg aria-hidden="true" class="octicon octicon-book" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M3 5h4v1H3V5zm0 3h4V7H3v1zm0 2h4V9H3v1zm11-5h-4v1h4V5zm0 2h-4v1h4V7zm0 2h-4v1h4V9zm2-6v9c0 .55-.45 1-1 1H9.5l-1 1-1-1H2c-.55 0-1-.45-1-1V3c0-.55.45-1 1-1h5.5l1 1 1-1H15c.55 0 1 .45 1 1zm-8 .5L7.5 3H2v9h6V3.5zm7-.5H9.5l-.5.5V12h6V3z"/></svg>
Wiki
</a>
<a href="/SpartanByte/Python_CalculationsExample/pulse" class="js-selected-navigation-item reponav-item" data-selected-links="pulse /SpartanByte/Python_CalculationsExample/pulse">
<svg aria-hidden="true" class="octicon octicon-pulse" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M11.5 8L8.8 5.4 6.6 8.5 5.5 1.6 2.38 8H0v2h3.6l.9-1.8.9 5.4L9 8.5l1.6 1.5H14V8z"/></svg>
Pulse
</a>
<a href="/SpartanByte/Python_CalculationsExample/graphs" class="js-selected-navigation-item reponav-item" data-selected-links="repo_graphs repo_contributors /SpartanByte/Python_CalculationsExample/graphs">
<svg aria-hidden="true" class="octicon octicon-graph" height="16" version="1.1" viewBox="0 0 16 16" width="16"><path fill-rule="evenodd" d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"/></svg>
Graphs
</a>
<a href="/SpartanByte/Python_CalculationsExample/settings" class="js-selected-navigation-item reponav-item" data-selected-links="repo_settings repo_branch_settings hooks integration_installations /SpartanByte/Python_CalculationsExample/settings">
<svg aria-hidden="true" class="octicon octicon-gear" height="16" version="1.1" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M14 8.77v-1.6l-1.94-.64-.45-1.09.88-1.84-1.13-1.13-1.81.91-1.09-.45-.69-1.92h-1.6l-.63 1.94-1.11.45-1.84-.88-1.13 1.13.91 1.81-.45 1.09L0 7.23v1.59l1.94.64.45 1.09-.88 1.84 1.13 1.13 1.81-.91 1.09.45.69 1.92h1.59l.63-1.94 1.11-.45 1.84.88 1.13-1.13-.92-1.81.47-1.09L14 8.75v.02zM7 11c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z"/></svg>
Settings
</a>
</nav>
</div>
</div>
<div class="container new-discussion-timeline experiment-repo-nav">
<div class="repository-content">
<a href="/SpartanByte/Python_CalculationsExample/blob/ca3f1af09cc4303a985c8060e284303f6d3d2dc6/Python-CalculationsExample.py" class="d-none js-permalink-shortcut" data-hotkey="y">Permalink</a>
<!-- blob contrib key: blob_contributors:v21:6069fcc90d44f8731d5a8c3bac79fe08 -->
<div class="file-navigation js-zeroclipboard-container">
<div class="select-menu branch-select-menu js-menu-container js-select-menu float-left">
<button class="btn btn-sm select-menu-button js-menu-target css-truncate" data-hotkey="w"
type="button" aria-label="Switch branches or tags" tabindex="0" aria-haspopup="true">
<i>Branch:</i>
<span class="js-select-button css-truncate-target">master</span>
</button>
<div class="select-menu-modal-holder js-menu-content js-navigation-container" data-pjax aria-hidden="true">
<div class="select-menu-modal">
<div class="select-menu-header">
<svg aria-label="Close" class="octicon octicon-x js-menu-close" height="16" role="img" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48z"/></svg>
<span class="select-menu-title">Switch branches/tags</span>
</div>
<div class="select-menu-filters">
<div class="select-menu-text-filter">
<input type="text" aria-label="Find or create a branch…" id="context-commitish-filter-field" class="form-control js-filterable-field js-navigation-enable" placeholder="Find or create a branch…">
</div>
<div class="select-menu-tabs">
<ul>
<li class="select-menu-tab">
<a href="#" data-tab-filter="branches" data-filter-placeholder="Find or create a branch…" class="js-select-menu-tab" role="tab">Branches</a>
</li>
<li class="select-menu-tab">
<a href="#" data-tab-filter="tags" data-filter-placeholder="Find a tag…" class="js-select-menu-tab" role="tab">Tags</a>
</li>
</ul>
</div>
</div>
<div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="branches" role="menu">
<div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring">
<a class="select-menu-item js-navigation-item js-navigation-open selected"
href="/SpartanByte/Python_CalculationsExample/blob/master/Python-CalculationsExample.py"
data-name="master"
data-skip-pjax="true"
rel="nofollow">
<svg aria-hidden="true" class="octicon octicon-check select-menu-item-icon" height="16" version="1.1" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M12 5l-8 8-4-4 1.5-1.5L4 10l6.5-6.5z"/></svg>
<span class="select-menu-item-text css-truncate-target js-select-menu-filter-text">
master
</span>
</a>
</div>
<!-- '"` --><!-- </textarea></xmp> --></option></form><form accept-charset="UTF-8" action="/SpartanByte/Python_CalculationsExample/branches" class="js-create-branch select-menu-item select-menu-new-item-form js-navigation-item js-new-item-form" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="<KEY> /></div>
<svg aria-hidden="true" class="octicon octicon-git-branch select-menu-item-icon" height="16" version="1.1" viewBox="0 0 10 16" width="10"><path fill-rule="evenodd" d="M10 5c0-1.11-.89-2-2-2a1.993 1.993 0 0 0-1 3.72v.3c-.02.52-.23.98-.63 1.38-.4.4-.86.61-1.38.63-.83.02-1.48.16-2 .45V4.72a1.993 1.993 0 0 0-1-3.72C.88 1 0 1.89 0 3a2 2 0 0 0 1 1.72v6.56c-.59.35-1 .99-1 1.72 0 1.11.89 2 2 2 1.11 0 2-.89 2-2 0-.53-.2-1-.53-1.36.09-.06.48-.41.59-.47.25-.11.56-.17.94-.17 1.05-.05 1.95-.45 2.75-1.25S8.95 7.77 9 6.73h-.02C9.59 6.37 10 5.73 10 5zM2 1.8c.66 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2C1.35 4.2.8 3.65.8 3c0-.65.55-1.2 1.2-1.2zm0 12.41c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2zm6-8c-.66 0-1.2-.55-1.2-1.2 0-.65.55-1.2 1.2-1.2.65 0 1.2.55 1.2 1.2 0 .65-.55 1.2-1.2 1.2z"/></svg>
<div class="select-menu-item-text">
<span class="select-menu-item-heading">Create branch: <span class="js-new-item-name"></span></span>
<span class="description">from ‘master’</span>
</div>
<input type="hidden" name="name" id="name" class="js-new-item-value">
<input type="hidden" name="branch" id="branch" value="master">
<input type="hidden" name="path" id="path" value="Python-CalculationsExample.py">
</form>
</div>
<div class="select-menu-list select-menu-tab-bucket js-select-menu-tab-bucket" data-tab-filter="tags">
<div data-filterable-for="context-commitish-filter-field" data-filterable-type="substring">
</div>
<div class="select-menu-no-results">Nothing to show</div>
</div>
</div>
</div>
</div>
<div class="BtnGroup float-right">
<a href="/SpartanByte/Python_CalculationsExample/find/master"
class="js-pjax-capture-input btn btn-sm BtnGroup-item"
data-pjax
data-hotkey="t">
Find file
</a>
<button aria-label="Copy file path to clipboard" class="js-zeroclipboard btn btn-sm BtnGroup-item tooltipped tooltipped-s" data-copied-hint="Copied!" type="button">Copy path</button>
</div>
<div class="breadcrumb js-zeroclipboard-target">
<span class="repo-root js-repo-root"><span class="js-path-segment"><a href="/SpartanByte/Python_CalculationsExample"><span>Python_CalculationsExample</span></a></span></span><span class="separator">/</span><strong class="final-path">Python-CalculationsExample.py</strong>
</div>
</div>
<include-fragment class="commit-tease" src="/SpartanByte/Python_CalculationsExample/contributors/master/Python-CalculationsExample.py">
<div>
Fetching contributors…
</div>
<div class="commit-tease-contributors">
<img alt="" class="loader-loading float-left" height="16" src="https://assets-cdn.github.com/images/spinners/octocat-spinner-32-EAF2F5.gif" width="16" />
<span class="loader-error">Cannot retrieve contributors at this time</span>
</div>
</include-fragment>
<div class="file">
<div class="file-header">
<div class="file-actions">
<div class="BtnGroup">
<a href="/SpartanByte/Python_CalculationsExample/raw/master/Python-CalculationsExample.py" class="btn btn-sm BtnGroup-item" id="raw-url">Raw</a>
<a href="/SpartanByte/Python_CalculationsExample/blame/master/Python-CalculationsExample.py" class="btn btn-sm js-update-url-with-hash BtnGroup-item" data-hotkey="b">Blame</a>
<a href="/SpartanByte/Python_CalculationsExample/commits/master/Python-CalculationsExample.py" class="btn btn-sm BtnGroup-item" rel="nofollow">History</a>
</div>
<a class="btn-octicon tooltipped tooltipped-nw"
href="github-windows://openRepo/https://github.com/SpartanByte/Python_CalculationsExample?branch=master&filepath=Python-CalculationsExample.py"
aria-label="Open this | |
<gh_stars>1-10
# -*- coding: utf-8 -*-
import io
import os
import pytest
import zipfile
from textwrap import dedent
from os.path import join
from .base import BaseTestApp
from .. import run_nbgrader
from ...utils import rmtree
@pytest.fixture
def archive_dir(request, course_dir):
path = os.path.join(course_dir, "downloaded", "ps1", "archive")
os.makedirs(path)
def fin():
rmtree(path)
request.addfinalizer(fin)
return path
def _count_zip_files(path):
with zipfile.ZipFile(path, 'r') as zip_file:
return len(zip_file.namelist())
class TestNbGraderZipCollect(BaseTestApp):
def _make_notebook(self, dest, *args):
notebook = '{}_{}_attempt_{}_{}.ipynb'.format(*args)
self._empty_notebook(join(dest, notebook))
def test_help(self):
"""Does the help display without error?"""
run_nbgrader(["zip_collect", "--help-all"])
def test_args(self):
# Should fail with no assignment id
run_nbgrader(["zip_collect"], retcode=1)
def test_no_archive_dir(self, course_dir):
# Should not fail with no archive_directory
run_nbgrader(["zip_collect", "ps1"])
def test_empty_folders(self, course_dir, archive_dir):
os.makedirs(join(archive_dir, "..", "extracted"))
run_nbgrader(["zip_collect", "ps1"])
assert not os.path.isdir(join(course_dir, "submitted"))
def test_extract_single_notebook(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
run_nbgrader(["zip_collect", "ps1"])
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 1
# Run again should fail
run_nbgrader(["zip_collect", "ps1"], retcode=1)
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 1
# Run again with --force flag should pass
run_nbgrader(["zip_collect", "--force", "ps1"])
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 1
def test_extract_sub_dir_single_notebook(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
self._make_notebook(join(archive_dir, 'hacker'),
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
run_nbgrader(["zip_collect", "ps1"])
assert os.path.isdir(extracted_dir)
assert os.path.isdir(join(extracted_dir, "hacker"))
assert len(os.listdir(join(extracted_dir, "hacker"))) == 1
def test_extract_archive(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted", "notebooks")
archive = join(archive_dir, "notebooks.zip")
self._copy_file(join("files", "notebooks.zip"), archive)
run_nbgrader(["zip_collect", "ps1"])
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == _count_zip_files(archive)
def test_extract_archive_copies(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
archive1 = join(archive_dir, "notebooks.zip")
archive2 = join(archive_dir, "notebooks_copy.zip")
self._copy_file(join("files", "notebooks.zip"), archive1)
self._copy_file(join("files", "notebooks.zip"), archive2)
cnt = 0
run_nbgrader(["zip_collect", "ps1"])
nfiles = _count_zip_files(archive1) + _count_zip_files(archive2)
assert os.path.isdir(extracted_dir)
for _, _, files in os.walk(extracted_dir):
cnt += len(files)
assert cnt == nfiles
def test_collect_no_regexp(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
run_nbgrader(["zip_collect", "--force", "ps1"])
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 1
assert not os.path.isdir(submitted_dir)
def test_collect_bad_regexp(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
with open("nbgrader_config.py", "a") as fh:
fh.write(dedent(
"""
c.FileNameCollectorPlugin.named_regexp = (
r"<NAME> picked ..."
)
"""
))
run_nbgrader(["zip_collect", "--force", "ps1"])
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 1
assert not os.path.isdir(submitted_dir)
def test_collect_regexp_missing_student_id(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
with open("nbgrader_config.py", "a") as fh:
fh.write(dedent(
"""
c.FileNameCollectorPlugin.named_regexp = (
r".+_(?P<foo>\w+)_attempt_(?P<timestamp>[0-9\-]+)_(?P<file_id>\w+)"
)
"""
))
run_nbgrader(["zip_collect", "ps1"], retcode=1)
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 1
assert not os.path.isdir(submitted_dir)
def test_collect_regexp_bad_student_id_type(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
with open('plugin_one.py', 'w') as fh:
fh.write(dedent(
"""
from nbgrader.plugins import FileNameCollectorPlugin
class CustomPlugin(FileNameCollectorPlugin):
def collect(self, submitted_file):
info = super(CustomPlugin, self).collect(submitted_file)
if info is not None:
info['student_id'] = 111
return info
"""
))
with open("nbgrader_config.py", "a") as fh:
fh.write(dedent(
"""
c.ZipCollectApp.collector_plugin = 'plugin_one.CustomPlugin'
c.FileNameCollectorPlugin.named_regexp = (
r".+_(?P<student_id>\w+)_attempt_(?P<timestamp>[0-9\-]+)_(?P<file_id>\w+)"
)
"""
))
run_nbgrader(["zip_collect", "ps1"], retcode=1)
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 1
assert not os.path.isdir(submitted_dir)
def test_collect_single_notebook(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
with open("nbgrader_config.py", "a") as fh:
fh.write(dedent(
"""
c.FileNameCollectorPlugin.named_regexp = (
r".+_(?P<student_id>\w+)_attempt_(?P<timestamp>[0-9\-]+)_(?P<file_id>\w+)"
)
"""
))
run_nbgrader(["zip_collect", "ps1"])
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 1
assert os.path.isdir(submitted_dir)
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'problem1.ipynb'))
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'timestamp.txt'))
assert len(os.listdir(join(submitted_dir, "hacker", "ps1"))) == 2
def test_collect_single_notebook_attempts(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-40-10', 'problem1')
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-50-10', 'problem1')
with open('plugin_two.py', 'w') as fh:
fh.write(dedent(
"""
from nbgrader.plugins import FileNameCollectorPlugin
class CustomPlugin(FileNameCollectorPlugin):
def collect(self, submitted_file):
info = super(CustomPlugin, self).collect(submitted_file)
if info is not None:
info['timestamp'] = '{}-{}-{} {}:{}:{}'.format(
*tuple(info['timestamp'].split('-'))
)
return info
"""
))
with open("nbgrader_config.py", "a") as fh:
fh.write(dedent(
"""
c.ZipCollectApp.collector_plugin = 'plugin_two.CustomPlugin'
c.FileNameCollectorPlugin.named_regexp = (
r".+_(?P<student_id>\w+)_attempt_(?P<timestamp>[0-9\-]+)_(?P<file_id>\w+)"
)
"""
))
run_nbgrader(["zip_collect", "ps1"])
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 3
assert os.path.isdir(submitted_dir)
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'problem1.ipynb'))
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'timestamp.txt'))
assert len(os.listdir(join(submitted_dir, "hacker", "ps1"))) == 2
with open(join(submitted_dir, "hacker", "ps1", 'timestamp.txt')) as ts:
timestamp = ts.read()
assert timestamp == '2016-01-30 15:50:10'
def test_collect_multiple_notebooks(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem2')
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-02-10-15-30-10', 'problem1')
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-02-10-15-30-10', 'problem2')
with open("nbgrader_config.py", "a") as fh:
fh.write(dedent(
"""
c.FileNameCollectorPlugin.named_regexp = (
r".+_(?P<student_id>\w+)_attempt_(?P<timestamp>[0-9\-]+)_(?P<file_id>\w+)"
)
"""
))
output = run_nbgrader(["zip_collect", "ps1"])
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 4
assert os.path.isdir(submitted_dir)
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'problem1.ipynb'))
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'problem2.ipynb'))
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'timestamp.txt'))
assert len(os.listdir(join(submitted_dir, "hacker", "ps1"))) == 3
# Issue #724 - check multiple attempts are collected properly
assert "Skipped submission file" not in output
msg = "Replacing previously collected submission file"
assert sum([msg in line for line in output.splitlines()]) == 2
def test_collect_sub_dir_single_notebook(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
self._make_notebook(join(archive_dir, 'bitdiddle'),
'ps1', 'bitdiddle', '2016-01-30-15-30-10', 'problem1')
with open("nbgrader_config.py", "a") as fh:
fh.write(dedent(
"""
c.FileNameCollectorPlugin.named_regexp = (
r".+_(?P<student_id>\w+)_attempt_(?P<timestamp>[0-9\-]+)_(?P<file_id>\w+)"
)
"""
))
run_nbgrader(["zip_collect", "ps1"])
assert os.path.isdir(extracted_dir)
assert os.path.isdir(submitted_dir)
assert len(os.listdir(submitted_dir)) == 2
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'problem1.ipynb'))
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'timestamp.txt'))
assert len(os.listdir(join(submitted_dir, "hacker", "ps1"))) == 2
assert os.path.isfile(join(submitted_dir, "bitdiddle", "ps1", 'problem1.ipynb'))
assert os.path.isfile(join(submitted_dir, "bitdiddle", "ps1", 'timestamp.txt'))
assert len(os.listdir(join(submitted_dir, "bitdiddle", "ps1"))) == 2
def test_collect_invalid_notebook(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
self._empty_notebook(join(course_dir, 'source', 'ps1', 'problem1.ipynb'))
with open("nbgrader_config.py", "a") as fh:
fh.write(dedent(
"""
c.CourseDirectory.db_assignments = [dict(name="ps1")]
c.FileNameCollectorPlugin.named_regexp = (
r".+_(?P<student_id>\w+)_attempt_(?P<timestamp>[0-9\-]+)_(?P<file_id>\w+)"
)
"""
))
run_nbgrader(["assign", "ps1"])
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'myproblem1')
# Should get collected without --strict flag
run_nbgrader(["zip_collect", "ps1"])
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 1
assert os.path.isdir(submitted_dir)
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'myproblem1.ipynb'))
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'timestamp.txt'))
assert len(os.listdir(join(submitted_dir, "hacker", "ps1"))) == 2
# Re-run with --strict flag
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
run_nbgrader(["zip_collect", "--force", "--strict", "ps1"])
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 2
assert os.path.isdir(submitted_dir)
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'problem1.ipynb'))
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'timestamp.txt'))
assert len(os.listdir(join(submitted_dir, "hacker", "ps1"))) == 2
def test_collect_timestamp_none(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
with open("nbgrader_config.py", "a") as fh:
fh.write(dedent(
"""
c.FileNameCollectorPlugin.named_regexp = (
r".+_(?P<student_id>\w+)_attempt_(?P<blarg>[0-9\-]+)_(?P<file_id>\w+)"
)
"""
))
run_nbgrader(["zip_collect", "ps1"])
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 1
assert os.path.isdir(submitted_dir)
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'problem1.ipynb'))
assert not os.path.isfile(join(submitted_dir, "hacker", "ps1", 'timestamp.txt'))
assert len(os.listdir(join(submitted_dir, "hacker", "ps1"))) == 1
def test_collect_timestamp_empty_str(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
with open('plugin_three.py', 'w') as fh:
fh.write(dedent(
"""
from nbgrader.plugins import FileNameCollectorPlugin
class CustomPlugin(FileNameCollectorPlugin):
def collect(self, submitted_file):
info = super(CustomPlugin, self).collect(submitted_file)
if info is not None:
info['timestamp'] = ""
return info
"""
))
with open("nbgrader_config.py", "a") as fh:
fh.write(dedent(
"""
c.ZipCollectApp.collector_plugin = 'plugin_three.CustomPlugin'
c.FileNameCollectorPlugin.named_regexp = (
r".+_(?P<student_id>\w+)_attempt_(?P<timestamp>[0-9\-]+)_(?P<file_id>\w+)"
)
"""
))
run_nbgrader(["zip_collect", "ps1"])
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 1
assert os.path.isdir(submitted_dir)
assert os.path.isfile(join(submitted_dir, "hacker", "ps1", 'problem1.ipynb'))
assert not os.path.isfile(join(submitted_dir, "hacker", "ps1", 'timestamp.txt'))
assert len(os.listdir(join(submitted_dir, "hacker", "ps1"))) == 1
def test_collect_timestamp_bad_str(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
self._make_notebook(archive_dir,
'ps1', 'hacker', '2016-01-30-15-30-10', 'problem1')
with open('plugin_four.py', 'w') as fh:
fh.write(dedent(
"""
from nbgrader.plugins import FileNameCollectorPlugin
class CustomPlugin(FileNameCollectorPlugin):
def collect(self, submitted_file):
info = super(CustomPlugin, self).collect(submitted_file)
if info is not None:
info['timestamp'] = "I'm still trying to be a timestamp str"
return info
"""
))
with open("nbgrader_config.py", "a") as fh:
fh.write(dedent(
"""
c.ZipCollectApp.collector_plugin = 'plugin_four.CustomPlugin'
c.FileNameCollectorPlugin.named_regexp = (
r".+_(?P<student_id>\w+)_attempt_(?P<timestamp>[0-9\-]+)_(?P<file_id>\w+)"
)
"""
))
run_nbgrader(["zip_collect", "ps1"], retcode=1)
assert os.path.isdir(extracted_dir)
assert len(os.listdir(extracted_dir)) == 1
assert not os.path.isdir(submitted_dir)
def test_collect_timestamp_skip_older(self, course_dir, archive_dir):
extracted_dir = join(archive_dir, "..", "extracted")
submitted_dir = join(course_dir, "submitted")
# submissions are sorted so a before b
os.makedirs(join(archive_dir, 'ps1_hacker_a_2017-01-30-15-30-10'))
with io.open(join(archive_dir, 'ps1_hacker_a_2017-01-30-15-30-10', 'problem1.ipynb'), mode='w', encoding='utf-8') as fh:
fh.write(u'')
os.makedirs(join(archive_dir, 'ps1_hacker_b_2016-01-30-15-30-10'))
with io.open(join(archive_dir, 'ps1_hacker_b_2016-01-30-15-30-10', 'problem1.ipynb'), mode='w', encoding='utf-8') as fh:
fh.write(u'')
with open('plugin_five.py', 'w') as fh:
fh.write(dedent(
"""
from nbgrader.plugins import FileNameCollectorPlugin
class CustomPlugin(FileNameCollectorPlugin):
def collect(self, submitted_file):
info = super(CustomPlugin, self).collect(submitted_file)
if info is not None:
info['timestamp'] = '{}-{}-{} {}:{}:{}'.format(
*tuple(info['timestamp'].split('-'))
)
return info
"""
))
with open("nbgrader_config.py", "a") as fh:
fh.write(dedent(
"""
c.ZipCollectApp.collector_plugin = 'plugin_five.CustomPlugin'
c.FileNameCollectorPlugin.valid_ext = ['.ipynb', '.txt']
c.FileNameCollectorPlugin.named_regexp = (
r".+ps1_(?P<student_id>\w+)_[a|b]_(?P<timestamp>[0-9\-]+)\W+(?P<file_id>.+)"
)
"""
))
run_nbgrader(["zip_collect", "ps1"])
| |
<reponame>fegonda/icon_demo
import cPickle
import gzip
import os
import sys
import time
import numpy
import numpy as np
import theano
import theano.tensor as T
from scipy.ndimage.interpolation import shift
base_path = os.path.dirname(__file__)
sys.path.insert(1,os.path.join(base_path, '../'))
sys.path.insert(2,os.path.join(base_path, '../../common'))
sys.path.insert(3,os.path.join(base_path, '../../database'))
print 'mlp path:', base_path
from db import DB
from paths import Paths
from utility import Utility
from hiddenlayer import HiddenLayer
from logistic_sgd import LogisticRegression
from generateTrainValTestData import gen_data_supervised, shared_dataset, normalizeImage, stupid_map_wrapper
import multiprocessing
from vsk_utils import shared_single_dataset
from activation_functions import rectified_linear
import smtplib
import getpass
class MLP(object):
def __init__(
self,
rng,
input,
n_in=None,
n_hidden=None,
n_out=2,
path=None,
id=None,
offline=False,
batch_size=None,
patch_size=None,
train_time=5.0,
learning_rate=0.1,
momentum=0.9,
activation=rectified_linear):
self.n_out = n_out
self.n_in = n_in
self.n_hidden = n_hidden
self.input = input
self.x = input
self.id = id
self.type = 'MLP'
self.offline = offline
self.rng = rng
self.done = False
self.path = path
self.activation = activation
self.hiddenSizes = n_hidden
self.batchSize = batch_size
self.patchSize = patch_size
self.hiddenSizes = n_hidden
self.learning_rate = learning_rate
self.momentum = momentum
self.trainTime = train_time
self.resample = False
self.best_validation_loss = numpy.inf
self.best_train_error = np.inf
self.revision = DB.getRevision( self.id )
self.initialize()
def get_path(self):
if self.offline:
return self.path
rev = DB.getRevision( self.id )
path = '%s/best_%s.%s.%d.pkl'%(Paths.Models, self.id, self.type, rev )
return path.lower()
def initialize(self):
self.hiddenLayers = []
self.params = []
input = self.input
rng = self.rng
n_out = self.n_out
path = self.get_path()
fromFile = (path is not None) and os.path.exists( path )
if fromFile:
with open(path, 'r') as file:
print 'loading mlp file from file...', path
d = cPickle.load(file)
savedhiddenLayers = d[0]
saved_logRegressionLayer = d[1]
self.n_in = d[2]
self.n_hidden = d[3]
next_input = input
next_n_in = self.n_in
print 'self.n_hidden:', self.n_hidden
for n_h in self.n_hidden:
hl = HiddenLayer(rng=rng, input=next_input,
n_in=next_n_in, n_out=n_h,
activation=self.activation)
next_input = hl.output
next_n_in = n_h
self.hiddenLayers.append(hl)
self.params += hl.params
self.logRegressionLayer = LogisticRegression(
input=self.hiddenLayers[-1].output,
n_in=self.n_hidden[-1],
n_out=n_out)
self.params += self.logRegressionLayer.params
self.negative_log_likelihood = self.logRegressionLayer.negative_log_likelihood
self.errors = self.logRegressionLayer.errors
self.p_y_given_x = self.logRegressionLayer.p_y_given_x
self.y_pred = self.logRegressionLayer.y_pred
if fromFile:
for hl, shl in zip(self.hiddenLayers, savedhiddenLayers):
hl.W.set_value(shl.W.get_value())
hl.b.set_value(shl.b.get_value())
self.logRegressionLayer.W.set_value(saved_logRegressionLayer.W.get_value())
self.logRegressionLayer.b.set_value(saved_logRegressionLayer.b.get_value())
self.cost = self.negative_log_likelihood
def save(self):
path = self.path
revision = 0
if not self.offline:
revision = DB.getRevision( self.id )
revision = (revision+1)%10
path = '%s/best_%s.%s.%d.pkl'%(Paths.Models, self.id, self.type, revision)
path = path.lower()
print 'saving...', path
with open(path, 'wb') as file:
cPickle.dump((
self.hiddenLayers,
self.logRegressionLayer,
self.n_in,
self.n_hidden), file)
if not self.offline:
DB.finishSaveModel( self.id, revision )
def get_patch_size(self):
return np.int(np.sqrt(self.hiddenLayers[0].W.eval().shape[0]))
def predict_image(self, x, img, normMean=None, norm_std=None):
start_time = time.clock()
row_range = 1
img = normalizeImage(img)
imSize = np.shape(img)
membraneProbabilities = np.zeros(1024*1024, dtype=int )
patchSize = np.int(np.sqrt(self.hiddenLayers[0].W.eval().shape[0]))
data_shared = shared_single_dataset(np.zeros((imSize[0]*row_range,patchSize**2)), borrow=True)
classify = theano.function(
[],
self.logRegressionLayer.y_pred,
givens={x: data_shared}
)
for row in xrange(0,1024,row_range):
if row%100 == 0:
print row
data = generate_patch_data_rows(img, rowOffset=row, rowRange=row_range, patchSize=patchSize, imSize=imSize, data_mean=normMean, data_std=norm_std)
data_shared.set_value(np.float32(data))
membraneProbabilities[row*1024:row*1024+row_range*1024] = classify()
end_time = time.clock()
total_time = (end_time - start_time)
print >> sys.stderr, ('Running time: ' +
'%.2fm' % (total_time / 60.))
return np.array(membraneProbabilities)
def classify(self, image, mean=None, std=None):
#imSize = (1024,1024)
imSize = np.shape(image)
print 'imSize:', imSize
image = Utility.pad_image( image, self.patchSize )
imSizePadded = np.shape(image)
print 'mlp.classify mean:', mean, 'std:', std
start_time = time.clock()
row_range = 1
#imSize = np.shape(image)
#membraneProbabilities = np.zeros(np.shape(image))
membraneProbabilities = np.zeros(imSize)
patchSize = np.int(np.sqrt(self.hiddenLayers[0].W.eval().shape[0]))
print 'imSize:', imSize
print 'imSizePadded:', imSizePadded
print 'mp:', np.shape(membraneProbabilities)
data_shared = shared_single_dataset(np.zeros((imSize[0]*row_range,patchSize**2)), borrow=True)
classify = theano.function(
[],
self.p_y_given_x,
givens={self.x: data_shared}
)
for row in xrange(0,1024,row_range):
if row%100 == 0:
print row
#data = Utility.get_patch(image, row, row_range, patchSize )
#print 'data shape:', data.shape
'''
data = Utility.generate_patch_data_rows(
image,
rowOffset=row,
rowRange=row_range,
patchSize=patchSize,
imSize=imSizePadded,
data_mean=mean,
data_std=std)
'''
data = Utility.get_patch(
image,
row,
row_range,
patchSize,
data_mean=mean,
data_std=std)
#print 'data:', np.shape(data)
data_shared.set_value(np.float32(data))
result = classify()
#print 'results:', np.shape(result)
membraneProbabilities[row,:] = result[:,0]
end_time = time.clock()
total_time = (end_time - start_time)
print >> sys.stderr, ('Running time: ' +
'%.2fm' % (total_time / 60.))
return np.array(membraneProbabilities)
def predict(self, image, mean=None, std=None, threshold=0.5):
prob = self.classify( image, mean=mean, std=std)
prob = self.threshold( prob, factor=threshold )
prob = prob.astype(dtype=int)
prob = prob.flatten()
return prob
def threshold(self, prob, factor=0.5):
prob[ prob > factor ] = 9
prob[ prob <= factor ] = 1
prob[ prob == 9 ] = 0
return prob
def reportTrainingStats(self, elapsedTime, batchIndex, valLoss, trainCost, mode=0):
if not self.offline:
DB.storeTrainingStats( self.id, valLoss, trainCost, mode=mode)
msg = '(%0.1f) %i %f%%'%\
(
elapsedTime,
batchIndex,
valLoss
)
status = '[%f]'%(trainCost)
Utility.report_status( msg, status )
def oldtrain(self, offline=False, data=None, mean=None,std=None):
if offline:
self.train_offline(data=data, mean=mean, std=std)
else:
self.train_online(data)
def train_online(self, data):
print 'train online...'
def gradient_updates_momentum(cost, params, learning_rate, momentum):
updates = []
for param in params:
param_update = theano.shared(param.get_value()*0., broadcastable=param.broadcastable)
updates.append((param, param - learning_rate*param_update))
updates.append((param_update, momentum*param_update + (1. - momentum)*T.grad(cost, param)))
return updates
# DATA INITIALIZATION
d = data.sample()
train_x = d[0]
train_y = d[1]
valid_x = d[2]
valid_y = d[3]
reset = d[4]
if reset:
self.best_validation_loss = numpy.inf
train_samples = len(train_y)
valid_samples = len(valid_y)
print 'valid_samples:',valid_samples
print 'train_samples:', train_samples
if self.resample:
self.lr_shared.set_value( np.float32(self.learning_rate) )
self.m_shared.set_value( np.float32(self.momentum) )
else:
self.resample = True
self.y = T.ivector('y') # the labels are presented as 1D vector of [int] labels
self.lr = T.scalar('learning_rate')
self.m = T.scalar('momentum')
self.lr_shared = theano.shared(np.float32(self.learning_rate))
self.m_shared = theano.shared(np.float32(self.momentum))
index = T.lscalar() # index to a [mini]batch
x = self.x
y = self.y
lr = self.lr
m = self.m
lr_shared = self.lr_shared
m_shared = self.m_shared
patchSize = self.patchSize
batchSize = self.batchSize
train_set_x, train_set_y = shared_dataset((train_x, train_y), doCastLabels=True)
if valid_samples > 0:
valid_set_x, valid_set_y = shared_dataset((valid_x, valid_y), doCastLabels=True)
# compute number of minibatches for training, validation
n_train_batches = train_samples / batchSize
n_valid_batches = valid_samples / batchSize
#BUILD THE MODEL
cost = self.cost(y)
if valid_samples > 0:
validate_model = theano.function(
[index],
self.errors(y),
givens={
x: valid_set_x[index * batchSize: (index + 1) * batchSize],
y: valid_set_y[index * batchSize: (index + 1) * batchSize]
}
)
'''
predict_samples = theano.function(
inputs=[index],
outputs=T.neq(self.y_pred, self.y),
givens={
x: train_set_x[index * batchSize: (index + 1) * batchSize],
y: train_set_y[index * batchSize: (index + 1) * batchSize]
}
)
'''
predict_samples = theano.function(
[],
outputs=T.neq(self.y_pred, self.y),
givens={
x: train_set_x,
y: train_set_y,
}
)
gparams = []
for param in self.params:
gparam = T.grad(cost, param)
gparams.append(gparam)
updates = gradient_updates_momentum(cost, self.params, lr, m)
train_model = theano.function(inputs=[index], outputs=cost,
updates=updates,
givens={
x: train_set_x[index * batchSize:(index + 1) * batchSize],
y: train_set_y[index * batchSize:(index + 1) * batchSize],
lr: lr_shared,
m: m_shared})
# TRAIN THE MODEL
print '... training'
print 'self.best_validation_loss:', self.best_validation_loss
best_iter = 0
validation_frequency = 1
start_time = time.clock()
elapsed_time = 0
iter = 0
minibatch_avg_costs = []
minibatch_index = 0
#while (elapsed_time < self.trainTime)\
# and (minibatch_index<n_train_batches)\
# and (not self.done):
while (minibatch_index<n_train_batches) and (not self.done):
if (elapsed_time >= self.trainTime):
break
train_cost = train_model(minibatch_index)
# test the trained samples against the target
# values to measure the training performance
i = minibatch_index
'''
probs = predict_samples(minibatch_index)
#print 'probs:', probs.shape
i_batch = data.i_train[ i * batchSize:(i+1)*batchSize ]
data.p[ i_batch ] = probs
'''
'''
good = np.where( probs == 0)[0]
bad = np.where( probs == 1)[0]
print 'bad:', len(bad)
print 'good:', len(good)
#print probs
'''
#print '----->traincost:', type(train_cost), train_cost
minibatch_avg_costs.append(train_cost)
iter += 1
#iter = (epoch - 1) * n_train_batches + minibatch_index
if (iter + 1) % validation_frequency == 0 and valid_samples > 0:
validation_losses = np.array([validate_model(i) for i in xrange(n_valid_batches)])
this_validation_loss = numpy.sum(validation_losses) * 100.0 / valid_samples
elapsed_time = time.clock() - start_time
'''
self.reportTrainingStats(elapsed_time,
minibatch_index,
this_validation_loss,
minibatch_avg_costs[-1].item(0))
'''
print this_validation_loss, '/', self.best_validation_loss
data.add_validation_loss( this_validation_loss )
# if we got the best validation score until now
if this_validation_loss < self.best_validation_loss:
self.best_validation_loss = this_validation_loss
best_iter = iter
self.save()
print "New best score!"
# advance to next mini batch
minibatch_index += 1
# update elapsed time
elapsed_time = time.clock() - start_time
if valid_samples == 0:
self.save()
probs = predict_samples()
data.p[ data.i_train ] = probs
elapsed_time = time.clock() - start_time
msg = 'The code an for'
status = '%f seconds' % (elapsed_time)
Utility.report_status( msg, status )
print 'done...'
def train(self,
offline=False,
data=None,
mean=None,
std=None
):
print 'mlp.train'
def gradient_updates_momentum(cost, params, learning_rate, momentum):
updates = []
for param in params:
param_update = theano.shared(param.get_value()*0., broadcastable=param.broadcastable)
| |
<filename>pronaHotMod/lib_parser.py
import math
import sys
import re
class ParseError(Exception): pass #To indicate a parsing error
class EmptyError(Exception): pass #To indicate empty data passed to the parser
class NoResultError(Exception): pass #To indicate that a method did not feel like producing a result, used in parse_psic()
def parse_sequence(d_in, d_fasta):
"""
pp returns two sequence files: query.in and query.fasta. No idea why.
Here we check that both are the same and return the sequence.
"""
seq_in = ''
seq_fasta = ''
for line in d_in.split('\n')[1:]:
if not line: continue
seq_in += line
for line in d_fasta.split('\n')[1:]:
if not line: continue
seq_fasta += ''.join(line.split()) #Get rid of those strange whitespaces within the sequence!
if seq_in != seq_fasta:
sys.exit("Error!!!ProNAhot can not be done for protein %s.\nProtein sequence of *in and * fasta are not identical.\npp seems to work with different sequences.\n" % d_fasta.split('\n')[0][1:])
return {'seq':seq_in},d_fasta.split('\n')[0][1:]
def parse_blast_reorder(d_blast):
ori_order='ARNDCQEGHILKMFPSTWYV'
#ress
new_order='RKDEQNHSTYCWAILMFVPG'
#res
# new_order='AVLIPFWMGSTCYNQDEKRH'
if d_blast == '':
raise EmptyError('Empty pssm file!')
pssm_mat = []
perc_mat = []
inf_per_pos = []
rel_weight = []
pssm_seq = ''
#First turn pssm into a matrix we can handle
for line in d_blast.split('\n'):
tokens = line.split()
if len(tokens) == 40 and line.strip() != 'A R N D C Q E G H I L K M F P S T W Y V A R N D C Q E G H I L K M F P S T W Y V':
raise ParseError("It seems that we have an issue now. Blast produces columns with altering meanings!")
if len(tokens) != 44: continue
pssm_seq += tokens[1]
inf_per_pos.append( float(tokens[42]) ) #The second last column in the blast output
rel_weight.append( float(tokens[43]) ) #The very last column
#The first matrix i.e. pssm
pssm_mat_row = []
tmp={}
for ind in range(len(ori_order)):
tmp[ori_order[ind]]=tokens[2:22][ind]
for r in new_order:
pssm_mat_row.append(int(tmp[r]))
#The second one, i.e. the percentages
perc_mat_row = []
tmp={}
for ind in range(len(ori_order)):
tmp[ori_order[ind]]=tokens[22:42][ind]
for r in new_order:
perc_mat_row.append(int(tmp[r]))
#Check if we are really dealing with 20 values here!
if len(pssm_mat_row) != 20 or len(perc_mat_row) != 20:
raise ParseError("It seems that we have a situation now. The expected amount of columns is 20, found: %s!" % len(pssm_mat_row))
pssm_mat.append(pssm_mat_row)
perc_mat.append(perc_mat_row)
#Further consistency check...
if len(pssm_mat) != len(pssm_seq) != len(perc_mat) != len(inf_per_pos) != len(rel_weight):
raise ParseError("It seems that we have an issue now. Something went wrong during parsing the pssm matrix!")
return {'seq':pssm_seq, 'pssm':pssm_mat, 'perc':perc_mat, 'inf_per_pos':inf_per_pos, 'rel_weight':rel_weight}
def parse_consurf(consurf):
if consurf == '':
raise EmptyError('Empty consurf file!')
out1 = []
out2 = []
for line in consurf.split('\n'):
tokens = line.split('\t')
if len(tokens) < 6 or 'COLOR' in line: continue
out1.append( float(tokens[2]) )
out2.append( float(tokens[4].lstrip()[0]) )
#Consistency check
if len(out1) != len(out2):
raise ParseError("Something happened! consurf returns different column lengths!")
return {'consurf_score':out1, 'consurf_color':out2}
def parse_blast(d_blast):
"""
Note that we do not parse out the weighted observed percentages part.
Meaning of pssm columns:
A R N D C Q E G H I L K M F P S T W Y V
Returns a dictionary with keys as follows:
'seq': The sequence as blast sees it
'pssm': pssm matrix as a list of lists. Each sublist represents a row in the PSSM matrix.
'perc': perc matrix
'inf_per_pos': The second last column in the blast output
'rel_weight': The last column
"""
if d_blast == '':
raise EmptyError('Empty pssm file!')
pssm_mat = []
perc_mat = []
inf_per_pos = []
rel_weight = []
pssm_seq = ''
#First turn pssm into a matrix we can handle
for line in d_blast.split('\n'):
tokens = line.split()
if len(tokens) == 40 and line.strip() != 'A R N D C Q E G H I L K M F P S T W Y V A R N D C Q E G H I L K M F P S T W Y V':
raise ParseError("It seems that we have an issue now. Blast produces columns with altering meanings!")
if len(tokens) != 44: continue
pssm_seq += tokens[1]
inf_per_pos.append( float(tokens[42]) ) #The second last column in the blast output
rel_weight.append( float(tokens[43]) ) #The very last column
#The first matrix i.e. pssm
pssm_mat_row = []
for t in tokens[2:22]:
pssm_mat_row.append(int(t))
#The second one, i.e. the percentages
perc_mat_row = []
for t in tokens[22:42]:
perc_mat_row.append(int(t))
#Check if we are really dealing with 20 values here!
if len(pssm_mat_row) != 20 or len(perc_mat_row) != 20:
raise ParseError("It seems that we have a situation now. The expected amount of columns is 20, found: %s!" % len(pssm_mat_row))
pssm_mat.append(pssm_mat_row)
perc_mat.append(perc_mat_row)
#Further consistency check...
if len(pssm_mat) != len(pssm_seq) != len(perc_mat) != len(inf_per_pos) != len(rel_weight):
raise ParseError("It seems that we have an issue now. Something went wrong during parsing the pssm matrix!")
return {'seq':pssm_seq, 'pssm':pssm_mat, 'perc':perc_mat, 'inf_per_pos':inf_per_pos, 'rel_weight':rel_weight}
def parse_psic(d_psic):
"""
Unfortunately, psic returns no sequence.
Meaning of psic's columns:
A R N D C Q E G H I L K M F P S T W Y V NumSeq
This is exactly what could be found in the sublist of each residue.
Returns a dictionary with keys as follows:
'psic': psic matrix as a list of lists. Each sublist represents a row in the psic matrix.
'NumSeq': the very last column, denoting NumSeq i.e. number of aligned sequences at that pos
"""
if d_psic == '':
raise EmptyError('Empty psic file!')
elif d_psic.startswith('sequence too short'):
raise NoResultError('Sequence seems to be too short for psic. No psic output found.')
psic_mat = []
numseq = []
for line in d_psic.split('\n'):
if line.startswith('Pos') or line == '': continue
tokens = line.split()
if len(tokens) != 22:
raise ParseError('"It seems that we have a situation now. The expected amount of columns is 22, found: %s!" % len(tokens)')
psic_mat_row = [ float(t) for t in tokens[1:21] ]
numseq.append( int(tokens[21]) ) #The last column is an integer denoting the amount of aligned seqs at that pos.
psic_mat.append(psic_mat_row) #Now glue the current column to the matrix
#Check!
if len(psic_mat) != len(numseq):
raise ParseError("It seems that we have an issue now. Something went wrong during parsing the psic matrix!")
return {'psic':psic_mat, 'NumSeq':numseq}
def parse_disis(d_disis):
"""
Returns a dictionary with keys as follows:
'seq': The sequence as disis sees it
'prd_bin': binary prdct
'prd_raw': raw prdct
"""
if d_disis == '':
raise EmptyError('Empty disis file!')
disis_seq_binprd = [] #Sequence parsed out of the binary prediction part
disis_seq_rawprd = [] #...parsed out of the raw (numeric) predictions
disis_prd_bin = [] #Binary predictions
disis_prd_raw = [] #Raw numeric predictions
cnt = 0
for line in d_disis.split('\n'):
if line == '': continue
tokens = line.split()
if len(tokens) == 1: #We are in the upper part of disis' output, i.e. the binary predictions
if cnt % 2 == 0:
disis_seq_binprd.extend( list(line) )
else:
disis_prd_bin.extend( list(line.replace('P','+')) )
elif len(tokens) == 2: #Now we are in the lower part, i.e. the numeric outputs of disis
disis_seq_rawprd.append( tokens[0] )
disis_prd_raw.append( int(tokens[1]) )
cnt += 1
#Now do some consistency checks
if disis_seq_binprd != disis_seq_rawprd:
raise ParseError("It seems that we have an issue now. Disis returns different sequences in the upper and lower part!")
if len(disis_seq_binprd) != len(disis_prd_bin) != len(disis_prd_raw):
raise ParseError("It seems that we have an issue now. Parsed datastructures have different lengths!")
return {'seq':''.join(disis_seq_binprd), 'prd_bin':disis_prd_bin, 'prd_raw':disis_prd_raw}
def parse_isis(d_isis):
"""
Returns a dictionary with keys as follows:
'seq': The sequence as isis sees it
'prd_bin': binary prdct
'prd_raw': raw prdct
"""
if d_isis == '':
raise EmptyError('Empty isis file!')
isis_seq_binprd = [] #Sequence parsed out of the binary prediction part
isis_seq_rawprd = [] #...parsed out of the raw (numeric) predictions
isis_prd_bin = [] #Binary predictions
isis_prd_raw = [] #Raw numeric predictions
cnt = 0
for line in d_isis.split('\n'):
if line == '' or line.startswith('>'): continue
tokens = line.split()
if len(tokens) == 1: #We are in the upper part of disis' output, i.e. the binary predictions
if cnt % 2 == 0:
isis_seq_binprd.extend( list(line) )
else:
isis_prd_bin.extend( list(line.replace('P','+')) )
elif len(tokens) == 3: #Now we are in the lower part, i.e. the numeric outputs of disis
isis_seq_rawprd.append( tokens[1] )
isis_prd_raw.append( int(tokens[2]) )
cnt += 1
#Now do some consistency checks
if isis_seq_binprd != isis_seq_rawprd:
raise ParseError("It seems that we have an issue now. Isis returns different sequences in the upper and lower part!")
if len(isis_seq_binprd) != len(isis_prd_bin) != len(isis_prd_raw):
raise ParseError("It seems that we have an issue now. Parsed datastructures have different lengths!")
return {'seq':''.join(isis_seq_binprd), 'prd_bin':isis_prd_bin, 'prd_raw':isis_prd_raw}
def parse_md(d_md):
"""
Returns a dictionary with keys as follows:
'seq': sequence as MD sees it
'norsnet_raw': raw norsnet prdct
'norsnet_bin': binary norsnet prdct
'bval_raw': raw bval prdct
'bval_bin': binary bval prdct
'ucon_raw': raw ucon prdct
'ucon_bin': binary ucon prdct
'prd_raw': MD's raw prdct
'prd_ri': MD's reliability index
'prd_bin': MD's binary prdct
"""
if d_md == '':
raise EmptyError('Empty md file!')
md_seq = []
md_norsnet_raw = []
md_norsnet_bin = []
md_bval_raw = []
md_bval_bin = []
md_ucon_raw = []
md_ucon_bin = []
md_raw = []
md_ri = []
md_bin = []
for line in d_md.split('\n'):
if line.startswith('Number'): continue #The header
if line == '': break #We reached the end of the output block
tokens = line.split()
if len(tokens) != 11:
raise ParseError("It seems that we have an issue now. MD returned an unexpected number of columns!")
md_seq.append( tokens[1] )
md_norsnet_raw.append( float(tokens[2]) )
md_norsnet_bin.append( tokens[3].replace('D','+') )
md_bval_raw.append( float(tokens[4]) )
md_bval_bin.append( tokens[5].replace('D','+') )
md_ucon_raw.append( float(tokens[6]) )
md_ucon_bin.append( tokens[7].replace('D','+') )
md_raw.append( float(tokens[8]) )
md_ri.append( int(tokens[9]) )
md_bin.append( tokens[10].replace('D','+') )
#Check it!
if len(md_seq) != len(md_norsnet_raw) != len(md_norsnet_bin) != len(md_bval_raw) != len(md_bval_bin) != len(md_ucon_raw) != len(md_ucon_bin) != len(md_raw) != len(md_ri) != len(md_bin):
raise ParseError("It seems that we have an issue now. MD returned unequal column lengths!")
return {'seq':''.join(md_seq), 'norsnet_raw':md_norsnet_raw, 'norsnet_bin':md_norsnet_bin, 'bval_raw':md_bval_raw, 'bval_bin':md_bval_bin, 'ucon_raw':md_ucon_raw, 'ucon_bin':md_ucon_bin, 'prd_raw':md_raw, 'prd_ri':md_ri, 'prd_bin':md_bin}
def parse_profsecacc(d_prof):
"""
Returns a dictionary where keys have the same designation as | |
<gh_stars>1-10
#!/usr/bin/env python
# coding: utf-8
# # Lexical normalization pipeline
#
# author - <NAME>
# date - 15-7-2019
#
# Python 3 script
#
# This pipeline takes raw text data and performs:
# - Removes URLs, email addresses
# - Tokenization with NLTK
# - Removes non_English posts (conservatively) using langid module with top 10 languages and threshold of 100
# - British English to American English
# - Normalization of contractions
# - Normalization of generic abbreviations and slang
# - Normalization of domain-specific (patient forum) abbreviations
# - Spelling correction
# In[1]:
import pickle
import numpy as np
import random
import pandas as pd
from collections import Counter, defaultdict, OrderedDict
from nltk import pos_tag, word_tokenize
import re
import seaborn as sns
import matplotlib.pyplot as plt
import editdistance
import kenlm
from sklearn.metrics import recall_score, precision_score, f1_score, fbeta_score
from nltk.tokenize.treebank import TreebankWordDetokenizer
from gensim.models import KeyedVectors
import langid
# In[2]:
class Normalizer ():
def __init__(self):
pass
#to use this function the files need to be sorted in the same folder as the script under /obj_lex/
def load_obj(self, name):
with open('obj_lex\\' + name + '.pkl', 'rb') as f:
return pickle.load(f, encoding='latin1')
def load_files(self):
self.abbr_dict = self.load_obj ('abbreviations_dict')
self.aspell_dict = self.load_obj ('aspell_dict_lower')
self.short_expanse_dict = self.load_obj ('short_expansions_dict')
self.cList = self.load_obj ('contractionslistone')
self.cList2 = self.load_obj ('contractionslisttwo')
self.drugnames = self.load_obj ('fdadrugslist')
def change_tup_to_list(self, tup):
thelist = list(tup)
return thelist
def change_list_to_tup(self,thelist):
tup = tuple(thelist)
return tup
#---------Remove URls, email addresses and personal pronouns ------------------
def replace_urls(self,list_of_msgs):
list_of_msgs2 = []
for msg in list_of_msgs:
nw_msg = re.sub(
r'\b' + r'((\(<{0,1}https|\(<{0,1}http|\[<{0,1}https|\[<{0,1}http|<{0,1}https|<{0,1}http)(:|;| |: )\/\/|www.)[\w\.\/#\?\=\+\;\,\&\%_\n-]+(\.[a-z]{2,4}\]{0,1}\){0,1}|\.html\]{0,1}\){0,1}|\/[\w\.\?\=#\+\;\,\&\%_-]+|[\w\/\.\?\=#\+\;\,\&\%_-]+|[0-9]+#m[0-9]+)+(\n|\b|\s|\/|\]|\)|>)',
'-URL-', msg)
list_of_msgs2.append(nw_msg)
return list_of_msgs2
def replace_email(self,list_of_msgs):
list_of_msgs2 = []
for msg in list_of_msgs:
nw_msg = re.sub (r"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+[. ])", ' ', msg) #remove email
nw_msg2 = re.sub (r"(@[a-zA-Z0-9]+[. ])", ' ', nw_msg) #remove usernames
# nw_msg3 = re.sub(r"(@ [a-zA-Z0-9]+[. ])", ' ', nw_msg2) #remove usernames
list_of_msgs2.append(nw_msg2)
return list_of_msgs2
def remove_empty (self,list_of_msgs):
empty = []
check_msgs3 =[]
for a, i in enumerate (list_of_msgs):
if len(i) == 0:
print('empty')
else:
check_msgs3.append(i)
return check_msgs3
def remove_registered_icon (self, msg):
nw_msg = re.sub ('\u00AE', '', msg)
nw_msg2 = re.sub ('\u00E9', 'e', nw_msg)
return nw_msg2
def escape_char (self, msg):
msg1 = msg.replace('\x08', '')
msg2 = msg1.replace ('\x8d', '')
msg3 = msg2.replace('ðŸ', '')
return msg3
def anonymize (self, posts):
posts2 = self.replace_urls (posts)
posts3 = self.replace_email (posts2)
posts4 = self.remove_empty(posts3)
posts5 = [self.remove_registered_icon(p) for p in posts4]
posts6 = [self.escape_char(p) for p in posts5]
return posts6
#---------Convert to lowercase ----------------------------------------------------
def lowercase (self, post):
post1 = []
for word in post:
word1 = word.lower()
post1.append (word1)
return post1
#---------Remove non_English posts -------------------------------------------------
def language_identify_basic (self, posts):
nw = []
tally = 0
list_removed = []
for post in posts:
out = langid.classify (post)
out2 = list(out)
if out2[0]=='en':
nw.append(post)
else:
tally += 1
list_removed.append(tuple ([post, out2[0], out2[1]]))
return nw, tally, list_removed
def language_identify_thres (self, msgs, lang_list, thres):
nw = []
tally = 0
list_removed = []
for post in msgs:
langid.set_languages(lang_list)
out = langid.classify (post)
out2 = list(out)
if out2[0]=='en':
nw.append(post)
elif out2[1] > thres:
nw.append(post)
else:
tally += 1
list_removed.append(tuple ([post, out2[0], out2[1]]))
return nw, tally, list_removed
def remove_non_english(self, posts):
# d = TreebankWordDetokenizer()
# posts2 = [d.detokenize(m) for m in posts]
posts_temp, tally, list_removed = self.language_identify_basic(posts)
lang = []
for itm in list_removed:
lang.append(itm[1])
c = Counter(lang)
lang_list = ['en']
for itm in c.most_common(10):
z = list(itm)
lang_list.append(z[0])
print("Most common 10 languages in the data are:" + str(lang_list))
posts3, tally_nw, list_removed_nw = self.language_identify_thres(posts, lang_list, thres = -100)
return posts3
## --- Contraction expansions ------------------------------##
def prepareContractions(self):
self.c_re = re.compile('(%s)' % '|'.join(self.cList.keys()))
self.c_re2 = re.compile('(%s)' % '|'.join(self.cList2.keys()))
def remove_apos (self, sent):
sent2 = re.sub ("'",'', sent)
return sent2
# except TypeError:
# pass
def expandContractions (self, text):
def replace(match):
return self.cList[match.group(0)]
return self.c_re.sub(replace, text)
#needs to happen after tokenization
def expandContractions_second (self, text):
text2 = []
for w in text:
if w.lower() in self.cList2:
v = word_tokenize(self.cList2[w.lower()])
for i in v:
text2.append(i)
else:
text2.append(w)
return text2
###--- 1-2 letter expansions -------------------------------##
def load_ngrammodel(self):
path = 'obj_lex\\tetragram_model.binary'
self.model = kenlm.Model(path)
def get_parameters_ngram_model (self, word, sent):
i = sent.index(word)
if ((i-2) >= 0) and (len(sent)>(i+2)):
out = sent[(i-2):(i+3)]
bos = False
eos = False
elif ((i-2) < 0) and (len(sent)> (i+2)) : #problem with beginning
bos = True
eos = False
out = sent[0:(i+3)]
elif ((i-2) >= 0) and (len(sent) <= (i+2)): #problem with end
bos = False
eos = True
out = sent[(i-2):]
else: #problem with both
out = sent
eos = True
bos = True
d = TreebankWordDetokenizer()
out2 = d.detokenize(out)
return bos, eos, out2
def get_prob(self, word, token, out, bos, eos): #token is candidate
out_nw = out.replace(word, token)
p = self.model.score(out_nw, bos = bos, eos = eos)
return p
def short_abbr_expansion(self, sent):
sent2 = []
for word in sent:
if len(word) > 2:
sent2.append(word)
else:
if word in self.short_expanse_dict .keys():
cand = self.short_expanse_dict [word]
final_p = -100
bos, eos, out = self.get_parameters_ngram_model(word,sent)
for i in cand:
p = self.get_prob(word, i, out, bos, eos)
if p > final_p:
final_p = p
correct = i
sent2.append(correct)
else:
sent2.append(word)
return sent2
#---------Lexical normalization pipeline (Sarker, 2017) -------------------------------
def loadItems(self):
'''
This is the primary load function.. calls other loader functions as required..
'''
global english_to_american
global noslang_dict
global IGNORE_LIST_TRAIN
global IGNORE_LIST
english_to_american = {}
lexnorm_oovs = []
IGNORE_LIST_TRAIN = []
IGNORE_LIST = []
english_to_american = self.loadEnglishToAmericanDict()
noslang_dict = self.loadDictionaryData()
for key, value in noslang_dict.items ():
value2 = value.lower ()
value3 = word_tokenize (value2)
noslang_dict[key] = value3
return None
def loadEnglishToAmericanDict(self):
etoa = {}
english = open('obj_lex/englishspellings.txt')
american = open('obj_lex/americanspellings.txt')
for line in english:
etoa[line.strip()] = american.readline().strip()
return etoa
def loadDictionaryData(self):
'''
this function loads the various dictionaries which can be used for mapping from oov to iv
'''
n_dict = {}
infile = open('obj_lex/noslang_mod.txt')
for line in infile:
items = line.split(' - ')
if len(items[0]) > 0 and len(items) > 1:
n_dict[items[0].strip()] = items[1].strip()
return n_dict
def preprocessText(self, tokens, IGNORE_LIST, ignore_username=False, ignore_hashtag=False, ignore_repeated_chars=True, eng_to_am=True, ignore_urls=False):
'''
Note the reason it ignores hashtags, @ etc. is because there is a preprocessing technique that is
designed to remove them
'''
normalized_tokens =[]
#print tokens
text_string = ''
# NOTE: if nesting if/else statements, be careful about execution sequence...
# tokens2 = [t[0] for t in tokens]
for t in tokens:
t_lower = t.strip().lower()
# if the token is not in the IGNORE_LIST, do various transformations (e.g., ignore usernames and hashtags, english to american conversion
# and others..
if t_lower not in IGNORE_LIST:
# ignore usernames '@'
if re.match('@', t) and ignore_username:
IGNORE_LIST.append(t_lower)
text_string += t_lower + ' '
#ignore hashtags
elif re.match('#', t_lower) and ignore_hashtag:
IGNORE_LIST.append(t_lower)
text_string += t_lower + ' '
#convert english spelling to american spelling
elif t.strip().lower() in english_to_american.keys() and eng_to_am:
text_string += english_to_american[t.strip().lower()] + ' '
#URLS
elif re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', t_lower) and ignore_urls:
IGNORE_LIST.append(t_lower)
text_string += t_lower + ' '
elif not ignore_repeated_chars and not re.search(r'[^a-zA-Z]', t_lower):
# if t_lower only contains alphabetic characters
t_lower = re.sub(r'([a-z])\1+', r'\1\1', t_lower)
text_string += t_lower + ' '
# print t_lower
# if none of the conditions match, just add the token without any changes..
else:
text_string += t + ' '
else: # i.e., if the token is in the ignorelist..
text_string += t_lower + ' '
normalized_tokens = text_string.split()
return normalized_tokens, IGNORE_LIST
def dictionaryBasedNormalization(self, tokens, I_LIST, M_LIST):
tokens2 =[]
for t in (tokens):
t_lower = t.strip().lower()
if t_lower in noslang_dict.keys() and len(t_lower)>2:
nt = noslang_dict[t_lower]
[tokens2.append(m) for m in nt]
if not t_lower in M_LIST:
M_LIST.append(t_lower)
if not nt in M_LIST:
M_LIST.append(nt)
else:
| |
df.agg("mean", axis="columns")
0 2.0
1 5.0
2 8.0
3 NaN
dtype: float64
See also
--------
DataFrame.apply : Perform any type of operations.
DataFrame.transform : Perform transformation type operations.
pandas.core.groupby.GroupBy : Perform operations over groups.
pandas.core.resample.Resampler : Perform operations over resampled bins.
pandas.core.window.Rolling : Perform operations over rolling window.
pandas.core.window.Expanding : Perform operations over expanding window.
pandas.core.window.EWM : Perform operation over exponential weighted
window.
""")
@Appender(_agg_doc)
@Appender(_shared_docs['aggregate'] % dict(
versionadded='.. versionadded:: 0.20.0',
**_shared_doc_kwargs))
def aggregate(self, func, axis=0, *args, **kwargs):
axis = self._get_axis_number(axis)
# TODO: flipped axis
result = None
if axis == 0:
try:
result, how = self._aggregate(func, axis=0, *args, **kwargs)
except TypeError:
pass
if result is None:
return self.apply(func, axis=axis, args=args, **kwargs)
return result
agg = aggregate
def apply(self, func, axis=0, broadcast=None, raw=False, reduce=None,
result_type=None, args=(), **kwds):
"""
Apply a function along an axis of the DataFrame.
Objects passed to the function are Series objects whose index is
either the DataFrame's index (``axis=0``) or the DataFrame's columns
(``axis=1``). By default (``result_type=None``), the final return type
is inferred from the return type of the applied function. Otherwise,
it depends on the `result_type` argument.
Parameters
----------
func : function
Function to apply to each column or row.
axis : {0 or 'index', 1 or 'columns'}, default 0
Axis along which the function is applied:
* 0 or 'index': apply function to each column.
* 1 or 'columns': apply function to each row.
broadcast : bool, optional
Only relevant for aggregation functions:
* ``False`` or ``None`` : returns a Series whose length is the
length of the index or the number of columns (based on the
`axis` parameter)
* ``True`` : results will be broadcast to the original shape
of the frame, the original index and columns will be retained.
.. deprecated:: 0.23.0
This argument will be removed in a future version, replaced
by result_type='broadcast'.
raw : bool, default False
* ``False`` : passes each row or column as a Series to the
function.
* ``True`` : the passed function will receive ndarray objects
instead.
If you are just applying a NumPy reduction function this will
achieve much better performance.
reduce : bool or None, default None
Try to apply reduction procedures. If the DataFrame is empty,
`apply` will use `reduce` to determine whether the result
should be a Series or a DataFrame. If ``reduce=None`` (the
default), `apply`'s return value will be guessed by calling
`func` on an empty Series
(note: while guessing, exceptions raised by `func` will be
ignored).
If ``reduce=True`` a Series will always be returned, and if
``reduce=False`` a DataFrame will always be returned.
.. deprecated:: 0.23.0
This argument will be removed in a future version, replaced
by ``result_type='reduce'``.
result_type : {'expand', 'reduce', 'broadcast', None}, default None
These only act when ``axis=1`` (columns):
* 'expand' : list-like results will be turned into columns.
* 'reduce' : returns a Series if possible rather than expanding
list-like results. This is the opposite of 'expand'.
* 'broadcast' : results will be broadcast to the original shape
of the DataFrame, the original index and columns will be
retained.
The default behaviour (None) depends on the return value of the
applied function: list-like results will be returned as a Series
of those. However if the apply function returns a Series these
are expanded to columns.
.. versionadded:: 0.23.0
args : tuple
Positional arguments to pass to `func` in addition to the
array/series.
**kwds
Additional keyword arguments to pass as keywords arguments to
`func`.
Notes
-----
In the current implementation apply calls `func` twice on the
first column/row to decide whether it can take a fast or slow
code path. This can lead to unexpected behavior if `func` has
side-effects, as they will take effect twice for the first
column/row.
See also
--------
DataFrame.applymap: For elementwise operations
DataFrame.aggregate: only perform aggregating type operations
DataFrame.transform: only perform transformating type operations
Examples
--------
>>> df = pd.DataFrame([[4, 9],] * 3, columns=['A', 'B'])
>>> df
A B
0 4 9
1 4 9
2 4 9
Using a numpy universal function (in this case the same as
``np.sqrt(df)``):
>>> df.apply(np.sqrt)
A B
0 2.0 3.0
1 2.0 3.0
2 2.0 3.0
Using a reducing function on either axis
>>> df.apply(np.sum, axis=0)
A 12
B 27
dtype: int64
>>> df.apply(np.sum, axis=1)
0 13
1 13
2 13
dtype: int64
Retuning a list-like will result in a Series
>>> df.apply(lambda x: [1, 2], axis=1)
0 [1, 2]
1 [1, 2]
2 [1, 2]
dtype: object
Passing result_type='expand' will expand list-like results
to columns of a Dataframe
>>> df.apply(lambda x: [1, 2], axis=1, result_type='expand')
0 1
0 1 2
1 1 2
2 1 2
Returning a Series inside the function is similar to passing
``result_type='expand'``. The resulting column names
will be the Series index.
>>> df.apply(lambda x: pd.Series([1, 2], index=['foo', 'bar']), axis=1)
foo bar
0 1 2
1 1 2
2 1 2
Passing ``result_type='broadcast'`` will ensure the same shape
result, whether list-like or scalar is returned by the function,
and broadcast it along the axis. The resulting column names will
be the originals.
>>> df.apply(lambda x: [1, 2], axis=1, result_type='broadcast')
A B
0 1 2
1 1 2
2 1 2
Returns
-------
applied : Series or DataFrame
"""
from pandas.core.apply import frame_apply
op = frame_apply(self,
func=func,
axis=axis,
broadcast=broadcast,
raw=raw,
reduce=reduce,
result_type=result_type,
args=args,
kwds=kwds)
return op.get_result()
def applymap(self, func):
"""
Apply a function to a DataFrame that is intended to operate
elementwise, i.e. like doing map(func, series) for each series in the
DataFrame
Parameters
----------
func : function
Python function, returns a single value from a single value
Examples
--------
>>> df = pd.DataFrame(np.random.randn(3, 3))
>>> df
0 1 2
0 -0.029638 1.081563 1.280300
1 0.647747 0.831136 -1.549481
2 0.513416 -0.884417 0.195343
>>> df = df.applymap(lambda x: '%.2f' % x)
>>> df
0 1 2
0 -0.03 1.08 1.28
1 0.65 0.83 -1.55
2 0.51 -0.88 0.20
Returns
-------
applied : DataFrame
See also
--------
DataFrame.apply : For operations on rows/columns
"""
# if we have a dtype == 'M8[ns]', provide boxed values
def infer(x):
if x.empty:
return lib.map_infer(x, func)
return lib.map_infer(x.astype(object).values, func)
return self.apply(infer)
# ----------------------------------------------------------------------
# Merging / joining methods
def append(self, other, ignore_index=False, verify_integrity=False):
"""
Append rows of `other` to the end of this frame, returning a new
object. Columns not in this frame are added as new columns.
Parameters
----------
other : DataFrame or Series/dict-like object, or list of these
The data to append.
ignore_index : boolean, default False
If True, do not use the index labels.
verify_integrity : boolean, default False
If True, raise ValueError on creating index with duplicates.
Returns
-------
appended : DataFrame
Notes
-----
If a list of dict/series is passed and the keys are all contained in
the DataFrame's index, the order of the columns in the resulting
DataFrame will be unchanged.
Iteratively appending rows to a DataFrame can be more computationally
intensive than a single concatenate. A better solution is to append
those rows to a list and then concatenate the list with the original
DataFrame all at once.
See also
--------
pandas.concat : General function to concatenate DataFrame, Series
or Panel objects
Examples
--------
>>> df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
>>> df
A B
0 1 2
1 3 4
>>> df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
>>> df.append(df2)
A B
0 1 2
1 3 4
0 5 6
1 7 8
With `ignore_index` set to True:
>>> df.append(df2, ignore_index=True)
A B
0 1 2
1 3 4
2 5 6
3 7 8
The following, while not recommended methods for generating DataFrames,
show two ways to generate a DataFrame from multiple data sources.
Less efficient:
>>> df = pd.DataFrame(columns=['A'])
>>> for i in range(5):
... df = df.append({'A': i}, ignore_index=True)
>>> df
A
0 | |
<filename>s9k.py
#!/usr/bin/env python3
import logging
import shlex
import argparse
import os
from geventwebsocket import WebSocketError
from geventwebsocket.handler import WebSocketHandler
from gevent import pywsgi
from gevent.select import select
from gevent.subprocess import Popen, PIPE
import bottle
from bottle.ext.websocket import GeventWebSocketServer
from bottle.ext.websocket import websocket
ERROR_MESSAGE_NO_DATA = "The server failed to get the requested command."
def read_static_file(file_name):
file_name = "./static-file/{}".format(file_name)
with open(file_name, "r") as file:
return file.read()
print("!! 404 {}".format(file_name))
return "404"
def get_style_sheet():
return read_static_file("css.css")
class Params:
kubeconfig_file = ""
command_name = "kubectl"
cert_file = "cert.pem"
key_file = "key.pem"
def __init__(self):
pass
def set_config(self, kubeconfig_cmd, kubeconfig_dir):
self.command_name = kubeconfig_cmd
if kubeconfig_dir != "":
self.kubeconfig_file = " --kubeconfig={}/config".format(kubeconfig_dir)
self.command_name += self.kubeconfig_file
def set_cert_files(self, key_file, cert_file):
self.cert_file = cert_file
self.key_file = key_file
params = Params()
def get_home_link():
return "<a href='/'>Home</a> "
class RunCommand:
def __init__(self, command_line, split_lines=True, pipe_as_input=None):
self.command_line = command_line
self.lines = []
self.exit_code = 0
self.run(command_line, split_lines, pipe_as_input)
def run(self, command_line, split_lines, pipe_as_input):
logging.info("command line: %s", command_line)
if pipe_as_input is None:
process = Popen(shlex.split(command_line), \
stdout=PIPE, stderr=PIPE)
(output, error_out) = process.communicate()
self.exit_code = process.wait()
else:
process = Popen(shlex.split(command_line), \
stdin=PIPE, stdout=PIPE, stderr=PIPE)
(output, error_out) = process.communicate(input=pipe_as_input.encode("utf-8"))
self.exit_code = process.wait()
if split_lines:
self.lines = output.splitlines()
else:
self.output = output.decode("utf-8")
self.error_out = error_out
return self.exit_code
def result(self):
return self.exit_code, self.lines
def make_error_message(command):
return_value = ERROR_MESSAGE_NO_DATA
if command.command_line != "":
return_value += " command line: {}.".format(command.command_line)
if command.exit_code != 0:
return_value += " exit status: {}. ".format(command.exit_code)
if command.error_out != "":
return_value += " " + command.error_out.decode("utf-8")
return return_value
class TextCommand:
def __init__(self, command):
self.token_start = []
self.token_end = []
self.titles = []
self.parsed_lines = []
self.parse_header(command.lines[0].decode("utf-8"))
self.parse_fields(command)
def parse_header(self, header_line):
# here it becomes a bit hacky
header_line = header_line.replace("CREATED AT", "CREATED_AT")
header_line = header_line.replace("NOMINATED NODE", "NOMINATED_NODE")
header_line = header_line.replace("READINESS GATES", "READINESS_GATES")
self.titles = header_line.split()
start = 0
for title_pos in range(len(self.titles)):
word_pos = header_line.find(self.titles[title_pos], start)
start = word_pos + len(self.titles[title_pos])
self.token_start.append(word_pos)
self.token_end.append(-1)
if title_pos > 0:
self.token_end[title_pos - 1] = word_pos
def parse_fields(self, command):
for line_pos in range(len(command.lines)):
if line_pos > 0:
line = command.lines[line_pos].decode("utf-8")
line_vals = []
for field_pos in range(len(self.token_start)):
tstart = self.token_start[field_pos]
tend = self.token_end[field_pos]
if tend != -1:
field_value = line[tstart : tend]
else:
field_value = line[tstart:]
line_vals.append(field_value.strip())
self.parsed_lines.append(line_vals)
def dump(self):
logging.info("header: %s", self.titles)
for line in self.parsed_lines:
logging.info("line: %s", line)
class ClientGoCmd:
def __init__(self, entity, is_namespaced, column_defs):
self.titles = []
self.parsed_lines = []
self.process(entity, is_namespaced, column_defs)
def process(self, entity, is_namespaced, column_defs):
if is_namespaced:
command_text = "{} get {} -A".format(params.command_name, entity)
else:
command_text = "{} get {}".format(params.command_name, entity)
if column_defs is not None:
command_text += ClientGoCmd.make_column_filter(column_defs)
command = RunCommand(command_text)
self.titles = []
for entry in column_defs:
self.titles.append(entry[0])
self.parsed_lines = []
for line in command.lines:
self.parsed_lines.append(line.split(","))
else:
command_text += " -o wide "
command = RunCommand(command_text)
text_command = TextCommand(command)
self.titles = text_command.titles
self.parsed_lines = text_command.parsed_lines
@staticmethod
def make_column_filter(column_defs):
command_text = ' -o go-template --template=\'{{range .items}}{{printf "'
command_text += "%s," * len(column_defs)
command_text += '\\n" '
for column_def in column_defs:
command_text += column_def[1]
command_text += " "
command_text += "}}{{end}}'"
return command_text
def find_index_in_list(slist, elem):
for i, item in enumerate(slist):
if item == elem:
return i
return -1
class HtmlTable:
def __init__(self, titles, parsed_lines):
self.titles = titles
self.parsed_lines = parsed_lines
self.html_text = ""
def make_html(self, column_subset, link_cb, is_editable, editlink):
if self.html_text != "":
return self.html_text
if link_cb is None:
link_cb = HtmlTable.make_object_link_def
if self.titles is None or self.parsed_lines is None:
ret = ERROR_MESSAGE_NO_DATA
else:
ret = get_style_sheet()
if is_editable:
ret += HtmlTable.make_script_switch_to_edit()
ret += self.make_table_header(column_subset)
if isinstance(self.parsed_lines, list):
for line in self.parsed_lines:
ret += '<tr>'
for pos in range(len(self.titles)):
if column_subset is None or pos in column_subset:
ret += '<td>{}</td>'.format(link_cb(line, pos))
ret += '</tr>\n'
else:
ret += '<tr id="displayform"><td>'
if is_editable:
ret += '<input type="button" onclick="startedit();" value="edit"/> '
ret += '<input type="button" onclick="deleteobj();" value="Delete"/>'
ret += '<br/>'
ret += '<pre id="toedit">{}</pre></td></tr>'.format(self.parsed_lines)
if is_editable:
ret += HtmlTable.make_edit_row(editlink)
ret += '</table>'
self.html_text = ret
return self.html_text
def make_table_header(self, column_subset):
hdr = HtmlTable.make_sort_jscript()
hdr += '<table class="js-sort-table"><thead><tr>'
for pos in range(len(self.titles)):
if column_subset is None or pos in column_subset:
title = self.titles[pos]
#hdr += '<th align="left"><a onclick="sortTable({})">{}</a></th>'.format(pos, title)
hdr += '<th align="left">{}</th>'.format(title)
hdr += '</tr></thead>'
return hdr
@staticmethod
def make_sort_jscript():
return "<script>\n" + \
read_static_file("sorttable/sort-table.min.js") + \
'</script>'
@staticmethod
def make_object_link_def(line, title_pos):
return line[title_pos]
@staticmethod
def make_edit_row(editlink):
return '<tr id ="editform" style="display:none"><td>{} {}</td></tr>'.\
format(HtmlTable.make_edit_form(editlink), HtmlTable.make_delete_form(editlink))
@staticmethod
def make_edit_form(editlink):
return '''<form method="post" action="{}" >\
<input type="submit" value="save"/><br/>\
<textarea name="edit" id="contentOnEdit" rows="40", cols="80"></textarea>\
</form>'''.format(editlink[0])
@staticmethod
def make_delete_form(editlink):
return '''<form id="deleteobj" method="post" action={} style="display:none">\
<textarea name="edit" id="contentOnDelete" style="display:none"></textarea>\
</form>'''.format(editlink[1])
@staticmethod
def make_script_switch_to_edit():
return '''<script>
function startedit() {
toedit = document.getElementById("toedit");
displayform = document.getElementById("displayform");
editform = document.getElementById("editform");
editctl = document.getElementById("contentOnEdit");
displayform.style.display = 'none';
editctl.value = toedit.innerHTML;
editform.style.display = '';
}
function deleteobj() {
if (confirm("Do you really want to delete the object ?")) {
toedit = document.getElementById("toedit");
edit = document.getElementById("contentOnDelete");
edit.value = toedit.innerHTML;
form = document.getElementById("deleteobj");
form.submit();
}
}
</script>
'''
class ApiResources:
def __init__(self):
self.html_table = None
self.name_index = None
self.namespaced_index = None
self.error_message = None
def load(self):
cmd = params.command_name + " api-resources"
run_command = RunCommand(cmd)
#for whatever reasons kubectl api-resources often returns error status,
#even it returned all resources.
#if run_command.exit_code == 0 and len(run_command.lines) != 0:
if len(run_command.lines) != 0:
text_command = TextCommand(run_command)
parsed_lines = sorted(text_command.parsed_lines, key=lambda entry: entry[0])
self.html_table = HtmlTable(text_command.titles, parsed_lines)
self.name_index = find_index_in_list(self.html_table.titles, "NAME")
self.namespaced_index = find_index_in_list(self.html_table.titles, "NAMESPACED")
else:
self.html_table = None
self.error_message = make_error_message(run_command)
def make_html(self, column_subset):
html = '<b>{}</b></br>'.format(get_home_link())
if self.html_table:
html += self.html_table.make_html(column_subset, self.make_object_link, False, "")
else:
html += self.error_message
return html
def make_object_link(self, line, title_pos):
return '<a href="/objectinstances/{}/{}">{}</a>'.\
format(line[self.name_index], line[self.namespaced_index], line[title_pos])
class ObjectListScreen:
def __init__(self, oname, namespaced, field_sel, label_sel):
cli_param = ""
self.namespaced = namespaced
self.object_type = oname
if namespaced == "true":
cli_param = "-A"
add = ""
if field_sel:
add += "--field-selector {}".format(field_sel)
if label_sel:
add += "--selector {}".format(label_sel)
cmd = "{} get {} -o wide {} --show-labels {}".format(\
params.command_name, oname, cli_param, add)
run_command = RunCommand(cmd)
if run_command.exit_code == 0 and len(run_command.lines) != 0:
text_command = TextCommand(run_command)
self.name_index = find_index_in_list(text_command.titles, "NAME")
self.namespace_index = find_index_in_list(text_command.titles, "NAMESPACE")
self.html_table = HtmlTable(text_command.titles, text_command.parsed_lines)
else:
self.html_table = None
self.error_message = make_error_message(run_command)
def make_html(self):
ret = get_home_link()
ret += self.get_self_link() + '</br>'
ret += self.make_query_fields()
if self.html_table is not None:
return ret + self.html_table.make_html(None, self.make_object_link, False, '')
return ret + self.error_message
def get_self_link(self):
return "<b><a href='/objectinstances/{0}/{1}'>{0}</a></b> ".\
format(self.object_type, self.namespaced)
def make_object_link(self, line, title_pos):
if self.object_type != 'customresourcedefinitions':
if self.namespace_index != -1:
link = '<a href="/objectinfo/get-yaml/{}/{}/{}/{}">{}</a>'.\
format(self.object_type, line[self.name_index],\
line[self.namespace_index], self.namespaced, line[title_pos])
else:
link = '<a href="/objectinfo/get-yaml/{}/{}/None/{}">{}</a>'.\
format(self.object_type, line[self.name_index], \
self.namespaced, line[title_pos])
else:
link = '<a href="/crds/list-objects/{}">{}</a>'.\
format(line[self.name_index], line[self.name_index])
return link
def make_query_fields(self):
return '''<form method="post" action="/objectinstances/{}/{}"><table><tr>\
<td width="1%">LabelSelector</td>\
<td><input name="labelsel"></td></tr>\
<tr><td>FieldSelector:</td><td><input name="fieldsel"></td></tr></table>\
<input type="submit" style="display: none" /></form>'''\
.format(self.object_type, self.namespaced)
class CrdScreen:
def __init__(self, screentype, oname, nspace):
self.screentype = screentype
self.oname = oname
self.namespaced = nspace
self.namespace_index = -1
self.name_index = -1
def make_html(self):
hdr = CrdScreen.make_hdr_links()
cmd = '{} get -A {}'.format(params.command_name, self.oname)
run_command = RunCommand(cmd)
if run_command.exit_code == 0 and len(run_command.lines) != 0:
text_command = TextCommand(run_command)
html_table = HtmlTable(text_command.titles, text_command.parsed_lines)
self.namespace_index = find_index_in_list(html_table.titles, "NAMESPACE")
self.name_index = find_index_in_list(html_table.titles, "NAME")
return hdr + html_table.make_html(None, self.make_object_link, False, '')
return hdr + make_error_message(run_command)
@staticmethod
def make_hdr_links():
ret = get_home_link()
ret += '<b><a href="/objectinstances/customresourcedefinitions/false">crds</a></b><br/>'
return ret
def make_object_link(self, line, title_pos):
if self.namespace_index != -1:
return '<a href="/crdinfo/get-yaml/{}/{}/{}">{}</a>'.\
format(self.oname, line[self.name_index],\
line[self.namespace_index], line[title_pos])
return '<a href="/crdinfo/get-yaml/{}/{}/None">{}</a>'.\
format(self.oname, line[self.name_index], line[title_pos])
class ObjectDetailScreenBase:
def __init__(self, urlbase, screentype, otype, oname, namespace, namespaced, request_types):
self.request_types = request_types
self.urlbase = urlbase
self.oname = oname
self.namespaced = namespaced
self.namespace = namespace
self.html_header = self.make_hdr_links(screentype, otype, oname, namespace, namespaced)
self.html = self.html_header
for request_def in self.request_types:
if screentype == request_def[0]:
cmd = ObjectDetailScreen.make_kubectl_cmd(request_def, namespace, otype, oname)
self.add_table(cmd, request_def[2])
return
logging.error("Illegal screen type %s", screentype)
@staticmethod
def make_kubectl_cmd(request_def, namespace, otype, oname):
nspace = ""
if namespace != 'None':
nspace = '-n {}'.format(namespace)
cmd = request_def[1].format(params.command_name, otype, oname, nspace)
return cmd
def add_table(self, cmd, is_editable):
run_command = RunCommand(cmd, False)
if run_command.exit_code == 0 and run_command.output != "":
html_table = HtmlTable([cmd], run_command.output)
self.html += html_table.make_html(None, None, is_editable, \
['/editobj/apply', '/editobj/delete'])
else:
self.html += make_error_message(run_command)
def make_html(self):
return self.html
def make_hdr_links(self, screen_type, otype, oname, namespace, isnamespaced):
ret = get_home_link()
ret += self.make_back_link(otype, isnamespaced)
for request_def | |
<filename>qwiic_oled_base/qwiic_oled_base.py
#-----------------------------------------------------------------------------
# qwiic_oled_base.py
#
#------------------------------------------------------------------------
#
# Written by SparkFun Electronics, May 2021
#
#
# More information on qwiic is at https:= www.sparkfun.com/qwiic
#
# Do you like this library? Help support SparkFun. Buy a board!
#
#==================================================================================
# Copyright (c) 2021 SparkFun Electronics
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#==================================================================================
#
# This is mostly a port of existing Arduino functionaly, so pylint is sad.
# The goal is to keep the public interface pthonic, but internal is internal
#
# pylint: disable=line-too-long, bad-whitespace, invalid-name, too-many-lines
# pylint: disable=too-many-lines, too-many-arguments, too-many-instance-attributes
# pylint: disable=too-many-public-methods
"""
qwiic_oled_base
=================
The base Python module for the SSD1306 display driver on the following OLED displays:
- [Qwiic Micro OLED]](https://www.sparkfun.com/products/14532)
- [Qwiic OLED Display](https://www.sparkfun.com/products/17153)
This python package is a port of the existing [SparkFun Micro OLED Arduino Library](https://github.com/sparkfun/SparkFun_Micro_OLED_Arduino_Library)
This package can be used in conjunction with the overall [SparkFun qwiic Python Package](https://github.com/sparkfun/Qwiic_Py)
New to qwiic? Take a look at the entire [SparkFun qwiic ecosystem](https://www.sparkfun.com/qwiic).
"""
from __future__ import print_function
import sys
import math
# import time
import qwiic_i2c
from . import oled_fonts
from . import oled_logos
# Define the device name and I2C addresses. These are set in the class defintion
# as class variables, making them avilable without having to create a class instance.
#
# The name of this device - note this is private
_DEFAULT_NAME = "OLED Display Driver (SSD1306)"
# Use the configuration for the Qwiic Micro OLED display as a default
#==================================================================================
# Some devices have multiple availabel addresses - this is a list of these addresses.
# NOTE: The first address in this list is considered the default I2C address for the
# device.
_AVAILABLE_I2C_ADDRESS = [0x3D, 0x3C]
_LCDWIDTH = 64
_LCDHEIGHT = 48
#==================================================================================
# The defines from the OLED Aurdino library
I2C_COMMAND = 0x00
I2C_DATA = 0x40
FONTHEADERSIZE = 6
WIDGETSTYLE0 = 0
WIDGETSTYLE1 = 1
WIDGETSTYLE2 = 2
SETCONTRAST = 0x81
DISPLAYALLONRESUME = 0xA4
DISPLAYALLON = 0xA5
NORMALDISPLAY = 0xA6
INVERTDISPLAY = 0xA7
DISPLAYOFF = 0xAE
DISPLAYON = 0xAF
SETDISPLAYOFFSET = 0xD3
SETCOMPINS = 0xDA
SETVCOMDESELECT = 0xDB
SETDISPLAYCLOCKDIV = 0xD5
SETPRECHARGE = 0xD9
SETMULTIPLEX = 0xA8
SETLOWCOLUMN = 0x00
SETHIGHCOLUMN = 0x10
SETSTARTLINE = 0x40
MEMORYMODE = 0x20
COMSCANINC = 0xC0
COMSCANDEC = 0xC8
SEGREMAP = 0xA0
CHARGEPUMP = 0x8D
EXTERNALVCC = 0x01
SWITCHCAPVCC = 0x02
# Scroll
ACTIVATESCROLL = 0x2F
DEACTIVATESCROLL = 0x2E
SETVERTICALSCROLLAREA = 0xA3
RIGHTHORIZONTALSCROLL = 0x26
LEFT_HORIZONTALSCROLL = 0x27
VERTICALRIGHTHORIZONTALSCROLL = 0x29
VERTICALLEFTHORIZONTALSCROLL = 0x2A
class QwiicOledBase(object):
"""
QwiicOledBase
:param address: The I2C address to use for the device.
If not provided, the default address is used.
:param i2c_driver: An existing i2c driver object. If not provided
a driver object is created.
:return: The SSD1306 OLED device object.
:rtype: Object
"""
# Constructor
device_name =_DEFAULT_NAME
available_addresses = _AVAILABLE_I2C_ADDRESS
# user exposed constants
BLACK = 0
WHITE = 1
NORM = 0
XOR = 1
PAGE = 0
ALL = 1
def __init__(self, address=None, pixel_width = _LCDWIDTH, pixel_height = _LCDHEIGHT, i2c_driver=None):
# Did the user specify an I2C address?
self.address = address if address is not None else self.available_addresses[0]
# Screen size:
self.LCDHEIGHT = pixel_height
self.LCDWIDTH = pixel_width
# Load the I2C driver if one isn't provided
if i2c_driver is None:
self._i2c = qwiic_i2c.getI2CDriver()
if self._i2c is None:
print("Unable to load I2C driver for this platform.")
return
else:
self._i2c = i2c_driver
# define the screen buffer - since this is a two color display, only bits are used
# So the height is 8 bits / byte or LCDHEIGHT/8
self._screenbuffer = bytearray(self.LCDWIDTH * int(math.ceil(self.LCDHEIGHT/8.)))
# Set initial contents
self._screenbuffer = [0x00]*int(self.LCDWIDTH*self.LCDHEIGHT/8) #Screen Area in bytes (Total Pixels/8)
# Display SparkFun Logo
oled_logos.add_logo(self._screenbuffer)
# Display ans Clear Page
# self.display()
# time.sleep(2)
# self.clear(self.PAGE)
self.cursorX = 0
self.cursorY = 0
self.foreColor = self.WHITE
self.drawMode = self.NORM
# self.fontWidth = 0
# self.fontHeight = 0
# self.fontStartChar = 0
# self.fontTotalChar = 0
self.fontType = 0
# self.fontData = None
self._font = None
self.nFonts = oled_fonts.count()
#--------------------------------------------------------------------------
def is_connected(self):
"""
Determine if a SSD1306 OLED device is conntected to the system..
:return: True if the device is connected, otherwise False.
:rtype: bool
"""
return qwiic_i2c.isDeviceConnected(self.address)
connected = property(is_connected)
#--------------------------------------------------------------------------
def begin(self):
"""
Initialize the operation of the SSD1306 display driver for the OLED module
:return: Returns true of the initializtion was successful, otherwise False.
:rtype: bool
"""
self.set_font_type(0)
self.set_color(self.WHITE)
self.set_draw_modee(self.NORM)
self.set_cursor(0,0)
# Display Init sequence
self._i2c.writeByte(self.address, I2C_COMMAND, DISPLAYOFF) # 0xAE
self._i2c.writeByte(self.address, I2C_COMMAND, SETDISPLAYCLOCKDIV) # 0xD5
self._i2c.writeByte(self.address, I2C_COMMAND, 0x80) # the suggested ratio 0x80
self._i2c.writeByte(self.address, I2C_COMMAND, SETMULTIPLEX) # 0xA8
self._i2c.writeByte(self.address, I2C_COMMAND, self.LCDHEIGHT - 1)
self._i2c.writeByte(self.address, I2C_COMMAND, SETDISPLAYOFFSET) # 0xD3
self._i2c.writeByte(self.address, I2C_COMMAND, 0x0) # no offset
self._i2c.writeByte(self.address, I2C_COMMAND, SETSTARTLINE | 0x0) # line #0
self._i2c.writeByte(self.address, I2C_COMMAND, CHARGEPUMP) # enable charge pump
self._i2c.writeByte(self.address, I2C_COMMAND, 0x14)
self._i2c.writeByte(self.address, I2C_COMMAND, NORMALDISPLAY) # 0xA6
self._i2c.writeByte(self.address, I2C_COMMAND, DISPLAYALLONRESUME) # 0xA4
self._i2c.writeByte(self.address, I2C_COMMAND, SEGREMAP | 0x1)
self._i2c.writeByte(self.address, I2C_COMMAND, COMSCANDEC)
self._i2c.writeByte(self.address, I2C_COMMAND, SETCOMPINS) # 0xDA
if len(self._screenbuffer) == 512:
self._i2c.writeByte(self.address, I2C_COMMAND, 0x02) # rect (128x32 OLED modules)
else:
self._i2c.writeByte(self.address, I2C_COMMAND, 0x12) # square and large (64x48 or 128x64 OLED modules)
self._i2c.writeByte(self.address, I2C_COMMAND, SETCONTRAST) # 0x81
self._i2c.writeByte(self.address, I2C_COMMAND, 0x8F)
self._i2c.writeByte(self.address, I2C_COMMAND, SETPRECHARGE) # 0xd9
self._i2c.writeByte(self.address, I2C_COMMAND, 0x22)
self._i2c.writeByte(self.address, I2C_COMMAND, SETVCOMDESELECT) # 0xDB
self._i2c.writeByte(self.address, I2C_COMMAND, 0x30)
self._i2c.writeByte(self.address, I2C_COMMAND, DISPLAYON) # --turn on oled panel
self.clear(self.ALL) # Erase hardware memory inside the OLED controller to aself random data in memory.
#----------------------------------------------------
# brief Set SSD1306 page address.
# Send page address command and address to the SSD1306 OLED controller.
def set_page_address(self, pageAddress):
"""
Set SSD1306 page address.
:param pageAddress: The page address command and address
:return: No return value
"""
# self._i2c.writeByte(self.address, I2C_COMMAND, 0xb0|pageAddress)
self._i2c.writeByte(self.address, I2C_COMMAND, 0x22)
self._i2c.writeByte(self.address, I2C_COMMAND, (pageAddress& (self.LCDHEIGHT - 1)))
self._i2c.writeByte(self.address, I2C_COMMAND, self.LCDHEIGHT - 1)
#----------------------------------------------------
# Send column address command and address to the SSD1306 OLED controller.
def set_column_address(self, colAddress):
"""
Set SSD1306 column address.
:param colAddress: The column address command and address
:return: No return value
"""
if len(self._screenbuffer) == 384:
self._i2c.writeByte(self.address, I2C_COMMAND, (0x10|(colAddress>>4))+0x02)
self._i2c.writeByte(self.address, I2C_COMMAND, (0x0f&colAddress))
else:
self._i2c.writeByte(self.address, I2C_COMMAND, 0x21)
self._i2c.writeByte(self.address, I2C_COMMAND, (colAddress& (self.LCDWIDTH - 1)))
self._i2c.writeByte(self.address, I2C_COMMAND, self.LCDWIDTH -1)
#----------------------------------------------------
# To clear GDRAM inside the LCD controller, pass in the variable mode = ALL and to clear screen page buffer pass in the variable mode = PAGE.
def clear(self, mode, value=0):
"""
Clear the display on the OLED Device.
:param mode: To clear GDRAM inside the LCD controller, pass in the variable mode = ALL,
and to clear screen page buffer pass in the variable mode = PAGE.
:param value: The value to clear the screen to. Default value is 0
:return: No return value
"""
if mode == self.ALL:
for i in range(8):
self.set_page_address(i)
self.set_column_address(0)
#pylint: disable=unused-variable
for j in range(0x80):
self._i2c.writeByte(self.address, I2C_DATA, value)
#pylint: enable=unused-variable
else:
self._screenbuffer[:] = [value]*len(self._screenbuffer)
#--------------------------------------------------------------------------
# The WHITE color of the display will turn to BLACK and the BLACK will turn to WHITE.
def invert(self, inv):
"""
Invert the display of the display. The WHITE color of the display will turn to BLACK and the BLACK will turn to WHITE.
:param inv: If True, the screen is inverted. If False the screen is set to Normal mode.
:return: No return value
"""
if inv:
self._i2c.writeByte(self.address, I2C_COMMAND, INVERTDISPLAY)
else:
self._i2c.writeByte(self.address, I2C_COMMAND, NORMALDISPLAY)
#--------------------------------------------------------------------------
# OLED contract value from 0 to 255. Note: Contrast level is not very obvious.
def contrast(self, contrast):
"""
Set the OLED contract value from 0 to 255. Note: | |
if (not minor) and (char >= "0" and char <= "9"): # noqa
major += char
continue
minor+=char
if debug:
myPrint("D","Decoded: %s.%s" %(major,minor))
try:
return [int(major),minor]
except:
return [0,0]
def check_for_updatable_extensions_on_startup(statusLabel):
global lIgnoreOutdatedExtensions_TB
Toolbox_version = 0
displayData = u"\nALERT INFORMATION ABOUT YOUR EXTENSIONS:\n\n"
try:
theUpdateList = get_extension_update_info()
if not theUpdateList or len(theUpdateList)<1:
return Toolbox_version
for key in theUpdateList.keys():
updateInfo = theUpdateList[key]
displayData+=u"** UPGRADEABLE EXTENSION: %s to version: %s\n" %(pad(key,20),(updateInfo[0].getBuild()))
myPrint(u"B", u"** UPGRADEABLE EXTENSION: %s to version: %s" %(pad(key,20),(updateInfo[0].getBuild())))
if key.lower() == u"%s" %myModuleID and int(updateInfo[0].getBuild()) > 0:
Toolbox_version = int(updateInfo[0].getBuild())
except:
dump_sys_error_to_md_console_and_errorlog()
return Toolbox_version
displayData+=u"\n<END>\n"
howMany = int(len(theUpdateList))
if not lIgnoreOutdatedExtensions_TB:
statusLabel.setText( (u"ALERT - YOU HAVE %s EXTENSION(S) THAT CAN BE UPGRADED!..." %howMany ).ljust(800, u" "))
statusLabel.setForeground(Color.BLUE)
jif = QuickJFrame(u"EXTENSIONS ALERT!", displayData, 1).show_the_frame()
options=[u"OK (keep reminding me)",u"OK - DON'T TELL ME AGAIN ON STARTUP!"]
response = JOptionPane.showOptionDialog(jif,
u"INFO: You have %s older Extensions that can be upgraded" %howMany,
u"OUTDATED EXTENSIONS",
0,
JOptionPane.QUESTION_MESSAGE,
None,
options,
options[0])
if response:
myPrint(u"B",u"User requested to ignore Outdated warning extensions going forward..... I will obey!!")
lIgnoreOutdatedExtensions_TB = True
else:
statusLabel.setText( (u"ALERT - YOU HAVE %s EXTENSION(S) THAT CAN BE UPGRADED!...STARTUP POPUP WARNINGS SUPPRESSED (by you)" %howMany ).ljust(800, " "))
statusLabel.setForeground(Color.BLUE)
return Toolbox_version
def check_for_old_StuWareSoftSystems_scripts(statusLabel):
global lPickle_version_warning, myParameters, i_am_an_extension_so_run_headless, debug
global MYPYTHON_DOWNLOAD_URL
lVersionWarning = False
if not myParameters and not lPickle_version_warning:
return
displayData = "\nStuWareSoftSystems: ALERT INFORMATION ABOUT SCRIPTS:\n\n"
if lPickle_version_warning:
displayData += "I detected an older (encrypted) version of saved parameter file for use with my Python scripts\n"
displayData += "No problem, I have updated / converted it.\n\n"
_MAJOR = 0
_MINOR = 1
iCountOldScripts = 0
if myParameters:
for key in sorted(myParameters.keys()):
if key.startswith("__") and key != "__Author":
myPrint("DB","Decoding old script versions for key: %s version_build: %s" %(key,myParameters[key]))
theVersion = extract_StuWareSoftSystems_version(myParameters[key])
if key == "__extract_currency_history_csv":
if theVersion[_MAJOR] < 1000:
pass
else: continue
elif key == "__StockGlance2020":
if theVersion[_MAJOR] < 1000:
pass
else: continue
elif key == "__extract_reminders_to_csv": # Old key - renamed... but see if it's around....
if theVersion[_MAJOR] < 1000:
pass
else: continue
elif key == "__extract_reminders_csv":
if theVersion[_MAJOR] < 1000:
pass
else: continue
elif key == "__extract_investment_transactions":
if theVersion[_MAJOR] < 1000:
pass
else: continue
else: continue
displayData+="ALERT: Script: %s is out of date - you have version_build: %s_%s\n" %(key,theVersion[_MAJOR],theVersion[_MINOR])
myPrint("DB", "Script %s is out of date - PLEASE UPDATE"%key)
iCountOldScripts+=1
lVersionWarning = True
if lPickle_version_warning or lVersionWarning:
displayData+="""
CURRENT SCRIPT VERSIONS ARE:
toolbox.py: >1000
extract_data: >1000
This is a consolidation of all prior extract scripts - including:
- stockglance2020.py:
- extract_reminders_csv.py:
- extract_currency_history_csv.py:
- extract_investment_transactions_csv.py:
- extract_account_registers_csv
Please update any that you use to at least these versions listed above....
Download from here: %s
""" %(MYPYTHON_DOWNLOAD_URL)
jif = QuickJFrame("StuWareSoftSystems - Scripts alert!", displayData, 1).show_the_frame()
statusLabel.setText( ("PLEASE UPDATE OLDER VERSIONS OF STUWARESOFTSYSTEMS SCRIPTS!...").ljust(800, " "))
statusLabel.setForeground(Color.BLUE)
myPopupInformationBox(jif, "You have %s older StuWareSoftSystems scripts - please upgrade them!" % iCountOldScripts, "STUWARESOFTSYSTEMS' SCRIPTS", JOptionPane.WARNING_MESSAGE)
return
def find_the_program_install_dir():
theDir = "" # noqa
if Platform.isOSX():
# Derive from these - not great, but OK: java.home, java.library.path, sun.boot.library.path
test = System.getProperty("java.home","").strip()
_i = test.lower().find(".app/") # noqa
if _i > 0:
theDir = test[:_i+4]
else:
theDir = System.getProperty("install4j.exeDir","").strip()
else:
theDir = System.getProperty("install4j.exeDir","").strip()
if not os.path.exists(theDir):
theDir = ""
return theDir
def get_orphaned_extension():
extension_prefs = moneydance_ui.getPreferences().getTableSetting("gen.fmodules",StreamTable())
# Get all keys in config dict
st,tk = read_preferences_file(lSaveFirst=True) # Must flush memory to disk first before we read the file....
confirmed_extn_keys = {}
for theKey in tk:
if not theKey.lower().startswith("confirmedext."):
continue # skip
confirmed_extn_keys[theKey.split('.')[1].lower().strip()] = theKey
outdated={}
x = moneydance.getOutdatedExtensionIDs()
for y in x: outdated[y.lower().strip()] = True
ok={}
x = moneydance.getLoadedModules()
for y in x: ok[str(y.getIDStr()).lower().strip()] = True
x = moneydance.getSuppressedExtensionIDs()
for y in x: ok[str(y).lower().strip()] = True
orphan_outdated_prefs = {}
for extn_pref in extension_prefs:
if not ok.get(extn_pref.lower().strip()) and not outdated.get(extn_pref.lower().strip()):
orphan_outdated_prefs[extn_pref] = "ORPHAN"
elif outdated.get(extn_pref.lower().strip()):
orphan_outdated_prefs[extn_pref] = "OUTDATED"
orphan_confirmed_extn_keys = {}
for extn_pref in confirmed_extn_keys:
if not ok.get(extn_pref.lower().strip()) and not outdated.get(extn_pref.lower().strip()):
orphan_confirmed_extn_keys[extn_pref] = ["ORPHAN",confirmed_extn_keys.get(extn_pref.lower().strip())]
elif outdated.get(extn_pref.lower().strip()):
orphan_confirmed_extn_keys[extn_pref] = ["OUTDATED",confirmed_extn_keys.get(extn_pref.lower().strip())]
orphan_outdated_files={}
extn_files_found=[]
extensionDir = Common.getFeatureModulesDirectory()
if extensionDir:
# noinspection PyTypeChecker
for root, dirs, files in os.walk(extensionDir.getAbsolutePath()):
for filename in files:
for extn in ModuleLoader.FEATURE_MODULE_EXTENSIONS:
if filename.endswith("."+extn):
# got an Extension
extn_files_found.append([os.path.splitext(filename)[0].lower().strip(),filename])
pass
for extn_file in extn_files_found:
if not ok.get(extn_file[0]):
if outdated.get(extn_file[0]):
orphan_outdated_files[extn_file[0]] = ["OUTDATED",extn_file[1]]
else:
orphan_outdated_files[extn_file[0]] = ["ORPHAN",extn_file[1]]
myPrint("DB","OK Extensions:", ok)
myPrint("DB","OUTDATED: Extensions:", outdated)
myPrint("DB","ORPHAN/OUTDATED Extension Preferences:", orphan_outdated_prefs)
myPrint("DB","ORPHAN/OUTDATED Extension Files:", orphan_outdated_files)
return [orphan_outdated_prefs, orphan_outdated_files, orphan_confirmed_extn_keys]
def diagnose_currencies(statusLabel, lFix=False):
global toolbox_frame_, debug, fixRCurrencyCheck, DARK_GREEN
myPrint("D", "In ", inspect.currentframe().f_code.co_name, "()" )
# reset_relative_currencies.py
if lFix:
myPrint("B", "Script running to FIX your relative currencies...............")
myPrint("P", "---------------------------------------------------------")
else:
myPrint("B", "Script running to diagnose your relative currencies...............")
myPrint("P", "---------------------------------------------------------")
if moneydance_data is None: return
VERBOSE=True
lFixErrors=lFixWarnings=False
lCurrencies=lSecurities=True
if lFix:
if not fixRCurrencyCheck:
statusLabel.setText(("Sorry, you must run 'DIAG: Diagnose Currencies' first!").ljust(800, " "))
statusLabel.setForeground(Color.RED)
myPopupInformationBox(toolbox_frame_,"Sorry, you must run the 'DIAG: Diagnose Currencies' option first! - NO CHANGES MADE!",theMessageType=JOptionPane.WARNING_MESSAGE)
return
elif fixRCurrencyCheck == 1:
statusLabel.setText(("'DIAG: Diagnose Currencies' reported no issues - so I will not run fixes").ljust(800, " "))
statusLabel.setForeground(Color.RED)
myPopupInformationBox(toolbox_frame_,"'DIAG: Diagnose Currencies' reported no issues - so I will not run fixes - NO CHANGES MADE!",theMessageType=JOptionPane.WARNING_MESSAGE)
return
elif fixRCurrencyCheck == 2:
pass
elif fixRCurrencyCheck != 3:
statusLabel.setText(("LOGIC ERROR reviewing 'DIAG: Diagnose Currencies' - so I will not run fixes").ljust(800, " "))
statusLabel.setForeground(Color.RED)
myPopupInformationBox(toolbox_frame_,"LOGIC ERROR reviewing 'DIAG: Diagnose Currencies' - so I will not run fixes - NO CHANGES MADE!",theMessageType=JOptionPane.WARNING_MESSAGE)
return
user_fixOnlyErrors = JRadioButton("Fix only Errors (ignore warnings)?", False)
user_fixErrorsAndWarnings = JRadioButton("Fix Errors AND warnings?", False)
bg1 = ButtonGroup()
bg1.add(user_fixOnlyErrors)
bg1.add(user_fixErrorsAndWarnings)
user_fixOnlyCurrencies = JRadioButton("Fix only Currencies?", False)
user_fixOnlySecurities = JRadioButton("Fix only Securities?", False)
user_fixBothCurrenciesAndSecurities = JRadioButton("Fix BOTH Currencies AND Securities?", False)
bg2 = ButtonGroup()
bg2.add(user_fixOnlyCurrencies)
bg2.add(user_fixOnlySecurities)
bg2.add(user_fixBothCurrenciesAndSecurities)
user_VERBOSE = JCheckBox("Verbose Output?",True)
userFilters = JPanel(GridLayout(0, 1))
if fixRCurrencyCheck != 2:
userFilters.add(user_fixOnlyErrors)
userFilters.add(user_fixErrorsAndWarnings)
userFilters.add(JLabel("-------------"))
userFilters.add(user_fixOnlyCurrencies)
userFilters.add(user_fixOnlySecurities)
userFilters.add(user_fixBothCurrenciesAndSecurities)
userFilters.add(JLabel("-------------"))
userFilters.add(user_VERBOSE)
while True:
options = ["EXIT", "PROCEED"]
userAction = (JOptionPane.showOptionDialog(toolbox_frame_,
userFilters,
"FIX RELATIVE CURRENCIES",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
moneydance_ui.getIcon("/com/moneydance/apps/md/view/gui/glyphs/appicon_64.png"),
options, options[0]))
if userAction != 1:
statusLabel.setText(("'FIX RELATIVE CURRENCIES' - No changes made.....").ljust(800, " "))
statusLabel.setForeground(Color.BLUE)
myPopupInformationBox(toolbox_frame_,"NO CHANGES MADE!",theMessageType=JOptionPane.WARNING_MESSAGE)
return
if not user_fixOnlyErrors.isSelected() and not user_fixErrorsAndWarnings.isSelected():
continue
if not user_fixOnlyCurrencies.isSelected() and not user_fixOnlySecurities.isSelected() and not user_fixBothCurrenciesAndSecurities.isSelected():
continue
break
del userFilters, bg1, bg2
if not confirm_backup_confirm_disclaimer(toolbox_frame_, statusLabel,"FIX RELATIVE CURRENCIES", "EXECUTE FIX RELATIVE CURRENCIES?"):
return
VERBOSE = user_VERBOSE.isSelected()
lFixErrors=True
lFixWarnings=user_fixErrorsAndWarnings.isSelected()
lCurrencies=(user_fixOnlyCurrencies.isSelected() or user_fixBothCurrenciesAndSecurities.isSelected())
lSecurities=(user_fixOnlySecurities.isSelected() or user_fixBothCurrenciesAndSecurities.isSelected())
# OK - let's do it!
fixRCurrencyCheck = None
lNeedFixScript = False
iWarnings = 0
currencies = moneydance_data.getCurrencies()
baseCurr = currencies.getBaseType()
if lFix:
output = "FIX RELATIVE CURRENCIES/SECURITIES\n" \
" =================================\n\n"
else:
output = "DIAGNOSE RELATIVE CURRENCIES & SECURITIES\n" \
" ========================================\n\n"
if lFix:
output += "FIX MODE:\n" \
" ========\n" \
"Parameters Selected:\n" \
"- Fix Errors: %s\n" \
"- Fix Errors and Warnings: %s\n" \
"- Fix Currencies: %s\n" \
"- Fix Securities: %s\n" \
"- VERBOSE: %s\n\n" \
% (lFixErrors, lFixWarnings, lCurrencies, lSecurities, VERBOSE)
if not lFix or lCurrencies:
output += "Analysing the Base currency setup....\n"
output += "Base currency: %s\n" % baseCurr
if baseCurr.getParameter("rrate", None) is None or baseCurr.getDoubleParameter("rrate", 0.0) != 1.0:
myPrint("J", "@@ERROR@@ - base currency %s has relative rate (rrate) <> 1: %s" %(baseCurr, baseCurr.getParameter("rrate", None)))
output += "----\n@@ ERROR @@ - base currency %s has relative rate (rrate) <> 1: %s\n----\n" %(baseCurr, baseCurr.getParameter("rrate", None))
lNeedFixScript = True
if lFix:
baseCurr.setParameter("rrate", 1.0)
myPrint("J", "@@CURRENCY FIX APPLIED@@")
output += "----\n@@CURRENCY FIX APPLIED@@\n----\n"
if baseCurr.getParameter("rate", None) is None or baseCurr.getDoubleParameter("rate", 0.0) != 1.0:
myPrint("J", "@@ERROR@@ - base currency has rate <> 1: %s" %(baseCurr.getParameter("rate", None)))
output += "----\n@@ ERROR @@ - base currency has rate <> 1: %s\n----\n" %(baseCurr.getParameter("rate", None))
lNeedFixScript = True
if lFix:
baseCurr.setParameter("rate", 1.0)
myPrint("J", "@@CURRENCY FIX APPLIED@@")
output += "----\n@@CURRENCY FIX APPLIED@@\n----\n"
if lFix and lNeedFixScript:
baseCurr.syncItem()
if not lNeedFixScript:
output += ("Base currency has Rate (rate) of: %s and Relative Rate (rrate): of %s. This is Correct...\n"
% (baseCurr.getParameter("rate", None), baseCurr.getParameter("rrate", None)))
baseSnapshots = baseCurr.getSnapshots()
if baseSnapshots.size() > 0:
lNeedFixScript = True
myPrint("J","ERROR: base currency has %s historical prices! These need to be deleted!" % (baseSnapshots.size()))
output += "----\n@@ | |
#/*
# * Copyright (c) 2019,2020 Xilinx Inc. All rights reserved.
# *
# * Author:
# * <NAME> <<EMAIL>>
# *
# * SPDX-License-Identifier: BSD-3-Clause
# */
import copy
import struct
import sys
import types
import unittest
import os
import getopt
import re
import subprocess
import shutil
from pathlib import Path
from pathlib import PurePath
from io import StringIO
import contextlib
import importlib
from lopper import Lopper
from lopper import LopperFmt
import lopper
from lopper.tree import *
from re import *
sys.path.append(os.path.dirname(__file__))
from openamp_xlnx_common import *
RPU_PATH = "/rpu@ff9a0000"
def is_compat( node, compat_string_to_test ):
if re.search( "openamp,xlnx-rpu", compat_string_to_test):
return xlnx_openamp_rpu
return ""
def xlnx_openamp_rpmsg_expand(tree, subnode, verbose = 0 ):
# Xilinx-specific YAML expansion of RPMsg description.
return True
def xlnx_openamp_remoteproc_expand(tree, subnode, verbose = 0 ):
# Xilinx-specific YAML expansion of Remoteproc description.
return True
def update_mbox_cntr_intr_parent(sdt):
# find phandle of a72 gic for mailbox controller
a72_gic_node = sdt.tree["/amba_apu/interrupt-controller@f9000000"]
# set mailbox controller interrupt-parent to this phandle
mailbox_cntr_node = sdt.tree["/zynqmp_ipi1"]
mailbox_cntr_node["interrupt-parent"].value = a72_gic_node.phandle
sdt.tree.sync()
sdt.tree.resolve()
# 1 for master, 0 for slave
# for each openamp channel, return mapping of role to resource group
def determine_role(sdt, domain_node):
rsc_groups = []
current_rsc_group = None
for value in domain_node.propval('include'):
current_rsc_group = sdt.tree.pnode(value)
if domain_node.propval(HOST_FLAG) != ['']: # only for openamp master
if current_rsc_group == None:
print("invalid resource group phandle: ", value)
return -1
rsc_groups.append(current_rsc_group)
else:
print("only do processing in host openamp channel domain ", value)
return -1
return rsc_groups
# in this case remote is rpu
# find node that is other end of openamp channel
def find_remote(sdt, domain_node, rsc_group_node):
domains = sdt.tree["/domains"]
# find other domain including the same resource group
remote_domain = None
for node in domains.subnodes():
# look for other domains with include
if node.propval("include") != [''] and node != domain_node:
# if node includes same rsc group, then this is remote
for i in node.propval("include"):
included_node = sdt.tree.pnode(i)
if included_node != None and included_node == rsc_group_node:
return node
return -1
# tests for a bit that is set, going fro 31 -> 0 from MSB to LSB
def check_bit_set(n, k):
if n & (1 << (k)):
return True
return False
# return rpu cluster configuration
# rpu cpus property fields: Cluster | cpus-mask | execution-mode
#
#execution mode ARM-R CPUs:
#bit 30: lockstep (lockstep enabled == 1)
#bit 31: secure mode / normal mode (secure mode == 1)
# e.g. &cpus_r5 0x2 0x80000000>
# this maps to arg1 as rpu_cluster node
# arg2: cpus-mask: 0x2 is r5-1, 0x1 is r5-0, 0x3 is both nodes
# if 0x3/both nodes and in split then need to openamp channels provided,
# otherwise return error
# if lockstep valid cpus-mask is 0x3 needed to denote both being used
#
def construct_carveouts(sdt, rsc_group_node, core, openamp_app_inputs):
# static var that persists beyond lifetime of first function call
# this is needed as there may be more than 1 openamp channel
# so multiple carveouts' phandles are required
if not hasattr(construct_carveouts,"carveout_phandle"):
# it doesn't exist yet, so initialize it
construct_carveouts.carveout_phandle = 0x5ed0
# carveouts each have addr,range
mem_regions = [[0 for x in range(2)] for y in range(4)]
mem_region_names = {
0 : "elfload",
1 : "vdev0vring0",
2 : "vdev0vring1",
3 : "vdev0buffer",
}
carveout_phandle_list = []
for index,value in enumerate(rsc_group_node["memory"].value):
if index % 2 == 1:
continue
region_name = mem_region_names[index/2]
name = "rpu"+str(core)+region_name
addr = value
length = rsc_group_node["memory"].value[index + 1]
openamp_app_inputs[rsc_group_node.name + region_name + '_base'] = hex(value)
openamp_app_inputs[rsc_group_node.name + region_name + '_size'] = hex(length)
new_node = LopperNode(-1, "/reserved-memory/"+name)
new_node + LopperProp(name="no-map", value=[])
new_node + LopperProp(name="reg",value=[0,addr,0,length])
new_node + LopperProp(name="phandle",value=construct_carveouts.carveout_phandle)
new_node.phandle = new_node
sdt.tree.add(new_node)
print("added node: ",new_node)
carveout_phandle_list.append(construct_carveouts.carveout_phandle)
construct_carveouts.carveout_phandle += 1
return carveout_phandle_list
def construct_mem_region(sdt, domain_node, rsc_group_node, core, openamp_app_inputs):
# add reserved mem if not present
res_mem_node = None
carveout_phandle_list = None
try:
res_mem_node = sdt.tree["/reserved-memory"]
print("found pre-existing reserved mem node")
except:
res_mem_node = LopperNode(-1, "/reserved-memory")
res_mem_node + LopperProp(name="#address-cells",value=2)
res_mem_node + LopperProp(name="#size-cells",value=2)
res_mem_node + LopperProp(name="ranges",value=[])
sdt.tree.add(res_mem_node)
print("added reserved mem node ", res_mem_node)
return construct_carveouts(sdt, rsc_group_node, core, openamp_app_inputs)
# set pnode id for current rpu node
def set_rpu_pnode(sdt, r5_node, rpu_config, core, platform, remote_domain):
if r5_node.propval("power-domain") != ['']:
print("pnode id already exists for node ", r5_node)
return -1
rpu_pnodes = {}
if platform == SOC_TYPE.VERSAL:
rpu_pnodes = {0 : 0x18110005, 1: 0x18110006}
elif platform == SOC_TYPE.ZYNQMP:
rpu_pnodes = {0 : 0x7, 1: 0x8}
else:
print("only versal supported for openamp domains")
return -1
rpu_pnode = None
# rpu config : true is split
if rpu_config == "lockstep":
rpu_pnode = rpu_pnodes[0]
else:
rpu_pnode = rpu_pnodes[core]
r5_node + LopperProp(name="power-domain", value = rpu_pnodes[core])
r5_node.sync(sdt.FDT)
return
def setup_mbox_info(sdt, domain_node, r5_node, mbox_ctr):
mbox_ctr.phandle = sdt.tree.phandle_gen()
if mbox_ctr.propval("reg-names") == [''] or mbox_ctr.propval("xlnx,ipi-id") == ['']:
print("invalid mbox ctr")
return -1
mbox_ctr_phandle = mbox_ctr.propval("phandle")
r5_node + LopperProp(name="mboxes",value=[mbox_ctr_phandle,0,mbox_ctr_phandle,1])
r5_node + LopperProp(name="mbox-names", value = ["tx", "rx"]);
sdt.tree.sync()
r5_node.sync(sdt.FDT)
return
# based on rpu_cluster_config + cores determine which tcm nodes to use
# add tcm nodes to device tree
def setup_tcm_nodes(sdt, r5_node, platform, rsc_group_node):
# determine which tcm nodes to use based on access list in rsc group
for i in rsc_group_node["access"].value:
tcm_node = sdt.tree.pnode(i)
print(tcm_node)
if tcm_node != None and tcm_node.propval("phandle") == ['']:
tcm_node + LopperProp( name="phandle", value = tcm_node.phandle )
r5_node + LopperProp(name="sram", value = rsc_group_node["access"].value.copy() )
return 0
def setup_r5_core_node(rpu_config, sdt, domain_node, rsc_group_node, core, remoteproc_node, platform, remote_domain, mbox_ctr, openamp_app_inputs):
carveout_phandle_list = None
r5_node = None
# add r5 node if not present
try:
r5_node = sdt.tree["/rpu@ff9a0000/r5_"+str(core)]
print("node already exists: ", r5_node)
except:
r5_node = LopperNode(-1, "/rpu@ff9a0000/r5_"+str(core))
r5_node + LopperProp(name="#address-cells",value=2)
r5_node + LopperProp(name="#size-cells",value=2)
r5_node + LopperProp(name="ranges",value=[])
r5_node + LopperProp(name="compatible",value="xilinx,r5f")
sdt.tree.add(r5_node)
print("added r5 node ", r5_node)
print("add props for ",str(r5_node))
# props
ret = set_rpu_pnode(sdt, r5_node, rpu_config, core, platform, remote_domain)
if ret == -1:
print("set_rpu_pnode failed")
return ret
ret = setup_mbox_info(sdt, domain_node, r5_node, mbox_ctr)
if ret == -1:
print("setup_mbox_info failed")
return ret
carveout_phandle_list = construct_mem_region(sdt, domain_node, rsc_group_node, core, openamp_app_inputs)
if carveout_phandle_list == -1:
print("construct_mem_region failed")
return ret
if carveout_phandle_list != None:
print("adding prop memory-region to ",r5_node)
r5_node + LopperProp(name="memory-region",value=carveout_phandle_list)
#tcm nodes
for i in r5_node.subnodes():
if "tcm" in i.abs_path:
"tcm nodes exist"
return -1
# tcm nodes do not exist. set them up
setup_tcm_nodes(sdt, r5_node, platform, rsc_group_node)
# add props to remoteproc node
def set_remoteproc_node(remoteproc_node, sdt, rpu_config):
props = []
props.append(LopperProp(name="reg", value = [0x0, 0xff9a0000, 0x0, 0x10000]))
props.append(LopperProp(name="#address-cells",value=2))
props.append(LopperProp(name="ranges",value=[]))
props.append(LopperProp(name="#size-cells",value=2))
if rpu_config == "split":
rpu_config = 0x1
else:
rpu_config = 0x0
props.append(LopperProp(name="xlnx,cluster-mode",value=rpu_config))
props.append(LopperProp(name="compatible",value="xlnx,zynqmp-r5-remoteproc"))
for i in props:
remoteproc_node + i
#
def determine_core(remote_domain):
cpus_prop_val = remote_domain.propval("cpus")
rpu_config = None # split or lockstep
if cpus_prop_val != ['']:
if len(cpus_prop_val) != 3:
print("rpu cluster cpu prop invalid len")
return -1
rpu_config = "lockstep" if check_bit_set(cpus_prop_val[2], 30)==True else "split"
if rpu_config == "lockstep":
core = 0
else:
core_prop_val = remote_domain.propval("cpus")
if core_prop_val == ['']:
print("no cpus val for core ", remote_domain)
else:
if core_prop_val[1] == 2:
core = 1
elif core_prop_val[1] == 1:
core = 0
else:
print("invalid cpu prop for core ", remote_domain, core_prop_val[1])
return -1
return [core, rpu_config]
#core = []
# this should only add nodes to tree
# openamp_app_inputs: dictionary to fill with openamp header info for openamp code base later on
def construct_remoteproc_node(remote_domain, rsc_group_node, sdt, domain_node, platform, mbox_ctr, openamp_app_inputs):
rpu_config = None # split or lockstep
core = 0
[core, rpu_config] = determine_core(remote_domain)
# only add remoteproc node if mbox is present in access list of domain node
# check domain's access list for mbox
has_corresponding_mbox = False
if domain_node.propval("access") != ['']:
for i in domain_node.propval("access"):
possible_mbox = sdt.tree.pnode(i)
if possible_mbox != None:
if possible_mbox.propval("reg-names") != ['']:
has_corresponding_mbox = True
# setup remoteproc node if not already present
remoteproc_node = None
try:
remoteproc_node = sdt.tree["/rpu@ff9a0000"]
except:
print("remoteproc node not present. now add it to tree")
remoteproc_node = LopperNode(-1, "/rpu@ff9a0000")
set_remoteproc_node(remoteproc_node, sdt, rpu_config)
sdt.tree.add(remoteproc_node, dont_sync = True)
remoteproc_node.sync(sdt.FDT)
remoteproc_node.resolve_all_refs()
sdt.tree.sync()
return setup_r5_core_node(rpu_config, sdt, domain_node, rsc_group_node, core, remoteproc_node, platform, remote_domain, mbox_ctr, openamp_app_inputs)
def validate_ipi_node(ipi_node, platform):
if ipi_node == None:
print("invalid "+role+" IPI - invalid phandle from access property.")
return False
if 'xlnx,zynqmp-ipi-mailbox' not in ipi_node.propval("compatible"):
print("invalid "+role+" IPI - wrong compatible string")
return False
ipi_base_addr = ipi_node.propval("reg")
if len(ipi_base_addr) != 4:
print("invalid "+role+" IPI - incorrect reg property of ipi", ipi_node)
return False
if platform == SOC_TYPE.VERSAL:
if ipi_base_addr[1] not in openamp_supported_ipis:
print(hex(ipi_base_addr[1]), "not supported")
return False
elif platform == SOC_TYPE.ZYNQMP:
if ipi_base_addr[1] in | |
from keras import backend as K
from keras.applications.imagenet_utils import _obtain_input_shape
from keras.models import Model
from keras.engine.topology import get_source_inputs
from keras.layers import Activation, Add, Concatenate, GlobalAveragePooling2D,GlobalMaxPooling2D, Input, Dense
from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, BatchNormalization, Lambda
from keras.applications.mobilenet import DepthwiseConv2D
import numpy as np
def ShuffleNet(include_top=True, input_tensor=None, scale_factor=1.0, pooling='max',
input_shape=(224,224,3), groups=1, load_model=None, num_shuffle_units=[3, 7, 3],
bottleneck_ratio=0.25, classes=1000):
"""
ShuffleNet implementation for Keras 2
ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices
<NAME>, <NAME>, <NAME>, <NAME>
https://arxiv.org/pdf/1707.01083.pdf
Note that only TensorFlow is supported for now, therefore it only works
with the data format `image_data_format='channels_last'` in your Keras
config at `~/.keras/keras.json`.
Parameters
----------
include_top: bool(True)
whether to include the fully-connected layer at the top of the network.
input_tensor:
optional Keras tensor (i.e. output of `layers.Input()`) to use as image input for the model.
scale_factor:
scales the number of output channels
input_shape:
pooling:
Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model
will be the 4D tensor output of the
last convolutional layer.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional layer, and thus
the output of the model will be a
2D tensor.
- `max` means that global max pooling will
be applied.
groups: int
number of groups per channel
num_shuffle_units: list([3,7,3])
number of stages (list length) and the number of shufflenet units in a
stage beginning with stage 2 because stage 1 is fixed
e.g. idx 0 contains 3 + 1 (first shuffle unit in each stage differs) shufflenet units for stage 2
idx 1 contains 7 + 1 Shufflenet Units for stage 3 and
idx 2 contains 3 + 1 Shufflenet Units
bottleneck_ratio:
bottleneck ratio implies the ratio of bottleneck channels to output channels.
For example, bottleneck ratio = 1 : 4 means the output feature map is 4 times
the width of the bottleneck feature map.
classes: int(1000)
number of classes to predict
Returns
-------
A Keras model instance
References
----------
- [ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices]
(http://www.arxiv.org/pdf/1707.01083.pdf)
"""
if K.backend() != 'tensorflow':
raise RuntimeError('Only TensorFlow backend is currently supported, '
'as other backends do not support ')
name = "ShuffleNet_%.2gX_g%d_br_%.2g_%s" % (scale_factor, groups, bottleneck_ratio, "".join([str(x) for x in num_shuffle_units]))
input_shape = _obtain_input_shape(input_shape,
default_size=224,
min_size=28,
require_flatten=include_top,
data_format=K.image_data_format())
out_dim_stage_two = {1: 144, 2: 200, 3: 240, 4: 272, 8: 384}
if groups not in out_dim_stage_two:
raise ValueError("Invalid number of groups.")
if pooling not in ['max','avg']:
raise ValueError("Invalid value for pooling.")
if not (float(scale_factor) * 4).is_integer():
raise ValueError("Invalid value for scale_factor. Should be x over 4.")
exp = np.insert(np.arange(0, len(num_shuffle_units), dtype=np.float32), 0, 0)
out_channels_in_stage = 2 ** exp
out_channels_in_stage *= out_dim_stage_two[groups] # calculate output channels for each stage
out_channels_in_stage[0] = 24 # first stage has always 24 output channels
out_channels_in_stage *= scale_factor
out_channels_in_stage = out_channels_in_stage.astype(int)
if input_tensor is None:
img_input = Input(shape=input_shape)
else:
if not K.is_keras_tensor(input_tensor):
img_input = Input(tensor=input_tensor, shape=input_shape)
else:
img_input = input_tensor
# create shufflenet architecture
x = Conv2D(filters=out_channels_in_stage[0], kernel_size=(3, 3), padding='same',
use_bias=False, strides=(2, 2), activation="relu", name="conv1")(img_input)
x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same', name="maxpool1")(x)
# create stages containing shufflenet units beginning at stage 2
for stage in range(0, len(num_shuffle_units)):
repeat = num_shuffle_units[stage]
x = _block(x, out_channels_in_stage, repeat=repeat,
bottleneck_ratio=bottleneck_ratio,
groups=groups, stage=stage + 2)
if pooling == 'avg':
x = GlobalAveragePooling2D(name="global_pool")(x)
elif pooling == 'max':
x = GlobalMaxPooling2D(name="global_pool")(x)
if include_top:
x = Dense(units=classes, name="fc")(x)
x = Activation('softmax', name='softmax')(x)
if input_tensor is not None:
inputs = get_source_inputs(input_tensor)
else:
inputs = img_input
model = Model(inputs=inputs, outputs=x, name=name)
if load_model is not None:
model.load_weights('', by_name=True)
return model
def _block(x, channel_map, bottleneck_ratio, repeat=1, groups=1, stage=1):
"""
creates a bottleneck block containing `repeat + 1` shuffle units
Parameters
----------
x:
Input tensor of with `channels_last` data format
channel_map: list
list containing the number of output channels for a stage
repeat: int(1)
number of repetitions for a shuffle unit with stride 1
groups: int(1)
number of groups per channel
bottleneck_ratio: float
bottleneck ratio implies the ratio of bottleneck channels to output channels.
For example, bottleneck ratio = 1 : 4 means the output feature map is 4 times
the width of the bottleneck feature map.
stage: int(1)
stage number
Returns
-------
"""
x = _shuffle_unit(x, in_channels=channel_map[stage - 2],
out_channels=channel_map[stage - 1], strides=2,
groups=groups, bottleneck_ratio=bottleneck_ratio,
stage=stage, block=1)
for i in range(1, repeat + 1):
x = _shuffle_unit(x, in_channels=channel_map[stage - 1],
out_channels=channel_map[stage - 1], strides=1,
groups=groups, bottleneck_ratio=bottleneck_ratio,
stage=stage, block=(i + 1))
return x
def _shuffle_unit(inputs, in_channels, out_channels, groups, bottleneck_ratio, strides=2, stage=1, block=1):
"""
creates a shuffleunit
Parameters
----------
inputs:
Input tensor of with `channels_last` data format
in_channels:
number of input channels
out_channels:
number of output channels
strides:
An integer or tuple/list of 2 integers,
specifying the strides of the convolution along the width and height.
groups: int(1)
number of groups per channel
bottleneck_ratio: float
bottleneck ratio implies the ratio of bottleneck channels to output channels.
For example, bottleneck ratio = 1 : 4 means the output feature map is 4 times
the width of the bottleneck feature map.
stage: int(1)
stage number
block: int(1)
block number
Returns
-------
"""
if K.image_data_format() == 'channels_last':
bn_axis = -1
else:
bn_axis = 1
prefix = 'stage%d/block%d' % (stage, block)
#if strides >= 2:
#out_channels -= in_channels
# default: 1/4 of the output channel of a ShuffleNet Unit
bottleneck_channels = int(out_channels * bottleneck_ratio)
groups = (1 if stage == 2 and block == 1 else groups)
x = _group_conv(inputs, in_channels, out_channels=bottleneck_channels,
groups=(1 if stage == 2 and block == 1 else groups),
name='%s/1x1_gconv_1' % prefix)
x = BatchNormalization(axis=bn_axis, name='%s/bn_gconv_1' % prefix)(x)
x = Activation('relu', name='%s/relu_gconv_1' % prefix)(x)
x = Lambda(channel_shuffle, arguments={'groups': groups}, name='%s/channel_shuffle' % prefix)(x)
x = DepthwiseConv2D(kernel_size=(3, 3), padding="same", use_bias=False,
strides=strides, name='%s/1x1_dwconv_1' % prefix)(x)
x = BatchNormalization(axis=bn_axis, name='%s/bn_dwconv_1' % prefix)(x)
x = _group_conv(x, bottleneck_channels, out_channels=out_channels if strides == 1 else out_channels - in_channels,
groups=groups, name='%s/1x1_gconv_2' % prefix)
x = BatchNormalization(axis=bn_axis, name='%s/bn_gconv_2' % prefix)(x)
if strides < 2:
ret = Add(name='%s/add' % prefix)([x, inputs])
else:
avg = AveragePooling2D(pool_size=3, strides=2, padding='same', name='%s/avg_pool' % prefix)(inputs)
ret = Concatenate(bn_axis, name='%s/concat' % prefix)([x, avg])
ret = Activation('relu', name='%s/relu_out' % prefix)(ret)
return ret
def _group_conv(x, in_channels, out_channels, groups, kernel=1, stride=1, name=''):
"""
grouped convolution
Parameters
----------
x:
Input tensor of with `channels_last` data format
in_channels:
number of input channels
out_channels:
number of output channels
groups:
number of groups per channel
kernel: int(1)
An integer or tuple/list of 2 integers, specifying the
width and height of the 2D convolution window.
Can be a single integer to specify the same value for
all spatial dimensions.
stride: int(1)
An integer or tuple/list of 2 integers,
specifying the strides of the convolution along the width and height.
Can be a single integer to specify the same value for all spatial dimensions.
name: str
A string to specifies the layer name
Returns
-------
"""
if groups == 1:
return Conv2D(filters=out_channels, kernel_size=kernel, padding='same',
use_bias=False, strides=stride, name=name)(x)
# number of intput channels per group
ig = in_channels // groups
group_list = []
assert out_channels % groups == 0
for i in range(groups):
offset = i * ig
group = Lambda(lambda z: z[:, :, :, offset: offset + ig], name='%s/g%d_slice' % (name, i))(x)
group_list.append(Conv2D(int(0.5 + out_channels / groups), kernel_size=kernel, strides=stride,
use_bias=False, padding='same', name='%s_/g%d' % (name, i))(group))
return Concatenate(name='%s/concat' % name)(group_list)
def channel_shuffle(x, groups):
"""
Parameters
----------
x:
Input tensor of with `channels_last` data format
groups: int
number of groups per channel
Returns
-------
channel shuffled output tensor
Examples
--------
Example for a 1D Array with 3 groups
>>> d = np.array([0,1,2,3,4,5,6,7,8])
>>> x = np.reshape(d, (3,3))
>>> x = np.transpose(x, [1,0])
>>> x = np.reshape(x, (9,))
'[0 1 2 3 4 5 6 7 8] --> [0 3 6 1 4 7 2 5 8]'
"""
height, width, in_channels = x.shape.as_list()[1:]
channels_per_group = in_channels // groups
x = K.reshape(x, [-1, height, width, groups, channels_per_group])
x = K.permute_dimensions(x, (0, 1, 2, 4, 3)) | |
#
# Copyright (c) 2015-2020 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
import json
import pecan
from pecan import rest
import six
from six.moves import http_client as httplib
from wsme import types as wsme_types
import wsmeext.pecan as wsme_pecan
from nfv_common import debug
from nfv_common import validate
from nfv_vim import rpc
from nfv_vim.api.controllers.v1.orchestration.sw_update._sw_update_defs import SW_UPDATE_ACTION
from nfv_vim.api.controllers.v1.orchestration.sw_update._sw_update_defs import SW_UPDATE_ALARM_RESTRICTION_TYPES
from nfv_vim.api.controllers.v1.orchestration.sw_update._sw_update_defs import SW_UPDATE_APPLY_TYPE
from nfv_vim.api.controllers.v1.orchestration.sw_update._sw_update_defs import SW_UPDATE_INSTANCE_ACTION
from nfv_vim.api.controllers.v1.orchestration.sw_update._sw_update_defs import SW_UPDATE_NAME
from nfv_vim.api.controllers.v1.orchestration.sw_update._sw_update_defs import SwUpdateActions
from nfv_vim.api.controllers.v1.orchestration.sw_update._sw_update_defs import SwUpdateAlarmRestrictionTypes
from nfv_vim.api.controllers.v1.orchestration.sw_update._sw_update_defs import SwUpdateApplyTypes
from nfv_vim.api.controllers.v1.orchestration.sw_update._sw_update_defs import SwUpdateInstanceActionTypes
from nfv_vim.api.controllers.v1.orchestration.sw_update._sw_update_defs import SwUpdateNames
DLOG = debug.debug_get_logger('nfv_vim.api.sw_update.strategy')
MIN_PARALLEL_HOSTS = 2
MAX_PARALLEL_PATCH_HOSTS = 100
MAX_PARALLEL_UPGRADE_HOSTS = 10
MAX_PARALLEL_FW_UPDATE_HOSTS = 5
def _get_sw_update_type_from_path(path):
split_path = path.split('/')
if 'sw-patch' in split_path:
return SW_UPDATE_NAME.SW_PATCH
elif 'sw-upgrade' in split_path:
return SW_UPDATE_NAME.SW_UPGRADE
elif 'fw-update' in split_path:
return SW_UPDATE_NAME.FW_UPDATE
else:
DLOG.error("Unknown sw_update_type in path: %s" % path)
return 'unknown'
class SwUpdateStrategyStageStepData(wsme_types.Base):
"""
Software Update Strategy - Stage Step Data
"""
step_id = wsme_types.wsattr(int, name='step-id')
step_name = wsme_types.wsattr(six.text_type, name='step-name')
timeout = wsme_types.wsattr(int, name='timeout')
entity_type = wsme_types.wsattr(six.text_type, name='entity-type')
entity_uuids = wsme_types.wsattr([six.text_type], name='entity-uuids')
entity_names = wsme_types.wsattr([six.text_type], name='entity-names')
result = wsme_types.wsattr(six.text_type, name='result')
reason = wsme_types.wsattr(six.text_type, name='reason')
start_date_time = wsme_types.wsattr(six.text_type, name='start-date-time')
end_date_time = wsme_types.wsattr(six.text_type, name='end-date-time')
class SwUpdateStrategyStageData(wsme_types.Base):
"""
Software Update Strategy - Stage Data
"""
stage_id = wsme_types.wsattr(int, name='stage-id')
stage_name = wsme_types.wsattr(six.text_type, name='stage-name')
timeout = wsme_types.wsattr(int, name='timeout')
total_steps = wsme_types.wsattr(int, name='total-steps')
current_step = wsme_types.wsattr(int, name='current-step')
steps = wsme_types.wsattr([SwUpdateStrategyStageStepData], name='steps')
inprogress = wsme_types.wsattr(bool, name='inprogress')
result = wsme_types.wsattr(six.text_type, name='result')
reason = wsme_types.wsattr(six.text_type, name='reason')
start_date_time = wsme_types.wsattr(six.text_type, name='start-date-time')
end_date_time = wsme_types.wsattr(six.text_type, name='end-date-time')
class SwUpdateStrategyPhaseData(wsme_types.Base):
"""
Software Update Strategy - Phase Data
"""
phase_name = wsme_types.wsattr(six.text_type, name='phase-name')
timeout = wsme_types.wsattr(int, name='timeout')
total_stages = wsme_types.wsattr(int, name='total-stages')
current_stage = wsme_types.wsattr(int, name='current-stage')
stop_at_stage = wsme_types.wsattr(int, name='stop-at-stage')
stages = wsme_types.wsattr([SwUpdateStrategyStageData], name='stages')
inprogress = wsme_types.wsattr(bool, name='inprogress')
completion_percentage = wsme_types.wsattr(int, name='completion-percentage')
result = wsme_types.wsattr(six.text_type, name='result')
reason = wsme_types.wsattr(six.text_type, name='reason')
start_date_time = wsme_types.wsattr(six.text_type, name='start-date-time')
end_date_time = wsme_types.wsattr(six.text_type, name='end-date-time')
class SwUpdateStrategyData(wsme_types.Base):
"""
Software Update Strategy - Data
"""
uuid = wsme_types.wsattr(six.text_type, name='uuid')
name = wsme_types.wsattr(SwUpdateNames, name='name')
controller_apply_type = wsme_types.wsattr(SwUpdateApplyTypes,
name='controller-apply-type')
storage_apply_type = wsme_types.wsattr(SwUpdateApplyTypes,
name='storage-apply-type')
swift_apply_type = wsme_types.wsattr(SwUpdateApplyTypes,
name='swift-apply-type')
worker_apply_type = wsme_types.wsattr(SwUpdateApplyTypes,
name='worker-apply-type')
max_parallel_worker_hosts = wsme_types.wsattr(
int, name='max-parallel-worker-hosts')
default_instance_action = wsme_types.wsattr(SwUpdateInstanceActionTypes,
name='default-instance-action')
alarm_restrictions = wsme_types.wsattr(SwUpdateAlarmRestrictionTypes,
name='alarm-restrictions')
state = wsme_types.wsattr(six.text_type, name='state')
current_phase = wsme_types.wsattr(six.text_type, name='current-phase')
current_phase_completion_percentage \
= wsme_types.wsattr(int, name='current-phase-completion-percentage')
build_phase = wsme_types.wsattr(SwUpdateStrategyPhaseData, name='build-phase')
apply_phase = wsme_types.wsattr(SwUpdateStrategyPhaseData, name='apply-phase')
abort_phase = wsme_types.wsattr(SwUpdateStrategyPhaseData, name='abort-phase')
class SwPatchStrategyCreateData(wsme_types.Base):
"""
Software Patch Strategy - Create Data
"""
controller_apply_type = wsme_types.wsattr(SwUpdateApplyTypes, mandatory=True,
name='controller-apply-type')
storage_apply_type = wsme_types.wsattr(SwUpdateApplyTypes, mandatory=True,
name='storage-apply-type')
swift_apply_type = wsme_types.wsattr(SwUpdateApplyTypes, mandatory=False,
name='swift-apply-type')
worker_apply_type = wsme_types.wsattr(SwUpdateApplyTypes, mandatory=True,
name='worker-apply-type')
max_parallel_worker_hosts = wsme_types.wsattr(
int, mandatory=False, name='max-parallel-worker-hosts')
default_instance_action = wsme_types.wsattr(SwUpdateInstanceActionTypes,
mandatory=True,
name='default-instance-action')
alarm_restrictions = wsme_types.wsattr(
SwUpdateAlarmRestrictionTypes, mandatory=False,
default=SW_UPDATE_ALARM_RESTRICTION_TYPES.STRICT,
name='alarm-restrictions')
class SwUpgradeStrategyCreateData(wsme_types.Base):
"""
Software Upgrade Strategy - Create Data
"""
storage_apply_type = wsme_types.wsattr(SwUpdateApplyTypes, mandatory=True,
name='storage-apply-type')
worker_apply_type = wsme_types.wsattr(SwUpdateApplyTypes, mandatory=True,
name='worker-apply-type')
max_parallel_worker_hosts = wsme_types.wsattr(
int, mandatory=False, name='max-parallel-worker-hosts')
# Disable support for start-upgrade as it was not completed
# start_upgrade = wsme_types.wsattr(
# bool, mandatory=False, default=False, name='start-upgrade')
complete_upgrade = wsme_types.wsattr(
bool, mandatory=False, default=False, name='complete-upgrade')
alarm_restrictions = wsme_types.wsattr(
SwUpdateAlarmRestrictionTypes, mandatory=False,
default=SW_UPDATE_ALARM_RESTRICTION_TYPES.STRICT,
name='alarm-restrictions')
class SwUpdateStrategyDeleteData(wsme_types.Base):
"""
Software Update Strategy - Delete Data
"""
force = wsme_types.wsattr(bool, mandatory=False, name='force',
default=False)
class FwUpdateStrategyCreateData(wsme_types.Base):
"""
Firmware Update Strategy - Create Data
"""
controller_apply_type = wsme_types.wsattr(SwUpdateApplyTypes, mandatory=True,
name='controller-apply-type')
storage_apply_type = wsme_types.wsattr(SwUpdateApplyTypes, mandatory=True,
name='storage-apply-type')
worker_apply_type = wsme_types.wsattr(SwUpdateApplyTypes, mandatory=True,
name='worker-apply-type')
max_parallel_worker_hosts = wsme_types.wsattr(
int, mandatory=False, name='max-parallel-worker-hosts')
default_instance_action = wsme_types.wsattr(SwUpdateInstanceActionTypes,
mandatory=True,
name='default-instance-action')
alarm_restrictions = wsme_types.wsattr(
SwUpdateAlarmRestrictionTypes, mandatory=False,
default=SW_UPDATE_ALARM_RESTRICTION_TYPES.STRICT,
name='alarm-restrictions')
class SwUpdateStrategyActionData(wsme_types.Base):
"""
Software Update Strategy - Action Data
"""
action = wsme_types.wsattr(SwUpdateActions, mandatory=True, name='action')
stage_id = wsme_types.wsattr(int, mandatory=False, name='stage-id')
class SwUpdateStrategyQueryData(wsme_types.Base):
"""
Software Update Strategy - Query Data
"""
strategy = wsme_types.wsattr(SwUpdateStrategyData, default=None,
name='strategy')
@staticmethod
def convert_strategy_phase(phase_data):
phase = SwUpdateStrategyPhaseData()
phase.phase_name = phase_data['name']
phase.timeout = phase_data['timeout']
phase.total_stages = phase_data['total_stages']
phase.current_stage = phase_data['current_stage']
phase.stop_at_stage = phase_data['stop_at_stage']
phase.stages = list()
for stage_data in phase_data['stages']:
stage = SwUpdateStrategyStageData()
stage.stage_id = stage_data['id']
stage.stage_name = stage_data['name']
stage.timeout = stage_data['timeout']
stage.total_steps = stage_data['total_steps']
stage.current_step = stage_data['current_step']
stage.steps = list()
for step_data in stage_data['steps']:
step = SwUpdateStrategyStageStepData()
step.step_id = step_data['id']
step.step_name = step_data['name']
step.timeout = step_data['timeout']
step.entity_type = step_data['entity_type']
step.entity_uuids = step_data['entity_uuids']
step.entity_names = step_data['entity_names']
step.result = step_data['result']
step.reason = step_data['result_reason']
step.start_date_time = step_data['start_date_time']
step.end_date_time = step_data['end_date_time']
stage.steps.append(step)
stage.inprogress = stage_data['inprogress']
stage.result = stage_data['result']
stage.reason = stage_data['result_reason']
stage.start_date_time = stage_data['start_date_time']
stage.end_date_time = stage_data['end_date_time']
phase.stages.append(stage)
phase.inprogress = phase_data['inprogress']
phase.completion_percentage = phase_data['completion_percentage']
phase.result = phase_data['result']
phase.reason = phase_data['result_reason']
phase.start_date_time = phase_data['start_date_time']
phase.end_date_time = phase_data['end_date_time']
return phase
def convert_strategy(self, strategy_data):
strategy = SwUpdateStrategyData()
strategy.uuid = strategy_data['uuid']
strategy.name = strategy_data['name']
strategy.controller_apply_type = strategy_data['controller_apply_type']
strategy.storage_apply_type = strategy_data['storage_apply_type']
strategy.swift_apply_type = strategy_data['swift_apply_type']
strategy.worker_apply_type = strategy_data['worker_apply_type']
strategy.max_parallel_worker_hosts = \
strategy_data['max_parallel_worker_hosts']
strategy.default_instance_action = strategy_data['default_instance_action']
strategy.alarm_restrictions = strategy_data['alarm_restrictions']
strategy.state = strategy_data['state']
strategy.current_phase = strategy_data['current_phase']
strategy.current_phase_completion_percentage \
= strategy_data['current_phase_completion_percentage']
strategy.build_phase = \
self.convert_strategy_phase(strategy_data['build_phase'])
strategy.apply_phase = \
self.convert_strategy_phase(strategy_data['apply_phase'])
strategy.abort_phase = \
self.convert_strategy_phase(strategy_data['abort_phase'])
self.strategy = strategy
class SwUpdateStrategyActionAPI(rest.RestController):
"""
Software Update Strategy Action Rest API
"""
@wsme_pecan.wsexpose(SwUpdateStrategyQueryData, six.text_type,
body=SwUpdateStrategyActionData,
status_code=httplib.ACCEPTED)
def post(self, request_data):
if wsme_types.Unset == request_data.stage_id:
if SW_UPDATE_ACTION.APPLY_STAGE == request_data.action or \
SW_UPDATE_ACTION.ABORT_STAGE == request_data.action:
DLOG.error("No stage-id received")
return pecan.abort(httplib.BAD_REQUEST, "No stage-id received")
request_data.stage_id = None
if SW_UPDATE_ACTION.APPLY_ALL == request_data.action or \
SW_UPDATE_ACTION.APPLY_STAGE == request_data.action:
rpc_request = rpc.APIRequestApplySwUpdateStrategy()
rpc_request.sw_update_type = _get_sw_update_type_from_path(
pecan.request.path)
rpc_request.stage_id = request_data.stage_id
vim_connection = pecan.request.vim.open_connection()
vim_connection.send(rpc_request.serialize())
msg = vim_connection.receive(timeout_in_secs=30)
if msg is None:
DLOG.error("No response received.")
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
response = rpc.RPCMessage.deserialize(msg)
if rpc.RPC_MSG_TYPE.APPLY_SW_UPDATE_STRATEGY_RESPONSE != response.type:
DLOG.error("Unexpected message type received, msg_type=%s."
% response.type)
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
if rpc.RPC_MSG_RESULT.SUCCESS == response.result:
strategy = json.loads(response.strategy)
query_data = SwUpdateStrategyQueryData()
query_data.convert_strategy(strategy)
return query_data
elif rpc.RPC_MSG_RESULT.NOT_FOUND == response.result:
DLOG.info("No strategy exists")
return pecan.abort(httplib.NOT_FOUND)
DLOG.error("Unexpected result received, result=%s." % response.result)
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
elif SW_UPDATE_ACTION.ABORT == request_data.action or \
SW_UPDATE_ACTION.ABORT_STAGE == request_data.action:
rpc_request = rpc.APIRequestAbortSwUpdateStrategy()
rpc_request.sw_update_type = _get_sw_update_type_from_path(
pecan.request.path)
rpc_request.stage_id = request_data.stage_id
vim_connection = pecan.request.vim.open_connection()
vim_connection.send(rpc_request.serialize())
msg = vim_connection.receive(timeout_in_secs=30)
if msg is None:
DLOG.error("No response received.")
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
response = rpc.RPCMessage.deserialize(msg)
if rpc.RPC_MSG_TYPE.ABORT_SW_UPDATE_STRATEGY_RESPONSE != response.type:
DLOG.error("Unexpected message type received, msg_type=%s."
% response.type)
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
if rpc.RPC_MSG_RESULT.SUCCESS == response.result:
strategy = json.loads(response.strategy)
query_data = SwUpdateStrategyQueryData()
query_data.convert_strategy(strategy)
return query_data
elif rpc.RPC_MSG_RESULT.NOT_FOUND == response.result:
DLOG.info("No strategy exists")
return pecan.abort(httplib.NOT_FOUND)
DLOG.error("Unexpected result received, result=%s." % response.result)
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
DLOG.error("Unexpected action received, result=%s." % request_data.action)
return pecan.abort(httplib.BAD_REQUEST)
class SwUpdateStrategyAPI(rest.RestController):
"""
Software Update Strategy Rest API
"""
actions = SwUpdateStrategyActionAPI()
@wsme_pecan.wsexpose(SwUpdateStrategyQueryData, six.text_type, status_code=httplib.OK)
def get_one(self, strategy_uuid):
if not validate.valid_uuid_str(strategy_uuid):
DLOG.error("Invalid strategy uuid received, uuid=%s." % strategy_uuid)
return pecan.abort(httplib.BAD_REQUEST,
"Invalid strategy uuid, uuid=%s" % strategy_uuid)
rpc_request = rpc.APIRequestGetSwUpdateStrategy()
rpc_request.uuid = strategy_uuid
vim_connection = pecan.request.vim.open_connection()
vim_connection.send(rpc_request.serialize())
msg = vim_connection.receive(timeout_in_secs=30)
if msg is None:
DLOG.error("No response received.")
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
response = rpc.RPCMessage.deserialize(msg)
if rpc.RPC_MSG_TYPE.GET_SW_UPDATE_STRATEGY_RESPONSE != response.type:
DLOG.error("Unexpected message type received, msg_type=%s."
% response.type)
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
if rpc.RPC_MSG_RESULT.SUCCESS == response.result:
strategy = json.loads(response.strategy)
query_data = SwUpdateStrategyQueryData()
query_data.convert_strategy(strategy)
return query_data
elif rpc.RPC_MSG_RESULT.NOT_FOUND == response.result:
DLOG.debug("No strategy exists matching strategy uuid %s"
% strategy_uuid)
return pecan.abort(httplib.NOT_FOUND)
DLOG.error("Unexpected result received, result=%s." % response.result)
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
@wsme_pecan.wsexpose(SwUpdateStrategyQueryData, status_code=httplib.OK)
def get_all(self):
rpc_request = rpc.APIRequestGetSwUpdateStrategy()
rpc_request.sw_update_type = _get_sw_update_type_from_path(
pecan.request.path)
vim_connection = pecan.request.vim.open_connection()
vim_connection.send(rpc_request.serialize())
msg = vim_connection.receive(timeout_in_secs=30)
if msg is None:
DLOG.error("No response received.")
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
response = rpc.RPCMessage.deserialize(msg)
if rpc.RPC_MSG_TYPE.GET_SW_UPDATE_STRATEGY_RESPONSE != response.type:
DLOG.error("Unexpected message type received, msg_type=%s."
% response.type)
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
if rpc.RPC_MSG_RESULT.SUCCESS == response.result:
strategy = json.loads(response.strategy)
query_data = SwUpdateStrategyQueryData()
query_data.convert_strategy(strategy)
return query_data
elif rpc.RPC_MSG_RESULT.NOT_FOUND == response.result:
DLOG.verbose("No strategy exists.")
query_data = SwUpdateStrategyQueryData()
return query_data
DLOG.error("Unexpected result received, result=%s." % response.result)
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
@wsme_pecan.wsexpose(None, six.text_type, body=SwUpdateStrategyDeleteData,
status_code=httplib.OK)
def delete(self, request_data):
rpc_request = rpc.APIRequestDeleteSwUpdateStrategy()
rpc_request.sw_update_type = _get_sw_update_type_from_path(
pecan.request.path)
rpc_request.force = request_data.force
vim_connection = pecan.request.vim.open_connection()
vim_connection.send(rpc_request.serialize())
msg = vim_connection.receive(timeout_in_secs=30)
if msg is None:
DLOG.error("No response received.")
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
response = rpc.RPCMessage.deserialize(msg)
if rpc.RPC_MSG_TYPE.DELETE_SW_UPDATE_STRATEGY_RESPONSE != response.type:
DLOG.error("Unexpected message type received, msg_type=%s."
% response.type)
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
if rpc.RPC_MSG_RESULT.SUCCESS == response.result:
return
elif rpc.RPC_MSG_RESULT.NOT_FOUND == response.result:
DLOG.info("No strategy exists")
return pecan.abort(httplib.NOT_FOUND)
elif rpc.RPC_MSG_RESULT.FAILED == response.result:
DLOG.info("Strategy delete failed")
return pecan.abort(httplib.CONFLICT)
DLOG.error("Unexpected result received, result=%s." % response.result)
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
class SwPatchStrategyAPI(SwUpdateStrategyAPI):
"""
Software Patch Strategy Rest API
"""
@wsme_pecan.wsexpose(SwUpdateStrategyQueryData,
body=SwPatchStrategyCreateData,
status_code=httplib.OK)
def post(self, request_data):
rpc_request = rpc.APIRequestCreateSwUpdateStrategy()
rpc_request.sw_update_type = _get_sw_update_type_from_path(
pecan.request.path)
rpc_request.controller_apply_type = request_data.controller_apply_type
rpc_request.storage_apply_type = request_data.storage_apply_type
if wsme_types.Unset == request_data.swift_apply_type:
rpc_request.swift_apply_type = SW_UPDATE_APPLY_TYPE.IGNORE
else:
rpc_request.swift_apply_type = request_data.swift_apply_type
rpc_request.worker_apply_type = request_data.worker_apply_type
if wsme_types.Unset != request_data.max_parallel_worker_hosts:
if request_data.max_parallel_worker_hosts < MIN_PARALLEL_HOSTS \
or request_data.max_parallel_worker_hosts > \
MAX_PARALLEL_PATCH_HOSTS:
return pecan.abort(
httplib.BAD_REQUEST,
"Invalid value for max-parallel-worker-hosts")
rpc_request.max_parallel_worker_hosts = \
request_data.max_parallel_worker_hosts
rpc_request.default_instance_action = request_data.default_instance_action
rpc_request.alarm_restrictions = request_data.alarm_restrictions
vim_connection = pecan.request.vim.open_connection()
vim_connection.send(rpc_request.serialize())
msg = vim_connection.receive(timeout_in_secs=30)
if msg is None:
DLOG.error("No response received.")
return pecan.abort(httplib.INTERNAL_SERVER_ERROR)
| |
<reponame>n-longuetmarx/tbip<gh_stars>10-100
"""Helpful functions for analysis."""
import numpy as np
import os
import scipy.sparse as sparse
from scipy.stats import bernoulli, poisson
def load_text_data(data_dir):
"""Load text data used to train the TBIP.
Args:
data_dir: Path to directory where data is stored.
Returns:
counts: A sparse matrix with shape [num_documents, num_words], representing
the documents in a bag-of-words format.
vocabulary: An array of strings with shape [num_words].
author_indices: An array of integeres with shape [num_documents], where
each entry represents the author who wrote the document.
author_map: An array of strings with shape [num_authors], containing the
names of each author.
raw_documents: A string vector with shape [num_documents] containing the
raw documents.
"""
counts = sparse.load_npz(
os.path.join(data_dir, "counts.npz"))
vocabulary = np.loadtxt(
os.path.join(data_dir, "vocabulary.txt"),
dtype=str,
delimiter="\n",
comments="<!-")
author_indices = np.load(
os.path.join(data_dir, "author_indices.npy")).astype(np.int32)
author_map = np.loadtxt(
os.path.join(data_dir, "author_map.txt"),
dtype=str,
delimiter="\n")
raw_documents = np.loadtxt(
os.path.join(data_dir, "raw_documents.txt"),
dtype=str,
delimiter="\n",
comments="<!-")
return counts, vocabulary, author_indices, author_map, raw_documents
def load_tbip_parameters(param_dir):
"""Load the TBIP model parameters from directory where they are stored.
Args:
param_dir: Path to directory where the TBIP fitted parameters are stored.
Returns:
document_loc: Variational lognormal location parameter for the
document intensities (theta), with shape [num_documents, num_topics].
document_loc: Variational lognormal scale parameter for the
document intensities (theta), with shape [num_documents, num_topics].
objective_topic_loc: Variational lognormal location parameter for the
objective topic (beta), with [num_topics, num_words].
objective_topic_scale: Variational lognormal scale parameter for the
objective topic (beta), with shape [num_topics, num_words].
ideological_topic_loc: Variational Gaussian location parameter for the
ideological topic (eta), with shape [num_topics, num_words].
ideological_topic_scale: Variational Gaussian scale parameter for the
ideological topic (eta), with shape [num_topics, num_words].
ideal_point_loc: Variational Gaussian location parameter for the
ideal points (x), with shape [num_authors].
ideal_point_scale: Variational Gaussian scale parameter for the
ideal points (x), with shape [num_authors].
"""
document_loc = np.load(
os.path.join(param_dir, "document_loc.npy"))
document_scale = np.load(
os.path.join(param_dir, "document_scale.npy"))
objective_topic_loc = np.load(
os.path.join(param_dir, "objective_topic_loc.npy"))
objective_topic_scale = np.load(
os.path.join(param_dir, "objective_topic_scale.npy"))
ideological_topic_loc = np.load(
os.path.join(param_dir, "ideological_topic_loc.npy"))
ideological_topic_scale = np.load(
os.path.join(param_dir, "ideological_topic_scale.npy"))
ideal_point_loc = np.load(
os.path.join(param_dir, "ideal_point_loc.npy"))
ideal_point_scale = np.load(
os.path.join(param_dir, "ideal_point_scale.npy"))
return (document_loc, document_scale, objective_topic_loc,
objective_topic_scale, ideological_topic_loc,
ideological_topic_scale, ideal_point_loc, ideal_point_scale)
def load_vote_data(vote_data_dir):
"""Load vote data used to train vote-based ideal points for Senators.
Args:
vote_data_dir: Path to directory where data is stored.
Returns:
votes: An array with shape [num_votes], containing the binary vote cast
for all recorded votes.
senator_indices: An array with shape [num_votes], where each entry is an
integer in {0, 1, ..., num_voters - 1}, containing the index for the
Senator corresponding to the vote in `votes`.
bill_indices: An array with shape [num_votes], where each entry is an
integer in {0, 1, ..., num_bills - 1}, containing the index for the
bill corresponding to the vote in `votes`.
voter_map: A string array with length [num_voters] containing the
name for each voter in the data set.
bill_descriptions: A string array with length [num_bills] containing
descriptions for each bill being voted on.
bill_descriptions: A string array with length [num_bills] containing
the name for each bill being voted on.
vote_ideal_points_dw_nominate: An array with shape [num_voters], containing
the DW-Nominate scores for each Senator. Note that these are not trained
locally; they are the values provided by Voteview.
"""
votes = np.load(os.path.join(vote_data_dir, "votes.npy"))
senator_indices = np.load(os.path.join(vote_data_dir, "senator_indices.npy"))
bill_indices = np.load(os.path.join(vote_data_dir, "bill_indices.npy"))
voter_map = np.loadtxt(os.path.join(vote_data_dir, "senator_map.txt"),
dtype=str,
delimiter="\n")
bill_descriptions = np.loadtxt(
os.path.join(vote_data_dir, "bill_descriptions.txt"),
dtype=str,
delimiter="\n")
bill_names = np.loadtxt(
os.path.join(vote_data_dir, "bill_names.txt"),
dtype=str,
delimiter="\n")
vote_ideal_points_dw_nominate = np.load(
os.path.join(vote_data_dir, "nominate_scores.npy"))
return (votes, senator_indices, bill_indices, voter_map, bill_descriptions,
bill_names, vote_ideal_points_dw_nominate)
def load_vote_ideal_point_parameters(param_dir):
"""Load the parameters for the 1D vote ideal point model.
Args:
param_dir: Path to directory containing the vote ideal point parameters.
Returns:
polarity_loc: Variational Gaussian location parameter for the polarities
(eta), with shape [num_bills].
polarity_scale: Variational Gaussian scale parameter for the polarities
(eta), with shape [num_bills].
popularity_loc: Variational Gaussian location parameter for the
popularities (alpha), with shape [num_bills].
popularity_scale: Variational Gaussian scale parameter for the
popularities (alpha), with shape [num_bills].
ideal_point_loc: Variational Gaussian location parameter for the
ideal points (x), with shape [num_authors].
ideal_point_scale: Variational Gaussian scale parameter for the
ideal points (x), with shape [num_authors].
"""
polarity_loc = np.load(os.path.join(param_dir, "polarity_loc.npy"))
polarity_scale = np.load(os.path.join(param_dir, "polarity_scale.npy"))
popularity_loc = np.load(os.path.join(param_dir, "popularity_loc.npy"))
popularity_scale = np.load(os.path.join(param_dir, "popularity_scale.npy"))
ideal_point_loc = np.load(os.path.join(param_dir, "ideal_point_loc.npy"))
ideal_point_scale = np.load(os.path.join(param_dir, "ideal_point_scale.npy"))
return (polarity_loc, polarity_scale, popularity_loc,
popularity_scale, ideal_point_loc, ideal_point_scale)
def get_ideological_topic_means(objective_topic_loc,
objective_topic_scale,
ideological_topic_loc,
ideological_topic_scale):
"""Returns neutral and ideological topics from variational parameters.
For each (k,v), we want to evaluate E[beta_kv], E[beta_kv * exp(eta_kv)],
and E[beta_kv * exp(-eta_kv)], where the expectations are with respect to the
variational distributions. Like the paper, beta refers to the obective topic
and eta refers to the ideological topic.
Dropping the indices and denoting by mu_b the objective topic location and
sigma_b the objective topic scale, we have E[beta] = exp(mu + sigma_b^2 / 2),
using the mean of a lognormal distribution.
Denoting by mu_e the ideological topic location and sigma_e the ideological
topic scale, we have E[beta * exp(eta)] = E[beta]E[exp(eta)] by the
mean-field assumption. exp(eta) is lognormal distributed, so E[exp(eta)] =
exp(mu_e + sigma_e^2 / 2). Thus, E[beta * exp(eta)] =
exp(mu_b + mu_e + (sigma_b^2 + sigma_e^2) / 2).
Finally, E[beta * exp(-eta)] =
exp(mu_b - mu_e + (sigma_b^2 + sigma_e^2) / 2).
Because we only care about the orderings of topics, we can drop the exponents
from the means.
Args:
objective_topic_loc: Variational lognormal location parameter for the
objective topic (beta). Should be shape [num_topics, num_words].
objective_topic_scale: Variational lognormal scale parameter for the
objective topic (beta). Should be positive, with shape
[num_topics, num_words].
ideological_topic_loc: Variational Gaussian location parameter for the
ideological topic (eta). Should be shape [num_topics, num_words].
ideological_topic_scale: Variational Gaussian scale parameter for the
ideological topic (eta). Should be positive, with shape
[num_topics, num_words].
Returns:
neutral_mean: A matrix with shape [num_topics, num_words] denoting the
variational mean for the neutral topics.
positive_mean: A matrix with shape [num_topics, num_words], denoting the
variational mean for the ideological topics with an ideal point of +1.
negative_mean: A matrix with shape [num_topics, num_words], denoting the
variational mean for the ideological topics with an ideal point of -1.
"""
neutral_mean = objective_topic_loc + objective_topic_scale ** 2 / 2
positive_mean = (objective_topic_loc +
ideological_topic_loc +
(objective_topic_scale ** 2 +
ideological_topic_scale ** 2) / 2)
negative_mean = (objective_topic_loc -
ideological_topic_loc +
(objective_topic_scale ** 2 +
ideological_topic_scale ** 2) / 2)
return neutral_mean, positive_mean, negative_mean
def print_topics(objective_topic_loc,
objective_topic_scale,
ideological_topic_loc,
ideological_topic_scale,
vocabulary,
words_per_topic=10):
"""Prints neutral and ideological topics from variational parameters.
Args:
objective_topic_loc: Variational lognormal location parameter for the
objective topic (beta). Should be shape [num_topics, num_words].
objective_topic_scale: Variational lognormal scale parameter for the
objective topic (beta). Should be positive, with shape
[num_topics, num_words].
ideological_topic_loc: Variational Gaussian location parameter for the
ideological topic (eta). Should be shape [num_topics, num_words].
ideological_topic_scale: Variational Gaussian scale parameter for the
ideological topic (eta). Should be positive, with shape
[num_topics, num_words].
vocabulary: A list of strings with shape [num_words].
words_per_topic: The number of words to print for each topic.
"""
neutral_mean, positive_mean, negative_mean = get_ideological_topic_means(
objective_topic_loc,
objective_topic_scale,
ideological_topic_loc,
ideological_topic_scale)
num_topics, num_words = neutral_mean.shape
top_neutral_words = np.argsort(-neutral_mean, axis=1)
top_negative_words = np.argsort(-negative_mean, axis=1)
top_positive_words = np.argsort(-positive_mean, axis=1)
topic_strings = []
for topic_idx in range(num_topics):
neutral_start_string = "Neutral {}:".format(topic_idx)
neutral_row = [vocabulary[word] for word in
top_neutral_words[topic_idx, :words_per_topic]]
neutral_row_string = ", ".join(neutral_row)
neutral_string = " ".join([neutral_start_string, neutral_row_string])
positive_start_string = "Positive {}:".format(topic_idx)
positive_row = [vocabulary[word] for word in
top_positive_words[topic_idx, :words_per_topic]]
positive_row_string = ", ".join(positive_row)
positive_string = " ".join([positive_start_string, positive_row_string])
negative_start_string = "Negative {}:".format(topic_idx)
negative_row = [vocabulary[word] for word in
top_negative_words[topic_idx, :words_per_topic]]
negative_row_string = ", ".join(negative_row)
negative_string = | |
"""
Module contains tools for processing files into DataFrames or other objects
"""
from StringIO import StringIO
import re
from itertools import izip
from urlparse import urlparse
import numpy as np
from pandas.core.index import Index, MultiIndex
from pandas.core.frame import DataFrame
import datetime
import pandas.core.common as com
import pandas._tseries as lib
from pandas.util import py3compat
from pandas.util.decorators import Appender
_parser_params = """Also supports optionally iterating or breaking of the file
into chunks.
Parameters
----------
filepath_or_buffer : string or file handle / StringIO. The string could be
a URL. Valid URL schemes include http://, ftp://, and file://. For
file:// URLs, a host is expected. For instance, a local file could be
file://localhost/path/to/table.csv
%s
header : int, default 0
Row to use for the column labels of the parsed DataFrame
skiprows : list-like or integer
Row numbers to skip (0-indexed) or number of rows to skip (int)
index_col : int or sequence, default None
Column to use as the row labels of the DataFrame. If a sequence is
given, a MultiIndex is used.
names : array-like
List of column names
na_values : list-like or dict, default None
Additional strings to recognize as NA/NaN. If dict passed, specific
per-column NA values
parse_dates : boolean or list of column numbers/name, default False
Attempt to parse dates in the indicated columns
date_parser : function
Function to use for converting dates to strings. Defaults to
dateutil.parser
dayfirst : boolean, default False
DD/MM format dates, international and European format
nrows : int, default None
Number of rows of file to read. Useful for reading pieces of large files
iterator : boolean, default False
Return TextParser object
chunksize : int, default None
Return TextParser object for iteration
skip_footer : int, default 0
Number of line at bottom of file to skip
converters : dict. optional
Dict of functions for converting values in certain columns. Keys can either
be integers or column labels
verbose : boolean, default False
Indicate number of NA values placed in non-numeric columns
delimiter : string, default None
Alternative argument name for sep
encoding : string, default None
Encoding to use for UTF when reading/writing (ex. 'utf-8')
Returns
-------
result : DataFrame or TextParser
"""
_csv_sep = """sep : string, default ','
Delimiter to use. If sep is None, will try to automatically determine
this"""
_table_sep = """sep : string, default \\t (tab-stop)
Delimiter to use"""
_read_csv_doc = """
Read CSV (comma-separated) file into DataFrame
%s
""" % (_parser_params % _csv_sep)
_read_table_doc = """
Read general delimited file into DataFrame
%s
""" % (_parser_params % _table_sep)
_fwf_widths = """\
colspecs : a list of pairs (tuples), giving the extents
of the fixed-width fields of each line as half-open internals
(i.e., [from, to[ ).
widths : a list of field widths, which can be used instead of
'colspecs' if the intervals are contiguous.
"""
_read_fwf_doc = """
Read a table of fixed-width formatted lines into DataFrame
%s
Also, 'delimiter' is used to specify the filler character of the
fields if it is not spaces (e.g., '~').
""" % (_parser_params % _fwf_widths)
def _is_url(url):
"""
Very naive check to see if url is an http(s), ftp, or file location.
"""
parsed_url = urlparse(url)
if parsed_url.scheme in ['http','file', 'ftp', 'https']:
return True
else:
return False
def _read(cls, filepath_or_buffer, kwds):
"Generic reader of line files."
encoding = kwds.get('encoding', None)
if isinstance(filepath_or_buffer, str) and _is_url(filepath_or_buffer):
from urllib2 import urlopen
filepath_or_buffer = urlopen(filepath_or_buffer)
if py3compat.PY3: # pragma: no cover
from io import TextIOWrapper
if encoding:
errors = 'strict'
else:
errors = 'replace'
encoding = 'utf-8'
bytes = filepath_or_buffer.read()
filepath_or_buffer = StringIO(bytes.decode(encoding, errors))
if hasattr(filepath_or_buffer, 'read'):
f = filepath_or_buffer
else:
try:
# universal newline mode
f = com._get_handle(filepath_or_buffer, 'U', encoding=encoding)
except Exception: # pragma: no cover
f = com._get_handle(filepath_or_buffer, 'r', encoding=encoding)
if kwds.get('date_parser', None) is not None:
kwds['parse_dates'] = True
# Extract some of the arguments (pass chunksize on).
kwds.pop('filepath_or_buffer')
iterator = kwds.pop('iterator')
nrows = kwds.pop('nrows')
chunksize = kwds.get('chunksize', None)
# Create the parser.
parser = cls(f, **kwds)
if nrows is not None:
return parser.get_chunk(nrows)
elif chunksize or iterator:
return parser
return parser.get_chunk()
@Appender(_read_csv_doc)
def read_csv(filepath_or_buffer,
sep=',',
header=0,
index_col=None,
names=None,
skiprows=None,
na_values=None,
parse_dates=False,
dayfirst=False,
date_parser=None,
nrows=None,
iterator=False,
chunksize=None,
skip_footer=0,
converters=None,
verbose=False,
delimiter=None,
encoding=None):
kwds = locals()
# Alias sep -> delimiter.
sep = kwds.pop('sep')
if kwds.get('delimiter', None) is None:
kwds['delimiter'] = sep
return _read(TextParser, filepath_or_buffer, kwds)
@Appender(_read_table_doc)
def read_table(filepath_or_buffer,
sep='\t',
header=0,
index_col=None,
names=None,
skiprows=None,
na_values=None,
parse_dates=False,
dayfirst=False,
date_parser=None,
nrows=None,
iterator=False,
chunksize=None,
skip_footer=0,
converters=None,
verbose=False,
delimiter=None,
encoding=None):
kwds = locals()
# Alias sep -> delimiter.
sep = kwds.pop('sep')
if kwds.get('delimiter', None) is None:
kwds['delimiter'] = sep
# Override as default encoding.
kwds['encoding'] = None
return _read(TextParser, filepath_or_buffer, kwds)
@Appender(_read_fwf_doc)
def read_fwf(filepath_or_buffer,
colspecs=None,
widths=None,
header=0,
index_col=None,
names=None,
skiprows=None,
na_values=None,
parse_dates=False,
dayfirst=False,
date_parser=None,
nrows=None,
iterator=False,
chunksize=None,
skip_footer=0,
converters=None,
delimiter=None,
verbose=False,
encoding=None):
kwds = locals()
# Check input arguments.
colspecs = kwds.get('colspecs', None)
widths = kwds.pop('widths', None)
if bool(colspecs is None) == bool(widths is None):
raise ValueError("You must specify only one of 'widths' and "
"'colspecs'")
# Compute 'colspec' from 'widths', if specified.
if widths is not None:
colspecs, col = [], 0
for w in widths:
colspecs.append( (col, col+w) )
col += w
kwds['colspecs'] = colspecs
return _read(FixedWidthFieldParser, filepath_or_buffer, kwds)
def read_clipboard(**kwargs): # pragma: no cover
"""
Read text from clipboard and pass to read_table. See read_table for the
full argument list
Returns
-------
parsed : DataFrame
"""
from pandas.util.clipboard import clipboard_get
text = clipboard_get()
return read_table(StringIO(text), **kwargs)
def to_clipboard(obj): # pragma: no cover
"""
Attempt to write text representation of object to the system clipboard
Notes
-----
Requirements for your platform
- Linux: xsel command line tool
- Windows: Python win32 extensions
- OS X:
"""
from pandas.util.clipboard import clipboard_set
clipboard_set(str(obj))
class BufferedReader(object):
"""
For handling different kinds of files, e.g. zip files where reading out a
chunk of lines is faster than reading out one line at a time.
"""
def __init__(self, fh, delimiter=','):
pass # pragma: no coverage
class BufferedCSVReader(BufferedReader):
pass
# common NA values
# no longer excluding inf representations
# '1.#INF','-1.#INF', '1.#INF000000',
_NA_VALUES = set(['-1.#IND', '1.#QNAN', '1.#IND', '-1.#QNAN',
'#N/A N/A', 'NA', '#NA', 'NULL', 'NaN',
'nan', ''])
class TextParser(object):
"""
Converts lists of lists/tuples into DataFrames with proper type inference
and optional (e.g. string to datetime) conversion. Also enables iterating
lazily over chunks of large files
Parameters
----------
data : file-like object or list
delimiter : separator character to use
names : sequence, default
header : int, default 0
Row to use to parse column labels. Defaults to the first row. Prior
rows will be discarded
index_col : int or list, default None
Column or columns to use as the (possibly hierarchical) index
na_values : iterable, default None
Custom NA values
parse_dates : boolean, default False
date_parser : function, default None
skiprows : list of integers
Row numbers to skip
skip_footer : int
Number of line at bottom of file to skip
encoding : string, default None
Encoding to use for UTF when reading/writing (ex. 'utf-8')
"""
def __init__(self, f, delimiter=None, names=None, header=0,
index_col=None, na_values=None, parse_dates=False,
date_parser=None, dayfirst=False, chunksize=None,
skiprows=None, skip_footer=0, converters=None,
verbose=False, encoding=None):
"""
Workhorse function for processing nested list into DataFrame
Should be replaced by np.genfromtxt eventually?
"""
self.data = None
self.buf = []
self.pos = 0
self.names = list(names) if names is not None else names
self.header = header
self.index_col = index_col
self.chunksize = chunksize
self.passed_names = names is not None
self.encoding = encoding
self.parse_dates = parse_dates
self.date_parser = date_parser
self.dayfirst = dayfirst
if com.is_integer(skiprows):
skiprows = range(skiprows)
self.skiprows = set() if skiprows is None else set(skiprows)
self.skip_footer = skip_footer
self.delimiter = delimiter
self.verbose = verbose
if converters is not None:
assert(isinstance(converters, dict))
self.converters = converters
else:
self.converters = {}
assert(self.skip_footer >= 0)
if na_values is None:
self.na_values = _NA_VALUES
elif isinstance(na_values, dict):
self.na_values = na_values
else:
self.na_values = set(list(na_values)) | _NA_VALUES
if hasattr(f, 'readline'):
self._make_reader(f)
else:
self.data = f
self.columns = self._infer_columns()
# get popped off for index
self.orig_columns = list(self.columns)
self.index_name = self._get_index_name()
self._first_chunk = True
def _make_reader(self, f):
import csv
sep = self.delimiter
if sep is None or len(sep) == 1:
sniff_sep = True
# default dialect
dia = csv.excel()
if sep is not None:
sniff_sep = False
dia.delimiter = sep
# attempt to sniff the delimiter
if sniff_sep:
line = f.readline()
while | |
data_dict.update({hdu.header['CTYPE' + str(i)]:
(hdu.header['NAXIS'] - i + 1,
hdu.header['NAXIS' + str(i)])})
# Save shape and dimensions of data recarray
self.data_dict = data_dict
self.nif = data_dict['IF'][1]
self.nstokes = data_dict['STOKES'][1]
# Create dictionary with necessary slices
slices_dict = OrderedDict()
for key, value in data_dict.items():
# FIXME: Generally we should avoid removing dims
if value[1] == 1 and key not in ['IF', 'STOKES']:
slices_dict.update({key: 0})
else:
slices_dict.update({key: slice(None, None)})
self.slices_dict = slices_dict
uvdata_slices_dict = OrderedDict()
for key, value in slices_dict.items():
if value != 0:
uvdata_slices_dict.update({key: value})
self.uvdata_slices_dict = uvdata_slices_dict
def new_slices(self, key, key_slice):
"""
Return VIEW of internal ``hdu.data.data`` numpy.ndarray with given
slice.
"""
slices_dict = self.slices_dict.copy()
slices_dict.update({key: key_slice})
return slices_dict
def view_uvdata(self, new_slices_dict):
"""
Return VIEW of internal ``hdu.data.data`` numpy.ndarray with given
slices.
:param new_slices_dict:
Ex. {'COMPLEX': slice(0, 1), 'IF': slice(0, 2)}
"""
slices_dict = self.slices_dict.copy()
for key, key_slice in new_slices_dict.items():
slices_dict.update({key: key_slice})
return self.hdu.data.data[list(slices_dict.values())]
@property
def stokes(self):
"""
Shortcut to correlations present (or Stokes parameters).
"""
if self._stokes is None:
ref_val = get_key(self.hdu.header, 'STOKES', 'CRVAL')
ref_pix = get_key(self.hdu.header, 'STOKES', 'CRPIX')
delta = get_key(self.hdu.header, 'STOKES', 'CDELT')
n_stokes = get_key(self.hdu.header, 'STOKES', 'NAXIS')
self._stokes = [stokes_dict[ref_val + (i - ref_pix) * delta] for i
in range(1, n_stokes + 1)]
return self._stokes
@property
def ra(self):
"""
:return:
Right Ascension of the observed source [deg]
"""
return get_key(self.hdu.header, 'RA', 'CRVAL')
@property
def dec(self):
"""
:return:
Declination of the observed source [deg]
"""
return get_key(self.hdu.header, 'DEC', 'CRVAL')
@property
def stokes_dict(self):
return {i: stokes for i, stokes in enumerate(self.stokes)}
@property
def stokes_dict_inv(self):
return {stokes: i for i, stokes in enumerate(self.stokes)}
@property
def uvdata(self):
"""
Returns (#groups, #if, #stokes,) complex numpy.ndarray with last
dimension - real&imag part of visibilities. It is A COPY of
``hdu.data.data`` numpy.ndarray.
"""
# Always return complex representation of internal ``hdu.data.data``
return self._uvdata
@uvdata.setter
def uvdata(self, other):
# Updates A COPY of ``hdu.data.data`` numpy.ndarray (complex repr.)
self._uvdata = other
# Sync internal representation with changed complex representation.
self.sync()
@property
def weights(self):
"""
Returns (#groups, #if, #stokes,) complex numpy.ndarray with last
dimension - weight of visibilities. It is A COPY of ``hdu.data.data``
numpy.ndarray.
"""
return self._weights
@property
def uvdata_weight_masked(self):
return np.ma.array(self.uvdata, mask=self._nw_indxs)
@property
def uvdata_freq_averaged(self):
"""
Returns ``self.uvdata`` averaged in IFs, that is complex numpy.ndarray
with shape (#N, #stokes).
"""
if self.nif > 1:
result = np.ma.mean(self.uvdata_weight_masked, axis=1)
# FIXME: if self.nif=1 then np.mean for axis=1 will remove this
# dimension. So don't need this if-else
else:
result = self.uvdata_weight_masked[:, 0, :]
return result
@property
def weights_nw_masked(self):
"""
Returns (#groups, #if, #stokes,) complex numpy.ndarray with last
dimension - weight of visibilities. It is A COPY of ``hdu.data.data``
numpy.ndarray.
"""
return np.ma.array(self._weights, mask=self._nw_indxs)
@property
def errors_from_weights(self):
"""
Returns (#groups, #if, #stokes,) complex numpy.ndarray with last
dimension - weight of visibilities. It is A COPY of ``hdu.data.data``
numpy.ndarray.
"""
return 1. / np.sqrt(self.weights_nw_masked)
@property
def errors_from_weights_masked_freq_averaged(self):
if self.nif > 1:
result = np.ma.mean(self.errors_from_weights, axis=1)/np.sqrt(self.nif)
else:
result = self.errors_from_weights[:, 0, :]
return result
@property
def baselines(self):
"""
Returns list of baselines numbers.
"""
result = list(set(self.hdu.data['BASELINE']))
return sorted(result)
@property
def antennas(self):
"""
Returns list of antennas numbers.
"""
return baselines_2_ants(self.baselines)
@property
def antenna_mapping(self):
"""
:return:
Dictionary with keys - antenna numbers and values - antenna names.
"""
return self._antenna_mapping
@property
def inverse_antenna_mapping(self):
"""
:return:
Dictionary with keys - antenna names and values - antenna numbers.
"""
return {v: k for k, v in self._antenna_mapping.items()}
@property
def frequency(self):
"""
Returns sky frequency in Hz.
"""
if self._frequency is None:
freq_card = find_card_from_header(self.hdu.header, value='FREQ')[0]
self._frequency = self.hdu.header['CRVAL{}'.format(freq_card[0][-1])]
return self._frequency
@property
def freq_width_if(self):
"""
Returns width of IF in Hz.
"""
if self._freq_width_if is None:
freq_card = find_card_from_header(self.hdu.header, value='FREQ')[0]
self._freq_width_if = self.hdu.header['CDELT{}'.format(freq_card[0][-1])]
return self._freq_width_if
@property
def freq_width(self):
"""
Returns width of all IFs in Hz.
"""
if self._freq_width is None:
freq_card = find_card_from_header(self.hdu.header, value='FREQ')[0]
self._freq_width = self.nif * self.hdu.header['CDELT{}'.format(freq_card[0][-1])]
return self._freq_width
@property
def band_center(self):
"""
Returns center of frequency bandwidth in Hz.
"""
if self._band_center is None:
self._band_center = self.frequency + self.freq_width_if * (self.nif / 2. - 0.5)
return self._band_center
@property
def times(self):
"""
Returns array of ``astropy.time.Time`` instances.
"""
if self._times is None:
self._times = Time(self.hdu.data['DATE'] + self.hdu.data['_DATE'],
format='jd')
return self._times
@property
def antennas_baselines(self):
if self._antennas_baselines is None:
self._antennas_baselines = dict()
for antenna in self.antennas:
self._antennas_baselines.update({antenna: list()})
for baseline in self.baselines:
ant1, ant2 = baselines_2_ants([baseline])
if ant1 == antenna or ant2 == antenna:
self._antennas_baselines[antenna].append(baseline)
return self._antennas_baselines
@property
def antennas_times(self):
if self._antennas_times is None:
self._antennas_times = dict()
for antenna in self.antennas:
self._antennas_times.update({antenna: list()})
for baseline in self.antennas_baselines[antenna]:
# Find times of current baseline
indexes = self._get_baseline_indexes(baseline)
bl_times = self.times[indexes]
self._antennas_times[antenna].extend(list(bl_times))
ordered_times = sorted(set(self._antennas_times[antenna]))
self._antennas_times[antenna] = ordered_times
return self._antennas_times
@property
def minimal_antennas_time(self):
if self._minimal_antennas_time is None:
minimal_times = [np.min(self.antennas_times[ant]) for ant in self.antennas]
self._minimal_antennas_time = np.min(minimal_times)
return self._minimal_antennas_time
def antennas_gains(self, amp_gpamp=np.exp(-3), amp_gpphase=np.exp(-3), scale_gpamp=np.exp(6),
scale_gpphase=np.exp(5), rewrite=False):
if self._antennas_gains is None or rewrite:
t_min = self.minimal_antennas_time
# For each antenna - create GP of amp and phase
self._antennas_gains = dict()
for ant in self.antennas:
self._antennas_gains[ant] = dict()
ant_time = self.antennas_times[ant]
tdeltas = [t - t_min for t in ant_time]
tdeltas = [dt.sec for dt in tdeltas]
for pol in ("r", "l"):
# Amplitude
v = np.random.normal(0, 1, size=len(tdeltas))
amp = 1 + gp_pred(amp_gpamp, scale_gpamp, v, np.array(tdeltas))
# Phase
v = np.random.normal(0, 1, size=len(tdeltas))
phase = gp_pred(amp_gpphase, scale_gpphase, v, np.array(tdeltas))
self._antennas_gains[ant][pol] = {"amp": {t: a for (t, a) in zip(ant_time, amp)},
"phase": {t: p for (t, p) in zip(ant_time, phase)}}
return self._antennas_gains
def plot_antennas_gains(self):
color_dict = {"r": "#1f77b4", "l": "#ff7f0e"}
antennas_gains = self.antennas_gains()
fig, axes = plt.subplots(len(antennas_gains), 2, sharex=True, figsize=(24, 20))
t_min = self.minimal_antennas_time
for i, ant in enumerate(antennas_gains):
ant_time = self.antennas_times[ant]
tdeltas = [t - t_min for t in ant_time]
tdeltas = [dt.sec for dt in tdeltas]
for pol in ("r", "l"):
amp = antennas_gains[ant][pol]["amp"]
phase = antennas_gains[ant][pol]["phase"]
if i == 0:
label = pol
else:
label = None
dots, = axes[i, 0].plot(tdeltas, list(amp.values()), '.', color=color_dict[pol])
if label is not None:
dots.set_label(label.upper())
axes[i, 0].legend(loc="upper right")
axes[i, 1].plot(tdeltas, list(phase.values()), '.', color=color_dict[pol])
axes[i, 1].yaxis.set_ticks_position("right")
axes[0, 0].set_title("Amplitudes")
axes[0, 1].set_title("Phases")
axes[i, 0].set_xlabel("time, s")
axes[i, 1].set_xlabel("time, s")
# if savefn:
# fig.savefig(savefn, bbox_inches="tight", dpi=300)
fig.show()
return fig
@property
def ngroups(self):
return self.hdu.header["GCOUNT"]
def inject_gains(self):
from cmath import exp
gains = self.antennas_gains()
baselines = self.hdu.data["BASELINE"]
for i in range(self.ngroups):
t = self.times[i]
baseline = baselines[i]
ant1, ant2 = baselines_2_ants([baseline])
amp1r = gains[ant1]["r"]["amp"][t]
amp1l = gains[ant1]["l"]["amp"][t]
amp2r = gains[ant2]["r"]["amp"][t]
amp2l = gains[ant2]["l"]["amp"][t]
phase1r = gains[ant1]["r"]["phase"][t]
phase1l = gains[ant1]["l"]["phase"][t]
phase2r = gains[ant2]["r"]["phase"][t]
phase2l = gains[ant2]["l"]["phase"][t]
gain1r = amp1r*exp(1j*phase1r)
gain1l = amp1l*exp(1j*phase1l)
gain2r = amp2r*exp(1j*phase2r)
gain2l = amp2l*exp(1j*phase2l)
# vis_real_new = amp1 * amp2 * (np.cos(phase1 - phase2) * vis_real - np.sin(phase1 - phase2) * vis_imag)
# vis_imag_new = amp1 * amp2 * (np.cos(phase1 - phase2) * vis_imag + np.sin(phase1 - phase2) * vis_real)
# vis_real_gained.append(vis_real_new)
# vis_imag_gained.append(vis_imag_new)
# Stokes 0 (RR)
if self._check_stokes_present("RR"):
self.uvdata[i, :, 0] = gain1r * gain2r.conjugate() * self.uvdata[i, :, 0]
if self._check_stokes_present("LL"):
self.uvdata[i, :, 1] = gain1l * gain2l.conjugate() * self.uvdata[i, :, 1]
if self._check_stokes_present("RL"):
self.uvdata[i, :, 2] = gain1r * gain2l.conjugate() * self.uvdata[i, :, 2]
if self._check_stokes_present("LR"):
self.uvdata[i, :, 3] = gain1l * gain2r.conjugate() * self.uvdata[i, :, 3]
self.sync()
def n_usable_visibilities_difmap(self, stokes="I", freq_average=False):
"""
Returns number of visibilities usable for fitting ``stokes``. To get
#DOF on has to double it (Re & Im parts) and subtract number of model
parameters.
:param stokes:
String of Stokes parameter or correlation.
:note:
For nonlinear models #DOF is actually a more complicated thing.
"""
self._check_stokes_present(stokes)
# (#, n_IF, 1) if not freq_average
stokes_vis = self._choose_uvdata(stokes=stokes,
freq_average=freq_average)
# Number of masked visibilities
n_bad = np.count_nonzero(stokes_vis.mask)
shape = stokes_vis.shape
if freq_average:
factor = 1.0
else:
factor = shape[1]
return shape[0]*factor - n_bad
def dof(self, model):
"""
Number of the Degrees Of Freedom given model.
:param model:
Instance of ``Model`` class. Should have ``stokes`` and ``size``
attributes.
:return:
Value of DOF.
:note:
For nonlinear models DOF != number of parameters in a model.
"""
return | |
<reponame>ydallilar/flaremodel
# Licensed under a 3-clause BSD style license - see LICENSE
import numpy as np
import warnings
from .utils import *
from .utils.gfuncs import GPU_ENABLED
class Geometry:
"""
Base Geometry class to extend for other geometries
Parameters
----------
edist: str
Name of the electron distribution for the geometry. Refer to docs.
method: str
Reserved for later use.
booster: class
A boosting implementation, ie. :class:`DopplerBooster`
"""
def __init__(self, edist="thermal", method="brute", booster=None):
self.name = self.__class__.__name__
self.edist = edist
if method == "brute":
self.j_nu_fun = j_nu_brute
self.a_nu_fun = a_nu_brute
else:
raise ValueError("% method is not implemented.")
self.booster = DopplerBooster if booster is None else booster
def _compute_synchrotron(self, nu, ne, g_params, B, params, **kwargs):
"""
Definition of synchrotron luminosity for the geometry
Parameters
----------
nu: np.ndarray
1-D frequencies to calculate synchrotron luminosity [Hz]
ne: float
Electron density [cm^-3]
g_params: list
Parameters for the implemented geometry
B: float
Magnetic Field [G]
params: list
List of parameters for the electron distribution
**kwargs:
Reserved for additional parameters
Returns
-------
L_nu: np.ndarray
[erg s-1 Hz-1]
"""
raise NotImplementedError()
def _compute_photon_density(self, nu, ne, g_params, B, params):
"""
Definition of photon density due to internal synchrotron.
Note that this can return anything for any specific SSC calculation and
typically not to be used for other purposes.
Parameters
----------
nu: np.ndarray
1-D frequencies to calculate synchrotron luminosity [Hz]
ne: float
Electron density [cm^-3]
g_params: list
Parameters for the implemented geometry
B: float
Magnetic Field [G]
params: list
List of parameters for the electron distribution
**kwargs:
Reserved for additional parameters
"""
raise NotImplementedError()
def _compute_IC(self, nu, ne, n_ph_fun, g_params, B, params, **kwargs):
"""
Definition of SSC luminosity for the geometry
Parameters
----------
nu: np.ndarray
1-D frequencies to calculate synchrotron luminosity [Hz]
ne: float
Electron density [cm^-3]
n_ph_fun: function
Function to calculate photon densities nph(nu) [cm-3 Hz-1]
g_params: list
Parameters for the implemented geometry
B: float
Magnetic Field [G]
params: list
List of parameters for the electron distribution
**kwargs:
Reserved for additional parameters
Returns
-------
L_nu: np.ndarray
[erg s-1 Hz-1]
"""
raise NotImplementedError()
def _compute_SSC(self, nu, ne, g_params, B, params, **kwargs):
"""
Definition of SSC luminosity for the geometry
Parameters
----------
nu: np.ndarray
1-D frequencies to calculate synchrotron luminosity [Hz]
ne: float
Electron density [cm^-3]
g_params: list
Parameters for the implemented geometry
B: float
Magnetic Field [G]
params: list
List of parameters for the electron distribution
**kwargs:
Reserved for additional parameters
Returns
-------
L_nu: np.ndarray
[erg s-1 Hz-1]
"""
raise NotImplementedError()
def compute_IC(self, nu, ne, n_ph_fun, g_params, B, params, boost_p=None, **kwargs):
"""
Same as :func:`Geometry._compute_IC` but accepts ``boost_p`` keyword. See class :class:`DopplerBooster`
"""
if boost_p is None:
return self._compute_IC(nu, ne, n_ph_fun, g_params, B, params, **kwargs)
else:
return self.booster(*boost_p)(self._compute_IC)(nu, ne, n_ph_fun, g_params, B, params, **kwargs)
def compute_SSC(self, nu, ne, g_params, B, params, boost_p=None, **kwargs):
"""
Same as :func:`Geometry._compute_SSC` but accepts ``boost_p`` keyword. See class :class:`DopplerBooster`
"""
if boost_p is None:
return self._compute_SSC(nu, ne, g_params, B, params, **kwargs)
else:
return self.booster(*boost_p)(self._compute_SSC)(nu, ne, g_params, B, params, **kwargs)
def compute_synchrotron(self, nu, ne, g_params, B, params, boost_p=None, **kwargs):
"""
Same as :func:`Geometry._compute_synchrotron` but accepts ``boost_p`` keyword. See class :class:`DopplerBooster`
"""
if boost_p is None:
return self._compute_synchrotron(nu, ne, g_params, B, params, **kwargs)
else:
return self.booster(*boost_p)(self._compute_synchrotron)(nu, ne, g_params, B, params, **kwargs)
class HomogeneousSphere(Geometry):
"""
Exact homogeneous sphere.
g_params for this class are:
- R, size of the sphere [cm]
- incang, Magnetic field configuration. -1 for tangled or uniform field lines at an angle to observer [rad]
Parameters
----------
edist: str
Name of the electron distribution for the geometry. Refer to docs.
method: str
Reserved for later use.
booster: class
A boosting implementation, ie. :class:`DopplerBooster`
"""
def _rtrans_homogeneous_sphere(self, nu, jnu, anu, R):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return np.select([anu*R < 1e-4, anu*R > 10],
[4*np.pi*jnu*R*R*R/3, np.pi*jnu*R*R/anu],
default=np.pi*jnu*R*R/anu*(1-1./(2.*anu*anu*R*R)*(1-np.exp(-2*anu*R)*(2*anu*R+1))))
def _compute_synchrotron(self, nu, ne, g_params, B, params, **kwargs):
jnu = self.j_nu_fun(nu, ne, B, params, edist=self.edist, incang=g_params[1], **kwargs)
anu = self.a_nu_fun(nu, ne, B, params, edist=self.edist, incang=g_params[1], **kwargs)
return 4*np.pi*self._rtrans_homogeneous_sphere(nu, jnu, anu, g_params[0])
def _compute_photon_density(self, nu, ne, g_params, B, params, **kwargs):
return self._compute_synchrotron(nu, ne, g_params, B, params, **kwargs)/(h**2*nu*c*4*np.pi*g_params[0]**2)
def _compute_SSC(self, nu, ne, g_params, B, params, **kwargs):
n_ph_fun = lambda nu: self._compute_photon_density(nu, ne, g_params, B, params, **kwargs)
return self._compute_IC(nu, ne, n_ph_fun, g_params, B, params, **kwargs)
def _compute_IC(self, nu, ne, n_ph_fun, g_params, B, params, **kwargs):
e_dist_fun = lambda gamma: eDist(gamma, ne, params, edist=self.edist)
j_nu_ic = compton_emissivity_from_fun(nu, n_ph_fun, e_dist_fun, **kwargs)
return (4*np.pi*j_nu_ic)*4*np.pi*g_params[0]**3/3.
class HomogeneousSphereUserdist(Geometry):
"""
Special geometry class with different interface to work with given user electron distribution.
Parameters
----------
booster: class
A boosting implementation, ie. :class:`DopplerBooster`
"""
def __init__(self, booster=None):
self.booster = DopplerBooster if booster is None else booster
def _rtrans_homogeneous_sphere(self, nu, jnu, anu, R):
with warnings.catch_warnings():
warnings.simplefilter("ignore") # since this computes all then selects wrt proper index, throws bunch of division errors.
return np.select([anu*R < 1e-4, anu*R > 10],
[4*np.pi*jnu*R*R*R/3, np.pi*jnu*R*R/anu],
default=np.pi*jnu*R*R/anu*(1-1./(2.*anu*anu*R*R)*(1-np.exp(-2*anu*R)*(2*anu*R+1))))
def _compute_synchrotron(self, nu, Ne, g_params, B, gamma, **kwargs):
"""
Computes synchrotron luminosity
Parameters
----------
nu : np.ndarray
Frequency array [Hz]
Ne : np.ndarray
Electron distribution on gamma grid. Note this is not density total electrons
g_params : list
Geometry parameters. same as :class:`HomogeneousSphere`
B : float
Magnetic field [G]
gamma : np.ndarray
gamma corresponding to Ne
Returns
-------
L_nu : np.ndarray
[erg s-1 Hz-1]
"""
V = 4./3.*np.pi*g_params[0]**3
jnu = j_nu_userdist(nu, B, gamma, Ne/V, incang=g_params[1], **kwargs)
anu = a_nu_userdist(nu, B, gamma, Ne/V, incang=g_params[1], **kwargs)
return 4*np.pi*self._rtrans_homogeneous_sphere(nu, jnu, anu, g_params[0])
def compute_synchrotron(self, nu, Ne, g_params, B, gamma, boost_p=None, **kwargs):
if boost_p is None:
return self._compute_synchrotron(nu, Ne, g_params, B, gamma, **kwargs)
else:
return self.booster(*boost_p)(self._compute_synchrotron)(nu, Ne, g_params, B, gamma, **kwargs)
class RadialSphere(Geometry):
"""
Numerical computation of spherical model where it is possible to set radial profiles in electron density or magnetic field.
g_params for this class are:
- R, size of the sphere [cm]
- R_in, inner radius of the sphere. 0 if not necessary.
- incang, Magnetic field configuration. -1 for tangled or uniform field lines at an angle to observer [rad]
Parameters
----------
n_r_fun: function
Radial profile of n_e
B_r_fun: function
Radial profile of magnetic field
edist: str
Electron distribution tag
method: str
Reserved for later
bh: boolean, default=False
Max absorption below R_in
rsteps: int
Specify number of radial grid points
target: str, default="cpu"
How to perform inverse Compton scattering, either "cpu" or "gpu".
"""
def __init__(self, n_r_fun=lambda x: 1., B_r_fun=lambda x: 1.,
edist="thermal", method="brute", bh=False, rsteps=64, target="cpu"):
self.rsteps = rsteps
if target == "gpu" and GPU_ENABLED == False:
warnings.warn("Setting target to cpu. GPU functions not available...")
self.target = "cpu"
else:
self.target = target
self.bh = bh
self.n_r_fun = n_r_fun
self.B_r_fun = B_r_fun
super().__init__(edist=edist, method=method)
def n_r_geom(self, r, R, R_in):
return np.piecewise(r, [np.logical_and(R_in < r, r < R)], [1., 0])
def abs_r_geom(self, r, R, R_in):
if self.bh == True:
return np.piecewise(r, [r < R_in, np.logical_and(R_in < r, r < R)],
[1e99, 1., 0.])
else:
return self.n_r_geom(r, R, R_in)
def _compute_grid(self, R):
rsteps = self.rsteps
xx = np.linspace(0, R, rsteps)+R/(rsteps-1)*0.5
xx_sq = xx**2
RR = np.sqrt(np.add.outer(xx_sq, xx_sq))
RR = np.concatenate((RR[:,::-1], RR[:,:]), axis=1)
dx = R/(rsteps-1)
return dx, xx, RR
def _radiative_transfer(self, nu, ne, g_params, B, params, **kwargs):
rsteps = self.rsteps
R, R_in = g_params[:2]
dx, xx, RR = self._compute_grid(R)
j_nu = np.zeros([nu.shape[0], rsteps, 2*rsteps])
a_nu = np.zeros([nu.shape[0], rsteps, 2*rsteps])
for i in range(rsteps):
j_nu[:,i,0] = self.j_nu_fun(nu, ne*self.n_r_fun(xx[i]), B*self.B_r_fun(xx[i]), params,
edist=self.edist, incang=g_params[-1], **kwargs)
a_nu[:,i,0] = self.a_nu_fun(nu, ne*self.n_r_fun(xx[i]), B*self.B_r_fun(xx[i]), params,
edist=self.edist, incang=g_params[-1], **kwargs)
for i in range(nu.shape[0]):
j_nu[i,:,:] = np.interp(RR, xx[:-1], j_nu[i,:-1,0])*self.n_r_geom(RR, R, R_in)
a_nu[i,:,:] = np.interp(RR, xx[:-1], a_nu[i,:-1,0])*self.abs_r_geom(RR, R, R_in)
return ray_tracing(j_nu, a_nu, dx), xx, RR
def _compute_synchrotron(self, nu, ne, g_params, B, params, **kwargs):
integrand_r, xx, _ = self._radiative_transfer(nu, ne, g_params, B, params, **kwargs)
return 4*np.pi*np.array([np.trapz(integrand_r[i,:,-1]*2*np.pi*xx, xx) for i in range(nu.shape[0])])
def _compute_photon_density(self, nu, ne, g_params, B, params, **kwargs):
rsteps = self.rsteps
R, R_in = g_params[:2]
S_nu, xx, RR = self._radiative_transfer(nu, ne, g_params, B, params, **kwargs)
n_ph = np.zeros([rsteps-1, nu.shape[0]])
bins = xx[1:] - R/(rsteps-1)*0.5
dcost = (np.tile(xx, (2*rsteps, 1)).T/RR)
cnts, _ = np.histogram(RR, bins=rsteps-1, range=[0,R], weights=dcost)
| |
validate(self):
return
def __hash__(self):
value = 17
value = (value * 31) ^ hash(self.cxt_id)
value = (value * 31) ^ hash(self.mgrp_handle)
value = (value * 31) ^ hash(self.l1_handle)
return value
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class bm_mc_node_associate_result:
"""
Attributes:
- ouch
"""
thrift_spec = (
None, # 0
(1, TType.STRUCT, 'ouch', (InvalidMcOperation, InvalidMcOperation.thrift_spec), None, ), # 1
)
def __init__(self, ouch=None,):
self.ouch = ouch
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.ouch = InvalidMcOperation()
self.ouch.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('bm_mc_node_associate_result')
if self.ouch is not None:
oprot.writeFieldBegin('ouch', TType.STRUCT, 1)
self.ouch.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __hash__(self):
value = 17
value = (value * 31) ^ hash(self.ouch)
return value
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class bm_mc_node_dissociate_args:
"""
Attributes:
- cxt_id
- mgrp_handle
- l1_handle
"""
thrift_spec = (
None, # 0
(1, TType.I32, 'cxt_id', None, None, ), # 1
(2, TType.I32, 'mgrp_handle', None, None, ), # 2
(3, TType.I32, 'l1_handle', None, None, ), # 3
)
def __init__(self, cxt_id=None, mgrp_handle=None, l1_handle=None,):
self.cxt_id = cxt_id
self.mgrp_handle = mgrp_handle
self.l1_handle = l1_handle
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.cxt_id = iprot.readI32();
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.I32:
self.mgrp_handle = iprot.readI32();
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.I32:
self.l1_handle = iprot.readI32();
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('bm_mc_node_dissociate_args')
if self.cxt_id is not None:
oprot.writeFieldBegin('cxt_id', TType.I32, 1)
oprot.writeI32(self.cxt_id)
oprot.writeFieldEnd()
if self.mgrp_handle is not None:
oprot.writeFieldBegin('mgrp_handle', TType.I32, 2)
oprot.writeI32(self.mgrp_handle)
oprot.writeFieldEnd()
if self.l1_handle is not None:
oprot.writeFieldBegin('l1_handle', TType.I32, 3)
oprot.writeI32(self.l1_handle)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __hash__(self):
value = 17
value = (value * 31) ^ hash(self.cxt_id)
value = (value * 31) ^ hash(self.mgrp_handle)
value = (value * 31) ^ hash(self.l1_handle)
return value
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class bm_mc_node_dissociate_result:
"""
Attributes:
- ouch
"""
thrift_spec = (
None, # 0
(1, TType.STRUCT, 'ouch', (InvalidMcOperation, InvalidMcOperation.thrift_spec), None, ), # 1
)
def __init__(self, ouch=None,):
self.ouch = ouch
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.ouch = InvalidMcOperation()
self.ouch.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('bm_mc_node_dissociate_result')
if self.ouch is not None:
oprot.writeFieldBegin('ouch', TType.STRUCT, 1)
self.ouch.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __hash__(self):
value = 17
value = (value * 31) ^ hash(self.ouch)
return value
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class bm_mc_node_destroy_args:
"""
Attributes:
- cxt_id
- l1_handle
"""
thrift_spec = (
None, # 0
(1, TType.I32, 'cxt_id', None, None, ), # 1
(2, TType.I32, 'l1_handle', None, None, ), # 2
)
def __init__(self, cxt_id=None, l1_handle=None,):
self.cxt_id = cxt_id
self.l1_handle = l1_handle
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.cxt_id = iprot.readI32();
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.I32:
self.l1_handle = iprot.readI32();
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('bm_mc_node_destroy_args')
if self.cxt_id is not None:
oprot.writeFieldBegin('cxt_id', TType.I32, 1)
oprot.writeI32(self.cxt_id)
oprot.writeFieldEnd()
if self.l1_handle is not None:
oprot.writeFieldBegin('l1_handle', TType.I32, 2)
oprot.writeI32(self.l1_handle)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __hash__(self):
value = 17
value = (value * 31) ^ hash(self.cxt_id)
value = (value * 31) ^ hash(self.l1_handle)
return value
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class bm_mc_node_destroy_result:
"""
Attributes:
- ouch
"""
thrift_spec = (
None, # 0
(1, TType.STRUCT, 'ouch', (InvalidMcOperation, InvalidMcOperation.thrift_spec), None, ), # 1
)
def __init__(self, ouch=None,):
self.ouch = ouch
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.STRUCT:
self.ouch = InvalidMcOperation()
self.ouch.read(iprot)
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('bm_mc_node_destroy_result')
if self.ouch is not None:
oprot.writeFieldBegin('ouch', TType.STRUCT, 1)
self.ouch.write(oprot)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __hash__(self):
value = 17
value = (value * 31) ^ hash(self.ouch)
return value
def __repr__(self):
L = ['%s=%r' % (key, value)
for key, value in self.__dict__.iteritems()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class bm_mc_node_update_args:
"""
Attributes:
- cxt_id
- l1_handle
- port_map
"""
thrift_spec = (
None, # 0
(1, TType.I32, 'cxt_id', None, None, ), # 1
(2, TType.I32, 'l1_handle', None, None, ), # 2
(3, TType.STRING, 'port_map', None, None, ), # 3
)
def __init__(self, cxt_id=None, l1_handle=None, port_map=None,):
self.cxt_id = cxt_id
self.l1_handle = l1_handle
self.port_map = port_map
def read(self, iprot):
if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None:
fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec))
return
iprot.readStructBegin()
while True:
(fname, ftype, fid) = iprot.readFieldBegin()
if ftype == TType.STOP:
break
if fid == 1:
if ftype == TType.I32:
self.cxt_id = iprot.readI32();
else:
iprot.skip(ftype)
elif fid == 2:
if ftype == TType.I32:
self.l1_handle = iprot.readI32();
else:
iprot.skip(ftype)
elif fid == 3:
if ftype == TType.STRING:
self.port_map = iprot.readString();
else:
iprot.skip(ftype)
else:
iprot.skip(ftype)
iprot.readFieldEnd()
iprot.readStructEnd()
def write(self, oprot):
if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None:
oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec)))
return
oprot.writeStructBegin('bm_mc_node_update_args')
if self.cxt_id is not None:
oprot.writeFieldBegin('cxt_id', TType.I32, 1)
oprot.writeI32(self.cxt_id)
oprot.writeFieldEnd()
if self.l1_handle is not None:
oprot.writeFieldBegin('l1_handle', TType.I32, 2)
oprot.writeI32(self.l1_handle)
oprot.writeFieldEnd()
if self.port_map is not None:
oprot.writeFieldBegin('port_map', TType.STRING, 3)
oprot.writeString(self.port_map)
oprot.writeFieldEnd()
oprot.writeFieldStop()
oprot.writeStructEnd()
def validate(self):
return
def __hash__(self):
value = 17
value = (value * 31) ^ hash(self.cxt_id)
value = (value * 31) ^ hash(self.l1_handle)
value = (value * 31) ^ hash(self.port_map)
return value
def __repr__(self):
L = | |
circmask
@staticmethod
def get_unique_values(mask):
"""Get all unique positive values from labeled mask."""
values = np.unique(mask[mask > 0])
if values.size == 0:
values = None
return values
@staticmethod
def get_unique_count(mask):
"""Get count of unique positive values from labeled mask."""
return np.unique(mask[mask > 0]).size
@staticmethod
def filter_property(properties, filter_param, filter_name, slice_type):
"""Get labels of beads outside/inside/up/down of propert limits.
Parameters
----------
properties : photutils table
Table with feature properties from labeled mask.
>>> from photutils import source_properties, properties_table
>>> tbl = properties_table(properties)
>>> properties = source_properties(mask, mask)
filter_param : float, int, list
Parameters to filter by.
If provided a list it will filter by range, inside or outside).
If provided a value it filter up or down that value.
slice_type : string
'outside' : < >
'inside' : >= <=
'up' : >
'down' : <
"""
if isinstance(filter_param, list):
if slice_type == 'outside':
lbls_out = properties[(properties[filter_name]
< filter_param[0])
| (properties[filter_name]
> filter_param[1])].label.values
elif slice_type == 'inside':
lbls_out = properties[(properties[filter_name]
>= filter_param[0])
& (properties[filter_name]
<= filter_param[1])].label.values
else:
if slice_type == 'up':
lbls_out = properties[properties[filter_name]
> filter_param].label.values
elif slice_type == 'down':
lbls_out = properties[properties[filter_name]
< filter_param].label.values
return lbls_out
@staticmethod
def _morph_mask_step(steps, mask):
"""Morph mask step-by-step using erosion or dilation.
This function will erode or dilate step-by-step, in a loop, each
labeled feature in labeled mask array.
Parameters
----------
steps : int
Set number of dilation (positive value, grow outward) or erosion
(negative value, shrink inward) steps.
mask : NumPy array
Labeled mask to be dilated or eroded.
"""
morph_mask = mask.copy()
if steps < 0:
for _ in range(abs(steps)):
morph_mask = sk.morphology.erosion(morph_mask)
elif steps > 0:
for _ in range(steps):
morph_mask = sk.morphology.dilation(morph_mask)
return morph_mask
@staticmethod
def _bin2seg(image):
"""Convert and adaptive threshold image."""
ellipse_kernel = cv2.getStructuringElement(shape=cv2.MORPH_ELLIPSE,
ksize=(3, 3))
seg_img = ndi.label(image, structure=ellipse_kernel)[0]
return seg_img
@staticmethod
def get_dimensions(mask):
"""Get dimensions of labeled regions in labeled mask."""
properties = photutils.source_properties(mask, mask)
if not properties:
return None
tbl = properties.to_table() # Convert to table
lbl = np.array(tbl['min_value'], dtype=np.int16)
reg_x = tbl['xcentroid']
reg_y = tbl['ycentroid']
reg_r = tbl['equivalent_radius']
reg_area = tbl['area']
perimeter = tbl['perimeter']
eccentricity = tbl['eccentricity']
pdata = np.array([lbl, reg_x, reg_y, reg_r, reg_area,
perimeter, eccentricity]).T
dims = pd.DataFrame(data=pdata,
columns=['label',
'x_centroid',
'y_centroid',
'radius',
'area',
'perimeter',
'eccentricity'])
return dims
@staticmethod
def cross_overlay(image, dims, color=True):
"""Create image with overlay crosses."""
img = skimage.color.gray2rgb(image)
if isinstance(dims, pd.DataFrame):
dims = np.array(np.round(dims.values.astype(np.float)),
dtype=np.int)
for center_x, center_y, radius in zip(dims[:, 0],
dims[:, 1],
dims[:, 2]):
line_y = slice(int(round(center_y) - round(radius)),
int(round(center_y) + round(radius)))
line_x = slice(int(round(center_x) - round(radius)),
int(round(center_x) + round(radius)))
width_x = int(round(center_x))
width_y = int(round(center_y))
img[width_y, line_x] = (20, 20, 220)
img[line_y, width_x] = (20, 20, 220)
if color is False:
img = skimage.color.rgb2gray(img)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
img = skimage.img_as_uint(img)
return img
@staticmethod
def show_image_overlay(image, image_blend,
alpha=0.3, cmap1='Greys_r', cmap2='jet'):
"""Overlay of 2 images using alpha blend.
Parameters
----------
image : NumPy array
Base image.
image_blend : NumPy arra
Image to blend over base image.
aplha : float
Amount of blending. Value between 0 and 1.
Defaults to 0.3.
c_map1 : cmap
Color scheme using cmap. See matplotlib for color schemes.
Defaults to 'Greys_r', which are reversed grey values.
"""
plt.axis('off')
plt.imshow(image, cmap=cmap1)
plt.imshow(image_blend, cmap=cmap2, interpolation='none', alpha=alpha)
@staticmethod
@accepts((np.ndarray, xr.DataArray))
def _img2ubyte(image):
"""Convert image to ubuyte (uint8) and rescale to min/max.
Parameters : NumPy or xarray
Image to be converted and rescaled to ubuyte.
"""
if isinstance(image, xr.DataArray):
image = image.values
img_dtype = image.dtype
if img_dtype is np.dtype('uint8'):
return image
img_min = image - image.min()
img_max = img_min.max()
img_conv = np.array((img_min / img_max) * 255, dtype=np.uint8)
return img_conv
@staticmethod
def _img_invert(img_thr):
"""Invert boolean image.
Parameters
----------
img_thr : NumPy array
Boolean image in NumPy format.
"""
img_inv = (~img_thr.astype(bool)).astype(int)
return img_inv
@staticmethod
def circle_area(diameter):
"""Return area of circle.
Parameters
----------
diameter : float
Diameter of circle.
"""
radius = ceil(diameter / 2)
return np.pi * radius**2
@staticmethod
def eccentricity(axis_a, axis_b):
"""Return eccentricity by major axes.
Parameters
----------
axis_a : float
Size major axis a.
axis_b : float
Size major axis b.
"""
major = max([axis_a, axis_b])
minor = min([axis_a, axis_b])
return sqrt(1 - (minor**2 / major**2))
class FindBeadsCircle(FindBeadsImaging):
"""Find and identify bead objects from image.
Parameters changes for each setup/magnification/bead-set.
Parameters
----------
min_r : int
Sets the minimum diameter of the bead in pixels.
max_r : int
Sets the maximum diameter of the bead in pixels.
param_1 : int
Sets the gradient steepness. CHECK
param_2 : int
Sets the sparsity. CHECK
annulus_width : int, optional
Sets the width of the annulus in pixels.
Defaults to 2 pixels.
min_dist : int, optional
Sets the minimal distance between the centers of the beads in pixels.
Defaults to 2x of the minimum diameter (min_r).
enlarge : float, optional
Enlarges the found diameter by this factor.
1 remains equal, 1.1 enlarges by 10% and 0.9 shrinks by 10%.
Defaults to 1, no enlarging/shrinking.
"""
def __init__(self, bead_size, min_r, max_r,
param_1=99, param_2=7,
annulus_width=2,
min_dist=None, enlarge=1,
auto_filt=True, border_clear=False,
parallelize=True):
"""Instantiate FindBeadsCircle."""
super(FindBeadsCircle, self).__init__(bead_size)
self.min_r = min_r
self.max_r = max_r
self.annulus_width = annulus_width
self.param_1 = param_1
self.param_2 = param_2
self.enlarge = enlarge
self.auto_filt = auto_filt
self.border_clear = border_clear
self.parallelize = parallelize
# Default values for local background
self.mask_bkg_size = 11
self.mask_bkg_buffer = 2
if min_dist is not None:
self.min_dist = min_dist
else:
self.min_dist = 2 * min_r
self._labeled_mask = None
self._labeled_annulus_mask = None
self._circles_dim = None
self._dataframe = None
@staticmethod
def circle_mask(image, min_dist, min_r, max_r, param_1, param_2, enlarge):
"""Find initial circles using Hough transform and return mask."""
try: # TO-DO: HACK - Fix later
circles = cv2.HoughCircles(image, cv2.HOUGH_GRADIENT, dp=1,
minDist=min_dist,
param1=param_1,
param2=param_2,
minRadius=min_r,
maxRadius=max_r)[0]
except ValueError:
return None
mask = np.zeros(image.shape, np.uint8) # Make mask
for c in circles:
x, y, r = c[0], c[1], int(np.ceil(c[2] * enlarge))
# Draw circle on mask (line width -1 fills circle)
cv2.circle(mask, (x, y), r, (255, 255, 255), -1)
return mask, circles
@staticmethod
def circle_separate(mask, circles):
"""Find and separate circles using watershed on initial mask."""
D = ndi.distance_transform_edt(mask, sampling=1)
markers_circles = np.zeros_like(mask)
for _, circle in enumerate(circles):
markers_circles[int(circle[1]), int(circle[0])] = 1
markers = ndi.label(markers_circles, structure=np.ones((3, 3)))[0]
labels = sk.morphology.watershed(np.negative(D), markers, mask=mask)
# print("Number of unique segments found: {}".format(
# len(np.unique(labels)) - 1))
return labels
def _get_dimensions(self, labels):
"""Find center of circle and return dimensions."""
idx = np.arange(1, len(np.unique(labels)))
circles_dim = np.empty((len(np.unique(labels)) - 1, 3))
for label in idx:
# Create single object mask
mask_detect = np.zeros(labels.shape, dtype="uint8")
mask_detect[labels == label] = 255
# Detect contours in the mask and grab the largest one
cnts = cv2.findContours(mask_detect.copy(),
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[-2]
c = max(cnts, key=cv2.contourArea)
# Get circle dimensions
((x, y), r) = cv2.minEnclosingCircle(c)
circles_dim[label - 1, 0] = int(x)
circles_dim[label - 1, 1] = int(y)
circles_dim[label - 1, 2] = int(r)
return circles_dim
# Main function
def find(self, image):
"""Execute finding beads image(s)."""
if isinstance(image, xr.DataArray):
image = image.values
if image.ndim == 3:
if (sys.version_info >= (3, 0)) and (self.parallelize is True):
mp_worker = mp.Pool()
result = mp_worker.map(self._find, image)
mp_worker.close()
mp_worker.join()
else:
result = list(map(self._find, image))
r_m = [i[0] for i in result]
r_d = [i[1] for i in result]
self._dataframe = xr.concat(r_m, dim='f')
self._bead_dims = pd.concat(r_d,
keys=list(range(len(r_d))),
names=['f', 'bead_index'])
else:
self._dataframe, self._bead_dims = self._find(image)
def _find(self, image):
"""Find objects in image and return data."""
img = self._img2ubyte(image)
mask, circles = self.circle_mask(img, self.min_dist,
self.min_r,
self.max_r,
self.param_1,
self.param_2,
self.enlarge)
if mask is None:
return None
self._labeled_mask = self.circle_separate(mask, circles)
self._circles_dim = self._get_dimensions(self._labeled_mask)
bead_dims = self.get_dimensions(self._labeled_mask)
self._labeled_annulus_mask = self.create_annulus_mask(
self._labeled_mask)
if self.auto_filt is True:
self._filter()
mask_outside = self.make_mask_outside(self._labeled_mask,
self.mask_bkg_size,
buffer=0)
mask_bkg = self.make_mask_outside(self._labeled_mask,
self.mask_bkg_size,
buffer=self.mask_bkg_buffer)
mask_inside = self._labeled_mask - self._labeled_annulus_mask
mask_inside[mask_inside < 0] = 0
bead_dims_overlay = bead_dims.loc[:, ('x_centroid',
'y_centroid',
'radius')]
overlay_image = self.cross_overlay(img,
bead_dims_overlay,
color=False)
masks = xr.DataArray(data=np.array([self._labeled_mask,
self._labeled_annulus_mask,
mask_inside,
mask_outside,
mask_bkg,
overlay_image],
dtype=np.uint16),
dims=['c', 'y', 'x'],
coords={'c': ['mask_full',
'mask_ring',
'mask_inside',
'mask_outside',
'mask_bkg',
'mask_check']})
return [masks, bead_dims]
def create_annulus_mask(self, labeled_mask):
"""Create annulus mask from regular mask."""
labeled_annulus_mask = labeled_mask.copy()
for cd in self._circles_dim:
if (int(cd[2] - self.annulus_width)) | |
<reponame>DeVriesMatt/VGN
# a special script for testing images in the HRF dataset
# here, multiple sub-images from a single image are independently tested
# and tiled to make a result for the whole image
# coded by syshin (180430)
# updated by syshin (180903)
import numpy as np
import os
import pdb
import argparse
import skimage.io
import networkx as nx
import pickle as pkl
import multiprocessing
import skfmm
import tensorflow as tf
from config import cfg
from model import vessel_segm_vgn
import util
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Test a vessel_segm_vgn network')
parser.add_argument('--dataset', default='HRF', help='Dataset to use', type=str)
#parser.add_argument('--use_multiprocessing', action='store_true', default=False, help='Whether to use the python multiprocessing module')
parser.add_argument('--use_multiprocessing', default=True, help='Whether to use the python multiprocessing module', type=bool)
parser.add_argument('--multiprocessing_num_proc', default=8, help='Number of CPU processes to use', type=int)
parser.add_argument('--win_size', default=32, help='Window size for srns', type=int) # for srns # [4,8,16,32]
parser.add_argument('--edge_type', default='srns_geo_dist_binary', \
help='Graph edge type: Can be srns_geo_dist_binary or srns_geo_dist_weighted', type=str)
parser.add_argument('--edge_geo_dist_thresh', default=80, help='Threshold for geodesic distance', type=float) # [10,20,40,80]
parser.add_argument('--model_path', default='../models/HRF/VGN/VGN_HRF.ckpt', \
help='Path for a trained model(.ckpt)', type=str)
parser.add_argument('--save_root', default='../models/HRF/VGN', \
help='Root path to save test results', type=str)
### cnn module related ###
parser.add_argument('--cnn_model', default='driu_large', help='CNN model to use', type=str)
parser.add_argument('--cnn_loss_on', default=True, help='Whether to use a cnn loss for training', type=bool)
### gnn module related ###
parser.add_argument('--gnn_loss_on', default=True, help='Whether to use a gnn loss for training', type=bool)
parser.add_argument('--gnn_loss_weight', default=1., help='Relative weight on the gnn loss', type=float)
# gat #
parser.add_argument('--gat_n_heads', default=[4,4], help='Numbers of heads in each layer', type=list) # [4,1]
#parser.add_argument('--gat_n_heads', nargs='+', help='Numbers of heads in each layer', type=int) # [4,1]
parser.add_argument('--gat_hid_units', default=[16], help='Numbers of hidden units per each attention head in each layer', type=list)
#parser.add_argument('--gat_hid_units', nargs='+', help='Numbers of hidden units per each attention head in each layer', type=int)
parser.add_argument('--gat_use_residual', action='store_true', default=False, help='Whether to use residual learning in GAT')
### inference module related ###
parser.add_argument('--norm_type', default=None, help='Norm. type', type=str)
parser.add_argument('--use_enc_layer', action='store_true', default=False, \
help='Whether to use additional conv. layers in a infer_module')
parser.add_argument('--infer_module_loss_masking_thresh', default=0.05, \
help='Threshold for loss masking', type=float)
parser.add_argument('--infer_module_kernel_size', default=3, \
help='Conv. kernel size for the inference module', type=int)
parser.add_argument('--infer_module_grad_weight', default=1., \
help='Relative weight of the grad. on the infer_module', type=float)
### training (declared but not used) ###
parser.add_argument('--do_simul_training', default=True, \
help='Whether to train the gnn and inference modules simultaneously or not', type=bool)
parser.add_argument('--max_iters', default=100000, help='Maximum number of iterations', type=int)
parser.add_argument('--old_net_ft_lr', default=1e-03, help='Learnining rate for fine-tuning of old parts of network', type=float)
parser.add_argument('--new_net_lr', default=1e-03, help='Learnining rate for a new part of network', type=float)
parser.add_argument('--opt', default='adam', help='Optimizer to use: Can be sgd or adam', type=str)
parser.add_argument('--lr_scheduling', default='pc', help='How to change the learning rate during training', type=str)
parser.add_argument('--lr_decay_tp', default=1., help='When to decrease the lr during training', type=float) # for pc
args = parser.parse_args()
return args
def save_dict(dic, filename):
with open(filename, 'wb') as f:
pkl.dump(dic, f)
def load_dict(filename):
with open(filename, 'rb') as f:
dic = pkl.load(f)
return dic
# This was modified to include loading CNN results due to a memory problem
def make_graph_using_srns((res_file_path, edge_type, win_size, edge_geo_dist_thresh)):
if 'srns' not in edge_type:
raise NotImplementedError
# loading
cur_res = load_dict(res_file_path)
fg_prob_map = cur_res['temp_fg_prob_map']
img_path = cur_res['img_path']
# find local maxima
vesselness = fg_prob_map
im_y = vesselness.shape[0]
im_x = vesselness.shape[1]
y_quan = range(0,im_y,win_size)
y_quan = sorted(list(set(y_quan) | set([im_y])))
x_quan = range(0,im_x,win_size)
x_quan = sorted(list(set(x_quan) | set([im_x])))
max_val = []
max_pos = []
for y_idx in xrange(len(y_quan)-1):
for x_idx in xrange(len(x_quan)-1):
cur_patch = vesselness[y_quan[y_idx]:y_quan[y_idx+1],x_quan[x_idx]:x_quan[x_idx+1]]
if np.sum(cur_patch)==0:
max_val.append(0)
max_pos.append((y_quan[y_idx]+cur_patch.shape[0]/2,x_quan[x_idx]+cur_patch.shape[1]/2))
else:
max_val.append(np.amax(cur_patch))
temp = np.unravel_index(cur_patch.argmax(), cur_patch.shape)
max_pos.append((y_quan[y_idx]+temp[0],x_quan[x_idx]+temp[1]))
graph = nx.Graph()
# add nodes
for node_idx, (node_y, node_x) in enumerate(max_pos):
graph.add_node(node_idx, kind='MP', y=node_y, x=node_x, label=node_idx)
print 'node label', node_idx, 'pos', (node_y,node_x), 'added'
speed = vesselness
node_list = list(graph.nodes)
for i, n in enumerate(node_list):
phi = np.ones_like(speed)
phi[graph.node[n]['y'],graph.node[n]['x']] = -1
if speed[graph.node[n]['y'],graph.node[n]['x']]==0:
continue
neighbor = speed[max(0,graph.node[n]['y']-1):min(im_y,graph.node[n]['y']+2), \
max(0,graph.node[n]['x']-1):min(im_x,graph.node[n]['x']+2)]
if np.mean(neighbor)<0.1:
continue
tt = skfmm.travel_time(phi, speed, narrow=edge_geo_dist_thresh) # travel time
for n_comp in node_list[i+1:]:
geo_dist = tt[graph.node[n_comp]['y'],graph.node[n_comp]['x']] # travel time
if geo_dist < edge_geo_dist_thresh:
graph.add_edge(n, n_comp, weight=edge_geo_dist_thresh/(edge_geo_dist_thresh+geo_dist))
print 'An edge BTWN', 'node', n, '&', n_comp, 'is constructed'
# (re-)save
cur_res['graph'] = graph
save_dict(cur_res, res_file_path)
print 'generated a graph for '+img_path
if __name__ == '__main__':
args = parse_args()
print('Called with args:')
print(args)
# added for testing on a restricted test set
test_type = ['dr', 'g', 'h']
# added for testing on a restricted test set
IMG_SIZE = [2336,3504]
SUB_IMG_SIZE = 768
SUB_IMG_ROOT_PATH = '../HRF/all_768'
y_mins = range(0,IMG_SIZE[0]-SUB_IMG_SIZE+1,SUB_IMG_SIZE-50)
x_mins = range(0,IMG_SIZE[1]-SUB_IMG_SIZE+1,SUB_IMG_SIZE-50)
y_mins = sorted(list(set(y_mins + [IMG_SIZE[0]-SUB_IMG_SIZE])))
x_mins = sorted(list(set(x_mins + [IMG_SIZE[1]-SUB_IMG_SIZE])))
with open('../HRF/test_fr.txt') as f:
test_whole_img_paths = [x.strip() for x in f.readlines()]
# added for testing on a restricted test set
temp = []
for i in xrange(len(test_whole_img_paths)):
for j in xrange(len(test_type)):
if test_type[j] in test_whole_img_paths[i][util.find(test_whole_img_paths[i],'/')[-1]+1:]:
temp.append(test_whole_img_paths[i])
break
test_whole_img_paths = temp
# added for testing on a restricted test set
test_whole_img_names = map(lambda x: x[util.find(x,'/')[-1]+1:], test_whole_img_paths) # different to 'test_img_names'
if args.use_multiprocessing:
pool = multiprocessing.Pool(processes=args.multiprocessing_num_proc)
#temp_graph_save_path = args.save_root + '/' + cfg.TRAIN.TEMP_GRAPH_SAVE_PATH if len(args.save_root)>0 else cfg.TRAIN.TEMP_GRAPH_SAVE_PATH
res_save_path = args.save_root + '/' + cfg.TEST.RES_SAVE_PATH if len(args.save_root)>0 else cfg.TEST.RES_SAVE_PATH
if len(args.save_root)>0 and not os.path.isdir(args.save_root):
os.mkdir(args.save_root)
if not os.path.isdir(res_save_path):
os.mkdir(res_save_path)
with open('../HRF/test_768.txt') as f:
test_img_names = [x.strip() for x in f.readlines()]
# added for testing on a restricted test set
temp = []
for i in xrange(len(test_img_names)):
for j in xrange(len(test_type)):
if test_type[j] in test_img_names[i][util.find(test_img_names[i],'/')[-1]+1:]:
temp.append(test_img_names[i])
break
test_img_names = temp
# added for testing on a restricted test set
len_test = len(test_img_names)
data_layer_test = util.DataLayer(test_img_names, \
is_training=False, \
use_padding=False)
network = vessel_segm_vgn(args, None)
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.InteractiveSession(config=config)
saver = tf.train.Saver()
sess.run(tf.global_variables_initializer())
assert args.model_path, 'Model path is not available'
print "Loading model..."
saver.restore(sess, args.model_path)
f_log = open(os.path.join(res_save_path,'log.txt'), 'w')
f_log.write(str(args)+'\n')
f_log.flush()
timer = util.Timer()
all_labels = np.concatenate(map(lambda x: np.expand_dims(skimage.io.imread(x+'.tif'), axis=0), test_whole_img_paths), axis=0)
all_masks = np.concatenate(map(lambda x: np.expand_dims(skimage.io.imread(x+'_mask.tif'), axis=0), test_whole_img_paths), axis=0)
all_masks = all_masks[:,:,:,0]
all_labels = ((all_labels.astype(float)/255)>=0.5).astype(float)
all_masks = ((all_masks.astype(float)/255)>=0.5).astype(float)
all_preds_cum_sum = np.zeros(all_labels.shape)
all_preds_cum_num = np.zeros(all_labels.shape)
print("Testing the model...")
### make cnn results (sub-image-wise) ###
res_file_path_list = []
for _ in xrange(int(np.ceil(float(len_test)/cfg.TRAIN.BATCH_SIZE))):
# get one batch
img_list, blobs_test = data_layer_test.forward()
img = blobs_test['img']
label = blobs_test['label']
conv_feats, fg_prob_tensor, \
cnn_feat_dict, cnn_feat_spatial_sizes_dict = sess.run(
[network.conv_feats,
network.img_fg_prob,
network.cnn_feat,
network.cnn_feat_spatial_sizes],
feed_dict={
network.imgs: img,
network.labels: label
})
cur_batch_size = len(img_list)
for img_idx in xrange(cur_batch_size):
cur_res = {}
cur_res['img_path'] = img_list[img_idx]
cur_res['img'] = img[[img_idx],:,:,:]
cur_res['label'] = label[[img_idx],:,:,:]
cur_res['conv_feats'] = conv_feats[[img_idx],:,:,:]
cur_res['temp_fg_prob_map'] = fg_prob_tensor[img_idx,:,:,0]
cur_res['cnn_feat'] = {k: v[[img_idx],:,:,:] for k, v in zip(cnn_feat_dict.keys(), cnn_feat_dict.values())}
cur_res['cnn_feat_spatial_sizes'] = cnn_feat_spatial_sizes_dict
cur_res['graph'] = None # will be filled at the next step
cur_res['final_fg_prob_map'] = cur_res['temp_fg_prob_map']
cur_res['ap_list'] = []
img_name = img_list[img_idx]
temp = img_name[util.find(img_name,'/')[-1]:]
mask = skimage.io.imread(SUB_IMG_ROOT_PATH + temp +'_mask.tif')
mask = ((mask.astype(float)/255)>=0.5).astype(float)
cur_res['mask'] = mask
# compute the current AP
cur_label = label[img_idx,:,:,0]
label_roi = cur_label[mask.astype(bool)].reshape((-1))
fg_prob_map_roi = cur_res['temp_fg_prob_map'][mask.astype(bool)].reshape((-1))
_, cur_cnn_ap = util.get_auc_ap_score(label_roi, fg_prob_map_roi)
cur_res['ap'] = cur_cnn_ap
cur_res['ap_list'].append(cur_cnn_ap)
# (initial) save
cur_res_file_path = res_save_path + temp + '.pkl'
save_dict(cur_res, cur_res_file_path)
res_file_path_list.append(cur_res_file_path)
### make final results (sub-image-wise) ###
# make graphs & append it to the existing pickle files # re-save
func_arg = []
for img_idx in xrange(len(res_file_path_list)):
func_arg.append((res_file_path_list[img_idx], args.edge_type, args.win_size, args.edge_geo_dist_thresh))
if args.use_multiprocessing:
pool.map(make_graph_using_srns, func_arg)
else:
for x in func_arg:
make_graph_using_srns(x)
# make final results
for img_idx in xrange(len(res_file_path_list)):
# load
cur_res = load_dict(res_file_path_list[img_idx])
cur_img = cur_res['img']
cur_conv_feats = cur_res['conv_feats']
cur_cnn_feat = cur_res['cnn_feat']
cur_cnn_feat_spatial_sizes = cur_res['cnn_feat_spatial_sizes']
cur_graph = cur_res['graph']
cur_graph = nx.convert_node_labels_to_integers(cur_graph)
node_byxs = util.get_node_byx_from_graph(cur_graph, [cur_graph.number_of_nodes()])
if 'geo_dist_weighted' in args.edge_type:
adj = nx.adjacency_matrix(cur_graph)
else:
adj = nx.adjacency_matrix(cur_graph,weight=None).astype(float)
adj_norm = util.preprocess_graph_gat(adj)
cur_feed_dict = \
{
network.imgs: cur_img,
network.conv_feats: cur_conv_feats,
network.node_byxs: node_byxs,
network.adj: adj_norm,
network.is_lr_flipped: False,
network.is_ud_flipped: False
}
cur_feed_dict.update({network.cnn_feat[cur_key]: cur_cnn_feat[cur_key] for cur_key in network.cnn_feat.keys()})
cur_feed_dict.update({network.cnn_feat_spatial_sizes[cur_key]: cur_cnn_feat_spatial_sizes[cur_key] for cur_key in network.cnn_feat_spatial_sizes.keys()})
res_prob_map = sess.run(
[network.post_cnn_img_fg_prob],
feed_dict=cur_feed_dict)
res_prob_map = res_prob_map[0]
res_prob_map = res_prob_map.reshape((res_prob_map.shape[1], res_prob_map.shape[2]))
# compute the current AP
cur_label = cur_res['label']
cur_label = np.squeeze(cur_label)
cur_mask = cur_res['mask']
label_roi = | |
f_dist_new[3])
f2_diff = f2_change / sampling_time
# Change in finger 3 distal x-coordinate position
f3_change = abs(f_dist_old[6] - f_dist_new[6])
f3_diff = f3_change / sampling_time
# Sum of changes in distal fingers
f_all_change = f1_diff + f2_diff + f3_diff
#print("f_all_change: ", f_all_change)
# If the fingers have only changed a small amount, we assume the object is grasped
if f_all_change < 0.0002:
return [1, f_all_change]
else:
return [0, f_all_change]
def NaiveController(lift_check, velocities):
""" Move fingers at a constant speed, return action """
# By default, close all fingers at a constant speed
action = np.array([0, velocities["constant_velocity"], velocities["constant_velocity"], velocities["constant_velocity"]])
# If ready to lift, set fingers to constant lifting velocities
if lift_check is True:
action = np.array([velocities["wrist_lift_velocity"], velocities["finger_lift_velocity"], velocities["finger_lift_velocity"],
velocities["finger_lift_velocity"]])
return action
def get_action(obs, lift_check, controller, env, pid_mode="combined"):
""" Get action based on controller (Naive, position-dependent, combined interpolation)
obs: Current state observation
controller: Initialized expert PID controller
env: Current Mujoco environment needed for expert PID controller
return action: np.array([wrist, f1, f2, f3]) (velocities in rad/sec)
"""
velocities = {"constant_velocity": 0.5, "min_velocity": 0.5, "max_velocity": 0.8, "finger_lift_velocity": 0.5, "wrist_lift_velocity": 0.6}
object_x_coord = obs[21] # Object x coordinate position
# By default, action is set to close fingers at a constant velocity
action = np.array([0, velocities["constant_velocity"], velocities["constant_velocity"], velocities["constant_velocity"]])
# NAIVE CONTROLLER: Close all fingers at a constant speed
if pid_mode == "naive":
action = NaiveController(lift_check, velocities)
# POSITION-DEPENDENT CONTROLLER: Only move fingers based on object x-coord position within hand
elif pid_mode == "position-dependent":
action, f1_vels, f2_vels, f3_vels, wrist_vels = controller.PDController(lift_check, obs, env.action_space, velocities)
# COMBINED CONTROLLER: Interpolate Naive and Position-Dependent controller output based on object x-coord position within hand
else:
# If object x position is on outer edges, do expert pid
if object_x_coord < -0.04 or object_x_coord > 0.04:
# Expert Nudge controller strategy
action, f1_vels, f2_vels, f3_vels, wrist_vels = controller.PDController(lift_check, obs, env.action_space, velocities)
# Object x position within the side-middle ranges, interpolate expert/naive velocity output
elif -0.04 <= object_x_coord <= -0.02 or 0.02 <= object_x_coord <= 0.04:
# Interpolate between naive and expert velocities
# position-dependent controller action (finger velocity based on object location within hand)
expert_action, f1_vels, f2_vels, f3_vels, wrist_vels = controller.PDController(lift_check, obs, env.action_space, velocities)
# Naive controller action (fingers move at constant velocity)
naive_action = NaiveController(lift_check, velocities)
# Only start to lift if we've had some RL time steps (multiple actions) to adjust hand
# Naive controller lift check determines whether we lift or not
if naive_action[0] == 0 and lift_check is True:
wrist_vel = 0
else:
wrist_vel = velocities["wrist_lift_velocity"] #naive_action[0] + expert_action[0] / 2
# Interpolate finger velocity values between position-dependent and Naive action output
finger_vels = np.interp(np.arange(1, 4), naive_action[1:3], expert_action[1:3])
action = np.array([wrist_vel, finger_vels[0], finger_vels[1], finger_vels[2]])
# Object x position is within center area, so use naive controller
else:
# Naive controller action (fingers move at constant velocity)
action = NaiveController(lift_check, velocities)
# From the controllers we get the iniividual finger velocities, then lift with the same wrist velocity
if lift_check is True:
action[0] = velocities["wrist_lift_velocity"]
else:
action[0] = 0
#print("**** action: ",action)
return action
def set_action_str(action, num_good_grasps, obj_local_pos, obs, reward, naive_ret, info):
""" Set string to show over simulation rendering for further context into finger/object movements, rewards,
and whether the controller has signaled it is ready to lift.
"""
velocity_str = "Wrist: " + str(action[0]) + "\nFinger1: " + str(action[1]) + "\nFinger2: " + str(
action[2]) + "\nFinger3: " + str(action[3])
lift_status_str = "\nnum_good_grasps: " + str(num_good_grasps) + "\nf_all_change: " + str(naive_ret)
obj_str = "\nObject Local x,y: (" + str(obj_local_pos[0]) + ", " + str(obj_local_pos[1]) + ") " + "\nobject center height: " + str(obs[23])
reward_str = "\ntimestep reward: " + str(reward) + "\nfinger reward: " + str(info["finger_reward"]) + \
"\ngrasp reward: " + str(info["grasp_reward"]) + "\nlift reward: " + str(info["lift_reward"])
action_str = velocity_str + lift_status_str + obj_str + reward_str
return action_str
def GenerateExpertPID_JointVel(episode_num, requested_shapes, requested_orientation, with_grasp, replay_buffer=None, save=True, render_imgs=False, pid_mode="combined"):
""" Generate expert data based on Expert PID and Naive PID controller action output.
episode_num: Number of episodes to generate expert data for
replay_buffer: Replay buffer to be passed in (set to None for testing purposes)
save: set to True if replay buffer data is to be saved
"""
env = gym.make('gym_kinova_gripper:kinovagripper-v0')
env.env.pid = True
# Use to test plotting the episode trajectory
plot_ep_trajectory = None
success_coords = {"x": [], "y": [], "orientation": []}
fail_coords = {"x": [], "y": [], "orientation": []}
# hand orientation types: NORMAL, Rotated (45 deg), Top (90 deg)
all_timesteps = np.array([]) # Keeps track of all timesteps to determine average timesteps needed
success_timesteps = np.array([]) # Successful episode timesteps count distribution
fail_timesteps = np.array([]) # Failed episode timesteps count distribution
datestr = datetime.datetime.now().strftime("%m_%d_%y_%H%M") # used for file name saving
print("----Generating {} expert episodes----".format(episode_num))
print("Using PID MODE: ", pid_mode)
# Beginning of episode loop
for i in range(episode_num):
print("PID ", i)
# Fill training object list using latin square
if env.check_obj_file_empty("objects.csv") or episode_num is 0:
env.Generate_Latin_Square(episode_num, "objects.csv", shape_keys=requested_shapes)
obs, done = env.reset(shape_keys=requested_shapes,hand_orientation=requested_orientation), False
# Record initial coordinate file path once shapes are generated
coord_filepath = env.get_coords_filename()
prev_obs = None # State observation of the previous state
num_good_grasps = 0 # Counts the number of good grasps (Number of times check_grasp() has returned True)
num_consistent_grasps = 1 # Number of RL steps needed
total_steps = 0 # Total RL timesteps passed within episode
action_str = "Initial time step" # Set the initial render output string
env._max_episode_steps = 30 # Sets number of timesteps per episode (counted from each step() call)
obj_coords = env.get_obj_coords()
# Local coordinate conversion
obj_local = np.append(obj_coords,1)
obj_local = np.matmul(env.Tfw,obj_local)
obj_local_pos = obj_local[0:3]
controller = ExpertPIDController(obs) # Initiate expert PID controller
# Record episode starting index if replay buffer is passed in
if replay_buffer is not None:
replay_buffer.add_episode(1)
# Add orientation noise to be recorded by replay buffer
orientation_idx = env.get_orientation_idx()
replay_buffer.add_orientation_idx_to_replay(orientation_idx)
# Beginning of RL time steps within the current episode
while not done:
# Distal finger x,y,z positions f1_dist, f2_dist, f3_dist
if prev_obs is None: # None if on the first RL episode time step
f_dist_old = None
else:
f_dist_old = prev_obs[9:17] # Track the changes in distal finger tip positions
f_dist_new = obs[9:17]
### READY FOR LIFTING CHECK ###
min_lift_timesteps = 10 # Number of time steps that must occur before attempting to lift object
lift_check = False # Check whether we have had enough good grasps and meet lifting requirements
# Check if ready to lift based on distal finger tip change in movement
naive_ret = check_grasp(f_dist_old, f_dist_new)
grasp_check = bool(naive_ret[0]) # (1) True if within distal finger movement is <= threshold (ready for lifting)
if grasp_check is True:
num_good_grasps += 1 # Increment the number of consecutive good grasps
# Check if we have been in a good grasp position for num_consistent_grasps time steps
if total_steps > min_lift_timesteps and num_good_grasps >= num_consistent_grasps:
lift_check = True
### END OF READY FOR LIFTING CHECK ###
# Get action based on the selected controller (Naive, position-dependent, combined Interpolation
action = get_action(obs, lift_check, controller, env, pid_mode)
# Take action (Reinforcement Learning step)
env.set_with_grasp_reward(with_grasp)
next_obs, reward, done, info = env.step(action)
# NAIVE RET SHOULD BE SET BASED ON MOST UP TO DATE F_DIST_OLD and F_DIST_NEW
# Check whether we are ready to lift for action string
#[naive_ret, _] = check_grasp(f_dist_old, f_dist_new)
# Set the info to be displayed in episode rendering based on current hand/object status
action_str = set_action_str(action, num_good_grasps, obj_local_pos, obs, reward, naive_ret, info)
# Render image from current episode
if render_imgs is True:
if total_steps % 1 == 0:
env.render_img(dir_name=pid_mode + "_" + datestr, text_overlay=action_str, episode_num=i,
timestep_num=total_steps,
obj_coords=str(obj_local_pos[0]) + "_" + str(obj_local_pos[1]))
else:
env._viewer = None
# Add experience to replay buffer
if replay_buffer is not None and not lift_check:
replay_buffer.add(obs[0:82], action, next_obs[0:82], reward, float(done))
if lift_check and done:
replay_buffer.replace(reward, done)
# print ("#######REWARD#######", reward)
# Once current timestep is over, update prev_obs | |
return
t = (cartype,
carclass,
railroad,
home_station,
car)
sql = 'update car set cartype = ?, carclass = ?, railroad = ?, home_station = ? where car = ?'
if self.db_update(sql, t) != 0:
return
#report the change to the screen
print('CAR DETAILS CHANGED SUCCESSFULLY')
print('RUNNING #: ' + car + 'TYPE: ' + cartype + cartype_name + 'CLASS: ' + carclass)
print(railroad + railroad_name + ' HOME STATION: ' + home_station + home_station_name)
print('AT: ' + station + station_name)
return errors
def maintc(self, message):
"""change maintenance status for cars. the time to maintenance and works time
can be amended up to the values held on the reference file. only one or the other
values can be set as both cannot have a value at the same time (ie a car is either
in traffic and counting down to maintenance, or is in maintenance and counting
down to going into traffic)
"""
if self.show_access(message, 'MAINTC car;(time to maint);(works time)', 'S') != 0:
return
errors = 0
maint_interval = 0
works_time = 0
#car code-----------------------------------------------------------------------------------
car, rc = self.extract_field(message, 0, 'CAR RUNNING NUMBER')
if rc > 0:
return
#read the database and populate the fields
t = (car,)
sql = 'select time_to_maint, time_in_maint from car where car.car = ? '
count, ds_cars = self.db_read(sql, t)
if count < 0:
return
if count == 0:
print('* CAR RUNNING NUMBER DOES NOT EXIST')
return
else:
for row in ds_cars:
time_to_maint = row[0]
time_in_maint = row[1]
t = ('CARWORKS',)
sql = 'select value from parameter where name = ?'
count, ds_param = self.db_read(sql, t)
if count < 0:
return
if count == 0:
print('* DEFAULT WORKS TIME FOR CARS DOES NOT EXIST: SET-UP REQUIRED')
return
else:
for row in ds_param:
works_time = row[0]
t = ('CARMAINT',)
sql = 'select value from parameter where name = ?'
count, ds_param = self.db_read(sql, t)
if count < 0:
return
if count == 0:
print('* DEFAULT MAINTENANCE INTERVAL FOR CARS DOES NOT EXIST: SET-UP REQUIRED')
return
else:
for row in ds_param:
maint_interval = row[0]
#time to maint------------------------------------------------------------------------------
value, rc = self.extract_field(message, 1, '')
if rc == 0:
time_to_maint = value
else:
time_to_maint = 0
try:
if int(time_to_maint) > 99999 or int(time_to_maint) < 0:
errors = errors + 1
print('* TIME TO MAINTENANCE MUST BE IN THE RANGE 0 to 99999')
except:
errors = errors + 1
print('* TIME TO MAINTENANCE MUST BE A WHOLE NUMBER')
return
if int(time_to_maint) > int(maint_interval):
errors = errors + 1
print('* MAINTENANCE INTERVAL OF CAR IS ' + str(maint_interval))
#TimeInMaint--------------------------------------------------------------------------------
value, rc = self.extract_field(message, 2, '')
if rc == 0:
time_in_maint = value
else:
time_in_maint = 0
if int(time_to_maint) != 0 and int(time_in_maint) != 0:
print('* EITHER TIME TO MAINTENANCE OR WORKS TIME MUST BE ZERO')
return
try:
if int(time_in_maint) > 99999 or int(time_in_maint) < 0:
errors = errors + 1
print('* TIME IN MAINTENANCE MUST BE IN THE RANGE 0 to 99999')
except:
errors = errors + 1
print('* TIME IN MAINTENANCE MUST BE A WHOLE NUMBER')
if int(time_in_maint) > int(works_time):
errors = errors + 1
print('* MAINTENANCE OUTAGE OF CAR is ' + works_time)
#build and store the new record-------------------------------------------------------------
if errors != 0:
return
t = (time_to_maint, time_in_maint, car)
sql = 'update car set time_to_maint = ?, time_in_maint = ? where car = ?'
if self.db_update(sql, t) != 0:
return
print('CAR MAINTENANCE DETAILS CHANGED SUCCESSFULLY')
print(car + ' TO MAINT: ' + str(time_to_maint) + ' IN MAINT: ' + str(time_in_maint))
return
def carxat(self, message):
"""relocate a car at a new station. this is used for correcting cars that
are not at the correct location. cars in maintenance cannot be moved
"""
if self.show_access(message, 'CARXAT car;^station^', 'N') != 0:
return
#car code-----------------------------------------------------------------------------------
car, rc = self.extract_field(message, 0, 'CAR RUNNING NUMBER')
if rc > 0:
return
t = (car,)
sql = 'select station, time_in_maint, is_attached_set, block from car where car.car = ? '
count, ds_cars = self.db_read(sql, t)
if count < 0:
return
if count == 0:
print('* CAR RUNNING NUMBER DOES NOT EXIST')
return
else:
for row in ds_cars:
time_in_maint = row[1]
attached_set = row[2]
block = row[3]
if attached_set != '':
print('* CAR IS ATTACHED TO A SET, CANNOT BE MOVED')
return
#HomeStation--------------------------------------------------------------------------------
station, rc = self.extract_field(message, 1, 'STATION CODE')
if rc > 0:
return
if time_in_maint > 0:
print('* CAR IN MAINTENANCE, CANNOT BE MOVED')
return
stax = (station,)
sql = 'select long_name from station where station = ?'
count, ds_stations = self.db_read(sql, stax)
if count < 0:
return
if count == 0:
print('* STATION CODE DOES NOT EXIST')
return
else:
for row in ds_stations:
stax_name = row[0]
#build and store the new record-------------------------------------------------------------
t = (station, '0', '', car)
sql = 'update car set station = ?, place_id = ?, train = ? where car = ?'
if self.db_update(sql, t) != 0:
return
#if the car was attached to a block, move the rest of the block as well
if block != '':
t = (station, 0, '', block)
sql = 'update car set station = ?, place_id = ?, train = ? where block = ?'
if self.db_update(sql, t) != 0:
return
#report the change to the screen
print('LOCATION OF CAR AT STATION CHANGED SUCCESSFULLY')
print(car + ' AT: ' + station + + ' ' + stax_name)
if block != '':
data = (block,) #Rev 1
sql = 'select car from car where block = ?'
count, dummy = self.db_read(sql, data)
if count < 0:
return
print(count-1 + 'ADDITIONAL CARS MOVED AS PART OF BLOCK') #Rev 1
return
def carxsp(self, message):
"""spot a car at a new location. if the car is spotted at a maintenance location then the
car will go into maintenance. if the car is at an industry then it will be loaded (in
turn, as only one car will load at a time)
"""
if self.show_access(message, 'CARXSP car;^place^', 'N') != 0:
return
#car code-----------------------------------------------------------------------------------
car, rc = self.extract_field(message, 0, 'CAR RUNNING NUMBER')
if rc > 0:
return
t = (car,)
sql = 'select station, time_to_maint, time_in_maint, ' +\
'clean_dirty, is_attached_set, block from car where car.car = ? '
count, ds_cars = self.db_read(sql, t)
if count < 0:
return
if count == 0:
print('* CAR RUNNING NUMBER DOES NOT EXIST')
return
else:
for row in ds_cars:
station = row[0]
time_to_maint = row[1]
time_in_maint = row[2]
car_cleaned = row[3]
attached_set = row[4]
block = row[5]
if attached_set != '':
print('* CAR IS ATTACHED TO A SET, CANNOT BE MOVED')
return
#Place---------------------------------------------------------------------------------------
place, rc = self.extract_field(message, 1, 'PLACE')
if rc > 0:
return
t = (station, place)
sql = 'select place.id, place.name, place.place_type, ' +\
'station.long_name from place, station ' +\
'where place.station = ? and place.code = ? and station.station = place.station'
count, ds_places = self.db_read(sql, t)
if count < 0:
return
if count == 0:
print('* STATION/PLACE DOES NOT EXIST')
return
else:
for row in ds_places:
current_place_id = row[0]
current_place_name = row[1]
place_type = row[2]
stax_name = row[3]
#if it is at a maintenance location, put it into maintenance--------------------------------
if place_type == 'M':
t = ('CARWORKS',)
sql = 'select value from parameter where name = ?'
count, ds_params = self.db_read(sql, t)
if count < 0:
return
for row in ds_params:
time_in_maint = int(row[0])
time_to_maint = 0
#if it is at a car cleaning location, clean the car-----------------------------------------
if place_type == 'C':
car_cleaned = 'C'
#build and store the new record-------------------------------------------------------------
t = (current_place_id, time_in_maint, time_to_maint, car_cleaned, car)
sql = 'update car set place_id = ?, time_in_maint = ?, time_to_maint = ?, ' +\
'clean_dirty = ? where car = ?'
if self.db_update(sql, t) != 0:
return
#if the car was attached to a block, move the rest of the block as | |
import os
import collections
import numpy as np
from ipywidgets import widgets
from IPython.core.display import display, HTML
import logging
from NeuNorm.normalization import Normalization
from __code import file_handler
from __code.ipywe import myfileselector
from __code.normalization.get import Get
from __code.normalization.metadata_handler import MetadataHandler, MetadataName, METADATA_KEYS
from __code.normalization import utilities
JSON_DEBUGGING = False
MAX_DF_COUNTS_ALLOWED = 900
METADATA_ERROR_ALLOWED = 1
LIST_METADATA_NOT_INSTRUMENT_RELATED = ['filename', 'time_stamp', 'time_stamp_user_format']
class NormalizationWithSimplifySelection:
working_dir = ''
def __init__(self, working_dir=''):
self.working_dir = working_dir
self.list_of_images = []
self.input_data_folder = []
# {0: {65027: 55.0,
# 65028: 59.2,
# 65029: 1.0,
# 'filename': 'full_filename',
# 'time_stamp': 1454544.34545,
# 'time_stamp_user_format': '2019-11-19 02:48:47'},
# ...,
# }
self.sample_metadata_dict = {}
self.ob_metadata_dict = {}
self.df_metadata_dict = {}
# key of dictionary being the acquisition time
# {50: {'config0': {'list_sample': [self.sample_metadata_dict[0],
# self.sample_metadata_dict[1],..],
# 'list_ob': [self.ob_metadata_dict[0],
# self.ob_metadata_dict[1],
# ...],
# 'list_df': [file1, file2, file3],
# 'metadata_infos': {},
# 'first_images': {'sample': {},
# 'ob': {},
# 'df': {}},
# 'last_images': {'sample': {},
# 'ob': {},
# 'df': {}},
# 'time_range_s_selected': {'before': np.NaN,
# 'after': np.NaN},
# 'time_range_s': {'before': np.NaN,
# 'after': np.NaN},
# },
# 'config1': {...},
# },
# 30: {...},
# }
self.final_full_master_dict = {}
# same as the final_full_master_dict but in this one, the OB outside the time range
# defined as excluded
self.final_with_time_range_master_dict = {}
o_get = Get(parent=self)
log_file_name = o_get.log_file_name()
logging.basicConfig(filename=log_file_name,
filemode='w',
format='[%(levelname)s] - %(asctime)s - %(message)s',
level=logging.INFO) # logging.INFO, logging.DEBUG
logging.info("*** Starting new session ***")
def select_sample_folder(self):
folder_sample_widget = myfileselector.MyFileSelectorPanel(instruction='select folder of images to normalize',
start_dir=self.working_dir,
next=self.retrieve_sample_metadata_from_sample_folder,
type='directory',
multiple=False)
folder_sample_widget.show()
def retrieve_sample_metadata_from_sample_folder(self, sample_folder):
logging.info(f"select sample folder: {sample_folder}")
[list_of_images, _] = file_handler.retrieve_list_of_most_dominant_extension_from_folder(folder=sample_folder)
can_we_continue = self.images_files_found_in_list(list_of_images)
if can_we_continue:
logging.info(f"-> number of images found: {len(list_of_images)}")
self.retrieve_sample_metadata(list_of_images)
else:
logging.info(f"-> No images found!")
display(HTML('<span style="font-size: 20px; color:Red">No images found in the folder selected!</span>'))
def images_files_found_in_list(self, list_of_images):
for _file in list_of_images:
if (".tiff" in _file) or (".tif" in _file) or (".fits" in _file):
return True
return False
def retrieve_sample_metadata(self, list_of_images):
__name__ = "retrieve_sample_metadata"
logging.info(f"Retrieving sample metadata ({__name__})")
self.list_of_images = list_of_images
self.sample_metadata_dict = MetadataHandler.retrieve_metadata(list_of_files=list_of_images,
display_infos=False,
label='sample')
# logging.info(f"self.sample_metadata_dict: {self.sample_metadata_dict}")
self.auto_retrieve_ob_metadata()
self.auto_retrieve_df_metadata()
self.match_files()
self.calculate_first_and_last_ob()
self.calculate_time_range()
self.display_time_range_selection_widgets()
def select_ob_folder(self):
self.select_folder(message='open beam',
next_function=self.retrieve_ob_metadata())
def retrieve_ob_metadata(self, selected_folder):
list_of_ob_files = Get.list_of_tiff_files(folder=selected_folder)
self.ob_metadata_dict = MetadataHandler.retrieve_metadata(list_of_files=list_of_ob_files)
def auto_retrieve_ob_metadata(self):
logging.info(f"> auto_retrieve_ob_metadata")
folder = os.path.join(self.working_dir, 'raw', 'ob')
logging.info(f"-> folder: {folder}")
list_of_ob_files = file_handler.get_list_of_all_files_in_subfolders(folder=folder,
extensions=['tiff', 'tif'])
logging.info(f"-> nbr of ob files found: {len(list_of_ob_files)}")
self.ob_metadata_dict = MetadataHandler.retrieve_metadata(list_of_files=list_of_ob_files,
label='ob')
# logging.info(f"ob metadata dict")
# logging.info(f"-> {self.ob_metadata_dict}")
def select_folder(self, message="", next_function=None):
folder_widget = myfileselector.MyFileSelectorPanel(instruction='select {} folder'.format(message),
start_dir=self.working_dir,
next=next_function,
type='directory',
multiple=False)
folder_widget.show()
def select_df_folder(self):
self.select_folder(message='dark field',
next_function=self.retrieve_df_metadata())
def retrieve_df_metadata(self, selected_folder):
list_of_df_files = Get.list_of_tiff_files(folder=selected_folder)
self.df_metadata_dict = MetadataHandler.retrieve_metadata(list_of_files=list_of_df_files)
def auto_retrieve_df_metadata(self):
folder = os.path.join(self.working_dir, 'raw', 'df')
list_of_df_files = file_handler.get_list_of_all_files_in_subfolders(folder=folder,
extensions=['tiff', 'tif'])
logging.info(f"-> nbr of df files found: {len(list_of_df_files)}")
self.df_metadata_dict = MetadataHandler.retrieve_metadata(list_of_files=list_of_df_files,
label='df')
def match_files(self):
"""This is where the files will be associated with their respective OB, DF by using the metadata"""
if not JSON_DEBUGGING:
self.create_master_sample_dict()
self.match_ob()
self.match_df()
if JSON_DEBUGGING:
# for debugging only, exporting the json
import json
with open('/Users/j35/Desktop/which_ob_and_df_to_use.json', 'w') as outfile:
json.dump(self.final_full_master_dict, outfile)
def match_ob(self):
"""we will go through all the ob and associate them with the right sample based on
- acquisition time
- detector type
- aperture
"""
list_ob_dict = self.ob_metadata_dict
final_full_master_dict = self.final_full_master_dict
list_of_sample_acquisition = final_full_master_dict.keys()
for _index_ob in list_ob_dict.keys():
_all_ob_instrument_metadata = Get.get_instrument_metadata_only(list_ob_dict[_index_ob])
_ob_instrument_metadata = utilities.isolate_instrument_metadata(
_all_ob_instrument_metadata)
_acquisition_time = _all_ob_instrument_metadata[MetadataName.EXPOSURE_TIME.value]['value']
if _acquisition_time in list_of_sample_acquisition:
for _config_id in final_full_master_dict[_acquisition_time].keys():
_sample_metadata_infos = final_full_master_dict[_acquisition_time][_config_id]['metadata_infos']
if utilities.all_metadata_match(_sample_metadata_infos, _ob_instrument_metadata):
final_full_master_dict[_acquisition_time][_config_id]['list_ob'].append(list_ob_dict[_index_ob])
self.final_full_master_dict = final_full_master_dict
def match_df(self):
"""
we will go through all the df of the IPTS and will associate the df with the right samples
based on:
- detector type used
- acquisition time
"""
list_df_dict = self.df_metadata_dict
final_full_master_dict = self.final_full_master_dict
list_of_sample_acquisition = final_full_master_dict.keys()
for _index_df in list_df_dict.keys():
_all_df_instrument_metadata = Get.get_instrument_metadata_only(list_df_dict[_index_df])
_df_instrument_metadata = utilities.isolate_instrument_metadata(
_all_df_instrument_metadata)
_acquisition_time = _all_df_instrument_metadata[MetadataName.EXPOSURE_TIME.value]['value']
if _acquisition_time in list_of_sample_acquisition:
for _config_id in final_full_master_dict[_acquisition_time].keys():
_sample_metadata_infos = final_full_master_dict[_acquisition_time][_config_id]['metadata_infos']
if utilities.all_metadata_match(_sample_metadata_infos, _df_instrument_metadata,
list_key_to_check=[METADATA_KEYS['df'][
1].value]):
final_full_master_dict[_acquisition_time][_config_id]['list_df'].append(list_df_dict[_index_df])
self.final_full_master_dict = final_full_master_dict
def create_master_sample_dict(self):
final_full_master_dict = collections.OrderedDict()
sample_metadata_dict = self.sample_metadata_dict
# we need to keep record of which image was the first one taken and which image was the last one taken
first_sample_image = sample_metadata_dict[0]
last_sample_image = sample_metadata_dict[0]
for _file_index in sample_metadata_dict.keys():
_dict_file_index = sample_metadata_dict[_file_index]
_sample_file = _dict_file_index['filename']
_acquisition_time = _dict_file_index[MetadataName.EXPOSURE_TIME.value]['value']
_instrument_metadata = utilities.isolate_instrument_metadata(_dict_file_index)
_sample_time_stamp = _dict_file_index['time_stamp']
# find which image was first and which image was last
if _sample_time_stamp < first_sample_image['time_stamp']:
first_sample_image = _dict_file_index
elif _sample_time_stamp > last_sample_image['time_stamp']:
last_sample_image = _dict_file_index
# first entry or first time seeing that acquisition time
if (len(final_full_master_dict) == 0) or not (_acquisition_time in final_full_master_dict.keys()):
_first_images_dict = {'sample': first_sample_image,
'ob' : {},
'df' : {}}
_last_images_dict = {'sample': last_sample_image,
'ob' : {},
'df' : {}}
_temp_dict = {'list_sample' : [_dict_file_index],
'first_images' : _first_images_dict,
'last_images' : _last_images_dict,
'list_ob' : [],
'list_df' : [],
'time_range_s_selected': {'before': np.NaN,
'after' : np.NaN},
'time_range_s' : {'before': np.NaN,
'after' : np.NaN},
'metadata_infos' : Get.get_instrument_metadata_only(
_instrument_metadata)}
final_full_master_dict[_acquisition_time] = {}
final_full_master_dict[_acquisition_time]['config0'] = _temp_dict
else:
# check that all the metadata_infos match for the first group of that acquisition time,
# otherwise check the next one or create a group
if _acquisition_time in final_full_master_dict.keys():
_dict_for_this_acquisition_time = final_full_master_dict[_acquisition_time]
_found_a_match = False
for _config_key in _dict_for_this_acquisition_time.keys():
_config = _dict_for_this_acquisition_time[_config_key]
if (utilities.all_metadata_match(metadata_1=_config['metadata_infos'],
metadata_2=_instrument_metadata)):
_config['list_sample'].append(_dict_file_index)
_first_images_dict = {'sample': first_sample_image,
'ob' : {},
'df' : {}}
_last_images_dict = {'sample': last_sample_image,
'ob' : {},
'df' : {}}
_config['first_images'] = _first_images_dict
_config['last_images'] = _last_images_dict
_found_a_match = True
if not _found_a_match:
_first_images_dict = {'sample': first_sample_image,
'ob' : {},
'df' : {}}
_last_images_dict = {'sample': last_sample_image,
'ob' : {},
'df' : {}}
_temp_dict = {'list_sample' : [_dict_file_index],
'first_images' : _first_images_dict,
'last_images' : _last_images_dict,
'list_ob' : [],
'list_df' : [],
'time_range_s_selected': {'before': np.NaN,
'after' : np.NaN},
'time_range_s' : {'before': np.NaN,
'after' : np.NaN},
'metadata_infos' : Get.get_instrument_metadata_only(
_instrument_metadata)}
nbr_config = len(_dict_for_this_acquisition_time.keys())
_dict_for_this_acquisition_time['config{}'.format(nbr_config)] = _temp_dict
else:
_first_images_dict = {'sample': first_sample_image,
'ob' : {},
'df' : {}}
_last_images_dict = {'sample': last_sample_image,
'ob' : {},
'df' : {}}
_temp_dict = {'list_sample' : [_dict_file_index],
'first_images' : _first_images_dict,
'last_images' : _last_images_dict,
'list_ob' : [],
'list_df' : [],
'time_range_s_selected': {'before': np.NAN,
'after' : np.NaN},
'time_range_s' : {'before': np.NaN,
'after' : np.NaN},
'metadata_infos' : Get.get_instrument_metadata_only(
_instrument_metadata)}
final_full_master_dict[_acquisition_time] = {}
final_full_master_dict[_acquisition_time]['config0'] = _temp_dict
self.final_full_master_dict = final_full_master_dict
def calculate_first_and_last_ob(self):
"""this will loop through all the acquisition time keys, and config keys, to figure out
what is the first ob and last ob in this dictionary"""
_final_full_master_dict = self.final_full_master_dict
for _acquisition in _final_full_master_dict.keys():
current_acquisition_dict = _final_full_master_dict[_acquisition]
_first_ob_time = np.NaN
_first_ob = {}
_last_ob_time = np.NaN
_last_ob = {}
for _config in current_acquisition_dict.keys():
current_acquisition_config_dict = current_acquisition_dict[_config]
for _ob in current_acquisition_config_dict['list_ob']:
_current_ob_time = _ob['time_stamp']
if np.isnan(_first_ob_time):
_first_ob_time = _current_ob_time
_last_ob_time = _current_ob_time
_first_ob = _last_ob = _ob
elif _current_ob_time < _first_ob_time:
_first_ob_time = _current_ob_time
_first_ob = _ob
elif _current_ob_time > _last_ob_time:
_last_ob_time = _current_ob_time
_last_ob = _ob
current_acquisition_config_dict['first_images']['ob'] = _first_ob
current_acquisition_config_dict['last_images']['ob'] = _last_ob
def calculate_time_range(self):
"""this method will calculate the max time range of OB taken before or after and will use that
for the slider selection time range
Provide option to use all (that means, do not used any time range)
"""
_final_full_master_dict = self.final_full_master_dict
for _acquisition in _final_full_master_dict.keys():
current_acquisition_dict = _final_full_master_dict[_acquisition]
for _config in current_acquisition_dict.keys():
current_acquisition_config_dict = current_acquisition_dict[_config]
first_sample_image = current_acquisition_config_dict['first_images']['sample']
first_ob_image = current_acquisition_config_dict['first_images']['ob']
delta_time_before = first_sample_image.get('time_stamp', 0) - first_ob_image.get('time_stamp', 0)
_time_range_s_before = delta_time_before if delta_time_before > 0 else 0
last_sample_image = current_acquisition_config_dict['last_images']['sample']
last_ob_image = current_acquisition_config_dict['last_images']['ob']
delta_time_after = last_ob_image.get('time_stamp', 0) - last_sample_image.get('time_stamp', 0)
_time_range_s_after = delta_time_after if delta_time_after > 0 else 0
_final_full_master_dict[_acquisition][_config]['time_range_s']['before'] = _time_range_s_before
_final_full_master_dict[_acquisition][_config]['time_range_s']['after'] = _time_range_s_after
def display_time_range_selection_widgets(self):
_final_full_master_dict = self.final_full_master_dict
_config_tab_dict = {} # will keep record of each config tab for each acquisition
_acquisition_tabs = widgets.Tab()
o_get = Get(parent=self)
for _acquisition_index, _acquisition in enumerate(_final_full_master_dict.keys()):
_dict_of_this_acquisition = _final_full_master_dict[_acquisition]
_config_tab = widgets.Tab()
_current_acquisition_tab_widgets_id = {'config_tab_id': _config_tab}
for _index, _config in enumerate(_dict_of_this_acquisition.keys()):
_dict_config = _dict_of_this_acquisition[_config]
_dict = o_get.full_layout_for_this_config(_dict_config)
_layout = _dict['verti_layout']
_config_widgets_id_dict = _dict['config_widgets_id_dict']
_config_tab.children += (_layout,)
_config_tab.set_title(_index, _config)
_current_acquisition_tab_widgets_id[_index] = _config_widgets_id_dict
_config_tab_dict[_acquisition_index] = _current_acquisition_tab_widgets_id
_acquisition_tabs.children += (_config_tab,) # add all the config tab to top acquisition tab
_acquisition_tabs.set_title(_acquisition_index, "Acquisition: {}s".format(_acquisition))
_config_tab
display(_acquisition_tabs)
self.acquisition_tab = _acquisition_tabs
self.config_tab_dict = _config_tab_dict
def calculate_max_time_before_and_after_exp_for_this_config(self, dict_config):
max_time_before = 0
first_sample_image_time_stamp = dict_config['first_images']['sample']['time_stamp']
first_ob_image_time_stamp = | |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListEventItems:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'id': 'str',
'time': 'int',
'policyid': 'str',
'sip': 'str',
'host': 'str',
'url': 'str',
'attack': 'str',
'rule': 'str',
'payload': 'str',
'action': 'str',
'request_line': 'str',
'headers': 'ListEventItemsHeaders',
'cookie': 'str',
'status': 'str',
'region': 'str',
'host_id': 'str',
'response_time': 'int',
'response_size': 'int',
'response_body': 'str'
}
attribute_map = {
'id': 'id',
'time': 'time',
'policyid': 'policyid',
'sip': 'sip',
'host': 'host',
'url': 'url',
'attack': 'attack',
'rule': 'rule',
'payload': 'payload',
'action': 'action',
'request_line': 'request_line',
'headers': 'headers',
'cookie': 'cookie',
'status': 'status',
'region': 'region',
'host_id': 'host_id',
'response_time': 'response_time',
'response_size': 'response_size',
'response_body': 'response_body'
}
def __init__(self, id=None, time=None, policyid=None, sip=None, host=None, url=None, attack=None, rule=None, payload=None, action=None, request_line=None, headers=None, cookie=None, status=None, region=None, host_id=None, response_time=None, response_size=None, response_body=None):
"""ListEventItems - a model defined in huaweicloud sdk"""
self._id = None
self._time = None
self._policyid = None
self._sip = None
self._host = None
self._url = None
self._attack = None
self._rule = None
self._payload = None
self._action = None
self._request_line = None
self._headers = None
self._cookie = None
self._status = None
self._region = None
self._host_id = None
self._response_time = None
self._response_size = None
self._response_body = None
self.discriminator = None
if id is not None:
self.id = id
if time is not None:
self.time = time
if policyid is not None:
self.policyid = policyid
if sip is not None:
self.sip = sip
if host is not None:
self.host = host
if url is not None:
self.url = url
if attack is not None:
self.attack = attack
if rule is not None:
self.rule = rule
if payload is not None:
self.payload = payload
if action is not None:
self.action = action
if request_line is not None:
self.request_line = request_line
if headers is not None:
self.headers = headers
if cookie is not None:
self.cookie = cookie
if status is not None:
self.status = status
if region is not None:
self.region = region
if host_id is not None:
self.host_id = host_id
if response_time is not None:
self.response_time = response_time
if response_size is not None:
self.response_size = response_size
if response_body is not None:
self.response_body = response_body
@property
def id(self):
"""Gets the id of this ListEventItems.
事件id
:return: The id of this ListEventItems.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this ListEventItems.
事件id
:param id: The id of this ListEventItems.
:type: str
"""
self._id = id
@property
def time(self):
"""Gets the time of this ListEventItems.
次数
:return: The time of this ListEventItems.
:rtype: int
"""
return self._time
@time.setter
def time(self, time):
"""Sets the time of this ListEventItems.
次数
:param time: The time of this ListEventItems.
:type: int
"""
self._time = time
@property
def policyid(self):
"""Gets the policyid of this ListEventItems.
策略id
:return: The policyid of this ListEventItems.
:rtype: str
"""
return self._policyid
@policyid.setter
def policyid(self, policyid):
"""Sets the policyid of this ListEventItems.
策略id
:param policyid: The policyid of this ListEventItems.
:type: str
"""
self._policyid = policyid
@property
def sip(self):
"""Gets the sip of this ListEventItems.
源ip
:return: The sip of this ListEventItems.
:rtype: str
"""
return self._sip
@sip.setter
def sip(self, sip):
"""Sets the sip of this ListEventItems.
源ip
:param sip: The sip of this ListEventItems.
:type: str
"""
self._sip = sip
@property
def host(self):
"""Gets the host of this ListEventItems.
域名
:return: The host of this ListEventItems.
:rtype: str
"""
return self._host
@host.setter
def host(self, host):
"""Sets the host of this ListEventItems.
域名
:param host: The host of this ListEventItems.
:type: str
"""
self._host = host
@property
def url(self):
"""Gets the url of this ListEventItems.
攻击的url链接
:return: The url of this ListEventItems.
:rtype: str
"""
return self._url
@url.setter
def url(self, url):
"""Sets the url of this ListEventItems.
攻击的url链接
:param url: The url of this ListEventItems.
:type: str
"""
self._url = url
@property
def attack(self):
"""Gets the attack of this ListEventItems.
攻击类型(XSS攻击:xss,sqli,命令注入:cmdi,恶意爬虫:robot,本地文件包含:lfi,远程文件包含:rfi,网站木马:webshell,cc攻击:cc,精准防护:custom_custom,IP黑白名单:custom_whiteblackip,地理位置访问控制:custom_geoip,防篡改:antitamper,反爬虫:anticrawler,网站信息防泄漏:leakage,非法请求:illegal,其它类型攻击:vuln)
:return: The attack of this ListEventItems.
:rtype: str
"""
return self._attack
@attack.setter
def attack(self, attack):
"""Sets the attack of this ListEventItems.
攻击类型(XSS攻击:xss,sqli,命令注入:cmdi,恶意爬虫:robot,本地文件包含:lfi,远程文件包含:rfi,网站木马:webshell,cc攻击:cc,精准防护:custom_custom,IP黑白名单:custom_whiteblackip,地理位置访问控制:custom_geoip,防篡改:antitamper,反爬虫:anticrawler,网站信息防泄漏:leakage,非法请求:illegal,其它类型攻击:vuln)
:param attack: The attack of this ListEventItems.
:type: str
"""
self._attack = attack
@property
def rule(self):
"""Gets the rule of this ListEventItems.
命中的规则id
:return: The rule of this ListEventItems.
:rtype: str
"""
return self._rule
@rule.setter
def rule(self, rule):
"""Sets the rule of this ListEventItems.
命中的规则id
:param rule: The rule of this ListEventItems.
:type: str
"""
self._rule = rule
@property
def payload(self):
"""Gets the payload of this ListEventItems.
命中的载荷
:return: The payload of this ListEventItems.
:rtype: str
"""
return self._payload
@payload.setter
def payload(self, payload):
"""Sets the payload of this ListEventItems.
命中的载荷
:param payload: The payload of this ListEventItems.
:type: str
"""
self._payload = payload
@property
def action(self):
"""Gets the action of this ListEventItems.
防护动作
:return: The action of this ListEventItems.
:rtype: str
"""
return self._action
@action.setter
def action(self, action):
"""Sets the action of this ListEventItems.
防护动作
:param action: The action of this ListEventItems.
:type: str
"""
self._action = action
@property
def request_line(self):
"""Gets the request_line of this ListEventItems.
请求方法和路径
:return: The request_line of this ListEventItems.
:rtype: str
"""
return self._request_line
@request_line.setter
def request_line(self, request_line):
"""Sets the request_line of this ListEventItems.
请求方法和路径
:param request_line: The request_line of this ListEventItems.
:type: str
"""
self._request_line = request_line
@property
def headers(self):
"""Gets the headers of this ListEventItems.
:return: The headers of this ListEventItems.
:rtype: ListEventItemsHeaders
"""
return self._headers
@headers.setter
def headers(self, headers):
"""Sets the headers of this ListEventItems.
:param headers: The headers of this ListEventItems.
:type: ListEventItemsHeaders
"""
self._headers = headers
@property
def cookie(self):
"""Gets the cookie of this ListEventItems.
请求cookie
:return: The cookie of this ListEventItems.
:rtype: str
"""
return self._cookie
@cookie.setter
def cookie(self, cookie):
"""Sets the cookie of this ListEventItems.
请求cookie
:param cookie: The cookie of this ListEventItems.
:type: str
"""
self._cookie = cookie
@property
def status(self):
"""Gets the status of this ListEventItems.
响应码状态
:return: The status of this ListEventItems.
:rtype: str
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this ListEventItems.
响应码状态
:param status: The status of this ListEventItems.
:type: str
"""
self._status = status
@property
def region(self):
"""Gets the region of this ListEventItems.
区域
:return: The region of this ListEventItems.
:rtype: str
"""
return self._region
@region.setter
def region(self, region):
"""Sets the region of this ListEventItems.
区域
:param region: The region of this ListEventItems.
:type: str
"""
self._region = region
@property
def host_id(self):
"""Gets the host_id of this ListEventItems.
域名id
:return: The host_id of this ListEventItems.
:rtype: str
"""
return self._host_id
@host_id.setter
def host_id(self, host_id):
"""Sets the host_id of this ListEventItems.
域名id
:param host_id: The host_id of this ListEventItems.
:type: str
"""
self._host_id = host_id
@property
def response_time(self):
"""Gets the response_time of this ListEventItems.
响应时长
:return: The response_time of this ListEventItems.
:rtype: int
"""
return self._response_time
@response_time.setter
def response_time(self, response_time):
"""Sets the response_time of this ListEventItems.
响应时长
:param response_time: The response_time of this ListEventItems.
:type: int
"""
self._response_time = response_time
@property
def response_size(self):
"""Gets the response_size of this ListEventItems.
响应体大小
:return: The response_size of this ListEventItems.
:rtype: int
"""
return self._response_size
@response_size.setter
def response_size(self, response_size):
"""Sets the response_size of this ListEventItems.
响应体大小
:param response_size: The response_size of this ListEventItems.
:type: int
"""
self._response_size = response_size
@property
def response_body(self):
"""Gets the response_body of this ListEventItems.
响应体
:return: The response_body of this ListEventItems.
:rtype: str
"""
return self._response_body
@response_body.setter
def response_body(self, response_body):
"""Sets the response_body of this ListEventItems.
响应体
:param response_body: The response_body of this ListEventItems.
:type: str
"""
self._response_body = response_body
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else | |
<reponame>rekhabiswal/sage<gh_stars>0
"""
Root system data for dual Cartan types
"""
#*****************************************************************************
# Copyright (C) 2008-2009 <NAME> <anne at math.ucdavis.edu>
# Copyright (C) 2008-2013 <NAME> <nthiery at users.sf.net>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import print_function
from __future__ import absolute_import
from sage.misc.misc import attrcall
from sage.misc.cachefunc import cached_method
from sage.misc.lazy_attribute import lazy_attribute
from sage.combinat.root_system import cartan_type
from sage.combinat.root_system.root_lattice_realizations import RootLatticeRealizations
from sage.combinat.root_system import ambient_space
class CartanType(cartan_type.CartanType_decorator, cartan_type.CartanType_crystallographic):
r"""
A class for dual Cartan types.
The dual of a (crystallographic) Cartan type is a Cartan type with
the same index set, but all arrows reversed in the Dynkin diagram
(otherwise said, the Cartan matrix is transposed). It shares a lot
of properties in common with its dual. In particular, the Weyl
group is isomorphic to that of the dual as a Coxeter group.
EXAMPLES:
For all finite Cartan types, and in particular the simply laced
ones, the dual Cartan type is given by another preexisting Cartan
type::
sage: CartanType(['A',4]).dual()
['A', 4]
sage: CartanType(['B',4]).dual()
['C', 4]
sage: CartanType(['C',4]).dual()
['B', 4]
sage: CartanType(['F',4]).dual()
['F', 4] relabelled by {1: 4, 2: 3, 3: 2, 4: 1}
So to exercise this class we consider some non simply laced affine
Cartan types and also create explicitely `F_4^*` as a dual cartan
type::
sage: from sage.combinat.root_system.type_dual import CartanType as CartanTypeDual
sage: F4d = CartanTypeDual(CartanType(['F',4])); F4d
['F', 4]^*
sage: G21d = CartanType(['G',2,1]).dual(); G21d
['G', 2, 1]^*
They share many properties with their original Cartan types::
sage: F4d.is_irreducible()
True
sage: F4d.is_crystallographic()
True
sage: F4d.is_simply_laced()
False
sage: F4d.is_finite()
True
sage: G21d.is_finite()
False
sage: F4d.is_affine()
False
sage: G21d.is_affine()
True
TESTS::
sage: TestSuite(F4d).run(skip=["_test_pickling"])
sage: TestSuite(G21d).run()
.. NOTE:: F4d is pickled by construction as F4.dual() hence the above failure.
"""
def __init__(self, type):
"""
INPUT:
- ``type`` -- a Cartan type
EXAMPLES::
sage: ct = CartanType(['F',4,1]).dual()
sage: TestSuite(ct).run()
TESTS::
sage: ct1 = CartanType(['B',3,1]).dual()
sage: ct2 = CartanType(['B',3,1]).dual()
sage: ct3 = CartanType(['D',4,1]).dual()
sage: ct1 == ct2
True
sage: ct1 == ct3
False
Test that the produced Cartan type is in the appropriate
abstract classes (see :trac:`13724`)::
sage: from sage.combinat.root_system import cartan_type
sage: ct = CartanType(['B',3,1]).dual()
sage: TestSuite(ct).run()
sage: isinstance(ct, cartan_type.CartanType_simple)
True
sage: isinstance(ct, cartan_type.CartanType_finite)
False
sage: isinstance(ct, cartan_type.CartanType_affine)
True
sage: isinstance(ct, cartan_type.CartanType_crystallographic)
True
sage: isinstance(ct, cartan_type.CartanType_simply_laced)
False
By default, the dual of a reducible and finite type is not
constructed as such::
sage: ct = CartanType([['B',4],['A',2]]).dual(); ct
C4xA2
In order to exercise the dual infrastructure we force the
construction as a dual::
sage: from sage.combinat.root_system import type_dual
sage: ct = type_dual.CartanType(CartanType([['B',4],['A',2]])); ct
B4xA2^*
sage: isinstance(ct, type_dual.CartanType)
True
sage: TestSuite(ct).run(skip=["_test_pickling"])
sage: isinstance(ct, cartan_type.CartanType_finite)
True
sage: isinstance(ct, cartan_type.CartanType_simple)
False
sage: isinstance(ct, cartan_type.CartanType_affine)
False
sage: isinstance(ct, cartan_type.CartanType_crystallographic)
True
sage: isinstance(ct, cartan_type.CartanType_simply_laced)
False
"""
if not type.is_crystallographic():
raise NotImplementedError("only implemented for crystallographic Cartan types")
cartan_type.CartanType_decorator.__init__(self, type)
# TODO: design an appropriate infrastructure to handle this
# automatically? Maybe using categories and axioms?
# See also type_relabel.CartanType.__init__
if type.is_finite():
self.__class__ = CartanType_finite
elif type.is_affine():
self.__class__ = CartanType_affine
abstract_classes = tuple(cls
for cls in self._stable_abstract_classes
if isinstance(type, cls))
if abstract_classes:
self._add_abstract_superclass(abstract_classes)
# For each class cls in _stable_abstract_classes, if ct is an
# instance of A then ct.relabel(...) is put in this class as well.
# The order is relevant to avoid MRO issues!
_stable_abstract_classes = [
cartan_type.CartanType_simple]
def _repr_(self, compact = False):
"""
EXAMPLES::
sage: CartanType(['F', 4, 1]).dual()
['F', 4, 1]^*
sage: CartanType(['F', 4, 1]).dual()._repr_(compact = True)
'F4~*'
"""
dual_str = self.options.dual_str
if self.is_affine() and self.options.notation == "Kac":
if self._type.type() == 'B':
if compact:
return 'A%s^2'%(self.classical().rank()*2-1)
return "['A', %s, 2]"%(self.classical().rank()*2-1)
elif self._type.type() == 'BC':
dual_str = '+'
elif self._type.type() == 'C':
if compact:
return 'D%s^2'%(self.rank())
return "['D', %s, 2]"%(self.rank())
elif self._type.type() == 'F':
if compact:
return 'E6^2'
return "['E', 6, 2]"
return self.dual()._repr_(compact)+(dual_str if compact else "^"+dual_str)
def _latex_(self):
r"""
EXAMPLES::
sage: latex(CartanType(['F', 4, 1]).dual())
F_4^{(1)\vee}
"""
return self._type._latex_()+"^"+self.options.dual_latex
def __reduce__(self):
"""
TESTS::
sage: CartanType(['F', 4, 1]).dual().__reduce__()
(*.dual(), (['F', 4, 1],))
"""
return (attrcall("dual"), (self._type,))
def _latex_dynkin_diagram(self, label=lambda i: i, node=None, node_dist=2):
r"""
EXAMPLES::
sage: print(CartanType(['F',4,1]).dual()._latex_dynkin_diagram())
\draw (0 cm,0) -- (2 cm,0);
{
\pgftransformxshift{2 cm}
\draw (0 cm,0) -- (2 cm,0);
\draw (2 cm, 0.1 cm) -- +(2 cm,0);
\draw (2 cm, -0.1 cm) -- +(2 cm,0);
\draw (4.0 cm,0) -- +(2 cm,0);
\draw[shift={(2.8, 0)}, rotate=180] (135 : 0.45cm) -- (0,0) -- (-135 : 0.45cm);
\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$1$};
\draw[fill=white] (2 cm, 0 cm) circle (.25cm) node[below=4pt]{$2$};
\draw[fill=white] (4 cm, 0 cm) circle (.25cm) node[below=4pt]{$3$};
\draw[fill=white] (6 cm, 0 cm) circle (.25cm) node[below=4pt]{$4$};
}
\draw[fill=white] (0 cm, 0 cm) circle (.25cm) node[below=4pt]{$0$};
"""
if node is None:
node = self._latex_draw_node
return self._type._latex_dynkin_diagram(label, node, node_dist, dual=True)
def ascii_art(self, label=lambda i: i, node=None):
"""
Return an ascii art representation of this Cartan type
(by hacking the ascii art representation of the dual Cartan type)
EXAMPLES::
sage: print(CartanType(["B", 3, 1]).dual().ascii_art())
O 0
|
|
O---O=<=O
1 2 3
sage: print(CartanType(["C", 4, 1]).dual().ascii_art())
O=<=O---O---O=>=O
0 1 2 3 4
sage: print(CartanType(["G", 2, 1]).dual().ascii_art())
3
O=>=O---O
1 2 0
sage: print(CartanType(["F", 4, 1]).dual().ascii_art())
O---O---O=<=O---O
0 1 2 3 4
sage: print(CartanType(["BC", 4, 2]).dual().ascii_art())
O=>=O---O---O=>=O
0 1 2 3 4
"""
if node is None:
node = self._ascii_art_node
res = self._type.ascii_art(label, node)
# swap, like a computer science freshman!
# This assumes that the oriented multiple arrows are always ascii arted as =<= or =>=
res = res.replace("=<=", "=?=")
res = res.replace("=>=", "=<=")
res = res.replace("=?=", "=>=")
return res
def __eq__(self, other):
"""
Return whether ``self`` is equal to ``other``.
EXAMPLES::
sage: B41 = CartanType(['B', 4, 1])
sage: B41dual = CartanType(['B', 4, 1]).dual()
sage: F41dual = CartanType(['F', 4, 1]).dual()
sage: F41dual == F41dual
True
sage: F41dual == B41dual
False
sage: B41dual == B41
False
"""
if not isinstance(other, CartanType):
return False
return self._type == other._type
def __ne__(self, other):
"""
Return whether ``self`` is equal to ``other``.
EXAMPLES::
sage: B41 = CartanType(['B', 4, 1])
sage: B41dual = CartanType(['B', 4, 1]).dual()
sage: F41dual = CartanType(['F', 4, 1]).dual()
sage: F41dual != F41dual
False
sage: F41dual != B41dual
True
sage: B41dual != B41
True
"""
return not (self == other)
def __hash__(self):
"""
Compute the hash of ``self``.
EXAMPLES::
sage: B41 = CartanType(['B', 4, 1])
sage: B41dual = CartanType(['B', 4, 1]).dual()
sage: h = hash(B41dual)
"""
return hash(self._type)
def dual(self):
"""
EXAMPLES::
sage: ct = CartanType(['F', 4, 1]).dual()
sage: ct.dual()
['F', 4, 1]
"""
return self._type
def dynkin_diagram(self):
"""
EXAMPLES::
sage: ct = CartanType(['F', 4, 1]).dual()
sage: ct.dynkin_diagram()
O---O---O=<=O---O
0 1 2 3 4
F4~*
"""
return self._type.dynkin_diagram().dual()
###########################################################################
class AmbientSpace(ambient_space.AmbientSpace):
"""
Ambient space for a dual finite Cartan type.
It is constructed in the canonical way from the ambient space of
the original Cartan type by switching the roles of simple roots,
fundamental weights, etc.
.. NOTE::
Recall that, for any finite Cartan type, and in particular the
a simply laced one, the dual Cartan type is constructed as
another preexisting Cartan type. Furthermore the ambient space
for an affine type is constructed from the ambient space for
its classical type. Thus this code is not actually currently
used.
It is kept for cross-checking and for reference in case it
could become useful, e.g., for dual of general Kac-Moody
types.
For the doctests, we need to explicitly create a dual type.
Subsequently, since reconstruction of the dual of type `F_4`
is the relabelled Cartan type, pickling fails on the
``TestSuite`` run.
EXAMPLES::
sage: ct = sage.combinat.root_system.type_dual.CartanType(CartanType(['F',4]))
sage: L = ct.root_system().ambient_space(); L
Ambient space of the Root system of type ['F', 4]^*
sage: TestSuite(L).run(skip=["_test_elements","_test_pickling"])
"""
@lazy_attribute
def _dual_space(self):
"""
The dual of this ambient space.
EXAMPLES::
sage: ct = sage.combinat.root_system.type_dual.CartanType(CartanType(['F',4]))
sage: L = ct.root_system().ambient_space(); L
Ambient space of the Root system of type ['F', 4]^*
sage: L._dual_space
Ambient space of the Root system of type ['F', 4]
The basic data for this space is fetched from the dual space::
sage: L._dual_space.simple_root(1)
(0, 1, -1, 0)
sage: L.simple_root(1)
(0, 1, -1, 0)
"""
K | |
check if it's in our lookup
if state in county_by_code and county_code in county_by_code[state]:
obj['legal_entity_county_name'] = county_by_code[state][county_code]
obj['legal_entity_zip5'] = obj['legal_entity_zip4'][:5]
if len(obj['legal_entity_zip4']) > 5:
obj['legal_entity_zip_last4'] = obj['legal_entity_zip4'][-4:]
# if there is any country code (checked outside function) but not a country name, try to get the country name
if not obj['legal_entity_country_name'] and obj['legal_entity_country_code'] in country_list:
obj['legal_entity_country_name'] = country_list[obj['legal_entity_country_code']]
def calculate_remaining_fields(obj, sess, sub_tier_list, county_by_name, county_by_code, state_code_list, country_list,
exec_comp_dict, atom_type):
""" Calculate values that aren't in any feed but can be calculated.
Args:
obj: a dictionary containing the details we need to derive from and to
sess: the database connection
sub_tier_list: a dictionary containing all the sub tier agency information keyed by sub tier agency code
county_by_name: a dictionary containing all county codes, keyed by state and county name
county_by_code: a dictionary containing all county names, keyed by state and county code
state_code_list: a dictionary containing all state names, keyed by state code
country_list: a dictionary containing all country names, keyed by country code
exec_comp_dict: a dictionary containing all the data for Executive Compensation data keyed by DUNS number
atom_type: a string indicating whether the atom feed being checked is 'award' or 'IDV'
Returns:
the object originally passed in with newly-calculated values added
"""
# we want to null out all the calculated columns in case this is an update to the records
obj['awarding_agency_code'] = None
obj['awarding_agency_name'] = None
obj['funding_agency_code'] = None
obj['funding_agency_name'] = None
obj['place_of_perform_county_co'] = None
obj['legal_entity_county_code'] = None
obj['legal_entity_county_name'] = None
obj['detached_award_proc_unique'] = None
# calculate awarding agency codes/names based on awarding sub tier agency codes
if obj['awarding_sub_tier_agency_c']:
try:
sub_tier_agency = sub_tier_list[obj['awarding_sub_tier_agency_c']]
use_frec = sub_tier_agency.is_frec
agency_data = sub_tier_agency.frec if use_frec else sub_tier_agency.cgac
obj['awarding_agency_code'] = agency_data.frec_code if use_frec else agency_data.cgac_code
obj['awarding_agency_name'] = agency_data.agency_name
except KeyError:
logger.info('WARNING: MissingSubtierCGAC: The awarding sub-tier cgac_code: %s does not exist in cgac table.'
' The FPDS-provided awarding sub-tier agency name (if given) for this cgac_code is %s. '
'The award has been loaded with awarding_agency_code 999.',
obj['awarding_sub_tier_agency_c'], obj['awarding_sub_tier_agency_n'])
obj['awarding_agency_code'] = '999'
obj['awarding_agency_name'] = None
# calculate funding agency codes/names based on funding sub tier agency codes
if obj['funding_sub_tier_agency_co']:
try:
sub_tier_agency = sub_tier_list[obj['funding_sub_tier_agency_co']]
use_frec = sub_tier_agency.is_frec
agency_data = sub_tier_agency.frec if use_frec else sub_tier_agency.cgac
obj['funding_agency_code'] = agency_data.frec_code if use_frec else agency_data.cgac_code
obj['funding_agency_name'] = agency_data.agency_name
except KeyError:
logger.info('WARNING: MissingSubtierCGAC: The funding sub-tier cgac_code: %s does not exist in cgac table. '
'The FPDS-provided funding sub-tier agency name (if given) for this cgac_code is %s. '
'The award has been loaded with funding_agency_code 999.',
obj['funding_sub_tier_agency_co'], obj['funding_sub_tier_agency_na'])
obj['funding_agency_code'] = '999'
obj['funding_agency_name'] = None
# do place of performance calculations only if we have SOME country code
if obj['place_of_perform_country_c']:
calculate_ppop_fields(obj, sess, county_by_name, county_by_code, state_code_list, country_list)
# do legal entity calculations only if we have SOME country code
if obj['legal_entity_country_code']:
calculate_legal_entity_fields(obj, sess, county_by_code, state_code_list, country_list)
# calculate business categories
obj['business_categories'] = get_business_categories(row=obj, data_type='fpds')
# Calculate executive compensation data for the entry.
if obj['awardee_or_recipient_uniqu'] and obj['awardee_or_recipient_uniqu'] in exec_comp_dict.keys():
exec_comp = exec_comp_dict[obj['awardee_or_recipient_uniqu']]
for i in range(1, 6):
obj['high_comp_officer{}_full_na'.format(i)] = exec_comp['officer{}_name'.format(i)]
obj['high_comp_officer{}_amount'.format(i)] = exec_comp['officer{}_amt'.format(i)]
else:
# Need to make sure they're null in case this is updating and the DUNS has changed somehow
for i in range(1, 6):
obj['high_comp_officer{}_full_na'.format(i)] = None
obj['high_comp_officer{}_amount'.format(i)] = None
# calculate unique award key
if atom_type == 'award':
unique_award_string_list = ['CONT_AWD']
key_list = ['piid', 'agency_id', 'parent_award_id', 'referenced_idv_agency_iden']
else:
unique_award_string_list = ['CONT_IDV']
key_list = ['piid', 'agency_id']
for item in key_list:
# Get the value in the object or, if the key doesn't exist or value is None, set it to "-none-"
unique_award_string_list.append(obj.get(item) or '-none-')
obj['unique_award_key'] = '_'.join(unique_award_string_list).upper()
# calculate unique key
key_list = ['agency_id', 'referenced_idv_agency_iden', 'piid', 'award_modification_amendme', 'parent_award_id',
'transaction_number']
idv_list = ['agency_id', 'piid', 'award_modification_amendme']
unique_string = ""
for item in key_list:
if len(unique_string) > 0:
unique_string += "_"
if atom_type == 'award' or item in idv_list:
# Get the value in the object or, if the key doesn't exist or value is None, set it to "-none-"
unique_string += obj.get(item) or '-none-'
else:
unique_string += '-none-'
# The order of the unique key is agency_id, referenced_idv_agency_iden, piid, award_modification_amendme,
# parent_award_id, transaction_number
obj['detached_award_proc_unique'] = unique_string
return obj
def process_data(data, sess, atom_type, sub_tier_list, county_by_name, county_by_code, state_code_list, country_list,
exec_comp_dict):
""" Process the data coming in.
Args:
data: an object containing the data gathered from the feed
sess: the database connection
atom_type: a string indicating whether the atom feed being checked is 'award' or 'IDV'
sub_tier_list: a dictionary containing all the sub tier agency information keyed by sub tier agency code
county_by_name: a dictionary containing all county codes, keyed by state and county name
county_by_code: a dictionary containing all county names, keyed by state and county code
state_code_list: a dictionary containing all state names, keyed by state code
country_list: a dictionary containing all country names, keyed by country code
exec_comp_dict: a dictionary containing all the data for Executive Compensation data keyed by DUNS number
Returns:
An object containing the processed and calculated data.
"""
obj = {}
if atom_type == "award":
# make sure key exists before passing it
try:
data['awardID']
except KeyError:
data['awardID'] = {}
obj = award_id_values(data['awardID'], obj)
else:
# transaction_number is a part of the unique identifier, set it to None
obj['transaction_number'] = None
# make sure key exists before passing it
try:
data['contractID']
except KeyError:
data['contractID'] = {}
obj = contract_id_values(data['contractID'], obj)
# make sure key exists before passing it
try:
data['competition']
except KeyError:
data['competition'] = {}
obj = competition_values(data['competition'], obj)
# make sure key exists before passing it
try:
data['contractData']
except KeyError:
data['contractData'] = {}
obj = contract_data_values(data['contractData'], obj, atom_type)
# make sure key exists before passing it
try:
data['dollarValues']
except KeyError:
data['dollarValues'] = {}
obj = dollar_values_values(data['dollarValues'], obj)
# make sure key exists before passing it
try:
data['totalDollarValues']
except KeyError:
data['totalDollarValues'] = {}
obj = total_dollar_values_values(data['totalDollarValues'], obj)
if atom_type == "award":
# make sure key exists before passing it
try:
data['placeOfPerformance']
except KeyError:
data['placeOfPerformance'] = {}
obj = place_of_performance_values(data['placeOfPerformance'], obj)
# these values need to be filled so the existence check when calculating county data doesn't freak out
else:
obj['place_of_perform_county_na'] = None
obj['place_of_performance_state'] = None
obj['place_of_perfor_state_desc'] = None
obj['place_of_performance_zip4a'] = None
obj['place_of_perform_country_c'] = None
obj['place_of_perf_country_desc'] = None
# make sure key exists before passing it
try:
data['legislativeMandates']
except KeyError:
data['legislativeMandates'] = {}
obj = legislative_mandates_values(data['legislativeMandates'], obj)
try:
obj['subcontracting_plan'] = extract_text(data['preferencePrograms']['subcontractPlan'])
except (KeyError, TypeError):
obj['subcontracting_plan'] = None
try:
obj['subcontracting_plan_desc'] = data['preferencePrograms']['subcontractPlan']['@description']
except (KeyError, TypeError):
obj['subcontracting_plan_desc'] = None
# make sure key exists before passing it
try:
data['productOrServiceInformation']
except KeyError:
data['productOrServiceInformation'] = {}
obj = product_or_service_information_values(data['productOrServiceInformation'], obj)
# make sure key exists before passing it
try:
data['purchaserInformation']
except KeyError:
data['purchaserInformation'] = {}
obj = purchaser_information_values(data['purchaserInformation'], obj)
# make sure key exists before passing it
try:
data['relevantContractDates']
except KeyError:
data['relevantContractDates'] = {}
obj = relevant_contract_dates_values(data['relevantContractDates'], obj)
# make sure key exists before passing it
try:
data['vendor']
except KeyError:
data['vendor'] = {}
obj = vendor_values(data['vendor'], obj)
# make sure key exists before passing it
try:
data['genericTags']
except KeyError:
data['genericTags'] = {}
obj = generic_values(data['genericTags'], obj)
obj = calculate_remaining_fields(obj, sess, sub_tier_list, county_by_name, county_by_code, state_code_list,
country_list, exec_comp_dict, atom_type)
try:
obj['last_modified'] = data['transactionInformation']['lastModifiedDate']
except (KeyError, TypeError):
obj['last_modified'] = None
try:
obj['initial_report_date'] = data['transactionInformation']['createdDate']
except (KeyError, TypeError):
obj['initial_report_date'] = None
obj['pulled_from'] = atom_type
# clear out potentially excel-breaking whitespace from specific fields
free_fields = ["award_description", "vendor_doing_as_business_n", "legal_entity_address_line1",
"legal_entity_address_line2", "legal_entity_address_line3", "ultimate_parent_legal_enti",
"awardee_or_recipient_legal", "other_statutory_authority"]
for field in free_fields:
if obj[field]:
obj[field] = re.sub('\s', ' ', obj[field])
return obj
def process_delete_data(data, atom_type):
""" process the delete feed data coming in """
unique_string = ""
# order of unique constraints in string: agency_id, referenced_idv_agency_iden, piid, award_modification_amendme,
# parent_award_id, transaction_number
# get all values that make up unique key
if atom_type == "award":
try:
unique_string += extract_text(data['awardID']['awardContractID']['agencyID'])
except (KeyError, TypeError):
unique_string += "-none-"
unique_string += "_"
try:
unique_string += extract_text(data['awardID']['referencedIDVID']['agencyID'])
except (KeyError, TypeError):
unique_string += "-none-"
unique_string += "_"
try:
unique_string += extract_text(data['awardID']['awardContractID']['PIID'])
except (KeyError, TypeError):
unique_string += "-none-"
unique_string += "_"
try:
unique_string += | |
= grad
assert w.is_dense()
return w
g_output = [from_untyped(grad) for grad in g_output]
grad_defs_str, g_input = C.get_gradient_defs(
op_def.SerializeToString(), g_output)
def to_untyped(grad_wrapper):
if grad_wrapper.is_empty():
return None
if grad_wrapper.is_sparse():
return GradientSlice(grad_wrapper.indices, grad_wrapper.values)
assert grad_wrapper.is_dense()
return grad_wrapper.dense
g_input = [to_untyped(grad_wrapper) for grad_wrapper in g_input]
grad_defs = []
for grad_def_str in grad_defs_str:
grad_def = caffe2_pb2.OperatorDef()
grad_def.ParseFromString(grad_def_str)
grad_defs.append(grad_def)
return grad_defs, g_input
@classmethod
def GetGradientForOp(cls, op, g_output):
try:
gradient_ops, g_input = cls._GetGradientForOpCC(op, g_output)
except Exception as e:
# Not supported in C++; will try python registration next.
if op.type in cls.gradient_registry_:
gradient_ops, g_input = cls.gradient_registry_[op.type](
op, g_output
)
else:
raise Exception(
"Exception when creating the gradient for [{}]: {}.".
format(op.type, e)
)
if gradient_ops is None:
return [], g_input
if type(gradient_ops) is not list:
gradient_ops = [gradient_ops]
return gradient_ops, g_input
@classmethod
def GetBackwardPass(cls, operators, ys, ys_generate_gradient=False):
"""Gets the backward pass for the list of operators.
Args:
operators: a list of operators constituting the forward pass.
ys: a list or a dictionary specifying what blobs we want to compute
derivatives of. If the input is a list, we will automatically
generate their gradients with all-one values; if the input is a
dictionary, for any dictionary entries that are not None, we'll
take the corresponding blobs as their gradients; for all those
that are None, we will auto-fill them with 1.
Returns:
gradient_ops: a list of gradient operators to run.
all_input_to_grads: a map from input to their corresponding
gradients.
"""
ir = IR(operators)
return ir.GetBackwardPass(ys)
def get_ssa(net, blob_versions=None):
"""
Given a net, return a structure containing the version of each input and
output blob used by each operator.
Args:
net: either a Net or a NetDef
blob_versions: (optional) map with current version number for given
blob names. If not provided or blob not found, start
from version 0.
Returns:
Tuple (ssa, blob_versions)
ssa: list of tuples (versioned_inputs, versioned_outputs)
for each op in the net. A versioned input is a tuple
(blob_name, version).
blob_versions: updated map with latest version of each blob found in
the net.
"""
proto = net.Proto() if isinstance(net, Net) else net
assert isinstance(proto, caffe2_pb2.NetDef)
if blob_versions is None:
blob_versions = {}
if isinstance(net, list):
return [get_ssa(n, blob_versions) for n in net], blob_versions
for i in proto.external_input:
if i not in blob_versions:
blob_versions[str(i)] = 0
ssa = []
for op in proto.op:
if not proto.external_input:
for i in op.input:
if i not in blob_versions:
blob_versions[i] = 0
inputs = [(str(i), blob_versions.get(str(i), 0)) for i in op.input]
for o in op.output:
blob_versions[str(o)] = blob_versions.get(str(o), 0) + 1
outputs = [(str(o), blob_versions[str(o)]) for o in op.output]
ssa.append((inputs, outputs))
return ssa, blob_versions
def get_undefined_blobs(ssa):
"""
Given a ssa in the format produced by get_ssa(), return a set of blobs that
are used before they are defined, which corresponds to inputs at version 0.
"""
undef_blobs = set()
for inputs, _outputs in ssa:
undef_blobs |= set(name for (name, ver) in inputs if ver == 0)
return undef_blobs
def get_output_producers(ssa):
"""
Given a ssa in the format produced by get_ssa(), returns a map from
versioned blob into the operator index that produces that version of
the blob. A versioned blob is a tuple (blob_name, version).
"""
producers = {}
for i, (_inputs, outputs) in enumerate(ssa):
for o in outputs:
producers[o] = i
return producers
def get_op_ids_in_path(ssa, blob_versions, inputs, outputs):
"""
Given a ssa and blob_versions as produced by get_ssa(), returns the list
of op indices that are necessary in order to generate the blobs in
`outputs`, given blobs in `inputs`.
Consider that the `inputs` are given in their latest version.
"""
inputs_set = set((str(i), blob_versions[str(i)]) for i in inputs)
producers = get_output_producers(ssa)
queue = [(str(o), blob_versions[str(o)]) for o in outputs]
used_op_ids = set()
while len(queue) > 0:
o = queue.pop()
if (o not in inputs_set) and (o in producers):
op_id = producers[o]
if op_id not in used_op_ids:
used_op_ids |= {op_id}
inputs, _ = ssa[op_id]
queue.extend(inputs)
return sorted(used_op_ids)
def clone_and_bind_net(net, name, prefix, blob_remap=None, inputs=None,
keep_schema=True):
"""
Clone the given Net, binding its input schema to the given `inputs` record.
Blob names defined by the net are prepended with the given `prefix`.
Args:
net: the net to clone
name: the name of the new net
prefix: the prefix to append to local blobs
blob_remap: (optional) dict with additional blob name remapping.
inputs: (optional) input record that will provide actual input
values for the cloned net. Must be compatible with the
net's input schema or be a strict superset of it
keep_schema: by default (True), the original schema will be kept and
remapped accordingly. otherwise, the schema will be set as
inputs or left empty if inputs is not given.
Returns:
Tuple (cloned_net, blob_remap)
clone_net: the cloned Net
blob_remap: a map from original blob names into remapped blob names
"""
from caffe2.python import schema
assert isinstance(net, Net)
if blob_remap is None:
blob_remap = {}
if inputs is not None:
assert isinstance(inputs, schema.Field)
original = net.input_record()
assert original is not None
# TODO(azzolini): improve schema type checking
diff = set(original.field_names()) - set(inputs.field_names())
assert len(diff) == 0, (
"Schemas don't match, extra fields {diff} found in the net {name}. "
"original: {original}; inputs: {inputs}"
.format(
diff=diff, name=net.Name(), original=original.field_names(),
inputs=inputs.field_names()
)
)
original_mapping = dict(zip(original.field_names(),
original.field_blobs()))
for fn, fb in zip(inputs.field_names(), inputs.field_blobs()):
if fn in original_mapping:
blob_remap[str(original_mapping[fn])] = str(fb)
proto = net.Proto()
ssa, blob_versions = get_ssa(proto)
undef_blobs = get_undefined_blobs(ssa)
for blob in viewkeys(blob_versions):
if blob in blob_remap:
continue
elif blob in undef_blobs:
blob_remap[blob] = blob
else:
blob_remap[blob] = prefix + blob
cloned_net = net.Clone(name, blob_remap, keep_schema=keep_schema)
if not keep_schema and inputs:
cloned_net.set_input_record(inputs)
return cloned_net, blob_remap
def _get_blob_ref(blob_name_or_ref):
return (
blob_name_or_ref if isinstance(input, BlobReference)
else BlobReference(blob_name_or_ref)
)
def _recover_record_by_prefix(names, prefix=''):
"""
Tries to recover record by taking a subset of blob names with
a given prefix name and interpreting them as schema column names
"""
from caffe2.python import schema
column_names = [name[len(prefix):] for name in names
if name.startswith(prefix)]
if not column_names:
return None
return schema.from_column_list(
column_names,
col_blobs=[_get_blob_ref(prefix + name) for name in column_names])
class Net(object):
_net_names_used = set()
operator_registry_ = {}
@staticmethod
def current_prefix():
from caffe2.python.net_builder import NetBuilder
builder = NetBuilder.current(required=False)
return builder.name if builder else ''
@staticmethod
def _get_next_net_name(basename):
name = basename = '/'.join(
x for x in [Net.current_prefix(), basename] if x
)
next_idx = 1
while name in Net._net_names_used:
name = basename + '_' + str(next_idx)
next_idx += 1
Net._net_names_used |= set([name])
return name
def __init__(self, name_or_proto):
"""
Create a Net.
Args:
name_or_proto: If a NetDef is provided, clone it. Otherwise,
create an empty net with the given name.
"""
self._input_record = None
self._output_record = None
# Register blobs so that it's guaranteed that different calls to
# NextBlob/NextScopedBlob always return blobs with different names
self._registered_blob_names = set()
self._recreate_lookup_tables = False
self._op_outputs = set()
self._external_input_map = set()
self._attr_dict = defaultdict(list)
if type(name_or_proto) is caffe2_pb2.NetDef:
proto = name_or_proto
# We rae initializing a network by a NetDef. In this case, we will
# initialize our network with the given netdef.
self._net = caffe2_pb2.NetDef()
self._net.CopyFrom(proto)
existing_outputs = [list(op.output) for op in self._net.op]
self._external_input_map.update(list(self._net.external_input))
# Set the next name index properly.
existing_names = set(
sum(
[list(op.input) for op in self._net.op], []
) + sum(
existing_outputs, []
)
)
for outs in existing_outputs:
self._op_outputs.update(outs)
prefix_len = len(self._net.name + '_blob_')
autogen_indices = []
for s in existing_names:
if s.startswith(self._net.name + '_blob_'):
try:
autogen_indices.append(int(s[prefix_len]))
except ValueError:
pass
if len(autogen_indices):
self._next_name_index = max(autogen_indices) + 1
else:
self._next_name_index = 0
name = self._net.name
else:
name = name_or_proto
self._net = caffe2_pb2.NetDef()
self._next_name_index = 0
# make sure that this net name hasn't been used before
self._net.name = Net._get_next_net_name(name)
def AppendNet(self, net):
assert isinstance(net, Net)
for i in net.Proto().external_input:
if (
i not in self.Proto().external_input and
i not in self._op_outputs
):
self.Proto().external_input.append(i)
self.Proto().external_output.extend(
[
o for o in net.Proto().external_output
if o not in self.Proto().external_output
]
)
self._ExtendOps(net.Proto().op)
return self
def LogInfo(self, *msg_or_blobs):
for msg_or_blob in msg_or_blobs:
if not isinstance(msg_or_blob, BlobReference):
blob = self.GivenTensorStringFill(
[], | |
"""Tests for Gremlin database."""
import requests
import pprint
from behave import then, when
from semantic_version import Version
import time
from src.attribute_checks import check_and_get_attribute, check_attribute_presence, check_cve_value
from src.json_utils import check_request_id_value_in_json_response
from src.utils import split_comma_separated_list
from src.graph_db_query import Query
import logging
# set up the logging for this module
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
# no data should have timestamp with earlier date than 2015-01-01, simply because
# this project was started after this date
BAYESSIAN_PROJECT_START_DATE = time.mktime(time.strptime("2015-01-01", "%Y-%m-%d"))
@when('I access Gremlin API')
def gremlin_url_access(context):
"""Access the Gremlin service API using the HTTP POST method."""
post_query(context, "")
@when('I ask Gremlin to find all vertexes having property {name} set to {value}')
def gremlin_search_vertexes(context, name, value):
"""Perform simple query to the Gremlin for all vertexes having the specified property."""
query = Query().has(name, value)
post_query(context, query)
@when('I ask Gremlin to find number of vertexes for the ecosystem {ecosystem}')
def gremlin_search_vertexes_for_the_ecosystem(context, ecosystem):
"""Perform simple query to the Gremlin for all vertexes having the specified property."""
query = Query().has("pecosystem", ecosystem).count()
post_query(context, query)
@when('I ask Gremlin to find all versions of the package {package:S} in the ecosystem {ecosystem}')
def gremlin_find_all_versions_of_package(context, package, ecosystem):
"""Try to find all versions of the given package in the selected ecosystem."""
query = Query().has("ecosystem", ecosystem).has("name", package).out("has_version")
post_query(context, query)
@when('I ask Gremlin to find the package {package:S} version {version} in the ecosystem '
'{ecosystem}')
def gremlin_find_package_version(context, package, version, ecosystem):
"""Try to find the package with version in the selected ecosystem."""
query = Query().has("pecosystem", ecosystem).has("pname", package).has("version", version)
post_query(context, query)
@when('I ask Gremlin to find the package {package:S} in the ecosystem {ecosystem}')
def gremlin_find_package(context, package, ecosystem):
"""Try to find the package in the selected ecosystem."""
query = Query().has("ecosystem", ecosystem).has("name", package)
post_query(context, query)
@when('I remember the current time')
def remember_current_time(context):
"""Remember the current time for further checks."""
context.current_time = time.time()
@when('I read the last update time for the package {package:S} version {version} in the ecosystem'
' {ecosystem}')
def gremlin_read_last_update_time(context, package, version, ecosystem):
"""Read the last update timestamp."""
query = Query().has("pecosystem", ecosystem).has("pname", package).has("version", version).\
first().value("last_updated")
post_query(context, query)
@when('I wait for the update in the graph database for the package {package:S} version {version}'
' in the ecosystem {ecosystem}')
def wait_for_update_in_graph_db(context, package, version, ecosystem):
"""Wait until the package metadata is not updated in the graph database."""
timeout = 300 * 60
sleep_amount = 10 # we don't want to overload the graph db, so 10 seconds seems to be good
max_iters = timeout // sleep_amount
start_time = time.time()
log.info("start time: " + str(start_time))
for i in range(max_iters):
gremlin_read_last_update_time(context, package, version, ecosystem)
timestamp = get_timestamp_from_gremlin(context)
log.info("Iteration {i} of {max}: start time: {t1}, timestamp: {t2}".format(i=i,
max=max_iters,
t1=start_time,
t2=timestamp))
if timestamp > start_time:
return
time.sleep(sleep_amount)
raise Exception('Timeout waiting for the new package metadata in graph DB!')
def post_query(context, query):
"""Post the already constructed query to the Gremlin."""
data = {"gremlin": str(query)}
context.response = requests.post(context.gremlin_url, json=data)
@then('I should get valid Gremlin response')
def valid_gremlin_response(context):
"""Check that the Gremlin response is valid."""
check_request_id_value_in_json_response(context, "requestId")
data = context.response.json()
assert data, "Gremlin does not send a proper response"
check_gremlin_status_node(data)
check_gremlin_result_node(data)
@then('I should get zero vertexes')
@then('I should get {num:d} vertexes')
def check_vertexes_count(context, num=0):
"""Check the number of vertexes returned in Gremlin response."""
data, meta = get_results_from_gremlin(context)
vertexes = len(data)
assert vertexes == num, "Expected %d vertexes, but got %d instead" % (num, vertexes)
@then('I should find at least one such vertex')
def check_non_zero_vertexes_count(context):
"""Check the number of vertexes returned in Gremlin response."""
data, meta = get_results_from_gremlin(context)
vertexes = len(data)
assert vertexes > 0, "Expected at least one vertex, but got zero instead"
def get_node_value_from_properties_returned_by_gremlin(context, node_name):
"""Try to retrieve node value from the 'properties' node returned by Gremlin."""
data, meta = get_results_from_gremlin(context)
assert len(data) == 1, "Expected precisely one vertex with package data"
assert data[0] is not None
properties = check_and_get_attribute(data[0], "properties")
return get_node_value(properties, node_name)
@then('I should find the package {package} name in the Gremlin response')
def check_package_name(context, package):
"""Check the package name in Gremlin response."""
name = get_node_value_from_properties_returned_by_gremlin(context, "name")
assert name == package, \
"Returned package name '{name}' is different from expected name '{package}'" \
.format(name=name, package=package)
@then('I should find the ecosystem {ecosystem} name in the Gremlin response')
def check_ecosystem_name(context, ecosystem):
"""Check the ecosystem name in Gremlin response."""
name = get_node_value_from_properties_returned_by_gremlin(context, "ecosystem")
assert name == ecosystem, \
"Returned ecosystem name '{name}' is different from expected name '{ecosystem}'" \
.format(name=name, ecosystem=ecosystem)
@then('I should find at least one package in the Gremlin response')
@then('I should find at least {expected:d} packages in the Gremlin response')
def check_number_of_packages_returned(context, expected=1):
"""Check the number of returned packages."""
data, meta = get_results_from_gremlin(context)
found = len(data)
assert found >= expected, \
"Expected at least %d packages, but %d was found instead" % (expected, found)
@then('I should find that all found packages have valid timestamp with the last update time')
def check_timestamp_for_all_packages_in_gremlin_response(context):
"""Check if the last_updated attribute exists and if it contain proper timestamp."""
data, meta = get_results_from_gremlin(context)
for package in data:
properties = check_and_get_attribute(package, "properties")
test_last_updated_attribute(properties)
def check_last_updated_value(comparison, value, remembered_time):
"""Check the 'last_update' attribute for data item stored in Gremlin."""
if comparison == "older":
assert value < remembered_time, "The last_updated attribute is less than current time"
elif comparison == "newer":
assert value > remembered_time, "The last_updated attribute is higher than current time"
else:
raise Exception("Wrong 'comparison' argument in test step {}".format(comparison))
@then('I should find that the package data is {comparison} than remembered time')
def package_data_timestamp_comparison_with_remembered_time(context, comparison):
"""Check if the last_updated attribute is older or newer than remembered time.
The timestamp is checked for all package versions.
"""
remembered_time = context.current_time
data, meta = get_results_from_gremlin(context)
for package in data:
properties = check_and_get_attribute(package, "properties")
last_updated = check_and_get_attribute(properties, "last_updated")
value = check_and_get_attribute(last_updated[0], "value")
check_last_updated_value(comparison, value, remembered_time)
def get_results_from_gremlin(context):
"""Try to take the results from the Gremlin response."""
data = context.response.json()
result = check_and_get_attribute(data, "result")
data = check_and_get_attribute(result, "data")
meta = check_and_get_attribute(result, "meta")
return data, meta
def check_gremlin_status_node(data):
"""Check the basic structure of the 'status' node in Gremlin response."""
status = check_and_get_attribute(data, "status")
message = check_and_get_attribute(status, "message")
code = check_and_get_attribute(status, "code")
attributes = check_and_get_attribute(status, "attributes")
assert message == ""
assert code == 200
# this node should be empty
assert not attributes
def check_gremlin_result_node(data):
"""Check the basic structure of the 'result' node in Gremlin response."""
result = check_and_get_attribute(data, "result")
data = check_and_get_attribute(result, "data")
meta = check_and_get_attribute(result, "meta")
assert type(data) is list
assert type(meta) is dict
@then('I should find the following properties ({properties}) in all found packages')
def check_properties_in_results(context, properties):
"""Check if all given properties can be found in all packages returned by Gremlin."""
data, meta = get_results_from_gremlin(context)
expected_properties = split_comma_separated_list(properties)
# we need to check if all expected properties are really returned by the Gremlin
for package in data:
check_attribute_presence(package, "properties")
properties = package["properties"].keys()
assert properties is not None
for expected_property in expected_properties:
if expected_property not in properties:
# print examined data so users would know what happened
formatted_data = pprint.pformat(package)
message = "Required property could not be found: {prop}\n" \
"Tested Gremlin results:\n{r}"
raise Exception(message.format(prop=expected_property, r=formatted_data))
@then('I should not find any property apart from ({properties}) in all found packages')
def check_unexpected_properties_in_results(context, properties):
"""Check if only given optional properties can be found in all packages returned by Gremlin."""
data, meta = get_results_from_gremlin(context)
expected_properties = split_comma_separated_list(properties)
for package in data:
check_attribute_presence(package, "properties")
properties = package["properties"].keys()
assert properties is not None
for prop in properties:
# check that the property is contained in a list of expected properties
if prop not in expected_properties:
raise Exception("Unexpected property has been found: {prop}".format(
prop=prop))
def get_timestamp_from_gremlin(context):
"""Get the value of timestamp attribute."""
data, meta = get_results_from_gremlin(context)
assert len(data) == 1
return data[0]
@then('I should get a valid timestamp represented as UNIX time')
def check_unix_timestamp(context):
"""Check that only proper timestamp is returned in Gremlin response."""
timestamp = get_timestamp_from_gremlin(context)
assert type(timestamp) is float
@then('I should find that the returned timestamp is {comparison} than remembered time')
def check_package_version_timestamp_comparison_with_remembered_time(context, comparison):
"""Check if the last_updated attribute is older or newer than remembered time."""
remembered_time = context.current_time
timestamp = get_timestamp_from_gremlin(context)
if comparison == "older":
assert timestamp < remembered_time
elif comparison == "newer":
assert timestamp > remembered_time
def read_property_value_from_gremlin_response(context, property_name):
"""Read property value from the Gremlin response with all checks."""
data, meta = get_results_from_gremlin(context)
package = data[0]
properties = check_and_get_attribute(package, "properties")
# try to retrieve list of id+value pairs
id_values = check_and_get_attribute(properties, property_name)
# we expect list with one value only
| |
<filename>BriVL-code-inference/models/vl_model.py
import torch
import torch.nn as nn
from .fakeTransformer import FakeTransformer
from .bert import Bert
from utils import pairLoss, alignmentLoss, attAlignmentLoss, AlignTripLoss, SimpTripLoss, NCELoss
import torch.nn.functional as F
import timm
import numpy as np
import sys
class ImgLearnableEncoder(nn.Module):
def __init__(self, model_cfg):
super(ImgLearnableEncoder, self).__init__()
self.backbone = timm.create_model(model_cfg.CNN, pretrained=True)
self.model_cfg = model_cfg
self.learnable = nn.ModuleDict()
self.learnable['imgFC'] = FakeTransformer(model_cfg.IMG_FEATURE_DIM, model_cfg.IMG_FEATURE_DIM, model_cfg.IMG_FEATURE_DIM)
img_encoder_layer = nn.TransformerEncoderLayer(d_model=model_cfg.IMG_FEATURE_DIM, nhead=model_cfg.IMG_TRANSFORMER_HEAD)
self.learnable['imgAtt'] = nn.TransformerEncoder(img_encoder_layer, num_layers=model_cfg.IMG_TRANSFORMER_LAYER)
self.learnable['max_pool'] = nn.Sequential(
nn.Conv2d(model_cfg.IMG_FEATURE_DIM, model_cfg.IMG_FEATURE_DIM, kernel_size=1),
nn.AvgPool2d(model_cfg.GRID_SIZE, stride=1)
)
self.init_param()
def init_param(self):
for name, param in self.backbone.named_parameters():
condition = 'blocks.6' not in name and 'blocks.5' not in name and 'blocks.4' not in name and 'blocks.3' not in name
if condition:
param.requires_grad = False
else:
print(name + ' need grads')
param.requires_grad = True
sys.stdout.flush()
def roi_grid_pool(self, spatial_features_2d, rois):
"""
Args:
rois: (B, num_rois, 4)
spatial_features_2d: (B, C, H, W)
Returns:
pooled_features : (B, num_rois, C)
"""
batch_size = spatial_features_2d.size(0)
rois = rois.detach()
height, width = spatial_features_2d.size(2), spatial_features_2d.size(3)
down_sample_ratio = self.model_cfg.IMG_SIZE / height
pooled_features_list = []
torch.backends.cudnn.enabled = False
for b_id in range(batch_size):
# Map global boxes coordinates to feature map coordinates
x1 = rois[b_id, :, 0] / down_sample_ratio
y1 = rois[b_id, :, 1] / down_sample_ratio
x2 = rois[b_id, :, 2] / down_sample_ratio
y2 = rois[b_id, :, 3] / down_sample_ratio
angle = torch.zeros((1), device=spatial_features_2d.device)
cosa = torch.cos(angle)
sina = torch.sin(angle)
theta = torch.stack((
(x2 - x1) / (width - 1) * cosa, (x2 - x1) / (width - 1) * (-sina), (x1 + x2 - width + 1) / (width - 1),
(y2 - y1) / (height - 1) * sina, (y2 - y1) / (height - 1) * cosa, (y1 + y2 - height + 1) / (height - 1)
), dim=1).view(-1, 2, 3).float()
grid_size = self.model_cfg.GRID_SIZE
grid = nn.functional.affine_grid(
theta,
torch.Size((rois.size(1), spatial_features_2d.size(1), grid_size, grid_size))
)
pooled_features = nn.functional.grid_sample(
spatial_features_2d[b_id].unsqueeze(0).expand(rois.size(1), spatial_features_2d.size(1), height, width),
grid
)
pooled_features = self.learnable['max_pool'](pooled_features)
pooled_features_list.append(pooled_features.squeeze())
torch.backends.cudnn.enabled = True
pooled_features = torch.stack(pooled_features_list, dim=0)
return pooled_features
def forward(self, imgFea, maskImages, image_boxs):
feature_map = self.backbone.forward_features(imgFea)
imgFea = self.roi_grid_pool(feature_map, image_boxs)
imgFea = F.normalize(imgFea, p=2, dim=-1)
imgFea = self.learnable['imgAtt'](imgFea.transpose(0, 1), src_key_padding_mask=(maskImages == 0)).transpose(0,1)
tmpMask = torch.where(maskImages == 1, torch.tensor([1.0], device=maskImages.device),
torch.tensor([0.0], device=maskImages.device))
imgFea = (imgFea * tmpMask.unsqueeze(-1)).sum(dim=1) / tmpMask.sum(dim=1).unsqueeze(-1)
imgFea = self.learnable['imgFC'](imgFea)
return imgFea
class TextLearnableEncoder(nn.Module):
def __init__(self, model_cfg):
super(TextLearnableEncoder, self).__init__()
self.backbone = Bert(model_cfg)
self.model_cfg = model_cfg
self.learnable = nn.ModuleDict()
self.learnable['textFC'] = FakeTransformer(model_cfg.TEXT_FEATURE_DIM, model_cfg.IMG_FEATURE_DIM, model_cfg.IMG_FEATURE_DIM)
text_encoder_layer = nn.TransformerEncoderLayer(d_model=model_cfg.TEXT_FEATURE_DIM, nhead=model_cfg.TEXT_TRANSFORMER_HEAD)
self.learnable['textAtt'] = nn.TransformerEncoder(text_encoder_layer, num_layers=model_cfg.TEXT_TRANSFORMER_LAYER)
self.init_param()
def init_param(self):
for name, param in self.backbone.named_parameters():
if 'large' not in self.model_cfg.ENCODER:
if 'layer.11' not in name and 'layer.10' not in name and 'layer.9' not in name and 'layer.8' not in name:
param.requires_grad = False
else:
print(name + ' need grads')
param.requires_grad = True
else:
if 'layer.21' not in name and 'layer.22' not in name and 'layer.23' not in name and 'layer.20' not in name: # and 'layer.9' not in name
param.requires_grad = False
else:
print(name + ' need grads')
param.requires_grad = True
sys.stdout.flush()
def forward(self, textFea, maskTexts):
textFea = self.backbone(textFea)
textFea = F.normalize(textFea, p=2, dim=-1)
textFea = self.learnable['textAtt'](textFea.transpose(0, 1), src_key_padding_mask=(maskTexts == 0)).transpose(0,1)
tmpMask = torch.where(maskTexts == 1, torch.tensor([1.0], device=maskTexts.device),
torch.tensor([0.0], device=maskTexts.device))
textFea = (textFea * tmpMask.unsqueeze(-1)).sum(dim=1) / tmpMask.sum(dim=1).unsqueeze(-1)
textFea = self.learnable['textFC'](textFea)
return textFea
class VL_model(nn.Module):
def __init__(self, model_cfg):
super(VL_model, self).__init__()
self.model_cfg = model_cfg
self.learnable = nn.ModuleDict()
self.learnable['imgencoder'] = ImgLearnableEncoder(model_cfg)
self.learnable['imgencoder_mom'] = ImgLearnableEncoder(model_cfg)
self.learnable['textencoder'] = TextLearnableEncoder(model_cfg)
self.learnable['textencoder_mom'] = TextLearnableEncoder(model_cfg)
############ add new params in .yml config file
self.K = model_cfg.QUEUE_SIZE
self.m = model_cfg.MOMENTUM
self.T = model_cfg.TEMPERATURE
self.topk = model_cfg.TOPK
self.multi_label = False
# init the parameter of two models
self.init_param()
# create the img queue
self.register_buffer("img_queue", torch.randn(model_cfg.IMG_FEATURE_DIM, self.K))
self.img_queue = nn.functional.normalize(self.img_queue, dim=0)
self.register_buffer("img_queue_ptr", torch.zeros(1, dtype=torch.long)) # image queue points
# create the text queue
self.register_buffer("text_queue", torch.randn(model_cfg.IMG_FEATURE_DIM, self.K))
self.text_queue = nn.functional.normalize(self.text_queue, dim=0)
self.register_buffer("text_queue_ptr", torch.zeros(1, dtype=torch.long)) # text queue points
def init_param(self):
for param_q, param_k in zip(self.learnable['imgencoder'].parameters(), self.learnable['imgencoder_mom'].parameters()):
param_k.data.copy_(param_q.data) # initialize
param_k.requires_grad = False # not update by gradient
for param_q, param_k in zip(self.learnable['textencoder'].parameters(), self.learnable['textencoder_mom'].parameters()):
param_k.data.copy_(param_q.data) # initialize
param_k.requires_grad = False # not update by gradient
@torch.no_grad()
def _momentum_update_key_encoder(self):
"""
Momentum update of the key encoder for image modal
"""
for param_q, param_k in zip(self.learnable['imgencoder'].parameters(), self.learnable['imgencoder_mom'].parameters()):
param_k.data = param_k.data * self.m + param_q.data * (1. - self.m)
for param_q, param_k in zip(self.learnable['textencoder'].parameters(), self.learnable['textencoder_mom'].parameters()):
param_k.data = param_k.data * self.m + param_q.data * (1. - self.m)
@torch.no_grad()
def _dequeue_and_enqueue(self, keys, option='img'):
# option in
# gather keys before updating queue
keys = concat_all_gather(keys)
batch_size = keys.shape[0]
if option == 'img':
ptr = int(self.img_queue_ptr)
assert self.K % batch_size == 0 # for simplicity
# replace the keys at ptr (dequeue and enqueue)
self.img_queue[:, ptr:ptr + batch_size] = keys.T
ptr = (ptr + batch_size) % self.K # move pointer
self.img_queue_ptr[0] = ptr
else:
ptr = int(self.text_queue_ptr)
assert self.K % batch_size == 0 # for simplicity
# replace the keys at ptr (dequeue and enqueue)
self.text_queue[:, ptr:ptr + batch_size] = keys.T
ptr = (ptr + batch_size) % self.K # move pointer
self.text_queue_ptr[0] = ptr
@torch.no_grad()
def _batch_shuffle_ddp(self, x, x_mask):
"""
Batch shuffle, for making use of BatchNorm.
*** Only support DistributedDataParallel (DDP) model. ***
"""
# gather from all gpus
batch_size_this = x.shape[0]
x_gather = concat_all_gather(x)
x_mask_gather = concat_all_gather(x_mask)
batch_size_all = x_gather.shape[0]
num_gpus = batch_size_all // batch_size_this
# random shuffle index
idx_shuffle = torch.randperm(batch_size_all).cuda()
# broadcast to all gpus
torch.distributed.broadcast(idx_shuffle, src=0)
# index for restoring
idx_unshuffle = torch.argsort(idx_shuffle)
# shuffled index for this gpu
gpu_idx = torch.distributed.get_rank()
idx_this = idx_shuffle.view(num_gpus, -1)[gpu_idx]
return x_gather[idx_this], x_mask_gather[idx_this], idx_unshuffle
@torch.no_grad()
def _batch_unshuffle_ddp(self, x, x_mask, idx_unshuffle):
"""
Undo batch shuffle.
*** Only support DistributedDataParallel (DDP) model. ***
"""
# gather from all gpus
batch_size_this = x.shape[0]
x_gather = concat_all_gather(x)
x_mask_gather = concat_all_gather(x_mask)
batch_size_all = x_gather.shape[0]
num_gpus = batch_size_all // batch_size_this
# restored index for this gpu
gpu_idx = torch.distributed.get_rank()
idx_this = idx_unshuffle.view(num_gpus, -1)[gpu_idx]
return x_gather[idx_this], x_mask_gather[idx_this]
def forward(self, imgFea, texts, maskImages, maskTexts, text_lens, image_boxs, is_training=True):
if self.model_cfg.IS_EXTRACT:
return self.extract(imgFea, texts, maskImages, maskTexts, image_boxs)
batch_size = imgFea.size(0)
imgFea_q = self.learnable['imgencoder'](imgFea, maskImages, image_boxs) # <bsz, img_dim>
imgFea_q = F.normalize(imgFea_q, p=2, dim=-1)
textFea_q = self.learnable['textencoder'](texts, maskTexts) # <bsz, img_dim>
textFea_q = F.normalize(textFea_q, p=2, dim=-1)
# compute key features
with torch.no_grad(): # no gradient to keys
self._momentum_update_key_encoder() # update the key encoder
# shuffle for making use of BN
imgFea, image_boxs, idx_unshuffle = self._batch_shuffle_ddp(imgFea, image_boxs)
imgFea_k = self.learnable['imgencoder_mom'](imgFea, maskImages, image_boxs) # <bsz, img_dim>
imgFea_k = F.normalize(imgFea_k, p=2, dim=-1)
# undo shuffle
imgFea_k, image_boxs = self._batch_unshuffle_ddp(imgFea_k, image_boxs, idx_unshuffle)
# shuffle for making use of BN
texts, maskTexts, idx_unshuffle = self._batch_shuffle_ddp(texts, maskTexts)
textFea_k = self.learnable['textencoder_mom'](texts, maskTexts) # <bsz, img_dim>
textFea_k = F.normalize(textFea_k, p=2, dim=-1)
# undo shuffle
textFea_k, maskTexts = self._batch_unshuffle_ddp(textFea_k, maskTexts, idx_unshuffle)
# compute logits for image -> text
# positive logits: Nx1
i2t_l_pos = torch.einsum('nc,nc->n', [imgFea_q, textFea_k]).unsqueeze(-1)
# negative logits: NxK
i2t_l_neg = torch.einsum('nc,ck->nk', [imgFea_q, self.text_queue.clone().detach()])
# logits: Nx(1+K)
i2t_logits = torch.cat([i2t_l_pos, i2t_l_neg], dim=-1)
i2t_logits /= self.T
# compute logits for text -> image
# positive logits: Nx1
t2i_l_pos = torch.einsum('nc,nc->n', [textFea_q, imgFea_k]).unsqueeze(-1)
# negative logits: NxK
t2i_l_neg = torch.einsum('nc,ck->nk', [textFea_q, self.img_queue.clone().detach()])
# logits: Nx(1+K)
t2i_logits = torch.cat([t2i_l_pos, t2i_l_neg], dim=-1)
t2i_logits /= self.T
### multi-label
mask = torch.zeros((batch_size, self.K)).bool().cuda() # <B, K>
if self.multi_label:
mask_sim_txt = textFea_k.matmul(self.text_queue.clone().detach()) # <B, dim> <dim, K> -> <B, K>
mask_sim_img = imgFea_k.matmul(self.img_queue.clone().detach())
_, topkidx_txt = torch.topk(mask_sim_txt, self.topk, dim=1) # <B, topk>
_, topkidx_img = torch.topk(mask_sim_img, self.topk, dim=1) # <B, topk>
topk_onehot_txt = torch.zeros_like(mask_sim_txt) # <B, K>
topk_onehot_txt.scatter_(1, topkidx_txt, 1) # one hot vector
topk_onehot_img = torch.zeros_like(mask_sim_img) # <B, K>
topk_onehot_img.scatter_(1, topkidx_img, 1) # one hot vector
mask[topk_onehot_txt.bool() & topk_onehot_img.bool()] = True # <B, K>
mask = torch.cat([torch.ones((batch_size, 1), dtype=torch.long, device=mask.device).bool(),
mask], dim=1) # <B, K+1>
### multi-label
t2i_loss = -1 * F.log_softmax(t2i_logits, dim=1) # <B, 1+K>
t2i_loss = torch.masked_select(t2i_loss, mask).sum() / batch_size # masked_select return 1-d tensor
i2t_loss = -1 * F.log_softmax(i2t_logits, dim=1)
i2t_loss = torch.masked_select(i2t_loss, mask).sum() / batch_size # masked_select return 1-d tensor
loss = t2i_loss + i2t_loss
## enqueue and dequeue
self._dequeue_and_enqueue(imgFea_k, option='img')
self._dequeue_and_enqueue(textFea_k, option='text')
return loss
def extract(self, | |
<gh_stars>10-100
import unittest
import sys
import inspect
from unittest.mock import Mock
from io import StringIO
from math import ceil
from damage import Damage
from classes import Paladin
from spells import PaladinSpell
from models.spells.loader import load_paladin_spells_for_level
class PaladinTests(unittest.TestCase):
def setUp(self):
self.name = "Netherblood"
self.level = 3
self.dummy = Paladin(name=self.name, level=self.level, health=100, mana=100, strength=10)
def test_init(self):
""" The __init__ should load/save all the spells for the Paladin"""
spells = [spell for level in range(1,self.level+1) for spell in load_paladin_spells_for_level(level)]
self.assertNotEqual(len(self.dummy.learned_spells), 0)
for spell in spells:
self.assertIn(spell.name, self.dummy.learned_spells)
char_spell = self.dummy.learned_spells[spell.name]
# find the largest rank in our spells list (the char has the highest rank only)
max_rank = list(sorted(filter(lambda x: x.name == spell.name, spells), key=lambda x: x.rank))[-1].rank
self.assertEqual(char_spell.rank, max_rank)
def test_leave_combat(self):
"""
Except the normal behaviour, leave_combat should remove the SOR buff from the pally
and reset his spell cds
"""
self.dummy._in_combat = True
self.dummy.SOR_ACTIVE = True
for spell in self.dummy.learned_spells.values():
spell._cooldown_counter = 100
self.assertTrue(self.dummy.is_in_combat())
self.dummy.leave_combat()
self.assertFalse(self.dummy.is_in_combat())
self.assertFalse(self.dummy.SOR_ACTIVE)
# All cooldowns should be reset
self.assertTrue(all([spell._cooldown_counter == 0 for spell in self.dummy.learned_spells.values()]))
def test_reset_spell_cooldowns(self):
""" The reset_spell_cooldowns goes through every spell and resets its CD"""
for spell in self.dummy.learned_spells.values():
spell._cooldown_counter = 100
self.assertTrue(all([spell._cooldown_counter != 0 for spell in self.dummy.learned_spells.values()]))
self.dummy.reset_spell_cooldowns()
self.assertTrue(all([spell._cooldown_counter == 0 for spell in self.dummy.learned_spells.values()]))
def test_level_up(self):
""" Except the normal behaviour, it should learn new spells for the character """
# empty the learned spells, it's stored as a static variable, which is not good practice but doesn't hurt in the game
Paladin.learned_spells = {}
pl = Paladin(name="fuck a nine to five")
spells_to_learn = [spell.name for spell in load_paladin_spells_for_level(pl.level + 1)]
for spell in spells_to_learn:
self.assertNotIn(spell, pl.learned_spells)
pl._level_up()
for spell in spells_to_learn:
self.assertIn(spell, pl.learned_spells)
def test_level_up_to_level(self):
""" Except the normal behaviour, it should learn new spells for the character """
# empty the learned spells, it's stored as a static variable, which is not good practice but doesn't hurt in the game
Paladin.learned_spells = {}
pl = Paladin(name="fuck a nine to five")
to_level = 4
spells_to_learn = [spell for level in range(2, to_level + 1) for spell in load_paladin_spells_for_level(level)]
for spell in spells_to_learn:
has_not_learned_spell = spell.name not in pl.learned_spells
has_smaller_rank = spell.rank > pl.learned_spells[spell.name].rank if not has_not_learned_spell else False
self.assertTrue(has_not_learned_spell or has_smaller_rank)
pl._level_up(to_level=to_level)
for spell in spells_to_learn:
self.assertIn(spell.name, pl.learned_spells)
def test_lookup_and_handle_new_spells(self):
""" Should look up the available spells for our level and learn them or update our existing ones"""
Paladin.learned_spells = {}
pl = Paladin(name="fuck a nine to five")
print(pl.learned_spells)
pl.level = 3
spells_to_learn = [spell for spell in load_paladin_spells_for_level(pl.level)]
for spell in spells_to_learn:
has_not_learned_spell = spell.name not in pl.learned_spells
has_smaller_rank = spell.rank > pl.learned_spells[spell.name].rank if not has_not_learned_spell else False
self.assertTrue(has_not_learned_spell or has_smaller_rank)
pl._lookup_and_handle_new_spells()
for spell in spells_to_learn:
self.assertIn(spell.name, pl.learned_spells)
def test_learn_new_spell(self):
""" Given a PaladinSpell, add it to the learned_spells dictionary"""
spell = PaladinSpell(name="Too_Alive", rank=5)
expected_message = f'You have learned a new spell - {spell.name}'
self.assertNotIn(spell.name, self.dummy.learned_spells)
try:
output = StringIO()
sys.stdout = output
self.dummy.learn_new_spell(spell)
self.assertIn(expected_message, output.getvalue())
finally:
sys.stdout = sys.__stdout__
self.assertIn(spell.name, self.dummy.learned_spells)
def test_lookup_available_spells_to_learn(self):
""" It's a generator function returning a spell that can be learnt for the level """
lev = 3
expected_spells = load_paladin_spells_for_level(lev)
generator = self.dummy._lookup_available_spells_to_learn(lev)
self.assertTrue(inspect.isgenerator(generator))
for spell in expected_spells:
self.assertEqual(vars(next(generator)), vars(spell))
def test_update_spell(self):
""" The update_spell() function updates a spell we already have learned"""
f_spell = PaladinSpell('Spell', rank=1)
s_spell = PaladinSpell('Spell', rank=2)
expected_message = f'Spell {f_spell.name} has been updated to rank {s_spell.rank}!'
self.dummy.learn_new_spell(f_spell)
try:
output = StringIO()
sys.stdout = output
self.dummy.update_spell(s_spell)
self.assertIn(expected_message, output.getvalue())
finally:
sys.stdout = sys.__stdout__
# assert that it updated the rank
self.assertEqual(self.dummy.learned_spells[s_spell.name].rank, s_spell.rank)
self.assertGreater(self.dummy.learned_spells[s_spell.name].rank, f_spell.rank)
def test_spell_handler_sor(self):
"""
The spell handler takes spell names and casts the appropriate function
It might work in a bad way since it's not too testable
"""
unsuccessful_message = 'Unsuccessful cast'
sor_success_msg = 'SOR_CASTED'
sor_command_name = 'sor'
# Mock the function that should get called
self.dummy.spell_seal_of_righteousness = lambda x: sor_success_msg
try:
output = StringIO()
sys.stdout = output
result = self.dummy.spell_handler(sor_command_name, None)
self.assertNotIn(unsuccessful_message, output.getvalue())
finally:
sys.stdout = sys.__stdout__
# Assert that it called the spell_seal_of_righteousness function
self.assertEqual(result, sor_success_msg)
def test_spell_handler_fol(self):
unsuccessful_message = 'Unsuccessful cast'
fol_success_msg = 'FOL_CASTED'
fol_command_name = 'fol'
# Mock the function that should get called
self.dummy.spell_flash_of_light = lambda x: fol_success_msg
try:
output = StringIO()
sys.stdout = output
result = self.dummy.spell_handler(fol_command_name, None)
self.assertNotIn(unsuccessful_message, output.getvalue())
finally:
sys.stdout = sys.__stdout__
# Assert that it called the spell_seal_of_righteousness function
self.assertEqual(result, fol_success_msg)
def test_spell_handler_ms(self):
unsuccessful_message = 'Unsuccessful cast'
ms_success_msg = 'MS_CASTED'
ms_command_name = 'ms'
# Mock the function that should get called
self.dummy.spell_melting_strike = lambda target=None, spell=None: ms_success_msg
try:
output = StringIO()
sys.stdout = output
result = self.dummy.spell_handler(ms_command_name, None)
self.assertNotIn(unsuccessful_message, output.getvalue())
finally:
sys.stdout = sys.__stdout__
# Assert that it called the spell_seal_of_righteousness function
self.assertEqual(result, ms_success_msg)
def test_spell_handler_invalid_spell(self):
unsuccessful_message = 'Unsuccessful cast'
invalid_command = 'WooHoo'
try:
output = StringIO()
sys.stdout = output
result = self.dummy.spell_handler(invalid_command, None)
self.assertIn(unsuccessful_message, output.getvalue())
finally:
sys.stdout = sys.__stdout__
self.assertFalse(result)
def test_spell_seal_of_righteousness(self):
sor: PaladinSpell = self.dummy.learned_spells[Paladin.KEY_SEAL_OF_RIGHTEOUSNESS]
expected_message = f'{self.dummy.name} activates {Paladin.KEY_SEAL_OF_RIGHTEOUSNESS}!'
expected_mana = self.dummy.mana - sor.mana_cost
self.assertFalse(self.dummy.SOR_ACTIVE)
self.assertEqual(self.dummy.SOR_TURNS, 0)
try:
output = StringIO()
sys.stdout = output
self.dummy.spell_seal_of_righteousness(sor)
self.assertIn(expected_message, output.getvalue())
finally:
sys.stdout = sys.__stdout__
self.assertTrue(self.dummy.SOR_ACTIVE)
self.assertEqual(self.dummy.SOR_TURNS, 3)
self.assertEqual(self.dummy.mana, expected_mana)
def test_spell_seal_of_righteousness_attack(self):
sor: PaladinSpell = self.dummy.learned_spells[Paladin.KEY_SEAL_OF_RIGHTEOUSNESS]
expected_damage = sor.damage1
self.dummy.spell_seal_of_righteousness(sor)
self.assertTrue(self.dummy.SOR_ACTIVE)
self.assertEqual(self.dummy.SOR_TURNS, 3)
result = self.dummy._spell_seal_of_righteousness_attack()
self.assertEqual(result, expected_damage)
self.assertEqual(self.dummy.SOR_TURNS, 2)
def test_spell_seal_of_righteousness_attack_fade(self):
sor: PaladinSpell = self.dummy.learned_spells[Paladin.KEY_SEAL_OF_RIGHTEOUSNESS]
expected_message = f'{Paladin.KEY_SEAL_OF_RIGHTEOUSNESS} has faded from {self.dummy.name}'
self.dummy.spell_seal_of_righteousness(sor)
self.assertTrue(self.dummy.SOR_ACTIVE)
self.dummy.SOR_TURNS = 1
self.dummy._spell_seal_of_righteousness_attack()
self.assertEqual(self.dummy.SOR_TURNS, 0)
self.assertTrue(self.dummy.SOR_ACTIVE)
# Should fade now and not do any damage on turn end
try:
output = StringIO()
sys.stdout = output
self.dummy.end_turn_update()
self.assertIn(expected_message, output.getvalue())
finally:
sys.stdout = sys.__stdout__
self.assertFalse(self.dummy.SOR_ACTIVE)
def test_spell_flash_of_light(self):
import heal
# Nullify the chance to double heal for consistent testing
heal.DOUBLE_HEAL_CHANCE = 0
fol: PaladinSpell = self.dummy.learned_spells[Paladin.KEY_FLASH_OF_LIGHT]
expected_message = f'{self.dummy.name} activates {Paladin.KEY_FLASH_OF_LIGHT}!'
expected_mana = self.dummy.mana - fol.mana_cost
orig_health = 1
self.dummy.health = orig_health
expected_message = f'{fol.name} healed {self.dummy.name} for {fol.heal1}.'
try:
output = StringIO()
sys.stdout = output
self.dummy.spell_flash_of_light(fol)
self.assertIn(expected_message, output.getvalue())
finally:
sys.stdout = sys.__stdout__
self.assertEqual(self.dummy.mana, expected_mana)
self.assertEqual(self.dummy.health, orig_health + fol.heal1)
def test_spell_flash_of_light_overheal(self):
import heal
# Nullify the chance to double heal for consistent testing
heal.DOUBLE_HEAL_CHANCE = 0
fol: PaladinSpell = self.dummy.learned_spells[Paladin.KEY_FLASH_OF_LIGHT]
expected_message = f'{fol.name} healed {self.dummy.name} for 0.00 ({fol.heal1:.2f} Overheal).'
expected_mana = self.dummy.mana - fol.mana_cost
orig_health = self.dummy.health
self.dummy.health = orig_health
try:
output = StringIO()
sys.stdout = output
self.dummy.spell_flash_of_light(fol)
self.assertIn(expected_message, output.getvalue())
finally:
sys.stdout = sys.__stdout__
self.assertEqual(self.dummy.mana, expected_mana)
self.assertEqual(self.dummy.health, orig_health) # should have only overhealed
def test_spell_melting_strike(self):
ms: PaladinSpell = self.dummy.learned_spells[Paladin.KEY_MELTING_STRIKE]
expected_mana = self.dummy.mana - ms.mana_cost
expected_message2 = 'Took attack'
expected_message3 = 'Took buff'
take_attack = lambda x, y: print('Took attack')
add_buff = lambda x: print('Took buff')
target = Mock(name="All",
take_attack=take_attack,
add_buff=add_buff)
expected_message = f'{ms.name} damages {target.name} for {ms.damage1:.2f} physical damage!'
try:
output = StringIO()
sys.stdout = output
result = self.dummy.spell_melting_strike(ms, target)
self.assertIn(expected_message, output.getvalue())
self.assertIn(expected_message2, output.getvalue())
self.assertIn(expected_message3, output.getvalue())
finally:
sys.stdout = sys.__stdout__
self.assertTrue(result)
self.assertEqual(expected_mana, self.dummy.mana)
def test_get_auto_attack_damage(self):
""" Applies damage reduction in regard to level and adds the sor_damage
It attaches the sor_damage to the magic_dmg in the Damage class and
returns the sor_dmg explicitly for easy printing"""
sor: PaladinSpell = self.dummy.learned_spells[Paladin.KEY_SEAL_OF_RIGHTEOUSNESS]
self.dummy.spell_seal_of_righteousness(sor)
received_dmg, sor_dmg = self.dummy.get_auto_attack_damage(self.dummy.level)
self.assertTrue(isinstance(received_dmg, Damage))
self.assertTrue(self.dummy.min_damage <= received_dmg.phys_dmg <= self.dummy.max_damage)
self.assertEqual(received_dmg.magic_dmg, sor.damage1)
self.assertEqual(sor_dmg, sor.damage1)
def test_get_auto_attack_damage_higher_level(self):
""" Applies damage reduction in regard to level and adds the sor_damage
It attaches the sor_damage to the magic_dmg in the Damage class and
returns the sor_dmg explicitly for easy printing"""
sor: PaladinSpell = self.dummy.learned_spells[Paladin.KEY_SEAL_OF_RIGHTEOUSNESS]
level_diff = 2
prc_mod = (level_diff * 0.1)
level = self.dummy.level + level_diff
expected_sor_dg = sor.damage1 - (sor.damage1 * prc_mod)
expected_min_dmg = int(self.dummy.min_damage) - (self.dummy.min_damage * prc_mod)
expected_max_dmg = int(self.dummy.max_damage) - (self.dummy.max_damage * prc_mod)
self.dummy.spell_seal_of_righteousness(sor)
received_dmg, sor_dmg = self.dummy.get_auto_attack_damage(level)
self.assertTrue(isinstance(received_dmg, Damage))
self.assertTrue(expected_min_dmg <= received_dmg.phys_dmg <= expected_max_dmg)
self.assertEqual(received_dmg.magic_dmg, expected_sor_dg)
self.assertEqual(sor_dmg, expected_sor_dg)
def test_attack(self):
expected_message2 = 'Took Attack!'
expected_message3 = 'Get_take_attack_damage_repr called!'
victim = Mock(level=self.dummy.level, take_attack=lambda x, y: print(expected_message2),
get_take_attack_damage_repr=lambda x,y: print(expected_message3))
expected_message = f'{self.dummy.name} attacks {victim.name}'
try:
output = StringIO()
sys.stdout = output
self.dummy.attack(victim)
self.assertIn(expected_message, output.getvalue())
self.assertIn(expected_message2, output.getvalue())
self.assertIn(expected_message3, output.getvalue())
finally:
sys.stdout = sys.__stdout__
def test_get_class(self):
""" get_class() returns the class name as a string in lowercase """
expected_result = 'paladin'
self.assertEqual(self.dummy.get_class(), expected_result)
if __name__ | |
<reponame>rashecl/COVID_Inisghts<filename>US_coronavirus_map.py<gh_stars>0
import matplotlib
matplotlib.use('Agg')
import numpy as np
from bokeh.io import show
from bokeh.layouts import column, row
from bokeh.io import curdoc
from bokeh.models import LogColorMapper, LinearColorMapper, ColorBar, ColumnDataSource, LogTicker, RadioGroup, Div
from bokeh.models import WheelZoomTool, TapTool, SaveTool, ResetTool, PanTool, HoverTool, Range1d, BoxZoomTool, \
FuncTickFormatter
from bokeh.models import TickFormatter
from bokeh.palettes import RdYlBu10 as palette, all_palettes
from bokeh.plotting import figure
from COVID.extract import COVID_counts
import pandas as pd
import pickle
[stateBorders, countyBorders] = pickle.load(open("./COVID/extract/regionBorders.p", "rb"))
[usPopulation, statePopulations, countyPopulations] = pickle.load(open("./COVID/extract/regionPopulations.p", "rb"))
[countyDF, stateDF_NYT, stateDF_CT, usDF_NYT, usDF_CT, lastUpdated] = pickle.load(
open("./COVID/extract/CovidCounts.p", "rb"))
print(lastUpdated)
# palette = tuple(palette)
palette = tuple([all_palettes['Turbo'][256][idx] for idx in range(50, 256)])
# color_mapper = LinearColorMapper(palette=palette)
color_mapper = LogColorMapper(palette=palette, low=1, high=200000)
us_TOOLS = [BoxZoomTool(), PanTool(), WheelZoomTool(), TapTool(), HoverTool(), ResetTool()]
state_TOOLS = [BoxZoomTool(), PanTool(), WheelZoomTool(), TapTool(), HoverTool(), ResetTool()]
cumul_TOOLS = [BoxZoomTool(), PanTool(), WheelZoomTool(), ResetTool(), SaveTool()]
daily_TOOLS = [BoxZoomTool(), PanTool(), WheelZoomTool(), ResetTool(), SaveTool()]
cumulCritical_TOOLS = [BoxZoomTool(), PanTool(), WheelZoomTool(), ResetTool(), SaveTool()]
dailyCritical_TOOLS = [BoxZoomTool(), PanTool(), WheelZoomTool(), ResetTool(), SaveTool()]
dailyDeath_TOOLS = [BoxZoomTool(), PanTool(), WheelZoomTool(), ResetTool(), SaveTool()]
colorBySelector = RadioGroup(labels=["positive", "death", "totalTestResults",
"hospitalizedCurrently", 'inIcuCurrently'], active=0)
# A) Define data and plot structures
# 1) Map of US
usData = ColumnDataSource(data=dict(x=[], y=[], cases=[], state=[]))
usPlot = figure(title="Cases of Coronavirus", tools=us_TOOLS,
x_axis_location=None, y_axis_location=None,
tooltips=[("Current cases", "@cases{(0.00 a)}"), ('State', '@state')],
width=60 * 15, height=27 * 15)
usPlot.grid.grid_line_color = None
usPlot.x_range = Range1d(-125, -65, bounds=(-145, -45))
usPlot.y_range = Range1d(23, 50, bounds=(13, 60))
usPlot.hover.point_policy = "follow_mouse"
# usPlot.image_url(url=['https://www.your-vector-maps.com/_kepek/_grey_images/USA-mercator-vector-map.jpg'], x=-126.5, y=51.2, w=61, h=30)
usPlot.patches('x', 'y', source=usData,
fill_color={'field': 'cases', 'transform': color_mapper},
fill_alpha=0.7, line_color="white", line_width=0.5)
usPlot.toolbar.active_drag = us_TOOLS[0]
tick_labels = {'0': '0', '1': '1', '10': '10',
'100': '100', '1000': '1000',
'10000': '10,000', '100000': '100,000', '1,000,000': '1,000,000'}
us_color_bar = ColorBar(color_mapper=color_mapper, ticker=LogTicker(),
label_standoff=12, border_line_color=None, orientation='horizontal', location=(0, 0),
major_label_overrides=tick_labels)
usPlot.add_layout(us_color_bar, 'below')
# usColorBar.right[0].formatter.use_scientific = False
# 2) Map of state
stateData = ColumnDataSource(data={'x': [], 'y': [], 'name': [], 'cases': [], 'state': []})
statePlot = figure(title="State map", tools=state_TOOLS,
x_axis_location=None, y_axis_location=None,
tooltips=[('Name', '@name'), ("Current cases", "@cases{(0,00)}"), ('State', '@state')],
height=405, width=405)
statePlot.toolbar.active_drag = state_TOOLS[0]
statePlot.grid.grid_line_color = None
statePlot.hover.point_policy = "follow_mouse"
statePlot.patches('x', 'y', source=stateData,
fill_color={'field': 'cases', 'transform': color_mapper},
fill_alpha=0.7, line_color="white", line_width=0.5)
# 3,4) Cumulative temporal graphs (tests, positive):
cumulativeData_CT = ColumnDataSource(data=dict(time=[], total_positive=[], total_testResults=[],
total_hospitalized=[], total_ICU=[], total_deaths=[], source=[]))
cumulativeData_NYT = ColumnDataSource(data=dict(time=[], total_positive=[], total_deaths=[], source=[]))
cumulPlot = figure(tools=cumul_TOOLS, x_axis_type='datetime', width=650, height=250)
cumulPlot.left[0].formatter.use_scientific = False
total_positive_CT = cumulPlot.line('time', 'total_positive', source=cumulativeData_CT, line_color='blue', line_width=2,
legend_label='positive_CT')
total_positive_NYT = cumulPlot.line('time', 'total_positive', source=cumulativeData_NYT, line_color='lightblue',
line_width=2,
legend_label='positive_NYT')
total_testResults = cumulPlot.line('time', 'total_testResults', source=cumulativeData_CT, line_color='green',
line_width=2,
legend_label='total_testResults')
# total_positive_NYT.visible = False
cumulPlot.yaxis.axis_label = '# of people'
# cumulPlot.yaxis.formatter = FuncTickFormatter(code="""
# parts = tick.toString().split(".");
# parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
# return parts.join(".");
# """)
cumulPlot.xaxis.axis_label = 'Date'
cumulPlot.legend.location = "top_left"
cumulPlot.legend.click_policy = "hide"
cumulPlot.add_tools(
HoverTool(renderers=[total_positive_CT],
tooltips=[("total_positive", "@total_positive{(0,00)}"), ("date", "@time{%F}")],
formatters={'@time': 'datetime'})
)
cumulPlot.add_tools(
HoverTool(renderers=[total_positive_NYT],
tooltips=[("total_positive", "@total_positive{(0,00)}"), ("date", "@time{%F}")],
formatters={'@time': 'datetime'})
)
cumulPlot.add_tools(
HoverTool(renderers=[total_testResults],
tooltips=[("total_testResults", "@total_testResults{(0,00)}"), ("date", "@time{%F}")],
formatters={'@time': 'datetime'})
)
# 4) Cumulative critical cases (deaths for now):
cumulCriticalPlot = figure(tools=cumulCritical_TOOLS, x_axis_type='datetime', width=650, height=250,
x_range=cumulPlot.x_range)
cumulCriticalPlot.left[0].formatter.use_scientific = False
total_deaths_CT = cumulCriticalPlot.line('time', 'total_deaths', source=cumulativeData_CT, line_color='red',
line_width=2,
legend_label='totalDeaths_CT')
total_deaths_NYT = cumulCriticalPlot.line('time', 'total_deaths', source=cumulativeData_NYT, line_color='magenta',
line_width=2, legend_label='totalDeaths_NYT')
# total_deaths_NYT.visible = False
cumulCriticalPlot.yaxis.axis_label = '# of people'
# cumulCriticalPlot.yaxis.formatter= FuncTickFormatter(code="""
# parts = tick.toString().split(".");
# parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
# return parts.join(".");
# """)
cumulCriticalPlot.xaxis.axis_label = 'Date'
cumulCriticalPlot.legend.location = "top_left"
cumulCriticalPlot.legend.click_policy = "hide"
cumulCriticalPlot.add_tools(
HoverTool(renderers=[total_deaths_CT], tooltips=[("total_deaths", "@total_deaths{(0,00)}"), ("date", "@time{%F}")],
formatters={'@time': 'datetime'})
)
cumulCriticalPlot.add_tools(
HoverTool(renderers=[total_deaths_NYT], tooltips=[("total_deaths", "@total_deaths{(0,00)}"), ("date", "@time{%F}")],
formatters={'@time': 'datetime'})
)
# 5-7) Daily temporal graphs:
dailyData_CT = ColumnDataSource(data=dict(time=[], new_positive=[], new_testResults=[],
current_hospitalized=[], current_ICU=[], new_deaths=[], source=[]))
dailyData_NYT = ColumnDataSource(data=dict(time=[], new_positive=[], new_deaths=[], source=[]))
dailyPlot = figure(tools=daily_TOOLS, x_axis_type='datetime', width=650, height=250, title="Daily statistics",
x_range=cumulPlot.x_range)
dailyPlot.left[0].formatter.use_scientific = False
new_positive_CT = dailyPlot.line('time', 'new_positive', source=dailyData_CT, line_color='blue', line_width=2,
legend_label='new_positive_CT')
new_testResults = dailyPlot.line('time', 'new_testResults', source=dailyData_CT, line_color='green', line_width=2,
legend_label='new_testResults')
new_positive_NYT = dailyPlot.line('time', 'new_positive', source=dailyData_NYT, line_color='lightblue', line_width=2,
legend_label='new_positive_NYT')
# new_positive_NYT.visible = False
dailyPlot.add_tools(
HoverTool(renderers=[new_positive_CT], tooltips=[("new_positive", "@new_positive{(0,00)}"), ("date", "@time{%F}")],
formatters={'@time': 'datetime'})
)
dailyPlot.add_tools(
HoverTool(renderers=[new_testResults], tooltips=[("new_testResults", "@new_testResults{(0,00)}"), ("date", "@time{%F}")],
formatters={'@time': 'datetime'})
)
dailyPlot.add_tools(
HoverTool(renderers=[new_positive_NYT], tooltips=[("new_positive", "@new_positive{(0,00)}"), ("date", "@time{%F}")],
formatters={'@time': 'datetime'})
)
dailyPlot.toolbar.active_drag = daily_TOOLS[1]
dailyPlot.yaxis.axis_label = '# of people'
# dailyPlot.yaxis.formatter = formatter = FuncTickFormatter(code="""
# parts = tick.toString().split(".");
# parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
# return parts.join(".");
# """)
dailyPlot.xaxis.axis_label = 'Date'
dailyPlot.legend.location = "top_left"
dailyPlot.legend.click_policy = "hide"
# 7 Daily death graph:
dailyDeathPlot = figure(tools=dailyCritical_TOOLS, x_axis_type='datetime', width=650, height=250,
title="Daily death statistics", x_range=cumulPlot.x_range)
dailyDeathPlot.left[0].formatter.use_scientific = False
new_deaths_CT = dailyDeathPlot.line('time', 'new_deaths', source=dailyData_CT, line_color='black', line_width=2,
legend_label='new_deaths_CT')
new_deaths_NYT = dailyDeathPlot.line('time', 'new_deaths', source=dailyData_NYT, line_color='grey', line_width=2,
legend_label='new_deaths_NYT')
# new_deaths_NYT.visible = False
dailyDeathPlot.add_tools(
HoverTool(renderers=[new_deaths_CT], tooltips=[("new_deaths", "@new_deaths{(0,00)}"), ("date", "@time{%F}")],
formatters={'@time': 'datetime'})
)
dailyDeathPlot.add_tools(
HoverTool(renderers=[new_deaths_NYT], tooltips=[("new_deaths", "@new_deaths{(0,00)}"), ("date", "@time{%F}")],
formatters={'@time': 'datetime'})
)
dailyDeathPlot.toolbar.active_drag = dailyDeath_TOOLS[1]
dailyDeathPlot.yaxis.axis_label = '# of people'
# dailyDeathPlot.yaxis.formatter = FuncTickFormatter(code="""
# parts = tick.toString().split(".");
# parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
# return parts.join(".");
# """)
dailyDeathPlot.xaxis.axis_label = 'Date'
dailyDeathPlot.legend.location = "top_left"
dailyDeathPlot.legend.click_policy = "hide"
# 7) dailyCritical plot:
dailyCriticalPlot = figure(tools=dailyCritical_TOOLS, x_axis_type='datetime', width=650, height=250,
title="*Daily hospitalization statistics", x_range=cumulPlot.x_range)
dailyCriticalPlot.left[0].formatter.use_scientific = False
current_hospitalized = dailyCriticalPlot.line('time', 'current_hospitalized', source=dailyData_CT, line_color='orange',
line_width=2, legend_label='current_hospitalized')
current_ICU = dailyCriticalPlot.line('time', 'current_ICU', source=dailyData_CT, line_color='red', line_width=2,
legend_label='current_ICU')
# new_deaths_NYT.visible = False
dailyCriticalPlot.add_tools(HoverTool(renderers=[current_hospitalized],
tooltips=[("current_hospitalized", "@current_hospitalized{(0,00)}"), ("date", "@time{%F}")],
formatters={'@time': 'datetime'})
)
dailyCriticalPlot.add_tools(
HoverTool(renderers=[current_ICU], tooltips=[("current_ICU", "@current_ICU{(0,00)}"), ("date", "@time{%F}")],
formatters={'@time': 'datetime'})
)
dailyCriticalPlot.toolbar.active_drag = dailyCritical_TOOLS[1]
dailyCriticalPlot.yaxis.axis_label = '# of people'
# dailyCriticalPlot.yaxis.formatter = FuncTickFormatter(code="""
# parts = tick.toString().split(".");
# parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
# return parts.join(".");
# """)
dailyCriticalPlot.xaxis.axis_label = 'Date'
dailyCriticalPlot.legend.location = "top_left"
dailyCriticalPlot.legend.click_policy = "hide"
print("Completed defining plot structures")
# B) Define the actual data for the plots:
# 1) Define data for US map plot:
state_xs = [stateBorders[state]["lons"] for state in stateBorders if state]
state_ys = [stateBorders[state]["lats"] for state in stateBorders if state]
state_names = [stateBorders[state]["name"] for state in stateBorders]
state_val = []
for state in stateBorders:
if (state in list(stateDF_CT.state.unique())):
state_val.append(stateDF_CT.query("state == '" + state + "'")['positive'].iloc[-1]) # latest positive
else:
print(state + ' does not have any records of cases')
state_val.append(0)
usData.data = dict(x=state_xs, y=state_ys, cases=state_val, state=state_names)
print("Completed defining data")
# 2) Define function on selection of new state:
def updateState():
global countyDF, state, stateCountyDF, stateBorders
print(state)
stateCountyDF = countyDF.query("state == '" + state + "'")
stateCountyBorders = countyBorders[countyBorders['state'] == state]
county_xs = [stateCountyBorders.iloc[i, :]['lons'] for i in range(len(stateCountyBorders))]
county_ys = [stateCountyBorders.iloc[i, :]['lats'] for i in range(len(stateCountyBorders))]
county_names = [stateCountyBorders.iloc[i, :]['county'] for i in range(len(stateCountyBorders))]
state_names = [state for i in range(len(stateCountyBorders))]
# county_val = [rand() for i in range(len(stateCounties))]
county_vals = []
for county in county_names:
if county in list(stateCountyDF['county'].unique()):
county_vals.append(
stateCountyDF[stateCountyDF['county'] == county].positive.values[-1]) # latest positive cases
else:
county_vals.append(0)
stateData.data = dict(
x=county_xs,
y=county_ys,
name=county_names,
cases=county_vals,
state=state_names)
# Set new limits and re-title state plot:
print('Setting limits: ' + state)
yrange = [np.nanmin(stateBorders[state]['lats']), np.nanmax(stateBorders[state]['lats'])]
xrange = [np.nanmin(stateBorders[state]['lons']), np.nanmax(stateBorders[state]['lons'])]
plotRange = np.diff(xrange)[0] if np.diff(xrange) > np.diff(yrange) else np.diff(yrange)[0]
# statePlot.x_range = Range1d((xrange[0] + plotRange/2) -.55*plotRange, (xrange[0] + plotRange/2) +.55*plotRange, bounds = ((xrange[0] + plotRange/2) -.55*plotRange, (xrange[0] + plotRange/2) +.55*plotRange))
statePlot.x_range.start = np.average(xrange) - .55 * plotRange
statePlot.x_range.end = np.average(xrange) + .55 * plotRange
# statePlot.y_range = Range1d((yrange[0] + plotRange/2) -.55*plotRange, (yrange[0] + plotRange/2) +.55*plotRange, bounds = ((yrange[0] + plotRange/2) -.55*plotRange, (yrange[0] + plotRange/2) +.55*plotRange))
statePlot.y_range.start = np.average(yrange) - .55 * plotRange
statePlot.y_range.end = np.average(yrange) + .55 * plotRange
state_name = stateBorders[state]['name']
cumulPlot.title.text = state_name + ': Cumulative testing data'
statePlot.title.text = state_name
cumulCriticalPlot.title.text = state_name + ': Cumulative deaths'
dailyPlot.title.text = state_name + ': Daily testing data'
dailyDeathPlot.title.text = state_name + ': Daily deaths'
dailyCriticalPlot.title.text = state_name + ': Daily hospitalization data*'
# Update stateData:
sourceStateData()
return
# 3) Define data for temporal graphs:
def sourceUSdata():
global usDF_CT
CTdf = usDF_CT
dailyData_CT.data = dict(
time=CTdf['date'],
# date=CTdf['date'].astype(str),
new_positive=CTdf['positiveIncrease'],
new_testResults=CTdf['totalTestResultsIncrease'],
current_hospitalized=CTdf['hospitalizedCurrently'],
current_ICU=CTdf['inIcuCurrently'],
new_deaths=CTdf['deathIncrease'],
source=CTdf['source'])
cumulativeData_CT.data = dict(
time=CTdf['date'],
# date=CTdf['date'].astype(str),
total_positive=CTdf['positive'],
total_testResults=CTdf['totalTestResults'],
total_hospitalized=CTdf['hospitalizedCumulative'],
total_ICU=CTdf['inIcuCumulative'],
total_deaths=CTdf['death'],
source=CTdf['source'])
NYTdf = usDF_NYT
dailyData_NYT.data = dict(
time=NYTdf['date'],
# date=NYTdf['date'].astype(str),
new_positive=NYTdf['positiveIncrease'],
new_deaths=NYTdf['deathIncrease'],
source=NYTdf['source'])
cumulativeData_NYT.data = dict(
time=NYTdf['date'],
# date=NYTdf['date'].astype(str),
total_positive=NYTdf['positive'],
total_deaths=NYTdf['death'],
source=NYTdf['source'])
cumulPlot.title.text = 'United States: Cumulative testing data'
cumulPlot.title.text = 'United States' + ': Cumulative testing data'
cumulCriticalPlot.title.text = 'United States' + ': Cumulative deaths'
dailyPlot.title.text = 'United States' + ': Daily testing data'
dailyDeathPlot.title.text = 'United States' + ': Daily deaths'
dailyCriticalPlot.title.text = 'United States' + ': Daily hospitalization data*'
return
def sourceStateData():
global stateCountyDF, county, state
# Update state level data:
CTdf = stateDF_CT.query("state == '" + state + "'")
dailyData_CT.data = dict(
time=CTdf['date'],
# date=CTdf['date'].astype(str),
new_positive=CTdf['positiveIncrease'],
new_testResults=CTdf['totalTestResultsIncrease'],
current_hospitalized=CTdf['hospitalizedCurrently'],
current_ICU=CTdf['inIcuCurrently'],
new_deaths=CTdf['deathIncrease'],
source=CTdf['source'])
cumulativeData_CT.data = dict(
time=CTdf['date'],
# date=CTdf['date'].astype(str),
total_positive=CTdf['positive'],
total_testResults=CTdf['totalTestResults'],
total_hospitalized=CTdf['hospitalizedCumulative'],
total_ICU=CTdf['inIcuCumulative'],
total_deaths=CTdf['death'],
source=CTdf['source'])
NYTdf = stateDF_NYT.query("state == '" + state + "'")
dailyData_NYT.data = dict(
time=NYTdf['date'],
# date=NYTdf['date'].astype(str),
new_positive=NYTdf['positiveIncrease'],
new_deaths=NYTdf['deathIncrease'],
source=NYTdf['source'])
cumulativeData_NYT.data = dict(
time=NYTdf['date'],
# date=NYTdf['date'].astype(str),
total_positive=NYTdf['positive'],
total_deaths=NYTdf['death'],
source=NYTdf['source'])
return
def sourceCountyData():
global stateCountyDF, county, state
NYTdf = stateCountyDF
dailyData_CT.data = dict(
time=[],
# date=[],
new_positive=[],
new_testResults=[],
current_hospitalized=[],
current_ICU=[],
new_deaths=[],
source=[])
cumulativeData_CT.data = dict(
time=[],
# date=[],
total_positive=[],
total_testResults=[],
total_hospitalized=[],
total_ICU=[],
total_deaths=[],
source=[])
dailyData_NYT.data = dict(
time=NYTdf['date'],
# date=NYTdf['date'].astype(str),
new_positive=NYTdf['positiveIncrease'],
new_deaths=NYTdf['deathIncrease'],
source=NYTdf['source'])
cumulativeData_NYT.data = dict(
time=NYTdf['date'],
# date=NYTdf['date'].astype(str),
total_positive=NYTdf['positive'],
total_deaths=NYTdf['death'],
source=NYTdf['source'])
cumulPlot.title.text = county + ': Cumulative data'
return
# C) Define interactivity functions
def us_tap_handler(attr, old, new):
global state
# index = new[0]
# print(attr)
# print([x for x in list(locals().keys()) if x[0] != '_'])
if len(new) == 0:
print('US')
sourceUSdata()
else:
state = stateBorders.columns[new[0]]
print(state)
updateState()
stateData.selected.indices | |
#!/usr/bin/env python
# This file is part of Diamond.
#
# Diamond is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Diamond is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Diamond. If not, see <http://www.gnu.org/licenses/>.
import base64
import bz2
import copy
import sys
import cStringIO
from lxml import etree
import debug
import choice
import plist
import preprocess
import tree
def memoise(f):
cache = {}
def memf(*x):
if x not in cache:
cache[x] = f(*x)
return cache[x]
return memf
##########################
# SCHEMA CLASS #
##########################
class Schema(object):
def __init__(self, schemafile):
p = etree.XMLParser(remove_comments=True)
self.tree = etree.parse(cStringIO.StringIO(preprocess.preprocess(schemafile)), p)
self.callbacks = {'element': self.cb_element,
'documentation': self.cb_documentation,
'value': self.cb_value,
'attribute': self.cb_attribute,
'data': self.cb_data,
'optional': self.cb_optional,
'zeroOrMore': self.cb_zeroormore,
'oneOrMore': self.cb_oneormore,
'choice': self.cb_choice,
'empty': self.cb_empty,
'list': self.cb_list,
'group': self.cb_group,
'interleave': self.cb_group,
'name': self.cb_name,
'text': self.cb_text,
'anyName' : self.cb_anyname,
'nsName' : self.cb_nsname,
'except' : self.cb_except,
'ignore' : self.cb_ignore,
'notAllowed' : self.cb_notallowed}
self.lost_eles = []
self.added_eles = []
self.lost_attrs = []
self.added_attrs = []
return
@memoise
def element_children(self, element):
"""
Return a list of the children of the supplied element, following references
as required.
"""
children = []
for child1 in element.iterchildren(tag=etree.Element):
if self.tag(child1) == "ref":
if not "name" in child1.keys():
debug.deprint("Warning: Encountered reference with no name")
continue
name = child1.get("name")
xpath = self.tree.xpath('/t:grammar/t:define[@name="' + name + '"]',
namespaces={'t': 'http://relaxng.org/ns/structure/1.0'})
if len(xpath) == 0:
debug.deprint("Warning: Schema reference %s not found" % name, 0)
continue
for child2 in self.element_children(xpath[0]):
children.append(child2)
else:
children.append(child1)
return children
def choice_children(self, children):
"""
Collapse all choices within a choice into a single list of (non-choice) children
"""
out_children = []
for child in children:
if self.tag(child) == "choice":
out_children = out_children + self.choice_children(self.element_children(child))
else:
out_children.append(child)
return out_children
def valid_children(self, eid):
if isinstance(eid, tree.Tree):
eid = eid.schemaname
if eid == ":start":
try:
node = self.tree.xpath('/t:grammar/t:start', namespaces={'t': 'http://relaxng.org/ns/structure/1.0'})[0]
except:
debug.deprint("No valid start node found. Are you using a library Relax-NG file like spud_base.rng?", 0)
sys.exit(0)
else:
xpath = self.tree.xpath(eid)
if len(xpath) == 0:
debug.deprint("Warning: no element with XPath %s" % eid)
return []
node = xpath[0]
results = []
for child in self.element_children(node):
self.append(results, self.to_tree(child))
if eid == ":start" and len(results) != 1:
debug.deprint("Error: there must be exactly one root element in an XML document, but found:", 0)
for result in results:
debug.deprint(" %s" % result.name, 0)
sys.exit(1)
return results
def valid_node(self, eid):
if isinstance(eid, tree.Tree) or isinstance(eid, choice.Choice):
eidtree = eid
eid = eid.schemaname
xpath = self.tree.xpath(eid)
if len(xpath) == 0:
debug.deprint("Warning: no element with XPath %s" % eid)
return None
node = xpath[0]
node = self.to_tree(node)
if eidtree is not None:
node.cardinality = eidtree.cardinality
node.parent = eidtree.parent
return node
def to_tree(self, element):
tag = self.tag(element)
f = self.callbacks[tag]
facts = {}
x = f(element, facts)
return x
#############################################
# Beginning of schema processing functions. #
#############################################
def cb_name(self, element, facts):
name = element.text
facts["name"] = name
def cb_element(self, element, facts):
newfacts = {}
if "cardinality" in facts:
newfacts["cardinality"] = facts["cardinality"]
if "name" in element.keys():
newfacts["name"] = element.get("name")
else:
debug.deprint("Warning: Encountered element with no name")
newfacts['schemaname'] = self.tree.getpath(element)
for child in self.element_children(element):
tag = self.tag(child)
if tag not in ['element', 'optional', 'zeroOrMore', 'oneOrMore', 'ignore']:
f = self.callbacks[tag]
x = f(child, newfacts)
try:
d = newfacts["datatype"]
if isinstance(d, tuple):
new_d = []
for x in d:
if x is not None:
new_d.append(x)
d = tuple(new_d)
newfacts["datatype"] = d
if len(d) == 0:
newfacts["datatype"] = None
elif len(d) == 1 and isinstance(d[0], plist.List):
newfacts["datatype"] = d[0]
else:
l_values = []
l_data = []
for x in d:
if isinstance(x, str):
l_values.append(x)
else:
l_data.append(x)
if len(l_data) > 1:
if "name" in element.keys():
debug.deprint("Warning: Element %s has multiple datatypes - using first one" % newfacts["name"])
else:
debug.deprint("Warning: Unnamed element has multiple datatypes - using first one")
if len(l_data) > 0:
if len(l_values) == 0:
newfacts["datatype"] = l_data[0]
else:
newfacts["datatype"] = tuple([tuple(l_values)] + l_data[0])
except KeyError:
pass
return tree.Tree(**newfacts)
def cb_documentation(self, element, facts):
facts['doc'] = element.text
def cb_value(self, element, facts):
if "datatype" in facts:
l = list(facts["datatype"])
else:
l = []
l.append(element.text)
facts["datatype"] = tuple(l)
def cb_attribute(self, element, facts):
if not "name" in element.keys():
debug.deprint("Warning: Encountered attribute with no name")
return
newfacts = {}
name = element.get("name")
for child in self.element_children(element):
tag = self.tag(child)
f = self.callbacks[tag]
x = f(child, newfacts)
if "attrs" not in facts:
facts["attrs"] = {}
try:
datatype = newfacts["datatype"]
except:
debug.deprint("Warning: Encountered attribute with no datatype")
return
curval = None
if isinstance(datatype, tuple):
new_datatype = []
for x in datatype:
if not x is None:
new_datatype.append(x)
datatype = new_datatype
if len(datatype) == 0:
datatype = None
elif len(datatype) == 1:
datatype = datatype[0]
if isinstance(datatype, str):
curval = datatype
datatype = 'fixed'
else:
curval = None
else:
l_values = []
l_data = []
for x in datatype:
if isinstance(x, str):
l_values.append(x)
else:
l_data.append(x)
if len(l_data) > 0:
debug.deprint("Warning: Attribute %s has multiple datatypes - using first one" % name)
if len(l_values) == 0:
datatype = l_data[0]
else:
datatype = tuple([tuple(l_values)] + l_data[0])
else:
datatype = tuple(l_values)
facts["attrs"][name] = (datatype, curval)
def cb_data(self, element, facts):
if "datatype" in facts:
if isinstance(facts["datatype"], tuple):
l = list(facts["datatype"])
else:
l = [facts["datatype"]]
else:
l = []
mapping = {'integer': int,
'float': float,
'double': float,
'decimal': float,
'string': str,
'ID' : str,
'anyURI' : str,
'IDREF' : int,
'NMTOKEN' : str,
'boolean': bool}
datatype_name = element.get("type")
l.append(mapping[datatype_name])
if len(l) == 1:
facts["datatype"] = l[0]
else:
facts["datatype"] = tuple(l)
def cb_optional(self, element, facts):
facts["cardinality"] = '?'
r = []
for child in self.element_children(element):
tag = self.tag(child)
f = self.callbacks[tag]
self.append(r, f(child, facts))
return r
def cb_zeroormore(self, element, facts):
facts["cardinality"] = '*'
r = []
for child in self.element_children(element):
tag = self.tag(child)
f = self.callbacks[tag]
self.append(r, f(child, facts))
return r
def cb_oneormore(self, element, facts):
facts["cardinality"] = '+'
r = []
for child in self.element_children(element):
tag = self.tag(child)
f = self.callbacks[tag]
self.append(r, f(child, facts))
return r
def cb_choice(self, element, facts):
# there are really two cases here.
# choice between values of elements,
# and choice between elements
tagnames = [self.tag(child) for child in element]
if "value" in tagnames:
for child in self.element_children(element):
tag = self.tag(child)
f = self.callbacks[tag]
x = f(child, facts)
else:
if "schemaname" in facts:
return
facts['schemaname'] = self.tree.getpath(element)
r = []
children = self.choice_children(self.element_children(element))
# bloody simplified RNG
if len(children) == 2:
empty = [x for x in children if self.tag(x) == "empty"]
if empty:
nonempty = [x for x in children if self.tag(x) != "empty"]
tag = self.tag(nonempty[0])
f = self.callbacks[tag]
return f(element, facts)
for child in children:
newfacts = {}
tag = self.tag(child)
f = self.callbacks[tag]
self.append(r, f(child, newfacts))
return choice.Choice(r, **facts)
def cb_empty(self, element, facts):
pass
def cb_list(self, element, facts):
newfacts = {}
for child in self.element_children(element):
tag = self.tag(child)
f = self.callbacks[tag]
f(child, newfacts)
d = newfacts["datatype"]
try:
c = newfacts["cardinality"]
except KeyError:
c = ''
if isinstance(d, tuple):
c = str(len(d))
d = d[0]
l = plist.List(d, c)
if "datatype" in facts:
e = list(facts["datatype"])
else:
e = []
e.append(l)
facts["datatype"] = tuple(e)
def cb_group(self, element, facts):
results = []
for child in self.element_children(element):
newfacts = {}
tag = self.tag(child)
f = self.callbacks[tag]
self.append(results, f(child, newfacts))
return results
def cb_text(self, element, facts):
if "datatype" in facts:
if isinstance(facts["datatype"], tuple):
l = list(facts["datatype"])
else:
l = [facts["datatype"]]
else:
l = []
l.append(str)
if len(l) == 1:
facts["datatype"] = l[0]
else:
facts["datatype"] = tuple(l)
def cb_anyname(self, element, facts):
debug.deprint("anyName element found. Yet to handle.", 0)
# sys.exit(1)
def cb_nsname(self, element, facts):
debug.deprint("nsName element found. Yet to handle.", 0)
# sys.exit(1)
| |
#!/usr/bin/env python3
# mc_chain_sw_module.py
#------------------------------------------------------------------------------------------------#
# This software was written in 2016/17 #
# by <NAME> <<EMAIL>>/<<EMAIL>> #
# and <NAME> <<EMAIL>> ("the authors"), #
# to accompany the book "Computer Simulation of Liquids", second edition, 2017 ("the text"), #
# published by Oxford University Press ("the publishers"). #
# #
# LICENCE #
# Creative Commons CC0 Public Domain Dedication. #
# To the extent possible under law, the authors have dedicated all copyright and related #
# and neighboring rights to this software to the PUBLIC domain worldwide. #
# This software is distributed without any warranty. #
# You should have received a copy of the CC0 Public Domain Dedication along with this software. #
# If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. #
# #
# DISCLAIMER #
# The authors and publishers make no warranties about the software, and disclaim liability #
# for all uses of the software, to the fullest extent permitted by applicable law. #
# The authors and publishers do not recommend use of this software for any purpose. #
# It is made freely available, solely to clarify points made in the text. When using or citing #
# the software, you should not imply endorsement by the authors or publishers. #
#------------------------------------------------------------------------------------------------#
"""Monte Carlo, single chain, square wells."""
fast = True # Change this to replace NumPy potential evaluation with slower Python
def introduction():
"""Prints out introductory statements at start of run."""
print('Hard-sphere chain with fixed bond length')
print('Square-well attractive potential')
print('Diameter, sigma = 1')
if fast:
print('Fast NumPy potential routine')
else:
print('Slow Python potential routine')
def conclusion():
"""Prints out concluding statements at end of run."""
print('Program ends')
def regrow ( s, m_max, k_max, bond, q_range, r, q ):
"""Carries out single regrowth move, returning new r, q and indicator of success."""
# A short sequence of m atoms (m<=m_max) is deleted and regrown in the CBMC manner
# We randomly select which end of the chain to apply each of these operations to
# At each stage, k_max different atom positions are tried
# The bond length is fixed throughout
# Weights used in the regrowth are athermal, computed only on the basis of the
# hard-core overlap part of the non-bonded interactions: essentially they count non-overlaps
# Hence they are suitable for use in both NVT and Wang-Landau simulations
# r_old and r_new are used as working arrays
import numpy as np
from maths_module import random_vector
w_tol = 1.e-10 # Min weight tolerance
n, d = r.shape
assert d==3, 'Dimension error in regrow'
r_try = np.empty((k_max,3),dtype=np.float_)
w = np.empty(k_max,dtype=np.float_)
r_old = np.copy(r) # Store copy of r
q_old = q # Store old q
if m_max <= 0:
return r_old, q_old, False
m = 1+np.random.randint ( m_max ) # Number of atoms to regrow
c = np.random.randint ( 4 ) # Growth option
# PART 1: CONSTRUCT NEW CONFIGURATION WITH NEW WEIGHT
if c==0: # Remove from end and add to end
r[:n-m,:] = r_old[:n-m,:] # Copy first n-m atoms
elif c==1: # Remove from end and add to start
r[:n-m,:] = r_old[n-m-1::-1,:] # Copy and reverse first n-m atoms
elif c==2: # Remove from start and add to start
r[:n-m,:] = r_old[:m-1:-1,:] # Copy and reverse last n-m atoms
else: # Remove from start and add to end
r[:n-m,:] = r_old[m:,:] # Copy last n-m atoms
# Take the opportunity to place atom 0 at the origin
r0 = np.copy(r[0,:])
r[:n-m,:] = r[:n-m,:] - r0
w_new = np.float_(1.0)
for i in range(n-m,n): # Loop to regrow last m atoms, computing new weight
for k in range(k_max): # Loop over k_max tries
r_try[k,:] = r[i-1,:] + bond * random_vector() # Trial position in random direction from i-1
w[k] = weight_1 ( r_try[k,:], r[:i-1,:] ) # Store overlap weight for this try
w_sum = np.sum(w)
if w_sum<w_tol: # Early exit if this happens at any stage
return r_old, q_old, False
w = w / w_sum
k = np.random.choice(k_max,p=w) # Pick winning try according to weights
r[i,:] = r_try[k,:] # Store winning position
w_new = w_new * w_sum # Accumulate total weight
if w_new<w_tol: # Exit if this happens
return r_old, q_old, False
q_new = qcount ( r, q_range ) # Compute full new nonbonded energy
r_new = np.copy(r) # Store new configuration
# END OF PART 1: NEW CONFIGURATION AND WEIGHT ARE COMPLETE
# PART 2: RECONSTRUCT OLD CONFIGURATION WITH OLD WEIGHT
if c==0 or c==1: # Remove and hence reconstruct at end
r[:,:] = r_old[:,:] # Copy all n atoms
else: # Remove and reconstruct at start
r[:,:] = r_old[::-1,:] # Copy and reverse all n atoms
w_old = np.float_(1.0)
for i in range(n-m,n):
# Old position and weight are stored as try 0
r_try[0,:] = r[i,:]
w[0] = 1 # Current weight must be 1
# Remaining tries only required to compute weight
for k in range(1,k_max): # Loop over k_max-1 other tries
r_try[k,:] = r[i-1,:] + bond * random_vector() # Trial position in random direction from i-1
w[k] = weight_1 ( r_try[k,:], r[:i-1,:] ) # Store overlap weight for this try
w_sum = np.sum(w)
r[i,:] = r_try[0,:] # Restore winning position (always the original one)
w_old = w_old * w_sum # Accumulate total weight
assert w_old>w_tol, 'Old weight error'
# END OF PART 2: OLD CONFIGURATION AND WEIGHT ARE COMPLETE
# Choose either old or new configuration
if accept ( s, q_old, q_new, w_old, w_new ):
return r_new, q_new, True
else:
return r_old, q_old, False
def pivot ( s, phi_max, q_range, r, q ):
"""Carries out a pivot move, returning new r, q and indicator of success."""
# An atom is picked at random, and the part of the chain lying to one side of it
# is rotated as a whole, by a random angle, about a randomly oriented axis
# There are no weights to take into account in the acceptance/rejection decision
# (the function weight_1 is used simply to indicate overlap / no overlap)
# r_old and r_new are used as working arrays
import numpy as np
from maths_module import random_vector, rotate_vector
n, d = r.shape
assert d==3, 'Dimension error in regrow'
if n<3:
return r, q, False # Makes no sense to pivot such a short chain
r_old = np.copy(r) # Store copy of r
q_old = q # Store old q
c = np.random.randint ( 2 ) # Which part to pivot (actually redundant here)
if c==0: # Copy atoms
r[:,:] = r_old[:,:]
else: # Copy and reverse atoms
r[:,:] = r_old[::-1,:]
# Take the opportunity to place atom 0 at the origin
r0 = np.copy(r[0,:])
r = r - r0
j = np.random.randint ( 1, n-1 ) # Pivot position (not at either end)
rj = r[j,:] # Pivot point
for i in range(1,j+1): # Loop over static atoms, redundant but for roundoff
if weight_1 ( r[i,:], r[:i-1,:] )==0: # Check for overlaps
return r_old, q_old, False
# Pivot, and check for overlap in new configuration
# NB include overlap checks within rotated segment, because of roundoff
axis = random_vector () # Pivot rotation axis
phi = phi_max * ( 2.0*np.random.rand() - 1.0 ) # Pivot rotation angle in desired range
for i in range(j+1,n): # Loop over moving atoms
rij = r[i,:] - rj # Relative vector of atom
rij = rotate_vector ( phi, axis, rij ) # Rotate relative vector
r[i,:] = rj + rij # New absolute position
if weight_1 ( r[i,:], r[:i-1,:] )==0: # Check for overlaps
return r_old, q_old, False
q_new = qcount ( r, q_range ) # Compute full new nonbonded energy
r_new = np.copy(r) # Store new configuration
# Choose either old or new configuration
if accept ( s, q_old, q_new ):
return r_new, q_new, True
else:
return r_old, q_old, False
def crank ( s, phi_max, q_range, r, q ):
"""Carries out a crankshaft move, returning new r, q and indicator of success."""
| |
Face
GUI selection: yes
Selection by name: yes
Recursive: yes
Default value: None
# rel
Description: If equals True, the function try to relimit the rebuild face using the source face edges.
Type: Boolean
GUI selection: -
Selection by name: -
Recursive: -
Default value: False
# switch
Description: If equals True, the iso-curves are switched from iso-u to iso-v.
Type: Boolean
GUI selection: -
Selection by name: -
Recursive: -
Default value: False
# tol
Description: See here.
Type: Float
GUI selection: -
Selection by name: -
Recursive: -
Default value: 1e-7
# single
Description: See here.
Type: Boolean
GUI selection: -
Selection by name: -
Recursive: -
Default value: True
# add
Description: See here.
Type: Boolean
GUI selection: -
Selection by name: -
Recursive: -
Default value: True
# infa
Description: See here.
Type: Boolean
GUI selection: -
Selection by name: -
Recursive: -
Default value: False
# dim
Description: See here.
Type: Integer
GUI selection: -
Selection by name: -
Recursive: -
Default value: 2
Returned Values:
"dim" value: 0
"single" value: False
Type: Vertex
Number: n
Name: "RebuiltFace (Vertex)"
"dim" value: 0
"single" value: True
Type: Compound of Vertexes
Number: 1
Name: "RebuiltFace (Vertexes)"
"dim" value: 1
"single" value: False
Type: Edge
Number: n
Name: "RebuiltFace (Edge)"
"dim" value: 1
"single" value: True
Type: Compound of Edges
Number: 1
Name: "RebuiltFace (Edges)"
"dim" value: 2
"single" value: -
Type: Face
Number: 1
Name: "RebuiltFace"
Conditions of use:
-
"""
if isinstance(np, str): print "[X] The first argument (np) should be an integer ."; return
if dim not in [0, 1, 2]: print "[X] There is no shape to return corresponding to the given dimension."; return
# Get the input shape(s)
face = GetGUISelection(face)
face = GetObject(face)
#-
# Make this function recursive
if isinstance(face, list):
return_list = []
for sub_object in face:
return_list.append(RebuildFace(np, sub_object, rel, switch, tol, single, add, infa, dim))
return return_list
#-
# Get input values
if isinstance(np, list) == False:
np = [np, np]
#-
# Check the input shape existence
if "error" in [face] or None in [face]: return
#-
# Set father object
father = None
if infa == True: father = face
#-
if False: pass
else:# All checks done
# Get the sub-shapes
face = GetSubShapes(face)
#-
# Create the iso curves
iso_curves = []
if dim == 0: iso_curve_vertexes_all = []
for i in [n / float(np[0]) for n in range(np[0] + 1)]:
iso_curve_vertexes = []
for j in [n / float(np[1]) for n in range(np[1] + 1)]:
if switch == True:
new_iso_curve_vertex = geompy.MakeVertexOnSurface(face[-1], j, i)
else:
new_iso_curve_vertex = geompy.MakeVertexOnSurface(face[-1], i, j)
iso_curve_vertexes.append(new_iso_curve_vertex)
if dim == 0: iso_curve_vertexes_all += iso_curve_vertexes
if dim != 0:
new_iso_curve = geompy.MakeInterpol(iso_curve_vertexes)
iso_curves.append(new_iso_curve)
#-
if dim == 0:
to_return = iso_curve_vertexes_all
to_return_name = "RebuiltFace (Vertex)"
if single == True:
# Put them into a compound
vertex_compound = geompy.MakeCompound(iso_curve_vertexes_all)
#-
to_return = vertex_compound
to_return_name = "RebuiltFace (Vertexes)"
else:
# Put them into a compound
iso_curve_compound = geompy.MakeCompound(iso_curves)
#-
if dim == 1:# If the output dimension is 1...
to_return = iso_curves
to_return_name = "RebuiltFace (Edge)"
if single == True:
to_return = iso_curve_compound
to_return_name = "RebuiltFace (Edges)"
else:# If the output dimension is 2...
# Create the filling from this compound
filling = geompy.MakeFilling(iso_curve_compound, theMinDeg = 10, theMaxDeg = 20, theTol2D = 1e-5, theTol3D = 1e-5)
#-
# Relimitate the filling
# TODO improve that ?
rebuild_face = filling
if rel == True:
#face_wire = geompy.SubShapeAll(face[-1], geompy.ShapeType["WIRE"])[0]
#fused_face = geompy.MakeFaceFromSurface(filling, face_wire)
projected_edges = []
for edge in face[1]:
try:
projected_edge = geompy.MakeProjection(edge, filling)
projected_edges.append(projected_edge)
except:
pass
if len(projected_edges) > 0:
filling_partition = geompy.MakePartition([filling], projected_edges)
filling_partition_faces = geompy.SubShapeAll(filling_partition, geompy.ShapeType["FACE"])
for filling_partition_face in filling_partition_faces:
filling_partition_face_vertexes = geompy.SubShapeAll(filling_partition_face, geompy.ShapeType["VERTEX"])
match = True
for filling_partition_face_vertex in filling_partition_face_vertexes:
projected_edge_compound = geompy.MakeCompound(projected_edges)
min_distance = geompy.MinDistance(filling_partition_face_vertex, projected_edge_compound)
if min_distance > tol:
match = False
if match == True:
rebuild_face = filling_partition_face
break
#-
to_return = rebuild_face
to_return_name = "RebuiltFace"
# Add and return the resulting shape(s)
if add == True:
slow_add = False
if not isinstance(to_return, list) or single == True: slow_add = True
AddToStudy(to_return, to_return_name, father, suffix = slow_add, refresh = slow_add)
if slow_add == False:
if salome.sg.hasDesktop():
salome.sg.updateObjBrowser(1)
return to_return
#-
rf = RebuildFace
def FuseCoplanarFaces( faces = [None], add = True ):
"""
Description:
Completely fuses two coplanar faces.
Arguments:
# faces
Description: The faces to fuse.
Type: List of 2 Faces
GUI selection: yes
Selection by name: yes
Recursive: -
Default value: [None]
# add
Description: See here.
Type: Boolean
GUI selection: -
Selection by name: -
Recursive: -
Default value: True
Returned Values:
"dim" value: -
"single" value: -
Type: Face
Number: 1
Name: "FusedFace"
Conditions of use:
-
"""
if isinstance(faces, list) == False: print "[X] The first argument (faces) should be an array."; return
# Get the input shape(s)
faces = GetGUISelection(faces)
faces = GetObject(faces)
#-
# Check the input shape existence
if "error" in faces or None in faces: return
#-
# Check the number of selected objects
if len(faces) != 2:
print "[X] Two shapes should be selected."
return
#-
else:# All checks done
# Get the plane normal
normal = geompy.GetNormal(faces[0])
#-
# Extrude the faces
extrusion_distance = 1e3
cutting_plane_position = extrusion_distance / 2
extruded_faces = [
geompy.MakePrismVecH(faces[0], normal, extrusion_distance),
geompy.MakePrismVecH(faces[1], normal, extrusion_distance)
]
#-
# Fuse the extruded faces
fused_extension = geompy.MakeFuse(extruded_faces[0], extruded_faces[1])
#-
# Get the length of the cutting plane
bounding_box = geompy.BoundingBox(fused_extension)
dx = abs(bounding_box[1] - bounding_box[0])
dy = abs(bounding_box[2] - bounding_box[1])
dz = abs(bounding_box[3] - bounding_box[2])
plane_length = 2 * dx + 2 * dy + 2 * dz
#-
# Create the cutting plane
cutting_plane = geompy.MakePlaneFace(faces[0], plane_length)
cutting_plane = geompy.MakeTranslationVectorDistance(cutting_plane, normal, cutting_plane_position)
#-
# Cut the fused extrusion with the plane
fused_face = geompy.MakeCommon(fused_extension, cutting_plane)
#-
# Remove shells (optional)
random_vertex = geompy.MakeVertex(0, 0, 0)# This vertex is only used to make the below partition possible
fused_face = geompy.MakePartition([fused_face], [random_vertex], Limit = geompy.ShapeType["FACE"])
#-
# Move the face to the original position
fused_face = geompy.MakeTranslationVectorDistance(fused_face, normal, - cutting_plane_position)
#-
# Add and return the resulting shape(s)
if add == True:
AddToStudy(fused_face, "FusedFace")
return fused_face
#-
fcf = FuseCoplanarFaces
def FuseShellFaces( shell = None, np = 400, strat = "rigid", curv = True, add = True, infa = False, dim = 2 ):
"""
Description:
Creates a single face from a shell.
Arguments:
# shell
Description: The shell to fuse.
Type: Shell
GUI selection: yes
Selection by name: yes
Recursive: yes
Default value: [None]
# np
Description: See here. In this case, the number of point is approximatively respected.
Type: Integer
GUI selection: -
Selection by name: -
Recursive: -
Default value: 400
# strat
Description: The strategy. If equals "flex", the function tries to insert smooth transitions between sub-faces of the input shell (the boundary wire is then modified). Equals "rigid" otherwise (necessitates the input sub-faces to be as tangential as possible).
Type: String
GUI selection: -
Selection by name: -
Recursive: -
Default value: "rigid"
# curv
Description: See here. In this case, applies only for the boundary wire reconstruction when strat equals "flex".
Type: Boolean
GUI selection: -
Selection by name: -
Recursive: -
Default value: True
# add
Description: See here.
Type: Boolean
GUI selection: -
Selection by name: -
Recursive: -
Default value: True
# infa
Description: See here.
Type: Boolean
GUI selection: -
Selection by name: -
Recursive: -
Default value: False
Returned Values:
"dim" value: 0
"single" value: -
Type: Compound of Vertexes
Number: 1
Name: "FusedShell (Vertexes)"
"dim" value: 2
"single" value: -
Type: Face
Number: 1
Name: "FusedShell"
Conditions of use:
The shell should have only one boundary wire.
Also, to be fused efficiently, the shell faces should have reasonable aspect ratio and local curvature.
"""
if isinstance(np, str): print "[X] The first argument (np) should be an integer ."; return
if dim not in [0, 2]: print "[X] There is no shape to return corresponding to the given dimension."; return
# Get the input shape(s)
shell = GetGUISelection(shell)
shell = GetObject(shell)
#-
# Make this function recursive
if isinstance(shell, list):
return_list = []
for sub_object in shell:
return_list.append(FuseShellFaces(sub_object, np, strat, curv, add, infa, dim))
return return_list
#-
# Check the input shape existence
if "error" in [shell] or None in [shell]: return
#-
# Set father object
father = None
if infa == True: father = shell
#-
if False: pass
else:# All checks done
# Check if the input shape is "shell-shaped"
shell_faces = GetSubShapes(shell)[2]
try:
shell = geompy.MakeShell(shell_faces)
except:
print "[X] The input 2D shape should be \"shell-shaped\"."; return
#-
# Get the input shell boundary wire
boundary_wire = geompy.GetFreeBoundary(shell)[1][0]
#-
# Get the input shell area
area = geompy.BasicProperties(shell)[1]
#-
# Get the cell size
cell_size = math.sqrt(area / np)
#-
# Mesh the input shell
mesh = smesh.Mesh(shell)
netgen_algo = mesh.Triangle(algo = smeshBuilder.NETGEN_1D2D)
netgen_hypo = netgen_algo.Parameters()
netgen_hypo.SetMinSize(cell_size)
netgen_hypo.SetMaxSize(cell_size)
netgen_hypo.SetFineness(2)
mesh.Compute()
#-
# Remove internal vertexes
if strat == "flex":# not "rigid"
# Get the internal edges
all_edges_group = PutAllSubShapesInAGroup(1, shell, add = False)
internal_edge_compound = geompy.MakeCut(all_edges_group, boundary_wire)
geompy.addToStudy(internal_edge_compound, "internal_edges")
#-
# Create the internal node mesh group
internal_nodes_mesh_filter = smesh.GetFilterFromCriteria([smesh.GetCriterion(SMESH.NODE, SMESH.FT_BelongToGeom, SMESH.FT_Undefined, internal_edge_compound)])
internal_nodes_mesh_filter.SetMesh(mesh.GetMesh())
internal_nodes_mesh_group = mesh.GroupOnFilter(SMESH.NODE, "internal_nodes", internal_nodes_mesh_filter)
#-
# Delete the | |
[])
events = ("start", "end")
context = iterparse(SIMPLE_XMLFILE, events)
self.assertEqual([(action, elem.tag) for action, elem in context], [
('start', 'root'),
('start', 'element'),
('end', 'element'),
('start', 'element'),
('end', 'element'),
('start', 'empty-element'),
('end', 'empty-element'),
('end', 'root'),
])
events = ("start", "end", "start-ns", "end-ns")
context = iterparse(SIMPLE_NS_XMLFILE, events)
self.assertEqual([(action, elem.tag) if action in ("start", "end")
else (action, elem)
for action, elem in context], [
('start-ns', ('', 'namespace')),
('start', '{namespace}root'),
('start', '{namespace}element'),
('end', '{namespace}element'),
('start', '{namespace}element'),
('end', '{namespace}element'),
('start', '{namespace}empty-element'),
('end', '{namespace}empty-element'),
('end', '{namespace}root'),
('end-ns', None),
])
events = ('start-ns', 'end-ns')
context = iterparse(io.StringIO(r"<root xmlns=''/>"), events)
res = [action for action, elem in context]
self.assertEqual(res, ['start-ns', 'end-ns'])
events = ("start", "end", "bogus")
with open(SIMPLE_XMLFILE, "rb") as f:
with self.assertRaises(ValueError) as cm:
iterparse(f, events)
self.assertFalse(f.closed)
self.assertEqual(str(cm.exception), "unknown event 'bogus'")
with support.check_no_resource_warning(self):
with self.assertRaises(ValueError) as cm:
iterparse(SIMPLE_XMLFILE, events)
self.assertEqual(str(cm.exception), "unknown event 'bogus'")
del cm
source = io.BytesIO(
b"<?xml version='1.0' encoding='iso-8859-1'?>\n"
b"<body xmlns='http://éffbot.org/ns'\n"
b" xmlns:cl\xe9='http://effbot.org/ns'>text</body>\n")
events = ("start-ns",)
context = iterparse(source, events)
self.assertEqual([(action, elem) for action, elem in context], [
('start-ns', ('', 'http://\xe9ffbot.org/ns')),
('start-ns', ('cl\xe9', 'http://effbot.org/ns')),
])
source = io.StringIO("<document />junk")
it = iterparse(source)
action, elem = next(it)
self.assertEqual((action, elem.tag), ('end', 'document'))
with self.assertRaises(ET.ParseError) as cm:
next(it)
self.assertEqual(str(cm.exception),
'junk after document element: line 1, column 12')
self.addCleanup(support.unlink, TESTFN)
with open(TESTFN, "wb") as f:
f.write(b"<document />junk")
it = iterparse(TESTFN)
action, elem = next(it)
self.assertEqual((action, elem.tag), ('end', 'document'))
with support.check_no_resource_warning(self):
with self.assertRaises(ET.ParseError) as cm:
next(it)
self.assertEqual(str(cm.exception),
'junk after document element: line 1, column 12')
del cm, it
def test_writefile(self):
elem = ET.Element("tag")
elem.text = "text"
self.serialize_check(elem, '<tag>text</tag>')
ET.SubElement(elem, "subtag").text = "subtext"
self.serialize_check(elem, '<tag>text<subtag>subtext</subtag></tag>')
# Test tag suppression
elem.tag = None
self.serialize_check(elem, 'text<subtag>subtext</subtag>')
elem.insert(0, ET.Comment("comment"))
self.serialize_check(elem,
'text<!--comment--><subtag>subtext</subtag>') # assumes 1.3
elem[0] = ET.PI("key", "value")
self.serialize_check(elem, 'text<?key value?><subtag>subtext</subtag>')
def test_custom_builder(self):
# Test parser w. custom builder.
with open(SIMPLE_XMLFILE) as f:
data = f.read()
class Builder(list):
def start(self, tag, attrib):
self.append(("start", tag))
def end(self, tag):
self.append(("end", tag))
def data(self, text):
pass
builder = Builder()
parser = ET.XMLParser(target=builder)
parser.feed(data)
self.assertEqual(builder, [
('start', 'root'),
('start', 'element'),
('end', 'element'),
('start', 'element'),
('end', 'element'),
('start', 'empty-element'),
('end', 'empty-element'),
('end', 'root'),
])
with open(SIMPLE_NS_XMLFILE) as f:
data = f.read()
class Builder(list):
def start(self, tag, attrib):
self.append(("start", tag))
def end(self, tag):
self.append(("end", tag))
def data(self, text):
pass
def pi(self, target, data):
self.append(("pi", target, data))
def comment(self, data):
self.append(("comment", data))
builder = Builder()
parser = ET.XMLParser(target=builder)
parser.feed(data)
self.assertEqual(builder, [
('pi', 'pi', 'data'),
('comment', ' comment '),
('start', '{namespace}root'),
('start', '{namespace}element'),
('end', '{namespace}element'),
('start', '{namespace}element'),
('end', '{namespace}element'),
('start', '{namespace}empty-element'),
('end', '{namespace}empty-element'),
('end', '{namespace}root'),
])
# Element.getchildren() and ElementTree.getiterator() are deprecated.
@checkwarnings(("This method will be removed in future versions. "
"Use .+ instead.",
DeprecationWarning))
def test_getchildren(self):
# Test Element.getchildren()
with open(SIMPLE_XMLFILE, "rb") as f:
tree = ET.parse(f)
self.assertEqual([summarize_list(elem.getchildren())
for elem in tree.getroot().iter()], [
['element', 'element', 'empty-element'],
[],
[],
[],
])
self.assertEqual([summarize_list(elem.getchildren())
for elem in tree.getiterator()], [
['element', 'element', 'empty-element'],
[],
[],
[],
])
elem = ET.XML(SAMPLE_XML)
self.assertEqual(len(elem.getchildren()), 3)
self.assertEqual(len(elem[2].getchildren()), 1)
self.assertEqual(elem[:], elem.getchildren())
child1 = elem[0]
child2 = elem[2]
del elem[1:2]
self.assertEqual(len(elem.getchildren()), 2)
self.assertEqual(child1, elem[0])
self.assertEqual(child2, elem[1])
elem[0:2] = [child2, child1]
self.assertEqual(child2, elem[0])
self.assertEqual(child1, elem[1])
self.assertNotEqual(child1, elem[0])
elem.clear()
self.assertEqual(elem.getchildren(), [])
def test_writestring(self):
elem = ET.XML("<html><body>text</body></html>")
self.assertEqual(ET.tostring(elem), b'<html><body>text</body></html>')
elem = ET.fromstring("<html><body>text</body></html>")
self.assertEqual(ET.tostring(elem), b'<html><body>text</body></html>')
def test_encoding(self):
def check(encoding, body=''):
xml = ("<?xml version='1.0' encoding='%s'?><xml>%s</xml>" %
(encoding, body))
self.assertEqual(ET.XML(xml.encode(encoding)).text, body)
self.assertEqual(ET.XML(xml).text, body)
check("ascii", 'a')
check("us-ascii", 'a')
check("iso-8859-1", '\xbd')
check("iso-8859-15", '\u20ac')
check("cp437", '\u221a')
check("mac-roman", '\u02da')
def xml(encoding):
return "<?xml version='1.0' encoding='%s'?><xml />" % encoding
def bxml(encoding):
return xml(encoding).encode(encoding)
supported_encodings = [
'ascii', 'utf-8', 'utf-8-sig', 'utf-16', 'utf-16be', 'utf-16le',
'iso8859-1', 'iso8859-2', 'iso8859-3', 'iso8859-4', 'iso8859-5',
'iso8859-6', 'iso8859-7', 'iso8859-8', 'iso8859-9', 'iso8859-10',
'iso8859-13', 'iso8859-14', 'iso8859-15', 'iso8859-16',
'cp437', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852',
'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862',
'cp863', 'cp865', 'cp866', 'cp869', 'cp874', 'cp1006', 'cp1125',
'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
'cp1256', 'cp1257', 'cp1258',
'mac-cyrillic', 'mac-greek', 'mac-iceland', 'mac-latin2',
'mac-roman', 'mac-turkish',
'iso2022-jp', 'iso2022-jp-1', 'iso2022-jp-2', 'iso2022-jp-2004',
'iso2022-jp-3', 'iso2022-jp-ext',
'koi8-r', 'koi8-t', 'koi8-u', 'kz1048',
'hz', 'ptcp154',
]
for encoding in supported_encodings:
self.assertEqual(ET.tostring(ET.XML(bxml(encoding))), b'<xml />')
unsupported_ascii_compatible_encodings = [
'big5', 'big5hkscs',
'cp932', 'cp949', 'cp950',
'euc-jp', 'euc-jis-2004', 'euc-jisx0213', 'euc-kr',
'gb2312', 'gbk', 'gb18030',
'iso2022-kr', 'johab',
'shift-jis', 'shift-jis-2004', 'shift-jisx0213',
'utf-7',
]
for encoding in unsupported_ascii_compatible_encodings:
self.assertRaises(ValueError, ET.XML, bxml(encoding))
unsupported_ascii_incompatible_encodings = [
'cp037', 'cp424', 'cp500', 'cp864', 'cp875', 'cp1026', 'cp1140',
'utf_32', 'utf_32_be', 'utf_32_le',
]
for encoding in unsupported_ascii_incompatible_encodings:
self.assertRaises(ET.ParseError, ET.XML, bxml(encoding))
self.assertRaises(ValueError, ET.XML, xml('undefined').encode('ascii'))
self.assertRaises(LookupError, ET.XML, xml('xxx').encode('ascii'))
def test_methods(self):
# Test serialization methods.
e = ET.XML("<html><link/><script>1 < 2</script></html>")
e.tail = "\n"
self.assertEqual(serialize(e),
'<html><link /><script>1 < 2</script></html>\n')
self.assertEqual(serialize(e, method=None),
'<html><link /><script>1 < 2</script></html>\n')
self.assertEqual(serialize(e, method="xml"),
'<html><link /><script>1 < 2</script></html>\n')
self.assertEqual(serialize(e, method="html"),
'<html><link><script>1 < 2</script></html>\n')
self.assertEqual(serialize(e, method="text"), '1 < 2\n')
def test_issue18347(self):
e = ET.XML('<html><CamelCase>text</CamelCase></html>')
self.assertEqual(serialize(e),
'<html><CamelCase>text</CamelCase></html>')
self.assertEqual(serialize(e, method="html"),
'<html><CamelCase>text</CamelCase></html>')
def test_entity(self):
# Test entity handling.
# 1) good entities
e = ET.XML("<document title='舰'>test</document>")
self.assertEqual(serialize(e, encoding="us-ascii"),
b'<document title="舰">test</document>')
self.serialize_check(e, '<document title="\u8230">test</document>')
# 2) bad entities
with self.assertRaises(ET.ParseError) as cm:
ET.XML("<document>&entity;</document>")
self.assertEqual(str(cm.exception),
'undefined entity: line 1, column 10')
with self.assertRaises(ET.ParseError) as cm:
ET.XML(ENTITY_XML)
self.assertEqual(str(cm.exception),
'undefined entity &entity;: line 5, column 10')
# 3) custom entity
parser = ET.XMLParser()
parser.entity["entity"] = "text"
parser.feed(ENTITY_XML)
root = parser.close()
self.serialize_check(root, '<document>text</document>')
# 4) external (SYSTEM) entity
with self.assertRaises(ET.ParseError) as cm:
ET.XML(EXTERNAL_ENTITY_XML)
self.assertEqual(str(cm.exception),
'undefined entity &entity;: line 4, column 10')
def test_namespace(self):
# Test namespace issues.
# 1) xml namespace
elem = ET.XML("<tag xml:lang='en' />")
self.serialize_check(elem, '<tag xml:lang="en" />') # 1.1
# 2) other "well-known" namespaces
elem = ET.XML("<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' />")
self.serialize_check(elem,
'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" />') # 2.1
elem = ET.XML("<html:html xmlns:html='http://www.w3.org/1999/xhtml' />")
self.serialize_check(elem,
'<html:html xmlns:html="http://www.w3.org/1999/xhtml" />') # 2.2
elem = ET.XML("<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope' />")
self.serialize_check(elem,
'<ns0:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope" />') # 2.3
# 3) unknown namespaces
elem = ET.XML(SAMPLE_XML_NS)
self.serialize_check(elem,
'<ns0:body xmlns:ns0="http://effbot.org/ns">\n'
' <ns0:tag>text</ns0:tag>\n'
' <ns0:tag />\n'
' <ns0:section>\n'
' <ns0:tag>subtext</ns0:tag>\n'
' </ns0:section>\n'
'</ns0:body>')
def test_qname(self):
# Test QName handling.
# 1) decorated tags
elem = ET.Element("{uri}tag")
self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') # 1.1
elem = ET.Element(ET.QName("{uri}tag"))
self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') # 1.2
elem = ET.Element(ET.QName("uri", "tag"))
self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') # 1.3
elem = ET.Element(ET.QName("uri", "tag"))
subelem = ET.SubElement(elem, ET.QName("uri", "tag1"))
subelem = ET.SubElement(elem, ET.QName("uri", "tag2"))
self.serialize_check(elem,
'<ns0:tag xmlns:ns0="uri"><ns0:tag1 /><ns0:tag2 /></ns0:tag>') # 1.4
# 2) decorated attributes
elem.clear()
elem.attrib["{uri}key"] = "value"
self.serialize_check(elem,
'<ns0:tag xmlns:ns0="uri" ns0:key="value" />') # 2.1
elem.clear()
elem.attrib[ET.QName("{uri}key")] = "value"
self.serialize_check(elem,
'<ns0:tag xmlns:ns0="uri" ns0:key="value" />') # 2.2
# 3) decorated values are not converted by default, but the
# QName wrapper can be used for values
elem.clear()
elem.attrib["{uri}key"] = "{uri}value"
self.serialize_check(elem,
'<ns0:tag xmlns:ns0="uri" ns0:key="{uri}value" />') # 3.1
elem.clear()
elem.attrib["{uri}key"] = ET.QName("{uri}value")
self.serialize_check(elem,
'<ns0:tag xmlns:ns0="uri" ns0:key="ns0:value" />') # 3.2
elem.clear()
subelem = ET.Element("tag")
subelem.attrib["{uri1}key"] = ET.QName("{uri2}value")
elem.append(subelem)
elem.append(subelem)
self.serialize_check(elem,
'<ns0:tag xmlns:ns0="uri" xmlns:ns1="uri1" xmlns:ns2="uri2">'
'<tag ns1:key="ns2:value" />'
'<tag ns1:key="ns2:value" />'
'</ns0:tag>') # 3.3
# 4) Direct QName tests
self.assertEqual(str(ET.QName('ns', 'tag')), '{ns}tag')
self.assertEqual(str(ET.QName('{ns}tag')), '{ns}tag')
q1 = ET.QName('ns', 'tag')
q2 = ET.QName('ns', 'tag')
self.assertEqual(q1, q2)
q2 = ET.QName('ns', 'other-tag')
self.assertNotEqual(q1, q2)
self.assertNotEqual(q1, 'ns:tag')
self.assertEqual(q1, '{ns}tag')
def test_doctype_public(self):
# Test PUBLIC doctype.
elem = ET.XML('<!DOCTYPE html PUBLIC'
' "-//W3C//DTD XHTML 1.0 Transitional//EN"'
' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
'<html>text</html>')
def test_xpath_tokenizer(self):
# Test the XPath tokenizer.
from xml.etree import ElementPath
def check(p, expected):
self.assertEqual([op or tag
for op, tag in ElementPath.xpath_tokenizer(p)],
expected)
# tests from the xml specification
check("*", ['*'])
check("text()", ['text', '()'])
check("@name", ['@', 'name'])
check("@*", ['@', '*'])
check("para[1]", ['para', '[', '1', ']'])
check("para[last()]", ['para', '[', 'last', '()', ']'])
check("*/para", ['*', '/', 'para'])
check("/doc/chapter[5]/section[2]",
['/', 'doc', '/', 'chapter', '[', '5', ']',
'/', 'section', '[', '2', ']'])
check("chapter//para", ['chapter', '//', 'para'])
check("//para", ['//', 'para'])
check("//olist/item", ['//', 'olist', '/', 'item'])
check(".", ['.'])
check(".//para", ['.', '//', 'para'])
check("..", ['..'])
check("../@lang", ['..', '/', '@', 'lang'])
check("chapter[title]", ['chapter', '[', 'title', ']'])
check("employee[@secretary and @assistant]", ['employee',
'[', '@', 'secretary', '', 'and', '', '@', 'assistant', ']'])
# additional tests
check("{http://spam}egg", ['{http://spam}egg'])
check("./spam.egg", ['.', '/', 'spam.egg'])
check(".//{http://spam}egg", ['.', '//', '{http://spam}egg'])
def test_processinginstruction(self):
# Test ProcessingInstruction directly
self.assertEqual(ET.tostring(ET.ProcessingInstruction('test', 'instruction')),
b'<?test instruction?>')
self.assertEqual(ET.tostring(ET.PI('test', 'instruction')),
b'<?test instruction?>')
# Issue #2746
self.assertEqual(ET.tostring(ET.PI('test', '<testing&>')),
b'<?test <testing&>?>')
self.assertEqual(ET.tostring(ET.PI('test', '<testing&>\xe3'), 'latin-1'),
b"<?xml version='1.0' encoding='latin-1'?>\n"
b"<?test <testing&>\xe3?>")
def test_html_empty_elems_serialization(self):
# issue 15970
# from http://www.w3.org/TR/html401/index/elements.html
for element in ['AREA', 'BASE', 'BASEFONT', 'BR', 'COL', 'FRAME', 'HR',
'IMG', 'INPUT', 'ISINDEX', 'LINK', 'META', 'PARAM']:
for elem in [element, | |
spring2_axis
spring3_pos = self.walls[(Num_layer - 1) * 6 + 4]
spring3_axis = self.walls[(Num_layer - 1) * 6 + 5]
spring3_end = spring3_pos + spring3_axis
dis_spr1 = (spring1_end - point_pos).mag - point_radius
dis_spr2 = (spring2_end - point_pos).mag - point_radius
dis_spr3 = (spring3_end - point_pos).mag - point_radius
dis_list = []
dis_list.append(dis_spr1)
dis_list.append(dis_spr2)
dis_list.append(dis_spr3)
return dis_list
def Distance_from_mid_layer_to_round_shape(self, LayerNum, point_pos, point_radius):
Num_layer = LayerNum
spring1_pos = self.walls[(LayerNum) * 6 + 0]
spring1_axis = self.walls[(LayerNum) * 6 + 1]
spring1_end = spring1_pos + spring1_axis
spring2_pos = self.walls[(LayerNum) * 6 + 2]
spring2_axis = self.walls[(LayerNum) * 6 + 3]
spring2_end = spring2_pos + spring2_axis
spring3_pos = self.walls[(LayerNum) * 6 + 4]
spring3_axis = self.walls[(LayerNum) * 6 + 5]
spring3_end = spring3_pos + spring3_axis
dis_spr1 = (spring1_end - point_pos).mag - point_radius
dis_spr2 = (spring2_end - point_pos).mag - point_radius
dis_spr3 = (spring3_end - point_pos).mag - point_radius
dis_list = []
dis_list.append(dis_spr1)
dis_list.append(dis_spr2)
dis_list.append(dis_spr3)
return dis_list
def Distance_from_top_to_rod_shape(self, rod_ending1, rod_ending2, rod_radius):
Num_layer = int(self.walls.__len__() / 6)
spring1_pos = self.walls[(Num_layer - 1) * 6 + 0]
spring1_axis = self.walls[(Num_layer - 1) * 6 + 1]
spring1_end = spring1_pos + spring1_axis
spring2_pos = self.walls[(Num_layer - 1) * 6 + 2]
spring2_axis = self.walls[(Num_layer - 1) * 6 + 3]
spring2_end = spring2_pos + spring2_axis
spring3_pos = self.walls[(Num_layer - 1) * 6 + 4]
spring3_axis = self.walls[(Num_layer - 1) * 6 + 5]
spring3_end = spring3_pos + spring3_axis
list = []
dis_spring1 = calulation_line_to_point(spring1_end, rod_ending1, rod_ending2) - rod_radius
dis_spring2 = calulation_line_to_point(spring2_end, rod_ending1, rod_ending2) - rod_radius
dis_spring3 = calulation_line_to_point(spring3_end, rod_ending1, rod_ending2) - rod_radius
list.append(dis_spring1)
list.append(dis_spring2)
list.append(dis_spring3)
return list
def Distance_from_mid_layer_to_rod_shape(self, LayerNum, rod_ending1, rod_ending2, rod_radius):
Num_layer = LayerNum
spring1_pos = self.walls[(LayerNum) * 6 + 0]
spring1_axis = self.walls[(LayerNum) * 6 + 1]
spring1_end = spring1_pos + spring1_axis
spring2_pos = self.walls[(LayerNum) * 6 + 2]
spring2_axis = self.walls[(LayerNum) * 6 + 3]
spring2_end = spring2_pos + spring2_axis
spring3_pos = self.walls[(LayerNum) * 6 + 4]
spring3_axis = self.walls[(LayerNum) * 6 + 5]
spring3_end = spring3_pos + spring3_axis
list = []
dis_spring1 = calulation_line_to_point(spring1_end, rod_ending1, rod_ending2) - rod_radius
dis_spring2 = calulation_line_to_point(spring2_end, rod_ending1, rod_ending2) - rod_radius
dis_spring3 = calulation_line_to_point(spring3_end, rod_ending1, rod_ending2) - rod_radius
list.append(dis_spring1)
list.append(dis_spring2)
list.append(dis_spring3)
return list
def append_dist2target(self, dist_list):
self.dist_springs2target.append([dist_list[0], dist_list[1], dist_list[2]])
def calculation_spring_axis(self, spring1_len, spring2_len, spring3_len, spring1_pos, spring2_pos, spring3_pos, Num_layer):
max_len = max(spring1_len, spring2_len, spring3_len)
min_len = min(spring1_len, spring2_len, spring3_len)
dif_len = max(spring1_len - min_len, spring2_len - min_len, spring3_len - min_len)
if self.max_len < max_len and self.max_dif_len < dif_len:
return 0 # indicate len out of limit
switch_num = switch_for_cal_vec(spring1_len, spring2_len, spring3_len)
# print("switch_num = {}".format(switch_num))
spring_len_array = [spring1_len, spring2_len, spring3_len]
spring_pos_array = [spring1_pos, spring2_pos, spring3_pos]
spring_len_after_switch = np.roll(spring_len_array, switch_num)
spring_pos_after_switch = np.roll(spring_pos_array, switch_num)
list_spring_unswitch_axix = calculation_spring_vector(spring_pos_after_switch[0], spring_pos_after_switch[1],
spring_pos_after_switch[2], spring_len_after_switch[0],
spring_len_after_switch[1], spring_len_after_switch[2],
self.spr_distance[Num_layer])
list_spring_axix = np.roll(list_spring_unswitch_axix, switch_num * -1)
return [list_spring_axix[0], list_spring_axix[1], list_spring_axix[2]]
def find_close_layer_point(self, *args, **kwargs):
dist_list_all = []
totall_layerN = int(self.walls.__len__() / 6)
for i in range(totall_layerN):
dist_list_all.append(self.Distance_from_mid_layer_to_target(LayerNum=i, *args, **kwargs))
dist_list_all = np.array(dist_list_all)
dist_list_all = dist_list_all.reshape(-1)
print("dist_list_all:{}".format(dist_list_all))
minN = np.where(dist_list_all == min(dist_list_all))
close_dist = dist_list_all[minN]
layer_Num = int(minN[0][0] / 3)
print("layer_Num:{}".format(layer_Num))
layer_dist = (self.Distance_from_mid_layer_to_target(LayerNum=layer_Num, *args, **kwargs))
layer_dist = np.array(layer_dist)
maxN = np.where(layer_dist == max(layer_dist))[0][0] # 0-2
print("maxN:{}".format(maxN))
return layer_Num * 3 + maxN, close_dist
def touchSense_close_layer_point_by_module(self, rodPos, rodEnd, rodRadius):
dist_list_all = []
layIndex = []
totall_moduleN = int(self.walls.__len__() / 6 / self.module_num)
totall_layerN = int(self.walls.__len__() / 6)
for i in range(1, totall_layerN, 1):
# print("module layer={}".format(i))
dist_list_all.append(self.Distance_from_center_to_rod_by_layer(i, rodPos, rodEnd, rodRadius))
layIndex.append(i)
dist_list_all = np.array(dist_list_all)
dist_list_all = dist_list_all.reshape(-1)
# print("dist_list_all:{}".format(dist_list_all))
minN = np.where(dist_list_all == min(dist_list_all))
close_dist = dist_list_all[minN]
layer_Num = layIndex[int(minN[0][0])]
print("closest layer_Num:{}".format(layer_Num))
dis_spring = self.Distance_from_mid_layer_to_rod_shape(layer_Num, rodPos, rodEnd, rodRadius)
return [layer_Num, dis_spring]
def touchSense_close_layer_point_by_module_from_new(self, module_number, rodPos, rodEnd, rodRadius):
# start sensing from module_number
dist_list_all = []
layIndex = []
totall_moduleN = int(self.walls.__len__() / 6 / self.module_num)
totall_layerN = int(self.walls.__len__() / 6)
for i in range(module_number * self.module_num, totall_layerN, 1):
# print("module layer={}".format(i))
dist_list_all.append(self.Distance_from_center_to_rod_by_layer(i, rodPos, rodEnd, rodRadius))
layIndex.append(i)
dist_list_all = np.array(dist_list_all)
dist_list_all = dist_list_all.reshape(-1)
# print("dist_list_all:{}".format(dist_list_all))
minN = np.where(dist_list_all == min(dist_list_all))
close_dist = dist_list_all[minN]
layer_Num = layIndex[int(minN[0][0])]
print("closest layer_Num:{}".format(layer_Num))
dis_spring = self.Distance_from_mid_layer_to_rod_shape(layer_Num, rodPos, rodEnd, rodRadius)
layer_Num_adj = layer_Num + module_number * self.module_num
return [layer_Num_adj, dis_spring]
def find_close_layer_point_by_module(self, *args, **kwargs):
dist_list_all = []
layIndex = []
totall_moduleN = int(self.walls.__len__() / 6 / self.module_num)
totall_layerN = int(self.walls.__len__() / 6)
for i in range(10, totall_layerN, self.module_num):
print("module layer={}".format(i))
dist_list_all.append(self.Distance_from_mid_layer_to_target(LayerNum=i, *args, **kwargs))
layIndex.append(i)
dist_list_all = np.array(dist_list_all)
dist_list_all = dist_list_all.reshape(-1)
print("dist_list_all:{}".format(dist_list_all))
minN = np.where(dist_list_all == min(dist_list_all))
close_dist = dist_list_all[minN]
layer_Num = layIndex[int(minN[0][0] / 3)]
print("closest layer_Num:{}".format(layer_Num))
layer_dist = (self.Distance_from_mid_layer_to_target(LayerNum=layer_Num, *args, **kwargs))
layer_dist = np.array(layer_dist)
maxN = np.where(layer_dist == max(layer_dist))[0][0] # 0-2
print("closest layer maxN:{}".format(maxN))
# return layerNumb, maxN of spring, short dist
return int(minN[0][0] / 3), maxN, close_dist
def touchSense_parameters_cal(self, LayerNum, rodPos, rodEnd, rodRadius):
spring1_pos = self.walls[(LayerNum) * 6 + 0]
spring1_axis = self.walls[(LayerNum) * 6 + 1]
spring1_end = spring1_pos + spring1_axis
spring2_pos = self.walls[(LayerNum) * 6 + 2]
spring2_axis = self.walls[(LayerNum) * 6 + 3]
spring2_end = spring2_pos + spring2_axis
spring3_pos = self.walls[(LayerNum) * 6 + 4]
spring3_axis = self.walls[(LayerNum) * 6 + 5]
spring3_end = spring3_pos + spring3_axis
up_center, down_center = self.get_center_positions(LayerNum)
dist_center2Rod = calulation_line_to_point(up_center, rodPos,
rodEnd) # - rodRadius - self.spr_distance*np.sqrt(3)/2
dist_list = self.Distance_from_mid_layer_to_rod_shape(LayerNum, rodPos, rodEnd, rodRadius)
angle0 = triangle_angle_from_3lines(dist_center2Rod, dist_list[0], self.spr_distance[LayerNum] / np.sqrt(3))
angle1 = triangle_angle_from_3lines(dist_center2Rod, dist_list[1], self.spr_distance[LayerNum] / np.sqrt(3))
angle2 = triangle_angle_from_3lines(dist_center2Rod, dist_list[2], self.spr_distance[LayerNum] / np.sqrt(3))
# angle = triangle_angle_from_3lines(dist_center2Rod, max(dist_list) + rodRadius , self.spr_distance/np.sqrt(3))
print("touchSense_parameters_cal: angle = {}, {}, {}".format(np.rad2deg(angle0), np.rad2deg(angle1),
np.rad2deg(angle2)))
def get_rotation_matrix_from_vector(v1, v2):
# v1 and v2 must be unit
v1 = v1.hat
v2 = v2.hat
if vector.dot(v1, v2) == 0:
theta = pi / 2
else:
theta = np.arctan(vector.cross(v1, v2).mag / vector.dot(v1, v2)) # to be done??? arctan2???
n = vector.cross(v1, v2).hat
q0 = np.cos(theta / 2)
q1 = np.sin(theta / 2) * n.x
q2 = np.sin(theta / 2) * n.y
q3 = np.sin(theta / 2) * n.z
r11 = 2 * (q0 * q0 + q1 * q1) - 1
r12 = 2 * (q1 * q2 - q0 * q3)
r13 = 2 * (q1 * q3 + q0 * q2)
r21 = 2 * (q1 * q2 + q0 * q3)
r22 = 2 * (q0 * q0 + q2 * q2) - 1
r23 = 2 * (q2 * q3 - q0 * q1)
r31 = 2 * (q1 * q3 - q0 * q2)
r32 = 2 * (q2 * q3 + q0 * q1)
r33 = 2 * (q0 * q0 + q3 * q3) - 1
R = [[r11, r12, r13], [r21, r22, r23], [r31, r32, r33]]
R = np.array(R)
# V = [[0, -n.z, n.y],[n.z, 0, -n.x],[-n.y, n.x, 0]]
# I = np.zeros((3, 3), int)
# np.fill_diagonal(I, 1)
# RR = I + V + np.matmul(V, V)/(1 + vector.dot(v1, v2))
return R
def calulation_line_to_point(pt, v1, v2):
# all input must be type of vector, not checking now
a = v1 - v2
b = pt - v2
c = pt - v1
a1 = np.arccos(vector.dot(a, b) / (a.mag * b.mag))
a2 = np.arccos(vector.dot(-a, c) / (a.mag * c.mag))
if max(np.rad2deg(a1), np.rad2deg(a2)) > 90:
dist = min(b.mag, c.mag)
else:
dist = vector.cross(a, b).mag / a.mag
return dist
def calculation_spring_vector(P0, P1, P2, P0_len, P1_len, P2_len, P_P_len):
# P0 has the shortest len
# P2 is the next point from conter-clockwise order, P1 is the next point from clockwise order
# if there are two shortest len, the order should be P0_len = P2_len are shortest
# P0, P1, P2, P0_len, P1_len, P2_len, P_P_len
''' trouble shooting
P0 = self.walls[0]
P1 = self.walls[2]
P2 = self.walls[4]
P0_len = 0.1
P1_len = 0.8
P2_len = 0.1
P_P_len = self.spr_distance
'''
P0_len = round(P0_len, 7)
P1_len = round(P1_len, 7)
P2_len = round(P2_len, 7)
L1 = P1_len - P0_len
L2 = P2_len - P0_len
# situation all len are the same
if P1_len == P0_len and P0_len == P2_len:
grow_dir = vector.cross(P2 - P0, P1 - P0)
list = []
list.append(grow_dir.hat | |
<filename>interface.py
import re
import googleapiclient
import os
import sys
import subprocess
import urllib.request
import tempfile
import tkinter
import ffmpeg_script
import api_logic
import typing
import time
from pathlib import Path
from tkinter import filedialog, messagebox, ttk, font
from ffmpeg_script import *
from api_logic import *
from typing import List, Tuple, Iterable, IO, Any
from functools import partial
from PIL import Image, ImageTk
from googleapiclient.discovery import build
current_directory = os.getcwd()
if getattr(sys, 'frozen', False):
current_directory = os.path.dirname(sys.argv[0])
else:
current_directory = Path(__file__).resolve().parent
root = tkinter.Tk()
canvas = tkinter.Canvas(root, name = "canvas", width = 485, height = 300, )
canvas.place(x = 5, y= 135)
thumbnails_list = []
search_type = tkinter.IntVar()
search_type.set(1)
download_type = tkinter.StringVar()
download_type.set("")
EYE_CLOSED_IMAGE = tkinter.PhotoImage(file = f"{current_directory}/images/password_eye_closed.png") # Mode 0
EYE_OPEN_IMAGE = tkinter.PhotoImage(file = f"{current_directory}/images/password_eye_open.png") # Mode 1
EYE_MODE = 0
videos_listed = []
class Thumbnail_Image():
def __init__(self, url: str = None, temp_file: IO[Any] = None, scale: int = None, width: int = None, height: int = None, image: tkinter.PhotoImage = None, overlord = None):
global thumbnails_list
self.url = url
self.temp_file = temp_file
self.scale = scale
self.width = width
self.height = height
self.image = image
self.overlord = overlord
thumbnails_list.append(self)
def download_from_url(self) -> None:
"""Downloads contents from self.url and stores it in a temp file referenced as self.temp_file."""
self.temp_file = tempfile.NamedTemporaryFile()
urllib.request.urlretrieve(url = self.url, filename= self.temp_file.name)
self.image = ImageTk.PhotoImage(Image.open(self.temp_file.name))
def place_thumbnail_from_temp(self) -> None:
"""Takes image stored in self.temp_file, and stores it in self.image -> places self.image on canvas using tkinter canvas.create_image()"""
self.image = ImageTk.PhotoImage(Image.open(self.temp_file.name))
thumbnail_placeholder = canvas.create_image((self.scale/2 + 20, self.scale/2 + 5), image = self.image)
def place_thumbnail_from_image(self) -> None:
"""Places self.image on canvas using tkinter canvas.create_image()."""
thumbnail_placeholder = canvas.create_image((self.scale/2 + 20, self.scale/2 + 5), image = self.image)
def destroy(self) -> None:
"""If there is a temp file referenced by self.temp_file, properly closes the temp file."""
if self.temp_file is not None:
self.temp_file.close()
class Error():
def __init__(self, master = root, title:str = "Error", message:str = "Error", name:str = None, frame: tkinter.Frame = None, x_pos:int = None, y_pos:int = None):
self.master = master
self.title = title
self.message = message
self.name = name
self.x_pos = x_pos
self.y_pos = y_pos
def popup(self) -> None:
global search_type
def place_frame_math(self) -> None:
"""Conducts the math necessary to place popup on canvas (in a pretty way :D)"""
my_font = font.Font(family = "Helevetica", size = 13) #Default is most likely the same font/size as this
text_length = my_font.measure(self.message) # Gets text message width
message = tkinter.Text(font = my_font)
message.insert("end", self.message,) # Gets text message height
width = text_length
height = 3 * message.cget("height") # 3 lines of text, presumably same message height
canvas_width = canvas.winfo_width()
canvas_height = canvas.winfo_height()
x = (canvas_width - width)//2 - 15 # Necessary shift of 15 to account for X button.
y = (canvas_height - height)//2
self.x_pos = x
self.y_pos = y
def move_self(self) -> None:
"""Places self at given x and y co-ordinates"""
self.frame.place(x = self.x_pos, y = self.y_pos)
canvas.update()
def kill_by_name(self) -> None:
"""Eliminated other objects with same name. All Error obj should have same name; 'popup' """
try:
fake = find_canvas_widget_by_name(self.name)
fake.kill_self(fake)
except:
#Means this is the first error popup. Others do have not been made yet.
pass
mode = search_type.get()
if mode == 1:
colour = "#ffc3a9"
elif mode == 2:
colour = "#ffd8a9"
else:
colour = "#ffada9"
kill_by_name(self.name)
self.frame = tkinter.Frame(master = canvas, name = self.name, bg = colour, relief = "solid", borderwidth = 2,)
exit_button = tkinter.Button(master= self.frame, text = "X", command = self.kill_self, highlightbackground = colour,).grid(row = 1, column = 3) #.place(x = 130, y = 2)
error_title = tkinter.Label(master = self.frame, text = self.title, bg = colour).grid(row = 1, column = 1)
filler = tkinter.Label(master = self.frame, text = "", bg = colour).grid(row= 2, column = 1)
error_message = tkinter.Label(master = self.frame, text = self.message, bg = colour, ).grid(row = 3, column = 1)
place_frame_math(self)
move_self(self)
def kill_self(self) -> None:
"""Eliminates own existance."""
self.frame.pack_forget()
self.frame.destroy()
#Mode 1 popup colour #ffc3a9
#Mode 2 popup colour #ffd8a9
#Mode 3 popup colour #ffada9
class Video():
def __init__(self, master:canvas, video_id:str, thumbnail:Thumbnail_Image = None, name:str = None, channel:str = None, selected:str = "1", yes_photo: tkinter.PhotoImage = None, no_photo: tkinter.PhotoImage = None, x:int = 0, y:int = 0, colour:str = None, video_canvas:canvas = None):
self.master = master
self.video_id = video_id
self.thumbnail = thumbnail
self.name = name
self.channel = channel
self.selected = selected
self.yes_photo = yes_photo
self.no_photo = no_photo
self.colour = colour
self.x = x
self.y = y
self.video_canvas = video_canvas
#Getting Thumbnail
thumbnail = Thumbnail_Image(url = f"https://img.youtube.com/vi/{self.video_id}/default.jpg", overlord = self)
thumbnail.download_from_url()
self.thumbnail = thumbnail
#Making check and x buttons' image
self.yes_photo = resize_image(f"{current_directory}/images/check_mark.png", 10, 10)
self.no_photo = resize_image(f"{current_directory}/images/x_mark.png", 10, 10)
#Setting background
current_mode = search_type.get()
if current_mode == 2:
self.colour = "#e4e0ff"
elif current_mode == 3:
self.colour = "#ebffef"
#Colours: Mode2: "#b2a9ff" Mode3: "#a9ffbc"
#Colours: Mode2: "#e4e0ff" Mode3: "#ebffef"
def get_video(self) -> None:
"""Conducts the search for video, updating information about self, or causing error popup."""
return_value = search_video(video_id = self.video_id, API_KEY= retrieve_key())
if return_value == "Invalid API Key":
error = Error(message = "Please input a valid Youtube V3 Data Api Key.", name = "popup")
error.popup()
return
elif return_value == "Invalid Video Info":
error = Error(message = "Please input valid video information.", name = "popup")
error.popup()
return
else:
title, channel_name, thumbnail_link, thumbnail_width, thumbnail_height = return_value
self.name = title
self.channel = channel_name
def draw_self(self) -> None:
"""Creates canvas, and draws self on it. Results in rectangular box with thumbnail image, name, channel, and buttons. """
self.video_canvas = tkinter.Canvas(self.master, width = 430, height = 100, bg = self.colour, highlightthickness = 0, bd = 1, relief = "ridge",)
self.master.create_window((self.x -66, self.y), window = self.video_canvas, width = 430, height = 100, anchor = "w")
self.video_canvas.create_image((70- 5, 55 - 5), image = self.thumbnail.image)
self.video_canvas.create_text((70 + 65, 55 - 25), text = self.name, anchor = "w",)
self.video_canvas.create_text((70 + 65, 55), text = self.channel, anchor = "w",)
MODES = [(self.yes_photo, "1"),
(self.no_photo, "2")]
variable = tkinter.StringVar()
variable.set(self.selected)
self.selected = variable
for image, mode in MODES:
button = tkinter.Radiobutton(master= self.video_canvas, image = image, variable = variable, value = mode, bg = self.colour, command = self.check_printable,)
button.place(x = 70 + 320, y = 55 + 20*int(mode) - 30)
self.master.update()
def destroy_temp_file(self) -> None:
""" Proper elimination of thumbnail and temp file of video's associated thumbnail image."""
self.thumbnail.destroy()
def check_printable(self) -> str:
"""Returns value for a video's selected attribute. This will be either 1 or 2, representing yes and no respectively."""
return self.selected.get()
def init_screen() -> None:
"""Creates the general screen of app"""
global download_type
def download_type_selection() -> None:
global download_type
download_formats = [
"mp4",
"m4a",
"webm",
]
download_type.set(download_formats[0])
drop = tkinter.OptionMenu(root, download_type, *download_formats)
drop.place(x = 375, y= 100)
root.title("Youtube Video Downloader")
root.geometry("500x500+650+250")
root.minsize(width = 500, height = 500)
root.maxsize(width = 500, height = 500)
#Setting main screen size, relative initial position, background colour
tkinter.Label(root, text = "Youtube API Key").place(x= 5, y = 10)
tkinter.Label(root, text = "Download Location").place(x = 5, y = 50)
tkinter.Entry(root, name = "api_input", width = 39).place(x = 130, y = 10)
tkinter.Entry(root, name = "path", width = 30).place(x= 130, y = 50)
tkinter.Button(root, name = "path_button", text = "Browse", width = 8, command = select_path).place(x = 415, y = 53)
tkinter.Button(root, name = "secret_button", image = EYE_CLOSED_IMAGE, command = swap_entry_mode).place(x = 466, y = 12)
tkinter.Button(root, name = "help button", text = "HELP", width = 5, pady= 5, command= help_me).place(x= 445, y = 97)
download_type_selection()
def select_path() -> None:
"""Opens popup prompting user to pick a directory. Fills 'path' entry widget with path."""
root.update()
directory = str(tkinter.filedialog.askdirectory(title= "Download Path Selection", parent= root))
root.update()
entry = find_widgets_by_name("path")
entry.delete(0, "end")
entry.insert(0, directory)
def help_me() -> None:
""" Makes a new window which is used to display help instructions."""
def popup_message(msg):
norm_font = ("Helvetica", 13)
pop_up = tkinter.Tk()
pop_up.wm_title("Helper")
label = tkinter.Label(pop_up, text = msg, font = norm_font, width = 75, height = 25)
label.pack(side= "right", fill = "x", pady = 10)
message = """
Instructions:
Get an API Key with https://developers.google.com/youtube/v3/getting-started
Follow the instruction at the link, | |
def make_partition_list(N, mod=10**9+7):
# http://d.hatena.ne.jp/inamori/20121216/p1
# N 以下の分割数のリストを返す O(n**(3/2))
# mod は素数でなくても良い
from itertools import count
P = [0]*(N+1)
P[0] = 1
for n in range(1, N+1):
p = 0
m1 = 0
for k in count(1):
m1 += 3*k - 2 # m1 = k * (3*k-1) // 2
if n < m1:
break
p += P[n-m1] if k%2==1 else -P[n-m1]
m2 = m1 + k # m2 = k * (3*k+1) // 2
if n < m2:
break
p += P[n-m2] if k%2==1 else -P[n-m2]
p %= mod
P[n] = p
return P
import sys
from functools import lru_cache
sys.setrecursionlimit(500000)
mod = 10**9+7
@lru_cache(maxsize=None)
def partition(n, k): # 自然数 n を k 個の自然数の和で表す場合の数
if n < 0 or n < k:
return 0
elif k == 1 or n == k:
return 1
else:
return (partition(n-k, k) + partition(n-1, k-1)) % mod # 1 を使わない場合と使う場合の和
"""
# 原始ピタゴラス数
from math import gcd
N = 1500000
cnt = [0]*(N+1)
L = []
for m in range(2, 10**4):
for n in range(1, m):
a = m*m-n*n
b = 2*m*n
c = m*m+n*n
if gcd(gcd(a,b),c)!=1: # 原始ピタゴラス数以外も生成するので弾く
continue
L.append(sorted([a,b,c]))
"""
def euler_phi(n):
# http://tjkendev.github.io/procon-library/python/prime/eulers-totient-function.html
# オイラーのφ関数
res = n
for x in range(2, int(n**.5)+1):
if n % x == 0:
res = res // x * (x-1)
while n % x == 0:
n //= x
return res
"""
# オイラーのφ関数(前計算あり)
N = 10**7
isPrime = [True] * (N+1)
isPrime[0] = isPrime[1] = False
for i in range(2, int((N+1)**0.5)+1):
if isPrime[i]:
for j in range(i*i, N+1, i):
isPrime[j] = False
primes = [i for i, f in enumerate(isPrime) if f]
prime_factors = [[] for _ in range(N+1)]
for p in primes:
for i in range(p, N+1, p):
prime_factors[i].append(p)
def euler_phi(n):
for p in prime_factors[n]:
n = n // p * (p-1)
return n
"""
"""
# Project Euler 80
# 平方根、任意精度小数
from decimal import Decimal, getcontext
getcontext().prec = 111
ans = 0
for i in range(100):
s = str(Decimal(i).sqrt()).replace(".", "")
if len(s)>100:
ans += sum(map(int, s[:100]))
print(ans)
"""
from math import gcd, sqrt
from collections import defaultdict
from itertools import count
def continued_frac(n):
# sqrt(n) の連分数展開
sqrt_n = int(sqrt(n))
if sqrt_n**2 == n:
return [sqrt_n], 0
a0 = r = sqrt_n
def solve(right, denom):
# (sqrt(n) - right) / denom を 1 / (? + (sqrt(n)-?) / ?) にする
assert right > 0, (n, right, denom)
denom_new = (n - right*right) // denom # 必ず割り切れる??
a, m = divmod(sqrt_n+right, denom_new)
return a, sqrt_n-m, denom_new
dd = defaultdict(lambda: -2)
d = 1
dd[(r, d)] = -1
res = [a0]
for i in count():
a, r, d = solve(r, d)
res.append(a)
if (r, d) in dd:
period = i - dd[(r, d)]
break
dd[(r, d)] = i
return res, period
def inv_continued_frac(L):
# 正則連分数を通常の分数に戻す
numer, denom = 1, L[-1]
for v in L[-2::-1]:
numer += v * denom
denom, numer = numer, denom
denom, numer = numer, denom
return numer, denom
def solve_pell(n):
# ペル方程式 x*x - n*y*y = 1 の最小整数解
# 解無しのとき -1, -1 を返す
if int(sqrt(n))**2 == n:
return -1, -1
con_fr, period = continued_frac(n)
x, y = inv_continued_frac(con_fr[:-1])
if period%2 == 1:
x, y = x*x + y*y*n, 2*x*y
return x, y
def more_pell_solutions(n, x, y):
# x, y が解のとき、
# x_k + y_k √n = (x + y √n)^k
# もすべて解となる(ブラーマグプタの恒等式)
yield x, y
x_, y_ = x, y
while True:
x, y = x*x_+n*y*y_, x*y_+y*x_
yield x, y
def solve_pell_minus(n):
# ペル方程式の拡張 x*x - n*y*y = -1 の最小整数解
# 解無しのとき -1, -1 を返す
if int(sqrt(n))**2 == n:
return -1, -1
con_fr, period = continued_frac(n)
x, y = inv_continued_frac(con_fr[:-1])
if period%2 == 1:
return x, y
else:
return (-1, -1)
def more_pell_minus_solutions(n, x, y):
x_, y_ = x*x + y*y*n, 2*x*y
while True:
x, y = x*x_+n*y*y_, x*y_+y*x_
yield x, y
# カレンダー系
# https://atcoder.jp/contests/arc010/submissions/6917100
# https://atcoder.jp/contests/arc002/submissions/6923018
days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
days_leap = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def is_leap_year(y): # 閏年判定
if y%400==0: return True
elif y%100==0: return False
elif y%4==0: return True
else: return False
def zeller(y, m, d): # ツェラーの公式
# 土曜日 -> 0
if m<=2:
m += 12
y -= 1
C, Y = divmod(y, 100)
h = (d + 26*(m+1)//10 + Y + Y//4 + (-2*C+C//4)) % 7
return h
def md2d(m, d): # m 月 d 日は 0-indexed で何日目か?
# 返り値は [0, 365)
return sum(days[:m]) + d - 1
def all_md():
for m, ds in enumerate(days[1:], 1):
for d in range(1, ds+1):
yield m, d
def all_ymd(y_start, y_end):
for y in range(y_start, y_end):
for m, d in all_md(days=days_leap if is_leap_year(y) else days):
yield y, m, d
class Factoradic:
# 階乗進数
# n (0-indexed) 桁目は n+1 進法、すなわち n 桁目の数字は [0, n] の範囲
# n 桁目の 1 は n! を表す
# 検証: https://atcoder.jp/contests/arc047/submissions/7436530
factorial = [1]
def __init__(self, a):
self.value = value = [] # 下の位から入れていく
if isinstance(a, int):
n = 1
while a:
a, m = divmod(a, n)
value.append(m)
n += 1
elif hasattr(a, "__iter__"):
self.value = list(a)
else:
raise TypeError
def __int__(self):
res = 0
f = 1
for i, v in enumerate(self.value[1:], 1):
f *= i
res += v * f
return res
def _set_factorial(self, val):
factorial = Factoradic.factorial
n = len(factorial)
f = factorial[-1]
while f < val:
f *= n
factorial.append(f)
n += 1
def to_permutation(self, d):
# [0, d) の順列のうち、辞書順 self 番目 (0_indexed) のものを返す
# self >= d! の場合は、self mod d! 番目のものを返す
# O(d log d)
value = self.value
value += [0] * (d-len(value))
res = []
n = 1 << d.bit_length()
bit = [i&-i for i in range(n)] # BIT を 1 で初期化 (1-indexed)
for v in value[d-1::-1]:
i, step = 0, n>>1
while step: # BIT 上の二分探索
if bit[i+step] <= v:
i += step
v -= bit[i]
else:
bit[i+step] -= 1 # 減算も同時に行う
step >>= 1
res.append(i) # i 要素目までの累積和が v 以下になる最大の i
return res
def __isub__(self, other): # other は Factoradic 型
value = self.value
value_ = other.value
value += [0] * (len(value_)-len(value))
m = 0 # 繰り下がり
for i, v in enumerate(value_[1:]+[0]*(len(value)-len(value_)), 1):
value[i] -= v + m
if value[i] < 0:
value[i] += i + 1
m = 1
else:
m = 0
if m==1:
assert False
return self
def __ifloordiv__(self, other): # other は int 型
value = self.value
m = 0
for n in range(len(value)-1, -1, -1):
v = value[n] + m
value[n], m = divmod(v, other)
m *= n
return self
def lagrange_interpolation(X, Y, mod):
# ラグランジュ補間 O(n^2)
# n 個の条件から n-1 次多項式を作る 返り値は次数の降順
# 検証: https://atcoder.jp/contests/abc137/submissions/6845025
# mod を取らない場合 scipy.interpolate.lagrange が使えそう
n = len(X)
g = [0]*(n+1)
g[0] = 1
for i, x in enumerate(X):
for j in range(i, -1, -1):
g[j+1] += g[j] * (-x) % mod
res = [0]*n
for x, y in zip(X, Y):
f = g[:]
denom = 0
v = 1
pow_x = [1] # x の idx 乗
for _ in range(n-1):
v = v * x % mod
pow_x.append(v)
pow_x.reverse() # n-1 乗 ~ 0 乗
for i, po in enumerate(pow_x):
f_i = f[i]
f[i+1] += f_i * x % mod # f = g / (x - x_i) を組立除法で求める
denom = (denom + f_i * po) % mod
denom_inv = pow(denom, mod-2, mod)
for i, f_i in enumerate(f[:n]):
res[i] += (f_i * y * denom_inv)# % mod # mod が大きいと 64bit に収まらなくなるのでひとつずつ mod 取った方がいいか?
return [v % mod for v in res]
# karatsuba 法
def list2bigint(lst, bit=64): # 非負整数のみ
fmt = "0{}x".format(bit//4)
return int("".join(format(v, fmt) for v in lst), 16)
def bigint2list(n, bit=64, length=None): # length を指定しない場合左側の 0 は省略されるので注意
n_hex = bit//4
s = format(n, "0{}x".format(n_hex*length) if length else "x")
s = -len(s) % n_hex * "0" + s
return [int(s[i:i+n_hex], 16) for i in range(0, len(s), n_hex)]
def gauss_jordan(A):
# F2 上の Gauss Jordan の掃き出し法
# 基底を取り出す
# 引数を破壊的に変更する
idx = 0
for i in range(59, -1, -1):
for j, a in enumerate(A[idx:], idx):
if a>>i & 1:
break
else:
continue
A[idx], A[j] = A[j], A[idx]
for | |
'M',
87: 'u', 88: 'E', 89: 'P', 90: 'W', 91: 'j', 92: 'L', 93: 'O', 94: 'T',
95: 'X', 96: 'p', 97: 'B', 98: 'u', 99: '^', 100: '\\', 101: 'c',
102: 'l', 103: 'k', 104: '0', 105: '4', 106: 'I', 107: 'C', 108: '^',
109: 'A', 110: '3', 111: 'E', 112: 'g', 113: 'b', 114: 'v', 115: '`',
116: '@', 117: 'U', 118: 'u', 119: 'h', 120: 'G', 121: 'S'},
100: {48: '\\', 49: 'v', 50: '3', 51: '[', 52: 'N', 53: '>', 54: 'x',
55: '2', 56: 'Z', 57: 'j', 58: 'v', 59: 'y', 60: '<', 61: 'S',
62: 'y', 63: '2', 64: 'k', 65: 'F', 66: '4', 67: '\\', 68: 'l',
69: 'p', 70: 'I', 71: 'c', 72: '4', 73: 'E', 74: '8', 75: 'N',
76: 'Z', 77: 'A', 78: 'A', 79: 'j', 80: 'u', 81: 't', 82: '7',
83: 'H', 84: 'L', 85: '6', 86: '_', 87: '0', 88: 'R', 89: 'n',
90: '4', 91: '0', 92: 'O', 93: 'F', 94: '>', 95: 'd', 96: 'C',
97: '6', 98: 'c', 99: 'L', 100: 'N', 101: '1', 102: '>', 103: '?',
104: 'c', 105: 'U', 106: 'G', 107: 'Z', 108: '1', 109: 'B', 110: '5',
111: 'm', 112: '<', 113: '`', 114: 'T', 115: 's', 116: '5', 117: 'S',
118: 'D', 119: 'l', 120: '9', 121: '^'},
101: {48: 'v', 49: 'W', 50: '^', 51: 'g', 52: '9', 53: 'y', 54: 't',
55: 'U', 56: 'm', 57: '?', 58: ':', 59: 'k', 60: '0', 61: 'O',
62: 'u', 63: 'S', 64: 'Y', 65: 'V', 66: 'v', 67: '6', 68: 'w',
69: 'Y', 70: 'y', 71: 'I', 72: '_', 73: 'G', 74: '[', 75: '2',
76: 'D', 77: 'U', 78: 'H', 79: 'g', 80: '<', 81: 'H', 82: 'u',
83: 'f', 84: 'b', 85: ';', 86: '<', 87: '[', 88: 'F', 89: '3',
90: ';', 91: 'y', 92: '?', 93: 'I', 94: 'M', 95: 'f', 96: 'S',
97: ';', 98: 'z', 99: 'W', 100: 'I', 101: 'f', 102: 'r', 103: 'z',
104: 'q', 105: 'Z', 106: 'Y', 107: 'S', 108: 'P', 109: 'Q', 110: 'Y',
111: 'M', 112: '1', 113: '9', 114: 'h', 115: '2', 116: '`', 117: '`',
118: 'I', 119: 'J', 120: 'Z', 121: 'M'},
102: {48: ']', 49: 'T', 50: '7', 51: 'K', 52: ']', 53: 'V', 54: 'W',
55: '2', 56: ';', 57: 's', 58: 'I', 59: 'h', 60: 'U', 61: 'u',
62: 'o', 63: 'f', 64: '`', 65: 'y', 66: 'q', 67: 'G', 68: '4',
69: 'h', 70: 'j', 71: 'J', 72: '2', 73: 'p', 74: ':', 75: '^',
76: 'B', 77: 'E', 78: '[', 79: 'q', 80: 'l', 81: 'L', 82: 'm',
83: '4', 84: 'm', 85: 'o', 86: 'g', 87: 'Y', 88: '<', 89: '<',
90: 'r', 91: 'p', 92: 'z', 93: '9', 94: 'P', 95: 'v', 96: 'y',
97: 'c', 98: 't', 99: 'B', 100: 'u', 101: '7', 102: 'S', 103: 'C',
104: 'q', 105: 'k', 106: ':', 107: 'Y', 108: 'e', 109: 'k', 110: '=',
111: 'o', 112: 'f', 113: 'V', 114: 'X', 115: 'O', 116: 'G', 117: 'f',
118: 'l', 119: 'B', 120: '=', 121: 'z'},
103: {48: '2', 49: 'd', 50: 'v', 51: 'f', 52: 't', 53: 'v', 54: 'm',
55: '?', 56: '\\', 57: 'Q', 58: 'j', 59: '?', 60: 'W', 61: '9',
62: '0', 63: '6', 64: 'I', 65: 'B', 66: 'p', 67: 'z', 68: '=',
69: '?', 70: ':', 71: '@', 72: 'Q', 73: 'G', 74: 'Z', 75: '?',
76: 'u', 77: 'f', 78: 'g', 79: 'Q', 80: 'y', 81: 'z', 82: 'U',
83: 'l', 84: ']', 85: 'F', 86: 'N', 87: 'J', 88: '`', 89: 'T',
90: 'D', 91: '8', 92: 'l', 93: 'c', 94: '<', 95: 'n', 96: 'Y',
97: 'p', 98: 'h', 99: 'r', 100: 'p', 101: ']', 102: 'z', 103: '>',
104: 'M', 105: '0', 106: 'P', 107: 'A', 108: '2', 109: 'R', 110: 'V',
111: 'W', 112: '@', 113: 'M', 114: '2', 115: 'v', 116: 'J', 117: '?',
118: '6', 119: 'A', 120: 'Q', 121: 'i'},
104: {48: '?', 49: 'X', 50: 'O', 51: 't', 52: 'y', 53: 'Z', 54: 'J',
55: '`', 56: 's', 57: '=', 58: 'z', 59: 'B', 60: '[', 61: 'U',
62: 'G', 63: 'z', 64: 'X', 65: 'Y', 66: '@', 67: 't', 68: 'k',
69: ']', 70: '?', 71: 'F', 72: '6', 73: 'G', 74: 'l', 75: '7',
76: 'f', 77: 'D', 78: 'l', 79: ';', 80: '[', 81: 'W', 82: '=',
83: 'u', 84: '6', 85: 'o', 86: '[', 87: 'D', 88: 'x', 89: 'n',
90: 'w', 91: 'S', 92: '[', 93: 'o', 94: 'Z', 95: 'c', 96: 'd',
97: 'g', 98: '?', 99: 'X', 100: '`', 101: 'q', 102: 'u', 103: '3',
104: 'v', 105: 'j', 106: 'b', 107: ':', 108: '1', 109: 'B', 110: 'e',
111: 'B', 112: '1', 113: 'G', 114: 'H', 115: 'I', 116: 'a', 117: 'W',
118: 'C', 119: 'Z', 120: 'g', 121: '0'},
105: {48: 'h', 49: 'W', 50: '5', 51: 'b', 52: '2', 53: '@', 54: 'F',
55: 'V', 56: '9', 57: 'i', 58: '5', 59: 'P', 60: 'w', 61: 'B',
62: '_', 63: 'w', 64: 'b', 65: '8', 66: '2', 67: 'd', 68: 'x',
69: 'v', 70: '=', 71: 'J', 72: '6', 73: 'h', 74: '1', 75: '6',
76: 'k', 77: 'f', 78: '_', 79: 'j', 80: 'D', 81: 'F', 82: '`',
83: 'k', 84: 'Y', 85: '^', 86: 'T', 87: '1', 88: '3', 89: '0',
90: '1', 91: 'x', 92: 'p', 93: 'N', 94: '2', 95: 'R', 96: ';',
97: '@', 98: 'M', 99: '[', 100: '[', 101: '3', 102: 's', 103: 'q',
104: 'C', 105: 'S', 106: 'w', 107: 'm', 108: 'm', 109: 'H', 110: 'v',
111: 'q', 112: '[', 113: '>', 114: '6', 115: 'v', 116: '2', 117: 'U',
118: 'N', 119: '^', 120: 'L', 121: 'D'},
106: {48: '^', 49: '3', 50: 'g', 51: 'z', 52: 'm', 53: 'V', 54: 'p',
55: '`', 56: 'q', 57: '@', 58: 'J', 59: 'S', 60: 'D', 61: '>',
62: 'w', 63: '^', 64: 'G', 65: '5', 66: 'x', 67: 'X', 68: '5',
69: 'e', 70: 'D', 71: 'R', 72: 'w', 73: 'V', 74: 'V', 75: ';',
76: '4', 77: 'W', 78: 'g', 79: '6', 80: ':', 81: 'm', 82: 'y',
83: 'p', 84: '<', 85: 'R', 86: '^', 87: 'D', 88: 'y', 89: 't',
90: ':', 91: 'I', 92: '6', 93: 'c', 94: 'e', 95: 'E', 96: 'm',
97: '[', 98: '_', 99: 'A', 100: 'O', 101: 'z', 102: 'f', 103: 'N',
104: '^', 105: 'R', 106: 'i', 107: '4', 108: 'p', 109: 'o', 110: '<',
111: 'u', 112: ':', 113: '>', 114: 'm', 115: 'k', 116: '_', 117: '3',
118: '2', 119: 'Z', 120: 'G', 121: 'l'},
107: {48: 'E', 49: 'n', 50: 'M', 51: 'D', 52: '[', 53: 'j', 54: 'S',
55: 'F', 56: '?', 57: '`', 58: 'P', 59: 'n', 60: 'H', 61: ';',
62: 'z', 63: 'n', 64: 'G', 65: 'F', 66: 'k', 67: 'i', 68: '3',
69: 'q', 70: 'v', 71: '[', 72: 'R', 73: '=', 74: '^', 75: '[',
76: 'o', 77: 'I', 78: 'L', 79: '5', 80: 'W', 81: 'J', 82: 'h',
83: 'W', 84: 'v', 85: 'j', 86: ';', 87: 'e', 88: 'v', 89: 'Z',
90: 'G', 91: 's', 92: '^', 93: 'y', 94: 'O', 95: 'q', 96: 'f',
97: 'F', 98: 'F', 99: 'Q', 100: 'I', 101: 'Y', 102: 'c', 103: 'G',
104: 'T', 105: 'L', 106: '_', 107: ';', 108: 'M', 109: 'p', 110: 'P',
111: '5', 112: 'Q', 113: 'n', 114: 'Q', 115: 'B', 116: 'V', 117: 'c',
118: 'j', 119: '\\', 120: '\\', 121: 'N'},
108: {48: 'w', 49: 'q', 50: 'w', 51: 'f', 52: 'a', 53: 'u', 54: '^',
55: 'S', | |
:type vv1: GXVV
:type vv2: GXVV
.. versionadded:: 5.0.8
**License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_
**Note:** Removes all indices where either `GXVV <geosoft.gxapi.GXVV>` has a dummy, or is
not defined (due to length differences).
"""
gxapi_cy.WrapVVU._remove_dummy2(GXContext._get_tls_geo(), vv1, vv2)
@classmethod
def remove_dummy3(cls, vv1, vv2, vv3):
"""
Remove dummy values from 3 VVs.
:param vv1: `GXVV <geosoft.gxapi.GXVV>` object
:param vv2: `GXVV <geosoft.gxapi.GXVV>` object
:param vv3: `GXVV <geosoft.gxapi.GXVV>` object
:type vv1: GXVV
:type vv2: GXVV
:type vv3: GXVV
.. versionadded:: 5.0.8
**License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_
**Note:** Removes all indices where any `GXVV <geosoft.gxapi.GXVV>` has a dummy, or is
not defined (due to length differences).
"""
gxapi_cy.WrapVVU._remove_dummy3(GXContext._get_tls_geo(), vv1, vv2, vv3)
@classmethod
def remove_dummy4(cls, vv1, vv2, vv3, vv4):
"""
Remove dummy values from 4 VVs.
:param vv1: `GXVV <geosoft.gxapi.GXVV>` object
:param vv2: `GXVV <geosoft.gxapi.GXVV>` object
:param vv3: `GXVV <geosoft.gxapi.GXVV>` object
:param vv4: `GXVV <geosoft.gxapi.GXVV>` object
:type vv1: GXVV
:type vv2: GXVV
:type vv3: GXVV
:type vv4: GXVV
.. versionadded:: 6.2
**License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_
**Note:** Removes all indices where any `GXVV <geosoft.gxapi.GXVV>` has a dummy, or is
not defined (due to length differences).
"""
gxapi_cy.WrapVVU._remove_dummy4(GXContext._get_tls_geo(), vv1, vv2, vv3, vv4)
@classmethod
def remove_dup(cls, data_vv, sample_vv, output):
"""
Remove/average duplicate sample pairs from a database.
:param data_vv: Data `GXVV <geosoft.gxapi.GXVV>`
:param sample_vv: Sample Type `GXVV <geosoft.gxapi.GXVV>`
:param output: :ref:`VV_DUP`
:type data_vv: GXVV
:type sample_vv: GXVV
:type output: int
.. versionadded:: 5.0
**License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_
**Note:** Created for duplicate sample handling in `GXCHIMERA <geosoft.gxapi.GXCHIMERA>`. On input,
a numeric or text `GXVV <geosoft.gxapi.GXVV>` containing data values, and a sample type `GXVV <geosoft.gxapi.GXVV>`.
Sample pairs have types "1" and "2". This routine searches for
types in order "1 2 1 2", and replaces the pair of values in the
data `GXVV <geosoft.gxapi.GXVV>` according to the :ref:`VV_DUP` value.
Results for samples out of order, for unmatched pairs, or when the
sample type does not equal "1" or "2" remain unchanged.
"""
gxapi_cy.WrapVVU._remove_dup(GXContext._get_tls_geo(), data_vv, sample_vv, output)
@classmethod
def remove_xy_dup(cls, xvv, yvv, zvv, xy_dup):
"""
Remove/average duplicate samples with the same (X, Y).
:param xvv: X `GXVV <geosoft.gxapi.GXVV>`
:param yvv: Y `GXVV <geosoft.gxapi.GXVV>`
:param zvv: (optional) Z `GXVV <geosoft.gxapi.GXVV>`
:param xy_dup: :ref:`VV_XYDUP`
:type xvv: GXVV
:type yvv: GXVV
:type zvv: GXVV
:type xy_dup: int
.. versionadded:: 5.0
**License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_
**Note:** Searches for duplicated (X, Y) locations and removes the
duplicates (can be more than just a pair). The "Z" values,
if defined, are treated according to the value of :ref:`VV_XYDUP`.
The returned VVs are shortened to the new length, without
duplicates.
The Z `GXVV <geosoft.gxapi.GXVV>` can be set to NULL on input, in which case it is ignored.
"""
gxapi_cy.WrapVVU._remove_xy_dup(GXContext._get_tls_geo(), xvv, yvv, zvv, xy_dup)
@classmethod
def remove_xy_dup_index(cls, xvv, yvv, index_vv):
"""
Remove duplicate samples with the same (X, Y) and update index.
:param xvv: X `GXVV <geosoft.gxapi.GXVV>`
:param yvv: Y `GXVV <geosoft.gxapi.GXVV>`
:param index_vv: Index `GXVV <geosoft.gxapi.GXVV>`
:type xvv: GXVV
:type yvv: GXVV
:type index_vv: GXVV
.. versionadded:: 7.2
**License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_
**Note:** Searches for duplicated (X, Y) locations and removes the
duplicates (can be more than just a pair). The Index `GXVV <geosoft.gxapi.GXVV>` is
updated accordingly .i.e if (X,Y) location of Index[0] == Index[1]
Index[1] is removed.
"""
gxapi_cy.WrapVVU._remove_xy_dup_index(GXContext._get_tls_geo(), xvv, yvv, index_vv)
@classmethod
def rolling_stats(cls, vv_i, vv_o, stat, window, shrink):
"""
Calculate a statistic in a rolling window.
:param vv_i: Input `GXVV <geosoft.gxapi.GXVV>`
:param vv_o: Output `GXVV <geosoft.gxapi.GXVV>`
:param stat: :ref:`ST_INFO`
:param window: Window size (>0, increased to nearest odd value)
:param shrink: Shrink window at ends (1:Yes, 0:No)
:type vv_i: GXVV
:type vv_o: GXVV
:type stat: int
:type window: int
:type shrink: int
.. versionadded:: 5.1
**License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_
**Note:** If the input VVs are not REAL, copies are made to
temporary REALs for processing.
If the window size is even, it is increased by 1 so that the
output value is put at the exact center index of the window.
Statistics are calculated on the values in a window
surrounding the individual data points.
By shrinking the window at the ends, one-sided effects can be
eliminated. For instance, if the data is linear to begin with,
a rolling mean will not alter the original data.
However, if the window size is kept constant, then values
near the ends tend to be pulled up or down.
With shrinking, the window is shrunk so that it always has the
same width on both sides of the data point under analysis;
at the end points the window width is 1, at the next point in
it is 3, and so on, until the full width is reached.
The median value is calculated by sorting the valid data in
the window, then selecting the middle value. If the number
of valid data points is even, then the average of the two
central values is returned.
The mode value is defined as the value which occurs most
frequently in the data. This value may not even exist, or
may not be unique. In this implementation, the following
algorithm is used: The valid data in the window is sorted
in ascending order. The number of occurrences of each data
value is tracked, and if it occurs more times than any
value, it becomes the modal value. If all
values are different, this procedure returns the smallest
value. If two or more values each have the same (maximum)
number of occurrences, then the smallest of these values is
returned.
"""
gxapi_cy.WrapVVU._rolling_stats(GXContext._get_tls_geo(), vv_i, vv_o, stat, window, shrink)
@classmethod
def search_replace(cls, vv, val, rpl):
"""
Search and replace numeric values in a `GXVV <geosoft.gxapi.GXVV>`.
:param val: Value to replace
:param rpl: Replacement
:type vv: GXVV
:type val: float
:type rpl: float
.. versionadded:: 5.0
**License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_
**Note:** Search comparison is made on double comparison
of the data.
.. seealso::
SearchReplaceText_VV
"""
gxapi_cy.WrapVVU._search_replace(GXContext._get_tls_geo(), vv, val, rpl)
@classmethod
def search_replace_text(cls, vv, format, decimal, val, rpl, mode):
"""
Search and replace text values in a `GXVV <geosoft.gxapi.GXVV>`
:param format: String format for numeric `GXVV <geosoft.gxapi.GXVV>`
:param decimal: Decimals for formating numeric `GXVV <geosoft.gxapi.GXVV>`
:param val: Formatted string to replace
:param rpl: Replacement
:param mode: :ref:`VVU_SRCHREPL_CASE`
:type vv: GXVV
:type format: int
:type decimal: int
:type val: str
:type rpl: str
:type mode: int
.. versionadded:: 5.0
**License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_
**Note:** Search comparison is made on string comparison
of the data.
.. seealso::
SearchReplace_VV
"""
gxapi_cy.WrapVVU._search_replace_text(GXContext._get_tls_geo(), vv, format, decimal, val.encode(), rpl.encode(), mode)
@classmethod
def search_replace_text_ex(cls, vv, format, decimal, val, rpl, mode, items):
"""
Search and replace text values in a `GXVV <geosoft.gxapi.GXVV>`, count items changed.
:param format: String format for numeric `GXVV <geosoft.gxapi.GXVV>`
:param decimal: Decimals for formating numeric `GXVV <geosoft.gxapi.GXVV>`
:param val: Formatted string to replace
:param rpl: Replacement
:param mode: :ref:`VVU_SRCHREPL_CASE`
:param items: Number of items replaced (returned)
:type vv: GXVV
:type format: int
:type decimal: int
:type val: str
:type rpl: str
:type mode: int
:type items: int_ref
.. versionadded:: 6.0.1
**License:** `Geosoft End-User License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-end-user-lic>`_
**Note:** Search comparison is made on a string comparison
of the data.
.. seealso::
SearchReplaceText_VV
"""
items.value = gxapi_cy.WrapVVU._search_replace_text_ex(GXContext._get_tls_geo(), vv, format, decimal, val.encode(), rpl.encode(), mode, items.value)
@classmethod
def spline(cls, vv_x, vv_y, vv_o, length, start, incr, gap, ext, type):
"""
Spline a Y `GXVV <geosoft.gxapi.GXVV>` onto an X `GXVV <geosoft.gxapi.GXVV>`.
:param vv_x: X (no dummies)
:param vv_y: Y to be splined (no dummies)
:param vv_o: Y output
:param length: Output Length
:param start: Starting Location
:param incr: Separation Distance
:param gap: Maximum gap to interpolate across
:param ext: Number of elements to extend
:param type: :ref:`VVU_SPL`
:type vv_x: GXVV
:type vv_y: GXVV
:type vv_o: GXVV
:type length: int
:type start: float
:type incr: float
:type gap: float
:type ext: int
| |
== sync_t.CONTEXT: # pragma: no cover
return
if te_inst.subformat == sync_t.TRAP:
self.report_trap(te_inst)
if not te_inst.interrupt:
self.report_epc(self.exception_address(te_inst))
if te_inst.thaddr == 0:
return
self.inferred_address = False
self.address = te_inst.address << self.settings["iaddress_lsb_p"]
assert self.address != 0, te_inst.address
if te_inst.subformat == sync_t.TRAP or self.start_of_trace:
self.branches = 0
self.branch_map = 0
if self.get_instr(self.address).is_branch:
self.branch_map |= te_inst.branch << self.branches
self.branches += 1
if te_inst.subformat == sync_t.START and not self.start_of_trace:
self.follow_execution_path(self.address, te_inst)
else:
self.set_pc(self.address)
self.report_pc(self.pc)
self.last_pc = self.pc
self.start_of_trace = False
self.irstack_depth = 0
else:
assert not self.start_of_trace
if te_inst.format == format_t.ADDR or te_inst.branches != 0:
self.stop_at_last_branch = False
address = te_inst.address << self.settings["iaddress_lsb_p"]
if self.settings["full-address"]:
self.address = address
else:
self.address += twoscomp(address, self.settings["iaddress_width_p"])
if te_inst.format == format_t.BRANCH:
self.stop_at_last_branch = (te_inst.branches == 0)
# Branch map will contain <= 1 branch (1 if last reported instruction was a branch)
self.branch_map |= (te_inst.branch_map << self.branches)
if te_inst.branches == 0:
self.branches += 31
else:
self.branches += te_inst.branches
self.follow_execution_path(self.address, te_inst)
def process_support(self, te_inst):
"""
Derive the options from a te_inst support packet.
Note that the order and the set of options is not dictated by the specification
and is implementation specific.
"""
options = te_inst.ioptions
# From decoder-algorithm.h
# define TE_OPTIONS_IMPLICIT_RETURN (1u)
# define TE_OPTIONS_IMPLICIT_EXCEPTION (1u << 1)
# define TE_OPTIONS_FULL_ADDRESS (1u << 2)
# define TE_OPTIONS_JUMP_TARGET_CACHE (1u << 3)
# define TE_OPTIONS_BRANCH_PREDICTION (1u << 4)
# define TE_OPTIONS_NUM_BITS (5u) /* number of bits to send te_options_t */
self.settings["implicit-return"] = (options & 1) == 1
self.settings["implicit-except"] = (options >> 1) & 1 == 1
self.settings["full-address"] = (options >> 2) & 1 == 1
self.settings["jump-target-cache"] = (options >> 3) & 1 == 1
self.settings["branch-prediction"] = (options >> 4) & 1 == 1
debug_print("implicit-return:%s" % self.settings["implicit-return"])
debug_print("implicit-except:%s" % self.settings["implicit-except"])
debug_print("full-address:%s" % self.settings["full-address"])
debug_print("jump-target-cache:%s" % self.settings["jump-target-cache"])
debug_print("branch-prediction:%s" % self.settings["branch-prediction"])
if te_inst.qual_status != qual_status_t.NO_CHANGE:
self.start_of_trace = True # Trace ended, so get ready to start again
if te_inst.qual_status == qual_status_t.ENDED_NTR and self.inferred_address: # pragma: no cover
local_previous_address = self.pc
self.inferred_address = False
while True:
local_stop_here = self.next_pc(local_previous_address)
self.report_pc(self.pc)
if local_stop_here:
return
def follow_execution_path(self, address, te_inst):
def branch_limit():
return 1 if self.get_instr(self.pc).is_branch else 0
if args.debug:
debug_print("follow_execution_path 0x%lx" % address)
local_previous_address = self.pc
local_stop_here = False
while True:
if self.inferred_address:
debug_print(" Inferred address: 0x%lx" % local_previous_address)
local_stop_here = self.next_pc(local_previous_address)
self.report_pc(self.pc)
if local_stop_here:
self.inferred_address = False
else:
debug_print(" Not inferred address: 0x%lx" % address)
local_stop_here = self.next_pc(address)
self.report_pc(self.pc)
if (
self.branches == 1
and self.get_instr(self.pc).is_branch
and self.stop_at_last_branch
):
# Reached final branch - stop here (do not follow to next instruction as
# we do not yet know whether it retires)
self.stop_at_last_branch = False
return
if local_stop_here:
# Reached reported address following an uninferable discontinuity - stop here
# Check all branches processed (except 1 if this instruction is a branch)
assert (
self.branches <= branch_limit()
), "Error: unprocessed branches"
return
if (
te_inst.format != format_t.SYNC
and self.pc == address
and not self.stop_at_last_branch
and self.flags["notify"]
and self.branches == branch_limit()
): # pragma: no cover
return
if (
te_inst.format != format_t.SYNC
and self.pc == address
and not self.stop_at_last_branch
and not self.is_uninferable_discon(self.get_instr(self.last_pc))
and not self.flags["updiscon"]
and self.branches == branch_limit()
and (
not self.flags["irreport"]
or te_inst.irdepth == self.irstack_depth
)
):
# All branches processed, and reached reported address, but not as an
# uninferable jump target
# Stop here for now, though flag indicates this may not be
# final retired instruction
self.inferred_address = True
return
if (
te_inst.format == format_t.SYNC
and self.pc == address
and self.branches == branch_limit()
):
# All branches processed, and reached reported address
return
def next_pc(self, address):
local_instr = self.get_instr(self.pc)
local_this_pc = self.pc
local_stop_here = False
if args.debug:
debug_print(" next_pc(0x%lx)" % address)
if self.is_inferable_jump(local_instr):
assert local_instr.imm is not None, local_instr
self.incr_pc(local_instr.imm)
# Not in the spec but stops an infinite loop
if local_instr.imm == 0: # pragma: no cover
local_stop_here = True
elif self.is_sequential_jump(local_instr, self.last_pc): # pragma: no cover
self.set_pc(self.sequential_jump_target(self.pc, self.last_pc))
elif self.is_implicit_return(local_instr): # pragma: no cover
self.set_pc(self.pop_return_stack())
elif self.is_uninferable_discon(local_instr):
assert (
not self.stop_at_last_branch
), "Error: Unexpected uninferable discontinuity"
self.set_pc(address)
local_stop_here = True
elif self.is_taken_branch(local_instr):
assert local_instr.imm is not None, local_instr
self.incr_pc(local_instr.imm)
# Not in the spec but stops an infinite loop
if local_instr.imm == 0: # pragma: no cover
local_stop_here = True
else:
self.incr_pc(local_instr.size)
if self.is_call(local_instr):
self.push_return_stack(local_this_pc)
self.last_pc = local_this_pc
return local_stop_here
def is_taken_branch(self, instr):
if not instr.is_branch:
return False
assert self.branches != 0, "Error: cannot resolve branch"
local_taken = (self.branch_map & 1) == 0
self.branches -= 1
self.branch_map = self.branch_map >> 1
return local_taken
def is_inferable_jump(self, instr):
if instr.opcode == "jalr":
assert instr.rs1 is not None
return instr.opcode in ("jal", "c.jal", "c.j") or (
instr.opcode == "jalr" and instr.rs1 == 0
)
def is_implicit_return(self, instr):
return False
def is_sequential_jump(self, instr, last_pc):
return False
def sequential_jump_target(self, pc, last_pc): # pragma: no cover
return None
def is_uninferable_jump(self, instr):
return instr.opcode in ("c.jalr", "c.jr") or (
instr.opcode == "jalr" and instr.rs1 != 0
)
def is_uninferable_discon(self, instr):
return self.is_uninferable_jump(instr) or instr.opcode in (
"uret",
"sret",
"mret",
"dret",
"ecall",
"ebreak",
"c.ebreak",
)
# Determine if instruction is a call
# - excludes tail calls as they do not push an address onto the return stack
def is_call(self, instr):
return (
instr.opcode in ("c.jalr", "c.jal")
or (instr.opcode == "jalr" and instr.rd == 1)
or (instr.opcode == "jal" and instr.rd == 1)
)
def push_return_stack(self, address):
pass
def pop_return_stack(self): # pragma: no cover
return None
def exception_address(self, te_inst):
local_instr = self.get_instr(self.pc)
local_address = None
if self.is_uninferable_discon(local_instr) and te_inst.thaddr == 0:
local_address = te_inst.address
elif local_instr.opcode in ("ecall", "ebreak", "c.ebreak"):
local_address = self.pc
else:
local_address = self.next_pc(self.pc)
debug_print(" exception_address: 0x%lx thaddr: %d" % (local_address, te_inst.thaddr))
return local_address
def report_trap(self, te_inst):
if args.debug:
if te_inst.interrupt:
debug_print(" TRAP(interrupt): ecause: %d" % te_inst.ecause)
else:
debug_print(" TRAP: ecause: %d tval: 0x%lx" % (te_inst.ecause, te_inst.tval))
def report_pc(self, address):
debug_print("report_pc[%d] --------------> 0x%lx" % (self.i_count, address))
self.trace_out.write("%lx\n" % address)
if self.i_count < len(self.expected): # pragma: no cover
if self.expected[self.i_count] != address:
print(
"Error: expected 0x%lx decoded 0x%lx" % (self.expected[self.i_count], address)
)
exit(1)
self.i_count += 1
def report_epc(self, address):
if args.debug:
debug_print(" EPC: 0x%lx" % address)
class Instruction:
"""
A representation of a single instruction using the text taken from objdump.
It "disassembles" the instruction where necessary to allow the decoder to determine
various attributes of the instruction.
Note that it is NOT a full disassembler.
"""
R_TYPE = (
"add",
"addw",
"sub",
"subw",
"xor",
"or",
"and",
"sll",
"sllw",
"srl",
"srlw",
"sra",
"sraw",
"slt",
"sltu",
"mul",
"mulh",
"mulhsu",
"mulhu",
"div",
"divu",
"rem",
"remu",
"mulw",
"divw",
"divuw",
"remw",
"remuw",
)
I_TYPE = (
"addi",
"addiw",
"xori",
"ori",
"andi",
"slli",
"slliw",
"srli",
"srliw",
"srai",
"sraiw",
"slti",
"sltiu",
"lb",
"lh",
"lw",
"lwu",
"ld",
"lbu",
"lhu",
"jalr",
)
CSR_TYPE = ("csrrw", "csrrs", "csrrc")
ICSR_TYPE = ("csrrwi", "csrrsi", "csrrci")
S_TYPE = ("sb", "sh", "sw", "sd")
B_TYPE = ("beq", "bne", "blt", "bge", "bltu", "bgeu")
U_TYPE = ("lui", "auipc")
J_TYPE = "jal"
SYS_TYPE = (
"ecall",
"ebreak",
"mret",
"sret",
"uret",
"fence",
"fence.i",
"sfence.vma",
"wfi",
)
CR_TYPE = ("c.jr", "c.mv", "c.ebreak", "c.jalr", "c.add")
CI_TYPE = (
"c.nop",
"c.addi",
"c.addiw",
"c.li",
"c.addi16sp",
"c.lui",
"c.srli",
"c.srli64",
"c.srai",
"c.srai64",
"c.andi",
"c.slli",
"c.slli64",
"c.fldsp",
"c.lqsp",
"c.lwsp",
"c.flwsp",
"c.ldsp",
)
CSS_TYPE = ("c.fsdsp", "c.sqsp", "c.swsp", "c.fswsp", "c.sdsp")
CIW_TYPE = "c.addi4spn"
CL_TYPE = (
"c.fld",
"c.lq",
"c.lw",
"c.flw",
"c.ld",
)
CS_TYPE = ("c.fsd", "c.sq", "c.sw", "c.fsw", "c.sd")
CA_TYPE = ("c.sub", "c.xor", "c.or", "c.and", "c.subw", "c.addw")
CB_TYPE = ("c.beqz", "c.bnez")
CJ_TYPE = ("c.j", "c.jal")
UNIMP_TYPE = "c.unimp"
# Some instructions use e.g 5(a0) syntax, so need to split this out
PATTERN = re.compile("([-]?[0-9]*)\(([a-z]+[0-9]*)\)")
def __init__(self, address, fields):
self.address = address
self.fields = fields
self.binary = fields[1].strip()
assert len(self.binary) in (4, 8), fields # 4 or 8 hex digits i.e. 2 or 4 bytes
self.size = len(self.binary) >> 1
self.opcode = fields[2]
self.args = []
if len(fields) > 3:
self.args = self.convert_args(fields[3])
self.r_type = self.opcode in Instruction.R_TYPE
self.i_type = self.opcode in Instruction.I_TYPE
self.csr_type = self.opcode in Instruction.CSR_TYPE
self.icsr_type = self.opcode in Instruction.ICSR_TYPE
self.s_type = | |
result = self.mgmt_client.disks.grant_access(resource_group.name, DISK_NAME, ACCESS, DURATION_IN_SECONDS)
result = result.result()
# SAS_URI = result.access_sas
# Grant acess snapshot (TODO: need swagger file)
ACCESS = "Read"
DURATION_IN_SECONDS = 1800
result = self.mgmt_client.snapshots.grant_access(resource_group.name, SNAPSHOT_NAME, ACCESS, DURATION_IN_SECONDS)
result = result.result()
# Update availability sets (TODO: need swagger file)
BODY = {
"platform_fault_domain_count": "2",
"platform_update_domain_count": "20"
}
result = self.mgmt_client.availability_sets.update(resource_group.name, AVAILABILITY_SET_NAME, BODY)
# Update a dedicated host (TODO: need swagger file )
BODY = {
"tags": {
"department": "HR"
},
}
result = self.mgmt_client.dedicated_hosts.update(resource_group.name, HOST_GROUP_NAME, HOST_NAME, BODY)
# Update a simple Gallery Image Version (Managed Image as source).[patch]
BODY = {
"publishing_profile": {
"target_regions": [
# {
# "name": "eastus",
# "regional_replica_count": "1"
# },
{
"name": "East US",
"regional_replica_count": "2",
"storage_account_type": "Standard_ZRS"
}
]
},
"storage_profile": {
"os_disk_image": {
"source": {
"id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/snapshots/" + SNAPSHOT_NAME + ""
},
"host_caching": "ReadOnly"
},
# TODO: NEED A IMAGE
# "source": {
# "id": "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP + "/providers/Microsoft.Compute/images/" + IMAGE_NAME + ""
# }
}
}
result = self.mgmt_client.gallery_image_versions.update(resource_group.name, GALLERY_NAME, IMAGE_NAME, VERSION_NAME, BODY)
result = result.result()
# Update a virtual machine scale set vm (TODO: need a swagger file)
# BODY = {
# "location": "eastus",
# "tags": {
# "department": "HR"
# }
# }
# BODY = INSTANCE_VM_1
# result = self.mgmt_client.virtual_machine_scale_set_vms.update(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_ID, INSTANCE_VM_1)
# result = result.result()
# Update a virtual machine scale set (TODO: need a swagger file)
BODY = {
"sku": {
"tier": "Standard",
"capacity": "2",
"name": "Standard_D1_v2"
},
"upgrade_policy": {
"mode": "Manual"
}
}
result = self.mgmt_client.virtual_machine_scale_sets.update(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, BODY)
result = result.result()
# Update instances of machine scale set (TODO: need swagger file)
# result = self.mgmt_client.virtual_machine_scale_sets.update_instances(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_IDS)
# result = result.result()
# Update a simple gallery Application.[patch]
BODY = {
"description": "This is the gallery application description.",
"eula": "This is the gallery application EULA.",
# "privacy_statement_uri": "myPrivacyStatementUri}",
# "release_note_uri": "myReleaseNoteUri",
"supported_os_type": "Windows",
"tags": {
"tag1": "tag1"
}
}
result = self.mgmt_client.gallery_applications.update(resource_group.name, GALLERY_NAME, APPLICATION_NAME, BODY)
result = result.result()
# Update a proximity placement group.[get]
BODY = {
"location": "eastus",
"proximity_placement_group_type": "Standard"
}
result = self.mgmt_client.proximity_placement_groups.update(resource_group.name, PROXIMITY_PLACEMENT_GROUP_NAME, BODY)
# Export logs which contain all Api requests made to Compute Resource Provider within the given time period broken down by intervals.[post]
# BODY = {
# "interval_length": "FiveMins",
# # "blob_container_sas_uri": "https://somesasuri",
# "blob_container_sas_uri": SAS_URI,
# "from_time": "2018-01-21T01:54:06.862601Z",
# "to_time": "2018-01-23T01:54:06.862601Z",
# "group_by_resource_name": True
# }
# result = self.mgmt_client.log_analytics.export_request_rate_by_interval(AZURE_LOCATION, LOG_ANALYTIC_NAME, BODY)
# result = result.result()
# VirtualMachineScaleSet vm restart (TODO: need swagger file)
# result = self.mgmt_client.virtual_machine_scale_set_vms.restart(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_ID)
# result = result.result()
# VirtualMachineScaleSet vm power off (TODO: need swagger file)
# result = self.mgmt_client.virtual_machine_scale_set_vms.power_off(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_ID)
# result = result.result()
# VirtualMachineScaleSet vm start (TODO: need swagger file)
# result = self.mgmt_client.virtual_machine_scale_set_vms.start(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_ID)
# result = result.result()
# VirtualMachineScaleSet restart (TODO: need swagger file)
result = self.mgmt_client.virtual_machine_scale_sets.restart(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME)
result = result.result()
# VirtualMachineScaleSet power off (TODO: need swagger file)
result = self.mgmt_client.virtual_machine_scale_sets.power_off(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME)
result = result.result()
# VirtualMachineScaleSet start (TODO: need swagger file)
result = self.mgmt_client.virtual_machine_scale_sets.start(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME)
result = result.result()
# Update VMSS vm extension (TODO: need swagger file)
# BODY = {
# "auto_upgrade_minor_version": True,
# "publisher": "Microsoft.Azure.NetworkWatcher",
# "virtual_machine_extension_type": "NetworkWatcherAgentWindows",
# "type_handler_version": "1.4",
# }
# result = self.mgmt_client.virtual_machine_scale_set_vm_extensions.update(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_ID, VIRTUAL_MACHINE_EXTENSION_NAME, BODY)
# Delete VMSS vm exnteison (TODO: need swagger file)
# result = self.mgmt_client.virtual_machine_scale_set_vm_extensions.delete(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_ID, VIRTUAL_MACHINE_EXTENSION_NAME)
# VMSSVMRunCommand[post]
# BODY = {
# "command_id": "RunPowerShellScript"
# }
# INSTANCE_ID = INSTANCE_ID_2
# result = self.mgmt_client.virtual_machine_scale_set_vms.run_command(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_ID, BODY)
# result = result.result()
# Delete instances of virtual machine scale sets (TODO: need swagger file)
# result = self.mgmt_client.virtual_machine_scale_sets.delete_instances(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_IDS)
# result = result.result()
# Update virtual machine sacle set extension (TODO: need swagger file)
BODY = {
"auto_upgrade_minor_version": True,
}
result = self.mgmt_client.virtual_machine_scale_set_extensions.update(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, VMSS_EXTENSION_NAME, BODY)
# Delete virtua machine scale set extension (TODO: need swagger file)
result = self.mgmt_client.virtual_machine_scale_set_extensions.delete(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, VMSS_EXTENSION_NAME)
result = result.result()
# VirtualMachineScaleSet stop againe.
result = self.mgmt_client.virtual_machine_scale_sets.power_off(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME)
result = result.result()
# VirtualMachineRunCommand[post]
BODY = {
"command_id": "RunPowerShellScript"
}
result = self.mgmt_client.virtual_machines.run_command(resource_group.name, VIRTUAL_MACHINE_NAME, BODY)
result = result.result()
# VirtualMachine restart (TODO: need swagger file)
result = self.mgmt_client.virtual_machines.restart(resource_group.name, VIRTUAL_MACHINE_NAME)
result = result.result()
# VirtualMachine power off (TODO:need swagger file)
result = self.mgmt_client.virtual_machines.power_off(resource_group.name, VIRTUAL_MACHINE_NAME)
result = result.result()
# VirtualMachine start (TODO: need swagger file)
result = self.mgmt_client.virtual_machines.start(resource_group.name, VIRTUAL_MACHINE_NAME)
result = result.result()
# Update virtual machine extension (TODO: need swagger file)
BODY = {
"auto_upgrade_minor_version": True,
"instance_view": {
"name": VIRTUAL_MACHINE_EXTENSION_NAME,
"type": "CustomScriptExtension"
}
}
result = self.mgmt_client.virtual_machine_extensions.update(resource_group.name, VIRTUAL_MACHINE_NAME, VIRTUAL_MACHINE_EXTENSION_NAME, BODY)
# This operation need VM running.
# Delete virtual machine extension (TODO: need swagger file)
result = self.mgmt_client.virtual_machine_extensions.delete(resource_group.name, VIRTUAL_MACHINE_NAME,VIRTUAL_MACHINE_EXTENSION_NAME)
result = result.result()
# VirtualMachine power off again.
result = self.mgmt_client.virtual_machines.power_off(resource_group.name, VIRTUAL_MACHINE_NAME)
result = result.result()
# Update a simple gallery image.[patch]
BODY = {
"os_type": "Windows",
"os_state": "Generalized",
"hyper_vgeneration": "V1",
"identifier": {
"publisher": "myPublisherName",
"offer": "myOfferName",
"sku": "mySkuName"
}
}
result = self.mgmt_client.gallery_images.update(resource_group.name, GALLERY_NAME, IMAGE_NAME, BODY)
result = result.result()
# Export logs which contain all throttled Api requests made to Compute Resource Provider within the given time period.[post]
# BODY = {
# # "blob_container_sas_uri": "https://somesasuri",
# "blob_container_sas_uri": SAS_URI,
# "from_time": "2018-01-21T01:54:06.862601Z",
# "to_time": "2018-01-23T01:54:06.862601Z",
# "group_by_operation_name": True,
# "group_by_resource_name": False
# }
# result = self.mgmt_client.log_analytics.export_throttled_requests(LOCATION_NAME, LOG_ANALYTIC_NAME, BODY)
# result = result.result()
# Revoke access disk (TODO: need swagger file)
result = self.mgmt_client.disks.revoke_access(resource_group.name, DISK_NAME)
result = result.result()
# Redeploy virtual machine scale set vm (TODO: need swagger file)
# result = self.mgmt_client.virtual_machine_scale_set_vms.redeploy(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_ID)
# result = result.result()
# Redeploy virtual machine scale set (TODO: need swagger file)
result = self.mgmt_client.virtual_machine_scale_sets.redeploy(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME)
result = result.result()
# Reapply the state of a virtual machine.[post]
result = self.mgmt_client.virtual_machines.reapply(resource_group.name, VIRTUAL_MACHINE_NAME)
result = result.result()
# Redeploy the virtual machine. (TODO: need swagger file)
result = self.mgmt_client.virtual_machines.redeploy(resource_group.name, VIRTUAL_MACHINE_NAME)
result = result.result()
# Perform maintenance virtual machine scale set vms (TODO: need swagger file)
# result = self.mgmt_client.virtual_machine_scale_set_vms.perform_maintenance(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_ID)
# result = result.result()
# TODO: Operation 'performMaintenance' is not allowed on VM 'virtualmachinescalesetname_2' since the Subscription of this VM is not eligible.
# Perform maintenance virtual machine scale set (TODO: need swagger file)
# result = self.mgmt_client.virtual_machine_scale_sets.perform_maintenance(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME)
# result = result.result()
# Reimage a virtual machine scale set vm (TODO: need swagger file)
# BODY = {
# "temp_disk": True
# }
# result = self.mgmt_client.virtual_machine_scale_set_vms.reimage(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_ID)
# result = result.result()
# Reimage all virtual machine scale sets vm (TODO: need swagger file)
# BODY = {
# "temp_disk": True
# }
# result = self.mgmt_client.virtual_machine_scale_set_vms.reimage_all(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME, INSTANCE_ID)
# result = result.result()
# Reimage a virtual machine scale set (TODO: need swagger file)
# BODY = {
# "temp_disk": True
# }
# result = self.mgmt_client.virtual_machine_scale_sets.reimage(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME)
# result = result.result()
# Reimage all virtual machine scale sets (TODO: need swagger file)
# BODY = {
# "temp_disk": True
# }
# result = self.mgmt_client.virtual_machine_scale_sets.reimage_all(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME)
# result = result.result()
# Force recovery service fabric platform update domain walk (TODO: need swagger file)
# result = self.mgmt_client.virtual_machine_scale_sets.force_recovery_service_fabric_platform_update_domain_walk(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME)
# Convert to single placement virtual machine scale sets (TODO: need swagger file)
# result = self.mgmt_client.virtual_machine_scale_sets.convert_to_single_placement_group(resource_group.name, VIRTUAL_MACHINE_SCALE_SET_NAME)
# # Perform maintenance the virtual machine (TODO: need swagger file)
# result = self.mgmt_client.virtual_machines.perform_maintenance(resource_group.name, VIRTUAL_MACHINE_NAME)
# result = result.result()
# # VirtualMachine convert to managed disks (TODO: need swagger file)
# result = self.mgmt_client.virtual_machines.convert_to_managed_disks(resource_group.name, VIRTUAL_MACHINE_NAME)
# result = result.result()
# TODO: Message: The Reimage and OSUpgrade Virtual Machine actions require that the virtual machine has Automatic OS Upgrades enabled.
# Reimage a Virtual Machine.[post]
# BODY = {
# "temp_disk": True
# }
# result = self.mgmt_client.virtual_machines.reimage(resource_group.name, VIRTUAL_MACHINE_NAME)
# result = result.result()
# TODO: NEED KEYVAULT
# Update a disk encryption set.[patch]
# BODY = {
# # "properties": {
# # "active_key": {
# # "source_vault": {
# # "id": | |
<gh_stars>1-10
#!/usr/bin/env python
# coding: utf-8
## How to get started with Numerai
## *The hardest data science tournament on the planet?*
# 如何开始使用Numerai
# 地球上最艰苦的数据科学比赛?
# 
#
# 
# This notebook accompanies the [Weights and Biases Gallery Report](https://app.wandb.ai/gallery) on getting started with [Numerai](https://numer.ai). We will go through the whole process from loading the data to submitting your predictions to Numerai. [Weights and Biases](https://www.wandb.com/) will be used for experiment tracking and hyperparameter optimization.
### Preparation
#### Install Numerai's API
#### pip install numerapi
#### Get the latest version of Weights and Biases
####pip install wandb --upgrade
import os
import numpy as np
import random as rn
import pandas as pd
import seaborn as sns
import lightgbm as lgb
import matplotlib.pyplot as plt
from scipy.stats import spearmanr
from sklearn.metrics import mean_absolute_error
import numerapi
import wandb
from wandb.lightgbm import wandb_callback
# Initialize Numerai's API
NAPI = numerapi.NumerAPI(verbosity="info")
# Weights and Biases requires you to add your WandB API key for logging in automatically. Because this is a secret key we will use [Kaggle User Secrets](https://www.kaggle.com/product-feedback/114053) to obfuscate the API key.
# Obfuscated WANDB API Key
# from kaggle_secrets import UserSecretsClient
# WANDB_KEY = '7d8786321b64e818153da23692d69d6ad4387b2e'#UserSecretsClient().get_secret("WANDB_API_KEY")
# wandb.login(key=WANDB_KEY)
# Data directory
DIR = "../working"
# Set seed for reproducability
seed = 1234
rn.seed(seed)
np.random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
# Surpress Pandas warnings
pd.set_option('chained_assignment', None)
# ## Data Processing
def download_current_data(directory: str):
"""
Downloads the data for the current round
:param directory: The path to the directory where the data needs to be saved
"""
current_round = NAPI.get_current_round()
if os.path.isdir(f'{directory}/numerai_dataset_{current_round}/'):
print(f"You already have the newest data! Current round is: {current_round}")
else:
print(f"Downloading new data for round: {current_round}!")
NAPI.download_current_dataset(dest_path=directory, unzip=True)
def load_data(directory: str, reduce_memory: bool=True) -> tuple:
"""
Get data for current round
:param directory: The path to the directory where the data needs to be saved
:return: A tuple containing the datasets
"""
print('Loading the data')
full_path = f'{directory}/numerai_dataset_{NAPI.get_current_round()}/'
train_path = full_path + 'numerai_training_data.csv'
test_path = full_path + 'numerai_tournament_data.csv'
train = pd.read_csv(train_path)
test = pd.read_csv(test_path)
# Reduce all features to 32-bit floats
if reduce_memory:
num_features = [f for f in train.columns if f.startswith("feature")]
train[num_features] = train[num_features].astype(np.float32)
test[num_features] = test[num_features].astype(np.float32)
val = test[test['data_type'] == 'validation']
return train, val, test
def get_group_stats(df: pd.DataFrame) -> pd.DataFrame:
"""
Create features by calculating statistical moments for each group.
:param df: Pandas DataFrame containing all features
"""
for group in ["intelligence", "wisdom", "charisma", "dexterity", "strength", "constitution"]:
cols = [col for col in df.columns if group in col]
df[f"feature_{group}_mean"] = df[cols].mean(axis=1)
df[f"feature_{group}_std"] = df[cols].std(axis=1)
df[f"feature_{group}_skew"] = df[cols].skew(axis=1)
return df
def _train():
# Configure and train model
wandb.init(name="LightGBM_sweep")
lgbm_config = {"num_leaves": wandb.config.num_leaves, "max_depth": wandb.config.max_depth,
"learning_rate": wandb.config.learning_rate,
"bagging_freq": wandb.config.bagging_freq, "bagging_fraction": wandb.config.bagging_fraction,
"feature_fraction": wandb.config.feature_fraction,
"metric": 'mse', "random_state": seed}
lgbm_model = lgb.train(lgbm_config, train_set=dtrain, num_boost_round=750, valid_sets=watchlist,
callbacks=[wandb_callback()], verbose_eval=100, early_stopping_rounds=50)
# Create predictions for evaluation
val_preds = lgbm_model.predict(val[feature_list], num_iteration=lgbm_model.best_iteration)
val.loc[:, "prediction_kazutsugi"] = val_preds
# W&B log metrics
spearman, payout, numerai_sharpe, mae = evaluate(val)
wandb.log(
{"Spearman": spearman, "Payout": payout, "Numerai Sharpe Ratio": numerai_sharpe, "Mean Absolute Error": mae})
### Metrics
# In this experiment we will monitor the Spearman correlation (main metric), the Sharpe ratio, payout and Mean Absolute Error (MAE).
def sharpe_ratio(corrs: pd.Series) -> np.float32:
"""
Calculate the Sharpe ratio for Numerai by using grouped per-era data
:param corrs: A Pandas Series containing the Spearman correlations for each era
:return: A float denoting the Sharpe ratio of your predictions.
"""
return corrs.mean() / corrs.std()
def evaluate(df: pd.DataFrame) -> tuple:
"""
Evaluate and display relevant metrics for Numerai
:param df: A Pandas DataFrame containing the columns "era", "target_kazutsugi" and a column for predictions
:param pred_col: The column where the predictions are stored
:return: A tuple of float containing the metrics
"""
def _score(sub_df: pd.DataFrame) -> np.float32:
"""Calculates Spearman correlation"""
return spearmanr(sub_df["target_kazutsugi"], sub_df["prediction_kazutsugi"])[0]
# Calculate metrics
corrs = df.groupby("era").apply(_score)
payout_raw = (corrs / 0.2).clip(-1, 1)
spearman = round(corrs.mean(), 4)
payout = round(payout_raw.mean(), 4)
numerai_sharpe = round(sharpe_ratio(corrs), 4)
mae = mean_absolute_error(df["target_kazutsugi"], df["prediction_kazutsugi"]).round(4)
# Display metrics
print(f"Spearman Correlation: {spearman}")
print(f"Average Payout: {payout}")
print(f"Sharpe Ratio: {numerai_sharpe}")
print(f"Mean Absolute Error (MAE): {mae}")
return spearman, payout, numerai_sharpe, mae
#
# # Download, unzip and load data
download_current_data(DIR)
train, val, test = load_data(DIR, reduce_memory=True)
# test = pd.read_csv("working/latest_numerai_tournament_data.csv.xz")
test = pd.read_csv("https://numerai-public-datasets.s3-us-west-2.amazonaws.com/latest_numerai_tournament_data.csv.xz")
### Exploratory Data Analysis (EDA)
# The Numerai data has 310 obfuscated numerical features that can hold values of 0.0, 0.25, 0.5, 0.75, 1.00. The features are divided into 6 groups ("intelligence", "wisdom", "charisma", "dexterity", "strength" and "constitution"). The meaning of the groups is unclear, but we can use the fact that features are within the same group.
print("Training data:")
print(train.head(2))
print("Test data:")
print(test.head(2))
print("Training set info:")
print(train.info())
print("Test set info:")
print(test.info())
# When we group by the eras it can be seen that the era sizes change over time. This can be taken into account when creating features using the eras.
# Extract era numbers
train["erano"] = train.era.str.slice(3).astype(int)
plt.figure(figsize=[14, 6])
train.groupby(train['erano'])["target_kazutsugi"].size().plot(title="Era sizes", figsize=(14, 8));
plt.show()
# Most of the features have similar standard deviations, but some have very low variability. Consider standardizing the features or removing these low variability features when experimenting with for example neural networks.
feats = [f for f in train.columns if "feature" in f]
plt.figure(figsize=(15, 5))
sns.distplot(pd.DataFrame(train[feats].std()), bins=100)
sns.distplot(pd.DataFrame(val[feats].std()), bins=100)
sns.distplot(pd.DataFrame(test[feats].std()), bins=100)
plt.legend(["Train", "Val", "Test"], fontsize=20)
plt.title("Standard deviations over all features in the data", weight='bold', fontsize=20);
plt.show()
# ## Feature Engineering
# The features have a remarkably low correlation to the target variable. Even the most correlated features only have around 1.5% correlation with the target. Engineering useful features out of feature + era groups is key for creating good Numerai models.
#
# Additionally, the importance of features may change over time and by selecting a limited number of features we risk having a high "feature exposure". Feature exposure can be quantified as the standard deviation of all your predictions' correlations with each feature. You can mitigate this risk by using dimensionality reduction techniques like Principal Component Analysis (PCA) to integrate almost all features into your model.
#
# One example of creating features out of the groups is to calculate statistical moments (mean, standard deviation, skewness) of every group.
# Add group statistics features
train = get_group_stats(train)
val = get_group_stats(val)
test = get_group_stats(test)
# ## Feature Selection
# The features have a remarkably low correlation to the target variable. Even the most correlated features only have around 1.5% correlation with the target. Engineering useful features out of feature and era groupings is key for creating good Numerai models.
#
# Also, the importance of features may change over time. By selecting a limited number of features we risk having a high "feature exposure". Feature exposure can be quantified as the standard deviation of all your predictions' correlations with each feature. You can mitigate this risk by using dimensionality reduction techniques like Principal Component Analysis (PCA) to integrate almost all features into your model. In this starter example we take the 150 features that are most correlated to the target variable.
# Calculate correlations with target
full_corr = train.corr()
corr_with_target = full_corr["target_kazutsugi"].T.apply(abs).sort_values(ascending=False)
# Select features with highest correlation to the target variable
features = corr_with_target[:150]
features.drop("target_kazutsugi", inplace=True)
print("Top 10 Features according to correlation with target:")
print(features[:10])
# Create list of most correlated features
feature_list = features.index.tolist()
### Modeling (using Weights and Biases)
# To get a first good model for Numerai we will train a [LightGBM](https://lightgbm.readthedocs.io/en/latest) model and use Weights and Biases to do a hyperparameter sweep. In this example it will be a grid search over some of the most important hyperparameters for LightGBM. First, we define the configuration of the sweep.
# Configuration for hyperparameter sweep
sweep_config = {
'method': 'grid',
'metric': {
'name': 'mse',
'goal': 'minimize'
},
'parameters': {
"num_leaves": {'values': [16, 32, 64]},
"max_depth": {'values': [4, 5]},
"learning_rate": {'values': [0.1, 0.05]},
"bagging_freq": {'values': [7]},
"bagging_fraction": {'values': [0.8]},
"feature_fraction": {'values': [0.65]},
}
}
sweep_id = wandb.sweep(sweep_config, project="numerai_tutorial")
# After that we define a function (_train) using wandb.config attributes so Weights and Biases can perform the grid search. We then log all the results and start the agent.
# Prepare data for LightGBM
dtrain = lgb.Dataset(train[feature_list], label=train["target_kazutsugi"])
dvalid = lgb.Dataset(val[feature_list], label=val["target_kazutsugi"])
watchlist = [dtrain, dvalid]
# Run hyperparameter sweep (grid search)
wandb.agent(sweep_id, function=_train)
# Now the grid search is finished we select the hyperparameters that lead to the highest Sharpe ratio.
# Train model with best configuration
wandb.init(project="numerai_tutorial", name="LightGBM")
best_config = {"num_leaves": 50, "max_depth": 6, "learning_rate": 0.1,
"bagging_freq": 7, "bagging_fraction": 0.6, "feature_fraction": 0.75,
"metric": 'mse', "random_state": seed}
lgbm_model = lgb.train(best_config, train_set=dtrain, num_boost_round=750, valid_sets=watchlist,
callbacks=[wandb_callback()], verbose_eval=100, early_stopping_rounds=50)
# Create final predictions | |
<gh_stars>0
#!/usr/bin/env python
# vim: tabstop=4 shiftwidth=4 softtabstop=4
import os
import sys
import logging
import gflags
import gettext
import time
import eventlet
import traceback
import json
import string
currentDir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.abspath('%s/..' % currentDir))
eventlet.monkey_patch()
from utils.underscore import _
import validate_entity
import provision_entity
LOG = logging.getLogger('hawk-rpc')
import utils.cloud_utils as cloud_utils
import utils.cache_utils as cache_utils
import entity_utils
import rpcResync as entity_resync
import cfd_keystone.cfd_keystone
import entity_constants
class Entity(object):
def __init__(self, child_table,
post_db_create_function,
pre_db_delete_function,
post_rest_get_function,
parent_uri_type,
rest_header,
rest_json_keys,
rest_build_function,
pre_db_create_function=None,
validate_entity_function=None,
provision_entity_function=None,
post_db_delete_function=None,
pre_rest_status_check_function=None,
post_entity_final_status_function=None,
entity_pending_states=entity_constants.default_entity_pending_states,
entity_completed_states=entity_constants.default_entity_completed_states,
entity_failed_states=entity_constants.default_entity_failed_states,
periodic_status_check_time=entity_constants.default_periodic_status_check_time,
periodic_max_status_check_iterations=entity_constants.default_periodic_max_status_check_iterations,
default_entity_name_prefix=None,
statistics_manager=None
):
self.child_table = child_table
# called after a row in tblentities and child table is created
if post_db_create_function:
self.post_db_create_function = post_db_create_function
else:
# assign a null function if nothing to call...
self.post_db_create_function = lambda *args, **kwargs: None
if pre_db_create_function:
self.pre_db_create_function = pre_db_create_function
else:
self.pre_db_create_function = lambda *args, **kwargs: None
# called after each get, post, or put response
if post_rest_get_function:
self.post_rest_get_function = post_rest_get_function
else:
# assign a null function if nothing to call...
self.post_rest_get_function = lambda *args, **kwargs: None
self.parent_uri_type = parent_uri_type
self.rest_header = rest_header
if post_db_delete_function:
self.post_db_delete_function = post_db_delete_function
else:
self.post_db_delete_function = lambda *args, **kwargs: None
# function to be called before REST API
self.pre_rest_status_check_function = pre_rest_status_check_function
# function to be called after the entity is in its "final" status
self.post_entity_final_status_function = post_entity_final_status_function
self.rest_json_keys = rest_json_keys
if rest_build_function:
self.rest_build_function = rest_build_function
else:
self.rest_build_function = None
if validate_entity_function:
self.validate_entity_function = validate_entity_function
else:
self.validate_entity_function = lambda *args, **kwargs: None
if pre_db_delete_function:
self.pre_db_delete_function = pre_db_delete_function
else:
self.pre_db_delete_function = lambda *args, **kwargs: None
if provision_entity_function:
self.provision_entity_function = provision_entity_function
else:
self.provision_entity_function = None
self.entity_pending_states = entity_pending_states
self.entity_completed_states = entity_completed_states
self.entity_failed_states = entity_failed_states
self.periodic_status_check_time = periodic_status_check_time
self.periodic_max_status_check_iterations = periodic_max_status_check_iterations
if default_entity_name_prefix:
self.default_entity_name_prefix = default_entity_name_prefix
else:
self.default_entity_name_prefix = "entity-"
self.statistics_manager = statistics_manager
def entity_rest_api_enabled(db, dbid, row, parent_row=None):
if "entitytype" not in row:
return None
entitytype = row["entitytype"]
'''if entitytype in skip_dept_org_group_child:
parent_row = cloud_utils.lower_key(db.get_row_dict("tblEntities", {"id": row["parententityid"]}, order="ORDER BY id LIMIT 1"))
if parent_row:
if parent_row["entitytype"] == "department" or parent_row["entitytype"] == "organization":
return
elif entitytype in skip_dept_org__child_group:
parent_row = cloud_utils.lower_key(db.get_row_dict("tblEntities", {"id": row["parententityid"]}, order="ORDER BY id LIMIT 1"))
if parent_row:
grandparent_row = cloud_utils.lower_key(db.get_row_dict("tblEntities", {"id": parent_row["parententityid"]}, order="ORDER BY id LIMIT 1"))
if grandparent_row:
if grandparent_row["entitytype"] == "department" or parent_row["entitytype"] == "organization":
return
'''
if not entities[entitytype].pre_rest_status_check_function or \
entities[entitytype].pre_rest_status_check_function(db, dbid, row):
return True
return None
# build entity json string
def get_entity_json(db, dbid, row, options=None, quick_provision=False):
if "entitytype" not in row:
return None, "Invalid database row dictionary"
entitytype = row["entitytype"]
try:
if entitytype not in entities.keys():
return None, "Unknown entity type %s" % entitytype
if quick_provision or entity_rest_api_enabled(db, dbid, row):
if not entities[entitytype].rest_build_function:
return None, None
return entities[entitytype].rest_build_function(db, dbid, row, entities[entitytype].rest_json_keys,
options=options)
else:
return None, None
except:
cloud_utils.log_exception(sys.exc_info())
return None, "Error in processing %s " % entitytype
def entitytype_rest(s):
if s in entities.keys():
return entities[s].rest_header
LOG.critical(_("Key %s not found in entites: %s" % (s, str(entities.keys()))))
return "Error"
def _copy_kv(row, keys):
j = {}
if keys:
for i in keys:
if i in row.keys():
if isinstance(row[i], (int, long)) or row[i]:
j[i] = row[i]
# else:
# LOG.warn(_("Key %s not found in row %s from keys %s" % (i, row, keys)))
return j
def str_list(s):
if s:
if isinstance(s, basestring):
return s.split(",")
else:
LOG.warn(_("Input %s is not a string" % s))
return []
def date_str(s):
if s:
return str(s)
return ""
import base64
def save_ssh_keys(db, dbid, options):
if "ssh_keys" in options and isinstance(options["ssh_keys"], list):
for key in options["ssh_keys"]:
if "name" in key and "public_key" in key:
cloud_utils.insert_db(db, "tblSSHPublicKeys", {"tblEntities": dbid, "name": key["name"],
"public_key": base64.b64encode(key["public_key"])})
else:
LOG.critical(_("Skipping SSH key: %s for dbid %s" % (key, dbid)))
def save_user_data(db, dbid, options):
cloud_utils.update_or_insert(db, "tblUserData", {"tblEntities": dbid, "user_data": options["user_data"]},
{"tblentities": dbid})
def save_entity_policy(db, dbid, options):
cloud_utils.update_or_insert(db, "tblEntityPolicies", {"tblEntities": dbid, "policy": options["policy"]},
{"tblentities": dbid})
def save_entity_classes(db, dbid, row, options):
if "classes" in options and isinstance(options["classes"], list):
if len(options["classes"]) == 0:
db.execute_db("DELETE FROM tblAttachedEntities WHERE (AttachedEntityId = %s AND EntityType='%s') " %
(dbid, entity_constants.entitytype_class[row["entitytype"]]))
else:
db.execute_db(
"UPDATE tblAttachedEntities SET internal_updated_flag=0 WHERE (AttachedEntityId = %s AND EntityType='%s') " %
(dbid, entity_constants.entitytype_class[row["entitytype"]]))
for device in options["classes"]:
if "id" in device:
search_dict = {"tblEntities": device["id"], "AttachedEntityId": dbid,
"attachedentityname": row["name"],
"AttachedEntityUniqueId": row["uniqueid"], "AttachedEntityType": row["entitytype"],
"entitytype": entity_constants.entitytype_class[row["entitytype"]]}
ndbid = cloud_utils.update_or_insert(db, "tblAttachedEntities", search_dict, search_dict)
db.execute_db("UPDATE tblAttachedEntities SET internal_updated_flag=1 WHERE id=%s " % ndbid)
db.execute_db(
"DELETE FROM tblAttachedEntities WHERE (AttachedEntityId = %s AND EntityType='%s' AND internal_updated_flag=0) " %
(dbid, entity_constants.entitytype_class[row["entitytype"]]))
def save_entity_flavors(db, dbid, options):
if "flavors" in options and isinstance(options["flavors"], list):
# db.delete_rows_dict("tblFlavors", {"tblentities": dbid})
for flavor in options["flavors"]:
if "type" in flavor:
if flavor["type"] == "create":
flavor["tblEntities"] = dbid
cloud_utils.insert_db(db, "tblFlavors", flavor)
continue
elif flavor["type"] == "delete" and "dbid" in flavor:
db.delete_rows_dict("tblFlavors", {"tblentities": dbid, "id": flavor["dbid"]})
continue
elif flavor["type"] == "update" and "dbid" in flavor:
cloud_utils.update_only(db, "tblFlavors", flavor, {"tblentities": dbid, "id": flavor["dbid"]})
continue
LOG.critical(_("Skipping flavor: %s for dbid %s" % (flavor, dbid)))
entity_keys = ["name", "description", "email", "administrator", "location"]
def _entity(db, dbid, row, keys, **kwargs):
j = _copy_kv(row, keys)
if "sortsequenceid" in row and row["sortsequenceid"] != 0:
j.update({"sequence_number": row["sortsequenceid"]})
return j
def _get_domain_row(db, dbid):
parent, error = entity_utils.read_full_entity_status_tuple(db, dbid)
if error:
return None
if parent["entitytype"] == "system":
pass
elif parent["entitytype"] == "organization":
pass
elif parent["entitytype"] == "department":
parent, error = entity_utils.read_full_entity_status_tuple(db, parent["parententityid"])
elif parent["entitytype"] == "vdc":
parent, error = entity_utils.read_full_entity_status_tuple(db, parent["parententityid"])
parent, error = entity_utils.read_full_entity_status_tuple(db, parent["parententityid"])
else:
return None
return parent
def _add_acl_roles(db, dbid, options, mode=None):
try:
if "aclrole" in options and "acl_dbids" in options and isinstance(options["acl_dbids"], list):
# delete old entries
db.delete_rows_dict("tblEntitiesACL", {"tblentities": dbid})
for id in options["acl_dbids"]:
if not id:
id = 0
db.execute_db(
"INSERT INTO tblEntitiesACL (tblEntities, AclRole, AclEntityId, ContainerEntityId) VALUES ('%s', '%s', '%s','%s')" %
(dbid, options["aclrole"], id, options.get("containerentityid", 0)))
except:
cloud_utils.log_exception(sys.exc_info())
def _add_developer_resources(db, dbid, options, mode=None):
try:
if "aclrole" in options and options["aclrole"].lower() == "developer":
resources = {"tblentities": dbid,
"entitytype": "user",
"parententityid": options["parententityid"],
"catagory": "allocated",
"typetitle": "Compute",
"type": "Default",
"ram": options.get("ram", 0),
"network": options.get("network", 0),
"cpu": options.get("cpu", 0),
}
cloud_utils.update_or_insert(db, "tblResourcesCompute", resources,
{"tblentities": dbid, "catagory": "allocated"})
resources = {"tblentities": dbid,
"entitytype": "user",
"parententityid": options["parententityid"],
"catagory": "deployed",
"typetitle": "Compute",
"type": "Default",
# "ram":0,
# "network":0,
# "cpu":0,
}
cloud_utils.update_or_insert(db, "tblResourcesCompute", resources,
{"tblentities": dbid, "catagory": "deployed"})
resources = {"tblentities": dbid,
"entitytype": "user",
"parententityid": options["parententityid"],
"catagory": "allocated",
"typetitle": "Latency",
"capacity": options.get("capacity", 0),
"type": options.get("type", "gold")
}
cloud_utils.update_or_insert(db, "tblResourcesStorage", resources,
{"tblentities": dbid, "catagory": "allocated"})
resources = {"tblentities": dbid,
"entitytype": "user",
"parententityid": options["parententityid"],
"catagory": "deployed",
"typetitle": "Latency",
# "capacity":0,
"type": options.get("type", "gold")
}
cloud_utils.update_or_insert(db, "tblResourcesStorage", resources,
{"tblentities": dbid, "catagory": "deployed"})
if "flavors" in options:
for flavor in options["flavors"]:
resources = {"tblentities": dbid,
"entitytype": "user",
"parententityid": options["parententityid"],
"catagory": "allocated",
"quantity": flavor.get("quantity", 0),
"tblflavors": flavor.get("tblflavors", 0),
}
cloud_utils.update_or_insert(db, "tblResourcesFlavors", resources,
{"tblentities": dbid, "tblflavors": flavor.get("tblflavors", 0),
"catagory": "allocated"})
resources = {"tblentities": dbid,
"entitytype": "user",
"parententityid": options["parententityid"],
"catagory": "deployed",
# "quantity":flavor.get("quantity",0),
"tblflavors": flavor.get("tblflavors", 0)
}
cloud_utils.update_or_insert(db, "tblResourcesFlavors", resources,
{"tblentities": dbid, "tblflavors": flavor.get("tblflavors", 0),
"catagory": "deployed"})
except:
cloud_utils.log_exception(sys.exc_info())
def _group_post_db_create(db, dbid, options, mode=None, **kwargs):
_add_acl_roles(db, dbid, options, mode=mode)
domain = _get_domain_row(db, options["parententityid"])
if not domain:
return None
cfd_keystone.cfd_keystone.get_create_group(db, cfd_keystone.cfd_keystone.system_token,
{"name": domain["name"], "description": domain["description"]},
{"name": options["name"], "description": options.get("description", "")})
def _group_pre_delete(db, dbid, options):
domain = _get_domain_row(db, options["parententityid"])
if not domain:
return None
cfd_keystone.cfd_keystone.delete_group(db, cfd_keystone.cfd_keystone.system_token,
{"name": domain["name"], "description": domain["description"]},
{"name": options["name"], "description": options.get("description", "")})
def _user_pre_db_create(db, options, mode=None, parent_row=None):
return entity_utils.confirm_options_keys(options, ["loginid", "password"])
def _user_post_db_create(db, dbid, options, mode=None, **kwargs):
try:
if not mode:
return
if "parententityid" not in options:
return
_add_acl_roles(db, dbid, options, mode=mode)
_add_developer_resources(db, dbid, options, mode=mode)
group, error = entity_utils.read_full_entity_status_tuple(db, options["parententityid"])
domain = _get_domain_row(db, group["parententityid"])
if not domain or not group:
return None
if mode == "create":
cfd_keystone.cfd_keystone.get_create_user(db, cfd_keystone.cfd_keystone.system_token,
{"name": domain["name"], "description": domain["description"]},
{"name": group["name"], "description": group["description"]},
{"name": options["loginid"],
"description": options.get("description", ""),
"enabled": options.get("enabled", True),
"email": options.get("email", ""),
"password": options["password"]})
return
if mode == "update":
if "user_row" in options:
# options["loginid"] = options["user_row"]["loginid"]
if options["user_row"]["entitydisabled"] == 1:
options["enabled"] = False
else:
options["enabled"] = True
if "password" in options:
cfd_keystone.cfd_keystone.update_user(db, cfd_keystone.cfd_keystone.system_token,
{"name": domain["name"], "description": domain["description"]},
{"name": group["name"], "description": group["description"]},
{"name": options["loginid"],
"description": options.get("description", ""),
"enabled": options.get("enabled", True),
"email": options.get("email", ""),
"password": options["password"]})
except:
cloud_utils.log_exception(sys.exc_info())
def _user_pre_delete(db, dbid, options):
group, error = entity_utils.read_full_entity_status_tuple(db, options["parententityid"])
db.delete_rows_dict("tblResourcesCompute", {"tblentities": dbid})
db.delete_rows_dict("tblResourcesStorage", {"tblentities": dbid})
db.delete_rows_dict("tblEntitiesACL", {"tblentities": dbid})
domain = _get_domain_row(db, group["parententityid"])
if not domain or not group:
return None
cfd_keystone.cfd_keystone.delete_user(db, cfd_keystone.cfd_keystone.system_token,
{"name": domain["name"], "description": domain["description"]},
{"name": group["name"], "description": group["description"]},
{"name": options["loginid"], "description": options.get("description", "")})
def | |
import re
import os.path
import functools
import mathutils
from math import radians
import bpy
import pyawd
from pyawd.core import *
from pyawd.anim import *
from pyawd.scene import *
from pyawd.geom import *
from pyawd.material import *
from pyawd.utils.math import *
from pyawd.utils.geom import AWDGeomUtil
class AWDBlockCache(object):
'''A cache of already created AWD blocks, and their connection to
nodes in the Maya DAG. The cache should always be checked before
creating a blocks, so that blocks can be reused within the file
when possible.'''
def __init__(self):
self.__cache = []
def get(self, path):
block = None
for item in self.__cache:
if item[0] == path:
block = item[1]
break
return block
def add(self, path, block):
if self.get(path) is None:
self.__cache.append((path, block))
class AWDExporter(object):
def __init__(self):
self.block_cache = AWDBlockCache()
self.exported_skeletons = []
self.animation_sequences = []
self.exported_objects = []
#self.vertex_indices = {}
# TODO: Don't hard code these
self.compression = DEFLATE
self.user_ns = AWDNamespace('default')
def export(self, context, filepath='',
include_materials = True,
embed_textures = True,
include_attr = True):
self.context = context
self.include_materials = include_materials
self.embed_textures = embed_textures
self.include_attr = include_attr
self.awd = AWD(self.compression)
for o in self.context.scene.objects:
if o.type == 'EMPTY':
self.export_container(o)
elif o.type == 'MESH':
self.export_mesh(o)
elif o.type == 'ARMATURE':
self.export_skeleton(o)
# Loop through scene objects again and add either directly
# to the AWD document root or to it's parent if one exists.
# At this point, an AWD representation of the parent is
# guaranteed to have been created if included in the export.
for o in self.exported_objects:
block = self.block_cache.get(o)
if o.parent is not None:
if o.parent.type == 'ARMATURE':
self.extract_joint_weights(o)
if o.parent.parent is not None:
par_block = self.block_cache.get(o.parent.parent)
par_block.add_child(block)
else:
self.awd.add_scene_block(block)
else:
par_block = self.block_cache.get(o.parent)
par_block.add_child(block)
else:
self.awd.add_scene_block(block)
# Export animation sequences
# self.export_animation()
with open(filepath, 'wb') as f:
self.awd.flush(f)
def extract_joint_weights(self, o):
armature = o.parent
geom = o.data
skel = self.block_cache.get(armature)
# TODO: Don't hard code
joints_per_vert = 3
joint_weights = []
joint_indices = []
vert_indices = self.vertex_indices[geom.name]
for bl_vidx in vert_indices:
v = geom.vertices[bl_vidx]
weight_objs = []
for ge in v.groups:
group = o.vertex_groups[ge.group]
j_idx = skel.joint_index(name=group.name)
if j_idx is not None:
weight_objs.append((j_idx, ge.weight))
else:
weight_objs.append((0, 0))
# Normalize weights by slicing to the desired length, calculating
# the sum of all weights and then dividing all weights by that sum.
weight_objs = weight_objs[0:joints_per_vert]
sum_obj = functools.reduce(lambda w0,w1: (0, w0[1]+w1[1]), weight_objs)
weight_objs = [(w[0], w[1]/sum_obj[1]) for w in weight_objs]
# Add more empty weight objects if too few
if len(weight_objs) != joints_per_vert:
weight_objs.extend([(0,0)] * (joints_per_vert-len(weight_objs)))
for w_obj in weight_objs:
joint_indices.append(w_obj[0])
joint_weights.append(w_obj[1])
# Add newly assembled streams
md = self.block_cache.get(geom)
md[0].add_stream(STR_JOINT_WEIGHTS, joint_weights)
md[0].add_stream(STR_JOINT_INDICES, joint_indices)
def export_container(self, o):
mtx = self.mtx_bl2awd(o.matrix_local)
ctr = AWDContainer(name=o.name, transform=mtx)
self.block_cache.add(o, ctr)
self.exported_objects.append(o)
if self.include_attr:
self.set_attributes(o, ctr)
def export_animation(self):
# Unlock from bind pose
for o in self.exported_skeletons:
o.data.pose_position = 'POSE'
for seq in self.animation_sequences:
skel_anims = {}
for o in self.exported_skeletons:
skel_anim = AWDSkeletonAnimation(seq[0])
skel_anims[o.name] = skel_anim
self.awd.add_skeleton_anim(skel_anim)
print('Exporting sequences %s (%d-%d)' % seq)
for frame in range(seq[1], seq[2]):
self.context.scene.frame_set(frame)
for o in self.exported_skeletons:
skel_pose = AWDSkeletonPose()
for bp in o.pose.bones:
mtx = self.mtx_bl2awd(bp.matrix_basis)
skel_pose.add_joint_transform(mtx)
# Pad with an identity transform to match the number
# of joints (for first joint both head and tail were
# included when skeleton was created.)
skel_pose.add_joint_transform(
self.mtx_bl2awd(mathutils.Matrix()))
self.awd.add_skeleton_pose(skel_pose)
skel_anims[o.name].add_frame(skel_pose, 40)
def export_mesh(self, o):
md = self.block_cache.get(o.data)
if md is None:
print('Creating mesh %s' % o.data.name)
# If bound to a skeleton, set that skeleton in bind pose
# to make sure that the geometry is defined in that state
if o.parent is not None and o.parent.type == 'ARMATURE':
o.parent.data.pose_position = 'REST'
md = self.build_mesh_data(o.data)
self.awd.add_mesh_data(md)
self.block_cache.add(o.data, md)
mtx = self.mtx_bl2awd(o.matrix_local)
inst = AWDMeshInst(data=md, name=o.name, transform=mtx)
self.block_cache.add(o, inst)
if self.include_materials:
print('Checking materials for %s' % o.name)
awd_mat = None
for ms in o.material_slots:
awd_tex = None
bl_mat = ms.material
if bl_mat is None or bl_mat.type != 'SURFACE':
continue # Ignore non-surface materials for now
awd_mat = self.block_cache.get(bl_mat)
if awd_mat is None:
for ts in bl_mat.texture_slots:
# Skip empty slots
if ts is None:
continue
if ts.use_map_color_diffuse:
# Main input!
bl_tex = ts.texture
awd_tex = self.block_cache.get(bl_tex)
if awd_tex is None:
if bl_tex.type == 'IMAGE' and bl_tex.image is not None:
bl_img = bl_tex.image
# BitmapMaterial
if self.embed_textures:
tex_type = None
if bl_img.file_format == 'PNG':
tex_type = AWDTexture.EMBED_PNG
elif bl_img.file_format == 'JPG':
tex_type = AWDTexture.EMBED_JPG
awd_tex = AWDTexture(tex_type, name=bl_tex.name)
awd_tex.embed_file( bpy.path.abspath( bl_img.filepath ))
else:
awd_tex = AWDTexture(AWDTexture.EXTERNAL, name=bl_tex.name)
awd_tex.url = bl_img.filepath
self.block_cache.add(bl_tex, awd_tex)
self.awd.add_texture(awd_tex)
break
print('Found texture to create material?')
if awd_tex is not None:
awd_mat = AWDMaterial(AWDMaterial.BITMAP, name=bl_mat.name)
awd_mat.texture = awd_tex
if self.include_attr:
self.set_attributes(bl_mat, awd_mat)
print('Yes! Created material!')
self.block_cache.add(bl_mat, awd_mat)
self.awd.add_material(awd_mat)
if awd_mat is not None:
inst.materials.append(awd_mat)
if self.include_attr:
self.set_attributes(o, inst)
self.exported_objects.append(o)
def export_skeleton(self, o):
root_joint = None
# Use bind pose
o.data.pose_position = 'REST'
for b in o.data.bones:
joint = AWDSkeletonJoint(b.name)
joint.inv_bind_mtx = self.mtx_bl2awd(
mathutils.Matrix.Translation(b.tail_local).inverted())
if root_joint is None:
root_joint = AWDSkeletonJoint('root')
root_joint.add_child_joint(joint)
root_joint.inv_bind_mtx = self.mtx_bl2awd(
mathutils.Matrix.Translation(b.head_local).inverted())
else:
p_block = self.block_cache.get(b.parent)
if p_block is not None:
p_block.add_child_joint(joint)
self.block_cache.add(b, joint)
if root_joint is not None:
skel = AWDSkeleton(name=o.name)
skel.root_joint = root_joint
self.awd.add_skeleton(skel)
self.block_cache.add(o, skel)
self.exported_skeletons.append(o)
def build_mesh_data(self, geom):
vertex_edges = {}
geom_util = AWDGeomUtil()
# Create lookup table for edges by vertex, to use
# when determining if a vertex is on a hard edge
for e in geom.edges:
for v in e.vertices:
if v not in vertex_edges:
vertex_edges[v] = []
vertex_edges[v].append(e)
tex_data = None
has_uvs = False
if len(geom.uv_textures):
has_uvs = True
tex_data = geom.uv_textures[0].data
# Generate expanded list of vertices
for f in geom.faces:
inds_in_face = [0,2,1]
if len(f.vertices)==4:
inds_in_face.extend((0,3,2))
for idx in inds_in_face:
vert = geom.vertices[f.vertices[idx]]
edges = vertex_edges[vert.index]
has_hard_edge = False
for e in edges:
if e.use_edge_sharp:
has_hard_edge = True
break
uv = None
if tex_data is not None and len(tex_data)>0:
# TODO: Implement secondary UV sets?
tex_face = tex_data[f.index]
uv = [tex_face.uv[idx][0], 1.0-tex_face.uv[idx][1]]
v = [vert.co.x, vert.co.z, vert.co.y]
n = [f.normal.x, f.normal.z, f.normal.y]
geom_util.append_vert_data(vert.index, v, uv, n, has_hard_edge)
# Find influences for all vertices
#for v0 in expanded_vertices:
# for v1 in expanded_vertices:
# angle = degrees(v0['normal'].angle(v1['normal']))
# if angle <= geom.auto_smooth_angle:
# v0['normal_influences'].append(v1['f'])
# v1['normal_influences'].append(v0['f'])
md = AWDMeshData(geom.name)
if geom.use_auto_smooth:
geom_util.normal_threshold = geom.auto_smooth_angle
geom_util.build_geom(md)
#md.add_sub_mesh(AWDSubMesh())
#md[0].add_stream(STR_VERTICES, vertices)
#md[0].add_stream(STR_TRIANGLES, indices)
#md[0].add_stream(STR_VERTEX_NORMALS, normals)
return md
def set_attributes(self, ob, awd_elem):
for key in ob.keys():
if (key != '_RNA_UI'):
print('setting prop %s.%s=%s' % (ob.name, key, ob[key]))
awd_elem.attributes[self.user_ns][str(key)] = str(ob[key])
def mtx_bl2awd(self, mtx):
# Decompose matrix
pos, rot, scale = mtx.decompose()
# Swap translation axes
tmp = pos.y
pos.y = pos.z
pos.z = tmp
# Swap rotation axes
tmp = rot.y
rot.x = -rot.x
rot.y = -rot.z
rot.z = -tmp
# Recompose matrix
mtx = mathutils.Matrix.Translation(pos).to_4x4() * rot.to_matrix().to_4x4()
# Create list from rows
rows = list(mtx)
mtx_list = []
mtx_list.extend(list(rows[0]))
mtx_list.extend(list(rows[1]))
mtx_list.extend(list(rows[2]))
mtx_list.extend(list(rows[3]))
# Apply swapped-axis scale
mtx_list[0] *= scale.x
mtx_list[5] *= scale.y
mtx_list[10] *= scale.z
#print(mtx_list[0:4])
#print(mtx_list[4:8])
#print(mtx_list[8:12])
#print(mtx_list[12:])
return AWDMatrix4x4(mtx_list)
if __name__ == '__main__':
def read_sequences(seq_path, base_path):
sequences = []
if seq_path is not None:
if not os.path.isabs(seq_path):
# Look for this file in a list of different locations,
# and use the first one in which it exists.
existed = False
bases = [
bpy.path.abspath('//'),
base_path
]
for base in bases:
new_path = os.path.join(base, seq_path)
print('Looking for sequence file in %s' % new_path)
if os.path.exists(new_path) and os.path.isfile(new_path):
existed = True
seq_path = new_path
break
if not existed:
#mc.warning('Could not find sequence file "%s. Will not export animation."' % seq_path)
return []
try:
with open(seq_path, | |
# Copyright (C) 2020 Georgia Tech Center for Experimental Research in Computer
# Systems
import argparse
import datetime
import os
import re
import shutil
import subprocess
import threading
import time
import jinja2
import yaml
from ssh_client import SSHClient
### Global variables
DOCKER_HUB_USERNAME = None
DOCKER_HUB_PASSWORD = None
SYS_CONF = None
WL_CONF = None
BACKEND_CONF = None
PARSE_LOG_FILES = None
DIRNAME = None
METADATA = None
### Utilities
LOG_FILENAME_TO_PARSER = {
"loadgen.log": "/opt/BuzzBlogBenchmark/analysis/parsers/loadgen_parser.py",
"queries.log": "/opt/BuzzBlogBenchmark/analysis/parsers/query_parser.py",
"redis.log": "/opt/BuzzBlogBenchmark/analysis/parsers/redis_parser.py",
"calls.log": "/opt/BuzzBlogBenchmark/analysis/parsers/rpc_parser.py",
}
def timestamp():
return datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
def update_metadata(metadata):
global METADATA
METADATA.update(metadata)
with open(os.path.join(DIRNAME, "metadata.yml"), 'w') as metadata_file:
metadata_file.write(yaml.dump(METADATA))
def build_backend_conf():
global BACKEND_CONF
BACKEND_CONF = {}
for node_hostname, node_conf in SYS_CONF.items():
for container_name, container_conf in \
node_conf.get("containers", {}).items():
if container_name.endswith("_service") or \
container_name.endswith("_database") or \
container_name.endswith("_redis"):
container_basename = container_name[:container_name.find('_')]
container_type = container_name[container_name.find('_') + 1:]
container_addr = node_hostname + ":" + \
container_conf["options"]["publish"].split(':')[0]
if container_basename not in BACKEND_CONF:
BACKEND_CONF[container_basename] = {"service": []}
if container_type == "service":
BACKEND_CONF[container_basename][container_type].append(
container_addr)
elif container_type == "database":
BACKEND_CONF[container_basename][container_type] = container_addr
elif container_type == "redis":
BACKEND_CONF[container_basename][container_type] = container_addr
def start_container(node_hostname, node_conf, container_name, ssh_client):
container_conf = node_conf["containers"][container_name]
ssh_client.exec("rm -rf /tmp/%s" % container_name)
ssh_client.exec("mkdir -p /tmp/%s" % container_name)
ssh_client.exec("sudo docker run " +
("--volume /tmp/%s:/tmp " % container_name) +
" ".join(["--%s %s" % (param, value) if isinstance(value, str) else
" ".join(["--%s %s" % (param, v) for v in value])
for (param, value) in container_conf.get("options", {}).items()]) +
" " +
"""$(echo $(cat /etc/hosts | grep node- | sed 's/[[:space:]]/ /g' | cut -d ' ' -f 1,4 | sed 's:^\(.*\) \(.*\):\\2\:\\1:' | awk '{print "--add-host="$1""}'))""" +
" " +
container_conf["image"])
time.sleep(16)
if container_conf["image"].startswith("postgres"):
# Setup the database.
subprocess.run("psql -U postgres -d %s -h %s -p %s -f %s" % (
container_name.split('_')[0],
node_hostname,
container_conf["options"]["publish"].split(':')[0],
"/opt/BuzzBlog/app/{service}/database/{service}_schema.sql".\
format(service=container_name.split('_')[0])), shell=True)
def count_containers(container_name_pat):
"""Count number of instances of the specified container (regex supported)."""
count = 0
for _, node_conf in SYS_CONF.items():
for container_name in node_conf.get("containers", {}):
if re.match(container_name_pat, container_name):
count += 1
return count
def all_nodes(func):
"""Run func for all nodes in parallel."""
def func_wrapper(*args, **kwargs):
threads = []
for node_hostname, node_conf in SYS_CONF.items():
ssh_client = SSHClient(node_hostname, node_conf["ssh"]["port"],
node_conf["ssh"]["username"], node_conf["ssh"]["key_filename"],
os.path.join(DIRNAME, "ssh",
"%s-%s" % (node_hostname, func.__name__)))
threads.append(threading.Thread(target=func,
args=[node_hostname, node_conf, ssh_client]))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return func_wrapper
def nodes_with_container(container_name_pat):
"""Run func for nodes with the specified container (regex supported)."""
def func_wrapper_outer(func):
def func_wrapper_inner(*args, **kwargs):
threads = []
for node_hostname, node_conf in SYS_CONF.items():
for container_name in node_conf.get("containers", {}):
if re.match(container_name_pat, container_name):
break
else:
continue
ssh_client = SSHClient(node_hostname, node_conf["ssh"]["port"],
node_conf["ssh"]["username"], node_conf["ssh"]["key_filename"],
os.path.join(DIRNAME, "ssh",
"%s-%s" % (node_hostname, func.__name__)))
threads.append(threading.Thread(target=func,
args=[node_hostname, node_conf, ssh_client]))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return func_wrapper_inner
return func_wrapper_outer
def nodes_with_monitor(monitor_name_pat):
"""Run func for nodes with the specified monitor (regex supported)."""
def func_wrapper_outer(func):
def func_wrapper_inner(*args, **kwargs):
threads = []
for node_hostname, node_conf in SYS_CONF.items():
for monitor_name in node_conf.get("monitors", {}):
if re.match(monitor_name_pat, monitor_name):
break
else:
continue
ssh_client = SSHClient(node_hostname, node_conf["ssh"]["port"],
node_conf["ssh"]["username"], node_conf["ssh"]["key_filename"],
os.path.join(DIRNAME, "ssh",
"%s-%s" % (node_hostname, func.__name__)))
threads.append(threading.Thread(target=func,
args=[node_hostname, node_conf, ssh_client]))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return func_wrapper_inner
return func_wrapper_outer
### Experiment workflow
@all_nodes
def configure_kernel(node_hostname, node_conf, ssh_client):
ssh_client.exec(" && ".join(["sudo sysctl -w %s=\"%s\"" % (param, value)
for param, value in node_conf.get("kernel", {}).items()]))
@all_nodes
def save_system_specs(node_hostname, node_conf, ssh_client):
with open(os.path.join(DIRNAME, "specs", node_hostname, "hw"), "wb+") as \
hw_file:
hw_file.write(ssh_client.exec("sudo lshw")[0])
with open(os.path.join(DIRNAME, "specs", node_hostname, "cpu"), "wb+") as \
cpu_file:
cpu_file.write(ssh_client.exec("lscpu")[0])
with open(os.path.join(DIRNAME, "specs", node_hostname, "mem"), "wb+") as \
mem_file:
mem_file.write(ssh_client.exec("lsmem")[0])
with open(os.path.join(DIRNAME, "specs", node_hostname, "blk"), "wb+") as \
blk_file:
blk_file.write(ssh_client.exec("lsblk")[0])
with open(os.path.join(DIRNAME, "specs", node_hostname, "kernel"), "wb+") as \
kernel_file:
kernel_file.write(ssh_client.exec("sudo sysctl -a")[0])
@nodes_with_container(".+")
def install_buzzblogbenchmark(node_hostname, node_conf, ssh_client):
VERSION = "0.1"
ssh_client.exec(
"sudo mkdir -p /opt/BuzzBlogBenchmark && "
"sudo curl "
"https://codeload.github.com/rodrigoalveslima/BuzzBlogBenchmark/tar.gz/refs/tags/v{VERSION} "
"--output /opt/BuzzBlogBenchmark/v{VERSION}.tar.gz && "
"sudo tar -C /opt/BuzzBlogBenchmark -xzf /opt/BuzzBlogBenchmark/v{VERSION}.tar.gz && "
"sudo mv /opt/BuzzBlogBenchmark/BuzzBlogBenchmark-{VERSION}/* /opt/BuzzBlogBenchmark && "
"sudo rm -rf /opt/BuzzBlogBenchmark/BuzzBlogBenchmark-{VERSION}".format(VERSION=VERSION))
@nodes_with_container(".+")
def install_docker(node_hostname, node_conf, ssh_client):
ssh_client.exec(
"sudo apt-get update && "
"sudo DEBIAN_FRONTEND=noninteractive apt-get -y install "
"apt-transport-https ca-certificates curl gnupg-agent "
"software-properties-common && "
"curl -fsSL https://download.docker.com/linux/ubuntu/gpg | "
"sudo apt-key add - && "
"sudo add-apt-repository "
"\"deb [arch=amd64] https://download.docker.com/linux/ubuntu "
"$(lsb_release -cs) stable\" && "
"sudo apt-get update && "
"sudo DEBIAN_FRONTEND=noninteractive apt-get install -y "
"docker-ce docker-ce-cli containerd.io")
@nodes_with_container(".+")
def install_pandas(node_hostname, node_conf, ssh_client):
ssh_client.exec(
"sudo apt-get update && "
"sudo DEBIAN_FRONTEND=noninteractive apt-get -y install "
"python3-pip && "
"pip3 install pandas==1.3.3")
@nodes_with_monitor(".+-bpfcc")
def install_bpfcc(node_hostname, node_conf, ssh_client):
ssh_client.exec(
"sudo apt-get update && "
"sudo DEBIAN_FRONTEND=noninteractive apt-get install -y "
"bpfcc-tools linux-headers-5.4.0-100-generic")
@nodes_with_monitor(".+-bpftrace")
def install_bpftrace(node_hostname, node_conf, ssh_client):
ssh_client.exec(
"sudo apt-get update && "
"sudo DEBIAN_FRONTEND=noninteractive apt-get install -y "
"linux-headers-5.4.0-100-generic && "
"sudo docker run -v $(pwd):/output quay.io/iovisor/bpftrace:v0.14.1-vanilla_llvm12_clang_glibc2.27 "
"/bin/bash -c \"cp /usr/bin/bpftrace /output\" && "
"sudo mv bpftrace /usr/local/bin/")
@nodes_with_monitor("collectl")
def install_collectl(node_hostname, node_conf, ssh_client):
ssh_client.exec(
"sudo apt-get update && "
"sudo DEBIAN_FRONTEND=noninteractive apt-get install -y collectl")
@nodes_with_monitor("radvisor")
def install_radvisor(node_hostname, node_conf, ssh_client):
# Note: we specify to only compile the Docker feature, which disables
# compiling Kubernetes support via conditional compilation.
VERSION = "1.3.1"
ssh_client.exec(
"sudo apt-get update && "
"sudo DEBIAN_FRONTEND=noninteractive apt-get install -y rustc cargo && "
"sudo mkdir -p /opt/radvisor && "
"sudo curl "
"https://codeload.github.com/elba-docker/radvisor/tar.gz/v{VERSION} "
"--output /opt/radvisor/v{VERSION}.tar.gz && "
"sudo tar -C /opt/radvisor -xzf /opt/radvisor/v{VERSION}.tar.gz && "
"sudo make -C /opt/radvisor/radvisor-{VERSION} compile "
"OUT_DIR=/opt/radvisor FEATURES=docker && "
"sudo cp /opt/radvisor/radvisor /usr/bin/".format(VERSION=VERSION))
@nodes_with_container(".+")
def pull_docker_images(node_hostname, node_conf, ssh_client):
if DOCKER_HUB_USERNAME and DOCKER_HUB_PASSWORD:
ssh_client.exec("sudo docker login -u {username} -p {password}".format(
username=DOCKER_HUB_USERNAME, password=<PASSWORD>))
threads = []
for container_conf in node_conf.get("containers", {}).values():
threads.append(threading.Thread(target=ssh_client.exec,
args=["sudo docker pull %s" % container_conf["image"].split(' ')[0]]))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
@nodes_with_container("loadgen.*")
def copy_workload_configuration_file(node_hostname, node_conf, ssh_client):
ssh_client.exec(
"sudo mkdir -p /usr/local/etc/loadgen && "
"echo \"{content}\" | sudo tee {filepath}".format(
content=yaml.dump(WL_CONF),
filepath="/usr/local/etc/loadgen/workload.yml"))
@all_nodes
def render_configuration_templates(node_hostname, node_conf, ssh_client):
env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(
os.path.dirname(os.path.realpath(__file__)), "templates")))
for template_name, template_conf in node_conf.get("templates", {}).items():
if os.path.split(template_conf["output"])[0]:
ssh_client.exec("sudo mkdir -p %s" % os.path.split(template_conf["output"])[0])
ssh_client.exec("echo \"{content}\" | sudo tee {filepath}".format(
content=env.get_template(template_name).\
render(**template_conf["params"]).replace('"', '\\"'),
filepath=template_conf["output"]))
@all_nodes
def generate_backend_configuration_file(node_hostname, node_conf, ssh_client):
ssh_client.exec(
"sudo mkdir -p /etc/opt/BuzzBlog && "
"echo \"{content}\" | sudo tee {filepath}".format(
content=yaml.dump(BACKEND_CONF),
filepath="/etc/opt/BuzzBlog/backend.yml"))
@all_nodes
def run_setup_scripts(node_hostname, node_conf, ssh_client):
for script in node_conf.get("setup", []):
ssh_client.exec(script)
@nodes_with_monitor(".+")
def start_monitors(node_hostname, node_conf, ssh_client):
for monitor_name, monitor_conf in node_conf["monitors"].items():
ssh_client.exec("rm -rf %s" % monitor_conf["dirpath"])
ssh_client.exec("mkdir -p %s" % monitor_conf["dirpath"])
ssh_client.exec("sudo nohup nice -n %s " %
monitor_conf.get("niceness", 19) +
"stdbuf -oL -eL " +
monitor_conf.get("command", monitor_name) + " " +
" ".join(["--%s %s" % (param, value) for (param, value) in
monitor_conf.get("options", {}).items()]) + " " +
"> {log} 2>&1 < /dev/null &".format(
log=monitor_conf.get("log", "/dev/null")))
def start_containers():
containers = []
for node_hostname, node_conf in SYS_CONF.items():
ssh_client = SSHClient(node_hostname, node_conf["ssh"]["port"],
node_conf["ssh"]["username"], node_conf["ssh"]["key_filename"],
os.path.join(DIRNAME, "ssh",
"%s-%s" % (node_hostname, "start_containers")))
for (container_name, container_conf) in \
node_conf.get("containers", {}).items():
containers.append((container_conf["start_order"], node_hostname,
node_conf, container_name, ssh_client))
for current_start_order in sorted(set([container[0] for container in containers])):
threads = []
for (start_order, node_hostname, node_conf, container_name, ssh_client) in containers:
if start_order == current_start_order:
threads.append(threading.Thread(target=start_container,
args=[node_hostname, node_conf, container_name, ssh_client]))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
@nodes_with_monitor(".+")
def stop_monitors(node_hostname, node_conf, ssh_client):
for monitor_name, monitor_conf in node_conf["monitors"].items():
ssh_client.exec("sudo pkill %s" %
monitor_conf.get("command", monitor_name).split(' ')[0])
@all_nodes
def run_teardown_scripts(node_hostname, node_conf, ssh_client):
for script in node_conf.get("teardown", []):
ssh_client.exec(script)
@all_nodes
def stop_containers(node_hostname, node_conf, ssh_client):
ssh_client.exec("sudo docker container stop $(sudo docker container ls -aq | grep -v ^$(sudo docker ps -aqf \"name=benchmarkcontroller\")$) && "
"sudo docker container rm $(sudo docker container ls -aq | grep -v ^$(sudo docker ps -aqf \"name=benchmarkcontroller\")$) && "
"sudo docker system prune -f --volumes")
@nodes_with_container(".*_database")
def clear_databases(node_hostname, node_conf, ssh_client):
for node_hostname, node_conf in SYS_CONF.items():
for container_name, container_conf in node_conf.get("containers", {}).items():
if container_name.endswith("_database"):
ssh_client.exec("sudo rm -rf %s" % container_conf["options"]["volume"].split(':')[0])
@nodes_with_monitor(".+")
def fetch_monitoring_data(node_hostname, node_conf, ssh_client):
for monitor_name, monitor_conf in node_conf["monitors"].items():
if PARSE_LOG_FILES:
if monitor_name == "collectl":
ssh_client.exec("for filename in $(find %s -name '*.gz' -type f); do "
"python3 /opt/BuzzBlogBenchmark/analysis/parsers/collectl_parser.py "
"--log_filepath ${filename} --csv_filepath ${filename/.gz/.csv}; done" % monitor_conf["dirpath"])
if monitor_name == "tcplistenbl-bpftrace":
ssh_client.exec("python3 /opt/BuzzBlogBenchmark/analysis/parsers/tcplistenbl_parser.py "
"--log_filepath {dirpath}/log --csv_filepath {dirpath}/log.csv".format(dirpath=monitor_conf["dirpath"]))
if monitor_name == "tcpretrans-bpftrace":
ssh_client.exec("python3 /opt/BuzzBlogBenchmark/analysis/parsers/tcpretrans_parser.py "
"--log_filepath {dirpath}/log --csv_filepath {dirpath}/log.csv".format(dirpath=monitor_conf["dirpath"]))
ssh_client.exec("tar -C {dirpath} -czf /tmp/{monitor_name}.tar.gz .".format(
monitor_name=monitor_name, dirpath=monitor_conf["dirpath"]))
ssh_client.copy("/tmp/{monitor_name}.tar.gz".format(
monitor_name=monitor_name),
os.path.join(DIRNAME, "logs", node_hostname))
@nodes_with_container(".+")
def fetch_container_logs(node_hostname, node_conf, ssh_client):
for container_name, container_conf in node_conf["containers"].items():
dirpath = "/tmp/%s" % container_name
ssh_client.exec("sudo docker logs {container_name} > "
"{dirpath}/{container_name}.log 2>&1".format(
container_name=container_name, dirpath=dirpath))
if PARSE_LOG_FILES:
for log_filename in ssh_client.exec("ls {dirpath}".format(dirpath=dirpath))[0].split():
if isinstance(log_filename, bytes):
log_filename = log_filename.decode("utf-8")
if log_filename in LOG_FILENAME_TO_PARSER:
ssh_client.exec("python3 {parser_path} "
"--log_filepath {log_filepath} "
"--csv_filepath {csv_filepath}".format(
parser_path=LOG_FILENAME_TO_PARSER[log_filename],
log_filepath=os.path.join(dirpath, log_filename),
csv_filepath=os.path.join(dirpath, os.path.splitext(log_filename)[0] + ".csv")))
ssh_client.exec("tar -C {dirpath} -czf | |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# sources: inference/dataplane.proto
# plugin: python-betterproto
from dataclasses import dataclass
from typing import Dict, List, Optional
import betterproto
import grpclib
from betterproto.grpc.grpclib_server import ServiceBase
@dataclass(eq=False, repr=False)
class ServerLiveRequest(betterproto.Message):
"""ServerLive messages."""
pass
@dataclass(eq=False, repr=False)
class ServerLiveResponse(betterproto.Message):
# True if the inference server is live, false if not live.
live: bool = betterproto.bool_field(1)
@dataclass(eq=False, repr=False)
class ServerReadyRequest(betterproto.Message):
"""ServerReady messages."""
pass
@dataclass(eq=False, repr=False)
class ServerReadyResponse(betterproto.Message):
# True if the inference server is ready, false if not ready.
ready: bool = betterproto.bool_field(1)
@dataclass(eq=False, repr=False)
class ModelReadyRequest(betterproto.Message):
"""ModelReady messages."""
# The name of the model to check for readiness.
name: str = betterproto.string_field(1)
# The version of the model to check for readiness. If not given the server
# will choose a version based on the model and internal policy.
version: str = betterproto.string_field(2)
@dataclass(eq=False, repr=False)
class ModelReadyResponse(betterproto.Message):
# True if the model is ready, false if not ready.
ready: bool = betterproto.bool_field(1)
@dataclass(eq=False, repr=False)
class ServerMetadataRequest(betterproto.Message):
"""ServerMetadata messages."""
pass
@dataclass(eq=False, repr=False)
class ServerMetadataResponse(betterproto.Message):
# The server name.
name: str = betterproto.string_field(1)
# The server version.
version: str = betterproto.string_field(2)
# The extensions supported by the server.
extensions: List[str] = betterproto.string_field(3)
@dataclass(eq=False, repr=False)
class ModelMetadataRequest(betterproto.Message):
"""ModelMetadata messages."""
# The name of the model.
name: str = betterproto.string_field(1)
# The version of the model to check for readiness. If not given the server
# will choose a version based on the model and internal policy.
version: str = betterproto.string_field(2)
@dataclass(eq=False, repr=False)
class ModelMetadataResponse(betterproto.Message):
# The model name.
name: str = betterproto.string_field(1)
# The versions of the model available on the server.
versions: List[str] = betterproto.string_field(2)
# The model's platform. See Platforms.
platform: str = betterproto.string_field(3)
# The model's inputs.
inputs: List["ModelMetadataResponseTensorMetadata"] = betterproto.message_field(4)
# The model's outputs.
outputs: List["ModelMetadataResponseTensorMetadata"] = betterproto.message_field(5)
# Optional default parameters for the request / response. NOTE: This is an
# extension to the standard
parameters: Dict[str, "InferParameter"] = betterproto.map_field(
6, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
)
@dataclass(eq=False, repr=False)
class ModelMetadataResponseTensorMetadata(betterproto.Message):
"""Metadata for a tensor."""
# The tensor name.
name: str = betterproto.string_field(1)
# The tensor data type.
datatype: str = betterproto.string_field(2)
# The tensor shape. A variable-size dimension is represented by a -1 value.
shape: List[int] = betterproto.int64_field(3)
# Optional default parameters for input. NOTE: This is an extension to the
# standard
parameters: Dict[str, "InferParameter"] = betterproto.map_field(
4, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
)
@dataclass(eq=False, repr=False)
class ModelInferRequest(betterproto.Message):
"""ModelInfer messages."""
# The name of the model to use for inferencing.
model_name: str = betterproto.string_field(1)
# The version of the model to use for inference. If not given the server will
# choose a version based on the model and internal policy.
model_version: str = betterproto.string_field(2)
# Optional identifier for the request. If specified will be returned in the
# response.
id: str = betterproto.string_field(3)
# Optional inference parameters.
parameters: Dict[str, "InferParameter"] = betterproto.map_field(
4, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
)
# The input tensors for the inference.
inputs: List["ModelInferRequestInferInputTensor"] = betterproto.message_field(5)
# The requested output tensors for the inference. Optional, if not specified
# all outputs produced by the model will be returned.
outputs: List["ModelInferRequestInferRequestedOutputTensor"] = betterproto.message_field(6)
@dataclass(eq=False, repr=False)
class ModelInferRequestInferInputTensor(betterproto.Message):
"""An input tensor for an inference request."""
# The tensor name.
name: str = betterproto.string_field(1)
# The tensor data type.
datatype: str = betterproto.string_field(2)
# The tensor shape.
shape: List[int] = betterproto.int64_field(3)
# Optional inference input tensor parameters.
parameters: Dict[str, "InferParameter"] = betterproto.map_field(
4, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
)
# The input tensor data.
contents: "InferTensorContents" = betterproto.message_field(5)
@dataclass(eq=False, repr=False)
class ModelInferRequestInferRequestedOutputTensor(betterproto.Message):
"""An output tensor requested for an inference request."""
# The tensor name.
name: str = betterproto.string_field(1)
# Optional requested output tensor parameters.
parameters: Dict[str, "InferParameter"] = betterproto.map_field(
2, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
)
@dataclass(eq=False, repr=False)
class ModelInferResponse(betterproto.Message):
# The name of the model used for inference.
model_name: str = betterproto.string_field(1)
# The version of the model used for inference.
model_version: str = betterproto.string_field(2)
# The id of the inference request if one was specified.
id: str = betterproto.string_field(3)
# Optional inference response parameters.
parameters: Dict[str, "InferParameter"] = betterproto.map_field(
4, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
)
# The output tensors holding inference results.
outputs: List["ModelInferResponseInferOutputTensor"] = betterproto.message_field(5)
@dataclass(eq=False, repr=False)
class ModelInferResponseInferOutputTensor(betterproto.Message):
"""An output tensor returned for an inference request."""
# The tensor name.
name: str = betterproto.string_field(1)
# The tensor data type.
datatype: str = betterproto.string_field(2)
# The tensor shape.
shape: List[int] = betterproto.int64_field(3)
# Optional output tensor parameters.
parameters: Dict[str, "InferParameter"] = betterproto.map_field(
4, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE
)
# The output tensor data.
contents: "InferTensorContents" = betterproto.message_field(5)
@dataclass(eq=False, repr=False)
class InferParameter(betterproto.Message):
"""An inference parameter value."""
# A boolean parameter value.
bool_param: bool = betterproto.bool_field(1, group="parameter_choice")
# An int64 parameter value.
int64_param: int = betterproto.int64_field(2, group="parameter_choice")
# A string parameter value.
string_param: str = betterproto.string_field(3, group="parameter_choice")
@dataclass(eq=False, repr=False)
class InferTensorContents(betterproto.Message):
"""
The data contained in a tensor. For a given data type the tensor contents
can be represented in "raw" bytes form or in the repeated type that matches
the tensor's data type. Protobuf oneof is not used because oneofs cannot
contain repeated fields.
"""
# Representation for BOOL data type. The size must match what is expected by
# the tensor's shape. The contents must be the flattened, one-dimensional,
# row-major order of the tensor elements.
bool_contents: List[bool] = betterproto.bool_field(1)
# Representation for INT8, INT16, and INT32 data types. The size must match
# what is expected by the tensor's shape. The contents must be the flattened,
# one-dimensional, row-major order of the tensor elements.
int_contents: List[int] = betterproto.int32_field(2)
# Representation for INT64 data types. The size must match what is expected
# by the tensor's shape. The contents must be the flattened, one-dimensional,
# row-major order of the tensor elements.
int64_contents: List[int] = betterproto.int64_field(3)
# Representation for UINT8, UINT16, and UINT32 data types. The size must
# match what is expected by the tensor's shape. The contents must be the
# flattened, one-dimensional, row-major order of the tensor elements.
uint_contents: List[int] = betterproto.uint32_field(4)
# Representation for UINT64 data types. The size must match what is expected
# by the tensor's shape. The contents must be the flattened, one-dimensional,
# row-major order of the tensor elements.
uint64_contents: List[int] = betterproto.uint64_field(5)
# Representation for FP32 data type. The size must match what is expected by
# the tensor's shape. The contents must be the flattened, one-dimensional,
# row-major order of the tensor elements.
fp32_contents: List[float] = betterproto.float_field(6)
# Representation for FP64 data type. The size must match what is expected by
# the tensor's shape. The contents must be the flattened, one-dimensional,
# row-major order of the tensor elements.
fp64_contents: List[float] = betterproto.double_field(7)
# Representation for BYTES data type. The size must match what is expected by
# the tensor's shape. The contents must be the flattened, one-dimensional,
# row-major order of the tensor elements.
bytes_contents: List[bytes] = betterproto.bytes_field(8)
class GrpcInferenceServiceStub(betterproto.ServiceStub):
async def server_live(self) -> "ServerLiveResponse":
request = ServerLiveRequest()
return await self._unary_unary(
"/inference.GRPCInferenceService/ServerLive", request, ServerLiveResponse
)
async def server_ready(self) -> "ServerReadyResponse":
request = ServerReadyRequest()
return await self._unary_unary(
"/inference.GRPCInferenceService/ServerReady", request, ServerReadyResponse
)
async def model_ready(self, *, name: str = "", version: str = "") -> "ModelReadyResponse":
request = ModelReadyRequest()
request.name = name
request.version = version
return await self._unary_unary(
"/inference.GRPCInferenceService/ModelReady", request, ModelReadyResponse
)
async def server_metadata(self) -> "ServerMetadataResponse":
request = ServerMetadataRequest()
return await self._unary_unary(
"/inference.GRPCInferenceService/ServerMetadata",
request,
ServerMetadataResponse,
)
async def model_metadata(self, *, name: str = "", version: str = "") -> "ModelMetadataResponse":
request = ModelMetadataRequest()
request.name = name
request.version = version
return await self._unary_unary(
"/inference.GRPCInferenceService/ModelMetadata",
request,
ModelMetadataResponse,
)
async def model_infer(
self,
*,
model_name: str = "",
model_version: str = "",
id: str = "",
parameters: Dict[str, "InferParameter"] = None,
inputs: Optional[List["ModelInferRequestInferInputTensor"]] = None,
outputs: Optional[List["ModelInferRequestInferRequestedOutputTensor"]] = None,
) -> "ModelInferResponse":
inputs = inputs or []
outputs = outputs or []
request = ModelInferRequest()
request.model_name = model_name
request.model_version = model_version
request.id = id
request.parameters = parameters
if inputs is not None:
request.inputs = inputs
if outputs is not None:
request.outputs = outputs
return await self._unary_unary(
"/inference.GRPCInferenceService/ModelInfer", request, ModelInferResponse
)
class GrpcInferenceServiceBase(ServiceBase):
async def server_live(self) -> "ServerLiveResponse":
raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
async def server_ready(self) -> "ServerReadyResponse":
raise grpclib.GRPCError(grpclib.const.Status.UNIMPLEMENTED)
async def model_ready(self, name: str, version: str) | |
1),
(7, 5, -5, -2): (0, 1),
(7, 5, -5, -1): (0, 1),
(7, 5, -5, 0): (0, 1),
(7, 5, -5, 1): (0, 1),
(7, 5, -5, 2): (0, 1),
(7, 5, -5, 3): (0, 1),
(7, 5, -5, 4): (0, 1),
(7, 5, -5, 5): (0, 1),
(7, 5, -4, -5): (-1, 0),
(7, 5, -4, -4): (-1, -1),
(7, 5, -4, -3): (0, 1),
(7, 5, -4, -2): (0, 1),
(7, 5, -4, -1): (0, 1),
(7, 5, -4, 0): (0, 1),
(7, 5, -4, 1): (0, 1),
(7, 5, -4, 2): (0, 1),
(7, 5, -4, 3): (0, 1),
(7, 5, -4, 4): (0, 1),
(7, 5, -4, 5): (0, 1),
(7, 5, -3, -5): (-1, 0),
(7, 5, -3, -4): (-1, -1),
(7, 5, -3, -3): (0, 1),
(7, 5, -3, -2): (0, 1),
(7, 5, -3, -1): (0, 1),
(7, 5, -3, 0): (0, 1),
(7, 5, -3, 1): (0, 1),
(7, 5, -3, 2): (0, 1),
(7, 5, -3, 3): (0, 1),
(7, 5, -3, 4): (0, 1),
(7, 5, -3, 5): (0, 1),
(7, 5, -2, -5): (-1, 0),
(7, 5, -2, -4): (0, 1),
(7, 5, -2, -3): (0, 1),
(7, 5, -2, -2): (0, 1),
(7, 5, -2, -1): (0, 1),
(7, 5, -2, 0): (1, 1),
(7, 5, -2, 1): (1, 1),
(7, 5, -2, 2): (1, 1),
(7, 5, -2, 3): (1, 1),
(7, 5, -2, 4): (1, 1),
(7, 5, -2, 5): (1, 0),
(7, 5, -1, -5): (-1, 1),
(7, 5, -1, -4): (-1, 1),
(7, 5, -1, -3): (-1, 1),
(7, 5, -1, -2): (-1, 1),
(7, 5, -1, -1): (1, 1),
(7, 5, -1, 0): (1, 1),
(7, 5, -1, 1): (1, 1),
(7, 5, -1, 2): (1, 1),
(7, 5, -1, 3): (1, 1),
(7, 5, -1, 4): (1, 1),
(7, 5, -1, 5): (1, 0),
(7, 5, 0, -5): (1, 0),
(7, 5, 0, -4): (1, -1),
(7, 5, 0, -3): (-1, 1),
(7, 5, 0, -2): (-1, 1),
(7, 5, 0, -1): (1, 1),
(7, 5, 0, 0): (1, 1),
(7, 5, 0, 1): (1, 1),
(7, 5, 0, 2): (1, 1),
(7, 5, 0, 3): (0, 1),
(7, 5, 0, 4): (0, 1),
(7, 5, 0, 5): (0, 1),
(7, 5, 1, -5): (1, 0),
(7, 5, 1, -4): (1, -1),
(7, 5, 1, -3): (1, 1),
(7, 5, 1, -2): (1, 1),
(7, 5, 1, -1): (0, 1),
(7, 5, 1, 0): (0, 1),
(7, 5, 1, 1): (0, 1),
(7, 5, 1, 2): (0, 1),
(7, 5, 1, 3): (-1, 1),
(7, 5, 1, 4): (-1, 1),
(7, 5, 1, 5): (-1, 1),
(7, 5, 2, -5): (0, 0),
(7, 5, 2, -4): (1, 1),
(7, 5, 2, -3): (1, 1),
(7, 5, 2, -2): (1, 1),
(7, 5, 2, -1): (1, 1),
(7, 5, 2, 0): (-1, 1),
(7, 5, 2, 1): (-1, 1),
(7, 5, 2, 2): (-1, 1),
(7, 5, 2, 3): (-1, 1),
(7, 5, 2, 4): (-1, 1),
(7, 5, 2, 5): (-1, 1),
(7, 5, 3, -5): (0, 1),
(7, 5, 3, -4): (0, 1),
(7, 5, 3, -3): (0, 1),
(7, 5, 3, -2): (0, 1),
(7, 5, 3, -1): (0, 1),
(7, 5, 3, 0): (0, 1),
(7, 5, 3, 1): (0, 1),
(7, 5, 3, 2): (0, 1),
(7, 5, 3, 3): (-1, 1),
(7, 5, 3, 4): (0, 1),
(7, 5, 3, 5): (0, 1),
(7, 5, 4, -5): (0, 1),
(7, 5, 4, -4): (0, 1),
(7, 5, 4, -3): (0, 1),
(7, 5, 4, -2): (0, 1),
(7, 5, 4, -1): (0, 1),
(7, 5, 4, 0): (0, 1),
(7, 5, 4, 1): (0, 1),
(7, 5, 4, 2): (0, 1),
(7, 5, 4, 3): (0, 1),
(7, 5, 4, 4): (0, 1),
(7, 5, 4, 5): (0, 1),
(7, 5, 5, -5): (0, 1),
(7, 5, 5, -4): (0, 1),
(7, 5, 5, -3): (0, 1),
(7, 5, 5, -2): (0, 1),
(7, 5, 5, -1): (0, 1),
(7, 5, 5, 0): (0, 1),
(7, 5, 5, 1): (0, 1),
(7, 5, 5, 2): (0, 1),
(7, 5, 5, 3): (0, 1),
(7, 5, 5, 4): (0, 1),
(7, 5, 5, 5): (0, 1),
(7, 6, -5, -5): (0, 1),
(7, 6, -5, -4): (0, 1),
(7, 6, -5, -3): (0, 1),
(7, 6, -5, -2): (0, 1),
(7, 6, -5, -1): (0, 1),
(7, 6, -5, 0): (0, 1),
(7, 6, -5, 1): (0, 1),
(7, 6, -5, 2): (0, 1),
(7, 6, -5, 3): (0, 1),
(7, 6, -5, 4): (0, 1),
(7, 6, -5, 5): (0, 1),
(7, 6, -4, -5): (0, 1),
(7, 6, -4, -4): (0, 1),
(7, 6, -4, -3): (0, 1),
(7, 6, -4, -2): (0, 1),
(7, 6, -4, -1): (0, 1),
(7, 6, -4, 0): (0, 1),
(7, 6, -4, 1): (0, 1),
(7, 6, -4, 2): (0, 1),
(7, 6, -4, 3): (0, 1),
(7, 6, -4, 4): (0, 1),
(7, 6, -4, 5): (0, 1),
(7, 6, -3, -5): (0, 1),
(7, 6, -3, -4): (0, 1),
(7, 6, -3, -3): (0, 1),
(7, 6, -3, -2): (0, 1),
(7, 6, -3, -1): (0, 1),
(7, 6, -3, 0): (0, 1),
(7, 6, -3, 1): (0, 1),
(7, 6, -3, 2): (0, 1),
(7, 6, -3, 3): (0, 1),
(7, 6, -3, 4): (0, 1),
(7, 6, -3, 5): (0, 1),
(7, 6, -2, -5): (0, 1),
(7, 6, -2, -4): (0, 1),
(7, 6, -2, -3): (0, 1),
(7, 6, -2, -2): (0, 1),
(7, 6, -2, -1): (0, 1),
(7, 6, -2, 0): (1, 1),
(7, 6, -2, 1): (1, 1),
(7, 6, -2, 2): (1, 1),
(7, 6, -2, 3): (1, 1),
(7, 6, -2, 4): (1, 1),
(7, 6, -2, 5): (1, 0),
(7, 6, -1, -5): (-1, 1),
(7, 6, -1, -4): (-1, 1),
(7, 6, -1, -3): (-1, 1),
(7, 6, -1, -2): (-1, 1),
(7, 6, -1, -1): (1, 1),
(7, 6, -1, 0): (1, 1),
(7, 6, -1, 1): (1, 1),
(7, 6, -1, 2): (1, 1),
(7, 6, -1, 3): (1, 1),
(7, 6, -1, 4): (1, 1),
(7, 6, -1, 5): (1, 0),
(7, 6, 0, -5): (-1, 1),
(7, 6, 0, -4): (-1, 1),
(7, 6, 0, -3): (-1, 1),
(7, 6, 0, -2): (1, 1),
(7, 6, 0, -1): (1, 1),
(7, 6, 0, 0): (1, 1),
(7, 6, 0, 1): (1, 1),
(7, 6, 0, 2): (1, 1),
(7, 6, 0, 3): (0, 1),
(7, 6, 0, 4): (0, 1),
(7, 6, 0, 5): (0, 1),
(7, 6, 1, -5): (0, 1),
(7, 6, 1, -4): (0, 1),
(7, 6, 1, -3): (1, 1),
(7, 6, 1, -2): (1, 1),
(7, 6, 1, -1): (0, 1),
(7, 6, 1, 0): (0, 1),
(7, 6, 1, 1): (0, 1),
(7, 6, 1, 2): (0, 1),
(7, 6, 1, 3): (-1, 1),
(7, 6, 1, 4): (-1, 1),
(7, 6, 1, 5): (-1, 1),
(7, 6, 2, -5): (1, 1),
(7, 6, 2, -4): (1, 1),
(7, 6, 2, -3): (1, 1),
(7, 6, 2, -2): (1, 1),
(7, 6, 2, -1): (1, 1),
(7, 6, 2, 0): (-1, 1),
(7, 6, 2, 1): (-1, 1),
(7, 6, 2, 2): (-1, 1),
(7, 6, 2, 3): (-1, 1),
(7, 6, 2, 4): (-1, 1),
(7, 6, 2, 5): (-1, 1),
(7, 6, 3, -5): (0, 1),
(7, 6, 3, -4): (0, 1),
(7, 6, 3, -3): (0, 1),
(7, 6, 3, -2): (0, 1),
(7, 6, 3, -1): (0, 1),
(7, 6, 3, 0): (0, 1),
(7, 6, 3, 1): (0, 1),
(7, | |
(self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
# Build the URL
url = "http://askcheck.com/reverse?reverse=%s" % (hashvalue)
# Make the request
response = do_HTTP_request ( url )
# Analyze the response
html = None
if response:
html = response.read()
else:
return None
match = search (r'Reverse value of [^\s]* hash <a[^<]*</a> is <a[^>]*>[^<]*</a>', html)
if match:
return match.group().split('>')[3][:-3]
else:
return None
class FOX21:
name = "fox21"
url = "http://cracker.fox21.at"
supported_algorithm = [MD5, LM, NTLM]
def isSupported (self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
hash2 = None
if alg in [LM, NTLM] and ':' in hashvalue:
if alg == LM:
hash2 = hashvalue.split(':')[0]
else:
hash2 = hashvalue.split(':')[1]
else:
hash2 = hashvalue
# Build the URL
url = "http://cracker.fox21.at/api.php?a=check&h=%s" % (hashvalue)
# Make the request
response = do_HTTP_request ( url )
# Analyze the response
xml = None
if response:
try:
doc = parseDoc ( response.read() )
except:
print "INFO: You need libxml2 to use this plugin."
return None
else:
return None
result = doc.xpathEval("//hash/@plaintext")
if result:
return result[0].content
else:
return None
class NICENAMECREW:
name = "nicenamecrew"
url = "http://crackfoo.nicenamecrew.com"
supported_algorithm = [MD5, SHA1, LM]
def isSupported (self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
hash2 = None
if alg in [LM] and ':' in hashvalue:
hash2 = hashvalue.split(':')[0]
else:
hash2 = hashvalue
# Build the URL
url = "http://crackfoo.nicenamecrew.com/?t=%s" % (alg)
# Build the parameters
params = { "q" : hash2,
"sa" : "Crack" }
# Make the request
response = do_HTTP_request ( url, params )
# Analyze the response
html = None
if response:
html = response.read()
else:
return None
match = search (r'The decrypted version of [^\s]* is:<br><strong>[^<]*</strong>', html)
if match:
return match.group().split('strong>')[1][:-2].strip()
else:
return None
class JOOMLAAA:
name = "joomlaaa"
url = "http://joomlaaa.com"
supported_algorithm = [MD5]
def isSupported (self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
# Build the URL
url = "http://joomlaaa.com/component/option,com_md5/Itemid,31/"
# Build the parameters
params = { "md5" : hashvalue,
"decode" : "Submit" }
# Make the request
response = do_HTTP_request ( url, params )
# Analyze the response
html = None
if response:
html = response.read()
else:
return None
match = search (r"<td class='title1'>not available</td>", html)
if not match:
match2 = findall (r"<td class='title1'>[^<]*</td>", html)
return match2[1].split('>')[1][:-4]
else:
return None
class MD5_LOOKUP:
name = "md5-lookup"
url = "http://md5-lookup.com"
supported_algorithm = [MD5]
def isSupported (self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
# Build the URL
url = "http://md5-lookup.com/livesearch.php?q=%s" % (hashvalue)
# Make the request
response = do_HTTP_request ( url )
# Analyze the response
html = None
if response:
html = response.read()
else:
return None
match = search (r'<td width="250">[^<]*</td>', html)
if match:
return match.group().split('>')[1][:-4]
else:
return None
class SHA1_LOOKUP:
name = "sha1-lookup"
url = "http://sha1-lookup.com"
supported_algorithm = [SHA1]
def isSupported (self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
# Build the URL
url = "http://sha1-lookup.com/livesearch.php?q=%s" % (hashvalue)
# Make the request
response = do_HTTP_request ( url )
# Analyze the response
html = None
if response:
html = response.read()
else:
return None
match = search (r'<td width="250">[^<]*</td>', html)
if match:
return match.group().split('>')[1][:-4]
else:
return None
class SHA256_LOOKUP:
name = "sha256-lookup"
url = "http://sha-256.sha1-lookup.com"
supported_algorithm = [SHA256]
def isSupported (self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
# Build the URL
url = "http://sha-256.sha1-lookup.com/livesearch.php?q=%s" % (hashvalue)
# Make the request
response = do_HTTP_request ( url )
# Analyze the response
html = None
if response:
html = response.read()
else:
return None
match = search (r'<td width="250">[^<]*</td>', html)
if match:
return match.group().split('>')[1][:-4]
else:
return None
class RIPEMD160_LOOKUP:
name = "ripemd-lookup"
url = "http://www.ripemd-lookup.com"
supported_algorithm = [RIPEMD]
def isSupported (self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
# Build the URL
url = "http://www.ripemd-lookup.com/livesearch.php?q=%s" % (hashvalue)
# Make the request
response = do_HTTP_request ( url )
# Analyze the response
html = None
if response:
html = response.read()
else:
return None
match = search (r'<td width="250">[^<]*</td>', html)
if match:
return match.group().split('>')[1][:-4]
else:
return None
class MD5_COM_CN:
name = "md5.com.cn"
url = "http://md5.com.cn"
supported_algorithm = [MD5]
def isSupported (self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
# Build the URL
url = "http://md5.com.cn/md5reverse"
# Build the parameters
params = { "md" : hashvalue,
"submit" : "MD5 Crack" }
# Make the request
response = do_HTTP_request ( url, params )
# Analyze the response
html = None
if response:
html = response.read()
else:
return None
match = search (r'<b style="color:red;">[^<]*</b><br/><span', html)
if match:
return match.group().split('>')[1][:-3]
else:
return None
class DIGITALSUN:
name = "digitalsun.pl"
url = "http://md5.digitalsun.pl"
supported_algorithm = [MD5]
def isSupported (self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
# Build the URL
url = "http://md5.digitalsun.pl/"
# Build the parameters
params = { "hash" : hashvalue }
# Make the request
response = do_HTTP_request ( url, params )
# Analyze the response
html = None
if response:
html = response.read()
else:
return None
match = search (r'<b>[^<]*</b> == [^<]*<br>\s*<br>', html)
if match:
return match.group().split('b>')[1][:-2]
else:
return None
class DRASEN:
name = "drasen.net"
url = "http://md5.drasen.net"
supported_algorithm = [MD5]
def isSupported (self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
# Build the URL
url = "http://md5.drasen.net/search.php?query=%s" % (hashvalue)
# Make the request
response = do_HTTP_request ( url )
# Analyze the response
html = None
if response:
html = response.read()
else:
return None
match = search (r'Hash: [^<]*<br />Plain: [^<]*<br />', html)
if match:
return match.group().split('<br />')[1][7:]
else:
return None
class MYINFOSEC:
name = "myinfosec"
url = "http://md5.myinfosec.net"
supported_algorithm = [MD5]
def isSupported (self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
# Build the URL
url = "http://md5.myinfosec.net/md5.php"
# Build the parameters
params = { "md5hash" : hashvalue }
# Make the request
response = do_HTTP_request ( url, params )
# Analyze the response
html = None
if response:
html = response.read()
else:
return None
match = search (r'<center></center>[^<]*<font color=green>[^<]*</font><br></center>', html)
if match:
return match.group().split('>')[3][:-6]
else:
return None
class MD5_NET:
name = "md5.net"
url = "http://md5.net"
supported_algorithm = [MD5]
def isSupported (self, alg):
"""Return True if HASHCRACK can crack this type of algorithm and
False if it cannot."""
if alg in self.supported_algorithm:
return True
else:
return False
def crack (self, hashvalue, alg):
"""Try to crack the hash.
@param hashvalue Hash to crack.
@param alg Algorithm to crack."""
# Check if the cracker can crack this kind of algorithm
if not self.isSupported (alg):
return None
# Build the URL
url = "http://www.md5.net/cracker.php"
# Build the parameters
params = { "hash" : hashvalue }
# Make the request
response = do_HTTP_request ( url, params )
# Analyze the response
html = None
if response:
html | |
<reponame>utdsimmons/ohpc
#!/usr/bin/env python
# ClusterShell (distant, pdsh worker) test suite
# Written by <NAME>
"""Unit test for ClusterShell Task (distant, pdsh worker)"""
import copy
import shutil
import sys
sys.path.insert(0, '../lib')
from TLib import HOSTNAME, make_temp_filename, make_temp_dir
from ClusterShell.Event import EventHandler
from ClusterShell.NodeSet import NodeSet
from ClusterShell.Task import *
from ClusterShell.Worker.Worker import WorkerBadArgumentError
from ClusterShell.Worker.Pdsh import WorkerPdsh
from ClusterShell.Worker.EngineClient import *
import socket
# TEventHandlerChecker 'received event' flags
EV_START = 0x01
EV_PICKUP = 0x02
EV_READ = 0x04
EV_WRITTEN = 0x08
EV_HUP = 0x10
EV_TIMEOUT = 0x20
EV_CLOSE = 0x40
class TaskDistantPdshMixin(object):
def setUp(self):
self._task = task_self()
def testWorkerPdshGetCommand(self):
# test worker.command with WorkerPdsh
worker1 = WorkerPdsh(HOSTNAME, command="/bin/echo foo bar fuu",
handler=None, timeout=5)
self._task.schedule(worker1)
worker2 = WorkerPdsh(HOSTNAME, command="/bin/echo blah blah foo",
handler=None, timeout=5)
self._task.schedule(worker2)
# run task
self._task.resume()
# test output
self.assertEqual(worker1.node_buffer(HOSTNAME), "foo bar fuu")
self.assertEqual(worker1.command, "/bin/echo foo bar fuu")
self.assertEqual(worker2.node_buffer(HOSTNAME), "blah blah foo")
self.assertEqual(worker2.command, "/bin/echo blah blah foo")
def testLocalhostExplicitPdshCopy(self):
# test simple localhost copy with explicit pdsh worker
dest = make_temp_filename(suffix='LocalhostExplicitPdshCopy')
try:
worker = WorkerPdsh(HOSTNAME, source="/etc/hosts",
dest=dest, handler=None, timeout=10)
self._task.schedule(worker)
self._task.resume()
self.assertEqual(worker.source, "/etc/hosts")
self.assertEqual(worker.dest, dest)
finally:
os.unlink(dest)
def testLocalhostExplicitPdshCopyWithOptions(self):
dest = make_temp_dir('testLocalhostExplicitPdshCopyWithOptions')
self._task.set_info("pdcp_path", "pdcp -p")
try:
worker = WorkerPdsh(HOSTNAME, source="/etc/hosts", dest=dest,
handler=None)
self._task.schedule(worker)
self._task.resume()
self.assertEqual(self._task.max_retcode(), 0)
self.assertTrue(os.path.exists(os.path.join(dest, "hosts")))
finally:
os.unlink(os.path.join(dest, "hosts"))
os.rmdir(dest)
# clear options after test
task_cleanup()
self.assertEqual(task_self().info("pdcp_path"), None)
def testLocalhostExplicitPdshCopyDir(self):
# test simple localhost copy dir with explicit pdsh worker
dtmp_src = make_temp_dir('src')
# pdcp worker doesn't create custom destination directory
dtmp_dst = make_temp_dir('testLocalhostExplicitPdshCopyDir')
try:
os.mkdir(os.path.join(dtmp_src, "lev1_a"))
os.mkdir(os.path.join(dtmp_src, "lev1_b"))
os.mkdir(os.path.join(dtmp_src, "lev1_a", "lev2"))
worker = WorkerPdsh(HOSTNAME, source=dtmp_src,
dest=dtmp_dst, handler=None, timeout=10)
self._task.schedule(worker)
self._task.resume()
self.assertTrue(os.path.exists(os.path.join(dtmp_dst, \
os.path.basename(dtmp_src), "lev1_a", "lev2")))
finally:
shutil.rmtree(dtmp_dst, ignore_errors=True)
shutil.rmtree(dtmp_src, ignore_errors=True)
def testLocalhostExplicitPdshCopyDirPreserve(self):
# test simple localhost preserve copy dir with explicit pdsh worker
dtmp_src = make_temp_dir('src')
# pdcp worker doesn't create custom destination directory
dtmp_dst = make_temp_dir('testLocalhostExplicitPdshCopyDirPreserve')
try:
os.mkdir(os.path.join(dtmp_src, "lev1_a"))
os.mkdir(os.path.join(dtmp_src, "lev1_b"))
os.mkdir(os.path.join(dtmp_src, "lev1_a", "lev2"))
worker = WorkerPdsh(HOSTNAME, source=dtmp_src,
dest=dtmp_dst, handler=None, timeout=10, preserve=True)
self._task.schedule(worker)
self._task.resume()
self.assert_(os.path.exists(os.path.join(dtmp_dst, \
os.path.basename(dtmp_src), "lev1_a", "lev2")))
finally:
shutil.rmtree(dtmp_dst, ignore_errors=True)
shutil.rmtree(dtmp_src, ignore_errors=True)
def testExplicitPdshWorker(self):
# test simple localhost command with explicit pdsh worker
# init worker
worker = WorkerPdsh(HOSTNAME, command="echo alright", handler=None)
self._task.schedule(worker)
# run task
self._task.resume()
# test output
self.assertEqual(worker.node_buffer(HOSTNAME), "alright")
def testExplicitPdshWorkerWithOptions(self):
self._task.set_info("pdsh_path", "/usr/bin/pdsh -S")
worker = WorkerPdsh(HOSTNAME, command="echo alright", handler=None)
self._task.schedule(worker)
# run task
self._task.resume()
# test output
self.assertEqual(worker.node_buffer(HOSTNAME), "alright")
# clear options after test
task_cleanup()
self.assertEqual(task_self().info("pdsh_path"), None)
def testExplicitPdshWorkerStdErr(self):
# test simple localhost command with explicit pdsh worker (stderr)
worker = WorkerPdsh(HOSTNAME, command="echo alright 1>&2",
handler=None, stderr=True)
self._task.schedule(worker)
# run task
self._task.resume()
# test output
self.assertEqual(worker.node_error_buffer(HOSTNAME), "alright")
# Re-test with stderr=False
worker = WorkerPdsh(HOSTNAME, command="echo alright 1>&2",
handler=None, stderr=False)
self._task.schedule(worker)
# run task
self._task.resume()
# test output
self.assertEqual(worker.node_error_buffer(HOSTNAME), None)
def testPdshWorkerWriteNotSupported(self):
# test that write is reported as not supported with pdsh
worker = WorkerPdsh(HOSTNAME, command="uname -r", handler=None,
timeout=5)
self.assertRaises(EngineClientNotSupportedError, worker.write, "toto")
class TEventHandlerChecker(EventHandler):
"""simple event trigger validator"""
def __init__(self, test):
self.test = test
self.flags = 0
self.read_count = 0
self.written_count = 0
def ev_start(self, worker):
self.test.assertEqual(self.flags, 0)
self.flags |= EV_START
def ev_pickup(self, worker):
self.test.assertTrue(self.flags & EV_START)
self.flags |= EV_PICKUP
self.last_node = worker.current_node
def ev_read(self, worker):
self.test.assertEqual(self.flags, EV_START | EV_PICKUP)
self.flags |= EV_READ
self.last_node = worker.current_node
self.last_read = worker.current_msg
def ev_written(self, worker):
self.test.assertTrue(self.flags & (EV_START | EV_PICKUP))
self.flags |= EV_WRITTEN
def ev_hup(self, worker):
self.test.assertTrue(self.flags & (EV_START | EV_PICKUP))
self.flags |= EV_HUP
self.last_node = worker.current_node
self.last_rc = worker.current_rc
def ev_timeout(self, worker):
self.test.assertTrue(self.flags & EV_START)
self.flags |= EV_TIMEOUT
self.last_node = worker.current_node
def ev_close(self, worker):
self.test.assertTrue(self.flags & EV_START)
self.test.assertTrue(self.flags & EV_CLOSE == 0)
self.flags |= EV_CLOSE
def testExplicitWorkerPdshShellEvents(self):
# test triggered events with explicit pdsh worker
test_eh = self.__class__.TEventHandlerChecker(self)
worker = WorkerPdsh(HOSTNAME, command="hostname", handler=test_eh, timeout=None)
self._task.schedule(worker)
# run task
self._task.resume()
# test events received: start, read, hup, close
self.assertEqual(test_eh.flags, EV_START | EV_PICKUP | EV_READ | EV_HUP | EV_CLOSE)
def testExplicitWorkerPdshShellEventsWithTimeout(self):
# test triggered events (with timeout) with explicit pdsh worker
test_eh = self.__class__.TEventHandlerChecker(self)
worker = WorkerPdsh(HOSTNAME, command="echo alright && sleep 10",
handler=test_eh, timeout=2)
self._task.schedule(worker)
# run task
self._task.resume()
# test events received: start, read, timeout, close
self.assertEqual(test_eh.flags, EV_START | EV_PICKUP | EV_READ | EV_TIMEOUT | EV_CLOSE)
self.assertEqual(worker.node_buffer(HOSTNAME), "alright")
def testShellPdshEventsNoReadNoTimeout(self):
# test triggered events (no read, no timeout) with explicit pdsh worker
test_eh = self.__class__.TEventHandlerChecker(self)
worker = WorkerPdsh(HOSTNAME, command="sleep 2",
handler=test_eh, timeout=None)
self._task.schedule(worker)
# run task
self._task.resume()
# test events received: start, close
self.assertEqual(test_eh.flags, EV_START | EV_PICKUP | EV_HUP | EV_CLOSE)
self.assertEqual(worker.node_buffer(HOSTNAME), None)
def testWorkerPdshBuffers(self):
# test buffers at pdsh worker level
worker = WorkerPdsh(HOSTNAME, command="printf 'foo\nbar\nxxx\n'",
handler=None, timeout=None)
self._task.schedule(worker)
self._task.resume()
cnt = 2
for buf, nodes in worker.iter_buffers():
cnt -= 1
if buf == "foo\nbar\nxxx\n":
self.assertEqual(len(nodes), 1)
self.assertEqual(str(nodes), HOSTNAME)
self.assertEqual(cnt, 1)
# new check in 1.7 to ensure match_keys is not a string
testgen = worker.iter_buffers(HOSTNAME)
# cast to list to effectively iterate
self.assertRaises(TypeError, list, testgen)
# and also fixed an issue when match_keys was an empty list
for buf, nodes in worker.iter_buffers([]):
self.assertFalse("Found buffer with empty match_keys?!")
for buf, nodes in worker.iter_buffers([HOSTNAME]):
cnt -= 1
if buf == "foo\nbar\nxxx\n":
self.assertEqual(len(nodes), 1)
self.assertEqual(str(nodes), HOSTNAME)
self.assertEqual(cnt, 0)
def testWorkerPdshNodeBuffers(self):
# test iter_node_buffers on distant pdsh workers
worker = WorkerPdsh(HOSTNAME, command="/usr/bin/printf 'foo\nbar\nxxx\n'",
handler=None, timeout=None)
self._task.schedule(worker)
self._task.resume()
cnt = 1
for node, buf in worker.iter_node_buffers():
cnt -= 1
if buf == "foo\nbar\nxxx\n":
self.assertEqual(node, HOSTNAME)
self.assertEqual(cnt, 0)
def testWorkerPdshNodeErrors(self):
# test iter_node_errors on distant pdsh workers
worker = WorkerPdsh(HOSTNAME, command="/usr/bin/printf 'foo\nbar\nxxx\n' 1>&2",
handler=None, timeout=None, stderr=True)
self._task.schedule(worker)
self._task.resume()
cnt = 1
for node, buf in worker.iter_node_errors():
cnt -= 1
if buf == "foo\nbar\nxxx\n":
self.assertEqual(node, HOSTNAME)
self.assertEqual(cnt, 0)
def testWorkerPdshRetcodes(self):
# test retcodes on distant pdsh workers
worker = WorkerPdsh(HOSTNAME, command="/bin/sh -c 'exit 3'",
handler=None, timeout=None)
self._task.schedule(worker)
self._task.resume()
cnt = 2
for rc, keys in worker.iter_retcodes():
cnt -= 1
self.assertEqual(rc, 3)
self.assertEqual(len(keys), 1)
self.assert_(keys[0] == HOSTNAME)
self.assertEqual(cnt, 1)
for rc, keys in worker.iter_retcodes(HOSTNAME):
cnt -= 1
self.assertEqual(rc, 3)
self.assertEqual(len(keys), 1)
self.assert_(keys[0] == HOSTNAME)
self.assertEqual(cnt, 0)
# test node_retcode
self.assertEqual(worker.node_retcode(HOSTNAME), 3) # 1.2.91+
self.assertEqual(worker.node_rc(HOSTNAME), 3)
# test node_retcode failure
self.assertRaises(KeyError, worker.node_retcode, "dummy")
# test max retcode API
self.assertEqual(self._task.max_retcode(), 3)
def testWorkerNodeRetcodes(self):
# test iter_node_retcodes on distant pdsh workers
worker = WorkerPdsh(HOSTNAME, command="/bin/sh -c 'exit 3'",
handler=None, timeout=None)
self._task.schedule(worker)
self._task.resume()
cnt = 1
for node, rc in worker.iter_node_retcodes():
cnt -= 1
self.assertEqual(rc, 3)
self.assertEqual(node, HOSTNAME)
self.assertEqual(cnt, 0)
def testEscapePdsh(self):
# test distant worker (pdsh) cmd with escaped variable
worker = WorkerPdsh(HOSTNAME, command="export CSTEST=foobar; /bin/echo \$CSTEST | sed 's/\ foo/bar/'",
handler=None, timeout=None)
#task.set_info("debug", True)
self._task.schedule(worker)
# execute
self._task.resume()
# read result
self.assertEqual(worker.node_buffer(HOSTNAME), "$CSTEST")
def testEscapePdsh2(self):
# test distant worker (pdsh) cmd with non-escaped variable
worker = WorkerPdsh(HOSTNAME, command="export CSTEST=foobar; /bin/echo $CSTEST | sed 's/\ foo/bar/'",
handler=None, timeout=None)
self._task.schedule(worker)
# execute
self._task.resume()
# read result
self.assertEqual(worker.node_buffer(HOSTNAME), "foobar")
def testShellPdshStderrWithHandler(self):
# test reading stderr of distant pdsh worker on event handler
class StdErrHandler(EventHandler):
def ev_error(self, worker):
assert worker.last_error() == "something wrong"
worker = WorkerPdsh(HOSTNAME, command="echo something wrong 1>&2",
handler=StdErrHandler(), timeout=None)
self._task.schedule(worker)
self._task.resume()
for buf, nodes in worker.iter_errors():
self.assertEqual(buf, "something wrong")
for buf, nodes in worker.iter_errors([HOSTNAME]):
self.assertEqual(buf, "something wrong")
def testCommandTimeoutOption(self):
# test pdsh shell with command_timeout set
command_timeout_orig = self._task.info("command_timeout")
self._task.set_info("command_timeout", 1)
worker = WorkerPdsh(HOSTNAME, command="sleep 10",
handler=None, timeout=None)
self._task.schedule(worker)
self.assert_(worker != None)
self._task.resume()
# restore original command_timeout (0)
self.assertEqual(command_timeout_orig, 0)
self._task.set_info("command_timeout", command_timeout_orig)
def testPdshBadArgumentOption(self):
# test WorkerPdsh constructor bad argument
# Check code < 1.4 compatibility
self.assertRaises(WorkerBadArgumentError, WorkerPdsh, HOSTNAME,
None, None)
# As of 1.4, ValueError is raised for missing parameter
self.assertRaises(ValueError, WorkerPdsh, HOSTNAME, None, None) # 1.4+
def testCopyEvents(self):
test_eh = self.__class__.TEventHandlerChecker(self)
dest = "/tmp/cs-test_testLocalhostPdshCopyEvents"
try:
worker = WorkerPdsh(HOSTNAME, source="/etc/hosts",
dest=dest, handler=test_eh, timeout=10)
self._task.schedule(worker)
self._task.resume()
self.assertEqual(test_eh.flags, EV_START | EV_PICKUP | EV_HUP | EV_CLOSE)
finally:
os.remove(dest)
def testWorkerAbort(self):
# test WorkerPdsh abort() on timer
class AbortOnTimer(EventHandler):
def __init__(self, worker):
EventHandler.__init__(self)
self.ext_worker = worker
self.testtimer = False
def ev_timer(self, timer):
self.ext_worker.abort()
self.testtimer = True
worker = WorkerPdsh(HOSTNAME, command="sleep 10",
handler=None, timeout=None)
self._task.schedule(worker)
aot = AbortOnTimer(worker)
self.assertEqual(aot.testtimer, False)
self._task.timer(2.0, handler=aot)
self._task.resume()
self.assertEqual(aot.testtimer, True)
def testWorkerAbortSanity(self):
# test WorkerPdsh abort() (sanity)
# test noop abort() on unscheduled worker
worker = WorkerPdsh(HOSTNAME, command="sleep 1", handler=None,
timeout=None)
worker.abort()
def testLocalhostExplicitPdshReverseCopy(self):
# test simple localhost rcopy with explicit pdsh worker
dest = "/tmp/cs-test_testLocalhostExplicitPdshRCopy"
shutil.rmtree(dest, ignore_errors=True)
try:
os.mkdir(dest)
worker = WorkerPdsh(HOSTNAME, source="/etc/hosts",
dest=dest, handler=None, | |
# Run the simulation
data.binary('sander', args, basename)
# Check if output is okay
util.check_output(sander_out, ['FATAL'])
top, crds, vels = get_restart_files(basename)
util.check_output(top)
util.check_output(crds)
# ##########################################################
# # 4. Read trajectories with some post-processing
# The units used in these files are:
# - positions: angstroms
# - velocities: angs/ps/20.455
class TrjReader:
"""
Class to read AMBER .trj and .trj.gz files.
.trj files do not tell us how many atoms are in each frame, this
must be entered. box dimensions are auto-detected.
Attributes:
top (str) - name of .top file
trj (str) - name of .trj file
file (file) - file object to trajectory
pos_start_frame (int) - position of the beginning of frames
size_frame (int) - the size of the frame in bytes
n_atom (int) - number of atoms simulated
n_frame (int) - number of frames in trajectory
i_frame (int) - index of current frame
frame (array) - container of coordinates of current frame
is_box_dims (bool) - frame contains extra line for periodic box
Methods:
__init__ - initializes trajectory and loads 1st frame
load_frame(i) - loads the i frame
__getitem__ - returns the frame
save_to_crd - save current frame to a .crd file
__repr__ - string representation
"""
def __init__(self, n_atom, trj):
self.n_atom = n_atom
self.trj = trj
# Since .trj is a text format, it can be readily gzip'd,
# so opening .trj.gz is a useful option to have.
if self.trj.split(".")[-1].strip().lower() == "gz":
self.file = gzip.GzipFile(self.trj, "r")
else:
self.file = open(self.trj, "r")
# only 1-line header, frames starts after this line
self.pos_start_frame = len(self.file.readline())
# get the size of all frames
self.file.seek(0, 2)
pos_eof = self.file.tell()
size_all_frames = pos_eof - self.pos_start_frame
# auto-detect n_frame
self.is_box_dims = False
self.size_frame = self.calc_size_frame(self.n_atom)
n_frame = size_all_frames / float(self.size_frame)
# check if n_frame is exact
if n_frame % 1.0 > 0.0:
# n_frame is not exact, check for box dimensions
self.size_frame = self.calc_size_frame(self.n_atom, True)
n_frame = size_all_frames / float(self.size_frame)
if n_frame % 1.0 != 0.0:
raise Exception('frames don\'t fit n_atom for ' + self.trj)
self.is_box_dims = True
self.n_frame = int(n_frame)
self.load_frame(0)
def calc_size_frame(self, n_crd, is_box_dims=False):
self.file.seek(self.pos_start_frame)
n_line = (3 * n_crd) / 10
if (3 * n_crd) % 10 > 0:
n_line += 1
if is_box_dims:
n_line += 1
size_frame = 0
for i in range(0, n_line):
size_frame += len(self.file.readline())
return size_frame
def load_frame(self, i_frame):
"""
Loads the frame into self.frame, a list of 3*n_atom floats
"""
# Check bounds
if i_frame < - 1*self.n_frame or i_frame >= self.n_frame:
raise IndexError
elif i_frame < 0:
i_frame = self.n_frame + i_frame
self.file.seek(self.pos_start_frame + i_frame*(self.size_frame))
# read frame as list of 3 floats
s = self.file.read(self.size_frame).replace('\n', '')
pieces = [s[i:i+8] for i in xrange(0, len(s), 8)]
vals = map(float, pieces)
# account for box dimensions
if self.is_box_dims:
# drop the box dimension values
vals = vals[:-3]
if len(vals) != 3*self.n_atom:
raise ValueError("Improper number of coordinates in frame.")
self.frame = vals
self.i_frame = i_frame
def __getitem__(self, i_frame):
"""
Returns the container for coordinates of the i'th frame.
"""
self.load_frame(i_frame)
return self.frame
def save_to_crd(self, crd):
"""
Saves coordinates of current frame to an AMBER .crd file.
"""
f = open(crd, "w")
coords = self.frame
f.write("ACE".ljust(80) + "\n")
f.write("%5d 0.0000000E+00\n" % (len(coords) // 3))
p = ["%12.7f" % x for x in coords]
n_val_per_line = 6
r = len(p) % n_val_per_line
if r > 0:
p.extend([""] * (n_val_per_line - r))
for i in xrange(0, len(p), n_val_per_line):
f.write("".join(p[i:i + n_val_per_line]) + "\n")
f.close()
def __repr__(self):
return "< Amber Coord file %s with %d frames of %d atoms >" % \
(self.trj, self.n_frame, self.n_atom)
class SoupTrajectory:
"""
Class to provide common frame API with AMBER trajectories.
"""
def __init__(self, soup, trj, vel_trj=''):
self.trj = trj
self.vel_trj = vel_trj
self.soup = soup
self.n_atom = len(soup.atoms())
self.trj_reader = TrjReader(self.n_atom, self.trj)
if self.vel_trj:
self.vel_trj_reader = TrjReader(self.n_atom, self.vel_trj)
else:
self.vel_trj_reader = None
self.n_frame = self.trj_reader.n_frame
def load_frame(self, i_frame):
# Load coordinates of soup with coordinates from self.trj_reader
crds = self.trj_reader[i_frame]
vels = self.vel_trj_reader[i_frame] if self.vel_trj_reader else None
atoms = self.soup.atoms()
for i in range(self.n_atom):
atom = atoms[i]
k = 3*i
v3.set_vector(atom.pos, crds[k], crds[k+1], crds[k+2])
if vels:
v3.set_vector(atom.vel, vels[k], vels[k+1], vels[k+2])
self.i_frame = self.trj_reader.i_frame
class Trajectory:
"""
Class to interact with an AMBER trajctory using soup.
Attributes:
basename (str) - basename used to guess required files
n_frame (int) - number of frames in trajectory
i_frame (int) - index of current frame
soup (Soup) - Soup object holding current coordinates/velocities
Methods:
load_frame - loads new frame into soup
"""
def __init__(self, basename):
self.basename = basename
self.top = basename + '.top'
self.soup = soup_from_top(self.top)
self.trj = basename + '.trj'
self.vel_trj = basename + '.vel.trj'
if not os.path.isfile(self.vel_trj):
self.vel_trj = ''
self.soup_trj = SoupTrajectory(self.soup, self.trj, self.vel_trj)
self.n_frame = self.soup_trj.n_frame
self.i_frame = 0
self.load_frame(0)
def load_frame(self, i_frame):
self.soup_trj.load_frame(i_frame)
self.i_frame = self.soup_trj.i_frame
def merge_amber_trajs(top, trajs, out_traj):
"""
Given a list of traj filenames (trajs), merges them into one complete
trajectory (out_traj) using top to work out the number of atoms, and
hence the size of the frame of the trajectory.
"""
# Get pos_start_frame and size_frame by opening one of the
# trajectories via trj_reader
topology = read_top(top)
trj_reader = TrjReader(topology['NATOM'], trajs[0])
pos_start_frame = trj_reader.pos_start_frame
size_frame = trj_reader.size_frame
del trj_reader
# Start the merged file by copying the first trajectory
shutil.copy(trajs[0], out_traj)
# Now open the merged file in appended form and add it to the
# merged file, one frame at a time
merge_traj_file = open(out_traj, "ab+")
for traj in trajs[1:]:
traj_file = open(traj, "rb")
traj_file.seek(-1, 2)
eof = traj_file.tell()
traj_file.seek(pos_start_frame)
while traj_file.tell() < eof:
merge_traj_file.write(traj_file.read(size_frame))
traj_file.close()
merge_traj_file.close()
def merge_trajectories(basename, traj_basenames):
"""
Given a list of directories with partial trajectories in each directory
with the same basename for the md, will splice them together into one uber
simulation.
"""
shutil.copy(traj_basenames[-1] + '.sander.in', basename + '.sander.in')
shutil.copy(traj_basenames[-1] + '.top', basename + '.top')
shutil.copy(traj_basenames[-1] + '.rst', basename + '.rst')
# merge energies of sims into one energy file
f = open(basename + '.energy', 'w')
f.write('[\n')
n_step = 0
time = 0.0
for traj_basename in traj_basenames:
energy_fname = traj_basename + '.energy'
if os.path.isfile(energy_fname):
blocks = eval(open(energy_fname).read())
else:
sander_out = traj_basename + '.sander.out'
blocks = read_dynamics_sander_out(sander_out)
for block in blocks:
block_n_step = int(block['NSTEP'])
block_time = float(block['TIME(PS)'])
block['NSTEP'] = str(block_n_step + n_step)
block['TIME(PS)'] = str(block_time + time)
f.write(str(block) + ',\n')
n_step = int(blocks[-1]['NSTEP'])
time = float(blocks[-1]['TIME(PS)'])
f.write(']\n')
f.close()
trajs = [b + '.trj' for b in traj_basenames]
merge_amber_trajs(basename + '.top', trajs, basename + '.trj')
vels = [b + '.vel.trj' for b in traj_basenames]
merge_amber_trajs(basename + '.top', vels, basename + '.vel.trj')
def convert_crd_to_trj_frame(crd):
"""
Returns a string that corresponds to a frame in a .trj from a
.crd file. This is for writing to .trj files.
"""
vals = [float(word) for word in util.words_in_file(crd)[1:]]
lines = []
line = ''
for i in range(0, len(vals)):
line += "%8.3f" % vals[i]
if (i % 10) == 9:
lines.append(line)
line = ''
if line:
lines.append(line)
return '\n'.join(lines) + '\n'
def read_dynamics_sander_out(sander_out):
"""
Returns a list of dictionaries containing energy values
from sander out file for molecular dynamics.
"""
results = []
block_dict = {}
is_header = True
for line in open(sander_out):
if is_header:
if '4' in line and 'RESULTS' in line:
is_header = False
continue
if 'A V E R A G E S' in line:
# End of time blocks
break
if line.startswith('|'):
continue
if '----' in line:
# New block: save last block
if block_dict:
results.append(block_dict.copy())
else:
words = line.split()
for i in range(len(words)):
if words[i] == "=":
key = words[i-1].strip()
val = words[i+1]
if key == 'NSTEP':
block_dict[key] = int(val)
else:
block_dict[key] = float(val)
return results
def read_minimization_sander_out(sander_out):
"""
Returns a list of dictionaries containing energy values
from sander out file for minimization steps.
"""
results = []
block_dict = {}
lines = open(sander_out).readlines()
is_results = False
for i, line in enumerate(lines):
if not is_results:
if '4' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.